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
pixelcmtd/CXClient
23,819
src/minecraft/net/minecraft/block/BlockRailBase.java
package net.minecraft.block; import com.google.common.collect.Lists; import java.util.List; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.util.IStringSerializable; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public abstract class BlockRailBase extends Block { protected final boolean isPowered; public static boolean isRailBlock(World worldIn, BlockPos pos) { return isRailBlock(worldIn.getBlockState(pos)); } public static boolean isRailBlock(IBlockState state) { Block block = state.getBlock(); return block == Blocks.rail || block == Blocks.golden_rail || block == Blocks.detector_rail || block == Blocks.activator_rail; } protected BlockRailBase(boolean isPowered) { super(Material.circuits); this.isPowered = isPowered; this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); this.setCreativeTab(CreativeTabs.tabTransport); } public AxisAlignedBB getCollisionBoundingBox(World worldIn, BlockPos pos, IBlockState state) { return null; } /** * Used to determine ambient occlusion and culling when rebuilding chunks for render */ public boolean isOpaqueCube() { return false; } /** * Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. */ public MovingObjectPosition collisionRayTrace(World worldIn, BlockPos pos, Vec3 start, Vec3 end) { this.setBlockBoundsBasedOnState(worldIn, pos); return super.collisionRayTrace(worldIn, pos, start, end); } public void setBlockBoundsBasedOnState(IBlockAccess worldIn, BlockPos pos) { IBlockState iblockstate = worldIn.getBlockState(pos); BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = iblockstate.getBlock() == this ? (BlockRailBase.EnumRailDirection)iblockstate.getValue(this.getShapeProperty()) : null; if (blockrailbase$enumraildirection != null && blockrailbase$enumraildirection.isAscending()) { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.625F, 1.0F); } else { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); } } public boolean isFullCube() { return false; } public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { return World.doesBlockHaveSolidTopSurface(worldIn, pos.down()); } public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) { if (!worldIn.isRemote) { state = this.func_176564_a(worldIn, pos, state, true); if (this.isPowered) { this.onNeighborBlockChange(worldIn, pos, state, this); } } } /** * Called when a neighboring block changes. */ public void onNeighborBlockChange(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock) { if (!worldIn.isRemote) { BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = (BlockRailBase.EnumRailDirection)state.getValue(this.getShapeProperty()); boolean flag = false; if (!World.doesBlockHaveSolidTopSurface(worldIn, pos.down())) { flag = true; } if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_EAST && !World.doesBlockHaveSolidTopSurface(worldIn, pos.east())) { flag = true; } else if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_WEST && !World.doesBlockHaveSolidTopSurface(worldIn, pos.west())) { flag = true; } else if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_NORTH && !World.doesBlockHaveSolidTopSurface(worldIn, pos.north())) { flag = true; } else if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_SOUTH && !World.doesBlockHaveSolidTopSurface(worldIn, pos.south())) { flag = true; } if (flag) { this.dropBlockAsItem(worldIn, pos, state, 0); worldIn.setBlockToAir(pos); } else { this.onNeighborChangedInternal(worldIn, pos, state, neighborBlock); } } } protected void onNeighborChangedInternal(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock) { } protected IBlockState func_176564_a(World worldIn, BlockPos p_176564_2_, IBlockState p_176564_3_, boolean p_176564_4_) { return worldIn.isRemote ? p_176564_3_ : (new BlockRailBase.Rail(worldIn, p_176564_2_, p_176564_3_)).func_180364_a(worldIn.isBlockPowered(p_176564_2_), p_176564_4_).getBlockState(); } public int getMobilityFlag() { return 0; } public EnumWorldBlockLayer getBlockLayer() { return EnumWorldBlockLayer.CUTOUT; } public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { super.breakBlock(worldIn, pos, state); if (((BlockRailBase.EnumRailDirection)state.getValue(this.getShapeProperty())).isAscending()) { worldIn.notifyNeighborsOfStateChange(pos.up(), this); } if (this.isPowered) { worldIn.notifyNeighborsOfStateChange(pos, this); worldIn.notifyNeighborsOfStateChange(pos.down(), this); } } public abstract IProperty<BlockRailBase.EnumRailDirection> getShapeProperty(); public static enum EnumRailDirection implements IStringSerializable { NORTH_SOUTH(0, "north_south"), EAST_WEST(1, "east_west"), ASCENDING_EAST(2, "ascending_east"), ASCENDING_WEST(3, "ascending_west"), ASCENDING_NORTH(4, "ascending_north"), ASCENDING_SOUTH(5, "ascending_south"), SOUTH_EAST(6, "south_east"), SOUTH_WEST(7, "south_west"), NORTH_WEST(8, "north_west"), NORTH_EAST(9, "north_east"); private static final BlockRailBase.EnumRailDirection[] META_LOOKUP = new BlockRailBase.EnumRailDirection[values().length]; private final int meta; private final String name; private EnumRailDirection(int meta, String name) { this.meta = meta; this.name = name; } public int getMetadata() { return this.meta; } public String toString() { return this.name; } public boolean isAscending() { return this == ASCENDING_NORTH || this == ASCENDING_EAST || this == ASCENDING_SOUTH || this == ASCENDING_WEST; } public static BlockRailBase.EnumRailDirection byMetadata(int meta) { if (meta < 0 || meta >= META_LOOKUP.length) { meta = 0; } return META_LOOKUP[meta]; } public String getName() { return this.name; } static { for (BlockRailBase.EnumRailDirection blockrailbase$enumraildirection : values()) { META_LOOKUP[blockrailbase$enumraildirection.getMetadata()] = blockrailbase$enumraildirection; } } } public class Rail { private final World world; private final BlockPos pos; private final BlockRailBase block; private IBlockState state; private final boolean isPowered; private final List<BlockPos> field_150657_g = Lists.<BlockPos>newArrayList(); public Rail(World worldIn, BlockPos pos, IBlockState state) { this.world = worldIn; this.pos = pos; this.state = state; this.block = (BlockRailBase)state.getBlock(); BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = (BlockRailBase.EnumRailDirection)state.getValue(BlockRailBase.this.getShapeProperty()); this.isPowered = this.block.isPowered; this.func_180360_a(blockrailbase$enumraildirection); } private void func_180360_a(BlockRailBase.EnumRailDirection p_180360_1_) { this.field_150657_g.clear(); switch (p_180360_1_) { case NORTH_SOUTH: this.field_150657_g.add(this.pos.north()); this.field_150657_g.add(this.pos.south()); break; case EAST_WEST: this.field_150657_g.add(this.pos.west()); this.field_150657_g.add(this.pos.east()); break; case ASCENDING_EAST: this.field_150657_g.add(this.pos.west()); this.field_150657_g.add(this.pos.east().up()); break; case ASCENDING_WEST: this.field_150657_g.add(this.pos.west().up()); this.field_150657_g.add(this.pos.east()); break; case ASCENDING_NORTH: this.field_150657_g.add(this.pos.north().up()); this.field_150657_g.add(this.pos.south()); break; case ASCENDING_SOUTH: this.field_150657_g.add(this.pos.north()); this.field_150657_g.add(this.pos.south().up()); break; case SOUTH_EAST: this.field_150657_g.add(this.pos.east()); this.field_150657_g.add(this.pos.south()); break; case SOUTH_WEST: this.field_150657_g.add(this.pos.west()); this.field_150657_g.add(this.pos.south()); break; case NORTH_WEST: this.field_150657_g.add(this.pos.west()); this.field_150657_g.add(this.pos.north()); break; case NORTH_EAST: this.field_150657_g.add(this.pos.east()); this.field_150657_g.add(this.pos.north()); } } private void func_150651_b() { for (int i = 0; i < this.field_150657_g.size(); ++i) { BlockRailBase.Rail blockrailbase$rail = this.findRailAt((BlockPos)this.field_150657_g.get(i)); if (blockrailbase$rail != null && blockrailbase$rail.func_150653_a(this)) { this.field_150657_g.set(i, blockrailbase$rail.pos); } else { this.field_150657_g.remove(i--); } } } private boolean hasRailAt(BlockPos pos) { return BlockRailBase.isRailBlock(this.world, pos) || BlockRailBase.isRailBlock(this.world, pos.up()) || BlockRailBase.isRailBlock(this.world, pos.down()); } private BlockRailBase.Rail findRailAt(BlockPos pos) { IBlockState iblockstate = this.world.getBlockState(pos); if (BlockRailBase.isRailBlock(iblockstate)) { return BlockRailBase.this.new Rail(this.world, pos, iblockstate); } else { BlockPos lvt_2_1_ = pos.up(); iblockstate = this.world.getBlockState(lvt_2_1_); if (BlockRailBase.isRailBlock(iblockstate)) { return BlockRailBase.this.new Rail(this.world, lvt_2_1_, iblockstate); } else { lvt_2_1_ = pos.down(); iblockstate = this.world.getBlockState(lvt_2_1_); return BlockRailBase.isRailBlock(iblockstate) ? BlockRailBase.this.new Rail(this.world, lvt_2_1_, iblockstate) : null; } } } private boolean func_150653_a(BlockRailBase.Rail p_150653_1_) { return this.func_180363_c(p_150653_1_.pos); } private boolean func_180363_c(BlockPos p_180363_1_) { for (int i = 0; i < this.field_150657_g.size(); ++i) { BlockPos blockpos = (BlockPos)this.field_150657_g.get(i); if (blockpos.getX() == p_180363_1_.getX() && blockpos.getZ() == p_180363_1_.getZ()) { return true; } } return false; } protected int countAdjacentRails() { int i = 0; for (EnumFacing enumfacing : EnumFacing.Plane.HORIZONTAL) { if (this.hasRailAt(this.pos.offset(enumfacing))) { ++i; } } return i; } private boolean func_150649_b(BlockRailBase.Rail rail) { return this.func_150653_a(rail) || this.field_150657_g.size() != 2; } private void func_150645_c(BlockRailBase.Rail p_150645_1_) { this.field_150657_g.add(p_150645_1_.pos); BlockPos blockpos = this.pos.north(); BlockPos blockpos1 = this.pos.south(); BlockPos blockpos2 = this.pos.west(); BlockPos blockpos3 = this.pos.east(); boolean flag = this.func_180363_c(blockpos); boolean flag1 = this.func_180363_c(blockpos1); boolean flag2 = this.func_180363_c(blockpos2); boolean flag3 = this.func_180363_c(blockpos3); BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = null; if (flag || flag1) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_SOUTH; } if (flag2 || flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.EAST_WEST; } if (!this.isPowered) { if (flag1 && flag3 && !flag && !flag2) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_EAST; } if (flag1 && flag2 && !flag && !flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_WEST; } if (flag && flag2 && !flag1 && !flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_WEST; } if (flag && flag3 && !flag1 && !flag2) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_EAST; } } if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.NORTH_SOUTH) { if (BlockRailBase.isRailBlock(this.world, blockpos.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_NORTH; } if (BlockRailBase.isRailBlock(this.world, blockpos1.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_SOUTH; } } if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.EAST_WEST) { if (BlockRailBase.isRailBlock(this.world, blockpos3.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_EAST; } if (BlockRailBase.isRailBlock(this.world, blockpos2.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_WEST; } } if (blockrailbase$enumraildirection == null) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_SOUTH; } this.state = this.state.withProperty(this.block.getShapeProperty(), blockrailbase$enumraildirection); this.world.setBlockState(this.pos, this.state, 3); } private boolean func_180361_d(BlockPos p_180361_1_) { BlockRailBase.Rail blockrailbase$rail = this.findRailAt(p_180361_1_); if (blockrailbase$rail == null) { return false; } else { blockrailbase$rail.func_150651_b(); return blockrailbase$rail.func_150649_b(this); } } public BlockRailBase.Rail func_180364_a(boolean p_180364_1_, boolean p_180364_2_) { BlockPos blockpos = this.pos.north(); BlockPos blockpos1 = this.pos.south(); BlockPos blockpos2 = this.pos.west(); BlockPos blockpos3 = this.pos.east(); boolean flag = this.func_180361_d(blockpos); boolean flag1 = this.func_180361_d(blockpos1); boolean flag2 = this.func_180361_d(blockpos2); boolean flag3 = this.func_180361_d(blockpos3); BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = null; if ((flag || flag1) && !flag2 && !flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_SOUTH; } if ((flag2 || flag3) && !flag && !flag1) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.EAST_WEST; } if (!this.isPowered) { if (flag1 && flag3 && !flag && !flag2) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_EAST; } if (flag1 && flag2 && !flag && !flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_WEST; } if (flag && flag2 && !flag1 && !flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_WEST; } if (flag && flag3 && !flag1 && !flag2) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_EAST; } } if (blockrailbase$enumraildirection == null) { if (flag || flag1) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_SOUTH; } if (flag2 || flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.EAST_WEST; } if (!this.isPowered) { if (p_180364_1_) { if (flag1 && flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_EAST; } if (flag2 && flag1) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_WEST; } if (flag3 && flag) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_EAST; } if (flag && flag2) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_WEST; } } else { if (flag && flag2) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_WEST; } if (flag3 && flag) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_EAST; } if (flag2 && flag1) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_WEST; } if (flag1 && flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_EAST; } } } } if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.NORTH_SOUTH) { if (BlockRailBase.isRailBlock(this.world, blockpos.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_NORTH; } if (BlockRailBase.isRailBlock(this.world, blockpos1.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_SOUTH; } } if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.EAST_WEST) { if (BlockRailBase.isRailBlock(this.world, blockpos3.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_EAST; } if (BlockRailBase.isRailBlock(this.world, blockpos2.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_WEST; } } if (blockrailbase$enumraildirection == null) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_SOUTH; } this.func_180360_a(blockrailbase$enumraildirection); this.state = this.state.withProperty(this.block.getShapeProperty(), blockrailbase$enumraildirection); if (p_180364_2_ || this.world.getBlockState(this.pos) != this.state) { this.world.setBlockState(this.pos, this.state, 3); for (int i = 0; i < this.field_150657_g.size(); ++i) { BlockRailBase.Rail blockrailbase$rail = this.findRailAt((BlockPos)this.field_150657_g.get(i)); if (blockrailbase$rail != null) { blockrailbase$rail.func_150651_b(); if (blockrailbase$rail.func_150649_b(this)) { blockrailbase$rail.func_150645_c(this); } } } } return this; } public IBlockState getBlockState() { return this.state; } } }
412
0.925584
1
0.925584
game-dev
MEDIA
0.991119
game-dev
0.945111
1
0.945111
Hendrix-Shen/MagicLib
3,077
magiclib-malilib-extra/src/main/java/top/hendrixshen/magiclib/mixin/malilib/config/ConfigBaseMixin.java
/* * This file is part of the TweakerMore project, licensed under the * GNU Lesser General Public License v3.0 * * Copyright (C) 2023 Fallen_Breath and contributors * * TweakerMore is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * TweakerMore 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 TweakerMore. If not, see <https://www.gnu.org/licenses/>. */ package top.hendrixshen.magiclib.mixin.malilib.config; import fi.dy.masa.malilib.config.options.ConfigBase; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import top.hendrixshen.magiclib.api.i18n.I18n; import top.hendrixshen.magiclib.api.malilib.config.option.MagicIConfigBase; import top.hendrixshen.magiclib.impl.malilib.config.GlobalConfigManager; /** * Reference to <a href="https://github.com/Fallen-Breath/tweakermore/blob/476a25a5458a7058bdd402683b1fd833b189ae60/src/main/java/me/fallenbreath/tweakermore/mixins/core/config/ConfigBaseMixin.java">TweakerMore</a>. */ @Mixin(value = ConfigBase.class, remap = false) public abstract class ConfigBaseMixin { @Shadow private String comment; @Final @Shadow private String prettyName; @Unique private boolean magiclib$isMagicConfig() { return this instanceof MagicIConfigBase; } @Inject(method = "getPrettyName", at = @At("HEAD"), cancellable = true, remap = false) private void tweakerMoreUseMyPrettyName(CallbackInfoReturnable<String> cir) { if (this.magiclib$isMagicConfig()) { GlobalConfigManager.getInstance().getContainerByConfig((MagicIConfigBase) this) .ifPresent(configContainer -> cir.setReturnValue(I18n.tr(this.prettyName))); } } @Inject(method = "getComment", at = @At("HEAD"), cancellable = true, remap = false) private void magiclibUseMagicComment(CallbackInfoReturnable<String> cir) { if (this.magiclib$isMagicConfig()) { GlobalConfigManager.getInstance().getContainerByConfig((MagicIConfigBase) this) .ifPresent(configContainer -> { String translatedComment = I18n.tr(this.comment); translatedComment = configContainer.modifyComment(translatedComment); cir.setReturnValue(translatedComment); }); } } }
412
0.797503
1
0.797503
game-dev
MEDIA
0.834077
game-dev
0.597302
1
0.597302
goldeneye-source/ges-code
93,684
game/client/c_te_legacytempents.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $Workfile: $ // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "model_types.h" #include "view_shared.h" #include "iviewrender.h" #include "tempentity.h" #include "dlight.h" #include "tempent.h" #include "c_te_legacytempents.h" #include "clientsideeffects.h" #include "cl_animevent.h" #include "iefx.h" #include "engine/IEngineSound.h" #include "env_wind_shared.h" #include "clienteffectprecachesystem.h" #include "fx_sparks.h" #include "fx.h" #include "movevars_shared.h" #include "engine/ivmodelinfo.h" #include "SoundEmitterSystem/isoundemittersystembase.h" #include "view.h" #include "tier0/vprof.h" #include "particles_localspace.h" #include "physpropclientside.h" #include "tier0/icommandline.h" #include "datacache/imdlcache.h" #include "engine/ivdebugoverlay.h" #include "effect_dispatch_data.h" #include "c_te_effect_dispatch.h" #include "c_props.h" #include "c_basedoor.h" // NOTE: Always include this last! #include "tier0/memdbgon.h" extern ConVar muzzleflash_light; #define TENT_WIND_ACCEL 50 //Precache the effects #ifndef TF_CLIENT_DLL CLIENTEFFECT_REGISTER_BEGIN( PrecacheEffectMuzzleFlash ) CLIENTEFFECT_MATERIAL( "effects/muzzleflash1" ) CLIENTEFFECT_MATERIAL( "effects/muzzleflash2" ) CLIENTEFFECT_MATERIAL( "effects/muzzleflash3" ) CLIENTEFFECT_MATERIAL( "effects/muzzleflash4" ) CLIENTEFFECT_MATERIAL( "effects/muzzleflash1_noz" ) CLIENTEFFECT_MATERIAL( "effects/muzzleflash2_noz" ) CLIENTEFFECT_MATERIAL( "effects/muzzleflash3_noz" ) CLIENTEFFECT_MATERIAL( "effects/muzzleflash4_noz" ) #ifndef CSTRIKE_DLL CLIENTEFFECT_MATERIAL( "effects/combinemuzzle1" ) CLIENTEFFECT_MATERIAL( "effects/combinemuzzle2" ) CLIENTEFFECT_MATERIAL( "effects/combinemuzzle1_noz" ) CLIENTEFFECT_MATERIAL( "effects/combinemuzzle2_noz" ) CLIENTEFFECT_MATERIAL( "effects/strider_muzzle" ) #endif CLIENTEFFECT_REGISTER_END() #endif //Whether or not to eject brass from weapons ConVar cl_ejectbrass( "cl_ejectbrass", "1" ); ConVar func_break_max_pieces( "func_break_max_pieces", "15", FCVAR_ARCHIVE | FCVAR_REPLICATED ); ConVar cl_fasttempentcollision( "cl_fasttempentcollision", "5" ); #if !defined( HL1_CLIENT_DLL ) // HL1 implements a derivative of CTempEnts // Temp entity interface static CTempEnts g_TempEnts; // Expose to rest of the client .dll ITempEnts *tempents = ( ITempEnts * )&g_TempEnts; #endif C_LocalTempEntity::C_LocalTempEntity() { #ifdef _DEBUG tentOffset.Init(); m_vecTempEntVelocity.Init(); m_vecTempEntAngVelocity.Init(); m_vecNormal.Init(); #endif m_vecTempEntAcceleration.Init(); m_pfnDrawHelper = 0; m_pszImpactEffect = NULL; } #if defined( CSTRIKE_DLL ) || defined (SDK_DLL ) #define TE_RIFLE_SHELL 1024 #define TE_PISTOL_SHELL 2048 #define TE_SHOTGUN_SHELL 4096 #endif //----------------------------------------------------------------------------- // Purpose: Prepare a temp entity for creation // Input : time - // *model - //----------------------------------------------------------------------------- void C_LocalTempEntity::Prepare( const model_t *pmodel, float time ) { Interp_SetupMappings( GetVarMapping() ); index = -1; Clear(); // Use these to set per-frame and termination conditions / actions flags = FTENT_NONE; die = time + 0.75; SetModelPointer( pmodel ); SetRenderMode( kRenderNormal ); m_nRenderFX = kRenderFxNone; m_nBody = 0; m_nSkin = 0; fadeSpeed = 0.5; hitSound = 0; clientIndex = -1; bounceFactor = 1; m_nFlickerFrame = 0; m_bParticleCollision = false; } //----------------------------------------------------------------------------- // Sets the velocity //----------------------------------------------------------------------------- void C_LocalTempEntity::SetVelocity( const Vector &vecVelocity ) { m_vecTempEntVelocity = vecVelocity; } //----------------------------------------------------------------------------- // Sets the velocity //----------------------------------------------------------------------------- void C_LocalTempEntity::SetAcceleration( const Vector &vecVelocity ) { m_vecTempEntAcceleration = vecVelocity; } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int C_LocalTempEntity::DrawStudioModel( int flags ) { VPROF_BUDGET( "C_LocalTempEntity::DrawStudioModel", VPROF_BUDGETGROUP_MODEL_RENDERING ); int drawn = 0; if ( !GetModel() || modelinfo->GetModelType( GetModel() ) != mod_studio ) return drawn; // Make sure m_pstudiohdr is valid for drawing MDLCACHE_CRITICAL_SECTION(); if ( !GetModelPtr() ) return drawn; if ( m_pfnDrawHelper ) { drawn = ( *m_pfnDrawHelper )( this, flags ); } else { drawn = modelrender->DrawModel( flags, this, MODEL_INSTANCE_INVALID, index, GetModel(), GetAbsOrigin(), GetAbsAngles(), m_nSkin, m_nBody, m_nHitboxSet ); } return drawn; } //----------------------------------------------------------------------------- // Purpose: // Input : flags - //----------------------------------------------------------------------------- int C_LocalTempEntity::DrawModel( int flags ) { int drawn = 0; if ( !GetModel() ) { return drawn; } if ( GetRenderMode() == kRenderNone ) return drawn; if ( this->flags & FTENT_BEOCCLUDED ) { // Check normal Vector vecDelta = (GetAbsOrigin() - MainViewOrigin()); VectorNormalize( vecDelta ); float flDot = DotProduct( m_vecNormal, vecDelta ); if ( flDot > 0 ) { float flAlpha = RemapVal( MIN(flDot,0.3), 0, 0.3, 0, 1 ); flAlpha = MAX( 1.0, tempent_renderamt - (tempent_renderamt * flAlpha) ); SetRenderColorA( flAlpha ); } } switch ( modelinfo->GetModelType( GetModel() ) ) { case mod_sprite: drawn = DrawSprite( this, GetModel(), GetAbsOrigin(), GetAbsAngles(), m_flFrame, // sprite frame to render m_nBody > 0 ? cl_entitylist->GetBaseEntity( m_nBody ) : NULL, // attach to m_nSkin, // attachment point GetRenderMode(), // rendermode m_nRenderFX, // renderfx m_clrRender->a, // alpha m_clrRender->r, m_clrRender->g, m_clrRender->b, m_flSpriteScale // sprite scale ); break; case mod_studio: drawn = DrawStudioModel( flags ); break; default: break; } return drawn; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool C_LocalTempEntity::IsActive( void ) { bool active = true; float life = die - gpGlobals->curtime; if ( life < 0 ) { if ( flags & FTENT_FADEOUT ) { int alpha; if (GetRenderMode() == kRenderNormal) { SetRenderMode( kRenderTransTexture ); } alpha = tempent_renderamt * ( 1 + life * fadeSpeed ); if ( alpha <= 0 ) { active = false; alpha = 0; } SetRenderColorA( alpha ); } else { active = false; } } // Never die tempents only die when their die is cleared if ( flags & FTENT_NEVERDIE ) { active = (die != 0); } return active; } bool C_LocalTempEntity::Frame( float frametime, int framenumber ) { float fastFreq = gpGlobals->curtime * 5.5; float gravity = -frametime * GetCurrentGravity(); float gravitySlow = gravity * 0.5; float traceFraction = 1; Assert( !GetMoveParent() ); m_vecPrevLocalOrigin = GetLocalOrigin(); m_vecTempEntVelocity = m_vecTempEntVelocity + ( m_vecTempEntAcceleration * frametime ); if ( flags & FTENT_PLYRATTACHMENT ) { if ( IClientEntity *pClient = cl_entitylist->GetClientEntity( clientIndex ) ) { SetLocalOrigin( pClient->GetAbsOrigin() + tentOffset ); } } else if ( flags & FTENT_SINEWAVE ) { x += m_vecTempEntVelocity[0] * frametime; y += m_vecTempEntVelocity[1] * frametime; SetLocalOrigin( Vector( x + sin( m_vecTempEntVelocity[2] + gpGlobals->curtime /* * anim.prevframe */ ) * (10*m_flSpriteScale), y + sin( m_vecTempEntVelocity[2] + fastFreq + 0.7 ) * (8*m_flSpriteScale), GetLocalOriginDim( Z_INDEX ) + m_vecTempEntVelocity[2] * frametime ) ); } else if ( flags & FTENT_SPIRAL ) { float s, c; SinCos( m_vecTempEntVelocity[2] + fastFreq, &s, &c ); SetLocalOrigin( GetLocalOrigin() + Vector( m_vecTempEntVelocity[0] * frametime + 8 * sin( gpGlobals->curtime * 20 ), m_vecTempEntVelocity[1] * frametime + 4 * sin( gpGlobals->curtime * 30 ), m_vecTempEntVelocity[2] * frametime ) ); } else { SetLocalOrigin( GetLocalOrigin() + m_vecTempEntVelocity * frametime ); } if ( flags & FTENT_SPRANIMATE ) { m_flFrame += frametime * m_flFrameRate; if ( m_flFrame >= m_flFrameMax ) { m_flFrame = m_flFrame - (int)(m_flFrame); if ( !(flags & FTENT_SPRANIMATELOOP) ) { // this animating sprite isn't set to loop, so destroy it. die = 0.0f; return false; } } } else if ( flags & FTENT_SPRCYCLE ) { m_flFrame += frametime * 10; if ( m_flFrame >= m_flFrameMax ) { m_flFrame = m_flFrame - (int)(m_flFrame); } } if ( flags & FTENT_SMOKEGROWANDFADE ) { m_flSpriteScale += frametime * 0.5f; //m_clrRender.a -= frametime * 1500; } if ( flags & FTENT_ROTATE ) { SetLocalAngles( GetLocalAngles() + m_vecTempEntAngVelocity * frametime ); } else if ( flags & FTENT_ALIGNTOMOTION ) { if ( m_vecTempEntVelocity.Length() > 0.0f ) { QAngle angles; VectorAngles( m_vecTempEntVelocity, angles ); SetAbsAngles( angles ); } } if ( flags & (FTENT_COLLIDEALL | FTENT_COLLIDEWORLD | FTENT_COLLIDEPROPS ) ) { Vector traceNormal; traceNormal.Init(); bool bShouldCollide = true; trace_t trace; if ( flags & (FTENT_COLLIDEALL | FTENT_COLLIDEPROPS) ) { Vector vPrevOrigin = m_vecPrevLocalOrigin; if ( cl_fasttempentcollision.GetInt() > 0 && flags & FTENT_USEFASTCOLLISIONS ) { if ( m_iLastCollisionFrame + cl_fasttempentcollision.GetInt() > gpGlobals->framecount ) { bShouldCollide = false; } else { if ( m_vLastCollisionOrigin != vec3_origin ) { vPrevOrigin = m_vLastCollisionOrigin; } m_iLastCollisionFrame = gpGlobals->framecount; bShouldCollide = true; } } if ( bShouldCollide == true ) { // If the FTENT_COLLISIONGROUP flag is set, use the entity's collision group int collisionGroup = COLLISION_GROUP_NONE; if ( flags & FTENT_COLLISIONGROUP ) { collisionGroup = GetCollisionGroup(); } UTIL_TraceLine( vPrevOrigin, GetLocalOrigin(), MASK_SOLID, GetOwnerEntity(), collisionGroup, &trace ); if ( (flags & FTENT_COLLIDEPROPS) && trace.m_pEnt ) { bool bIsDynamicProp = ( NULL != dynamic_cast<CDynamicProp *>( trace.m_pEnt ) ); bool bIsDoor = ( NULL != dynamic_cast<CBaseDoor *>( trace.m_pEnt ) ); if ( !bIsDynamicProp && !bIsDoor && !trace.m_pEnt->IsWorld() ) // Die on props, doors, and the world. return true; } // Make sure it didn't bump into itself... (?!?) if ( (trace.fraction != 1) && ( (trace.DidHitWorld()) || (trace.m_pEnt != ClientEntityList().GetEnt(clientIndex)) ) ) { traceFraction = trace.fraction; VectorCopy( trace.plane.normal, traceNormal ); } m_vLastCollisionOrigin = trace.endpos; } } else if ( flags & FTENT_COLLIDEWORLD ) { CTraceFilterWorldOnly traceFilter; UTIL_TraceLine( m_vecPrevLocalOrigin, GetLocalOrigin(), MASK_SOLID, &traceFilter, &trace ); if ( trace.fraction != 1 ) { traceFraction = trace.fraction; VectorCopy( trace.plane.normal, traceNormal ); } } if ( traceFraction != 1 ) // Decent collision now, and damping works { float proj, damp; SetLocalOrigin( trace.endpos ); // Damp velocity damp = bounceFactor; if ( flags & (FTENT_GRAVITY|FTENT_SLOWGRAVITY) ) { damp *= 0.5; if ( traceNormal[2] > 0.9 ) // Hit floor? { if ( m_vecTempEntVelocity[2] <= 0 && m_vecTempEntVelocity[2] >= gravity*3 ) { damp = 0; // Stop flags &= ~(FTENT_ROTATE|FTENT_GRAVITY|FTENT_SLOWGRAVITY|FTENT_COLLIDEWORLD|FTENT_SMOKETRAIL); SetLocalAnglesDim( X_INDEX, 0 ); SetLocalAnglesDim( Z_INDEX, 0 ); } } } if ( flags & (FTENT_CHANGERENDERONCOLLIDE) ) { m_RenderGroup = RENDER_GROUP_OTHER; flags &= ~FTENT_CHANGERENDERONCOLLIDE; } if (hitSound) { tempents->PlaySound(this, damp); } if ( m_pszImpactEffect ) { CEffectData data; //data.m_vOrigin = newOrigin; data.m_vOrigin = trace.endpos; data.m_vStart = trace.startpos; data.m_nSurfaceProp = trace.surface.surfaceProps; data.m_nHitBox = trace.hitbox; data.m_nDamageType = TEAM_UNASSIGNED; IClientNetworkable *pClient = cl_entitylist->GetClientEntity( clientIndex ); if ( pClient ) { C_BasePlayer *pPlayer = dynamic_cast<C_BasePlayer*>(pClient); if( pPlayer ) { data.m_nDamageType = pPlayer->GetTeamNumber(); } } if ( trace.m_pEnt ) { data.m_hEntity = ClientEntityList().EntIndexToHandle( trace.m_pEnt->entindex() ); } DispatchEffect( m_pszImpactEffect, data ); } // Check for a collision and stop the particle system. if ( flags & FTENT_CLIENTSIDEPARTICLES ) { // Stop the emission of particles on collision - removed from the ClientEntityList on removal from the tempent pool. ParticleProp()->StopEmission(); m_bParticleCollision = true; } if (flags & FTENT_COLLIDEKILL) { // die on impact flags &= ~FTENT_FADEOUT; die = gpGlobals->curtime; } else if ( flags & FTENT_ATTACHTOTARGET) { // If we've hit the world, just stop moving if ( trace.DidHitWorld() && !( trace.surface.flags & SURF_SKY ) ) { m_vecTempEntVelocity = vec3_origin; m_vecTempEntAcceleration = vec3_origin; // Remove movement flags so we don't keep tracing flags &= ~(FTENT_COLLIDEALL | FTENT_COLLIDEWORLD); } else { // Couldn't attach to this entity. Die. flags &= ~FTENT_FADEOUT; die = gpGlobals->curtime; } } else { // Reflect velocity if ( damp != 0 ) { proj = ((Vector)m_vecTempEntVelocity).Dot(traceNormal); VectorMA( m_vecTempEntVelocity, -proj*2, traceNormal, m_vecTempEntVelocity ); // Reflect rotation (fake) SetLocalAnglesDim( Y_INDEX, -GetLocalAnglesDim( Y_INDEX ) ); } if ( damp != 1 ) { VectorScale( m_vecTempEntVelocity, damp, m_vecTempEntVelocity ); SetLocalAngles( GetLocalAngles() * 0.9 ); } } } } if ( (flags & FTENT_FLICKER) && framenumber == m_nFlickerFrame ) { dlight_t *dl = effects->CL_AllocDlight (LIGHT_INDEX_TE_DYNAMIC); VectorCopy (GetLocalOrigin(), dl->origin); dl->radius = 60; dl->color.r = 255; dl->color.g = 120; dl->color.b = 0; dl->die = gpGlobals->curtime + 0.01; } if ( flags & FTENT_SMOKETRAIL ) { Assert( !"FIXME: Rework smoketrail to be client side\n" ); } // add gravity if we didn't collide in this frame if ( traceFraction == 1 ) { if ( flags & FTENT_GRAVITY ) m_vecTempEntVelocity[2] += gravity; else if ( flags & FTENT_SLOWGRAVITY ) m_vecTempEntVelocity[2] += gravitySlow; } if ( flags & FTENT_WINDBLOWN ) { Vector vecWind; GetWindspeedAtTime( gpGlobals->curtime, vecWind ); for ( int i = 0 ; i < 2 ; i++ ) { if ( m_vecTempEntVelocity[i] < vecWind[i] ) { m_vecTempEntVelocity[i] += ( frametime * TENT_WIND_ACCEL ); // clamp if ( m_vecTempEntVelocity[i] > vecWind[i] ) m_vecTempEntVelocity[i] = vecWind[i]; } else if (m_vecTempEntVelocity[i] > vecWind[i] ) { m_vecTempEntVelocity[i] -= ( frametime * TENT_WIND_ACCEL ); // clamp. if ( m_vecTempEntVelocity[i] < vecWind[i] ) m_vecTempEntVelocity[i] = vecWind[i]; } } } return true; } //----------------------------------------------------------------------------- // Purpose: Attach a particle effect to a temp entity. //----------------------------------------------------------------------------- CNewParticleEffect* C_LocalTempEntity::AddParticleEffect( const char *pszParticleEffect ) { // Do we have a valid particle effect. if ( !pszParticleEffect || ( pszParticleEffect[0] == '\0' ) ) return NULL; // Check to see that we don't already have a particle effect. if ( ( flags & FTENT_CLIENTSIDEPARTICLES ) != 0 ) return NULL; // Add the entity to the ClientEntityList and create the particle system. ClientEntityList().AddNonNetworkableEntity( this ); CNewParticleEffect* pEffect = ParticleProp()->Create( pszParticleEffect, PATTACH_ABSORIGIN_FOLLOW ); // Set the particle flag on the temp entity and save the name of the particle effect. flags |= FTENT_CLIENTSIDEPARTICLES; SetParticleEffect( pszParticleEffect ); return pEffect; } //----------------------------------------------------------------------------- // Purpose: This helper keeps track of batches of "breakmodels" so that they can all share the lighting origin // of the first of the group (because the server sends down 15 chunks at a time, and rebuilding 15 light cache // entries for a map with a lot of worldlights is really slow). //----------------------------------------------------------------------------- class CBreakableHelper { public: void Insert( C_LocalTempEntity *entity, bool isSlave ); void Remove( C_LocalTempEntity *entity ); void Clear(); const Vector *GetLightingOrigin( C_LocalTempEntity *entity ); private: // A context is the first master until the next one, which starts a new context struct BreakableList_t { unsigned int context; C_LocalTempEntity *entity; }; CUtlLinkedList< BreakableList_t, unsigned short > m_Breakables; unsigned int m_nCurrentContext; }; //----------------------------------------------------------------------------- // Purpose: Adds brekable to list, starts new context if needed // Input : *entity - // isSlave - //----------------------------------------------------------------------------- void CBreakableHelper::Insert( C_LocalTempEntity *entity, bool isSlave ) { // A master signifies the start of a new run of broken objects if ( !isSlave ) { ++m_nCurrentContext; } BreakableList_t entry; entry.context = m_nCurrentContext; entry.entity = entity; m_Breakables.AddToTail( entry ); } //----------------------------------------------------------------------------- // Purpose: Removes all instances of entity in the list // Input : *entity - //----------------------------------------------------------------------------- void CBreakableHelper::Remove( C_LocalTempEntity *entity ) { for ( unsigned short i = m_Breakables.Head(); i != m_Breakables.InvalidIndex() ; ) { unsigned short n = m_Breakables.Next( i ); if ( m_Breakables[ i ].entity == entity ) { m_Breakables.Remove( i ); } i = n; } } //----------------------------------------------------------------------------- // Purpose: For a given breakable, find the "first" or head object and use it's current // origin as the lighting origin for the entire group of objects // Input : *entity - // Output : const Vector //----------------------------------------------------------------------------- const Vector *CBreakableHelper::GetLightingOrigin( C_LocalTempEntity *entity ) { unsigned int nCurContext = 0; C_LocalTempEntity *head = NULL; FOR_EACH_LL( m_Breakables, i ) { BreakableList_t& e = m_Breakables[ i ]; if ( e.context != nCurContext ) { nCurContext = e.context; head = e.entity; } if ( e.entity == entity ) { Assert( head ); return head ? &head->GetAbsOrigin() : NULL; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: Wipe breakable helper list // Input : - //----------------------------------------------------------------------------- void CBreakableHelper::Clear() { m_Breakables.RemoveAll(); m_nCurrentContext = 0; } static CBreakableHelper g_BreakableHelper; //----------------------------------------------------------------------------- // Purpose: See if it's in the breakable helper list and, if so, remove // Input : - //----------------------------------------------------------------------------- void C_LocalTempEntity::OnRemoveTempEntity() { g_BreakableHelper.Remove( this ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTempEnts::CTempEnts( void ) : m_TempEntsPool( ( MAX_TEMP_ENTITIES / 20 ), CUtlMemoryPool::GROW_SLOW ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTempEnts::~CTempEnts( void ) { m_TempEntsPool.Clear(); m_TempEnts.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: Create a fizz effect // Input : *pent - // modelIndex - // density - //----------------------------------------------------------------------------- void CTempEnts::FizzEffect( C_BaseEntity *pent, int modelIndex, int density, int current ) { C_LocalTempEntity *pTemp; const model_t *model; int i, width, depth, count, frameCount; float maxHeight, speed, xspeed, yspeed; Vector origin; Vector mins, maxs; if ( !pent->GetModel() || !modelIndex ) return; model = modelinfo->GetModel( modelIndex ); if ( !model ) return; count = density + 1; density = count * 3 + 6; modelinfo->GetModelBounds( pent->GetModel(), mins, maxs ); maxHeight = maxs[2] - mins[2]; width = maxs[0] - mins[0]; depth = maxs[1] - mins[1]; speed = current; SinCos( pent->GetLocalAngles()[1]*M_PI/180, &yspeed, &xspeed ); xspeed *= speed; yspeed *= speed; frameCount = modelinfo->GetModelFrameCount( model ); for (i=0 ; i<count ; i++) { origin[0] = mins[0] + random->RandomInt(0,width-1); origin[1] = mins[1] + random->RandomInt(0,depth-1); origin[2] = mins[2]; pTemp = TempEntAlloc( origin, model ); if (!pTemp) return; pTemp->flags |= FTENT_SINEWAVE; pTemp->x = origin[0]; pTemp->y = origin[1]; float zspeed = random->RandomInt(80,140); pTemp->SetVelocity( Vector(xspeed, yspeed, zspeed) ); pTemp->die = gpGlobals->curtime + (maxHeight / zspeed) - 0.1; pTemp->m_flFrame = random->RandomInt(0,frameCount-1); // Set sprite scale pTemp->m_flSpriteScale = 1.0 / random->RandomFloat(2,5); pTemp->SetRenderMode( kRenderTransAlpha ); pTemp->SetRenderColorA( 255 ); } } //----------------------------------------------------------------------------- // Purpose: Create bubbles // Input : *mins - // *maxs - // height - // modelIndex - // count - // speed - //----------------------------------------------------------------------------- void CTempEnts::Bubbles( const Vector &mins, const Vector &maxs, float height, int modelIndex, int count, float speed ) { C_LocalTempEntity *pTemp; const model_t *model; int i, frameCount; float sine, cosine; Vector origin; if ( !modelIndex ) return; model = modelinfo->GetModel( modelIndex ); if ( !model ) return; frameCount = modelinfo->GetModelFrameCount( model ); for (i=0 ; i<count ; i++) { origin[0] = random->RandomInt( mins[0], maxs[0] ); origin[1] = random->RandomInt( mins[1], maxs[1] ); origin[2] = random->RandomInt( mins[2], maxs[2] ); pTemp = TempEntAlloc( origin, model ); if (!pTemp) return; pTemp->flags |= FTENT_SINEWAVE; pTemp->x = origin[0]; pTemp->y = origin[1]; SinCos( random->RandomInt( -3, 3 ), &sine, &cosine ); float zspeed = random->RandomInt(80,140); pTemp->SetVelocity( Vector(speed * cosine, speed * sine, zspeed) ); pTemp->die = gpGlobals->curtime + ((height - (origin[2] - mins[2])) / zspeed) - 0.1; pTemp->m_flFrame = random->RandomInt( 0, frameCount-1 ); // Set sprite scale pTemp->m_flSpriteScale = 1.0 / random->RandomFloat(4,16); pTemp->SetRenderMode( kRenderTransAlpha ); pTemp->SetRenderColor( 255, 255, 255, 192 ); } } //----------------------------------------------------------------------------- // Purpose: Create bubble trail // Input : *start - // *end - // height - // modelIndex - // count - // speed - //----------------------------------------------------------------------------- void CTempEnts::BubbleTrail( const Vector &start, const Vector &end, float flWaterZ, int modelIndex, int count, float speed ) { C_LocalTempEntity *pTemp; const model_t *model; int i, frameCount; float dist, angle; Vector origin; if ( !modelIndex ) return; model = modelinfo->GetModel( modelIndex ); if ( !model ) return; frameCount = modelinfo->GetModelFrameCount( model ); for (i=0 ; i<count ; i++) { dist = random->RandomFloat( 0, 1.0 ); VectorLerp( start, end, dist, origin ); pTemp = TempEntAlloc( origin, model ); if (!pTemp) return; pTemp->flags |= FTENT_SINEWAVE; pTemp->x = origin[0]; pTemp->y = origin[1]; angle = random->RandomInt( -3, 3 ); float zspeed = random->RandomInt(80,140); pTemp->SetVelocity( Vector(speed * cos(angle), speed * sin(angle), zspeed) ); pTemp->die = gpGlobals->curtime + ((flWaterZ - origin[2]) / zspeed) - 0.1; pTemp->m_flFrame = random->RandomInt(0,frameCount-1); // Set sprite scale pTemp->m_flSpriteScale = 1.0 / random->RandomFloat(4,8); pTemp->SetRenderMode( kRenderTransAlpha ); pTemp->SetRenderColor( 255, 255, 255, 192 ); } } #define SHARD_VOLUME 12.0 // on shard ever n^3 units //----------------------------------------------------------------------------- // Purpose: Only used by BreakModel temp ents for now. Allows them to share a single // lighting origin amongst a group of objects. If the master object goes away, the next object // in the group becomes the new lighting origin, etc. // Input : *entity - // flags - // Output : int //----------------------------------------------------------------------------- int BreakModelDrawHelper( C_LocalTempEntity *entity, int flags ) { ModelRenderInfo_t sInfo; sInfo.flags = flags; sInfo.pRenderable = entity; sInfo.instance = MODEL_INSTANCE_INVALID; sInfo.entity_index = entity->index; sInfo.pModel = entity->GetModel(); sInfo.origin = entity->GetRenderOrigin(); sInfo.angles = entity->GetRenderAngles(); sInfo.skin = entity->m_nSkin; sInfo.body = entity->m_nBody; sInfo.hitboxset = entity->m_nHitboxSet; // This is the main change, look up a lighting origin from the helper singleton const Vector *pLightingOrigin = g_BreakableHelper.GetLightingOrigin( entity ); if ( pLightingOrigin ) { sInfo.pLightingOrigin = pLightingOrigin; } int drawn = modelrender->DrawModelEx( sInfo ); return drawn; } //----------------------------------------------------------------------------- // Purpose: Create model shattering shards // Input : *pos - // *size - // *dir - // random - // life - // count - // modelIndex - // flags - //----------------------------------------------------------------------------- void CTempEnts::BreakModel( const Vector &pos, const QAngle &angles, const Vector &size, const Vector &dir, float randRange, float life, int count, int modelIndex, char flags) { int i, frameCount; C_LocalTempEntity *pTemp; const model_t *pModel; if (!modelIndex) return; pModel = modelinfo->GetModel( modelIndex ); if ( !pModel ) return; // See g_BreakableHelper above for notes... bool isSlave = ( flags & BREAK_SLAVE ) ? true : false; frameCount = modelinfo->GetModelFrameCount( pModel ); if (count == 0) { // assume surface (not volume) count = (size[0] * size[1] + size[1] * size[2] + size[2] * size[0])/(3 * SHARD_VOLUME * SHARD_VOLUME); } if ( count > func_break_max_pieces.GetInt() ) { count = func_break_max_pieces.GetInt(); } matrix3x4_t transform; AngleMatrix( angles, pos, transform ); for ( i = 0; i < count; i++ ) { Vector vecLocalSpot, vecSpot; // fill up the box with stuff vecLocalSpot[0] = random->RandomFloat(-0.5,0.5) * size[0]; vecLocalSpot[1] = random->RandomFloat(-0.5,0.5) * size[1]; vecLocalSpot[2] = random->RandomFloat(-0.5,0.5) * size[2]; VectorTransform( vecLocalSpot, transform, vecSpot ); pTemp = TempEntAlloc(vecSpot, pModel); if (!pTemp) return; // keep track of break_type, so we know how to play sound on collision pTemp->hitSound = flags; if ( modelinfo->GetModelType( pModel ) == mod_sprite ) { pTemp->m_flFrame = random->RandomInt(0,frameCount-1); } else if ( modelinfo->GetModelType( pModel ) == mod_studio ) { pTemp->m_nBody = random->RandomInt(0,frameCount-1); } pTemp->flags |= FTENT_COLLIDEWORLD | FTENT_FADEOUT | FTENT_SLOWGRAVITY; if ( random->RandomInt(0,255) < 200 ) { pTemp->flags |= FTENT_ROTATE; pTemp->m_vecTempEntAngVelocity[0] = random->RandomFloat(-256,255); pTemp->m_vecTempEntAngVelocity[1] = random->RandomFloat(-256,255); pTemp->m_vecTempEntAngVelocity[2] = random->RandomFloat(-256,255); } if ( (random->RandomInt(0,255) < 100 ) && (flags & BREAK_SMOKE) ) { pTemp->flags |= FTENT_SMOKETRAIL; } if ((flags & BREAK_GLASS) || (flags & BREAK_TRANS)) { pTemp->SetRenderMode( kRenderTransTexture ); pTemp->SetRenderColorA( 128 ); pTemp->tempent_renderamt = 128; pTemp->bounceFactor = 0.3f; } else { pTemp->SetRenderMode( kRenderNormal ); pTemp->tempent_renderamt = 255; // Set this for fadeout } pTemp->SetVelocity( Vector( dir[0] + random->RandomFloat(-randRange,randRange), dir[1] + random->RandomFloat(-randRange,randRange), dir[2] + random->RandomFloat( 0,randRange) ) ); pTemp->die = gpGlobals->curtime + life + random->RandomFloat(0,1); // Add an extra 0-1 secs of life // We use a special rendering function because these objects will want to share their lighting // origin with the first/master object. Prevents a huge spike in Light Cache building in maps // with many worldlights. pTemp->SetDrawHelper( BreakModelDrawHelper ); g_BreakableHelper.Insert( pTemp, isSlave ); } } void CTempEnts::PhysicsProp( int modelindex, int skin, const Vector& pos, const QAngle &angles, const Vector& vel, int flags, int effects ) { C_PhysPropClientside *pEntity = C_PhysPropClientside::CreateNew(); if ( !pEntity ) return; const model_t *model = modelinfo->GetModel( modelindex ); if ( !model ) { DevMsg("CTempEnts::PhysicsProp: model index %i not found\n", modelindex ); return; } pEntity->SetModelName( modelinfo->GetModelName(model) ); pEntity->m_nSkin = skin; pEntity->SetAbsOrigin( pos ); pEntity->SetAbsAngles( angles ); pEntity->SetPhysicsMode( PHYSICS_MULTIPLAYER_CLIENTSIDE ); pEntity->SetEffects( effects ); if ( !pEntity->Initialize() ) { pEntity->Release(); return; } IPhysicsObject *pPhysicsObject = pEntity->VPhysicsGetObject(); if( pPhysicsObject ) { pPhysicsObject->AddVelocity( &vel, NULL ); } else { // failed to create a physics object pEntity->Release(); return; } if ( flags & 1 ) { pEntity->SetHealth( 0 ); pEntity->Break(); } } //----------------------------------------------------------------------------- // Purpose: Create a clientside projectile // Input : vecOrigin - // vecVelocity - // modelindex - // lifetime - // *pOwner - //----------------------------------------------------------------------------- C_LocalTempEntity *CTempEnts::ClientProjectile( const Vector& vecOrigin, const Vector& vecVelocity, const Vector& vecAcceleration, int modelIndex, int lifetime, CBaseEntity *pOwner, const char *pszImpactEffect, const char *pszParticleEffect ) { C_LocalTempEntity *pTemp; const model_t *model; if ( !modelIndex ) return NULL; model = modelinfo->GetModel( modelIndex ); if ( !model ) { Warning("ClientProjectile: No model %d!\n", modelIndex); return NULL; } pTemp = TempEntAlloc( vecOrigin, model ); if (!pTemp) return NULL; pTemp->SetVelocity( vecVelocity ); pTemp->SetAcceleration( vecAcceleration ); QAngle angles; VectorAngles( vecVelocity, angles ); pTemp->SetAbsAngles( angles ); pTemp->SetAbsOrigin( vecOrigin ); pTemp->die = gpGlobals->curtime + lifetime; pTemp->flags = FTENT_COLLIDEALL | FTENT_ATTACHTOTARGET | FTENT_ALIGNTOMOTION; pTemp->clientIndex = ( pOwner != NULL ) ? pOwner->entindex() : 0; pTemp->SetOwnerEntity( pOwner ); pTemp->SetImpactEffect( pszImpactEffect ); if ( pszParticleEffect ) { // Add the entity to the ClientEntityList and create the particle system. ClientEntityList().AddNonNetworkableEntity( pTemp ); pTemp->ParticleProp()->Create( pszParticleEffect, PATTACH_ABSORIGIN_FOLLOW ); // Set the particle flag on the temp entity and save the name of the particle effect. pTemp->flags |= FTENT_CLIENTSIDEPARTICLES; pTemp->SetParticleEffect( pszParticleEffect ); } return pTemp; } //----------------------------------------------------------------------------- // Purpose: Create sprite TE // Input : *pos - // *dir - // scale - // modelIndex - // rendermode - // renderfx - // a - // life - // flags - // Output : C_LocalTempEntity //----------------------------------------------------------------------------- C_LocalTempEntity *CTempEnts::TempSprite( const Vector &pos, const Vector &dir, float scale, int modelIndex, int rendermode, int renderfx, float a, float life, int flags, const Vector &normal ) { C_LocalTempEntity *pTemp; const model_t *model; int frameCount; if ( !modelIndex ) return NULL; model = modelinfo->GetModel( modelIndex ); if ( !model ) { Warning("No model %d!\n", modelIndex); return NULL; } frameCount = modelinfo->GetModelFrameCount( model ); pTemp = TempEntAlloc( pos, model ); if (!pTemp) return NULL; pTemp->m_flFrameMax = frameCount - 1; pTemp->m_flFrameRate = 10; pTemp->SetRenderMode( (RenderMode_t)rendermode ); pTemp->m_nRenderFX = renderfx; pTemp->m_flSpriteScale = scale; pTemp->tempent_renderamt = a * 255; pTemp->m_vecNormal = normal; pTemp->SetRenderColor( 255, 255, 255, a * 255 ); pTemp->flags |= flags; pTemp->SetVelocity( dir ); pTemp->SetLocalOrigin( pos ); if ( life ) pTemp->die = gpGlobals->curtime + life; else pTemp->die = gpGlobals->curtime + (frameCount * 0.1) + 1; pTemp->m_flFrame = 0; return pTemp; } //----------------------------------------------------------------------------- // Purpose: Spray sprite // Input : *pos - // *dir - // modelIndex - // count - // speed - // iRand - //----------------------------------------------------------------------------- void CTempEnts::Sprite_Spray( const Vector &pos, const Vector &dir, int modelIndex, int count, int speed, int iRand ) { C_LocalTempEntity *pTemp; const model_t *pModel; float noise; float znoise; int frameCount; int i; noise = (float)iRand / 100; // more vertical displacement znoise = noise * 1.5; if ( znoise > 1 ) { znoise = 1; } pModel = modelinfo->GetModel( modelIndex ); if ( !pModel ) { Warning("No model %d!\n", modelIndex); return; } frameCount = modelinfo->GetModelFrameCount( pModel ) - 1; for ( i = 0; i < count; i++ ) { pTemp = TempEntAlloc( pos, pModel ); if (!pTemp) return; pTemp->SetRenderMode( kRenderTransAlpha ); pTemp->SetRenderColor( 255, 255, 255, 255 ); pTemp->tempent_renderamt = 255; pTemp->m_nRenderFX = kRenderFxNoDissipation; //pTemp->scale = random->RandomFloat( 0.1, 0.25 ); pTemp->m_flSpriteScale = 0.5; pTemp->flags |= FTENT_FADEOUT | FTENT_SLOWGRAVITY; pTemp->fadeSpeed = 2.0; // make the spittle fly the direction indicated, but mix in some noise. Vector velocity; velocity.x = dir[ 0 ] + random->RandomFloat ( -noise, noise ); velocity.y = dir[ 1 ] + random->RandomFloat ( -noise, noise ); velocity.z = dir[ 2 ] + random->RandomFloat ( 0, znoise ); velocity *= random->RandomFloat( (speed * 0.8), (speed * 1.2) ); pTemp->SetVelocity( velocity ); pTemp->SetLocalOrigin( pos ); pTemp->die = gpGlobals->curtime + 0.35; pTemp->m_flFrame = random->RandomInt( 0, frameCount ); } } void CTempEnts::Sprite_Trail( const Vector &vecStart, const Vector &vecEnd, int modelIndex, int nCount, float flLife, float flSize, float flAmplitude, int nRenderamt, float flSpeed ) { C_LocalTempEntity *pTemp; const model_t *pModel; int flFrameCount; pModel = modelinfo->GetModel( modelIndex ); if ( !pModel ) { Warning("No model %d!\n", modelIndex); return; } flFrameCount = modelinfo->GetModelFrameCount( pModel ); Vector vecDelta; VectorSubtract( vecEnd, vecStart, vecDelta ); Vector vecDir; VectorCopy( vecDelta, vecDir ); VectorNormalize( vecDir ); flAmplitude /= 256.0; for ( int i = 0 ; i < nCount; i++ ) { Vector vecPos; // Be careful of divide by 0 when using 'count' here... if ( i == 0 ) { VectorMA( vecStart, 0, vecDelta, vecPos ); } else { VectorMA( vecStart, i / (nCount - 1.0), vecDelta, vecPos ); } pTemp = TempEntAlloc( vecPos, pModel ); if (!pTemp) return; pTemp->flags |= FTENT_COLLIDEWORLD | FTENT_SPRCYCLE | FTENT_FADEOUT | FTENT_SLOWGRAVITY; Vector vecVel = vecDir * flSpeed; vecVel.x += random->RandomInt( -127,128 ) * flAmplitude; vecVel.y += random->RandomInt( -127,128 ) * flAmplitude; vecVel.z += random->RandomInt( -127,128 ) * flAmplitude; pTemp->SetVelocity( vecVel ); pTemp->SetLocalOrigin( vecPos ); pTemp->m_flSpriteScale = flSize; pTemp->SetRenderMode( kRenderGlow ); pTemp->m_nRenderFX = kRenderFxNoDissipation; pTemp->tempent_renderamt = nRenderamt; pTemp->SetRenderColor( 255, 255, 255 ); pTemp->m_flFrame = random->RandomInt( 0, flFrameCount - 1 ); pTemp->m_flFrameMax = flFrameCount - 1; pTemp->die = gpGlobals->curtime + flLife + random->RandomFloat( 0, 4 ); } } //----------------------------------------------------------------------------- // Purpose: Attaches entity to player // Input : client - // modelIndex - // zoffset - // life - //----------------------------------------------------------------------------- void CTempEnts::AttachTentToPlayer( int client, int modelIndex, float zoffset, float life ) { C_LocalTempEntity *pTemp; const model_t *pModel; Vector position; int frameCount; if ( client <= 0 || client > gpGlobals->maxClients ) { Warning("Bad client in AttachTentToPlayer()!\n"); return; } IClientEntity *clientClass = cl_entitylist->GetClientEntity( client ); if ( !clientClass ) { Warning("Couldn't get IClientEntity for %i\n", client ); return; } pModel = modelinfo->GetModel( modelIndex ); if ( !pModel ) { Warning("No model %d!\n", modelIndex); return; } VectorCopy( clientClass->GetAbsOrigin(), position ); position[ 2 ] += zoffset; pTemp = TempEntAllocHigh( position, pModel ); if (!pTemp) { Warning("No temp ent.\n"); return; } pTemp->SetRenderMode( kRenderNormal ); pTemp->SetRenderColorA( 255 ); pTemp->tempent_renderamt = 255; pTemp->m_nRenderFX = kRenderFxNoDissipation; pTemp->clientIndex = client; pTemp->tentOffset[ 0 ] = 0; pTemp->tentOffset[ 1 ] = 0; pTemp->tentOffset[ 2 ] = zoffset; pTemp->die = gpGlobals->curtime + life; pTemp->flags |= FTENT_PLYRATTACHMENT | FTENT_PERSIST; // is the model a sprite? if ( modelinfo->GetModelType( pTemp->GetModel() ) == mod_sprite ) { frameCount = modelinfo->GetModelFrameCount( pModel ); pTemp->m_flFrameMax = frameCount - 1; pTemp->flags |= FTENT_SPRANIMATE | FTENT_SPRANIMATELOOP; pTemp->m_flFrameRate = 10; } else { // no animation support for attached clientside studio models. pTemp->m_flFrameMax = 0; } pTemp->m_flFrame = 0; } //----------------------------------------------------------------------------- // Purpose: Detach entity from player //----------------------------------------------------------------------------- void CTempEnts::KillAttachedTents( int client ) { if ( client <= 0 || client > gpGlobals->maxClients ) { Warning("Bad client in KillAttachedTents()!\n"); return; } FOR_EACH_LL( m_TempEnts, i ) { C_LocalTempEntity *pTemp = m_TempEnts[ i ]; if ( pTemp->flags & FTENT_PLYRATTACHMENT ) { // this TENT is player attached. // if it is attached to this client, set it to die instantly. if ( pTemp->clientIndex == client ) { pTemp->die = gpGlobals->curtime;// good enough, it will die on next tent update. } } } } //----------------------------------------------------------------------------- // Purpose: Create ricochet sprite // Input : *pos - // *pmodel - // duration - // scale - //----------------------------------------------------------------------------- void CTempEnts::RicochetSprite( const Vector &pos, model_t *pmodel, float duration, float scale ) { C_LocalTempEntity *pTemp; pTemp = TempEntAlloc( pos, pmodel ); if (!pTemp) return; pTemp->SetRenderMode( kRenderGlow ); pTemp->m_nRenderFX = kRenderFxNoDissipation; pTemp->SetRenderColorA( 200 ); pTemp->tempent_renderamt = 200; pTemp->m_flSpriteScale = scale; pTemp->flags = FTENT_FADEOUT; pTemp->SetVelocity( vec3_origin ); pTemp->SetLocalOrigin( pos ); pTemp->fadeSpeed = 8; pTemp->die = gpGlobals->curtime; pTemp->m_flFrame = 0; pTemp->SetLocalAnglesDim( Z_INDEX, 45 * random->RandomInt( 0, 7 ) ); } //----------------------------------------------------------------------------- // Purpose: Create blood sprite // Input : *org - // colorindex - // modelIndex - // modelIndex2 - // size - //----------------------------------------------------------------------------- void CTempEnts::BloodSprite( const Vector &org, int r, int g, int b, int a, int modelIndex, int modelIndex2, float size ) { const model_t *model; //Validate the model first if ( modelIndex && (model = modelinfo->GetModel( modelIndex ) ) != NULL ) { C_LocalTempEntity *pTemp; int frameCount = modelinfo->GetModelFrameCount( model ); color32 impactcolor = { (byte)r, (byte)g, (byte)b, (byte)a }; //Large, single blood sprite is a high-priority tent if ( ( pTemp = TempEntAllocHigh( org, model ) ) != NULL ) { pTemp->SetRenderMode( kRenderTransTexture ); pTemp->m_nRenderFX = kRenderFxClampMinScale; pTemp->m_flSpriteScale = random->RandomFloat( size / 25, size / 35); pTemp->flags = FTENT_SPRANIMATE; pTemp->m_clrRender = impactcolor; pTemp->tempent_renderamt= pTemp->m_clrRender->a; pTemp->SetVelocity( vec3_origin ); pTemp->m_flFrameRate = frameCount * 4; // Finish in 0.250 seconds pTemp->die = gpGlobals->curtime + (frameCount / pTemp->m_flFrameRate); // Play the whole thing Once pTemp->m_flFrame = 0; pTemp->m_flFrameMax = frameCount - 1; pTemp->bounceFactor = 0; pTemp->SetLocalAnglesDim( Z_INDEX, random->RandomInt( 0, 360 ) ); } } } //----------------------------------------------------------------------------- // Purpose: Create default sprite TE // Input : *pos - // spriteIndex - // framerate - // Output : C_LocalTempEntity //----------------------------------------------------------------------------- C_LocalTempEntity *CTempEnts::DefaultSprite( const Vector &pos, int spriteIndex, float framerate ) { C_LocalTempEntity *pTemp; int frameCount; const model_t *pSprite; // don't spawn while paused if ( gpGlobals->frametime == 0.0 ) return NULL; pSprite = modelinfo->GetModel( spriteIndex ); if ( !spriteIndex || !pSprite || modelinfo->GetModelType( pSprite ) != mod_sprite ) { DevWarning( 1,"No Sprite %d!\n", spriteIndex); return NULL; } frameCount = modelinfo->GetModelFrameCount( pSprite ); pTemp = TempEntAlloc( pos, pSprite ); if (!pTemp) return NULL; pTemp->m_flFrameMax = frameCount - 1; pTemp->m_flSpriteScale = 1.0; pTemp->flags |= FTENT_SPRANIMATE; if ( framerate == 0 ) framerate = 10; pTemp->m_flFrameRate = framerate; pTemp->die = gpGlobals->curtime + (float)frameCount / framerate; pTemp->m_flFrame = 0; pTemp->SetLocalOrigin( pos ); return pTemp; } //----------------------------------------------------------------------------- // Purpose: Create sprite smoke // Input : *pTemp - // scale - //----------------------------------------------------------------------------- void CTempEnts::Sprite_Smoke( C_LocalTempEntity *pTemp, float scale ) { if ( !pTemp ) return; pTemp->SetRenderMode( kRenderTransAlpha ); pTemp->m_nRenderFX = kRenderFxNone; pTemp->SetVelocity( Vector( 0, 0, 30 ) ); int iColor = random->RandomInt(20,35); pTemp->SetRenderColor( iColor, iColor, iColor, 255 ); pTemp->SetLocalOriginDim( Z_INDEX, pTemp->GetLocalOriginDim( Z_INDEX ) + 20 ); pTemp->m_flSpriteScale = scale; pTemp->flags = FTENT_WINDBLOWN; } //----------------------------------------------------------------------------- // Purpose: // Input : pos1 - // angles - // type - //----------------------------------------------------------------------------- void CTempEnts::EjectBrass( const Vector &pos1, const QAngle &angles, const QAngle &gunAngles, int type ) { if ( cl_ejectbrass.GetBool() == false ) return; const model_t *pModel = m_pShells[type]; if ( pModel == NULL ) return; C_LocalTempEntity *pTemp = TempEntAlloc( pos1, pModel ); if ( pTemp == NULL ) return; //Keep track of shell type if ( type == 2 ) { pTemp->hitSound = BOUNCE_SHOTSHELL; } #ifdef GE_DLL else if ( type == 3 ) { pTemp->hitSound = BOUNCE_GRENADE; } else if ( type > 3 ) { pTemp->hitSound = BOUNCE_METAL; } #endif else { pTemp->hitSound = BOUNCE_SHELL; } pTemp->m_nBody = 0; pTemp->flags |= ( FTENT_COLLIDEWORLD | FTENT_FADEOUT | FTENT_GRAVITY | FTENT_ROTATE ); pTemp->m_vecTempEntAngVelocity[0] = random->RandomFloat(-1024,1024); pTemp->m_vecTempEntAngVelocity[1] = random->RandomFloat(-1024,1024); pTemp->m_vecTempEntAngVelocity[2] = random->RandomFloat(-1024,1024); //Face forward pTemp->SetAbsAngles( gunAngles ); pTemp->SetRenderMode( kRenderNormal ); pTemp->tempent_renderamt = 255; // Set this for fadeout Vector dir; AngleVectors( angles, &dir ); dir *= random->RandomFloat( 150.0f, 200.0f ); pTemp->SetVelocity( Vector(dir[0] + random->RandomFloat(-64,64), dir[1] + random->RandomFloat(-64,64), dir[2] + random->RandomFloat( 0,64) ) ); pTemp->die = gpGlobals->curtime + 1.0f + random->RandomFloat( 0.0f, 1.0f ); // Add an extra 0-1 secs of life } //----------------------------------------------------------------------------- // Purpose: Create some simple physically simulated models //----------------------------------------------------------------------------- C_LocalTempEntity * CTempEnts::SpawnTempModel( const model_t *pModel, const Vector &vecOrigin, const QAngle &vecAngles, const Vector &vecVelocity, float flLifeTime, int iFlags ) { Assert( pModel ); // Alloc a new tempent C_LocalTempEntity *pTemp = TempEntAlloc( vecOrigin, pModel ); if ( !pTemp ) return NULL; pTemp->SetAbsAngles( vecAngles ); pTemp->m_nBody = 0; pTemp->flags |= iFlags; pTemp->m_vecTempEntAngVelocity[0] = random->RandomFloat(-255,255); pTemp->m_vecTempEntAngVelocity[1] = random->RandomFloat(-255,255); pTemp->m_vecTempEntAngVelocity[2] = random->RandomFloat(-255,255); pTemp->SetRenderMode( kRenderNormal ); pTemp->tempent_renderamt = 255; pTemp->SetVelocity( vecVelocity ); pTemp->die = gpGlobals->curtime + flLifeTime; return pTemp; } //----------------------------------------------------------------------------- // Purpose: // Input : type - // entityIndex - // attachmentIndex - // firstPerson - //----------------------------------------------------------------------------- void CTempEnts::MuzzleFlash( int type, ClientEntityHandle_t hEntity, int attachmentIndex, bool firstPerson ) { switch( type ) { case MUZZLEFLASH_COMBINE: if ( firstPerson ) { MuzzleFlash_Combine_Player( hEntity, attachmentIndex ); } else { MuzzleFlash_Combine_NPC( hEntity, attachmentIndex ); } break; case MUZZLEFLASH_SMG1: if ( firstPerson ) { MuzzleFlash_SMG1_Player( hEntity, attachmentIndex ); } else { MuzzleFlash_SMG1_NPC( hEntity, attachmentIndex ); } break; case MUZZLEFLASH_PISTOL: if ( firstPerson ) { MuzzleFlash_Pistol_Player( hEntity, attachmentIndex ); } else { MuzzleFlash_Pistol_NPC( hEntity, attachmentIndex ); } break; case MUZZLEFLASH_SHOTGUN: if ( firstPerson ) { MuzzleFlash_Shotgun_Player( hEntity, attachmentIndex ); } else { MuzzleFlash_Shotgun_NPC( hEntity, attachmentIndex ); } break; case MUZZLEFLASH_357: if ( firstPerson ) { MuzzleFlash_357_Player( hEntity, attachmentIndex ); } break; case MUZZLEFLASH_RPG: if ( firstPerson ) { // MuzzleFlash_RPG_Player( hEntity, attachmentIndex ); } else { MuzzleFlash_RPG_NPC( hEntity, attachmentIndex ); } break; break; default: { //NOTENOTE: This means you specified an invalid muzzleflash type, check your spelling? Assert( 0 ); } break; } } //----------------------------------------------------------------------------- // Purpose: Play muzzle flash // Input : *pos1 - // type - //----------------------------------------------------------------------------- void CTempEnts::MuzzleFlash( const Vector& pos1, const QAngle& angles, int type, ClientEntityHandle_t hEntity, bool firstPerson ) { #ifdef CSTRIKE_DLL return; #else //NOTENOTE: This function is becoming obsolete as the muzzles are moved over to being local to attachments switch ( type ) { // // Shotgun // case MUZZLEFLASH_SHOTGUN: if ( firstPerson ) { MuzzleFlash_Shotgun_Player( hEntity, 1 ); } else { MuzzleFlash_Shotgun_NPC( hEntity, 1 ); } break; // UNDONE: These need their own effects/sprites. For now use the pistol // SMG1 case MUZZLEFLASH_SMG1: if ( firstPerson ) { MuzzleFlash_SMG1_Player( hEntity, 1 ); } else { MuzzleFlash_SMG1_NPC( hEntity, 1 ); } break; // SMG2 case MUZZLEFLASH_SMG2: case MUZZLEFLASH_PISTOL: if ( firstPerson ) { MuzzleFlash_Pistol_Player( hEntity, 1 ); } else { MuzzleFlash_Pistol_NPC( hEntity, 1 ); } break; case MUZZLEFLASH_COMBINE: if ( firstPerson ) { //FIXME: These should go away MuzzleFlash_Combine_Player( hEntity, 1 ); } else { //FIXME: These should go away MuzzleFlash_Combine_NPC( hEntity, 1 ); } break; default: // There's no supported muzzle flash for the type specified! Assert(0); break; } #endif } //----------------------------------------------------------------------------- // Purpose: Create explosion sprite // Input : *pTemp - // scale - // flags - //----------------------------------------------------------------------------- void CTempEnts::Sprite_Explode( C_LocalTempEntity *pTemp, float scale, int flags ) { if ( !pTemp ) return; if ( flags & TE_EXPLFLAG_NOADDITIVE ) { // solid sprite pTemp->SetRenderMode( kRenderNormal ); pTemp->SetRenderColorA( 255 ); } else if( flags & TE_EXPLFLAG_DRAWALPHA ) { // alpha sprite pTemp->SetRenderMode( kRenderTransAlpha ); pTemp->SetRenderColorA( 180 ); } else { // additive sprite pTemp->SetRenderMode( kRenderTransAdd ); pTemp->SetRenderColorA( 180 ); } if ( flags & TE_EXPLFLAG_ROTATE ) { pTemp->SetLocalAnglesDim( Z_INDEX, random->RandomInt( 0, 360 ) ); } pTemp->m_nRenderFX = kRenderFxNone; pTemp->SetVelocity( Vector( 0, 0, 8 ) ); pTemp->SetRenderColor( 255, 255, 255 ); pTemp->SetLocalOriginDim( Z_INDEX, pTemp->GetLocalOriginDim( Z_INDEX ) + 10 ); pTemp->m_flSpriteScale = scale; } enum { SHELL_NONE = 0, SHELL_SMALL, SHELL_BIG, SHELL_SHOTGUN, }; //----------------------------------------------------------------------------- // Purpose: Clear existing temp entities //----------------------------------------------------------------------------- void CTempEnts::Clear( void ) { FOR_EACH_LL( m_TempEnts, i ) { C_LocalTempEntity *p = m_TempEnts[ i ]; m_TempEntsPool.Free( p ); } m_TempEnts.RemoveAll(); g_BreakableHelper.Clear(); } C_LocalTempEntity *CTempEnts::FindTempEntByID( int nID, int nSubID ) { // HACK HACK: We're using skin and hitsounds as a hacky way to store an ID and sub-ID for later identification FOR_EACH_LL( m_TempEnts, i ) { C_LocalTempEntity *p = m_TempEnts[ i ]; if ( p && p->m_nSkin == nID && p->hitSound == nSubID ) { return p; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: Allocate temp entity ( normal/low priority ) // Input : *org - // *model - // Output : C_LocalTempEntity //----------------------------------------------------------------------------- C_LocalTempEntity *CTempEnts::TempEntAlloc( const Vector& org, const model_t *model ) { C_LocalTempEntity *pTemp; if ( !model ) { DevWarning( 1, "Can't create temporary entity with NULL model!\n" ); return NULL; } pTemp = TempEntAlloc(); if ( !pTemp ) { DevWarning( 1, "Overflow %d temporary ents!\n", MAX_TEMP_ENTITIES ); return NULL; } m_TempEnts.AddToTail( pTemp ); pTemp->Prepare( model, gpGlobals->curtime ); pTemp->priority = TENTPRIORITY_LOW; pTemp->SetAbsOrigin( org ); pTemp->m_RenderGroup = RENDER_GROUP_OTHER; pTemp->AddToLeafSystem( pTemp->m_RenderGroup ); if ( CommandLine()->CheckParm( "-tools" ) != NULL ) { #ifdef _DEBUG static bool first = true; if ( first ) { Msg( "Currently not recording tempents, since recording them as entites causes them to be deleted as entities, even though they were allocated through the tempent pool. (crash)\n" ); first = false; } #endif // ClientEntityList().AddNonNetworkableEntity( pTemp ); } return pTemp; } //----------------------------------------------------------------------------- // Purpose: // Output : C_LocalTempEntity //----------------------------------------------------------------------------- C_LocalTempEntity *CTempEnts::TempEntAlloc() { if ( m_TempEnts.Count() >= MAX_TEMP_ENTITIES ) return NULL; C_LocalTempEntity *pTemp = m_TempEntsPool.AllocZero(); return pTemp; } void CTempEnts::TempEntFree( int index ) { C_LocalTempEntity *pTemp = m_TempEnts[ index ]; if ( pTemp ) { // Remove from the active list. m_TempEnts.Remove( index ); // Cleanup its data. pTemp->RemoveFromLeafSystem(); // Remove the tempent from the ClientEntityList before removing it from the pool. if ( ( pTemp->flags & FTENT_CLIENTSIDEPARTICLES ) ) { // Stop the particle emission if this hasn't happened already - collision or system timing out on its own. if ( !pTemp->m_bParticleCollision ) { pTemp->ParticleProp()->StopEmission(); } ClientEntityList().RemoveEntity( pTemp->GetRefEHandle() ); } pTemp->OnRemoveTempEntity(); m_TempEntsPool.Free( pTemp ); } } // Free the first low priority tempent it finds. bool CTempEnts::FreeLowPriorityTempEnt() { int next = 0; for( int i = m_TempEnts.Head(); i != m_TempEnts.InvalidIndex(); i = next ) { next = m_TempEnts.Next( i ); C_LocalTempEntity *pActive = m_TempEnts[ i ]; if ( pActive->priority == TENTPRIORITY_LOW ) { TempEntFree( i ); return true; } } return false; } //----------------------------------------------------------------------------- // Purpose: Allocate a temp entity, if there are no slots, kick out a low priority // one if possible // Input : *org - // *model - // Output : C_LocalTempEntity //----------------------------------------------------------------------------- C_LocalTempEntity *CTempEnts::TempEntAllocHigh( const Vector& org, const model_t *model ) { C_LocalTempEntity *pTemp; if ( !model ) { DevWarning( 1, "temporary ent model invalid\n" ); return NULL; } pTemp = TempEntAlloc(); if ( !pTemp ) { // no temporary ents free, so find the first active low-priority temp ent // and overwrite it. FreeLowPriorityTempEnt(); pTemp = TempEntAlloc(); } if ( !pTemp ) { // didn't find anything? The tent list is either full of high-priority tents // or all tents in the list are still due to live for > 10 seconds. DevWarning( 1,"Couldn't alloc a high priority TENT (max %i)!\n", MAX_TEMP_ENTITIES ); return NULL; } m_TempEnts.AddToTail( pTemp ); pTemp->Prepare( model, gpGlobals->curtime ); pTemp->priority = TENTPRIORITY_HIGH; pTemp->SetLocalOrigin( org ); pTemp->m_RenderGroup = RENDER_GROUP_OTHER; pTemp->AddToLeafSystem( pTemp->m_RenderGroup ); if ( CommandLine()->CheckParm( "-tools" ) != NULL ) { ClientEntityList().AddNonNetworkableEntity( pTemp ); } return pTemp; } //----------------------------------------------------------------------------- // Purpose: Play sound when temp ent collides with something // Input : *pTemp - // damp - //----------------------------------------------------------------------------- void CTempEnts::PlaySound ( C_LocalTempEntity *pTemp, float damp ) { const char *soundname = NULL; float fvol; bool isshellcasing = false; int zvel; switch ( pTemp->hitSound ) { default: return; // null sound case BOUNCE_GLASS: { soundname = "Bounce.Glass"; } break; case BOUNCE_METAL: { soundname = "Bounce.Metal"; } break; case BOUNCE_FLESH: { soundname = "Bounce.Flesh"; } break; case BOUNCE_WOOD: { soundname = "Bounce.Wood"; } break; case BOUNCE_SHRAP: { soundname = "Bounce.Shrapnel"; } break; case BOUNCE_SHOTSHELL: { soundname = "Bounce.ShotgunShell"; isshellcasing = true; // shell casings have different playback parameters } break; case BOUNCE_SHELL: { soundname = "Bounce.Shell"; isshellcasing = true; // shell casings have different playback parameters } break; case BOUNCE_CONCRETE: { soundname = "Bounce.Concrete"; } break; #ifdef GE_DLL case BOUNCE_GRENADE: { soundname = "Grenade.ImpactHard"; } break; #endif #ifdef CSTRIKE_DLL case TE_PISTOL_SHELL: { soundname = "Bounce.PistolShell"; } break; case TE_RIFLE_SHELL: { soundname = "Bounce.RifleShell"; } break; case TE_SHOTGUN_SHELL: { soundname = "Bounce.ShotgunShell"; } break; #endif } zvel = abs( pTemp->GetVelocity()[2] ); // only play one out of every n if ( isshellcasing ) { // play first bounce, then 1 out of 3 if ( zvel < 200 && random->RandomInt(0,3) ) return; } else { if ( random->RandomInt(0,5) ) return; } CSoundParameters params; if ( !C_BaseEntity::GetParametersForSound( soundname, params, NULL ) ) return; fvol = params.volume; if ( damp > 0.0 ) { int pitch; if ( isshellcasing ) { fvol *= MIN (1.0, ((float)zvel) / 350.0); } else { fvol *= MIN (1.0, ((float)zvel) / 450.0); } if ( !random->RandomInt(0,3) && !isshellcasing ) { pitch = random->RandomInt( params.pitchlow, params.pitchhigh ); } else { pitch = params.pitch; } CLocalPlayerFilter filter; EmitSound_t ep; ep.m_nChannel = params.channel; ep.m_pSoundName = params.soundname; ep.m_flVolume = fvol; ep.m_SoundLevel = params.soundlevel; ep.m_nPitch = pitch; ep.m_pOrigin = &pTemp->GetAbsOrigin(); C_BaseEntity::EmitSound( filter, SOUND_FROM_WORLD, ep ); } } //----------------------------------------------------------------------------- // Purpose: Add temp entity to visible entities list of it's in PVS // Input : *pEntity - // Output : int //----------------------------------------------------------------------------- int CTempEnts::AddVisibleTempEntity( C_LocalTempEntity *pEntity ) { int i; Vector mins, maxs; Vector model_mins, model_maxs; if ( !pEntity->GetModel() ) return 0; modelinfo->GetModelBounds( pEntity->GetModel(), model_mins, model_maxs ); for (i=0 ; i<3 ; i++) { mins[i] = pEntity->GetAbsOrigin()[i] + model_mins[i]; maxs[i] = pEntity->GetAbsOrigin()[i] + model_maxs[i]; } // FIXME: Vis isn't setup by the time we get here, so this call fails if // you try to add a tempent before the first frame is drawn, and it's // one frame behind the rest of the time. Fix this. // does the box intersect a visible leaf? //if ( engine->IsBoxInViewCluster( mins, maxs ) ) { // Temporary entities have no corresponding element in cl_entitylist pEntity->index = -1; // Add to list if( pEntity->m_RenderGroup == RENDER_GROUP_OTHER ) { pEntity->AddToLeafSystem(); } else { pEntity->AddToLeafSystem( pEntity->m_RenderGroup ); } return 1; } return 0; } //----------------------------------------------------------------------------- // Purpose: Runs Temp Ent simulation routines //----------------------------------------------------------------------------- void CTempEnts::Update(void) { VPROF_("CTempEnts::Update", 1, VPROF_BUDGETGROUP_CLIENT_SIM, false, BUDGETFLAG_CLIENT); static int gTempEntFrame = 0; float frametime; // Don't simulate while loading if ( ( m_TempEnts.Count() == 0 ) || !engine->IsInGame() ) { return; } // !!!BUGBUG -- This needs to be time based gTempEntFrame = (gTempEntFrame+1) & 31; frametime = gpGlobals->frametime; // in order to have tents collide with players, we have to run the player prediction code so // that the client has the player list. We run this code once when we detect any COLLIDEALL // tent, then set this BOOL to true so the code doesn't get run again if there's more than // one COLLIDEALL ent for this update. (often are). // !!! Don't simulate while paused.... This is sort of a hack, revisit. if ( frametime == 0 ) { FOR_EACH_LL( m_TempEnts, i ) { C_LocalTempEntity *current = m_TempEnts[ i ]; AddVisibleTempEntity( current ); } } else { int next = 0; for( int i = m_TempEnts.Head(); i != m_TempEnts.InvalidIndex(); i = next ) { next = m_TempEnts.Next( i ); C_LocalTempEntity *current = m_TempEnts[ i ]; // Kill it if ( !current->IsActive() || !current->Frame( frametime, gTempEntFrame ) ) { TempEntFree( i ); } else { // Cull to PVS (not frustum cull, just PVS) if ( !AddVisibleTempEntity( current ) ) { if ( !( current->flags & FTENT_PERSIST ) ) { // If we can't draw it this frame, just dump it. current->die = gpGlobals->curtime; // Don't fade out, just die current->flags &= ~FTENT_FADEOUT; TempEntFree( i ); } } } } } } // Recache tempents which might have been flushed void CTempEnts::LevelInit() { #ifndef TF_CLIENT_DLL m_pSpriteMuzzleFlash[0] = (model_t *)engine->LoadModel( "sprites/ar2_muzzle1.vmt" ); m_pSpriteMuzzleFlash[1] = (model_t *)engine->LoadModel( "sprites/muzzleflash4.vmt" ); m_pSpriteMuzzleFlash[2] = (model_t *)engine->LoadModel( "sprites/muzzleflash4.vmt" ); m_pSpriteAR2Flash[0] = (model_t *)engine->LoadModel( "sprites/ar2_muzzle1b.vmt" ); m_pSpriteAR2Flash[1] = (model_t *)engine->LoadModel( "sprites/ar2_muzzle2b.vmt" ); m_pSpriteAR2Flash[2] = (model_t *)engine->LoadModel( "sprites/ar2_muzzle3b.vmt" ); m_pSpriteAR2Flash[3] = (model_t *)engine->LoadModel( "sprites/ar2_muzzle4b.vmt" ); m_pSpriteCombineFlash[0] = (model_t *)engine->LoadModel( "effects/combinemuzzle1.vmt" ); m_pSpriteCombineFlash[1] = (model_t *)engine->LoadModel( "effects/combinemuzzle2.vmt" ); #ifdef GE_DLL m_pShells[0] = (model_t *) engine->LoadModel( "models/weapons/shells/pistolcase.mdl" ); m_pShells[1] = (model_t *) engine->LoadModel( "models/weapons/shells/riflecase.mdl" ); m_pShells[2] = (model_t *) engine->LoadModel( "models/weapons/shells/shotgunshell.mdl" ); m_pShells[3] = (model_t *) engine->LoadModel( "models/weapons/shells/grenadeshell.mdl" ); m_pShells[4] = (model_t *) engine->LoadModel( "models/weapons/mags/mag_pistol.mdl" ); m_pShells[5] = (model_t *) engine->LoadModel( "models/weapons/mags/mag_ar33.mdl" ); m_pShells[6] = (model_t *) engine->LoadModel( "models/weapons/mags/mag_d5k.mdl" ); m_pShells[7] = (model_t *) engine->LoadModel( "models/weapons/mags/mag_kf7.mdl" ); m_pShells[8] = (model_t *) engine->LoadModel( "models/weapons/mags/mag_phantom.mdl" ); #else m_pShells[0] = (model_t *) engine->LoadModel( "models/weapons/shell.mdl" ); m_pShells[1] = (model_t *) engine->LoadModel( "models/weapons/rifleshell.mdl" ); m_pShells[2] = (model_t *) engine->LoadModel( "models/weapons/shotgun_shell.mdl" ); #endif #endif #if defined( HL1_CLIENT_DLL ) m_pHL1Shell = (model_t *)engine->LoadModel( "models/shell.mdl" ); m_pHL1ShotgunShell = (model_t *)engine->LoadModel( "models/shotgunshell.mdl" ); #endif #if defined( CSTRIKE_DLL ) || defined ( SDK_DLL ) m_pCS_9MMShell = (model_t *)engine->LoadModel( "models/Shells/shell_9mm.mdl" ); m_pCS_57Shell = (model_t *)engine->LoadModel( "models/Shells/shell_57.mdl" ); m_pCS_12GaugeShell = (model_t *)engine->LoadModel( "models/Shells/shell_12gauge.mdl" ); m_pCS_556Shell = (model_t *)engine->LoadModel( "models/Shells/shell_556.mdl" ); m_pCS_762NATOShell = (model_t *)engine->LoadModel( "models/Shells/shell_762nato.mdl" ); m_pCS_338MAGShell = (model_t *)engine->LoadModel( "models/Shells/shell_338mag.mdl" ); #endif } //----------------------------------------------------------------------------- // Purpose: Initialize TE system //----------------------------------------------------------------------------- void CTempEnts::Init (void) { m_pSpriteMuzzleFlash[0] = NULL; m_pSpriteMuzzleFlash[1] = NULL; m_pSpriteMuzzleFlash[2] = NULL; m_pSpriteAR2Flash[0] = NULL; m_pSpriteAR2Flash[1] = NULL; m_pSpriteAR2Flash[2] = NULL; m_pSpriteAR2Flash[3] = NULL; m_pSpriteCombineFlash[0] = NULL; m_pSpriteCombineFlash[1] = NULL; m_pShells[0] = NULL; m_pShells[1] = NULL; m_pShells[2] = NULL; #ifdef GE_DLL m_pShells[3] = NULL; #endif #if defined( HL1_CLIENT_DLL ) m_pHL1Shell = NULL; m_pHL1ShotgunShell = NULL; #endif #if defined( CSTRIKE_DLL ) || defined ( SDK_DLL ) m_pCS_9MMShell = NULL; m_pCS_57Shell = NULL; m_pCS_12GaugeShell = NULL; m_pCS_556Shell = NULL; m_pCS_762NATOShell = NULL; m_pCS_338MAGShell = NULL; #endif // Clear out lists to start Clear(); } void CTempEnts::LevelShutdown() { // Free all active tempents. Clear(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTempEnts::Shutdown() { LevelShutdown(); } //----------------------------------------------------------------------------- // Purpose: Cache off all material references // Input : *pEmitter - Emitter used for material lookup //----------------------------------------------------------------------------- inline void CTempEnts::CacheMuzzleFlashes( void ) { int i; for ( i = 0; i < 4; i++ ) { if ( m_Material_MuzzleFlash_Player[i] == NULL ) { m_Material_MuzzleFlash_Player[i] = ParticleMgr()->GetPMaterial( VarArgs( "effects/muzzleflash%d_noz", i+1 ) ); } } for ( i = 0; i < 4; i++ ) { if ( m_Material_MuzzleFlash_NPC[i] == NULL ) { m_Material_MuzzleFlash_NPC[i] = ParticleMgr()->GetPMaterial( VarArgs( "effects/muzzleflash%d", i+1 ) ); } } for ( i = 0; i < 2; i++ ) { if ( m_Material_Combine_MuzzleFlash_Player[i] == NULL ) { m_Material_Combine_MuzzleFlash_Player[i] = ParticleMgr()->GetPMaterial( VarArgs( "effects/combinemuzzle%d_noz", i+1 ) ); } } for ( i = 0; i < 2; i++ ) { if ( m_Material_Combine_MuzzleFlash_NPC[i] == NULL ) { m_Material_Combine_MuzzleFlash_NPC[i] = ParticleMgr()->GetPMaterial( VarArgs( "effects/combinemuzzle%d", i+1 ) ); } } } //----------------------------------------------------------------------------- // Purpose: // Input : entityIndex - // attachmentIndex - //----------------------------------------------------------------------------- void CTempEnts::MuzzleFlash_Combine_Player( ClientEntityHandle_t hEntity, int attachmentIndex ) { VPROF_BUDGET( "MuzzleFlash_Combine_Player", VPROF_BUDGETGROUP_PARTICLE_RENDERING ); CSmartPtr<CLocalSpaceEmitter> pSimple = CLocalSpaceEmitter::Create( "MuzzleFlash", hEntity, attachmentIndex, FLE_VIEWMODEL ); CacheMuzzleFlashes(); SimpleParticle *pParticle; Vector forward(1,0,0), offset; //NOTENOTE: All coords are in local space float flScale = random->RandomFloat( 2.0f, 2.25f ); pSimple->SetDrawBeforeViewModel( true ); // Flash for ( int i = 1; i < 6; i++ ) { offset = (forward * (i*8.0f*flScale)); pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), m_Material_Combine_MuzzleFlash_Player[random->RandomInt(0,1)], offset ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = 0.025f; pParticle->m_vecVelocity.Init(); pParticle->m_uchColor[0] = 255; pParticle->m_uchColor[1] = 255; pParticle->m_uchColor[2] = 200+random->RandomInt(0,55); pParticle->m_uchStartAlpha = 255; pParticle->m_uchEndAlpha = 255; pParticle->m_uchStartSize = ( (random->RandomFloat( 6.0f, 8.0f ) * (12-(i))/12) * flScale ); pParticle->m_uchEndSize = pParticle->m_uchStartSize; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = 0.0f; } // Tack on the smoke pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), m_Material_Combine_MuzzleFlash_Player[random->RandomInt(0,1)], vec3_origin ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = 0.025f; pParticle->m_vecVelocity.Init(); pParticle->m_uchColor[0] = 255; pParticle->m_uchColor[1] = 255; pParticle->m_uchColor[2] = 255; pParticle->m_uchStartAlpha = random->RandomInt( 64, 128 ); pParticle->m_uchEndAlpha = 32; pParticle->m_uchStartSize = random->RandomFloat( 10.0f, 16.0f ); pParticle->m_uchEndSize = pParticle->m_uchStartSize; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = 0.0f; } //----------------------------------------------------------------------------- // Purpose: // Input : &origin - // &angles - // entityIndex - //----------------------------------------------------------------------------- void CTempEnts::MuzzleFlash_Combine_NPC( ClientEntityHandle_t hEntity, int attachmentIndex ) { VPROF_BUDGET( "MuzzleFlash_Combine_NPC", VPROF_BUDGETGROUP_PARTICLE_RENDERING ); // If the material isn't available, let's not do anything. if ( g_Mat_Combine_Muzzleflash[0] == NULL ) { return; } CSmartPtr<CLocalSpaceEmitter> pSimple = CLocalSpaceEmitter::Create( "MuzzleFlash_Combine_NPC", hEntity, attachmentIndex ); SimpleParticle *pParticle; Vector forward(1,0,0), offset; //NOTENOTE: All coords are in local space float flScale = random->RandomFloat( 1.0f, 1.5f ); float burstSpeed = random->RandomFloat( 50.0f, 150.0f ); #define FRONT_LENGTH 6 // Front flash for ( int i = 1; i < FRONT_LENGTH; i++ ) { offset = (forward * (i*2.0f*flScale)); pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), g_Mat_Combine_Muzzleflash[random->RandomInt(0,1)], offset ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = 0.1f; pParticle->m_vecVelocity = forward * burstSpeed; pParticle->m_uchColor[0] = 255; pParticle->m_uchColor[1] = 255; pParticle->m_uchColor[2] = 255; pParticle->m_uchStartAlpha = 255.0f; pParticle->m_uchEndAlpha = 0; pParticle->m_uchStartSize = ( (random->RandomFloat( 6.0f, 8.0f ) * (FRONT_LENGTH*1.25f-(i))/(FRONT_LENGTH)) * flScale ); pParticle->m_uchEndSize = pParticle->m_uchStartSize; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = 0.0f; } Vector right(0,1,0), up(0,0,1); Vector dir = right - up; #define SIDE_LENGTH 6 burstSpeed = random->RandomFloat( 50.0f, 150.0f ); // Diagonal flash for ( int i = 1; i < SIDE_LENGTH; i++ ) { offset = (dir * (i*flScale)); pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), g_Mat_Combine_Muzzleflash[random->RandomInt(0,1)], offset ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = 0.2f; pParticle->m_vecVelocity = dir * burstSpeed * 0.25f; pParticle->m_uchColor[0] = 255; pParticle->m_uchColor[1] = 255; pParticle->m_uchColor[2] = 255; pParticle->m_uchStartAlpha = 255; pParticle->m_uchEndAlpha = 0; pParticle->m_uchStartSize = ( (random->RandomFloat( 2.0f, 4.0f ) * (SIDE_LENGTH-(i))/(SIDE_LENGTH*0.5f)) * flScale ); pParticle->m_uchEndSize = pParticle->m_uchStartSize; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = 0.0f; } dir = right + up; burstSpeed = random->RandomFloat( 50.0f, 150.0f ); // Diagonal flash for ( int i = 1; i < SIDE_LENGTH; i++ ) { offset = (-dir * (i*flScale)); pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), g_Mat_Combine_Muzzleflash[random->RandomInt(0,1)], offset ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = 0.2f; pParticle->m_vecVelocity = dir * -burstSpeed * 0.25f; pParticle->m_uchColor[0] = 255; pParticle->m_uchColor[1] = 255; pParticle->m_uchColor[2] = 255; pParticle->m_uchStartAlpha = 255; pParticle->m_uchEndAlpha = 0; pParticle->m_uchStartSize = ( (random->RandomFloat( 2.0f, 4.0f ) * (SIDE_LENGTH-(i))/(SIDE_LENGTH*0.5f)) * flScale ); pParticle->m_uchEndSize = pParticle->m_uchStartSize; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = 0.0f; } dir = up; burstSpeed = random->RandomFloat( 50.0f, 150.0f ); // Top flash for ( int i = 1; i < SIDE_LENGTH; i++ ) { offset = (dir * (i*flScale)); pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), g_Mat_Combine_Muzzleflash[random->RandomInt(0,1)], offset ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = 0.2f; pParticle->m_vecVelocity = dir * burstSpeed * 0.25f; pParticle->m_uchColor[0] = 255; pParticle->m_uchColor[1] = 255; pParticle->m_uchColor[2] = 255; pParticle->m_uchStartAlpha = 255; pParticle->m_uchEndAlpha = 0; pParticle->m_uchStartSize = ( (random->RandomFloat( 2.0f, 4.0f ) * (SIDE_LENGTH-(i))/(SIDE_LENGTH*0.5f)) * flScale ); pParticle->m_uchEndSize = pParticle->m_uchStartSize; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = 0.0f; } pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), g_Mat_Combine_Muzzleflash[2], vec3_origin ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = random->RandomFloat( 0.3f, 0.4f ); pParticle->m_vecVelocity.Init(); pParticle->m_uchColor[0] = 255; pParticle->m_uchColor[1] = 255; pParticle->m_uchColor[2] = 255; pParticle->m_uchStartAlpha = 255; pParticle->m_uchEndAlpha = 0; pParticle->m_uchStartSize = flScale * random->RandomFloat( 12.0f, 16.0f ); pParticle->m_uchEndSize = 0.0f; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = 0.0f; matrix3x4_t matAttachment; Vector origin; // Grab the origin out of the transform for the attachment if ( FX_GetAttachmentTransform( hEntity, attachmentIndex, matAttachment ) ) { origin.x = matAttachment[0][3]; origin.y = matAttachment[1][3]; origin.z = matAttachment[2][3]; } else { //NOTENOTE: If you're here, you've specified an entity or an attachment that is invalid Assert(0); return; } if ( muzzleflash_light.GetBool() ) { C_BaseEntity *pEnt = ClientEntityList().GetBaseEntityFromHandle( hEntity ); if ( pEnt ) { dlight_t *el = effects->CL_AllocElight( LIGHT_INDEX_MUZZLEFLASH + pEnt->entindex() ); el->origin = origin; el->color.r = 64; el->color.g = 128; el->color.b = 255; el->color.exponent = 5; el->radius = random->RandomInt( 32, 128 ); el->decay = el->radius / 0.05f; el->die = gpGlobals->curtime + 0.05f; } } } //================================================== // Purpose: // Input: //================================================== void CTempEnts::MuzzleFlash_AR2_NPC( const Vector &origin, const QAngle &angles, ClientEntityHandle_t hEntity ) { //Draw the cloud of fire FX_MuzzleEffect( origin, angles, 1.0f, hEntity ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTempEnts::MuzzleFlash_SMG1_NPC( ClientEntityHandle_t hEntity, int attachmentIndex ) { //Draw the cloud of fire FX_MuzzleEffectAttached( 1.0f, hEntity, attachmentIndex, NULL, true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTempEnts::MuzzleFlash_SMG1_Player( ClientEntityHandle_t hEntity, int attachmentIndex ) { VPROF_BUDGET( "MuzzleFlash_SMG1_Player", VPROF_BUDGETGROUP_PARTICLE_RENDERING ); CSmartPtr<CLocalSpaceEmitter> pSimple = CLocalSpaceEmitter::Create( "MuzzleFlash_SMG1_Player", hEntity, attachmentIndex, FLE_VIEWMODEL ); CacheMuzzleFlashes(); SimpleParticle *pParticle; Vector forward(1,0,0), offset; //NOTENOTE: All coords are in local space float flScale = random->RandomFloat( 1.25f, 1.5f ); pSimple->SetDrawBeforeViewModel( true ); // Flash for ( int i = 1; i < 6; i++ ) { offset = (forward * (i*8.0f*flScale)); pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), m_Material_MuzzleFlash_Player[random->RandomInt(0,3)], offset ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = 0.025f; pParticle->m_vecVelocity.Init(); pParticle->m_uchColor[0] = 255; pParticle->m_uchColor[1] = 255; pParticle->m_uchColor[2] = 200+random->RandomInt(0,55); pParticle->m_uchStartAlpha = 255; pParticle->m_uchEndAlpha = 255; pParticle->m_uchStartSize = ( (random->RandomFloat( 6.0f, 8.0f ) * (8-(i))/6) * flScale ); pParticle->m_uchEndSize = pParticle->m_uchStartSize; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = 0.0f; } } //================================================== // Purpose: // Input: //================================================== void CTempEnts::MuzzleFlash_Shotgun_Player( ClientEntityHandle_t hEntity, int attachmentIndex ) { VPROF_BUDGET( "MuzzleFlash_Shotgun_Player", VPROF_BUDGETGROUP_PARTICLE_RENDERING ); CSmartPtr<CSimpleEmitter> pSimple = CSimpleEmitter::Create( "MuzzleFlash_Shotgun_Player" ); pSimple->SetDrawBeforeViewModel( true ); CacheMuzzleFlashes(); Vector origin; QAngle angles; // Get our attachment's transformation matrix FX_GetAttachmentTransform( hEntity, attachmentIndex, &origin, &angles ); pSimple->GetBinding().SetBBox( origin - Vector( 4, 4, 4 ), origin + Vector( 4, 4, 4 ) ); Vector forward; AngleVectors( angles, &forward, NULL, NULL ); SimpleParticle *pParticle; Vector offset; float flScale = random->RandomFloat( 1.25f, 1.5f ); // Flash for ( int i = 1; i < 6; i++ ) { offset = origin + (forward * (i*8.0f*flScale)); pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), m_Material_MuzzleFlash_Player[random->RandomInt(0,3)], offset ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = 0.0001f; pParticle->m_vecVelocity.Init(); pParticle->m_uchColor[0] = 255; pParticle->m_uchColor[1] = 255; pParticle->m_uchColor[2] = 200+random->RandomInt(0,55); pParticle->m_uchStartAlpha = 255; pParticle->m_uchEndAlpha = 255; pParticle->m_uchStartSize = ( (random->RandomFloat( 6.0f, 8.0f ) * (8-(i))/6) * flScale ); pParticle->m_uchEndSize = pParticle->m_uchStartSize; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = 0.0f; } } //================================================== // Purpose: // Input: //================================================== void CTempEnts::MuzzleFlash_Shotgun_NPC( ClientEntityHandle_t hEntity, int attachmentIndex ) { //Draw the cloud of fire FX_MuzzleEffectAttached( 0.75f, hEntity, attachmentIndex ); // If the material isn't available, let's not do anything else. if ( g_Mat_SMG_Muzzleflash[0] == NULL ) { return; } QAngle angles; Vector forward; int i; // Setup the origin. Vector origin; IClientRenderable *pRenderable = ClientEntityList().GetClientRenderableFromHandle( hEntity ); if ( !pRenderable ) return; pRenderable->GetAttachment( attachmentIndex, origin, angles ); AngleVectors( angles, &forward ); //Embers less often if ( random->RandomInt( 0, 2 ) == 0 ) { //Embers CSmartPtr<CEmberEffect> pEmbers = CEmberEffect::Create( "muzzle_embers" ); pEmbers->SetSortOrigin( origin ); SimpleParticle *pParticle; int numEmbers = random->RandomInt( 0, 4 ); for ( int i = 0; i < numEmbers; i++ ) { pParticle = (SimpleParticle *) pEmbers->AddParticle( sizeof( SimpleParticle ), g_Mat_SMG_Muzzleflash[0], origin ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = random->RandomFloat( 0.2f, 0.4f ); pParticle->m_vecVelocity.Random( -0.05f, 0.05f ); pParticle->m_vecVelocity += forward; VectorNormalize( pParticle->m_vecVelocity ); pParticle->m_vecVelocity *= random->RandomFloat( 64.0f, 256.0f ); pParticle->m_uchColor[0] = 255; pParticle->m_uchColor[1] = 128; pParticle->m_uchColor[2] = 64; pParticle->m_uchStartAlpha = 255; pParticle->m_uchEndAlpha = 0; pParticle->m_uchStartSize = 1; pParticle->m_uchEndSize = 0; pParticle->m_flRoll = 0; pParticle->m_flRollDelta = 0; } } // // Trails // CSmartPtr<CTrailParticles> pTrails = CTrailParticles::Create( "MuzzleFlash_Shotgun_NPC" ); pTrails->SetSortOrigin( origin ); TrailParticle *pTrailParticle; pTrails->SetFlag( bitsPARTICLE_TRAIL_FADE ); pTrails->m_ParticleCollision.SetGravity( 0.0f ); int numEmbers = random->RandomInt( 4, 8 ); for ( i = 0; i < numEmbers; i++ ) { pTrailParticle = (TrailParticle *) pTrails->AddParticle( sizeof( TrailParticle ), g_Mat_SMG_Muzzleflash[0], origin ); if ( pTrailParticle == NULL ) return; pTrailParticle->m_flLifetime = 0.0f; pTrailParticle->m_flDieTime = random->RandomFloat( 0.1f, 0.2f ); float spread = 0.05f; pTrailParticle->m_vecVelocity.Random( -spread, spread ); pTrailParticle->m_vecVelocity += forward; VectorNormalize( pTrailParticle->m_vecVelocity ); VectorNormalize( forward ); float dot = forward.Dot( pTrailParticle->m_vecVelocity ); dot = (1.0f-fabs(dot)) / spread; pTrailParticle->m_vecVelocity *= (random->RandomFloat( 256.0f, 1024.0f ) * (1.0f-dot)); Color32Init( pTrailParticle->m_color, 255, 242, 191, 255 ); pTrailParticle->m_flLength = 0.05f; pTrailParticle->m_flWidth = random->RandomFloat( 0.25f, 0.5f ); } } //================================================== // Purpose: //================================================== void CTempEnts::MuzzleFlash_357_Player( ClientEntityHandle_t hEntity, int attachmentIndex ) { VPROF_BUDGET( "MuzzleFlash_357_Player", VPROF_BUDGETGROUP_PARTICLE_RENDERING ); CSmartPtr<CSimpleEmitter> pSimple = CSimpleEmitter::Create( "MuzzleFlash_357_Player" ); pSimple->SetDrawBeforeViewModel( true ); CacheMuzzleFlashes(); Vector origin; QAngle angles; // Get our attachment's transformation matrix FX_GetAttachmentTransform( hEntity, attachmentIndex, &origin, &angles ); pSimple->GetBinding().SetBBox( origin - Vector( 4, 4, 4 ), origin + Vector( 4, 4, 4 ) ); Vector forward; AngleVectors( angles, &forward, NULL, NULL ); SimpleParticle *pParticle; Vector offset; // Smoke offset = origin + forward * 8.0f; pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), g_Mat_DustPuff[0], offset ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = random->RandomFloat( 0.5f, 1.0f ); pParticle->m_vecVelocity.Init(); pParticle->m_vecVelocity = forward * random->RandomFloat( 8.0f, 64.0f ); pParticle->m_vecVelocity[2] += random->RandomFloat( 4.0f, 16.0f ); int color = random->RandomInt( 200, 255 ); pParticle->m_uchColor[0] = color; pParticle->m_uchColor[1] = color; pParticle->m_uchColor[2] = color; pParticle->m_uchStartAlpha = random->RandomInt( 64, 128 ); pParticle->m_uchEndAlpha = 0; pParticle->m_uchStartSize = random->RandomInt( 2, 4 ); pParticle->m_uchEndSize = pParticle->m_uchStartSize * 8.0f; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = random->RandomFloat( -0.5f, 0.5f ); float flScale = random->RandomFloat( 1.25f, 1.5f ); // Flash for ( int i = 1; i < 6; i++ ) { offset = origin + (forward * (i*8.0f*flScale)); pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), m_Material_MuzzleFlash_Player[random->RandomInt(0,3)], offset ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = 0.01f; pParticle->m_vecVelocity.Init(); pParticle->m_uchColor[0] = 255; pParticle->m_uchColor[1] = 255; pParticle->m_uchColor[2] = 200+random->RandomInt(0,55); pParticle->m_uchStartAlpha = 255; pParticle->m_uchEndAlpha = 255; pParticle->m_uchStartSize = ( (random->RandomFloat( 6.0f, 8.0f ) * (8-(i))/6) * flScale ); pParticle->m_uchEndSize = pParticle->m_uchStartSize; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = 0.0f; } } //================================================== // Purpose: // Input: //================================================== void CTempEnts::MuzzleFlash_Pistol_Player( ClientEntityHandle_t hEntity, int attachmentIndex ) { VPROF_BUDGET( "MuzzleFlash_Pistol_Player", VPROF_BUDGETGROUP_PARTICLE_RENDERING ); CSmartPtr<CSimpleEmitter> pSimple = CSimpleEmitter::Create( "MuzzleFlash_Pistol_Player" ); pSimple->SetDrawBeforeViewModel( true ); CacheMuzzleFlashes(); Vector origin; QAngle angles; // Get our attachment's transformation matrix FX_GetAttachmentTransform( hEntity, attachmentIndex, &origin, &angles ); pSimple->GetBinding().SetBBox( origin - Vector( 4, 4, 4 ), origin + Vector( 4, 4, 4 ) ); Vector forward; AngleVectors( angles, &forward, NULL, NULL ); SimpleParticle *pParticle; Vector offset; // Smoke offset = origin + forward * 8.0f; if ( random->RandomInt( 0, 3 ) != 0 ) { pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), g_Mat_DustPuff[0], offset ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = random->RandomFloat( 0.25f, 0.5f ); pParticle->m_vecVelocity.Init(); pParticle->m_vecVelocity = forward * random->RandomFloat( 48.0f, 64.0f ); pParticle->m_vecVelocity[2] += random->RandomFloat( 4.0f, 16.0f ); int color = random->RandomInt( 200, 255 ); pParticle->m_uchColor[0] = color; pParticle->m_uchColor[1] = color; pParticle->m_uchColor[2] = color; pParticle->m_uchStartAlpha = random->RandomInt( 64, 128 ); pParticle->m_uchEndAlpha = 0; pParticle->m_uchStartSize = random->RandomInt( 2, 4 ); pParticle->m_uchEndSize = pParticle->m_uchStartSize * 4.0f; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = random->RandomFloat( -0.1f, 0.1f ); } float flScale = random->RandomFloat( 1.0f, 1.25f ); // Flash for ( int i = 1; i < 6; i++ ) { offset = origin + (forward * (i*4.0f*flScale)); pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), m_Material_MuzzleFlash_Player[random->RandomInt(0,3)], offset ); if ( pParticle == NULL ) return; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = 0.01f; pParticle->m_vecVelocity.Init(); pParticle->m_uchColor[0] = 255; pParticle->m_uchColor[1] = 255; pParticle->m_uchColor[2] = 200+random->RandomInt(0,55); pParticle->m_uchStartAlpha = 255; pParticle->m_uchEndAlpha = 255; pParticle->m_uchStartSize = ( (random->RandomFloat( 6.0f, 8.0f ) * (8-(i))/6) * flScale ); pParticle->m_uchEndSize = pParticle->m_uchStartSize; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = 0.0f; } } //================================================== // Purpose: // Input: //================================================== void CTempEnts::MuzzleFlash_Pistol_NPC( ClientEntityHandle_t hEntity, int attachmentIndex ) { FX_MuzzleEffectAttached( 0.5f, hEntity, attachmentIndex, NULL, true ); } //================================================== // Purpose: // Input: //================================================== void CTempEnts::MuzzleFlash_RPG_NPC( ClientEntityHandle_t hEntity, int attachmentIndex ) { //Draw the cloud of fire FX_MuzzleEffectAttached( 1.5f, hEntity, attachmentIndex ); } void CTempEnts::RocketFlare( const Vector& pos ) { C_LocalTempEntity *pTemp; const model_t *model; int nframeCount; model = (model_t *)engine->LoadModel( "sprites/animglow01.vmt" ); if ( !model ) { return; } nframeCount = modelinfo->GetModelFrameCount( model ); pTemp = TempEntAlloc( pos, model ); if ( !pTemp ) return; pTemp->m_flFrameMax = nframeCount - 1; pTemp->SetRenderMode( kRenderGlow ); pTemp->m_nRenderFX = kRenderFxNoDissipation; pTemp->tempent_renderamt = 255; pTemp->m_flFrameRate = 1.0; pTemp->m_flFrame = random->RandomInt( 0, nframeCount - 1); pTemp->m_flSpriteScale = 1.0; pTemp->SetAbsOrigin( pos ); pTemp->die = gpGlobals->curtime + 0.01; } void CTempEnts::HL1EjectBrass( const Vector &vecPosition, const QAngle &angAngles, const Vector &vecVelocity, int nType ) { const model_t *pModel = NULL; #if defined( HL1_CLIENT_DLL ) switch ( nType ) { case 0: default: pModel = m_pHL1Shell; break; case 1: pModel = m_pHL1ShotgunShell; break; } #endif if ( pModel == NULL ) return; C_LocalTempEntity *pTemp = TempEntAlloc( vecPosition, pModel ); if ( pTemp == NULL ) return; switch ( nType ) { case 0: default: pTemp->hitSound = BOUNCE_SHELL; break; case 1: pTemp->hitSound = BOUNCE_SHOTSHELL; break; } pTemp->m_nBody = 0; pTemp->flags |= ( FTENT_COLLIDEWORLD | FTENT_FADEOUT | FTENT_GRAVITY | FTENT_ROTATE ); pTemp->m_vecTempEntAngVelocity[0] = random->RandomFloat( -512,511 ); pTemp->m_vecTempEntAngVelocity[1] = random->RandomFloat( -256,255 ); pTemp->m_vecTempEntAngVelocity[2] = random->RandomFloat( -256,255 ); //Face forward pTemp->SetAbsAngles( angAngles ); pTemp->SetRenderMode( kRenderNormal ); pTemp->tempent_renderamt = 255; // Set this for fadeout pTemp->SetVelocity( vecVelocity ); pTemp->die = gpGlobals->curtime + 2.5; } #define SHELLTYPE_PISTOL 0 #define SHELLTYPE_RIFLE 1 #define SHELLTYPE_SHOTGUN 2 void CTempEnts::CSEjectBrass( const Vector &vecPosition, const QAngle &angVelocity, int nVelocity, int shellType, CBasePlayer *pShooter ) { const model_t *pModel = NULL; int hitsound = TE_BOUNCE_SHELL; #if defined ( CSTRIKE_DLL ) || defined ( SDK_DLL ) switch( shellType ) { default: case CS_SHELL_9MM: hitsound = TE_PISTOL_SHELL; pModel = m_pCS_9MMShell; break; case CS_SHELL_57: hitsound = TE_PISTOL_SHELL; pModel = m_pCS_57Shell; break; case CS_SHELL_12GAUGE: hitsound = TE_SHOTGUN_SHELL; pModel = m_pCS_12GaugeShell; break; case CS_SHELL_556: hitsound = TE_RIFLE_SHELL; pModel = m_pCS_556Shell; break; case CS_SHELL_762NATO: hitsound = TE_RIFLE_SHELL; pModel = m_pCS_762NATOShell; break; case CS_SHELL_338MAG: hitsound = TE_RIFLE_SHELL; pModel = m_pCS_338MAGShell; break; } #endif if ( pModel == NULL ) return; Vector forward, right, up; Vector velocity; Vector origin; QAngle angle; // Add some randomness to the velocity AngleVectors( angVelocity, &forward, &right, &up ); velocity = forward * nVelocity * random->RandomFloat( 1.2, 2.8 ) + up * random->RandomFloat( -10, 10 ) + right * random->RandomFloat( -20, 20 ); if( pShooter ) velocity += pShooter->GetAbsVelocity(); C_LocalTempEntity *pTemp = TempEntAlloc( vecPosition, pModel ); if ( !pTemp ) return; if( pShooter ) pTemp->SetAbsAngles( pShooter->EyeAngles() ); else pTemp->SetAbsAngles( vec3_angle ); pTemp->SetVelocity( velocity ); pTemp->hitSound = hitsound; pTemp->SetGravity( 0.4 ); pTemp->m_nBody = 0; pTemp->flags = FTENT_FADEOUT | FTENT_GRAVITY | FTENT_COLLIDEALL | FTENT_HITSOUND | FTENT_ROTATE | FTENT_CHANGERENDERONCOLLIDE; pTemp->m_vecTempEntAngVelocity[0] = random->RandomFloat(-256,256); pTemp->m_vecTempEntAngVelocity[1] = random->RandomFloat(-256,256); pTemp->m_vecTempEntAngVelocity[2] = 0; pTemp->SetRenderMode( kRenderNormal ); pTemp->tempent_renderamt = 255; pTemp->die = gpGlobals->curtime + 10; bool bViewModelBrass = false; if ( pShooter && pShooter->GetObserverMode() == OBS_MODE_IN_EYE ) { // we are spectating the shooter in first person view pShooter = ToBasePlayer( pShooter->GetObserverTarget() ); bViewModelBrass = true; } if ( pShooter ) { pTemp->clientIndex = pShooter->entindex(); bViewModelBrass |= pShooter->IsLocalPlayer(); } else { pTemp->clientIndex = 0; } if ( bViewModelBrass ) { // for viewmodel brass put it in the viewmodel renderer group pTemp->m_RenderGroup = RENDER_GROUP_VIEW_MODEL_OPAQUE; } }
412
0.933142
1
0.933142
game-dev
MEDIA
0.865428
game-dev
0.950922
1
0.950922
the-synister/the-source
2,325
juce/modules/juce_box2d/box2d/Collision/Shapes/b2EdgeShape.h
/* * Copyright (c) 2006-2010 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_EDGE_SHAPE_H #define B2_EDGE_SHAPE_H #include "b2Shape.h" /// A line segment (edge) shape. These can be connected in chains or loops /// to other edge shapes. The connectivity information is used to ensure /// correct contact normals. class b2EdgeShape : public b2Shape { public: b2EdgeShape(); /// Set this as an isolated edge. void Set(const b2Vec2& v1, const b2Vec2& v2); /// Implement b2Shape. b2Shape* Clone(b2BlockAllocator* allocator) const; /// @see b2Shape::GetChildCount int32 GetChildCount() const; /// @see b2Shape::TestPoint bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; /// Implement b2Shape. bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform, int32 childIndex) const; /// @see b2Shape::ComputeAABB void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; /// @see b2Shape::ComputeMass void ComputeMass(b2MassData* massData, float32 density) const; /// These are the edge vertices b2Vec2 m_vertex1, m_vertex2; /// Optional adjacent vertices. These are used for smooth collision. b2Vec2 m_vertex0, m_vertex3; bool m_hasVertex0, m_hasVertex3; }; inline b2EdgeShape::b2EdgeShape() { m_type = e_edge; m_radius = b2_polygonRadius; m_vertex0.x = 0.0f; m_vertex0.y = 0.0f; m_vertex3.x = 0.0f; m_vertex3.y = 0.0f; m_hasVertex0 = false; m_hasVertex3 = false; } #endif
412
0.97775
1
0.97775
game-dev
MEDIA
0.899149
game-dev
0.897788
1
0.897788
Farama-Foundation/MicroRTS
1,290
src/ai/synthesis/dslForScriptGenerator/DSLParametersConcrete/RandomEnemy.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ai.synthesis.dslForScriptGenerator.DSLParametersConcrete; import java.util.Random; import rts.GameState; import rts.PhysicalGameState; import rts.units.Unit; /** * * @author rubens Julian */ public class RandomEnemy extends BehaviorAbstract{ @Override public Unit getEnemytByBehavior(GameState game, int player, Unit unitAlly) { PhysicalGameState pgs = game.getPhysicalGameState(); Unit randomEnemy = null; Random r=new Random(); int quantityUnits=0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() == player) { quantityUnits++; } } int idUnit=r.nextInt(quantityUnits); int counterUnits=0; for (Unit u2 : pgs.getUnits()) { if (u2.getPlayer() >= 0 && u2.getPlayer() == player && counterUnits==idUnit) { counterUnits++; randomEnemy=u2; } } return randomEnemy; } @Override public String toString() { return "RandomEnemy:{-}"; } }
412
0.811827
1
0.811827
game-dev
MEDIA
0.600922
game-dev
0.811021
1
0.811021
FrankvdStam/SoulSplitter
2,901
src/SoulSplitter/Splits/DarkSouls1/Split.cs
// This file is part of the SoulSplitter distribution (https://github.com/FrankvdStam/SoulSplitter). // Copyright (c) 2022 Frank van der Stam. // https://github.com/FrankvdStam/SoulSplitter/blob/main/LICENSE // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3. // // 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/>. using System; using SoulMemory.DarkSouls1; using SoulSplitter.UI.Generic; namespace SoulSplitter.Splits.DarkSouls1; internal class Split { public Split(TimingType timingType, SplitType splitType, object split) { TimingType = timingType; SplitType = splitType; switch (SplitType) { default: throw new ArgumentException($"unsupported split type {SplitType}"); case SplitType.Boss: Boss = (Boss)split; Flag = (uint)Boss; break; case SplitType.Attribute: Attribute = (Attribute)split; break; case SplitType.Position: Position = (VectorSize)split; break; case SplitType.KnownFlag: KnownFlag = (KnownFlag)split; Flag = (uint)KnownFlag; break; case SplitType.Flag: Flag = ((FlagDescription)split).Flag; break; case SplitType.Item: ItemState = (ItemState)split; break; case SplitType.Bonfire: BonfireState = (BonfireState)split; break; case SplitType.Credits: break; } } public readonly TimingType TimingType; public readonly SplitType SplitType; public readonly Boss Boss; public readonly Attribute Attribute = null!; public readonly ItemState ItemState = null!; public readonly BonfireState BonfireState = null!; public readonly VectorSize Position = null!; public readonly uint Flag; public readonly KnownFlag KnownFlag; /// <summary> /// Set to true when split conditions are met. Does not trigger a split until timing conditions are met /// </summary> public bool SplitConditionMet = false; /// <summary> /// True after this split object cause a split. No longer need to check split conditions /// </summary> public bool SplitTriggered = false; public bool Quitout = false; }
412
0.749476
1
0.749476
game-dev
MEDIA
0.178961
game-dev
0.868757
1
0.868757
pontos2024/PCSX2_ARM64
2,008
app/src/main/cpp/pcsx2/DebugTools/MipsAssembler.h
// SPDX-FileCopyrightText: 2002-2025 PCSX2 Dev Team // SPDX-License-Identifier: GPL-3.0+ #pragma once #include "MipsAssemblerTables.h" #include "DebugInterface.h" enum MipsImmediateType { MIPS_NOIMMEDIATE, MIPS_IMMEDIATE5, MIPS_IMMEDIATE16, MIPS_IMMEDIATE20, MIPS_IMMEDIATE26 }; enum MipsArchType { MARCH_PSX = 0, MARCH_N64, MARCH_PS2, MARCH_PSP, MARCH_INVALID }; typedef struct { const char* name; short num; } tMipsRegister; typedef struct { char name[5]; short num; } MipsRegisterInfo; struct MipsImmediate { int value; int originalValue; }; struct MipsOpcodeRegisters { MipsRegisterInfo grs; // general source reg MipsRegisterInfo grt; // general target reg MipsRegisterInfo grd; // general dest reg MipsRegisterInfo frs; // float source reg MipsRegisterInfo frt; // float target reg MipsRegisterInfo frd; // float dest reg MipsRegisterInfo ps2vrs; // ps2 vector source reg MipsRegisterInfo ps2vrt; // ps2 vector target reg MipsRegisterInfo ps2vrd; // ps2 vector dest reg void reset() { grs.num = grt.num = grd.num = -1; frs.num = frt.num = frd.num = -1; ps2vrs.num = ps2vrt.num = ps2vrd.num = -1; } }; class CMipsInstruction { public: CMipsInstruction(DebugInterface* cpu); bool Load(const char* Name, const char* Params, int RamPos); virtual bool Validate(); virtual void Encode(); u32 getEncoding() { return encoding; }; std::string getErrorMessage() { return error; }; private: void encodeNormal(); bool parseOpcode(const tMipsOpcode& SourceOpcode, const char* Line); bool LoadEncoding(const tMipsOpcode& SourceOpcode, const char* Line); void setOmittedRegisters(); tMipsOpcode Opcode; bool NoCheckError; bool Loaded; int RamPos; // opcode variables MipsOpcodeRegisters registers; MipsImmediateType immediateType; MipsImmediate immediate; int vfpuSize; DebugInterface* cpu; u32 encoding; std::string error; }; bool MipsAssembleOpcode(const char* line, DebugInterface* cpu, u32 address, u32& dest, std::string& errorText);
412
0.726281
1
0.726281
game-dev
MEDIA
0.27313
game-dev
0.726188
1
0.726188
amethyst/evoli
5,066
src/systems/main_game_ui.rs
use amethyst::{ ecs::*, input::{InputEvent, StringBindings}, shrev::{EventChannel, ReaderId}, ui::*, }; pub struct ButtonInfo { pub name: &'static str, pub text: &'static str, pub action: &'static str, } const DEFAULT_BUTTON: ButtonInfo = ButtonInfo { name: "", text: "", action: "", }; impl Default for &ButtonInfo { fn default() -> Self { &DEFAULT_BUTTON } } // centralize the button strings here (used in both button creation and response logic) // NOTE name and text will need to be kept in alignment with main_game.ron; action will need to be kept in alignment with input.ron pub const MENU_BUTTON: ButtonInfo = ButtonInfo { name: "menu button", text: "Menu", action: "Menu", }; pub const PAUSE_BUTTON: ButtonInfo = ButtonInfo { name: "pause button", text: "Pause", action: "TogglePause", }; pub const SLOW_DOWN_BUTTON: ButtonInfo = ButtonInfo { name: "slow down button", text: "Slow Down", action: "SlowDown", }; pub const SPEED_UP_BUTTON: ButtonInfo = ButtonInfo { name: "speed up button", text: "Speed Up", action: "SpeedUp", }; pub const BUTTON_INFOS: [&ButtonInfo; 4] = [ &MENU_BUTTON, &PAUSE_BUTTON, &SLOW_DOWN_BUTTON, &SPEED_UP_BUTTON, ]; #[derive(Default)] struct Button { info: &'static ButtonInfo, entity: Option<Entity>, } #[derive(Default)] pub struct MainGameUiSystem { ui_reader_id: Option<ReaderId<UiEvent>>, input_reader_id: Option<ReaderId<InputEvent<StringBindings>>>, buttons: Vec<Button>, pause_button_text: Option<Entity>, } // implementation-specific, hidden way of producing the name of a button's child text widget, given the button name fn make_ui_text_name(button_name: &str) -> String { format!("{}_btn_txt", button_name) } impl<'s> MainGameUiSystem { fn find_ui_elements(&mut self, finder: &UiFinder) { if self.buttons.is_empty() { self.buttons = BUTTON_INFOS .iter() .map(|info| Button { info, entity: finder.find(info.name), }) .collect::<Vec<Button>>(); self.pause_button_text = finder.find(&make_ui_text_name(PAUSE_BUTTON.name)); } } // translate ui button clicks into input actions for registered buttons fn translate_click( &self, clicked: Entity, input_events: &mut Write<'s, EventChannel<InputEvent<StringBindings>>>, ) { if let Some(button) = self .buttons .iter() .find(|button| button.entity == Some(clicked)) { input_events.single_write(InputEvent::ActionPressed(button.info.action.to_string())); } } fn handle_action(&self, action: &str, ui_texts: &mut WriteStorage<'s, UiText>) { // only one action handled right now; change to 'match' when we handle more if action != PAUSE_BUTTON.action { return; } // toggle text between 'Play' and 'Pause' depending on what the next click will do const PAUSE_TEXT: &str = PAUSE_BUTTON.text; const PLAY_TEXT: &str = "Play"; if let Some(text_entity) = self.pause_button_text { if let Some(ui_text) = ui_texts.get_mut(text_entity) { if ui_text.text == PAUSE_TEXT { ui_text.text = PLAY_TEXT.to_string(); } else if ui_text.text == PLAY_TEXT { ui_text.text = PAUSE_TEXT.to_string(); } } } } } impl<'s> System<'s> for MainGameUiSystem { type SystemData = ( UiFinder<'s>, Read<'s, EventChannel<UiEvent>>, WriteStorage<'s, UiText>, Write<'s, EventChannel<InputEvent<StringBindings>>>, ); fn setup(&mut self, world: &mut World) { <Self as System<'_>>::SystemData::setup(world); self.ui_reader_id = Some(world.fetch_mut::<EventChannel<UiEvent>>().register_reader()); self.input_reader_id = Some( world .fetch_mut::<EventChannel<InputEvent<StringBindings>>>() .register_reader(), ); } fn run(&mut self, (ui_finder, ui_events, mut ui_texts, mut input_events): Self::SystemData) { self.find_ui_elements(&ui_finder); ui_events .read(self.ui_reader_id.as_mut().unwrap()) // filter for Clicks; change to 'match' when other UiEventType variants need to be handled .filter(|event| event.event_type == UiEventType::Click) .for_each(|event| self.translate_click(event.target, &mut input_events)); input_events .read(self.input_reader_id.as_mut().unwrap()) .for_each(|event| { // change from if-let to match when more InputEvent variants need to be handled if let InputEvent::ActionPressed(action_name) = event { self.handle_action(action_name, &mut ui_texts); } }); } }
412
0.92931
1
0.92931
game-dev
MEDIA
0.463131
game-dev
0.924913
1
0.924913
HaHaWTH/HybridFix
1,827
src/main/java/io/wdsj/hybridfix/api/bukkit/event/entity/EntityAttackEvent.java
package io.wdsj.hybridfix.api.bukkit.event.entity; import org.bukkit.entity.Entity; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.entity.EntityEvent; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; /** * Called when an entity is attacked, even the entity damaged is in invulnerable time. * This event is a bukkit-side equivalent of Forge's {@link net.minecraftforge.event.entity.living.LivingAttackEvent}. * Fired earlier than the {@link org.bukkit.event.entity.EntityDamageEvent}, thus at this point the damage modifiers have not been applied yet. */ @SuppressWarnings("unused") public class EntityAttackEvent extends EntityEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancel = false; private final double damage; private final String damageType; @ApiStatus.Internal public EntityAttackEvent(Entity victim, double damage, String damageType) { super(victim); this.damage = damage; this.damageType = damageType; } /** * Get the <b>base</b> damage in the attack. * * @return the damage */ public double getDamage() { return damage; } /** * Get the damage type of the attack. * @see net.minecraft.util.DamageSource * * @return the damage type */ @NotNull public String getDamageType() { return damageType; } public boolean isCancelled() { return cancel; } public void setCancelled(boolean cancel) { this.cancel = cancel; } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } }
412
0.740761
1
0.740761
game-dev
MEDIA
0.922594
game-dev
0.625901
1
0.625901
MehVahdJukaar/Supplementaries
1,278
common/src/main/java/net/mehvahdjukaar/supplementaries/common/misc/map_markers/markers/WaystoneMarker.java
package net.mehvahdjukaar.supplementaries.common.misc.map_markers.markers; import net.mehvahdjukaar.moonlight.api.map.markers.SimpleMapBlockMarker; import net.mehvahdjukaar.supplementaries.common.misc.map_markers.ModMapMarkers; import net.mehvahdjukaar.supplementaries.integration.CompatHandler; import net.mehvahdjukaar.supplementaries.integration.WaystonesCompat; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.world.level.BlockGetter; import org.jetbrains.annotations.Nullable; public class WaystoneMarker extends SimpleMapBlockMarker { public WaystoneMarker() { super(ModMapMarkers.WAYSTONE_DECORATION_TYPE); } public WaystoneMarker(BlockPos pos, @Nullable Component name) { super(ModMapMarkers.WAYSTONE_DECORATION_TYPE); this.setName(name); this.setPos(pos); } @Nullable public static WaystoneMarker getFromWorld(BlockGetter world, BlockPos pos) { if (CompatHandler.WAYSTONES) { var te = world.getBlockEntity(pos); if (WaystonesCompat.isWaystone(te)) { Component name = WaystonesCompat.getName(te); return new WaystoneMarker(pos, name); } } return null; } }
412
0.772044
1
0.772044
game-dev
MEDIA
0.947564
game-dev
0.509352
1
0.509352
Fluorohydride/ygopro-scripts
4,016
c68468459.lua
--アルバスの落胤 function c68468459.initial_effect(c) --fusion summon local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_FUSION_SUMMON) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetCountLimit(1,68468459) e1:SetCondition(c68468459.condition) e1:SetCost(c68468459.cost) e1:SetTarget(c68468459.target) e1:SetOperation(c68468459.activate) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2) end function c68468459.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetCurrentPhase()&(PHASE_DAMAGE+PHASE_DAMAGE_CAL)==0 end function c68468459.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,e:GetHandler()) end Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD) end function c68468459.filter0(c) return c:IsFaceup() and c:IsCanBeFusionMaterial() end function c68468459.filter1(c,e) return not c:IsImmuneToEffect(e) end function c68468459.filter2(c,e,tp,m,f,gc,chkf) return c:IsType(TYPE_FUSION) and (not f or f(c)) and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_FUSION,tp,false,false) and c:CheckFusionMaterial(m,gc,chkf) end function c68468459.chkfilter(c,tp) return c:IsOnField() and c:IsControler(tp) end function c68468459.fcheck(c) return function(tp,sg,fc) return not sg:IsExists(c68468459.chkfilter,1,c,tp) end end function c68468459.target(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then local chkf=tp local mg1=Duel.GetFusionMaterial(tp):Filter(Card.IsOnField,nil) local mg2=Duel.GetMatchingGroup(c68468459.filter0,tp,0,LOCATION_MZONE,nil) if mg2:GetCount()>0 then mg1:Merge(mg2) end aux.FCheckAdditional=c68468459.fcheck(c) local res=Duel.IsExistingMatchingCard(c68468459.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg1,nil,c,chkf) if not res then local ce=Duel.GetChainMaterial(tp) if ce~=nil then local fgroup=ce:GetTarget() local mg3=fgroup(ce,e,tp) local mf=ce:GetValue() res=Duel.IsExistingMatchingCard(c68468459.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg3,mf,c,chkf) end end aux.FCheckAdditional=nil return res and c:IsRelateToEffect(e) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) end function c68468459.activate(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local chkf=tp if Duel.GetCurrentPhase()&(PHASE_DAMAGE+PHASE_DAMAGE_CAL)~=0 then return end if not c:IsRelateToEffect(e) or c:IsImmuneToEffect(e) then return end local mg1=Duel.GetFusionMaterial(tp):Filter(Card.IsOnField,nil):Filter(c68468459.filter1,nil,e) local mg2=Duel.GetMatchingGroup(c68468459.filter0,tp,0,LOCATION_MZONE,nil):Filter(c68468459.filter1,nil,e) if mg2:GetCount()>0 then mg1:Merge(mg2) end aux.FCheckAdditional=c68468459.fcheck(c) local sg1=Duel.GetMatchingGroup(c68468459.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg1,nil,c,chkf) local mg3=nil local sg2=nil local ce=Duel.GetChainMaterial(tp) if ce~=nil then local fgroup=ce:GetTarget() mg3=fgroup(ce,e,tp) local mf=ce:GetValue() sg2=Duel.GetMatchingGroup(c68468459.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg3,mf,c,chkf) end if sg1:GetCount()>0 or (sg2~=nil and sg2:GetCount()>0) then local sg=sg1:Clone() if sg2 then sg:Merge(sg2) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local tg=sg:Select(tp,1,1,nil) local tc=tg:GetFirst() if sg1:IsContains(tc) and (sg2==nil or not sg2:IsContains(tc) or not Duel.SelectYesNo(tp,ce:GetDescription())) then local mat1=Duel.SelectFusionMaterial(tp,tc,mg1,c,chkf) tc:SetMaterial(mat1) Duel.SendtoGrave(mat1,REASON_EFFECT+REASON_MATERIAL+REASON_FUSION) Duel.BreakEffect() Duel.SpecialSummon(tc,SUMMON_TYPE_FUSION,tp,tp,false,false,POS_FACEUP) else local mat2=Duel.SelectFusionMaterial(tp,tc,mg3,c,chkf) local fop=ce:GetOperation() fop(ce,e,tp,tc,mat2) end tc:CompleteProcedure() end aux.FCheckAdditional=nil end
412
0.949559
1
0.949559
game-dev
MEDIA
0.925813
game-dev
0.97146
1
0.97146
Draakoor/h2m-gscscripts
2,114
user_scripts/mp/OneInTheChamber.gsc
#include common_scripts\utility; #include maps\mp\_utility; #include maps\mp\gametypes\_hud_util; #include maps\mp\gametypes\_gamelogic; init() { setDvar("oneInTheChamber", "0"); setDvar("sv_gametype", "dm"); if (getDvarInt("oneInTheChamber") == 1) { level thread onPlayerConnect(); } } onPlayerConnect() { for(;;) { level waittill("connected", player); player thread onPlayerSpawned(); } } onPlayerSpawned() { self endon("disconnect"); for(;;) { self waittill("spawned_player"); if(getDvarInt("oneInTheChamber") == 1) { self thread applyGameMode(); } } } applyGameMode() { self.maxhealth = 50; self.health = 50; self takeAllWeapons(); self giveWeapon("h2_deserteagle_mp"); self setWeaponAmmoClip("h2_deserteagle_mp", 1); self setWeaponAmmoStock("h2_deserteagle_mp", 0); wait 0.1; self switchToWeapon("h2_deserteagle_mp"); self clearPerks(); self takeWeapon("frag_grenade_mp"); self takeWeapon("flash_grenade_mp"); self iPrintLnBold("^3One in the Chamber (FFA): 1 bullet, 50 HP!"); self thread monitorKills(); self thread restrictWeapons(); } monitorKills() { self endon("death"); self endon("disconnect"); for(;;) { self waittill("killed_enemy"); self setWeaponAmmoClip("h2_deserteagle_mp", self getWeaponAmmoClip("h2_deserteagle_mp") + 1); self iPrintLnBold("^2+1 bullet for your kill!"); } } restrictWeapons() { self endon("death"); self endon("disconnect"); for(;;) { weapon = self getCurrentWeapon(); if(isDefined(weapon) && weapon != "none" && weapon != "h2_deserteagle_mp") { self takeWeapon(weapon); self giveWeapon("h2_deserteagle_mp"); self setWeaponAmmoClip("h2_deserteagle_mp", 1); wait 0.1; self switchToWeapon("h2_deserteagle_mp"); self iPrintLnBold("^1Only h2_deserteagle_mp is allowed!"); } wait 0.05; } }
412
0.909799
1
0.909799
game-dev
MEDIA
0.987423
game-dev
0.684098
1
0.684098
oot-pc-port/oot-pc-port
3,196
asm/non_matchings/overlays/actors/ovl_Boss_Sst/func_80930474.s
glabel func_80930474 /* 03EA4 80930474 27BDFFE8 */ addiu $sp, $sp, 0xFFE8 ## $sp = FFFFFFE8 /* 03EA8 80930478 AFBF0014 */ sw $ra, 0x0014($sp) /* 03EAC 8093047C 848F001C */ lh $t7, 0x001C($a0) ## 0000001C /* 03EB0 80930480 3C018093 */ lui $at, %hi(D_8093746C) ## $at = 80930000 /* 03EB4 80930484 240E0002 */ addiu $t6, $zero, 0x0002 ## $t6 = 00000002 /* 03EB8 80930488 000FC080 */ sll $t8, $t7, 2 /* 03EBC 8093048C 00380821 */ addu $at, $at, $t8 /* 03EC0 80930490 00803825 */ or $a3, $a0, $zero ## $a3 = 00000000 /* 03EC4 80930494 AC2E746C */ sw $t6, %lo(D_8093746C)($at) /* 03EC8 80930498 84F9001C */ lh $t9, 0x001C($a3) ## 0000001C /* 03ECC 8093049C 3C058093 */ lui $a1, %hi(D_80937884) ## $a1 = 80930000 /* 03ED0 809304A0 AFA70018 */ sw $a3, 0x0018($sp) /* 03ED4 809304A4 00194080 */ sll $t0, $t9, 2 /* 03ED8 809304A8 00A82821 */ addu $a1, $a1, $t0 /* 03EDC 809304AC 8CA57884 */ lw $a1, %lo(D_80937884)($a1) /* 03EE0 809304B0 2484014C */ addiu $a0, $a0, 0x014C ## $a0 = 0000014C /* 03EE4 809304B4 0C029490 */ jal func_800A5240 /* 03EE8 809304B8 3C064120 */ lui $a2, 0x4120 ## $a2 = 41200000 /* 03EEC 809304BC 8FA40018 */ lw $a0, 0x0018($sp) /* 03EF0 809304C0 00002825 */ or $a1, $zero, $zero ## $a1 = 00000000 /* 03EF4 809304C4 908903E4 */ lbu $t1, 0x03E4($a0) ## 000003E4 /* 03EF8 809304C8 908B03E5 */ lbu $t3, 0x03E5($a0) ## 000003E5 /* 03EFC 809304CC 8C8D0004 */ lw $t5, 0x0004($a0) ## 00000004 /* 03F00 809304D0 312AFFFC */ andi $t2, $t1, 0xFFFC ## $t2 = 00000000 /* 03F04 809304D4 356C0001 */ ori $t4, $t3, 0x0001 ## $t4 = 00000001 /* 03F08 809304D8 35AF0001 */ ori $t7, $t5, 0x0001 ## $t7 = 00000001 /* 03F0C 809304DC A08A03E4 */ sb $t2, 0x03E4($a0) ## 000003E4 /* 03F10 809304E0 A08C03E5 */ sb $t4, 0x03E5($a0) ## 000003E5 /* 03F14 809304E4 0C24CF3B */ jal func_80933CEC /* 03F18 809304E8 AC8F0004 */ sw $t7, 0x0004($a0) ## 00000004 /* 03F1C 809304EC 8FA70018 */ lw $a3, 0x0018($sp) /* 03F20 809304F0 3C014040 */ lui $at, 0x4040 ## $at = 40400000 /* 03F24 809304F4 44812000 */ mtc1 $at, $f4 ## $f4 = 3.00 /* 03F28 809304F8 3C0E8093 */ lui $t6, %hi(func_8093051C) ## $t6 = 80930000 /* 03F2C 809304FC 25CE051C */ addiu $t6, $t6, %lo(func_8093051C) ## $t6 = 8093051C /* 03F30 80930500 A4E00198 */ sh $zero, 0x0198($a3) ## 00000198 /* 03F34 80930504 ACEE0190 */ sw $t6, 0x0190($a3) ## 00000190 /* 03F38 80930508 E4E40068 */ swc1 $f4, 0x0068($a3) ## 00000068 /* 03F3C 8093050C 8FBF0014 */ lw $ra, 0x0014($sp) /* 03F40 80930510 27BD0018 */ addiu $sp, $sp, 0x0018 ## $sp = 00000000 /* 03F44 80930514 03E00008 */ jr $ra /* 03F48 80930518 00000000 */ nop
412
0.635427
1
0.635427
game-dev
MEDIA
0.952302
game-dev
0.613529
1
0.613529
lua9520/source-engine-2018-cstrike15_src
9,599
game/client/gameui/nuggets/ui_nugget.h
//=========== (C) Copyright Valve, L.L.C. All rights reserved. =========== #ifndef UI_NUGGET_H #define UI_NUGGET_H #include "game_controls/igameuisystemmgr.h" #include "matchmaking/imatchframework.h" #include "fmtstr.h" #include "utlstringmap.h" class CUiNuggetBase; class CUiNuggetReference; class CUiNuggetFactoryRegistrarBase; class CUiNuggetFactoryRegistrarBaseInstances; class CUiNuggetFactoryRegistrarBaseSingleton; ////////////////////////////////////////////////////////////////////////// // // Base class for implementing UI nuggets // class CUiNuggetBase : public IGameUIScreenController { public: CUiNuggetBase(); virtual ~CUiNuggetBase(); // IGameUIScreenController public: // Connects a screen to the controller, returns number of // remaining connected screens (or 1 for the first connection) virtual int OnScreenConnected( IGameUISystem *pScreenView ); // Releases the screen from controller, returns number of // remaining connected screens (returns 0 if no screens are // connected - new object must be reacquired from factory // in this case) virtual int OnScreenDisconnected( IGameUISystem *pScreenView ); // Callback for screen events handling virtual KeyValues * OnScreenEvent( IGameUISystem *pScreenView, KeyValues *kvEvent ); // Broadcast an event to all connected screens (caller retains ownership of keyvalues) virtual void BroadcastEventToScreens( KeyValues *kvEvent ); public: // Add a reference to the nugget to be notified upon release virtual void AddReferenceSink( CUiNuggetReference *pSink ) { m_arrReferences.AddToTail( pSink ); } protected: // Policy for whether the object should be deleted when no screen references remain virtual bool ShouldDeleteOnLastScreenDisconnect() { return true; } protected: struct ConnectionInfo_t { IGameUISystem *m_pScreen; int m_nRefCount; explicit ConnectionInfo_t( IGameUISystem *pScreen = NULL ) : m_pScreen( pScreen ), m_nRefCount( 0 ) {} bool operator == ( ConnectionInfo_t const &other ) const { return m_pScreen == other.m_pScreen; } }; typedef CUtlVector< ConnectionInfo_t > ConnectedScreens; ConnectedScreens m_arrConnectedScreens; CUtlVector< int > m_arrEventsDisabledScreenHandles; KeyValues *m_pUiNuggetData; KeyValues::AutoDelete m_autodelete_m_pUiNuggetData; private: CUtlVector< int * > m_arrBroadcastEventIdxArray; CUtlVector< CUiNuggetReference * > m_arrReferences; }; ////////////////////////////////////////////////////////////////////////// // // Declaration of UI nuggets factories // class CUiNuggetFactoryRegistrarBase : public IGameUIScreenControllerFactory { public: CUiNuggetFactoryRegistrarBase(); ~CUiNuggetFactoryRegistrarBase(); virtual void Register(); virtual char const *GetName() = 0; public: static void RegisterAll(); private: CUiNuggetFactoryRegistrarBase *m_pPrev, *m_pNext; }; class CUiNuggetFactoryRegistrarBaseGlobalInstance : public CUiNuggetFactoryRegistrarBase { public: // Returns an instance of a controller interface virtual IGameUIScreenController * GetController( KeyValues *kvRequest ) = 0; // Access controller instances virtual int GetControllerInstancesCount() { return 1; } virtual IGameUIScreenController * GetControllerInstance( int iIndex ) = 0; }; class CUiNuggetFactoryRegistrarBaseSingleton : public CUiNuggetFactoryRegistrarBase { friend class CUiNuggetFactoryRegistrarBaseSingletonReferenceTracker; public: CUiNuggetFactoryRegistrarBaseSingleton(); public: // Returns an instance of a controller interface virtual IGameUIScreenController * GetController( KeyValues *kvRequest ); // Access controller instances virtual int GetControllerInstancesCount() { return !!m_pSingleton; } virtual IGameUIScreenController * GetControllerInstance( int iIndex ) { return m_pSingleton; } public: // Creates an instance of a controller interface virtual CUiNuggetBase * CreateNewController() = 0; protected: CUiNuggetBase *m_pSingleton; }; class CUiNuggetFactoryRegistrarBaseInstances : public CUiNuggetFactoryRegistrarBase { friend class CUiNuggetFactoryRegistrarBaseInstancesReferenceTracker; public: // Returns an instance of a controller interface virtual IGameUIScreenController * GetController( KeyValues *kvRequest ); // Access controller instances virtual int GetControllerInstancesCount() { return m_arrInstances.Count(); } virtual IGameUIScreenController * GetControllerInstance( int iIndex ) { return m_arrInstances.IsValidIndex( iIndex ) ? m_arrInstances[iIndex] : NULL; } public: // Creates an instance of a controller interface virtual CUiNuggetBase * CreateNewController() = 0; protected: // Nugget instances CUtlVector< CUiNuggetBase * > m_arrInstances; }; ////////////////////////////////////////////////////////////////////////// // // Macros to be used to declare UI nuggets factories // // Global instance factory - a nugget instance always exists in a global variable // and is always shared with all screens. #define UI_NUGGET_FACTORY_GLOBAL_INSTANCE( nuggetclassname, instanceptr, scriptname ) \ namespace { \ class Factory_##nuggetclassname##_Class : public CUiNuggetFactoryRegistrarBaseGlobalInstance \ { \ virtual IGameUIScreenController * GetController( KeyValues *kvRequest ) { return static_cast< nuggetclassname * >( instanceptr ); } \ virtual IGameUIScreenController * GetControllerInstance( int iIndex ) { return static_cast< nuggetclassname * >( instanceptr ); } \ virtual char const * GetName() { return scriptname; } \ } \ g_factory_##nuggetclassname##_globalinstance; \ }; // Singleton factory - create a new nugget instance and share it with all screens // until all references to the nugget are released and nugget is destroyed. // If nugget policy is not deleting the nugget upon last release, then a single nugget // instance will be created once and shared with all screens. #define UI_NUGGET_FACTORY_SINGLETON( nuggetclassname, scriptname ) \ namespace { \ class Factory_##nuggetclassname##_Class : public CUiNuggetFactoryRegistrarBaseSingleton \ { \ virtual CUiNuggetBase * CreateNewController() { return new nuggetclassname; } \ virtual char const * GetName() { return scriptname; } \ } \ g_factory_##nuggetclassname##_singleton; \ }; // Instances factory - create a new nugget instance per each request. // Screens need to implement own methods of sharing data from a single nugget // instance. Nugget instance must be marked for delete upon last release. #define UI_NUGGET_FACTORY_INSTANCES( nuggetclassname, scriptname ) \ namespace { \ class Factory_##nuggetclassname##_Class : public CUiNuggetFactoryRegistrarBaseInstances \ { \ virtual CUiNuggetBase * CreateNewController() { return new nuggetclassname; } \ virtual char const * GetName() { return scriptname; } \ } \ g_factory_##nuggetclassname##_instances; \ }; ////////////////////////////////////////////////////////////////////////// // // Macros to be used to declare nuggets functions // #define DECLARE_NUGGET_FN_MAP( classname, baseclass ) \ typedef classname NuggetEventMapClass; \ typedef baseclass NuggetEventMapBaseClass; \ class NuggetEventMap : \ public CUtlStringMap< KeyValues * (classname::*)( IGameUISystem *pScreenView, KeyValues *args ) > \ {} \ m_NuggetEventMap; \ class NuggetPreBroadcastMap : \ public CUtlStringMap< bool (classname::*)( KeyValues *args ) > \ {} \ m_NuggetPreBroadcastMap; \ virtual KeyValues * OnScreenEvent( IGameUISystem *pScreenView, KeyValues *args ) { \ char const *szEvent = args->GetName(); \ UtlSymId_t sym = m_NuggetEventMap.Find( szEvent ); \ if ( sym != m_NuggetEventMap.InvalidIndex() ) { \ return (this->* (m_NuggetEventMap[sym]) )( pScreenView, args ); \ } \ return NuggetEventMapBaseClass::OnScreenEvent( pScreenView, args ); \ } \ virtual void BroadcastEventToScreens( KeyValues *args ) { \ char const *szEvent = args->GetName(); \ UtlSymId_t sym = m_NuggetPreBroadcastMap.Find( szEvent ); \ if ( sym != m_NuggetPreBroadcastMap.InvalidIndex() ) { \ if ( ! (this->* (m_NuggetPreBroadcastMap[sym]) )( args ) ) return; \ } \ return NuggetEventMapBaseClass::BroadcastEventToScreens( args ); \ } #define NUGGET_FN( eventname ) \ class eventname##_EventRegistrar { \ public: typedef eventname##_EventRegistrar ThisClass; \ eventname##_EventRegistrar() { \ NuggetEventMapClass *pNugget = reinterpret_cast< NuggetEventMapClass * >( reinterpret_cast< size_t >( this ) - offsetof( NuggetEventMapClass, m_##eventname##_EventRegistrar ) ); \ pNugget->m_NuggetEventMap[ #eventname ] = &NuggetEventMapClass::Event_##eventname; \ COMPILE_TIME_ASSERT( offsetof( NuggetEventMapClass, m_##eventname##_EventRegistrar ) > offsetof( NuggetEventMapClass, m_NuggetEventMap ) ); \ } } m_##eventname##_EventRegistrar; \ KeyValues * Event_##eventname( IGameUISystem *pScreenView, KeyValues *args ) #define NUGGET_BROADCAST_FN( eventname ) \ class eventname##_BroadcastRegistrar { \ public: typedef eventname##_BroadcastRegistrar ThisClass; \ eventname##_BroadcastRegistrar() { \ NuggetEventMapClass *pNugget = reinterpret_cast< NuggetEventMapClass * >( reinterpret_cast< size_t >( this ) - offsetof( NuggetEventMapClass, m_##eventname##_BroadcastRegistrar ) ); \ pNugget->m_NuggetPreBroadcastMap[ #eventname ] = &NuggetEventMapClass::Broadcast_##eventname; \ COMPILE_TIME_ASSERT( offsetof( NuggetEventMapClass, m_##eventname##_BroadcastRegistrar ) > offsetof( NuggetEventMapClass, m_NuggetPreBroadcastMap ) ); \ } } m_##eventname##_BroadcastRegistrar; \ bool Broadcast_##eventname( KeyValues *args ) #endif // UI_NUGGET_H
412
0.598424
1
0.598424
game-dev
MEDIA
0.677205
game-dev
0.624959
1
0.624959
EFanZh/LeetCode
5,398
src/problem_0749_contain_virus/bfs.rs
pub struct Solution; // ------------------------------------------------------ snip ------------------------------------------------------ // use std::collections::{HashSet, VecDeque}; enum State { Empty, Infected, Contained, } #[derive(Default)] struct Region { frontier: HashSet<(usize, usize)>, threatens: HashSet<(usize, usize)>, walls: u32, } struct ObjectPool<T>(Vec<T>); impl<T: Default> ObjectPool<T> { fn allocate(&mut self) -> T { self.0.pop().unwrap_or_default() } fn free(&mut self, value: T) { self.0.push(value); } } impl Solution { fn bfs( states: &mut [State], rows: usize, columns: usize, queue: &mut VecDeque<(usize, usize)>, visited: &mut HashSet<(usize, usize)>, regions: &mut Vec<Region>, region_pool: &mut ObjectPool<Region>, ) -> u32 { for y in 0..rows { for x in 0..columns { if matches!(states[columns * y + x], State::Infected) && visited.insert((y, x)) { let mut current_y = y; let mut current_x = x; let mut region = region_pool.allocate(); loop { for (next_y, next_x) in [ (current_y.wrapping_sub(1), current_x), (current_y, current_x.wrapping_sub(1)), (current_y, current_x + 1), (current_y + 1, current_x), ] { if next_y < rows && next_x < columns { match states[columns * next_y + next_x] { State::Empty => { region.frontier.insert((current_y, current_x)); region.threatens.insert((next_y, next_x)); region.walls += 1; } State::Infected => { if visited.insert((next_y, next_x)) { queue.push_back((next_y, next_x)); } } State::Contained => {} } } } if let Some((next_y, next_x)) = queue.pop_front() { current_y = next_y; current_x = next_x; } else { break; } } if region.walls == 0 { region_pool.free(region); } else { regions.push(region); } } } } if let Some((i, region)) = regions .iter() .enumerate() .max_by_key(|(_, region)| region.threatens.len()) { let result = region.walls; // Contain the region that threats most cells. for &(y, x) in &region.frontier { states[columns * y + x] = State::Contained; } // Expand the rest infected region. for regions in [&regions[..i], &regions[i + 1..]] { for region in regions { for &(y, x) in &region.threatens { states[columns * y + x] = State::Infected; } } } // Free memory. visited.clear(); for mut region in regions.drain(..) { region.frontier.clear(); region.threatens.clear(); region.walls = 0; region_pool.free(region); } result } else { 0 } } pub fn contain_virus(is_infected: Vec<Vec<i32>>) -> i32 { let rows = is_infected.len(); let columns = is_infected.first().map_or(0, Vec::len); let mut states = is_infected .into_iter() .flatten() .map(|value| if value == 0 { State::Empty } else { State::Infected }) .collect::<Vec<_>>(); let mut queue = VecDeque::new(); let mut visited = HashSet::new(); let mut regions = Vec::new(); let mut region_pool = ObjectPool(Vec::new()); let mut result = 0; loop { let walls = Self::bfs( &mut states, rows, columns, &mut queue, &mut visited, &mut regions, &mut region_pool, ); if walls == 0 { break; } result += walls; } result as _ } } // ------------------------------------------------------ snip ------------------------------------------------------ // impl super::Solution for Solution { fn contain_virus(is_infected: Vec<Vec<i32>>) -> i32 { Self::contain_virus(is_infected) } } #[cfg(test)] mod tests { #[test] fn test_solution() { super::super::tests::run::<super::Solution>(); } }
412
0.979791
1
0.979791
game-dev
MEDIA
0.341481
game-dev
0.997024
1
0.997024
Fluorohydride/ygopro-scripts
1,925
c81524977.lua
--種子弾丸 function c81524977.initial_effect(c) c:EnableCounterPermit(0x20) c:SetCounterLimit(0x20,5) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --add counter local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetProperty(EFFECT_FLAG_DELAY) e2:SetRange(LOCATION_SZONE) e2:SetCode(EVENT_SUMMON_SUCCESS) e2:SetCondition(c81524977.ctcon) e2:SetOperation(c81524977.ctop) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e3) local e4=e2:Clone() e4:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e4) --damage local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(81524977,0)) e5:SetCategory(CATEGORY_DAMAGE) e5:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e5:SetType(EFFECT_TYPE_IGNITION) e5:SetRange(LOCATION_SZONE) e5:SetCost(c81524977.damcost) e5:SetTarget(c81524977.damtg) e5:SetOperation(c81524977.damop) c:RegisterEffect(e5) end function c81524977.ctfilter(c) return c:IsFaceup() and c:IsRace(RACE_PLANT) end function c81524977.ctcon(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c81524977.ctfilter,1,nil) end function c81524977.ctop(e,tp,eg,ep,ev,re,r,rp) e:GetHandler():AddCounter(0x20,1) end function c81524977.damcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end e:SetLabel(e:GetHandler():GetCounter(0x20)) Duel.SendtoGrave(e:GetHandler(),REASON_COST) end function c81524977.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetCounter(0x20)>0 end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(e:GetLabel()*500) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,e:GetLabel()*500) end function c81524977.damop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end
412
0.855977
1
0.855977
game-dev
MEDIA
0.96431
game-dev
0.897565
1
0.897565
mixandjam/MarioGalaxy-LaunchStar
8,850
Assets/DOTween/Modules/DOTweenModuleAudio.cs
// Author: Daniele Giardini - http://www.demigiant.com // Created: 2018/07/13 #if true // MODULE_MARKER using System; using DG.Tweening.Core; using DG.Tweening.Plugins.Options; using UnityEngine; #if UNITY_5 || UNITY_2017_1_OR_NEWER using UnityEngine.Audio; // Required for AudioMixer #endif #pragma warning disable 1591 namespace DG.Tweening { public static class DOTweenModuleAudio { #region Shortcuts #region Audio /// <summary>Tweens an AudioSource's volume to the given value. /// Also stores the AudioSource 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> DOFade(this AudioSource target, float endValue, float duration) { if (endValue < 0) endValue = 0; else if (endValue > 1) endValue = 1; TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.volume, x => target.volume = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens an AudioSource's pitch to the given value. /// Also stores the AudioSource 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> DOPitch(this AudioSource target, float endValue, float duration) { TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.pitch, x => target.pitch = x, endValue, duration); t.SetTarget(target); return t; } #endregion #if UNITY_5 || UNITY_2017_1_OR_NEWER #region AudioMixer (Unity 5 or Newer) /// <summary>Tweens an AudioMixer's exposed float to the given value. /// Also stores the AudioMixer as the tween's target so it can be used for filtered operations. /// Note that you need to manually expose a float in an AudioMixerGroup in order to be able to tween it from an AudioMixer.</summary> /// <param name="floatName">Name given to the exposed float to set</param> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<float, float, FloatOptions> DOSetFloat(this AudioMixer target, string floatName, float endValue, float duration) { TweenerCore<float, float, FloatOptions> t = DOTween.To(()=> { float currVal; target.GetFloat(floatName, out currVal); return currVal; }, x=> target.SetFloat(floatName, x), endValue, duration); t.SetTarget(target); return t; } #region Operation Shortcuts /// <summary> /// Completes all tweens that have this target as a reference /// (meaning tweens that were started from this target, or that had this target added as an Id) /// and returns the total number of tweens completed /// (meaning the tweens that don't have infinite loops and were not already complete) /// </summary> /// <param name="withCallbacks">For Sequences only: if TRUE also internal Sequence callbacks will be fired, /// otherwise they will be ignored</param> public static int DOComplete(this AudioMixer target, bool withCallbacks = false) { return DOTween.Complete(target, withCallbacks); } /// <summary> /// Kills all tweens that have this target as a reference /// (meaning tweens that were started from this target, or that had this target added as an Id) /// and returns the total number of tweens killed. /// </summary> /// <param name="complete">If TRUE completes the tween before killing it</param> public static int DOKill(this AudioMixer target, bool complete = false) { return DOTween.Kill(target, complete); } /// <summary> /// Flips the direction (backwards if it was going forward or viceversa) of all tweens that have this target as a reference /// (meaning tweens that were started from this target, or that had this target added as an Id) /// and returns the total number of tweens flipped. /// </summary> public static int DOFlip(this AudioMixer target) { return DOTween.Flip(target); } /// <summary> /// Sends to the given position all tweens that have this target as a reference /// (meaning tweens that were started from this target, or that had this target added as an Id) /// and returns the total number of tweens involved. /// </summary> /// <param name="to">Time position to reach /// (if higher than the whole tween duration the tween will simply reach its end)</param> /// <param name="andPlay">If TRUE will play the tween after reaching the given position, otherwise it will pause it</param> public static int DOGoto(this AudioMixer target, float to, bool andPlay = false) { return DOTween.Goto(target, to, andPlay); } /// <summary> /// Pauses all tweens that have this target as a reference /// (meaning tweens that were started from this target, or that had this target added as an Id) /// and returns the total number of tweens paused. /// </summary> public static int DOPause(this AudioMixer target) { return DOTween.Pause(target); } /// <summary> /// Plays all tweens that have this target as a reference /// (meaning tweens that were started from this target, or that had this target added as an Id) /// and returns the total number of tweens played. /// </summary> public static int DOPlay(this AudioMixer target) { return DOTween.Play(target); } /// <summary> /// Plays backwards all tweens that have this target as a reference /// (meaning tweens that were started from this target, or that had this target added as an Id) /// and returns the total number of tweens played. /// </summary> public static int DOPlayBackwards(this AudioMixer target) { return DOTween.PlayBackwards(target); } /// <summary> /// Plays forward all tweens that have this target as a reference /// (meaning tweens that were started from this target, or that had this target added as an Id) /// and returns the total number of tweens played. /// </summary> public static int DOPlayForward(this AudioMixer target) { return DOTween.PlayForward(target); } /// <summary> /// Restarts all tweens that have this target as a reference /// (meaning tweens that were started from this target, or that had this target added as an Id) /// and returns the total number of tweens restarted. /// </summary> public static int DORestart(this AudioMixer target) { return DOTween.Restart(target); } /// <summary> /// Rewinds all tweens that have this target as a reference /// (meaning tweens that were started from this target, or that had this target added as an Id) /// and returns the total number of tweens rewinded. /// </summary> public static int DORewind(this AudioMixer target) { return DOTween.Rewind(target); } /// <summary> /// Smoothly rewinds all tweens that have this target as a reference /// (meaning tweens that were started from this target, or that had this target added as an Id) /// and returns the total number of tweens rewinded. /// </summary> public static int DOSmoothRewind(this AudioMixer target) { return DOTween.SmoothRewind(target); } /// <summary> /// Toggles the paused state (plays if it was paused, pauses if it was playing) of all tweens that have this target as a reference /// (meaning tweens that were started from this target, or that had this target added as an Id) /// and returns the total number of tweens involved. /// </summary> public static int DOTogglePause(this AudioMixer target) { return DOTween.TogglePause(target); } #endregion #endregion #endif #endregion } } #endif
412
0.798459
1
0.798459
game-dev
MEDIA
0.963202
game-dev
0.953189
1
0.953189
dirkwhoffmann/virtualc64
2,122
GUI/Metal/Layers/Layer.swift
// ----------------------------------------------------------------------------- // This file is part of VirtualC64 // // Copyright (C) Dirk W. Hoffmann. www.dirkwhoffmann.de // Licensed under the GNU General Public License v3 // // See https://www.gnu.org for license information // ----------------------------------------------------------------------------- class Layer: NSObject { let renderer: Renderer var controller: MyController { return renderer.parent } var ressourceManager: RessourceManager { return renderer.ressourceManager } var device: MTLDevice { return renderer.device } var view: MTKView { return renderer.view } var emu: EmulatorProxy? { return renderer.parent.emu } // Alpha channel of this layer var alpha: AnimatedFloat = AnimatedFloat(0.0) // // Initializing // init(renderer: Renderer) { self.renderer = renderer super.init() } // // Querying the visual state // var isVisible: Bool { return alpha.current > 0.0 } var isOpaque: Bool { return alpha.current == 1.0 } var isTransparent: Bool { return alpha.current < 1.0 } var isAnimating: Bool { return alpha.animates } var isFadingIn: Bool { return alpha.target > alpha.current } var isFadingOut: Bool { return alpha.target < alpha.current } // // Opening and closing // func open(delay: Double) { alpha.steps = Int(60 * delay); open() } func close(delay: Double) { alpha.steps = Int(60 * delay); close() } func open() { alpha.target = 1.0 } func close() { alpha.target = 0.0 } func toggle() { if isVisible { close() } else { open() } } // // Performing continuous tasks // func update(frames: Int64) { if alpha.animates { alpha.move() alphaDidChange() if !alpha.animates { if isVisible { layerDidOpen() } else { layerDidClose() } } } } func alphaDidChange() { } func layerDidOpen() { } func layerDidClose() { } }
412
0.709789
1
0.709789
game-dev
MEDIA
0.638086
game-dev,graphics-rendering
0.910057
1
0.910057
grayj/Jedi-Academy
7,419
codemp/botlib/be_aas_routealt.cpp
/***************************************************************************** * name: be_aas_routealt.c * * desc: AAS * * $Archive: /MissionPack/code/botlib/be_aas_routealt.c $ * $Author: Zaphod $ * $Revision: 5 $ * $Modtime: 11/22/00 8:47a $ * $Date: 11/22/00 8:55a $ * *****************************************************************************/ #include "../game/q_shared.h" #include "l_utils.h" #include "l_memory.h" #include "l_log.h" #include "l_script.h" #include "l_precomp.h" #include "l_struct.h" #include "aasfile.h" #include "../game/botlib.h" #include "../game/be_aas.h" #include "be_aas_funcs.h" #include "be_interface.h" #include "be_aas_def.h" #define ENABLE_ALTROUTING //#define ALTROUTE_DEBUG typedef struct midrangearea_s { int valid; unsigned short starttime; unsigned short goaltime; } midrangearea_t; midrangearea_t *midrangeareas; int *clusterareas; int numclusterareas; //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_AltRoutingFloodCluster_r(int areanum) { int i, otherareanum; aas_area_t *area; aas_face_t *face; //add the current area to the areas of the current cluster clusterareas[numclusterareas] = areanum; numclusterareas++; //remove the area from the mid range areas midrangeareas[areanum].valid = qfalse; //flood to other areas through the faces of this area area = &aasworld.areas[areanum]; for (i = 0; i < area->numfaces; i++) { face = &aasworld.faces[abs(aasworld.faceindex[area->firstface + i])]; //get the area at the other side of the face if (face->frontarea == areanum) otherareanum = face->backarea; else otherareanum = face->frontarea; //if there is an area at the other side of this face if (!otherareanum) continue; //if the other area is not a midrange area if (!midrangeareas[otherareanum].valid) continue; // AAS_AltRoutingFloodCluster_r(otherareanum); } //end for } //end of the function AAS_AltRoutingFloodCluster_r //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags, aas_altroutegoal_t *altroutegoals, int maxaltroutegoals, int type) { #ifndef ENABLE_ALTROUTING return 0; #else int i, j, bestareanum; int numaltroutegoals, nummidrangeareas; int starttime, goaltime, goaltraveltime; float dist, bestdist; vec3_t mid, dir; #ifdef ALTROUTE_DEBUG int startmillisecs; startmillisecs = Sys_MilliSeconds(); #endif if (!startareanum || !goalareanum) return 0; //travel time towards the goal area goaltraveltime = AAS_AreaTravelTimeToGoalArea(startareanum, start, goalareanum, travelflags); //clear the midrange areas Com_Memset(midrangeareas, 0, aasworld.numareas * sizeof(midrangearea_t)); numaltroutegoals = 0; // nummidrangeareas = 0; // for (i = 1; i < aasworld.numareas; i++) { // if (!(type & ALTROUTEGOAL_ALL)) { if (!(type & ALTROUTEGOAL_CLUSTERPORTALS && (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL))) { if (!(type & ALTROUTEGOAL_VIEWPORTALS && (aasworld.areasettings[i].contents & AREACONTENTS_VIEWPORTAL))) { continue; } //end if } //end if } //end if //if the area has no reachabilities if (!AAS_AreaReachability(i)) continue; //tavel time from the area to the start area starttime = AAS_AreaTravelTimeToGoalArea(startareanum, start, i, travelflags); if (!starttime) continue; //if the travel time from the start to the area is greater than the shortest goal travel time if (starttime > (float) 1.1 * goaltraveltime) continue; //travel time from the area to the goal area goaltime = AAS_AreaTravelTimeToGoalArea(i, NULL, goalareanum, travelflags); if (!goaltime) continue; //if the travel time from the area to the goal is greater than the shortest goal travel time if (goaltime > (float) 0.8 * goaltraveltime) continue; //this is a mid range area midrangeareas[i].valid = qtrue; midrangeareas[i].starttime = starttime; midrangeareas[i].goaltime = goaltime; Log_Write("%d midrange area %d", nummidrangeareas, i); nummidrangeareas++; } //end for // for (i = 1; i < aasworld.numareas; i++) { if (!midrangeareas[i].valid) continue; //get the areas in one cluster numclusterareas = 0; AAS_AltRoutingFloodCluster_r(i); //now we've got a cluster with areas through which an alternative route could go //get the 'center' of the cluster VectorClear(mid); for (j = 0; j < numclusterareas; j++) { VectorAdd(mid, aasworld.areas[clusterareas[j]].center, mid); } //end for VectorScale(mid, 1.0 / numclusterareas, mid); //get the area closest to the center of the cluster bestdist = 999999; bestareanum = 0; for (j = 0; j < numclusterareas; j++) { VectorSubtract(mid, aasworld.areas[clusterareas[j]].center, dir); dist = VectorLength(dir); if (dist < bestdist) { bestdist = dist; bestareanum = clusterareas[j]; } //end if } //end for //now we've got an area for an alternative route //FIXME: add alternative goal origin VectorCopy(aasworld.areas[bestareanum].center, altroutegoals[numaltroutegoals].origin); altroutegoals[numaltroutegoals].areanum = bestareanum; altroutegoals[numaltroutegoals].starttraveltime = midrangeareas[bestareanum].starttime; altroutegoals[numaltroutegoals].goaltraveltime = midrangeareas[bestareanum].goaltime; altroutegoals[numaltroutegoals].extratraveltime = (midrangeareas[bestareanum].starttime + midrangeareas[bestareanum].goaltime) - goaltraveltime; numaltroutegoals++; // #ifdef ALTROUTE_DEBUG AAS_ShowAreaPolygons(bestareanum, 1, qtrue); #endif //don't return more than the maximum alternative route goals if (numaltroutegoals >= maxaltroutegoals) break; } //end for #ifdef ALTROUTE_DEBUG botimport.Print(PRT_MESSAGE, "alternative route goals in %d msec\n", Sys_MilliSeconds() - startmillisecs); #endif return numaltroutegoals; #endif } //end of the function AAS_AlternativeRouteGoals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_InitAlternativeRouting(void) { #ifdef ENABLE_ALTROUTING if (midrangeareas) FreeMemory(midrangeareas); midrangeareas = (midrangearea_t *) GetMemory(aasworld.numareas * sizeof(midrangearea_t)); if (clusterareas) FreeMemory(clusterareas); clusterareas = (int *) GetMemory(aasworld.numareas * sizeof(int)); #endif } //end of the function AAS_InitAlternativeRouting //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_ShutdownAlternativeRouting(void) { #ifdef ENABLE_ALTROUTING if (midrangeareas) FreeMemory(midrangeareas); midrangeareas = NULL; if (clusterareas) FreeMemory(clusterareas); clusterareas = NULL; numclusterareas = 0; #endif } //end of the function AAS_ShutdownAlternativeRouting
412
0.749
1
0.749
game-dev
MEDIA
0.536149
game-dev
0.897858
1
0.897858
opentibiabr/canary
39,205
data/libs/compat/compat.lua
if type(result) then result = Result end result.getDataInt = result.getNumber result.getDataLong = result.getNumber result.getDataString = result.getString result.getDataStream = result.getStream STACKPOS_TOP_CREATURE = 253 STACKPOS_TOP_FIELD = 254 STACKPOS_TOP_MOVABLE_ITEM_OR_CREATURE = 255 THING_TYPE_PLAYER = CREATURETYPE_PLAYER + 1 THING_TYPE_MONSTER = CREATURETYPE_MONSTER + 1 THING_TYPE_NPC = CREATURETYPE_NPC + 1 function pushThing(thing) local t = { uid = 0, itemid = 0, type = 0, actionid = 0 } if thing then if thing:isItem() then t.uid = thing:getUniqueId() t.itemid = thing:getId() if ItemType(t.itemid):hasSubType() then t.type = thing:getSubType() end t.actionid = thing:getActionId() elseif thing:isCreature() then t.uid = thing:getId() t.itemid = 1 if thing:isPlayer() then t.type = THING_TYPE_PLAYER elseif thing:isMonster() then t.type = THING_TYPE_MONSTER else t.type = THING_TYPE_NPC end end end return t end createCombatObject = Combat addCombatCondition = Combat.addCondition setCombatArea = Combat.setArea setCombatCallback = Combat.setCallback setCombatFormula = Combat.setFormula setCombatParam = Combat.setParameter Combat.setCondition = function(...) logger.warn("[Combat.setCondition] - Function was renamed to Combat.addCondition and will be removed in the future") Combat.addCondition(...) end setCombatCondition = function(...) logger.warn("[setCombatCondition] - Function was renamed to Combat.addCondition and will be removed in the future") Combat.addCondition(...) end createConditionObject = Condition setConditionParam = Condition.setParameter setConditionFormula = Condition.setFormula addDamageCondition = Condition.addDamage addOutfitCondition = Condition.setOutfit function doCombat(cid, combat, var) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'doCombat(cid, combat, var)' is outdated. Please use the new format 'combat:execute(cid, var)'. Update needed at: Line {}, Source: {}.", line, source) return combat:execute(cid, var) end function isCreature(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'isCreature(cid)' is outdated. Please use the new format 'Creature(cid)'. Update needed at: Line {}, Source: {}.", line, source) return Creature(cid) ~= nil end function isPlayer(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'isPlayer(cid)' is outdated. Please use the new format 'Player(cid)'. Update needed at: Line {}, Source: {}.", line, source) return Player(cid) ~= nil end function isMonster(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'isMonster(cid)' is outdated. Please use the new format 'Monster(cid)'. Update needed at: Line {}, Source: {}.", line, source) return Monster(cid) ~= nil end function isSummon(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'isSummon(cid)' is outdated. Please use the new format 'c:getMaster()', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) return Creature(cid):getMaster() ~= nil end function isNpc(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'isNpc(cid)' is outdated. Please use the new format 'Npc(cid)'. Update needed at: Line {}, Source: {}.", line, source) return Npc(cid) ~= nil end function isItem(uid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'isItem(uid)' is outdated. Please use the new format 'Item(uid)'. Update needed at: Line {}, Source: {}.", line, source) return Item(uid) ~= nil end function isContainer(uid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'isContainer(uid)' is outdated. Please use the new format 'Container(uid)'. Update needed at: Line {}, Source: {}.", line, source) return Container(uid) ~= nil end function getCreatureName(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'getCreatureName(cid)' is outdated. Please use the new format 'c:getName()', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) local c = Creature(cid) return c and c:getName() or false end function getCreatureHealth(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'getCreatureHealth(cid)' is outdated. Please use the new format 'c:getHealth()', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) local c = Creature(cid) return c and c:getHealth() or false end function getCreatureMaxHealth(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'getCreatureMaxHealth(cid)' is outdated. Please use the new format 'c:getMaxHealth()', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) local c = Creature(cid) return c and c:getMaxHealth() or false end function getCreaturePosition(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'getCreaturePosition(cid)' is outdated. Please use the new format 'c:getPosition()', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) local c = Creature(cid) return c and c:getPosition() or false end function getCreatureOutfit(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'getCreatureOutfit(cid)' is outdated. Please use the new format 'c:getOutfit()', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) local c = Creature(cid) return c and c:getOutfit() or false end function getCreatureSpeed(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'getCreatureSpeed(cid)' is outdated. Please use the new format 'c:getSpeed()', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) local c = Creature(cid) return c and c:getSpeed() or false end function getCreatureBaseSpeed(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'getCreatureBaseSpeed(cid)' is outdated. Please use the new format 'c:getBaseSpeed()', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) local c = Creature(cid) return c and c:getBaseSpeed() or false end function getCreatureTarget(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'getCreatureTarget(cid)' is outdated. Please use the new format 'c:getTarget():getId()', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) local c = Creature(cid) if c then local target = c:getTarget() return target and target:getId() or 0 end return false end function getCreatureMaster(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'getCreatureMaster(cid)' is outdated. Please use the new format 'c:getMaster():getId()', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) local c = Creature(cid) if c then local master = c:getMaster() return master and master:getId() or c:getId() end return false end function getCreatureSummons(cid) local c = Creature(cid) if not c then return false end local result = {} for _, summon in ipairs(c:getSummons()) do result[#result + 1] = summon:getId() end return result end getCreaturePos = getCreaturePosition function doCreatureAddHealth(cid, health) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'doCreatureAddHealth(cid, health)' is outdated. Please use the new format 'c:addHealth(health)', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) local c = Creature(cid) return c and c:addHealth(health) or false end function doRemoveCreature(cid) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'doRemoveCreature(cid)' is outdated. Please use the new format 'c:remove()', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) local c = Creature(cid) return c and c:remove() or false end function doCreatureSetLookDir(cid, direction) local line = debug.getinfo(2).currentline local source = debug.getinfo(2).source:match("@?(.*)") logger.warn("Deprecation Warning: The function 'doCreatureSetLookDir(cid, direction)' is outdated. Please use the new format 'c:setDirection(direction)', where 'c' refers to a Creature (player or monster). Update needed at: Line {}, Source: {}.", line, source) local c = Creature(cid) return c and c:setDirection(direction) or false end function doCreatureSay(cid, text, type, ...) local c = Creature(cid) return c and c:say(text, type, ...) or false end function doCreatureChangeOutfit(cid, outfit) local c = Creature(cid) return c and c:setOutfit(outfit) or false end function doSetCreatureDropLoot(cid, doDrop) local c = Creature(cid) return c and c:setDropLoot(doDrop) or false end function doChangeSpeed(cid, delta) local c = Creature(cid) return c and c:changeSpeed(delta) or false end function doAddCondition(cid, conditionId) local c = Creature(cid) return c and c:addCondition(conditionId) or false end function doRemoveCondition(cid, conditionType, subId) local c = Creature(cid) return c and (c:removeCondition(conditionType, CONDITIONID_COMBAT, subId) or c:removeCondition(conditionType, CONDITIONID_DEFAULT, subId) or true) end function getCreatureCondition(cid, type, subId) local c = Creature(cid) return c and c:hasCondition(type, subId) or false end doSetCreatureDirection = doCreatureSetLookDir function registerCreatureEvent(cid, name) local c = Creature(cid) return c and c:registerEvent(name) or false end function unregisterCreatureEvent(cid, name) local c = Creature(cid) return c and c:unregisterEvent(name) or false end function getPlayerByName(name) local p = Player(name) return p and p:getId() or false end function getIPByPlayerName(name) local p = Player(name) return p and p:getIp() or false end function getPlayerGUID(cid) local p = Player(cid) return p and p:getGuid() or false end function getPlayerIp(cid) local p = Player(cid) return p and p:getIp() or false end function getPlayerAccountType(cid) local p = Player(cid) return p and p:getAccountType() or false end function getPlayerLastLoginSaved(cid) local p = Player(cid) return p and p:getLastLoginSaved() or false end function getPlayerName(cid) local p = Player(cid) return p and p:getName() or false end function getPlayerFreeCap(cid) local p = Player(cid) return p and (p:getFreeCapacity() / 100) or false end function getPlayerPosition(cid) local p = Player(cid) return p and p:getPosition() or false end function getPlayerMagLevel(cid) local p = Player(cid) return p and p:getMagicLevel() or false end function getPlayerAccess(cid) local player = Player(cid) if player == nil then return false end return player:getGroup():getAccess() and 1 or 0 end function getPlayerSkill(cid, skillId) local p = Player(cid) return p and p:getSkillLevel(skillId) or false end function getPlayerMana(cid) local p = Player(cid) return p and p:getMana() or false end function getPlayerMaxMana(cid) local p = Player(cid) return p and p:getMaxMana() or false end function getPlayerLevel(cid) local p = Player(cid) return p and p:getLevel() or false end function getPlayerTown(cid) local p = Player(cid) return p and p:getTown():getId() or false end function getPlayerVocation(cid) local p = Player(cid) return p and p:getVocation():getId() or false end function getPlayerSoul(cid) local p = Player(cid) return p and p:getSoul() or false end function getPlayerSex(cid) local p = Player(cid) return p and p:getSex() or false end function getPlayerStorageValue(cid, key) local p = Player(cid) return p and p:getStorageValue(key) or false end function getPlayerBalance(cid) local p = Player(cid) return p and p:getBankBalance() or false end function getPlayerMoney(cid) local p = Player(cid) return p and p:getMoney() or false end function getPlayerGroupId(cid) local p = Player(cid) return p and p:getGroup():getId() or false end function getPlayerLookDir(cid) local p = Player(cid) return p and p:getDirection() or false end function getPlayerLight(cid) local p = Player(cid) return p and p:getLight() or false end function getPlayerDepotItems(cid, depotId) local p = Player(cid) return p and p:getDepotItems(depotId) or false end function getPlayerSkullType(cid) local p = Player(cid) return p and p:getSkull() or false end function getPlayerLossPercent(cid) local p = Player(cid) return p and p:getDeathPenalty() or false end function getPlayerMount(cid, mountId) local p = Player(cid) return p and p:hasMount(mountId) or false end function getPlayerPremiumDays(cid) local p = Player(cid) return p and p:getPremiumDays() or false end function getPlayerBlessing(cid, blessing) local p = Player(cid) return p and p:hasBlessing(blessing) or false end function getPlayerFlagValue(cid, flag) local p = Player(cid) return p ~= nil and p:hasFlag(flag) or false end function getPlayerParty(cid) local player = Player(cid) if player == nil then return false end local party = player:getParty() if party == nil then return nil end return party:getLeader():getId() end function getPlayerGuildId(cid) local player = Player(cid) if player == nil then return false end local guild = player:getGuild() if guild == nil then return false end return guild:getId() end function getPlayerGuildLevel(cid) local p = Player(cid) return p and p:getGuildLevel() or false end function getPlayerGuildName(cid) local player = Player(cid) if player == nil then return false end local guild = player:getGuild() if guild == nil then return false end return guild:getName() end function getPlayerGuildRank(cid) local player = Player(cid) if player == nil then return false end local guild = player:getGuild() if guild == nil then return false end local rank = guild:getRankByLevel(player:getGuildLevel()) return rank and rank.name or false end function getPlayerGuildNick(cid) local p = Player(cid) return p and p:getGuildNick() or false end function getPlayerMasterPos(cid) local p = Player(cid) return p and p:getTown():getTemplePosition() or false end function getPlayerItemCount(cid, itemId, ...) local p = Player(cid) return p and p:getItemCount(itemId, ...) or false end function getPlayerSlotItem(cid, slot) local player = Player(cid) if player == nil then return pushThing(nil) end return pushThing(player:getSlotItem(slot)) end function getPlayerItemById(cid, deepSearch, itemId, ...) local player = Player(cid) if player == nil then return pushThing(nil) end return pushThing(player:getItemById(itemId, deepSearch, ...)) end function getPlayerFood(cid) local player = Player(cid) if player == nil then return false end local c = player:getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT) return c and math.floor(c:getTicks() / 1000) or 0 end function canPlayerLearnInstantSpell(cid, name) local p = Player(cid) return p and p:canLearnSpell(name) or false end function getPlayerLearnedInstantSpell(cid, name) local p = Player(cid) return p and p:hasLearnedSpell(name) or false end function isPlayerGhost(cid) local p = Player(cid) return p ~= nil and p:isInGhostMode() or false end function isPlayerPzLocked(cid) local p = Player(cid) return p ~= nil and p:isPzLocked() or false end function isPremium(cid) local p = Player(cid) return p ~= nil and p:isPremium() or false end function getBlessingCost(level, byCommand, blessId) return Blessings.getBlessingCost(level, byCommand, blessId) end function getPvpBlessingCost(level, byCommand) return Blessings.getPvpBlessingCost(level, byCommand) end function getPlayersByIPAddress(ip, mask) if mask == nil then mask = 0xFFFFFFFF end local masked = bit.band(ip, mask) local result = {} for _, player in ipairs(Game.getPlayers()) do if bit.band(player:getIp(), mask) == masked then result[#result + 1] = player:getId() end end return result end function getOnlinePlayers() local result = {} for _, player in ipairs(Game.getPlayers()) do result[#result + 1] = player:getName() end return result end function getPlayerGUIDByName(name) local player = Player(name) if player then return player:getGuid() end local resultId = db.storeQuery("SELECT `id` FROM `players` WHERE `name` = " .. db.escapeString(name)) if resultId ~= false then local guid = Result.getNumber(resultId, "id") Result.free(resultId) return guid end return 0 end function getAccountNumberByPlayerName(name) return Game.getPlayerAccountId(name) end getPlayerAccountBalance = getPlayerBalance getIpByName = getIPByPlayerName function setPlayerStorageValue(cid, key, value) local p = Player(cid) return p and p:setStorageValue(key, value) or false end function doPlayerSetBalance(cid, balance) local p = Player(cid) return p and p:setBankBalance(balance) or false end function doPlayerAddMoney(cid, money) local p = Player(cid) return p and p:addMoney(money) or false end function doPlayerRemoveMoney(cid, money) local p = Player(cid) return p and p:removeMoney(money) or false end function doPlayerTakeItem(cid, itemid, count) local p = Player(cid) return p and p:removeItem(itemid, count) or false end function doPlayerAddSoul(cid, soul) local p = Player(cid) return p and p:addSoul(soul) or false end function doPlayerSetVocation(cid, vocation) local p = Player(cid) return p and p:setVocation(Vocation(vocation)) or false end function doPlayerSetTown(cid, town) local p = Player(cid) return p and p:setTown(Town(town)) or false end function setPlayerGroupId(cid, groupId) local p = Player(cid) return p and p:setGroup(Group(groupId)) or false end function doPlayerSetSex(cid, sex) local p = Player(cid) return p and p:setSex(sex) or false end function doPlayerSetGuildLevel(cid, level) local p = Player(cid) return p and p:setGuildLevel(level) or false end function doPlayerSetGuildNick(cid, nick) local p = Player(cid) return p and p:setGuildNick(nick) or false end function doPlayerSetOfflineTrainingSkill(cid, skillId) local p = Player(cid) return p and p:setOfflineTrainingSkill(skillId) or false end function doShowTextDialog(cid, itemId, text) local p = Player(cid) return p and p:showTextDialog(itemId, text) or false end function doPlayerAddItemEx(cid, uid, ...) local p = Player(cid) return p and p:addItemEx(Item(uid), ...) or false end function doPlayerRemoveItem(cid, itemid, count, ...) local p = Player(cid) return p and p:removeItem(itemid, count, ...) or false end function doPlayerAddPremiumDays(cid, days) local p = Player(cid) return p and p:addPremiumDays(days) or false end function doPlayerRemovePremiumDays(cid, days) local p = Player(cid) return p and p:removePremiumDays(days) or false end function doPlayerAddBlessing(cid, blessing) local p = Player(cid) return p and p:addBlessing(blessing) or false end function doPlayerAddOutfit(cid, lookType, addons) local p = Player(cid) return p and p:addOutfitAddon(lookType, addons) or false end function doPlayerRemOutfit(cid, lookType, addons) local player = Player(cid) if player == nil then return false end if addons == 255 then return player:removeOutfit(lookType) else return player:removeOutfitAddon(lookType, addons) end end function canPlayerWearOutfit(cid, lookType, addons) local p = Player(cid) return p and p:hasOutfit(lookType, addons) or false end function doPlayerAddMount(cid, mountId) local p = Player(cid) return p and p:addMount(mountId) or false end function doPlayerRemoveMount(cid, mountId) local p = Player(cid) return p and p:removeMount(mountId) or false end function doPlayerSendCancel(cid, text) local p = Player(cid) return p and p:sendCancelMessage(text) or false end function doPlayerFeed(cid, food) local p = Player(cid) return p and p:feed(food) or false end function playerLearnInstantSpell(cid, name) local p = Player(cid) return p and p:learnSpell(name) or false end function doPlayerPopupFYI(cid, message) local p = Player(cid) return p and p:popupFYI(message) or false end function doSendTutorial(cid, tutorialId) local p = Player(cid) return p and p:sendTutorial(tutorialId) or false end function doAddMapMark(cid, pos, type, description) local p = Player(cid) return p and p:addMapMark(pos, type, description or "") or false end function doPlayerSendTextMessage(cid, type, text, ...) local p = Player(cid) return p and p:sendTextMessage(type, text, ...) or false end function doPlayerSendChannelMessage(cid, author, message, SpeakClasses, channel) local p = Player(cid) return p and p:sendChannelMessage(author, message, SpeakClasses, channel) or false end function doSendAnimatedText() debugPrint("Deprecated function.") return true end function doPlayerAddManaSpent(cid, mana) local p = Player(cid) return p and p:addManaSpent(mana) or false end function doPlayerAddSkillTry(cid, skillid, n) local p = Player(cid) return p and p:addSkillTries(skillid, n) or false end function doPlayerAddMana(cid, mana, ...) local p = Player(cid) return p and p:addMana(mana, ...) or false end function doPlayerJoinParty(cid, leaderId) local player = Player(cid) if player == nil then return false end if player:getParty() then player:sendTextMessage(MESSAGE_PARTY_MANAGEMENT, "You are already in a party.") return true end local leader = Player(leaderId) if leader == nil then return false end local party = leader:getParty() if party == nil or party:getLeader() ~= leader then return true end for _, invitee in ipairs(party:getInvitees()) do if player ~= invitee then return true end end party:addMember(player) return true end function getPartyMembers(cid) local player = Player(cid) if player == nil then return false end local party = player:getParty() if party == nil then return false end local result = { party:getLeader():getId() } for _, member in ipairs(party:getMembers()) do result[#result + 1] = member:getId() end return result end doPlayerSendDefaultCancel = doPlayerSendCancel function getMonsterTargetList(cid) local monster = Monster(cid) if monster == nil then return false end local result = {} for _, creature in ipairs(monster:getTargetList()) do if monster:isTarget(creature) then result[#result + 1] = creature:getId() end end return result end function getMonsterFriendList(cid) local monster = Monster(cid) if monster == nil then return false end local z = monster:getPosition().z local result = {} for _, creature in ipairs(monster:getFriendList()) do if not creature:isRemoved() and creature:getPosition().z == z then result[#result + 1] = creature:getId() end end return result end function doSetMonsterTarget(cid, target) local monster = Monster(cid) if monster == nil then return false end if monster:getMaster() then return true end local target = Creature(cid) if target == nil then return false end monster:selectTarget(target) return true end function doMonsterChangeTarget(cid) local monster = Monster(cid) if monster == nil then return false end if monster:getMaster() then return true end monster:searchTarget(1) return true end function doCreateNpc(name, pos, ...) local npc = Game.createNpc(name, pos, ...) return npc and npc:setMasterPos(pos) or false end function doSummonCreature(name, pos, ...) local m = Game.createMonster(name, pos, ...) return m and m:getId() or false end function doConvinceCreature(cid, target) local creature = Creature(cid) if creature == nil then return false end local targetCreature = Creature(target) if targetCreature == nil then return false end creature:setSummon(targetCreature) return true end function getTownId(townName) local t = Town(townName) return t and t:getId() or false end function getTownName(townId) local t = Town(townId) return t and t:getName() or false end function getTownTemplePosition(townId) local t = Town(townId) return t and t:getTemplePosition() or false end function doSetItemActionId(uid, actionId) local i = Item(uid) return i and i:setActionId(actionId) or false end function doTransformItem(uid, newItemId, ...) local i = Item(uid) return i and i:transform(newItemId, ...) or false end function doChangeTypeItem(uid, newType) local i = Item(uid) return i and i:transform(i:getId(), newType) or false end function doRemoveItem(uid, ...) local i = Item(uid) return i and i:remove(...) or false end function getContainerSize(uid) local c = Container(uid) return c and c:getSize() or false end function getContainerCap(uid) local c = Container(uid) return c and c:getCapacity() or false end function getContainerItem(uid, slot) local container = Container(uid) if container == nil then return pushThing(nil) end return pushThing(container:getItem(slot)) end function doAddContainerItemEx(uid, virtualId) local container = Container(uid) if container == nil then return false end local res = container:addItemEx(Item(virtualId)) if res == nil then return false end return res end function doSendMagicEffect(pos, magicEffect, ...) return Position(pos):sendMagicEffect(magicEffect, ...) end function doSendDistanceShoot(fromPos, toPos, distanceEffect, ...) return Position(fromPos):sendDistanceEffect(toPos, distanceEffect, ...) end function isSightClear(fromPos, toPos, floorCheck) return Position(fromPos):isSightClear(toPos, floorCheck) end function getPromotedVocation(vocationId) local vocation = Vocation(vocationId) if vocation == nil then return 0 end local promotedVocation = vocation:getPromotion() if promotedVocation == nil then return 0 end return promotedVocation:getId() end function getGuildId(guildName) local resultId = db.storeQuery("SELECT `id` FROM `guilds` WHERE `name` = " .. db.escapeString(guildName)) if resultId == false then return false end local guildId = Result.getNumber(resultId, "id") Result.free(resultId) return guildId end function getHouseName(houseId) local h = House(houseId) return h and h:getName() or false end function getHouseOwner(houseId) local h = House(houseId) return h and h:getOwnerGuid() or false end function getHouseEntry(houseId) local h = House(houseId) return h and h:getExitPosition() or false end function getHouseTown(houseId) local h = House(houseId) if h == nil then return false end local t = h:getTown() return t and t:getId() or false end function getHouseTilesSize(houseId) local h = House(houseId) return h and h:getTileCount() or false end function isItemStackable(itemId) return ItemType(itemId):isStackable() end function isItemRune(itemId) return ItemType(itemId):isRune() end function isItemDoor(itemId) return ItemType(itemId):isDoor() end function isItemContainer(itemId) return ItemType(itemId):isContainer() end function isItemFluidContainer(itemId) return ItemType(itemId):isFluidContainer() end function isItemMovable(itemId) return ItemType(itemId):isMovable() end function isCorpse(uid) local i = Item(uid) return i ~= nil and ItemType(i:getId()):isCorpse() or false end isItemMovable = isItemMovable isMovable = isMovable function getItemName(itemId) return ItemType(itemId):getName() end function getItemWeight(itemId, ...) return ItemType(itemId):getWeight(...) / 100 end function getItemDescriptions(itemId) local itemType = ItemType(itemId) return { name = itemType:getName(), plural = itemType:getPluralName(), article = itemType:getArticle(), description = itemType:getDescription(), } end function getItemIdByName(name) local id = ItemType(name):getId() if id == 0 then return false end return id end function getItemWeightByUID(uid, ...) local item = Item(uid) if item == nil then return false end local itemType = ItemType(item:getId()) return itemType:isStackable() and (itemType:getWeight(item:getCount(), ...) / 100) or (itemType:getWeight(1, ...) / 100) end function getItemRWInfo(uid) local item = Item(uid) if item == nil then return false end local rwFlags = 0 local itemType = ItemType(item:getId()) if itemType:isReadable() then rwFlags = bit.bor(rwFlags, 1) end if itemType:isWritable() then rwFlags = bit.bor(rwFlags, 2) end return rwFlags end function getContainerCapById(itemId) return ItemType(itemId):getCapacity() end function getFluidSourceType(itemId) local it = ItemType(itemId) return it.id ~= 0 and it:getFluidSource() or false end function hasProperty(uid, prop) local item = Item(uid) if item == nil then return false end local parent = item:getParent() if parent:isTile() and item == parent:getGround() then return parent:hasProperty(prop) else return item:hasProperty(prop) end end function doSetItemText(uid, text) local item = Item(uid) if item == nil then return false end if text ~= "" then item:setAttribute(ITEM_ATTRIBUTE_TEXT, text) else item:removeAttribute(ITEM_ATTRIBUTE_TEXT) end return true end function doSetItemSpecialDescription(uid, desc) local item = Item(uid) if item == nil then return false end if desc ~= "" then item:setAttribute(ITEM_ATTRIBUTE_DESCRIPTION, desc) else item:removeAttribute(ITEM_ATTRIBUTE_DESCRIPTION) end return true end function doDecayItem(uid) local i = Item(uid) return i and i:decay() or false end function setHouseOwner(id, guid) local h = House(id) return h and h:setHouseOwner(guid) or false end function getHouseRent(id) local h = House(id) return h and h:getRent() or nil end function getHouseAccessList(id, listId) local h = House(id) return h and h:getAccessList(listId) or nil end function setHouseAccessList(id, listId, listText) local h = House(id) return h and h:setAccessList(listId, listText) or false end function getHouseByPlayerGUID(playerGUID) for _, house in ipairs(Game.getHouses()) do if house:getOwnerGuid() == playerGUID then return house:getId() end end return nil end function getTileHouseInfo(pos) local t = Tile(pos) if t == nil then return false end local h = t:getHouse() return h and h:getId() or false end function getTileInfo(position) local t = Tile(position) if t == nil then return false end local ret = pushThing(t:getGround()) ret.protection = t:hasFlag(TILESTATE_PROTECTIONZONE) ret.pvp = t:hasFlag(TILESTATE_PVPZONE) ret.nopvp = t:hasFlag(TILESTATE_NOPVPZONE) ret.nopz = ret.protection ret.nologout = t:hasFlag(TILESTATE_NOLOGOUT) ret.refresh = t:hasFlag(TILESTATE_REFRESH) ret.house = t:getHouse() ~= nil ret.bed = t:hasFlag(TILESTATE_BED) ret.depot = t:hasFlag(TILESTATE_DEPOT) ret.things = t:getThingCount() ret.creatures = t:getCreatureCount() ret.items = t:getItemCount() ret.topItems = t:getTopItemCount() ret.downItems = t:getDownItemCount() return ret end function getTileItemByType(position, itemType) local t = Tile(position) if t == nil then return pushThing(nil) end return pushThing(t:getItemByType(itemType)) end function getTileItemById(position, itemId, ...) local t = Tile(position) if t == nil then return pushThing(nil) end return pushThing(t:getItemById(itemId, ...)) end function getTileThingByPos(position) local t = Tile(position) if t == nil then if position.stackpos == -1 then return -1 end return pushThing(nil) end if position.stackpos == -1 then return t:getThingCount() end return pushThing(t:getThing(position.stackpos)) end function getTileThingByTopOrder(position, topOrder) local t = Tile(position) if t == nil then return pushThing(nil) end return pushThing(t:getItemByTopOrder(topOrder)) end function getTopCreature(position) local t = Tile(position) if t == nil then return pushThing(nil) end return pushThing(t:getTopCreature()) end function queryTileAddThing(thing, position, ...) local t = Tile(position) return t and t:queryAdd(thing, ...) or false end function doTeleportThing(uid, dest, pushMovement) if type(uid) == "userdata" then if uid:isCreature() then return uid:teleportTo(dest, pushMovement or false) else return uid:moveTo(dest) end else if uid >= 0x10000000 then local creature = Creature(uid) if creature then return creature:teleportTo(dest, pushMovement or false) end else local item = Item(uid) if item then return item:moveTo(dest) end end end return false end function getThingPos(uid) local thing if type(uid) ~= "userdata" then if uid >= 0x10000000 then thing = Creature(uid) else thing = Item(uid) end else thing = uid end if thing == nil then return false end local stackpos = 0 local tile = thing:getTile() if tile then stackpos = tile:getThingIndex(thing) end local position = thing:getPosition() position.stackpos = stackpos return position end function getThingfromPos(pos) local tile = Tile(pos) if tile == nil then return pushThing(nil) end local thing local stackpos = pos.stackpos or 0 if stackpos == STACKPOS_TOP_MOVABLE_ITEM_OR_CREATURE then thing = tile:getTopCreature() if thing == nil then local item = tile:getTopDownItem() if item and item:getType():isMovable() then thing = item end end elseif stackpos == STACKPOS_TOP_FIELD then thing = tile:getFieldItem() elseif stackpos == STACKPOS_TOP_CREATURE then thing = tile:getTopCreature() else thing = tile:getThing(stackpos) end return pushThing(thing) end function getThing(uid) return uid >= 0x10000000 and pushThing(Creature(uid)) or pushThing(Item(uid)) end function getConfigInfo(info) if type(info) ~= "string" then return nil end dofile("config.lua") return _G[info] end function getWorldCreatures(type) if type == 0 then return Game.getPlayerCount() elseif type == 1 then return Game.getMonsterCount() elseif type == 2 then return Game.getNpcCount() end return Game.getPlayerCount() + Game.getMonsterCount() + Game.getNpcCount() end saveData = saveServer function getGlobalStorageValue(key) return Game.getStorageValue(key) or -1 end function setGlobalStorageValue(key, value) Game.setStorageValue(key, value) return true end getWorldType = Game.getWorldType numberToVariant = Variant stringToVariant = Variant positionToVariant = Variant function targetPositionToVariant(position) local variant = Variant(position) variant.type = VARIANT_TARGETPOSITION return variant end variantToNumber = Variant.getNumber variantToString = Variant.getString variantToPosition = Variant.getPosition function doCreateTeleport(itemId, destination, position) local item = Game.createItem(itemId, 1, position) if not item:isTeleport() then item:remove() return false end item:setDestination(destination) return item:getUniqueId() end function getSpectators(centerPos, rangex, rangey, multifloor, onlyPlayers) local result = Game.getSpectators(centerPos, multifloor, onlyPlayers or false, rangex, rangex, rangey, rangey) if #result == 0 then return nil end for index, spectator in ipairs(result) do result[index] = spectator:getId() end return result end function broadcastMessage(message, messageType) Game.broadcastMessage(message, messageType) logger.info("Broadcasted message: {}", message) end function Guild.addMember(self, player) return player:setGuild(guild) end function Guild.removeMember(self, player) return player:getGuild() == self and player:setGuild(nil) end function getPlayerInstantSpellCount(cid) local p = Player(cid) return p and #p:getInstantSpells() end function getPlayerInstantSpellInfo(cid, spellId) local player = Player(cid) if not player then return false end local spell = Spell(spellId) if not spell or not player:canCast(spell) then return false end return spell end function doSetItemOutfit(cid, item, time) local c = Creature(cid) return c and c:setItemOutfit(item, time) end function doSetMonsterOutfit(cid, name, time) local c = Creature(cid) return c and c:setMonsterOutfit(name, time) end function doSetCreatureOutfit(cid, outfit, time) local creature = Creature(cid) if not creature then return false end local condition = Condition(CONDITION_OUTFIT) condition:setOutfit(outfit) condition:setTicks(time) creature:addCondition(condition) return true end function doTileAddItemEx(pos, uid, flags) local tile = Tile(pos) if not tile then return false end local item = Item(uid) if item then return tile:addItemEx(item, flags) end return false end function isInArray(array, value) return table.contains(array, value) end function doCreateItem(itemid, count, pos) local tile = Tile(pos) if not tile then return false end local item = Game.createItem(itemid, count, pos) if item then return item:getUniqueId() end return false end function doCreateItemEx(itemid, count) local item = Game.createItem(itemid, count) if item then return item:getUniqueId() end return false end function doMoveCreature(cid, direction) local c = Creature(cid) return c ~= nil and c:move(direction) end function doSetCreatureLight(cid, lightLevel, lightColor, time) local creature = Creature(cid) if not creature then return false end local condition = Condition(CONDITION_LIGHT) condition:setParameter(CONDITION_PARAM_LIGHT_LEVEL, lightLevel) condition:setParameter(CONDITION_PARAM_LIGHT_COLOR, lightColor) condition:setTicks(time) creature:addCondition(condition) return true end
412
0.852462
1
0.852462
game-dev
MEDIA
0.84714
game-dev
0.895422
1
0.895422
opentibiabr/canary
1,145
data-otservbr-global/scripts/game_migrations/20241708000535_move_achievement_to_kv.lua
local achievementProgressStorage = 20000 local achievementStorage = 30000 local function migrateAchievementProgress(player) for id, achievement in pairs(ACHIEVEMENTS) do local oldStorageKey = achievementProgressStorage + id local progressNumber = player:getStorageValue(oldStorageKey) if progressNumber > 0 then local achievScopeName = tostring(achievement.name .. "-progress") player:kv():scoped(achievScopeName, progressNumber) player:setStorageValue(oldStorageKey, -1) end local oldAchievement = player:getStorageValue(achievementStorage + id) if oldAchievement > 0 then player:addAchievement(achievement.name) player:setStorageValue(achievementStorage + id, -1) end end local points = 0 local list = player:getAchievements() if #list > 0 then for i = 1, #list do local a = Game.getAchievementInfoById(list[i]) if a.points > 0 then points = points + a.points end end end player:addAchievementPoints(points) end local migration = Migration("20241708000535_move_achievement_to_kv") function migration:onExecute() self:forEachPlayer(migrateAchievementProgress) end migration:register()
412
0.526388
1
0.526388
game-dev
MEDIA
0.823045
game-dev
0.891042
1
0.891042
daid/EmptyEpsilon
4,280
scripts/ee.lua
--- Elementary Lua additions to EE. -- -- (It might be a good idea to let EE provide some of these values.) -- -- **Planned additions** -- -- - Constants for crew positions. -- -- **Changelog** -- -- *Version 0.7* (2020.08) -- -- - Add constants for the scanned states and the array `SCANNED_STATES`. -- -- *Version 0.6* (2020.05) -- -- - Add the constant `MAX_PLAYER_SHIPS`. -- - Add constants for the missile types and the array `MISSILE_TYPES`. -- - Add constants for the alert levels and the array `ALERT_LEVELS`. -- -- *Version 0.5* (2020.05) -- -- - Add the constants `SYS_REACTOR` etc. and the array `SYSTEMS`. -- -- @usage -- require("ee.lua") -- -- and see below -- -- @module ee -- @author Tom --- Playerships. -- @section playerships --- Maximum number of player spaceships. -- -- @usage -- for index = 1, MAX_PLAYER_SHIPS do -- local pship = getPlayerShip(index) -- if pship then -- -- do something -- print(index, pship:getCallSign()) -- end -- end MAX_PLAYER_SHIPS = 32 --- Missiles. -- -- String constants for the missile types (type `EMissileWeapons` in `script_reference.html`). -- -- @section missile_types --- `"Homing"` MISSILE_HOMING = "Homing" --- `"Nuke"` MISSILE_NUKE = "Nuke" --- `"Mine"` MISSILE_MINE = "Mine" --- `"EMP"` MISSILE_EMP = "EMP" --- `"HVLI"` MISSILE_HVLI = "HVLI" --- Array of the missile types. MISSILE_TYPES = { MISSILE_HOMING, MISSILE_NUKE, MISSILE_MINE, MISSILE_EMP, MISSILE_HVLI } --- Systems. -- -- String constants for the systems (type `ESystem` in `script_reference.html`). -- They can be used as argument in functions concerning Engineering. -- -- The values are taken from `shipTemplate.hpp`. -- -- @section systems --- `"reactor"` SYS_REACTOR = "reactor" --- `"beamweapons"` SYS_BEAMWEAPONS = "beamweapons" --- `"missilesystem"` SYS_MISSILESYSTEM = "missilesystem" --- `"maneuver"` SYS_MANEUVER = "maneuver" --- `"impulse"` SYS_IMPULSE = "impulse" --- `"warp"` SYS_WARP = "warp" --- `"jumpdrive"` SYS_JUMPDRIVE = "jumpdrive" --- `"frontshield"` SYS_FRONTSHIELD = "frontshield" --- `"rearshield"` SYS_REARSHIELD = "rearshield" --- Array of the system names. -- -- @usage -- local pship = getPlayerShip(-1) -- for idx, system in ipairs(SYSTEMS) do -- pship:setSystemHealth(system, 1.0) -- pship:setSystemHeat(system, 0.0) -- pship:setSystemPower(system, 1.0) -- pship:commandSetSystemPowerRequest(system, 1.0) -- pship:setSystemCoolant(system, 0.0) -- pship:commandSetSystemCoolantRequest(system, 0.0) -- end SYSTEMS = { SYS_REACTOR, SYS_BEAMWEAPONS, SYS_MISSILESYSTEM, SYS_MANEUVER, SYS_IMPULSE, SYS_WARP, SYS_JUMPDRIVE, SYS_FRONTSHIELD, SYS_REARSHIELD } --- Scanned states. -- -- String constants for the scanned states (type `EScannedState` in `script_reference.html`). -- -- See `EScannedState` in `spaceObject.h`. -- -- @section scanned_states --- `"notscanned"` SS_NOT_SCANNED = "notscanned" --- `"friendorfoeidentified"` SS_FRIEND_OR_FOE_IDENTIFIED = "friendorfoeidentified" --- `"simplescan"` SS_SIMPLE_SCAN = "simplescan" --- `"fullscan"` SS_FULL_SCAN = "fullscan" --- Array of the scanned states. SCANNED_STATES = { SS_NOT_SCANNED, SS_FRIEND_OR_FOE_IDENTIFIED, SS_SIMPLE_SCAN, SS_FULL_SCAN } --- Alert Levels. -- -- String constants for the alert levels (type `EAlertLevel` in `script_reference.html`). -- -- See `playerSpaceship.cpp`. -- -- @section alert_levels --- `"Normal"` alert ALERT_NORMAL = "Normal" --- `"YELLOW ALERT"` ALERT_YELLOW = "YELLOW ALERT" --- `"RED ALERT"` ALERT_RED = "RED ALERT" --- Array of the alert levels. ALERT_LEVELS = { ALERT_NORMAL, ALERT_YELLOW, ALERT_RED } --- Scanning Complexity. -- -- String constants for scanning complexity (type `EScanningComplexity` in `script_reference.html`). -- -- See `gameGlobalInfo.h`. SC_NONE = "none" SC_SIMPLE = "simple" SC_NORMAL = "normal" SC_ADVANCED = "advanced" --- Array of the scan complexities. SCANNING_COMPLEXITIES = { SC_NONE, SC_SIMPLE, SC_NORMAL, SC_ADVANCED } --- Hacking Games. -- -- String constants for hacking games (type `EHackingGames` in `script_reference.html`). -- -- See `gameGlobalInfo.h`. HG_Mine = "mines" HG_Lights = "lights" HG_All = "all" --- Array of the scan complexities. HACKING_GAMES = { HG_Mine, HG_Lights, HG_All, }
412
0.658495
1
0.658495
game-dev
MEDIA
0.926151
game-dev
0.809341
1
0.809341
Arakne/Araknemu
5,988
src/test/java/fr/quatrevieux/araknemu/game/chat/ChatServiceTest.java
/* * This file is part of Araknemu. * * Araknemu is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Araknemu 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 Araknemu. If not, see <https://www.gnu.org/licenses/>. * * Copyright (c) 2017-2019 Vincent Quatrevieux */ package fr.quatrevieux.araknemu.game.chat; import fr.quatrevieux.araknemu.core.di.ContainerException; import fr.quatrevieux.araknemu.core.event.DefaultListenerAggregate; import fr.quatrevieux.araknemu.core.event.ListenerAggregate; import fr.quatrevieux.araknemu.game.GameBaseCase; import fr.quatrevieux.araknemu.game.GameConfiguration; import fr.quatrevieux.araknemu.game.chat.channel.Channel; import fr.quatrevieux.araknemu.game.chat.channel.GlobalChannel; import fr.quatrevieux.araknemu.game.chat.channel.MapChannel; import fr.quatrevieux.araknemu.game.listener.player.chat.AddChatChannels; import fr.quatrevieux.araknemu.game.listener.player.chat.InitializeChat; import fr.quatrevieux.araknemu.game.listener.player.chat.MessageReceived; import fr.quatrevieux.araknemu.game.listener.player.chat.PrivateMessageReceived; import fr.quatrevieux.araknemu.game.player.PlayerService; import fr.quatrevieux.araknemu.game.player.event.PlayerLoaded; import fr.quatrevieux.araknemu.network.game.in.chat.Message; import fr.quatrevieux.araknemu.network.game.out.chat.MessageSent; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.sql.SQLException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class ChatServiceTest extends GameBaseCase { private ChatService service; @Override @BeforeEach public void setUp() throws Exception { super.setUp(); service = new ChatService( container.get(GameConfiguration.class).chat(), new Channel[] { new MapChannel(), new GlobalChannel(ChannelType.TRADE, container.get(PlayerService.class)) } ); } @Test void listeners() { ListenerAggregate dispatcher = new DefaultListenerAggregate(); dispatcher.register(service); assertTrue(dispatcher.has(AddChatChannels.class)); } @Test void playerLoadListener() throws SQLException, ContainerException { ListenerAggregate dispatcher = new DefaultListenerAggregate(); dispatcher.register(service); dispatcher.dispatch(new PlayerLoaded(gamePlayer())); assertTrue(gamePlayer().dispatcher().has(InitializeChat.class)); assertTrue(gamePlayer().dispatcher().has(MessageReceived.class)); assertTrue(gamePlayer().dispatcher().has(PrivateMessageReceived.class)); } @Test void sendMapChat() throws SQLException, ContainerException, ChatException { explorationPlayer(); gamePlayer().dispatcher().add(new MessageReceived( gamePlayer() )); service.send( gamePlayer(), new Message(ChannelType.MESSAGES, "", "My message", "") ); requestStack.assertLast( new MessageSent( gamePlayer(), ChannelType.MESSAGES, "My message", "" ) ); } @Test void sendChannelNotEnabled() throws SQLException, ContainerException, ChatException { explorationPlayer(); gamePlayer().dispatcher().add(new MessageReceived( gamePlayer() )); gamePlayer().subscriptions().remove(ChannelType.MESSAGES); requestStack.clear(); try { service.send( gamePlayer(), new Message(ChannelType.MESSAGES, "", "My message", "") ); } catch (ChatException e) { assertEquals(ChatException.Error.NOT_SUBSCRIBED, e.error()); } requestStack.assertEmpty(); } @Test void sendSyntaxError() throws SQLException, ContainerException, ChatException { explorationPlayer(); assertThrows(ChatException.class, () -> service.send(gamePlayer(), new Message(ChannelType.MESSAGES, "", "°0", "1234"))); assertThrows(ChatException.class, () -> service.send(gamePlayer(), new Message(ChannelType.MESSAGES, "", "message", "2443!76#12#0#0#0d0+18,7e#1b#0#0#0d0+27"))); assertThrows(ChatException.class, () -> service.send(gamePlayer(), new Message(ChannelType.MESSAGES, "", "°0", "aaa!zzz"))); assertThrows(ChatException.class, () -> service.send(gamePlayer(), new Message(ChannelType.MESSAGES, "", "°0", "123!45#10"))); } @Test void sendUnauthorized() throws SQLException, ContainerException, ChatException { explorationPlayer(); assertThrows(ChatException.class, () -> service.send(gamePlayer(), new Message(ChannelType.ADMIN, "", "°0", "1234"))); } @Test void sendWithItemSuccess() throws SQLException, ContainerException, ChatException { gamePlayer(true).dispatcher().add(new MessageReceived( gamePlayer() )); service.send(gamePlayer(), new Message(ChannelType.TRADE, "", "Hello °0", "2443!76#12#0#0#0d0+18,7e#1b#0#0#0d0+27")); requestStack.assertLast( new MessageSent( gamePlayer(), ChannelType.TRADE, "Hello °0", "2443!76#12#0#0#0d0+18,7e#1b#0#0#0d0+27" ) ); } }
412
0.91869
1
0.91869
game-dev
MEDIA
0.596585
game-dev,testing-qa
0.839218
1
0.839218
GiganticMinecraft/SeichiAssist
2,217
src/main/scala/com/github/unchama/minecraft/bukkit/objects/BukkitBossBar.scala
package com.github.unchama.minecraft.bukkit.objects import cats.effect.Sync import com.github.unchama.generic.ReadWrite import com.github.unchama.minecraft.objects.MinecraftBossBar import org.bukkit.Bukkit import org.bukkit.boss.{BarColor, BarFlag, BarStyle, BossBar} class BukkitBossBar[F[_]] private (instance: BossBar)(implicit F: Sync[F]) extends MinecraftBossBar[F] { override type Player = org.bukkit.entity.Player override type Style = BarStyle override type Color = BarColor override type Flag = BarFlag override val title: ReadWrite[F, String] = ReadWrite.liftUnsafe(instance.getTitle, instance.setTitle) override val color: ReadWrite[F, BarColor] = ReadWrite.liftUnsafe(instance.getColor, instance.setColor) override val style: ReadWrite[F, BarStyle] = ReadWrite.liftUnsafe(instance.getStyle, instance.setStyle) override val progress: ReadWrite[F, Double] = ReadWrite.liftUnsafe(instance.getProgress, instance.setProgress) override val visibility: ReadWrite[F, Boolean] = ReadWrite.liftUnsafe(instance.isVisible, instance.setVisible) override val flags: FlagOperations = new FlagOperations { override def add(flag: BarFlag): F[Unit] = F.delay(instance.addFlag(flag)) override def remove(flag: BarFlag): F[Unit] = F.delay(instance.removeFlag(flag)) override def has(flag: BarFlag): F[Unit] = F.delay(instance.hasFlag(flag)) } override val players: PlayerOperations = new PlayerOperations { override val removeAll: F[Unit] = F.delay(instance.removeAll()) override def add(player: Player): F[Unit] = F.delay(instance.addPlayer(player)) override def remove(player: Player): F[Unit] = F.delay(instance.removePlayer(player)) import scala.jdk.CollectionConverters._ override def getAll: F[List[Player]] = F.delay(instance.getPlayers.asScala.toList) } } object BukkitBossBar { def apply[F[_]: Sync](title: String, color: BarColor, style: BarStyle): F[BukkitBossBar[F]] = in[F, F](title, color, style) def in[G[_]: Sync, F[_]: Sync]( title: String, color: BarColor, style: BarStyle ): G[BukkitBossBar[F]] = Sync[G].delay(new BukkitBossBar(Bukkit.getServer.createBossBar(title, color, style))) }
412
0.852075
1
0.852075
game-dev
MEDIA
0.963101
game-dev
0.926116
1
0.926116
erica/iphone-3.0-cookbook-
2,827
C14-Device/09-Accel Shakes/AccelerometerHelper.m
#import "AccelerometerHelper.h" #define UNDEFINED_VALUE 999.99f #define SIGN(x) ((x < 0.0f) ? -1.0f : 1.0f) @implementation AccelerometerHelper @synthesize sensitivity; @synthesize lockout; @synthesize triggerTime; @synthesize delegate; static AccelerometerHelper *sharedInstance = nil; +(AccelerometerHelper *) sharedInstance { if(!sharedInstance) sharedInstance = [[self alloc] init]; return sharedInstance; } - (id) init { if (!(self = [super init])) return self; self.triggerTime = [NSDate date]; cx = UNDEFINED_VALUE; cy = UNDEFINED_VALUE; cz = UNDEFINED_VALUE; lx = UNDEFINED_VALUE; ly = UNDEFINED_VALUE; lz = UNDEFINED_VALUE; px = UNDEFINED_VALUE; py = UNDEFINED_VALUE; pz = UNDEFINED_VALUE; self.sensitivity = 0.5f; self.lockout = 0.5f; // Start the accelerometer going [[UIAccelerometer sharedAccelerometer] setDelegate:self]; return self; } - (void) setX: (float) aValue { px = lx; lx = cx; cx = aValue; } - (void) setY: (float) aValue { py = ly; ly = cy; cy = aValue; } - (void) setZ: (float) aValue { pz = lz; lz = cz; cz = aValue; } - (float) dAngle { if (cx == UNDEFINED_VALUE) return UNDEFINED_VALUE; if (lx == UNDEFINED_VALUE) return UNDEFINED_VALUE; if (px == UNDEFINED_VALUE) return UNDEFINED_VALUE; // Calculate the dot product of the first pair float dot1 = cx * lx + cy * ly + cz * lz; float a = ABS(sqrt(cx * cx + cy * cy + cz * cz)); float b = ABS(sqrt(lx * lx + ly * ly + lz * lz)); dot1 /= (a * b); // Calculate the dot product of the second pair float dot2 = lx * px + ly * py + lz * pz; a = ABS(sqrt(px * px + py * py + pz * pz)); dot2 /= a * b; // Return the difference between the vector angles return acos(dot2) - acos(dot1); } - (BOOL) checkTrigger { if (lx == UNDEFINED_VALUE) return NO; // Check to see if the new data can be triggered if ([[NSDate date] timeIntervalSinceDate:self.triggerTime] < self.lockout) return NO; // Get the current angular change float change = [self dAngle]; // If we have not yet gathered two samples, return NO if (change == UNDEFINED_VALUE) return NO; // Check to see if the dot product falls below the trigger sensitivity if (change > self.sensitivity) { self.triggerTime = [NSDate date]; return YES; } else return NO; } - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { [self setX:-[acceleration x]]; [self setY:[acceleration y]]; [self setZ:[acceleration z]]; // All accelerometer events if (self.delegate && [self.delegate respondsToSelector:@selector(ping)]) [self.delegate performSelector:@selector(ping)]; // All shake events if ([self checkTrigger] && self.delegate && [self.delegate respondsToSelector:@selector(shake)]) { [self.delegate performSelector:@selector(shake)]; } } @end
412
0.878827
1
0.878827
game-dev
MEDIA
0.876108
game-dev
0.901312
1
0.901312
Reinisch/Darkest-Dungeon-Unity
1,579
Assets/Photon Unity Networking/Demos/DemoHub/ToHubButton.cs
using UnityEngine; using UnityEngine.SceneManagement; public class ToHubButton : MonoBehaviour { public Texture2D ButtonTexture; private Rect ButtonRect; private static ToHubButton instance; public static ToHubButton Instance { get { if (instance == null) { instance = FindObjectOfType(typeof (ToHubButton)) as ToHubButton; } return instance; } } public void Awake() { if (Instance != null && Instance != this) { Destroy(gameObject); } } // Use this for initialization public void Start() { if (this.ButtonTexture == null) { gameObject.SetActive(false); return; } DontDestroyOnLoad(gameObject); } public void OnGUI() { bool sceneZeroLoaded = false; #if UNITY_5 && !UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2 || UNITY_5_4_OR_NEWER sceneZeroLoaded = SceneManager.GetActiveScene().buildIndex == 0; #else sceneZeroLoaded = Application.loadedLevel == 0; #endif if (!sceneZeroLoaded) { int w = this.ButtonTexture.width + 4; int h = this.ButtonTexture.height + 4; this.ButtonRect = new Rect(Screen.width - w, Screen.height - h, w, h); if (GUI.Button(this.ButtonRect, this.ButtonTexture, GUIStyle.none)) { PhotonNetwork.Disconnect(); SceneManager.LoadScene(0); } } } }
412
0.854443
1
0.854443
game-dev
MEDIA
0.975835
game-dev
0.932832
1
0.932832
Twin1dev/MagmaGS-11.31
1,072
FortMP/SDK/S_TRV_Water_Shallow_1x4_functions.cpp
#pragma once // Dumped with Dumper-7! #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------------------------------------------------- // FUNCTIONS //--------------------------------------------------------------------------------------------------------------------- // BlueprintGeneratedClass S_TRV_Water_Shallow_1x4.S_TRV_Water_Shallow_1x4_C // (Actor) class UClass* AS_TRV_Water_Shallow_1x4_C::StaticClass() { static class UClass* Clss = nullptr; if (!Clss) Clss = UObject::FindClassFast("S_TRV_Water_Shallow_1x4_C"); return Clss; } // S_TRV_Water_Shallow_1x4_C S_TRV_Water_Shallow_1x4.Default__S_TRV_Water_Shallow_1x4_C // (Public, ClassDefaultObject, ArchetypeObject, WasLoaded, LoadCompleted) class AS_TRV_Water_Shallow_1x4_C* AS_TRV_Water_Shallow_1x4_C::GetDefaultObj() { static class AS_TRV_Water_Shallow_1x4_C* Default = nullptr; if (!Default) Default = static_cast<AS_TRV_Water_Shallow_1x4_C*>(AS_TRV_Water_Shallow_1x4_C::StaticClass()->DefaultObject); return Default; } }
412
0.620711
1
0.620711
game-dev
MEDIA
0.29287
game-dev
0.750686
1
0.750686
Team-RTG/Realistic-Terrain-Generation
2,982
src/main/java/rtg/world/biome/realistic/thaumcraft/RealisticBiomeTCMagicalForest.java
package rtg.world.biome.realistic.thaumcraft; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.ChunkPrimer; import rtg.api.config.BiomeConfig; import rtg.api.world.RTGWorld; import rtg.api.world.surface.SurfaceBase; import rtg.api.world.terrain.TerrainBase; import rtg.api.world.biome.RealisticBiomeBase; public class RealisticBiomeTCMagicalForest extends RealisticBiomeBase { public RealisticBiomeTCMagicalForest(Biome biome) { super(biome); } @Override public void initConfig() { } @Override public TerrainBase initTerrain() { return new TerrainTCMagicalForest(); } public static final class TerrainTCMagicalForest extends TerrainBase { private TerrainTCMagicalForest() { } @Override public float generateNoise(RTGWorld rtgWorld, int x, int y, float border, float river) { return terrainForest(x, y, rtgWorld, river, 70f); } } @Override public SurfaceBase initSurface() { return new SurfaceTCMagicalForest(getConfig(), baseBiome().topBlock, baseBiome().fillerBlock); } public static final class SurfaceTCMagicalForest extends SurfaceBase { private SurfaceTCMagicalForest(BiomeConfig config, IBlockState top, IBlockState filler) { super(config, top, filler); } @Override public void paintTerrain(ChunkPrimer primer, int i, int j, int x, int z, int depth, RTGWorld rtgWorld, float[] noise, float river, Biome[] base) { IBlockState bs; for (int y = 255; y >= 0; y--) { bs = primer.getBlockState(x, y, z); if (bs == Blocks.AIR.getDefaultState()) { depth = -1; } else if (bs == Blocks.STONE.getDefaultState()) { depth++; if (TerrainBase.calcCliff(x, z, noise, river) > 1.4f) { if (depth > -1 && depth < 2) { if (rtgWorld.rand().nextInt(3) == 0) { primer.setBlockState(x, y, z, this.hcCobble()); } else { primer.setBlockState(x, y, z, this.hcStone()); } } else if (depth < 10) { primer.setBlockState(x, y, z, this.hcStone()); } } else { if (depth == 0 && y > 61) { primer.setBlockState(x, y, z, this.topBlock); } else if (depth < 4) { primer.setBlockState(x, y, z, this.fillerBlock); } } } } } } @Override public void initDecos() { } }
412
0.890546
1
0.890546
game-dev
MEDIA
0.944088
game-dev
0.907411
1
0.907411
oot-pc-port/oot-pc-port
1,466
asm/non_matchings/overlays/actors/ovl_En_Nb/func_80AB16FC.s
glabel func_80AB16FC /* 0096C 80AB16FC 27BDFFE8 */ addiu $sp, $sp, 0xFFE8 ## $sp = FFFFFFE8 /* 00970 80AB1700 AFBF0014 */ sw $ra, 0x0014($sp) /* 00974 80AB1704 90AE1D6C */ lbu $t6, 0x1D6C($a1) ## 00001D6C /* 00978 80AB1708 51C0000D */ beql $t6, $zero, .L80AB1740 /* 0097C 80AB170C 8FBF0014 */ lw $ra, 0x0014($sp) /* 00980 80AB1710 8CA21D90 */ lw $v0, 0x1D90($a1) ## 00001D90 /* 00984 80AB1714 5040000A */ beql $v0, $zero, .L80AB1740 /* 00988 80AB1718 8FBF0014 */ lw $ra, 0x0014($sp) /* 0098C 80AB171C 944F0000 */ lhu $t7, 0x0000($v0) ## 00000000 /* 00990 80AB1720 24030002 */ addiu $v1, $zero, 0x0002 ## $v1 = 00000002 /* 00994 80AB1724 24180001 */ addiu $t8, $zero, 0x0001 ## $t8 = 00000001 /* 00998 80AB1728 546F0005 */ bnel $v1, $t7, .L80AB1740 /* 0099C 80AB172C 8FBF0014 */ lw $ra, 0x0014($sp) /* 009A0 80AB1730 AC830278 */ sw $v1, 0x0278($a0) ## 00000278 /* 009A4 80AB1734 0C2AC55E */ jal func_80AB1578 /* 009A8 80AB1738 AC98027C */ sw $t8, 0x027C($a0) ## 0000027C /* 009AC 80AB173C 8FBF0014 */ lw $ra, 0x0014($sp) .L80AB1740: /* 009B0 80AB1740 27BD0018 */ addiu $sp, $sp, 0x0018 ## $sp = 00000000 /* 009B4 80AB1744 03E00008 */ jr $ra /* 009B8 80AB1748 00000000 */ nop
412
0.636746
1
0.636746
game-dev
MEDIA
0.964053
game-dev
0.65989
1
0.65989
cubk1/vapev3-opensource
1,942
gg/vape/module/other/AntiAFK.java
package gg.vape.module.other; import gg.vape.event.impl.EventPlayerTick; import gg.vape.mapping.MappedClasses; import gg.vape.module.Category; import gg.vape.module.Mod; import gg.vape.utils.TimerUtil; import gg.vape.value.NumberValue; import gg.vape.wrapper.impl.GameSettings; import gg.vape.wrapper.impl.KeyBinding; import gg.vape.wrapper.impl.Minecraft; import java.util.Random; public class AntiAFK extends Mod { public final TimerUtil c5891 = new TimerUtil(); public final TimerUtil c6297 = new TimerUtil(); public final KeyBinding[] c5924; public KeyBinding c3915; public final Random c1438 = new Random(); public final NumberValue c7118 = NumberValue.c8404(this, "Frequency", "##", "", 1.0, 30.0, 200.0, "How often you will move"); public AntiAFK() { super("Anti-AFK", 9782004, Category.Other); GameSettings var1 = Minecraft.gameSettings(); this.c5924 = new KeyBinding[]{var1.c4590(), var1.c1091(), var1.c2387(), var1.c4599()}; this.addValue(this.c7118); } public void onTick(EventPlayerTick event) { if (!Minecraft.currentScreen().isInstance(MappedClasses.GuiInventory)) { if (this.c3915 == null) { if (Minecraft.thePlayer().moveForward() != 0.0F || Minecraft.thePlayer().moveStrafe() != 0.0F) { return; } if (this.c5891.hasTimeElapsed(this.c7118.getValue().longValue() * 1000L + (long)this.c1438.nextInt(4000))) { this.c3915 = this.c5924[this.c1438.nextInt(this.c5924.length)]; KeyBinding.setKeyBindState(this.c3915.getKeyCode(), true); KeyBinding.onTick(this.c3915.getKeyCode()); this.c6297.reset(); } } else if (this.c6297.hasTimeElapsed(this.c1438.nextInt(50))) { KeyBinding.setKeyBindState(this.c3915.getKeyCode(), false); this.c3915 = null; this.c5891.reset(); } } } }
412
0.734741
1
0.734741
game-dev
MEDIA
0.727837
game-dev
0.536217
1
0.536217
dogballs/cattle-bity
1,059
src/gameObjects/menu/MenuCursor.ts
import { Animation, GameObject, SpriteAlignment, SpritePainter, } from '../../core'; import { GameUpdateArgs, Rotation } from '../../game'; import { TankAnimationFrame, TankColor, TankType, TankMoveAnimation, } from '../../tank'; export class MenuCursor extends GameObject { public readonly painter = new SpritePainter(); private animation: Animation<TankAnimationFrame>; constructor() { super(60, 60); this.painter.alignment = SpriteAlignment.MiddleCenter; } protected setup({ spriteLoader }: GameUpdateArgs): void { this.animation = new TankMoveAnimation( spriteLoader, TankType.PlayerA(), [TankColor.Primary], Rotation.Right, ); this.updateSprite(); } protected update(updateArgs: GameUpdateArgs): void { this.animation.update(updateArgs.deltaTime); this.updateSprite(); this.setNeedsPaint(); } private updateSprite(): void { const frame = this.animation.getCurrentFrame(); const sprite = frame.getSprite(0); this.painter.sprite = sprite; } }
412
0.613908
1
0.613908
game-dev
MEDIA
0.977682
game-dev
0.933228
1
0.933228
4RTools/4RTools
1,966
Forms/StuffAutoBuffForm.cs
using System.Windows.Forms; using System.Windows.Input; using System.Collections.Generic; using _4RTools.Utils; using _4RTools.Model; using static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace _4RTools.Forms { public partial class StuffAutoBuffForm : Form, IObserver { private List<BuffContainer> stuffContainers = new List<BuffContainer>(); public StuffAutoBuffForm(Subject subject) { InitializeComponent(); stuffContainers.Add(new BuffContainer(this.PotionsGP, Buff.GetPotionsBuffs())); stuffContainers.Add(new BuffContainer(this.ElementalsGP, Buff.GetElementalsBuffs())); stuffContainers.Add(new BuffContainer(this.BoxesGP, Buff.GetBoxesBuffs())); stuffContainers.Add(new BuffContainer(this.FoodsGP, Buff.GetFoodBuffs())); stuffContainers.Add(new BuffContainer(this.ScrollBuffsGP, Buff.GetScrollBuffs())); stuffContainers.Add(new BuffContainer(this.EtcGP, Buff.GetETCBuffs())); stuffContainers.Add(new BuffContainer(this.CandiesGP, Buff.GetCandiesBuffs())); stuffContainers.Add(new BuffContainer(this.ExpGP, Buff.GetEXPBuffs())); new BuffRenderer("Autobuff", stuffContainers, toolTip1).doRender(); subject.Attach(this); } public void Update(ISubject subject) { switch ((subject as Subject).Message.code) { case MessageCode.PROFILE_CHANGED: BuffRenderer.doUpdate(new Dictionary<EffectStatusIDs, Key>(ProfileSingleton.GetCurrent().Autobuff.buffMapping), this); break; case MessageCode.TURN_OFF: ProfileSingleton.GetCurrent().Autobuff.Stop(); break; case MessageCode.TURN_ON: ProfileSingleton.GetCurrent().Autobuff.Start(); break; } } } }
412
0.71946
1
0.71946
game-dev
MEDIA
0.650581
game-dev
0.952911
1
0.952911
PCGen/pcgen
1,991
data/35e/paizo/adventure_path/rise_of_the_runelords/chapter_2_the_skinsaw_murders/pf2_classes_prestige.lst
# CVS $Revision$ $Author$ -- Fri Jan 1 12:57:05 2016 -- reformated by PCGen PrettyLST v6.06.00 SOURCELONG:Rise of the Runelords - Chapter 2: The Skinsaw Murders SOURCESHORT:PF2 SOURCEWEB:http://paizo.com/pathfinder/v5748btpy8029 SOURCEDATE:2007-10 # Original Entry by: Stefan Radermacher # Class Name Hit Dice Type Max Level Source Page Combat bonus Save bonus Modify VAR FACT CLASS:Spherewalker HD:8 TYPE:PC.Prestige MAXLEVEL:5 SOURCEPAGE:p.73 BONUS:COMBAT|BASEAB|classlevel("APPLIEDAS=NONEPIC")*3/4|TYPE=Base.REPLACE|PREVAREQ:UseFractionalBAB,0 BONUS:SAVE|BASE.Will|classlevel("APPLIEDAS=NONEPIC")/3 BONUS:SAVE|BASE.Fortitude,BASE.Reflex|classlevel("APPLIEDAS=NONEPIC")/2+2 BONUS:VAR|ClassBABModerate|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalBAB,1 FACT:ClassType|Prestige FACT:Abb|Sph # Class Name Required Ability Required Deity Required Skill PRETOTALAB Req. Weapond Prof. CLASS:Spherewalker PREABILITY:1,CATEGORY=FEAT,Great Fortitude,Iron Will,Lightning Reflexes PREABILITY:1,CATEGORY=FEAT,Acrobatic,Agile,Athletic,Endurance,Run,Self-Sufficient PREDEITY:1,Desna PRESKILL:2,Climb=5,Knowledge (Geography)=5,Knowledge (Nature)=5,Knowledge (Religion)=5,TYPE.Perform=5,Ride=5,Survival=5,Swim=5 PRETOTALAB:5 PREWEAPONPROF:1,Starknife # Class Name Skill Pts/Lvl Class Skill CLASS:Spherewalker STARTSKILLPTS:4 CSKILL:Balance|Climb|Concentration|Escape Artist|Handle Animal|Heal|Jump|Knowledge (geography)|TYPE=Perform|Ride|Spot|Survival|Swim|Tumble 1 ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Landmark|Longstrider 2 ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Efficient Sleep|Star Slinger 3 ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Dream Link 4 BONUS:VAR|DivineLuckLVL|CL ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Divine Luck 5 BONUS:VAR|SwarmFormLVL|CL ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Swarm Form
412
0.761402
1
0.761402
game-dev
MEDIA
0.968055
game-dev
0.970233
1
0.970233
ArchipelagoMW/Archipelago
20,103
Main.py
import collections from collections.abc import Mapping import concurrent.futures import logging import os import tempfile import time from typing import Any import zipfile import zlib import worlds from BaseClasses import CollectionState, Item, Location, LocationProgressType, MultiWorld from Fill import FillError, balance_multiworld_progression, distribute_items_restrictive, flood_items, \ parse_planned_blocks, distribute_planned_blocks, resolve_early_locations_for_planned from NetUtils import convert_to_base_types from Options import StartInventoryPool from Utils import __version__, output_path, restricted_dumps, version_tuple from settings import get_settings from worlds import AutoWorld from worlds.generic.Rules import exclusion_rules, locality_rules __all__ = ["main"] def main(args, seed=None, baked_server_options: dict[str, object] | None = None): if not baked_server_options: baked_server_options = get_settings().server_options.as_dict() assert isinstance(baked_server_options, dict) if args.outputpath: os.makedirs(args.outputpath, exist_ok=True) output_path.cached_path = args.outputpath start = time.perf_counter() # initialize the multiworld multiworld = MultiWorld(args.multi) logger = logging.getLogger() multiworld.set_seed(seed, args.race, str(args.outputname) if args.outputname else None) multiworld.plando_options = args.plando multiworld.game = args.game.copy() multiworld.player_name = args.name.copy() multiworld.sprite = args.sprite.copy() multiworld.sprite_pool = args.sprite_pool.copy() multiworld.set_options(args) if args.csv_output: from Options import dump_player_options dump_player_options(multiworld) multiworld.set_item_links() multiworld.state = CollectionState(multiworld) logger.info('Archipelago Version %s - Seed: %s\n', __version__, multiworld.seed) logger.info(f"Found {len(AutoWorld.AutoWorldRegister.world_types)} World Types:") longest_name = max(len(text) for text in AutoWorld.AutoWorldRegister.world_types) world_classes = AutoWorld.AutoWorldRegister.world_types.values() version_count = max(len(cls.world_version.as_simple_string()) for cls in world_classes) item_count = len(str(max(len(cls.item_names) for cls in world_classes))) location_count = len(str(max(len(cls.location_names) for cls in world_classes))) for name, cls in AutoWorld.AutoWorldRegister.world_types.items(): if not cls.hidden and len(cls.item_names) > 0: logger.info(f" {name:{longest_name}}: " f"v{cls.world_version.as_simple_string():{version_count}} | " f"Items: {len(cls.item_names):{item_count}} | " f"Locations: {len(cls.location_names):{location_count}}") del item_count, location_count # This assertion method should not be necessary to run if we are not outputting any multidata. if not args.skip_output and not args.spoiler_only: AutoWorld.call_stage(multiworld, "assert_generate") AutoWorld.call_all(multiworld, "generate_early") logger.info('') for player in multiworld.player_ids: for item_name, count in multiworld.worlds[player].options.start_inventory.value.items(): for _ in range(count): multiworld.push_precollected(multiworld.create_item(item_name, player)) for item_name, count in getattr(multiworld.worlds[player].options, "start_inventory_from_pool", StartInventoryPool({})).value.items(): for _ in range(count): multiworld.push_precollected(multiworld.create_item(item_name, player)) # remove from_pool items also from early items handling, as starting is plenty early. early = multiworld.early_items[player].get(item_name, 0) if early: multiworld.early_items[player][item_name] = max(0, early-count) remaining_count = count-early if remaining_count > 0: local_early = multiworld.local_early_items[player].get(item_name, 0) if local_early: multiworld.early_items[player][item_name] = max(0, local_early - remaining_count) del local_early del early # items can't be both local and non-local, prefer local multiworld.worlds[player].options.non_local_items.value -= multiworld.worlds[player].options.local_items.value multiworld.worlds[player].options.non_local_items.value -= set(multiworld.local_early_items[player]) # Clear non-applicable local and non-local items. if multiworld.players == 1: multiworld.worlds[1].options.non_local_items.value = set() multiworld.worlds[1].options.local_items.value = set() logger.info('Creating MultiWorld.') AutoWorld.call_all(multiworld, "create_regions") logger.info('Creating Items.') AutoWorld.call_all(multiworld, "create_items") logger.info('Calculating Access Rules.') AutoWorld.call_all(multiworld, "set_rules") for player in multiworld.player_ids: exclusion_rules(multiworld, player, multiworld.worlds[player].options.exclude_locations.value) multiworld.worlds[player].options.priority_locations.value -= multiworld.worlds[player].options.exclude_locations.value world_excluded_locations = set() for location_name in multiworld.worlds[player].options.priority_locations.value: try: location = multiworld.get_location(location_name, player) except KeyError: continue if location.progress_type != LocationProgressType.EXCLUDED: location.progress_type = LocationProgressType.PRIORITY else: logger.warning(f"Unable to prioritize location \"{location_name}\" in player {player}'s world because the world excluded it.") world_excluded_locations.add(location_name) multiworld.worlds[player].options.priority_locations.value -= world_excluded_locations # Set local and non-local item rules. # This function is called so late because worlds might otherwise overwrite item_rules which are how locality works if multiworld.players > 1: locality_rules(multiworld) multiworld.plando_item_blocks = parse_planned_blocks(multiworld) AutoWorld.call_all(multiworld, "connect_entrances") AutoWorld.call_all(multiworld, "generate_basic") # remove starting inventory from pool items. # Because some worlds don't actually create items during create_items this has to be as late as possible. fallback_inventory = StartInventoryPool({}) depletion_pool: dict[int, dict[str, int]] = { player: getattr(multiworld.worlds[player].options, "start_inventory_from_pool", fallback_inventory).value.copy() for player in multiworld.player_ids } target_per_player = { player: sum(target_items.values()) for player, target_items in depletion_pool.items() if target_items } if target_per_player: new_itempool: list[Item] = [] # Make new itempool with start_inventory_from_pool items removed for item in multiworld.itempool: if depletion_pool[item.player].get(item.name, 0): depletion_pool[item.player][item.name] -= 1 else: new_itempool.append(item) # Create filler in place of the removed items, warn if any items couldn't be found in the multiworld itempool for player, target in target_per_player.items(): unfound_items = {item: count for item, count in depletion_pool[player].items() if count} if unfound_items: player_name = multiworld.get_player_name(player) logger.warning(f"{player_name} tried to remove items from their pool that don't exist: {unfound_items}") needed_items = target_per_player[player] - sum(unfound_items.values()) new_itempool += [multiworld.worlds[player].create_filler() for _ in range(needed_items)] assert len(multiworld.itempool) == len(new_itempool), "Item Pool amounts should not change." multiworld.itempool[:] = new_itempool multiworld.link_items() if any(world.options.item_links for world in multiworld.worlds.values()): multiworld._all_state = None logger.info("Running Item Plando.") resolve_early_locations_for_planned(multiworld) distribute_planned_blocks(multiworld, [x for player in multiworld.plando_item_blocks for x in multiworld.plando_item_blocks[player]]) logger.info('Running Pre Main Fill.') AutoWorld.call_all(multiworld, "pre_fill") logger.info(f'Filling the multiworld with {len(multiworld.itempool)} items.') if multiworld.algorithm == 'flood': flood_items(multiworld) # different algo, biased towards early game progress items elif multiworld.algorithm == 'balanced': distribute_items_restrictive(multiworld, get_settings().generator.panic_method) AutoWorld.call_all(multiworld, 'post_fill') if multiworld.players > 1 and not args.skip_prog_balancing: balance_multiworld_progression(multiworld) else: logger.info("Progression balancing skipped.") # we're about to output using multithreading, so we're removing the global random state to prevent accidental use multiworld.random.passthrough = False if args.skip_output: logger.info('Done. Skipped output/spoiler generation. Total Time: %s', time.perf_counter() - start) return multiworld logger.info(f'Beginning output...') outfilebase = 'AP_' + multiworld.seed_name if args.spoiler_only: if args.spoiler > 1: logger.info('Calculating playthrough.') multiworld.spoiler.create_playthrough(create_paths=args.spoiler > 2) multiworld.spoiler.to_file(output_path('%s_Spoiler.txt' % outfilebase)) logger.info('Done. Skipped multidata modification. Total time: %s', time.perf_counter() - start) return multiworld output = tempfile.TemporaryDirectory() with output as temp_dir: output_players = [player for player in multiworld.player_ids if AutoWorld.World.generate_output.__code__ is not multiworld.worlds[player].generate_output.__code__] with concurrent.futures.ThreadPoolExecutor(len(output_players) + 2) as pool: check_accessibility_task = pool.submit(multiworld.fulfills_accessibility) output_file_futures = [pool.submit(AutoWorld.call_stage, multiworld, "generate_output", temp_dir)] for player in output_players: # skip starting a thread for methods that say "pass". output_file_futures.append( pool.submit(AutoWorld.call_single, multiworld, "generate_output", player, temp_dir)) # collect ER hint info er_hint_data: dict[int, dict[int, str]] = {} AutoWorld.call_all(multiworld, 'extend_hint_information', er_hint_data) def write_multidata(): import NetUtils from NetUtils import HintStatus slot_data: dict[int, Mapping[str, Any]] = {} client_versions: dict[int, tuple[int, int, int]] = {} games: dict[int, str] = {} minimum_versions: NetUtils.MinimumVersions = { "server": AutoWorld.World.required_server_version, "clients": client_versions } slot_info: dict[int, NetUtils.NetworkSlot] = {} names = [[name for player, name in sorted(multiworld.player_name.items())]] for slot in multiworld.player_ids: player_world: AutoWorld.World = multiworld.worlds[slot] minimum_versions["server"] = max(minimum_versions["server"], player_world.required_server_version) client_versions[slot] = player_world.required_client_version games[slot] = multiworld.game[slot] slot_info[slot] = NetUtils.NetworkSlot(names[0][slot - 1], multiworld.game[slot], multiworld.player_types[slot]) for slot, group in multiworld.groups.items(): games[slot] = multiworld.game[slot] slot_info[slot] = NetUtils.NetworkSlot(group["name"], multiworld.game[slot], multiworld.player_types[slot], group_members=sorted(group["players"])) precollected_items = {player: [item.code for item in world_precollected if type(item.code) == int] for player, world_precollected in multiworld.precollected_items.items()} precollected_hints: dict[int, set[NetUtils.Hint]] = { player: set() for player in range(1, multiworld.players + 1 + len(multiworld.groups)) } for slot in multiworld.player_ids: slot_data[slot] = multiworld.worlds[slot].fill_slot_data() def precollect_hint(location: Location, auto_status: HintStatus): entrance = er_hint_data.get(location.player, {}).get(location.address, "") hint = NetUtils.Hint(location.item.player, location.player, location.address, location.item.code, False, entrance, location.item.flags, auto_status) precollected_hints[location.player].add(hint) if location.item.player not in multiworld.groups: precollected_hints[location.item.player].add(hint) else: for player in multiworld.groups[location.item.player]["players"]: precollected_hints[player].add(hint) locations_data: dict[int, dict[int, tuple[int, int, int]]] = {player: {} for player in multiworld.player_ids} for location in multiworld.get_filled_locations(): if type(location.address) == int: assert location.item.code is not None, "item code None should be event, " \ "location.address should then also be None. Location: " \ f" {location}, Item: {location.item}" assert location.address not in locations_data[location.player], ( f"Locations with duplicate address. {location} and " f"{locations_data[location.player][location.address]}") locations_data[location.player][location.address] = \ location.item.code, location.item.player, location.item.flags auto_status = HintStatus.HINT_AVOID if location.item.trap else HintStatus.HINT_PRIORITY if location.name in multiworld.worlds[location.player].options.start_location_hints: if not location.item.trap: # Unspecified status for location hints, except traps auto_status = HintStatus.HINT_UNSPECIFIED precollect_hint(location, auto_status) elif location.item.name in multiworld.worlds[location.item.player].options.start_hints: precollect_hint(location, auto_status) elif any([location.item.name in multiworld.worlds[player].options.start_hints for player in multiworld.groups.get(location.item.player, {}).get("players", [])]): precollect_hint(location, auto_status) # embedded data package data_package = { game_world.game: worlds.network_data_package["games"][game_world.game] for game_world in multiworld.worlds.values() } data_package["Archipelago"] = worlds.network_data_package["games"]["Archipelago"] checks_in_area: dict[int, dict[str, int | list[int]]] = {} # get spheres -> filter address==None -> skip empty spheres: list[dict[int, set[int]]] = [] for sphere in multiworld.get_sendable_spheres(): current_sphere: dict[int, set[int]] = collections.defaultdict(set) for sphere_location in sphere: current_sphere[sphere_location.player].add(sphere_location.address) if current_sphere: spheres.append(dict(current_sphere)) multidata: NetUtils.MultiData | bytes = { "slot_data": slot_data, "slot_info": slot_info, "connect_names": {name: (0, player) for player, name in multiworld.player_name.items()}, "locations": locations_data, "checks_in_area": checks_in_area, "server_options": baked_server_options, "er_hint_data": er_hint_data, "precollected_items": precollected_items, "precollected_hints": precollected_hints, "version": (version_tuple.major, version_tuple.minor, version_tuple.build), "tags": ["AP"], "minimum_versions": minimum_versions, "seed_name": multiworld.seed_name, "spheres": spheres, "datapackage": data_package, "race_mode": int(multiworld.is_race), } # TODO: change to `"version": version_tuple` after getting better serialization AutoWorld.call_all(multiworld, "modify_multidata", multidata) for key in ("slot_data", "er_hint_data"): multidata[key] = convert_to_base_types(multidata[key]) multidata = zlib.compress(restricted_dumps(multidata), 9) with open(os.path.join(temp_dir, f'{outfilebase}.archipelago'), 'wb') as f: f.write(bytes([3])) # version of format f.write(multidata) output_file_futures.append(pool.submit(write_multidata)) if not check_accessibility_task.result(): if not multiworld.can_beat_game(): raise FillError("Game appears as unbeatable. Aborting.", multiworld=multiworld) else: logger.warning("Location Accessibility requirements not fulfilled.") # retrieve exceptions via .result() if they occurred. for i, future in enumerate(concurrent.futures.as_completed(output_file_futures), start=1): if i % 10 == 0 or i == len(output_file_futures): logger.info(f'Generating output files ({i}/{len(output_file_futures)}).') future.result() if args.spoiler > 1: logger.info('Calculating playthrough.') multiworld.spoiler.create_playthrough(create_paths=args.spoiler > 2) if args.spoiler: multiworld.spoiler.to_file(os.path.join(temp_dir, '%s_Spoiler.txt' % outfilebase)) zipfilename = output_path(f"AP_{multiworld.seed_name}.zip") logger.info(f"Creating final archive at {zipfilename}") with zipfile.ZipFile(zipfilename, mode="w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf: for file in os.scandir(temp_dir): zf.write(file.path, arcname=file.name) logger.info('Done. Enjoy. Total Time: %s', time.perf_counter() - start) return multiworld
412
0.868785
1
0.868785
game-dev
MEDIA
0.76638
game-dev
0.870882
1
0.870882
Slattstudio/BetrayedAllianceBook1
15,731
SRC/rm059.sc
;;; Sierra Script 1.0 - (do not remove this comment) (script# 59) (include sci.sh) (include game.sh) (use controls) (use cycle) (use feature) (use game) (use inv) (use main) (use obj) (use follow) (public rm059 0 ) (local ; Cavern of Madness (Ghost) myEvent ghostAwake = 0 awakening = 0 intro = 0 target = 0 shot = 0 flow1 = 0 flow2 = 0 flow3 = 0 flow4 = 0 tripped = 0 deathAnimation = 0 ) (instance rm059 of Rm (properties picture scriptNumber north 0 east 0 south 0 west 0 ) (method (init) (super init:) (self setScript: RoomScript setRegions: 204) (switch gPreviousRoomNumber (else (gEgo posn: 146 170 loop: 1) ) (73 (gEgo posn: 146 170 loop: 3) ) ) (SetUpEgo) (gEgo init: setPri: 4) (water1 init: hide: setPri: 1 setScript: stream1Script) (water2 init: hide: setPri: 2 setScript: ghost2Script) (water3 init: hide: setPri: 0 setScript: stream2Script) (water4 init: hide: setPri: 1) (water5 init: hide: setPri: 0 setScript: stream3Script) (water6 init: hide: setPri: 2) (water7 init: hide: setPri: 2 setScript: stream4Script) (water8 init: hide: setPri: 0) (ghost init: hide: setPri: 4 cycleSpeed: 2 setScript: ghostScript xStep: 4 yStep: 2 ignoreActors:) (waterButton1 init: setPri: 4) (waterButton2 init: setPri: 4) (waterButton3 init: setPri: 4) (waterButton4 init: setPri: 5 ignoreActors:) (dart init: hide: ignoreActors: xStep: 15 yStep: 15 setPri: 4 ignoreControl: ctlWHITE ) (alterEgo init: ignoreActors: ignoreControl: ctlWHITE hide: setScript: tripScript ) (ghostScript changeState: 1) (ghost2Script changeState: 1) (alterGhost init: hide: ignoreActors:) (skeleton init: ignoreActors:) ) ) (instance RoomScript of Script (properties) (method (changeState mainState &tmp dyingScript) (= state mainState) (switch state (0 (= seconds 2)) (1 (= seconds 2) ) (2 (= intro 1)) (3 (= intro 0)) (4 (gEgo hide:) (alterEgo show: view: 428 loop: 1 cel: 0 posn: (+ (gEgo x?) 14) (- (gEgo y?) 0) ) (ghost hide:) (alterGhost show: posn: (ghost x?) (ghost y?) setCycle: End RoomScript cycleSpeed: 2 ) ) (5 (alterEgo setCycle: End RoomScript cycleSpeed: 2) ) (6 (= cycles 10) (ShakeScreen 1) (gTheSoundFX number: 200 play:) ) (7 (= dyingScript (ScriptID DYING_SCRIPT)) (dyingScript caller: 604 register: {The hatred and sheer malice of this apparition fill every thought in your mind and all you can hear is a voice saying, 'now you're mine forever.'} ) (gGame setScript: dyingScript) ) ) ) (method (handleEvent pEvent &tmp dyingScript) (super handleEvent: pEvent) (if (== (pEvent type?) evMOUSEBUTTON) (if (& (pEvent modifiers?) emRIGHT_BUTTON) (if (and (> (pEvent x?) (ghost nsLeft?)) (< (pEvent x?) (ghost nsRight?)) (> (pEvent y?) (ghost nsTop?)) (< (pEvent y?) (ghost nsBottom?)) ) (PrintOther 59 3) (return) ) (if (and (> (pEvent x?) (skeleton nsLeft?)) (< (pEvent x?) (skeleton nsRight?)) (> (pEvent y?) (skeleton nsTop?)) (< (pEvent y?) (skeleton nsBottom?)) ) (PrintOther 59 13) ) ) (if (not shot) (if (== target 1) (if (> gApple 0) (if (not deathAnimation) (dartScript changeState: 1) ) else (PrintOther 59 0) ) ) (if (== target 2) (if (> gApple 0) (if (not deathAnimation) (dartScript changeState: 3) ) else (PrintOther 59 0) ) ) (if (== target 3) (if (> gApple 0) (if (not deathAnimation) (dartScript changeState: 5) ) else (PrintOther 59 0) ) ) (if (== target 4) (if (> gApple 0) (if (not deathAnimation) (dartScript changeState: 7) ) else (PrintOther 59 0) ) ) ) ) (if (Said 'look>') (if (Said '/ghost') (if ghostAwake (PrintOther 59 3) else (PrintOther 59 4) ) ) (if (Said '/switch,button') (PrintOther 59 5) ) (if (Said '/skeleton,corpse,body') (PrintOther 59 13) ) (if (Said '/floor,floor,path') (PrintOther 59 6) (PrintOther 59 7) ) (if (Said '[/!*]') ; this will handle just "look" by itself (PrintOther 59 8) (if ghostAwake (PrintOther 59 9) ) ) ) (if (Said 'talk,ask/ghost,man') (PrintOther 59 10) ) (if (Said 'attack,fight/ghost,man') (PrintOther 59 11) ) (if (Said 'use,shoot,blow/dart,dartgun,gun,(dart<gun)') (PrintOther 59 12) ) ; (stream1Script:changeState(1)) ; (stream2Script:changeState(1)) ; (stream3Script:changeState(1)) ; (stream4Script:changeState(1)) (if (or (Said 'look,use,read,open/portal,map') (Said 'map')) (Print 0 88) ) (if (or (Said 'listen[/!*]') (Said 'listen/voice')) (PrintWhisper) (if (== gListened 74) (PrintOther 58 75) ) (if (== gListened 75) (= dyingScript (ScriptID DYING_SCRIPT)) (dyingScript caller: 604 register: {Where the voice came from, you cannot say. But you dwelt too deeply on despairing thoughts, driving you to lose your mind and your life.} ) (gGame setScript: dyingScript) ) ) ) (method (doit &tmp dyingScript) (super doit:) (= myEvent (Event new: evNULL)) (if (gEgo has: 8) ; INV_BLOW_DART_GUN (cond ( (and (> (myEvent x?) (waterButton1 nsLeft?)) (< (myEvent x?) (waterButton1 nsRight?)) (> (myEvent y?) (waterButton1 nsTop?)) (< (myEvent y?) (waterButton1 nsBottom?)) ) (SetCursor 994 (HaveMouse)) (= gCurrentCursor 994) (= target 1) (= gNoClick 1) ) ( (and (> (myEvent x?) (waterButton2 nsLeft?)) (< (myEvent x?) (waterButton2 nsRight?)) (> (myEvent y?) (waterButton2 nsTop?)) (< (myEvent y?) (waterButton2 nsBottom?)) ) (SetCursor 994 (HaveMouse)) (= gCurrentCursor 994) (= target 2) (= gNoClick 1) ) ( (and (> (myEvent x?) (waterButton4 nsLeft?)) (< (myEvent x?) (waterButton4 nsRight?)) (> (myEvent y?) (waterButton4 nsTop?)) (< (myEvent y?) (waterButton4 nsBottom?)) ) (SetCursor 994 (HaveMouse)) (= gCurrentCursor 994) (= target 3) (= gNoClick 1) ) ( (and (> (myEvent x?) (waterButton3 nsLeft?)) (< (myEvent x?) (waterButton3 nsRight?)) (> (myEvent y?) (waterButton3 nsTop?)) (< (myEvent y?) (waterButton3 nsBottom?)) ) (SetCursor 994 (HaveMouse)) (= gCurrentCursor 994) (= target 4) (= gNoClick 1) ) (else (= target 0) (SetCursor 999 (HaveMouse)) (= gCurrentCursor 999) (= gNoClick 0) ) ) ) (myEvent dispose:) (if (& (gEgo onControl:) ctlGREY) (if (not ghostAwake) (if (not awakening) (ghost2Script changeState: 6) (= awakening 1) ) ) ) (if (& (gEgo onControl:) ctlSILVER) (gRoom newRoom: 73) ) (if (& (gEgo onControl:) ctlMAROON) (gRoom newRoom: 75) ) (if (& (gEgo onControl:) ctlBLUE) (if gEgoRunning (if (not tripped) (= tripped 1) (tripScript changeState: 1) ) ) ) ; (if(& (send gEgo:onControl()) ctlGREY) ; (if(not(intro)) ; = intro 1 // sends the ghost after you ; ) ; ) (if ghostAwake (cond (flow1 (if (< (ghost y?) 96) (ghost setMotion: MoveTo (gEgo x?) (ghost y?)) else ; horizontal (ghost setMotion: Follow gEgo) ) ) (flow2 (if (< (ghost x?) 96) (ghost setMotion: MoveTo (ghost x?) (gEgo y?)) else (ghost setMotion: Follow gEgo) ) ) (flow3 (if (< (ghost y?) 115) (ghost setMotion: Follow gEgo) else (ghost setMotion: MoveTo (gEgo x?) (ghost y?)) ) ) ((>= (gEgo distanceTo: ghost) 30) (if intro (ghost setMotion: Follow gEgo) else (ghost setMotion: MoveTo (gEgo x?) (ghost y?)) ) ) ) (cond ((>= (gEgo distanceTo: ghost) 20)) ; /(if(intro) ; (ghost:setMotion(Follow gEgo)) ; ) ((not deathAnimation) (RoomScript changeState: 4) (= deathAnimation 1)) ) (if (> (gEgo x?) (ghost x?)) (ghost loop: 1) else (ghost loop: 0) ) ) ) ) ; (if(>=(send gEgo:distanceTo(ghost))30) ; (if(intro) ; (ghost:setMotion(Follow gEgo)) ; ) ; )(else ; //death ; ) (instance stream1Script of Script (properties) (method (changeState newState) (= state newState) (switch state (0) (1 (= flow1 1) (ghost observeControl: $0400) ; LIGHT GREEN (gEgo observeControl: $0400) (water1 show: setCycle: End stream1Script) (gTheSoundFX number: 202 play:) ) (2 (water2 show: setCycle: End stream1Script) ) (3 (= seconds 8) (if (not intro) (= intro 1)) ; Print("Well that wasn't what you expected!") ; Print("The dart passed right through him and hit the switch, unleashing a torrent of water.") ) (4 (ghost ignoreControl: $0400) (gEgo ignoreControl: $0400) (water1 hide:) (water2 hide:) (= flow1 0) ) ) ) ) (instance stream2Script of Script (properties) (method (changeState newState) (= state newState) (switch state (0) (1 (= flow2 1) (water3 show: setCycle: End stream2Script) (ghost observeControl: ctlGREEN) (gEgo observeControl: ctlGREEN) (gTheSoundFX number: 202 play:) ) (2 (water4 show: setCycle: End stream2Script) ) (3 (= seconds 8)) (4 (ghost ignoreControl: ctlGREEN) (gEgo ignoreControl: ctlGREEN) (water3 hide:) (water4 hide:) (= flow2 0) ) ) ) ) (instance stream3Script of Script (properties) (method (changeState newState) (= state newState) (switch state (0) (1 (= flow3 1) (ghost observeControl: ctlTEAL) (gEgo observeControl: ctlTEAL) (water5 show: setCycle: End stream3Script) (gTheSoundFX number: 202 play:) ) (2 (water6 show: setCycle: End stream3Script) ) (3 (= seconds 8)) (4 (water5 hide:) (water6 hide:) (ghost ignoreControl: ctlTEAL) (gEgo ignoreControl: ctlTEAL) (= flow3 0) ) ) ) ) (instance stream4Script of Script (properties) (method (changeState newState) (= state newState) (switch state (0) (1 (= flow4 1) (ghost observeControl: ctlPURPLE) (gEgo observeControl: ctlPURPLE) (water7 show: setCycle: End stream4Script) (gTheSoundFX number: 202 play:) ) (2 (water8 show: setCycle: End stream4Script) ) (3 (= seconds 8)) (4 (water7 hide:) (water8 hide:) (ghost ignoreControl: ctlPURPLE) (gEgo ignoreControl: ctlPURPLE) (= flow4 0) ) ) ) ) (instance ghostScript of Script (properties) (method (changeState newState) (= state newState) (switch state (0) ; floating ghost (1 (= cycles 3) (if ghostAwake (ghost posn: (ghost x?) (+ (ghost y?) 1)) ) ) (2 (= cycles 3) (if ghostAwake (ghost posn: (ghost x?) (- (ghost y?) 1)) ) ) (3 (ghostScript changeState: 1)) ) ) ) (instance ghost2Script of Script (properties) (method (changeState newState) (= state newState) (switch state (0) (1 (= cycles 2) (if ghostAwake (ghost cel: 0) ) ) (2 (= cycles 2) (if ghostAwake (ghost cel: 1) ) ) (3 (= cycles 2) (if ghostAwake (ghost cel: 2) ) ) (4 (= cycles 2) (if ghostAwake (ghost cel: 3) ) ) (5 (ghost2Script changeState: 1) ) ; ghost "awakening (6 (ProgramControl) (SetCursor 997 (HaveMouse)) (= gCurrentCursor 997) (self cycles: 0) (ghost show: view: 428 loop: 5 cel: 0 setCycle: End self cycleSpeed: 3) (gTheMusic number: 59 loop: -1 play:) ) (7 (= cycles 5) (PrintOther 59 1 ) (PrintOther 59 2 ) ) (8 (ghost view: 332) (= ghostAwake 1) (self changeState: 1) (PlayerControl) (SetCursor 999 (HaveMouse)) (= gCurrentCursor 999) ) ) ) ) (instance dartScript of Script (properties) (method (changeState newState) (= state newState) (switch state (0) (1 (dart show: view: 57 posn: (gEgo x?) (- (gEgo y?) 30) setMotion: MoveTo 218 19 dartScript ) (= shot 1) (-- gApple) (gTheSoundFX number: 204 play:) ) (2 (dart hide:) (stream1Script changeState: 1) (= shot 0) ) (3 (dart show: view: 157 posn: (gEgo x?) (- (gEgo y?) 30) setMotion: MoveTo 20 105 dartScript ) (= shot 1) (-- gApple) ) (4 (dart hide:) (stream2Script changeState: 1) (= shot 0) ) (5 (dart show: view: 57 posn: (gEgo x?) (- (gEgo y?) 30) setMotion: MoveTo 185 152 dartScript ) (= shot 1) (-- gApple) ) (6 (dart hide:) (stream3Script changeState: 1) (= shot 0) ) (7 (dart show: view: 157 posn: (gEgo x?) (- (gEgo y?) 30) setMotion: MoveTo 289 84 dartScript ) (= shot 1) (-- gApple) ) (8 (dart hide:) (stream4Script changeState: 1) (= shot 0) ) ) ) ) (instance tripScript of Script (properties) (method (changeState newState) (= state newState) (switch state (1 (ProgramControl) (SetCursor 997 (HaveMouse)) (= gCurrentCursor 997) (gEgo hide:) (alterEgo show: view: 410 loop: 1 cel: 0 posn: (gEgo x?) (gEgo y?) setCycle: End tripScript cycleSpeed: 1 ignoreActors: ) ) (2 (Print {Ouch! The watery flood is too slippery to run on.} ) ) ) ) ) (procedure (PrintOther textRes textResIndex) (Print textRes textResIndex #width 280 #at -1 140) ) (procedure (PrintWhisper) (= gWndColor 9) (= gWndBack 0) (Print 58 gListened #width 280 #at -1 20 #title {A voice within your mind:}) (= gWndColor 0) ; clBLACK (= gWndBack 15) (++ gListened) ) (instance alterEgo of Act (properties y 180 x 27 view 410 loop 1 ) ) (instance dart of Act (properties y 135 x 161 view 57 ; 157 for horizontal ) ) (instance ghost of Act (properties y 60 x 171 view 332 loop 1 ) ) (instance alterGhost of Act (properties y 1 x 1 view 428 loop 4 ) ) (instance skeleton of Prop (properties y 70 x 171 view 411 loop 1 cel 1 ) ) (instance water1 of Prop (properties y 97 x 227 view 69 ) ) (instance water2 of Prop (properties y 97 x 135 view 69 loop 1 ) ) (instance water3 of Prop (properties y 141 x 59 view 69 loop 2 ) ) (instance water4 of Prop (properties y 135 x 110 view 69 loop 3 ) ) (instance water5 of Prop (properties y 187 x 186 view 69 loop 4 ) ) (instance water6 of Prop (properties y 116 x 107 view 69 loop 5 ) ) (instance water7 of Prop (properties y 118 x 246 view 69 loop 6 ) ) (instance water8 of Prop (properties y 181 x 214 view 69 loop 7 ) ) (instance waterButton1 of Prop (properties y 31 x 218 view 331 loop 2 ) ) (instance waterButton2 of Prop (properties y 122 x 20 view 331 loop 3 ) ) (instance waterButton3 of Prop (properties y 98 x 288 view 331 loop 3 ) ) (instance waterButton4 of Prop (properties y 168 x 187 view 331 loop 4 ) )
412
0.850445
1
0.850445
game-dev
MEDIA
0.897398
game-dev
0.927946
1
0.927946
rottaca/LEDTableEngine
3,426
LEDTableEngine/src/inputHandlers/keyboardInput.cpp
#include <LEDTableEngine/inputHandlers/keyboardInput.hpp> #include <LEDTableEngine/configuration.hpp> namespace led{ KeyboardInput::KeyboardInput(std::string keyboardDev) { m_keyboardDevName = keyboardDev; } KeyboardInput::~KeyboardInput() { } bool KeyboardInput::initialize() { return m_keyboard.start(m_keyboardDevName); } BaseInput::InputEvents KeyboardInput::getInputEvents() { InputEvents ie; BaseInput::InputEvent e; e.state = InputEventState::KEY_PRESSED; if (m_keyboard.getKeyState(KEYBOARD_CTR_0_KEYMAP_LEFT)) { e.name = BaseInput::InputEventName::LEFT; e.playerId = PLAYER_0; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_0_KEYMAP_RIGHT)) { e.name = BaseInput::InputEventName::RIGHT; e.playerId = PLAYER_0; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_0_KEYMAP_UP)) { e.name = BaseInput::InputEventName::UP; e.playerId = PLAYER_0; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_0_KEYMAP_DOWN)) { e.name = BaseInput::InputEventName::DOWN; e.playerId = PLAYER_0; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_0_KEYMAP_EXIT)) { e.name = BaseInput::InputEventName::EXIT; e.playerId = PLAYER_0; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_0_KEYMAP_ENTER)) { e.name = BaseInput::InputEventName::ENTER; e.playerId = PLAYER_0; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_0_KEYMAP_A)) { e.name = BaseInput::InputEventName::A; e.playerId = PLAYER_0; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_0_KEYMAP_B)) { e.name = BaseInput::InputEventName::B; e.playerId = PLAYER_0; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_1_KEYMAP_LEFT)) { e.name = BaseInput::InputEventName::LEFT; e.playerId = PLAYER_1; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_1_KEYMAP_RIGHT)) { e.name = BaseInput::InputEventName::RIGHT; e.playerId = PLAYER_1; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_1_KEYMAP_UP)) { e.name = BaseInput::InputEventName::UP; e.playerId = PLAYER_1; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_1_KEYMAP_DOWN)) { e.name = BaseInput::InputEventName::DOWN; e.playerId = PLAYER_1; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_1_KEYMAP_EXIT)) { e.name = BaseInput::InputEventName::EXIT; e.playerId = PLAYER_1; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_1_KEYMAP_ENTER)) { e.name = BaseInput::InputEventName::ENTER; e.playerId = PLAYER_1; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_1_KEYMAP_A)) { e.name = BaseInput::InputEventName::A; e.playerId = PLAYER_1; ie.push_back(e); } if (m_keyboard.getKeyState(KEYBOARD_CTRL_1_KEYMAP_B)) { e.name = BaseInput::InputEventName::B; e.playerId = PLAYER_1; ie.push_back(e); } return ie; } size_t KeyboardInput::getSupportedPlayerCnt(){ return 2; } }
412
0.736918
1
0.736918
game-dev
MEDIA
0.578866
game-dev
0.581114
1
0.581114
The-Aether-Team/The-Aether
2,932
src/main/java/com/aetherteam/aether/client/renderer/entity/FloatingBlockRenderer.java
package com.aetherteam.aether.client.renderer.entity; import com.aetherteam.aether.entity.block.FloatingBlockEntity; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.BlockRenderDispatcher; import net.minecraft.client.renderer.entity.EntityRenderer; import net.minecraft.client.renderer.entity.EntityRendererProvider; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; import net.minecraft.world.inventory.InventoryMenu; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.state.BlockState; import net.neoforged.neoforge.client.model.data.ModelData; public class FloatingBlockRenderer extends EntityRenderer<FloatingBlockEntity> { public FloatingBlockRenderer(EntityRendererProvider.Context context) { super(context); this.shadowRadius = 0.5F; } @Override public void render(FloatingBlockEntity floatingBlock, float entityYaw, float partialTicks, PoseStack poseStack, MultiBufferSource buffer, int packedLightIn) { BlockState blockState = floatingBlock.getBlockState(); if (blockState.getRenderShape() == RenderShape.MODEL) { Level world = floatingBlock.level(); if (blockState != world.getBlockState(floatingBlock.blockPosition()) && blockState.getRenderShape() != RenderShape.INVISIBLE) { poseStack.pushPose(); BlockPos blockPos = BlockPos.containing(floatingBlock.getX(), floatingBlock.getBoundingBox().maxY, floatingBlock.getZ()); poseStack.translate(-0.5, 0.0, -0.5); BlockRenderDispatcher blockRenderDispatcher = Minecraft.getInstance().getBlockRenderer(); BakedModel model = blockRenderDispatcher.getBlockModel(blockState); for (RenderType renderType : model.getRenderTypes(blockState, RandomSource.create(blockState.getSeed(floatingBlock.getStartPos())), ModelData.EMPTY)) { blockRenderDispatcher.getModelRenderer().tesselateBlock(world, model, blockState, blockPos, poseStack, buffer.getBuffer(renderType), false, RandomSource.create(), blockState.getSeed(floatingBlock.getStartPos()), OverlayTexture.NO_OVERLAY, ModelData.EMPTY, renderType); } poseStack.popPose(); super.render(floatingBlock, entityYaw, partialTicks, poseStack, buffer, packedLightIn); } } } @Override public ResourceLocation getTextureLocation(FloatingBlockEntity floatingBlock) { return InventoryMenu.BLOCK_ATLAS; } }
412
0.727548
1
0.727548
game-dev
MEDIA
0.941546
game-dev,graphics-rendering
0.947578
1
0.947578
PySport/kloppy
15,190
kloppy/infra/serializers/tracking/pff.py
import json import logging from collections import defaultdict from datetime import timedelta, timezone from typing import IO, Dict, NamedTuple, Optional, Union, List import warnings from dateutil.parser import parse from kloppy.domain import ( BallState, DatasetFlag, Ground, Metadata, Orientation, Period, Player, PlayerData, Point, Point3D, PositionType, Provider, Team, TrackingDataset, AttackingDirection, Frame, ) from kloppy.domain.services.frame_factory import create_frame from kloppy.domain.services import attacking_direction_from_frame from kloppy.exceptions import DeserializationError from kloppy.infra.serializers.tracking.deserializer import ( TrackingDataDeserializer, ) from kloppy.utils import performance_logging logger = logging.getLogger(__name__) position_types_mapping: Dict[str, PositionType] = { "CB": PositionType.CenterBack, "LCB": PositionType.LeftCenterBack, "RCB": PositionType.RightCenterBack, "LB": PositionType.LeftBack, "RB": PositionType.RightBack, "DM": PositionType.DefensiveMidfield, "CM": PositionType.CenterMidfield, "LW": PositionType.LeftWing, "RW": PositionType.RightWing, "D": PositionType.Defender, "CF": PositionType.Striker, "M": PositionType.Midfielder, "AM": PositionType.AttackingMidfield, "GK": PositionType.Goalkeeper, "F": PositionType.Attacker, } class GameEventType: """ GameEventType Type of game event. Attributes: FIRST_KICK_OFF: First half kick-off. SECOND_KICK_OFF: Second half kick-off. THIRD_KICK_OFF: Third half kick-off (if applicable). FOURTH_KICK_OFF: Fourth half kick-off (if applicable). PERIOD_END: End of half. STAYS_IN_PLAY: Ball hits post, bar, or corner flag and stays in play. PLAYER_OFF: Player off. PLAYER_ON: Player on. ON_THE_BALL: On-the-ball event. BALL_OUT: Ball out-of-play. SUBSTITUTION: Substitution event. VIDEO_MISSING: Video data missing. """ FIRST_KICK_OFF = "FIRSTKICKOFF" SECOND_KICK_OFF = "SECONDKICKOFF" THIRD_KICK_OFF = "THIRDKICKOFF" FOURTH_KICK_OFF = "FOURTHKICKOFF" PERIOD_END = "END" STAYS_IN_PLAY = "G" PLAYER_OFF = "OFF" PLAYER_ON = "ON" ON_THE_BALL = "OTB" BALL_OUT = "OUT" SUBSTITUTION = "SUB" VIDEO_MISSING = "VID" class PFF_TrackingInputs(NamedTuple): meta_data: IO[bytes] roster_meta_data: IO[bytes] raw_data: IO[bytes] class PFF_TrackingDeserializer(TrackingDataDeserializer[PFF_TrackingInputs]): def __init__( self, limit: Optional[int] = None, sample_rate: Optional[float] = None, coordinate_system: Optional[Union[str, Provider]] = None, only_alive: Optional[bool] = False, ): super().__init__(limit, sample_rate, coordinate_system) self.only_alive = only_alive self._ball_owning_team = None self._ball_state = BallState.DEAD @property def provider(self) -> Provider: return Provider.PFF @classmethod def _get_frame_data( cls, players, periods, ball_owning_team, ball_state, frame, ): """Gets a Frame""" # Get Frame information frame_period = frame["period"] frame_id = frame["frameNum"] frame_timestamp = timedelta(seconds=frame["periodElapsedTime"]) # Ball coordinates ball_smoothed = frame.get("ballsSmoothed") if ball_smoothed: ball_x = ball_smoothed.get("x") ball_y = ball_smoothed.get("y") ball_z = ball_smoothed.get("z") if ball_x is None or ball_y is None: ball_coordinates = None else: ball_coordinates = Point3D( x=float(ball_x), y=float(ball_y), z=float(ball_z) if ball_z is not None else None, ) else: ball_coordinates = None # Player coordinates players_data = {} # Helper function to map players def map_players(players_smoothed, team): if players_smoothed is None: return for player_info in players_smoothed: jersey_num = int(player_info.get("jerseyNum")) player = next( ( p for p in players[team].values() if p.jersey_no == jersey_num ), None, ) if player: player_x = player_info.get("x") player_y = player_info.get("y") if player_x is not None and player_y is not None: player_data = PlayerData( coordinates=Point(player_x, player_y) ) players_data[player] = player_data # Process home and away players map_players(frame.get("homePlayersSmoothed"), "HOME") map_players(frame.get("awayPlayersSmoothed"), "AWAY") return create_frame( frame_id=frame_id, timestamp=frame_timestamp, ball_coordinates=ball_coordinates, players_data=players_data, period=periods[frame_period], ball_state=ball_state, ball_owning_team=ball_owning_team, other_data={}, ) @classmethod def __get_periods(cls, tracking, frame_rate): """Gets the Periods contained in the tracking data""" periods = {} frames_by_period = defaultdict(list) for raw_frame in tracking: frame = json.loads(raw_frame) if frame["period"] is not None: frames_by_period[frame["period"]].append(frame) for period, frames in frames_by_period.items(): periods[period] = Period( id=period, start_timestamp=timedelta( seconds=frames[0]["frameNum"] / frame_rate ), end_timestamp=timedelta( seconds=frames[-1]["frameNum"] / frame_rate ), ) return periods def deserialize(self, inputs: PFF_TrackingInputs) -> TrackingDataset: # Load datasets metadata = json.load(inputs.meta_data)[0] roster_meta_data = json.load(inputs.roster_meta_data) raw_data = inputs.raw_data.readlines() # Obtain game_id from metadata game_id = int(metadata["id"]) if not metadata: raise DeserializationError( "The game_id of this game is not contained within the provided meta data file" ) # Get metadata variables home_team = metadata["homeTeam"] away_team = metadata["awayTeam"] stadium = metadata["stadium"] game_week = metadata["week"] # Obtain frame rate frame_rate = metadata["fps"] home_team_id = home_team["id"] away_team_id = away_team["id"] with performance_logging("Loading metadata", logger=logger): periods = self.__get_periods(raw_data, frame_rate) pitch_size_width = stadium["pitches"][0]["width"] pitch_size_length = stadium["pitches"][0]["length"] transformer = self.get_transformer( pitch_length=pitch_size_length, pitch_width=pitch_size_width ) date = metadata.get("date") if date: date = parse(date).replace(tzinfo=timezone.utc) players = {"HOME": {}, "AWAY": {}} # Create Team objects for home and away sides home_team = Team( team_id=home_team_id, name=home_team["name"], ground=Ground.HOME, ) away_team = Team( team_id=away_team_id, name=away_team["name"], ground=Ground.AWAY, ) teams = [home_team, away_team] for player in roster_meta_data: team_id = player["team"]["id"] player_col = player["player"] player_id = player_col["id"] player_name = player_col["nickname"] shirt_number = int(player["shirtNumber"]) player_position = player["positionGroupType"] if team_id == home_team_id: team_string = "HOME" team = home_team elif team_id == away_team_id: team_string = "AWAY" team = away_team else: raise DeserializationError(f"Unknown team_id: {team_id}") # Create Player object players[team_string][player_id] = Player( player_id=player_id, team=team, jersey_no=shirt_number, name=player_name, starting_position=position_types_mapping.get( player_position, PositionType.Unknown ), starting=None, ) home_team.players = list(players["HOME"].values()) away_team.players = list(players["AWAY"].values()) with performance_logging("Loading data", logger=logger): def _iter(): sample = 1.0 / self.sample_rate n = 0 for raw_frame in raw_data: frame = json.loads(raw_frame) # Identify Period frame_period = frame.get("period") # Find ball owning team game_event = frame.get("game_event") if game_event: game_event_type = game_event.get("game_event_type") if game_event_type in ( GameEventType.BALL_OUT, GameEventType.PERIOD_END, ): self._ball_state = BallState.DEAD elif game_event_type in ( GameEventType.FIRST_KICK_OFF, GameEventType.SECOND_KICK_OFF, GameEventType.THIRD_KICK_OFF, GameEventType.FOURTH_KICK_OFF, GameEventType.ON_THE_BALL, ): self._ball_state = BallState.ALIVE else: # for other events leave ball state as is pass if game_event.get("home_ball") is not None: self._ball_owning_team = ( home_team if game_event["home_ball"] else away_team ) if self.only_alive and self._ball_state == BallState.DEAD: continue if frame_period is not None and n % sample == 0: yield frame, frame_period n += 1 frames, et_frames = [], [] n_frames = 0 for _frame, _frame_period in _iter(): # Create and transform Frame object frame = transformer.transform_frame( self._get_frame_data( players, periods, self._ball_owning_team, self._ball_state, _frame, ) ) # if Regular Time if _frame_period in {1, 2}: frames.append(frame) # else if extra time elif _frame_period in {3, 4}: et_frames.append(frame) n_frames += 1 if self.limit and n_frames >= self.limit: break first_frame_p1 = next( frame for frame in frames if frame.period.id == 1 ) is_home_team_left = ( True if attacking_direction_from_frame(first_frame_p1) == AttackingDirection.LTR else False ) if et_frames: first_frame_p3 = next( frame for frame in et_frames if frame.period.id == 3 ) is_home_team_extra_time_left = ( True if attacking_direction_from_frame(first_frame_p3) == AttackingDirection.LTR else False ) # If first period and third period attacking direction for home team is inconsistent, flip the direction of the extra time frames if is_home_team_left != is_home_team_extra_time_left: for et_frame in et_frames: # Loop through each PlayerData in the players_data dictionary for _, player_data in et_frame.players_data.items(): if ( player_data.coordinates and player_data.coordinates.x is not None and player_data.coordinates.y is not None ): # Create a new Point with multiplied coordinates for each player player_data.coordinates = Point( -player_data.coordinates.x, -player_data.coordinates.y, ) # Multiply the x and y coordinates of the ball by -1 if ( et_frame.ball_coordinates and et_frame.ball_coordinates.x is not None and et_frame.ball_coordinates.y is not None ): et_frame.ball_coordinates = Point3D( -et_frame.ball_coordinates.x, -et_frame.ball_coordinates.y, et_frame.ball_coordinates.z, ) orientation = ( Orientation.HOME_AWAY if is_home_team_left else Orientation.AWAY_HOME ) frames.extend(et_frames) metadata = Metadata( teams=teams, periods=sorted(periods.values(), key=lambda p: p.id), pitch_dimensions=transformer.get_to_coordinate_system().pitch_dimensions, frame_rate=frame_rate, orientation=orientation, provider=Provider.PFF, flags=DatasetFlag.BALL_OWNING_TEAM | DatasetFlag.BALL_STATE, coordinate_system=transformer.get_to_coordinate_system(), date=date, game_id=game_id, game_week=game_week, ) return TrackingDataset( records=frames, metadata=metadata, )
412
0.782406
1
0.782406
game-dev
MEDIA
0.298505
game-dev
0.869441
1
0.869441
ProjectIgnis/CardScripts
1,924
rush/c160210064.lua
--SPアシスタント・ヒーヤ --Icelyn the Super Assistant --scripted by YoshiDuels local s,id=GetID() function s.initial_effect(c) --Draw local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_DRAW|CATEGORY_TODECK) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCondition(s.drcon) e1:SetCost(s.drcost) e1:SetTarget(s.drtg) e1:SetOperation(s.drop) c:RegisterEffect(e1) end s.listed_names={160316023} --Super Assistant Achi function s.drcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetFieldGroupCount(tp,LOCATION_DECK,0)>=10 end function s.costfilter(c) return c:IsMonster() and c:IsType(TYPE_EFFECT) and c:IsAttribute(ATTRIBUTE_FIRE) and c:IsAbleToGraveAsCost() end function s.drcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.costfilter,tp,LOCATION_HAND,0,1,nil) end end function s.drtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(1) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function s.tdfilter(c) return c:IsCode(160316023) and c:IsAbleToDeck() end function s.drop(e,tp,eg,ep,ev,re,r,rp) --Requirement Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,s.costfilter,tp,LOCATION_HAND,0,1,1,nil) if Duel.SendtoGrave(g,REASON_COST)<1 then return end --Effect local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) if Duel.Draw(p,d,REASON_EFFECT)>0 and Duel.IsExistingMatchingCard(s.tdfilter,tp,LOCATION_GRAVE,0,1,nil) and Duel.SelectYesNo(tp,aux.Stringid(id,1)) then local g2=Duel.GetMatchingGroup(s.tdfilter,tp,LOCATION_GRAVE,0,nil) local ct=Duel.SendtoDeck(g2,nil,SEQ_DECKBOTTOM,REASON_COST) if ct>0 then Duel.SortDeckbottom(tp,tp,ct) Duel.BreakEffect() Duel.Draw(tp,2,REASON_EFFECT) end end end
412
0.854278
1
0.854278
game-dev
MEDIA
0.961693
game-dev
0.956774
1
0.956774
diwu/Tiny-Wings-Remake-on-Android
3,245
twxes10/libs/Box2D/Collision/Shapes/b2PolygonShape.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_POLYGON_SHAPE_H #define B2_POLYGON_SHAPE_H #include <Box2D/Collision/Shapes/b2Shape.h> /// A convex polygon. It is assumed that the interior of the polygon is to /// the left of each edge. /// Polygons have a maximum number of vertices equal to b2_maxPolygonVertices. /// In most cases you should not need many vertices for a convex polygon. class b2PolygonShape : public b2Shape { public: b2PolygonShape(); /// Implement b2Shape. b2Shape* Clone(b2BlockAllocator* allocator) const; /// @see b2Shape::GetChildCount int32 GetChildCount() const; /// Copy vertices. This assumes the vertices define a convex polygon. /// It is assumed that the exterior is the the right of each edge. /// The count must be in the range [3, b2_maxPolygonVertices]. void Set(const b2Vec2* vertices, int32 vertexCount); /// Build vertices to represent an axis-aligned box. /// @param hx the half-width. /// @param hy the half-height. void SetAsBox(float32 hx, float32 hy); /// Build vertices to represent an oriented box. /// @param hx the half-width. /// @param hy the half-height. /// @param center the center of the box in local coordinates. /// @param angle the rotation of the box in local coordinates. void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle); /// @see b2Shape::TestPoint bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; /// Implement b2Shape. bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform, int32 childIndex) const; /// @see b2Shape::ComputeAABB void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; /// @see b2Shape::ComputeMass void ComputeMass(b2MassData* massData, float32 density) const; /// Get the vertex count. int32 GetVertexCount() const { return m_vertexCount; } /// Get a vertex by index. const b2Vec2& GetVertex(int32 index) const; b2Vec2 m_centroid; b2Vec2 m_vertices[b2_maxPolygonVertices]; b2Vec2 m_normals[b2_maxPolygonVertices]; int32 m_vertexCount; }; inline b2PolygonShape::b2PolygonShape() { m_type = e_polygon; m_radius = b2_polygonRadius; m_vertexCount = 0; m_centroid.SetZero(); } inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const { b2Assert(0 <= index && index < m_vertexCount); return m_vertices[index]; } #endif
412
0.944846
1
0.944846
game-dev
MEDIA
0.865294
game-dev
0.930425
1
0.930425
mapron/FreeHeroes
11,643
src/Core/GameObjects/AdventureHero.hpp
/* * Copyright (C) 2020 Smirnov Vladimir / mapron1@gmail.com * SPDX-License-Identifier: MIT * See LICENSE file for details. */ #pragma once #include "LibraryHero.hpp" #include "LibraryArtifact.hpp" #include "LibraryFaction.hpp" #include "LibrarySpell.hpp" #include "BonusRatio.hpp" #include <vector> #include <set> #include <cassert> namespace FreeHeroes::Core { struct AdventureHero { AdventureHero() = default; explicit AdventureHero(LibraryHeroConstPtr library) { reset(library); } void reset(LibraryHeroConstPtr plibrary) { this->library = plibrary; secondarySkills = getInitialSkills(); currentBasePrimary = getInitialPrimary(); name = getInitialName(); setSpellAvailable(getInitialSpell(), true); level = 1; } HeroSkillsList getInitialSkills() const { return library ? library->secondarySkills : HeroSkillsList{}; } HeroPrimaryParams getInitialPrimary() const { return library ? library->heroClass()->startParams : HeroPrimaryParams(); } std::string getInitialName() const { return library ? library->untranslatedName : std::string(); } LibrarySpellConstPtr getInitialSpell() const { return library ? library->startSpell : nullptr; } int getSkillLevel(LibrarySecondarySkillConstPtr skill) const { auto it = std::find_if(secondarySkills.cbegin(), secondarySkills.cend(), [skill](auto sk) { return sk.skill == skill; }); if (it == secondarySkills.cend()) return -1; return it->level; }; bool setSkillLevel(LibrarySecondarySkillConstPtr skill, int plevel, int limit) { if (plevel < 0 || plevel > 2) return false; auto it = std::find_if(secondarySkills.begin(), secondarySkills.end(), [skill](auto sk) { return sk.skill == skill; }); if (it == secondarySkills.cend()) { if (static_cast<int>(secondarySkills.size()) >= limit) return false; secondarySkills.emplace_back(skill, plevel); return true; } it->level = plevel; return true; }; bool removeSkill(LibrarySecondarySkillConstPtr skill) { auto it = std::find_if(secondarySkills.begin(), secondarySkills.end(), [skill](auto sk) { return sk.skill == skill; }); if (it != secondarySkills.end()) secondarySkills.erase(it); else return false; return true; } void setSpellAvailable(LibrarySpellConstPtr spell, bool state) { if (state && spell) { spellbook.insert(spell); return; } auto it = spellbook.find(spell); if (it != spellbook.end()) spellbook.erase(it); } LibraryUnit::HeroStackSize getExpectedStackSize(size_t index) const { if (library && index < library->startStacks.size()) { auto c = library->startStacks[index]; return c.stackSize.isValid() ? c.stackSize : c.unit->countWithHeroBase; } return {}; } LibraryArtifactConstPtr getArtifact(ArtifactSlotType slot) const { return artifactsOn.contains(slot) ? artifactsOn.at(slot) : nullptr; } int getBagCount(LibraryArtifactConstPtr art) const { return artifactsBag.contains(art) ? artifactsBag.at(art) : 0; } bool isArtifactOn(LibraryArtifactConstPtr art) const { for (auto& p : artifactsOn) { if (p.second == art) return true; } return false; } size_t getWearingCountFromSet(LibraryArtifactConstPtr artSet) const { size_t count = 0; for (auto part : artSet->parts) { if (!isArtifactOn(part)) continue; count++; } return count; } std::vector<LibraryArtifactConstPtr> getMissingPartsFromSet(LibraryArtifactConstPtr artSet) const { std::vector<LibraryArtifactConstPtr> result; for (auto part : artSet->parts) { if (!isArtifactOn(part)) result.push_back(part); } return result; } using ArtifactsBagMap = std::map<LibraryArtifactConstPtr, int>; using ArtifactsBagList = std::vector<LibraryArtifactConstPtr>; using ArtifactsOnMap = std::map<ArtifactSlotType, LibraryArtifactConstPtr>; // main params: LibraryHeroConstPtr library = nullptr; HeroPrimaryParams currentBasePrimary; // base parameters without artifacts. ArtifactsOnMap artifactsOn; ArtifactsBagMap artifactsBag; ArtifactsBagList artifactsBagList; // @todo: back and forth with artifactsBag HeroSkillsList secondarySkills; std::set<LibrarySpellConstPtr> spellbook; LibrarySpell::Type someSpell = LibrarySpell::Type::Offensive; bool hasSpellBook = false; int level = 0; int64_t experience = 0; int mana = 0; int movePointsRemain = 0; int thisDayMovePoints = 0; bool newBornHero = true; // for full mana and MP. int levelupsWithoutWisdom = 1; int levelupsWithoutSchool = 1; auto asTuple() const noexcept { return std::tie(library, currentBasePrimary, artifactsOn, artifactsBag, secondarySkills, spellbook, hasSpellBook, level, experience, mana, movePointsRemain); } bool isEqualTo(const AdventureHero& another) const noexcept { if (isValid() != another.isValid()) return false; //if (!isValid() && !another.isValid()) // return true; return asTuple() == another.asTuple(); } bool isValid() const noexcept { return !!library; } // editor params struct EditorParams { bool expIsDirty = false; bool levelIsDirty = false; }; EditorParams editorParams; // display params std::string name; // estimation cache: struct SpellDetails { LibrarySpellConstPtr spell = nullptr; int manaCost = 0; int level = 0; int hintDamage = 0; }; using SpellList = std::vector<SpellDetails>; struct EstimatedParams { int nextDayMovePoints = 0; int nextDayMovePointsWater = 0; int extraMovePoints = 0; // artifacts + stables/map objects etc int extraMovePointsWater = 0; // artifacts + beacons/etc int armyMovePoints = 0; int maxMana = 0; // skills int manaRegenAbs = 1; // skills,artifacts int scoutingRadius = 5; // skills,artifacts int maxLearningSpellLevel = 2; int maxTeachingSpellLevel = 0; int64_t experienceStartLevel = 0; int64_t experienceNextLevel = 0; HeroPrimaryParams primary; // skills + artifacts PrimaryRngParams rngParams; // skills + artifacts PrimaryRngParams rngParamsForOpponent; // artifacts RngChanceMultiplier rngMult; // artifacts: 0 morale, 0 luck BonusRatio meleeAttack = { 0, 1 }; // skills BonusRatio rangedAttack = { 0, 1 }; // skills BonusRatio defense = { 0, 1 }; // skills MagicIncrease magicIncrease; // skills MagicReduce magicReduce; // this currently never used by database. created for symmetry.. BonusRatio magicResistChance = { 0, 1 }; // skills + artifacts SpellFilter immunities; // protector artifacts SpellFilter forbidSpells; // artifacts int unitBattleSpeedAbs = 0; // artifacts, spec on speed int unitLifeAbs = 0; // artifacts BonusRatio unitLife = { 0, 1 }; // artifacts std::set<RangeAttackPenalty> disabledPenalties; // artifacts BonusRatio spReduceOpp = { 0, 1 }; // skills + artifacts BonusRatio manaIncrease = { 0, 1 }; // skills BonusRatio mpIncrease = { 0, 1 }; // skills BonusRatio mpWaterIncrease = { 0, 1 }; // skills bool regenerateStackHealth = false; // artifacts. MoraleDetails moraleDetails; LuckDetails luckDetails; SpellList availableSpells; // sorted by order. MagicSchoolLevels schoolLevels; // skills int extraRounds = 0; SpellCastParamsList castsBeforeStart; BonusRatio surrenderDiscount = { 0, 1 }; // skills + artifacts BonusRatio neutralJoinChance = { 0, 1 }; // skills int greatLibraryVisitLevel = 10; // skills BonusRatio bonusExperience = { 0, 1 }; // skills BonusRatio eagleEyeChance = { 0, 1 }; // skills + artifacts BonusRatio necromancy = { 0, 1 }; // skills + artifacts ResourceAmount dayIncome; std::set<LibraryArtifact::SpecialEffect> specialArtifactEffects; using PrimaryWeights = LibraryFactionHeroClass::PrimaryWeights; using SkillWeights = LibraryFactionHeroClass::SkillWeights; struct LevelupParams { struct Special { bool canBeSuggested = false; bool canBeSuggestedNew = false; bool canBeSuggestedUpgrade = false; bool forceNew = false; bool forceUpgrade = false; int suggestEveryLevel = 0; }; struct PriorSkillWeights { SkillWeights high; SkillWeights normal; size_t size() const { return high.size() + normal.size(); } bool isEmpty() const { return high.empty() && normal.empty(); } void erase(LibrarySecondarySkillConstPtr key) { if (!high.empty()) high.erase(key); if (!normal.empty()) normal.erase(key); } }; Special wisdom; Special school; PrimaryWeights primaryWeights; PriorSkillWeights weightsForNew; PriorSkillWeights weightsForUpgrade; int unupgradedSkillCount = 0; }; LevelupParams levelUp; struct SlotsInfo { ArtifactSlotRequirement mainUsed; ArtifactSlotRequirement allUsed; ArtifactSlotRequirement extraUsed; ArtifactSlotRequirement freeUsed; ArtifactWearingSet allWearing; ArtifactWearingSet mainWearing; ArtifactWearingSet extraWearing; ArtifactWearingSet freeWearing; }; SlotsInfo slotsInfo; }; // not really used; for UI usage only. struct EstimatedParamsSquad { PrimaryRngParams rngParams; PrimaryRngParams rngParamsForOpponent; MoraleDetails moraleDetails; LuckDetails luckDetails; int armySpeed = 0; int fastestBattleSpeed = 0; }; EstimatedParams estimated; EstimatedParamsSquad estimatedFromSquad; }; using AdventureHeroConstPtr = const AdventureHero*; using AdventureHeroMutablePtr = AdventureHero*; }
412
0.902416
1
0.902416
game-dev
MEDIA
0.930022
game-dev
0.928521
1
0.928521
pyfa-org/eos
30,710
eos/calculator/service.py
# ============================================================================== # Copyright (C) 2011 Diego Duclos # Copyright (C) 2011-2018 Anton Vorobyov # # This file is part of Eos. # # Eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Eos 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 Eos. If not, see <http://www.gnu.org/licenses/>. # ============================================================================== from eos.cache_handler import BuffTemplatesFetchError from eos.const.eve import AttrId from eos.const.eve import EffectCategoryId from eos.eve_obj.effect.warfare_buff.base import WarfareBuffEffect from eos.eve_obj.modifier import BasePythonModifier from eos.eve_obj.modifier import DogmaModifier from eos.eve_obj.modifier import ModificationCalculationError from eos.item.mixin.solar_system import SolarSystemItemMixin from eos.pubsub.message import AttrsValueChanged from eos.pubsub.message import AttrsValueChangedMasked from eos.pubsub.message import EffectApplied from eos.pubsub.message import EffectUnapplied from eos.pubsub.message import EffectsStarted from eos.pubsub.message import EffectsStopped from eos.pubsub.message import FleetFitAdded from eos.pubsub.message import FleetFitRemoved from eos.pubsub.message import ItemLoaded from eos.pubsub.message import ItemUnloaded from eos.pubsub.subscriber import BaseSubscriber from eos.util.keyed_storage import KeyedStorage from .affection import AffectionRegister from .misc import AffectorSpec from .misc import Projector from .projection import ProjectionRegister WARFARE_BUFF_ATTRS = { AttrId.warfare_buff_1_id: AttrId.warfare_buff_1_value, AttrId.warfare_buff_2_id: AttrId.warfare_buff_2_value, AttrId.warfare_buff_3_id: AttrId.warfare_buff_3_value, AttrId.warfare_buff_4_id: AttrId.warfare_buff_4_value} class CalculationService(BaseSubscriber): """Service which supports attribute calculation. This class collects data about various items and relations between them, and via exposed methods which provice data about these connections helps attribute map to calculate modified attribute values. """ def __init__(self, solar_system): self.__solar_system = solar_system self.__affections = AffectionRegister() self.__projections = ProjectionRegister() # Format: {projector: {modifiers}} self.__warfare_buffs = KeyedStorage() # Container with affector specs which will receive messages # Format: {message type: set(affector specs)} self.__subscribed_affectors = KeyedStorage() def get_modifications(self, affectee_item, affectee_attr_id): """Get modifications of affectee attribute on affectee item. Args: affectee_item: Item, for which we're getting modifications. affectee_attr_id: Affectee attribute ID; only modifications which influence attribute with this ID will be returned. Returns: Set with tuples in (modification operator, modification value, resistance value, affector item) format. """ # Use list because we can have multiple tuples with the same values # as valid configuration mods = [] for affector_spec in self.__affections.get_affector_specs( affectee_item ): affector_modifier = affector_spec.modifier affector_item = affector_spec.item if affector_modifier.affectee_attr_id != affectee_attr_id: continue try: mod_op, mod_value, mod_aggregate_mode, mod_aggregate_key = ( affector_modifier.get_modification(affector_item)) # Do nothing here - errors should be logged in modification # getter or even earlier except ModificationCalculationError: continue # Get resistance value resist_attr_id = affector_spec.effect.resist_attr_id carrier_item = affectee_item._solsys_carrier if resist_attr_id and carrier_item is not None: try: resist_value = carrier_item.attrs[resist_attr_id] except KeyError: resist_value = 1 else: resist_value = 1 mods.append(( mod_op, mod_value, resist_value, mod_aggregate_mode, mod_aggregate_key, affector_item)) return mods # Handle fits def _handle_fit_added(self, fit): fit._subscribe(self, self._handler_map.keys()) def _handle_fit_removed(self, fit): fit._unsubscribe(self, self._handler_map.keys()) # Handle item changes which are significant for calculator def _handle_fleet_fit_added(self, msg): fits_effect_applications = {} for projector in self.__projections.get_projectors(): if not isinstance(projector.effect, WarfareBuffEffect): continue projector_fit = projector.item._fit # Affect this fit by buffs existing in fleet if ( msg.fit.ship is not None and projector_fit.fleet is msg.fit.fleet ): fits_effect_applications.setdefault( projector_fit, []).append( (projector, [msg.fit.ship])) # Affect other fits by buffs from this fit if projector_fit is msg.fit: for fit in msg.fit.fleet.fits: if fit is msg.fit: continue fits_effect_applications.setdefault( projector_fit, []).append( (projector, [fit.ship])) # Apply warfare buffs if fits_effect_applications: for fit, effect_applications in fits_effect_applications.items(): msgs = [] for projector, tgt_items in effect_applications: msgs.append(EffectApplied( projector.item, projector.effect.id, tgt_items)) fit._publish_bulk(msgs) def _handle_fleet_fit_removed(self, msg): fits_effect_unapplications = {} for projector in self.__projections.get_projectors(): if not isinstance(projector.effect, WarfareBuffEffect): continue projector_fit = projector.item._fit # Unaffect this fit by buffs existing in fleet if ( msg.fit.ship is not None and projector_fit.fleet is msg.fit.fleet ): fits_effect_unapplications.setdefault( projector_fit, []).append( (projector, [msg.fit.ship])) # Unaffect other fits by buffs from this fit if projector_fit is msg.fit: for fit in msg.fit.fleet.fits: if fit is msg.fit: continue fits_effect_unapplications.setdefault( projector_fit, []).append( (projector, [fit.ship])) # Unapply warfare buffs if fits_effect_unapplications: for fit, effect_unapplications in ( fits_effect_unapplications.items() ): msgs = [] for projector, tgt_items in effect_unapplications: msgs.append(EffectUnapplied( projector.item, projector.effect.id, tgt_items)) fit._publish_bulk(msgs) def _handle_item_loaded(self, msg): item = msg.item self.__affections.register_affectee_item(item) if isinstance(item, SolarSystemItemMixin): self.__projections.register_solsys_item(item) def _handle_item_unloaded(self, msg): item = msg.item self.__affections.unregister_affectee_item(item) if isinstance(item, SolarSystemItemMixin): self.__projections.unregister_solsys_item(item) def _handle_effects_started(self, msg): item = msg.item effect_ids = msg.effect_ids attr_changes = {} for affector_spec in self.__generate_local_affector_specs( item, effect_ids ): # Register the affector spec if isinstance(affector_spec.modifier, BasePythonModifier): self.__subscribe_python_affector_spec(msg.fit, affector_spec) self.__affections.register_local_affector_spec(affector_spec) # Clear values of attributes dependent on the affector spec for affectee_item in self.__affections.get_local_affectee_items( affector_spec ): attr_id = affector_spec.modifier.affectee_attr_id if affectee_item.attrs._force_recalc(attr_id): attr_ids = attr_changes.setdefault(affectee_item, set()) attr_ids.add(attr_id) # Register projectors for projector in self.__generate_projectors(item, effect_ids): self.__projections.register_projector(projector) # Register warfare buffs effect_applications = [] item_fleet = msg.fit.fleet for effect_id in effect_ids: effect = item._type_effects[effect_id] if not isinstance(effect, WarfareBuffEffect): continue projector = Projector(item, effect) for buff_id_attr_id in WARFARE_BUFF_ATTRS: try: buff_id = item.attrs[buff_id_attr_id] except KeyError: continue getter = ( self.__solar_system.source.cache_handler.get_buff_templates) try: buff_templates = getter(buff_id) except BuffTemplatesFetchError: continue affector_attr_id = WARFARE_BUFF_ATTRS[buff_id_attr_id] if not buff_templates: continue for buff_template in buff_templates: modifier = DogmaModifier._make_from_buff_template( buff_template, affector_attr_id) affector_spec = AffectorSpec(item, effect, modifier) self.__warfare_buffs.add_data_entry( projector, affector_spec) tgt_ships = [] for tgt_fit in self.__solar_system.fits: if ( tgt_fit is msg.fit or (item_fleet is not None and tgt_fit.fleet is item_fleet) ): tgt_ship = tgt_fit.ship if tgt_ship is not None: tgt_ships.append(tgt_ship) effect_applications.append((projector, tgt_ships)) if attr_changes: self.__publish_attr_changes(attr_changes) # Apply warfare buffs if effect_applications: msgs = [] for projector, tgt_items in effect_applications: msgs.append(EffectApplied( projector.item, projector.effect.id, tgt_items)) msg.fit._publish_bulk(msgs) def _handle_effects_stopped(self, msg): # Get info on warfare buffs effect_unapplications = [] for projector in self.__generate_projectors(msg.item, msg.effect_ids): if projector not in self.__warfare_buffs: continue tgt_ships = self.__projections.get_projector_tgts(projector) effect_unapplications.append((projector, tgt_ships)) # Unapply and unregister warfare buffs if effect_unapplications: msgs = [] for projector, tgt_items in effect_unapplications: msgs.append(EffectUnapplied( projector.item, projector.effect.id, tgt_items)) msg.fit._publish_bulk(msgs) for projector, _ in effect_unapplications: del self.__warfare_buffs[projector] attr_changes = {} # Remove values of affectee attributes for affector_spec in self.__generate_local_affector_specs( msg.item, msg.effect_ids ): # Clear values of attributes dependent on the affector spec for affectee_item in self.__affections.get_local_affectee_items( affector_spec ): attr_id = affector_spec.modifier.affectee_attr_id if affectee_item.attrs._force_recalc(attr_id): attr_ids = attr_changes.setdefault(affectee_item, set()) attr_ids.add(attr_id) # Unregister the affector spec self.__affections.unregister_local_affector_spec(affector_spec) if isinstance(affector_spec.modifier, BasePythonModifier): self.__unsubscribe_python_affector_spec(msg.fit, affector_spec) # Unregister projectors for projector in self.__generate_projectors(msg.item, msg.effect_ids): self.__projections.unregister_projector(projector) if attr_changes: self.__publish_attr_changes(attr_changes) def _handle_effect_applied(self, msg): attr_changes = {} for affector_spec in self.__generate_projected_affectors( msg.item, (msg.effect_id,) ): # Register the affector spec self.__affections.register_projected_affector_spec( affector_spec, msg.tgt_items) # Clear values of attributes dependent on the affector spec for affectee_item in self.__affections.get_projected_affectee_items( affector_spec, msg.tgt_items ): attr_id = affector_spec.modifier.affectee_attr_id if affectee_item.attrs._force_recalc(attr_id): attr_ids = attr_changes.setdefault(affectee_item, set()) attr_ids.add(attr_id) # Apply projector for projector in self.__generate_projectors(msg.item, (msg.effect_id,)): self.__projections.apply_projector(projector, msg.tgt_items) if attr_changes: self.__publish_attr_changes(attr_changes) def _handle_effect_unapplied(self, msg): attr_changes = {} for affector_spec in self.__generate_projected_affectors( msg.item, (msg.effect_id,) ): # Clear values of attributes dependent on the affector spec for affectee_item in self.__affections.get_projected_affectee_items( affector_spec, msg.tgt_items ): attr_id = affector_spec.modifier.affectee_attr_id if affectee_item.attrs._force_recalc(attr_id): attr_ids = attr_changes.setdefault(affectee_item, set()) attr_ids.add(attr_id) # Unregister the affector spec self.__affections.unregister_projected_affector( affector_spec, msg.tgt_items) # Un-apply projector for projector in self.__generate_projectors(msg.item, (msg.effect_id,)): self.__projections.unapply_projector(projector, msg.tgt_items) if attr_changes: self.__publish_attr_changes(attr_changes) # Methods to clear calculated child attributes when parent attributes change def _revise_regular_attr_dependents(self, msg): """Remove calculated attribute values which rely on passed attribute. Removing them allows to recalculate updated value. Here we process all regular dependents, which include dependencies specified via capped attribute map and via affector specs with dogma modifiers. Affector specs with python modifiers are processed separately. """ affections = self.__affections projections = self.__projections effect_unapplications = [] # Unapply warfare buffs for item, attr_ids in msg.attr_changes.items(): for effect in item._type_effects.values(): projector = Projector(item, effect) if projector not in self.__warfare_buffs: continue if not attr_ids.intersection(WARFARE_BUFF_ATTRS): continue tgt_items = self.__projections.get_projector_tgts(projector) effect_unapplications.append((projector, tgt_items)) msgs = [] for projector, tgt_items in effect_unapplications: msgs.append(EffectUnapplied( projector.item, projector.effect.id, tgt_items)) msg.fit._publish_bulk(msgs) attr_changes = {} for item, attr_ids in msg.attr_changes.items(): # Remove values of affectee attributes capped by the changing # attribute for attr_id in attr_ids: for capped_attr_id in item.attrs._cap_map.get(attr_id, ()): if item.attrs._force_recalc(capped_attr_id): attr_changes.setdefault(item, set()).add(capped_attr_id) # Force attribute recalculation when local affector spec # modification changes for affector_spec in self.__generate_local_affector_specs( item, item._running_effect_ids ): affector_modifier = affector_spec.modifier # Only dogma modifiers have source attribute specified, python # modifiers are processed separately if ( not isinstance(affector_modifier, DogmaModifier) or affector_modifier.affector_attr_id not in attr_ids ): continue # Remove values for affectee_item in affections.get_local_affectee_items( affector_spec ): attr_id = affector_modifier.affectee_attr_id if affectee_item.attrs._force_recalc(attr_id): attr_changes.setdefault(affectee_item, set()).add( attr_id) # Force attribute recalculation when projected affector spec # modification changes for projector in self.__generate_projectors( item, item._running_effect_ids ): tgt_items = projections.get_projector_tgts(projector) # When projector doesn't target any items, then we do not need # to clean anything if not tgt_items: continue for affector_spec in self.__generate_projected_affectors( item, (projector.effect.id,) ): affector_modifier = affector_spec.modifier # Only dogma modifiers have source attribute specified, # python modifiers are processed separately if ( not isinstance(affector_modifier, DogmaModifier) or affector_modifier.affector_attr_id not in attr_ids ): continue for affectee_item in ( affections.get_projected_affectee_items( affector_spec, tgt_items) ): attr_id = affector_modifier.affectee_attr_id if affectee_item.attrs._force_recalc(attr_id): attr_changes.setdefault(affectee_item, set()).add( attr_id) # Force attribute recalculation if changed attribute defines # resistance to some effect for projector in projections.get_tgt_projectors(item): effect = projector.effect if effect.resist_attr_id not in attr_ids: continue tgt_items = projections.get_projector_tgts(projector) for affector_spec in self.__generate_projected_affectors( projector.item, (effect.id,) ): for affectee_item in ( affections.get_projected_affectee_items( affector_spec, tgt_items) ): attr_id = affector_spec.modifier.affectee_attr_id if affectee_item.attrs._force_recalc(attr_id): attr_changes.setdefault(affectee_item, set()).add( attr_id) # Unregister warfare buffs only after composing list of attributes we # should update for projector, tgt_items in effect_unapplications: del self.__warfare_buffs[projector] if attr_changes: self.__publish_attr_changes(attr_changes) # Register warfare buffs effect_applications = [] for item, attr_ids in msg.attr_changes.items(): if not attr_ids.intersection(WARFARE_BUFF_ATTRS): continue item_fleet = item._fit.fleet for effect_id in item._running_effect_ids: effect = item._type_effects[effect_id] if not isinstance(effect, WarfareBuffEffect): continue projector = Projector(item, effect) for buff_id_attr_id in WARFARE_BUFF_ATTRS: try: buff_id = item.attrs[buff_id_attr_id] except KeyError: continue getter = ( self.__solar_system.source. cache_handler.get_buff_templates) try: buff_templates = getter(buff_id) except BuffTemplatesFetchError: continue affector_attr_id = WARFARE_BUFF_ATTRS[buff_id_attr_id] if not buff_templates: continue for buff_template in buff_templates: modifier = DogmaModifier._make_from_buff_template( buff_template, affector_attr_id) affector_spec = AffectorSpec(item, effect, modifier) self.__warfare_buffs.add_data_entry( projector, affector_spec) tgt_ships = [] for tgt_fit in self.__solar_system.fits: if ( tgt_fit is msg.fit or ( item_fleet is not None and tgt_fit.fleet is item_fleet) ): tgt_ship = tgt_fit.ship if tgt_ship is not None: tgt_ships.append(tgt_ship) effect_applications.append((projector, tgt_ships)) if attr_changes: self.__publish_attr_changes(attr_changes) # Apply warfare buffs if effect_applications: msgs = [] for projector, tgt_items in effect_applications: msgs.append(EffectApplied( projector.item, projector.effect.id, tgt_items)) msg.fit._publish_bulk(msgs) def _revise_python_attr_dependents(self, msg): """Remove calculated attribute values when necessary. Here we go through python modifiers, deliver to them message, and if, based on contents of the message, they decide that calculated values should be removed, we remove values which depend on such modifiers. """ attr_changes = {} # If there's no subscribed affector specs for received message type, do # nothing msg_type = type(msg) if msg_type not in self.__subscribed_affectors: return # Otherwise, ask modifier if value of attribute it calculates may # change, and force recalculation if answer is yes for affector_spec in self.__subscribed_affectors[msg_type]: if not affector_spec.modifier.revise_modification( msg, affector_spec.item ): continue for affectee_item in self.__affections.get_local_affectee_items( affector_spec ): attr_id = affector_spec.modifier.affectee_attr_id if affectee_item.attrs._force_recalc(attr_id): attr_ids = attr_changes.setdefault(affectee_item, set()) attr_ids.add(attr_id) if attr_changes: self.__publish_attr_changes(attr_changes) # Message routing _handler_map = { FleetFitAdded: _handle_fleet_fit_added, FleetFitRemoved: _handle_fleet_fit_removed, ItemLoaded: _handle_item_loaded, ItemUnloaded: _handle_item_unloaded, EffectsStarted: _handle_effects_started, EffectsStopped: _handle_effects_stopped, EffectApplied: _handle_effect_applied, EffectUnapplied: _handle_effect_unapplied, AttrsValueChanged: _revise_regular_attr_dependents} def _notify(self, msg): BaseSubscriber._notify(self, msg) # Relay all messages to python modifiers, as in case of python modifiers # any message may result in deleting dependent attributes self._revise_python_attr_dependents(msg) # Affector-related methods def __generate_local_affector_specs(self, item, effect_ids): """Get local affector specs for passed item and effects.""" affector_specs = set() item_effects = item._type_effects for effect_id in effect_ids: effect = item_effects[effect_id] for modifier in effect.local_modifiers: affector_spec = AffectorSpec(item, effect, modifier) affector_specs.add(affector_spec) return affector_specs def __generate_projected_affectors(self, item, effect_ids): """Get projected affector specs for passed item and effects.""" affector_specs = set() item_effects = item._type_effects for effect_id in effect_ids: effect = item_effects[effect_id] projector = Projector(item, effect) if projector in self.__warfare_buffs: affector_specs.update(self.__warfare_buffs[projector]) for modifier in effect.projected_modifiers: affector_spec = AffectorSpec(item, effect, modifier) affector_specs.add(affector_spec) return affector_specs def __subscribe_python_affector_spec(self, fit, affector_spec): """Subscribe affector spec with python modifier.""" to_subscribe = set() for msg_type in affector_spec.modifier.revise_msg_types: # Subscribe service to new message type only if there's no such # subscription yet if ( msg_type not in self._handler_map and msg_type not in self.__subscribed_affectors ): to_subscribe.add(msg_type) # Add affector spec to subscriber map to let it receive messages self.__subscribed_affectors.add_data_entry(msg_type, affector_spec) if to_subscribe: fit._subscribe(self, to_subscribe) def __unsubscribe_python_affector_spec(self, fit, affector_spec): """Unsubscribe affector spec with python modifier.""" to_ubsubscribe = set() for msg_type in affector_spec.modifier.revise_msg_types: # Make sure affector spec will not receive messages anymore self.__subscribed_affectors.rm_data_entry(msg_type, affector_spec) # Unsubscribe service from message type if there're no recipients # anymore if ( msg_type not in self._handler_map and msg_type not in self.__subscribed_affectors ): to_ubsubscribe.add(msg_type) if to_ubsubscribe: fit._unsubscribe(self, to_ubsubscribe) # Warfare buffs-related methods # Projector-related methods def __generate_projectors(self, item, effect_ids): """Get projectors spawned by the item.""" projectors = set() item_effects = item._type_effects for effect_id in effect_ids: effect = item_effects[effect_id] if ( effect.category_id == EffectCategoryId.target or isinstance(effect, WarfareBuffEffect) ): projector = Projector(item, effect) projectors.add(projector) return projectors # Auxiliary methods def __publish_attr_changes(self, attr_changes): # Format: {fit: {item: {attr_ids}}} fit_changes_regular = {} # Format: {fit: {item: {attr_ids}}} fit_changes_masked = {} for item, attr_ids in attr_changes.items(): item_fit = item._fit item_attr_overrides = item.attrs._override_callbacks item_changes_regular = attr_ids.difference(item_attr_overrides) item_changes_masked = attr_ids.intersection(item_attr_overrides) if item_changes_regular: fit_changes_regular.setdefault( item_fit, {})[item] = item_changes_regular if item_changes_masked: fit_changes_masked.setdefault( item_fit, {})[item] = item_changes_masked # Format: {fit, [messages]} fits_msgs = {} for fit, attr_changes in fit_changes_regular.items(): msg = AttrsValueChanged(attr_changes) fits_msgs.setdefault(fit, []).append(msg) for fit, attr_changes in fit_changes_masked.items(): msg = AttrsValueChangedMasked(attr_changes) fits_msgs.setdefault(fit, []).append(msg) for fit, msgs in fits_msgs.items(): fit._publish_bulk(msgs)
412
0.543286
1
0.543286
game-dev
MEDIA
0.850391
game-dev
0.848522
1
0.848522
Venomalia/EFSAdvent
6,415
FSALib/Structs/Actor.cs
using AuroraLib.Core.Format.Identifier; using System; using System.Buffers.Binary; using System.Runtime.InteropServices; using System.Text.RegularExpressions; namespace FSALib.Structs { /// <summary> /// Represents an actor in the FSA game world. /// </summary> [StructLayout(LayoutKind.Explicit, Size = 11)] public struct Actor : IComparable<Actor> { public static Actor Null => new Actor() { ID = new Identifier32(0x20, 0x20, 0x20, 0x20) }; private static readonly Regex regex = new Regex(@"^(.{4}), L:(\d+), X:(\d+), Y:(\d+), V:(\d+),(\d+),(\d+),(\d+)"); /// <summary> /// The identifier for the actor type. /// </summary> [FieldOffset(0)] public Identifier32 ID; /// <summary> /// The layer on which the actor is placed. /// </summary> [FieldOffset(4)] public byte Layer; /// <summary> /// The X-coordinate of the actor in the game world, measured in half-tiles. /// </summary> [FieldOffset(5)] public byte XCoord; /// <summary> /// The Y-coordinate of the actor in the game world, measured in half-tiles. /// </summary> [FieldOffset(6)] public byte YCoord; [FieldOffset(7)] private uint variable; /// <summary> /// Additional variable data associated with the actor, used for customization or behavior. /// </summary> public uint Variable { readonly get => BinaryPrimitives.ReverseEndianness(variable); set => variable = BinaryPrimitives.ReverseEndianness(value); } public byte VariableByte1 { readonly get => (byte)(variable >> 24); set => variable = variable & 0x00FFFFFF | (uint)value << 24; } public byte VariableByte2 { readonly get => (byte)(variable >> 16); set => variable = variable & 0xFF00FFFF | (uint)value << 16; } public byte VariableByte3 { readonly get => (byte)(variable >> 8); set => variable = variable & 0xFFFF00FF | (uint)value << 8; } public byte VariableByte4 { readonly get => (byte)variable; set => variable = variable & 0xFFFFFF00 | value; } public string Name { get => ID.ToString(); set => ID = new Identifier32(value.AsSpan()); } /// <inheritdoc/> public int CompareTo(Actor other) { int result; if ((result = Layer.CompareTo(other.Layer)) != 0) return result; if ((result = XCoord.CompareTo(other.XCoord)) != 0) return result; if ((result = YCoord.CompareTo(other.YCoord)) != 0) return result; if ((result = ID.CompareTo(other.ID)) != 0) return result; return variable.CompareTo(other.variable); } public Actor(Identifier32 iD, byte layer, byte xCoord, byte yCoord, uint variable) { ID = iD; Layer = layer; XCoord = xCoord; YCoord = yCoord; this.variable = BinaryPrimitives.ReverseEndianness(variable); } /// <summary> /// Determines if the given <see cref="string"/> represents a valid <see cref="Actor"/>. /// </summary> /// <param name="actor">The string to check against the regex pattern for a valid actor format.</param> /// <returns>True if the string matches the actor format, otherwise false.</returns> public static bool IsStringActor(string actor) => regex.Match(actor).Success; /// <summary> /// Parses a <see cref="string"/> into an <see cref="Actor"/> if the string matches the expected format. /// </summary> /// <param name="actor">The string representing the actor, expected to contain ID, Layer, Coordinates, and Variables.</param> /// <param name="newActor">The Actor that will be populated with the parsed data.</param> /// <returns>True if the string successfully parses into an Actor, otherwise false.</returns> public static bool PasteFromString(string actor, out Actor newActor) { newActor = default; var match = regex.Match(actor); if (!match.Success) { return false; } newActor.ID = new Identifier32(match.Groups[1].Value.AsSpan()); newActor.Layer = byte.Parse(match.Groups[2].Value); newActor.XCoord = byte.Parse(match.Groups[3].Value); newActor.YCoord = byte.Parse(match.Groups[4].Value); newActor.VariableByte4 = byte.Parse(match.Groups[5].Value); newActor.VariableByte3 = byte.Parse(match.Groups[6].Value); newActor.VariableByte2 = byte.Parse(match.Groups[7].Value); newActor.VariableByte1 = byte.Parse(match.Groups[8].Value); return true; } /// <inheritdoc/> public readonly string ToStringCode() => $"{ID}, L:{Layer}, X:{XCoord}, Y:{YCoord}, V:{VariableByte4},{VariableByte3},{VariableByte2},{VariableByte1}."; /// <inheritdoc/> public readonly override string ToString() => ID.ToString(); /// <inheritdoc/> public override readonly bool Equals(object? obj) => obj is Actor actor && ID.Equals(actor.ID) && Layer == actor.Layer && XCoord == actor.XCoord && YCoord == actor.YCoord && variable == actor.variable; /// <inheritdoc/> public override readonly int GetHashCode() { #if NET6_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER HashCode hashCode = new HashCode(); hashCode.Add(ID); hashCode.Add(Layer); hashCode.Add(XCoord); hashCode.Add(YCoord); hashCode.Add(Variable); return hashCode.ToHashCode(); #else int hashCode = 414193188; hashCode = hashCode * -1521134295 + ID.GetHashCode(); hashCode = hashCode * -1521134295 + Layer.GetHashCode(); hashCode = hashCode * -1521134295 + XCoord.GetHashCode(); hashCode = hashCode * -1521134295 + YCoord.GetHashCode(); hashCode = hashCode * -1521134295 + variable.GetHashCode(); return hashCode; #endif } } }
412
0.84416
1
0.84416
game-dev
MEDIA
0.384924
game-dev
0.788654
1
0.788654
pyfa-org/Pyfa
4,183
graphs/data/fitShieldRegen/graph.py
# ============================================================================= # Copyright (C) 2010 Diego Duclos # # This file is part of pyfa. # # pyfa 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. # # pyfa 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 pyfa. If not, see <http://www.gnu.org/licenses/>. # ============================================================================= import wx import gui.mainFrame from graphs.data.base import FitGraph, Input, XDef, YDef from .getter import (ShieldAmount2ShieldAmountGetter, ShieldAmount2ShieldRegenGetter, Time2ShieldAmountGetter, Time2ShieldRegenGetter) _t = wx.GetTranslation class FitShieldRegenGraph(FitGraph): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.isEffective = gui.mainFrame.MainFrame.getInstance().statsPane.nameViewMap['resistancesViewFull'].showEffective # UI stuff internalName = 'shieldRegenGraph' name = _t('Shield Regeneration') inputs = [ Input(handle='time', unit='s', label=_t('Time'), iconID=1392, defaultValue=120, defaultRange=(0, 300), conditions=[ (('time', 's'), None)]), Input(handle='shieldAmount', unit='%', label=_t('Shield amount'), iconID=1384, defaultValue=25, defaultRange=(0, 100), conditions=[ (('shieldAmount', 'EHP'), None), (('shieldAmount', 'HP'), None), (('shieldAmount', '%'), None)]), Input(handle='shieldAmountT0', unit='%', label=_t('Starting shield amount'), iconID=1384, defaultValue=0, defaultRange=(0, 100), conditions=[ (('time', 's'), None)])] srcExtraCols = ('ShieldAmount', 'ShieldTime') usesHpEffectivity = True @property def xDefs(self): return [ XDef(handle='time', unit='s', label=_t('Time'), mainInput=('time', 's')), XDef(handle='shieldAmount', unit='EHP' if self.isEffective else 'HP', label=_t('Shield amount'), mainInput=('shieldAmount', '%')), XDef(handle='shieldAmount', unit='%', label=_t('Shield amount'), mainInput=('shieldAmount', '%'))] @property def yDefs(self): return [ YDef(handle='shieldAmount', unit='EHP' if self.isEffective else 'HP', label=_t('Shield amount')), YDef(handle='shieldRegen', unit='EHP/s' if self.isEffective else 'HP/s', label=_t('Shield regen'))] # Calculation stuff _normalizers = { ('shieldAmount', '%'): lambda v, src, tgt: v / 100 * src.item.ship.getModifiedItemAttr('shieldCapacity'), ('shieldAmountT0', '%'): lambda v, src, tgt: None if v is None else v / 100 * src.item.ship.getModifiedItemAttr('shieldCapacity'), # Needed only for "x mark" support, to convert EHP x into normalized value ('shieldAmount', 'EHP'): lambda v, src, tgt: v / src.item.damagePattern.effectivify(src.item.ship, 1, 'shield')} _limiters = { 'shieldAmount': lambda src, tgt: (0, src.item.ship.getModifiedItemAttr('shieldCapacity')), 'shieldAmountT0': lambda src, tgt: (0, src.item.ship.getModifiedItemAttr('shieldCapacity'))} _getters = { ('time', 'shieldAmount'): Time2ShieldAmountGetter, ('time', 'shieldRegen'): Time2ShieldRegenGetter, ('shieldAmount', 'shieldAmount'): ShieldAmount2ShieldAmountGetter, ('shieldAmount', 'shieldRegen'): ShieldAmount2ShieldRegenGetter} _denormalizers = { ('shieldAmount', '%'): lambda v, src, tgt: v * 100 / src.item.ship.getModifiedItemAttr('shieldCapacity'), ('shieldAmount', 'EHP'): lambda v, src, tgt: src.item.damagePattern.effectivify(src.item.ship, v, 'shield'), ('shieldRegen', 'EHP/s'): lambda v, src, tgt: src.item.damagePattern.effectivify(src.item.ship, v, 'shield')}
412
0.870925
1
0.870925
game-dev
MEDIA
0.609513
game-dev
0.793425
1
0.793425
STREGAsGate/GateEngine
5,793
Sources/GateEngine/ECS/2D Specific/Sprite/SpriteComponent.swift
/* * Copyright © 2025 Dustin Collins (Strega's Gate) * All Rights Reserved. * * http://stregasgate.com */ public final class SpriteComponent: Component { public var depth: Float = 0 public var opacity: Float = 1 public var tintColor: Color = .white public var spriteSheet: SpriteSheet? public var spriteRect: Rect public var spriteSize: Size2 { get { return self.spriteRect.size } set { self.spriteRect.size = newValue } } public var spriteCoordinate: Position2 { get { let x = self.spriteRect.position.x / self.spriteSize.width let y = self.spriteRect.position.y / self.spriteSize.height return Position2(x, y) } set { precondition(spriteSize != .zero, "spriteSize must be set first!") let x = self.spriteSize.width * newValue.x let y = self.spriteSize.height * newValue.y self.spriteRect.position = Position2(x, y) } } public var animations: [SpriteAnimation] public var activeAnimationIndex: Int? { return animationQueue.first } internal var activeAnimationIndexDidChange: Bool = true public var animationQueue: [Int] { didSet { self.moveToNextAnimationIfNeeded = false self.activeAnimationIndexDidChange = true } } internal var moveToNextAnimationIfNeeded: Bool = false public var activeAnimation: SpriteAnimation? { get { if let index = self.animationQueue.first { return self.animations[index] } return nil } set { if let newValue { if let index = self.animationQueue.first { self.animations[index] = newValue } } } } /// Appends the given animation index to the end of the animation queue. public func queueAnimation(_ animationIndex: Int) { assert(animations.indices.contains(animationIndex), "Animations does not have an index \(animationIndex).") animationQueue.append(animationIndex) } /// Replaces the entire animation queue with the given animation index. public func setAnimation(_ animationIndex: Int) { assert(animations.indices.contains(animationIndex), "Animations does not have an index \(animationIndex).") animationQueue = [animationIndex] } /// Removes all animations form the animation queue. public func clearAnimationQueue() { animationQueue.removeAll(keepingCapacity: true) } public enum PlaybackState { /// Moves through the active animation over time case play /// Keeps the active animation locked on the current frame case pause /// Locks the active animation at the last frame next time it's encountered case pauseAtLoop /// Keeps the active animation locked on the first frame case stop /// Locks the active animation at the first frame next time it's encountered case stopAtLoop /// If the animation queue has another animation it will begin on the next last frame of the current animation case playNextAnimationAtLoop } public var playbackState: PlaybackState internal var previousCoordinate: Position2 = .zero @MainActor public func sprite() -> Sprite? { assert(spriteSize != .zero, "spriteSize cannot be zero.") if let animation = activeAnimation, let texture = spriteSheet?.texture, texture.state == .ready { let columns = texture.size.width / spriteSize.width let rows = texture.size.height / spriteSize.height let startFrame = (animation.spriteSheetStart.y * columns) + animation.spriteSheetStart.x let endFrame = { if let frameCount = animation.frameCount { return startFrame + (frameCount - 1) } let framesInAnimation = (columns * rows) - startFrame return framesInAnimation }() let currentFrame = floor( startFrame.interpolated(to: endFrame, .linear(animation.progress)) ) let currentRow = floor(currentFrame / columns) let currentColumn = currentFrame - (columns * currentRow) let coord = Position2(currentColumn, currentRow) return spriteSheet?.sprite(at: coord, withSpriteSize: spriteSize) } // no animations, so return the first sprite return spriteSheet?.sprite(at: spriteCoordinate, withSpriteSize: spriteSize) } public init() { self.spriteRect = .zero self.spriteSheet = nil self.animationQueue = [0] self.animations = [] self.playbackState = .play } public init(spriteRect: Rect, spriteSheet: SpriteSheet, activeAnimationIndex: Int = 0, animations: [SpriteAnimation], playbackState: PlaybackState = .play) { self.spriteRect = spriteRect self.spriteSheet = spriteSheet self.animationQueue = [activeAnimationIndex] self.animations = animations self.playbackState = playbackState } public init(spriteSize: Size2, spriteSheet: SpriteSheet, activeAnimationIndex: Int = 0, animations: [SpriteAnimation], playbackState: PlaybackState = .play) { self.spriteRect = Rect(size: spriteSize) self.spriteSheet = spriteSheet self.animationQueue = [activeAnimationIndex] self.animations = animations self.playbackState = playbackState } public static let componentID: ComponentID = ComponentID() }
412
0.57127
1
0.57127
game-dev
MEDIA
0.84154
game-dev,graphics-rendering
0.792237
1
0.792237
marcmerlin/FastLED_NeoMatrix_SmartMatrix_LEDMatrix_GFX_Demos
4,261
LEDMatrix/Table_Mark_Estes14-int16-wip/PatternFlock.h
/* * Aurora: https://github.com/pixelmatix/aurora * Copyright (c) 2014 Jason Coon * * Portions of this code are adapted from "Flocking" in "The Nature of Code" by Daniel Shiffman: http://natureofcode.com/ * Copyright (c) 2014 Daniel Shiffman * http://www.shiffman.net * * 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. */ // Flocking // Daniel Shiffman <http://www.shiffman.net> // The Nature of Code, Spring 2009 // Demonstration of Craig Reynolds' "Flocking" behavior // See: http://www.red3d.com/cwr/ // Rules: Cohesion, Separation, Alignment #include "matrix.h" #ifndef PatternFlock_H #define PatternFlock_H class PatternFlock : public AuroraDrawable { public: PatternFlock() { name = (char *)"Flock"; } static const int boidCount = mmin(MATRIX_WIDTH/3, AVAILABLE_BOID_COUNT); Boid predator; PVector wind; byte hue = 0; bool predatorPresent = true; void start() { for (int i = 0; i < boidCount; i++) { boids[i] = Boid(MATRIX_CENTRE_X, MATRIX_CENTRE_Y); boids[i].maxspeed = 0.380; boids[i].maxforce = 0.015; } predator = Boid(MATRIX_CENTER_X / 2, MATRIX_CENTER_Y / 2); predatorPresent = true; predator.maxspeed = 0.385; predator.maxforce = 0.020; predator.neighbordist = 16.0; predator.desiredseparation = 0.0; } unsigned int drawFrame() { effects.DimAll(230); bool applyWind = random(0, 255) > 250; if (applyWind) { wind.x = Boid::randomf() * .015; wind.y = Boid::randomf() * .015; } CRGB color = effects.ColorFromCurrentPalette(hue); for (int i = 0; i < boidCount; i++) { Boid * boid = &boids[i]; if (predatorPresent) { // flee from predator boid->repelForce(predator.location, 10); } boid->run(boids, boidCount); boid->wrapAroundBorders(); //boid->avoidBorders(); PVector location = boid->location; // PVector velocity = boid->velocity; // backgroundLayer.drawLine(location.x, location.y, location.x - velocity.x, location.y - velocity.y, color); // effects.leds[XY(location.x, location.y)] += color; //backgroundLayer.drawPixel(location.x, location.y, color); matrix->drawPixel(location.x, location.y, color); if (applyWind) { boid->applyForce(wind); applyWind = false; } } if (predatorPresent) { predator.run(boids, boidCount); predator.wrapAroundBorders(); //predator.avoidBorders(); color = effects.ColorFromCurrentPalette(hue + 128); PVector location = predator.location; // PVector velocity = predator.velocity; // backgroundLayer.drawLine(location.x, location.y, location.x - velocity.x, location.y - velocity.y, color); // effects.leds[XY(location.x, location.y)] += color; //backgroundLayer.drawPixel(location.x, location.y, color); matrix->drawPixel(location.x, location.y, color); } EVERY_N_MILLIS(200) { hue++; } #if 0 EVERY_N_SECONDS(30) { predatorPresent = !predatorPresent; } #endif return 0; } }; #endif
412
0.793995
1
0.793995
game-dev
MEDIA
0.77588
game-dev,graphics-rendering
0.781083
1
0.781083
CalamityTeam/CalamityModPublic
4,840
Tiles/Furniture/Monoliths/BlueDistortedMonolithTile.cs
using CalamityMod.Dusts; using CalamityMod.Items.Placeables.Furniture.Monoliths; using CalamityMod.NPCs.Yharon; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.Audio; using Terraria.DataStructures; using Terraria.Enums; using Terraria.GameContent; using Terraria.GameContent.ObjectInteractions; using Terraria.ID; using Terraria.ModLoader; using Terraria.ObjectData; namespace CalamityMod.Tiles.Furniture.Monoliths { public class BlueDistortedMonolithTile : ModTile { public override void SetStaticDefaults() { RegisterItemDrop(ModContent.ItemType<BlueDistortedMonolith>()); Main.tileFrameImportant[Type] = true; TileObjectData.newTile.CopyFrom(TileObjectData.Style3x3); TileObjectData.newTile.Width = 5; TileObjectData.newTile.Height = 5; TileObjectData.newTile.Origin = new Point16(2, 4); TileObjectData.newTile.CoordinateHeights = new[] { 16, 16, 16, 16, 18 }; TileObjectData.newTile.LavaDeath = false; TileObjectData.newTile.UsesCustomCanPlace = true; TileObjectData.newTile.AnchorBottom = new AnchorData(AnchorType.SolidTile | AnchorType.SolidWithTop, 5, 0); TileObjectData.addTile(Type); AddMapEntry(new Color(50, 127, 209)); DustType = (int)CalamityDusts.BlueCosmilite; AnimationFrameHeight = 92; } public override void NearbyEffects(int i, int j, bool closer) { if (Main.tile[i, j].TileFrameY < 90) { return; } Player player = Main.LocalPlayer; if (player is null) { return; } if (player.active) { Main.LocalPlayer.Calamity().monolithDevourerBShader = 30; } } public override void AnimateTile(ref int frame, ref int frameCounter) { frameCounter++; if (frameCounter >= 7.2) { frameCounter = 0; if (++frame >= 6) { frame = 1; } } } public override void MouseOver(int i, int j) { Player player = Main.LocalPlayer; player.noThrow = 2; player.cursorItemIconEnabled = true; player.cursorItemIconID = ModContent.ItemType<BlueDistortedMonolith>(); } public override bool HasSmartInteract(int i, int j, SmartInteractScanSettings settings) => true; public override bool RightClick(int i, int j) { HitWire(i, j); SoundEngine.PlaySound(SoundID.Mech, new Vector2(i * 16, j * 16)); return true; } public override void HitWire(int i, int j) { int x = i - Main.tile[i, j].TileFrameX / 18 % 5; int y = j - Main.tile[i, j].TileFrameY / 18 % 5; int tileXX18 = 92; for (int l = x; l < x + 5; l++) { for (int m = y; m < y + 5; m++) { if (Main.tile[l, m].HasTile && Main.tile[l, m].TileType == Type) { if (Main.tile[l, m].TileFrameY < tileXX18) Main.tile[l, m].TileFrameY += (short)(tileXX18); else Main.tile[l, m].TileFrameY -= (short)(tileXX18); } } } if (Wiring.running) { for (int o = 0; o < 5; o++) { for (int p = 0; p < 5; p++) { Wiring.SkipWire(x + 0, x + p); } } } NetMessage.SendTileSquare(-1, x, y + 1, 3); } public override bool PreDraw(int i, int j, SpriteBatch spriteBatch) { Tile tile = Main.tile[i, j]; Texture2D texture; texture = TextureAssets.Tile[Type].Value; Vector2 zero = new(Main.offScreenRange, Main.offScreenRange); if (Main.drawToScreen) { zero = Vector2.Zero; } int height = 18; int animate = 0; if (tile.TileFrameY >= 92) { animate = Main.tileFrame[Type] * 92; } Main.spriteBatch.Draw(texture, new Vector2(i * 16 - (int)Main.screenPosition.X, j * 16 - (int)Main.screenPosition.Y) + zero, new Rectangle(tile.TileFrameX, tile.TileFrameY + animate, 16, height), Lighting.GetColor(i, j), 0f, default(Vector2), 1f, SpriteEffects.None, 0f); return false; } } }
412
0.777441
1
0.777441
game-dev
MEDIA
0.945892
game-dev
0.956856
1
0.956856
elmindreda/Nori
3,517
deps/bullet/btCompoundCollisionAlgorithm.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_COMPOUND_COLLISION_ALGORITHM_H #define BT_COMPOUND_COLLISION_ALGORITHM_H #include "btActivatingCollisionAlgorithm.h" #include "btDispatcher.h" #include "btBroadphaseInterface.h" #include "btPersistentManifold.h" class btDispatcher; #include "btBroadphaseProxy.h" #include "btCollisionCreateFunc.h" #include "btAlignedObjectArray.h" class btDispatcher; class btCollisionObject; /// btCompoundCollisionAlgorithm supports collision between CompoundCollisionShapes and other collision shapes class btCompoundCollisionAlgorithm : public btActivatingCollisionAlgorithm { btAlignedObjectArray<btCollisionAlgorithm*> m_childCollisionAlgorithms; bool m_isSwapped; class btPersistentManifold* m_sharedManifold; bool m_ownsManifold; int m_compoundShapeRevision;//to keep track of changes, so that childAlgorithm array can be updated void removeChildAlgorithms(); void preallocateChildAlgorithms(btCollisionObject* body0,btCollisionObject* body1); public: btCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1,bool isSwapped); virtual ~btCompoundCollisionAlgorithm(); virtual void processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); virtual void getAllContactManifolds(btManifoldArray& manifoldArray) { int i; for (i=0;i<m_childCollisionAlgorithms.size();i++) { if (m_childCollisionAlgorithms[i]) m_childCollisionAlgorithms[i]->getAllContactManifolds(manifoldArray); } } struct CreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCollisionAlgorithm)); return new(mem) btCompoundCollisionAlgorithm(ci,body0,body1,false); } }; struct SwappedCreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCollisionAlgorithm)); return new(mem) btCompoundCollisionAlgorithm(ci,body0,body1,true); } }; }; #endif //BT_COMPOUND_COLLISION_ALGORITHM_H
412
0.877842
1
0.877842
game-dev
MEDIA
0.994276
game-dev
0.664991
1
0.664991
opanel-mc/opanel
4,998
forge-1.20.1/src/main/java/net/opanel/forge_1_20_1/ForgeOfflinePlayer.java
package net.opanel.forge_1_20_1; import com.mojang.authlib.GameProfile; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtAccounter; import net.minecraft.nbt.NbtIo; import net.minecraft.server.*; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.players.GameProfileCache; import net.minecraft.server.players.PlayerList; import net.minecraft.server.players.UserBanList; import net.minecraft.server.players.UserBanListEntry; import net.minecraft.world.level.GameType; import net.minecraft.world.level.storage.LevelResource; import net.opanel.common.OPanelGameMode; import net.opanel.common.OPanelPlayer; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Date; import java.util.Optional; import java.util.UUID; public class ForgeOfflinePlayer implements OPanelPlayer { private final PlayerList playerManager; private final Path playerDataPath; private final GameProfile profile; private final UUID uuid; public ForgeOfflinePlayer(MinecraftServer server, UUID uuid) { playerManager = server.getPlayerList(); playerDataPath = server.getWorldPath(LevelResource.PLAYER_DATA_DIR).resolve(uuid +".dat"); GameProfileCache profileCache = server.getProfileCache(); this.uuid = uuid; if(!Files.exists(playerDataPath)) { throw new NullPointerException("Player data file for UUID "+ uuid +" unavailable."); } if(profileCache == null) { throw new NullPointerException("Cannot get player profile cache."); } ServerPlayer serverPlayer = playerManager.getPlayer(uuid); if(serverPlayer != null && !serverPlayer.hasDisconnected()) { throw new IllegalStateException("The provided player is online, please use ForgePlayer class instead."); } Optional<GameProfile> profileOpt = profileCache.get(uuid); if(profileOpt.isEmpty()) { throw new NullPointerException("Cannot get the game profile of the provided player."); } profile = profileOpt.get(); } @Override public String getName() { return profile.getName(); } @Override public String getUUID() { return uuid.toString(); } @Override public boolean isOnline() { return false; } @Override public boolean isOp() { return playerManager.isOp(profile); } @Override public boolean isBanned() { return playerManager.getBans().isBanned(profile); } @Override public OPanelGameMode getGameMode() { try { CompoundTag nbt = NbtIo.readCompressed(playerDataPath.toFile()); int gamemodeId = nbt.getInt("playerGameType"); GameType gamemode = GameType.byId(gamemodeId); switch(gamemode) { case ADVENTURE -> { return OPanelGameMode.ADVENTURE; } case SURVIVAL -> { return OPanelGameMode.SURVIVAL; } case CREATIVE -> { return OPanelGameMode.CREATIVE; } case SPECTATOR -> { return OPanelGameMode.SPECTATOR; } } } catch (IOException e) { e.printStackTrace(); } return null; } @Override public void setGameMode(OPanelGameMode gamemode) { try { CompoundTag nbt = NbtIo.readCompressed(playerDataPath.toFile()); switch(gamemode) { case ADVENTURE -> nbt.putInt("playerGameType", 2); case SURVIVAL -> nbt.putInt("playerGameType", 0); case CREATIVE -> nbt.putInt("playerGameType", 1); case SPECTATOR -> nbt.putInt("playerGameType", 3); } NbtIo.writeCompressed(nbt, playerDataPath.toFile()); } catch (IOException e) { e.printStackTrace(); } } @Override public void giveOp() { if(isOp()) return; playerManager.op(profile); } @Override public void depriveOp() { if(!isOp()) return; playerManager.deop(profile); } @Override public void kick(String reason) { throw new IllegalStateException("The player is offline."); } @Override public void ban(String reason) { if(isBanned()) return; UserBanList bannedList = playerManager.getBans(); UserBanListEntry entry = new UserBanListEntry(profile, new Date(), null, null, reason); bannedList.add(entry); } @Override public String getBanReason() { if(!isBanned()) return null; UserBanListEntry banEntry = playerManager.getBans().get(profile); if(banEntry == null) return null; return banEntry.getReason(); } @Override public void pardon() { if(!isBanned()) return; playerManager.getBans().remove(profile); } @Override public int getPing() { throw new IllegalStateException("The player is offline."); } }
412
0.932187
1
0.932187
game-dev
MEDIA
0.597883
game-dev
0.979767
1
0.979767
ScRichard/GOTHAJ_RECODE_UNRELEASED
2,369
net/minecraft/item/ItemReed.java
package net.minecraft.item; import net.minecraft.block.Block; import net.minecraft.block.BlockSnow; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; public class ItemReed extends Item { private Block block; public ItemReed(Block block) { this.block = block; } public boolean onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ) { IBlockState iblockstate = worldIn.getBlockState(pos); Block block = iblockstate.getBlock(); if (block == Blocks.snow_layer && ((Integer)iblockstate.getValue(BlockSnow.LAYERS)).intValue() < 1) { side = EnumFacing.UP; } else if (!block.isReplaceable(worldIn, pos)) { pos = pos.offset(side); } if (!playerIn.canPlayerEdit(pos, side, stack)) { return false; } else if (stack.stackSize == 0) { return false; } else { if (worldIn.canBlockBePlaced(this.block, pos, false, side, (Entity)null, stack)) { IBlockState iblockstate1 = this.block.onBlockPlaced(worldIn, pos, side, hitX, hitY, hitZ, 0, playerIn); if (worldIn.setBlockState(pos, iblockstate1, 3)) { iblockstate1 = worldIn.getBlockState(pos); if (iblockstate1.getBlock() == this.block) { ItemBlock.setTileEntityNBT(worldIn, playerIn, pos, stack); iblockstate1.getBlock().onBlockPlacedBy(worldIn, pos, iblockstate1, playerIn, stack); } worldIn.playSoundEffect((double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), this.block.stepSound.getPlaceSound(), (this.block.stepSound.getVolume() + 1.0F) / 2.0F, this.block.stepSound.getFrequency() * 0.8F); --stack.stackSize; return true; } } return false; } } }
412
0.874674
1
0.874674
game-dev
MEDIA
0.995362
game-dev
0.945542
1
0.945542
phuang/ibus-pinyin
11,648
src/PYDoublePinyinEditor.cc
/* vim:set et ts=4 sts=4: * * ibus-pinyin - The Chinese PinYin engine for IBus * * Copyright (c) 2008-2010 Peng Huang <shawn.p.huang@gmail.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, 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "PYDoublePinyinEditor.h" #include "PYConfig.h" namespace PY { #define DEFINE_DOUBLE_PINYIN_TABLES #include "PYDoublePinyinTable.h" /* * c in 'a' ... 'z' => id = c - 'a' * c == ';' => id = 26 * else => id = -1 */ #define ID(c) \ ((c >= IBUS_a && c <= IBUS_z) ? c - IBUS_a : (c == IBUS_semicolon ? 26 : -1)) #define ID_TO_SHENG(id) \ (double_pinyin_map[m_config.doublePinyinSchema ()].sheng[id]) #define ID_TO_YUNS(id) \ (double_pinyin_map[m_config.doublePinyinSchema ()].yun[id]) #define IS_ALPHA(c) \ ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) DoublePinyinEditor::DoublePinyinEditor (PinyinProperties & props, Config & config) : PinyinEditor (props, config) { } gboolean DoublePinyinEditor::insert (gint ch) { gint id; /* is full */ if (G_UNLIKELY (m_text.length () >= MAX_PINYIN_LEN)) return TRUE; id = ID (ch); if (id == -1) { /* it is not availidate ch */ return FALSE; } if (G_UNLIKELY (m_text.empty () && ID_TO_SHENG (id) == PINYIN_ID_VOID)) { return FALSE; } m_text.insert (m_cursor++, ch); if (m_cursor > m_pinyin_len + 2 || updatePinyin (FALSE) == FALSE) { if (!IS_ALPHA (ch)) { m_text.erase (--m_cursor, 1); return FALSE; } else { if (updateSpecialPhrases ()) { update (); } else { updatePreeditText (); updateAuxiliaryText (); } return TRUE; } } else { updateSpecialPhrases (); updatePhraseEditor (); update (); return TRUE; } } gboolean DoublePinyinEditor::removeCharBefore (void) { if (G_UNLIKELY (m_cursor == 0)) return FALSE; m_cursor --; m_text.erase (m_cursor, 1); if (updatePinyin (FALSE)) { updateSpecialPhrases (); updatePhraseEditor (); update (); } else { if (updateSpecialPhrases ()) { update (); } else { updatePreeditText (); updateAuxiliaryText (); } } return TRUE; } gboolean DoublePinyinEditor::removeCharAfter (void) { if (G_UNLIKELY (m_cursor == m_text.length ())) return FALSE; m_text.erase (m_cursor, 1); if (updateSpecialPhrases ()) { update (); } else { updatePreeditText (); updateAuxiliaryText (); } return TRUE; } gboolean DoublePinyinEditor::removeWordBefore (void) { if (G_UNLIKELY (m_cursor == 0)) return FALSE; if (G_UNLIKELY (m_cursor > m_pinyin_len)) { m_text.erase (m_pinyin_len, m_cursor - m_pinyin_len); m_cursor = m_pinyin_len; if (updateSpecialPhrases ()) { update (); } else { updatePreeditText (); updateAuxiliaryText (); } } else { m_pinyin_len = m_pinyin.back ().begin; m_pinyin.pop_back (); m_text.erase (m_pinyin_len, m_cursor - m_pinyin_len); m_cursor = m_pinyin_len; updateSpecialPhrases (); updatePhraseEditor (); update (); } return TRUE; } gboolean DoublePinyinEditor::removeWordAfter (void) { if (G_UNLIKELY (m_cursor == m_text.length ())) return FALSE; m_text.erase (m_cursor); if (updateSpecialPhrases ()) { update (); } else { updatePreeditText (); updateAuxiliaryText (); } return TRUE; } gboolean DoublePinyinEditor::moveCursorLeft (void) { if (G_UNLIKELY (m_cursor == 0)) return FALSE; m_cursor --; if (m_cursor >= m_pinyin_len) { if (updateSpecialPhrases ()) { update (); } else { updatePreeditText (); updateAuxiliaryText (); } } else { if (updatePinyin (FALSE)) { updateSpecialPhrases (); updatePhraseEditor (); update (); } else { if (updateSpecialPhrases ()) { update (); } else { updatePreeditText (); updateAuxiliaryText (); } } } return TRUE; } gboolean DoublePinyinEditor::moveCursorRight (void) { if (G_UNLIKELY (m_cursor == m_text.length ())) return FALSE; m_cursor ++; if (updatePinyin (FALSE)) { updateSpecialPhrases (); updatePhraseEditor (); update (); } else { if (updateSpecialPhrases ()) { update (); } else { updatePreeditText (); updateAuxiliaryText (); } } return TRUE; } gboolean DoublePinyinEditor::moveCursorLeftByWord (void) { if (G_UNLIKELY (m_cursor == 0)) return FALSE; if (G_UNLIKELY (m_cursor > m_pinyin_len)) { m_cursor = m_pinyin_len; if (updateSpecialPhrases ()) { update (); } else { updatePreeditText (); updateAuxiliaryText (); } } else { m_cursor = m_pinyin_len = m_pinyin.back ().begin; m_pinyin.pop_back (); updateSpecialPhrases (); updatePhraseEditor (); update (); } return TRUE; } gboolean DoublePinyinEditor::moveCursorRightByWord (void) { return moveCursorToEnd (); } gboolean DoublePinyinEditor::moveCursorToBegin (void) { if (G_UNLIKELY (m_cursor == 0)) return FALSE; m_cursor = 0; m_pinyin.clear (); m_pinyin_len = 0; updateSpecialPhrases (); updatePhraseEditor (); update (); return TRUE; } gboolean DoublePinyinEditor::moveCursorToEnd (void) { if (G_UNLIKELY (m_cursor == m_text.length ())) return FALSE; m_cursor = m_text.length (); if (updatePinyin (FALSE)) { updateSpecialPhrases (); updatePhraseEditor (); update (); } else { if (updateSpecialPhrases ()) { update (); } else { updatePreeditText (); updateAuxiliaryText (); } } return TRUE; } void DoublePinyinEditor::reset (void) { PinyinEditor::reset (); } inline const Pinyin * DoublePinyinEditor::isPinyin (gint i) { if ((m_config.option () & PINYIN_INCOMPLETE_PINYIN) == 0) { return NULL; } gint8 sheng = ID_TO_SHENG (i); if (sheng == PINYIN_ID_VOID) { return NULL; } return PinyinParser::isPinyin (sheng, 0, PINYIN_INCOMPLETE_PINYIN); } inline const Pinyin * DoublePinyinEditor::isPinyin (gint i, gint j) { const Pinyin *pinyin; gint8 sheng = ID_TO_SHENG (i); const gint8 *yun = ID_TO_YUNS (j); if (sheng == PINYIN_ID_VOID || yun[0] == PINYIN_ID_VOID) return NULL; if (sheng == PINYIN_ID_ZERO && yun[0] == PINYIN_ID_ZERO) return NULL; if (yun[1] == PINYIN_ID_VOID) { return PinyinParser::isPinyin (sheng, yun[0], m_config.option () & (PINYIN_FUZZY_ALL | PINYIN_CORRECT_V_TO_U)); } pinyin = PinyinParser::isPinyin (sheng, yun[0], m_config.option () & (PINYIN_FUZZY_ALL)); if (pinyin == NULL) pinyin = PinyinParser::isPinyin (sheng, yun[1], m_config.option () & (PINYIN_FUZZY_ALL)); if (pinyin != NULL) return pinyin; /* if sheng == j q x y and yun == v, try to correct v to u */ if ((m_config.option () & PINYIN_CORRECT_V_TO_U) == 0) return NULL; if (yun[0] != PINYIN_ID_V && yun[1] != PINYIN_ID_V) return NULL; switch (sheng) { case PINYIN_ID_J: case PINYIN_ID_Q: case PINYIN_ID_X: case PINYIN_ID_Y: return PinyinParser::isPinyin (sheng, PINYIN_ID_V, m_config.option () & (PINYIN_FUZZY_ALL | PINYIN_CORRECT_V_TO_U)); default: return NULL; } } inline gboolean DoublePinyinEditor::updatePinyin (gboolean all) { gboolean retval = FALSE; if (all && (m_pinyin_len != 0 || !m_pinyin.empty ())) { m_pinyin.clear (); m_pinyin_len = 0; retval = TRUE; } if (m_pinyin_len > m_cursor) { retval = TRUE; while (m_pinyin_len > m_cursor) { m_pinyin_len = m_pinyin.back ().begin; m_pinyin.pop_back (); } } if (m_pinyin_len == m_cursor) { return retval; } if (m_pinyin_len < m_cursor) { guint len = m_pinyin_len; if (m_pinyin.empty () == FALSE && m_pinyin.back ()->flags & PINYIN_INCOMPLETE_PINYIN) { const Pinyin *pinyin = isPinyin (ID (m_text[m_pinyin_len -1]),ID (m_text[m_pinyin_len])); if (pinyin) { m_pinyin.pop_back (); m_pinyin.append (pinyin, m_pinyin_len - 1, 2); m_pinyin_len += 1; } } while (m_pinyin_len < m_cursor && m_pinyin.size () < MAX_PHRASE_LEN) { const Pinyin *pinyin = NULL; if (m_pinyin_len == m_cursor - 1) { pinyin = isPinyin (ID (m_text[m_pinyin_len])); } else { pinyin = isPinyin (ID (m_text[m_pinyin_len]), ID (m_text[m_pinyin_len + 1])); if (pinyin == NULL) pinyin = isPinyin (ID (m_text[m_pinyin_len])); } if (pinyin == NULL) break; if (pinyin->flags & PINYIN_INCOMPLETE_PINYIN) { m_pinyin.append (pinyin, m_pinyin_len, 1); m_pinyin_len += 1; } else { m_pinyin.append (pinyin, m_pinyin_len, 2); m_pinyin_len += 2; } } if (len == m_pinyin_len) return retval; return TRUE; } return retval; } void DoublePinyinEditor::updateAuxiliaryTextAfter (String &buffer) { if (G_LIKELY (!m_config.doublePinyinShowRaw ())) return; if (G_LIKELY (m_config.orientation () == IBUS_ORIENTATION_HORIZONTAL)) { buffer << " [ "; } else { buffer << "\n[ "; } if (G_LIKELY (m_cursor == m_text.length ())) { m_buffer << m_text << " ]"; } else { buffer.append (m_text.c_str (), m_cursor); buffer << " "; buffer.append (m_text.c_str () + m_cursor); buffer << " ]"; } } gboolean DoublePinyinEditor::processKeyEvent (guint keyval, guint keycode, guint modifiers) { /* handle ';' key */ if (G_UNLIKELY (keyval == IBUS_semicolon)) { if (cmshm_filter (modifiers) == 0) { if (insert (keyval)) return TRUE; } } return PinyinEditor::processKeyEvent (keyval, keycode, modifiers); } };
412
0.631805
1
0.631805
game-dev
MEDIA
0.566762
game-dev,desktop-app
0.964167
1
0.964167
ogclub02/OGCLUB-LEAKS
80,369
Gamesense/Lua/vandal.lua
local vandal = { variables = { states = { "default", "standing", "moving", "in air", "slowwalking", "crouching", "crouch moving", "crouch in air" }, minified_states = { "STA", "MOV", "AIR", "SW", "DU", "DUM", "AD" }, references = { enabled = ui.reference("AA", "Anti-aimbot angles", "Enabled"), pitch = {ui.reference("AA", "Anti-aimbot angles", "Pitch")}, yaw_base = ui.reference("AA", "Anti-aimbot angles", "Yaw base"), yaw = {ui.reference("AA", "Anti-aimbot angles", "Yaw")}, yaw_jitter = {ui.reference("AA", "Anti-aimbot angles", "Yaw jitter")}, body_yaw = {ui.reference("AA", "Anti-aimbot angles", "Body yaw")}, freestanding_body_yaw = ui.reference("AA", "Anti-aimbot angles", "Freestanding body yaw"), edge_yaw = ui.reference("AA", "Anti-aimbot angles", "Edge yaw"), freestanding = {ui.reference("AA", "Anti-aimbot angles", "Freestanding")}, roll = ui.reference("AA", "Anti-aimbot angles", "Roll"), keybinds = { items = { double_tap = {ui.reference("RAGE", "Aimbot", "Double tap")}, hide_shots = {ui.reference("AA", "Other", "On shot anti-aim")}, slowwalk = {ui.reference("AA", "Other", "Slow Motion")}, force_body = ui.reference("RAGE", "Aimbot", "Force body aim"), quick_peek = {ui.reference("RAGE", "Other", "Quick peek assist")}, minumum_damage_override = {ui.reference("RAGE", "Aimbot", "Minimum damage override")}, force_safe_point = ui.reference("RAGE", "Aimbot", "Force safe point") } }, other = { items = { leg_movement = ui.reference("AA", "Other", "Leg movement") } } }, visuals = { generation = { angle = 0, damage = 0, backtrack = 0, best_position = nil, dangerous = false, avoiding = false }, user = obex_fetch and obex_fetch() or { username = "Svvayyz", build = "Source", discord = "" }, crosshair = { text_alpha = 255, text_alpha_2 = 155, step = 1 }, watermark = {}, notifications = {} }, anti_aim = { var = { side = -1 }, anti_bruteforce = { activated = 0, angle = 0, phase = 1 }, defensive = { ticks_left = 0, last_simtime = 0, max_ticks = 12 }, manuals = { cache = { left = false, right = false, forward = false }, left = false, right = false, forward = false }, generation = { yaw = 0, head_size_in_yaw = 90, data = {} } }, settings = { var = json.parse(database.read("vandal-settings") or "{}"), old_set = "", names = {} } }, liblaries = { vector = require("vector"), entity = require("gamesense/entity"), base64 = require("gamesense/base64"), antiaim = require("gamesense/antiaim_funcs"), clipboard = require("gamesense/clipboard"), weapons = require("gamesense/csgo_weapons"), engineclient = require("gamesense/engineclient"), http = require("gamesense/http") }, menu = { enabled = ui.new_checkbox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - ena\a78BBF9FFbled"), tab = ui.new_combobox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - \a78BBF9FFtab", {"anti-aim", "visuals", "misc", "settings"}), anti_aim = {}, visuals = { elements = ui.new_multiselect("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - \a78BBF9FFelements", {"crosshair", "watermark", "arrows", "notifications"}), primary_color = ui.new_color_picker("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - primary \a78BBF9FFcolor", 120, 187, 249, 200), secondary_color = ui.new_color_picker("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - secondary \a78BBF9FFcolor", 232, 204, 21, 200), glow_amount = ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - notifications glow \a78BBF9FFamount", 3, 5, 3, true, "px"), arrows_offset = ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - arrows \a78BBF9FFoffset", -100, 20, 0, true, "px"), spready_arrows = ui.new_checkbox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - spready \a78BBF9FFarrows"), customize_text = ui.new_checkbox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - custom crosshair \a78BBF9FFtext"), custom_text = ui.new_textbox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - custom crosshair \a78BBF9FFtext"), custom_text_2 = ui.new_textbox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - custom crosshair \a78BBF9FFtext #2") }, misc = { manual_forward = ui.new_hotkey("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - manual \a78BBF9FFforward"), manual_left = ui.new_hotkey("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - manual \a78BBF9FFleft"), manual_right = ui.new_hotkey("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - manual \a78BBF9FFright"), freestanding = ui.new_hotkey("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - free\a78BBF9FFstanding"), anti_backstab = ui.new_checkbox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - anti \a78BBF9FFbackstab"), freestanding_disablers = ui.new_multiselect("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - freestanding \a78BBF9FFdisablers", {"in air", "crouch", "manuals"}), yaw_disablers = ui.new_multiselect("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - yaw \a78BBF9FFdisablers", {"freestanding", "manuals", "knife in air"}), animbreakers = ui.new_multiselect("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - animation \a78BBF9FFbreakers", {"legbreaker", "static legs in air", "moonwalk in air", "body lean"}), resolver_enabled = ui.new_checkbox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - resolver \a78BBF9FFenabled") }, settings = {} }, math = { pi = 180 / math.pi }, utils = { table_contains = function(table, content) for i=1, #table do if table[i] == content then return true end end return false end, phase_to_int = function(phase) return tonumber(phase:sub(2,2)) end, normalize_yaw = function(yaw) while yaw > 180 do yaw = yaw - 360 end while yaw < -180 do yaw = yaw + 360 end return yaw end, get_fake_amount = function() return entity.get_prop(entity.get_local_player(), "m_flPoseParameter", 11) * 120 - 60 end, clamp = function(value, min, max) if value > max then value = max end if value < min then value = min end return value end, rgba_to_hex = function(r, g, b, a) return string.format("%02x%02x%02x%02x", r, g, b, a) end, time_to_ticks = function(time) return math.floor(0.5 + (time / globals.tickinterval())) end, ticks_to_time = function(ticks) return ticks * globals.tickinterval() end }, generation = {}, resolver = { helpers = { }, data = { side = {} } } } vandal.resolver.helpers.refresh_data = function() vandal.liblaries.http.get("https://vandal.vip/data/resolver.txt", function(success, response) local s, e = pcall(function() json.parse(response.body) end) if not s then return false end vandal.resolver.data = json.parse(response.body) return true end) end local t = vandal.resolver.helpers.refresh_data() and "" or vandal.resolver.helpers.refresh_data() vandal.utils.gradient_text = function(text, w, h, r1, g1, b1, a1, r2, g2, b2, a2) local delta_r, delta_g, delta_b, delta_a, final_text, text_len = r1 - r2, g1 - g2, b1 - b2, a1 - a2, "", string.len(text) for i=1, text_len do final_text = ""..final_text.."\a"..vandal.utils.rgba_to_hex(r1 - (i * (delta_r / text_len)), g1 - (i * (delta_g / text_len)), b1 - (i * (delta_b / text_len)), a1 - (i * (delta_a / #text)))..""..text:sub(i, i).."" end renderer.text(w, h, 255, 255, 255, 255, "-", 0, final_text) end vandal.utils.get_side = function() return vandal.utils.get_fake_amount() > 1 and -1 or 1 end vandal.utils.should_anti_knife = function() local enemies = entity.get_players(true) for i=1, #enemies do local dist = vandal.liblaries.vector(entity.get_origin(enemies[i])):dist2d(vandal.liblaries.vector(entity.get_origin(entity.get_local_player()))) if entity.get_classname(entity.get_player_weapon(enemies[i])) == "CKnife" and dist < 100 then return true and ui.get(vandal.menu.misc.anti_backstab) end end return false end vandal.utils.get_manual_yaw = function() if vandal.variables.anti_aim.manuals.forward then return 180 elseif vandal.variables.anti_aim.manuals.left then return -90 elseif vandal.variables.anti_aim.manuals.right then return 90 elseif vandal.utils.should_anti_knife() then return 180 end return 0 end vandal.utils.notify = function(string) vandal.variables.visuals.notifications[#vandal.variables.visuals.notifications + 1] = {text = string, start = globals.realtime(), alpha = 0, progress = 0} end vandal.math.calc_angle = function(src, dst) local delta = vandal.liblaries.vector((src.x - dst.x), (src.y - dst.y), (src.z - dst.z)) local hyp = math.sqrt(delta.x * delta.x + delta.y * delta.y) return vandal.liblaries.vector(vandal.math.pi * math.atan(delta.z / hyp), vandal.math.pi * math.atan(delta.y / delta.x), 0) end vandal.state = { get = function(player) local data = { velocity = vandal.liblaries.vector(entity.get_prop(player, "m_vecVelocity")):length2d(), is_in_air = bit.band(entity.get_prop(player, "m_fFlags"), 1) == 0, is_crouching = bit.band(entity.get_prop(player, "m_fFlags"), bit.lshift(1, 1)) ~= 0, is_slowwalking = ui.get(vandal.variables.references.keybinds.items.slowwalk[2]) } if data.velocity < 2 and not data.is_in_air and not data.is_crouching then return 2 elseif data.velocity > 2 and not data.is_in_air and not data.is_slowwalking and not data.is_crouching then return 3 elseif not data.is_crouching and data.is_in_air then return 4 elseif data.is_slowwalking and not data.is_in_air and not data.is_crouching then return 5 elseif data.is_crouching and data.velocity < 2 and not data.is_in_air then return 6 elseif data.is_crouching and data.velocity > 2 and not data.is_in_air then return 7 elseif data.is_crouching and data.is_in_air then return 8 end return 2 end } vandal.utils.should_freestand = function() local boolean = vandal.state.get(entity.get_local_player()) == 4 and vandal.utils.table_contains(ui.get(vandal.menu.misc.freestanding_disablers), "in air") or vandal.state.get(entity.get_local_player()) == 7 and vandal.utils.table_contains(ui.get(vandal.menu.misc.freestanding_disablers), "in air") or vandal.state.get(entity.get_local_player()) == 6 and vandal.utils.table_contains(ui.get(vandal.menu.misc.freestanding_disablers), "crouch") or vandal.utils.get_manual_yaw() ~= 0 and vandal.utils.table_contains(ui.get(vandal.menu.misc.freestanding_disablers), "manuals") return not boolean end vandal.utils.should_jitter = function() local boolean = vandal.utils.table_contains(ui.get(vandal.menu.misc.yaw_disablers), "freestanding") and vandal.utils.should_freestand() and ui.get(vandal.menu.misc.freestanding) or vandal.utils.table_contains(ui.get(vandal.menu.misc.yaw_disablers), "manuals") and vandal.utils.get_manual_yaw() ~= 0 or vandal.utils.table_contains(ui.get(vandal.menu.misc.yaw_disablers), "knife in air") and entity.get_classname(entity.get_player_weapon(entity.get_local_player())) == "CKnife" and vandal.state.get(entity.get_local_player()) == 8 return not boolean end vandal.resolver.helpers.angle_mod = function(angle) return ((360 / 65536) * (angle * (65536 / 360))) end vandal.resolver.helpers.approach_angle = function(target, value, speed) local adjusted_speed = speed if adjusted_speed < 0.0 then adjusted_speed = adjusted_speed * -1 end local angle_mod_target = vandal.resolver.helpers.angle_mod(target) local angle_mod_value = vandal.resolver.helpers.angle_mod(value) local delta = angle_mod_target - angle_mod_value if delta >= -180 then if delta >= 180 then delta = delta - 360 end else if delta <= -180 then delta = delta + 360 end end local ret = 0 if delta <= adjusted_speed then if (adjusted_speed * -1) <= delta then ret = angle_mod_target else ret = (angle_mod_value - adjusted_speed) end else ret = angle_mod_value + adjusted_speed end return ret end vandal.resolver.helpers.angle_diff = function(dest_angle, src_angle) local delta = math.fmod(dest_angle - src_angle, 360) if dest_angle > src_angle then if delta >= 180 then delta = delta - 360 end else if delta <= -180 then delta = delta + 360 end end return delta end vandal.resolver.helpers.get_side = function(player, animlayer) local left_best_delta, right_best_delta = 9999, 9999 for i=1, #vandal.resolver.data.side[1] do local left_delta = math.abs(animlayer.playback_rate - vandal.resolver.data.side[1][i]) if left_delta < left_best_delta then left_best_delta = left_delta end end for i=1, #vandal.resolver.data.side[2] do local right_delta = math.abs(animlayer.playback_rate - vandal.resolver.data.side[2][i]) if right_delta < right_best_delta then right_best_delta = right_delta end end return left_best_delta < right_best_delta and -1 or 1 end vandal.resolver.helpers.process_side = function(player, side) if vandal.resolver.data[player].misses then if vandal.resolver.data[player].misses % 2 == 1 then side = side * -1 end end return side end vandal.menu.state_selection = ui.new_combobox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - \a78BBF9FFstate", vandal.variables.states) for i=1, #vandal.variables.states do vandal.menu.anti_aim[i] = { enabled = ui.new_checkbox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - \a78BBF9FFenabled"), stuff = { pitch = ui.new_combobox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - \a78BBF9FFpitch", {"off", "default", "up", "down", "minimal", "random", "custom", "exploit"}), custom_pitch = ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - custom \a78BBF9FFpitch", -89, 89, 0), yaw_base = ui.new_combobox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - yaw \a78BBF9FFbase", {"local view", "at targets"}), yaw = ui.new_combobox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - yaw \a78BBF9FFbase", {"off", "180", "spin", "static", "180 Z", "crosshair"}), yaw_amount_left = ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - yaw amount \a78BBF9FFleft", -180, 180, 0), yaw_amount_right = ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - yaw amount \a78BBF9FFright", -180, 180, 0), yaw_jitter = ui.new_combobox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - yaw \a78BBF9FFjitter", {"off", "offset", "center", "random", "skitter", "delayed"}), yaw_jitter_delay = ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - jitter \a78BBF9FFdelay", 1, 64, 0), yaw_jitter_amount = ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - yaw \a78BBF9FFjitter", -180, 180, 0), yaw_jitter_amount_2 = ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - yaw \a78BBF9FFjitter #2", -180, 180, 0), body_yaw = ui.new_combobox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - body \a78BBF9FFyaw", {"off", "opposite", "jitter", "static"}), body_yaw_amount = ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - body \a78BBF9FFyaw amount", -180, 180, 0), avoidness = ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - avoidness \a78BBF9FFpercentage", 0, 100, 20), anti_bruteforce_type = ui.new_combobox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - anti-bruteforce \a78BBF9FFtype", {"off", "yaw-generation", "jitter-generation", "custom"}), jitter_generation_limit = ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - generation angle \a78BBF9FFlimit", 0, 180, 90), anti_bruteforce_phase = ui.new_combobox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - anti-bruteforce \a78BBF9FFphase", {"#1", "#2", "#3", "#4", "#5"}), anti_bruteforce = { ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - jitter value \a78BBF9FF#1", -180, 180, 0), ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - jitter value \a78BBF9FF#2", -180, 180, 0), ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - jitter value \a78BBF9FF#3", -180, 180, 0), ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - jitter value \a78BBF9FF#4", -180, 180, 0), ui.new_slider("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - jitter value \a78BBF9FF#5", -180, 180, 0) }, defensive_flicks = ui.new_combobox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - "..vandal.variables.states[i].." - defensive flicks \a78BBF9FFtype", {"off", "highest-damage"}) } } end vandal.utils.export_settings = function() local settings = {} for i=1, #vandal.variables.states do local state = vandal.variables.states[i] settings[state] = {} for i2,v in pairs(vandal.menu.anti_aim[i].stuff) do settings[state][i2] = {} settings[state]["enabled"] = ui.get(vandal.menu.anti_aim[i].enabled) if type(v) == "table" then for i3, v2 in pairs(v) do settings[state][i2][i3] = ui.get(v2) end else settings[state][i2] = ui.get(v) end end end return vandal.liblaries.base64.encode(json.stringify(settings)) end vandal.utils.import_settings = function(setts) local settings = json.parse(vandal.liblaries.base64.decode(setts)) for i=1, #vandal.variables.states do local state = vandal.variables.states[i] for i2,v in pairs(vandal.menu.anti_aim[i].stuff) do local s, e = pcall(function() ui.set(vandal.menu.anti_aim[i].enabled, settings[state]["enabled"]) end) if type(v) == "table" then for i3, v2 in pairs(v) do local s, e = pcall(function() ui.set(v2, settings[state][i2][i3]) end) end else local s, e = pcall(function() ui.set(v, settings[state][i2]) end) end end end end vandal.menu.settings = { selection = ui.new_listbox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - settings \a78BBF9FFselection", vandal.variables.settings.names), name = ui.new_textbox("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - settings \a78BBF9FFname") } vandal.utils.refresh_settings = function(write) vandal.variables.settings.names = {} for i, v in pairs(vandal.variables.settings.var) do if v ~= nil then vandal.variables.settings.names[#vandal.variables.settings.names + 1] = i end end ui.update(vandal.menu.settings.selection, vandal.variables.settings.names) if write then database.write("vandal-settings", json.stringify(vandal.variables.settings.var)) if ui.get(vandal.menu.settings.selection) ~= nil then local num = tonumber(ui.get(vandal.menu.settings.selection)) + 1 ui.set(vandal.menu.settings.name, vandal.variables.settings.names[num]) end end end vandal.utils.refresh_settings(false) vandal.menu.settings.load_settings = ui.new_button("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - load \a78BBF9FFsettings", function() local success, e = pcall(function() vandal.utils.import_settings(vandal.variables.settings.var[ui.get(vandal.menu.settings.name)]) end) vandal.utils.notify(success and "settings loaded successfully" or "failed to load settings") end) vandal.menu.settings.save_settings = ui.new_button("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - save \a78BBF9FFsettings", function() vandal.variables.settings.var[ui.get(vandal.menu.settings.name)] = vandal.utils.export_settings() vandal.utils.notify("saved settings") vandal.utils.refresh_settings(true) end) vandal.menu.settings.delete_settings = ui.new_button("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - delete \a78BBF9FFsettings", function() vandal.variables.settings.var[ui.get(vandal.menu.settings.name)] = nil vandal.utils.notify("deleted settings") vandal.utils.refresh_settings(true) end) vandal.menu.settings.reset_settings = ui.new_button("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - reset \a78BBF9FFsettings", function() vandal.variables.settings.var[ui.get(vandal.menu.settings.name)] = "eyJtb3ZpbmciOnsieWF3X2Jhc2UiOiJsb2NhbCB2aWV3IiwiYm9keV95YXdfYW1vdW50IjowLCJwaXRjaCI6Im9mZiIsImF2b2lkbmVzcyI6MCwiYm9keV95YXciOiJvZmYiLCJhbnRpX2JydXRlZm9yY2VfcGhhc2UiOiIjMSIsInlhdyI6Im9mZiIsInlhd19hbW91bnQiOjAsImFudGlfYnJ1dGVmb3JjZV90eXBlIjoib2ZmIiwiaml0dGVyX2dlbmVyYXRpb25fbGltaXQiOjkwLCJleHRyYXBvbGF0aW9uIjowLCJ5YXdfaml0dGVyX2Ftb3VudCI6MCwieWF3X2ppdHRlciI6Im9mZiIsImVuYWJsZWQiOmZhbHNlLCJhbnRpX2JydXRlZm9yY2UiOlswLDAsMCwwLDBdLCJkZWZlbnNpdmVfZmxpY2tzIjoib2ZmIn0sImluIGFpciI6eyJ5YXdfYmFzZSI6ImxvY2FsIHZpZXciLCJib2R5X3lhd19hbW91bnQiOjAsInBpdGNoIjoib2ZmIiwiYXZvaWRuZXNzIjowLCJib2R5X3lhdyI6Im9mZiIsImFudGlfYnJ1dGVmb3JjZV9waGFzZSI6IiMxIiwieWF3Ijoib2ZmIiwieWF3X2Ftb3VudCI6MCwiYW50aV9icnV0ZWZvcmNlX3R5cGUiOiJvZmYiLCJqaXR0ZXJfZ2VuZXJhdGlvbl9saW1pdCI6OTAsImV4dHJhcG9sYXRpb24iOjAsInlhd19qaXR0ZXJfYW1vdW50IjowLCJ5YXdfaml0dGVyIjoib2ZmIiwiZW5hYmxlZCI6ZmFsc2UsImFudGlfYnJ1dGVmb3JjZSI6WzAsMCwwLDAsMF0sImRlZmVuc2l2ZV9mbGlja3MiOiJvZmYifSwic2xvd3dhbGtpbmciOnsieWF3X2Jhc2UiOiJsb2NhbCB2aWV3IiwiYm9keV95YXdfYW1vdW50IjowLCJwaXRjaCI6Im9mZiIsImF2b2lkbmVzcyI6MCwiYm9keV95YXciOiJvZmYiLCJhbnRpX2JydXRlZm9yY2VfcGhhc2UiOiIjMSIsInlhdyI6Im9mZiIsInlhd19hbW91bnQiOjAsImFudGlfYnJ1dGVmb3JjZV90eXBlIjoib2ZmIiwiaml0dGVyX2dlbmVyYXRpb25fbGltaXQiOjkwLCJleHRyYXBvbGF0aW9uIjowLCJ5YXdfaml0dGVyX2Ftb3VudCI6MCwieWF3X2ppdHRlciI6Im9mZiIsImVuYWJsZWQiOmZhbHNlLCJhbnRpX2JydXRlZm9yY2UiOlswLDAsMCwwLDBdLCJkZWZlbnNpdmVfZmxpY2tzIjoib2ZmIn0sImNyb3VjaCBpbiBhaXIiOnsieWF3X2Jhc2UiOiJsb2NhbCB2aWV3IiwiYm9keV95YXdfYW1vdW50IjowLCJwaXRjaCI6Im9mZiIsImF2b2lkbmVzcyI6MCwiYm9keV95YXciOiJvZmYiLCJhbnRpX2JydXRlZm9yY2VfcGhhc2UiOiIjMSIsInlhdyI6Im9mZiIsInlhd19hbW91bnQiOjAsImFudGlfYnJ1dGVmb3JjZV90eXBlIjoib2ZmIiwiaml0dGVyX2dlbmVyYXRpb25fbGltaXQiOjkwLCJleHRyYXBvbGF0aW9uIjowLCJ5YXdfaml0dGVyX2Ftb3VudCI6MCwieWF3X2ppdHRlciI6Im9mZiIsImVuYWJsZWQiOmZhbHNlLCJhbnRpX2JydXRlZm9yY2UiOlswLDAsMCwwLDBdLCJkZWZlbnNpdmVfZmxpY2tzIjoib2ZmIn0sImNyb3VjaGluZyI6eyJ5YXdfYmFzZSI6ImxvY2FsIHZpZXciLCJib2R5X3lhd19hbW91bnQiOjAsInBpdGNoIjoib2ZmIiwiYXZvaWRuZXNzIjowLCJib2R5X3lhdyI6Im9mZiIsImFudGlfYnJ1dGVmb3JjZV9waGFzZSI6IiMxIiwieWF3Ijoib2ZmIiwieWF3X2Ftb3VudCI6MCwiYW50aV9icnV0ZWZvcmNlX3R5cGUiOiJvZmYiLCJqaXR0ZXJfZ2VuZXJhdGlvbl9saW1pdCI6OTAsImV4dHJhcG9sYXRpb24iOjAsInlhd19qaXR0ZXJfYW1vdW50IjowLCJ5YXdfaml0dGVyIjoib2ZmIiwiZW5hYmxlZCI6ZmFsc2UsImFudGlfYnJ1dGVmb3JjZSI6WzAsMCwwLDAsMF0sImRlZmVuc2l2ZV9mbGlja3MiOiJvZmYifSwic3RhbmRpbmciOnsieWF3X2Jhc2UiOiJsb2NhbCB2aWV3IiwiYm9keV95YXdfYW1vdW50IjowLCJwaXRjaCI6Im9mZiIsImF2b2lkbmVzcyI6MCwiYm9keV95YXciOiJvZmYiLCJhbnRpX2JydXRlZm9yY2VfcGhhc2UiOiIjMSIsInlhdyI6Im9mZiIsInlhd19hbW91bnQiOjAsImFudGlfYnJ1dGVmb3JjZV90eXBlIjoib2ZmIiwiaml0dGVyX2dlbmVyYXRpb25fbGltaXQiOjkwLCJleHRyYXBvbGF0aW9uIjowLCJ5YXdfaml0dGVyX2Ftb3VudCI6MCwieWF3X2ppdHRlciI6Im9mZiIsImVuYWJsZWQiOmZhbHNlLCJhbnRpX2JydXRlZm9yY2UiOlswLDAsMCwwLDBdLCJkZWZlbnNpdmVfZmxpY2tzIjoib2ZmIn0sImRlZmF1bHQiOnsieWF3X2Jhc2UiOiJsb2NhbCB2aWV3IiwiYm9keV95YXdfYW1vdW50IjowLCJwaXRjaCI6Im9mZiIsImF2b2lkbmVzcyI6MCwiYm9keV95YXciOiJvZmYiLCJhbnRpX2JydXRlZm9yY2VfcGhhc2UiOiIjMSIsInlhdyI6Im9mZiIsInlhd19hbW91bnQiOjAsImFudGlfYnJ1dGVmb3JjZV90eXBlIjoib2ZmIiwiaml0dGVyX2dlbmVyYXRpb25fbGltaXQiOjkwLCJleHRyYXBvbGF0aW9uIjowLCJ5YXdfaml0dGVyX2Ftb3VudCI6MCwieWF3X2ppdHRlciI6Im9mZiIsImVuYWJsZWQiOnRydWUsImFudGlfYnJ1dGVmb3JjZSI6WzAsMCwwLDAsMF0sImRlZmVuc2l2ZV9mbGlja3MiOiJvZmYifX0=" vandal.utils.notify("resetted settings") vandal.utils.refresh_settings(true) end) vandal.menu.settings.export_settings = ui.new_button("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - export to \a78BBF9FFclipboard", function() vandal.liblaries.clipboard.set(vandal.utils.export_settings()) vandal.utils.notify("exported settings") end) vandal.menu.settings.import_settings = ui.new_button("AA", "Anti-aimbot angles", "\a78BBF9FFvandal\aE8CC15FF.tech\aFFFFFFB2 - import from \a78BBF9FFclipboard", function() local success, e = pcall(function() vandal.utils.import_settings(vandal.liblaries.clipboard.get()) end) vandal.utils.notify(success and "settings imported successfully" or "failed to import settings") end) local function process_settings() if ui.get(vandal.menu.settings.selection) ~= nil and vandal.variables.settings.old_set ~= ui.get(vandal.menu.settings.selection) then local num = tonumber(ui.get(vandal.menu.settings.selection)) + 1 ui.set(vandal.menu.settings.name, vandal.variables.settings.names[num]) vandal.variables.settings.old_set = ui.get(vandal.menu.settings.selection) end end vandal.generation.get_lerp_time = function() local minupdate, maxupdate = cvar.sv_minupdaterate:get_float(), cvar.sv_maxupdaterate:get_float() local ratio = cvar.cl_interp_ratio:get_float() == 0.0 and 1.0 or cvar.cl_interp_ratio:get_float() local lerp = cvar.cl_interp:get_float() local cmin, cmax = cvar.sv_client_min_interp_ratio:get_float(), cvar.sv_client_max_interp_ratio:get_float() if cmin ~= 1 then ratio = vandal.utils.clamp(ratio, cmin, cmax) end return math.max(lerp, ratio / maxupdate) end vandal.generation.get_backtrack_ticks = function(player) local net_channel = vandal.liblaries.engineclient.get_net_channel_info() local sv_maxunlag = cvar.sv_maxunlag:get_float() local correct = vandal.utils.clamp(vandal.generation.get_lerp_time() + net_channel.avg_latency[0] + net_channel.avg_latency[1], 0, sv_maxunlag) local best_ticks, best_dmg = 0, 0 for i=1, 64 do if vandal.variables.anti_aim.generation.data[globals.tickcount() - i] then if math.abs(correct - (globals.curtime() - vandal.variables.anti_aim.generation.data[globals.tickcount() - i].simtime)) < sv_maxunlag + net_channel.avg_latency[0] + net_channel.avg_latency[1] then local head_pos = vandal.variables.anti_aim.generation.data[globals.tickcount() - i].head_pos local enemy_head_pos = vandal.liblaries.vector(entity.hitbox_position(player, 0)) local ent, dmg = client.trace_bullet(player, enemy_head_pos.x, enemy_head_pos.y, enemy_head_pos.z, head_pos.x, head_pos.y, head_pos.z, player) if dmg >= best_dmg then best_ticks = i best_dmg = dmg end end end end vandal.variables.visuals.generation.backtrack = best_ticks return best_ticks end vandal.generation.calculate_damage = function(player, angle) local net_channel = vandal.liblaries.engineclient.get_net_channel_info() local head_pos = vandal.liblaries.vector(entity.hitbox_position(entity.get_local_player(), 0)) local enemy_head_pos = vandal.liblaries.vector(entity.hitbox_position(player, 0)) local origin = vandal.liblaries.vector(entity.get_origin(entity.get_local_player())) local rad = origin:dist2d(head_pos) origin.z = head_pos.z origin = origin - (vandal.liblaries.vector(entity.get_prop(entity.get_local_player()), "m_vecVelocity") * vandal.utils.time_to_ticks(net_channel.latency[0] + net_channel.latency[1])) local angles = vandal.liblaries.vector():init_from_angles(0, angle + vandal.variables.anti_aim.generation.yaw, 0) * rad local final_pos = origin + angles local final_enemy_pos = enemy_head_pos + vandal.math.calc_angle(enemy_head_pos, final_pos) local ent, damage = client.trace_bullet(player, final_enemy_pos.x, final_enemy_pos.y, final_enemy_pos.z, final_pos.x, final_pos.y, final_pos.z, player) -- local x, y = renderer.world_to_screen(final_pos.x, final_pos.y, final_pos.z) -- renderer.text(x, y, damage > 0 and 255 or 0, damage > 0 and 0 or 255, 0, 255, "-", 0, damage) vandal.variables.visuals.generation.head_size_in_yaw = (4.2000004200000 * 4.5) / (vandal.liblaries.vector():init_from_angles(0, 1, 0) * rad):length2d() return damage, final_pos end vandal.generation.generate_angle = function(player, avoidness) if avoidness <= 10 then return 0 end vandal.variables.visuals.generation.dangerous = false local lowest_dmg, best_angle, best_position = 9999, 0, vandal.liblaries.vector(0, 0, 0) local percentage = (avoidness / 100) / 2 local step = math.floor(10 * (avoidness / 100)) -- 20 local range = 180 / step for i=-range, range do local angle = i * range local damage, position = vandal.generation.calculate_damage(player, angle, avoidness) if damage > 0 then vandal.variables.visuals.generation.dangerous = true end if damage < lowest_dmg or damage == lowest_dmg and best_angle > 0 and angle < best_angle or damage == lowest_dmg and best_angle < 0 and best_angle < angle then lowest_dmg = damage best_angle = angle best_position = position end end for i=best_angle - (range - 1), best_angle + (range - 1) do if avoidness == 100 or i % (1 / percentage) == 1 then local damage, position = vandal.generation.calculate_damage(player, i, avoidness) if damage > 0 then vandal.variables.visuals.generation.dangerous = true end if damage < lowest_dmg or damage == lowest_dmg and best_angle > 0 and i < best_angle or damage == lowest_dmg and best_angle < 0 and best_angle < i then lowest_dmg = damage best_angle = i best_position = position end end end vandal.variables.visuals.generation.angle = math.floor(best_angle) vandal.variables.visuals.generation.damage = math.floor(lowest_dmg) vandal.variables.visuals.generation.best_position = best_position return vandal.utils.normalize_yaw(math.floor(best_angle + (vandal.variables.anti_aim.generation.head_size_in_yaw * best_angle))) end vandal.generation.generate_flick = function(player, avoidness) local best_dmg, best_angle = 0, 0 local percentage = avoidness / 100 for i=-180 * percentage, 180 * percentage do local damage = vandal.generation.calculate_damage(player, i, avoidness, 0) if damage > best_dmg then best_dmg = damage best_angle = i end end return vandal.utils.normalize_yaw(math.floor(best_angle + (vandal.variables.anti_aim.generation.head_size_in_yaw * best_angle))) end vandal.generation.generate_jitter = function(player, avoidness) local lowest_dmg, best_angle = 9999, 0 local percentage = avoidness / 100 for i=0, 180 * percentage do local damage, damage2 = vandal.generation.calculate_damage(player, i, avoidness), vandal.generation.calculate_damage(player, -i, avoidness) damage = damage + damage2 if damage < lowest_dmg or damage == lowest_dmg and best_angle > 0 and i < best_angle or damage == lowest_dmg and best_angle < 0 and best_angle < i then lowest_dmg = damage best_angle = i end end vandal.variables.visuals.generation.damage = lowest_dmg return vandal.utils.normalize_yaw(math.floor(best_angle + (vandal.variables.anti_aim.generation.head_size_in_yaw * best_angle))) end local function initialize_menu() ui.set(vandal.menu.visuals.customize_text, false) end initialize_menu() local function menu_handler() local lua_enabled = ui.get(vandal.menu.enabled) local lua_menu_enabled = not lua_enabled local lua_aa_enabled = lua_enabled and ui.get(vandal.menu.tab) == "anti-aim" local lua_visuals_enabled = lua_enabled and ui.get(vandal.menu.tab) == "visuals" local lua_misc_enabled = lua_enabled and ui.get(vandal.menu.tab) == "misc" local lua_settings_enabled = lua_enabled and ui.get(vandal.menu.tab) == "settings" for i, v in pairs(vandal.variables.references) do if type(v) == "table" then for i2, v2 in pairs(v) do if type(v2) == "table" then for i3, v3 in pairs(v2) do if not type(v3) == "table" then ui.set_visible(v3, lua_menu_enabled) end end else ui.set_visible(v2, lua_menu_enabled) end end else ui.set_visible(v, lua_menu_enabled) end end ui.set_visible(vandal.menu.tab, lua_enabled) ui.set_visible(vandal.menu.state_selection, lua_aa_enabled) for i,v in pairs(vandal.menu.visuals) do ui.set_visible(v, lua_visuals_enabled) end ui.set_visible(vandal.menu.visuals.arrows_offset, lua_visuals_enabled and vandal.utils.table_contains(ui.get(vandal.menu.visuals.elements), "arrows")) ui.set_visible(vandal.menu.visuals.spready_arrows, lua_visuals_enabled and vandal.utils.table_contains(ui.get(vandal.menu.visuals.elements), "arrows")) ui.set_visible(vandal.menu.visuals.glow_amount, lua_visuals_enabled and vandal.utils.table_contains(ui.get(vandal.menu.visuals.elements), "notifications")) ui.set_visible(vandal.menu.visuals.customize_text, lua_visuals_enabled and vandal.utils.table_contains(ui.get(vandal.menu.visuals.elements), "crosshair")) ui.set_visible(vandal.menu.visuals.custom_text, lua_visuals_enabled and ui.get(vandal.menu.visuals.customize_text) and vandal.utils.table_contains(ui.get(vandal.menu.visuals.elements), "crosshair")) ui.set_visible(vandal.menu.visuals.custom_text_2, lua_visuals_enabled and ui.get(vandal.menu.visuals.customize_text) and vandal.utils.table_contains(ui.get(vandal.menu.visuals.elements), "crosshair")) if not ui.get(vandal.menu.visuals.customize_text) then ui.set(vandal.menu.visuals.custom_text, "VANDAL") ui.set(vandal.menu.visuals.custom_text_2, "TECH") end for i,v in pairs(vandal.menu.misc) do ui.set_visible(v, lua_misc_enabled) end if not (vandal.variables.visuals.user.build == "Debug" or vandal.variables.visuals.user.build == "Private" or vandal.variables.visuals.user.build == "Source") then ui.set(vandal.menu.misc.resolver_enabled, false) ui.set_visible(vandal.menu.misc.resolver_enabled, false) end for i,v in pairs(vandal.menu.settings) do ui.set_visible(v, lua_settings_enabled) end for i=1, #vandal.variables.states do for i2,v in pairs(vandal.menu.anti_aim[i]) do if type(v) == "table" then for i3, v2 in pairs(v) do if type(v2) == "table" then for i4, v3 in pairs(v2) do ui.set_visible(v3, false) end else ui.set_visible(v2, false) end end else ui.set_visible(v, false) end end end for i=1, #vandal.variables.states do if ui.get(vandal.menu.state_selection) == vandal.variables.states[i] then ui.set_visible(vandal.menu.anti_aim[i].enabled, lua_aa_enabled) local state_enabled = ui.get(vandal.menu.anti_aim[i].enabled) and lua_aa_enabled ui.set_visible(vandal.menu.anti_aim[i].stuff.pitch, state_enabled) ui.set_visible(vandal.menu.anti_aim[i].stuff.custom_pitch, state_enabled and ui.get(vandal.menu.anti_aim[i].stuff.pitch) == "custom") ui.set_visible(vandal.menu.anti_aim[i].stuff.yaw_base, state_enabled) ui.set_visible(vandal.menu.anti_aim[i].stuff.yaw, state_enabled) ui.set_visible(vandal.menu.anti_aim[i].stuff.yaw_amount_left, state_enabled and ui.get(vandal.menu.anti_aim[i].stuff.yaw) ~= "off") ui.set_visible(vandal.menu.anti_aim[i].stuff.yaw_amount_right, state_enabled and ui.get(vandal.menu.anti_aim[i].stuff.yaw) ~= "off") ui.set_visible(vandal.menu.anti_aim[i].stuff.yaw_jitter, state_enabled) ui.set_visible(vandal.menu.anti_aim[i].stuff.yaw_jitter_delay, state_enabled and ui.get(vandal.menu.anti_aim[i].stuff.yaw_jitter) == "delayed") ui.set_visible(vandal.menu.anti_aim[i].stuff.yaw_jitter_amount, state_enabled and ui.get(vandal.menu.anti_aim[i].stuff.yaw_jitter) ~= "off") ui.set_visible(vandal.menu.anti_aim[i].stuff.yaw_jitter_amount_2, state_enabled and ui.get(vandal.menu.anti_aim[i].stuff.yaw_jitter) == "delayed") ui.set_visible(vandal.menu.anti_aim[i].stuff.body_yaw, state_enabled) ui.set_visible(vandal.menu.anti_aim[i].stuff.body_yaw_amount, state_enabled and ui.get(vandal.menu.anti_aim[i].stuff.body_yaw) ~= "off" and ui.get(vandal.menu.anti_aim[i].stuff.body_yaw) ~= "opposite") ui.set_visible(vandal.menu.anti_aim[i].stuff.avoidness, state_enabled) ui.set_visible(vandal.menu.anti_aim[i].stuff.anti_bruteforce_type, state_enabled) ui.set_visible(vandal.menu.anti_aim[i].stuff.jitter_generation_limit, state_enabled and ui.get(vandal.menu.anti_aim[i].stuff.anti_bruteforce_type) == "jitter-generation") ui.set_visible(vandal.menu.anti_aim[i].stuff.anti_bruteforce_phase, state_enabled and ui.get(vandal.menu.anti_aim[i].stuff.anti_bruteforce_type) == "custom") ui.set_visible(vandal.menu.anti_aim[i].stuff.anti_bruteforce[vandal.utils.phase_to_int(ui.get(vandal.menu.anti_aim[i].stuff.anti_bruteforce_phase))], state_enabled and ui.get(vandal.menu.anti_aim[i].stuff.anti_bruteforce_type) == "custom") ui.set_visible(vandal.menu.anti_aim[i].stuff.defensive_flicks, state_enabled) end end end local function anti_aim_handler() if not ui.get(vandal.menu.enabled) and ui.get(vandal.menu.anti_aim[1].enabled) then return end vandal.utils.should_anti_knife() local state = ui.get(vandal.menu.anti_aim[vandal.state.get(entity.get_local_player())].enabled) and vandal.state.get(entity.get_local_player()) or 1 if ui.get(vandal.menu.anti_aim[state].stuff.pitch) ~= "exploit" then ui.set(vandal.variables.references.pitch[1], ui.get(vandal.menu.anti_aim[state].stuff.pitch)) else if vandal.variables.anti_aim.defensive.ticks_left > 0 then ui.set(vandal.variables.references.pitch[1], ui.get(vandal.variables.references.pitch[1]) == "Down" and "up" or "down") else ui.set(vandal.variables.references.pitch[1], "down") end end ui.set(vandal.variables.references.pitch[2], ui.get(vandal.menu.anti_aim[state].stuff.custom_pitch)) ui.set(vandal.variables.references.yaw_base, ui.get(vandal.menu.anti_aim[state].stuff.yaw_base)) ui.set(vandal.variables.references.yaw[1], ui.get(vandal.menu.anti_aim[state].stuff.yaw)) local yaw = vandal.utils.get_side() == -1 and ui.get(vandal.menu.anti_aim[state].stuff.yaw_amount_left) or ui.get(vandal.menu.anti_aim[state].stuff.yaw_amount_right) if vandal.utils.should_jitter() then if ui.get(vandal.menu.anti_aim[state].stuff.yaw_jitter) == "delayed" and vandal.variables.anti_aim.anti_bruteforce.activated > 0.75 then ui.set(vandal.variables.references.yaw_jitter[1], "off") yaw = vandal.utils.normalize_yaw(yaw + (vandal.variables.anti_aim.var.side == -1 and ui.get(vandal.menu.anti_aim[state].stuff.yaw_jitter_amount) or ui.get(vandal.menu.anti_aim[state].stuff.yaw_jitter_amount_2))) else ui.set(vandal.variables.references.yaw_jitter[1], ui.get(vandal.menu.anti_aim[state].stuff.yaw_jitter) == "delayed" and "center" or ui.get(vandal.menu.anti_aim[state].stuff.yaw_jitter)) if ui.get(vandal.menu.anti_aim[state].stuff.anti_bruteforce_type) == "jitter-generation" and globals.realtime() - vandal.variables.anti_aim.anti_bruteforce.activated < 0.75 or ui.get(vandal.menu.anti_aim[state].stuff.anti_bruteforce_type) == "custom" and globals.realtime() - vandal.variables.anti_aim.anti_bruteforce.activated < 0.75 then ui.set(vandal.variables.references.yaw_jitter[2], vandal.utils.normalize_yaw(vandal.variables.anti_aim.anti_bruteforce.angle)) else ui.set(vandal.variables.references.yaw_jitter[2], ui.get(vandal.menu.anti_aim[state].stuff.yaw_jitter_amount)) end end ui.set(vandal.variables.references.body_yaw[1], globals.realtime() - vandal.variables.anti_aim.anti_bruteforce.activated < 0.75 and "Off" or ui.get(vandal.menu.anti_aim[state].stuff.body_yaw)) ui.set(vandal.variables.references.body_yaw[2], ui.get(vandal.menu.anti_aim[state].stuff.body_yaw_amount)) else ui.set(vandal.variables.references.yaw_jitter[1], "Off") ui.set(vandal.variables.references.body_yaw[1], "Off") end ui.set(vandal.variables.references.freestanding[1], vandal.utils.should_freestand() and ui.get(vandal.menu.misc.freestanding)) ui.set(vandal.variables.references.freestanding[2], ui.get(vandal.menu.misc.freestanding) and "Always on" or "Off hotkey") if ui.get(vandal.menu.anti_aim[state].stuff.yaw_jitter_delay) ~= 1 and globals.tickcount() % ui.get(vandal.menu.anti_aim[state].stuff.yaw_jitter_delay) == 1 or 1 == 1 then vandal.variables.anti_aim.var.side = vandal.variables.anti_aim.var.side * -1 end ui.set(vandal.variables.references.yaw[2], yaw) -- makes animfix put current animations on simulating the newest angle so we its easier to do avoidness if ui.get(vandal.menu.anti_aim[state].stuff.anti_bruteforce_type) == "yaw-generation" and globals.realtime() - vandal.variables.anti_aim.anti_bruteforce.activated < 0.75 then yaw = vandal.utils.normalize_yaw(yaw + vandal.variables.anti_aim.anti_bruteforce.angle + vandal.utils.get_manual_yaw()) else if client.current_threat() then if vandal.variables.anti_aim.defensive.ticks_left > 0 and ui.get(vandal.menu.anti_aim[state].stuff.defensive_flicks) == "highest-damage" then yaw = vandal.utils.normalize_yaw(vandal.generation.generate_flick(client.current_threat(), ui.get(vandal.menu.anti_aim[state].stuff.avoidness))) else yaw = vandal.utils.normalize_yaw(yaw + vandal.generation.generate_angle(client.current_threat(), ui.get(vandal.menu.anti_aim[state].stuff.avoidness)) + vandal.utils.get_manual_yaw()) end else yaw = vandal.utils.normalize_yaw(yaw + vandal.utils.get_manual_yaw()) end end ui.set(vandal.variables.references.yaw[2], yaw) end local function anti_bruteforce_handler(event) local enemy = client.userid_to_entindex(event.userid) local dist = vandal.liblaries.vector(entity.hitbox_position(entity.get_local_player(), 0)):dist2d(vandal.liblaries.vector(event.x, event.y, event.z)) if not entity.is_enemy(enemy) or not entity.is_alive(enemy) or not entity.is_alive(entity.get_local_player()) or dist > 300 or globals.realtime() - vandal.variables.anti_aim.anti_bruteforce.activated < 0.75 then return end local backtrack = vandal.generation.get_backtrack_ticks(enemy) local state = ui.get(vandal.menu.anti_aim[vandal.state.get(entity.get_local_player())].enabled) and vandal.state.get(entity.get_local_player()) or 1 if ui.get(vandal.menu.anti_aim[state].stuff.anti_bruteforce_type) == "off" then return end local angle = 0 if ui.get(vandal.menu.anti_aim[state].stuff.anti_bruteforce_type) == "yaw-generation" then angle = vandal.generation.generate_angle(enemy, 100) client.log("[vandal] generated yaw: "..angle.." (damage: "..vandal.variables.visuals.generation.damage.." bt: "..backtrack..")") elseif ui.get(vandal.menu.anti_aim[state].stuff.anti_bruteforce_type) == "jitter-generation" then angle = vandal.generation.generate_jitter(enemy, (ui.get(vandal.menu.anti_aim[state].stuff.jitter_generation_limit) / 180) * 100) client.log("[vandal] generated jitter: "..angle.." (damage: "..(vandal.variables.visuals.generation.damage / 2).." bt: "..backtrack..")") elseif ui.get(vandal.menu.anti_aim[state].stuff.anti_bruteforce_type) == "custom" then angle = ui.get(vandal.menu.anti_aim[state].stuff.anti_bruteforce[vandal.variables.anti_aim.anti_bruteforce.phase]) end vandal.variables.anti_aim.anti_bruteforce.activated = globals.realtime() vandal.variables.anti_aim.anti_bruteforce.angle = angle if ui.get(vandal.menu.anti_aim[state].stuff.anti_bruteforce_type) == "custom" then if vandal.variables.anti_aim.anti_bruteforce.phase >= 5 then vandal.variables.anti_aim.anti_bruteforce.phase = 1 else vandal.variables.anti_aim.anti_bruteforce.phase = vandal.variables.anti_aim.anti_bruteforce.phase + 1 end end vandal.utils.notify("anti-brute triggered due to shot by "..entity.get_player_name(enemy).." bt: "..backtrack.."t angle: "..angle.."°") end local function initialize_indicators() local w, h = client.screen_size() vandal.variables.visuals.watermark = { width = w / 2 - (61 / 2), height = h - 10 } end initialize_indicators() local function indicators_handler() local w, h = client.screen_size() local state = vandal.state.get(entity.get_local_player()) - 1 local main_r, main_g, main_b, main_a = ui.get(vandal.menu.visuals.primary_color) local sec_r, sec_g, sec_b, sec_a = ui.get(vandal.menu.visuals.secondary_color) if entity.is_alive(entity.get_local_player()) then if vandal.utils.table_contains(ui.get(vandal.menu.visuals.elements), "crosshair") then local stuff = { { text = ui.get(vandal.menu.visuals.custom_text), get_color = function() local min, max, step = 1.75, 200, 1.75 if vandal.variables.visuals.crosshair.step == 1 then if vandal.variables.visuals.crosshair.text_alpha_2 < max then vandal.variables.visuals.crosshair.text_alpha_2 = vandal.variables.visuals.crosshair.text_alpha_2 + step end if vandal.variables.visuals.crosshair.text_alpha > min then vandal.variables.visuals.crosshair.text_alpha = vandal.variables.visuals.crosshair.text_alpha - step end if vandal.variables.visuals.crosshair.text_alpha <= min and vandal.variables.visuals.crosshair.text_alpha_2 >= max then vandal.variables.visuals.crosshair.step = 2 end elseif vandal.variables.visuals.crosshair.step == 2 then if vandal.variables.visuals.crosshair.text_alpha_2 > min then vandal.variables.visuals.crosshair.text_alpha_2 = vandal.variables.visuals.crosshair.text_alpha_2 - step end if vandal.variables.visuals.crosshair.text_alpha < max then vandal.variables.visuals.crosshair.text_alpha = vandal.variables.visuals.crosshair.text_alpha + step end if vandal.variables.visuals.crosshair.text_alpha_2 <= min and vandal.variables.visuals.crosshair.text_alpha >= max then vandal.variables.visuals.crosshair.step = 3 end else if vandal.variables.visuals.crosshair.text_alpha > min then vandal.variables.visuals.crosshair.text_alpha = vandal.variables.visuals.crosshair.text_alpha - step end if vandal.variables.visuals.crosshair.text_alpha <= min then vandal.variables.visuals.crosshair.step = 1 end end return {r = main_r, g = main_g, b = main_b, a = vandal.variables.visuals.crosshair.text_alpha, r2 = main_r, g2 = main_g, b2 = main_b, a2 = vandal.variables.visuals.crosshair.text_alpha_2} end, is_active = function() return true end, is_a_gradient = true }, { text = " "..ui.get(vandal.menu.visuals.custom_text_2).."", get_color = function() return {r = sec_r, g = sec_g, b = sec_b, a = vandal.variables.visuals.crosshair.text_alpha_2, r2 = sec_r, g2 = sec_g, b2 = sec_b, a2 = vandal.variables.visuals.crosshair.text_alpha} end, is_active = function() return true end, is_a_gradient = true }, { text = "A: "..vandal.variables.visuals.generation.damage.."DMG", get_color = function() return {r = 255, g = 255, b = 255, a = vandal.variables.visuals.generation.damage > 0 and 255 or 75} end, is_active = function() return true end }, { text = "BT: "..vandal.variables.visuals.generation.backtrack.."T", get_color = function() return {r = 255, g = 255, b = 255, a = vandal.variables.visuals.generation.backtrack > 0 and 255 or 75} end, is_active = function() return true end }, { text = ui.get(vandal.variables.references.keybinds.items.double_tap[2]) and "DT" or ui.get(vandal.variables.references.keybinds.items.hide_shots[2]) and "OS", get_color = function() return {r = 255, g = 255, b = 255, a = 255} end, is_active = function() return ui.get(vandal.variables.references.keybinds.items.double_tap[2]) or ui.get(vandal.variables.references.keybinds.items.hide_shots[2]) end }, { text = "DMG", get_color = function() return {r = 255, g = 255, b = 255, a = 255} end, is_active = function() return ui.get(vandal.variables.references.keybinds.items.minumum_damage_override[2]) end }, { text = "BAIM", get_color = function() return {r = 255, g = 255, b = 255, a = 255} end, is_active = function() return ui.get(vandal.variables.references.keybinds.items.force_body) end } } local width, max_width, height = 0, renderer.measure_text("-", ui.get(vandal.menu.visuals.custom_text)) + renderer.measure_text("-", " "..ui.get(vandal.menu.visuals.custom_text_2)..""), 0 for i=1, #stuff do local v = stuff[i] if v.is_active() then local clr = v.get_color() if v.is_a_gradient then vandal.utils.gradient_text(v.text, w / 2 + width, h / 2 + 19 + height, clr.r, clr.g, clr.b, clr.a, clr.r2, clr.g2, clr.b2, clr.a2) else renderer.text(w / 2 + width, h / 2 + 19 + height, clr.r, clr.g, clr.b, clr.a, "-", 0, v.text) end if width > max_width - renderer.measure_text("-", v.text) then width = 0 height = height + 8 else width = width + (renderer.measure_text("-", v.text) + 2) end end end end if vandal.utils.table_contains(ui.get(vandal.menu.visuals.elements), "arrows") then local spready_offset = ui.get(vandal.menu.visuals.spready_arrows) and 20 * (math.abs(vandal.liblaries.vector(entity.get_prop(entity.get_local_player(), "m_vecVelocity")):length2d()) / 320) or 0 local arrows_offset = ui.get(vandal.menu.visuals.arrows_offset) spready_offset = ui.get(vandal.menu.visuals.arrows_offset) >= 0 and -spready_offset or spready_offset if vandal.utils.get_side() == -1 then renderer.line(w / 2 - 33 - arrows_offset + spready_offset, h / 2 - 10, w / 2 - 33 - arrows_offset + spready_offset, h / 2 + 10, sec_r, sec_g, sec_b, sec_a) renderer.line(w / 2 + 33 + arrows_offset - spready_offset, h / 2 - 10, w / 2 + 33 + arrows_offset - spready_offset, h / 2 + 10, 25, 25, 25, 125) else renderer.line(w / 2 + 33 + arrows_offset - spready_offset, h / 2 - 10, w / 2 + 33 + arrows_offset - spready_offset, h / 2 + 10, sec_r, sec_g, sec_b, sec_a) renderer.line(w / 2 - 33 - arrows_offset + spready_offset, h / 2 - 10, w / 2 - 33 - arrows_offset + spready_offset, h / 2 + 10, 25, 25, 25, 125) end if vandal.utils.get_manual_yaw() == -90 then renderer.triangle(w / 2 - 35 - arrows_offset + spready_offset, h / 2 - 10, w / 2 - 35 - arrows_offset + spready_offset, h / 2 + 10, w / 2 - 50 - arrows_offset + spready_offset, h / 2, main_r, main_g, main_b, main_a) renderer.triangle(w / 2 + 35 + arrows_offset - spready_offset, h / 2 - 10, w / 2 + 35 + arrows_offset - spready_offset, h / 2 + 10, w / 2 + 50 + arrows_offset - spready_offset, h / 2, 25, 25, 25, 125) elseif vandal.utils.get_manual_yaw() == 90 then renderer.triangle(w / 2 - 35 - arrows_offset + spready_offset, h / 2 - 10, w / 2 - 35 - arrows_offset + spready_offset, h / 2 + 10, w / 2 - 50 - arrows_offset + spready_offset, h / 2, 25, 25, 25, 125) renderer.triangle(w / 2 + 35 + arrows_offset - spready_offset, h / 2 - 10, w / 2 + 35 + arrows_offset - spready_offset, h / 2 + 10, w / 2 + 50 + arrows_offset - spready_offset, h / 2, main_r, main_g, main_b, main_a) else renderer.triangle(w / 2 - 35 - arrows_offset + spready_offset, h / 2 - 10, w / 2 - 35 - arrows_offset + spready_offset, h / 2 + 10, w / 2 - 50 - arrows_offset + spready_offset, h / 2, 25, 25, 25, 125) renderer.triangle(w / 2 + 35 + arrows_offset - spready_offset, h / 2 - 10, w / 2 + 35 + arrows_offset - spready_offset, h / 2 + 10, w / 2 + 50 + arrows_offset - spready_offset, h / 2, 25, 25, 25, 125) end end if vandal.utils.table_contains(ui.get(vandal.menu.visuals.elements), "watermark") then local width = renderer.measure_text("-", "VANDAL | "..string.upper(vandal.variables.visuals.user.build).."") if client.key_state(0x01) and ui.is_menu_open() then local x, y = ui.mouse_position() if vandal.variables.visuals.watermark.width + (width) >= x and vandal.variables.visuals.watermark.width - (width) <= x and vandal.variables.visuals.watermark.height + 20 >= y and vandal.variables.visuals.watermark.height - 10 <= y then vandal.variables.visuals.watermark.width = x vandal.variables.visuals.watermark.height = y end renderer.line(vandal.variables.visuals.watermark.width + (width / 2), vandal.variables.visuals.watermark.height - 10, vandal.variables.visuals.watermark.width + (width / 2), vandal.variables.visuals.watermark.height, 255, 255, 255, 255) renderer.line(vandal.variables.visuals.watermark.width + (width / 2), vandal.variables.visuals.watermark.height + 20, vandal.variables.visuals.watermark.width + (width / 2), vandal.variables.visuals.watermark.height + 10, 255, 255, 255, 255) renderer.line(vandal.variables.visuals.watermark.width + width + 5, vandal.variables.visuals.watermark.height + 5, vandal.variables.visuals.watermark.width + width + 15, vandal.variables.visuals.watermark.height + 5, 255, 255, 255, 255) renderer.line(vandal.variables.visuals.watermark.width - 3, vandal.variables.visuals.watermark.height + 5, vandal.variables.visuals.watermark.width - 13, vandal.variables.visuals.watermark.height + 5, 255, 255, 255, 255) end vandal.utils.gradient_text("VANDAL | "..string.upper(vandal.variables.visuals.user.build).."", vandal.variables.visuals.watermark.width, vandal.variables.visuals.watermark.height, main_r, main_g, main_b, 255, sec_r, sec_g, sec_b, 255) end end end local function notifications_handler() local w, h = client.screen_size() local main_r, main_g, main_b, main_a = ui.get(vandal.menu.visuals.primary_color) local sec_r, sec_g, sec_b, sec_a = ui.get(vandal.menu.visuals.secondary_color) if vandal.utils.table_contains(ui.get(vandal.menu.visuals.elements), "notifications") then for i=1, #vandal.variables.visuals.notifications do if not vandal.variables.visuals.notifications[i] then return end local delta = globals.realtime() - vandal.variables.visuals.notifications[i].start local offset = ((i - 1) * 35 - 100) + (60 * vandal.variables.visuals.notifications[i].progress) if delta < 2.0 and vandal.variables.visuals.notifications[i].alpha < 255 then vandal.variables.visuals.notifications[i].alpha = vandal.variables.visuals.notifications[i].alpha + 2.5 end if delta > 4.0 and vandal.variables.visuals.notifications[i].alpha > 0 then vandal.variables.visuals.notifications[i].alpha = vandal.variables.visuals.notifications[i].alpha - 2.5 end if vandal.variables.visuals.notifications[i].progress < 0.80 then vandal.variables.visuals.notifications[i].progress = vandal.variables.visuals.notifications[i].progress + 0.02 elseif vandal.variables.visuals.notifications[i].progress < 1.00 then vandal.variables.visuals.notifications[i].progress = vandal.variables.visuals.notifications[i].progress + 0.005 end local size = 5 + renderer.measure_text("", "vandal") + 1 + renderer.measure_text("", ".tech") + 11 + renderer.measure_text("", vandal.variables.visuals.notifications[i].text) renderer.rectangle(w / 2 - size / 2, h - 100 - offset, size, 25, 0, 0, 0, vandal.variables.visuals.notifications[i].alpha) renderer.rectangle(w / 2 - size / 2 - 5, h - 95 - offset, size + 10, 15, 0, 0, 0, vandal.variables.visuals.notifications[i].alpha) for i2=1, ui.get(vandal.menu.visuals.glow_amount) do i2 = i2 - 2 renderer.circle(w / 2 - size / 2, h - 80 - offset, 0, 0, 0, vandal.variables.visuals.notifications[i].alpha, 5, 270, 0.25) renderer.circle_outline(w / 2 - size / 2, h - 80 - offset, main_r, main_g, main_b, vandal.variables.visuals.notifications[i].alpha / i2, 5 + i2, 90, 0.25, 1) renderer.circle(w / 2 - size / 2, h - 95 - offset, 0, 0, 0, vandal.variables.visuals.notifications[i].alpha, 5, 180, 0.25) renderer.circle_outline(w / 2 - size / 2, h - 95- offset, sec_r, sec_g, sec_b, vandal.variables.visuals.notifications[i].alpha / i2, 5 + i2, 180, 0.25, 1) renderer.circle(w / 2 + size / 2, h - 80 - offset, 0, 0, 0, vandal.variables.visuals.notifications[i].alpha, 5, 0, 0.25) renderer.circle_outline(w / 2 + size / 2, h - 80 - offset, sec_r, sec_g, sec_b, vandal.variables.visuals.notifications[i].alpha / i2, 5 + i2, 0, 0.25, 1) renderer.circle(w / 2 + size / 2, h - 95 - offset, 0, 0, 0, vandal.variables.visuals.notifications[i].alpha, 5, 90, 0.25) renderer.circle_outline(w / 2 + size / 2, h - 95 - offset, main_r, main_g, main_b, vandal.variables.visuals.notifications[i].alpha / i2, 5 + i2, 270, 0.25, 1) renderer.gradient(w / 2 - size / 2, h - 100 - offset - i2, size * vandal.variables.visuals.notifications[i].progress, 1, sec_r, sec_g, sec_b, vandal.variables.visuals.notifications[i].alpha / i2, main_a, main_g, main_b, vandal.variables.visuals.notifications[i].alpha / i2, true) renderer.gradient(w / 2 - size / 2, h - 76 - offset + i2, size * vandal.variables.visuals.notifications[i].progress, 1, main_a, main_g, main_b, vandal.variables.visuals.notifications[i].alpha / i2, sec_r, sec_g, sec_b, vandal.variables.visuals.notifications[i].alpha / i2, true) renderer.gradient(w / 2 - size / 2 - 5 - i2, h - 95 - offset, 1, 15 * vandal.variables.visuals.notifications[i].progress, sec_r, sec_g, sec_b, vandal.variables.visuals.notifications[i].alpha / i2, main_a, main_g, main_b, vandal.variables.visuals.notifications[i].alpha / i2, false) renderer.gradient(w / 2 + size / 2 + 4 + i2, h - 95 - offset, 1, 15 * vandal.variables.visuals.notifications[i].progress, main_a, main_g, main_b, vandal.variables.visuals.notifications[i].alpha / i2, sec_r, sec_g, sec_b, vandal.variables.visuals.notifications[i].alpha / i2, false) end renderer.text(w / 2 - size / 2 + 2, h - 93 - offset, 255, 255, 255, vandal.variables.visuals.notifications[i].alpha, "", 0, "\a"..vandal.utils.rgba_to_hex(main_r, main_g, main_b, vandal.variables.visuals.notifications[i].alpha).."vandal\a"..vandal.utils.rgba_to_hex(sec_r, sec_g, sec_b, vandal.variables.visuals.notifications[i].alpha)..".tech\a"..vandal.utils.rgba_to_hex(200, 200, 200, vandal.variables.visuals.notifications[i].alpha).." - "..vandal.variables.visuals.notifications[i].text.."") if delta > 2.0 and vandal.variables.visuals.notifications[i].alpha <= 0 then table.remove(vandal.variables.visuals.notifications, i) end end end end local function animbreaker_handler() if not entity.is_alive(entity.get_local_player()) then return end local localplayer = vandal.liblaries.entity.new(entity.get_local_player()) if not localplayer then return end if vandal.utils.table_contains(ui.get(vandal.menu.misc.animbreakers), "legbreaker") then ui.set(vandal.variables.references.other.items.leg_movement, ui.get(vandal.variables.references.other.items.leg_movement) == "Always slide" and "Off" or "Always slide") entity.set_prop(entity.get_local_player(), "m_flPoseParameter", globals.tickcount() % 2 == 1 and 25 or 1, globals.tickcount() % 2 == 1 and 0 or 1) end if vandal.utils.table_contains(ui.get(vandal.menu.misc.animbreakers), "static legs in air") then entity.set_prop(entity.get_local_player(), "m_flPoseParameter", 1, 6) end if vandal.utils.table_contains(ui.get(vandal.menu.misc.animbreakers), "moonwalk in air") and (vandal.state.get(entity.get_local_player()) == 4 or vandal.state.get(entity.get_local_player()) == 8) then localplayer:get_anim_overlay(6).weight = 1.0 end if vandal.utils.table_contains(ui.get(vandal.menu.misc.animbreakers), "body lean") then localplayer:get_anim_overlay(12).weight = 1.0 end end local function defensive_handler(cmd) vandal.variables.anti_aim.generation.data[globals.tickcount()] = { head_pos = vandal.liblaries.vector(entity.hitbox_position(entity.get_local_player(), 0)), origin = vandal.liblaries.vector(entity.get_origin(entity.get_local_player())), simtime = entity.get_prop(entity.get_local_player(), "m_flSimulationTime"), yaw = vandal.liblaries.antiaim.get_body_yaw(1) } vandal.variables.anti_aim.generation.yaw = vandal.liblaries.antiaim.get_body_yaw(1) -- vandal.liblaries.antiaim.get_body_yaw(2) if cmd.in_attack == 1 then vandal.variables.anti_aim.defensive.ticks_left = 0 return end cmd.force_defensive = true if client.current_threat() and vandal.generation.get_backtrack_ticks(client.current_threat()) > 12 and ui.get(vandal.variables.references.keybinds.items.double_tap[2]) then -- cmd.no_choke = true cmd.quick_stop = true end end local function defensive_variables_handler() if not entity.get_local_player() or not entity.is_alive(entity.get_local_player()) then return end local simtime = entity.get_prop(entity.get_local_player(), "m_flSimulationTime") vandal.variables.anti_aim.defensive.ticks_left = vandal.utils.time_to_ticks(math.abs(simtime - vandal.variables.anti_aim.defensive.last_simtime) - client.latency()) if vandal.variables.anti_aim.defensive.last_simtime ~= simtime then vandal.variables.anti_aim.defensive.last_simtime = simtime end end local function anti_aim_manuals_handler() if ui.get(vandal.menu.misc.manual_forward) ~= vandal.variables.anti_aim.manuals.cache.forward then vandal.variables.anti_aim.manuals.cache.forward = ui.get(vandal.menu.misc.manual_forward) vandal.variables.anti_aim.manuals.forward = ui.get(vandal.menu.misc.manual_forward) vandal.variables.anti_aim.manuals.left = false vandal.variables.anti_aim.manuals.right = false ui.set(vandal.menu.misc.manual_left, false) ui.set(vandal.menu.misc.manual_right, false) end if ui.get(vandal.menu.misc.manual_left) ~= vandal.variables.anti_aim.manuals.cache.left then vandal.variables.anti_aim.manuals.cache.left = ui.get(vandal.menu.misc.manual_left) vandal.variables.anti_aim.manuals.forward = false vandal.variables.anti_aim.manuals.left = ui.get(vandal.menu.misc.manual_left) vandal.variables.anti_aim.manuals.right = false ui.set(vandal.menu.misc.manual_forward, false) ui.set(vandal.menu.misc.manual_right, false) end if ui.get(vandal.menu.misc.manual_right) ~= vandal.variables.anti_aim.manuals.cache.right then vandal.variables.anti_aim.manuals.cache.right = ui.get(vandal.menu.misc.manual_right) vandal.variables.anti_aim.manuals.forward = false vandal.variables.anti_aim.manuals.left = false vandal.variables.anti_aim.manuals.right = ui.get(vandal.menu.misc.manual_right) ui.set(vandal.menu.misc.manual_forward, false) ui.set(vandal.menu.misc.manual_left, false) end end local function shutdown() for i, v in pairs(vandal.variables.references) do if type(v) == "table" then for i2, v2 in pairs(v) do if type(v2) == "table" then for i3, v3 in pairs(v2) do if not type(v3) == "table" then ui.set_visible(v3, true) end end else ui.set_visible(v2, true) end end else ui.set_visible(v, true) end end end local done = false local function resolver_handler() local enemies = entity.get_players(true) for i=1, #enemies do local enemy = enemies[i] if not vandal.resolver.data[enemy] then vandal.resolver.data[enemy] = { misses = 0, playback = { left = 5, right = 6 }, lby = { next_update = globals.tickinterval() * entity.get_prop(enemy, "m_nTickBase") }, yaw = { last_yaw = 0, delta = 0, last_change = globals.curtime() } } end if ui.get(vandal.menu.misc.resolver_enabled) then plist.set(enemy, "Correction active", false) plist.set(enemy, "Force body yaw", false) local player = vandal.liblaries.entity.new(enemy) if not player then return end local animstate = player:get_anim_state() local animlayer = player:get_anim_overlay(6) local max_speed = 260 if entity.get_player_weapon(enemy) then max_speed = math.max(vandal.liblaries.weapons(entity.get_player_weapon(enemy)).max_player_speed, 0.001) end local running_speed = math.max(vandal.liblaries.vector(entity.get_prop(player, "m_vecVelocity")):length2d(), 260) / (max_speed * 0.520) local ducking_speed = math.max(vandal.liblaries.vector(entity.get_prop(player, "m_vecVelocity")):length2d(), 260) / (max_speed * 0.340) local server_time = vandal.utils.ticks_to_time(entity.get_prop(enemy, "m_nTickBase")) local yaw = animstate.goal_feet_yaw local eye_feet_delta = animstate.eye_angles_y - animstate.goal_feet_yaw local yaw_modifier = ((((animstate.stop_to_full_running_fraction * -0.3) - 0.2) * vandal.utils.clamp(running_speed, 0, 1)) + 1) if animstate.duck_amount > 0 then yaw_modifier = yaw_modifier + (animstate.duck_amount * (vandal.utils.clamp(ducking_speed, 0, 1)) * (0.5 - yaw_modifier)) end local max_yaw_modifier = yaw_modifier * animstate.max_yaw local min_yaw_modifier = yaw_modifier * animstate.min_yaw if eye_feet_delta <= max_yaw_modifier then if min_yaw_modifier > eye_feet_delta then yaw = math.abs(min_yaw_modifier) + animstate.eye_angles_y end else yaw = animstate.eye_angles_y - math.abs(max_yaw_modifier) end if vandal.liblaries.vector(entity.get_prop(player, "m_vecVelocity")):length2d() > 0.01 or math.abs(vandal.liblaries.vector(entity.get_prop(player, "m_vecVelocity")).z) > 100 then yaw = vandal.resolver.helpers.approach_angle(animstate.eye_angles_y, yaw, ((animstate.stop_to_full_running_fraction * 20) + 30) * animstate.last_client_side_animation_update_time) else yaw = vandal.resolver.helpers.approach_angle(entity.get_prop(enemy, "m_flLowerBodyYawTarget"), yaw, animstate.last_client_side_animation_update_time * 100) end local desync = animstate.goal_feet_yaw - yaw local eye_goalfeet_delta = vandal.resolver.helpers.angle_diff(animstate.eye_angles_y - yaw, 360) if eye_goalfeet_delta < 0.0 or animstate.max_yaw == 0.0 then if animstate.min_yaw ~= 0.0 then desync = ((eye_goalfeet_delta / animstate.min_yaw) * 360) * -58 end else desync = ((eye_goalfeet_delta / animstate.max_yaw) * 360) * 58 end if server_time >= vandal.resolver.data[enemy].lby.next_update then desync = 120 / 58 -- lby breaker fix end local delta = desync - vandal.resolver.data[enemy].yaw.last_yaw local time_delta = entity.get_prop(enemy, "m_flSimulationTime") - vandal.resolver.data[enemy].yaw.last_change local modifier = time_delta / vandal.resolver.data[enemy].yaw.delta desync = (desync * 58) + (delta * modifier) desync = desync * vandal.resolver.helpers.process_side(enemy, vandal.resolver.helpers.get_side(enemy, animlayer)) plist.set(enemy, "Force body yaw", true) plist.set(enemy, "Force body yaw value", desync) plist.set(enemy, "High priority", math.floor(time_delta) ~= 0) -- prevent missing LC if animstate.eye_timer ~= 0 then if animstate.m_velocity > 0.1 then vandal.resolver.data[enemy].lby.next_update = server_time + 0.22 end if math.abs((animstate.goal_feet_yaw - animstate.eye_angles_y) / 360) > 35 and server_time > vandal.resolver.data[enemy].lby.next_update then vandal.resolver.data[enemy].lby.next_update = server_time + 1.1 end end if vandal.resolver.data[enemy].yaw.last_yaw ~= desync then vandal.resolver.data[enemy].yaw.last_yaw = desync end if delta ~= 0 then if vandal.resolver.data[enemy].yaw.delta ~= delta then vandal.resolver.data[enemy].yaw.last_change = entity.get_prop(enemy, "m_flSimulationTime") vandal.resolver.data[enemy].yaw.delta = delta end end done = false else if not done then plist.set(enemy, "Correction active", true) plist.set(enemy, "Force body yaw", false) done = true end end end end local function resolver_on_miss(event) if not ui.get(vandal.menu.misc.resolver_enabled) or event.reason == "spread" or event.reason == "death" or event.reason == "unregistered shot" then return end vandal.resolver.data[event.target].misses = vandal.resolver.data[event.target].misses and vandal.resolver.data[event.target].misses + 1 or 1 local player = vandal.liblaries.entity.new(event.target) if not player then return end local animlayer = player:get_anim_overlay(6) local left, right = vandal.resolver.data[event.target].playback.left, vandal.resolver.data[event.target].playback.right local side = vandal.resolver.helpers.process_side(event.target, vandal.resolver.helpers.get_side(event.target, animlayer)) if side == -1 then left = animlayer.playback_rate elseif side == 1 then right = animlayer.playback_rate end vandal.resolver.data[event.target].playback = { left = left, right = right } client.log("[vandal resolver] detected miss at "..entity.get_player_name(event.target).." | desync: "..plist.get(event.target, "Force body yaw value").."") end client.set_event_callback("aim_miss", function(event) resolver_on_miss(event) end) client.set_event_callback("bullet_impact", function(event) anti_bruteforce_handler(event) end) client.set_event_callback("paint_ui", function() menu_handler() notifications_handler() process_settings() end) client.set_event_callback("paint", function() anti_aim_handler() anti_aim_manuals_handler() indicators_handler() resolver_handler() end) client.set_event_callback("net_update_start", function() defensive_variables_handler() end) client.set_event_callback("pre_render", function() animbreaker_handler() end) client.set_event_callback("setup_command", function(cmd) defensive_handler(cmd) end) client.set_event_callback("shutdown", function() shutdown() end)
412
0.946692
1
0.946692
game-dev
MEDIA
0.901897
game-dev
0.683556
1
0.683556
InfernumTeam/InfernumMode
22,639
Content/Projectiles/Melee/PunctusProjectile.cs
using System.Collections.Generic; using CalamityMod; using CalamityMod.Particles; using InfernumMode.Assets.Effects; using InfernumMode.Assets.ExtraTextures; using InfernumMode.Assets.Sounds; using InfernumMode.Common.Graphics.Interfaces; using InfernumMode.Common.Graphics.Particles; using InfernumMode.Common.Graphics.Primitives; using InfernumMode.Content.Projectiles.Wayfinder; using InfernumMode.Core.GlobalInstances.Players; using Luminance.Common.Easings; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.Audio; using Terraria.GameContent; using Terraria.Graphics.Shaders; using Terraria.ID; using Terraria.ModLoader; using static InfernumMode.Content.Projectiles.Melee.PunctusRock; namespace InfernumMode.Content.Projectiles.Melee { public class PunctusProjectile : ModProjectile, IPixelPrimitiveDrawer { #region Enumerations public enum UseMode { NormalThrow, RockThrow } public enum UseState { Aiming, Firing, Hit } #endregion #region Properties public UseMode CurrentMode { get => (UseMode)Projectile.ai[0]; set => Projectile.ai[0] = (int)value; } public UseState CurrentState { get => (UseState)Projectile.ai[1]; set => Projectile.ai[1] = (int)value; } public ref float Timer => ref Projectile.ai[2]; public Player Owner => Main.player[Projectile.owner]; public PrimitiveTrailCopy AfterimageDrawer { get; private set; } public float PullbackCompletion => Utilities.Saturate(Timer / PullbackLength); public List<Vector2> OldPositions; public bool ShouldCreateMoreRocks; public bool ShouldHome; public Vector2 OffsetToTargetCenter; #endregion #region Constants public const int PullbackLength = 30; public const int FadeOutLength = 10; public const int TintLength = 10; public const int MinRocksForHoming = 3; public const int MaxCirclingRocks = 6; #endregion #region AI public override string Texture => "InfernumMode/Content/Items/Weapons/Melee/Punctus"; public override void SetStaticDefaults() { ProjectileID.Sets.TrailingMode[Projectile.type] = 2; ProjectileID.Sets.TrailCacheLength[Projectile.type] = 10; } public override void SetDefaults() { Projectile.width = Projectile.height = 90; Projectile.friendly = true; Projectile.hostile = false; Projectile.DamageType = DamageClass.Melee; Projectile.tileCollide = false; Projectile.ignoreWater = true; Projectile.netImportant = true; Projectile.penetrate = 2; Projectile.timeLeft = 240; Projectile.usesIDStaticNPCImmunity = true; Projectile.idStaticNPCHitCooldown = -1; OldPositions = []; } public override void AI() { switch (CurrentState) { case UseState.Aiming: DoBehavior_Aim(); break; case UseState.Firing: DoBehavior_Fire(); break; case UseState.Hit: DoBehavior_Hit(); break; } // Ensure the projectile doesn't die before being fired. if (CurrentState is UseState.Aiming) Projectile.timeLeft = 240; else if (CurrentMode is UseMode.NormalThrow && ShouldHome) { // Add to the custom old positions list, removing the last one if too many are present. if (OldPositions.Count >= ProjectileID.Sets.TrailCacheLength[Type]) OldPositions.RemoveAt(OldPositions.Count - 1); OldPositions.Insert(0, Projectile.Center); } Timer++; } public void DoBehavior_Aim() { // Aim the spear at the mouse. if (Main.myPlayer == Projectile.owner) { float aimInterpolant = Utils.GetLerpValue(5f, 25f, Owner.Distance(Main.MouseWorld), true); Vector2 oldVelocity = Projectile.velocity; Projectile.velocity = Vector2.Lerp(Projectile.velocity, Owner.SafeDirectionTo(Main.MouseWorld), aimInterpolant); if (Projectile.velocity != oldVelocity) { Projectile.netSpam = 0; Projectile.netUpdate = true; } // Don't bother playing this for other players, it's only useful for the owner. // Also, don't play it if neither mouse button is being held. //if (Timer == PullbackLength && (Owner.channel || Owner.Calamity().mouseRight)) // SoundEngine.PlaySound(SoundID.Item29 with { Pitch = -0.1f }, Owner.Center); } // Calculate rotation, and set the player's arm to look as if its holding the spear. Projectile.rotation = Projectile.velocity.ToRotation() + PiOver4; Owner.ChangeDir((Projectile.velocity.X > 0f).ToDirectionInt()); float frontArmRotation = Projectile.rotation - PiOver4 - PullbackCompletion * Owner.direction * 0.74f; if (Owner.direction == 1) frontArmRotation += Pi; // Stick to the player. Projectile.Center = Owner.Center + (frontArmRotation + PiOver2).ToRotationVector2() * Projectile.scale * 16f + Projectile.velocity * Projectile.scale * 40f; Owner.heldProj = Projectile.whoAmI; Owner.SetDummyItemTime(2); // Perform directioning. Projectile.spriteDirection = Owner.direction; if (Owner.direction == -1) Projectile.rotation += PiOver2; // Pause the global rock circling timer if this is a rock throw, as the rocks should not be moving. // This is important to prevent any new rocks currently spawning from moving a bit before they should be, // messing up the positions. if (CurrentMode is UseMode.RockThrow) Owner.GetModPlayer<PunctusPlayer>().PauseTimer = true; // Determine whether the spear should create more rocks on hit. int activeRocks = ActiveRocks(Owner); if (CurrentMode is UseMode.RockThrow && activeRocks >= MaxCirclingRocks) ShouldCreateMoreRocks = true; // Update the player's arm directions to make it look as though they're holding the spear. Owner.SetCompositeArmFront(true, Player.CompositeArmStretchAmount.Full, frontArmRotation); // Fire the spear if ready. if (CurrentMode is UseMode.NormalThrow ? !Owner.channel : !Owner.Calamity().mouseRight) { if (PullbackCompletion == 1f) { // Ensure the timer resumes once the spear is fired. Owner.GetModPlayer<PunctusPlayer>().PauseTimer = false; // Restore the players arm. Owner.SetCompositeArmFront(false, Player.CompositeArmStretchAmount.Full, 0f); SoundEngine.PlaySound(InfernumSoundRegistry.PunctusThrowSound with { Volume = 0.5f, Pitch = 0.2f }, Owner.Center); SoundEngine.PlaySound(SoundID.DD2_MonkStaffSwing with { Volume = 1f, Pitch = -0.2f }, Owner.Center); // Determine whether the spear should home. 3 rocks must be circling, and it must be a normal throw. int circlingRocks = PassiveRocks(Owner); if (circlingRocks >= MinRocksForHoming && CurrentMode is UseMode.NormalThrow) ShouldHome = true; // Swap the current state to firing, set the velocity, reset the timer and sync. CurrentState = UseState.Firing; Projectile.velocity *= Owner.ActiveItem().shootSpeed; Timer = 0f; Projectile.netUpdate = true; } } } public void DoBehavior_Fire() { // Ensure these remain correct. Projectile.rotation = Projectile.velocity.ToRotation() + PiOver4; Projectile.spriteDirection = 1; // Check whether the timer can be reset, to handle it overflowing (VERY unlikely to happen ever regardless but yeah). if (Timer == 3f) Owner.GetModPlayer<PunctusPlayer>().CheckToResetTimer = true; Lighting.AddLight(Projectile.Center, WayfinderSymbol.Colors[1].ToVector3()); // Release anime-like streak particle effects at the side of the spear to indicate motion. if (Timer % 3 == 2 || Main.rand.NextBool(3)) { Vector2 energySpawnPosition = Projectile.Center + Main.rand.NextVector2Circular(10f, 10f) + Projectile.velocity * 2f; Vector2 energyVelocity = -Projectile.velocity.SafeNormalize(Vector2.UnitX * Projectile.direction) * Main.rand.NextFloat(4f, 6.75f); Particle energyLeak = new SquishyLightParticle(energySpawnPosition, energyVelocity, Main.rand.NextFloat(0.35f, 0.5f), Color.Lerp(WayfinderSymbol.Colors[1], WayfinderSymbol.Colors[2], Main.rand.NextFloat()), 30, 0.5f, 4.5f, 3f); GeneralParticleHandler.SpawnParticle(energyLeak); } // Only home if it should. if (!ShouldHome) return; // Locate the closest target, prioritising bosses, and lightly home towards them. NPC target = CalamityUtils.ClosestNPCAt(Projectile.Center, 250f, true, true); if (target == null) return; float newSpeed = Clamp(Projectile.velocity.Length() * 1.032f, 6f, 42f); Projectile.velocity = Vector2.Lerp(Projectile.velocity, Projectile.SafeDirectionTo(target.Center) * newSpeed, 0.24f).RotateTowards(Projectile.AngleTo(target.Center), 0.1f); Projectile.velocity = Projectile.velocity.SafeNormalize(Vector2.UnitY) * newSpeed; } // Fade out once it's hit something. public void DoBehavior_Hit() { Projectile.Opacity = Utils.GetLerpValue(FadeOutLength, 0f, Timer, true); if (Projectile.Opacity == 0f) Projectile.Kill(); } public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) { float collisionPoint = 0; // Custom collision code to check along the spear in a line. float distance = Projectile.Size.Length() * Projectile.scale; Vector2 start = Projectile.Center - Projectile.velocity.SafeNormalize(Vector2.UnitY) * distance * 0.5f; Vector2 end = Projectile.Center + Projectile.velocity.SafeNormalize(Vector2.UnitY) * distance * 0.5f; return Collision.CheckAABBvLineCollision(targetHitbox.TopLeft(), targetHitbox.Size(), start, end, 15f * Projectile.scale, ref collisionPoint); } // Only hit stuff if it hasn't already lost a pierce from hitting. public override bool? CanHitNPC(NPC target) => Projectile.penetrate > 1 ? null : false; // Only hit stuff if it hasn't already lost a pierce from hitting. public override bool CanHitPlayer(Player target) => Projectile.penetrate > 1; // Only hit stuff if it hasn't already lost a pierce from hitting. public override bool CanHitPvp(Player target) => Projectile.penetrate > 1; public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { // Swap the state to hit. Projectile.netUpdate = true; Timer = 0; CurrentState = UseState.Hit; // Get the tip of the spear. float spearLength = Projectile.Size.Length(); Vector2 spearTip = Projectile.Center + Projectile.velocity.SafeNormalize(Vector2.Zero) * spearLength * 0.5f; // Spawn the rock(s). These handle their own rock particle visuals. if (Main.myPlayer == Owner.whoAmI) { int numberOfExistingRocks = 0; for (int i = 0; i < Main.maxProjectiles; i++) { if (!Main.projectile[i].active || Main.projectile[i].owner != Owner.whoAmI || Main.projectile[i].type != ModContent.ProjectileType<PunctusRock>() || Main.projectile[i].ModProjectile is not PunctusRock rock) continue; if (rock.CurrentState is State.Circling or State.Aiming) { if (rock.HasDoneInitialGlow) { rock.Timer = rock.CurrentState is State.Circling ? 300 : CircleLength - 300f; rock.Projectile.timeLeft = rock.CurrentState is State.Circling ? CircleLength : 300; } numberOfExistingRocks++; } } bool anyRocksCreated = false; // If there isnt already 6 rocks, and is a left click throw, spawn a rock and update the amount of existing ones. if (numberOfExistingRocks < MaxCirclingRocks && CurrentMode is not UseMode.RockThrow) { Projectile.NewProjectile(Projectile.GetSource_FromAI(), spearTip, Projectile.velocity, ModContent.ProjectileType<PunctusRock>(), Projectile.damage, 3f, Owner.whoAmI, Tau * numberOfExistingRocks / MaxCirclingRocks); numberOfExistingRocks++; anyRocksCreated = true; } // If this is a 6 rock throw, spawn 3 more rocks if able to, regardless of click mode. if (ShouldCreateMoreRocks) { for (int i = 0; i < 3; i++) { // Ensure more than 6 rocks aren't created. if (numberOfExistingRocks == MaxCirclingRocks) break; Projectile.NewProjectile(Projectile.GetSource_FromAI(), spearTip, Projectile.velocity, ModContent.ProjectileType<PunctusRock>(), Projectile.damage, 3f, Owner.whoAmI, Tau * numberOfExistingRocks / MaxCirclingRocks); numberOfExistingRocks++; anyRocksCreated = true; } } if (!anyRocksCreated) { // Crumble away into rocks on death. for (int i = 0; i < 10; i++) { Vector2 velocity = Projectile.velocity.SafeNormalize(Vector2.Zero).RotatedBy(Main.rand.NextFloat(-0.5f, 0.5f)) * Main.rand.NextFloat(1f, 8f); Particle rock = new ProfanedRockParticle(spearTip, velocity, Color.White, Main.rand.NextFloat(0.65f, 0.95f), 60, Main.rand.NextFloat(0f, 0.2f), false); GeneralParticleHandler.SpawnParticle(rock); } } } // Hit sounds. Not that bad but could do with custom sounds. Look into? SoundEngine.PlaySound(SoundID.DD2_LightningBugZap, spearTip); SoundEngine.PlaySound(SoundID.DD2_ExplosiveTrapExplode with { Pitch = 0.95f, Volume = 0.9f }, spearTip); // Make the spear abruptly freeze in place with some screenshake to imply a heavy impact. Projectile.velocity = Vector2.Zero; Owner.Infernum_Camera().CurrentScreenShakePower = ShouldCreateMoreRocks ? 4f : 2f; float scaleModifier = 0.8f; // Spawn a bunch of light particles. for (int i = 0; i < 10; i++) { Vector2 position = spearTip + Main.rand.NextVector2Circular(20f, 20f); Particle light = new GlowyLightParticle(position, spearTip.DirectionTo(position) * Main.rand.NextFloat(0.5f, 1f), Main.rand.NextBool() ? WayfinderSymbol.Colors[1] : Color.OrangeRed, 60, Main.rand.NextFloat(0.85f, 1.15f) * scaleModifier, Main.rand.NextFloat(0.95f, 1.05f), false); GeneralParticleHandler.SpawnParticle(light); } // Create a fire explosion. for (int i = 0; i < 10; i++) { MediumMistParticle fireExplosion = new(spearTip + Main.rand.NextVector2Circular(30f, 30f), Vector2.Zero, Main.rand.NextBool() ? WayfinderSymbol.Colors[0] : WayfinderSymbol.Colors[1], Color.Gray, Main.rand.NextFloat(0.85f, 1.15f) * scaleModifier, Main.rand.NextFloat(220f, 250f)); GeneralParticleHandler.SpawnParticle(fireExplosion); } // Pretty bloom thing. var bloom = new StrongBloom(spearTip, Vector2.Zero, Color.Lerp(WayfinderSymbol.Colors[0], WayfinderSymbol.Colors[1], Main.rand.NextFloat(0.3f, 0.7f)), 1f * scaleModifier, 40); GeneralParticleHandler.SpawnParticle(bloom); // Visual sparks as an indication of the high energy impact. Considered using the electric ones but they looked kinda bad. for (int i = 0; i < 8; i++) { Vector2 sparkVelocity = Main.rand.NextVector2Unit() * Main.rand.NextFloat(1f, 5f); Color sparkColor = Color.Lerp(WayfinderSymbol.Colors[0], WayfinderSymbol.Colors[1], Main.rand.NextFloat(0.4f, 1f)); GeneralParticleHandler.SpawnParticle(new SparkParticle(spearTip, sparkVelocity, false, 40, 2f * scaleModifier, sparkColor)); } } // Don't do damage while aiming, to prevent "poking" strats where massive damage is acquired from just sitting on top of enemies with the spear. public override bool? CanDamage() => CurrentState != UseState.Aiming; #endregion #region Drawing public float WidthFunction(float completionRatio) => SmoothStep(21f, 5f, completionRatio) * Projectile.Opacity; public Color ColorFunction(float completionRatio) { float trailOpacity = Utils.GetLerpValue(0.75f, 0.27f, completionRatio, true) * Utils.GetLerpValue(0f, 0.067f, completionRatio, true) * 0.9f; Color startingColor = new(255, 191, 73); Color middleColor = new(89, 43, 49); Color endColor = new(25, 8, 8); Color color = LumUtils.MulticolorLerp(Utilities.Saturate(completionRatio - 0.1f), startingColor, middleColor, endColor) * trailOpacity; color.A = (byte)(trailOpacity * 255); return color * Projectile.Opacity; } public void DrawPixelPrimitives(SpriteBatch spriteBatch) { // Only draw the trail if flying, and homing. if (CurrentMode is not UseMode.NormalThrow || CurrentState < UseState.Firing || !ShouldHome) return; AfterimageDrawer ??= new PrimitiveTrailCopy(WidthFunction, ColorFunction, null, true, GameShaders.Misc["CalamityMod:ImpFlameTrail"]); // Prepare the flame trail shader with its map texture. GameShaders.Misc["CalamityMod:ImpFlameTrail"].SetShaderTexture(InfernumTextureRegistry.StreakMagma); AfterimageDrawer.DrawPixelated(OldPositions, -Main.screenPosition - Vector2.One.RotatedBy(Projectile.rotation - PiOver2) * 10f, 30); } public override bool PreDraw(ref Color lightColor) { Texture2D spear = TextureAssets.Projectile[Type].Value; Vector2 drawPosition = Projectile.Center - Main.screenPosition; // Account for the player moving up slopes if being held. if (CurrentState is UseState.Aiming) drawPosition.Y += Owner.gfxOffY; SpriteEffects direction = Projectile.spriteDirection == 1 ? SpriteEffects.None : SpriteEffects.FlipHorizontally; // Draw some backglow if the next shot can be homing, or will create extra rocks. int rockTotal = PassiveRocks(Owner); float glowDistance = 2f; if ((CurrentMode is UseMode.NormalThrow && rockTotal >= MinRocksForHoming && CurrentState is not UseState.Aiming) || (CurrentMode is UseMode.RockThrow && rockTotal == MaxCirclingRocks)) glowDistance = 4f; float backglowAmount = 12f; for (int i = 0; i < backglowAmount; i++) { Vector2 backglowOffset = (TwoPi * i / backglowAmount).ToRotationVector2() * glowDistance * Utilities.Saturate(Timer / 10f); Color backglowColor = WayfinderSymbol.Colors[1]; backglowColor.A = 0; Main.spriteBatch.Draw(spear, drawPosition + backglowOffset, null, backglowColor * Projectile.Opacity, Projectile.rotation, spear.Size() * 0.5f, Projectile.scale, direction, 0); } // Apply a tint to the spear to indicate it can be fired, along with the sound played. bool useTint = CurrentState is UseState.Aiming && PullbackCompletion >= 1f && Timer < PullbackLength + TintLength * 2f; if (useTint) { Main.spriteBatch.EnterShaderRegion(); float shiftAmount = Utils.GetLerpValue(PullbackLength, PullbackLength + TintLength * 0.75f, Timer, true) * Utils.GetLerpValue(PullbackLength + TintLength * 2f, PullbackLength + TintLength * 1.25f, Timer, true); InfernumEffectsRegistry.BasicTintShader.UseSaturation(Lerp(0f, 0.55f, EasingCurves.Circ.InFunction(shiftAmount))); InfernumEffectsRegistry.BasicTintShader.UseOpacity(1f); InfernumEffectsRegistry.BasicTintShader.UseColor(WayfinderSymbol.Colors[0]); InfernumEffectsRegistry.BasicTintShader.Apply(); } // Draw the spear. Main.spriteBatch.Draw(spear, drawPosition, null, Projectile.GetAlpha(lightColor) * Projectile.Opacity, Projectile.rotation, spear.Size() * 0.5f, Projectile.scale, direction, 0); // Restore the spritebatch if needed. if (useTint) Main.spriteBatch.ExitShaderRegion(); return false; } #endregion } }
412
0.977725
1
0.977725
game-dev
MEDIA
0.997638
game-dev
0.992062
1
0.992062
neuroprod/webgpu
1,907
frontend/src/trigers/DoorInsideTrigger.ts
import HitTrigger from "./HitTrigger"; import GameModel, {StateFasion, Transitions} from "../GameModel"; import {CURSOR} from "../ui/Cursor"; export default class DoorInsideTrigger extends HitTrigger { protected click() { GameModel.sound.playClick(0.2) if (GameModel.stateFashion == StateFasion.START) { GameModel.setTransition(Transitions.TEXT_INFO, "readMailFirst") return; } if (GameModel.stateFashion == StateFasion.CAN_READ_MAIL_MAILBOX && GameModel.roomCamOffset > 0.1) { GameModel.setTransition(Transitions.TEXT_INFO, "readMailFirst") return; } if (GameModel.stateFashion == StateFasion.CAN_MAKE_TRIANGLE && GameModel.roomCamOffset > 0) { GameModel.setTransition(Transitions.TEXT_INFO, "makeTriangleFirst") return; } let door = GameModel.renderer.modelByLabel["_HitCenterDoor"] let world = door.getWorldPos() GameModel.gameUI.cursor.hide() GameModel.characterHandler.walkTo(world, 0, this.onCompleteWalk, true) GameModel.hitObjectLabel = "" } protected over() { //UI.logEvent("Over", this.objectLabel); if (GameModel.isLeftRoom) { GameModel.gameUI.cursor.show(CURSOR.ARROW_RIGHT) } else { GameModel.gameUI.cursor.show(CURSOR.ARROW_LEFT) } } protected out() { // UI.logEvent("Out", this.objectLabel); GameModel.gameUI.cursor.hide() } onCompleteWalk() { if (GameModel.isLeftRoom) { GameModel.setTransition(Transitions.GO_RIGHT_ROOM) } else { GameModel.setTransition(Transitions.GO_LEFT_ROOM) } // GameModel.setScene(Scenes.OUTSIDE) //let door = GameModel.renderer.modelByLabel["door"] //GameModel.characterPos = door.getWorldPos() } }
412
0.709565
1
0.709565
game-dev
MEDIA
0.753048
game-dev
0.954173
1
0.954173
ddionisio/MateUnity
1,422
Scripts/GameObject/GOActivatorActivateBoxCheck.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace M8 { /// <summary> /// Do a periodic check for colliders based on layer mask, ensure Activators have a collider with matching layer. /// </summary> [AddComponentMenu("M8/Game Object/Activator Activate Box Check")] #if !M8_PHYSICS_DISABLED public class GOActivatorActivateBoxCheck : GOActivatorActivateCheckBase<Collider> { public Vector3 extent; protected override int PopulateCollisions(Collider[] cache) { var t = transform; return Physics.OverlapBoxNonAlloc(t.position, extent, cache, t.rotation, layerMask); } void OnDrawGizmos() { if(extent.x > 0f && extent.y > 0f && extent.z > 0f) { Gizmos.color = Color.green; Gizmo.DrawWireCube(transform.position, transform.rotation, extent); } } } #else public class GOActivatorActivateBoxCheck : GOActivatorActivateCheckBase<Component> { public Vector3 extent; protected override int PopulateCollisions(Component[] cache) { return 0; } void OnDrawGizmos() { if(extent.x > 0f && extent.y > 0f && extent.z > 0f) { Gizmos.color = Color.green; Gizmo.DrawWireCube(transform.position, transform.rotation, extent); } } } #endif }
412
0.91844
1
0.91844
game-dev
MEDIA
0.93993
game-dev
0.865438
1
0.865438
DamiTheHuman/quill-framework
19,789
Assets/Resources/Regular Stage/Player/Scripts/Actions/Climb.cs
using System; using System.Collections; using System.Linq; using UnityEngine; /// <summary> /// A unique action that allows players to climb certain objects within the <see cref="Sensors.climbableCollisionMask"/> /// </summary> public class Climb : HedgePrimaryAction { [SerializeField] private Glide glide; [SerializeField] private ClimbState climbState = ClimbState.None; [SerializeField, DirectionList, Tooltip("The direction of the wall being climbed")] private int wallDirection = 1; [SerializeField, Tooltip("The info of the wall being climbed")] private CollisionInfoData currentWallInfo; [SerializeField, Tooltip("The current position of the ledge")] private Vector2 ledgePosition; [SerializeField, Range(0, 1), FirstFoldOutItem("Pull Up Info")] private float currentAnimationTime = 0; [SerializeField, Tooltip("Calculate the final position of the player and camera once the pull up animation is done playing")] private Vector2 finalPositionAfterPullUp; [FirstFoldOutItem("Sensor Colours")] public Color ledgeSensorColor = General.RGBToColour(0, 240, 0); public Color fallSensorColor = General.RGBToColour(56, 255, 162); public Color findLedgeSensorColor = General.RGBToColour(0, 174, 239); [LastFoldoutItem] public Color ceilingSensorColor = General.RGBToColour(255, 242, 56); [SerializeField, Tooltip("Radius in which a wall can be climbed")] private float noClimbRadius = 0; [Tooltip("Current wall collision info"), SerializeField] private CollisionInfoData wallLedgeCollisionInfo = new CollisionInfoData(); public override void Start() { base.Start(); if (this.glide == null) { this.Reset(); } } /// <summary> /// Mainly used to set the defaults /// </summary> public override void Reset() { base.Reset(); this.actionID = 17f; this.climbState = ClimbState.None; this.attackingAction = false; this.wallDirection = 1; this.primaryAnimationID = ActionSubState.Climbing; this.glide = this.player.GetActionManager().GetAction<Glide>() as Glide; } /// <summary> /// If we are currently gliding or turning within a glid action we can perform the action /// </summary> public override bool CanPerformAction() { if (this.player.GetActionManager().GetAction<Glide>() == null) { return false; } if ((this.player.GetActionManager().CheckActionIsBeingPerformed<Glide>() && this.glide.GetGlideState() == GlideState.Gliding) || this.glide.GetGlideState() == GlideState.Turning) { return true; } return false; } /// <summary> /// Wait until the player comes in contact with climbable object and if so perform the action /// </summary> public override bool LaunchActionConditon() { if ( this.player.GetSensors().wallCollisionInfo.GetCurrentCollisionInfo().GetHit() && this.IsClimbable(this.player.GetSensors().wallCollisionInfo.GetCurrentCollisionInfo().GetHit().transform.gameObject) && General.CheckAngleIsWithinOrEqualRange(Mathf.RoundToInt(this.player.GetSensors().wallCollisionInfo.GetCurrentCollisionInfo().GetAngleInDegrees()), 90 + this.noClimbRadius, 270 - this.noClimbRadius) ) { if (Mathf.Sign(this.player.velocity.x) == this.player.GetSensors().wallCollisionInfo.GetCurrentCollisionInfo().GetSensorHitDirection()) { return true; } } return false; } /// <summary> /// Loop through the players positions to calculate the final position post pull up /// </summary> private Vector2 CalculatePlayerFinalPosition() { Vector2 finalPosition = this.player.transform.position; foreach (Vector2 position in this.player.GetPlayerPhysicsInfo().pullUpPositionIncrements) { finalPosition += position * new Vector2(this.wallDirection, 1); } return finalPosition; } /// <summary> /// Sets the player to the climb state /// </summary> public override void OnActionStart() { this.player.GetAnimatorManager().SwitchActionSubstate(this.primaryAnimationID); this.climbState = ClimbState.Climb; this.wallDirection = this.player.GetSensors().wallCollisionInfo.GetCurrentCollisionInfo().GetSensorHitDirection(); this.currentWallInfo = this.player.GetSensors().wallCollisionInfo.GetCurrentCollisionInfo(); this.player.velocity.x = 0; this.player.velocity.y = 0; GMAudioManager.Instance().PlayOneShot(this.player.GetPlayerActionAudio().grab); } /// <summary> /// Perform different actions based on the players current climb state /// </summary> public override void OnPerformingAction() { if (this.climbState == ClimbState.Climb) { this.HandleClimbingState(); } else if (this.climbState == ClimbState.PullUp) { this.player.GetAnimatorManager().PlayAnimation("Clambering", this.currentAnimationTime); } else if (this.climbState == ClimbState.Drop) { this.HandleDroppingState(); } } /// <summary> /// Exits the climb state when the climb state is set to none or they touch the ground /// </summary> public override bool ExitActionCondition() { if (this.climbState == ClimbState.None || (this.player.GetGrounded() && this.climbState == ClimbState.Climb)) { return true; } return false; } /// <summary> /// The commands performed at the end of the climb action /// </summary> public override void OnActionEnd() { this.player.GetAnimatorManager().SwitchActionSecondarySubstate(0); this.player.GetAnimatorManager().SwitchActionSubstate(0); this.player.GetAnimatorManager().SwitchGimmickSubstate(0); this.player.GetAnimatorManager().SetOtherAnimationSubstate(0); this.player.GetInputManager().SetInputRestriction(InputRestriction.None); this.SetClimbState(ClimbState.None); } /// <summary> /// Set the current climb state of the action and update the animation where available /// <param name="climbState">The new climb state for the climb action </param> /// </summary> public void SetClimbState(ClimbState climbState) { if (this.climbState == climbState) { return; } this.climbState = climbState; if (climbState != ClimbState.None) { int index = (int)climbState; this.player.GetAnimatorManager().SetOtherAnimationSubstate(index); if (climbState == ClimbState.PullUp) { this.OnSwitchToPullUpState(); } else if (climbState == ClimbState.StandUp) { this.OnSwitchToStandUpState(); } } else { this.player.GetActionManager().EndCurrentAction(); this.player.GetAnimatorManager().SetOtherAnimationSubstate(0); } } /// <summary> /// Checks to slide of the wall or climb, the movement of the player while on the wall and whether the jump button was pressed to get off the wall /// </summary> private void HandleClimbingState() { this.player.velocity.y = this.player.GetInputManager().GetCurrentInput().y * this.player.GetPlayerPhysicsInfo().climbSpeed; //If the player tries to move upwards while the ceiling info is set neutralize the vertical velocity if (this.player.velocity.y > 0) { if (this.CheckForCeiling(this.player.transform.position) || this.player.PlayerIsAboveTopBounds() || (this.wallLedgeCollisionInfo.GetHit() && !General.CheckAngleIsWithinOrEqualRange(Mathf.RoundToInt(this.wallLedgeCollisionInfo.GetAngleInDegrees()), 90 + this.noClimbRadius, 270 - this.noClimbRadius))) { this.player.velocity.y = 0; } } this.player.SetPlayerDirection(this.wallDirection);//Face the wall D: if (this.player.GetInputManager().GetJumpButton().GetButtonPressed() && this.player.PlayerIsAboveTopBounds() == false) { int currentWallDirection = this.wallDirection;//This action is about to be exit and reset() so save the wall direction this.player.GetActionManager().PerformAction<Jump>(); this.player.velocity.x = 4 * -currentWallDirection;//Jump away from the wall this.player.velocity.y = 4; this.player.SetPlayerDirection((int)Mathf.Sign(this.player.velocity.x));//Be free return; } this.CheckForWallLedge(this.transform.position); if (this.player.velocity.y < 0) { this.CheckToFallOfLedge(this.transform.position); } } /// <summary> /// While in the pull up state force the animation frame based on the animation time of the coroutine /// </summary> private void HandlePullUpState() { this.player.GetAnimatorManager().PlayAnimation("Pull Up", this.currentAnimationTime); this.player.GetAnimatorManager().GetAnimator().Update(Time.deltaTime); } /// <summary> /// While the player is dropping from a climb we need to wait for them to hit the ground before standing up /// </summary> private void HandleDroppingState() { if (this.player.GetGrounded()) { this.player.GetAnimatorManager().GetAnimator().Update(Time.deltaTime); this.player.groundVelocity = 0; this.player.velocity.x = 0; this.player.GetInputManager().SetInputRestriction(InputRestriction.All); GMAudioManager.Instance().PlayOneShot(this.player.GetPlayerActionAudio().land); this.SetClimbState(ClimbState.StandUp); } } /// <summary> /// Calculate the actual position of the ledge and adjust the player accordingly /// </summary> private void FindLedgePosition(Vector2 position) { float distance = GMStageManager.Instance().GetMaxBlockSize(); SensorData sensorData = new SensorData(0, -90, 0, distance); Vector2 findLedgeSensorPositon = General.CalculateAngledObjectPosition(position, sensorData.GetAngleInRadians(), new Vector2((this.player.GetSensors().characterBuild.pushRadius + 1) * this.wallDirection, distance)); // B - Right Ground Sensor RaycastHit2D findLedgeSensor = Physics2D.Raycast(findLedgeSensorPositon, sensorData.GetCastDirection(), sensorData.GetCastDistance(), this.player.GetSensors().wallCollisionInfo.GetClimbableCollisionMask()); Debug.DrawLine(findLedgeSensorPositon, findLedgeSensorPositon + (sensorData.GetCastDirection() * sensorData.GetCastDistance()), this.findLedgeSensorColor); if (findLedgeSensor) { position.y = findLedgeSensor.point.y - this.player.GetSensors().currentBodyHeightRadius + 1f; this.ledgePosition = findLedgeSensor.point; } this.player.transform.position = position; } /// <summary> /// Check if the player has reached the top of the ledge /// </summary> private void CheckForWallLedge(Vector2 position) { SensorData sensorData = new SensorData(0, 0, 0, (this.player.GetSensors().characterBuild.pushRadius + 1) * this.wallDirection); Vector2 ledgeSensorPosition = General.CalculateAngledObjectPosition(position, sensorData.GetAngleInRadians(), new Vector2(0, this.player.GetSensors().currentBodyHeightRadius)); //Setup sensor position RaycastHit2D ledgeSensor = Physics2D.Raycast(ledgeSensorPosition, sensorData.GetCastDirection(), sensorData.GetCastDistance(), this.player.GetSensors().wallCollisionInfo.GetClimbableCollisionMask()); Debug.DrawLine(ledgeSensorPosition, ledgeSensorPosition + (sensorData.GetCastDirection() * sensorData.GetCastDistance()), this.ledgeSensorColor); if (ledgeSensor) { this.wallLedgeCollisionInfo = new CollisionInfoData(ledgeSensor, this.wallDirection == 1 ? SensorHitDirectionEnum.Right : SensorHitDirectionEnum.Left); } else { this.wallLedgeCollisionInfo = new CollisionInfoData(); } if (!ledgeSensor) { if (this.wallLedgeCollisionInfo.GetHit() && !General.CheckAngleIsWithinRange(Mathf.RoundToInt(this.wallLedgeCollisionInfo.GetAngleInDegrees()), 90 + this.noClimbRadius, 270 - this.noClimbRadius)) { return; } this.FindLedgePosition(position); this.SetClimbState(ClimbState.PullUp); } } /// <summary> /// Check if the player has reached the bottom of the ledge /// private void CheckToFallOfLedge(Vector2 position) { SensorData sensorData = new SensorData(0, 0, 0, (this.player.GetSensors().characterBuild.pushRadius + 1) * this.wallDirection); Vector2 fallSensorPosition = General.CalculateAngledObjectPosition(position, sensorData.GetAngleInRadians(), new Vector2(0, -this.player.GetSensors().currentBodyHeightRadius)); //Setup sensor position RaycastHit2D fallSensor = Physics2D.Raycast(fallSensorPosition, sensorData.GetCastDirection(), sensorData.GetCastDistance(), this.player.GetSensors().wallCollisionInfo.GetClimbableCollisionMask()); Debug.DrawLine(fallSensorPosition, fallSensorPosition + (sensorData.GetCastDirection() * sensorData.GetCastDistance()), this.fallSensorColor); if (!fallSensor) { this.player.velocity.y = 0; this.SetClimbState(ClimbState.Drop); } } public ClimbState GetClimbState() => this.climbState; /// <summary> /// Checks if there is a ceiling above the player /// <param name="position"> The current position of the player</param> /// </summary> private bool CheckForCeiling(Vector2 position) { float angleInRadians = 0; float sensorAngle = angleInRadians * Mathf.Rad2Deg;//The angle the sensors will be cast in Vector2 direction = General.AngleToVector(sensorAngle * Mathf.Deg2Rad); //Set the ray direction Vector2 ceilingCheckRange = new Vector2(this.player.GetSensors().characterBuild.bodyWidthRadius * 2, this.player.GetSensors().characterBuild.bodyHeightRadius); Vector2 lowCeilingSensorPosition = General.CalculateAngledObjectPosition(position, angleInRadians, new Vector2(-this.player.GetSensors().characterBuild.bodyWidthRadius, ceilingCheckRange.y)); RaycastHit2D lowCeilingSensor = Physics2D.Raycast(lowCeilingSensorPosition, direction, ceilingCheckRange.x, this.player.GetSensors().ceilingCollisionInfo.GetCollisionMask()); Debug.DrawLine(lowCeilingSensorPosition, lowCeilingSensorPosition + (direction * ceilingCheckRange), this.ceilingSensorColor); return lowCeilingSensor; } /// <summary> /// Actions performed when the pull up state is switched to /// </summary> private void OnSwitchToPullUpState() { this.finalPositionAfterPullUp = this.CalculatePlayerFinalPosition(); this.player.velocity.y = 0; this.player.GetInputManager().SetInputRestriction(InputRestriction.All); this.currentAnimationTime = 0; this.StartCoroutine(this.BeginPullUp()); this.StartCoroutine(this.PullUpCameraMovement()); } /// <summary> /// Actions performed when the stand up state is switched to /// </summary> private void OnSwitchToStandUpState() { this.player.GetSensors().SetSizeMode(SizeMode.Regular); this.StartCoroutine(this.WaitTillStandingCoroutine()); } /// <summary> /// Moves the player through the motions and position of the pull up animation /// </summary> private IEnumerator BeginPullUp() { yield return new WaitForEndOfFrame(); this.player.GetAnimatorManager().SetAnimatorSpeed(0); for (int x = 0; x < this.player.GetPlayerPhysicsInfo().pullUpPositionIncrements.Count; x++) { Vector2 position = this.player.transform.position; position += this.player.GetPlayerPhysicsInfo().pullUpPositionIncrements[x] * new Vector2(this.wallDirection, 1); this.player.transform.position = position; this.currentAnimationTime = x / (float)this.player.GetPlayerPhysicsInfo().pullUpPositionIncrements.Count; this.player.GetAnimatorManager().GetAnimator().playbackTime = this.currentAnimationTime; this.HandlePullUpState(); yield return new WaitForSeconds(this.player.GetPlayerPhysicsInfo().pullUpAnimationClip.length / 4f); } this.player.GetAnimatorManager().SetAnimatorSpeed(1); this.SetClimbState(ClimbState.StandUp); yield return null; } /// <summary> /// While doing a pullup we want to hijack the camera movement so it can perform a smooth follow to the end pull up point /// </summary> private IEnumerator PullUpCameraMovement() { //Hijack the camera movement and control it on this side in parallel to pull up HedgehogCamera hedgehogCamera = HedgehogCamera.Instance(); hedgehogCamera.SetCameraMode(CameraMode.Freeze); float currentTime = 0; Vector3 startPosition = hedgehogCamera.transform.position; Vector3 target = this.finalPositionAfterPullUp; target.z = hedgehogCamera.transform.position.z; while (currentTime < 1) { currentTime += Time.deltaTime / this.player.GetPlayerPhysicsInfo().pullUpAnimationClip.length; hedgehogCamera.SetCameraPosition(Vector3.Lerp(startPosition, target, currentTime)); yield return new WaitForFixedUpdate(); } hedgehogCamera.SetCameraMode(CameraMode.FollowTarget); yield return null; } /// <summary> /// Waits until the players standing animation is played out before moving on /// </summary> private IEnumerator WaitTillStandingCoroutine() { yield return new WaitForEndOfFrame(); while (this.climbState == ClimbState.StandUp && this.player.GetAnimatorManager().GetCurrentAnimationNormalizedTime() < 1) { yield return new WaitForFixedUpdate(); } this.SetClimbState(ClimbState.None); yield return null; } /// <summary> /// Check to see if the <see cref="GameObject"/> can be climbed /// </summary> /// <param name="target"></param> /// <returns></returns> private bool IsClimbable(GameObject target) { if (target == null) { return false; } bool objectIsInClimbableMask = General.ContainsLayer(this.player.GetSensors().wallCollisionInfo.GetClimbableCollisionMask(), target.layer); target.TryGetComponent<MonoBehaviour>(out MonoBehaviour targetObjectClass); //If its the object is not a MonoBehaviour checking if its in the climbable mask will suffice if (targetObjectClass == null) { return objectIsInClimbableMask; } //Checks if the object belongs to a class in our non climbable list bool cannotBeClimbed = this.player.GetPlayerPhysicsInfo().nonClimbableObjectControllers.Any(climbableObject => climbableObject == targetObjectClass.GetType().ToString()); if (cannotBeClimbed) { return false; } return objectIsInClimbableMask; } }
412
0.9161
1
0.9161
game-dev
MEDIA
0.980557
game-dev
0.990155
1
0.990155
Winds-Studio/Leaf
3,333
leaf-archived-patches/removed/1.21.8/mcserver/0185-Cache-random-tick-block-status.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Dreeam <61569423+Dreeam-qwq@users.noreply.github.com> Date: Sat, 23 Nov 2024 09:04:46 -0500 Subject: [PATCH] Cache random tick block status Removed since Leaf 1.21.8, useless. Leaf already has random tick optimization diff --git a/net/minecraft/world/level/chunk/LevelChunkSection.java b/net/minecraft/world/level/chunk/LevelChunkSection.java index df717c545472006b99532280c38c1fbef12bcf82..36c033b0ee63dfc273d721fb4b614733e8fdef19 100644 --- a/net/minecraft/world/level/chunk/LevelChunkSection.java +++ b/net/minecraft/world/level/chunk/LevelChunkSection.java @@ -21,6 +21,7 @@ public class LevelChunkSection implements ca.spottedleaf.moonrise.patches.block_ short nonEmptyBlockCount; // Paper - package private private short tickingBlockCount; private short tickingFluidCount; + private boolean isRandomlyTickingBlocksStatus; // Leaf - Cache random tick block status public final PalettedContainer<BlockState> states; private PalettedContainer<Holder<Biome>> biomes; // CraftBukkit - read/write @@ -54,6 +55,7 @@ public class LevelChunkSection implements ca.spottedleaf.moonrise.patches.block_ this.tickingFluidCount = section.tickingFluidCount; this.states = section.states.copy(); this.biomes = section.biomes.copy(); + this.isRandomlyTickingBlocksStatus = this.tickingBlockCount > 0; // Leaf - Cache random tick block status } public LevelChunkSection(PalettedContainer<BlockState> states, PalettedContainer<Holder<Biome>> biomes) { // CraftBukkit - read/write @@ -165,6 +167,7 @@ public class LevelChunkSection implements ca.spottedleaf.moonrise.patches.block_ } this.updateBlockCallback(x, y, z, state, blockState); // Paper - block counting + this.isRandomlyTickingBlocksStatus = this.tickingBlockCount > 0; // Leaf - Cache random tick block status return blockState; } @@ -178,7 +181,7 @@ public class LevelChunkSection implements ca.spottedleaf.moonrise.patches.block_ } public boolean isRandomlyTickingBlocks() { - return this.tickingBlockCount > 0; + return isRandomlyTickingBlocksStatus; // Leaf - Cache random tick block status } public boolean isRandomlyTickingFluids() { @@ -193,6 +196,7 @@ public class LevelChunkSection implements ca.spottedleaf.moonrise.patches.block_ this.tickingFluidCount = (short)0; this.specialCollidingBlocks = (short)0; this.tickingBlocks.clear(); + this.isRandomlyTickingBlocksStatus = false; // Leaf - Cache random tick block status if (this.maybeHas((final BlockState state) -> !state.isAir())) { final PalettedContainer.Data<BlockState> data = this.states.data; @@ -226,6 +230,7 @@ public class LevelChunkSection implements ca.spottedleaf.moonrise.patches.block_ this.nonEmptyBlockCount += (short)paletteCount; if (state.isRandomlyTicking()) { this.tickingBlockCount += (short)paletteCount; + this.isRandomlyTickingBlocksStatus = this.tickingBlockCount > 0; // Leaf - Cache random tick block status final short[] raw = coordinates.elements(); final int rawLen = raw.length;
412
0.681244
1
0.681244
game-dev
MEDIA
0.951406
game-dev
0.880562
1
0.880562
ProjectIgnis/CardScripts
1,836
rush/c160019035.lua
--トランザム・アサルトライナック --Transamu Assault Rainac --Scripted by YoshiDuels local s,id=GetID() function s.initial_effect(c) --Fusion Procedure c:EnableReviveLimit() Fusion.AddProcMixN(c,true,true,CARD_TRANSAMU_RAINAC,1,s.ffilter,1) --Reduce Level local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCondition(s.condition) e1:SetCost(s.cost) e1:SetOperation(s.operation) c:RegisterEffect(e1) end s.named_material={CARD_TRANSAMU_RAINAC} function s.ffilter(c,fc,sumtype,tp) return c:IsType(TYPE_EFFECT,fc,sumtype,tp) and c:IsRace(RACE_GALAXY,fc,sumtype,tp) and not c:IsLevel(7) end function s.condition(e,tp,eg,ep,ev,re,r,r,rp) return e:GetHandler():IsLevelAbove(4) end function s.filter(c) return c:IsMonster() and c:IsAbleToDeckOrExtraAsCost() end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.filter,tp,LOCATION_GRAVE,0,2,nil) end end function s.checkfilter(c) return c:IsLocation(LOCATION_DECK) and c:IsCode(160402024) end function s.operation(e,tp,eg,ep,ev,re,r,rp) --Requirement Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g=Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_GRAVE,0,2,2,nil) if #g==0 then return end Duel.HintSelection(g) if Duel.SendtoDeck(g,nil,SEQ_DECKSHUFFLE,REASON_COST)==0 then return end --Effect local c=e:GetHandler() --decrease level by 3 c:UpdateLevel(-3,RESETS_STANDARD_PHASE_END,c) if g:FilterCount(s.checkfilter,nil)>0 then local e1=Effect.CreateEffect(c) e1:SetDescription(3208) e1:SetProperty(EFFECT_FLAG_CLIENT_HINT) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_PIERCE) e1:SetReset(RESETS_STANDARD_PHASE_END) e1:SetValue(DOUBLE_DAMAGE) c:RegisterEffect(e1) end end
412
0.957551
1
0.957551
game-dev
MEDIA
0.954095
game-dev
0.970456
1
0.970456
LandSandBoat/server
1,139
scripts/missions/rotz/10_The_Temple_of_Desolation.lua
----------------------------------- -- The Temple of Desolation -- Zilart M10 ----------------------------------- -- !addmission 3 20 -- Kamui : !pos 120.121 -8.009 -7.298 252 -- _6z0 : !pos 0 -12 48 251 ----------------------------------- local mission = Mission:new(xi.mission.log_id.ZILART, xi.mission.id.zilart.THE_TEMPLE_OF_DESOLATION) mission.reward = { title = xi.title.SEALER_OF_THE_PORTAL_OF_THE_GODS, nextMission = { xi.mission.log_id.ZILART, xi.mission.id.zilart.THE_HALL_OF_THE_GODS }, } mission.sections = { { check = function(player, currentMission, missionStatus, vars) return currentMission == mission.missionId end, [xi.zone.NORG] = { ['Gilgamesh'] = mission:event(10), ['Kamui'] = mission:event(11), }, [xi.zone.HALL_OF_THE_GODS] = { ['_6z0'] = mission:progressEvent(1), onEventFinish = { [1] = function(player, csid, option, npc) mission:complete(player) end, }, }, }, } return mission
412
0.561166
1
0.561166
game-dev
MEDIA
0.876859
game-dev
0.519875
1
0.519875
habanero-rice/hclib
1,070
test/performance-regression/full-apps/kastors-1.1/jacobi/src/jacobi-block-for.cuda.c
#include "hclib.h" #ifdef __cplusplus #include "hclib_cpp.h" #include "hclib_system.h" #ifdef __CUDACC__ #include "hclib_cuda.h" #endif #endif # include "poisson.h" /* #pragma omp task/taskwait version of SWEEP. */ void sweep (int nx, int ny, double dx, double dy, double *f_, int itold, int itnew, double *u_, double *unew_, int block_size) { int it; int block_x, block_y; if (block_size == 0) block_size = nx; int max_blocks_x = (nx / block_size); int max_blocks_y = (ny / block_size); for (it = itold + 1; it <= itnew; it++) { // Save the current estimate. for (block_x = 0; block_x < max_blocks_x; block_x++) for (block_y = 0; block_y < max_blocks_y; block_y++) copy_block(nx, ny, block_x, block_y, u_, unew_, block_size); for (block_x = 0; block_x < max_blocks_x; block_x++) for (block_y = 0; block_y < max_blocks_y; block_y++) compute_estimate(block_x, block_y, u_, unew_, f_, dx, dy, nx, ny, block_size); } }
412
0.871205
1
0.871205
game-dev
MEDIA
0.681804
game-dev
0.915927
1
0.915927
TheThirdOne/rars
1,064
src/rars/riscv/instructions/FSQRTD.java
package rars.riscv.instructions; import jsoftfloat.Environment; import jsoftfloat.types.Float64; import rars.ProgramStatement; import rars.SimulationException; import rars.riscv.BasicInstruction; import rars.riscv.BasicInstructionFormat; import rars.riscv.hardware.FloatingPointRegisterFile; public class FSQRTD extends BasicInstruction { public FSQRTD() { super("fsqrt.d f1, f2, dyn", "Floating SQuare RooT (64 bit): Assigns f1 to the square root of f2", BasicInstructionFormat.I_FORMAT, "0101101 00000 sssss ttt fffff 1010011"); } public void simulate(ProgramStatement statement) throws SimulationException { int[] operands = statement.getOperands(); Environment e = new Environment(); e.mode = Floating.getRoundingMode(operands[2],statement); Float64 result = jsoftfloat.operations.Arithmetic.squareRoot(new Float64(FloatingPointRegisterFile.getValueLong(operands[1])),e); Floating.setfflags(e); FloatingPointRegisterFile.updateRegisterLong(operands[0],result.bits); } }
412
0.763732
1
0.763732
game-dev
MEDIA
0.334915
game-dev
0.934745
1
0.934745
Fluorohydride/ygopro-scripts
4,137
c88693151.lua
--トリックスター・フュージョン function c88693151.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(88693151,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_FUSION_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c88693151.target) e1:SetOperation(c88693151.activate) c:RegisterEffect(e1) --salvage local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_TOHAND) e2:SetDescription(aux.Stringid(88693151,1)) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_GRAVE) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCost(aux.bfgcost) e2:SetTarget(c88693151.thtg) e2:SetOperation(c88693151.thop) c:RegisterEffect(e2) end function c88693151.filter1(c,e) return not c:IsImmuneToEffect(e) end function c88693151.filter2(c,e,tp,m,f,chkf) return c:IsType(TYPE_FUSION) and c:IsSetCard(0xfb) and (not f or f(c)) and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_FUSION,tp,false,false) and c:CheckFusionMaterial(m,nil,chkf) end function c88693151.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then local chkf=tp local mg1=Duel.GetFusionMaterial(tp) local res=Duel.IsExistingMatchingCard(c88693151.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg1,nil,chkf) if not res then local ce=Duel.GetChainMaterial(tp) if ce~=nil then local fgroup=ce:GetTarget() local mg2=fgroup(ce,e,tp) local mf=ce:GetValue() res=Duel.IsExistingMatchingCard(c88693151.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg2,mf,chkf) end end return res end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) end function c88693151.activate(e,tp,eg,ep,ev,re,r,rp) local chkf=tp local mg1=Duel.GetFusionMaterial(tp):Filter(c88693151.filter1,nil,e) local sg1=Duel.GetMatchingGroup(c88693151.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg1,nil,chkf) local mg2=nil local sg2=nil local ce=Duel.GetChainMaterial(tp) if ce~=nil then local fgroup=ce:GetTarget() mg2=fgroup(ce,e,tp) local mf=ce:GetValue() sg2=Duel.GetMatchingGroup(c88693151.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg2,mf,chkf) end if sg1:GetCount()>0 or (sg2~=nil and sg2:GetCount()>0) then local sg=sg1:Clone() if sg2 then sg:Merge(sg2) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local tg=sg:Select(tp,1,1,nil) local tc=tg:GetFirst() if sg1:IsContains(tc) and (sg2==nil or not sg2:IsContains(tc) or not Duel.SelectYesNo(tp,ce:GetDescription())) then local mat1=Duel.SelectFusionMaterial(tp,tc,mg1,nil,chkf) tc:SetMaterial(mat1) Duel.SendtoGrave(mat1,REASON_EFFECT+REASON_MATERIAL+REASON_FUSION) Duel.BreakEffect() Duel.SpecialSummon(tc,SUMMON_TYPE_FUSION,tp,tp,false,false,POS_FACEUP) else local mat2=Duel.SelectFusionMaterial(tp,tc,mg2,nil,chkf) local fop=ce:GetOperation() fop(ce,e,tp,tc,mat2) end tc:CompleteProcedure() end end function c88693151.thfilter(c) return c:IsSetCard(0xfb) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c88693151.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c88693151.thfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c88693151.thfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectTarget(tp,c88693151.thfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0) end function c88693151.thop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and Duel.SendtoHand(tc,nil,REASON_EFFECT)~=0 and tc:IsLocation(LOCATION_HAND) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_SUMMON) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetTarget(c88693151.sumlimit) e1:SetLabel(tc:GetCode()) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) local e2=e1:Clone() e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) Duel.RegisterEffect(e2,tp) local e3=e1:Clone() e3:SetCode(EFFECT_CANNOT_MSET) Duel.RegisterEffect(e3,tp) end end function c88693151.sumlimit(e,c) return c:IsCode(e:GetLabel()) end
412
0.948561
1
0.948561
game-dev
MEDIA
0.986195
game-dev
0.967019
1
0.967019
lua9520/source-engine-2018-cstrike15_src
1,377
game/server/weapon_cubemap.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" class CWeaponCubemap : public CBaseCombatWeapon { public: DECLARE_CLASS( CWeaponCubemap, CBaseCombatWeapon ); void Precache( void ); bool HasAnyAmmo( void ) { return true; } void Spawn( void ); DECLARE_SERVERCLASS(); }; LINK_ENTITY_TO_CLASS( weapon_cubemap, CWeaponCubemap ); IMPLEMENT_SERVERCLASS_ST( CWeaponCubemap, DT_WeaponCubemap ) END_SEND_TABLE() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponCubemap::Precache( void ) { BaseClass::Precache(); } void CWeaponCubemap::Spawn( void ) { BaseClass::Spawn(); //Hack to fix the cubemap weapon not being held by the player. //Problem is the model has huge bounds so the new pickup code that checks if the player can see the model fails cause half the entity's bounds are inside the ground. //Since this is just a dev tool I made this quick hack so level designers can use it again asap. - Adrian UTIL_SetSize( this, Vector( -16, -16, -16 ), Vector( 16, 16, 16 ) ); }
412
0.830498
1
0.830498
game-dev
MEDIA
0.983651
game-dev
0.875885
1
0.875885
magefree/mage
2,413
Mage.Sets/src/mage/cards/s/SageOfAncientLore.java
package mage.cards.s; import mage.MageInt; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.common.WerewolfFrontTriggeredAbility; import mage.abilities.condition.common.NotTransformedCondition; import mage.abilities.decorator.ConditionalContinuousEffect; import mage.abilities.dynamicvalue.common.CardsInControllerHandCount; import mage.abilities.effects.common.DrawCardSourceControllerEffect; import mage.abilities.effects.common.continuous.SetBasePowerToughnessSourceEffect; import mage.abilities.keyword.TransformAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Zone; import java.util.UUID; /** * @author fireshoes */ public final class SageOfAncientLore extends CardImpl { public SageOfAncientLore(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{G}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.SHAMAN); this.subtype.add(SubType.WEREWOLF); this.power = new MageInt(0); this.toughness = new MageInt(0); this.secondSideCardClazz = mage.cards.w.WerewolfOfAncientHunger.class; // Sage of Ancient Lore's power and toughness are each equal to the number of cards in your hand. this.addAbility(new SimpleStaticAbility( Zone.ALL, new ConditionalContinuousEffect( new SetBasePowerToughnessSourceEffect(CardsInControllerHandCount.ANY), NotTransformedCondition.instance, "{this}'s power and toughness are each equal to the total number of cards in your hand" ) )); // When Sage of Ancient Lore enters the battlefield, draw a card. this.addAbility(new EntersBattlefieldTriggeredAbility(new DrawCardSourceControllerEffect(1), false)); // At the beginning of each upkeep, if no spells were cast last turn, transform Sage of Ancient Lore. this.addAbility(new TransformAbility()); this.addAbility(new WerewolfFrontTriggeredAbility()); } private SageOfAncientLore(final SageOfAncientLore card) { super(card); } @Override public SageOfAncientLore copy() { return new SageOfAncientLore(this); } }
412
0.936329
1
0.936329
game-dev
MEDIA
0.978589
game-dev
0.995014
1
0.995014
FallingColors/HexMod
2,039
Fabric/src/main/java/at/petrak/hexcasting/fabric/cc/adimpl/CCHexHolder.java
package at.petrak.hexcasting.fabric.cc.adimpl; import at.petrak.hexcasting.api.addldata.ADHexHolder; import at.petrak.hexcasting.api.item.HexHolderItem; import at.petrak.hexcasting.api.casting.iota.Iota; import at.petrak.hexcasting.api.pigment.FrozenPigment; import at.petrak.hexcasting.fabric.cc.HexCardinalComponents; import dev.onyxstudios.cca.api.v3.item.ItemComponent; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.Nullable; import java.util.List; public abstract class CCHexHolder extends ItemComponent implements ADHexHolder { public CCHexHolder(ItemStack stack) { super(stack, HexCardinalComponents.HEX_HOLDER); } public static class ItemBased extends CCHexHolder { private final HexHolderItem hexHolder; public ItemBased(ItemStack owner) { super(owner); var item = owner.getItem(); if (!(item instanceof HexHolderItem hexHolderItem)) { throw new IllegalStateException("item is not a pigment: " + owner); } this.hexHolder = hexHolderItem; } @Override public boolean canDrawMediaFromInventory() { return this.hexHolder.canDrawMediaFromInventory(this.stack); } @Override public boolean hasHex() { return this.hexHolder.hasHex(this.stack); } @Override public @Nullable List<Iota> getHex(ServerLevel level) { return this.hexHolder.getHex(this.stack, level); } @Override public void writeHex(List<Iota> patterns, @Nullable FrozenPigment pigment, long media) { this.hexHolder.writeHex(this.stack, patterns, pigment, media); } @Override public void clearHex() { this.hexHolder.clearHex(this.stack); } @Override public @Nullable FrozenPigment getPigment() { return this.hexHolder.getPigment(this.stack); } } }
412
0.810978
1
0.810978
game-dev
MEDIA
0.951551
game-dev
0.72506
1
0.72506
magefree/mage
1,556
Mage.Sets/src/mage/cards/c/CabalCoffers.java
package mage.cards.c; import java.util.UUID; import mage.Mana; import mage.abilities.Ability; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.costs.mana.GenericManaCost; import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount; import mage.abilities.hint.Hint; import mage.abilities.hint.ValueHint; import mage.abilities.mana.DynamicManaAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.common.FilterControlledPermanent; /** * * @author North */ public final class CabalCoffers extends CardImpl { private static final FilterControlledPermanent filter = new FilterControlledPermanent("Swamp you control"); static { filter.add(SubType.SWAMP.getPredicate()); } private static final Hint hint = new ValueHint( "Swamps you control", new PermanentsOnBattlefieldCount(filter) ); public CabalCoffers(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.LAND}, ""); // {2}, {T}: Add {B} for each Swamp you control. Ability ability = new DynamicManaAbility(Mana.BlackMana(1), new PermanentsOnBattlefieldCount(filter), new GenericManaCost(2)); ability.addCost(new TapSourceCost()); this.addAbility(ability.addHint(hint)); } private CabalCoffers(final CabalCoffers card) { super(card); } @Override public CabalCoffers copy() { return new CabalCoffers(this); } }
412
0.944117
1
0.944117
game-dev
MEDIA
0.961521
game-dev
0.992925
1
0.992925
Squalr/Squally
4,402
Source/Objects/Platformer/Breakables/BreakableCage.cpp
#include "BreakableCage.h" #include "cocos/2d/CCActionInstant.h" #include "cocos/2d/CCActionInterval.h" #include "cocos/2d/CCSprite.h" #include "Engine/Animations/SmartAnimationSequenceNode.h" #include "Engine/Events/ObjectEvents.h" #include "Engine/Physics/CollisionObject.h" #include "Engine/Sound/WorldSound.h" #include "Scenes/Platformer/Level/Physics/PlatformerPhysicsTypes.h" #include "Resources/FXResources.h" #include "Resources/ObjectResources.h" #include "Resources/SoundResources.h" using namespace cocos2d; const std::string BreakableCage::MapKey = "breakable-cage"; BreakableCage* BreakableCage::create(ValueMap& properties) { BreakableCage* instance = new BreakableCage(properties); instance->autorelease(); return instance; } BreakableCage::BreakableCage(ValueMap& properties, int requiredHits) : super(properties, CSize(196.0f, 112.0f + 64.0f), requiredHits) { this->cageBottom = CollisionObject::create(CollisionObject::createBox(CSize(160.0f, 32.0f)), (CollisionType)PlatformerCollisionType::Physics, CollisionObject::Properties(true, true, 0.1f, 0.2f)); this->cagedContentNode = Node::create(); this->cage = CollisionObject::create(CollisionObject::createBox(CSize(160.0f, 112.0f)), (CollisionType)PlatformerCollisionType::Physics, CollisionObject::Properties(true, true, 0.1f, 0.2f)); this->cageTop = CollisionObject::create(CollisionObject::createBox(CSize(160.0f, 32.0f)), (CollisionType)PlatformerCollisionType::Physics, CollisionObject::Properties(true, true, 0.1f, 0.2f)); this->explosion = SmartAnimationSequenceNode::create(); this->breakSound = WorldSound::create(SoundResources::Platformer_Objects_WoodBreak_WoodBreak1); this->cageBottom->addChild(Sprite::create(ObjectResources::Breakables_CageBottom)); this->cage->addChild(Sprite::create(ObjectResources::Breakables_CageSide)); this->cageTop->addChild(Sprite::create(ObjectResources::Breakables_CageTop)); this->cageBottom->setPhysicsFlagEnabled(false); this->cage->setPhysicsFlagEnabled(false); this->cageTop->setPhysicsFlagEnabled(false); this->contentNode->addChild(this->cageBottom); this->contentNode->addChild(this->cagedContentNode); this->contentNode->addChild(this->cage); this->contentNode->addChild(this->cageTop); this->contentNode->addChild(this->explosion); this->contentNode->addChild(this->breakSound); } BreakableCage::~BreakableCage() { } void BreakableCage::initializePositions() { super::initializePositions(); this->cageBottom->setPosition(Vec2(0.0f, -48.0f)); this->contentNode->setPosition(Vec2(0.0f, 0.0f)); this->cage->setPosition(Vec2(0.0f, 0.0f)); this->cageTop->setPosition(Vec2(-4.0f, 58.0f)); } void BreakableCage::initializeListeners() { super::initializeListeners(); this->cageBottom->whileCollidesWith({ (CollisionType)PlatformerCollisionType::Solid, (CollisionType)PlatformerCollisionType::PassThrough, (CollisionType)PlatformerCollisionType::Physics, (CollisionType)PlatformerCollisionType::Player, (CollisionType)PlatformerCollisionType::PlayerWeapon }, [=](CollisionData collisionData) { return CollisionResult::CollideWithPhysics; }); this->cage->whileCollidesWith({ (CollisionType)PlatformerCollisionType::Solid, (CollisionType)PlatformerCollisionType::PassThrough, (CollisionType)PlatformerCollisionType::Physics, (CollisionType)PlatformerCollisionType::Player, (CollisionType)PlatformerCollisionType::PlayerWeapon }, [=](CollisionData collisionData) { return CollisionResult::CollideWithPhysics; }); this->cageTop->whileCollidesWith({ (CollisionType)PlatformerCollisionType::Solid, (CollisionType)PlatformerCollisionType::PassThrough, (CollisionType)PlatformerCollisionType::Physics, (CollisionType)PlatformerCollisionType::Player, (CollisionType)PlatformerCollisionType::PlayerWeapon }, [=](CollisionData collisionData) { return CollisionResult::CollideWithPhysics; }); } Vec2 BreakableCage::getButtonOffset() { return Vec2(0.0f, 96.0f); } void BreakableCage::onBreak() { super::onBreak(); this->explosion->playAnimation(FXResources::ExplosionNormal_Explosion_0000, 0.035f, true); this->cageBottom->setPhysicsFlagEnabled(true); this->cage->setPhysicsFlagEnabled(true); this->cageTop->setPhysicsFlagEnabled(true); this->breakSound->play(); this->cageBottom->setVelocity(Vec2(-12800.0f, 7600.0f)); this->cage->setVelocity(Vec2(-6400.0f, 5600.0f)); this->cageTop->setVelocity(Vec2(12800.0f, 9600.0f)); }
412
0.631988
1
0.631988
game-dev
MEDIA
0.986319
game-dev
0.880392
1
0.880392
0015/map_tiles
8,744
examples/basic_map_display.c
#include "map_tiles.h" #include "lvgl.h" #include "esp_log.h" static const char* TAG = "map_example"; // Map tiles handle static map_tiles_handle_t map_handle = NULL; // LVGL objects for displaying tiles static lv_obj_t* map_container = NULL; static lv_obj_t** tile_images = NULL; // Dynamic array for configurable grid static int grid_cols = 0, grid_rows = 0, tile_count = 0; /** * @brief Initialize the map display */ void map_display_init(void) { // Configure map tiles with multiple tile types and custom grid size const char* tile_folders[] = {"street_map", "satellite", "terrain", "hybrid"}; map_tiles_config_t config = { .base_path = "/sdcard", .tile_folders = {tile_folders[0], tile_folders[1], tile_folders[2], tile_folders[3]}, .tile_type_count = 4, .default_zoom = 10, .use_spiram = true, .default_tile_type = 0, // Start with street map .grid_cols = 5, // 5x5 grid (configurable) .grid_rows = 5 }; // Initialize map tiles map_handle = map_tiles_init(&config); if (!map_handle) { ESP_LOGE(TAG, "Failed to initialize map tiles"); return; } // Get grid dimensions map_tiles_get_grid_size(map_handle, &grid_cols, &grid_rows); tile_count = map_tiles_get_tile_count(map_handle); // Allocate tile images array tile_images = malloc(tile_count * sizeof(lv_obj_t*)); if (!tile_images) { ESP_LOGE(TAG, "Failed to allocate tile images array"); map_tiles_cleanup(map_handle); return; } // Create map container map_container = lv_obj_create(lv_screen_active()); lv_obj_set_size(map_container, grid_cols * MAP_TILES_TILE_SIZE, grid_rows * MAP_TILES_TILE_SIZE); lv_obj_center(map_container); lv_obj_set_style_pad_all(map_container, 0, 0); lv_obj_set_style_border_width(map_container, 0, 0); // Create image widgets for each tile for (int i = 0; i < tile_count; i++) { tile_images[i] = lv_image_create(map_container); // Position tile in grid int row = i / grid_cols; int col = i % grid_cols; lv_obj_set_pos(tile_images[i], col * MAP_TILES_TILE_SIZE, row * MAP_TILES_TILE_SIZE); lv_obj_set_size(tile_images[i], MAP_TILES_TILE_SIZE, MAP_TILES_TILE_SIZE); } ESP_LOGI(TAG, "Map display initialized"); } /** * @brief Load and display map tiles for a GPS location * * @param lat Latitude in degrees * @param lon Longitude in degrees */ void map_display_load_location(double lat, double lon) { if (!map_handle) { ESP_LOGE(TAG, "Map not initialized"); return; } ESP_LOGI(TAG, "Loading map for GPS: %.6f, %.6f", lat, lon); // Set center from GPS coordinates map_tiles_set_center_from_gps(map_handle, lat, lon); // Get current tile position int base_tile_x, base_tile_y; map_tiles_get_position(map_handle, &base_tile_x, &base_tile_y); // Load tiles in a configurable grid for (int row = 0; row < grid_rows; row++) { for (int col = 0; col < grid_cols; col++) { int index = row * grid_cols + col; int tile_x = base_tile_x + col; int tile_y = base_tile_y + row; // Load the tile bool loaded = map_tiles_load_tile(map_handle, index, tile_x, tile_y); if (loaded) { // Update the image widget lv_image_dsc_t* img_dsc = map_tiles_get_image(map_handle, index); if (img_dsc) { lv_image_set_src(tile_images[index], img_dsc); ESP_LOGD(TAG, "Loaded tile %d (%d, %d)", index, tile_x, tile_y); } } else { ESP_LOGW(TAG, "Failed to load tile %d (%d, %d)", index, tile_x, tile_y); // Set a placeholder or clear the image lv_image_set_src(tile_images[index], NULL); } } } ESP_LOGI(TAG, "Map tiles loaded for location"); } /** * @brief Set the map tile type and reload tiles * * @param tile_type Tile type index (0=street, 1=satellite, 2=terrain, 3=hybrid) * @param lat Current latitude * @param lon Current longitude */ void map_display_set_tile_type(int tile_type, double lat, double lon) { if (!map_handle) { ESP_LOGE(TAG, "Map not initialized"); return; } // Validate tile type int max_types = map_tiles_get_tile_type_count(map_handle); if (tile_type < 0 || tile_type >= max_types) { ESP_LOGW(TAG, "Invalid tile type %d (valid range: 0-%d)", tile_type, max_types - 1); return; } ESP_LOGI(TAG, "Setting tile type to %d (%s)", tile_type, map_tiles_get_tile_type_folder(map_handle, tile_type)); // Set tile type if (map_tiles_set_tile_type(map_handle, tile_type)) { // Reload tiles for the new type map_display_load_location(lat, lon); } } /** * @brief Set the zoom level and reload tiles * * @param zoom New zoom level * @param lat Current latitude * @param lon Current longitude */ void map_display_set_zoom(int zoom, double lat, double lon) { if (!map_handle) { ESP_LOGE(TAG, "Map not initialized"); return; } ESP_LOGI(TAG, "Setting zoom to %d", zoom); // Update zoom level map_tiles_set_zoom(map_handle, zoom); // Reload tiles for the new zoom level map_display_load_location(lat, lon); } /** * @brief Add a GPS marker to the map * * @param lat Latitude in degrees * @param lon Longitude in degrees */ void map_display_add_marker(double lat, double lon) { if (!map_handle) { ESP_LOGE(TAG, "Map not initialized"); return; } // Check if GPS position is within current tiles if (!map_tiles_is_gps_within_tiles(map_handle, lat, lon)) { ESP_LOGW(TAG, "GPS position outside current tiles, reloading map"); map_display_load_location(lat, lon); return; } // Get marker offset within the current tile grid int offset_x, offset_y; map_tiles_get_marker_offset(map_handle, &offset_x, &offset_y); // Create or update marker object static lv_obj_t* marker = NULL; if (!marker) { marker = lv_obj_create(map_container); lv_obj_set_size(marker, 10, 10); lv_obj_set_style_bg_color(marker, lv_color_hex(0xFF0000), 0); lv_obj_set_style_radius(marker, 5, 0); lv_obj_set_style_border_width(marker, 1, 0); lv_obj_set_style_border_color(marker, lv_color_hex(0xFFFFFF), 0); } // Position marker based on GPS offset int center_tile_col = grid_cols / 2; int center_tile_row = grid_rows / 2; int marker_x = center_tile_col * MAP_TILES_TILE_SIZE + offset_x - 5; int marker_y = center_tile_row * MAP_TILES_TILE_SIZE + offset_y - 5; lv_obj_set_pos(marker, marker_x, marker_y); ESP_LOGI(TAG, "GPS marker positioned at (%d, %d)", marker_x, marker_y); } /** * @brief Clean up map display resources */ void map_display_cleanup(void) { if (tile_images) { free(tile_images); tile_images = NULL; } if (map_handle) { map_tiles_cleanup(map_handle); map_handle = NULL; } if (map_container) { lv_obj_delete(map_container); map_container = NULL; } grid_cols = grid_rows = tile_count = 0; ESP_LOGI(TAG, "Map display cleaned up"); } /** * @brief Example usage in main application */ void app_main(void) { // Initialize LVGL and display driver first... // Initialize map display map_display_init(); // Load map for San Francisco double lat = 37.7749; double lon = -122.4194; map_display_load_location(lat, lon); // Add GPS marker map_display_add_marker(lat, lon); // Example: Change to satellite view (tile type 1) // map_display_set_tile_type(1, lat, lon); // Example: Change to terrain view (tile type 2) // map_display_set_tile_type(2, lat, lon); // Example: Change zoom level // map_display_set_zoom(12, lat, lon); // Example: Update GPS position // map_display_add_marker(37.7849, -122.4094); // NOTE: To use different grid sizes, modify the grid_cols and grid_rows // in the config structure above. Examples: // - 3x3 grid: .grid_cols = 3, .grid_rows = 3 (9 tiles, ~1.1MB RAM) // - 5x5 grid: .grid_cols = 5, .grid_rows = 5 (25 tiles, ~3.1MB RAM) // - 7x7 grid: .grid_cols = 7, .grid_rows = 7 (49 tiles, ~6.1MB RAM) }
412
0.930261
1
0.930261
game-dev
MEDIA
0.619206
game-dev
0.835267
1
0.835267
NetCodersX/Unity-Script
9,657
2d 寻路/Assets/AstarPathfindingProject/Core/Misc/MovementUtilities.cs
using UnityEngine; using System.Collections; namespace Pathfinding.Util { public static class MovementUtilities { /// <summary> /// Clamps the velocity to the max speed and optionally the forwards direction. /// /// Note that all vectors are 2D vectors, not 3D vectors. /// /// Returns: The clamped velocity in world units per second. /// </summary> /// <param name="velocity">Desired velocity of the character. In world units per second.</param> /// <param name="maxSpeed">Max speed of the character. In world units per second.</param> /// <param name="slowdownFactor">Value between 0 and 1 which determines how much slower the character should move than normal. /// Normally 1 but should go to 0 when the character approaches the end of the path.</param> /// <param name="slowWhenNotFacingTarget">Prevent the velocity from being too far away from the forward direction of the character /// and slow the character down if the desired velocity is not in the same direction as the forward vector.</param> /// <param name="forward">Forward direction of the character. Used together with the slowWhenNotFacingTarget parameter.</param> public static Vector2 ClampVelocity (Vector2 velocity, float maxSpeed, float slowdownFactor, bool slowWhenNotFacingTarget, Vector2 forward) { // Max speed to use for this frame var currentMaxSpeed = maxSpeed * slowdownFactor; // Check if the agent should slow down in case it is not facing the direction it wants to move in if (slowWhenNotFacingTarget && (forward.x != 0 || forward.y != 0)) { float currentSpeed; var normalizedVelocity = VectorMath.Normalize(velocity, out currentSpeed); float dot = Vector2.Dot(normalizedVelocity, forward); // Lower the speed when the character's forward direction is not pointing towards the desired velocity // 1 when velocity is in the same direction as forward // 0.2 when they point in the opposite directions float directionSpeedFactor = Mathf.Clamp(dot+0.707f, 0.2f, 1.0f); currentMaxSpeed *= directionSpeedFactor; currentSpeed = Mathf.Min(currentSpeed, currentMaxSpeed); // Angle between the forwards direction of the character and our desired velocity float angle = Mathf.Acos(Mathf.Clamp(dot, -1, 1)); // Clamp the angle to 20 degrees // We cannot keep the velocity exactly in the forwards direction of the character // because we use the rotation to determine in which direction to rotate and if // the velocity would always be in the forwards direction of the character then // the character would never rotate. // Allow larger angles when near the end of the path to prevent oscillations. angle = Mathf.Min(angle, (20f + 180f*(1 - slowdownFactor*slowdownFactor))*Mathf.Deg2Rad); float sin = Mathf.Sin(angle); float cos = Mathf.Cos(angle); // Determine if we should rotate clockwise or counter-clockwise to move towards the current velocity sin *= Mathf.Sign(normalizedVelocity.x*forward.y - normalizedVelocity.y*forward.x); // Rotate the #forward vector by #angle radians // The rotation is done using an inlined rotation matrix. // See https://en.wikipedia.org/wiki/Rotation_matrix return new Vector2(forward.x*cos + forward.y*sin, forward.y*cos - forward.x*sin) * currentSpeed; } else { return Vector2.ClampMagnitude(velocity, currentMaxSpeed); } } /// <summary>Calculate an acceleration to move deltaPosition units and get there with approximately a velocity of targetVelocity</summary> public static Vector2 CalculateAccelerationToReachPoint (Vector2 deltaPosition, Vector2 targetVelocity, Vector2 currentVelocity, float forwardsAcceleration, float rotationSpeed, float maxSpeed, Vector2 forwardsVector) { // Guard against div by zero if (forwardsAcceleration <= 0) return Vector2.zero; float currentSpeed = currentVelocity.magnitude; // Convert rotation speed to an acceleration // See https://en.wikipedia.org/wiki/Centripetal_force var sidewaysAcceleration = currentSpeed * rotationSpeed * Mathf.Deg2Rad; // To avoid weird behaviour when the rotation speed is very low we allow the agent to accelerate sideways without rotating much // if the rotation speed is very small. Also guards against division by zero. sidewaysAcceleration = Mathf.Max(sidewaysAcceleration, forwardsAcceleration); // Transform coordinates to local space where +X is the forwards direction // This is essentially equivalent to Transform.InverseTransformDirection. deltaPosition = VectorMath.ComplexMultiplyConjugate(deltaPosition, forwardsVector); targetVelocity = VectorMath.ComplexMultiplyConjugate(targetVelocity, forwardsVector); currentVelocity = VectorMath.ComplexMultiplyConjugate(currentVelocity, forwardsVector); float ellipseSqrFactorX = 1 / (forwardsAcceleration*forwardsAcceleration); float ellipseSqrFactorY = 1 / (sidewaysAcceleration*sidewaysAcceleration); // If the target velocity is zero we can use a more fancy approach // and calculate a nicer path. // In particular, this is the case at the end of the path. if (targetVelocity == Vector2.zero) { // Run a binary search over the time to get to the target point. float mn = 0.01f; float mx = 10; while (mx - mn > 0.01f) { var time = (mx + mn) * 0.5f; // Given that we want to move deltaPosition units from out current position, that our current velocity is given // and that when we reach the target we want our velocity to be zero. Also assume that our acceleration will // vary linearly during the slowdown. Then we can calculate what our acceleration should be during this frame. //{ t = time //{ deltaPosition = vt + at^2/2 + qt^3/6 //{ 0 = v + at + qt^2/2 //{ solve for a // a = acceleration vector // q = derivative of the acceleration vector var a = (6*deltaPosition - 4*time*currentVelocity)/(time*time); var q = 6*(time*currentVelocity - 2*deltaPosition)/(time*time*time); // Make sure the acceleration is not greater than our maximum allowed acceleration. // If it is we increase the time we want to use to get to the target // and if it is not, we decrease the time to get there faster. // Since the acceleration is described by acceleration = a + q*t // we only need to check at t=0 and t=time. // Note that the acceleration limit is described by an ellipse, not a circle. var nextA = a + q*time; if (a.x*a.x*ellipseSqrFactorX + a.y*a.y*ellipseSqrFactorY > 1.0f || nextA.x*nextA.x*ellipseSqrFactorX + nextA.y*nextA.y*ellipseSqrFactorY > 1.0f) { mn = time; } else { mx = time; } } var finalAcceleration = (6*deltaPosition - 4*mx*currentVelocity)/(mx*mx); // Boosting { // The trajectory calculated above has a tendency to use very wide arcs // and that does unfortunately not look particularly good in some cases. // Here we amplify the component of the acceleration that is perpendicular // to our current velocity. This will make the agent turn towards the // target quicker. // How much amplification to use. Value is unitless. const float Boost = 1; finalAcceleration.y *= 1 + Boost; // Clamp the velocity to the maximum acceleration. // Note that the maximum acceleration constraint is shaped like an ellipse, not like a circle. float ellipseMagnitude = finalAcceleration.x*finalAcceleration.x*ellipseSqrFactorX + finalAcceleration.y*finalAcceleration.y*ellipseSqrFactorY; if (ellipseMagnitude > 1.0f) finalAcceleration /= Mathf.Sqrt(ellipseMagnitude); } return VectorMath.ComplexMultiply(finalAcceleration, forwardsVector); } else { // Here we try to move towards the next waypoint which has been modified slightly using our // desired velocity at that point so that the agent will more smoothly round the corner. // How much to strive for making sure we reach the target point with the target velocity. Unitless. const float TargetVelocityWeight = 0.5f; // Limit to how much to care about the target velocity. Value is in seconds. // This prevents the character from moving away from the path too much when the target point is far away const float TargetVelocityWeightLimit = 1.5f; float targetSpeed; var normalizedTargetVelocity = VectorMath.Normalize(targetVelocity, out targetSpeed); var distance = deltaPosition.magnitude; var targetPoint = deltaPosition - normalizedTargetVelocity * System.Math.Min(TargetVelocityWeight * distance * targetSpeed / (currentSpeed + targetSpeed), maxSpeed*TargetVelocityWeightLimit); // How quickly the agent will try to reach the velocity that we want it to have. // We need this to prevent oscillations and jitter which is what happens if // we let the constant go towards zero. Value is in seconds. const float TimeToReachDesiredVelocity = 0.1f; // TODO: Clamp to ellipse using more accurate acceleration (use rotation speed as well) var finalAcceleration = (targetPoint.normalized*maxSpeed - currentVelocity) * (1f/TimeToReachDesiredVelocity); // Clamp the velocity to the maximum acceleration. // Note that the maximum acceleration constraint is shaped like an ellipse, not like a circle. float ellipseMagnitude = finalAcceleration.x*finalAcceleration.x*ellipseSqrFactorX + finalAcceleration.y*finalAcceleration.y*ellipseSqrFactorY; if (ellipseMagnitude > 1.0f) finalAcceleration /= Mathf.Sqrt(ellipseMagnitude); return VectorMath.ComplexMultiply(finalAcceleration, forwardsVector); } } } }
412
0.962363
1
0.962363
game-dev
MEDIA
0.868801
game-dev
0.970787
1
0.970787
Grimrukh/SoulsAI
5,043
ai_scripts/m18_00_00_00/349100_battle.lua
REGISTER_GOAL(GOAL_DriftItemEvil349100_Battle, "DriftItemEvil349100Battle") local Att3000_Dist_min = 0 local Att3000_Dist_max = 0.9 local Att3002_Dist_min = 0 local Att3002_Dist_max = 1 local Att3003_Dist_min = 6 local Att3003_Dist_max = 14 REGISTER_GOAL_NO_UPDATE(GOAL_DriftItemEvil349100_Battle, 1) function DriftItemEvil349100Battle_Activate(ai, goal) local actPerArr = {} local actFuncArr = {} local defFuncParamTbl = {} Common_Clear_Param(actPerArr, actFuncArr, defFuncParamTbl) local targetDist = ai:GetDist(TARGET_ENE_0) if 10 <= targetDist then actPerArr[2] = 5 actPerArr[3] = 5 actPerArr[4] = 90 elseif 6 <= targetDist then actPerArr[2] = 20 actPerArr[3] = 20 actPerArr[4] = 60 else actPerArr[2] = 55 actPerArr[3] = 45 actPerArr[4] = 0 end actFuncArr[2] = REGIST_FUNC(ai, goal, DriftItemEvil349100_Act02) actFuncArr[3] = REGIST_FUNC(ai, goal, DriftItemEvil349100_Act03) actFuncArr[4] = REGIST_FUNC(ai, goal, DriftItemEvil349100_Act04) local local0 = {0, 70, 10, 10, 10, 0} local atkAfterFunc = REGIST_FUNC(ai, goal, HumanCommon_ActAfter_AdjustSpace, local0) Common_Battle_Activate(ai, goal, actPerArr, actFuncArr, atkAfterFunc, defFuncParamTbl) return end Att3000_Dist_min = Att3000_Dist_max function DriftItemEvil349100_Act02(ai, goal, paramTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) local jumptimer = ai:GetRandam_Int(20, 30) local approachDist = Att3000_Dist_max local dashDist = Att3000_Dist_max + 2 local Odds_Guard = 0 if ai:IsFinishTimer(0) == true then if 10 <= targetDist then ai:SetTimer(0, jumptimer) goal:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 10, TARGET_SELF, false, -1) goal:AddSubGoal(GOAL_COMMON_Attack, 5, 3004, TARGET_SELF, DIST_NONE, 0) elseif 7 <= targetDist then ai:SetTimer(0, jumptimer) goal:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 7, TARGET_SELF, false, -1) goal:AddSubGoal(GOAL_COMMON_Attack, 5, 3004, TARGET_SELF, DIST_NONE, 0) elseif 3.8 <= targetDist then ai:SetTimer(0, jumptimer) goal:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 3.8, TARGET_SELF, false, -1) goal:AddSubGoal(GOAL_COMMON_Attack, 5, 3004, TARGET_SELF, DIST_NONE, 0) end end Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) if fate <= 30 then goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0) else goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0) goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3001, TARGET_ENE_0, DIST_Middle, 0) end GetWellSpace_Odds = 100 return GetWellSpace_Odds end Att3000_Dist_min = Att3002_Dist_max function DriftItemEvil349100_Act03(ai, goal, paramTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) local jumptimer = ai:GetRandam_Int(20, 30) local approachDist = Att3002_Dist_max local dashDist = Att3002_Dist_max + 2 local Odds_Guard = 0 if ai:IsFinishTimer(0) == true then if 10 <= targetDist then ai:SetTimer(0, jumptimer) goal:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 10, TARGET_SELF, false, -1) goal:AddSubGoal(GOAL_COMMON_Attack, 5, 3004, TARGET_SELF, DIST_NONE, 0) elseif 7 <= targetDist then ai:SetTimer(0, jumptimer) goal:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 7, TARGET_SELF, false, -1) goal:AddSubGoal(GOAL_COMMON_Attack, 5, 3004, TARGET_SELF, DIST_NONE, 0) elseif 3.8 <= targetDist then ai:SetTimer(0, jumptimer) goal:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 3.8, TARGET_SELF, false, -1) goal:AddSubGoal(GOAL_COMMON_Attack, 5, 3004, TARGET_SELF, DIST_NONE, 0) end end Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) goal:AddSubGoal(GOAL_COMMON_Attack, 5, 3002, TARGET_ENE_0, DIST_Middle) GetWellSpace_Odds = 100 return GetWellSpace_Odds end Att3000_Dist_min = Att3003_Dist_max function DriftItemEvil349100_Act04(ai, goal, paramTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) local approachDist = Att3003_Dist_max local dashDist = Att3003_Dist_max + 2 local Odds_Guard = 0 Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) goal:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3003, TARGET_ENE_0, DIST_Middle, -1, 40) GetWellSpace_Odds = 100 return GetWellSpace_Odds end function DriftItemEvil349100Battle_Update(ai, goal) return GOAL_RESULT_Continue end function DriftItemEvil349100Battle_Terminate(ai, goal) return end function DriftItemEvil349100Battle_Interupt(ai, goal) return false end return
412
0.838144
1
0.838144
game-dev
MEDIA
0.967241
game-dev
0.891432
1
0.891432
cymcsg/UltimateAndroid
1,366
deprecated/UltimateAndroidGradle/ultimateandroiduicomponent/src/main/java/com/marshalchen/common/uimodule/flipViews/flipview/RubberBandOverFlipper.java
package com.marshalchen.common.uimodule.flipViews.flipview; import android.graphics.Canvas; public class RubberBandOverFlipper implements OverFlipper { private static final float MAX_OVER_FLIP_DISTANCE = 70; private static final float EXPONENTIAL_DECREES = 0.85f; private float mTotalOverFlip; private float mCurrentOverFlip; @Override public float calculate(float flipDistance, float minFlipDistance, float maxFlipDistance) { float deltaOverFlip; if(flipDistance<minFlipDistance) { deltaOverFlip = flipDistance - minFlipDistance - mCurrentOverFlip; }else { deltaOverFlip = flipDistance - maxFlipDistance - mCurrentOverFlip; } mTotalOverFlip += deltaOverFlip; float sign = Math.signum(mTotalOverFlip); mCurrentOverFlip = (float) Math.pow(Math.abs(mTotalOverFlip), EXPONENTIAL_DECREES) * sign; if(mCurrentOverFlip < 0) { mCurrentOverFlip = Math.max(-MAX_OVER_FLIP_DISTANCE, mCurrentOverFlip); }else { mCurrentOverFlip = Math.min(MAX_OVER_FLIP_DISTANCE, mCurrentOverFlip); } return mCurrentOverFlip + (mCurrentOverFlip < 0 ? minFlipDistance : maxFlipDistance); } @Override public boolean draw(Canvas c) { return false; } @Override public void overFlipEnded() { mTotalOverFlip = 0; mCurrentOverFlip = 0; } @Override public float getTotalOverFlip() { return mTotalOverFlip; } }
412
0.698916
1
0.698916
game-dev
MEDIA
0.413296
game-dev,graphics-rendering
0.946934
1
0.946934
Kirin0v0/ARPG-Demo
5,607
Assets/Scripts/Features/Main/UI/MainSettingsPanel.cs
using System.Globalization; using Common; using Framework.Common.Debug; using Framework.Common.UI.Panel; using Framework.Common.Util; using Inputs; using TMPro; using UnityEngine.EventSystems; using UnityEngine.InputSystem; using UnityEngine.UI; using VContainer; using PlayerInputManager = Inputs.PlayerInputManager; namespace Features.Main { public class MainSettingsPanel : BaseUGUIPanel { [Inject] private EventSystem _eventSystem; [Inject] private PlayerInputManager _playerInputManager; [Inject] private UGUIPanelManager _panelManager; [Inject] private IObjectResolver _objectResolver; private Button _btnClose; private TMP_Dropdown _ddScreenMode; private TMP_Dropdown _ddResolution; private TMP_Dropdown _ddFrameRate; private Slider _sliderMusic; private TextMeshProUGUI _textMusicValue; private Slider _sliderSound; private TextMeshProUGUI _textSoundValue; protected override void OnInit() { _btnClose = GetWidget<Button>("BtnClose"); _ddScreenMode = GetWidget<TMP_Dropdown>("DdScreenMode"); _ddResolution = GetWidget<TMP_Dropdown>("DdResolution"); _ddFrameRate = GetWidget<TMP_Dropdown>("DdFrameRate"); _sliderMusic = GetWidget<Slider>("SliderMusic"); _textMusicValue = GetWidget<TextMeshProUGUI>("TextMusicValue"); _sliderSound = GetWidget<Slider>("SliderSound"); _textSoundValue = GetWidget<TextMeshProUGUI>("TextSoundValue"); } protected override void OnShow(object payload) { _btnClose.onClick.AddListener(OnCloseButtonClicked); _ddScreenMode.onValueChanged.AddListener(OnScreenModeDropdownChanged); _ddResolution.onValueChanged.AddListener(OnResolutionDropdownChanged); _ddFrameRate.onValueChanged.AddListener(OnFrameRateDropdownChanged); _sliderMusic.onValueChanged.AddListener(OnMusicSliderChanged); _sliderSound.onValueChanged.AddListener(OnSoundSliderChanged); if (Focus) { _eventSystem.SetSelectedGameObject(null); } _ddScreenMode.value = (int)GameApplication.Instance.GlobalSettingsDataManager.ScreenMode; _ddResolution.value = (int)GameApplication.Instance.GlobalSettingsDataManager.DisplayResolution; _ddFrameRate.value = (int)GameApplication.Instance.GlobalSettingsDataManager.FrameRate; _sliderMusic.value = GameApplication.Instance.GlobalSettingsDataManager.MusicVolume; _sliderSound.value = GameApplication.Instance.GlobalSettingsDataManager.SoundVolume; } protected override void OnShowingUpdate(bool focus) { if (focus && !_eventSystem.currentSelectedGameObject && _playerInputManager.WasPerformedThisFrame(InputConstants.Navigate)) { _eventSystem.SetSelectedGameObject(_btnClose.gameObject); } if (focus && _playerInputManager.WasPerformedThisFrame(InputConstants.Cancel)) { _eventSystem.SetSelectedGameObject(_btnClose.gameObject); } } protected override void OnHide() { _btnClose.onClick.RemoveListener(OnCloseButtonClicked); _ddScreenMode.onValueChanged.RemoveListener(OnScreenModeDropdownChanged); _ddResolution.onValueChanged.RemoveListener(OnResolutionDropdownChanged); _ddFrameRate.onValueChanged.RemoveListener(OnFrameRateDropdownChanged); _sliderMusic.onValueChanged.RemoveListener(OnMusicSliderChanged); _sliderSound.onValueChanged.RemoveListener(OnSoundSliderChanged); UGUIUtil.DeselectIfSelectedInTargetChildren(_eventSystem, transform); } private void OnCloseButtonClicked() { _panelManager.Hide<MainSettingsPanel>(); } private void OnScreenModeDropdownChanged(int index) { GameApplication.Instance.GlobalSettingsDataManager.ScreenMode = index switch { 1 => Common.ScreenMode.FullScreenWindow, 2 => ScreenMode.Windowed, _ => Common.ScreenMode.ExclusiveFullScreen }; } private void OnResolutionDropdownChanged(int index) { GameApplication.Instance.GlobalSettingsDataManager.DisplayResolution = index switch { 1 => Common.DisplayResolution.W1280H960, 2 => Common.DisplayResolution.W1440H1080, 3 => Common.DisplayResolution.W2560H1440, _ => Common.DisplayResolution.W1920H1080 }; } private void OnFrameRateDropdownChanged(int index) { GameApplication.Instance.GlobalSettingsDataManager.FrameRate = index switch { 1 => Common.FrameRate.FPS30, 2 => Common.FrameRate.FPS120, _ => Common.FrameRate.FPS60 }; } private void OnMusicSliderChanged(float value) { GameApplication.Instance.GlobalSettingsDataManager.MusicVolume = value; _textMusicValue.text = value.ToString(CultureInfo.InvariantCulture); } private void OnSoundSliderChanged(float value) { GameApplication.Instance.GlobalSettingsDataManager.SoundVolume = value; _textSoundValue.text = value.ToString(CultureInfo.InvariantCulture); } } }
412
0.952436
1
0.952436
game-dev
MEDIA
0.778191
game-dev
0.968817
1
0.968817
folgerwang/UnrealEngine
8,106
Engine/Source/Runtime/Engine/Private/Particles/ParticleTrailModules.cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. /*============================================================================= ParticleTrailModules.cpp: Particle module implementations for trails. =============================================================================*/ #include "CoreMinimal.h" #include "ParticleHelper.h" #include "ParticleEmitterInstances.h" #include "Particles/ParticleSystemComponent.h" #include "Distributions/DistributionFloatConstant.h" #include "Particles/Trail/ParticleModuleTrailBase.h" #include "Particles/Trail/ParticleModuleTrailSource.h" #include "Particles/TypeData/ParticleModuleTypeDataAnimTrail.h" #include "Particles/TypeData/ParticleModuleTypeDataRibbon.h" UParticleModuleTrailBase::UParticleModuleTrailBase(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { bSpawnModule = false; bUpdateModule = false; } /*----------------------------------------------------------------------------- Abstract base modules used for categorization. -----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------- UParticleModuleTrailSource implementation. -----------------------------------------------------------------------------*/ UParticleModuleTrailSource::UParticleModuleTrailSource(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { // Structure to hold one-time initialization struct FConstructorStatics { FName NAME_None; FConstructorStatics() : NAME_None(TEXT("None")) { } }; static FConstructorStatics ConstructorStatics; SourceMethod = PET2SRCM_Default; SourceName = ConstructorStatics.NAME_None; SelectionMethod = EPSSM_Sequential; bInheritRotation = false; } void UParticleModuleTrailSource::InitializeDefaults() { if (!SourceStrength.IsCreated()) { UDistributionFloatConstant* DistributionSourceStrength = NewObject<UDistributionFloatConstant>(this, TEXT("DistributionSourceStrength")); DistributionSourceStrength->Constant = 100.0f; SourceStrength.Distribution = DistributionSourceStrength; } } void UParticleModuleTrailSource::PostInitProperties() { Super::PostInitProperties(); if (!HasAnyFlags(RF_ClassDefaultObject | RF_NeedLoad)) { InitializeDefaults(); } } #if WITH_EDITOR void UParticleModuleTrailSource::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { InitializeDefaults(); // SourceOffsetCount // SourceOffsetDefaults UProperty* PropertyThatChanged = PropertyChangedEvent.Property; if (PropertyThatChanged) { if (PropertyThatChanged->GetFName() == FName(TEXT("SourceOffsetCount"))) { if (SourceOffsetDefaults.Num() > 0) { if (SourceOffsetDefaults.Num() < SourceOffsetCount) { // Add additional slots SourceOffsetDefaults.InsertZeroed(SourceOffsetDefaults.Num(), SourceOffsetCount - SourceOffsetDefaults.Num()); } else if (SourceOffsetDefaults.Num() > SourceOffsetCount) { // Remove the required slots int32 RemoveIndex = SourceOffsetCount ? (SourceOffsetCount - 1) : 0; SourceOffsetDefaults.RemoveAt(RemoveIndex, SourceOffsetDefaults.Num() - SourceOffsetCount); } } else { if (SourceOffsetCount > 0) { // Add additional slots SourceOffsetDefaults.InsertZeroed(0, SourceOffsetCount); } } } } Super::PostEditChangeProperty(PropertyChangedEvent); } #endif // WITH_EDITOR void UParticleModuleTrailSource::AutoPopulateInstanceProperties(UParticleSystemComponent* PSysComp) { check(IsInGameThread()); switch (SourceMethod) { case PET2SRCM_Actor: { bool bFound = false; for (int32 i = 0; i < PSysComp->InstanceParameters.Num(); i++) { FParticleSysParam* Param = &(PSysComp->InstanceParameters[i]); if (Param->Name == SourceName) { bFound = true; break; } } if (!bFound) { int32 NewParamIndex = PSysComp->InstanceParameters.AddZeroed(); PSysComp->InstanceParameters[NewParamIndex].Name = SourceName; PSysComp->InstanceParameters[NewParamIndex].ParamType = PSPT_Actor; PSysComp->InstanceParameters[NewParamIndex].Actor = NULL; } } break; } } void UParticleModuleTrailSource::GetParticleSysParamsUtilized(TArray<FString>& ParticleSysParamList) { if (SourceMethod == PET2SRCM_Actor) { ParticleSysParamList.Add(FString::Printf(TEXT("TrailSource: Actor: %s\n"), *(SourceName.ToString()))); } } bool UParticleModuleTrailSource::ResolveSourceOffset(int32 InTrailIdx, FParticleEmitterInstance* InEmitterInst, FVector& OutSourceOffset) { // For now, we are only supporting the default values (for ribbon emitters) if (InTrailIdx < SourceOffsetDefaults.Num()) { OutSourceOffset = SourceOffsetDefaults[InTrailIdx]; return true; } return false; } /*----------------------------------------------------------------------------- UParticleModuleTypeDataRibbon implementation. -----------------------------------------------------------------------------*/ UParticleModuleTypeDataRibbon::UParticleModuleTypeDataRibbon(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { MaxTessellationBetweenParticles = 25; SheetsPerTrail = 1; MaxTrailCount = 1; MaxParticleInTrailCount = 500; bDeadTrailsOnDeactivate = true; bClipSourceSegement = true; bEnablePreviousTangentRecalculation = true; bTangentRecalculationEveryFrame = false; bDeadTrailsOnSourceLoss = true; TangentSpawningScalar = 0.0f; bRenderGeometry = true; bRenderSpawnPoints = false; bRenderTangents = false; bRenderTessellation = false; DistanceTessellationStepSize = 15.0f; TangentTessellationScalar = 5.0f; } uint32 UParticleModuleTypeDataRibbon::RequiredBytes(UParticleModuleTypeDataBase* TypeData) { return sizeof(FRibbonTypeDataPayload); } #if WITH_EDITOR void UParticleModuleTypeDataRibbon::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { Super::PostEditChangeProperty(PropertyChangedEvent); UProperty* PropertyThatChanged = PropertyChangedEvent.Property; if (PropertyThatChanged && PropertyThatChanged->GetName() == TEXT("MaxTessellationBetweenParticles")) { if (MaxTessellationBetweenParticles < 0) { MaxTessellationBetweenParticles = 0; } } else if (PropertyThatChanged && PropertyThatChanged->GetName() == TEXT("SheetsPerTrail")) { if (SheetsPerTrail <= 0) { SheetsPerTrail = 1; } } else if (PropertyThatChanged && PropertyThatChanged->GetName() == TEXT("MaxTrailCount")) { if (MaxTrailCount <= 0) { MaxTrailCount = 1; } } else if (PropertyThatChanged && PropertyThatChanged->GetName() == TEXT("MaxParticleInTrailCount")) { if (MaxParticleInTrailCount < 0) { MaxParticleInTrailCount = 0; } } } #endif // WITH_EDITOR FParticleEmitterInstance* UParticleModuleTypeDataRibbon::CreateInstance(UParticleEmitter* InEmitterParent, UParticleSystemComponent* InComponent) { FParticleEmitterInstance* Instance = new FParticleRibbonEmitterInstance(); check(Instance); Instance->InitParameters(InEmitterParent, InComponent); return Instance; } /*----------------------------------------------------------------------------- UParticleModuleTypeDataAnimTrail implementation. -----------------------------------------------------------------------------*/ UParticleModuleTypeDataAnimTrail::UParticleModuleTypeDataAnimTrail(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { bDeadTrailsOnDeactivate = true; bEnablePreviousTangentRecalculation = true; bTangentRecalculationEveryFrame = false; DistanceTessellationStepSize = 10.0f; TangentTessellationStepSize = 0.0f; } uint32 UParticleModuleTypeDataAnimTrail::RequiredBytes(UParticleModuleTypeDataBase* TypeData) { return sizeof(FAnimTrailTypeDataPayload); } FParticleEmitterInstance* UParticleModuleTypeDataAnimTrail::CreateInstance(UParticleEmitter* InEmitterParent, UParticleSystemComponent* InComponent) { FParticleEmitterInstance* Instance = new FParticleAnimTrailEmitterInstance(); check(Instance); Instance->InitParameters(InEmitterParent, InComponent); return Instance; }
412
0.940941
1
0.940941
game-dev
MEDIA
0.83336
game-dev
0.862325
1
0.862325
SWRC-Modding/CT
3,502
Engine/Inc/UnPrim.h
/*============================================================================= UnPrim.h: Unreal UPrimitive definition. Copyright 1997-1999 Epic Games, Inc. All Rights Reserved. Revision history: * Created by Tim Sweeney =============================================================================*/ class UMaterial; /*----------------------------------------------------------------------------- FCheckResult. -----------------------------------------------------------------------------*/ // // Results of an actor check. // struct FIteratorActorList : public FIteratorList{ // Variables. AActor* Actor; // Functions. FIteratorActorList(){} FIteratorActorList(FIteratorActorList* InNext, AActor* InActor) : FIteratorList(InNext), Actor(InActor){} FIteratorActorList* GetNext(){ return (FIteratorActorList*) Next; } }; // // Results from a collision check. // struct FCheckResult : public FIteratorActorList{ // Variables. FVector Location; // Location of the hit in coordinate system of the returner. FVector Normal; // Normal vector in coordinate system of the returner. Zero=none. UPrimitive* Primitive; // Actor primitive which was hit, or NULL=none. FLOAT Time; // Time until hit, if line check. INT Item; // Primitive data item which was hit, INDEX_NONE=none. UMaterial* Material; // Material of the item which was hit. // Functions. FCheckResult(){} FCheckResult(FLOAT InTime, FCheckResult* InNext = NULL) : FIteratorActorList(InNext, NULL), Location(0,0,0), Normal(0,0,0), Primitive(NULL), Time(InTime), Item(INDEX_NONE), Material(NULL){} FCheckResult*& GetNext(){ return *(FCheckResult**)&Next; } friend QSORT_RETURN CDECL CompareHits(const FCheckResult* A, const FCheckResult* B) { return A->Time < B->Time ? -1 : A->Time > B->Time ? 1 : 0; } }; /*----------------------------------------------------------------------------- UPrimitive. -----------------------------------------------------------------------------*/ // // UPrimitive, the base class of geometric entities capable of being // rendered and collided with. // class ENGINE_API UPrimitive : public UObject{ DECLARE_CLASS(UPrimitive,UObject,0,Engine) // Variables. FBox BoundingBox; FSphere BoundingSphere; // Constructor. UPrimitive() : BoundingBox(0), BoundingSphere(0){} //UObject interface. void Serialize( FArchive& Ar ); //Virtual Functions virtual UBOOL PointCheck ( FCheckResult& Result, AActor* Owner, const FVector& Location, const FVector& Extent, DWORD ExtraNodeFlags ); virtual UBOOL LineCheck ( FCheckResult& Result, AActor* Owner, const FVector& End, const FVector& Start, const FVector& Extent, DWORD ExtraNodeFlags, DWORD TraceFlags ); virtual FBox GetRenderBoundingBox(const AActor* Owner); virtual FSphere GetRenderBoundingSphere(const AActor* Owner); virtual FBox GetCollisionBoundingBox(const AActor* Owner) const; virtual int UseCylinderCollision(const AActor*); virtual void Illuminate(AActor* Owner, UBOOL ChangedOnly = 0); virtual FVector GetEncroachExtent(AActor* Owner); virtual FVector GetEncroachCenter(AActor* Owner); }; /*---------------------------------------------------------------------------- The End. ----------------------------------------------------------------------------*/
412
0.857904
1
0.857904
game-dev
MEDIA
0.904153
game-dev
0.879281
1
0.879281
ComfyFactory/ComfyFactorio
5,325
maps/fish_defender_v2/table.lua
-- one table to rule them all! local Global = require 'utils.global' local Difficulty = require 'modules.difficulty_vote' local Event = require 'utils.event' local this = {} local Public = {} Global.register( this, function (tbl) this = tbl end ) function Public.reset_table() -- @start -- these 3 are in case of stop/start/reloading the instance. this.soft_reset = true this.restart = false this.shutdown = false this.announced_message = false this.force_chunk = false this.fish_eye = false this.chunk_load_tick = game.tick + 500 -- @end this.game_has_ended = false this.game_reset = false this.spawn_area_generated = false this.results_sent = false this.explosive_bullets_unlocked = false this.bouncy_shells_unlocked = false this.trapped_capsules_unlocked = false this.ultra_mines_unlocked = false this.laser_pointer_unlocked = false this.crumbly_walls_unlocked = false this.vehicle_nanobots_unlocked = false this.game_restart_timer = nil this.wave_count = 0 this.wave_limit = 2000 this.attack_wave_threat = nil this.market = nil this.market_age = nil this.last_reset = game.tick this.wave_interval = 3600 this.wave_grace_period = game.tick + 72000 -- this.wave_grace_period = game.tick + 3600 this.boss_biters = {} this.acid_lines_delay = {} this.entity_limits = { ['ammo-turret'] = { placed = 1, limit = 6, str = 'gun turret', slot_price = 70 }, ['electric-turret'] = { placed = 0, limit = 1, str = 'laser turret', slot_price = 300 }, ['artillery-turret'] = { placed = 0, limit = 1, str = 'artillery turret', slot_price = 500 }, ['fluid-turret'] = { placed = 0, limit = 0, str = 'flamethrower turret', slot_price = 50000 }, ['land-mine'] = { placed = 0, limit = 1, str = 'mine', slot_price = 20 } } this.difficulties_votes = { [1] = { wave_interval = 5000, amount_modifier = 0.90, strength_modifier = 0.90, boss_modifier = 5.0 }, [2] = { wave_interval = 3500, amount_modifier = 1.00, strength_modifier = 1.00, boss_modifier = 6.0 }, [3] = { wave_interval = 3400, amount_modifier = 1.10, strength_modifier = 1.30, boss_modifier = 7.0 }, [4] = { wave_interval = 3200, amount_modifier = 1.20, strength_modifier = 1.60, boss_modifier = 8.0 }, [5] = { wave_interval = 3000, amount_modifier = 1.40, strength_modifier = 2.20, boss_modifier = 9.0 } } this.boss_waves = { [50] = { { name = 'big-biter', count = 3 } }, [100] = { { name = 'behemoth-biter', count = 1 } }, [150] = { { name = 'behemoth-spitter', count = 4 }, { name = 'big-spitter', count = 16 } }, [200] = { { name = 'behemoth-biter', count = 4 }, { name = 'behemoth-spitter', count = 2 }, { name = 'big-biter', count = 32 } }, [250] = { { name = 'behemoth-biter', count = 8 }, { name = 'behemoth-spitter', count = 4 }, { name = 'big-spitter', count = 32 } }, [300] = { { name = 'behemoth-biter', count = 16 }, { name = 'behemoth-spitter', count = 8 } } } this.comfylatron_habitat = { left_top = { x = -1500, y = -1500 }, right_bottom = { x = -80, y = 1500 } } this.shotgun_shell_damage_modifier_old = {} this.fish_eye = false this.stop_generating_map = false end function Public.get(key) if key then return this[key] else return this end end function Public.set(key, value) if key and value == false then if this[key] then this[key] = false return this[key] end end if key and not value then if this[key] then this[key] = nil return end end if key and value then this[key] = value return this[key] end end function Public.get_current_difficulty_wave_interval() local diff_index = Difficulty.get_difficulty_vote_index() if this.difficulties_votes[diff_index] then return this.difficulties_votes[diff_index].wave_interval end end function Public.get_current_difficulty_boss_modifier() local diff_index = Difficulty.get_difficulty_vote_index() if this.difficulties_votes[diff_index] then return this.difficulties_votes[diff_index].boss_modifier end end function Public.get_current_difficulty_strength_modifier() local diff_index = Difficulty.get_difficulty_vote_index() if this.difficulties_votes[diff_index] then return this.difficulties_votes[diff_index].strength_modifier end end function Public.get_current_difficulty_amount_modifier() local diff_index = Difficulty.get_difficulty_vote_index() if this.difficulties_votes[diff_index] then return this.difficulties_votes[diff_index].amount_modifier end end local on_init = function () Public.reset_table() end Event.on_init(on_init) return Public
412
0.973863
1
0.973863
game-dev
MEDIA
0.973333
game-dev
0.904154
1
0.904154
sunsvip/GF_X
1,944
Assets/Plugins/UnityGameFramework/Scripts/Runtime/Debugger/DebuggerComponent.SceneInformationWindow.cs
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2021 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ using UnityEngine; using UnityEngine.SceneManagement; namespace UnityGameFramework.Runtime { public sealed partial class DebuggerComponent : GameFrameworkComponent { private sealed class SceneInformationWindow : ScrollableDebuggerWindowBase { protected override void OnDrawScrollableWindow() { GUILayout.Label("<b>Scene Information</b>"); GUILayout.BeginVertical("box"); { DrawItem("Scene Count", SceneManager.sceneCount.ToString()); DrawItem("Scene Count In Build Settings", SceneManager.sceneCountInBuildSettings.ToString()); Scene activeScene = SceneManager.GetActiveScene(); #if UNITY_2018_3_OR_NEWER DrawItem("Active Scene Handle", activeScene.handle.ToString()); #endif DrawItem("Active Scene Name", activeScene.name); DrawItem("Active Scene Path", activeScene.path); DrawItem("Active Scene Build Index", activeScene.buildIndex.ToString()); DrawItem("Active Scene Is Dirty", activeScene.isDirty.ToString()); DrawItem("Active Scene Is Loaded", activeScene.isLoaded.ToString()); DrawItem("Active Scene Is Valid", activeScene.IsValid().ToString()); DrawItem("Active Scene Root Count", activeScene.rootCount.ToString()); #if UNITY_2019_1_OR_NEWER DrawItem("Active Scene Is Sub Scene", activeScene.isSubScene.ToString()); #endif } GUILayout.EndVertical(); } } } }
412
0.727697
1
0.727697
game-dev
MEDIA
0.71301
game-dev
0.90134
1
0.90134
IcySon55/Kuriimu
2,138
src/image/image_ctxb/CtxbAdapter.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using Kontract.Interface; using Kontract.IO; using System.Linq; namespace image_ctxb { public sealed class CtxbAdapter : IImageAdapter { private CTXB _ctxb = null; private List<BitmapInfo> _bitmaps; #region Properties public string Name => "CTXB"; public string Description => "CTR TeXture Box"; public string Extension => "*.ctxb"; public string About => "This is the CTXB image adapter for Kukkii."; // Feature Support public bool FileHasExtendedProperties => false; public bool CanSave => true; public FileInfo FileInfo { get; set; } #endregion public bool Identify(string filename) { using (var br = new BinaryReaderX(File.OpenRead(filename))) { if (br.BaseStream.Length < 4) return false; return br.ReadString(4) == "ctxb"; } } public void Load(string filename) { FileInfo = new FileInfo(filename); if (FileInfo.Exists) { _ctxb = new CTXB(FileInfo.OpenRead()); var _bmpList = _ctxb.bmps.Select((o, i) => new CTXBBitmapInfo { Bitmap = o, Format = _ctxb.settingsList[i].Format.FormatName }).ToList(); _bitmaps = new List<BitmapInfo>(); _bitmaps.AddRange(_bmpList); } } public void Save(string filename = "") { if (filename.Trim() != string.Empty) FileInfo = new FileInfo(filename); _ctxb.bmps = _bitmaps.Select(o => o.Bitmap).ToList(); _ctxb.Save(FileInfo.FullName); } // Bitmaps public IList<BitmapInfo> Bitmaps => _bitmaps; public bool ShowProperties(Icon icon) => false; public sealed class CTXBBitmapInfo : BitmapInfo { [Category("Properties")] [ReadOnly(true)] public string Format { get; set; } } } }
412
0.700497
1
0.700497
game-dev
MEDIA
0.617851
game-dev,graphics-rendering
0.642066
1
0.642066
mordentral/VRExpansionPlugin
12,031
VRExpansionPlugin/Source/VRExpansionPlugin/Public/ParentRelativeAttachmentComponent.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" //#include "Engine/Engine.h" #include "VRExpansionFunctionLibrary.h" #include "Components/ShapeComponent.h" #include "VRTrackedParentInterface.h" #include "ParentRelativeAttachmentComponent.generated.h" class AVRBaseCharacter; class AVRCharacter; /** Delegate for notification when the PRC starts rotating in yaw to match the snap / yaw tolerances. */ DECLARE_DYNAMIC_MULTICAST_DELEGATE(FVRPRCBeginYawRotationEventSignature); // Type of rotation sampling to use UENUM(BlueprintType) enum class EVR_PRC_RotationMethod : uint8 { // Rotate purely to the HMD yaw, default mode PRC_ROT_HMD UMETA(DisplayName = "HMD rotation"), // Rotate to a blend between the HMD and Controller facing PRC_ROT_HMDControllerBlend UMETA(DisplayName = "ROT HMD Controller Blend"), // Rotate to the controllers with behind the back detection, clamp within neck limit PRC_ROT_ControllerHMDClamped UMETA(DisplayName = "Controller Clamped to HMD") }; /** * A component that will track the HMD/Cameras location and YAW rotation to allow for chest/waist attachements. * This is intended to be parented to the root component of a pawn, it will then either find and track the camera * or use the HMD's position if one is connected. This allows it to work in multiplayer since the camera will * have its position replicated. */ UCLASS(Blueprintable, meta = (BlueprintSpawnableComponent), ClassGroup = VRExpansionLibrary) class VREXPANSIONPLUGIN_API UParentRelativeAttachmentComponent : public USceneComponent, public IVRTrackedParentInterface { GENERATED_BODY() public: UParentRelativeAttachmentComponent(const FObjectInitializer& ObjectInitializer); virtual void InitializeComponent() override; // Rotation method to use for facing calulations //UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRExpansionLibrary") //EVR_PRC_RotationMethod YawRotationMethod; // Angle tolerance before we lerp / snap to the new rotation UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRExpansionLibrary", meta = (ClampMin = "0", UIMin = "0")) float YawTolerance; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRExpansionLibrary", meta = (ClampMin = "0", UIMin = "0")) float LerpSpeed; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRExpansionLibrary") bool bLerpTransition; float LastRot; float LastLerpVal; float LerpTarget; bool bWasSetOnce; FTransform LeftControllerTrans; FTransform RightControllerTrans; UPROPERTY(BlueprintAssignable, Category = "PRC Events") FVRPRCBeginYawRotationEventSignature OnYawToleranceExceeded; // If true uses feet/bottom of the capsule as the base Z position for this component instead of the HMD/Camera Z position UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRExpansionLibrary") bool bUseFeetLocation = false; // If true uses center of capsule as the feet location instead UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRExpansionLibrary", meta = (EditCondition = "bUseFeetLocation")) bool bUseCenterAsFeetLocation = false; // Should really be an enum with the above but that would make people change projects // An additional value added to the relative position of the PRC // Can be used to offset the floor, or component heights if needed UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRExpansionLibrary") FVector CustomOffset; // If true will subtract the HMD's location from the position, useful for if the actors base is set to the HMD location always (simple character). //UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRExpansionLibrary") //bool bOffsetByHMD; // If true, will not set rotation every frame, only position UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRExpansionLibrary") bool bIgnoreRotationFromParent; // If true, this component will not perform logic in its tick, it will instead allow the character movement component to move it (unless the CMC is inactive, then it will go back to self managing) UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRExpansionLibrary") bool bUpdateInCharacterMovement; private: UPROPERTY() bool bIsPaused; public: // Set the paused state of the PRC, if setting to paused then zero out rotation and zero out location will null out those values UFUNCTION(BlueprintCallable, Category = "VRExpansionLibrary") void SetPaused(bool bNewPaused, bool bZeroOutRotation, bool bZeroOutLocation); // If valid will use this as the tracked parent instead of the HMD / Parent UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "VRTrackedParentInterface") FBPVRWaistTracking_Info OptionalWaistTrackingParent; virtual void SetTrackedParent(UPrimitiveComponent * NewParentComponent, float WaistRadius, EBPVRWaistTrackingMode WaistTrackingMode) override { IVRTrackedParentInterface::Default_SetTrackedParent_Impl(NewParentComponent, WaistRadius, WaistTrackingMode, OptionalWaistTrackingParent, this); } UPROPERTY() TObjectPtr<AVRCharacter> AttachChar; UPROPERTY() TObjectPtr<AVRBaseCharacter> AttachBaseChar; void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) override; virtual void OnAttachmentChanged() override; void UpdateTracking(float DeltaTime); bool IsLocallyControlled() const { // I like epics implementation better than my own const AActor* MyOwner = GetOwner(); return MyOwner->HasLocalNetOwner(); //const APawn* MyPawn = Cast<APawn>(MyOwner); //return MyPawn ? MyPawn->IsLocallyControlled() : (MyOwner->Role == ENetRole::ROLE_Authority); } // Sets the rotation and location depending on the control variables. Trying to remove some code duplication here inline void SetRelativeRotAndLoc(FVector NewRelativeLocation, FRotator NewRelativeRotation, float DeltaTime); FQuat GetCalculatedRotation(FRotator InverseRot, float DeltaTime) { FRotator FinalRot = FRotator::ZeroRotator; if (FPlatformMath::Abs(FMath::FindDeltaAngleDegrees(InverseRot.Yaw, LastRot)) < YawTolerance) // This is never true with the default value of 0.0f { if (!bWasSetOnce) { LastRot = FRotator::ClampAxis(InverseRot.Yaw); LastLerpVal = LastRot; LerpTarget = LastRot; bWasSetOnce = true; } if (bLerpTransition && !FMath::IsNearlyEqual(LastLerpVal, LerpTarget)) { LastLerpVal = FMath::FixedTurn(LastLerpVal, LerpTarget, LerpSpeed * DeltaTime); FinalRot = FRotator(0, LastLerpVal, 0); } else { FinalRot = FRotator(0, LastRot, 0); LastLerpVal = LastRot; } } else { // If we are using a snap threshold if (!FMath::IsNearlyZero(YawTolerance)) { LerpTarget = FRotator::ClampAxis(InverseRot.Yaw); LastLerpVal = FMath::FixedTurn(/*LastRot*/LastLerpVal, LerpTarget, LerpSpeed * DeltaTime); FinalRot = FRotator(0, LastLerpVal, 0); OnYawToleranceExceeded.Broadcast(); } else // If we aren't then just directly set it to the correct rotation { FinalRot = FRotator(0, FRotator::ClampAxis(InverseRot.Yaw), 0); } LastRot = FRotator::ClampAxis(InverseRot.Yaw); } return FinalRot.Quaternion(); } void RunSampling(FRotator &HMDRotation, FVector &HMDLocation) { /*switch(YawRotationMethod) { case EVR_PRC_RotationMethod::PRC_ROT_HMD: { return; }break; case EVR_PRC_RotationMethod::PRC_ROT_HMDControllerBlend: { return; }break; case EVR_PRC_RotationMethod::PRC_ROT_ControllerHMDClamped: { GetEstShoulderRotation(HMDRotation, HMDLocation); return; }break; }*/ } // Get combined direction angle up void GetEstShoulderRotation(FRotator &InputHMDRotation, FVector &InputHMDLocation) { /*float WorldToMeters = GetWorld() ? GetWorld()->GetWorldSettings()->WorldToMeters : 100.0f; // Position shoulder (neck) FTransform shoulder = FTransform::Identity; FVector headNeckDirectionVector = FVector(-.05f, 0.f, -1.f); FVector neckShoulderDistance = FVector(-0.02f, 0.f, -.15f) * WorldToMeters; // World To Meters idealy float headNeckDistance = 0.03f * WorldToMeters; // World To Meters idealy FVector headNeckOffset = InputHMDRotation.RotateVector(headNeckDirectionVector); FVector targetPosition = InputHMDLocation + headNeckOffset * headNeckDistance; shoulder.SetLocation(targetPosition + InputHMDRotation.RotateVector(neckShoulderDistance)); //DrawDebugSphere(GetWorld(), (shoulder * GetAttachParent()->GetComponentTransform()).GetLocation(), 4.0f, 32, FColor::White); return; */ /*if (IsLocallyControlled() && GEngine->XRSystem.IsValid()) { FVector Position = GetRelativeLocation(); FRotator Orientation = GetRelativeRotation(); if (AttachBaseChar.IsValid()) { if (AttachBaseChar->LeftMotionController) { const bool bNewTrackedState = AttachBaseChar->LeftMotionController->GripPollControllerState(Position, Orientation, WorldToMeters); bool bTracked = bNewTrackedState && CurrentTrackingStatus != ETrackingStatus::NotTracked; if (bTracked) { LeftControllerTrans = FTransform(Position, Orientation); } } if (AttachBaseChar->RightMotionController) { const bool bNewTrackedState = AttachBaseChar->RightMotionController->GripPollControllerState(Position, Orientation, WorldToMeters); bool bTracked = bNewTrackedState && CurrentTrackingStatus != ETrackingStatus::NotTracked; if (bTracked) { RightControllerTrans = FTransform(Position, Orientation); } } } } else if (AttachBaseChar.IsValid()) { LeftControllerTrans = AttachBaseChar->LeftMotionController->GetRelativeTransform(); RightControllerTrans = AttachBaseChar->RightMotionController->GetRelativeTransform(); } FVector LeftHand = LeftControllerTrans.GetLocation(); FVector RightHand = RightControllerTrans.GetLocation(); //FRotator LeveledRel = CurrentTransforms.PureCameraYaw; FVector DistLeft = LeftHand - shoulder.Transform.GetLocation(); FVector DistRight = RightHand - shoulder.Transform.GetLocation(); if (bIgnoreZPos) { DistLeft.Z = 0.0f; DistRight.Z = 0.0f; } FVector DirLeft = DistLeft.GetSafeNormal(); FVector DirRight = DistRight.GetSafeNormal(); FVector CombinedDir = DirLeft + DirRight; float FinalRot = FMath::RadiansToDegrees(FMath::Atan2(CombinedDir.Y, CombinedDir.X)); DetectHandsBehindHead(FinalRot, InputHMDRotation); ClampHeadRotationDelta(FinalRot, InputHMDRotation); return FinalRot;*/ } void DetectHandsBehindHead(float& TargetRot, FRotator HMDRotation) { /*float delta = FRotator::ClampAxis(FMath::FindDeltaAngleDegrees(TargetRot, LastTargetRot));// FRotator::ClampAxis(TargetRot - LastTargetRot); if (delta > 150.f && delta < 210.0f && !FMath::IsNearlyZero(LastTargetRot) && !bClampingHeadRotation) { bHandsBehindHead = !bHandsBehindHead; if (bHandsBehindHead) { BehindHeadAngle = TargetRot; } else { BehindHeadAngle = 0.f; } } else if (bHandsBehindHead) { float delta2 = FMath::Abs(FMath::FindDeltaAngleDegrees(TargetRot, BehindHeadAngle)); if (delta2 > 90.f) { bHandsBehindHead = !bHandsBehindHead; BehindHeadAngle = 0.f; } } LastTargetRot = TargetRot; if (bHandsBehindHead) { TargetRot += 180.f; }*/ } // Clamp head rotation delta yaw void ClampHeadRotationDelta(float& TargetRotation, FRotator HMDRotation) { /*float HeadRotation = FRotator::ClampAxis(CurrentTransforms.PureCameraYaw.Yaw); float cTargetRotation = FRotator::ClampAxis(TargetRotation); float delta = HeadRotation - cTargetRotation; if ((delta > 80.f && delta < 180.f) || (delta < -180.f && delta >= -360.f + 80)) { TargetRotation = HeadRotation - 80.f; bClampingHeadRotation = true; } else if ((delta < -80.f && delta > -180.f) || (delta > 180.f && delta < 360.f - 80.f)) { TargetRotation = HeadRotation + 80.f; bClampingHeadRotation = true; } else { bClampingHeadRotation = false; }*/ } };
412
0.983386
1
0.983386
game-dev
MEDIA
0.814351
game-dev
0.966199
1
0.966199
StrangeLoopGames/EcoModKit
12,944
Examples/Blockset/Client/Assets/EcoModKit/ThirdParty/DOTween/Modules/DOTweenModuleUnityVersion.cs
// Author: Daniele Giardini - http://www.demigiant.com // Created: 2018/07/13 using System; using UnityEngine; using DG.Tweening.Core; using DG.Tweening.Plugins.Options; #pragma warning disable 1591 namespace DG.Tweening { /// <summary> /// Shortcuts/functions that are not strictly related to specific Modules /// but are available only on some Unity versions /// </summary> public static class DOTweenModuleUnityVersion { #if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1_OR_NEWER #region Unity 4.3 or Newer #region Material /// <summary>Tweens a Material's color 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 Material 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; } /// <summary>Tweens a Material's named color property 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="property">The name of the material property to tween (like _Tint or _SpecColor)</param> /// <param name="duration">The duration of the tween</param> public static Sequence DOGradientColor(this Material target, Gradient gradient, string property, 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.SetColor(property, 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, property, colorDuration).SetEase(Ease.Linear)); } s.SetTarget(target); return s; } #endregion #endregion #endif #if UNITY_5_3_OR_NEWER || UNITY_2017_1_OR_NEWER #region Unity 5.3 or Newer #region CustomYieldInstructions /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or complete. /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForCompletion(true);</code> /// </summary> public static CustomYieldInstruction WaitForCompletion(this Tween t, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForCompletion(t); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or rewinded. /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForRewind();</code> /// </summary> public static CustomYieldInstruction WaitForRewind(this Tween t, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForRewind(t); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed. /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForKill();</code> /// </summary> public static CustomYieldInstruction WaitForKill(this Tween t, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForKill(t); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or has gone through the given amount of loops. /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForElapsedLoops(2);</code> /// </summary> /// <param name="elapsedLoops">Elapsed loops to wait for</param> public static CustomYieldInstruction WaitForElapsedLoops(this Tween t, int elapsedLoops, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForElapsedLoops(t, elapsedLoops); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or has reached the given position (loops included, delays excluded). /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForPosition(2.5f);</code> /// </summary> /// <param name="position">Position (loops included, delays excluded) to wait for</param> public static CustomYieldInstruction WaitForPosition(this Tween t, float position, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForPosition(t, position); } /// <summary> /// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or started /// (meaning when the tween is set in a playing state the first time, after any eventual delay). /// It can be used inside a coroutine as a yield. /// <para>Example usage:</para><code>yield return myTween.WaitForStart();</code> /// </summary> public static CustomYieldInstruction WaitForStart(this Tween t, bool returnCustomYieldInstruction) { if (!t.active) { if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); return null; } return new DOTweenCYInstruction.WaitForStart(t); } #endregion #endregion #endif #if UNITY_2018_1_OR_NEWER #region Unity 2018.1 or Newer #region Material /// <summary>Tweens a Material's named texture offset property with the given ID to the given value. /// Also stores the material 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="propertyID">The ID of the material property to tween (also called nameID in Unity's manual)</param> /// <param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOOffset(this Material target, Vector2 endValue, int propertyID, float duration) { if (!target.HasProperty(propertyID)) { if (Debugger.logPriority > 0) Debugger.LogMissingMaterialProperty(propertyID); return null; } TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.GetTextureOffset(propertyID), x => target.SetTextureOffset(propertyID, x), endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a Material's named texture scale property with the given ID to the given value. /// Also stores the material 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="propertyID">The ID of the material property to tween (also called nameID in Unity's manual)</param> /// <param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOTiling(this Material target, Vector2 endValue, int propertyID, float duration) { if (!target.HasProperty(propertyID)) { if (Debugger.logPriority > 0) Debugger.LogMissingMaterialProperty(propertyID); return null; } TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.GetTextureScale(propertyID), x => target.SetTextureScale(propertyID, x), endValue, duration); t.SetTarget(target); return t; } #endregion #endregion #endif } // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ // ███ CLASSES █████████████████████████████████████████████████████████████████████████████████████████████████████████ // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ #if UNITY_5_3_OR_NEWER || UNITY_2017_1_OR_NEWER public static class DOTweenCYInstruction { public class WaitForCompletion : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && !t.IsComplete(); }} readonly Tween t; public WaitForCompletion(Tween tween) { t = tween; } } public class WaitForRewind : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && (!t.playedOnce || t.position * (t.CompletedLoops() + 1) > 0); }} readonly Tween t; public WaitForRewind(Tween tween) { t = tween; } } public class WaitForKill : CustomYieldInstruction { public override bool keepWaiting { get { return t.active; }} readonly Tween t; public WaitForKill(Tween tween) { t = tween; } } public class WaitForElapsedLoops : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && t.CompletedLoops() < elapsedLoops; }} readonly Tween t; readonly int elapsedLoops; public WaitForElapsedLoops(Tween tween, int elapsedLoops) { t = tween; this.elapsedLoops = elapsedLoops; } } public class WaitForPosition : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && t.position * (t.CompletedLoops() + 1) < position; }} readonly Tween t; readonly float position; public WaitForPosition(Tween tween, float position) { t = tween; this.position = position; } } public class WaitForStart : CustomYieldInstruction { public override bool keepWaiting { get { return t.active && !t.playedOnce; }} readonly Tween t; public WaitForStart(Tween tween) { t = tween; } } } #endif }
412
0.914204
1
0.914204
game-dev
MEDIA
0.614984
game-dev,graphics-rendering
0.901555
1
0.901555
oculus-samples/Unity-CrypticCabinet
6,213
Assets/Photon/Fusion/Scripts/Prototyping/SpawnPoints/SpawnPointManagerPrototype.cs
using UnityEngine; using Fusion; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; using Fusion.Editor; #endif /// <summary> /// Derive from this class for different <see cref="ISpawnPointPrototype"/> types. /// Derived manager will only find that spawn point type, allowing for separate handling of player spawn points from other spawn-able items such as AI. /// </summary> /// <typeparam name="T"></typeparam> [ScriptHelp(BackColor = EditorHeaderBackColor.Steel)] public abstract class SpawnPointManagerPrototype<T> : Fusion.Behaviour, ISpawnPointManagerPrototype<T> where T : Component, ISpawnPointPrototype { public enum SpawnSequence { PlayerId, RoundRobin, Random } /// <summary> /// How spawn points will be selected from the <see cref="_spawnPoints"/> collection. /// </summary> [InlineHelp] public SpawnSequence Sequence; /// <summary> /// LayerMask for which physics layers should be used for blocked spawn point checks. /// </summary> [InlineHelp] public LayerMask BlockingLayers; /// <summary> /// The search radius used for detecting if a spawn point is blocked by an object. /// </summary> [InlineHelp] public float BlockedCheckRadius = 2f; /// <summary> /// Serialized collection of all <see cref="ISpawnPointPrototype"/> of the type T found in the same scene as this component. /// </summary> [System.NonSerialized] internal List<Component> _spawnPoints = new List<Component>(); [System.NonSerialized] public int LastSpawnIndex = -1; NetworkRNG rng; private void Awake() { rng = new NetworkRNG(0); } #if UNITY_EDITOR [BehaviourAction] protected void DrawFoundSpawnPointCount() { if (Application.isPlaying == false) { GUILayout.BeginVertical(FusionGUIStyles.GroupBoxType.Info.GetStyle()); GUILayout.Space(4); if (GUI.Button(EditorGUILayout.GetControlRect(), "Find Spawn Points")) { _spawnPoints.Clear(); var found = UnityEngine.SceneManagement.SceneManager.GetActiveScene().FindObjectsOfTypeInOrder<T, Component>(); _spawnPoints.AddRange(found); } GUILayout.Space(4); EditorGUI.BeginDisabledGroup(true); foreach (var point in _spawnPoints) { EditorGUILayout.ObjectField(point.name, point, typeof(T), true); } EditorGUI.EndDisabledGroup(); EditorGUILayout.LabelField($"{typeof(T).Name}(s): {_spawnPoints.Count}"); GUILayout.EndVertical(); } } #endif /// <summary> /// Find all <see cref="ISpawnPointPrototype"/> instances in the same scene as this spawner. /// This should only be done at development time if using the Photon relay for any spawn logic. /// </summary> public void CollectSpawnPoints(NetworkRunner runner) { _spawnPoints.Clear(); _spawnPoints.AddRange(runner.SimulationUnityScene.FindObjectsOfTypeInOrder<T, Component>()); } /// <summary> /// Select the next spawn point using the defined <see cref="Sequence"/>. Override this method to expand on this, such as detecting if a spawn point is blocked. /// </summary> public virtual Transform GetNextSpawnPoint(NetworkRunner runner, PlayerRef player, bool skipIfBlocked = true) { CollectSpawnPoints(runner); int spawnCount = _spawnPoints.Count; if (_spawnPoints == null || spawnCount == 0) return null; Component next; int nextIndex; if (Sequence == SpawnSequence.PlayerId) { nextIndex = player % spawnCount; next = _spawnPoints[nextIndex]; } else if (Sequence == SpawnSequence.RoundRobin) { nextIndex = (LastSpawnIndex + 1) % spawnCount; next = _spawnPoints[nextIndex]; } else { nextIndex = rng.RangeInclusive(0, spawnCount); next = _spawnPoints[nextIndex]; } // Handling for blocked spawn points. By default this never happens, as the IsBlocked test always returns true. if (skipIfBlocked && BlockingLayers.value != 0 && IsBlocked(next)) { var unblocked = GetNextUnblocked(nextIndex); if (unblocked.Item1 > -1) { LastSpawnIndex = unblocked.Item1; return unblocked.Item2.transform; } // leave LastSpawnIndex the same since we haven't arrived at a new spawn point. next = unblocked.Item2; } else { LastSpawnIndex = nextIndex; return next.transform; } return AllSpawnPointsBlockedFallback(); } /// <summary> /// Handling for if all spawn points are blocked. /// </summary> /// <returns></returns> public virtual Transform AllSpawnPointsBlockedFallback() { return transform; } /// <summary> /// Cycles through all remaining spawn points searching for unblocked. Will return null if all points return <see cref="IsBlocked(Transform)"/> == true. /// </summary> /// <param name="failedIndex">The index of the first tried SpawnPoints[] element, which was blocked.</param> /// <returns>(<see cref="_spawnPoints"/> index, <see cref="ISpawnPointPrototype"/>)</returns> public virtual (int, Component) GetNextUnblocked(int failedIndex) { for (int i = 1, cnt = _spawnPoints.Count; i < cnt; ++i) { var sp = _spawnPoints[i % cnt]; if (!IsBlocked(sp)) return (i, sp); } return (-1, null); } protected static Collider[] blocked3D; /// <summary> /// Override this method with any logic for checking if a spawn point is blocked. /// </summary> /// <param name="spawnPoint"></param> /// <returns></returns> public virtual bool IsBlocked(Component spawnPoint) { var physics3d = spawnPoint.gameObject.scene.GetPhysicsScene(); if (physics3d != null) { if (blocked3D == null) { blocked3D = new Collider[1]; } var blockedCount = physics3d.OverlapSphere(spawnPoint.transform.position, BlockedCheckRadius, blocked3D, BlockingLayers.value, QueryTriggerInteraction.UseGlobal); if (blockedCount > 0) Debug.LogWarning(blocked3D[0].name + " is blocking " + spawnPoint.name); return blockedCount > 0; } var physics2d = spawnPoint.gameObject.scene.GetPhysicsScene2D(); if (physics2d != null) { throw new System.NotImplementedException(); //return false; } return false; } }
412
0.826771
1
0.826771
game-dev
MEDIA
0.960369
game-dev
0.896156
1
0.896156
lua9520/source-engine-2018-cstrike15_src
114,990
engine/cl_demo.cpp
//========= Copyright (c) Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "client_pch.h" #include "enginestats.h" #include "iprediction.h" #include "cl_demo.h" #include "cl_demoactionmanager.h" #include "cl_pred.h" #include "baseautocompletefilelist.h" #include "demofile/demoformat.h" #include "gl_matsysiface.h" #include "materialsystem/imaterialsystemhardwareconfig.h" #include "tier0/icommandline.h" #include "vengineserver_impl.h" #include "console.h" #include "dt_common_eng.h" #include "gl_model_private.h" #include "decal.h" #include "icliententitylist.h" #include "icliententity.h" #include "cl_demouipanel.h" #include "materialsystem/materialsystem_config.h" #include "tier2/tier2.h" #include "vgui_baseui_interface.h" #include "con_nprint.h" #include "networkstringtableclient.h" #include "host_cmd.h" #include "matchmaking/imatchframework.h" #include "tier0/perfstats.h" #include "GameEventManager.h" #include "tier1/bitbuf.h" #include "net_chan.h" #include "tier1/characterset.h" #include "cl_steamauth.h" #if !defined DEDICATED #include "sound.h" #endif #if IsPlatformWindowsPC() #define WIN32_LEAN_AND_MEAN #undef INVALID_HANDLE_VALUE #include <winsock2.h> // gethostname #elif !IsGameConsole() #include <sys/unistd.h> // gethostname #endif #ifdef DEDICATED #include "server.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #ifdef _GAMECONSOLE // Disable demos on consoles by default, to avoid unwanted memory allocations, file I/O and computation #define ENABLE_DEMOS_BY_DEFAULT false #else #define ENABLE_DEMOS_BY_DEFAULT true #endif static ConVar demo_recordcommands( "demo_recordcommands", "1", FCVAR_CHEAT, "Record commands typed at console into .dem files." ); static ConVar demo_quitafterplayback( "demo_quitafterplayback", "0", #if defined( ALLOW_TEXT_MODE ) FCVAR_RELEASE, #else 0, #endif "Quits game after demo playback." ); extern ConVar demo_debug; static ConVar demo_interpolateview( "demo_interpolateview", "1", 0, "Do view interpolation during dem playback." ); static ConVar demo_pauseatservertick( "demo_pauseatservertick", "0", 0, "Pauses demo playback at server tick" ); static ConVar demo_enabledemos( "demo_enabledemos", ENABLE_DEMOS_BY_DEFAULT ? "1" : "0", 0, "Enable recording demos (must be set true before loading a map)" ); extern ConVar demo_strict_validation; // singeltons: static char g_pStatsFile[MAX_OSPATH] = { NULL }; static bool s_bBenchframe = false; static CDemoRecorder s_ClientDemoRecorder; CDemoRecorder *g_pClientDemoRecorder = &s_ClientDemoRecorder; IDemoRecorder *demorecorder = g_pClientDemoRecorder; static CDemoPlayer s_ClientDemoPlayer; CDemoPlayer *g_pClientDemoPlayer = &s_ClientDemoPlayer; IDemoPlayer *demoplayer = g_pClientDemoPlayer; extern CNetworkStringTableContainer *networkStringTableContainerClient; CUtlVector<RegisteredDemoCustomDataCallbackPair_t> g_RegisteredDemoCustomDataCallbacks; // This is the number of units under which we are allowed to interpolate, otherwise pop. // This fixes problems with in-level transitions. static ConVar demo_interplimit( "demo_interplimit", "4000", 0, "How much origin velocity before it's considered to have 'teleported' causing interpolation to reset." ); static ConVar demo_avellimit( "demo_avellimit", "2000", 0, "Angular velocity limit before eyes considered snapped for demo playback." ); #define DEMO_HEADER_FILE "demoheader.tmp" // Fast forward convars static ConVar demo_fastforwardstartspeed( "demo_fastforwardstartspeed", "2", 0, "Go this fast when starting to hold FF button." ); static ConVar demo_fastforwardfinalspeed( "demo_fastforwardfinalspeed", "20", 0, "Go this fast when starting to hold FF button." ); static ConVar demo_fastforwardramptime( "demo_fastforwardramptime", "5", 0, "How many seconds it takes to get to full FF speed." ); // highlight convars static ConVar demo_highlight_timebefore( "demo_highlight_timebefore", "6", 0, "How many seconds before highlight event to stop fast forwarding." ); static ConVar demo_highlight_timeafter( "demo_highlight_timeafter", "4", 0, "How many seconds after highlight event to start fast forwarding." ); static ConVar demo_highlight_fastforwardspeed( "demo_highlight_fastforwardspeed", "10", 0, "Speed to use when fast forwarding to highlights." ); static ConVar demo_highlight_skipthreshold( "demo_highlight_skipthreshold", "10", 0, "Number of seconds between previous highlight event and round start that will fast forward instead of skipping." ); float scr_demo_override_fov = 0.0f; // Defined in engine static ConVar cl_interpolate( "cl_interpolate", "1", FCVAR_RELEASE, "Enables or disables interpolation on listen servers or during demo playback" ); void SetPlaybackParametersLockFirstPersonAccountID( uint32 nAccountID ); void CL_ScanDemoDone( const char *pszMode ); //----------------------------------------------------------------------------- // Purpose: Implements IDemo and handles demo file i/o // Demos are more or less driven off of network traffic, but there are a few // other kinds of data items that are also included in the demo file: specifically // commands that the client .dll itself issued to the engine are recorded, though they // probably were not the result of network traffic. // At the start of a connection to a map/server, all of the signon, etc. network packets // are buffered. This allows us to actually decide to start recording the demo at a later // time. Once we actually issue the recording command, we don't actually start recording // network traffic, but instead we ask the server for an "uncompressed" packet (otherwise // we wouldn't be able to deal with the incoming packets during playback because we'd be missing the // data to delta from ) and go into a waiting state. Once an uncompressed packet is received, // we unset the waiting state and start recording network packets from that point forward. // Demo's record the elapsed time based on the current client clock minus the time the demo was started // During playback, the elapsed time for playback ( based on the host_time, which is subject to the // host_frametime cvar ) is compared with the elapsed time on the message from the demo file. // If it's not quite time for the message yet, the demo input stream is rewound // The demo system sits at the point where the client is checking to see if any network messages // have arrived from the server. If the message isn't ready for processing, the demo system // just responds that there are no messages waiting and the client continues on // Once a true network message with entity data is read from the demo stream, a couple of other // actions occur. First, the timestamp in the demo file and the view origin/angles corresponding // to the message are cached off. Then, we search ahead (into the future) to find out the next true network message // we are going to read from the demo file. We store of it's elapsed time and view origin/angles // Every frame that the client is rendering, even if there is no data from the demo system, // the engine asks the demo system to compute an interpolated origin and view angles. This // is done by taking the current time on the host and figuring out how far that puts us between // the last read origin from the demo file and the time when we'll actually read out and use the next origin // We use Quaternions to avoid gimbel lock on interpolating the view angles // To make a movie recorded at a fixed frame rate you would simply set the host_framerate to the // desired playback fps ( e.g., 0.02 == 50 fps ), then issue the startmovie command, and then // play the demo. The demo system will think that the engine is running at 50 fps and will pull // messages accordingly, even though movie recording kills the actually framerate. // It will also render frames with render origin/angles interpolated in-between the previous and next origins // even if the recording framerate was not 50 fps or greater. The interpolation provides a smooth visual playback // of the demo information to the client without actually adding latency to the view position (because we are // looking into the future for the position, not buffering the past data ). //----------------------------------------------------------------------------- bool IsControlCommand( unsigned char cmd ) { return ( (cmd == dem_signon) || (cmd == dem_stop) || (cmd == dem_synctick) || (cmd == dem_datatables ) || (cmd == dem_stringtables) ); } // Puts a flashing overlay on the screen during demo recording/playback static ConVar cl_showdemooverlay( "cl_showdemooverlay", "0", 0, "How often to flash demo recording/playback overlay (0 - disable overlay, -1 - show always)" ); class DemoOverlay { public: DemoOverlay(); ~DemoOverlay(); public: void Tick(); void DrawOverlay( float fSetting ); protected: float m_fLastTickTime; float m_fLastTickOverlay; enum Overlay { OVR_NONE = 0, OVR_REC = 1 << 1, OVR_PLAY = 1 << 2 }; bool m_bTick; int m_maskDrawnOverlay; } g_DemoOverlay; DemoOverlay::DemoOverlay() : m_fLastTickTime( 0.f ), m_fLastTickOverlay( 0.f ), m_bTick( false ), m_maskDrawnOverlay( OVR_NONE ) { } DemoOverlay::~DemoOverlay() { } void DemoOverlay::Tick() { if ( !m_bTick ) { m_bTick = true; float const fRealTime = Sys_FloatTime(); if ( m_fLastTickTime != fRealTime ) { m_fLastTickTime = fRealTime; float const fDelta = m_fLastTickTime - m_fLastTickOverlay; float const fSettingDelta = cl_showdemooverlay.GetFloat(); if ( fSettingDelta <= 0.f || fDelta >= fSettingDelta ) { m_fLastTickOverlay = m_fLastTickTime; DrawOverlay( fSettingDelta ); } } m_bTick = false; } } void DemoOverlay::DrawOverlay( float fSetting ) { int maskDrawnOverlay = OVR_NONE; if ( fSetting < 0.f ) { // Keep drawing maskDrawnOverlay = ( demorecorder->IsRecording() ? OVR_REC : 0 ) | ( demoplayer->IsPlayingBack() ? OVR_PLAY : 0 ); } else if ( fSetting == 0.f ) { // None maskDrawnOverlay = OVR_NONE; } else { // Flash maskDrawnOverlay = ( !m_maskDrawnOverlay ) ? ( ( demorecorder->IsRecording() ? OVR_REC : 0 ) | ( demoplayer->IsPlayingBack() ? OVR_PLAY : 0 ) ) : OVR_NONE; } int const idx = 1; if ( OVR_NONE == maskDrawnOverlay && OVR_NONE != m_maskDrawnOverlay ) { con_nprint_s xprn; memset( &xprn, 0, sizeof( xprn ) ); xprn.index = idx; xprn.time_to_live = -1; Con_NXPrintf( &xprn, "" ); } if ( OVR_PLAY & maskDrawnOverlay ) { con_nprint_s xprn; memset( &xprn, 0, sizeof( xprn ) ); xprn.index = idx; xprn.color[0] = 0.f; xprn.color[1] = 1.f; xprn.color[2] = 0.f; xprn.fixed_width_font = true; xprn.time_to_live = ( fSetting > 0.f ) ? fSetting : 1.f; Con_NXPrintf( &xprn, " PLAY " ); } if ( OVR_REC & maskDrawnOverlay ) { con_nprint_s xprn; memset( &xprn, 0, sizeof( xprn ) ); xprn.index = idx; xprn.color[0] = 1.f; xprn.color[1] = 0.f; xprn.color[2] = 0.f; xprn.fixed_width_font = true; xprn.time_to_live = ( fSetting > 0.f ) ? fSetting : 1.f; Con_NXPrintf( &xprn, " REC " ); } m_maskDrawnOverlay = maskDrawnOverlay; } //----------------------------------------------------------------------------- // Purpose: Mark whether we are waiting for the first uncompressed update packet // Input : waiting - //----------------------------------------------------------------------------- void CDemoRecorder::SetSignonState(SIGNONSTATE state) { if ( demoplayer->IsPlayingBack() ) return; if ( !demo_enabledemos.GetBool() ) return; if ( state == SIGNONSTATE_NEW ) { if ( m_DemoFile.IsOpen() ) { // we are already recording a demo file CloseDemoFile(); // prepare for recording next demo m_nDemoNumber++; } StartupDemoHeader(); } else if ( state == SIGNONSTATE_SPAWN ) { // close demo file header when this packet is finished m_bCloseDemoFile = true; } else if ( state == SIGNONSTATE_FULL ) { if ( m_bRecording ) { StartupDemoFile(); } } } int CDemoRecorder::GetRecordingTick( void ) { if ( GetBaseLocalClient().m_nMaxClients > 1 ) { return TIME_TO_TICKS( net_time ) - m_nStartTick; } else { return GetBaseLocalClient().GetClientTickCount() - m_nStartTick; } } void CDemoRecorder::ResyncDemoClock() { if ( GetBaseLocalClient().m_nMaxClients > 1 ) { m_nStartTick = TIME_TO_TICKS( net_time ); } else { m_nStartTick = GetBaseLocalClient().GetClientTickCount(); } } //----------------------------------------------------------------------------- // Purpose: // Input : info - //----------------------------------------------------------------------------- void CDemoRecorder::GetClientCmdInfo( democmdinfo_t& cmdInfo ) { for ( int hh = 0; hh < host_state.max_splitscreen_players; ++hh ) { ACTIVE_SPLITSCREEN_PLAYER_GUARD( hh ); democmdinfo_t::Split_t &info = cmdInfo.u[ hh ]; info.flags = FDEMO_NORMAL; if( m_bResetInterpolation ) { info.flags |= FDEMO_NOINTERP; m_bResetInterpolation = false; } g_pClientSidePrediction->GetViewOrigin( info.viewOrigin ); #ifndef DEDICATED info.viewAngles = GetLocalClient().viewangles; #endif g_pClientSidePrediction->GetLocalViewAngles( info.localViewAngles ); // Nothing by default info.viewOrigin2.Init(); info.viewAngles2.Init(); info.localViewAngles2.Init(); } m_bResetInterpolation = false; } void CDemoRecorder::WriteSplitScreenPlayers() { char data[NET_MAX_PAYLOAD]; bf_write msg; msg.StartWriting( data, NET_MAX_PAYLOAD ); msg.SetDebugName( "DemoFileWriteSplitScreenPlayers" ); FOR_EACH_VALID_SPLITSCREEN_PLAYER( i ) { if ( i == 0 ) continue; CSVCMsg_SplitScreen_t ss; ss.set_type( MSG_SPLITSCREEN_ADDUSER ); ss.set_slot( i ); ss.set_player_index( splitscreen->GetSplitScreenPlayerEntity( i ) ); ss.WriteToBuffer( msg ); } WriteMessages( msg ); } void CDemoRecorder::WriteBSPDecals() { decallist_t *decalList = (decallist_t*)malloc( sizeof(decallist_t) * Draw_DecalMax() ); int decalcount = DecalListCreate( decalList ); char data[NET_MAX_PAYLOAD]; bf_write msg; msg.StartWriting( data, NET_MAX_PAYLOAD ); msg.SetDebugName( "DemoFileWriteBSPDecals" ); for ( int i = 0; i < decalcount; i++ ) { decallist_t *entry = &decalList[ i ]; CSVCMsg_BSPDecal_t decal; bool found = false; IClientEntity *clientEntity = entitylist->GetClientEntity( entry->entityIndex ); if ( !clientEntity ) continue; const model_t * pModel = clientEntity->GetModel(); decal.mutable_pos()->set_x( entry->position.x ); decal.mutable_pos()->set_y( entry->position.y ); decal.mutable_pos()->set_z( entry->position.z ); decal.set_entity_index( entry->entityIndex ); decal.set_decal_texture_index( Draw_DecalIndexFromName( entry->name, &found ) ); decal.set_model_index( pModel ? GetBaseLocalClient().LookupModelIndex( modelloader->GetName( pModel ) ) : 0 ); decal.WriteToBuffer( msg ); } WriteMessages( msg ); free( decalList ); } void CDemoRecorder::RecordServerClasses( ServerClass *pClasses ) { MEM_ALLOC_CREDIT(); if ( !m_DemoFile.IsOpen() ) return; char *pBigBuffer; CUtlBuffer bigBuff; int buffSize = DEMO_RECORD_BUFFER_SIZE; // keep temp large allocations off of stack bigBuff.EnsureCapacity( buffSize ); pBigBuffer = (char*)bigBuff.Base(); bf_write buf( "CDemoRecorder::RecordServerClasses", pBigBuffer, buffSize ); // Send SendTable info. DataTable_WriteSendTablesBuffer( pClasses, &buf ); // Send class descriptions. DataTable_WriteClassInfosBuffer( pClasses, &buf ); if ( buf.GetNumBitsLeft() <= 0 ) { Sys_Error( "unable to record server classes\n" ); } // Now write the buffer into the demo file m_DemoFile.WriteNetworkDataTables( &buf, GetRecordingTick() ); } void CDemoRecorder::RecordStringTables() { MEM_ALLOC_CREDIT(); if ( !m_DemoFile.IsOpen() ) return; char *pBigBuffer; CUtlBuffer bigBuff; int buffSize = DEMO_RECORD_BUFFER_SIZE; // keep temp large allocations off of stack bigBuff.EnsureCapacity( buffSize ); pBigBuffer = (char*)bigBuff.Base(); bf_write buf( pBigBuffer, buffSize ); networkStringTableContainerClient->WriteStringTables( buf ); if ( buf.GetNumBitsLeft() <= 0 ) { Sys_Error( "unable to record server classes\n" ); } // Now write the buffer into the demo file m_DemoFile.WriteStringTables( &buf, GetRecordingTick() ); } void CDemoRecorder::RecordCustomData( int iCallbackIndex, const void *pData, size_t iDataLength ) { if ( !m_DemoFile.IsOpen() ) return; m_DemoFile.WriteCustomData( iCallbackIndex, pData, iDataLength, GetRecordingTick() ); } void CDemoRecorder::RecordUserInput( int cmdnumber ) { if ( !m_DemoFile.IsOpen() ) return; char buffer[256]; bf_write msg( "CDemo::WriteUserCmd", buffer, sizeof(buffer) ); ASSERT_LOCAL_PLAYER_RESOLVABLE(); int nSlot = GET_ACTIVE_SPLITSCREEN_SLOT(); g_ClientDLL->EncodeUserCmdToBuffer( nSlot, msg, cmdnumber ); m_DemoFile.WriteUserCmd( cmdnumber, buffer, msg.GetNumBytesWritten(), GetRecordingTick(), nSlot ); } void CDemoRecorder::ResetDemoInterpolation( void ) { m_bResetInterpolation = true; } //----------------------------------------------------------------------------- // Purpose: saves all cvars falgged with FVAR_DEMO to demo file //----------------------------------------------------------------------------- void CDemoRecorder::WriteDemoCvars() { if ( !m_DemoFile.IsOpen() ) return; ICvar::Iterator iter( g_pCVar ); for ( iter.SetFirst() ; iter.IsValid() ; iter.Next() ) { ConCommandBase *var = iter.Get(); if ( var->IsCommand() ) continue; const ConVar *cvar = ( const ConVar * )var; if ( !cvar->IsFlagSet( FCVAR_DEMO ) ) continue; char cvarcmd[MAX_OSPATH]; V_sprintf_safe( cvarcmd,"%s \"%s\"", cvar->GetName(), Host_CleanupConVarStringValue( cvar->GetString() ) ); m_DemoFile.WriteConsoleCommand( cvarcmd, GetRecordingTick(), 0 ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *cmdname - //----------------------------------------------------------------------------- void CDemoRecorder::RecordCommand( const char *cmdstring ) { if ( !IsRecording() ) return; if ( !cmdstring || !cmdstring[0] ) return; if ( !demo_recordcommands.GetInt() ) return; ASSERT_LOCAL_PLAYER_RESOLVABLE(); m_DemoFile.WriteConsoleCommand( cmdstring, GetRecordingTick(), GET_ACTIVE_SPLITSCREEN_SLOT() ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CDemoRecorder::StartupDemoHeader( void ) { CloseDemoFile(); // make sure it's closed // Note: this is replacing tmpfile() if ( !m_DemoFile.Open( DEMO_HEADER_FILE, false ) ) { ConDMsg ("ERROR: couldn't open temporary header file.\n"); return; } m_bIsDemoHeader = true; Assert( m_MessageData.GetBasePointer() == NULL ); // setup writing data buffer m_MessageData.StartWriting( new unsigned char[NET_MAX_PAYLOAD], NET_MAX_PAYLOAD ); m_MessageData.SetDebugName( "DemoHeaderWriteBuffer" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CDemoRecorder::StartupDemoFile( void ) { if ( !m_bRecording ) return; // Already recording!!! if ( m_DemoFile.IsOpen() ) return; if ( !demo_enabledemos.GetBool() ) { Warning( "DEMO: cannot start recording a demo (set 'demo_enabledemos' to 1 and restart the map to enable demos)\n" ); return; } char demoFileName[MAX_OSPATH]; if ( m_nDemoNumber <= 1 ) { V_sprintf_safe( demoFileName, "%s.dem", m_szDemoBaseName ); } else { V_sprintf_safe( demoFileName, "%s_%i.dem", m_szDemoBaseName, m_nDemoNumber ); } if ( !m_DemoFile.Open( demoFileName, false ) ) return; // open demo header file containing sigondata FileHandle_t hDemoHeader = g_pFileSystem->OpenEx( DEMO_HEADER_FILE, "rb", IsGameConsole() ? FSOPEN_NEVERINPACK : 0 ); if ( hDemoHeader == FILESYSTEM_INVALID_HANDLE ) { ConMsg ("StartupDemoFile: couldn't open demo file header.\n"); return; } Assert( m_MessageData.GetBasePointer() == NULL ); // setup writing data buffer m_MessageData.StartWriting( new unsigned char[NET_MAX_PAYLOAD], NET_MAX_PAYLOAD ); m_MessageData.SetDebugName( "DemoFileWriteBuffer" ); // fill demo header info demoheader_t *dh = &m_DemoFile.m_DemoHeader; V_memset(dh, 0, sizeof(demoheader_t)); dh->demoprotocol = DEMO_PROTOCOL; dh->networkprotocol = GetHostVersion(); V_strcpy_safe(dh->demofilestamp, DEMO_HEADER_ID ); V_FileBase( modelloader->GetName( host_state.worldmodel ), dh->mapname, sizeof( dh->mapname ) ); char szGameDir[MAX_OSPATH]; V_strcpy_safe(szGameDir, com_gamedir ); V_FileBase( szGameDir, dh->gamedirectory, sizeof( dh->gamedirectory ) ); V_strcpy_safe( dh->servername, GetBaseLocalClient().m_Remote.Get( 0 ).m_szRetryAddress ); V_strcpy_safe( dh->clientname, cl_name.GetString() ); // goto end of demo header g_pFileSystem->Seek(hDemoHeader, 0, FILESYSTEM_SEEK_TAIL); // get size signon data size dh->signonlength = g_pFileSystem->Tell(hDemoHeader); // go back to start g_pFileSystem->Seek(hDemoHeader, 0, FILESYSTEM_SEEK_HEAD); // write demo file header info m_DemoFile.WriteDemoHeader(); // copy signon data from header file to demo file m_DemoFile.WriteFileBytes( hDemoHeader, dh->signonlength ); // close but keep header file, we might need it for a second record g_pFileSystem->Close( hDemoHeader ); m_nFrameCount = 0; m_bIsDemoHeader = false; ResyncDemoClock(); // reset demo clock // tell client to sync demo clock too m_DemoFile.WriteCmdHeader( dem_synctick, 0, 0 ); //write out the custom data callback table if we have any entries int iCustomDataCallbacks = g_RegisteredDemoCustomDataCallbacks.Count(); if( iCustomDataCallbacks != 0 ) { size_t iCombinedStringLength = 0; for( int i = 0; i != iCustomDataCallbacks; ++i ) { iCombinedStringLength += V_strlen( STRING( g_RegisteredDemoCustomDataCallbacks[i].szSaveID ) ) + 1; } size_t iTotalDataSize = iCombinedStringLength + sizeof( int ); uint8 *pWriteBuffer = (uint8 *)stackalloc( iTotalDataSize ); uint8 *pWrite = pWriteBuffer; iCustomDataCallbacks = LittleDWord( iCustomDataCallbacks ); *(int *)pWrite = iCustomDataCallbacks; pWrite += sizeof( int ); for( int i = 0; i != iCustomDataCallbacks; ++i ) { size_t iStringLength = V_strlen( STRING( g_RegisteredDemoCustomDataCallbacks[i].szSaveID ) ) + 1; memcpy( pWrite, STRING( g_RegisteredDemoCustomDataCallbacks[i].szSaveID ), iStringLength ); pWrite += iStringLength; } Assert( pWrite == (pWriteBuffer + iTotalDataSize) ); m_DemoFile.WriteCustomData( -1, pWriteBuffer, iTotalDataSize, 0 ); } RecordStringTables(); // Demo playback should read this as an incoming message. WriteDemoCvars(); // save all cvars marked with FCVAR_DEMO WriteBSPDecals(); // Dump all accumulated avatar data messages into the starting portion of the demo file CNETMsg_PlayerAvatarData_t *pMsgMyOwnAvatarData = GetBaseLocalClient().AllocOwnPlayerAvatarData(); FOR_EACH_MAP_FAST( GetBaseLocalClient().m_mapPlayerAvatarData, iData ) { CNETMsg_PlayerAvatarData_t &msgPlayerAvatarData = *GetBaseLocalClient().m_mapPlayerAvatarData.Element( iData ); // if the server authoritative data overrides local version of avatar data then don't write local version if ( pMsgMyOwnAvatarData && ( msgPlayerAvatarData.accountid() == pMsgMyOwnAvatarData->accountid() ) ) { delete pMsgMyOwnAvatarData; pMsgMyOwnAvatarData = NULL; } byte buffer[ NET_MAX_PAYLOAD ]; bf_write bfWrite( "CDemoRecorder::NETMsg_PlayerAvatarData", buffer, sizeof( buffer ) ); msgPlayerAvatarData.WriteToBuffer( bfWrite ); WriteMessages( bfWrite ); } if ( pMsgMyOwnAvatarData ) { byte buffer[ NET_MAX_PAYLOAD ]; bf_write bfWrite( "CDemoRecorder::NETMsg_PlayerAvatarData", buffer, sizeof( buffer ) ); pMsgMyOwnAvatarData->WriteToBuffer( bfWrite ); WriteMessages( bfWrite ); delete pMsgMyOwnAvatarData; pMsgMyOwnAvatarData = NULL; } g_ClientDLL->HudReset(); if ( splitscreen->GetNumSplitScreenPlayers() > 1 ) { WriteSplitScreenPlayers(); } // tell server that we started recording a demo GetBaseLocalClient().SendStringCmd( "demorestart" ); ConMsg ("Recording to %s...\n", demoFileName); } CDemoRecorder::CDemoRecorder() { } CDemoRecorder::~CDemoRecorder() { CloseDemoFile(); } CDemoFile *CDemoRecorder::GetDemoFile() { return &m_DemoFile; } void CDemoRecorder::ResumeRecording() { } void CDemoRecorder::PauseRecording() { } void CDemoRecorder::CloseDemoFile() { if ( m_DemoFile.IsOpen()) { if ( !m_bIsDemoHeader ) { // Demo playback should read this as an incoming message. m_DemoFile.WriteCmdHeader( dem_stop, GetRecordingTick(), 0 ); // update demo header infos m_DemoFile.m_DemoHeader.playback_ticks = GetRecordingTick(); m_DemoFile.m_DemoHeader.playback_time = host_state.interval_per_tick * GetRecordingTick(); m_DemoFile.m_DemoHeader.playback_frames = m_nFrameCount; // go back to header and write demoHeader with correct time and #frame again m_DemoFile.WriteDemoHeader(); ConMsg ("Completed demo, recording time %.1f, game frames %i.\n", m_DemoFile.m_DemoHeader.playback_time, m_DemoFile.m_DemoHeader.playback_frames ); } if ( demo_debug.GetInt() ) { ConMsg ("Closed demo file, %i bytes.\n", m_DemoFile.GetSize() ); } m_DemoFile.Close(); } m_bCloseDemoFile = false; m_bIsDemoHeader = false; // clear writing data buffer if ( m_MessageData.GetBasePointer() ) { delete [] m_MessageData.GetBasePointer(); m_MessageData.StartWriting( NULL, 0 ); } } void CDemoRecorder::RecordMessages(bf_read &data, int bits) { if ( m_MessageData.GetBasePointer() && (bits>0) ) { m_MessageData.WriteBitsFromBuffer( &data, bits ); Assert( !m_MessageData.IsOverflowed() ); } } void CDemoRecorder::RecordPacket() { WriteMessages( m_MessageData ); m_MessageData.Reset(); // clear message buffer if ( m_bCloseDemoFile ) { CloseDemoFile(); } } void CDemoRecorder::WriteMessages( bf_write &message ) { if ( !m_DemoFile.IsOpen() ) return; int len = message.GetNumBytesWritten(); if (len <= 0) return; // fill last bits in last byte with NOP if necessary int nRemainingBits = message.GetNumBitsWritten() % 8; if ( nRemainingBits > 0 && nRemainingBits <= (8-NETMSG_TYPE_BITS) ) { CNETMsg_NOP_t nop; nop.WriteToBuffer( message ); } Assert( len < NET_MAX_MESSAGE ); // if signondata read as fast as possible, no rewind // and wait for packet time unsigned char cmd = m_bIsDemoHeader ? dem_signon : dem_packet; if ( cmd == dem_packet ) { m_nFrameCount++; } // write command & time m_DemoFile.WriteCmdHeader( cmd, GetRecordingTick(), 0 ); democmdinfo_t info; // Snag current info GetClientCmdInfo( info ); // Store it m_DemoFile.WriteCmdInfo( info ); // write network channel sequencing infos int nOutSequenceNr, nInSequenceNr, nOutSequenceNrAck; GetBaseLocalClient().m_NetChannel->GetSequenceData( nOutSequenceNr, nInSequenceNr, nOutSequenceNrAck ); m_DemoFile.WriteSequenceInfo( nInSequenceNr, nOutSequenceNrAck ); // Output the messge buffer. m_DemoFile.WriteRawData( (char*) message.GetBasePointer(), len ); if ( demo_debug.GetInt() >= 1 ) { Msg( "Writing demo message %i bytes at file pos %i\n", len, m_DemoFile.GetCurPos( false ) ); } } //----------------------------------------------------------------------------- // Purpose: stop recording a demo //----------------------------------------------------------------------------- void CDemoRecorder::StopRecording( const CGameInfo *pGameInfo ) { if ( !IsRecording() ) { return; } if ( m_MessageData.GetBasePointer() ) { delete[] m_MessageData.GetBasePointer(); m_MessageData.StartWriting( NULL, 0); } CloseDemoFile(); m_bRecording = false; m_nDemoNumber = 0; g_DemoOverlay.Tick(); } //----------------------------------------------------------------------------- // Purpose: // Input : *name - // track - //----------------------------------------------------------------------------- void CDemoRecorder::StartRecording( const char *name, bool bContinuously ) { V_strcpy_safe( m_szDemoBaseName, name ); m_bRecording = true; m_nDemoNumber = 1; m_bResetInterpolation = false; g_DemoOverlay.Tick(); // request a full game update from server GetBaseLocalClient().ForceFullUpdate( "recording demo" ); } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CDemoRecorder::IsRecording( void ) { g_DemoOverlay.Tick(); return m_bRecording; } // // Demo highlight helpers // struct DemoUserInfo_t { DemoUserInfo_t() : userID( -1 ) , name( NULL ) { } int userID; char *name; CSteamID steamID; }; CUtlVector< DemoUserInfo_t > s_demoUserInfo; void Callback_DemoScanUserInfoChanged( void *object, INetworkStringTable *stringTable, int stringNumber, const char *newString, const void *newData ) { // stringnumber == player slot player_info_t *player = (player_info_t*)newData; if ( !player ) { if ( s_demoUserInfo.Count() > stringNumber ) { // clear out the entry in our user info array s_demoUserInfo[ stringNumber ].userID = -1; s_demoUserInfo[ stringNumber ].name = NULL; s_demoUserInfo[ stringNumber ].steamID.SetFromUint64( 0 ); } return; // player left the game } CByteswap byteswap; byteswap.SetTargetBigEndian( true ); byteswap.SwapFieldsToTargetEndian( player ); if ( s_demoUserInfo.Count() <= stringNumber ) { s_demoUserInfo.SetCountNonDestructively( stringNumber + 1 ); } DemoUserInfo_t &entry = s_demoUserInfo.Element( stringNumber ); entry.userID = player->userID; entry.name = player->name; entry.steamID.SetFromUint64( player->xuid ); } void GetExtraDeathEventInfo( KeyValues *pKeys ) { int nAttackerID = pKeys->GetInt( "attacker" ); int nVictimID = pKeys->GetInt( "userid" ); int nAssisterID = pKeys->GetInt( "assister" ); FOR_EACH_VEC( s_demoUserInfo, i ) { if ( nAttackerID == s_demoUserInfo[ i ].userID ) { pKeys->SetString( "attacker_name", s_demoUserInfo[ i ].name ); pKeys->SetUint64( "attacker_xuid", s_demoUserInfo[ i ].steamID.ConvertToUint64() ); } else if ( nVictimID == s_demoUserInfo[ i ].userID ) { pKeys->SetString( "victim_name", s_demoUserInfo[ i ].name ); pKeys->SetUint64( "victim_xuid", s_demoUserInfo[ i ].steamID.ConvertToUint64() ); } else if ( nAssisterID == s_demoUserInfo[ i ].userID ) { pKeys->SetString( "assister_name", s_demoUserInfo[ i ].name ); pKeys->SetUint64( "assister_xuid", s_demoUserInfo[ i ].steamID.ConvertToUint64() ); } } } void GetExtraEventInfo( KeyValues *pKeys ) { int nUserID = pKeys->GetInt( "userid" ); FOR_EACH_VEC( s_demoUserInfo, i ) { if ( nUserID == s_demoUserInfo[ i ].userID ) { pKeys->SetString( "player_name", s_demoUserInfo[ i ].name ); pKeys->SetUint64( "player_xuid", s_demoUserInfo[ i ].steamID.ConvertToUint64() ); } } } static int s_nMaxViewers = 0; static int s_nMaxExternalTotal = 0; static int s_nMaxExternalLinked = 0; static int s_nMaxCombinedViewers = 0; void GetEventInfoForScan( const char *pszMode, KeyValues *pKeys ) { if ( V_strcasecmp( pszMode, "hltv_status" ) == 0 ) { int nClients = pKeys->GetInt( "clients", -1 ); int nProxies = pKeys->GetInt( "proxies", -1 ); int nExternalTotal = pKeys->GetInt( "externaltotal", -1 ); int nExternalLinked = pKeys->GetInt( "externallinked", -1 ); Msg( " GOTV Viewers: %d External Viewers: %d Linked: %d Combined Viewers: %d \n", nClients - nProxies, nExternalTotal, nExternalLinked, ( nClients - nProxies ) + nExternalTotal ); if ( ( nClients - nProxies ) > s_nMaxViewers ) { s_nMaxViewers = nClients - nProxies; } if ( nExternalTotal > s_nMaxExternalTotal ) { s_nMaxExternalTotal = nExternalTotal; } if ( nExternalLinked > s_nMaxExternalLinked ) { s_nMaxExternalLinked = nExternalLinked; } if ( ( ( nClients - nProxies ) + nExternalTotal ) > s_nMaxCombinedViewers ) { s_nMaxCombinedViewers = ( nClients - nProxies ) + nExternalTotal; } } } bool CheckKeyXuid( const CSteamID &steamID, KeyValues *pKeys, const char* pKeyWithXuid ) { CSteamID playerSteamID( pKeys->GetUint64( pKeyWithXuid ) ); if ( steamID.GetAccountID() == playerSteamID.GetAccountID() ) { return true; } return false; } int GetPlayerIndex( const CSteamID &steamID ) { FOR_EACH_VEC( s_demoUserInfo, i ) { if ( s_demoUserInfo[ i ].steamID.GetAccountID() == steamID.GetAccountID() ) { return i + 1; } } return -1; } //----------------------------------------------------------------------------- // Purpose: Called when a demo file runs out, or the user starts a game // Output : void CDemo::StopPlayback //----------------------------------------------------------------------------- void CDemoPlayer::StopPlayback( void ) { if ( !IsPlayingBack() ) return; demoaction->StopPlaying(); m_DemoFile.Close(); m_bPlayingBack = false; m_bPlaybackPaused = false; m_flAutoResumeTime = 0.0f; if ( m_bTimeDemo ) { g_EngineStats.EndRun(); if ( !s_bBenchframe ) { WriteTimeDemoResults(); } else { mat_norendering.SetValue( 0 ); } m_bTimeDemo = false; } else { int framecount = host_framecount - m_nTimeDemoStartFrame; float demotime = Sys_FloatTime() - m_flTimeDemoStartTime; if ( demotime > 0.0f ) { DevMsg( "Demo playback finished ( %.1f seconds, %i render frames, %.2f fps).\n", demotime, framecount, framecount/demotime); } } m_flPlaybackRateModifier = 1.0f; delete[] m_DemoPacket.data; m_DemoPacket.data = NULL; scr_demo_override_fov = 0.0f; if ( demo_quitafterplayback.GetBool() ) { Cbuf_AddText( Cbuf_GetCurrentPlayer(), "quit\n" ); } g_ClientDLL->OnDemoPlaybackStop(); FOR_EACH_VEC( m_ImportantTicks, i ) { if ( m_ImportantTicks[ i ].pKeys ) { m_ImportantTicks[ i ].pKeys->deleteThis(); } } m_ImportantTicks.RemoveAll(); m_ImportantGameEvents.RemoveAll(); m_highlights.RemoveAll(); m_nCurrentHighlight = -1; m_highlightSteamID.SetFromUint64( 0 ); m_nHighlightPlayerIndex = -1; m_bScanMode = false; m_szScanMode[0] = 0; } #define SKIP_TO_TICK_FLAG uint32( uint32( 0x88 ) << 24 ) bool CDemoPlayer::IsSkipping( void )const { return m_bPlayingBack && ( ( m_nSkipToTick != -1 ) || g_ClientDLL->ShouldSkipEvidencePlayback( m_pPlaybackParameters ) ); } int CDemoPlayer::GetTotalTicks(void) { return m_DemoFile.m_DemoHeader.playback_ticks; // == m_DemoFile.GetTotalTicks(); } void CDemoPlayer::SetPacketReadSuspended( bool bSuspendPacketReading ) { if ( m_bPacketReadSuspended == bSuspendPacketReading ) return; // same state m_bPacketReadSuspended = bSuspendPacketReading; if ( !m_bPacketReadSuspended ) ResyncDemoClock(); // Make sure we resync demo clock when we resume packet reading } void CDemoPlayer::SkipToTick( int tick, bool bRelative, bool bPause ) { if ( m_bPacketReadSuspended ) return; // demo ticks and host ticks aren't resync'd when packet read is suspended if ( bRelative ) { tick = GetPlaybackTick() + tick; } if ( tick < 0 ) return; if ( tick < GetPlaybackTick() ) { if ( m_pPlaybackParameters && m_pPlaybackParameters->m_bAnonymousPlayerIdentity ) { Msg( "Going backwards not available in Overwatch!\n" ); return; } RestartPlayback(); #if 0 // old way // we have to reload the whole demo file // we need to create a temp copy of the filename char fileName[MAX_OSPATH]; V_strcpy_safe( fileName, m_DemoFile.m_szFileName ); StopPlayback(); // disconnect before reloading demo, to avoid sometimes loading into game instead of demo GetBaseLocalClient().Disconnect(false); // reload current demo file StartPlayback( fileName, m_bTimeDemo, NULL ); // Make sure the proper skipping occurs after reload if ( tick > 0 ) tick |= SKIP_TO_TICK_FLAG; #endif } if ( tick != GetPlaybackTick() ) { m_nSkipToTick = tick; } if ( bPause || m_bPlaybackPaused ) { int nTicksPerFrame = m_DemoFile.GetTicksPerFrame( ); m_nTickToPauseOn = tick + nTicksPerFrame; m_bSavedInterpolateState = cl_interpolate.GetBool(); cl_interpolate.SetValue( 0 ); ResumePlayback(); } } void CDemoPlayer::SkipToImportantTick( const DemoImportantTick_t *pTick ) { if ( m_bPacketReadSuspended ) return; // demo ticks and host ticks aren't resync'd when packet read is suspended int nStartTick = GetPlaybackTick(); int nTargetTick = pTick->nPreviousTick; int nTicksBeforeEvent = m_ImportantGameEvents[ pTick->nImportanGameEventIndex ].flSeekTimeBefore / host_state.interval_per_tick; if ( nTicksBeforeEvent > 0 ) { int nTargetTick = pTick->nTick - nTicksBeforeEvent; // handle case where desired next tick is close to where we already are and going to 'ticks before event' would cause us to seek backwards. // instead we won't skip at all if ( pTick->nTick >= nStartTick && nTargetTick < nStartTick ) { nTargetTick = nStartTick; } if ( nTargetTick < 0 ) { nTargetTick = 0; } } if ( nTargetTick < nStartTick ) { if ( m_pPlaybackParameters && m_pPlaybackParameters->m_bAnonymousPlayerIdentity ) { Msg( "Going backwards not available in Overwatch!\n" ); return; } RestartPlayback(); } if ( nTargetTick != nStartTick ) { m_nSkipToTick = nTargetTick; } if ( m_bPlaybackPaused ) { // this code sets things up so that we will pause once we reach the tick. int nTicksPerFrame = m_DemoFile.GetTicksPerFrame(); m_nTickToPauseOn = pTick->nTick + nTicksPerFrame; // turn interpolation off for the time between seeking and playing until pause state m_bSavedInterpolateState = cl_interpolate.GetBool(); cl_interpolate.SetValue( 0 ); ResumePlayback(); } } //----------------------------------------------------------------------------- // Purpose: Read in next demo message and send to local client over network channel, if it's time. // Output : bool //----------------------------------------------------------------------------- bool CDemoPlayer::ParseAheadForInterval( int curtick, int intervalticks ) { int tick = 0; int dummy; byte cmd = dem_stop; democmdinfo_t nextinfo; long starting_position = m_DemoFile.GetCurPos( true ); // remove all entrys older than 32 ticks while ( m_DestCmdInfo.Count() > 0 ) { DemoCommandQueue& entry = m_DestCmdInfo[ 0 ]; if ( entry.tick >= (curtick - 32) ) break; if ( entry.filepos >= starting_position ) break; m_DestCmdInfo.Remove( 0 ); } if ( m_bTimeDemo ) return false; while ( true ) { // skip forward to the next dem_packet or dem_signon bool swallowmessages = true; do { int nPlayerSlot = 0; m_DemoFile.ReadCmdHeader( cmd, tick, nPlayerSlot ); // COMMAND HANDLERS switch ( cmd ) { case dem_synctick: case dem_stop: { m_DemoFile.SeekTo( starting_position, true ); return false; } break; case dem_consolecmd: { ACTIVE_SPLITSCREEN_PLAYER_GUARD( nPlayerSlot ); m_DemoFile.ReadConsoleCommand(); } break; case dem_datatables: { m_DemoFile.ReadNetworkDataTables( NULL ); } break; case dem_usercmd: { ACTIVE_SPLITSCREEN_PLAYER_GUARD( nPlayerSlot ); m_DemoFile.ReadUserCmd( NULL, dummy ); } break; case dem_customdata: { m_DemoFile.ReadCustomData( NULL, NULL ); } break; case dem_stringtables: { m_DemoFile.ReadStringTables( NULL ); } break; default: { swallowmessages = false; } break; } } while ( swallowmessages ); int curpos = m_DemoFile.GetCurPos( true ); // we read now a dem_packet m_DemoFile.ReadCmdInfo( nextinfo ); m_DemoFile.ReadSequenceInfo( dummy, dummy ); m_DemoFile.ReadRawData( NULL, 0 ); DemoCommandQueue entry; entry.info = nextinfo; entry.tick = tick; entry.filepos = curpos; int i = 0; int c = m_DestCmdInfo.Count(); for ( ; i < c; ++i ) { if ( m_DestCmdInfo[ i ].filepos == entry.filepos ) break; // cmdinfo is already in list } if ( i >= c ) { // add cmdinfo to list if ( c > 0 ) { if ( m_DestCmdInfo[ c - 1 ].tick > tick ) { m_DestCmdInfo.RemoveAll(); } } m_DestCmdInfo.AddToTail( entry ); } if ( ( tick - curtick ) > intervalticks ) break; } m_DemoFile.SeekTo( starting_position, true ); return true; } //----------------------------------------------------------------------------- // Purpose: Read in next demo message and send to local client over network channel, if it's time. // Output : bool //----------------------------------------------------------------------------- netpacket_t *CDemoPlayer::ReadPacket( void ) { int tick = 0; byte cmd = dem_signon; long curpos = 0; if ( ! m_DemoFile.IsOpen() ) { m_bPlayingBack = false; Host_EndGame( true, "Tried to read a demo message with no demo file\n" ); return NULL; } // If game is still shutting down, then don't read any demo messages from file quite yet if ( HostState_IsGameShuttingDown() ) { return NULL; } Assert( IsPlayingBack() ); if ( m_nTimeDemoCurrentFrame >= 0 ) { // don't scan when doing overwatch if ( !m_pPlaybackParameters || !m_pPlaybackParameters->m_bAnonymousPlayerIdentity ) { GetImportantGameEventIDs(); ScanForImportantTicks(); if ( m_bScanMode && m_ImportantTicks.Count() > 0 ) { CL_ScanDemoDone( m_szScanMode ); return NULL; } if ( m_bDoHighlightScan ) { BuildHighlightList(); } } } // External editor has paused playback if ( CheckPausedPlayback() ) return NULL; // handle highlights if ( m_nCurrentHighlight != -1 && !IsSkipping() ) { int nCurrentTick = GetPlaybackTick(); if ( nCurrentTick >= m_highlights[ m_nCurrentHighlight ].nPlayToTick ) { m_nCurrentHighlight++; if ( m_nCurrentHighlight >= m_highlights.Count() ) { m_nCurrentHighlight = -1; SetPlaybackTimeScale( 1.0f ); g_ClientDLL->ShowHighlightSkippingMessage( false ); m_pPlaybackParameters = NULL; return NULL; } } const DemoHighlightEntry_t &highlight = m_highlights[ m_nCurrentHighlight ]; SetPlaybackParametersLockFirstPersonAccountID( highlight.unAccountID ); // deal with skipping and fast forwarding if ( highlight.nSeekToTick != -1 && nCurrentTick < highlight.nSeekToTick ) { g_ClientDLL->ShowHighlightSkippingMessage( true, nCurrentTick, highlight.nSeekToTick, highlight.nPlayToTick ); m_nSkipToTick = highlight.nSeekToTick; } else { if ( nCurrentTick < highlight.nFastForwardToTick ) { g_ClientDLL->ShowHighlightSkippingMessage( true, nCurrentTick, highlight.nSeekToTick, highlight.nPlayToTick ); SetPlaybackTimeScale( demo_highlight_fastforwardspeed.GetFloat() ); } else { SetPlaybackTimeScale( 1.0f ); g_ClientDLL->ShowHighlightSkippingMessage( false, nCurrentTick, highlight.nSeekToTick, highlight.nPlayToTick ); } } } bool bStopReading = false; while ( !bStopReading ) { curpos = m_DemoFile.GetCurPos( true ); int nPlayerSlot = 0; m_DemoFile.ReadCmdHeader( cmd, tick, nPlayerSlot ); m_nPacketTick = tick; if ( m_nTickToPauseOn != -1 && tick >= m_nTickToPauseOn ) { m_nTickToPauseOn = -1; PausePlayback( -1 ); cl_interpolate.SetValue( m_bSavedInterpolateState ? 1 : 0 ); } if ( m_nCurrentHighlight != -1 && IsSkipping() ) { if ( m_highlights[ m_nCurrentHighlight ].nSeekToTick != -1 && tick >= m_highlights[ m_nCurrentHighlight ].nSeekToTick ) { m_nSkipToTick = -1; } } // always read control commands if ( !IsControlCommand( cmd ) ) { int playbacktick = GetPlaybackTick(); if ( !m_bTimeDemo ) { // Time demo ignores clocks and tries to synchronize frames to what was recorded // I.e., while frame is the same, read messages, otherwise, skip out. // If we're still signing on, then just parse messages until fully connected no matter what if ( GetBaseLocalClient().IsActive() && (tick > playbacktick) && !IsSkipping() ) { // is not time yet bStopReading = true; } } else { if ( m_nTimeDemoCurrentFrame == host_framecount ) { if ( !IsSkipping() ) { // If we are playing back a timedemo, and we've already passed on a // frame update for this host_frame tag, then we'll just skip this mess bStopReading = true; } } } if ( bStopReading ) { demoaction->Update( false, playbacktick, TICKS_TO_TIME( playbacktick ) ); m_DemoFile.SeekTo( curpos, true ); // go back to start of current demo command return NULL; // Not time yet, dont return packet data. } } // COMMAND HANDLERS switch ( cmd ) { case dem_synctick: { if ( demo_debug.GetBool() ) { Msg( "%d dem_synctick\n", tick ); } ResyncDemoClock(); m_nRestartFilePos = m_DemoFile.GetCurPos( true ); // Once demo clock got resync-ed we can go ahead and // perform skipping logic normally if ( ( m_nSkipToTick != -1 ) && ( ( m_nSkipToTick & SKIP_TO_TICK_FLAG ) == SKIP_TO_TICK_FLAG ) ) { m_nSkipToTick &= ~SKIP_TO_TICK_FLAG; } } break; case dem_stop: { if ( demo_debug.GetBool() ) { Msg( "%d dem_stop\n", tick ); } if ( g_pMatchFramework ) { g_pMatchFramework->GetEventsSubscription()->BroadcastEvent( new KeyValues( "OnDemoFileEndReached" ) ); } FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh ) { ACTIVE_SPLITSCREEN_PLAYER_GUARD( hh ); GetBaseLocalClient().Disconnect(true); } return NULL; } break; case dem_consolecmd: { ACTIVE_SPLITSCREEN_PLAYER_GUARD( nPlayerSlot ); const char * command = m_DemoFile.ReadConsoleCommand(); if ( demo_debug.GetBool() ) { Msg( "%d dem_consolecmd [%s]\n", tick, command ); } Cbuf_AddText( Cbuf_GetCurrentPlayer(), command, kCommandSrcDemoFile ); Cbuf_Execute(); } break; case dem_datatables: { if ( demo_debug.GetBool() ) { Msg( "%d dem_datatables\n", tick ); } void *data = malloc( DEMO_RECORD_BUFFER_SIZE ); // X360TBD: How much memory is really needed here? bf_read buf( "dem_datatables", data, DEMO_RECORD_BUFFER_SIZE ); m_DemoFile.ReadNetworkDataTables( &buf ); buf.Seek( 0 ); // re-read data // support for older engine demos if ( !DataTable_LoadDataTablesFromBuffer( &buf, m_DemoFile.m_DemoHeader.demoprotocol ) ) { Host_Error( "Error parsing network data tables during demo playback." ); } free( data ); } break; case dem_stringtables: { void *data = malloc( DEMO_RECORD_BUFFER_SIZE ); // X360TBD: How much memory is really needed here? bf_read buf( "dem_stringtables", data, DEMO_RECORD_BUFFER_SIZE ); m_DemoFile.ReadStringTables( &buf ); buf.Seek( 0 ); if ( !networkStringTableContainerClient->ReadStringTables( buf ) ) { Host_Error( "Error parsing string tables during demo playback." ); } free( data ); } break; case dem_usercmd: { ACTIVE_SPLITSCREEN_PLAYER_GUARD( nPlayerSlot ); if ( demo_debug.GetBool() ) { Msg( "%d dem_usercmd\n", tick ); } char buffer[256]; int length = sizeof(buffer); int outgoing_sequence = m_DemoFile.ReadUserCmd( buffer, length ); // put it into a bitbuffer bf_read msg( "CDemo::ReadUserCmd", buffer, length ); g_ClientDLL->DecodeUserCmdFromBuffer( nPlayerSlot, msg, outgoing_sequence ); // Note, we need to have the current outgoing sequence correct so we can do prediction // correctly during playback GetBaseLocalClient().lastoutgoingcommand = outgoing_sequence; } break; case dem_customdata: { int iCallbackIndex; uint8 *pData; int iSize = m_DemoFile.ReadCustomData( &iCallbackIndex, &pData ); if( iCallbackIndex == -1 ) { //special handler, this is the data that fills in the rest of the data uint8 *pParse = pData; int iTableEntries = *(int *)pParse; pParse += sizeof( int ); iTableEntries = LittleDWord( iTableEntries ); m_CustomDataCallbackMap.SetSize( iTableEntries ); for( int i = 0; i != iTableEntries; ++i ) { m_CustomDataCallbackMap[i].name = (char *)pParse; pParse += V_strlen( (char *)pParse ) + 1; //now that we have the name, map that to a registered callback function int j; for( j = 0; j != g_RegisteredDemoCustomDataCallbacks.Count(); ++j ) { if( V_stricmp( m_CustomDataCallbackMap[i].name.Get(), STRING( g_RegisteredDemoCustomDataCallbacks[j].szSaveID ) ) == 0 ) { //match m_CustomDataCallbackMap[i].pCallback = g_RegisteredDemoCustomDataCallbacks[j].pCallback; break; } } Assert( j != g_RegisteredDemoCustomDataCallbacks.Count() ); //found a match } Assert( pParse == (pData + iSize) ); //properly parsed the table } else { //send it off Assert( iCallbackIndex < m_CustomDataCallbackMap.Count() ); Assert( m_CustomDataCallbackMap[iCallbackIndex].pCallback != NULL ); if( m_CustomDataCallbackMap[iCallbackIndex].pCallback != NULL ) m_CustomDataCallbackMap[iCallbackIndex].pCallback( pData, iSize ); else Warning( "Unable to decode custom demo data, callback \"%s\" not found.\n", m_CustomDataCallbackMap[iCallbackIndex].name.Get() ); } } break; default: { bStopReading = true; if ( IsSkipping() ) { // adjust playback host_tickcount when skipping m_nStartTick = host_tickcount - tick; } } break; } } if ( cmd == dem_packet ) { // remember last frame we read a dem_packet update m_nTimeDemoCurrentFrame = host_framecount; } int inseq, outseqack, outseq = 0; m_DemoFile.ReadCmdInfo( m_LastCmdInfo ); m_DemoFile.ReadSequenceInfo( inseq, outseqack ); GetBaseLocalClient().m_NetChannel->SetSequenceData( outseq, inseq, outseqack ); int length = m_DemoFile.ReadRawData( (char*)m_DemoPacket.data, NET_MAX_PAYLOAD ); if ( demo_debug.GetBool() ) { Msg( "%d network packet [%d]\n", tick, length ); } if ( length > 0 ) { // succsessfully read new demopacket m_DemoPacket.received = realtime; m_DemoPacket.size = length; m_DemoPacket.message.StartReading( m_DemoPacket.data, m_DemoPacket.size ); if ( demo_debug.GetInt() >= 1 ) { Msg( "Demo message, tick %i, %i bytes\n", GetPlaybackTick(), length ); } } // Try and jump ahead one frame m_bInterpolateView = ParseAheadForInterval( tick, 8 ); // ConMsg( "Reading message for %i : %f skip %i\n", m_nFrameCount, fElapsedTime, forceskip ? 1 : 0 ); // Skip a few ticks before doing any timing if ( (m_nTimeDemoStartFrame < 0) && GetPlaybackTick() > 100 ) { m_nTimeDemoStartFrame = host_framecount; m_flTimeDemoStartTime = Sys_FloatTime(); m_flTotalFPSVariability = 0.0f; if ( m_bTimeDemo ) { g_EngineStats.BeginRun(); g_PerfStats.Reset(); } } if ( m_nSnapshotTick > 0 && m_nSnapshotTick <= GetPlaybackTick() ) { const char *filename = "benchframe"; if ( m_SnapshotFilename[0] ) filename = m_SnapshotFilename; CL_TakeScreenshot( filename ); // take a screenshot m_nSnapshotTick = 0; if ( s_bBenchframe ) { Cbuf_AddText( Cbuf_GetCurrentPlayer(), "stopdemo\n" ); } } return &m_DemoPacket; } void CDemoPlayer::InterpolateDemoCommand( int nSlot, int targettick, DemoCommandQueue& prev, DemoCommandQueue& next ) { CUtlVector< DemoCommandQueue >& list = m_DestCmdInfo; int c = list.Count(); prev.info.Reset(); next.info.Reset(); if ( c < 2 ) { // we need at least two entries to interpolate return; } int i = 0; int savedI = -1; DemoCommandQueue *entry1 = &list[ i ]; DemoCommandQueue *entry2 = &list[ i+1 ]; while ( true ) { if ( (entry1->tick <= targettick) && (entry2->tick > targettick) ) { // Means we hit a FDEMO_NOINTERP along the way to now if ( savedI != -1 ) { prev = list[ savedI ]; next = list[ savedI + 1 ]; } else { prev = *entry1; next = *entry2; } return; } // If any command between the previous target and now has the FDEMO_NOINTERP, we need to stop at the command just before that (entry), so we save off the I // We can't just return since we need to see if we actually get to a spanning pair (though we always should). Also, we only latch this final interp spot on /// the first FDEMO_NOINTERP we see if ( savedI == -1 && entry2->tick > m_nPreviousTick && entry2->tick <= targettick && entry2->info.u[ nSlot ].flags & FDEMO_NOINTERP ) { savedI = i; } if ( i+2 == c ) break; i++; entry1 = &list[ i ]; entry2 = &list[ i+1 ]; } } static ConVar demo_legacy_rollback( "demo_legacy_rollback", "1", 0, "Use legacy view interpolation rollback amount in demo playback." ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CDemoPlayer::InterpolateViewpoint( void ) { if ( !IsPlayingBack() ) return; democmdinfo_t outinfo; outinfo.Reset(); FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh ) { ACTIVE_SPLITSCREEN_PLAYER_GUARD( hh ); bool bHasValidData = m_LastCmdInfo.u[ hh ].viewOrigin != vec3_origin || m_LastCmdInfo.u[ hh ].viewAngles != vec3_angle || m_LastCmdInfo.u[ hh ].localViewAngles != vec3_angle || m_LastCmdInfo.u[ hh ].flags != 0; int nTargetTick = GetPlaybackTick(); // Player view needs to be one tick interval in the past like the client DLL entities if ( GetBaseLocalClient().m_nMaxClients == 1 ) { if ( demo_legacy_rollback.GetBool() ) { nTargetTick -= TIME_TO_TICKS( GetBaseLocalClient().GetClientInterpAmount() ) + 1; } else { nTargetTick -= 1; } } float vel = 0.0f; float angVel = 0.0f; if ( m_bInterpolateView && demo_interpolateview.GetBool() && bHasValidData ) { DemoCommandQueue prev, next; float frac = 0.0f; prev.info = m_LastCmdInfo; prev.tick = -1; next.info = m_LastCmdInfo; next.tick = -1; // Determine current time slice InterpolateDemoCommand( hh, nTargetTick, prev, next ); float dt = TICKS_TO_TIME(next.tick-prev.tick); frac = (TICKS_TO_TIME(nTargetTick-prev.tick)+GetBaseLocalClient().m_tickRemainder)/dt; frac = clamp( frac, 0.0f, 1.0f ); // Now interpolate Vector delta; Vector startorigin = prev.info.u[ hh ].GetViewOrigin(); Vector destorigin = next.info.u[ hh ].GetViewOrigin(); // check for teleporting - since there can be multiple cmd packets between a game frame, // we need to check from the last actually ran command to see if there was a teleport VectorSubtract( destorigin, m_LastCmdInfo.u[ hh ].GetViewOrigin(), delta ); float distmoved = delta.Length(); if ( dt > 0.0f ) { vel = distmoved / dt; } if ( dt > 0.0f ) { QAngle startang = prev.info.u[ hh ].GetLocalViewAngles(); QAngle destang = next.info.u[ hh ].GetLocalViewAngles(); for ( int i = 0; i < 3; ++i ) { float dAng = AngleNormalizePositive( destang[ i ] ) - AngleNormalizePositive( startang[ i ] ); dAng = AngleNormalize( dAng ); float aVel = fabs( dAng ) / dt; if ( aVel > angVel ) { angVel = aVel; } } } // FIXME: This should be velocity based maybe? if ( (vel > demo_interplimit.GetFloat()) || (angVel > demo_avellimit.GetFloat() ) || m_bResetInterpolation ) { m_bResetInterpolation = false; // it's a teleport, just let it happen naturally next frame // setting frac to 1.0 (like it was previously) would just mean that we // are teleporting a frame ahead of when we should outinfo.u[ hh ].viewOrigin = m_LastCmdInfo.u[ hh ].GetViewOrigin(); outinfo.u[ hh ].viewAngles = m_LastCmdInfo.u[ hh ].GetViewAngles(); outinfo.u[ hh ].localViewAngles = m_LastCmdInfo.u[ hh ].GetLocalViewAngles(); } else { outinfo.u[ hh ].viewOrigin = startorigin + frac * ( destorigin - startorigin ); Quaternion src, dest; Quaternion result; AngleQuaternion( prev.info.u[ hh ].GetViewAngles(), src ); AngleQuaternion( next.info.u[ hh ].GetViewAngles(), dest ); QuaternionSlerp( src, dest, frac, result ); QuaternionAngles( result, outinfo.u[ hh ].viewAngles ); AngleQuaternion( prev.info.u[ hh ].GetLocalViewAngles(), src ); AngleQuaternion( next.info.u[ hh ].GetLocalViewAngles(), dest ); QuaternionSlerp( src, dest, frac, result ); QuaternionAngles( result, outinfo.u[ hh ].localViewAngles ); } } else if ( bHasValidData ) { // don't interpolate, just copy values outinfo.u[ hh ].viewOrigin = m_LastCmdInfo.u[ hh ].GetViewOrigin(); outinfo.u[ hh ].viewAngles = m_LastCmdInfo.u[ hh ].GetViewAngles(); outinfo.u[ hh ].localViewAngles = m_LastCmdInfo.u[ hh ].GetLocalViewAngles(); } m_nPreviousTick = nTargetTick; // let any demo system override view ( drive, editor, smoother etc) bHasValidData |= OverrideView( outinfo ); if ( !bHasValidData ) continue; // no validate data & no override, exit g_pClientSidePrediction->SetViewOrigin( outinfo.u[ hh ].viewOrigin ); g_pClientSidePrediction->SetViewAngles( outinfo.u[ hh ].viewAngles ); g_pClientSidePrediction->SetLocalViewAngles( outinfo.u[ hh ].localViewAngles ); #ifndef DEDICATED VectorCopy( outinfo.u[ hh ].viewAngles, GetLocalClient().viewangles ); #endif } } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CDemoPlayer::IsPlayingTimeDemo( void )const { return m_bTimeDemo && m_bPlayingBack; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CDemoPlayer::IsPlayingBack( void )const { return m_bPlayingBack; } CDemoPlayer::CDemoPlayer() { m_flAutoResumeTime = 0.0f; m_flPlaybackRateModifier = 1.0f; m_bTimeDemo = false; m_nTimeDemoStartFrame = -1; m_flTimeDemoStartTime = 0.0f; m_flTotalFPSVariability = 0.0f; m_nTimeDemoCurrentFrame = -1; m_nPacketTick = 0; // pulling together with broadcast m_bPlayingBack = false; m_bPlaybackPaused = false; m_nSkipToTick = -1; m_nSnapshotTick = 0; m_SnapshotFilename[0] = 0; m_bResetInterpolation = false; m_nPreviousTick = 0; m_pPlaybackParameters = NULL; m_bPacketReadSuspended = false; m_nRestartFilePos = -1; m_pImportantEventData = NULL; m_nTickToPauseOn = -1; m_bSavedInterpolateState = true; m_highlightSteamID.SetFromUint64( 0 ); m_nHighlightPlayerIndex = -1; m_bDoHighlightScan = false; m_nCurrentHighlight = -1; m_bLowlightsMode = false; m_bScanMode = false; m_szScanMode[0] = 0; } CDemoPlayer::~CDemoPlayer() { StopPlayback(); if ( g_ClientDLL ) { g_ClientDLL->OnDemoPlaybackStop(); } } CDemoPlaybackParameters_t const * CDemoPlayer::GetDemoPlaybackParameters() { return m_bPlayingBack ? m_pPlaybackParameters : NULL; } //----------------------------------------------------------------------------- // Purpose: Start's demo playback // Input : *name - //----------------------------------------------------------------------------- bool CDemoPlayer::StartPlayback( const char *filename, bool bAsTimeDemo, CDemoPlaybackParameters_t const *pPlaybackParameters, int nStartingTick ) { m_pPlaybackParameters = pPlaybackParameters; m_bPacketReadSuspended = false; SCR_BeginLoadingPlaque(); // Disconnect from server or stop running one int oldn = GetBaseLocalClient().demonum; GetBaseLocalClient().demonum = -1; Host_Disconnect( false ); GetBaseLocalClient().demonum = oldn; m_bPlayingBack = true; if ( !m_DemoFile.Open( filename, true ) ) { m_bPlayingBack = false; GetBaseLocalClient().demonum = -1; // stop demo loop return false; } // Read in the m_DemoHeader demoheader_t *dh = m_DemoFile.ReadDemoHeader( pPlaybackParameters ); if ( !dh ) { m_bPlayingBack = false; ConMsg( "Failed to read demo header.\n" ); m_DemoFile.Close(); GetBaseLocalClient().demonum = -1; return false; } if ( dh->playback_frames == 0 && dh->playback_ticks == 0 && dh->playback_time == 0 ) { ConMsg( "Demo %s is incomplete\n", filename ); } else { ConMsg( "Playing demo from %s.\n", filename ); } FOR_EACH_VEC( m_ImportantTicks, i ) { if ( m_ImportantTicks[ i ].pKeys ) { m_ImportantTicks[ i ].pKeys->deleteThis(); } } m_ImportantTicks.RemoveAll(); m_ImportantGameEvents.RemoveAll(); m_highlights.RemoveAll(); m_nCurrentHighlight = -1; // Now read in the directory structure. m_nSkipToTick = nStartingTick; // reset skip-to-tick, otherwise it remains stale from old skipping if ( nStartingTick != -1 ) { m_nSkipToTick |= SKIP_TO_TICK_FLAG; } GetBaseLocalClient().m_nSignonState= SIGNONSTATE_CONNECTED; ResyncDemoClock(); // create a fake channel with a NULL address (no encryption keys in demos) GetBaseLocalClient().m_NetChannel = NET_CreateNetChannel( NS_CLIENT, NULL, "DEMO", &GetBaseLocalClient(), NULL, false ); if ( !GetBaseLocalClient().m_NetChannel ) { ConMsg ("CDemo::Play: failed to create demo net channel\n" ); m_DemoFile.Close(); GetBaseLocalClient().demonum = -1; // stop demo loop Host_Disconnect(true); return false; } GetBaseLocalClient().m_NetChannel->SetTimeout( -1.0f ); // never timeout V_memset( &m_DemoPacket, 0, sizeof(m_DemoPacket) ); // setup demo packet data buffer m_DemoPacket.data = new unsigned char[ NET_MAX_PAYLOAD ]; m_DemoPacket.from.SetAddrType( NSAT_NETADR ); m_DemoPacket.from.m_adr.SetType( NA_LOOPBACK ); GetBaseLocalClient().chokedcommands = 0; GetBaseLocalClient().lastoutgoingcommand = -1; GetBaseLocalClient().m_flNextCmdTime = net_time; m_bTimeDemo = bAsTimeDemo; m_nTimeDemoCurrentFrame = -1; m_nTimeDemoStartFrame = -1; m_nPacketTick = 0; if ( m_bTimeDemo ) { SeedRandomNumberGenerator( true ); } demoaction->StartPlaying( filename ); // m_bFastForwarding = false; m_flAutoResumeTime = 0.0f; m_flPlaybackRateModifier = 1.0f; demoplayer = this; scr_demo_override_fov = 0.0f; return true; } bool CDemoPlayer::ScanDemo( const char *filename, const char* pszMode ) { m_bScanMode = true; V_strcpy_safe( m_szScanMode, pszMode ); return StartPlayback( filename, false, NULL ); } void CDemoPlayer::RestartPlayback( void ) { if ( m_nRestartFilePos != -1 ) { m_DemoFile.SeekTo( m_nRestartFilePos, true ); ResyncDemoClock(); GetBaseLocalClient().DeleteClientFrames( -1 ); GetBaseLocalClient().SetFrameTime( 0 ); GetBaseLocalClient().chokedcommands = 0; GetBaseLocalClient().lastoutgoingcommand = -1; GetBaseLocalClient().m_flNextCmdTime = net_time; GetBaseLocalClient().events.RemoveAll(); #ifndef DEDICATED S_StopAllSounds( true ); g_ClientDLL->OnDemoPlaybackRestart(); #endif } } //----------------------------------------------------------------------------- // Purpose: // Input : flCurTime - //----------------------------------------------------------------------------- void CDemoPlayer::MarkFrame( float flFPSVariability ) { m_flTotalFPSVariability += flFPSVariability; } void ComputeTimedemoResultsFilename( CFmtStr &fileName, CFmtStr &dateString ) { // Write the results to a CSV file. // If specified on the command-line, write to a specific benchmark path. // Include the GPU name and host computer name for convenient sorting in Explorer. // Compute a date+time string struct tm time; Plat_GetLocalTime( &time ); dateString.sprintf( "%04d_%02d_%02d__%02d_%02d_%02d", time.tm_year+1900, time.tm_mon+1, time.tm_mday, time.tm_hour, time.tm_min, time.tm_sec ); // Compute prettified GPU name MaterialAdapterInfo_t info; materials->GetDisplayAdapterInfo( materials->GetCurrentAdapter(), info ); CUtlString gpuName( info.m_pDriverName ); const char *pVendors[] = { "nvidia", "ati" }; for ( int i = 0; i < ARRAYSIZE( pVendors ); i++ ) { const char *pVendor = V_stristr( gpuName.Get(), pVendors[i] ); if ( pVendor ) { int nVendorLen = V_strlen( pVendors[i] ); if ( pVendor[nVendorLen] == ' ' ) nVendorLen++; CUtlString tail = pVendor + nVendorLen; gpuName.SetLength( pVendor - gpuName.Get() ); gpuName += tail; break; } } // Now replace any non-alphanumerics with an underscore char *pGPUName = gpuName.Get(); for ( int i = 0; i < gpuName.Length(); i++ ) { if ( !V_isalnum( pGPUName[i] ) ) pGPUName[i] = '_'; } // Compute the local computer's name char host[256] = ""; DWORD length = sizeof( host ) - 1; #if !IsGameConsole() if ( gethostname( host, length ) < 0 ) #endif { // Use dateString as a fallback, if we can't get the host name V_strncpy( host, dateString.Access(), length ); } host[ length ] = '\0'; // Get the destination path (default to the gamedir) CUtlString benchmarkPath = CommandLine()->ParmValue( "-benchmark_path" ); if ( benchmarkPath.Length() && !IsOSX() ) // Don't bother on Mac, we can't write to an smb share trivially { benchmarkPath.StripTrailingSlash(); V_FixSlashes( benchmarkPath.Get() ); } else { benchmarkPath = "."; } // Slap it all together fileName.sprintf( "%s%sSourceBench_%s_%s.csv", benchmarkPath.Get(), CORRECT_PATH_SEPARATOR_S, gpuName.Get(), host ); } void CDemoPlayer::WriteTimeDemoResults( void ) { int frames = MAX( 1, ( (host_framecount - m_nTimeDemoStartFrame) - 1 ) ); float time = MAX( 1, ( Sys_FloatTime() - m_flTimeDemoStartTime ) ); float flVariability = m_flTotalFPSVariability / (float)frames; ConMsg( "%i frames %5.3f seconds %5.2f fps (%5.2f ms/f) %5.3f fps variability\n", frames, time, frames/time, 1000*time/frames, flVariability ); // Open the file (write the CSV to a benchmark path, if specified on the command-line, and name after the GPU and host computer) CFmtStr fileName, dateString; ComputeTimedemoResultsFilename( fileName, dateString ); bool bEmptyFile = !g_pFileSystem->FileExists( fileName.Access() ); FileHandle_t fileHandle = g_pFileSystem->Open( fileName.Access(), "a+" ); if ( fileHandle == FILESYSTEM_INVALID_HANDLE ) { Warning( "DEMO: Failed to open %s!\n", fileName.Access() ); return; } bEmptyFile = !g_pFileSystem->Size( fileHandle ); // Write the header line when starting a new file if( bEmptyFile ) { g_pFileSystem->FPrintf( fileHandle, "Benchmark Results\n\n" ); g_pFileSystem->FPrintf( fileHandle, "demofile," ); g_pFileSystem->FPrintf( fileHandle, "frame data csv," ); g_pFileSystem->FPrintf( fileHandle, "fps," ); g_pFileSystem->FPrintf( fileHandle, "fps variability," ); g_pFileSystem->FPrintf( fileHandle, "total sec," ); g_pFileSystem->FPrintf( fileHandle, "avg ms," ); for ( int lp = 0; lp < PERF_STATS_SLOT_MAX; ++lp ) { g_pFileSystem->FPrintf( fileHandle, "%s (avg ms),", g_PerfStats.m_Slots[lp].m_pszName ); } g_pFileSystem->FPrintf( fileHandle, "width," ); g_pFileSystem->FPrintf( fileHandle, "height," ); g_pFileSystem->FPrintf( fileHandle, "msaa," ); g_pFileSystem->FPrintf( fileHandle, "aniso," ); g_pFileSystem->FPrintf( fileHandle, "picmip," ); g_pFileSystem->FPrintf( fileHandle, "numframes," ); g_pFileSystem->FPrintf( fileHandle, "dxlevel," ); g_pFileSystem->FPrintf( fileHandle, "backbuffer," ); g_pFileSystem->FPrintf( fileHandle, "cmdline," ); g_pFileSystem->FPrintf( fileHandle, "driver," ); g_pFileSystem->FPrintf( fileHandle, "vendor id," ); g_pFileSystem->FPrintf( fileHandle, "device id," ); //g_pFileSystem->FPrintf( fileHandle, "subsys id," ); //g_pFileSystem->FPrintf( fileHandle, "revision," ); //g_pFileSystem->FPrintf( fileHandle, "shaderdll," ); g_pFileSystem->FPrintf( fileHandle, "sound," ); g_pFileSystem->FPrintf( fileHandle, "vsync," ); g_pFileSystem->FPrintf( fileHandle, "gpu_level," ); g_pFileSystem->FPrintf( fileHandle, "cpu_level," ); g_pFileSystem->FPrintf( fileHandle, "date," ); g_pFileSystem->FPrintf( fileHandle, "csm enabled," ); g_pFileSystem->FPrintf( fileHandle, "csm quality," ); g_pFileSystem->FPrintf( fileHandle, "fxaa," ); g_pFileSystem->FPrintf( fileHandle, "motionblur," ); g_pFileSystem->FPrintf( fileHandle, "\n" ); } // Append a new line of data static ConVarRef gpu_level( "gpu_level" ); static ConVarRef cpu_level( "cpu_level" ); static ConVarRef mat_vsync( "mat_vsync" ); static ConVarRef mat_antialias( "mat_antialias" ); static ConVarRef mat_forceaniso( "mat_forceaniso" ); static ConVarRef mat_picmip( "mat_picmip" ); static ConVarRef cl_csm_enabled( "cl_csm_enabled" ); static ConVarRef csm_quality_level( "csm_quality_level" ); static ConVarRef mat_software_aa_strength( "mat_software_aa_strength" ); static ConVarRef mat_motion_blur_enabled( "mat_motion_blur_enabled" ); int width, height; MaterialAdapterInfo_t info; CMatRenderContextPtr pRenderContext( materials ); pRenderContext->GetWindowSize( width, height ); ImageFormat backBufferFormat = materials->GetBackBufferFormat(); materials->GetDisplayAdapterInfo( materials->GetCurrentAdapter(), info ); g_pFileSystem->Seek( fileHandle, 0, FILESYSTEM_SEEK_TAIL ); g_pFileSystem->FPrintf( fileHandle, "%s,", m_DemoFile.m_szFileName ); g_pFileSystem->FPrintf( fileHandle, "%s,", g_pStatsFile ); g_pFileSystem->FPrintf( fileHandle, "%5.1f,", frames/time ); g_pFileSystem->FPrintf( fileHandle, "%5.1f,", flVariability ); g_pFileSystem->FPrintf( fileHandle, "%5.1f,", time ); g_pFileSystem->FPrintf( fileHandle, "%5.3f,", 1000*time/frames ); for ( int lp = 0; lp < PERF_STATS_SLOT_MAX; ++lp ) { g_pFileSystem->FPrintf( fileHandle, "%6.3f,", g_PerfStats.m_Slots[lp].m_AccTotalTime.GetMillisecondsF() / g_PerfStats.m_nFrames ); } g_pFileSystem->FPrintf( fileHandle, "%i,", width ); g_pFileSystem->FPrintf( fileHandle, "%i,", height ); g_pFileSystem->FPrintf( fileHandle, "%i,", MAX( 1, mat_antialias.GetInt() ) ); g_pFileSystem->FPrintf( fileHandle, "%i,", mat_forceaniso.GetInt() ); g_pFileSystem->FPrintf( fileHandle, "%i,", mat_picmip.GetInt() ); g_pFileSystem->FPrintf( fileHandle, "%i,", frames ); g_pFileSystem->FPrintf( fileHandle, "%s,", COM_DXLevelToString( g_pMaterialSystemHardwareConfig->GetDXSupportLevel() ) ); g_pFileSystem->FPrintf( fileHandle, "%s,", ImageLoader::GetName( backBufferFormat ) ); g_pFileSystem->FPrintf( fileHandle, "%s,", CommandLine()->GetCmdLine() ); g_pFileSystem->FPrintf( fileHandle, "%s,", info.m_pDriverName ); g_pFileSystem->FPrintf( fileHandle, "0x%x,", info.m_VendorID ); g_pFileSystem->FPrintf( fileHandle, "0x%x,", info.m_DeviceID ); //g_pFileSystem->FPrintf( fileHandle, "0x%x,", info.m_SubSysID ); //g_pFileSystem->FPrintf( fileHandle, "0x%x,", info.m_Revision ); //g_pFileSystem->FPrintf( fileHandle, "%s,", g_pMaterialSystemHardwareConfig->GetShaderDLLName() ); g_pFileSystem->FPrintf( fileHandle, "%s,", CommandLine()->CheckParm( "-nosound" ) ? "disabled" : "enabled" ); g_pFileSystem->FPrintf( fileHandle, "%s,", CommandLine()->CheckParm( "-mat_vsync" ) || mat_vsync.GetBool() ? "enabled" : "disabled" ); g_pFileSystem->FPrintf( fileHandle, "%d,", gpu_level.GetInt() ); g_pFileSystem->FPrintf( fileHandle, "%d,", cpu_level.GetInt() ); g_pFileSystem->FPrintf( fileHandle, "%s,", dateString.Access() ); g_pFileSystem->FPrintf( fileHandle, "%i,", cl_csm_enabled.GetInt() ); g_pFileSystem->FPrintf( fileHandle, "%i,", csm_quality_level.GetInt() ); g_pFileSystem->FPrintf( fileHandle, "%i,", mat_software_aa_strength.GetInt() ); g_pFileSystem->FPrintf( fileHandle, "%i,", mat_motion_blur_enabled.GetInt() ); g_pFileSystem->FPrintf( fileHandle, "\n" ); g_pFileSystem->Close( fileHandle ); } void CDemoPlayer::PausePlayback( float seconds ) { m_bPlaybackPaused = true; if ( seconds > 0.0f ) { // Use true clock since everything else is frozen m_flAutoResumeTime = Sys_FloatTime() + seconds; } else { m_flAutoResumeTime = 0.0f; } } void CDemoPlayer::ResumePlayback() { m_bPlaybackPaused = false; m_flAutoResumeTime = 0.0f; } bool CDemoPlayer::CheckPausedPlayback() { if ( m_bPacketReadSuspended ) return true; // When packet reading is suspended it trumps all other states if ( demo_pauseatservertick.GetInt() > 0 ) { if ( GetBaseLocalClient().GetServerTickCount() >= demo_pauseatservertick.GetInt() ) { PausePlayback( -1 ); m_nSkipToTick = -1; demo_pauseatservertick.SetValue( 0 ); Msg( "Demo paused at server tick %i\n", GetBaseLocalClient().GetServerTickCount() ); } } if ( IsSkipping() ) { if ( ( m_nSkipToTick > GetPlaybackTick() ) || ( ( m_nSkipToTick & SKIP_TO_TICK_FLAG ) == SKIP_TO_TICK_FLAG ) ) { // we are skipping return false; } else { // we can't skip back (or finished skipping), so disable skipping m_nSkipToTick = -1; } } if ( !IsPlaybackPaused() ) return false; if ( m_bPlaybackPaused ) { if ( (m_flAutoResumeTime > 0.0f) && (Sys_FloatTime() >= m_flAutoResumeTime) ) { // it's time to unpause replay ResumePlayback(); } } return m_bPlaybackPaused; } bool CDemoPlayer::IsPlaybackPaused()const { if ( !IsPlayingBack() ) return false; // never pause while reading signon data if ( m_nTimeDemoCurrentFrame < 0 ) return false; // If skipping then do not pretend paused if ( IsSkipping() ) return false; return m_bPlaybackPaused; } int CDemoPlayer::GetPlaybackStartTick( void ) { return m_nStartTick; } int CDemoPlayer::GetPlaybackTick( void ) { return host_tickcount - m_nStartTick; } int CDemoPlayer::GetPlaybackDeltaTick( void ) { return host_tickcount - m_nStartTick; } int CDemoPlayer::GetPacketTick() { return m_nPacketTick; } void CDemoPlayer::ResyncDemoClock() { m_nStartTick = host_tickcount; m_nPreviousTick = m_nStartTick; } float CDemoPlayer::GetPlaybackTimeScale() { return m_flPlaybackRateModifier; } void CDemoPlayer::SetPlaybackTimeScale(float timescale) { m_flPlaybackRateModifier = timescale; } void CDemoPlayer::SetBenchframe( int tick, const char *filename ) { m_nSnapshotTick = tick; if ( filename ) { V_strcpy_safe( m_SnapshotFilename, filename ); } } void CDemoPlayer::SetImportantEventData( const KeyValues *pData ) { m_pImportantEventData = pData->MakeCopy(); } void CDemoPlayer::GetImportantGameEventIDs() { if ( m_ImportantGameEvents.Count() == 0 ) { KeyValues *pCurrentEvent = m_pImportantEventData->GetFirstSubKey(); while( pCurrentEvent != NULL ) { const char *pEventName = pCurrentEvent->GetName(); CGameEventDescriptor *descriptor = g_GameEventManager.GetEventDescriptor( pEventName ); if ( descriptor ) { DemoImportantGameEvent_t event; event.nEventID = descriptor->eventid; event.pszEventName = pEventName; event.pszUIName = pCurrentEvent->GetString( "uiname" ); event.flSeekTimeBefore = pCurrentEvent->GetFloat( "seek_time_before", 0.0f ); event.flSeekForwardOffset = pCurrentEvent->GetFloat( "seek_back_offset", 0.0f ); event.flSeekBackwardOffset = pCurrentEvent->GetFloat( "seek_forward_offset", 0.0f ); event.bScanOnly = pCurrentEvent->GetBool( "scanonly" ); m_ImportantGameEvents.AddToTail( event ); } else { Msg( "GetImportantGameEventIDs: Couldn't get descriptor for %s\n", pEventName ); } pCurrentEvent = pCurrentEvent->GetNextKey(); } } } void CDemoPlayer::SetHighlightXuid( uint64 xuid, bool bLowlights ) { m_highlightSteamID.SetFromUint64( xuid ); if ( xuid != 0 ) { m_bDoHighlightScan = true; m_bLowlightsMode = bLowlights; } g_ClientDLL->SetDemoPlaybackHighlightXuid( xuid, bLowlights ); } void ParseEventKeys( CSVCMsg_GameEvent_t *msg, CGameEventDescriptor *pDescriptor, const char *pszEventName, KeyValues **ppKeys ) { int nKeyCount = msg->keys().size(); if ( nKeyCount > 0 ) { // build proper key values from descriptor plus message keys *ppKeys = new KeyValues( pszEventName ); if ( *ppKeys ) { KeyValues *pDescriptorKey = pDescriptor->keys->GetFirstSubKey(); for( int nKey = 0; nKey < nKeyCount; nKey++ ) { const CSVCMsg_GameEvent::key_t& KeyValue = msg->keys( nKey ); if( KeyValue.has_val_string() ) { (*ppKeys)->SetString( pDescriptorKey->GetName(), KeyValue.val_string().c_str() ); } else if( KeyValue.has_val_float() ) { (*ppKeys)->SetFloat( pDescriptorKey->GetName(), KeyValue.val_float() ); } else if( KeyValue.has_val_long() ) { (*ppKeys)->SetInt( pDescriptorKey->GetName(), KeyValue.val_long() ); } else if( KeyValue.has_val_short() ) { (*ppKeys)->SetInt( pDescriptorKey->GetName(), KeyValue.val_short() ); } else if( KeyValue.has_val_byte() ) { (*ppKeys)->SetInt( pDescriptorKey->GetName(), KeyValue.val_byte() ); } else if( KeyValue.has_val_bool() ) { (*ppKeys)->SetBool( pDescriptorKey->GetName(), KeyValue.val_bool() ); } else if( KeyValue.has_val_uint64() ) { (*ppKeys)->SetUint64( pDescriptorKey->GetName(), KeyValue.val_uint64() ); } pDescriptorKey = pDescriptorKey->GetNextKey(); } } } else { (*ppKeys) = NULL; } } void CDemoPlayer::ScanForImportantTicks() { if ( m_ImportantTicks.Count() > 0 || m_ImportantGameEvents.Count() == 0 ) return; s_demoUserInfo.RemoveAll(); // setup a string table for use while scanning CNetworkStringTableContainer demoScanStringTables; demoScanStringTables.AllowCreation( true ); int numTables = networkStringTableContainerClient->GetNumTables(); for ( int i =0; i<numTables; i++) { // iterate through server tables CNetworkStringTable *serverTable = (CNetworkStringTable*)networkStringTableContainerClient->GetTable( i ); if ( !serverTable ) continue; // get matching client table CNetworkStringTable *demoTable = (CNetworkStringTable*)demoScanStringTables.CreateStringTable( serverTable->GetTableName(), serverTable->GetMaxStrings(), serverTable->GetUserDataSize(), serverTable->GetUserDataSizeBits(), serverTable->IsUsingDictionary() ? NSF_DICTIONARY_ENABLED : NSF_NONE ); if ( !demoTable ) { DevMsg("CDemoPlayer::ScanForImportantTicks: failed to create table \"%s\".\n ", serverTable->GetTableName() ); continue; } if ( V_strcasecmp( demoTable->GetTableName(), USER_INFO_TABLENAME ) == 0 ) { demoTable->SetStringChangedCallback( NULL, Callback_DemoScanUserInfoChanged ); } // make demo scan table an exact copy of server table demoTable->CopyStringTable( serverTable ); } demoScanStringTables.AllowCreation( false ); m_nHighlightPlayerIndex = GetPlayerIndex( m_highlightSteamID ); democmdinfo_t info; int dummy; char buf[ NET_MAX_PAYLOAD ]; long starting_position = m_DemoFile.GetCurPos( true ); m_DemoFile.SeekTo( 0, true ); // Read in the m_DemoHeader demoheader_t *dh = m_DemoFile.ReadDemoHeader( m_pPlaybackParameters ); if ( !dh ) { ConMsg( "Failed to read demo header while scanning for important ticks.\n" ); m_DemoFile.SeekTo( starting_position, true ); return; } int previousTick = 0, nDemoPackets = 0; bool demofinished = false; while ( !demofinished ) { int tick = 0; byte cmd; bool swallowmessages = true; do { int nPlayerSlot = 0; m_DemoFile.ReadCmdHeader( cmd, tick, nPlayerSlot ); // COMMAND HANDLERS switch ( cmd ) { case dem_synctick: break; case dem_stop: { swallowmessages = false; demofinished = true; } break; case dem_consolecmd: { ACTIVE_SPLITSCREEN_PLAYER_GUARD( nPlayerSlot ); m_DemoFile.ReadConsoleCommand(); } break; case dem_datatables: { m_DemoFile.ReadNetworkDataTables( NULL ); } break; case dem_stringtables: { void *data = malloc( DEMO_RECORD_BUFFER_SIZE ); bf_read buf( "dem_stringtables", data, DEMO_RECORD_BUFFER_SIZE ); m_DemoFile.ReadStringTables( &buf ); buf.Seek( 0 ); if ( !demoScanStringTables.ReadStringTables( buf ) ) { Host_Error( "Error parsing string tables during demo scan." ); } free( data ); } break; case dem_usercmd: { ACTIVE_SPLITSCREEN_PLAYER_GUARD( nPlayerSlot ); m_DemoFile.ReadUserCmd( NULL, dummy ); } break; case dem_packet: nDemoPackets++; // fall through default: { swallowmessages = false; } break; } } while ( swallowmessages ); if ( demofinished ) { break; } m_DemoFile.ReadCmdInfo( info ); m_DemoFile.ReadSequenceInfo( dummy, dummy ); int length = m_DemoFile.ReadRawData( buf, NET_MAX_PAYLOAD ); if ( length > 0 ) { bf_read message; message.StartReading( buf, length ); CNetChan *pNetChannel = ( CNetChan * ) GetBaseLocalClient().m_NetChannel; while ( true ) { if ( message.IsOverflowed() ) { Msg( "Packet message is overflowed while scanning for important ticks!\n" ); break; } // Are we at the end? if ( message.GetNumBitsLeft() < 8 ) // Minimum bits for message header encoded using VarInt32 { break; } // see if we have a registered message object for this type unsigned char cmd = message.ReadVarInt32(); INetMessageBinder *pMsgBind = pNetChannel->FindMessageBinder( cmd, 0 ); if ( pMsgBind ) { INetMessage *netmsg = pMsgBind->CreateFromBuffer( message ); if ( netmsg && netmsg->GetType() == svc_GameEvent ) // only care about game events { CSVCMsg_GameEvent_t *msg = static_cast< CSVCMsg_GameEvent_t * >( netmsg ); CGameEventDescriptor *pDescriptor = g_GameEventManager.GetEventDescriptor( msg->eventid() ); for ( int nEvent = 0; nEvent < m_ImportantGameEvents.Count(); nEvent++ ) { if ( msg->eventid() == m_ImportantGameEvents[ nEvent ].nEventID ) { DemoImportantTick_t importantTick; importantTick.nTick = tick; importantTick.nPreviousTick = previousTick; importantTick.nImportanGameEventIndex = nEvent; importantTick.bCanDirectSeek = false; importantTick.pKeys = NULL; bool bIgnore = false; ParseEventKeys( msg, pDescriptor, m_ImportantGameEvents[ nEvent ].pszEventName, &importantTick.pKeys ); if ( !m_ImportantGameEvents[ nEvent ].bScanOnly ) { if ( V_strcasecmp( m_ImportantGameEvents[ nEvent ].pszEventName, "player_death" ) == 0 ) { GetExtraDeathEventInfo( importantTick.pKeys ); } else if ( V_strcasecmp( m_ImportantGameEvents[ nEvent ].pszEventName, "bomb_defused" ) == 0 || V_strcasecmp( m_ImportantGameEvents[ nEvent ].pszEventName, "bomb_planted" ) == 0 ) { if ( m_bLowlightsMode ) bIgnore = true; else GetExtraEventInfo( importantTick.pKeys ); } if ( !bIgnore ) m_ImportantTicks.AddToTail( importantTick ); } else { if ( m_bScanMode && V_strcasecmp( m_ImportantGameEvents[nEvent].pszEventName, m_szScanMode ) == 0 ) { GetEventInfoForScan( m_szScanMode, importantTick.pKeys ); } importantTick.pKeys->deleteThis(); // cleanup keys since we aren't saving this tick } break; } } } else if ( netmsg && netmsg->GetType() == svc_UpdateStringTable ) { CSVCMsg_UpdateStringTable_t *msg = static_cast< CSVCMsg_UpdateStringTable_t * >( netmsg ); CNetworkStringTable *table = (CNetworkStringTable*) demoScanStringTables.GetTable( msg->table_id() ); bf_read data( &msg->string_data()[0], msg->string_data().size() ); table->ParseUpdate( data, msg->num_changed_entries() ); } delete netmsg; } } } previousTick = tick; } demoScanStringTables.RemoveAllTables(); m_DemoFile.SeekTo( starting_position, true ); if ( m_DemoFile.m_DemoHeader.playback_time == 0.0f && m_DemoFile.m_DemoHeader.playback_ticks == 0 && m_DemoFile.m_DemoHeader.playback_frames == 0 ) { // this is a corrupt/incomplete file if ( !demo_strict_validation.GetInt() && previousTick > 1 && nDemoPackets > 1 ) { m_DemoFile.m_DemoHeader.playback_ticks = previousTick; if ( m_nTickToPauseOn == -1 ) { m_nTickToPauseOn = previousTick; } m_DemoFile.m_DemoHeader.playback_frames = nDemoPackets - 1; m_DemoFile.m_DemoHeader.playback_time = previousTick * host_state.interval_per_tick; // and we are allowed to "heal" it Msg( "Attempting to heal incomplete demo file: assuming %d ticks, %d frames, %.2f seconds @%.0fHz\n", m_DemoFile.m_DemoHeader.playback_ticks, m_DemoFile.m_DemoHeader.playback_frames, m_DemoFile.m_DemoHeader.playback_time, 1.0f / host_state.interval_per_tick ); } } } void CDemoPlayer::BuildHighlightList() { if ( m_bDoHighlightScan && m_highlightSteamID.ConvertToUint64() != 0 ) { m_highlights.RemoveAll(); DemoHighlightEntry_t entry; int nTicksAfterEvent = demo_highlight_timeafter.GetFloat() / host_state.interval_per_tick; int nTicksBeforeEvent = demo_highlight_timebefore.GetFloat() / host_state.interval_per_tick; const char *szKeyToCheck = m_bLowlightsMode ? "victim_xuid" : "attacker_xuid"; int nImportantTickIndex = FindNextImportantTickByXuid( 0, m_highlightSteamID ); while ( nImportantTickIndex != -1 ) { if ( CheckKeyXuid( m_highlightSteamID, m_ImportantTicks[ nImportantTickIndex ].pKeys, szKeyToCheck ) || CheckKeyXuid( m_highlightSteamID, m_ImportantTicks[ nImportantTickIndex ].pKeys, "player_xuid" ) ) { entry.nSeekToTick = entry.nFastForwardToTick = Max( m_ImportantTicks[ nImportantTickIndex ].nPreviousTick - nTicksBeforeEvent, 0 ); // no need to play before the beginning of the stream entry.nPlayToTick = m_ImportantTicks[ nImportantTickIndex ].nTick + nTicksAfterEvent; entry.nActualFirstEventTick = entry.nActualLastEventTick = m_ImportantTicks[ nImportantTickIndex ].nTick; entry.nNumEvents = 1; if ( m_bLowlightsMode ) { CSteamID attackerSteamID( m_ImportantTicks[ nImportantTickIndex ].pKeys->GetUint64( "attacker_xuid" ) ); entry.unAccountID = attackerSteamID.GetAccountID(); } else { entry.unAccountID = m_highlightSteamID.GetAccountID(); } // check if next event is close enough to this one to just include in this highlight entry int nNextImportantTickIndex = FindNextImportantTickByXuid( m_ImportantTicks[ nImportantTickIndex ].nTick + 1, m_highlightSteamID ); while ( nNextImportantTickIndex != -1 ) { if ( CheckKeyXuid( m_highlightSteamID, m_ImportantTicks[ nNextImportantTickIndex ].pKeys, szKeyToCheck ) || CheckKeyXuid( m_highlightSteamID, m_ImportantTicks[ nNextImportantTickIndex ].pKeys, "player_xuid" ) ) { if ( m_ImportantTicks[ nNextImportantTickIndex ].nPreviousTick - nTicksBeforeEvent <= entry.nPlayToTick ) { entry.nPlayToTick = m_ImportantTicks[ nNextImportantTickIndex ].nTick + nTicksAfterEvent; entry.nActualLastEventTick = m_ImportantTicks[ nNextImportantTickIndex ].nTick; entry.nNumEvents++; nImportantTickIndex = nNextImportantTickIndex; } else { break; } } nNextImportantTickIndex = FindNextImportantTickByXuid( m_ImportantTicks[ nNextImportantTickIndex ].nTick + 1, m_highlightSteamID ); } m_highlights.AddToTail( entry ); } nImportantTickIndex = FindNextImportantTickByXuid( m_ImportantTicks[ nImportantTickIndex ].nTick + 1, m_highlightSteamID ); } // when we cross a round start between highlights, we include the round start in the highlight // the playback will fast forward from the round start until nearby the highlight if ( 0 ) for ( int i = 1; i < m_highlights.Count(); i++ ) { int nTicksSkipToRoundThreshold = demo_highlight_skipthreshold.GetFloat() / host_state.interval_per_tick; int nRoundTick = FindPreviousImportantTick( m_highlights[ i ].nFastForwardToTick, "round_start" ); if ( nRoundTick != -1 && ( m_ImportantTicks[ nRoundTick ].nTick - m_highlights[ i - 1 ].nPlayToTick ) > nTicksSkipToRoundThreshold ) { m_highlights[ i ].nSeekToTick = m_ImportantTicks[ nRoundTick ].nPreviousTick; } } if ( m_highlights.Count() > 0 ) { // add on a seek to the end of the match and play from their to the end of the demo, this will show the scoreboard int nEndMatchTickIndex = demoplayer->FindPreviousImportantTick( m_DemoFile.m_DemoHeader.playback_ticks, "announce_phase_end" ); if ( nEndMatchTickIndex != -1 ) { int nTicksBeforeMatchEnd = 1.0f / host_state.interval_per_tick; entry.nSeekToTick = m_ImportantTicks[ nEndMatchTickIndex ].nPreviousTick - nTicksBeforeMatchEnd; entry.nFastForwardToTick = m_ImportantTicks[ nEndMatchTickIndex ].nPreviousTick - nTicksBeforeMatchEnd; entry.nPlayToTick = m_ImportantTicks[ nEndMatchTickIndex ].nTick; entry.nActualFirstEventTick = entry.nActualLastEventTick = m_ImportantTicks[ nEndMatchTickIndex ].nTick; entry.nNumEvents = 0; entry.unAccountID = m_highlightSteamID.GetAccountID(); m_highlights.AddToTail( entry ); } m_nCurrentHighlight = 0; } else { // didn't find any highlights, so kill the parameters so the demo will play normally m_pPlaybackParameters = NULL; } m_bDoHighlightScan = false; } } int CDemoPlayer::FindNextImportantTick( int nCurrentTick, const char *pEventName /* = NULL */ ) { FOR_EACH_VEC( m_ImportantTicks, i ) { if ( m_ImportantTicks[ i ].nTick > nCurrentTick ) { if ( pEventName == NULL || V_stricmp( m_ImportantGameEvents[ m_ImportantTicks[ i ].nImportanGameEventIndex ].pszEventName, pEventName ) == 0 ) { return i; } } } return -1; } int CDemoPlayer::FindPreviousImportantTick( int nCurrentTick, const char *pEventName /* = NULL */ ) { FOR_EACH_VEC_BACK( m_ImportantTicks, i ) { if ( m_ImportantTicks[ i ].nTick < nCurrentTick ) { if ( pEventName == NULL || V_stricmp( m_ImportantGameEvents[ m_ImportantTicks[ i ].nImportanGameEventIndex ].pszEventName, pEventName ) == 0 ) { return i; } } } return -1; } int CDemoPlayer::FindNextImportantTickByXuidAndEvent( int nCurrentTick, const CSteamID &steamID, const char *pKeyWithXuid, const char *pEventName /* = NULL */ ) { FOR_EACH_VEC( m_ImportantTicks, i ) { if ( m_ImportantTicks[ i ].nTick > nCurrentTick ) { CSteamID compareSteamID( m_ImportantTicks[ i ].pKeys->GetUint64( pKeyWithXuid ) ); if ( ( steamID.GetAccountID() == compareSteamID.GetAccountID() ) && ( pEventName == NULL || V_stricmp( m_ImportantGameEvents[ m_ImportantTicks[ i ].nImportanGameEventIndex ].pszEventName, pEventName ) == 0 ) ) { return i; } } } return -1; } int CDemoPlayer::FindNextImportantTickByXuid( int nCurrentTick, const CSteamID &steamID ) { FOR_EACH_VEC( m_ImportantTicks, i ) { if ( m_ImportantTicks[ i ].nTick > nCurrentTick ) { CSteamID playerSteamID( m_ImportantTicks[ i ].pKeys->GetUint64( "player_xuid" ) ); if ( steamID.GetAccountID() == playerSteamID.GetAccountID() ) { return i; } CSteamID attackerSteamID( m_ImportantTicks[ i ].pKeys->GetUint64( "attacker_xuid" ) ); if ( steamID.GetAccountID() == attackerSteamID.GetAccountID() ) { return i; } CSteamID victimSteamID( m_ImportantTicks[ i ].pKeys->GetUint64( "victim_xuid" ) ); if ( steamID.GetAccountID() == victimSteamID.GetAccountID() ) { return i; } } } return -1; } int CDemoPlayer::FindPreviousImportantTickByXuidAndEvent( int nCurrentTick, const CSteamID &steamID, const char *pKeyWithXuid, const char *pEventName /* = NULL */ ) { FOR_EACH_VEC_BACK( m_ImportantTicks, i ) { if ( m_ImportantTicks[ i ].nTick < nCurrentTick ) { CSteamID compareSteamID( m_ImportantTicks[ i ].pKeys->GetUint64( pKeyWithXuid ) ); if ( ( steamID.GetAccountID() == compareSteamID.GetAccountID() ) && ( pEventName == NULL || V_stricmp( m_ImportantGameEvents[ m_ImportantTicks[ i ].nImportanGameEventIndex ].pszEventName, pEventName ) == 0 ) ) { return i; } } } return -1; } const DemoImportantTick_t *CDemoPlayer::GetImportantTick( int nIndex ) { if ( m_ImportantTicks.IsValidIndex( nIndex ) ) { return &m_ImportantTicks[ nIndex ]; } return NULL; } const DemoImportantGameEvent_t *CDemoPlayer::GetImportantGameEvent( const char *pszEventName ) { FOR_EACH_VEC( m_ImportantGameEvents, i ) { if ( V_strcasecmp( m_ImportantGameEvents[ i ].pszEventName, pszEventName ) == 0 ) { return &m_ImportantGameEvents[ i ]; } } return NULL; } void CDemoPlayer::ListImportantTicks() { Msg( "Important Ticks in demo:\n" ); FOR_EACH_VEC( m_ImportantTicks, i ) { if ( V_strcasecmp( m_ImportantGameEvents[ m_ImportantTicks[ i ].nImportanGameEventIndex ].pszEventName, "player_death" ) == 0 ) { if ( m_ImportantTicks[ i ].pKeys->GetBool( "headshot" ) ) { Msg( "Tick: %d : %s killed %s with a headshot using a %s\n", m_ImportantTicks[ i ].nTick, m_ImportantTicks[ i ].pKeys->GetString( "attacker_name" ), m_ImportantTicks[ i ].pKeys->GetString( "victim_name" ), m_ImportantTicks[ i ].pKeys->GetString( "weapon" ) ); } else { Msg( "Tick: %d : %s killed %s using a %s\n", m_ImportantTicks[ i ].nTick, m_ImportantTicks[ i ].pKeys->GetString( "attacker_name" ), m_ImportantTicks[ i ].pKeys->GetString( "victim_name" ), m_ImportantTicks[ i ].pKeys->GetString( "weapon" ) ); } } else { Msg( "Tick: %d Event: %s \n", m_ImportantTicks[ i ].nTick, m_ImportantGameEvents[ m_ImportantTicks[ i ].nImportanGameEventIndex ].pszEventName ); } } } void CDemoPlayer::ListHighlightData() { if ( m_highlights.Count() > 0 ) { Msg( "Highlights in demo:\n" ); FOR_EACH_VEC( m_highlights, i ) { Msg( "highlight: %d >> %d -> %d (%d) (%d,%d)\n", m_highlights[ i ].nSeekToTick, m_highlights[ i ].nFastForwardToTick, m_highlights[ i ].nPlayToTick, m_highlights[ i ].nNumEvents, m_highlights[ i ].nActualFirstEventTick, m_highlights[ i ].nActualLastEventTick ); } } else { Msg( "No Highlights.\n" ); } } static bool ComputeNextIncrementalDemoFilename( char *name, int namesize ) { FileHandle_t test; test = g_pFileSystem->Open( name, "rb" ); if ( FILESYSTEM_INVALID_HANDLE == test ) { // file doesn't exist, so we can use that return true; } g_pFileSystem->Close( test ); char basename[ MAX_OSPATH ]; V_StripExtension( name, basename, sizeof( basename ) ); // Start looking for a valid name int i = 0; for ( i = 0; i < 1000; i++ ) { char newname[ MAX_OSPATH ]; V_sprintf_safe( newname, "%s%03i.dem", basename, i ); test = g_pFileSystem->Open( newname, "rb" ); if ( FILESYSTEM_INVALID_HANDLE == test ) { V_strncpy( name, newname, namesize ); return true; } g_pFileSystem->Close( test ); } ConMsg( "Unable to find a valid incremental demo filename for %s, try clearing the directory of %snnn.dem\n", name, basename ); return false; } //----------------------------------------------------------------------------- // Purpose: List the contents of a demo file. //----------------------------------------------------------------------------- void CL_ListDemo_f( const CCommand &args ) { // Find the file char name[MAX_OSPATH]; V_sprintf_safe(name, "%s", args[1]); V_DefaultExtension( name, ".dem", sizeof( name ) ); ConMsg ("Demo contents for %s:\n", name); CDemoFile demofile; if ( !demofile.Open( name, true ) ) { ConMsg ("ERROR: couldn't open.\n"); return; } demofile.ReadDemoHeader( NULL ); demoheader_t *header = &demofile.m_DemoHeader; if ( !header ) { ConMsg( "Failed reading demo header.\n" ); demofile.Close(); return; } if ( V_strcmp( header->demofilestamp, DEMO_HEADER_ID ) ) { ConMsg( "%s is not a valid demo file\n", name); return; } ConMsg("Network protocol: %i\n", header->networkprotocol); ConMsg("Demo version : %i\n", header->demoprotocol); ConMsg("Server name : %s\n", header->servername); ConMsg("Map name : %s\n", header->mapname); ConMsg("Game : %s\n", header->gamedirectory); ConMsg("Player name : %s\n", header->clientname); ConMsg("Time : %.1f\n", header->playback_time); ConMsg("Ticks : %i\n", header->playback_ticks); ConMsg("Frames : %i\n", header->playback_frames); ConMsg("Signon size : %i\n", header->signonlength); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CON_COMMAND( stop, "Finish recording demo." ) { if ( !demorecorder->IsRecording() ) { ConDMsg ("Not recording a demo.\n"); return; } char name[ MAX_OSPATH ] = "Cannot stop recording now"; if ( !g_ClientDLL->CanStopRecordDemo( name, sizeof( name ) ) ) { ConMsg( "%s\n", name ); // re-use name as the error string if the client prevents us from stopping the demo return; } demorecorder->StopRecording(); // Notify the client g_ClientDLL->OnDemoRecordStop(); } static void DemoRecord( char const *pchDemoFileName, bool incremental ) { if ( g_ClientDLL == NULL ) { ConMsg( "Can't record on dedicated server.\n" ); return; } if ( demorecorder->IsRecording() ) { ConMsg ("Already recording.\n"); return; } if ( demoplayer->IsPlayingBack() ) { ConMsg ("Can't record during demo playback.\n"); return; } // check path first if ( !COM_IsValidPath( pchDemoFileName ) ) { ConMsg( "record %s: invalid path.\n", pchDemoFileName ); return; } char name[ MAX_OSPATH ] = "Cannot record now"; if ( !g_ClientDLL->CanRecordDemo( name, sizeof( name ) ) ) { ConMsg( "%s\n", name ); // re-use name as the error string if the client prevents us from starting a demo return; } // remove .dem extentsion if user added it V_StripExtension( pchDemoFileName, name, sizeof( name ) ); if ( incremental ) { // If file exists, construct a better name if ( !ComputeNextIncrementalDemoFilename( name, sizeof( name ) ) ) { return; } } // Notify polisher of record g_ClientDLL->OnDemoRecordStart( name ); // Record it demorecorder->StartRecording( name, incremental ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CON_COMMAND_F( record, "Record a demo.", FCVAR_DONTRECORD ) { if ( args.ArgC() != 2 && args.ArgC() != 3 ) { ConMsg ("record <demoname> [incremental]\n"); return; } bool incremental = false; if ( args.ArgC() == 3 ) { if ( !V_stricmp( args[2], "incremental" ) ) { incremental = true; } } DemoRecord( args[ 1 ], incremental ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CON_COMMAND_F( _record, "Record a demo incrementally.", FCVAR_DONTRECORD ) { if ( g_ClientDLL == NULL ) { ConMsg ("Can't record on dedicated server.\n"); return; } if ( args.ArgC() != 2 ) { ConMsg ("_record <demoname>\n"); return; } DemoRecord( args[ 1 ], true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- static CDemoPlaybackParameters_t s_DemoPlaybackParams; // make sure these parameters are available throughout demo playback void SetPlaybackParametersLockFirstPersonAccountID( uint32 nAccountID ) { s_DemoPlaybackParams.m_uiLockFirstPersonAccountID = nAccountID; } void CL_PlayDemo_f( const CCommand &passed_args ) { demoplayer->StopPlayback(); // disconnect before loading demo, to avoid sometimes loading into game instead of demo GetBaseLocalClient().Disconnect( false ); // need to re-tokenize the args without the default breakset // the default splits out and of {}(): into separate args along with splitting on spaces // that makes it impossible to rebuild a file path that has a mixture of those characters in them characterset_t breakset; CharacterSetBuild( &breakset, "" ); CCommand args; args.Tokenize( passed_args.GetCommandString(), passed_args.Source(), &breakset ); if ( args.ArgC() < 2 ) { ConMsg ("playdemo <demoname> <steamid>: plays a demo file. If steamid is given, then play highlights of that player \n"); return; } if ( !net_time && !NET_IsMultiplayer() ) { ConMsg( "Deferring playdemo command!\n" ); return; } int nEndNameArg = args.ArgC() - 1; int nStartRound = 0; const char *szCurArg = args[ nEndNameArg ]; const char *szStartRoundPrefix = "startround:"; if ( char* szStartRoundParam = V_strstr( szCurArg, szStartRoundPrefix ) ) { szStartRoundParam += strlen( szStartRoundPrefix ); nStartRound = V_atoi( szStartRoundParam ); nEndNameArg--; } // first check if last arg is "lowlights" and set flag bool bLowlights = false; if ( V_stricmp( args[ nEndNameArg ], "lowlights" ) == 0 ) { bLowlights = true; nEndNameArg--; } // then check the last (or next to last if last was lowlights) to get the steam ID // steam IDs are numbers only, we just check for digits in all of it int nSteamIDArg = nEndNameArg; bool bSteamID_self = !V_strcmp( args[ nSteamIDArg ], "self" ); if ( bSteamID_self ) { nEndNameArg--; } else { for ( int i = 0; i < V_strlen( args[ nSteamIDArg ] ); i++ ) { if ( !V_isdigit( args[ nSteamIDArg ][ 0 ] ) ) { nSteamIDArg = -1; break; } } if ( nSteamIDArg != -1 ) { nEndNameArg--; } else if ( bLowlights ) { ConMsg( "Warning: lowlights argument given without valid steam id, ignoring.\n" ); bLowlights = false; } } // now take all remaining args and build them back into a path (will be multiple args if it has spaces or contains a ':' char name[ MAX_OSPATH ]; if ( nEndNameArg > 1 ) { V_strcpy_safe( name, args[ 1 ] ); for ( int i = 2; i <= nEndNameArg; i++ ) { V_strcat_safe( name, " " ); V_strcat_safe( name, args[ i ] ); } } else { V_strcpy_safe( name, args[ 1 ] ); } // see if there is a starting tick attached to the filename (filename@####) int nStartingTick = -1; char *pTemp = V_strstr( name, "@" ); if ( pTemp != NULL ) { Assert( nStartRound == 0 ); // Don't specify both of these, start round will stomp nStartingTick = V_atoi(&pTemp[ 1 ]); if ( nStartingTick <= 0 ) { nStartingTick = -1; } pTemp[0] = 0; } // set current demo player to client demo player demoplayer = g_pClientDemoPlayer; if ( demoplayer->IsPlayingBack() ) { demoplayer->StopPlayback(); } // disconnect before loading demo, to avoid sometimes loading into game instead of demo GetBaseLocalClient().Disconnect( false ); CDemoPlaybackParameters_t *pParams = NULL; if ( nSteamIDArg != -1 ) { CSteamID steamID; if ( bSteamID_self ) { if ( ISteamUser* pSteamUser = Steam3Client().SteamUser() ) { steamID = pSteamUser->GetSteamID(); } else { ConMsg( "Cannot obtain user id\n" ); return; } } else { steamID = CSteamID( args[ nSteamIDArg ] ); } demoplayer->SetHighlightXuid( steamID.ConvertToUint64(), bLowlights ); V_memset( &s_DemoPlaybackParams, 0, sizeof( s_DemoPlaybackParams ) ); s_DemoPlaybackParams.m_uiHeaderPrefixLength = 0; s_DemoPlaybackParams.m_bAnonymousPlayerIdentity = false; s_DemoPlaybackParams.m_uiLockFirstPersonAccountID = steamID.GetAccountID(); s_DemoPlaybackParams.m_numRoundSkip = 0; s_DemoPlaybackParams.m_numRoundStop = 999; s_DemoPlaybackParams.m_bSkipWarmup = false; pParams = &s_DemoPlaybackParams; } else if ( nStartRound > 0 ) { s_DemoPlaybackParams.m_uiHeaderPrefixLength = 0; s_DemoPlaybackParams.m_bAnonymousPlayerIdentity = false; s_DemoPlaybackParams.m_uiLockFirstPersonAccountID = 0; s_DemoPlaybackParams.m_numRoundSkip = nStartRound - 1; s_DemoPlaybackParams.m_numRoundStop = 999; s_DemoPlaybackParams.m_bSkipWarmup = true; pParams = &s_DemoPlaybackParams; demoplayer->SetHighlightXuid( 0, false ); } else { demoplayer->SetHighlightXuid( 0, false ); } // // open the demo file // V_DefaultExtension( name, ".dem", sizeof( name ) ); if ( demoplayer != g_pClientDemoPlayer ) { demoplayer->StopPlayback(); demoplayer = g_pClientDemoPlayer; } if ( g_pClientDemoPlayer->StartPlayback( name, false, pParams, nStartingTick ) ) { // Remove extension char basename[ MAX_OSPATH ]; V_StripExtension( name, basename, sizeof( basename ) ); g_ClientDLL->OnDemoPlaybackStart( basename ); } else { SCR_EndLoadingPlaque(); } } void CL_ScanDemo_f(const CCommand &args) { if (args.ArgC() < 2) { ConMsg("scandemo <demoname>: scans a demo file.\n"); return; } // set current demo player to client demo player demoplayer = g_pClientDemoPlayer; if (demoplayer->IsPlayingBack()) { demoplayer->StopPlayback(); } // disconnect before loading demo, to avoid sometimes loading into game instead of demo GetBaseLocalClient().Disconnect(false); demoplayer->SetHighlightXuid( 0, false ); // // open the demo file // char name[MAX_OSPATH]; V_strcpy_safe( name, args[ 1 ] ); V_DefaultExtension( name, ".dem", sizeof( name ) ); s_nMaxViewers = 0; s_nMaxExternalTotal = 0; s_nMaxExternalLinked = 0; s_nMaxCombinedViewers = 0; if ( demoplayer->ScanDemo( name, "hltv_status" ) ) { // Remove extension char basename[ MAX_OSPATH ]; V_StripExtension( name, basename, sizeof( basename ) ); g_ClientDLL->OnDemoPlaybackStart( basename ); } else { SCR_EndLoadingPlaque(); } } void CL_ScanDemoDone( const char *pszMode ) { if ( V_strcasecmp( pszMode, "hltv_status" ) == 0 ) { Msg( "Max GOTV Viewers: %d Max External Viewers: %d Max External Linked: %d Max Combined Viewers: %d \n", s_nMaxViewers, s_nMaxExternalTotal, s_nMaxExternalLinked, s_nMaxCombinedViewers ); } demoplayer->StopPlayback(); GetBaseLocalClient().Disconnect( false ); } void CL_PlayOverwatchEvidence_f( const CCommand &args ) { if ( args.ArgC() != 3 ) { DevMsg( "playoverwatchevidence syntax error.\n" ); return; } // // Validate the header // char const *szCaseKey = args[1]; char name[ MAX_OSPATH ]; V_strcpy_safe( name, args[2] ); if ( !g_pFullFileSystem->FileExists( name ) ) { DevMsg( "playoverwatchevidence no file.\n" ); return; } CUtlBuffer bufHeader; if ( !g_pFullFileSystem->ReadFile( name, NULL, bufHeader, 128 ) ) { DevMsg( "playoverwatchevidence read file error.\n" ); return; } if ( bufHeader.TellMaxPut() != 128 ) { DevMsg( "playoverwatchevidence header of invalid size.\n" ); return; } static CDemoPlaybackParameters_t params; // make sure these parameters are available throughout demo playback V_memset( &params, 0, sizeof( params ) ); params.m_uiHeaderPrefixLength = 128; if ( !g_ClientDLL->ValidateSignedEvidenceHeader( szCaseKey, bufHeader.Base(), &params ) ) return; // set current demo player to client demo player demoplayer = g_pClientDemoPlayer; // // open the demo file // if ( g_pClientDemoPlayer->StartPlayback( name, false, &params ) ) { // Remove extension char basename[ MAX_OSPATH ]; V_StripExtension( name, basename, sizeof( basename ) ); g_ClientDLL->OnDemoPlaybackStart( basename ); } else { SCR_EndLoadingPlaque(); } } void CL_TimeDemo_Helper( const char *pDemoName, const char *pStatsFileName, const char *pVProfStatsFileName ) { V_strncpy( g_pStatsFile, pStatsFileName ? pStatsFileName : "UNKNOWN", sizeof( g_pStatsFile ) ); // set current demo player to client demo player demoplayer = g_pClientDemoPlayer; // open the demo file char name[ MAX_OSPATH ]; V_strcpy_safe(name, pDemoName ); V_DefaultExtension( name, ".dem", sizeof( name ) ); if( pVProfStatsFileName ) { g_EngineStats.EnableVProfStatsRecording( pVProfStatsFileName ); } if ( !g_pClientDemoPlayer->StartPlayback( name, true, NULL ) ) { SCR_EndLoadingPlaque(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CL_TimeDemo_f( const CCommand &args ) { if ( args.ArgC() < 2 || args.ArgC() > 3 ) { ConMsg ("timedemo <demoname> <optional stats.txt> : gets demo speeds, writing perf resutls to the optional stats.txt\n"); return; } CL_TimeDemo_Helper( args[1], ( args.ArgC() >= 3 ) ? args[2] : NULL, NULL ); } void CL_TimeDemo_VProfRecord_f( const CCommand &args ) { if ( args.ArgC() != 3 ) { ConMsg ("timedemo_vprofrecord <demoname> <vprof stats filename> : gets demo speeds, recording perf data to a vprof stats file\n"); return; } CL_TimeDemo_Helper( args[1], NULL, args[2] ); } void CL_TimeDemoQuit_f( const CCommand &args ) { demo_quitafterplayback.SetValue( 1 ); CL_TimeDemo_f( args ); } void CL_BenchFrame_f( const CCommand &args ) { if ( args.ArgC() != 4 ) { ConMsg ("benchframe <demoname> <frame> <tgafilename>: takes a snapshot of a particular frame in a demo\n"); return; } g_pClientDemoPlayer->SetBenchframe( MAX( 0, atoi( args[2] ) ), args[3] ); s_bBenchframe = true; mat_norendering.SetValue( 1 ); // set current demo player to client demo player demoplayer = g_pClientDemoPlayer; // open the demo file char name[ MAX_OSPATH ]; V_strcpy_safe(name, args[1] ); V_DefaultExtension( name, ".dem", sizeof( name ) ); if ( !g_pClientDemoPlayer->StartPlayback( name, true, NULL ) ) { SCR_EndLoadingPlaque(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CON_COMMAND( vtune, "Controls VTune's sampling." ) { if ( args.ArgC() != 2 ) { ConMsg ("vtune \"pause\" | \"resume\" : Suspend or resume VTune's sampling.\n"); return; } if( !V_strcasecmp( args[1], "pause" ) ) { if(!vtune(false)) { ConMsg("Failed to find \"VTPause()\" in \"vtuneapi.dll\".\n"); return; } ConMsg("VTune sampling paused.\n"); } else if( !V_strcasecmp( args[1], "resume" ) ) { if(!vtune(true)) { ConMsg("Failed to find \"VTResume()\" in \"vtuneapi.dll\".\n"); return; } ConMsg("VTune sampling resumed.\n"); } else { ConMsg("Unknown vtune option.\n"); } } CON_COMMAND_AUTOCOMPLETEFILE( playdemo, CL_PlayDemo_f, "Play a recorded demo file (.dem ).", NULL, dem ); CON_COMMAND_AUTOCOMPLETEFILE( scandemo, CL_ScanDemo_f, "Scan a recorded demo file (.dem ) for specific game events and dump data.", NULL, dem ); CON_COMMAND_EXTERN_F( playoverwatchevidence, CL_PlayOverwatchEvidence_f, "Play evidence for an overwatch case.", FCVAR_HIDDEN ); CON_COMMAND_AUTOCOMPLETEFILE( timedemo, CL_TimeDemo_f, "Play a demo and report performance info.", NULL, dem ); CON_COMMAND_AUTOCOMPLETEFILE( timedemoquit, CL_TimeDemoQuit_f, "Play a demo, report performance info, and then exit", NULL, dem ); CON_COMMAND_AUTOCOMPLETEFILE( listdemo, CL_ListDemo_f, "List demo file contents.", NULL, dem ); CON_COMMAND_AUTOCOMPLETEFILE( benchframe, CL_BenchFrame_f, "Takes a snapshot of a particular frame in a time demo.", NULL, dem ); CON_COMMAND_AUTOCOMPLETEFILE( timedemo_vprofrecord, CL_TimeDemo_VProfRecord_f, "Play a demo and report performance info. Also record vprof data for the span of the demo", NULL, dem ); CON_COMMAND( demo_pause, "Pauses demo playback." ) { float seconds = -1.0; if ( args.ArgC() == 2 ) { seconds = atof( args[1] ); } demoplayer->PausePlayback( seconds ); } CON_COMMAND( demo_resume, "Resumes demo playback." ) { demoplayer->ResumePlayback(); } CON_COMMAND( demo_togglepause, "Toggles demo playback." ) { if ( !demoplayer->IsPlayingBack() ) return; if ( demoplayer->IsPlaybackPaused() ) { demoplayer->ResumePlayback(); } else { demoplayer->PausePlayback( -1 ); } } CON_COMMAND( demo_goto, "Skips to location in demo." ) { bool bRelative = false; bool bPause = false; if ( args.ArgC() < 2 ) { Msg( "Syntax: demo_goto <tick> [relative] [pause]\n" ); Msg( " eg: 'demo_gototick 6666' or 'demo_gototick 25%' or 'demo_gototick 42min'\n" ); if ( demoplayer && demoplayer->IsPlayingBack() ) { IDemoStream *pDemoStream = demoplayer->GetDemoStream(); float flTotalTime = TICKS_TO_TIME( pDemoStream->GetTotalTicks() ) / 60.0f; Msg( " Currently playing %d of %d ticks. Minutes:%.2f File:%s\n", demoplayer->GetPlaybackTick(), pDemoStream->GetTotalTicks(), flTotalTime, pDemoStream->GetUrl() ); } return; } int iArg = 1; const char *strTick = args[ iArg++ ]; int nTick = atoi( strTick ); // If they gave us "50%" or "50 %", then head to percentage of the file. bool bIsPct = !!strchr( strTick, '%' ); bool bIsMinutes = !!strchr( strTick, 'm' ); if ( !bIsPct && ( args[ iArg ][ 0 ] == '%' ) ) { iArg++; bIsPct = true; } else if ( !bIsMinutes && ( args[ iArg ][ 0 ] == 'm' ) ) { iArg++; bIsMinutes = true; } if ( bIsPct ) { nTick = Clamp( nTick, 0, 100 ) * demoplayer->GetDemoStream()->GetTotalTicks() / 100; } else if ( bIsMinutes ) { nTick = Clamp( 60 * TIME_TO_TICKS( nTick ), 0, demoplayer->GetDemoStream()->GetTotalTicks() - 100 ); } for ( ; iArg < args.ArgC(); iArg++ ) { switch ( toupper( args[ iArg ][ 0 ] ) ) { case 'R': bRelative = true; break; case 'P': bPause = true; break; } } demoplayer->SkipToTick( nTick, bRelative, bPause ); } CON_COMMAND( demo_gototick, "Skips to a tick in demo." ) { demo_goto( args ); } CON_COMMAND( demo_info, "Print information about currently playing demo." ) { if ( !demoplayer->IsPlayingBack() ) { Msg( "Error - Not currently playing back a demo.\n" ); return; } ConMsg("Demo contents for %s:\n", demoplayer->GetDemoStream()->GetUrl()); } CON_COMMAND( demo_timescale, "Sets demo replay speed." ) { float fScale = 1.0f; if ( args.ArgC() == 2 ) { fScale = atof( args[1] ); fScale = clamp( fScale, 0.0f, 100.0f ); } demoplayer->SetPlaybackTimeScale( fScale ); } CON_COMMAND( demo_listimportantticks, "List all important ticks in the demo." ) { demoplayer->ListImportantTicks(); } CON_COMMAND( demo_listhighlights, "List all highlights data for the demo." ) { demoplayer->ListHighlightData(); } bool CDemoPlayer::OverrideView( democmdinfo_t& info ) { #if !defined( LINUX ) if ( g_pDemoUI && g_pDemoUI->OverrideView( info, GetPlaybackTick() ) ) return true; if ( demoaction && demoaction->OverrideView( info, GetPlaybackTick() ) ) return true; #endif return false; } void CDemoPlayer::ResetDemoInterpolation( void ) { m_bResetInterpolation = true; }
412
0.972059
1
0.972059
game-dev
MEDIA
0.537839
game-dev
0.757782
1
0.757782
egoal/darkest-pixel-dungeon
5,617
core/src/main/java/com/egoal/darkestpixeldungeon/items/unclassified/Weightstone.kt
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2016 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.egoal.darkestpixeldungeon.items.unclassified import com.egoal.darkestpixeldungeon.Assets import com.egoal.darkestpixeldungeon.actors.hero.Hero import com.egoal.darkestpixeldungeon.items.Item import com.egoal.darkestpixeldungeon.items.weapon.Weapon import com.egoal.darkestpixeldungeon.items.weapon.melee.BattleGloves import com.egoal.darkestpixeldungeon.messages.M import com.egoal.darkestpixeldungeon.messages.Messages import com.egoal.darkestpixeldungeon.scenes.GameScene import com.egoal.darkestpixeldungeon.scenes.PixelScene import com.egoal.darkestpixeldungeon.sprites.ItemSpriteSheet import com.egoal.darkestpixeldungeon.ui.RedButton import com.egoal.darkestpixeldungeon.ui.RenderedTextMultiline import com.egoal.darkestpixeldungeon.utils.GLog import com.egoal.darkestpixeldungeon.windows.IconTitle import com.egoal.darkestpixeldungeon.windows.WndBag import com.egoal.darkestpixeldungeon.ui.Window import com.watabou.noosa.audio.Sample import java.util.ArrayList class Weightstone : Item() { private val itemSelector = WndBag.Listener { item -> if (item != null) { GameScene.show(WndBalance(item as Weapon)) } } init { image = ItemSpriteSheet.WEIGHT stackable = true bones = true } override fun actions(hero: Hero): ArrayList<String> { val actions = super.actions(hero) actions.add(AC_APPLY) return actions } override fun execute(hero: Hero, action: String) { super.execute(hero, action) if (action == AC_APPLY) { GameScene.selectItem(itemSelector, M.L(this, "select"), WndBag.Filter { WndBag.FilterByMode(it, WndBag.Mode.WEAPON) && it !is BattleGloves }) } } override val isUpgradable: Boolean get() = false override val isIdentified: Boolean get() = true private fun apply(weapon: Weapon, forSpeed: Boolean) { detach(curUser.belongings.backpack) if (forSpeed) { weapon.imbue = if (weapon.imbue == Weapon.Imbue.HEAVY) Weapon.Imbue.NONE else Weapon.Imbue.LIGHT GLog.p(Messages.get(this, "light")) } else { weapon.imbue = if (weapon.imbue == Weapon.Imbue.LIGHT) Weapon.Imbue.NONE else Weapon.Imbue.HEAVY GLog.p(Messages.get(this, "heavy")) } curUser.sprite.operate(curUser.pos) Sample.INSTANCE.play(Assets.SND_MISS) curUser.spend(TIME_TO_APPLY) curUser.busy() } override fun price(): Int { return 50 * quantity } inner class WndBalance(weapon: Weapon) : Window() { init { val titlebar = IconTitle(weapon) titlebar.setRect(0f, 0f, WIDTH.toFloat(), 0f) add(titlebar) val tfMesage = PixelScene.renderMultiline(Messages .get(this, "choice"), 8) tfMesage.maxWidth(WIDTH - MARGIN * 2) tfMesage.setPos(MARGIN.toFloat(), titlebar.bottom() + MARGIN) add(tfMesage) var pos = tfMesage.top() + tfMesage.height() if (weapon.imbue != Weapon.Imbue.LIGHT) { val btnSpeed = object : RedButton(Messages.get(this, "light")) { override fun onClick() { hide() this@Weightstone.apply(weapon, true) } } btnSpeed.setRect(MARGIN.toFloat(), pos + MARGIN, BUTTON_WIDTH.toFloat(), BUTTON_HEIGHT.toFloat()) add(btnSpeed) pos = btnSpeed.bottom() } if (weapon.imbue != Weapon.Imbue.HEAVY) { val btnAccuracy = object : RedButton(Messages.get(this, "heavy")) { override fun onClick() { hide() this@Weightstone.apply(weapon, false) } } btnAccuracy.setRect(MARGIN.toFloat(), pos + MARGIN, BUTTON_WIDTH.toFloat(), BUTTON_HEIGHT.toFloat()) add(btnAccuracy) pos = btnAccuracy.bottom() } val btnCancel = object : RedButton(Messages.get(this, "cancel")) { override fun onClick() { hide() } } btnCancel.setRect(MARGIN.toFloat(), pos + MARGIN, BUTTON_WIDTH.toFloat(), BUTTON_HEIGHT.toFloat()) add(btnCancel) resize(WIDTH, btnCancel.bottom().toInt() + MARGIN) } } companion object { private const val WIDTH = 120 private const val MARGIN = 2 private const val BUTTON_WIDTH = WIDTH - MARGIN * 2 private const val BUTTON_HEIGHT = 20 private const val TIME_TO_APPLY = 2f private const val AC_APPLY = "APPLY" } }
412
0.868479
1
0.868479
game-dev
MEDIA
0.992953
game-dev
0.968224
1
0.968224
traggett/UnityFramework
8,996
Framework/Utils/Assets/PrefabInstancePool.cs
using System; using UnityEditor; using UnityEngine; using UnityEngine.SceneManagement; namespace Framework { namespace Utils { public class PrefabInstancePool : MonoBehaviour { #region Serialised Data [SerializeField] private GameObject _prefab; [SerializeField] private bool _initialiseOnAwake; [SerializeField] private int _initialPoolSize = 10; [SerializeField] private int _growAmount = 1; [SerializeField] private PooledPrefab[] _instances; #endregion #region Public Properties public GameObject Prefab { get { return _prefab; } } public int PoolSize { get { return _instances != null ? _instances.Length : 0; } } public int ActivePrefabCount { get { int count = 0; if (_instances != null) { for (int i = 0; i < _instances.Length; i++) { if (!_instances[i]._isFree) { count++; } } } return count; } } #endregion #region Helper Struct private class PooledPrefab : MonoBehaviour { #region Public Data public PrefabInstancePool _pool; public bool _isFree; public bool _markedForDestroy; #endregion } #endregion #region Private Data private bool _prefabsToDestroy; #endregion #region Unity Messages private void Awake() { if (_initialiseOnAwake) { InitialisePool(); } } private void Update() { if (_prefabsToDestroy) { for (int i = 0; i < _instances.Length; i++) { if (_instances[i] != null && _instances[i]._markedForDestroy) { DestroyAtIndex(i); } } _prefabsToDestroy = false; } } #endregion #region Public Interface public void InitialisePool() { if (_prefab != null && (_instances == null || _instances.Length == 0)) { _instances = new PooledPrefab[Math.Max(_initialPoolSize, 1)]; for (int i = 0; i < _instances.Length; i++) { InstantiatePrefab(i); } } } public void DeInitialisePool() { if (_instances != null) { for (int i = 0; i < _instances.Length; i++) { if (_instances[i] != null) { #if UNITY_EDITOR if (!Application.isPlaying) { UnityEngine.Object.DestroyImmediate(_instances[i].gameObject); } else #endif { UnityEngine.Object.Destroy(_instances[i].gameObject); } } } _instances = null; } } public static void InitialiseAllPrefabInstancePools() { for (int i = 0; i < SceneManager.sceneCount; i++) { Scene scene = SceneManager.GetSceneAt(i); InitialiseScenePrefabInstancePools(scene); } } public static void InitialiseScenePrefabInstancePools(Scene scene) { PrefabInstancePool[] prefabPools = SceneUtils.FindAllComponentInferfacesInScene<PrefabInstancePool>(scene, true); for (int j = 0; j < prefabPools.Length; j++) { prefabPools[j].InitialisePool(); } } public T Instantiate<T>(Transform parent = null, bool resetTransform = true) where T : Component { GameObject gameObject = Instantiate(parent, resetTransform); if (gameObject != null) { T component = gameObject.GetComponent<T>(); if (component != null) { return component; } else { #if DEBUG UnityEngine.Debug.LogError("PrefabInstancePool " + GameObjectUtils.GetGameObjectPath(this.gameObject) + " prefab has no component of type " + typeof(T).Name); #endif Destroy(gameObject); } } return null; } public GameObject Instantiate(Transform parent = null, bool resetTransform = true) { InitialisePool(); GameObject newInstance = null; for (int i = 0; i < _instances.Length; i++) { if (_instances[i] != null && _instances[i]._isFree) { newInstance = _instances[i].gameObject; _instances[i]._isFree = false; break; } } if (newInstance == null) { int origSize = _instances.Length; int growAmount = Math.Max(1, _growAmount); ArrayUtils.Resize(ref _instances, _instances.Length + growAmount); for (int i = origSize; i < _instances.Length; i++) { InstantiatePrefab(i); } //Return first new instance newInstance = _instances[origSize].gameObject; _instances[origSize]._isFree = false; } if (parent == null) { parent = this.transform; } if (newInstance.transform.parent != parent) { newInstance.transform.SetParent(parent, false); } if (resetTransform) { newInstance.transform.localPosition = _prefab.transform.localPosition; newInstance.transform.localRotation = _prefab.transform.localRotation; newInstance.transform.localScale = _prefab.transform.localScale; if (newInstance.transform is RectTransform rectTransform && _prefab.transform is RectTransform prefabRectTransform) { rectTransform.anchoredPosition = prefabRectTransform.anchoredPosition; rectTransform.anchorMin = prefabRectTransform.anchorMin; rectTransform.anchorMax = prefabRectTransform.anchorMax; rectTransform.sizeDelta = prefabRectTransform.sizeDelta; rectTransform.pivot = prefabRectTransform.pivot; } } newInstance.hideFlags = HideFlags.None; newInstance.SetActive(true); return newInstance; } private int GetPrefabInstanceIndex(GameObject prefab) { for (int i = 0; i < _instances.Length; i++) { if (_instances[i] != null && _instances[i].gameObject == prefab) { return i; } } return -1; } public static void DestroyPrefab(GameObject prefab, bool instant = true) { if (prefab.TryGetComponent(out PooledPrefab pooledPrefab)) { pooledPrefab._pool.Destroy(prefab, instant); } } public static void DestroyPrefab(Component component, bool instant = true) { DestroyPrefab(component.gameObject, instant); } public bool Destroy(GameObject gameObject, bool instant = true) { int index = GetPrefabInstanceIndex(gameObject); if (index != -1) { return Destroy(index, instant); } return false; } public bool Destroy(Component component, bool instant = true) { int index = GetPrefabInstanceIndex(component.gameObject); if (index != -1) { return Destroy(index, instant); } return false; } public void DestroyAll(bool instant = true) { if (_instances != null) { for (int i = 0; i < _instances.Length; i++) { if (instant) { DestroyAtIndex(i); } else if (_instances[i] != null) { _instances[i]._markedForDestroy = true; _prefabsToDestroy = true; _instances[i].gameObject.SetActive(false); } } } } #endregion #region Private Functions private void InstantiatePrefab(int index) { #if DEBUG if (_prefab == null) { UnityEngine.Debug.LogError("PrefabInstancePool " + GameObjectUtils.GetGameObjectPath(this.gameObject) + " is missing it's prefab!"); return; } #endif GameObject gameObject; #if UNITY_EDITOR if (!Application.isPlaying) { gameObject = PrefabUtility.InstantiatePrefab(_prefab, this.transform) as GameObject; } else #endif { gameObject = UnityEngine.Object.Instantiate(_prefab, this.transform); } gameObject.hideFlags = HideFlags.HideInHierarchy; gameObject.gameObject.SetActive(false); _instances[index] = gameObject.AddComponent<PooledPrefab>(); _instances[index].hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy; _instances[index]._pool = this; _instances[index]._isFree = true; _instances[index]._markedForDestroy = false; } private bool Destroy(int index, bool instant) { #if UNITY_EDITOR // Always destroy instantly in edit mode if (!Application.isPlaying) { instant = true; } #endif if (index != -1 && !_instances[index]._isFree) { if (instant) { DestroyAtIndex(index); } else { _instances[index]._markedForDestroy = true; _prefabsToDestroy = true; if (_instances[index] != null) { _instances[index].gameObject.SetActive(false); _instances[index].gameObject.hideFlags = HideFlags.HideInHierarchy; } } return true; } return false; } private void DestroyAtIndex(int index) { if (_instances[index] != null) { _instances[index]._isFree = true; _instances[index]._markedForDestroy = false; GameObject gameObject = _instances[index].gameObject; if (gameObject.transform.parent != this.transform) { gameObject.transform.SetParent(this.transform, false); } gameObject.SetActive(false); gameObject.hideFlags = HideFlags.HideInHierarchy; } } #endregion } } }
412
0.78981
1
0.78981
game-dev
MEDIA
0.974019
game-dev
0.91346
1
0.91346
oculus-samples/Unity-Decommissioned
7,023
Assets/Decommissioned/Scripts/UI/MainRoomHealthGauge.cs
// Copyright (c) Meta Platforms, Inc. and affiliates. // Use of the material below is subject to the terms of the MIT License // https://github.com/oculus-samples/Unity-Decommissioned/tree/main/Assets/Decommissioned/LICENSE using Meta.Decommissioned.Game; using Meta.Decommissioned.Game.MiniGames; using Meta.Utilities; using Meta.XR.Samples; using TMPro; using Unity.Mathematics; using Unity.Netcode; using UnityEngine; using UnityEngine.Events; namespace Meta.Decommissioned.UI { [MetaCodeSample("Decommissioned")] public class MainRoomHealthGauge : Multiton<MainRoomHealthGauge> { [Tooltip("The task room that this gauge will keep track of.")] [field: SerializeField] public MiniGameRoom MiniGameRoom { get; private set; } = MiniGameRoom.None; [Tooltip("A reference to the needle on the gauge that will move to display the health.")] [SerializeField] private Transform m_displayNeedle; [SerializeField] private TextMeshPro m_healthDisplay; [SerializeField] private bool m_updateHealthChangeDisplay; [SerializeField] private MeshRenderer m_gaugeFlashingMesh; [SerializeField] private MeshRenderer m_gaugeBaseMesh; [SerializeField, AutoSetFromChildren] private StationHealthChangeDisplay m_healthChangeDisplay; [SerializeField] private UnityEvent<int> m_onGaugeReadoutChanged; [SerializeField] private EnumDictionary<MiniGameRoom, float> m_textVerticalOffsets = new(); [SerializeField] private float m_textHorizontalOffset = 0.915f; [SerializeField] private float m_textHorizontalScale = 13f; public bool ShouldFlashForCallout => m_gaugeFlashingMesh != null; private int m_healthAtPhaseStart = 100; private float m_minNeedlePosition = 0.06f; private float m_maxNeedlePosition = 0; private float m_currentNeedlePosition; private MaterialPropertyBlock m_materialProperties; private readonly int m_textOffsetName = Shader.PropertyToID("_DetailAlbedoMap_ST"); internal MiniGame m_miniGame; private new void Awake() { m_materialProperties = new(); m_materialProperties.SetVector(m_textOffsetName, new Vector4(m_textHorizontalScale, 12, m_textHorizontalOffset, m_textVerticalOffsets[MiniGameRoom])); m_gaugeBaseMesh.SetPropertyBlock(m_materialProperties); if (MiniGameRoom == MiniGameRoom.None) { Debug.LogError("A MainRoomHealthGauge was not assigned to a minigame room! It will be disabled this session."); gameObject.SetActive(false); } } private void Start() { m_healthChangeDisplay.ResetDisplay(); InitializeMiniGame(); } private new void OnEnable() { base.OnEnable(); if (GamePhaseManager.Instance != null) { GamePhaseManager.Instance.OnPhaseChanged += OnPhaseChanged; } if (GameManager.Instance != null) { GameManager.OnGameStateChanged += OnGameStateChanged; } UpdateGaugeText(); if (!m_miniGame) { return; } m_miniGame.OnHealthChanged += OnMiniGameHealthChanged; m_miniGame.SpawnPoint.OnOccupyingPlayerChanged += OnPlayerChanged; } private new void OnDisable() { if (GamePhaseManager.Instance != null) { GamePhaseManager.Instance.OnPhaseChanged -= OnPhaseChanged; } if (m_miniGame != null) { m_miniGame.OnHealthChanged -= OnMiniGameHealthChanged; } base.OnDisable(); } private void InitializeMiniGame() { m_miniGame = MiniGame.GetByMiniGameRoom(MiniGameRoom); if (m_miniGame == null) { Debug.LogError("A MainRoomHealthGauge was unable to find a minigame in the assigned " + "MiniGameRoom. It will be disabled this session."); gameObject.SetActive(false); return; } m_miniGame.OnHealthChanged += OnMiniGameHealthChanged; OnMiniGameHealthChanged(); } private void OnGameStateChanged(GameState state) { if (state != GameState.Gameplay) { return; } m_healthChangeDisplay.ResetDisplay(); } private void OnPlayerChanged(NetworkObject prevPlayer, NetworkObject newPlayer) => OnMiniGameHealthChanged(); private void OnPhaseChanged(Phase phase) { switch (phase) { case Phase.Night: m_healthAtPhaseStart = m_miniGame.CurrentHealth; m_healthChangeDisplay.ResetDisplay(); break; case Phase.Discussion: m_healthChangeDisplay.UpdateDisplay(m_miniGame.GetHealthChange(), m_miniGame.CurrentHealth > m_healthAtPhaseStart); UpdateGaugeText(); break; case Phase.Voting: break; case Phase.Invalid: break; case Phase.Planning: break; default: break; } } private void OnMiniGameHealthChanged() { UpdateGaugeText(); m_onGaugeReadoutChanged?.Invoke(m_miniGame.CurrentHealth); } private void UpdateGaugeText() { if (m_miniGame == null) { return; } m_healthDisplay.text = m_miniGame.GetMiniGameHealthRatio() * 100 + "%"; if (m_updateHealthChangeDisplay) { m_healthChangeDisplay.UpdateDisplay(m_miniGame.GetHealthChange(), m_miniGame.CurrentHealth > m_healthAtPhaseStart); } } public void SetGaugeDangerFlash(bool on) => m_gaugeFlashingMesh.gameObject.SetActive(on); private void FixedUpdate() { var xPos = GetNeedlePosition(); m_currentNeedlePosition = Mathf.MoveTowards(m_currentNeedlePosition, xPos, .001f); var localNeedlePosition = m_displayNeedle.localPosition; m_displayNeedle.localPosition = new Vector3(m_currentNeedlePosition, localNeedlePosition.y, localNeedlePosition.z); } private float GetNeedlePosition() { if (m_miniGame == null) { return 1; } var healthValue = (float)m_miniGame.CurrentHealth / m_miniGame.Config.MaxHealth; //Gives a 0-1 float var position = math.remap(0, 1, m_minNeedlePosition, m_maxNeedlePosition, healthValue); return position; } } }
412
0.929768
1
0.929768
game-dev
MEDIA
0.92651
game-dev
0.976628
1
0.976628
ancientElement/BEPUPhysicsIntForUnity
44,828
Assets/BEPUPhysics/BEPUphysics/Character/CharacterController.cs
using System; using System.Collections.Generic; using BEPUphysics.BroadPhaseEntries; using BEPUphysics.BroadPhaseEntries.MobileCollidables; using BEPUphysics.Entities.Prefabs; using BEPUphysics.UpdateableSystems; using BEPUutilities; using BEPUphysics.NarrowPhaseSystems.Pairs; using BEPUphysics.Materials; using BEPUphysics.PositionUpdating; using System.Diagnostics; using System.Threading; using FixMath.NET; namespace BEPUphysics.Character { /// <summary> /// Gives a physical object FPS-like control, including stepping and jumping. /// </summary> public class CharacterController : Updateable, IBeforeSolverUpdateable { /// <summary> /// Gets the physical body of the character. Do not use this reference to modify the character's height and radius. Instead, use the BodyRadius property and the StanceManager's StandingHeight and CrouchingHeight properties. /// </summary> public Cylinder Body { get; private set; } /// <summary> /// Gets the contact categorizer used by the character to determine how contacts affect the character's movement. /// </summary> public CharacterContactCategorizer ContactCategorizer { get; private set; } /// <summary> /// Gets the manager responsible for finding places for the character to step up and down to. /// </summary> public StepManager StepManager { get; private set; } /// <summary> /// Gets the manager responsible for crouching, standing, and the verification involved in changing states. /// </summary> public StanceManager StanceManager { get; private set; } /// <summary> /// Gets the support system which other systems use to perform local ray casts and contact queries. /// </summary> public QueryManager QueryManager { get; private set; } /// <summary> /// Gets the constraint used by the character to handle horizontal motion. This includes acceleration due to player input and deceleration when the relative velocity /// between the support and the character exceeds specified maximums. /// </summary> public HorizontalMotionConstraint HorizontalMotionConstraint { get; private set; } /// <summary> /// Gets the constraint used by the character to stay glued to surfaces it stands on. /// </summary> public VerticalMotionConstraint VerticalMotionConstraint { get; private set; } /// <summary> /// Gets or sets the pair locker used by the character controller to avoid interfering with the behavior of other characters. /// </summary> private CharacterPairLocker PairLocker { get; set; } /// <summary> /// Gets or sets the down direction of the character, defining its orientation. /// </summary> public Vector3 Down { get { return Body.OrientationMatrix.Down; } set { //Update the character's orientation to something compatible with the new direction. Quaternion orientation; Fix64 lengthSquared = value.LengthSquared(); if (lengthSquared < Toolbox.Epsilon) value = Body.OrientationMatrix.Down; //Silently fail. Assuming here that a dynamic process is setting this property; don't need to make a stink about it. else Vector3.Divide(ref value, Fix64.Sqrt(lengthSquared), out value); Quaternion.GetQuaternionBetweenNormalizedVectors(ref Toolbox.DownVector, ref value, out orientation); Body.Orientation = orientation; } } Vector3 viewDirection = new Vector3(F64.C0, F64.C0, -1); /// <summary> /// Gets or sets the view direction associated with the character. /// Also sets the horizontal view direction internally based on the current down vector. /// This is used to interpret the movement directions. /// </summary> public Vector3 ViewDirection { get { return viewDirection; } set { Fix64 lengthSquared = value.LengthSquared(); if (lengthSquared > F64.C1em7) { Vector3.Divide(ref value, Fix64.Sqrt(lengthSquared), out viewDirection); } else { value = Vector3.Cross(Down, Toolbox.UpVector); lengthSquared = value.LengthSquared(); if (lengthSquared > F64.C1em7) { Vector3.Divide(ref value, Fix64.Sqrt(lengthSquared), out viewDirection); } else { value = Vector3.Cross(Down, Toolbox.ForwardVector); Vector3.Normalize(ref value, out viewDirection); } } } } private Fix64 jumpSpeed; /// <summary> /// Gets or sets the speed at which the character leaves the ground when it jumps. /// </summary> public Fix64 JumpSpeed { get { return jumpSpeed; } set { if (value < F64.C0) throw new ArgumentException("Value must be nonnegative."); jumpSpeed = value; } } Fix64 slidingJumpSpeed; /// <summary> /// Gets or sets the speed at which the character leaves the ground when it jumps without traction. /// </summary> public Fix64 SlidingJumpSpeed { get { return slidingJumpSpeed; } set { if (value < F64.C0) throw new ArgumentException("Value must be nonnegative."); slidingJumpSpeed = value; } } Fix64 jumpForceFactor = F64.C1; /// <summary> /// Gets or sets the amount of force to apply to supporting dynamic entities as a fraction of the force used to reach the jump speed. /// </summary> public Fix64 JumpForceFactor { get { return jumpForceFactor; } set { if (value < F64.C0) throw new ArgumentException("Value must be nonnegative."); jumpForceFactor = value; } } Fix64 standingSpeed; /// <summary> /// Gets or sets the speed at which the character will try to move while standing with a support that provides traction. /// Relative velocities with a greater magnitude will be decelerated. /// </summary> public Fix64 StandingSpeed { get { return standingSpeed; } set { if (value < F64.C0) throw new ArgumentException("Value must be nonnegative."); standingSpeed = value; } } Fix64 crouchingSpeed; /// <summary> /// Gets or sets the speed at which the character will try to move while crouching with a support that provides traction. /// Relative velocities with a greater magnitude will be decelerated. /// </summary> public Fix64 CrouchingSpeed { get { return crouchingSpeed; } set { if (value < F64.C0) throw new ArgumentException("Value must be nonnegative."); crouchingSpeed = value; } } Fix64 proneSpeed; /// <summary> /// Gets or sets the speed at which the character will try to move while prone with a support that provides traction. /// Relative velocities with a greater magnitude will be decelerated. /// </summary> public Fix64 ProneSpeed { get { return proneSpeed; } set { if (value < F64.C0) throw new ArgumentException("Value must be nonnegative."); proneSpeed = value; } } Fix64 tractionForce; /// <summary> /// Gets or sets the maximum force that the character can apply while on a support which provides traction. /// </summary> public Fix64 TractionForce { get { return tractionForce; } set { if (value < F64.C0) throw new ArgumentException("Value must be nonnegative."); tractionForce = value; } } Fix64 slidingSpeed; /// <summary> /// Gets or sets the speed at which the character will try to move while on a support that does not provide traction. /// Relative velocities with a greater magnitude will be decelerated. /// </summary> public Fix64 SlidingSpeed { get { return slidingSpeed; } set { if (value < F64.C0) throw new ArgumentException("Value must be nonnegative."); slidingSpeed = value; } } Fix64 slidingForce; /// <summary> /// Gets or sets the maximum force that the character can apply while on a support which does not provide traction. /// </summary> public Fix64 SlidingForce { get { return slidingForce; } set { if (value < F64.C0) throw new ArgumentException("Value must be nonnegative."); slidingForce = value; } } Fix64 airSpeed; /// <summary> /// Gets or sets the speed at which the character will try to move with no support. /// The character will not be decelerated while airborne. /// </summary> public Fix64 AirSpeed { get { return airSpeed; } set { if (value < F64.C0) throw new ArgumentException("Value must be nonnegative."); airSpeed = value; } } Fix64 airForce; /// <summary> /// Gets or sets the maximum force that the character can apply with no support. /// </summary> public Fix64 AirForce { get { return airForce; } set { if (value < F64.C0) throw new ArgumentException("Value must be nonnegative."); airForce = value; } } private Fix64 speedScale = F64.C1; /// <summary> /// Gets or sets a scaling factor to apply to the maximum speed of the character. /// This is useful when a character does not have 0 or MaximumSpeed target speed, but rather /// intermediate values. A common use case is analog controller sticks. /// </summary> public Fix64 SpeedScale { get { return speedScale; } set { speedScale = value; } } /// <summary> /// Gets or sets the radius of the body cylinder. To change the height, use the StanceManager.StandingHeight and StanceManager.CrouchingHeight. /// </summary> public Fix64 BodyRadius { get { return Body.CollisionInformation.Shape.Radius; } set { if (value <= F64.C0) throw new ArgumentException("Radius must be positive."); Body.CollisionInformation.Shape.Radius = value; //Tell the query manager to update its representation. StanceManager.UpdateQueryShapes(); } } /// <summary> /// Gets or sets the collision margin of the body cylinder. Also updates the StanceManager's query shapes to match. /// </summary> public Fix64 CollisionMargin { get { return Body.CollisionInformation.Shape.CollisionMargin; } set { if (value <= F64.C0) throw new ArgumentException("Radius must be positive."); Body.CollisionInformation.Shape.CollisionMargin = value; //Tell the query manager to update its representation. StanceManager.UpdateQueryShapes(); } } /// <summary> /// Gets the support finder used by the character. /// The support finder analyzes the character's contacts to see if any of them provide support and/or traction. /// </summary> public SupportFinder SupportFinder { get; private set; } /// <summary> /// Constructs a new character controller. /// </summary> /// <param name="position">Initial position of the character.</param> /// <param name="height">Height of the character body while standing.</param> /// <param name="crouchingHeight">Height of the character body while crouching.</param> /// <param name="proneHeight">Height of the character body while prone.</param> /// <param name="radius">Radius of the character body.</param> /// <param name="margin">Radius of 'rounding' applied to the cylindrical body. Higher values make the cylinder's edges more rounded. /// The margin is contained within the cylinder's height and radius, so it must not exceed the radius or height of the cylinder. /// To change the collision margin later, use the CharacterController.CollisionMargin property.</param> /// <param name="mass">Mass of the character body.</param> /// <param name="maximumTractionSlope">Steepest slope, in radians, that the character can maintain traction on.</param> /// <param name="maximumSupportSlope">Steepest slope, in radians, that the character can consider a support.</param> /// <param name="standingSpeed">Speed at which the character will try to move while crouching with a support that provides traction. /// Relative velocities with a greater magnitude will be decelerated.</param> /// <param name="crouchingSpeed">Speed at which the character will try to move while crouching with a support that provides traction. /// Relative velocities with a greater magnitude will be decelerated.</param> /// <param name="proneSpeed">Speed at which the character will try to move while prone with a support that provides traction. /// Relative velocities with a greater magnitude will be decelerated.</param> /// <param name="tractionForce">Maximum force that the character can apply while on a support which provides traction.</param> /// <param name="slidingSpeed">Speed at which the character will try to move while on a support that does not provide traction. /// Relative velocities with a greater magnitude will be decelerated.</param> /// <param name="slidingForce">Maximum force that the character can apply while on a support which does not provide traction</param> /// <param name="airSpeed">Speed at which the character will try to move with no support. /// The character will not be decelerated while airborne.</param> /// <param name="airForce">Maximum force that the character can apply with no support.</param> /// <param name="jumpSpeed">Speed at which the character leaves the ground when it jumps</param> /// <param name="slidingJumpSpeed">Speed at which the character leaves the ground when it jumps without traction</param> /// <param name="maximumGlueForce">Maximum force the vertical motion constraint is allowed to apply in an attempt to keep the character on the ground.</param> public CharacterController( // Fix64 cannot be used for default parameters. As a workaround, make all parameters nullable and assign default values inside the constructor Vector3 position = new Vector3(), Fix64? height = null, Fix64? crouchingHeight = null, Fix64? proneHeight = null, Fix64? radius = null, Fix64? margin = null, Fix64? mass = null, Fix64? maximumTractionSlope = null, Fix64? maximumSupportSlope = null, Fix64? standingSpeed = null, Fix64? crouchingSpeed = null, Fix64? proneSpeed = null, Fix64? tractionForce = null, Fix64? slidingSpeed = null, Fix64? slidingForce = null, Fix64? airSpeed = null, Fix64? airForce = null, Fix64? jumpSpeed = null, Fix64? slidingJumpSpeed = null, Fix64? maximumGlueForce = null ) { if (height == null) height = (Fix64)1.7m; if (crouchingHeight == null) crouchingHeight = (Fix64)(1.7m * .7m); if (proneHeight == null) proneHeight = (Fix64)(1.7m * 0.3m); if (radius == null) radius = (Fix64)0.6m; if (margin == null) margin = (Fix64)0.1m; if (mass == null) mass = 10; if (maximumTractionSlope == null) maximumTractionSlope = (Fix64)0.8m; if (maximumSupportSlope == null) maximumSupportSlope = (Fix64)1.3m; if (standingSpeed == null) standingSpeed = 8; if (crouchingSpeed == null) crouchingSpeed = 3; if (proneSpeed == null) proneSpeed = (Fix64)1.5m; if (tractionForce == null) tractionForce = 1000; if (slidingSpeed == null) slidingSpeed = 6; if (slidingForce == null) slidingForce = 50; if (airSpeed == null) airSpeed = 1; if (airForce == null) airForce = 250; if (jumpSpeed == null) jumpSpeed = (Fix64)4.5m; if (slidingJumpSpeed == null) slidingJumpSpeed = 3; if (maximumGlueForce == null) maximumGlueForce = 5000; if (margin > radius || margin > crouchingHeight || margin > height) throw new ArgumentException("Margin must not be larger than the character's radius or height."); Body = new Cylinder(position, (Fix64)height, (Fix64)radius, (Fix64)mass); Body.IgnoreShapeChanges = true; //Wouldn't want inertia tensor recomputations to occur when crouching and such. Body.CollisionInformation.Shape.CollisionMargin = (Fix64)margin; //Making the character a continuous object prevents it from flying through walls which would be pretty jarring from a player's perspective. Body.PositionUpdateMode = PositionUpdateMode.Continuous; Body.LocalInertiaTensorInverse = new Matrix3x3(); //TODO: In v0.16.2, compound bodies would override the material properties that get set in the CreatingPair event handler. //In a future version where this is changed, change this to conceptually minimally required CreatingPair. Body.CollisionInformation.Events.DetectingInitialCollision += RemoveFriction; Body.LinearDamping = F64.C0; ContactCategorizer = new CharacterContactCategorizer((Fix64)maximumTractionSlope, (Fix64)maximumSupportSlope); QueryManager = new QueryManager(Body, ContactCategorizer); SupportFinder = new SupportFinder(Body, QueryManager, ContactCategorizer); HorizontalMotionConstraint = new HorizontalMotionConstraint(Body, SupportFinder); HorizontalMotionConstraint.PositionAnchorDistanceThreshold = (Fix64)radius * F64.C0p25; VerticalMotionConstraint = new VerticalMotionConstraint(Body, SupportFinder, (Fix64)maximumGlueForce); StepManager = new StepManager(Body, ContactCategorizer, SupportFinder, QueryManager, HorizontalMotionConstraint); StanceManager = new StanceManager(Body, (Fix64)crouchingHeight, (Fix64)proneHeight, QueryManager, SupportFinder); PairLocker = new CharacterPairLocker(Body); StandingSpeed = (Fix64)standingSpeed; CrouchingSpeed = (Fix64)crouchingSpeed; ProneSpeed = (Fix64)proneSpeed; TractionForce = (Fix64)tractionForce; SlidingSpeed = (Fix64)slidingSpeed; SlidingForce = (Fix64)slidingForce; AirSpeed = (Fix64)airSpeed; AirForce = (Fix64)airForce; JumpSpeed = (Fix64)jumpSpeed; SlidingJumpSpeed = (Fix64)slidingJumpSpeed; //Enable multithreading for the characters. IsUpdatedSequentially = false; //Link the character body to the character controller so that it can be identified by the locker. //Any object which replaces this must implement the ICharacterTag for locking to work properly. Body.CollisionInformation.Tag = new CharacterSynchronizer(Body); } void RemoveFriction(EntityCollidable sender, BroadPhaseEntry other, NarrowPhasePair pair) { var collidablePair = pair as CollidablePairHandler; if (collidablePair != null) { //The default values for InteractionProperties is all zeroes- zero friction, zero bounciness. //That's exactly how we want the character to behave when hitting objects. collidablePair.UpdateMaterialProperties(new InteractionProperties()); } } /// <summary> /// Cylinder shape used to compute the expanded bounding box of the character. /// </summary> void ExpandBoundingBox() { if (Body.ActivityInformation.IsActive) { //This runs after the bounding box updater is run, but before the broad phase. //Expanding the character's bounding box ensures that minor variations in velocity will not cause //any missed information. //TODO: seems a bit silly to do this work sequentially. Would be better if it could run in parallel in the proper location. var down = Down; var boundingBox = Body.CollisionInformation.BoundingBox; //Expand the bounding box up and down using the step height. Vector3 expansion; Vector3.Multiply(ref down, StepManager.MaximumStepHeight, out expansion); expansion.X = Fix64.Abs(expansion.X); expansion.Y = Fix64.Abs(expansion.Y); expansion.Z = Fix64.Abs(expansion.Z); //When the character climbs a step, it teleports horizontally a little to gain support. Expand the bounding box to accommodate the margin. //Compute the expansion caused by the extra radius along each axis. //There's a few ways to go about doing this. //The following is heavily cooked, but it is based on the angle between the vertical axis and a particular axis. //Given that, the amount of the radial expansion required along that axis can be computed. //The dot product would provide the cos(angle) between the vertical axis and a chosen axis. //Equivalently, it is how much expansion would be along that axis, if the vertical axis was the axis of expansion. //However, it's not. The dot product actually gives us the expansion along an axis perpendicular to the chosen axis, pointing away from the character's vertical axis. //What we need is actually given by the sin(angle), which is given by ||verticalAxis x testAxis||. //The sin(angle) is the projected length of the verticalAxis (not the expansion!) on the axis perpendicular to the testAxis pointing away from the character's vertical axis. //That projected length, however is equal to the expansion along the test axis, which is exactly what we want. //To show this, try setting up the triangles at the corner of a cylinder with the world axes and cylinder axes. //Since the test axes we're using are all standard directions ({0,0,1}, {0,1,0}, and {0,0,1}), most of the cross product logic simplifies out, and we are left with: var horizontalExpansionAmount = Body.CollisionInformation.Shape.CollisionMargin * F64.C1p1; Vector3 squaredDown; squaredDown.X = down.X * down.X; squaredDown.Y = down.Y * down.Y; squaredDown.Z = down.Z * down.Z; expansion.X += horizontalExpansionAmount * Fix64.Sqrt(squaredDown.Y + squaredDown.Z); expansion.Y += horizontalExpansionAmount * Fix64.Sqrt(squaredDown.X + squaredDown.Z); expansion.Z += horizontalExpansionAmount * Fix64.Sqrt(squaredDown.X + squaredDown.Y); Vector3.Add(ref expansion, ref boundingBox.Max, out boundingBox.Max); Vector3.Subtract(ref boundingBox.Min, ref expansion, out boundingBox.Min); Body.CollisionInformation.BoundingBox = boundingBox; } } void IBeforeSolverUpdateable.Update(Fix64 dt) { //Someone may want to use the Body.CollisionInformation.Tag for their own purposes. //That could screw up the locking mechanism above and would be tricky to track down. //Consider using the making the custom tag implement ICharacterTag, modifying LockCharacterPairs to analyze the different Tag type, or using the Entity.Tag for the custom data instead. Debug.Assert(Body.CollisionInformation.Tag is ICharacterTag, "The character.Body.CollisionInformation.Tag must implement ICharacterTag to link the CharacterController and its body together for character-related locking to work in multithreaded simulations."); SupportData supportData; HorizontalMotionConstraint.UpdateMovementBasis(ref viewDirection); //We can't let multiple characters manage the same pairs simultaneously. Lock it up! PairLocker.LockCharacterPairs(); try { CorrectContacts(); bool hadSupport = SupportFinder.HasSupport; SupportFinder.UpdateSupports(ref HorizontalMotionConstraint.movementDirection3d); supportData = SupportFinder.SupportData; //Compute the initial velocities relative to the support. Vector3 relativeVelocity; ComputeRelativeVelocity(ref supportData, out relativeVelocity); Fix64 verticalVelocity = Vector3.Dot(supportData.Normal, relativeVelocity); //Don't attempt to use an object as support if we are flying away from it (and we were never standing on it to begin with). if (SupportFinder.HasSupport && !hadSupport && verticalVelocity < F64.C0) { SupportFinder.ClearSupportData(); supportData = new SupportData(); } //Attempt to jump. if (TryToJump) { //In the following, note that the jumping velocity changes are computed such that the separating velocity is specifically achieved, //rather than just adding some speed along an arbitrary direction. This avoids some cases where the character could otherwise increase //the jump speed, which may not be desired. if (SupportFinder.HasTraction) { //The character has traction, so jump straight up. Fix64 currentDownVelocity = Vector3.Dot(Down, relativeVelocity); //Target velocity is JumpSpeed. Fix64 velocityChange = MathHelper.Max(jumpSpeed + currentDownVelocity, F64.C0); ApplyJumpVelocity(ref supportData, Down * -velocityChange, ref relativeVelocity); //Prevent any old contacts from hanging around and coming back with a negative depth. foreach (var pair in Body.CollisionInformation.Pairs) pair.ClearContacts(); SupportFinder.ClearSupportData(); supportData = new SupportData(); } else if (SupportFinder.HasSupport) { //The character does not have traction, so jump along the surface normal instead. Fix64 currentNormalVelocity = Vector3.Dot(supportData.Normal, relativeVelocity); //Target velocity is JumpSpeed. Fix64 velocityChange = MathHelper.Max(slidingJumpSpeed - currentNormalVelocity, F64.C0); ApplyJumpVelocity(ref supportData, supportData.Normal * -velocityChange, ref relativeVelocity); //Prevent any old contacts from hanging around and coming back with a negative depth. foreach (var pair in Body.CollisionInformation.Pairs) pair.ClearContacts(); SupportFinder.ClearSupportData(); supportData = new SupportData(); } } TryToJump = false; //Try to step! Vector3 newPosition; //Note: downstepping is often not required. //It's only really there for games that expect to be able to run down stairs at 40 miles an hour without zipping off into the void. //Most of the time, you can just comment out downstepping, and so long as the character is running at a reasonable speed, //gravity will do the work. //If your game would work without teleportation-based downstepping, it's probably a good idea to comment it out. //Downstepping can be fairly expensive. //You can also avoid doing upstepping by fattening up the character's margin, turning it into more of a capsule. //Instead of teleporting up steps, it would slide up. //Without teleportation-based upstepping, steps usually need to be quite a bit smaller (i.e. fairly normal sized, instead of 2 feet tall). if (StepManager.TryToStepDown(out newPosition) || StepManager.TryToStepUp(out newPosition)) { supportData = TeleportToPosition(newPosition, dt); } if (StanceManager.UpdateStance(out newPosition)) { supportData = TeleportToPosition(newPosition, dt); } } finally { PairLocker.UnlockCharacterPairs(); } //Tell the constraints to get ready to solve. HorizontalMotionConstraint.UpdateSupportData(); VerticalMotionConstraint.UpdateSupportData(); //Update the horizontal motion constraint's state. if (supportData.SupportObject != null) { Fix64 speed; switch (StanceManager.CurrentStance) { case Stance.Prone: speed = proneSpeed; break; case Stance.Crouching: speed = crouchingSpeed; break; default: speed = standingSpeed; break; } if (SupportFinder.HasTraction) { HorizontalMotionConstraint.MovementMode = MovementMode.Traction; HorizontalMotionConstraint.TargetSpeed = speed; HorizontalMotionConstraint.MaximumForce = tractionForce; } else { HorizontalMotionConstraint.MovementMode = MovementMode.Sliding; HorizontalMotionConstraint.TargetSpeed = MathHelper.Min(speed, slidingSpeed); HorizontalMotionConstraint.MaximumForce = MathHelper.Min(tractionForce, slidingForce); } } else { HorizontalMotionConstraint.MovementMode = MovementMode.Floating; HorizontalMotionConstraint.TargetSpeed = airSpeed; HorizontalMotionConstraint.MaximumForce = airForce; } HorizontalMotionConstraint.TargetSpeed *= SpeedScale; } SupportData TeleportToPosition(Vector3 newPosition, Fix64 dt) { Body.Position = newPosition; var orientation = Body.Orientation; //The re-do of contacts won't do anything unless we update the collidable's world transform. Body.CollisionInformation.UpdateWorldTransform(ref newPosition, ref orientation); //Refresh all the narrow phase collisions. foreach (var pair in Body.CollisionInformation.Pairs) { //Clear out the old contacts. This prevents contacts in persistent manifolds from surviving the step //Such old contacts might still have old normals which blocked the character's forward motion. pair.ClearContacts(); pair.UpdateCollision(dt); } //Also re-collect supports. //This will ensure the constraint and other velocity affectors have the most recent information available. SupportFinder.UpdateSupports(ref HorizontalMotionConstraint.movementDirection3d); return SupportFinder.SupportData; } void CorrectContacts() { //Go through the contacts associated with the character. //If the contact is at the bottom of the character, regardless of its normal, take a closer look. //If the direction from the closest point on the inner cylinder to the contact position has traction //and the contact's normal does not, then replace the contact normal with the offset direction. //This is necessary because various convex pair manifolds use persistent manifolds. //Contacts in these persistent manifolds can live too long for the character to behave perfectly //when going over (usually tiny) steps. Vector3 downDirection = Body.OrientationMatrix.Down; Vector3 position = Body.Position; Fix64 margin = Body.CollisionInformation.Shape.CollisionMargin; Fix64 minimumHeight = Body.Height * F64.C0p5 - margin; Fix64 coreRadius = Body.Radius - margin; Fix64 coreRadiusSquared = coreRadius * coreRadius; foreach (var pair in Body.CollisionInformation.Pairs) { foreach (var contactData in pair.Contacts) { var contact = contactData.Contact; Fix64 dot; //Check to see if the contact position is at the bottom of the character. Vector3 offset = contact.Position - Body.Position; Vector3.Dot(ref offset, ref downDirection, out dot); if (dot > minimumHeight) { //It is a 'bottom' contact! //So, compute the offset from the inner cylinder to the contact. //To do this, compute the closest point on the inner cylinder. //Since we know it's on the bottom, all we need is to compute the horizontal offset. Vector3.Dot(ref offset, ref downDirection, out dot); Vector3 horizontalOffset; Vector3.Multiply(ref downDirection, dot, out horizontalOffset); Vector3.Subtract(ref offset, ref horizontalOffset, out horizontalOffset); Fix64 length = horizontalOffset.LengthSquared(); if (length > coreRadiusSquared) { //It's beyond the edge of the cylinder; clamp it. Vector3.Multiply(ref horizontalOffset, coreRadius / Fix64.Sqrt(length), out horizontalOffset); } //It's on the bottom, so add the bottom height. Vector3 closestPointOnCylinder; Vector3.Multiply(ref downDirection, minimumHeight, out closestPointOnCylinder); Vector3.Add(ref closestPointOnCylinder, ref horizontalOffset, out closestPointOnCylinder); Vector3.Add(ref closestPointOnCylinder, ref position, out closestPointOnCylinder); //Compute the offset from the cylinder to the offset. Vector3 offsetDirection; Vector3.Subtract(ref contact.Position, ref closestPointOnCylinder, out offsetDirection); length = offsetDirection.LengthSquared(); if (length > Toolbox.Epsilon) { //Normalize the offset. Vector3.Divide(ref offsetDirection, Fix64.Sqrt(length), out offsetDirection); } else continue; //If there's no offset, it's really deep and correcting this contact might be a bad idea. Vector3.Dot(ref offsetDirection, ref downDirection, out dot); Fix64 dotOriginal; Vector3.Dot(ref contact.Normal, ref downDirection, out dotOriginal); if (dot > Fix64.Abs(dotOriginal)) //if the new offsetDirection normal is less steep than the original slope... { //Then use it! Vector3.Dot(ref offsetDirection, ref contact.Normal, out dot); if (dot < F64.C0) { //Don't flip the normal relative to the contact normal. That would be bad! Vector3.Negate(ref offsetDirection, out offsetDirection); dot = -dot; } //Update the contact data using the corrected information. //The penetration depth is conservatively updated; it will be less than or equal to the 'true' depth in this direction. contact.PenetrationDepth *= dot; contact.Normal = offsetDirection; } } } } } void ComputeRelativeVelocity(ref SupportData supportData, out Vector3 relativeVelocity) { //Compute the relative velocity between the body and its support, if any. //The relative velocity will be updated as impulses are applied. relativeVelocity = Body.LinearVelocity; if (SupportFinder.HasSupport) { //Only entities have velocity. var entityCollidable = supportData.SupportObject as EntityCollidable; if (entityCollidable != null) { //It's possible for the support's velocity to change due to another character jumping if the support is dynamic. //Don't let that happen while the character is computing a relative velocity! Vector3 entityVelocity; bool locked = entityCollidable.Entity.IsDynamic; if (locked) entityCollidable.Entity.Locker.Enter(); try { entityVelocity = Toolbox.GetVelocityOfPoint(supportData.Position, entityCollidable.Entity.Position, entityCollidable.Entity.LinearVelocity, entityCollidable.Entity.AngularVelocity); } finally { if (locked) entityCollidable.Entity.Locker.Exit(); } Vector3.Subtract(ref relativeVelocity, ref entityVelocity, out relativeVelocity); } } } /// <summary> /// Changes the relative velocity between the character and its support. /// </summary> /// <param name="supportData">Support data to use to jump.</param> /// <param name="velocityChange">Change to apply to the character and support relative velocity.</param> /// <param name="relativeVelocity">Relative velocity to update.</param> void ApplyJumpVelocity(ref SupportData supportData, Vector3 velocityChange, ref Vector3 relativeVelocity) { Body.LinearVelocity += velocityChange; var entityCollidable = supportData.SupportObject as EntityCollidable; if (entityCollidable != null) { if (entityCollidable.Entity.IsDynamic) { Vector3 change = velocityChange * jumpForceFactor; //Multiple characters cannot attempt to modify another entity's velocity at the same time. entityCollidable.Entity.Locker.Enter(); try { entityCollidable.Entity.LinearMomentum += change * -Body.Mass; } finally { entityCollidable.Entity.Locker.Exit(); } velocityChange += change; } } //Update the relative velocity as well. It's a ref parameter, so this update will be reflected in the calling scope. Vector3.Add(ref relativeVelocity, ref velocityChange, out relativeVelocity); } /// <summary> /// <para>Gets or sets whether the character should attempt to jump during the next update. During each update, this flag will be set to false. /// If it has traction, it will go straight up. If it doesn't have traction, but is still supported by something, it will jump in the direction of the surface normal.</para> /// <para>Setting this to true has the same effect as calling Jump. This property is primarily useful for fully resetting the physical state to avoid desynchronization, e.g. in networking.</para> /// </summary> public bool TryToJump { get; set; } /// <summary> /// <para>Jumps the character off of whatever it's currently standing on during the next update. If it has traction, it will go straight up. /// If it doesn't have traction, but is still supported by something, it will jump in the direction of the surface normal.</para> /// <para>The same effect can be achieved by setting TryToJump to true.</para> /// </summary> public void Jump() { //The actual jump velocities are applied next frame. This ensures that gravity doesn't pre-emptively slow the jump, and uses more //up-to-date support data. TryToJump = true; } public override void OnAdditionToSpace(Space newSpace) { //Add any supplements to the space too. newSpace.Add(Body); newSpace.Add(HorizontalMotionConstraint); newSpace.Add(VerticalMotionConstraint); //This character controller requires the standard implementation of Space. newSpace.BoundingBoxUpdater.Finishing += ExpandBoundingBox; Body.AngularVelocity = new Vector3(); Body.LinearVelocity = new Vector3(); } public override void OnRemovalFromSpace(Space oldSpace) { //Remove any supplements from the space too. oldSpace.Remove(Body); oldSpace.Remove(HorizontalMotionConstraint); oldSpace.Remove(VerticalMotionConstraint); //This character controller requires the standard implementation of Space. oldSpace.BoundingBoxUpdater.Finishing -= ExpandBoundingBox; SupportFinder.ClearSupportData(); Body.AngularVelocity = new Vector3(); Body.LinearVelocity = new Vector3(); } } }
412
0.943986
1
0.943986
game-dev
MEDIA
0.989697
game-dev
0.962085
1
0.962085
davidly/cpm_compilers
13,008
hisoft hi-tech c v3.09/TTT.C
/* This version builds with old compilers including: Aztec C 1.06 for 8080 & Z80 on CP/M. Microsoft C Compiler V1.04 for 8086 on DOS. (This is Lattice C) Microsoft C Compiler V2.03 for 8086 on DOS. (Still Lattice C) Microsoft C Compiler V3.00 for 8086 on DOS. QuickC 1.0 Turbo C 2.0 The syntax is old and reminds me of 7th grade summer vacation. Much of this code is awkward to satisfy the lowest common denominator of many compilers. unsigned long isn't supported in many older compilers, so long is used instead. Early DOS and CP/M require register variabes to be int, not char or other types. The perf improvement of using register-int instead of stack-char is worth it. */ #define LINT_ARGS #include <stdio.h> #ifdef DOSTIME #include <time.h> #include <dos.h> #endif #define true 1 #define false 0 /* Function Pointers are the fastest implementation for almost every compiler */ #define UseFunPointers 1 #define UseWinner2 2 #define UseLookForWinner 3 #define WinMethod UseFunPointers #define ABPrune true /* alpha beta pruning */ #define WinLosePrune true /* stop early on win/lose */ #define ScoreWin 6 #define ScoreTie 5 #define ScoreLose 4 #define ScoreMax 9 #define ScoreMin 2 #define DefaultIterations 1 #define PieceX 1 #define PieceO 2 #define PieceBlank 0 #ifdef AZTECCPM /* another exception: aztec C for CP/M, which does all char computations as promoted 2-byte integers with range 0-255. It's slightly faster to just use int and avoid the promotions. */ typedef int ttype; #else typedef char ttype; /* 8-bit and 16-bit cpus do best with char aside from register in locals */ #endif int g_Iterations = DefaultIterations; ttype g_board[ 9 ]; #if WinMethod == UseFunPointers ttype pos0func() { /* using "register int" instead of "ttype" for x is faster on 8086 and Z80 */ register int x = g_board[0]; if ( ( x == g_board[1] && x == g_board[2] ) || ( x == g_board[3] && x == g_board[6] ) || ( x == g_board[4] && x == g_board[8] ) ) return x; return PieceBlank; } ttype pos1func() { register int x = g_board[1]; if ( ( x == g_board[0] && x == g_board[2] ) || ( x == g_board[4] && x == g_board[7] ) ) return x; return PieceBlank; } ttype pos2func() { register int x = g_board[2]; if ( ( x == g_board[0] && x == g_board[1] ) || ( x == g_board[5] && x == g_board[8] ) || ( x == g_board[4] && x == g_board[6] ) ) return x; return PieceBlank; } ttype pos3func() { register int x = g_board[3]; if ( ( x == g_board[4] && x == g_board[5] ) || ( x == g_board[0] && x == g_board[6] ) ) return x; return PieceBlank; } ttype pos4func() { register int x = g_board[4]; if ( ( x == g_board[0] && x == g_board[8] ) || ( x == g_board[2] && x == g_board[6] ) || ( x == g_board[1] && x == g_board[7] ) || ( x == g_board[3] && x == g_board[5] ) ) return x; return PieceBlank; } ttype pos5func() { register int x = g_board[5]; if ( ( x == g_board[3] && x == g_board[4] ) || ( x == g_board[2] && x == g_board[8] ) ) return x; return PieceBlank; } ttype pos6func() { register int x = g_board[6]; if ( ( x == g_board[7] && x == g_board[8] ) || ( x == g_board[0] && x == g_board[3] ) || ( x == g_board[4] && x == g_board[2] ) ) return x; return PieceBlank; } ttype pos7func() { register int x = g_board[7]; if ( ( x == g_board[6] && x == g_board[8] ) || ( x == g_board[1] && x == g_board[4] ) ) return x; return PieceBlank; } ttype pos8func() { register int x = g_board[8]; if ( ( x == g_board[6] && x == g_board[7] ) || ( x == g_board[2] && x == g_board[5] ) || ( x == g_board[0] && x == g_board[4] ) ) return x; return PieceBlank; } typedef ttype pfunc_t(); pfunc_t * winner_functions[9] = { pos0func, pos1func, pos2func, pos3func, pos4func, pos5func, pos6func, pos7func, pos8func, }; #endif #if WinMethod == UseWinner2 ttype winner2( move ) ttype move; { register int x; /* faster than ttype x on the stack */ switch( move ) /* msc v3 from 1985 generates a jump table! */ { case 0: { x = g_board[ 0 ]; if ( ( ( x == g_board[1] ) && ( x == g_board[2] ) ) || ( ( x == g_board[3] ) && ( x == g_board[6] ) ) || ( ( x == g_board[4] ) && ( x == g_board[8] ) ) ) return x; break; } case 1: { x = g_board[ 1 ]; if ( ( ( x == g_board[0] ) && ( x == g_board[2] ) ) || ( ( x == g_board[4] ) && ( x == g_board[7] ) ) ) return x; break; } case 2: { x = g_board[ 2 ]; if ( ( ( x == g_board[0] ) && ( x == g_board[1] ) ) || ( ( x == g_board[5] ) && ( x == g_board[8] ) ) || ( ( x == g_board[4] ) && ( x == g_board[6] ) ) ) return x; break; } case 3: { x = g_board[ 3 ]; if ( ( ( x == g_board[4] ) && ( x == g_board[5] ) ) || ( ( x == g_board[0] ) && ( x == g_board[6] ) ) ) return x; break; } case 4: { x = g_board[ 4 ]; if ( ( ( x == g_board[0] ) && ( x == g_board[8] ) ) || ( ( x == g_board[2] ) && ( x == g_board[6] ) ) || ( ( x == g_board[1] ) && ( x == g_board[7] ) ) || ( ( x == g_board[3] ) && ( x == g_board[5] ) ) ) return x; break; } case 5: { x = g_board[ 5 ]; if ( ( ( x == g_board[3] ) && ( x == g_board[4] ) ) || ( ( x == g_board[2] ) && ( x == g_board[8] ) ) ) return x; break; } case 6: { x = g_board[ 6 ]; if ( ( ( x == g_board[7] ) && ( x == g_board[8] ) ) || ( ( x == g_board[0] ) && ( x == g_board[3] ) ) || ( ( x == g_board[4] ) && ( x == g_board[2] ) ) ) return x; break; } case 7: { x = g_board[ 7 ]; if ( ( ( x == g_board[6] ) && ( x == g_board[8] ) ) || ( ( x == g_board[1] ) && ( x == g_board[4] ) ) ) return x; break; } case 8: { x = g_board[ 8 ]; if ( ( ( x == g_board[6] ) && ( x == g_board[7] ) ) || ( ( x == g_board[2] ) && ( x == g_board[5] ) ) || ( ( x == g_board[0] ) && ( x == g_board[4] ) ) ) return x; break; } } return PieceBlank; } /*winner2*/ #endif #if WinMethod == UseLookForWinner ttype LookForWinner() { register int p = g_board[0]; /* faster as register int than ttype on 8086 and Z80 */ if ( PieceBlank != p ) { if ( p == g_board[1] && p == g_board[2] ) return p; if ( p == g_board[3] && p == g_board[6] ) return p; } p = g_board[3]; if ( PieceBlank != p && p == g_board[4] && p == g_board[5] ) return p; p = g_board[6]; if ( PieceBlank != p && p == g_board[7] && p == g_board[8] ) return p; p = g_board[1]; if ( PieceBlank != p && p == g_board[4] && p == g_board[7] ) return p; p = g_board[2]; if ( PieceBlank != p && p == g_board[5] && p == g_board[8] ) return p; p = g_board[4]; if ( PieceBlank != p ) { if ( ( p == g_board[0] ) && ( p == g_board[8] ) ) return p; if ( ( p == g_board[2] ) && ( p == g_board[6] ) ) return p; } return PieceBlank; } /*LookForWinner*/ #endif int g_IMoves = 0; ttype MinMax( alpha, beta, depth, move ) ttype alpha; ttype beta; ttype depth; ttype move; { ttype pieceMove, score; /* better perf with char than int. out of registers so use stack */ register int p, value; /* better perf with these as an int on Z80, 8080, and 8086 */ g_IMoves++; if ( depth >= 4 ) { #if WinMethod == UseFunPointers p = ( * winner_functions[ move ] )(); #endif #if WinMethod == UseWinner2 p = winner2( move ); #endif #if WinMethod == UseLookForWinner p = LookForWinner(); #endif if ( PieceBlank != p ) { if ( PieceX == p ) return ScoreWin; return ScoreLose; } if ( 8 == depth ) return ScoreTie; } if ( depth & 1 ) { value = ScoreMin; pieceMove = PieceX; } else { value = ScoreMax; pieceMove = PieceO; } for ( p = 0; p < 9; p++ ) { if ( PieceBlank == g_board[ p ] ) { g_board[p] = pieceMove; score = MinMax( alpha, beta, depth + 1, p ); g_board[p] = PieceBlank; if ( depth & 1 ) { #if WinLosePrune /* #if statements must be in first column for MS C 1.0 */ if ( ScoreWin == score ) return ScoreWin; #endif if ( score > value ) { value = score; #if ABPrune if ( value >= beta ) return value; if ( value > alpha ) alpha = value; #endif } } else { #if WinLosePrune if ( ScoreLose == score ) return ScoreLose; #endif if ( score < value ) { value = score; #if ABPrune if ( value <= alpha ) return value; if ( value < beta ) beta = value; #endif } } } } return value; } /*MinMax*/ long g_Moves = 0; int FindSolution( position ) ttype position; { register int i; for ( i = 0; i < 9; i++ ) g_board[ i ] = PieceBlank; g_board[ position ] = PieceX; for ( i = 0; i < g_Iterations; i++ ) { g_IMoves = 0; MinMax( ScoreMin, ScoreMax, 0, position ); g_Moves += g_IMoves; /* do the 4-byte long addition once per loop to save work */ } return 0; } /*FindSolution*/ #ifdef CPMTIME struct CPMTimeValue { int h, m, s, l; }; void print_time_now() { /* This CP/M BDOS call of 180 is only implemented in NTVCM -- it's not a standard CP/M 2.2 call */ struct CPMTimeValue t; t.h = t.m = t.s = t.l = 0; bdos( 180, &t ); printf( "current time: %02d:%02d:%02d.%02d\n", t.h, t.m, t.s, t.l ); } /*print_time_now*/ long get_ms() { /* This CP/M BDOS call of 180 is only implemented in NTVCM -- it's not a standard CP/M 2.2 call */ long h, m, s, l; struct CPMTimeValue t; t.h = t.m = t.s = t.l = 0; bdos( 180, &t ); h = t.h; m = t.m; s = t.s; l = t.l; return h * 3600000 + m * 60000 + s * 1000 + l * 10; } /*get_ms*/ #else /* no elif with old compilers */ #ifdef DOSTIME void print_time_now() { /* Make a DOS interrupt call to get the time */ union REGS wrIn, wrOut; wrIn.h.ah = 0x2c; intdos( &wrIn, &wrOut ); printf( "current time: %02d:%02d:%02d.%02d\n", wrOut.h.ch, wrOut.h.cl, wrOut.h.dh, wrOut.h.dl ); fflush( stdout ); } /*print_time_now*/ long get_ms() { /* this function takes about 3 milliseconds on the original IBM PC */ long h, m, s, l; union REGS wrIn, wrOut; wrIn.h.ah = 0x2c; intdos( &wrIn, &wrOut ); h = wrOut.h.ch; m = wrOut.h.cl; s = wrOut.h.dh; l = wrOut.h.dl; return h * 3600000 + m * 60000 + s * 1000 + l * 10; } /*get_ms*/ #else /* must do this on actual CP/M machines */ int print_time_now() { return 0; } long get_ms() { return 0; } #endif #endif int main( argc, argv ) int argc; char * argv[]; { long start_time, end_time; if ( 2 == argc ) sscanf( argv[ 1 ], "%d", &g_Iterations ); /* no atoi in MS C 1.0 */ printf( "starting\n" ); start_time = get_ms(); FindSolution( 0 ); FindSolution( 1 ); FindSolution( 4 ); end_time = get_ms(); printf( "runtime in ms: %ld\n", end_time - start_time ); printf( "move count: %ld\n", g_Moves ); /* 6493 * g_Iterations */ printf( "iteration count: %d\n", g_Iterations ); printf( "method: %s\n", ( WinMethod == UseFunPointers ) ? "function pointers" : ( WinMethod == UseWinner2 ) ? "winner2" : ( WinMethod == UseLookForWinner ) ? "look for winner" : "invalid method" ); return 0; } /*main*/
412
0.808461
1
0.808461
game-dev
MEDIA
0.426495
game-dev,embedded-firmware
0.900058
1
0.900058
ErichStyger/mcuoneclipse
3,829
Examples/KDS/FRDM-K64F120M/FRDM-K64F_Zork/Sources/Zork/dso2.c
/* MOVETO- MOVE PLAYER TO NEW ROOM */ /*COPYRIGHT 1980, INFOCOM COMPUTERS AND COMMUNICATIONS, CAMBRIDGE MA. 02142*/ /* ALL RIGHTS RESERVED, COMMERCIAL USAGE STRICTLY PROHIBITED */ /* WRITTEN BY R. M. SUPNIK */ #include <stdio.h> #include "funcs.h" #include "vars.h" logical moveto_(nr, who) integer nr; integer who; { /* System generated locals */ logical ret_val; /* Local variables */ integer j; logical lhr; logical lnr, nlv; integer bits; ret_val = FALSE_; /* !ASSUME FAILS. */ lhr = (rooms_1.rflag[play_1.here - 1] & RLAND) != 0; lnr = (rooms_1.rflag[nr - 1] & RLAND) != 0; j = advs_1.avehic[who - 1]; /* !HIS VEHICLE */ if (j != 0) { goto L100; } /* !IN VEHICLE? */ if (lnr) { goto L500; } /* !NO, GOING TO LAND? */ rspeak_(427); /* !CAN'T GO WITHOUT VEHICLE. */ return ret_val; L100: bits = 0; /* !ASSUME NOWHERE. */ if (j == oindex_1.rboat) { bits = RWATER; } /* !IN BOAT? */ if (j == oindex_1.ballo) { bits = RAIR; } /* !IN BALLOON? */ if (j == oindex_1.bucke) { bits = RBUCK; } /* !IN BUCKET? */ nlv = (rooms_1.rflag[nr - 1] & bits) == 0; if (! lnr && nlv || lnr && lhr && nlv && bits != RLAND) { goto L800; } L500: ret_val = TRUE_; /* !MOVE SHOULD SUCCEED. */ if ((rooms_1.rflag[nr - 1] & RMUNG) == 0) { goto L600; } rspeak_(rrand[nr - 1]); /* !YES, TELL HOW. */ return ret_val; L600: if (who != aindex_1.player) { newsta_(advs_1.aobj[who - 1], 0, nr, 0, 0); } if (j != 0) { newsta_(j, 0, nr, 0, 0); } play_1.here = nr; advs_1.aroom[who - 1] = play_1.here; scrupd_(rooms_1.rval[nr - 1]); /* !SCORE ROOM */ rooms_1.rval[nr - 1] = 0; return ret_val; L800: rspsub_(428, objcts_1.odesc2[j - 1]); /* !WRONG VEHICLE. */ return ret_val; } /* moveto_ */ /* SCORE-- PRINT OUT CURRENT SCORE */ /* DECLARATIONS */ void score_(flg) logical flg; { /* Initialized data */ static const integer rank[10] = { 20,19,18,16,12,8,4,2,1,0 }; static const integer erank[5] = { 20,15,10,5,0 }; /* System generated locals */ integer i__1; /* Local variables */ integer i, as; as = advs_1.ascore[play_1.winner - 1]; if (findex_1.endgmf) { goto L60; } /* !ENDGAME? */ more_output(NULL); printf("Your score "); if (flg) printf("would be"); else printf("is"); printf(" %d [total of %d points], in %d move", as, state_1.mxscor, state_1.moves); if (state_1.moves != 1) printf("s"); printf(".\n"); for (i = 1; i <= 10; ++i) { if (as * 20 / state_1.mxscor >= rank[i - 1]) { goto L50; } /* L10: */ } L50: i__1 = i + 484; rspeak_(i__1); return; L60: more_output(NULL); printf("Your score in the endgame "); if (flg) printf("would be"); else printf("is"); printf(" %d [total of %d points], in %d moves.\n", state_1.egscor, state_1.egmxsc, state_1.moves); for (i = 1; i <= 5; ++i) { if (state_1.egscor * 20 / state_1.egmxsc >= erank[i - 1]) { goto L80; } /* L70: */ } L80: i__1 = i + 786; rspeak_(i__1); } /* score_ */ /* SCRUPD- UPDATE WINNER'S SCORE */ /* DECLARATIONS */ void scrupd_(n) integer n; { if (findex_1.endgmf) { goto L100; } /* !ENDGAME? */ advs_1.ascore[play_1.winner - 1] += n; /* !UPDATE SCORE */ state_1.rwscor += n; /* !UPDATE RAW SCORE */ if (advs_1.ascore[play_1.winner - 1] < state_1.mxscor - state_1.deaths * 10) { return; } cevent_1.cflag[cindex_1.cevegh - 1] = TRUE_; /* !TURN ON END GAME */ cevent_1.ctick[cindex_1.cevegh - 1] = 15; return; L100: state_1.egscor += n; /* !UPDATE EG SCORE. */ } /* scrupd_ */
412
0.74109
1
0.74109
game-dev
MEDIA
0.653931
game-dev
0.968886
1
0.968886
LinkedInLearning/complete-guide-to-cpp-programming-foundations-3846057
1,070
src/Ch07/07_07e/CodeDemo.cpp
// Complete Guide to C++ Programming Foundations // Exercise 07_07 // Using Several Source Files, by Eduardo Corpeño #include "inventory.h" #include <iostream> int main(){ // Create an inventory with capacity of 5 items Inventory myInventory(5); // Add 5 items myInventory.addItem("Health Potion"); myInventory.addItem("Mana Potion"); myInventory.addItem("Sword"); myInventory.addItem("Shield"); myInventory.addItem("Bow"); // Display current inventory myInventory.displayInventory(); // Try to add another item when inventory is full myInventory.addItem("Arrow"); // Remove an item myInventory.removeItem("Mana Potion"); // Display the item count std::cout << "The inventory now contains: " << myInventory.getItemCount() << " items." << std::endl; // Access item by index std::cout << "Item at index 2: " << myInventory.getItem(2) << std::endl; // Display final state of inventory myInventory.displayInventory(); std::cout << std::endl << std::endl; return 0; }
412
0.530567
1
0.530567
game-dev
MEDIA
0.482217
game-dev
0.528613
1
0.528613
RetroAchievements/RAEmus
38,559
RASnes9x/win32/InputCustom.cpp
/*********************************************************************************** Snes9x - Portable Super Nintendo Entertainment System (TM) emulator. (c) Copyright 1996 - 2002 Gary Henderson (gary.henderson@ntlworld.com), Jerremy Koot (jkoot@snes9x.com) (c) Copyright 2002 - 2004 Matthew Kendora (c) Copyright 2002 - 2005 Peter Bortas (peter@bortas.org) (c) Copyright 2004 - 2005 Joel Yliluoma (http://iki.fi/bisqwit/) (c) Copyright 2001 - 2006 John Weidman (jweidman@slip.net) (c) Copyright 2002 - 2006 funkyass (funkyass@spam.shaw.ca), Kris Bleakley (codeviolation@hotmail.com) (c) Copyright 2002 - 2010 Brad Jorsch (anomie@users.sourceforge.net), Nach (n-a-c-h@users.sourceforge.net), (c) Copyright 2002 - 2011 zones (kasumitokoduck@yahoo.com) (c) Copyright 2006 - 2007 nitsuja (c) Copyright 2009 - 2011 BearOso, OV2 BS-X C emulator code (c) Copyright 2005 - 2006 Dreamer Nom, zones C4 x86 assembler and some C emulation code (c) Copyright 2000 - 2003 _Demo_ (_demo_@zsnes.com), Nach, zsKnight (zsknight@zsnes.com) C4 C++ code (c) Copyright 2003 - 2006 Brad Jorsch, Nach DSP-1 emulator code (c) Copyright 1998 - 2006 _Demo_, Andreas Naive (andreasnaive@gmail.com), Gary Henderson, Ivar (ivar@snes9x.com), John Weidman, Kris Bleakley, Matthew Kendora, Nach, neviksti (neviksti@hotmail.com) DSP-2 emulator code (c) Copyright 2003 John Weidman, Kris Bleakley, Lord Nightmare (lord_nightmare@users.sourceforge.net), Matthew Kendora, neviksti DSP-3 emulator code (c) Copyright 2003 - 2006 John Weidman, Kris Bleakley, Lancer, z80 gaiden DSP-4 emulator code (c) Copyright 2004 - 2006 Dreamer Nom, John Weidman, Kris Bleakley, Nach, z80 gaiden OBC1 emulator code (c) Copyright 2001 - 2004 zsKnight, pagefault (pagefault@zsnes.com), Kris Bleakley Ported from x86 assembler to C by sanmaiwashi SPC7110 and RTC C++ emulator code used in 1.39-1.51 (c) Copyright 2002 Matthew Kendora with research by zsKnight, John Weidman, Dark Force SPC7110 and RTC C++ emulator code used in 1.52+ (c) Copyright 2009 byuu, neviksti S-DD1 C emulator code (c) Copyright 2003 Brad Jorsch with research by Andreas Naive, John Weidman S-RTC C emulator code (c) Copyright 2001 - 2006 byuu, John Weidman ST010 C++ emulator code (c) Copyright 2003 Feather, John Weidman, Kris Bleakley, Matthew Kendora Super FX x86 assembler emulator code (c) Copyright 1998 - 2003 _Demo_, pagefault, zsKnight Super FX C emulator code (c) Copyright 1997 - 1999 Ivar, Gary Henderson, John Weidman Sound emulator code used in 1.5-1.51 (c) Copyright 1998 - 2003 Brad Martin (c) Copyright 1998 - 2006 Charles Bilyue' Sound emulator code used in 1.52+ (c) Copyright 2004 - 2007 Shay Green (gblargg@gmail.com) SH assembler code partly based on x86 assembler code (c) Copyright 2002 - 2004 Marcus Comstedt (marcus@mc.pp.se) 2xSaI filter (c) Copyright 1999 - 2001 Derek Liauw Kie Fa HQ2x, HQ3x, HQ4x filters (c) Copyright 2003 Maxim Stepin (maxim@hiend3d.com) NTSC filter (c) Copyright 2006 - 2007 Shay Green GTK+ GUI code (c) Copyright 2004 - 2011 BearOso Win32 GUI code (c) Copyright 2003 - 2006 blip, funkyass, Matthew Kendora, Nach, nitsuja (c) Copyright 2009 - 2011 OV2 Mac OS GUI code (c) Copyright 1998 - 2001 John Stiles (c) Copyright 2001 - 2011 zones Specific ports contains the works of other authors. See headers in individual files. Snes9x homepage: http://www.snes9x.com/ Permission to use, copy, modify and/or distribute Snes9x in both binary and source form, for non-commercial purposes, is hereby granted without fee, providing that this license information and copyright notice appear with all copies and any derived work. This software is provided 'as-is', without any express or implied warranty. In no event shall the authors be held liable for any damages arising from the use of this software or it's derivatives. Snes9x is freeware for PERSONAL USE only. Commercial users should seek permission of the copyright holders first. Commercial use includes, but is not limited to, charging money for Snes9x or software derived from Snes9x, including Snes9x or derivatives in commercial game bundles, and/or using Snes9x as a promotion for your commercial product. The copyright holders request that bug fixes and improvements to the code should be forwarded to them so everyone can benefit from the modifications in future versions. Super NES and Super Nintendo Entertainment System are trademarks of Nintendo Co., Limited and its subsidiary companies. ***********************************************************************************/ #ifdef __MINGW32__ #define _WIN32_IE 0x0501 #define _WIN32_WINNT 0x0501 #endif #define STRICT #include <windows.h> #include <io.h> #if (((defined(_MSC_VER) && _MSC_VER >= 1300)) || defined(__MINGW32__)) // both MINGW and VS.NET use fstream instead of fstream.h which is deprecated #include <fstream> using namespace std; #else // for VC++ 6 #include <fstream.h> #endif #include "InputCustom.h" #include "wsnes9x.h" #include "wlanguage.h" static TCHAR szClassName[] = _T("InputCustom"); static TCHAR szHotkeysClassName[] = _T("InputCustomHot"); static LRESULT CALLBACK InputCustomWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK HotInputCustomWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); extern SJoyState JoystickF [16]; HWND funky; //WPARAM tid; void JoystickChanged( short ID, short Movement) { // don't allow two changes to happen too close together in time { static bool first = true; static DWORD lastTime = 0; if(first || timeGetTime() - lastTime > 300) // 0.3 seconds { first = false; lastTime = timeGetTime(); } else { return; // too soon after last change } } WORD JoyKey; JoyKey = 0x8000; JoyKey |= (WORD)(ID << 8); JoyKey |= Movement; SendMessage(funky,WM_USER+45,JoyKey,0); // KillTimer(funky,tid); } int FunkyNormalize(int cur, int min, int max) { int Result = 0; if ((max - min) == 0) return (Result); Result = cur - min; Result = (Result * 200) / (max - min); Result -= 100; return Result; } void CheckAxis (short joy, short control, int val, int min, int max, bool &first, bool &second) { if (FunkyNormalize (val, min, max) < -S9X_JOY_NEUTRAL) { second = false; if (!first) { JoystickChanged (joy, control); first = true; } } else first = false; if (FunkyNormalize (val, min, max) > S9X_JOY_NEUTRAL) { first = false; if (!second) { JoystickChanged (joy, (short) (control + 1)); second = true; } } else second = false; } void FunkyJoyStickTimer() { JOYINFOEX jie; for (short C = 0; C != 16; C ++) { jie.dwSize = sizeof( jie); jie.dwFlags = JOY_RETURNALL; if (joyGetPosEx (JOYSTICKID1 + C, &jie) != JOYERR_NOERROR) continue; CheckAxis (C, 0, jie.dwXpos, JoystickF[C].Caps.wXmin, JoystickF[C].Caps.wXmax, JoystickF[C].Left, JoystickF[C].Right); CheckAxis (C, 2, jie.dwYpos, JoystickF[C].Caps.wYmin, JoystickF[C].Caps.wYmax, JoystickF[C].Up, JoystickF[C].Down); if(JoystickF[C].Caps.wCaps & JOYCAPS_HASZ) { CheckAxis (C, 41, jie.dwZpos, JoystickF[C].Caps.wZmin, JoystickF[C].Caps.wZmax, JoystickF[C].ZUp, JoystickF[C].ZDown); } if(JoystickF[C].Caps.wCaps & JOYCAPS_HASR) { CheckAxis (C, 43, jie.dwRpos, JoystickF[C].Caps.wRmin, JoystickF[C].Caps.wRmax, JoystickF[C].RUp, JoystickF[C].RDown); } if(JoystickF[C].Caps.wCaps & JOYCAPS_HASU) { CheckAxis (C, 45, jie.dwUpos, JoystickF[C].Caps.wUmin, JoystickF[C].Caps.wUmax, JoystickF[C].UUp, JoystickF[C].UDown); } if(JoystickF[C].Caps.wCaps & JOYCAPS_HASV) { CheckAxis (C, 47, jie.dwVpos, JoystickF[C].Caps.wVmin, JoystickF[C].Caps.wVmax, JoystickF[C].VUp, JoystickF[C].VDown); } switch (jie.dwPOV) { case JOY_POVBACKWARD: if( !JoystickF[C].PovDown) { JoystickChanged( C, 7); } JoystickF[C].PovDown = true; JoystickF[C].PovUp = false; JoystickF[C].PovLeft = false; JoystickF[C].PovRight = false; JoystickF[C].PovDnLeft = false; JoystickF[C].PovDnRight = false; JoystickF[C].PovUpLeft = false; JoystickF[C].PovUpRight = false; break; case 4500: if( !JoystickF[C].PovUpRight) { JoystickChanged( C, 52); } JoystickF[C].PovDown = false; JoystickF[C].PovUp = false; JoystickF[C].PovLeft = false; JoystickF[C].PovRight = false; JoystickF[C].PovDnLeft = false; JoystickF[C].PovDnRight = false; JoystickF[C].PovUpLeft = false; JoystickF[C].PovUpRight = true; break; case 13500: if( !JoystickF[C].PovDnRight) { JoystickChanged( C, 50); } JoystickF[C].PovDown = false; JoystickF[C].PovUp = false; JoystickF[C].PovLeft = false; JoystickF[C].PovRight = false; JoystickF[C].PovDnLeft = false; JoystickF[C].PovDnRight = true; JoystickF[C].PovUpLeft = false; JoystickF[C].PovUpRight = false; break; case 22500: if( !JoystickF[C].PovDnLeft) { JoystickChanged( C, 49); } JoystickF[C].PovDown = false; JoystickF[C].PovUp = false; JoystickF[C].PovLeft = false; JoystickF[C].PovRight = false; JoystickF[C].PovDnLeft = true; JoystickF[C].PovDnRight = false; JoystickF[C].PovUpLeft = false; JoystickF[C].PovUpRight = false; break; case 31500: if( !JoystickF[C].PovUpLeft) { JoystickChanged( C, 51); } JoystickF[C].PovDown = false; JoystickF[C].PovUp = false; JoystickF[C].PovLeft = false; JoystickF[C].PovRight = false; JoystickF[C].PovDnLeft = false; JoystickF[C].PovDnRight = false; JoystickF[C].PovUpLeft = true; JoystickF[C].PovUpRight = false; break; case JOY_POVFORWARD: if( !JoystickF[C].PovUp) { JoystickChanged( C, 6); } JoystickF[C].PovDown = false; JoystickF[C].PovUp = true; JoystickF[C].PovLeft = false; JoystickF[C].PovRight = false; JoystickF[C].PovDnLeft = false; JoystickF[C].PovDnRight = false; JoystickF[C].PovUpLeft = false; JoystickF[C].PovUpRight = false; break; case JOY_POVLEFT: if( !JoystickF[C].PovLeft) { JoystickChanged( C, 4); } JoystickF[C].PovDown = false; JoystickF[C].PovUp = false; JoystickF[C].PovLeft = true; JoystickF[C].PovRight = false; JoystickF[C].PovDnLeft = false; JoystickF[C].PovDnRight = false; JoystickF[C].PovUpLeft = false; JoystickF[C].PovUpRight = false; break; case JOY_POVRIGHT: if( !JoystickF[C].PovRight) { JoystickChanged( C, 5); } JoystickF[C].PovDown = false; JoystickF[C].PovUp = false; JoystickF[C].PovLeft = false; JoystickF[C].PovRight = true; JoystickF[C].PovDnLeft = false; JoystickF[C].PovDnRight = false; JoystickF[C].PovUpLeft = false; JoystickF[C].PovUpRight = false; break; default: JoystickF[C].PovDown = false; JoystickF[C].PovUp = false; JoystickF[C].PovLeft = false; JoystickF[C].PovRight = false; JoystickF[C].PovDnLeft = false; JoystickF[C].PovDnRight = false; JoystickF[C].PovUpLeft = false; JoystickF[C].PovUpRight = false; break; } for( short B = 0; B != 32; B ++, jie.dwButtons >>= 1) if( (jie.dwButtons&1)) { if( !JoystickF[C].Button[B]) { JoystickChanged( C, (short)(8+B)); JoystickF[C].Button[B] = true; } } else { JoystickF[C].Button[B] = false; } } } void TranslateKey(WORD keyz,char *out) { // sprintf(out,"%d",keyz); // return; char temp[128]; if(keyz&0x8000) { sprintf(out,GAMEDEVICE_JOYNUMPREFIX,((keyz>>8)&0xF)); switch(keyz&0xFF) { case 0: strcat(out,GAMEDEVICE_XNEG); break; case 1: strcat(out,GAMEDEVICE_XPOS); break; case 2: strcat(out,GAMEDEVICE_YPOS); break; case 3: strcat(out,GAMEDEVICE_YNEG); break; case 4: strcat(out,GAMEDEVICE_POVLEFT); break; case 5: strcat(out,GAMEDEVICE_POVRIGHT); break; case 6: strcat(out,GAMEDEVICE_POVUP); break; case 7: strcat(out,GAMEDEVICE_POVDOWN); break; case 49: strcat(out,GAMEDEVICE_POVDNLEFT); break; case 50: strcat(out,GAMEDEVICE_POVDNRIGHT); break; case 51: strcat(out,GAMEDEVICE_POVUPLEFT); break; case 52: strcat(out,GAMEDEVICE_POVUPRIGHT); break; case 41: strcat(out,GAMEDEVICE_ZPOS); break; case 42: strcat(out,GAMEDEVICE_ZNEG); break; case 43: strcat(out,GAMEDEVICE_RPOS); break; case 44: strcat(out,GAMEDEVICE_RNEG); break; case 45: strcat(out,GAMEDEVICE_UPOS); break; case 46: strcat(out,GAMEDEVICE_UNEG); break; case 47: strcat(out,GAMEDEVICE_VPOS); break; case 48: strcat(out,GAMEDEVICE_VNEG); break; default: if ((keyz & 0xff) > 40) { sprintf(temp,GAMEDEVICE_JOYBUTPREFIX,keyz&0xFF); strcat(out,temp); break; } sprintf(temp,GAMEDEVICE_BUTTON,(keyz&0xFF)-8); strcat(out,temp); break; } return; } sprintf(out,GAMEDEVICE_KEY,keyz); if((keyz>='0' && keyz<='9')||(keyz>='A' &&keyz<='Z')) { sprintf(out,"%c",keyz); return; } if( keyz >= VK_NUMPAD0 && keyz <= VK_NUMPAD9) { sprintf(out,GAMEDEVICE_NUMPADPREFIX,'0'+(keyz-VK_NUMPAD0)); return ; } switch(keyz) { case 0: sprintf(out,GAMEDEVICE_DISABLED); break; case VK_TAB: sprintf(out,GAMEDEVICE_VK_TAB); break; case VK_BACK: sprintf(out,GAMEDEVICE_VK_BACK); break; case VK_CLEAR: sprintf(out,GAMEDEVICE_VK_CLEAR); break; case VK_RETURN: sprintf(out,GAMEDEVICE_VK_RETURN); break; case VK_LSHIFT: sprintf(out,GAMEDEVICE_VK_LSHIFT); break; case VK_RSHIFT: sprintf(out,GAMEDEVICE_VK_RSHIFT); break; case VK_LCONTROL: sprintf(out,GAMEDEVICE_VK_LCONTROL); break; case VK_RCONTROL: sprintf(out,GAMEDEVICE_VK_RCONTROL); break; case VK_LMENU: sprintf(out,GAMEDEVICE_VK_LMENU); break; case VK_RMENU: sprintf(out,GAMEDEVICE_VK_RMENU); break; case VK_PAUSE: sprintf(out,GAMEDEVICE_VK_PAUSE); break; case VK_CANCEL: sprintf(out,GAMEDEVICE_VK_PAUSE); break; // the Pause key can resolve to either "Pause" or "Cancel" depending on when it's pressed case VK_CAPITAL: sprintf(out,GAMEDEVICE_VK_CAPITAL); break; case VK_ESCAPE: sprintf(out,GAMEDEVICE_VK_ESCAPE); break; case VK_SPACE: sprintf(out,GAMEDEVICE_VK_SPACE); break; case VK_PRIOR: sprintf(out,GAMEDEVICE_VK_PRIOR); break; case VK_NEXT: sprintf(out,GAMEDEVICE_VK_NEXT); break; case VK_HOME: sprintf(out,GAMEDEVICE_VK_HOME); break; case VK_END: sprintf(out,GAMEDEVICE_VK_END); break; case VK_LEFT: sprintf(out,GAMEDEVICE_VK_LEFT ); break; case VK_RIGHT: sprintf(out,GAMEDEVICE_VK_RIGHT); break; case VK_UP: sprintf(out,GAMEDEVICE_VK_UP); break; case VK_DOWN: sprintf(out,GAMEDEVICE_VK_DOWN); break; case VK_SELECT: sprintf(out,GAMEDEVICE_VK_SELECT); break; case VK_PRINT: sprintf(out,GAMEDEVICE_VK_PRINT); break; case VK_EXECUTE: sprintf(out,GAMEDEVICE_VK_EXECUTE); break; case VK_SNAPSHOT: sprintf(out,GAMEDEVICE_VK_SNAPSHOT); break; case VK_INSERT: sprintf(out,GAMEDEVICE_VK_INSERT); break; case VK_DELETE: sprintf(out,GAMEDEVICE_VK_DELETE); break; case VK_HELP: sprintf(out,GAMEDEVICE_VK_HELP); break; case VK_LWIN: sprintf(out,GAMEDEVICE_VK_LWIN); break; case VK_RWIN: sprintf(out,GAMEDEVICE_VK_RWIN); break; case VK_APPS: sprintf(out,GAMEDEVICE_VK_APPS); break; case VK_MULTIPLY: sprintf(out,GAMEDEVICE_VK_MULTIPLY); break; case VK_ADD: sprintf(out,GAMEDEVICE_VK_ADD); break; case VK_SEPARATOR: sprintf(out,GAMEDEVICE_VK_SEPARATOR); break; case /*VK_OEM_1*/0xBA: sprintf(out,GAMEDEVICE_VK_OEM_1); break; case /*VK_OEM_2*/0xBF: sprintf(out,GAMEDEVICE_VK_OEM_2); break; case /*VK_OEM_3*/0xC0: sprintf(out,GAMEDEVICE_VK_OEM_3); break; case /*VK_OEM_4*/0xDB: sprintf(out,GAMEDEVICE_VK_OEM_4); break; case /*VK_OEM_5*/0xDC: sprintf(out,GAMEDEVICE_VK_OEM_5); break; case /*VK_OEM_6*/0xDD: sprintf(out,GAMEDEVICE_VK_OEM_6); break; case /*VK_OEM_7*/0xDE: sprintf(out,GAMEDEVICE_VK_OEM_7); break; case /*VK_OEM_COMMA*/0xBC: sprintf(out,GAMEDEVICE_VK_OEM_COMMA );break; case /*VK_OEM_PERIOD*/0xBE: sprintf(out,GAMEDEVICE_VK_OEM_PERIOD);break; case VK_SUBTRACT: sprintf(out,GAMEDEVICE_VK_SUBTRACT); break; case VK_DECIMAL: sprintf(out,GAMEDEVICE_VK_DECIMAL); break; case VK_DIVIDE: sprintf(out,GAMEDEVICE_VK_DIVIDE); break; case VK_NUMLOCK: sprintf(out,GAMEDEVICE_VK_NUMLOCK); break; case VK_SCROLL: sprintf(out,GAMEDEVICE_VK_SCROLL); break; case /*VK_OEM_MINUS*/0xBD: sprintf(out,GAMEDEVICE_VK_OEM_MINUS); break; case /*VK_OEM_PLUS*/0xBB: sprintf(out,GAMEDEVICE_VK_OEM_PLUS); break; case VK_SHIFT: sprintf(out,GAMEDEVICE_VK_SHIFT); break; case VK_CONTROL: sprintf(out,GAMEDEVICE_VK_CONTROL); break; case VK_MENU: sprintf(out,GAMEDEVICE_VK_MENU); break; case VK_F1: sprintf(out,GAMEDEVICE_VK_F1); break; case VK_F2: sprintf(out,GAMEDEVICE_VK_F2); break; case VK_F3: sprintf(out,GAMEDEVICE_VK_F3); break; case VK_F4: sprintf(out,GAMEDEVICE_VK_F4); break; case VK_F5: sprintf(out,GAMEDEVICE_VK_F5); break; case VK_F6: sprintf(out,GAMEDEVICE_VK_F6); break; case VK_F7: sprintf(out,GAMEDEVICE_VK_F7); break; case VK_F8: sprintf(out,GAMEDEVICE_VK_F8); break; case VK_F9: sprintf(out,GAMEDEVICE_VK_F9); break; case VK_F10: sprintf(out,GAMEDEVICE_VK_F10); break; case VK_F11: sprintf(out,GAMEDEVICE_VK_F11); break; case VK_F12: sprintf(out,GAMEDEVICE_VK_F12); break; } return ; } bool IsReserved (WORD Key, int modifiers) { // keys that do other stuff in Windows if(Key == VK_CAPITAL || Key == VK_NUMLOCK || Key == VK_SCROLL || Key == VK_SNAPSHOT || Key == VK_LWIN || Key == VK_RWIN || Key == VK_APPS || Key == /*VK_SLEEP*/0x5F || (Key == VK_F4 && (modifiers & CUSTKEY_ALT_MASK) != 0)) // alt-f4 (behaves unlike accelerators) return true; // menu shortcuts (accelerators) -- TODO: should somehow parse GUI.Accelerators for this information if(modifiers == CUSTKEY_CTRL_MASK && (Key == 'O') || modifiers == CUSTKEY_ALT_MASK && (Key == VK_F5 || Key == VK_F7 || Key == VK_F8 || Key == VK_F9 || Key == 'R' || Key == 'T' || Key == /*VK_OEM_4*/0xDB || Key == /*VK_OEM_6*/0xDD || Key == 'E' || Key == 'A' || Key == VK_RETURN || Key == VK_DELETE)) return true; return false; } int GetNumHotKeysAssignedTo (WORD Key, int modifiers) { int count = 0; { #define MATCHES_KEY(k) \ (modifiers == CustomKeys.k.modifiers \ && Key != 0 && Key != VK_ESCAPE \ && (Key == CustomKeys.k.key \ || (Key == VK_SHIFT && (CustomKeys.k.modifiers & CUSTKEY_SHIFT_MASK) != 0) \ || (Key == VK_MENU && (CustomKeys.k.modifiers & CUSTKEY_ALT_MASK) != 0) \ || (Key == VK_CONTROL && (CustomKeys.k.modifiers & CUSTKEY_CTRL_MASK) != 0) \ || (CustomKeys.k.key == VK_SHIFT) \ || (CustomKeys.k.key == VK_MENU) \ || (CustomKeys.k.key == VK_CONTROL))) if(MATCHES_KEY(SpeedUp)) count++; if(MATCHES_KEY(SpeedDown)) count++; if(MATCHES_KEY(Pause)) count++; if(MATCHES_KEY(FrameAdvance)) count++; if(MATCHES_KEY(SkipUp)) count++; if(MATCHES_KEY(SkipDown)) count++; if(MATCHES_KEY(ScopeTurbo)) count++; if(MATCHES_KEY(ScopePause)) count++; if(MATCHES_KEY(FrameCount)) count++; if(MATCHES_KEY(ReadOnly)) count++; for(int i = 0 ; i < 10 ; i++) { if(MATCHES_KEY(Save[i])) count++; if(MATCHES_KEY(Load[i])) count++; if(MATCHES_KEY(SelectSave[i])) count++; } if(MATCHES_KEY(FastForward)) count++; if(MATCHES_KEY(ShowPressed)) count++; if(MATCHES_KEY(SaveScreenShot)) count++; if(MATCHES_KEY(SlotPlus)) count++; if(MATCHES_KEY(SlotMinus)) count++; if(MATCHES_KEY(SlotSave)) count++; if(MATCHES_KEY(SlotLoad)) count++; if(MATCHES_KEY(BGL1)) count++; if(MATCHES_KEY(BGL2)) count++; if(MATCHES_KEY(BGL3)) count++; if(MATCHES_KEY(BGL4)) count++; if(MATCHES_KEY(BGL5)) count++; if(MATCHES_KEY(ClippingWindows)) count++; // if(MATCHES_KEY(BGLHack)) count++; if(MATCHES_KEY(Transparency)) count++; // if(MATCHES_KEY(GLCube)) count++; // if(MATCHES_KEY(InterpMode7)) count++; if(MATCHES_KEY(JoypadSwap)) count++; if(MATCHES_KEY(SwitchControllers)) count++; if(MATCHES_KEY(TurboA)) count++; if(MATCHES_KEY(TurboB)) count++; if(MATCHES_KEY(TurboY)) count++; if(MATCHES_KEY(TurboX)) count++; if(MATCHES_KEY(TurboL)) count++; if(MATCHES_KEY(TurboR)) count++; if(MATCHES_KEY(TurboStart)) count++; if(MATCHES_KEY(TurboSelect)) count++; if(MATCHES_KEY(TurboLeft)) count++; if(MATCHES_KEY(TurboUp)) count++; if(MATCHES_KEY(TurboRight)) count++; if(MATCHES_KEY(TurboDown)) count++; if(MATCHES_KEY(ResetGame)) count++; if(MATCHES_KEY(ToggleCheats)) count++; if(MATCHES_KEY(QuitS9X)) count++; if(MATCHES_KEY(Rewind)) count++; #undef MATCHES_KEY } return count; } int GetNumButtonsAssignedTo (WORD Key) { int count = 0; for(int J = 0; J < 5*2; J++) { // don't want to report conflicts with disabled keys if(!Joypad[J%5].Enabled || Key == 0 || Key == VK_ESCAPE) continue; if(Key == Joypad[J].Left) count++; if(Key == Joypad[J].Right) count++; if(Key == Joypad[J].Left_Up) count++; if(Key == Joypad[J].Left_Down) count++; if(Key == Joypad[J].Right_Up) count++; if(Key == Joypad[J].Right_Down) count++; if(Key == Joypad[J].Up) count++; if(Key == Joypad[J].Down) count++; if(Key == Joypad[J].Start) count++; if(Key == Joypad[J].Select) count++; if(Key == Joypad[J].A) count++; if(Key == Joypad[J].B) count++; if(Key == Joypad[J].X) count++; if(Key == Joypad[J].Y) count++; if(Key == Joypad[J].L) count++; if(Key == Joypad[J].R) count++; } return count; } COLORREF CheckButtonKey( WORD Key) { COLORREF red,magenta,blue,white; red =RGB(255,0,0); magenta =RGB(255,0,255); blue = RGB(0,0,255); white = RGB(255,255,255); // Check for conflict with reserved windows keys if(IsReserved(Key,0)) return red; // Check for conflict with Snes9X hotkeys if(GetNumHotKeysAssignedTo(Key,0) > 0) return magenta; // Check for duplicate button keys if(GetNumButtonsAssignedTo(Key) > 1) return blue; return white; } COLORREF CheckHotKey( WORD Key, int modifiers) { COLORREF red,magenta,blue,white; red =RGB(255,0,0); magenta =RGB(255,0,255); blue = RGB(0,0,255); white = RGB(255,255,255); // Check for conflict with reserved windows keys if(IsReserved(Key,modifiers)) return red; // Check for conflict with button keys if(modifiers == 0 && GetNumButtonsAssignedTo(Key) > 0) return magenta; // Check for duplicate Snes9X hotkeys if(GetNumHotKeysAssignedTo(Key,modifiers) > 1) return blue; return white; } void InitInputCustomControl() { WNDCLASSEX wc; wc.cbSize = sizeof(wc); wc.lpszClassName = szClassName; wc.hInstance = GetModuleHandle(0); wc.lpfnWndProc = InputCustomWndProc; wc.hCursor = LoadCursor (NULL, IDC_ARROW); wc.hIcon = 0; wc.lpszMenuName = 0; wc.hbrBackground = (HBRUSH)GetSysColorBrush(COLOR_BTNFACE); wc.style = 0; wc.cbClsExtra = 0; wc.cbWndExtra = sizeof(InputCust *); wc.hIconSm = 0; RegisterClassEx(&wc); } void InitKeyCustomControl() { WNDCLASSEX wc; wc.cbSize = sizeof(wc); wc.lpszClassName = szHotkeysClassName; wc.hInstance = GetModuleHandle(0); wc.lpfnWndProc = HotInputCustomWndProc; wc.hCursor = LoadCursor (NULL, IDC_ARROW); wc.hIcon = 0; wc.lpszMenuName = 0; wc.hbrBackground = (HBRUSH)GetSysColorBrush(COLOR_BTNFACE); wc.style = 0; wc.cbClsExtra = 0; wc.cbWndExtra = sizeof(InputCust *); wc.hIconSm = 0; RegisterClassEx(&wc); } HWND CreateInputCustom(HWND hwndParent) { HWND hwndCtrl; hwndCtrl = CreateWindowEx( WS_EX_CLIENTEDGE, // give it a standard border szClassName, _T("A custom control"), WS_VISIBLE | WS_CHILD, 0, 0, 100, 100, hwndParent, NULL, GetModuleHandle(0), NULL ); return hwndCtrl; } InputCust * GetInputCustom(HWND hwnd) { return (InputCust *)GetWindowLong(hwnd, 0); } void SetInputCustom(HWND hwnd, InputCust *icp) { SetWindowLong(hwnd, 0, (LONG)icp); } LRESULT InputCustom_OnPaint(InputCust *ccp, WPARAM wParam, LPARAM lParam) { HDC hdc; PAINTSTRUCT ps; HANDLE hOldFont; TCHAR szText[200]; RECT rect; SIZE sz; int x,y; // Get a device context for this window hdc = BeginPaint(ccp->hwnd, &ps); // Set the font we are going to use hOldFont = SelectObject(hdc, ccp->hFont); // Set the text colours SetTextColor(hdc, ccp->crForeGnd); SetBkColor (hdc, ccp->crBackGnd); // Find the text to draw GetWindowText(ccp->hwnd, szText, sizeof(szText)); // Work out where to draw GetClientRect(ccp->hwnd, &rect); // Find out how big the text will be GetTextExtentPoint32(hdc, szText, lstrlen(szText), &sz); // Center the text x = (rect.right - sz.cx) / 2; y = (rect.bottom - sz.cy) / 2; // Draw the text ExtTextOut(hdc, x, y, ETO_OPAQUE, &rect, szText, lstrlen(szText), 0); // Restore the old font when we have finished SelectObject(hdc, hOldFont); // Release the device context EndPaint(ccp->hwnd, &ps); return 0; } static LRESULT CALLBACK InputCustomWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { // retrieve the custom structure POINTER for THIS window InputCust *icp = GetInputCustom(hwnd); HWND pappy = (HWND__ *)GetWindowLongPtr(hwnd,GWLP_HWNDPARENT); funky= hwnd; static HWND selectedItem = NULL; char temp[100]; COLORREF col; switch(msg) { case WM_GETDLGCODE: return DLGC_WANTARROWS|DLGC_WANTALLKEYS|DLGC_WANTCHARS; break; case WM_NCCREATE: // Allocate a new CustCtrl structure for this window. icp = (InputCust *) malloc( sizeof(InputCust) ); // Failed to allocate, stop window creation. if(icp == NULL) return FALSE; // Initialize the CustCtrl structure. icp->hwnd = hwnd; icp->crForeGnd = GetSysColor(COLOR_WINDOWTEXT); icp->crBackGnd = GetSysColor(COLOR_WINDOW); icp->hFont = (HFONT__ *) GetStockObject(DEFAULT_GUI_FONT); // Assign the window text specified in the call to CreateWindow. SetWindowText(hwnd, ((CREATESTRUCT *)lParam)->lpszName); // Attach custom structure to this window. SetInputCustom(hwnd, icp); InvalidateRect(icp->hwnd, NULL, FALSE); UpdateWindow(icp->hwnd); selectedItem = NULL; SetTimer(hwnd,777,125,NULL); // Continue with window creation. return TRUE; // Clean up when the window is destroyed. case WM_NCDESTROY: free(icp); break; case WM_PAINT: return InputCustom_OnPaint(icp,wParam,lParam); break; case WM_ERASEBKGND: return 1; case WM_USER+45: case WM_KEYDOWN: TranslateKey(wParam,temp); col = CheckButtonKey(wParam); icp->crForeGnd = ((~col) & 0x00ffffff); icp->crBackGnd = col; SetWindowText(hwnd,_tFromChar(temp)); InvalidateRect(icp->hwnd, NULL, FALSE); UpdateWindow(icp->hwnd); SendMessage(pappy,WM_USER+43,wParam,(LPARAM)hwnd); break; case WM_USER+44: TranslateKey(wParam,temp); if(IsWindowEnabled(hwnd)) { col = CheckButtonKey(wParam); } else { col = RGB( 192,192,192); } icp->crForeGnd = ((~col) & 0x00ffffff); icp->crBackGnd = col; SetWindowText(hwnd,_tFromChar(temp)); InvalidateRect(icp->hwnd, NULL, FALSE); UpdateWindow(icp->hwnd); break; case WM_SETFOCUS: { selectedItem = hwnd; col = RGB( 0,255,0); icp->crForeGnd = ((~col) & 0x00ffffff); icp->crBackGnd = col; InvalidateRect(icp->hwnd, NULL, FALSE); UpdateWindow(icp->hwnd); // tid = wParam; break; } case WM_KILLFOCUS: { selectedItem = NULL; SendMessage(pappy,WM_USER+46,wParam,(LPARAM)hwnd); // refresh fields on deselect break; } case WM_TIMER: if(hwnd == selectedItem) { FunkyJoyStickTimer(); } SetTimer(hwnd,777,125,NULL); break; case WM_LBUTTONDOWN: SetFocus(hwnd); break; case WM_ENABLE: COLORREF col; if(wParam) { col = RGB( 255,255,255); icp->crForeGnd = ((~col) & 0x00ffffff); icp->crBackGnd = col; } else { col = RGB( 192,192,192); icp->crForeGnd = ((~col) & 0x00ffffff); icp->crBackGnd = col; } InvalidateRect(icp->hwnd, NULL, FALSE); UpdateWindow(icp->hwnd); return true; default: break; } return DefWindowProc(hwnd, msg, wParam, lParam); } static void TranslateKeyWithModifiers(int wParam, int modifiers, char * outStr) { // if the key itself is a modifier, special case output: if(wParam == VK_SHIFT) strcpy(outStr, "Shift"); else if(wParam == VK_MENU) strcpy(outStr, "Alt"); else if(wParam == VK_CONTROL) strcpy(outStr, "Control"); else { // otherwise, prepend the modifier(s) if(wParam != VK_ESCAPE && wParam != 0) { if((modifiers & CUSTKEY_CTRL_MASK) != 0) { sprintf(outStr,HOTKEYS_CONTROL_MOD); outStr += strlen(HOTKEYS_CONTROL_MOD); } if((modifiers & CUSTKEY_ALT_MASK) != 0) { sprintf(outStr,HOTKEYS_ALT_MOD); outStr += strlen(HOTKEYS_ALT_MOD); } if((modifiers & CUSTKEY_SHIFT_MASK) != 0) { sprintf(outStr,HOTKEYS_SHIFT_MOD); outStr += strlen(HOTKEYS_SHIFT_MOD); } } // and append the translated non-modifier key TranslateKey(wParam,outStr); } } static bool keyPressLock = false; static LRESULT CALLBACK HotInputCustomWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { // retrieve the custom structure POINTER for THIS window InputCust *icp = GetInputCustom(hwnd); HWND pappy = (HWND__ *)GetWindowLongPtr(hwnd,GWLP_HWNDPARENT); funky= hwnd; static HWND selectedItem = NULL; char temp[100]; COLORREF col; switch(msg) { case WM_GETDLGCODE: return DLGC_WANTARROWS|DLGC_WANTALLKEYS|DLGC_WANTCHARS; break; case WM_NCCREATE: // Allocate a new CustCtrl structure for this window. icp = (InputCust *) malloc( sizeof(InputCust) ); // Failed to allocate, stop window creation. if(icp == NULL) return FALSE; // Initialize the CustCtrl structure. icp->hwnd = hwnd; icp->crForeGnd = GetSysColor(COLOR_WINDOWTEXT); icp->crBackGnd = GetSysColor(COLOR_WINDOW); icp->hFont = (HFONT__ *) GetStockObject(DEFAULT_GUI_FONT); // Assign the window text specified in the call to CreateWindow. SetWindowText(hwnd, ((CREATESTRUCT *)lParam)->lpszName); // Attach custom structure to this window. SetInputCustom(hwnd, icp); InvalidateRect(icp->hwnd, NULL, FALSE); UpdateWindow(icp->hwnd); keyPressLock = false; selectedItem = NULL; SetTimer(hwnd,747,125,NULL); // Continue with window creation. return TRUE; // Clean up when the window is destroyed. case WM_NCDESTROY: free(icp); break; case WM_PAINT: return InputCustom_OnPaint(icp,wParam,lParam); break; case WM_ERASEBKGND: return 1; /* case WM_KEYUP: { int count = 0; for(int i=0;i<256;i++) if(GetAsyncKeyState(i)) count++; if(count < 2) { int p = count; } if(count < 1) { int p = count; } TranslateKey(wParam,temp); col = CheckButtonKey(wParam); icp->crForeGnd = ((~col) & 0x00ffffff); icp->crBackGnd = col; SetWindowText(hwnd,temp); InvalidateRect(icp->hwnd, NULL, FALSE); UpdateWindow(icp->hwnd); SendMessage(pappy,WM_USER+43,wParam,(LPARAM)hwnd); } break; */ case WM_SYSKEYDOWN: case WM_KEYDOWN: { int count = 0; for(int i=2;i<256;i++) { if(i >= VK_LSHIFT && i <= VK_RMENU) continue; if(GetAsyncKeyState(i)) count++; } if(count <= 1) { keyPressLock = false; } } // no break case WM_USER+45: // assign a hotkey: { // don't assign pure modifiers on key-down (they're assigned on key-up) if(wParam == VK_SHIFT || wParam == VK_MENU || wParam == VK_CONTROL) break; int modifiers = 0; if(GetAsyncKeyState(VK_MENU)) modifiers |= CUSTKEY_ALT_MASK; if(GetAsyncKeyState(VK_CONTROL)) modifiers |= CUSTKEY_CTRL_MASK; if(GetAsyncKeyState(VK_SHIFT)) modifiers |= CUSTKEY_SHIFT_MASK; TranslateKeyWithModifiers(wParam, modifiers, temp); col = CheckHotKey(wParam,modifiers); /// if(col == RGB(255,0,0)) // un-redify /// col = RGB(255,255,255); icp->crForeGnd = ((~col) & 0x00ffffff); icp->crBackGnd = col; SetWindowText(hwnd,_tFromChar(temp)); InvalidateRect(icp->hwnd, NULL, FALSE); UpdateWindow(icp->hwnd); SendMessage(pappy,WM_USER+43,wParam,(LPARAM)hwnd); keyPressLock = true; } break; case WM_SYSKEYUP: case WM_KEYUP: if(!keyPressLock) { int count = 0; for(int i=2;i<256;i++) { if(i >= VK_LSHIFT && i <= VK_RMENU) continue; if(GetAsyncKeyState(i)) count++; } if(count <= 1) { if(wParam == VK_SHIFT || wParam == VK_MENU || wParam == VK_CONTROL) { if(wParam == VK_SHIFT) sprintf(temp, "Shift"); if(wParam == VK_MENU) sprintf(temp, "Alt"); if(wParam == VK_CONTROL) sprintf(temp, "Control"); col = CheckHotKey(wParam,0); icp->crForeGnd = ((~col) & 0x00ffffff); icp->crBackGnd = col; SetWindowText(hwnd,_tFromChar(temp)); InvalidateRect(icp->hwnd, NULL, FALSE); UpdateWindow(icp->hwnd); SendMessage(pappy,WM_USER+43,wParam,(LPARAM)hwnd); } } } break; case WM_USER+44: // set a hotkey field: { int modifiers = lParam; TranslateKeyWithModifiers(wParam, modifiers, temp); if(IsWindowEnabled(hwnd)) { col = CheckHotKey(wParam,modifiers); /// if(col == RGB(255,0,0)) // un-redify /// col = RGB(255,255,255); } else { col = RGB( 192,192,192); } icp->crForeGnd = ((~col) & 0x00ffffff); icp->crBackGnd = col; SetWindowText(hwnd,_tFromChar(temp)); InvalidateRect(icp->hwnd, NULL, FALSE); UpdateWindow(icp->hwnd); } break; case WM_SETFOCUS: { selectedItem = hwnd; col = RGB( 0,255,0); icp->crForeGnd = ((~col) & 0x00ffffff); icp->crBackGnd = col; InvalidateRect(icp->hwnd, NULL, FALSE); UpdateWindow(icp->hwnd); // tid = wParam; break; } case WM_KILLFOCUS: { selectedItem = NULL; SendMessage(pappy,WM_USER+46,wParam,(LPARAM)hwnd); // refresh fields on deselect break; } case WM_TIMER: if(hwnd == selectedItem) { FunkyJoyStickTimer(); } SetTimer(hwnd,747,125,NULL); break; case WM_LBUTTONDOWN: SetFocus(hwnd); break; case WM_ENABLE: COLORREF col; if(wParam) { col = RGB( 255,255,255); icp->crForeGnd = ((~col) & 0x00ffffff); icp->crBackGnd = col; } else { col = RGB( 192,192,192); icp->crForeGnd = ((~col) & 0x00ffffff); icp->crBackGnd = col; } InvalidateRect(icp->hwnd, NULL, FALSE); UpdateWindow(icp->hwnd); return true; default: break; } return DefWindowProc(hwnd, msg, wParam, lParam); }
412
0.879937
1
0.879937
game-dev
MEDIA
0.921309
game-dev
0.608
1
0.608
PowerNukkitX/PowerNukkitX
1,634
src/main/java/cn/nukkit/blockentity/BlockEntityGlowItemFrame.java
package cn.nukkit.blockentity; import cn.nukkit.block.Block; import cn.nukkit.block.BlockID; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.level.format.IChunk; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; public class BlockEntityGlowItemFrame extends BlockEntityItemFrame { public BlockEntityGlowItemFrame(IChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override public String getName() { return this.hasName() ? this.namedTag.getString("CustomName") : "Glow Item Frame"; } public boolean hasName() { return namedTag.contains("CustomName"); } @Override public CompoundTag getSpawnCompound() { if (!this.namedTag.contains("Item")) { this.setItem(new ItemBlock(Block.get(BlockID.AIR)), false); } Item item = getItem(); CompoundTag tag = super.getSpawnCompound(); if (!item.isNull()) { CompoundTag itemTag = NBTIO.putItemHelper(item); int networkDamage = item.getDamage(); String namespacedId = item.getId(); if (namespacedId != null) { itemTag.remove("id"); itemTag.putShort("Damage", networkDamage); itemTag.putString("Name", namespacedId); } if (item.isBlock()) { itemTag.putCompound("Block", item.getBlockUnsafe().getBlockState().getBlockStateTag()); } tag.putCompound("Item", itemTag) .putByte("ItemRotation", this.getItemRotation()); } return tag; } }
412
0.801236
1
0.801236
game-dev
MEDIA
0.995081
game-dev
0.743991
1
0.743991
Forlornicus/forlornware-executor
2,222
forlornware/dependencies/luau/Ast/include/Luau/Location.h
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details #pragma once namespace Luau { struct Position { unsigned int line, column; Position(unsigned int line, unsigned int column) : line(line) , column(column) { } bool operator==(const Position& rhs) const { return this->column == rhs.column && this->line == rhs.line; } bool operator!=(const Position& rhs) const { return !(*this == rhs); } bool operator<(const Position& rhs) const { if (line == rhs.line) return column < rhs.column; else return line < rhs.line; } bool operator>(const Position& rhs) const { if (line == rhs.line) return column > rhs.column; else return line > rhs.line; } bool operator<=(const Position& rhs) const { return *this == rhs || *this < rhs; } bool operator>=(const Position& rhs) const { return *this == rhs || *this > rhs; } void shift(const Position& start, const Position& oldEnd, const Position& newEnd); }; struct Location { Position begin, end; Location() : begin(0, 0) , end(0, 0) { } Location(const Position& begin, const Position& end) : begin(begin) , end(end) { } Location(const Position& begin, unsigned int length) : begin(begin) , end(begin.line, begin.column + length) { } Location(const Location& begin, const Location& end) : begin(begin.begin) , end(end.end) { } bool operator==(const Location& rhs) const { return this->begin == rhs.begin && this->end == rhs.end; } bool operator!=(const Location& rhs) const { return !(*this == rhs); } bool encloses(const Location& l) const; bool overlaps(const Location& l) const; bool contains(const Position& p) const; bool containsClosed(const Position& p) const; void extend(const Location& other); void shift(const Position& start, const Position& oldEnd, const Position& newEnd); }; } // namespace Luau
412
0.776246
1
0.776246
game-dev
MEDIA
0.302647
game-dev
0.897376
1
0.897376
anathema/anathema_legacy
1,076
Namegenerator/src/main/java/net/sf/anathema/namegenerator/domain/realm/RealmWordFactory.java
package net.sf.anathema.namegenerator.domain.realm; import net.sf.anathema.lib.util.RandomUtilities; import net.sf.anathema.namegenerator.domain.syllable.IWordFactory; import net.sf.anathema.namegenerator.domain.syllable.SimpleWordFactory; public class RealmWordFactory implements IWordFactory { private final String[] commonFamilyNames = new String[] { "Cathak", "Cynis", "Iselsi", "Ledaal", "Mnemon", "Nellens", "Peleps", "Ragara", "Sesus", "Tepet", "V'Neef" }; private final SimpleWordFactory wordFactory = new SimpleWordFactory( new RealmSyllableFactory(), new RealmSyllableCalculator()); private final int commonFamilyPercent; public RealmWordFactory(int commonFamilyPercent) { this.commonFamilyPercent = commonFamilyPercent; } @Override public String createWord(int wordIndex) { if (wordIndex == 0 && RandomUtilities.nextPercent() < commonFamilyPercent) { return RandomUtilities.choose(commonFamilyNames); } return wordFactory.createWord(wordIndex); } }
412
0.86338
1
0.86338
game-dev
MEDIA
0.356682
game-dev
0.673524
1
0.673524
frank-w/BPI-Router-Linux
5,365
include/rdma/uverbs_std_types.h
/* SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB */ /* * Copyright (c) 2017, Mellanox Technologies inc. All rights reserved. */ #ifndef _UVERBS_STD_TYPES__ #define _UVERBS_STD_TYPES__ #include <rdma/uverbs_types.h> #include <rdma/uverbs_ioctl.h> #include <rdma/ib_user_ioctl_verbs.h> /* Returns _id, or causes a compile error if _id is not a u32. * * The uobj APIs should only be used with the write based uAPI to access * object IDs. The write API must use a u32 for the object handle, which is * checked by this macro. */ #define _uobj_check_id(_id) ((_id) * typecheck(u32, _id)) #define uobj_get_type(_attrs, _object) \ uapi_get_object((_attrs)->ufile->device->uapi, _object) #define uobj_get_read(_type, _id, _attrs) \ rdma_lookup_get_uobject(uobj_get_type(_attrs, _type), (_attrs)->ufile, \ _uobj_check_id(_id), UVERBS_LOOKUP_READ, \ _attrs) #define ufd_get_read(_type, _fdnum, _attrs) \ rdma_lookup_get_uobject(uobj_get_type(_attrs, _type), (_attrs)->ufile, \ (_fdnum)*typecheck(s32, _fdnum), \ UVERBS_LOOKUP_READ, _attrs) static inline void *_uobj_get_obj_read(struct ib_uobject *uobj) { if (IS_ERR(uobj)) return ERR_CAST(uobj); return uobj->object; } #define uobj_get_obj_read(_object, _type, _id, _attrs) \ ((struct ib_##_object *)_uobj_get_obj_read( \ uobj_get_read(_type, _id, _attrs))) #define uobj_get_write(_type, _id, _attrs) \ rdma_lookup_get_uobject(uobj_get_type(_attrs, _type), (_attrs)->ufile, \ _uobj_check_id(_id), UVERBS_LOOKUP_WRITE, \ _attrs) int __uobj_perform_destroy(const struct uverbs_api_object *obj, u32 id, struct uverbs_attr_bundle *attrs); #define uobj_perform_destroy(_type, _id, _attrs) \ __uobj_perform_destroy(uobj_get_type(_attrs, _type), \ _uobj_check_id(_id), _attrs) struct ib_uobject *__uobj_get_destroy(const struct uverbs_api_object *obj, u32 id, struct uverbs_attr_bundle *attrs); #define uobj_get_destroy(_type, _id, _attrs) \ __uobj_get_destroy(uobj_get_type(_attrs, _type), _uobj_check_id(_id), \ _attrs) static inline void uobj_put_destroy(struct ib_uobject *uobj) { rdma_lookup_put_uobject(uobj, UVERBS_LOOKUP_DESTROY); } static inline void uobj_put_read(struct ib_uobject *uobj) { rdma_lookup_put_uobject(uobj, UVERBS_LOOKUP_READ); } #define uobj_put_obj_read(_obj) \ uobj_put_read((_obj)->uobject) static inline void uobj_put_write(struct ib_uobject *uobj) { rdma_lookup_put_uobject(uobj, UVERBS_LOOKUP_WRITE); } static inline void uobj_alloc_abort(struct ib_uobject *uobj, struct uverbs_attr_bundle *attrs) { rdma_alloc_abort_uobject(uobj, attrs, false); } static inline void uobj_finalize_uobj_create(struct ib_uobject *uobj, struct uverbs_attr_bundle *attrs) { /* * Tell the core code that the write() handler has completed * initializing the object and that the core should commit or * abort this object based upon the return code from the write() * method. Similar to what uverbs_finalize_uobj_create() does for * ioctl() */ WARN_ON(attrs->uobject); attrs->uobject = uobj; } static inline struct ib_uobject * __uobj_alloc(const struct uverbs_api_object *obj, struct uverbs_attr_bundle *attrs, struct ib_device **ib_dev) { struct ib_uobject *uobj = rdma_alloc_begin_uobject(obj, attrs); if (!IS_ERR(uobj)) *ib_dev = attrs->context->device; return uobj; } #define uobj_alloc(_type, _attrs, _ib_dev) \ __uobj_alloc(uobj_get_type(_attrs, _type), _attrs, _ib_dev) static inline void uverbs_flow_action_fill_action(struct ib_flow_action *action, struct ib_uobject *uobj, struct ib_device *ib_dev, enum ib_flow_action_type type) { atomic_set(&action->usecnt, 0); action->device = ib_dev; action->type = type; action->uobject = uobj; uobj->object = action; } struct ib_uflow_resources { size_t max; size_t num; size_t collection_num; size_t counters_num; struct ib_counters **counters; struct ib_flow_action **collection; }; struct ib_uflow_object { struct ib_uobject uobject; struct ib_uflow_resources *resources; }; struct ib_uflow_resources *flow_resources_alloc(size_t num_specs); void flow_resources_add(struct ib_uflow_resources *uflow_res, enum ib_flow_spec_type type, void *ibobj); void ib_uverbs_flow_resources_free(struct ib_uflow_resources *uflow_res); static inline void ib_set_flow(struct ib_uobject *uobj, struct ib_flow *ibflow, struct ib_qp *qp, struct ib_device *device, struct ib_uflow_resources *uflow_res) { struct ib_uflow_object *uflow; uobj->object = ibflow; ibflow->uobject = uobj; if (qp) { atomic_inc(&qp->usecnt); ibflow->qp = qp; } ibflow->device = device; uflow = container_of(uobj, typeof(*uflow), uobject); uflow->resources = uflow_res; } struct uverbs_api_object { const struct uverbs_obj_type *type_attrs; const struct uverbs_obj_type_class *type_class; u8 disabled:1; u32 id; }; static inline u32 uobj_get_object_id(struct ib_uobject *uobj) { return uobj->uapi_object->id; } #endif
412
0.839623
1
0.839623
game-dev
MEDIA
0.634303
game-dev
0.881777
1
0.881777
libvips/nip2
1,168
share/nip2/compat/7.16/Object.def
Object_duplicate_item = class Menuaction "_Duplicate" "take a copy of an object" { action x = map_unary copy x; } #separator Object_list_to_group_item = class Menuaction "_List to Group" "turn a list of objects into a group" { action x = to_group x; } Object_group_to_list_item = class Menuaction "_Group to List" "turn a group into a list of objects" { action x = to_list x; } #separator Object_break_item = class Menuaction "_Break Up Object" "break an object into a list of components" { action x = map_unary break x { break x = bandsplit x, is_Image x = map Vector x.value, is_Matrix x = x.value, is_Vector x || is_Real x = error "Breakup: not Image/Matrix/Vector/Real"; } } Object_assemble_item = class Menuaction "_Assemble Objects" "assemble a list (or group) of objects into a single object" { action x = map_unary ass x { ass x = [], x == [] = Vector x, is_real_list x = Matrix x, is_matrix x = bandjoin x, is_listof is_Image x = Vector (map get_value x), is_listof is_Real x = Matrix (map get_value x), is_listof is_Vector x = error "Assemble: not list of Image/Vector/Real/image/real"; } }
412
0.811448
1
0.811448
game-dev
MEDIA
0.702325
game-dev
0.950147
1
0.950147
ericraio/vanilla-wow-addons
27,554
t/TheoryCraft/TheoryCraftMessy.lua
-- These functions still need rewriting -- They were written before I new about for in pairs, captures -- or even patterns other then %d+... you gotta start somewhere =) local data = {} local _, class = UnitClass("player") local function findpattern(text, pattern, start) if (text and pattern and (string.find(text, pattern, start))) then return string.sub(text, string.find(text, pattern, start)) else return "" end end local function round(arg1, decplaces) if (decplaces == nil) then decplaces = 0 end if arg1 == nil then arg1 = 0 end return string.format ("%."..decplaces.."f", arg1) end local function getmanacost(frame) index = 1 local ltext = getglobal(frame:GetName().."TextLeft"..index):GetText() local manaCost = 0 while (ltext) do if (strfind(ltext, TheoryCraft_Locale.Mana)) then manaCost = findpattern(ltext, "%d+") end index = index + 1; ltext = getglobal(frame:GetName().."TextLeft"..index):GetText() end manaCost = tonumber(manaCost) if manaCost then return manaCost else return 0 end end function TheoryCraft_getMinMax(spelldata, returndata, frame) if returndata["description"] == nil then return end local description = returndata["description"] local baseincrease = returndata["baseincrease"] local dotbaseincrease = baseincrease local gearbaseincrease = baseincrease if spelldata.ismelee == nil then baseincrease = baseincrease*returndata["talentbaseincreaseupfront"] if spelldata.talentsbeforegear == nil then gearbaseincrease = gearbaseincrease*returndata["talentbaseincrease"]*returndata["talentbaseincreaseupfront"] end baseincrease = baseincrease*returndata["talentbaseincrease"] dotbaseincrease = dotbaseincrease*returndata["talentbaseincrease"] end local plusdam = (returndata["damfinal"] or 0)*gearbaseincrease local plusdam2 = returndata["plusdam2"] or 0 local to = TheoryCraft_Locale.to returndata["backstabmult"] = 1 if spelldata.autoattack then returndata["mindamage"] = (TheoryCraft_GetStat("MeleeMin")+(TheoryCraft_Data.Stats["attackpower"]/14)*TheoryCraft_GetStat("MainSpeed")) returndata["maxdamage"] = returndata["mindamage"]-TheoryCraft_GetStat("MeleeMin")+TheoryCraft_GetStat("MeleeMax") baseincrease = TheoryCraft_GetStat("Meleemodifier")+TheoryCraft_GetStat("Meleetalentmod") returndata["mindamage"] = returndata["mindamage"]*baseincrease returndata["maxdamage"] = returndata["maxdamage"]*baseincrease returndata["critdmgchance"] = TheoryCraft_Data.Stats["meleecritchance"]/100 if TheoryCraft_GetStat("OffhandMin") == 0 then returndata["description"] = "Attacks the target for "..math.floor(returndata["mindamage"]).." to "..math.floor(returndata["maxdamage"]).."." else returndata["offhandmindamage"] = (TheoryCraft_GetStat("OffhandMin")+(TheoryCraft_Data.Stats["attackpower"]/14)*TheoryCraft_GetStat("OffhandSpeed")) returndata["offhandmaxdamage"] = returndata["offhandmindamage"]-TheoryCraft_GetStat("OffhandMin")+TheoryCraft_GetStat("OffhandMax") local offhandbaseincrease = baseincrease/2 returndata["offhandmindamage"] = returndata["offhandmindamage"]*offhandbaseincrease returndata["offhandmaxdamage"] = returndata["offhandmaxdamage"]*offhandbaseincrease if TheoryCraft_GetStat("MeleeMin") == 0 then returndata["description"] = "Off-hand attacks for "..math.floor(returndata["offhandmindamage"]).." to "..math.floor(returndata["offhandmaxdamage"]).."." else returndata["description"] = "Main hand attacks the target for "..math.floor(returndata["mindamage"]).." to "..math.floor(returndata["maxdamage"])..", off-hand for "..math.floor(returndata["offhandmindamage"]).." to "..math.floor(returndata["offhandmaxdamage"]).."." end end return end if spelldata.iscombo then local _, convert _, _, convert = strfind(returndata["description"], TheoryCraft_MeleeComboEnergyConverter) returndata["comboconvert"] = tonumber(convert) for points, tmp, mindamage, maxdamage in string.gfind(returndata["description"], TheoryCraft_MeleeComboReader) do returndata["combo"..points.."mindamage"] = mindamage returndata["combo"..points.."maxdamage"] = maxdamage end returndata["beforecombo"] = returndata["description"] elseif spelldata.shoot then local a = TheoryCraft_Locale.MinMax if (TheoryCraft_Data.EquipEffects["RangedMin"]) and (TheoryCraft_Data.EquipEffects["RangedMin"] ~= 0) then returndata["mindamage"] = TheoryCraft_Data.EquipEffects["RangedMin"] returndata["maxdamage"] = TheoryCraft_Data.EquipEffects["RangedMax"] returndata["description"] = a.autoshotbefore..returndata["mindamage"]..to..returndata["maxdamage"]..a.autoshotafter else returndata["mindamage"] = 0 returndata["maxdamage"] = 0 description = a.shooterror end returndata["critchance"] = 5 returndata["critbonus"] = 0.5 if (TheoryCraft_Data.EquipEffects["RangedSpeed"]) and (TheoryCraft_Data.EquipEffects["RangedSpeed"] ~= 0) then local tmp = (returndata["mindamage"]+returndata["maxdamage"])/2 returndata["dps"] = (tmp+tmp*returndata["critbonus"]*returndata["critchance"]/100)/TheoryCraft_Data.EquipEffects["RangedSpeed"] else returndata["dps"] = 0 end elseif spelldata.autoshot then -- Autoshot is calculated here returndata["mindamage"] = TheoryCraft_GetStat("RangedMin")+TheoryCraft_Data.Stats["rangedattackpower"]/14*TheoryCraft_GetStat("RangedSpeed") returndata["maxdamage"] = returndata["mindamage"]-TheoryCraft_GetStat("RangedMin")+TheoryCraft_GetStat("RangedMax") baseincrease = TheoryCraft_GetStat("Rangedmodifier")+TheoryCraft_GetStat("Rangedtalentmod") returndata["maxdamage"] = returndata["maxdamage"]*baseincrease+TheoryCraft_GetStat("AmmoDPS")*TheoryCraft_GetStat("RangedSpeed") returndata["mindamage"] = returndata["mindamage"]*baseincrease+TheoryCraft_GetStat("AmmoDPS")*TheoryCraft_GetStat("RangedSpeed") returndata["description"] = TheoryCraft_Locale.MinMax.autoshotbefore..(round(returndata["mindamage"]))..to..(round(returndata["maxdamage"]))..TheoryCraft_Locale.MinMax.autoshotafter local averageauto, averageaimed, averagemulti, averagearcane = 0, 0, 0, 0 local aimedmana, multimana = 0, 0 averageauto = (returndata["maxdamage"]+returndata["mindamage"])/2 averageauto = averageauto+averageauto*TheoryCraft_Data.Stats["rangedcritchance"]/100*returndata["critbonus"] for i = 1, 20 do if TheoryCraft_TooltipData[TheoryCraft_Locale.MinMax.aimedshotname.."("..i..")"] and TheoryCraft_TooltipData[TheoryCraft_TooltipData[TheoryCraft_Locale.MinMax.aimedshotname.."("..i..")"]].averagedam then averageaimed = TheoryCraft_TooltipData[TheoryCraft_TooltipData[TheoryCraft_Locale.MinMax.aimedshotname.."("..i..")"]].averagedam aimedmana = TheoryCraft_TooltipData[TheoryCraft_TooltipData[TheoryCraft_Locale.MinMax.aimedshotname.."("..i..")"]].manacost end if TheoryCraft_TooltipData[TheoryCraft_Locale.MinMax.multishotname.."("..i..")"] and TheoryCraft_TooltipData[TheoryCraft_TooltipData[TheoryCraft_Locale.MinMax.multishotname.."("..i..")"]].averagedam then averagemulti = TheoryCraft_TooltipData[TheoryCraft_TooltipData[TheoryCraft_Locale.MinMax.multishotname.."("..i..")"]].averagedam multimana = TheoryCraft_TooltipData[TheoryCraft_TooltipData[TheoryCraft_Locale.MinMax.multishotname.."("..i..")"]].manacost end if TheoryCraft_TooltipData[TheoryCraft_Locale.MinMax.arcaneshotname.."("..i..")"] and TheoryCraft_TooltipData[TheoryCraft_TooltipData[TheoryCraft_Locale.MinMax.arcaneshotname.."("..i..")"]].dps then averagearcane = TheoryCraft_TooltipData[TheoryCraft_TooltipData[TheoryCraft_Locale.MinMax.arcaneshotname.."("..i..")"]].dps end end -- averageauto = 651 -- averageaimed = 1293 -- averagemulti = 662 local rotationlength1, rotationlength2, rotationdps1, rotationdps2, autoshotcount1, autoshotcount2 local speed = TheoryCraft_GetStat("RangedSpeed")*TheoryCraft_GetStat("Rangedhastebonus") -- speed = 2.19 returndata["dps"] = averageauto/speed returndata["manacost"] = aimedmana+multimana returndata["basemanacost"] = aimedmana+multimana returndata["dontshowmana"] = true -- MS Rotation Calculated Here: rotationlength1 = 10 rotationlength2 = math.ceil(7/speed)*speed+3 if (speed > 3) or (averageaimed == 0) then autoshotcount1 = math.floor(rotationlength1/speed) autoshotcount2 = math.floor(rotationlength2/speed) else autoshotcount1 = math.floor((rotationlength1-3)/speed)+1 autoshotcount2 = math.floor((rotationlength2-3)/speed)+1 end rotationdps1 = (averageaimed+averagemulti+averageauto*autoshotcount1)/rotationlength1 rotationdps2 = (averageaimed+averagemulti+averageauto*autoshotcount2)/rotationlength2 if (rotationdps1 > rotationdps2) then returndata["msrotationdps"] = rotationdps1 returndata["msrotationlength"] = rotationlength1 if TheoryCraft_Settings["procs"] then returndata["manacost"] = returndata["manacost"]-autoshotcount1*0.04*TheoryCraft_GetStat("Beastmanarestore") end else returndata["msrotationdps"] = rotationdps2 returndata["msrotationlength"] = rotationlength2 if TheoryCraft_Settings["procs"] then returndata["manacost"] = returndata["manacost"]-autoshotcount2*0.04*TheoryCraft_GetStat("Beastmanarestore") end end returndata["regencasttime"] = returndata["msrotationlength"]-3 -- AS Rotation Calculated Here: rotationlength1 = 9 rotationlength2 = math.ceil(6/speed)*speed+3 if rotationlength2 > 10 then rotationlength2 = 9 end if (speed > 3) or (averageaimed == 0) then autoshotcount1 = math.floor(rotationlength1/speed) autoshotcount2 = math.floor(rotationlength2/speed) else autoshotcount1 = math.floor((rotationlength1-3)/speed)+1 autoshotcount2 = math.floor((rotationlength2-3)/speed)+1 end rotationdps1 = (averageaimed*6+averagemulti*5+averageauto*autoshotcount1*6)/(rotationlength1*6) rotationdps2 = (averageaimed*6+averagemulti*5+averageauto*autoshotcount2*6)/(rotationlength2*6) if (rotationdps1 > rotationdps2) then returndata["asrotationdps"] = rotationdps1 returndata["asrotationlength"] = rotationlength1 else returndata["asrotationdps"] = rotationdps2 returndata["asrotationlength"] = rotationlength2 end -- MS/Arc Rotation Calculated Here: returndata["arcrotationdps"] = (averagearcane*10+averagemulti+averageauto*(10/speed))/10 returndata["arcmagicdps"] = averagearcane elseif (spelldata.ismelee) or (spelldata.isranged) then local normalized if spelldata.noscale then returndata["backstabmult"] = 0 end if spelldata.isranged then normalized = (TheoryCraft_Data.Stats["rangedattackpower"]/14)*returndata["RangedAPMult"] returndata["mindamage"] = TheoryCraft_Data.EquipEffects["RangedMin"] returndata["maxdamage"] = TheoryCraft_Data.EquipEffects["RangedMax"] else if spelldata.forcemult then normalized = TheoryCraft_Data.Stats["attackpower"]/14*spelldata.forcemult elseif spelldata.nextattack then normalized = TheoryCraft_Data.Stats["attackpower"]/14*TheoryCraft_Data.EquipEffects["MainSpeed"] else normalized = TheoryCraft_Data.Stats["attackpower"]/14*(TheoryCraft_Data.EquipEffects["MeleeAPMult"] or 1) end returndata["mindamage"] = TheoryCraft_Data.EquipEffects["MeleeMin"] returndata["maxdamage"] = TheoryCraft_Data.EquipEffects["MeleeMax"] end local i = 1 local removetalents = 1 baseincrease = 0 removetalents = removetalents + TheoryCraft_GetStat(spelldata.id.."modifier") baseincrease = baseincrease + TheoryCraft_GetStat(spelldata.id.."baseincrease") baseincrease = baseincrease + TheoryCraft_GetStat(spelldata.id.."modifier")+TheoryCraft_GetStat(spelldata.id.."talentmod") while spelldata.Schools[i] do if (spelldata.Schools[i] ~= "Ranged") and (spelldata.Schools[i] ~= "Melee") then removetalents = removetalents + TheoryCraft_GetStat(spelldata.Schools[i].."modifier") baseincrease = baseincrease + TheoryCraft_GetStat(spelldata.Schools[i].."baseincrease") end baseincrease = baseincrease+TheoryCraft_GetStat(spelldata.Schools[i].."modifier")+TheoryCraft_GetStat(spelldata.Schools[i].."talentmod") i = i + 1 end local a = TheoryCraft_MeleeMinMaxReader local _ local found if spelldata.dontusemelee then baseincrease = 1 end TheoryCraft_DeleteTable(data) returndata["addeddamage"] = 0 local range for k, pattern in pairs(a) do if strfind(returndata["description"], pattern.pattern) then _, _, data[1], data[2], data[3], data[4], data[5], data[6] = strfind(returndata["description"], pattern.pattern) for k, type in pairs(pattern.type) do if (type == "mindamage") or (type == "maxdamage") then returndata[type] = data[k] range = true end end end end if range then range = nil elseif strfind(returndata["description"], "%d+"..to.."%d+") then range = true returndata["description"] = string.gsub(returndata["description"], "%d+"..to.."%d+", findpattern(findpattern(returndata["description"], "%d+"..to.."%d+"), "%d+")) end for k, pattern in pairs(a) do if strfind(returndata["description"], pattern.pattern) then _, _, data[1], data[2], data[3], data[4], data[5], data[6] = strfind(returndata["description"], pattern.pattern) for k, type in pairs(pattern.type) do if (type == "backstabmult") or (type == "bloodthirstmult") then returndata[type] = tonumber(data[k])/100 else returndata[type] = data[k] end end end end if returndata["bloodthirstmult"] then returndata["mindamage"] = returndata["bloodthirstmult"]*TheoryCraft_Data.Stats["attackpower"] returndata["maxdamage"] = returndata["mindamage"] returndata["backstabmult"] = 1 normalized = 0 end if range then returndata["addeddamage"] = returndata["addeddamage"] + 0.5 end if class ~= "ROGUE" then returndata["addeddamage"] = returndata["addeddamage"]/removetalents end if returndata["backstabmult"] ~= 1 then returndata["backstabmult"] = returndata["backstabmult"]/removetalents end -- Print("("..round(normalized).."+"..returndata["mindamage"]..")*"..returndata["backstabmult"].."+"..returndata["addeddamage"]..")*"..baseincrease) local ranged for k,v in pairs(returndata["schools"]) do if v == "Ranged" then ranged = true end end returndata["mindamage"] = ((normalized+returndata["mindamage"])*returndata["backstabmult"] + returndata["addeddamage"])*baseincrease returndata["maxdamage"] = ((normalized+returndata["maxdamage"])*returndata["backstabmult"] + returndata["addeddamage"])*baseincrease if ranged then returndata["mindamage"] = returndata["mindamage"]+TheoryCraft_GetStat("AmmoDPS")*TheoryCraft_GetStat("RangedSpeed") returndata["maxdamage"] = returndata["maxdamage"]+TheoryCraft_GetStat("AmmoDPS")*TheoryCraft_GetStat("RangedSpeed") end a = TheoryCraft_MeleeMinMaxReplacer local damagetext if returndata["mindamage"] == returndata["maxdamage"] then damagetext = round(returndata["mindamage"]) else damagetext = round(returndata["mindamage"])..to..round(returndata["maxdamage"]) end local blocktext if TheoryCraft_Data.EquipEffects["ShieldEquipped"] then blocktext = floor(TheoryCraft_GetStat("BlockValue")) end for k, pattern in pairs(a) do if strfind(returndata["description"], pattern.search) then local replace = string.gsub(pattern.replacewith, "%$damage%$", damagetext) if (not strfind(replace, "%$blockvalue%$")) or (blocktext) then if blocktext then replace = string.gsub(replace, "%$blockvalue%$", blocktext) end returndata["description"] = string.gsub(returndata["description"], pattern.search, replace) end break end end return elseif (spelldata.isseal) then local a = TheoryCraft_Locale.MinMax local alreadybuffedbonus = TheoryCraft_GetStat("AttackPowerCrusader") local attackbaseincrease = TheoryCraft_GetStat(spelldata.id.."baseincrease") attackbaseincrease = attackbaseincrease + TheoryCraft_GetStat("Meleemodifier")+TheoryCraft_GetStat("Meleetalentmod") attackbaseincrease = attackbaseincrease + TheoryCraft_GetStat(spelldata.id.."modifier")+TheoryCraft_GetStat(spelldata.id.."talentmod") local minDamage, maxDamage, lengthofdamagetext local baseincrease = 1 while spelldata.Schools[i] do if (spelldata.Schools[i] ~= "Ranged") and (spelldata.Schools[i] ~= "Melee") then baseincrease = baseincrease + TheoryCraft_GetStat(spelldata.Schools[i].."baseincrease") end baseincrease = baseincrease+TheoryCraft_GetStat(spelldata.Schools[i].."modifier")+TheoryCraft_GetStat(spelldata.Schools[i].."talentmod") i = i + 1 end if (spelldata.crusader) then local lowDmg, hiDmg, offlowDmg, offhiDmg, posBuff, negBuff, percentmod = UnitDamage("player"); local attackspeed = UnitAttackSpeed("player") lowDmg = lowDmg/attackspeed hiDmg = hiDmg/attackspeed local apbonus = findpattern(description, a.crusader) apbonus = tonumber(findpattern(apbonus, "%d+")) or 0 maxDamage = ((TheoryCraft_Data.Stats["attackpower"]-alreadybuffedbonus)/14*TheoryCraft_Data.EquipEffects["MainSpeed"]+TheoryCraft_Data.EquipEffects["MeleeMax"]) minDamage = ((TheoryCraft_Data.Stats["attackpower"]-alreadybuffedbonus)/14*TheoryCraft_Data.EquipEffects["MainSpeed"]+TheoryCraft_Data.EquipEffects["MeleeMin"]) local averagehit = (maxDamage+minDamage)/2*attackbaseincrease averagehit = (averagehit + averagehit * TheoryCraft_Data.Stats["meleecritchance"]/100)/TheoryCraft_Data.EquipEffects["MainSpeed"] returndata["sealunbuffed"] = averagehit maxDamage = ((TheoryCraft_Data.Stats["attackpower"]+apbonus-alreadybuffedbonus)/14*TheoryCraft_Data.EquipEffects["MainSpeed"]+TheoryCraft_Data.EquipEffects["MeleeMax"]) minDamage = ((TheoryCraft_Data.Stats["attackpower"]+apbonus-alreadybuffedbonus)/14*TheoryCraft_Data.EquipEffects["MainSpeed"]+TheoryCraft_Data.EquipEffects["MeleeMin"]) local averagehit = (maxDamage+minDamage)/2*attackbaseincrease averagehit = (averagehit + averagehit * TheoryCraft_Data.Stats["meleecritchance"]/100)/TheoryCraft_Data.EquipEffects["MainSpeed"] returndata["sealbuffed"] = averagehit elseif (spelldata.command) then minDamage = findpattern(description, "%d+"..to.."%d+") maxDamage = findpattern(minDamage, to.."%d+") minDamage = string.sub(minDamage, string.find(minDamage, "%d+", 0)) maxDamage = string.sub(maxDamage, string.find(maxDamage, "%d+", 0)) lengthofdamagetext = string.len(minDamage..to..maxDamage); minDamage = math.floor((minDamage + plusdam)*baseincrease) maxDamage = math.floor((maxDamage + plusdam)*baseincrease) local tmp2 = string.sub(description, string.find(description, "%d+"..to.."%d+", 0)+lengthofdamagetext) local minDamage2 = findpattern(tmp2, "%d+"..to.."%d+") local maxDamage2 = findpattern(minDamage2, to.."%d+") minDamage2 = string.sub(minDamage2, string.find(minDamage2, "%d+", 0)) maxDamage2 = string.sub(maxDamage2, string.find(maxDamage2, "%d+", 0)) minDamage2 = math.floor((minDamage2 + plusdam2)*baseincrease) maxDamage2 = math.floor((maxDamage2 + plusdam2)*baseincrease) description = string.gsub(description, "%d+"..to.."%d+", "tmpABC", 1) description = string.gsub(description, "%d+"..to.."%d+", minDamage2..to..maxDamage2) description = string.gsub(description, "tmpABC", minDamage..to..maxDamage) maxDamage = ((TheoryCraft_Data.Stats["attackpower"]-alreadybuffedbonus)/14*TheoryCraft_Data.EquipEffects["MainSpeed"]+TheoryCraft_Data.EquipEffects["MeleeMax"])*attackbaseincrease minDamage = ((TheoryCraft_Data.Stats["attackpower"]-alreadybuffedbonus)/14*TheoryCraft_Data.EquipEffects["MainSpeed"]+TheoryCraft_Data.EquipEffects["MeleeMin"])*attackbaseincrease local averagehit = (maxDamage+minDamage)/2 averagehit = averagehit + averagehit * TheoryCraft_Data.Stats["meleecritchance"]/100 returndata["sealunbuffed"] = averagehit/TheoryCraft_Data.EquipEffects["MainSpeed"] averagehit = averagehit+(7/(60/TheoryCraft_Data.EquipEffects["MainSpeed"])*0.7)*averagehit returndata["sealbuffed"] = averagehit/TheoryCraft_Data.EquipEffects["MainSpeed"] elseif (spelldata.righteousness) then minDamage = findpattern(description, "%d+"..to.."%d+") maxDamage = findpattern(minDamage, to.."%d+") minDamage = string.sub(minDamage, string.find(minDamage, "%d+", 0)) maxDamage = string.sub(maxDamage, string.find(maxDamage, "%d+", 0)) lengthofdamagetext = string.len(minDamage..to..maxDamage); minDamage = math.floor((minDamage + plusdam)*baseincrease) maxDamage = math.floor((maxDamage + plusdam)*baseincrease) local tmp2 = string.sub(description, string.find(description, "%d+"..to.."%d+", 0)+lengthofdamagetext) local minDamage2 = findpattern(tmp2, "%d+"..to.."%d+") local maxDamage2 = findpattern(minDamage2, to.."%d+") if minDamage2 and string.find(minDamage2, "%d+") then minDamage2 = string.sub(minDamage2, string.find(minDamage2, "%d+", 0)) maxDamage2 = string.sub(maxDamage2, string.find(maxDamage2, "%d+", 0)) minDamage2 = math.floor((minDamage2 + plusdam2)*baseincrease) maxDamage2 = math.floor((maxDamage2 + plusdam2)*baseincrease) description = string.gsub(description, "%d+"..to.."%d+", "tmpABC", 1) description = string.gsub(description, "%d+"..to.."%d+", minDamage2..to..maxDamage2) description = string.gsub(description, "tmpABC", minDamage..to..maxDamage) else description = string.gsub(description, "%d+"..to.."%d+", minDamage..to..maxDamage) end end returndata["description"] = description elseif (spelldata.holynova) then local minDamage = findpattern(description, "%d+"..to.."%d+") local maxDamage = findpattern(minDamage, to.."%d+") minDamage = findpattern(minDamage, "%d+") maxDamage = findpattern(maxDamage, "%d+") local lengthofdamagetext = string.len(minDamage..to..maxDamage); minDamage = minDamage*baseincrease + plusdam maxDamage = maxDamage*baseincrease + plusdam local minHeal = string.sub(description, string.find(description, "%d+"..to.."%d+")+lengthofdamagetext) minHeal = findpattern(minHeal, "%d+"..to.."%d+") local maxHeal = findpattern(minHeal, to.."%d+") minHeal = findpattern(minHeal, "%d+") maxHeal = findpattern(maxHeal, "%d+") local basehealincrease = TheoryCraft_GetStat("Allbaseincrease")+(TheoryCraft_GetStat("Holybaseincrease") or 0)+(TheoryCraft_GetStat("Healingbaseincrease") or 0) local plusheal = (TheoryCraft_GetStat("All") + TheoryCraft_GetStat("Holy") + TheoryCraft_GetStat("Healing"))*spelldata.percentheal local lengthofhealtext = string.len(minHeal..to..maxHeal); minHeal = (minHeal + plusheal)*basehealincrease maxHeal = (maxHeal + plusheal)*basehealincrease description = string.sub(description, 0, string.find(description, "%d+"..to.."%d+", 0)-1).. round(minDamage)..to..round(maxDamage).. string.sub(description, string.find(description, "%d+"..to.."%d+", 0)+lengthofdamagetext) local descriptionbegin = string.sub(description, 0, string.find(description, "%d+"..to.."%d+")+string.len(minDamage..to..maxDamage)) local descriptionrest = string.sub(description, string.find(description, "%d+"..to.."%d+")+string.len(minDamage..to..maxDamage)+1) descriptionrest=string.sub(descriptionrest, 0, string.find(descriptionrest, "%d+"..to.."%d+", 0)-1).. round(minHeal)..to..round(maxHeal).. string.sub(descriptionrest, string.find(descriptionrest, "%d+"..to.."%d+", 0)+lengthofhealtext) description = descriptionbegin..descriptionrest returndata["description"] = description returndata["critdmgchance"] = returndata["critchance"] returndata["crithealchance"] = returndata["critchance"] returndata["mindamage"] = minDamage returndata["maxdamage"] = maxDamage returndata["minheal"] = minHeal returndata["maxheal"] = maxHeal return else local a = TheoryCraft_SpellMinMaxReader local _ TheoryCraft_DeleteTable(data) local found for k, pattern in pairs(a) do if strfind(returndata["description"], pattern.pattern) then _, _, data[1], data[2], data[3], data[4], data[5], data[6] = strfind(returndata["description"], pattern.pattern) for k, type in pairs(pattern.type) do if type == "bothdamage" then returndata["mindamage"] = tonumber(data[k]) returndata["maxdamage"] = tonumber(data[k]) elseif type == "dotbothdamage" then returndata["dotmindamage"] = tonumber(data[k]) returndata["dotmaxdamage"] = tonumber(data[k]) else returndata[type] = data[k] returndata[type] = data[k] end end found = pattern break end end if found == nil then return end local baseincrease = returndata["baseincrease"] local dotbaseincrease = baseincrease local gearbaseincrease = baseincrease baseincrease = baseincrease*returndata["talentbaseincreaseupfront"] if spelldata.talentsbeforegear == nil then gearbaseincrease = gearbaseincrease*returndata["talentbaseincrease"]*returndata["talentbaseincreaseupfront"] end baseincrease = baseincrease*returndata["talentbaseincrease"] dotbaseincrease = dotbaseincrease*returndata["talentbaseincrease"] local plusdam = (returndata["damfinal"] or 0)*gearbaseincrease local plusdam2 = returndata["plusdam2"] or 0 returndata["backstabmult"] = 1 returndata["basemindamage"] = returndata["mindamage"] returndata["basemaxdamage"] = returndata["maxdamage"] if returndata["mindamage"] then returndata["mindamage"] = returndata["mindamage"]*baseincrease + plusdam end if returndata["maxdamage"] then returndata["maxdamage"] = returndata["maxdamage"]*baseincrease + plusdam end if returndata["dotmindamage"] then returndata["dotmindamage"] = returndata["dotmindamage"]*dotbaseincrease + plusdam2 end if returndata["dotmaxdamage"] then returndata["dotmaxdamage"] = returndata["dotmaxdamage"]*dotbaseincrease + plusdam2 end if returndata["dotmindamage"] and returndata["dotmaxdamage"] then returndata["dotdamage"] = (returndata["dotmindamage"]+returndata["dotmaxdamage"])/2 end if returndata["hotheal"] then returndata["hotheal"] = returndata["hotheal"]*dotbaseincrease + plusdam2 end if returndata["oversecs"] then if returndata["dotdamage"] then returndata["dotdps"] = returndata["dotdamage"]/returndata["oversecs"] end if returndata["hotheal"] then returndata["hothps"] = returndata["hotheal"]/returndata["oversecs"] end end for k, type in pairs(found.type) do if type == "bothdamage" then data[k] = round(returndata["mindamage"]) elseif type == "dotbothdamage" then data[k] = round(returndata["dotmindamage"]) else if tonumber(returndata[type]) then data[k] = round(returndata[type]) else data[k] = returndata[type] end end end local counter = 0 local function replacer() counter = counter + 1 return data[counter] end returndata["description"] = string.gsub(returndata["description"], found.pattern, string.gsub(found.pattern, "(%(.-%))", replacer), 1) end if (spelldata.isheal) then returndata["minheal"] = returndata["mindamage"] returndata["maxheal"] = returndata["maxdamage"] if spelldata.hasdot then returndata["hothps"] = returndata["dotdps"] returndata["hotheal"] = returndata["dotdamage"] end returndata["mindamage"] = nil returndata["maxdamage"] = nil returndata["dotdps"] = nil returndata["dotdamage"] = nil end if (spelldata.drain) then returndata["minheal"] = returndata["mindamage"]+returndata["mindamage"]*returndata["illum"]*baseincrease returndata["maxheal"] = returndata["maxdamage"]+returndata["maxdamage"]*returndata["illum"]*baseincrease end end
412
0.771895
1
0.771895
game-dev
MEDIA
0.656117
game-dev
0.842285
1
0.842285
TelepathicGrunt/RepurposedStructures
2,227
common/src/main/java/com/telepathicgrunt/repurposedstructures/world/processors/BlockRemovalPostProcessor.java
package com.telepathicgrunt.repurposedstructures.world.processors; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import com.telepathicgrunt.repurposedstructures.modinit.RSProcessors; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessor; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorType; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class BlockRemovalPostProcessor extends StructureProcessor { public static final MapCodec<BlockRemovalPostProcessor> CODEC = RecordCodecBuilder.mapCodec((instance) -> instance.group( BuiltInRegistries.BLOCK.byNameCodec().listOf().fieldOf("remove_blocks").orElse(new ArrayList<>()).xmap(HashSet::new, ArrayList::new).forGetter(config -> config.removeBlocks) ).apply(instance, instance.stable(BlockRemovalPostProcessor::new))); private final HashSet<Block> removeBlocks; private BlockRemovalPostProcessor(HashSet<Block> removeBlocks) { this.removeBlocks = removeBlocks; } @Override public List<StructureTemplate.StructureBlockInfo> finalizeProcessing(ServerLevelAccessor serverLevelAccessor, BlockPos blockPos, BlockPos blockPos2, List<StructureTemplate.StructureBlockInfo> list, List<StructureTemplate.StructureBlockInfo> list2, StructurePlaceSettings structurePlaceSettings) { if (removeBlocks.isEmpty()) { return list2; } for(int i = list2.size() - 1; i >= 0; i--) { if (removeBlocks.contains(list2.get(i).state().getBlock())) { list2.remove(i); } } return list2; } @Override protected StructureProcessorType<?> getType() { return RSProcessors.BLOCK_REMOVAL_POST_PROCESSOR.get(); } }
412
0.765576
1
0.765576
game-dev
MEDIA
0.978751
game-dev
0.791626
1
0.791626
1812598631/Amos-slam
2,757
Thirdparty/DBoW2/DUtils/Random.cpp
/* * File: Random.cpp * Project: DUtils library * Author: Dorian Galvez-Lopez * Date: April 2010 * Description: manages pseudo-random numbers * License: see the LICENSE.txt file * */ #include "Random.h" #include "Timestamp.h" #include <cstdlib> using namespace std; bool DUtils::Random::m_already_seeded = false; void DUtils::Random::SeedRand(){ Timestamp time; time.setToCurrentTime(); srand((unsigned)time.getFloatTime()); } void DUtils::Random::SeedRandOnce() { if(!m_already_seeded) { DUtils::Random::SeedRand(); m_already_seeded = true; } } void DUtils::Random::SeedRand(int seed) { srand(seed); } void DUtils::Random::SeedRandOnce(int seed) { if(!m_already_seeded) { DUtils::Random::SeedRand(seed); m_already_seeded = true; } } int DUtils::Random::RandomInt(int min, int max){ int d = max - min + 1; return int(((double)rand()/((double)RAND_MAX + 1.0)) * d) + min; } // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- DUtils::Random::UnrepeatedRandomizer::UnrepeatedRandomizer(int min, int max) { if(min <= max) { m_min = min; m_max = max; } else { m_min = max; m_max = min; } createValues(); } // --------------------------------------------------------------------------- DUtils::Random::UnrepeatedRandomizer::UnrepeatedRandomizer (const DUtils::Random::UnrepeatedRandomizer& rnd) { *this = rnd; } // --------------------------------------------------------------------------- int DUtils::Random::UnrepeatedRandomizer::get() { if(empty()) createValues(); DUtils::Random::SeedRandOnce(); int k = DUtils::Random::RandomInt(0, m_values.size()-1); int ret = m_values[k]; m_values[k] = m_values.back(); m_values.pop_back(); return ret; } // --------------------------------------------------------------------------- void DUtils::Random::UnrepeatedRandomizer::createValues() { int n = m_max - m_min + 1; m_values.resize(n); for(int i = 0; i < n; ++i) m_values[i] = m_min + i; } // --------------------------------------------------------------------------- void DUtils::Random::UnrepeatedRandomizer::reset() { if((int)m_values.size() != m_max - m_min + 1) createValues(); } // --------------------------------------------------------------------------- DUtils::Random::UnrepeatedRandomizer& DUtils::Random::UnrepeatedRandomizer::operator= (const DUtils::Random::UnrepeatedRandomizer& rnd) { if(this != &rnd) { this->m_min = rnd.m_min; this->m_max = rnd.m_max; this->m_values = rnd.m_values; } return *this; } // ---------------------------------------------------------------------------
412
0.820166
1
0.820166
game-dev
MEDIA
0.300135
game-dev
0.906182
1
0.906182
Hiiragi283/ragium
7,258
src/main/kotlin/hiiragi283/ragium/common/block/entity/HTMachineBlockEntity.kt
package hiiragi283.ragium.common.block.entity import hiiragi283.ragium.api.RagiumConst import hiiragi283.ragium.api.RagiumPlatform import hiiragi283.ragium.api.block.entity.HTOwnedBlockEntity import hiiragi283.ragium.api.registry.impl.HTDeferredBlockEntityType import hiiragi283.ragium.api.serialization.codec.VanillaBiCodecs import hiiragi283.ragium.api.serialization.value.HTValueInput import hiiragi283.ragium.api.serialization.value.HTValueOutput import hiiragi283.ragium.api.storage.HTAccessConfiguration import hiiragi283.ragium.api.storage.HTContentListener import hiiragi283.ragium.api.storage.energy.HTEnergyBattery import hiiragi283.ragium.api.storage.holder.HTEnergyStorageHolder import hiiragi283.ragium.api.storage.item.HTItemSlot import hiiragi283.ragium.api.storage.item.getItemStack import hiiragi283.ragium.api.variant.HTVariantKey import hiiragi283.ragium.common.storage.HTAccessConfigCache import hiiragi283.ragium.common.storage.energy.HTEnergyBatteryWrapper import hiiragi283.ragium.common.storage.holder.HTSimpleEnergyStorageHolder import hiiragi283.ragium.common.storage.item.HTMachineUpgradeItemHandler import hiiragi283.ragium.setup.RagiumAttachmentTypes import hiiragi283.ragium.setup.RagiumMenuTypes import net.minecraft.core.BlockPos import net.minecraft.core.Direction import net.minecraft.network.chat.Component import net.minecraft.server.level.ServerLevel import net.minecraft.util.Mth import net.minecraft.world.InteractionHand import net.minecraft.world.InteractionResult import net.minecraft.world.ItemInteractionResult import net.minecraft.world.entity.LivingEntity import net.minecraft.world.entity.player.Player import net.minecraft.world.inventory.ContainerData import net.minecraft.world.item.ItemStack import net.minecraft.world.level.Level import net.minecraft.world.level.block.state.BlockState import net.minecraft.world.phys.BlockHitResult import net.neoforged.neoforge.common.Tags import net.neoforged.neoforge.items.ItemHandlerHelper import java.util.* import java.util.function.Consumer abstract class HTMachineBlockEntity(type: HTDeferredBlockEntityType<*>, pos: BlockPos, state: BlockState) : HTBlockEntity(type, pos, state), HTOwnedBlockEntity, HTAccessConfiguration.Holder { constructor(variant: HTVariantKey.WithBE<*>, pos: BlockPos, state: BlockState) : this(variant.blockEntityHolder, pos, state) val upgradeHandler: HTMachineUpgradeItemHandler get() = getData(RagiumAttachmentTypes.MACHINE_UPGRADE) override fun writeValue(output: HTValueOutput) { super.writeValue(output) output.store(RagiumConst.OWNER, VanillaBiCodecs.UUID, ownerId) accessConfigCache.serialize(output) } override fun readValue(input: HTValueInput) { super.readValue(input) ownerId = input.read(RagiumConst.OWNER, VanillaBiCodecs.UUID) accessConfigCache.deserialize(input) } override fun onRightClickedWithItem( stack: ItemStack, state: BlockState, level: Level, pos: BlockPos, player: Player, hand: InteractionHand, hitResult: BlockHitResult, ): ItemInteractionResult { if (stack.`is`(Tags.Items.TOOLS_WRENCH)) { RagiumMenuTypes.ACCESS_CONFIG.openMenu(player, name, this, ::writeExtraContainerData) return ItemInteractionResult.sidedSuccess(level.isClientSide) } return super.onRightClickedWithItem(stack, state, level, pos, player, hand, hitResult) } override fun onRightClicked( state: BlockState, level: Level, pos: BlockPos, player: Player, hitResult: BlockHitResult, ): InteractionResult = openGui(player, name) protected abstract fun openGui(player: Player, title: Component): InteractionResult override fun setPlacedBy( level: Level, pos: BlockPos, state: BlockState, placer: LivingEntity?, stack: ItemStack, ) { super.setPlacedBy(level, pos, state, placer, stack) this.ownerId = placer?.uuid } override fun dropInventory(consumer: Consumer<ItemStack>) { super.dropInventory(consumer) upgradeHandler.getItemSlots(upgradeHandler.getItemSideFor()).map(HTItemSlot::getItemStack).forEach(consumer) } final override fun getComparatorOutput(state: BlockState, level: Level, pos: BlockPos): Int = ItemHandlerHelper.calcRedstoneFromInventory(getItemHandler(null)) // Ticking // /** * このブロックエンティティがtick当たりで消費する電力の値 */ protected abstract val energyUsage: Int protected var isActive: Boolean = false protected var requiredEnergy: Int = 0 protected var usedEnergy: Int = 0 protected open fun getModifiedEnergy(base: Int): Int = upgradeHandler.getTier()?.modifyProcessorRate(base) ?: base final override fun onUpdateServer(level: ServerLevel, pos: BlockPos, state: BlockState): Boolean { val network: HTEnergyBattery = getter(level) ?: return false val result: Boolean = onUpdateServer(level, pos, state, network) isActive = result return result } protected abstract fun onUpdateServer( level: ServerLevel, pos: BlockPos, state: BlockState, network: HTEnergyBattery, ): Boolean val progress: Float get() { val totalTick: Int = usedEnergy val maxTicks: Int = requiredEnergy if (maxTicks <= 0) return 0f val fixedTotalTicks: Int = totalTick % maxTicks return Mth.clamp(fixedTotalTicks / maxTicks.toFloat(), 0f, 1f) } // Energy Storage // private val getter: (Level?) -> HTEnergyBattery? = RagiumPlatform.INSTANCE::getEnergyNetwork override fun initializeEnergyStorage(listener: HTContentListener): HTEnergyStorageHolder? = createStorageHolder( HTEnergyBatteryWrapper { getter(level) }, ) protected open fun createStorageHolder(battery: HTEnergyBattery): HTEnergyStorageHolder = HTSimpleEnergyStorageHolder.input(this, battery) // HTOwnedBlockEntity // private var ownerId: UUID? = null override fun getOwnerUUID(): UUID { if (ownerId == null) { ownerId = UUID.randomUUID() } return ownerId!! } // HTAccessConfiguration // private val accessConfigCache = HTAccessConfigCache() override fun getAccessConfiguration(side: Direction): HTAccessConfiguration = accessConfigCache.getAccessConfiguration(side) override fun setAccessConfiguration(side: Direction, value: HTAccessConfiguration) { accessConfigCache.setAccessConfiguration(side, value) } // Menu // final override fun getDisplayName(): Component = super.getDisplayName() // Slot // val containerData: ContainerData = object : ContainerData { override fun get(index: Int): Int = when (index) { 0 -> usedEnergy 1 -> requiredEnergy else -> -1 } override fun set(index: Int, value: Int) { when (index) { 0 -> usedEnergy = value 1 -> requiredEnergy = value } } override fun getCount(): Int = 2 } }
412
0.823351
1
0.823351
game-dev
MEDIA
0.991696
game-dev
0.935377
1
0.935377
Misaka-Mikoto-Tech/UIControlBinding
7,246
Assets/3rdParty/XLua/XLua/Src/DelegateBridge.cs
/* * Tencent is pleased to support the open source community by making xLua available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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. */ #if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace XLua { public abstract class DelegateBridgeBase : LuaBase { private Type firstKey = null; private Delegate firstValue = null; private Dictionary<Type, Delegate> bindTo = null; protected int errorFuncRef; public DelegateBridgeBase(int reference, LuaEnv luaenv) : base(reference, luaenv) { errorFuncRef = luaenv.errorFuncRef; } public bool TryGetDelegate(Type key, out Delegate value) { if(key == firstKey) { value = firstValue; return true; } if (bindTo != null) { return bindTo.TryGetValue(key, out value); } value = null; return false; } public void AddDelegate(Type key, Delegate value) { if (key == firstKey) { throw new ArgumentException("An element with the same key already exists in the dictionary."); } if (firstKey == null && bindTo == null) // nothing { firstKey = key; firstValue = value; } else if (firstKey != null && bindTo == null) // one key existed { bindTo = new Dictionary<Type, Delegate>(); bindTo.Add(firstKey, firstValue); firstKey = null; firstValue = null; bindTo.Add(key, value); } else { bindTo.Add(key, value); } } public virtual Delegate GetDelegateByType(Type type) { return null; } } public static class HotfixDelegateBridge { #if UNITY_IPHONE && !UNITY_EDITOR [DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)] public static extern bool xlua_get_hotfix_flag(int idx); [DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)] public static extern void xlua_set_hotfix_flag(int idx, bool flag); #else public static bool xlua_get_hotfix_flag(int idx) { return (idx < DelegateBridge.DelegateBridgeList.Length) && (DelegateBridge.DelegateBridgeList[idx] != null); } #endif public static DelegateBridge Get(int idx) { return DelegateBridge.DelegateBridgeList[idx]; } public static void Set(int idx, DelegateBridge val) { if (idx >= DelegateBridge.DelegateBridgeList.Length) { DelegateBridge[] newList = new DelegateBridge[idx + 1]; for (int i = 0; i < DelegateBridge.DelegateBridgeList.Length; i++) { newList[i] = DelegateBridge.DelegateBridgeList[i]; } DelegateBridge.DelegateBridgeList = newList; } DelegateBridge.DelegateBridgeList[idx] = val; #if UNITY_IPHONE && !UNITY_EDITOR xlua_set_hotfix_flag(idx, val != null); #endif } } public partial class DelegateBridge : DelegateBridgeBase { internal static DelegateBridge[] DelegateBridgeList = new DelegateBridge[0]; public static bool Gen_Flag = false; public DelegateBridge(int reference, LuaEnv luaenv) : base(reference, luaenv) { } #if HOTFIX_ENABLE private int _oldTop = 0; private Stack<int> _stack = new Stack<int>(); public void InvokeSessionStart() { System.Threading.Monitor.Enter(luaEnv.luaEnvLock); var L = luaEnv.L; _stack.Push(_oldTop); _oldTop = LuaAPI.lua_gettop(L); LuaAPI.load_error_func(L, luaEnv.errorFuncRef); LuaAPI.lua_getref(L, luaReference); } public void Invoke(int nRet) { int error = LuaAPI.lua_pcall(luaEnv.L, LuaAPI.lua_gettop(luaEnv.L) - _oldTop - 2, nRet, _oldTop + 1); if (error != 0) { var lastOldTop = _oldTop; InvokeSessionEnd(); luaEnv.ThrowExceptionFromError(lastOldTop); } } public void InvokeSessionEnd() { LuaAPI.lua_settop(luaEnv.L, _oldTop); _oldTop = _stack.Pop(); System.Threading.Monitor.Exit(luaEnv.luaEnvLock); } public TResult InvokeSessionEndWithResult<TResult>() { if (LuaAPI.lua_gettop(luaEnv.L) < _oldTop + 2) { InvokeSessionEnd(); throw new InvalidOperationException("no result!"); } try { TResult ret; luaEnv.translator.Get(luaEnv.L, _oldTop + 2, out ret); return ret; } finally { InvokeSessionEnd(); } } public void InParam<T>(T p) { try { luaEnv.translator.PushByType(luaEnv.L, p); } catch (Exception e) { InvokeSessionEnd(); throw e; } } public void InParams<T>(T[] ps) { try { for (int i = 0; i < ps.Length; i++) { luaEnv.translator.PushByType<T>(luaEnv.L, ps[i]); } } catch (Exception e) { InvokeSessionEnd(); throw e; } } //pos start from 0 public void OutParam<TResult>(int pos, out TResult ret) { if (LuaAPI.lua_gettop(luaEnv.L) < _oldTop + 2 + pos) { InvokeSessionEnd(); throw new InvalidOperationException("no result in " + pos); } try { luaEnv.translator.Get(luaEnv.L, _oldTop + 2 + pos, out ret); } catch (Exception e) { InvokeSessionEnd(); throw e; } } #endif } }
412
0.918727
1
0.918727
game-dev
MEDIA
0.825901
game-dev
0.919898
1
0.919898
Croquetx/thecolony
4,412
Colony-Mac/source/gotomap.c
/*----------------------------------* * The Colony * Copyright 1988 by David A. Smith * All Rights Reserved * David A. Smith * 111 Gold Meadow Dr. * Cary, NC 27513 * (919) 469-8485 *----------------------------------*/ /*----------------------------------------------------------------------* * gotomap.c *----------------------------------------------------------------------* * int GoToMap(mapdata,direction) * char mapdata[5]; * int direction; * OpenDoor(mapdata) * char mapdata[5]; * OpenElevator(mapdata) * char mapdata[5]; * OpenAirLock(mapdata,direction) * char mapdata[5]; * int direction; * UpStairs(mapdata) * char mapdata[5]; * DownStairs(mapdata) * char mapdata[5]; * int GoTo(mapdata) * unsigned char mapdata[5]; * DoUpStairs() * DoDnStairs() *----------------------------------------------------------------------*/ #define EXT extern #include "cgamedefs.h" extern int ctype; /*----------------------------------------------------------------------*/ int GoToMap(mapdata,direction) char mapdata[5]; int direction; { switch(mapdata[0]) { case 0:/*no wall*/ return(FALSE); break; case 1:/*blank wall*/ break; case DOOR: /*Inform("\pDoor");*/ return(OpenDoor(mapdata)); CUnLoad(); break; case WINDOW: break; case SHELVES: break; case UPSTAIRS: /*Inform("\pUpstairs");*/ return(UpStairs(mapdata)); break; case DNSTAIRS: return(DownStairs(mapdata)); break; case CHAR: break; case GLYPH: break; case ELEVATOR: /*Inform("\pElevator");*/ return(OpenElevator(mapdata)); CUnLoad(); break; case TUNNEL: /*Inform("\pTunnel");*/ return(tunnel(FALSE,mapdata)); CUnLoad(); break; case AIRLOCK: /*Inform("\pAirlock");*/ return(OpenAirLock(mapdata,direction)); CUnLoad(); break; } return(FALSE); } /*----------------------------------------------------------------------*/ OpenDoor(mapdata) char mapdata[5]; { if(mapdata[1])/*closed or locked door*/ { if(ctype==0)return(0);/*don't let the robots go if closed or locked*/ if(DoDoor(mapdata[1]))return(GoTo(mapdata)); else return(0); } else /*open door*/ { return(GoTo(mapdata)); } } /*----------------------------------------------------------------------*/ OpenElevator(mapdata) char mapdata[5]; { if(ctype==0)return(0);/*don't let the robots go if closed or locked*/ if(DoElevator(mapdata))return(GoTo(mapdata)); else return(0); } /*----------------------------------------------------------------------*/ OpenAirLock(mapdata,direction) char mapdata[5]; int direction; { if(ctype==0) { if(mapdata[1]||mapdata[2]||mapdata[3]||mapdata[4])return(0); else return(1); } if(DoAirLock(&mapdata[1],direction))return(GoTo(mapdata)); else return(0); } /*----------------------------------------------------------------------*/ UpStairs(mapdata) char mapdata[5]; { int val; if(ctype!=0)if(fl)return(0); val=GoTo(mapdata); if(ctype != 0)DoUpStairs(); return(val); } /*----------------------------------------------------------------------*/ DownStairs(mapdata) char mapdata[5]; { int val; val=GoTo(mapdata); if(ctype != 0)if(fl)DoDnStairs(); return(val); } /*----------------------------------------------------------------------*/ int GoTo(mapdata) unsigned char mapdata[5]; { int xmod,ymod; int val=1; int map,xcell,ycell; /*these values need to be copied because loading a new map file destroys their original values*/ map=mapdata[2]; xcell=mapdata[3]; ycell=mapdata[4]; if((map || xcell || ycell) && ctype==0) return(0);/*don't let the robots go anywhere*/ if(map==127) { TunnelAirlock(); SaveLevel(); BUnLoad(); game=BATTLE; Me.xloc=xcell<<8; Me.yloc=ycell<<8; DrawCompass(); /* DoCompass(1);*/ if(orbit||!(armor||fl)){Terminate(FALSE); return(0);} level=0; return(2); } else if(map==100) { Dimension8(); return(0); } if(xcell && ycell) { if((!map) && robotarray[xcell][ycell])return(0); robotarray[Me.xindex][Me.yindex]=0; xmod=Me.xloc-(Me.xindex<<8); ymod=Me.yloc-(Me.yindex<<8); Me.xloc=((int)xcell<<8)+xmod; Me.xindex=xcell; Me.yloc=((int)ycell<<8)+ymod; Me.yindex=ycell; robotarray[xcell][ycell]=MENUM; val=2; } if(map)load_mapnum((int)mapdata[2],TRUE); return(val); } /*----------------------------------------------------------------------*/ DoUpStairs() { } /*----------------------------------------------------------------------*/ DoDnStairs() { FillRect(&Clip,black); DoClatterSound(); fadein=4; }
412
0.628507
1
0.628507
game-dev
MEDIA
0.533188
game-dev
0.930388
1
0.930388