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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
HellFirePvP/AstralSorcery | 3,533 | src/main/java/hellfirepvp/astralsorcery/common/util/block/BlockStateList.java | /*******************************************************************************
* HellFirePvP / Astral Sorcery 2022
*
* All rights reserved.
* The source code is available on github: https://github.com/HellFirePvP/AstralSorcery
* For further details, see the License file there.
******************************************************************************/
package hellfirepvp.astralsorcery.common.util.block;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import hellfirepvp.astralsorcery.common.data.config.base.ConfiguredBlockStateList;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeConfigSpec;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
/**
* This class is part of the Astral Sorcery Mod
* The complete source code for this mod can be found on github.
* Class: BlockStateList
* Created by HellFirePvP
* Date: 02.08.2020 / 09:23
*/
public class BlockStateList implements BlockPredicate, Predicate<BlockState> {
public static final Codec<BlockStateList> CODEC = RecordCodecBuilder.create(codecBuilder -> codecBuilder.group(
BlockState.CODEC.listOf().fieldOf("blockStates").forGetter(stateList -> {
List<BlockState> applicable = new ArrayList<>();
stateList.configuredMatches.forEach(predicate -> {
predicate.validMatch.ifLeft(applicable::addAll).ifRight(block -> {
applicable.addAll(block.getStateContainer().getValidStates());
});
});
return applicable;
}))
.apply(codecBuilder, states -> {
BlockStateList list = new BlockStateList();
states.forEach(list::add);
return list;
}));
private final List<SimpleBlockPredicate> configuredMatches = new ArrayList<>();
public BlockStateList add(BlockState... states) {
this.configuredMatches.add(new SimpleBlockPredicate(states));
return this;
}
public BlockStateList add(Block block) {
this.configuredMatches.add(new SimpleBlockPredicate(block));
return this;
}
public ConfiguredBlockStateList getAsConfig(ForgeConfigSpec.Builder cfgBuilder, String key, String translationKey, String comment) {
List<String> out = new ArrayList<>();
configuredMatches.stream().map(SimpleBlockPredicate::getAsConfigList).forEach(out::addAll);
return new ConfiguredBlockStateList(cfgBuilder
.comment(comment)
.translation(translationKey)
.define(key, out));
}
public static BlockStateList fromConfig(List<String> serializedBlockPredicates) {
BlockStateList list = new BlockStateList();
for (String str : serializedBlockPredicates) {
SimpleBlockPredicate predicate = SimpleBlockPredicate.fromConfig(str);
if (predicate != null) {
list.configuredMatches.add(predicate);
}
}
return list;
}
@Override
public boolean test(BlockState state) {
return configuredMatches.stream().anyMatch(predicate -> predicate.test(state));
}
@Override
public boolean test(World world, BlockPos pos, BlockState state) {
return configuredMatches.stream().anyMatch(predicate -> predicate.test(world, pos, state));
}
}
| 412 | 0.756698 | 1 | 0.756698 | game-dev | MEDIA | 0.962512 | game-dev | 0.649181 | 1 | 0.649181 |
Sigma-Skidder-Team/SigmaRebase | 4,939 | src/main/java/net/minecraft/block/HoneyBlock.java | package net.minecraft.block;
import net.minecraft.advancements.CriteriaTriggers;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.item.BoatEntity;
import net.minecraft.entity.item.TNTEntity;
import net.minecraft.entity.item.minecart.AbstractMinecartEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.particles.BlockParticleData;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.World;
public class HoneyBlock extends BreakableBlock
{
protected static final VoxelShape SHAPES = Block.makeCuboidShape(1.0D, 0.0D, 1.0D, 15.0D, 15.0D, 15.0D);
public HoneyBlock(AbstractBlock.Properties properties)
{
super(properties);
}
private static boolean hasSlideEffects(Entity entity)
{
return entity instanceof LivingEntity || entity instanceof AbstractMinecartEntity || entity instanceof TNTEntity || entity instanceof BoatEntity;
}
public VoxelShape getCollisionShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context)
{
return SHAPES;
}
/**
* Block's chance to react to a living entity falling on it.
*/
public void onFallenUpon(World worldIn, BlockPos pos, Entity entityIn, float fallDistance)
{
entityIn.playSound(SoundEvents.BLOCK_HONEY_BLOCK_SLIDE, 1.0F, 1.0F);
if (!worldIn.isRemote)
{
worldIn.setEntityState(entityIn, (byte)54);
}
if (entityIn.onLivingFall(fallDistance, 0.2F))
{
entityIn.playSound(this.soundType.getFallSound(), this.soundType.getVolume() * 0.5F, this.soundType.getPitch() * 0.75F);
}
}
public void onEntityCollision(BlockState state, World worldIn, BlockPos pos, Entity entityIn)
{
if (this.isSliding(pos, entityIn))
{
this.triggerSlideDownBlock(entityIn, pos);
this.setSlideVelocity(entityIn);
this.slideEffects(worldIn, entityIn);
}
super.onEntityCollision(state, worldIn, pos, entityIn);
}
private boolean isSliding(BlockPos pos, Entity entity)
{
if (entity.isOnGround())
{
return false;
}
else if (entity.getPosY() > (double)pos.getY() + 0.9375D - 1.0E-7D)
{
return false;
}
else if (entity.getMotion().y >= -0.08D)
{
return false;
}
else
{
double d0 = Math.abs((double)pos.getX() + 0.5D - entity.getPosX());
double d1 = Math.abs((double)pos.getZ() + 0.5D - entity.getPosZ());
double d2 = 0.4375D + (double)(entity.getWidth() / 2.0F);
return d0 + 1.0E-7D > d2 || d1 + 1.0E-7D > d2;
}
}
private void triggerSlideDownBlock(Entity entity, BlockPos pos)
{
if (entity instanceof ServerPlayerEntity && entity.world.getGameTime() % 20L == 0L)
{
CriteriaTriggers.SLIDE_DOWN_BLOCK.test((ServerPlayerEntity)entity, entity.world.getBlockState(pos));
}
}
private void setSlideVelocity(Entity entity)
{
Vector3d vector3d = entity.getMotion();
if (vector3d.y < -0.13D)
{
double d0 = -0.05D / vector3d.y;
entity.setMotion(new Vector3d(vector3d.x * d0, -0.05D, vector3d.z * d0));
}
else
{
entity.setMotion(new Vector3d(vector3d.x, -0.05D, vector3d.z));
}
entity.fallDistance = 0.0F;
}
private void slideEffects(World world, Entity entity)
{
if (hasSlideEffects(entity))
{
if (world.rand.nextInt(5) == 0)
{
entity.playSound(SoundEvents.BLOCK_HONEY_BLOCK_SLIDE, 1.0F, 1.0F);
}
if (!world.isRemote && world.rand.nextInt(5) == 0)
{
world.setEntityState(entity, (byte)53);
}
}
}
public static void entitySlideParticles(Entity entity)
{
slideParticles(entity, 5);
}
public static void livingSlideParticles(Entity entity)
{
slideParticles(entity, 10);
}
private static void slideParticles(Entity entity, int particleCount)
{
if (entity.world.isRemote)
{
BlockState blockstate = Blocks.HONEY_BLOCK.getDefaultState();
for (int i = 0; i < particleCount; ++i)
{
entity.world.addParticle(new BlockParticleData(ParticleTypes.BLOCK, blockstate), entity.getPosX(), entity.getPosY(), entity.getPosZ(), 0.0D, 0.0D, 0.0D);
}
}
}
}
| 412 | 0.870848 | 1 | 0.870848 | game-dev | MEDIA | 0.99068 | game-dev | 0.959196 | 1 | 0.959196 |
LordOfDragons/dragengine | 9,293 | src/deigde/editors/world/src/world/pathfinding/mePathFindTest.cpp | /*
* MIT License
*
* Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mePathFindTest.h"
#include "types/mePathFindTestType.h"
#include "../meWorld.h"
#include <dragengine/deEngine.h>
#include <dragengine/logger/deLogger.h>
#include <dragengine/resources/debug/deDebugDrawerShapeFace.h>
#include <dragengine/resources/debug/deDebugDrawerManager.h>
#include <dragengine/resources/debug/deDebugDrawer.h>
#include <dragengine/resources/navigation/navigator/deNavigator.h>
#include <dragengine/resources/navigation/navigator/deNavigatorType.h>
#include <dragengine/resources/navigation/navigator/deNavigatorManager.h>
#include <dragengine/resources/navigation/space/deNavigationSpace.h>
#include <dragengine/resources/world/deWorld.h>
#include <dragengine/common/exceptions.h>
#include <deigde/gui/wrapper/debugdrawer/igdeWDebugDrawerShape.h>
// Definitions
////////////////
#define LOGSOURCE "World Editor"
// Class mePathFindTest
/////////////////////////
// Constructor, destructor
////////////////////////////
mePathFindTest::mePathFindTest( deEngine *engine ){
if( ! engine ){
DETHROW( deeInvalidParam );
}
pEngine = engine;
pWorld = NULL;
pDDSPath = NULL;
pEngNavigator = NULL;
pLayer = 0;
pBlockingCost = 1000.0f;
pSpaceType = deNavigationSpace::estMesh;
pShowPath = false;
pDirtyPath = true;
try{
pEngNavigator = engine->GetNavigatorManager()->CreateNavigator();
pEngNavigator->SetSpaceType( pSpaceType );
pEngNavigator->SetMaxOutsideDistance( 0.5f );
pEngNavigator->SetBlockingCost( pBlockingCost );
// create debug drawer and shapes
pDebugDrawer = engine->GetDebugDrawerManager()->CreateDebugDrawer();
pDebugDrawer->SetXRay( true );
pDebugDrawer->SetVisible( pShowPath );
pDDSPath = new igdeWDebugDrawerShape;
pDDSPath->SetEdgeColor( decColor( 1.0f, 0.0f, 0.5f, 1.0f ) );
pDDSPath->SetFillColor( decColor( 1.0f, 0.0f, 0.5f, 0.25f ) );
pDDSPath->SetParentDebugDrawer( pDebugDrawer );
}catch( const deException & ){
pCleanUp();
throw;
}
}
mePathFindTest::~mePathFindTest(){
pCleanUp();
}
// Management
///////////////
void mePathFindTest::SetWorld( meWorld *world ){
if( world == pWorld ){
return;
}
if( pWorld ){
pWorld->GetEngineWorld()->RemoveNavigator( pEngNavigator );
pWorld->GetEngineWorld()->RemoveDebugDrawer( pDebugDrawer );
}
pWorld = world;
if( world ){
world->GetEngineWorld()->AddDebugDrawer( pDebugDrawer );
world->GetEngineWorld()->AddNavigator( pEngNavigator );
}
Invalidate();
}
void mePathFindTest::SetStartPosition( const decDVector &position ){
if( pStartPosition.IsEqualTo( position ) ){
return;
}
pStartPosition = position;
pDDSPath->SetPosition( position );
if( pWorld ){
pWorld->NotifyPathFindTestChanged();
}
Invalidate();
}
void mePathFindTest::SetGoalPosition( const decDVector &position ){
if( pGoalPosition.IsEqualTo( position ) ){
return;
}
pGoalPosition = position;
if( pWorld ){
pWorld->NotifyPathFindTestChanged();
}
Invalidate();
}
void mePathFindTest::SetStartOrientation( const decVector &orientation ){
if( orientation.IsEqualTo( pStartOrientation ) ){
return;
}
pStartOrientation = orientation;
//const decQuaternion realor = decQuaternion::CreateFromEuler( orientation * DEG2RAD );
//pEngNavigator->SetOrientation( realor );
if( pWorld ){
pWorld->NotifyPathFindTestChanged();
}
Invalidate();
}
void mePathFindTest::SetGoalOrientation( const decVector &orientation ){
if( orientation.IsEqualTo( pGoalOrientation ) ){
return;
}
pGoalOrientation = orientation;
//const decQuaternion realor = decQuaternion::CreateFromEuler( orientation * DEG2RAD );
//pEngNavigator->SetOrientation( realor );
if( pWorld ){
pWorld->NotifyPathFindTestChanged();
}
Invalidate();
}
void mePathFindTest::SetLayer( int layer ){
if( layer == pLayer ){
return;
}
pLayer = layer;
pEngNavigator->SetLayer( layer );
if( pWorld ){
pWorld->NotifyPathFindTestChanged();
}
Invalidate();
}
void mePathFindTest::SetSpaceType( deNavigationSpace::eSpaceTypes spaceType ){
if( spaceType == pSpaceType ){
return;
}
pSpaceType = spaceType;
pEngNavigator->SetSpaceType( spaceType );
if( pWorld ){
pWorld->NotifyPathFindTestChanged();
}
Invalidate();
}
void mePathFindTest::SetPath( const deNavigatorPath &path ){
pPath = path;
}
void mePathFindTest::SetBlockingCost( float cost ){
if( fabsf( cost - pBlockingCost ) < FLOAT_SAFE_EPSILON ){
return;
}
pBlockingCost = cost;
pEngNavigator->SetBlockingCost( cost );
if( pWorld ){
pWorld->NotifyPathFindTestChanged();
}
Invalidate();
}
void mePathFindTest::SetShowPath( bool showPath ){
if( showPath == pShowPath ){
return;
}
pShowPath = showPath;
pDebugDrawer->SetVisible( showPath );
if( pWorld ){
pWorld->NotifyPathFindTestChanged();
}
}
void mePathFindTest::NotifyTypesChanged(){
pUpdateTypes();
Invalidate();
pWorld->NotifyPathFindTestChanged();
}
void mePathFindTest::Invalidate(){
pDirtyPath = true;
}
void mePathFindTest::Update(){
if( ! pDirtyPath || ! pShowPath ){
return;
}
pEngNavigator->FindPath( pPath, pStartPosition, pGoalPosition );
pUpdateDDPath();
pDirtyPath = false;
}
// Private Functions
//////////////////////
void mePathFindTest::pCleanUp(){
SetWorld( NULL );
if( pEngNavigator ){
pEngNavigator->FreeReference();
}
if( pDDSPath ){
delete pDDSPath;
}
if( pDebugDrawer ){
pDebugDrawer->FreeReference();
}
}
void mePathFindTest::pUpdateDDPath(){
if( ! pDDSPath ){
return;
}
pDDSPath->RemoveAllFaces();
const int count = pPath.GetCount();
if( count == 0 ){
return;
}
const int circlePointCount = 8;
const float radius = 0.02f;
const float circleStep = DEG2RAD * ( 360.0f / ( float )circlePointCount );
const decVector up( 0.0f, 1.0f, 0.0f );
deDebugDrawerShapeFace *ddsFace = NULL;
decVector lastPoints[ circlePointCount ], points[ circlePointCount ];
decVector prevPos, pos, nextPos;
decMatrix matrix;
decVector view;
float len;
int i, j;
try{
for( i=0; i<count; i++ ){
pos = ( pPath.GetAt( i ) - pStartPosition ).ToVector();
if( i > 0 ){
prevPos = ( pPath.GetAt( i - 1 ) - pStartPosition ).ToVector();
}
if( i < count - 1 ){
nextPos = ( pPath.GetAt( i + 1 ) - pStartPosition ).ToVector();
}else{
nextPos = pos;
}
if( i == 0 ){
view = pos - prevPos;
len = view.Length();
if( len < 0.001f ){
view.Set( 0.0f, 0.0f, 1.0f );
}else{
view /= len;
}
matrix.SetWorld( decVector(), view, up );
for( j=0; j<circlePointCount; j++ ){
lastPoints[ j ] = matrix.Transform( radius * sinf( circleStep * ( float )j ), radius * cosf( circleStep * ( float )j ), 0.0f );
}
}
view = nextPos - prevPos;
len = view.Length();
if( len < 0.001f ){
view.Set( 0.0f, 0.0f, 1.0f );
}else{
view /= len;
}
matrix.SetWorld( pos, view, up );
for( j=0; j<circlePointCount; j++ ){
points[ j ] = matrix.Transform( radius * sinf( circleStep * ( float )j ), radius * cosf( circleStep * ( float )j ), 0.0f );
}
for( j=0; j<circlePointCount; j++ ){
ddsFace = new deDebugDrawerShapeFace;
ddsFace->AddVertex( lastPoints[ j ] );
ddsFace->AddVertex( points[ j ] );
ddsFace->AddVertex( points[ ( j + 1 ) % circlePointCount ] );
ddsFace->AddVertex( lastPoints[ ( j + 1 ) % circlePointCount ] );
pDDSPath->AddFace( ddsFace );
ddsFace = NULL;
}
for( j=0; j<circlePointCount; j++ ){
lastPoints[ j ] = points[ j ];
}
}
}catch( const deException & ){
if( ddsFace ){
delete ddsFace;
}
throw;
}
}
void mePathFindTest::pUpdateTypes(){
const int count = pTypeList.GetCount();
int i;
pEngNavigator->RemoveAllTypes();
for( i=0; i<count; i++ ){
const mePathFindTestType &type = *pTypeList.GetAt( i );
deNavigatorType &engType = *pEngNavigator->AddType( type.GetTypeNumber() );
engType.SetFixCost( type.GetFixCost() );
engType.SetCostPerMeter( type.GetCostPerMeter() );
}
pEngNavigator->NotifyTypesChanged();
}
| 412 | 0.974557 | 1 | 0.974557 | game-dev | MEDIA | 0.5801 | game-dev,desktop-app | 0.972353 | 1 | 0.972353 |
alliedmodders/sourcemod | 7,664 | core/NextMap.cpp | /**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include "NextMap.h"
#include "Logger.h"
#include "HalfLife2.h"
#include "sourcemm_api.h"
#include "sm_stringutil.h"
#include "sourcehook.h"
#include "logic_bridge.h"
#include "compat_wrappers.h"
#include <time.h>
#include <bridge/include/ILogger.h>
NextMapManager g_NextMap;
#if SOURCE_ENGINE != SE_DARKMESSIAH
SH_DECL_HOOK2_void(IVEngineServer, ChangeLevel, SH_NOATTRIB, 0, const char *, const char *);
#else
SH_DECL_HOOK4_void(IVEngineServer, ChangeLevel, SH_NOATTRIB, 0, const char *, const char *, const char *, bool);
#endif
#if SOURCE_ENGINE >= SE_ORANGEBOX
SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
#else
SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
#endif
ConCommand *changeLevelCmd = NULL;
ConVar sm_nextmap("sm_nextmap", "", FCVAR_NOTIFY);
ConVar sm_maphistory_size("sm_maphistory_size", "20");
bool g_forcedChange = false;
void NextMapManager::OnSourceModAllInitialized_Post()
{
SH_ADD_HOOK(IVEngineServer, ChangeLevel, engine, SH_MEMBER(this, &NextMapManager::HookChangeLevel), false);
ConCommand *pCmd = FindCommand("changelevel");
if (pCmd != NULL)
{
SH_ADD_HOOK(ConCommand, Dispatch, pCmd, SH_STATIC(CmdChangeLevelCallback), false);
changeLevelCmd = pCmd;
}
}
void NextMapManager::OnSourceModShutdown()
{
SH_REMOVE_HOOK(IVEngineServer, ChangeLevel, engine, SH_MEMBER(this, &NextMapManager::HookChangeLevel), false);
if (changeLevelCmd != NULL)
{
SH_REMOVE_HOOK(ConCommand, Dispatch, changeLevelCmd, SH_STATIC(CmdChangeLevelCallback), false);
}
SourceHook::List<MapChangeData *>::iterator iter;
iter = m_mapHistory.begin();
while (iter != m_mapHistory.end())
{
delete (MapChangeData *)*iter;
iter = m_mapHistory.erase(iter);
}
}
const char *NextMapManager::GetNextMap()
{
return sm_nextmap.GetString();
}
bool NextMapManager::SetNextMap(const char *map)
{
if (!g_HL2.IsMapValid(map))
{
return false;
}
sm_nextmap.SetValue(map);
return true;
}
static char g_nextMap[PLATFORM_MAX_PATH];
#if SOURCE_ENGINE != SE_DARKMESSIAH
void NextMapManager::HookChangeLevel(const char *map, const char *unknown)
#else
void NextMapManager::HookChangeLevel(const char *map, const char *unknown, const char *video, bool bLongLoading)
#endif
{
if (g_forcedChange)
{
logger->LogMessage("[SM] Changed map to \"%s\"", map);
RETURN_META(MRES_IGNORED);
}
const char *newmap = sm_nextmap.GetString();
if (newmap[0] != '\0') {
ke::SafeStrcpy(g_nextMap, sizeof(g_nextMap), newmap);
newmap = g_nextMap;
// Clear the value so that if the map load fails later we don't get stuck in a loop.
// This might cause us to go off-cycle for a map, but nextmap will get us back on track.
sm_nextmap.SetValue("");
}
if (newmap[0] == '\0' || !g_HL2.IsMapValid(newmap))
{
RETURN_META(MRES_IGNORED);
}
logger->LogMessage("[SM] Changed map to \"%s\"", newmap);
ke::SafeStrcpy(m_tempChangeInfo.m_mapName, sizeof(m_tempChangeInfo.m_mapName), newmap);
ke::SafeStrcpy(m_tempChangeInfo.m_changeReason, sizeof(m_tempChangeInfo.m_changeReason), "Normal level change");
#if SOURCE_ENGINE != SE_DARKMESSIAH
RETURN_META_NEWPARAMS(MRES_IGNORED, &IVEngineServer::ChangeLevel, (newmap, unknown));
#else
RETURN_META_NEWPARAMS(MRES_IGNORED, &IVEngineServer::ChangeLevel, (newmap, unknown, video, bLongLoading));
#endif
}
void NextMapManager::OnSourceModLevelChange( const char *mapName )
{
// If we were controlling the map change, reset sm_nextmap to be the name of the map we successfully changed to.
// This maintains an old API contract on the plugin side. We use the real map name even if it was different from
// the expected map name as if the expected map failed to load we let the game take over instead, but the nextmap
// plugin compares the sm_nextmap value to the current map to decide if it should advance the mapcycle.
if (g_nextMap[0] != '\0') {
sm_nextmap.SetValue(mapName);
g_nextMap[0] = '\0';
}
/* Skip the first 'mapchange' when the server starts up */
if (m_tempChangeInfo.startTime != 0)
{
if (strcmp(mapName, m_tempChangeInfo.m_mapName) == 0)
{
/* The map change was as we expected */
m_mapHistory.push_back(new MapChangeData(lastMap, m_tempChangeInfo.m_changeReason, m_tempChangeInfo.startTime));
}
else
{
/* Something intercepted the mapchange */
char newReason[255];
ke::SafeSprintf(newReason, sizeof(newReason), "%s (Map overridden)", m_tempChangeInfo.m_changeReason);
m_mapHistory.push_back(new MapChangeData(lastMap, newReason, m_tempChangeInfo.startTime));
}
int historydiff = sm_maphistory_size.GetInt();
if (historydiff > 0)
{
historydiff -= m_mapHistory.size();
} else if (historydiff < 0)
{
historydiff = (m_mapHistory.size() * -1);
}
for (SourceHook::List<MapChangeData *>::iterator iter = m_mapHistory.begin(); historydiff++ < 0; iter = m_mapHistory.erase(iter))
{
delete (MapChangeData *)*iter;
}
}
m_tempChangeInfo.m_mapName[0] ='\0';
m_tempChangeInfo.m_changeReason[0] = '\0';
m_tempChangeInfo.startTime = time(NULL);
ke::SafeStrcpy(lastMap, sizeof(lastMap), mapName);
}
void NextMapManager::ForceChangeLevel( const char *mapName, const char* changeReason )
{
/* Store the mapname and reason */
ke::SafeStrcpy(m_tempChangeInfo.m_mapName, sizeof(m_tempChangeInfo.m_mapName), mapName);
ke::SafeStrcpy(m_tempChangeInfo.m_changeReason, sizeof(m_tempChangeInfo.m_changeReason), changeReason);
/* Change level and skip our hook */
g_forcedChange = true;
engine->ChangeLevel(mapName, NULL);
g_forcedChange = false;
}
NextMapManager::NextMapManager()
{
m_tempChangeInfo = MapChangeData();
m_mapHistory = SourceHook::List<MapChangeData *>();
}
#if SOURCE_ENGINE >= SE_ORANGEBOX
void CmdChangeLevelCallback(const CCommand &command)
{
#else
void CmdChangeLevelCallback()
{
CCommand command;
#endif
if (command.ArgC() < 2)
{
return;
}
if (g_NextMap.m_tempChangeInfo.m_mapName[0] == '\0')
{
ke::SafeStrcpy(g_NextMap.m_tempChangeInfo.m_mapName, sizeof(g_NextMap.m_tempChangeInfo.m_mapName), command.Arg(1));
ke::SafeStrcpy(g_NextMap.m_tempChangeInfo.m_changeReason, sizeof(g_NextMap.m_tempChangeInfo.m_changeReason), "changelevel Command");
}
}
| 412 | 0.944993 | 1 | 0.944993 | game-dev | MEDIA | 0.414998 | game-dev | 0.826926 | 1 | 0.826926 |
qt/qtwebkit | 7,947 | Source/WebCore/inspector/InspectorTimelineAgent.h | /*
* Copyright (C) 2012 Google Inc. All rights reserved.
* Copyright (C) 2014 University of Washington.
* Copyright (C) 2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef InspectorTimelineAgent_h
#define InspectorTimelineAgent_h
#include "InspectorWebAgentBase.h"
#include "LayoutRect.h"
#include <inspector/InspectorBackendDispatchers.h>
#include <inspector/InspectorFrontendDispatchers.h>
#include <inspector/InspectorValues.h>
#include <inspector/ScriptDebugListener.h>
#include <wtf/Vector.h>
namespace JSC {
class Profile;
}
namespace WebCore {
class Event;
class FloatQuad;
class Frame;
class InspectorPageAgent;
class RenderObject;
class RunLoopObserver;
typedef String ErrorString;
enum class TimelineRecordType {
EventDispatch,
ScheduleStyleRecalculation,
RecalculateStyles,
InvalidateLayout,
Layout,
Paint,
Composite,
RenderingFrame,
TimerInstall,
TimerRemove,
TimerFire,
EvaluateScript,
TimeStamp,
Time,
TimeEnd,
FunctionCall,
ProbeSample,
ConsoleProfile,
RequestAnimationFrame,
CancelAnimationFrame,
FireAnimationFrame,
};
class InspectorTimelineAgent final
: public InspectorAgentBase
, public Inspector::TimelineBackendDispatcherHandler
, public Inspector::ScriptDebugListener {
WTF_MAKE_NONCOPYABLE(InspectorTimelineAgent);
WTF_MAKE_FAST_ALLOCATED;
public:
InspectorTimelineAgent(WebAgentContext&, InspectorPageAgent*);
virtual ~InspectorTimelineAgent();
virtual void didCreateFrontendAndBackend(Inspector::FrontendRouter*, Inspector::BackendDispatcher*) override;
virtual void willDestroyFrontendAndBackend(Inspector::DisconnectReason) override;
virtual void start(ErrorString&, const int* maxCallStackDepth = nullptr) override;
virtual void stop(ErrorString&) override;
int id() const { return m_id; }
void didCommitLoad();
// Methods called from WebCore.
void startFromConsole(JSC::ExecState*, const String &title);
RefPtr<JSC::Profile> stopFromConsole(JSC::ExecState*, const String& title);
// InspectorInstrumentation callbacks.
void didInstallTimer(int timerId, int timeout, bool singleShot, Frame*);
void didRemoveTimer(int timerId, Frame*);
void willFireTimer(int timerId, Frame*);
void didFireTimer();
void willCallFunction(const String& scriptName, int scriptLine, Frame*);
void didCallFunction(Frame*);
void willDispatchEvent(const Event&, Frame*);
void didDispatchEvent();
void willEvaluateScript(const String&, int, Frame&);
void didEvaluateScript(Frame&);
void didInvalidateLayout(Frame&);
void willLayout(Frame&);
void didLayout(RenderObject*);
void willComposite(Frame&);
void didComposite();
void willPaint(Frame&);
void didPaint(RenderObject*, const LayoutRect&);
void willRecalculateStyle(Frame*);
void didRecalculateStyle();
void didScheduleStyleRecalculation(Frame*);
void didTimeStamp(Frame&, const String&);
void didRequestAnimationFrame(int callbackId, Frame*);
void didCancelAnimationFrame(int callbackId, Frame*);
void willFireAnimationFrame(int callbackId, Frame*);
void didFireAnimationFrame();
void time(Frame&, const String&);
void timeEnd(Frame&, const String&);
protected:
// ScriptDebugListener
virtual void didParseSource(JSC::SourceID, const Script&) override { }
virtual void failedToParseSource(const String&, const String&, int, int, const String&) override { }
virtual void didPause(JSC::ExecState*, const Deprecated::ScriptValue&, const Deprecated::ScriptValue&) override { }
virtual void didContinue() override { }
virtual void breakpointActionLog(JSC::ExecState*, const String&) override { }
virtual void breakpointActionSound(int) override { }
virtual void breakpointActionProbe(JSC::ExecState*, const Inspector::ScriptBreakpointAction&, unsigned batchId, unsigned sampleId, const Deprecated::ScriptValue& result) override;
private:
friend class TimelineRecordStack;
struct TimelineRecordEntry {
TimelineRecordEntry()
: type(TimelineRecordType::EventDispatch) { }
TimelineRecordEntry(RefPtr<Inspector::InspectorObject>&& record, RefPtr<Inspector::InspectorObject>&& data, RefPtr<Inspector::InspectorArray>&& children, TimelineRecordType type)
: record(WTFMove(record))
, data(WTFMove(data))
, children(WTFMove(children))
, type(type)
{
}
RefPtr<Inspector::InspectorObject> record;
RefPtr<Inspector::InspectorObject> data;
RefPtr<Inspector::InspectorArray> children;
TimelineRecordType type;
};
void internalStart(const int* maxCallStackDepth = nullptr);
void internalStop();
double timestamp();
void sendEvent(RefPtr<Inspector::InspectorObject>&&);
void appendRecord(RefPtr<Inspector::InspectorObject>&& data, TimelineRecordType, bool captureCallStack, Frame*);
void pushCurrentRecord(RefPtr<Inspector::InspectorObject>&&, TimelineRecordType, bool captureCallStack, Frame*);
void pushCurrentRecord(const TimelineRecordEntry& record) { m_recordStack.append(record); }
TimelineRecordEntry createRecordEntry(RefPtr<Inspector::InspectorObject>&& data, TimelineRecordType, bool captureCallStack, Frame*);
void setFrameIdentifier(Inspector::InspectorObject* record, Frame*);
void didCompleteRecordEntry(const TimelineRecordEntry&);
void didCompleteCurrentRecord(TimelineRecordType);
void addRecordToTimeline(RefPtr<Inspector::InspectorObject>&&, TimelineRecordType);
void clearRecordStack();
void localToPageQuad(const RenderObject&, const LayoutRect&, FloatQuad*);
std::unique_ptr<Inspector::TimelineFrontendDispatcher> m_frontendDispatcher;
RefPtr<Inspector::TimelineBackendDispatcher> m_backendDispatcher;
InspectorPageAgent* m_pageAgent;
Vector<TimelineRecordEntry> m_recordStack;
int m_id { 1 };
int m_maxCallStackDepth { 5 };
Vector<TimelineRecordEntry> m_pendingConsoleProfileRecords;
bool m_enabled { false };
bool m_enabledFromFrontend { false };
#if PLATFORM(COCOA)
std::unique_ptr<WebCore::RunLoopObserver> m_frameStartObserver;
std::unique_ptr<WebCore::RunLoopObserver> m_frameStopObserver;
#endif
int m_runLoopNestingLevel { 0 };
bool m_startedComposite { false };
};
} // namespace WebCore
#endif // !defined(InspectorTimelineAgent_h)
| 412 | 0.885525 | 1 | 0.885525 | game-dev | MEDIA | 0.486204 | game-dev | 0.879671 | 1 | 0.879671 |
Elfansoer/dota-2-lua-abilities | 2,558 | scripts/vscripts/lua_abilities/bane_brain_sap_lua/bane_brain_sap_lua.lua | bane_brain_sap_lua = class({})
--------------------------------------------------------------------------------
-- Custom KV
function bane_brain_sap_lua:GetCooldown( level )
if self:GetCaster():HasScepter() then
return self:GetSpecialValueFor( "cooldown_scepter" )
end
return self.BaseClass.GetCooldown( self, level )
end
--------------------------------------------------------------------------------
-- Ability Cast Filter
function bane_brain_sap_lua:CastFilterResultTarget( hTarget )
local immune = 0
if self:GetCaster():HasScepter() then
immune = DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES
end
local nResult = UnitFilter(
hTarget,
DOTA_UNIT_TARGET_TEAM_ENEMY,
DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP,
immune,
self:GetCaster():GetTeamNumber()
)
if nResult ~= UF_SUCCESS then
return nResult
end
return UF_SUCCESS
end
--------------------------------------------------------------------------------
-- Ability Start
function bane_brain_sap_lua:OnSpellStart()
-- unit identifier
local caster = self:GetCaster()
local target = self:GetCursorTarget()
-- load data
local damage = self:GetSpecialValueFor("brain_sap_damage")
local heal = self:GetSpecialValueFor("tooltip_brain_sap_heal_amt")
-- cancel if linken
if target:TriggerSpellAbsorb( self ) then
return
end
-- heal
caster:Heal( heal, self )
-- damage
local damageTable = {
victim = target,
attacker = caster,
damage = damage,
damage_type = DAMAGE_TYPE_PURE,
ability = self, --Optional.
}
ApplyDamage(damageTable)
-- Play effects
self:PlayEffects( target )
end
--------------------------------------------------------------------------------
function bane_brain_sap_lua:PlayEffects( target )
-- Get Resources
local particle_cast = "particles/units/heroes/hero_bane/bane_sap.vpcf"
local sound_cast = "Hero_Bane.BrainSap"
local sound_target = "Hero_Bane.BrainSap.Target"
-- Create Particle
local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_ABSORIGIN_FOLLOW, self:GetCaster() )
ParticleManager:SetParticleControlEnt(
effect_cast,
0,
self:GetCaster(),
PATTACH_POINT_FOLLOW,
"attach_hitloc",
self:GetCaster():GetOrigin(), -- unknown
true -- unknown, true
)
ParticleManager:SetParticleControlEnt(
effect_cast,
1,
target,
PATTACH_POINT_FOLLOW,
"attach_hitloc",
target:GetOrigin(), -- unknown
true -- unknown, true
)
ParticleManager:ReleaseParticleIndex( effect_cast )
-- Create Sound
EmitSoundOn( sound_cast, self:GetCaster() )
EmitSoundOn( sound_target, target )
end | 412 | 0.793101 | 1 | 0.793101 | game-dev | MEDIA | 0.994067 | game-dev | 0.96751 | 1 | 0.96751 |
Enigma-Game/Enigma | 2,442 | src/stones/BlockerStone.hh | /*
* Copyright (C) 2002,2003,2004 Daniel Heck
* Copyright (C) 2008 Ronald Lamprecht
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef BLOCKERSTONE_HH
#define BLOCKERSTONE_HH
#include "stones.hh"
#include "laser.hh"
#include "stones_internal.hh"
namespace enigma {
/**
* A door like object that can be opened and closed by a BoulderStone. This
* stone represents the closed state of the door. The open state is represented
* by a BlockerItem.
*
* TODO autonaming for keeping identity in groups
* TODO performAction on opening (as notification of boulder triggering)
* TODO animation slowed down by a major factor for PerOxyd compatibility
*/
class BlockerStone : public Stone {
DECL_TRAITS;
private:
enum iState {
SOLID, ///<
SHRINKING, ///<
GROWING ///<
};
public:
BlockerStone(bool solid);
// Object interface
virtual std::string getClass() const;
virtual BlockerStone *clone();
virtual void dispose();
virtual Value message(const Message &m);
// StateObject interface
virtual void toggleState();
virtual int externalState() const;
virtual void setState(int extState);
// GridObject interface
virtual void init_model();
// ModelCallback interface
virtual void animcb();
// Stone interface
virtual StoneResponse collision_response(const StoneContact &sc);
virtual void actor_contact(Actor * a);
virtual void actor_inside(Actor * a);
private:
void setIState(iState newState);
};
} // namespace enigma
#endif
| 412 | 0.829989 | 1 | 0.829989 | game-dev | MEDIA | 0.366654 | game-dev | 0.51281 | 1 | 0.51281 |
MemoriesOfTime/Nukkit-MOT | 1,881 | src/main/java/cn/nukkit/block/BlockWoodBark.java | package cn.nukkit.block;
import cn.nukkit.Player;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemBlock;
import cn.nukkit.math.BlockFace;
public class BlockWoodBark extends BlockWood {
private static final String[] NAMES = {
"Oak Wood",
"Spruce Wood",
"Birch Wood",
"Jungle Wood",
"Acacia Wood",
"Dark Oak Wood",
};
public static final int STRIPPED_BIT = 0b1000;
public BlockWoodBark() {
this(0);
}
public BlockWoodBark(int meta) {
super(meta);
}
@Override
public void setDamage(int meta) {
super.setDamage(meta);
}
@Override
public int getId() {
return WOOD_BARK;
}
@Override
public String getName() {
int variant = (this.getDamage() & 0x7);
String name = variant >= NAMES.length ? NAMES[0] : NAMES[variant];
if ((this.getDamage() & STRIPPED_BIT) != 0) {
name = "Stripped " + name;
}
return name;
}
@Override
protected int getStrippedId() {
return getId();
}
@Override
protected int getStrippedDamage() {
return getDamage() | STRIPPED_BIT;
}
@Override
public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) {
if (face.getAxis().isHorizontal()) {
if (face.getAxis() == BlockFace.Axis.X) {
setDamage(getDamage() | 0x10);
} else {
setDamage(getDamage() | 0x20);
}
}
this.getLevel().setBlock(block, this, true, true);
return true;
}
@Override
public Item toItem() {
int meta = getDamage() & 0xF;
return new ItemBlock(Block.get(WOOD_BARK, meta), meta);
}
}
| 412 | 0.906781 | 1 | 0.906781 | game-dev | MEDIA | 0.974993 | game-dev | 0.83407 | 1 | 0.83407 |
RaiderIO/keystone.guru | 1,490 | database/migrations/2023_05_21_145706_migrate_npcs_to_npc_enemy_forces_table.php | <?php
use App\Models\Mapping\MappingVersion;
use App\Models\Npc\Npc;
use App\Models\Npc\NpcEnemyForces;
use Illuminate\Database\Migrations\Migration;
return new class extends Migration {
/**
* Run the migrations.
*/
public function up(): void
{
// Don't do anything - this should already be done and the result committed to repository
if (config('app.env') !== 'mapping') {
return;
}
$allNpcs = Npc::all();
foreach (MappingVersion::all() as $mappingVersion) {
/** @var MappingVersion $mappingVersion */
foreach ($allNpcs->whereIn('dungeon_id', [-1, $mappingVersion->dungeon_id]) as $npc) {
/** @var \App\Models\Npc\Npc $npc */
NpcEnemyForces::create([
'npc_id' => $npc->id,
'mapping_version_id' => $mappingVersion->id,
'enemy_forces' => $npc->enemy_forces > 0 ? $npc->enemy_forces : 0,
'enemy_forces_teeming' => $npc->enemy_forces_teeming > 0 ? $npc->enemy_forces_teeming : null,
]);
}
}
}
/**
* Reverse the migrations.
*/
public function down(): void
{
// Don't do anything - this should already be done and the result committed to repository
if (config('app.env') !== 'mapping') {
return;
}
DB::table('npc_enemy_forces')->truncate();
}
};
| 412 | 0.832304 | 1 | 0.832304 | game-dev | MEDIA | 0.93914 | game-dev | 0.858933 | 1 | 0.858933 |
narknon/FF7R2UProj | 1,200 | Source/EndGame/Public/EndSmoothTerrainCollisionVolume.h | #pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "EndSmoothTerrainCollisionVolume.generated.h"
class UBodySetup;
class UBoxComponent;
class UEndSmoothTerrainCollisionComponent;
UCLASS(Blueprintable)
class ENDGAME_API AEndSmoothTerrainCollisionVolume : public AActor {
GENERATED_BODY()
public:
private:
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float MaxClimbHeight;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float MinSlopeDiffDegrees;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float MinDebugDrawSlopeDiffDegrees;
public:
UPROPERTY(BlueprintReadWrite, EditAnywhere, Instanced, meta=(AllowPrivateAccess=true))
UBoxComponent* BoxComponent;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Instanced, meta=(AllowPrivateAccess=true))
UEndSmoothTerrainCollisionComponent* CollisionComponent;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
UBodySetup* TempBodySetup;
AEndSmoothTerrainCollisionVolume(const FObjectInitializer& ObjectInitializer);
};
| 412 | 0.820032 | 1 | 0.820032 | game-dev | MEDIA | 0.88243 | game-dev | 0.623775 | 1 | 0.623775 |
h65wang/slide-puzzle-challenge | 5,063 | lib/puzzle/puzzle_piece.dart | import 'package:flutter/material.dart';
import '../data/game_state.dart';
import '../data/board_config.dart';
import 'shiny_text.dart';
/// A UI representation of the [Piece] data object on the screen.
///
/// Each piece should also come with a [PuzzlePieceShadow] and a couple
/// [PuzzlePieceAttachment] on the side, to make it look more realistic when
/// interacting with other pieces.
class PuzzlePiece extends StatefulWidget {
final Piece piece;
final bool disableGestures; // whether to wrap the piece in a GestureDetector
final GameState? gameState;
final VoidCallback? onMove;
const PuzzlePiece({
Key? key,
required this.piece,
this.disableGestures = false,
this.gameState,
this.onMove,
}) : assert(gameState != null || disableGestures,
'Must pass in game state to enable moving.'),
super(key: key);
@override
State<PuzzlePiece> createState() => _PuzzlePieceState();
}
class _PuzzlePieceState extends State<PuzzlePiece> {
bool _dispatched = false;
late Offset _dragStart;
@override
Widget build(BuildContext context) {
final unitSize = BoardConfig.of(context).unitSize;
final child = Container(
width: unitSize * 0.99 + (widget.piece.width - 1) * unitSize,
height: unitSize * 0.99 + (widget.piece.height - 1) * unitSize,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: widget.piece.id == 0
? [
BoardConfig.of(context).corePieceColor1,
BoardConfig.of(context).corePieceColor2,
]
: [
BoardConfig.of(context).pieceColor1,
BoardConfig.of(context).pieceColor2,
],
),
borderRadius: BorderRadius.circular(unitSize * 0.04),
),
child: Center(child: ShinyText(label: widget.piece.label)),
);
if (widget.disableGestures) {
return child;
}
return GestureDetector(
onPanStart: (DragStartDetails details) {
_dispatched = false;
_dragStart = details.localPosition;
},
onPanUpdate: (DragUpdateDetails details) {
if (_dispatched) return;
final delta = details.localPosition - _dragStart;
final direction = _getDirection(delta, 5);
if (direction == null) return;
// Check if the user input is a legal move
if (widget.gameState!.canMove(widget.piece, direction.x, direction.y)) {
// move the piece (this triggers a value notifier)
widget.piece.move(direction.x, direction.y);
// fire the callback
widget.onMove?.call();
// do not dispatch the same move again
_dispatched = true;
}
},
child: child,
);
}
Coordinates? _getDirection(Offset delta, [double minThreshold = 5.0]) {
if (delta.dx.abs() < minThreshold && delta.dy.abs() < minThreshold) {
return null; // ignore tiny movements
}
if (delta.dx.abs() > delta.dy.abs()) {
return Coordinates(delta.dx < 0 ? -1 : 1, 0); // left or right
} else {
return Coordinates(0, delta.dy < 0 ? -1 : 1); // up or down
}
}
}
class PuzzlePieceAttachment extends StatelessWidget {
final Piece piece;
const PuzzlePieceAttachment({
Key? key,
required this.piece,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final unitSize = BoardConfig.of(context).unitSize;
final decoration = DecoratedBox(
decoration: BoxDecoration(
color: BoardConfig.of(context).pieceAttachmentColor,
borderRadius: BorderRadius.circular(unitSize * 0.04),
),
);
return Stack(
clipBehavior: Clip.none,
children: [
SizedBox(
width: piece.width * unitSize * 0.99,
height: piece.height * unitSize * 0.99,
),
Positioned(
top: unitSize * -0.1,
right: unitSize * 0.1,
child: SizedBox(
width: piece.width * unitSize * 0.8,
height: piece.height * unitSize * 0.2,
child: decoration,
),
),
Positioned(
top: unitSize * 0.1,
right: unitSize * -0.1,
child: SizedBox(
width: piece.width * unitSize * 0.2,
height: piece.height * unitSize * 0.8,
child: decoration,
),
),
],
);
}
}
class PuzzlePieceShadow extends StatelessWidget {
final Piece piece;
const PuzzlePieceShadow({
Key? key,
required this.piece,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final unitSize = BoardConfig.of(context).unitSize;
return Container(
width: piece.width * unitSize * 0.99,
height: unitSize * 1.05 + (piece.height - 1) * unitSize,
decoration: BoxDecoration(
color: BoardConfig.of(context).pieceShadowColor,
borderRadius: BorderRadius.circular(unitSize * 0.04),
),
);
}
}
| 412 | 0.955723 | 1 | 0.955723 | game-dev | MEDIA | 0.322442 | game-dev | 0.975557 | 1 | 0.975557 |
caelan-douglas/tinybox | 2,652 | src/ActivatorBrick.gd | # Tinybox
# Copyright (C) 2023-present Caelan Douglas
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
extends MotorController
class_name ActivatorBrick
var acceleration : int = 0
var steering : int = 0
var follow_nearby_player : bool = true
# Set a custom property
func set_property(property : StringName, value : Variant) -> void:
super(property, value)
# set mass after determing mass mult from size
mass = 10 * mass_mult
# Set the material of this brick to a different one,
# and update any related properties.
@rpc("call_local")
func set_material(new : Brick.BrickMaterial) -> void:
# don't change material on activator bricks
pass
@rpc("any_peer", "call_local", "reliable")
func set_colour(new : Color) -> void:
# don't change colour
pass
func _init() -> void:
_brick_spawnable_type = "brick_activator"
properties_to_save = ["global_position", "global_rotation", "brick_scale", "immovable", "indestructible", "acceleration", "steering", "follow_nearby_player"]
func _ready() -> void:
super()
if Global.get_world().tbw_loading:
await Global.get_world().tbw_loaded
await get_tree().create_timer(0.5).timeout
activate()
func _physics_process(delta : float) -> void:
super(delta)
if attached_motors.size() > 0:
if follow_nearby_player:
var nearest : RigidPlayer = null
var nearest_dist : float = 999999
for player : RigidPlayer in Global.get_world().rigidplayer_list:
var dist := player.global_position.distance_to(self.global_position)
if dist < nearest_dist:
nearest = player
nearest_dist = dist
if nearest != null:
var z_vec : Vector3 = global_transform.basis.z
var x_vec : Vector3 = global_transform.basis.x
var rel_pos : Vector3 = (global_position - nearest.global_position).normalized()
var accel : float = z_vec.dot(rel_pos)
var steer : float = -x_vec.dot(rel_pos)
if accel > 0:
accel = 1
elif accel < 0:
accel = -1
else: accel = 0
drive.rpc(accel, (steer * accel))
else:
drive.rpc(acceleration, steering)
| 412 | 0.73142 | 1 | 0.73142 | game-dev | MEDIA | 0.864835 | game-dev | 0.590582 | 1 | 0.590582 |
pWn3d1337/Techguns2 | 6,012 | src/main/java/techguns/tileentities/operation/AmmoPressBuildPlans.java | package techguns.tileentities.operation;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraftforge.oredict.OreDictionary;
import techguns.TGItems;
import techguns.tileentities.AmmoPressTileEnt;
public class AmmoPressBuildPlans {
public static final int AMMOUNT_PISTOL = 12;
public static final int AMMOUNT_SHOTGUN = 16;
public static final int AMMOUNT_RIFLE = 8;
public static final int AMMOUNT_SNIPER = 4;
public static ArrayList<ItemStack> metal1 = new ArrayList<ItemStack>();
public static ArrayList<ItemStack> metal2 = new ArrayList<ItemStack>();
public static ArrayList<ItemStack> powder = new ArrayList<ItemStack>();
public static void init(ArrayList<String> metal1_names, ArrayList<String> metal2_names, ArrayList<String> powder_names) {
if (metal1_names != null) {
for (int i = 0; i < metal1_names.size(); i++) {
String name = metal1_names.get(i);
NonNullList<ItemStack> ores = OreDictionary.getOres(name);
if (ores.size() > 0) {
for (int j = 0; j < ores.size(); j++) {
metal1.add(ores.get(j));
}
}
}
}
if (metal2_names != null) {
for (int i = 0; i < metal2_names.size(); i++) {
String name = metal2_names.get(i);
NonNullList<ItemStack> ores = OreDictionary.getOres(name);
if (ores.size() > 0) {
for (int j = 0; j < ores.size(); j++) {
ItemStack stack = ores.get(j).copy();
stack.setCount(2);
metal2.add(stack);
}
}
}
}
if (powder_names != null) {
for (int i = 0; i < powder_names.size(); i++) {
String name = powder_names.get(i);
NonNullList<ItemStack> ores = OreDictionary.getOres(name);
if (ores.size() > 0) {
for (int j = 0; j < ores.size(); j++) {
powder.add(ores.get(j));
}
}
}
}
}
public static int getAmountForRecipe(int itemdmg) {
if (itemdmg == TGItems.PISTOL_ROUNDS.getItemDamage()) {
return AMMOUNT_PISTOL;
} else if (itemdmg == TGItems.SHOTGUN_ROUNDS.getItemDamage()) {
return AMMOUNT_SHOTGUN;
} else if (itemdmg == TGItems.RIFLE_ROUNDS.getItemDamage()) {
return AMMOUNT_RIFLE;
} else if (itemdmg == TGItems.SNIPER_ROUNDS.getItemDamage()) {
return AMMOUNT_SNIPER;
}
return 1;
}
public static ItemStack[] getPossibleResults() {
return new ItemStack[] { TGItems.newStack(TGItems.PISTOL_ROUNDS, AMMOUNT_PISTOL), TGItems.newStack(TGItems.SHOTGUN_ROUNDS, AMMOUNT_SHOTGUN),
TGItems.newStack(TGItems.RIFLE_ROUNDS, AMMOUNT_RIFLE), TGItems.newStack(TGItems.SNIPER_ROUNDS, AMMOUNT_SNIPER) };
}
public static boolean isInList(ItemStack it, ArrayList<ItemStack> list) {
boolean valid = false;
// System.out.println("Check for:"+it.getDisplayName());
for (int i = 0; i < list.size(); i++) {
// System.out.println("---Check
// against:"+list.get(i).getDisplayName());
if (OreDictionary.itemMatches(list.get(i), it, false)) {
// System.out.println("---Valid");
valid = true;
break;
} else {
// System.out.println("---NOT VALID");
}
}
return valid;
}
public static boolean isValidFor(ItemStack input, int slot) {
switch (slot) {
case AmmoPressTileEnt.SLOT_METAL1:
return isInList(input, metal1);
case AmmoPressTileEnt.SLOT_METAL2:
return isInList(input, metal2);
case AmmoPressTileEnt.SLOT_POWDER:
return isInList(input, powder);
default:
return false;
}
}
public static int getTotalPower(int recipeIndex) {
return 100 * 5;
}
/*
* private static boolean itemStacksEqualForRecipe(ItemStack i1, ItemStack
* i2){ return (OreDictionary.itemMatches(i1, i2,true) ) &&
* (i2.stackSize>=i1.stackSize);
*
* }
*/
public static ItemStack getOutputFor(ItemStack metal1, ItemStack metal2, ItemStack powder, int plan) {
if (isValidFor(metal1, 0) && isValidFor(metal2, 1) && isValidFor(powder, 2)) {
if (metal1.getCount() >= 1 && metal2.getCount() >= 2 && powder.getCount() >= 1) {
switch (plan) {
case 0:
return new ItemStack(TGItems.PISTOL_ROUNDS.getItem(), AMMOUNT_PISTOL, TGItems.PISTOL_ROUNDS.getItemDamage());
case 1:
return new ItemStack(TGItems.SHOTGUN_ROUNDS.getItem(), AMMOUNT_SHOTGUN, TGItems.SHOTGUN_ROUNDS.getItemDamage());
case 2:
return new ItemStack(TGItems.RIFLE_ROUNDS.getItem(), AMMOUNT_RIFLE, TGItems.RIFLE_ROUNDS.getItemDamage());
case 3:
return new ItemStack(TGItems.SNIPER_ROUNDS.getItem(), AMMOUNT_SNIPER, TGItems.SNIPER_ROUNDS.getItemDamage());
}
}
} else {
// System.out.println("Not valid inputs");
}
return ItemStack.EMPTY;
}
public static class AmmoPressMachineRecipe implements IMachineRecipe{
byte plan;
public AmmoPressMachineRecipe(int plan) {
super();
this.plan = (byte) plan;
}
@Override
public List<List<ItemStack>> getItemInputs() {
List<List<ItemStack>> inputs = new ArrayList<List<ItemStack>>();
inputs.add(metal1);
inputs.add(metal2);
inputs.add(powder);
return inputs;
}
@Override
public List<List<ItemStack>> getItemOutputs() {
List<List<ItemStack>> outputs = new ArrayList<List<ItemStack>>();
ArrayList<ItemStack> output = new ArrayList<ItemStack>();
ItemStack stack = ItemStack.EMPTY;
switch (plan) {
case 0:
stack= new ItemStack(TGItems.PISTOL_ROUNDS.getItem(), AMMOUNT_PISTOL, TGItems.PISTOL_ROUNDS.getItemDamage());
break;
case 1:
stack = new ItemStack(TGItems.SHOTGUN_ROUNDS.getItem(), AMMOUNT_SHOTGUN, TGItems.SHOTGUN_ROUNDS.getItemDamage());
break;
case 2:
stack = new ItemStack(TGItems.RIFLE_ROUNDS.getItem(), AMMOUNT_RIFLE, TGItems.RIFLE_ROUNDS.getItemDamage());
break;
case 3:
stack = new ItemStack(TGItems.SNIPER_ROUNDS.getItem(), AMMOUNT_SNIPER, TGItems.SNIPER_ROUNDS.getItemDamage());
break;
}
output.add(stack);
outputs.add(output);
return outputs;
}
}
public static IMachineRecipe getRecipeForType(int type) {
IMachineRecipe rec = new AmmoPressMachineRecipe(type);
return rec;
}
}
| 412 | 0.759973 | 1 | 0.759973 | game-dev | MEDIA | 0.987139 | game-dev | 0.925033 | 1 | 0.925033 |
deephaven/deephaven-core | 1,230 | engine/table/src/main/java/io/deephaven/engine/table/impl/sources/regioned/DeferredColumnRegionShort.java | //
// Copyright (c) 2016-2025 Deephaven Data Labs and Patent Pending
//
// ****** AUTO-GENERATED CLASS - DO NOT EDIT MANUALLY
// ****** Edit DeferredColumnRegionChar and run "./gradlew replicateRegionsAndRegionedSources" to regenerate
//
// @formatter:off
package io.deephaven.engine.table.impl.sources.regioned;
import io.deephaven.chunk.attributes.Any;
import org.jetbrains.annotations.NotNull;
import java.util.function.Supplier;
/**
* {@link ColumnRegionShort} implementation for deferred regions, i.e. regions that will be properly constructed on first
* access.
*/
public class DeferredColumnRegionShort<ATTR extends Any>
extends DeferredColumnRegionBase<ATTR, ColumnRegionShort<ATTR>>
implements ColumnRegionShort<ATTR> {
DeferredColumnRegionShort(final long pageMask, @NotNull Supplier<ColumnRegionShort<ATTR>> resultRegionFactory) {
super(pageMask, resultRegionFactory);
}
@Override
public short getShort(final long elementIndex) {
return getResultRegion().getShort(elementIndex);
}
@Override
public short getShort(@NotNull final FillContext context, final long elementIndex) {
return getResultRegion().getShort(context, elementIndex);
}
}
| 412 | 0.837039 | 1 | 0.837039 | game-dev | MEDIA | 0.446281 | game-dev,graphics-rendering | 0.670434 | 1 | 0.670434 |
eclipse-4diac/4diac-forte | 3,540 | src/stdfblib/ita/RMT_RES.cpp | /*******************************************************************************
* Copyright (c) 2005 - 2015 ACIN, Profactor GmbH, fortiss GmbH
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Alois Zoitl, Gerhard Ebenhofer, Rene Smodic, Thomas Strasser,
* Martin Melik Merkumians, Ingo Hegny
* - initial API and implementation and/or initial documentation
*******************************************************************************/
#include "RMT_RES.h"
#ifdef FORTE_ENABLE_GENERATED_SOURCE_CPP
#include "RMT_RES_gen.cpp"
#endif
#include "../../core/ecet.h"
DEFINE_FIRMWARE_FB(RMT_RES, g_nStringIdRMT_RES);
const CStringDictionary::TStringId RMT_RES::scm_aunVarInputNameIds[] = {g_nStringIdMGR_ID};
const CStringDictionary::TStringId RMT_RES::scm_aunDIDataTypeIds[] = {g_nStringIdWSTRING};
const SFBInterfaceSpec RMT_RES::scm_stFBInterfaceSpec = {
0,
0,
0,
0,
0,
0,
0,
0,
1,
scm_aunVarInputNameIds,
scm_aunDIDataTypeIds,
0,
0,
0,
0,
0
};
RMT_RES::RMT_RES(CStringDictionary::TStringId pa_nInstanceNameId, CResource* pa_poDevice):
CResource(pa_poDevice, &scm_stFBInterfaceSpec, pa_nInstanceNameId, m_anFBConnData, m_anFBVarsData){
addFB(CTypeLib::createFB(g_nStringIdSTART, g_nStringIdE_RESTART, this));
addFB(CTypeLib::createFB(g_nStringIdMGR_FF, g_nStringIdE_SR, this));
addFB(CTypeLib::createFB(g_nStringIdMGR, g_nStringIdDEV_MGR, this));
forte::core::SManagementCMD command;
command.mFirstParam.pushBack(g_nStringIdSTART);
command.mFirstParam.pushBack(g_nStringIdCOLD);
command.mSecondParam.pushBack(g_nStringIdMGR_FF);
command.mSecondParam.pushBack(g_nStringIdS);
createConnection(command);
command.mFirstParam.clear();
command.mFirstParam.pushBack(g_nStringIdSTART);
command.mFirstParam.pushBack(g_nStringIdwARM);
command.mSecondParam.clear();
command.mSecondParam.pushBack(g_nStringIdMGR_FF);
command.mSecondParam.pushBack(g_nStringIdS);
createConnection(command);
command.mFirstParam.clear();
command.mFirstParam.pushBack(g_nStringIdSTART);
command.mFirstParam.pushBack(g_nStringIdSTOP);
command.mSecondParam.clear();
command.mSecondParam.pushBack(g_nStringIdMGR_FF);
command.mSecondParam.pushBack(g_nStringIdR);
createConnection(command);
command.mFirstParam.clear();
command.mFirstParam.pushBack(g_nStringIdMGR_FF);
command.mFirstParam.pushBack(g_nStringIdEO);
command.mSecondParam.clear();
command.mSecondParam.pushBack(g_nStringIdMGR);
command.mSecondParam.pushBack(g_nStringIdINIT);
createConnection(command);
command.mFirstParam.clear();
command.mFirstParam.pushBack(g_nStringIdMGR_FF);
command.mFirstParam.pushBack(g_nStringIdQ);
command.mSecondParam.clear();
command.mSecondParam.pushBack(g_nStringIdMGR);
command.mSecondParam.pushBack(g_nStringIdQI);
createConnection(command);
command.mFirstParam.clear();
command.mFirstParam.pushBack(g_nStringIdMGR_ID);
command.mSecondParam.clear();
command.mSecondParam.pushBack(g_nStringIdMGR);
command.mSecondParam.pushBack(g_nStringIdID);
createConnection(command);
//Perform reset command normally done by the typelib during the creation process
changeFBExecutionState(cg_nMGM_CMD_Reset);
}
RMT_RES::~RMT_RES(){
}
void RMT_RES::joinResourceThread() const {
getResourceEventExecution()->joinEventChainExecutionThread();
}
| 412 | 0.692814 | 1 | 0.692814 | game-dev | MEDIA | 0.153607 | game-dev | 0.688445 | 1 | 0.688445 |
PlayFab/UnrealMarketplacePlugin | 1,285 | 4.26/PlayFabPlugin/PlayFab/Source/PlayFabCommon/PlayFabCommon.Build.cs | //////////////////////////////////////////////////////
// Copyright (C) Microsoft. 2018. All rights reserved.
//////////////////////////////////////////////////////
using UnrealBuildTool;
using System.IO;
public class PlayFabCommon : ModuleRules
{
public PlayFabCommon(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicIncludePaths.Add(Path.Combine(ModuleDirectory, "Public"));
PrivateIncludePaths.Add(Path.Combine(ModuleDirectory, "Private"));
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
"HTTP",
"Json",
"JsonUtilities",
}
);
if (Target.bBuildEditor == true)
{
PrivateDependencyModuleNames.AddRange(new string[] {
"Settings"
});
}
BuildVersion Version;
BuildVersion.TryRead(BuildVersion.GetDefaultFileName(), out Version);
PublicDefinitions.Add(string.Format("ENGINE_MAJOR_VERSION={0}", Version.MajorVersion));
PublicDefinitions.Add(string.Format("ENGINE_MINOR_VERSION={0}", Version.MinorVersion));
}
}
| 412 | 0.773384 | 1 | 0.773384 | game-dev | MEDIA | 0.802614 | game-dev | 0.795866 | 1 | 0.795866 |
wangzexi/NodeMCU-Tutorial | 1,592 | 相关资源/nodemcu-flasher-master/SerialPortsCtrl.pas | // -----------------------------------------------------------------------------
// Դڻ,лԭ.
// http://bbs.csdn.net/topics/310211601
// -----------------------------------------------------------------------------
// : SerialPortsCtrl
// ע: нӿö
// -----------------------------------------------------------------------------
unit SerialPortsCtrl;
interface
uses
Windows, Classes, ExtCtrls;
procedure EnumComPorts(Ports: TStrings);
implementation
procedure EnumComPorts(Ports: TStrings);
var
KeyHandle: HKEY;
ErrCode, Index: Integer;
ValueName, Data: string;
ValueLen, DataLen, ValueType: DWORD;
TmpPorts: TStringList;
begin
ErrCode := RegOpenKeyEx(HKEY_LOCAL_MACHINE, 'HARDWARE\DEVICEMAP\SERIALCOMM',
0, KEY_READ, KeyHandle);
if ErrCode <> ERROR_SUCCESS then
Exit; // raise EComPort.Create(CError_RegError, ErrCode);
TmpPorts := TStringList.Create;
try
Index := 0;
repeat
ValueLen := 256;
DataLen := 256;
SetLength(ValueName, ValueLen);
SetLength(Data, DataLen);
ErrCode := RegEnumValue(KeyHandle, Index, PChar(ValueName),
Cardinal(ValueLen), nil, @ValueType, PByte(PChar(Data)), @DataLen);
if ErrCode = ERROR_SUCCESS then
begin
SetLength(Data, DataLen);
TmpPorts.Add(Data);
Inc(Index);
end
else if ErrCode <> ERROR_NO_MORE_ITEMS then
Exit; // raise EComPort.Create(CError_RegError, ErrCode);
until (ErrCode <> ERROR_SUCCESS);
TmpPorts.Sort;
Ports.Assign(TmpPorts);
finally
RegCloseKey(KeyHandle);
TmpPorts.Free;
end;
end;
end.
| 412 | 0.720324 | 1 | 0.720324 | game-dev | MEDIA | 0.92169 | game-dev | 0.777936 | 1 | 0.777936 |
Xentios/DinoWithBlackjack | 3,326 | Assets/Plugins/Simple Pie Menu/Scripts/Pie Menu/PieMenu.cs | using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
namespace SimplePieMenu
{
[ExecuteInEditMode]
public class PieMenu : MonoBehaviour
{
public PieMenuInfo PieMenuInfo { get; private set; }
public PieMenuElements PieMenuElements { get; private set; }
public MenuItemsTracker MenuItemsTracker { get; private set; }
public MenuItemSelectionHandler SelectionHandler { get; private set; }
public MenuItemTemplate MenuItemTemplate { get; private set; }
public event System.Action OnComponentsInitialized;
public event System.Action OnPieMenuFullyInitialized;
#if UNITY_EDITOR
private void OnEnable()
{
AssemblyReloadEvents.afterAssemblyReload += OnAfterAssemblyReload;
}
private void OnDisable()
{
AssemblyReloadEvents.afterAssemblyReload -= OnAfterAssemblyReload;
}
#endif
private void Start()
{
InitializePieMenu();
}
private void OnAfterAssemblyReload()
{
InitializePieMenu();
}
public Dictionary<int, PieMenuItem> GetMenuItems()
{
return MenuItemsTracker.PieMenuItems;
}
public Transform GetTemplate()
{
return MenuItemTemplate.GetTemplate(MenuItemsTracker.PieMenuItems).transform;
}
private void InitializePieMenu()
{
if (PrefabIsolationModeHelper.IsInPrefabIsolationMode()) return;
InitializeComponents();
ReadDataAndSetPieMenuInfoFields();
OnComponentsInitialized?.Invoke();
OnPieMenuFullyInitialized?.Invoke();
if (gameObject.activeSelf && Application.isPlaying)
{
PieMenuShared.References.PieMenuToggler.SetActive(this, true);
}
}
private void InitializeComponents()
{
PieMenuInfo = GetComponentInChildren<PieMenuInfo>();
PieMenuElements = GetComponentInChildren<PieMenuElements>();
MenuItemsTracker = GetComponentInChildren<MenuItemsTracker>();
MenuItemsTracker.Initialize(PieMenuElements.MenuItemsDir);
SelectionHandler = GetComponentInChildren<MenuItemSelectionHandler>();
MenuItemTemplate = PieMenuShared.References.MenuItemTemplate;
}
private void ReadDataAndSetPieMenuInfoFields()
{
PieMenuInfo.SetFillAmount(GetTemplate().GetComponent<Image>().fillAmount);
float menuItemInitialSize = MenuItemTemplate.MenuItem.GetComponent<RectTransform>().sizeDelta.x;
PieMenuInfo.SetMenuItemInitialSize((int)menuItemInitialSize);
float menuItemSize = GetTemplate().GetComponent<RectTransform>().sizeDelta.x;
PieMenuInfo.SetMenuItemSize((int)menuItemSize);
float scale = PieMenuSizeHandler.CalculatePieMenuScale(this, (int)menuItemSize);
PieMenuInfo.SetScale(scale);
int rotation = (int)PieMenuElements.MenuItemsDir.rotation.eulerAngles.z;
PieMenuInfo.SetRotation(rotation);
RectTransform rectTransform = GetComponent<RectTransform>();
PieMenuInfo.SetAnchoredPosition(rectTransform);
}
}
}
| 412 | 0.783521 | 1 | 0.783521 | game-dev | MEDIA | 0.810704 | game-dev | 0.90868 | 1 | 0.90868 |
OpenXRay/xray-16 | 4,555 | src/xrGame/memory_space.h | ////////////////////////////////////////////////////////////////////////////
// Module : memory_space.h
// Created : 25.12.2003
// Modified : 25.12.2003
// Author : Dmitriy Iassenev
// Description : Memory space
////////////////////////////////////////////////////////////////////////////
#pragma once
#include "ai_sounds.h"
#include "xrServer_Space.h"
#include "alife_space.h"
#include "xrCore/_flags.h"
#include "xrCommon/misc_math_types.h"
//#define USE_GAME_TIME
#define USE_LEVEL_TIME
#ifdef USE_GAME_TIME
#define USE_LAST_GAME_TIME
#endif
#ifdef USE_LEVEL_TIME
#define USE_LAST_LEVEL_TIME
#endif
#ifdef USE_GAME_TIME
#define USE_FIRST_GAME_TIME
#endif
#ifdef USE_LEVEL_TIME
//# define USE_FIRST_LEVEL_TIME
#endif
//#define USE_UPDATE_COUNT
//#define USE_ORIENTATION
#define USE_STALKER_VISION_FOR_MONSTERS
class CEntityAlive;
class CGameObject;
namespace MemorySpace
{
typedef u64 squad_mask_type;
struct CNotYetVisibleObject
{
const CGameObject* m_object;
float m_value;
u32 m_update_time;
u32 m_prev_time;
};
struct SObjectParams
{
u32 m_level_vertex_id;
Fvector m_position;
#ifdef USE_ORIENTATION
SRotation m_orientation;
#endif
};
template <typename T>
struct CObjectParams : public SObjectParams
{
IC SRotation orientation(const T* object) const;
IC void fill(const T* game_object);
};
struct SMemoryObject
{
#ifdef USE_GAME_TIME
ALife::_TIME_ID m_game_time;
#endif
#ifdef USE_LEVEL_TIME
u32 m_level_time;
#endif
#ifdef USE_LAST_GAME_TIME
ALife::_TIME_ID m_last_game_time;
#endif
#ifdef USE_LAST_LEVEL_TIME
u32 m_last_level_time;
#endif
#ifdef USE_FIRST_GAME_TIME
ALife::_TIME_ID m_first_game_time;
#endif
#ifdef USE_FIRST_LEVEL_TIME
u32 m_first_level_time;
#endif
#ifdef USE_UPDATE_COUNT
u32 m_update_count;
#endif
bool m_enabled;
SMemoryObject()
:
#ifdef USE_GAME_TIME
m_game_time(0),
#endif
#ifdef USE_LEVEL_TIME
m_level_time(0),
#endif
#ifdef USE_LAST_GAME_TIME
m_last_game_time(0),
#endif
#ifdef USE_LAST_LEVEL_TIME
m_last_level_time(0),
#endif
#ifdef USE_FIRST_GAME_TIME
m_first_game_time(0),
#endif
#ifdef USE_FIRST_LEVEL_TIME
m_first_level_time(0),
#endif
#ifdef USE_UPDATE_COUNT
m_update_count(0),
#endif
m_enabled(true)
{
}
IC void fill() { m_enabled = true; }
};
template <typename T>
struct CMemoryObject : public SMemoryObject
{
const T* m_object;
CObjectParams<T> m_object_params;
CObjectParams<T> m_self_params;
_flags<squad_mask_type> m_squad_mask;
IC CMemoryObject();
IC bool operator==(u16 id) const;
IC void fill(const T* game_object, const T* self, const squad_mask_type& mask);
};
struct CVisibleObject : CMemoryObject<CGameObject>
{
typedef CMemoryObject<CGameObject> inherited;
_flags<squad_mask_type> m_visible;
public:
IC CVisibleObject() { m_visible.zero(); }
[[nodiscard]]
IC bool visible(const squad_mask_type& mask) const { return (!!m_visible.test(mask)); }
IC void visible(const squad_mask_type& mask, bool value) { m_visible.set(mask, value); }
IC void fill(const CGameObject* game_object, const CGameObject* self, const squad_mask_type& mask,
const squad_mask_type& visibility_mask)
{
inherited::fill(game_object, self, mask);
m_visible.set(visibility_mask, TRUE);
}
};
struct CHitObject : public CMemoryObject<CEntityAlive>
{
Fvector m_direction;
u16 m_bone_index;
float m_amount;
};
struct CSoundObject : public CMemoryObject<CGameObject>
{
ESoundTypes m_sound_type;
float m_power;
IC void fill(const CGameObject* game_object, const CGameObject* self, const ESoundTypes sound_type,
const float sound_power, const squad_mask_type& mask)
{
CMemoryObject<CGameObject>::fill(game_object, self, mask);
m_sound_type = sound_type;
m_power = sound_power;
}
IC int sound_type() const { return (int(m_sound_type)); }
};
struct CMemoryInfo : public CVisibleObject
{
bool m_visual_info;
bool m_sound_info;
bool m_hit_info;
CMemoryInfo()
{
m_visual_info = false;
m_sound_info = false;
m_hit_info = false;
}
private:
DECLARE_SCRIPT_REGISTER_FUNCTION();
};
template <typename T>
struct SLevelTimePredicate
{
bool operator()(const CMemoryObject<T>& object1, const CMemoryObject<T>& object2) const
{
return (object1.m_level_time < object2.m_level_time);
}
};
};
using namespace MemorySpace;
| 412 | 0.897826 | 1 | 0.897826 | game-dev | MEDIA | 0.956731 | game-dev | 0.639354 | 1 | 0.639354 |
GrognardsFromHell/TemplePlus | 3,670 | TemplePlus/ui/ui_char_editor.h | #pragma once
#include "common.h"
#include <spell_structs.h>
#include <EASTL/fixed_string.h>
#include <EASTL/hash_map.h>
#include "EASTL/vector.h"
#include "ui_chargen.h"
struct UiResizeArgs;
struct GameSystemConf;
struct KnownSpellInfo {
int spEnum = 0;
/* spFlag (not actually flag, just status)
1 - denotes a replaceable spell (e.g. for sorcerers)
2 - replaced spell (i.e. the slot had a previous spell and now has a new one)
3 - new spell slot; use 0 for the spell level labels
*/
uint8_t spFlag = 0;
int spellClass = 0;
int spellLevel = 0;
KnownSpellInfo() { spEnum = 0; spFlag = 0; spellClass = 0; };
KnownSpellInfo(int SpellEnum, int SpellFlag);
KnownSpellInfo(int SpellEnum, int SpellFlag, int SpellClass);
KnownSpellInfo(int SpellEnum, int SpellFlag, int SpellClass, int isDomain);
};
enum FeatInfoFlag
{
NoFeatInfoFlag = 0,
DisregardPrereqs = 4,
BonusOnly = 8
};
enum CharEditorStages : int {
CE_Stage_Class = 0,
CE_Stage_Stats,
CE_Stage_Features,
CE_Stage_Skills,
CE_Stage_Feats,
CE_Stage_Spells,
CE_STAGE_COUNT
};
class CharEditorSystem {
public:
virtual const std::string &GetName() const = 0;
virtual ~CharEditorSystem() = default;
//CharEditorSystem(const GameSystemConf &) = delete;
virtual BOOL Resize(const UiResizeArgs &) =0;
int pad; // possibly some unused callback?
void(__cdecl *free)();
void(__cdecl *hide)();
void(__cdecl *show)();
int(__cdecl *checkComplete)(); // checks if the char editing stage is complete (thus allowing you to move on to the next stage). This is checked at every render call.
int(__cdecl*debugMaybe)();
void(__cdecl *reset)(CharEditorSelectionPacket & editSpec);
BOOL(__cdecl *activate)(); // inits values and sets appropriate states for buttons based on gameplay logic (e.g. stuff exclusive to certain classes etc.)
};
class CharEditorClassSystem : public CharEditorSystem {
public:
static constexpr auto Name = "char_editor_class";
CharEditorClassSystem(const GameSystemConf &config);
~CharEditorClassSystem();
const std::string &GetName() const override;
};
const auto testSizeOfCharEditorSelectionPacket = sizeof(CharEditorSelectionPacket); // should be 3640 (0xE38)
/*
Used by UiCharEditor and UiPcCreation systems
*/
class Chargen {
public:
objHndl GetEditedChar();
CharEditorSelectionPacket & GetCharEditorSelPacket();
std::vector<KnownSpellInfo>& GetKnownSpellInfo();
std::vector<KnownSpellInfo> &GetAvailableSpells();
int * GetRolledStats();
int GetRolledStatIdx(int x, int y, int *xyOut = nullptr); // gets the index of the Rolled Stats button according to the mouse position. Returns -1 if none.
void SetIsNewChar(bool state);
bool IsNewChar(void);
bool IsSelectingFeats();
bool SpellsNeedReset();
void SpellsNeedResetSet(bool value);
// utilities
bool SpellIsAlreadyKnown(int spEnum, int spellClass);
bool SpellIsForbidden(int spEnum, int spellClass);
void BonusFeatsClear();
void SetBonusFeats(std::vector<FeatInfo> & fti);
int GetNewLvl(Stat classCode = stat_level);
bool IsClassBonusFeat(feat_enums feat);
bool IsBonusFeatDisregardingPrereqs(feat_enums feat);
bool IsBonusOnlyFeat(feat_enums feat);
eastl::vector<string> levelLabels;
eastl::vector<string> spellLevelLabels;
protected:
std::vector<KnownSpellInfo> mSpellInfo;
std::vector<KnownSpellInfo> mAvailableSpells; // spells available for learning
std::vector<FeatInfo> mExistingFeats, mSelectableFeats, mMultiSelectFeats, mMultiSelectMasterFeats, mBonusFeats;
bool mSpellsNeedReset;
bool mIsNewChar = false; // used in differentiating new character generation vs. levelup
};
extern Chargen chargen;
int HookedFeatMultiselectSub_101A8080(feat_enums feat); | 412 | 0.915091 | 1 | 0.915091 | game-dev | MEDIA | 0.857475 | game-dev | 0.689235 | 1 | 0.689235 |
NEZNAMY/TAB | 1,449 | bukkit/v1_7_R2/src/main/java/me/neznamy/tab/platforms/bukkit/v1_7_R2/NMSImplementationProvider.java | package me.neznamy.tab.platforms.bukkit.v1_7_R2;
import io.netty.channel.Channel;
import lombok.Getter;
import me.neznamy.tab.platforms.bukkit.BukkitTabPlayer;
import me.neznamy.tab.platforms.bukkit.provider.ComponentConverter;
import me.neznamy.tab.platforms.bukkit.provider.ImplementationProvider;
import me.neznamy.tab.shared.platform.Scoreboard;
import me.neznamy.tab.shared.platform.TabList;
import me.neznamy.tab.shared.util.function.FunctionWithException;
import org.bukkit.craftbukkit.v1_7_R2.entity.CraftPlayer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Implementation provider using direct NMS code for 1.7.5.
*/
@Getter
public class NMSImplementationProvider implements ImplementationProvider {
@NotNull
private final ComponentConverter<?> componentConverter = new NMSComponentConverter();
@Override
@NotNull
public Scoreboard newScoreboard(@NotNull BukkitTabPlayer player) {
return new NMSPacketScoreboard(player);
}
@Override
@NotNull
public TabList newTabList(@NotNull BukkitTabPlayer player) {
return new NMSPacketTabList(player);
}
@Override
@Nullable
public FunctionWithException<BukkitTabPlayer, Channel> getChannelFunction() {
return null;
}
@Override
public int getPing(@NotNull BukkitTabPlayer player) {
return ((CraftPlayer)player.getPlayer()).getHandle().ping;
}
} | 412 | 0.663172 | 1 | 0.663172 | game-dev | MEDIA | 0.969081 | game-dev | 0.746392 | 1 | 0.746392 |
opentibiabr/otservbr-global | 1,124 | data/scripts/actions/quests/cults_of_tibia/document.lua | local cultsOfTibiaDocument = Action()
function cultsOfTibiaDocument.onUse(player, item, fromPosition, target, toPosition, isHotkey)
local posDocument = Position(33279, 32169, 8)
-- Document
if item:getPosition() == posDocument then
if player:getStorageValue(Storage.CultsOfTibia.MotA.Mission) == 2 then
player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "Dear curator, this recently opened museum is a really nice place to be.")
player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "But wait! What about the empty space in front of you? What a pity!")
player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "It seems that somebody has removed one of the beautiful pictures. But come on! You have the money and we need it.")
player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "So for a small expense allowance you'll get it back. Just talk to Iwar in Kazordoon for further information. ")
player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "Ask him: Has the cat got your tongue?")
player:setStorageValue(Storage.CultsOfTibia.MotA.Mission, 3)
end
end
return true
end
cultsOfTibiaDocument:aid(5522)
cultsOfTibiaDocument:register() | 412 | 0.758814 | 1 | 0.758814 | game-dev | MEDIA | 0.80877 | game-dev,testing-qa | 0.7828 | 1 | 0.7828 |
riksweeney/edgar | 16,200 | src/boss/fly_boss.c | /*
Copyright (C) 2009-2024 Parallel Realities
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
*/
#include "../headers.h"
#include "../audio/audio.h"
#include "../audio/music.h"
#include "../collisions.h"
#include "../credits.h"
#include "../custom_actions.h"
#include "../entity.h"
#include "../game.h"
#include "../geometry.h"
#include "../graphics/animation.h"
#include "../graphics/decoration.h"
#include "../graphics/graphics.h"
#include "../hud.h"
#include "../item/item.h"
#include "../item/key_items.h"
#include "../map.h"
#include "../player.h"
#include "../projectile.h"
#include "../system/error.h"
#include "../system/properties.h"
#include "../system/random.h"
#include "../world/target.h"
extern Entity *self, player;
static int drawSuspended(void);
static void takeDamage(Entity *, int);
static void initialise(void);
static void doIntro(void);
static void introPause(void);
static void entityWait(void);
static void hover(void);
static void moveToTarget(void);
static void flyToTopTarget(void);
static void bulletFireInit(void);
static void bulletFireMoveToPosition(void);
static void fireBullets(void);
static void slimeFireInit(void);
static void slimeFireMoveToPosition(void);
static void fireSlime(void);
static void attackFinished(void);
static void slimePlayer(Entity *);
static void headButtInit(void);
static void headButtMoveToPosition(void);
static void moveToHeadButtRange(void);
static void headButt(void);
static void headButtFinish(void);
static void selectRandomBottomTarget(void);
static void reactToHeadButtBlock(Entity *);
static void dropInit(void);
static void drop(void);
static void dropWait(void);
static void stingAttackInit(void);
static void stingAttackMoveToPosition(void);
static void stingAttackWindUp(void);
static void stingAttack(void);
static void stingAttackPause(void);
static void fallout(void);
static void ramTouch(Entity *);
static void die(void);
static void dieFinish(void);
static void creditsMove(void);
Entity *addFlyBoss(int x, int y, char *name)
{
Entity *e = getFreeEntity();
if (e == NULL)
{
showErrorAndExit("No free slots to add the Fly Boss");
}
loadProperties(name, e);
e->x = x;
e->y = y;
e->action = &initialise;
e->draw = &drawSuspended;
e->takeDamage = NULL;
e->type = ENEMY;
e->flags |= FLY;
e->active = FALSE;
e->fallout = &fallout;
e->die = ¨
e->creditsAction = &creditsMove;
setEntityAnimation(e, "CUSTOM_1");
return e;
}
static void initialise()
{
self->thinkTime++;
if (self->thinkTime >= 360)
{
self->thinkTime = 0;
}
if (self->active == TRUE)
{
if (self->thinkTime == 1 || self->thinkTime == 181)
{
self->thinkTime = 0;
}
if (cameraAtMinimum())
{
centerMapOnEntity(NULL);
self->dirX = self->speed;
self->action = &doIntro;
self->thinkTime = 180;
setContinuePoint(FALSE, self->name, NULL);
}
}
self->x = self->startX + sin(DEG_TO_RAD(self->thinkTime)) * 10;
}
static void doIntro()
{
int i;
Entity *e;
self->thinkTime--;
if (self->thinkTime <= 0)
{
self->x = self->startX;
setEntityAnimation(self, "STAND");
playSoundToMap("sound/common/gib", -1, self->x, self->y, 0);
for (i=0;i<11;i++)
{
e = addTemporaryItem("boss/fly_boss_cocoon_piece", self->x, self->y, RIGHT, 0, 0);
e->x += (self->w - e->w) / 2;
e->y += (self->h - e->h) / 2;
e->dirX = (prand() % 3) * (prand() % 2 == 0 ? -1 : 1);
e->dirY = ITEM_JUMP_HEIGHT + (prand() % ITEM_JUMP_HEIGHT);
setEntityAnimationByID(e, i);
e->thinkTime = 180 + (prand() % 60);
}
self->draw = &drawLoopingAnimationToMap;
playSoundToMap("sound/boss/fly_boss/buzz", BOSS_CHANNEL, self->x, self->y, 0);
self->takeDamage = &takeDamage;
self->action = &introPause;
self->touch = &entityTouch;
self->thinkTime = 120;
self->startY = self->y;
self->dirY = self->dirX = 0;
self->startX = 0;
facePlayer();
}
else
{
if (self->x == self->startX || (self->thinkTime % 2 == 0))
{
self->x = self->startX + (3 * (self->x < self->startX ? 1 : -1));
}
}
}
static void introPause()
{
hover();
self->dirX = 0.5;
checkToMap(self);
self->thinkTime--;
if (self->thinkTime <= 0)
{
playDefaultBossMusic();
initBossHealthBar();
self->action = &entityWait;
self->flags |= LIMIT_TO_SCREEN;
}
facePlayer();
}
static void entityWait()
{
int i;
self->thinkTime--;
facePlayer();
hover();
if (self->thinkTime <= 0 && player.health > 0)
{
i = self->health <= (self->maxHealth / 10) ? prand() % 10 : prand() % 4;
switch (i)
{
case 0:
self->action = &bulletFireInit;
break;
case 1:
self->action = &headButtInit;
break;
case 2:
self->thinkTime = 120 + prand() % 180;
self->action = &dropInit;
break;
case 3:
self->action = &slimeFireInit;
break;
default:
self->action = &stingAttackInit;
break;
}
self->damage = 1;
playSoundToMap("sound/boss/fly_boss/buzz", BOSS_CHANNEL, self->x, self->y, 0);
}
}
static int drawSuspended()
{
drawLine(self->startX + self->w / 2, self->startY, self->x + self->w / 2, self->y + 15, 255, 255, 255);
drawLoopingAnimationToMap();
return TRUE;
}
static void hover()
{
self->startX++;
if (self->startX >= 360)
{
self->startX = 0;
}
self->y = self->startY + sin(DEG_TO_RAD(self->startX)) * 8;
}
static void flyToTopTarget()
{
Target *t;
/* Don't fly through the player, that'd be really annoying */
if (player.x < self->x)
{
t = getTargetByName("FLY_BOSS_TARGET_TOP_RIGHT");
}
else
{
t = getTargetByName("FLY_BOSS_TARGET_TOP_LEFT");
}
if (t == NULL)
{
showErrorAndExit("Fly boss cannot find target");
}
self->targetX = t->x;
self->targetY = t->y;
calculatePath(self->x, self->y, self->targetX, self->targetY, &self->dirX, &self->dirY);
self->dirX *= self->speed;
self->dirY *= self->speed;
self->action = &moveToTarget;
}
static void moveToTarget()
{
checkToMap(self);
facePlayer();
if (atTarget())
{
self->thinkTime = 120;
self->x = self->targetX;
self->y = self->targetY;
self->dirX = 0;
self->dirY = 0;
self->startX = 0;
self->startY = self->y;
self->action = &entityWait;
}
}
static void dropInit()
{
Target *left, *right;
setEntityAnimation(self, "ATTACK_1");
self->dirY = 0;
left = getTargetByName("FLY_BOSS_TARGET_TOP_LEFT");
right = getTargetByName("FLY_BOSS_TARGET_TOP_RIGHT");
self->thinkTime--;
self->targetX = player.x - self->w / 2 + player.w / 2;
if (self->thinkTime > 0)
{
/* Move towards player */
if (fabsf(self->x - self->targetX) <= self->speed)
{
self->dirX = 0;
}
else
{
self->dirX = self->targetX < self->x ? -self->speed : self->speed;
}
checkToMap(self);
if (self->x < left->x)
{
self->x = left->x;
self->dirX = 0;
}
else if (self->x > right->x)
{
self->x = right->x;
self->dirX = 0;
}
}
else
{
self->thinkTime = 0;
self->action = &drop;
self->dirX = 0;
}
}
static void drop()
{
int i;
long onGround = (self->flags & ON_GROUND);
self->thinkTime--;
if (self->thinkTime > 0)
{
hover();
}
else
{
self->frameSpeed = 0;
self->thinkTime = 0;
self->flags &= ~FLY;
checkToMap(self);
if (onGround == 0 && (self->flags & ON_GROUND))
{
playSoundToMap("sound/common/crash", BOSS_CHANNEL, self->x, self->y, 0);
shakeScreen(LIGHT, 15);
self->thinkTime = 90;
self->action = &dropWait;
for (i=0;i<20;i++)
{
addSmoke(self->x + prand() % self->w, self->y + self->h - prand() % 10, "decoration/dust");
}
}
}
}
static void dropWait()
{
self->thinkTime--;
facePlayer();
if (self->thinkTime <= 0)
{
self->flags |= FLY;
self->action = &attackFinished;
}
}
static void bulletFireInit()
{
selectRandomBottomTarget();
self->action = &bulletFireMoveToPosition;
}
static void bulletFireMoveToPosition()
{
checkToMap(self);
facePlayer();
if (atTarget())
{
self->maxThinkTime = 5 + prand() % 15;
self->x = self->targetX;
self->y = self->targetY;
self->dirX = 0;
self->dirY = 0;
self->startX = 0;
self->startY = self->y;
self->action = &fireBullets;
}
}
static void fireBullets()
{
Entity *e;
self->thinkTime--;
if (self->thinkTime <= 0)
{
self->maxThinkTime--;
playSoundToMap("sound/boss/fly_boss/fly_boss_bullet", -1, self->x, self->y, 0);
e = addProjectile("boss/fly_boss_shot", self, self->x + (self->face == RIGHT ? self->w : 0), self->y + self->h / 2, (self->face == RIGHT ? 7 : -7), 0);
e->dirY = 0.1 * (prand() % 2 == 0 ? -1 : 1);
e->reactToBlock = &bounceOffShield;
if (self->maxThinkTime <= 0)
{
self->thinkTime = 120;
self->action = &attackFinished;
}
else
{
self->thinkTime = 6;
}
}
}
static void slimeFireInit()
{
selectRandomBottomTarget();
self->action = &slimeFireMoveToPosition;
}
static void slimeFireMoveToPosition()
{
checkToMap(self);
facePlayer();
if (atTarget())
{
self->maxThinkTime = 1 + prand() % 4;
self->x = self->targetX;
self->y = self->targetY;
self->dirX = 0;
self->dirY = 0;
self->startX = 0;
self->startY = self->y;
self->action = &fireSlime;
}
}
static void fireSlime()
{
Entity *e;
self->thinkTime--;
if (self->thinkTime <= 0)
{
self->maxThinkTime--;
playSoundToMap("sound/boss/grub_boss/fire", -1, self->x, self->y, 0);
e = addProjectile("boss/fly_boss_slime", self, self->x + (self->face == RIGHT ? self->w : 0), self->y + self->h / 2, (self->face == RIGHT ? 7 : -7), 0);
e->touch = &slimePlayer;
if (self->maxThinkTime <= 0)
{
self->thinkTime = 60;
self->action = ((player.flags & HELPLESS) || prand() % 3 == 0) ? &bulletFireMoveToPosition : &attackFinished;
}
else
{
self->thinkTime = 30;
}
}
}
static void headButtInit()
{
selectRandomBottomTarget();
self->action = &headButtMoveToPosition;
}
static void headButtMoveToPosition()
{
checkToMap(self);
facePlayer();
if (atTarget())
{
self->flags &= ~(FLY|UNBLOCKABLE);
setEntityAnimation(self, "ATTACK_2");
self->thinkTime = 60;
self->x = self->targetX;
self->y = self->targetY;
self->dirX = 0;
self->dirY = 0;
self->startX = 0;
self->startY = self->y;
self->action = &moveToHeadButtRange;
}
}
static void moveToHeadButtRange()
{
int playerX, bossX;
facePlayer();
self->thinkTime--;
if (self->thinkTime <= 0)
{
bossX = self->x + (self->face == LEFT ? 0 : self->w - 1);
playerX = player.x + (self->face == RIGHT ? 0 : player.w - 1);
if (abs(bossX - playerX) < 24)
{
self->dirX = self->face == LEFT ? -self->speed * 3 : self->speed * 3;
self->dirY = -3;
self->action = &headButt;
self->reactToBlock = &reactToHeadButtBlock;
}
else
{
self->dirX = self->face == LEFT ? -self->speed : self->speed;
}
}
checkToMap(self);
}
static void headButt()
{
self->touch = &ramTouch;
checkToMap(self);
if (self->dirX == 0)
{
self->dirX = (self->face == LEFT ? 4 : -4);
self->dirY = -6;
self->action = &headButtFinish;
}
}
static void headButtFinish()
{
self->touch = &entityTouch;
if (self->flags & ON_GROUND)
{
facePlayer();
self->dirX = 0;
self->thinkTime = 120;
if (prand() % 2 == 0)
{
self->action = &attackFinished;
}
else
{
self->action = &moveToHeadButtRange;
}
}
checkToMap(self);
}
static void stingAttackInit()
{
selectRandomBottomTarget();
self->action = &stingAttackMoveToPosition;
}
static void stingAttackMoveToPosition()
{
int bottomY;
checkToMap(self);
facePlayer();
if (atTarget())
{
self->dirY = 0;
self->dirX = 0;
bottomY = self->y + self->h - 1;
setEntityAnimation(self, "ATTACK_3");
self->y = bottomY - self->h;
self->frameSpeed = 12;
self->thinkTime = 120;
self->action = &stingAttackWindUp;
}
}
static void stingAttackWindUp()
{
self->thinkTime--;
if (self->thinkTime == 0)
{
self->thinkTime = 15;
self->dirX = self->face == RIGHT ? -4 : 4;
self->action = &stingAttack;
}
}
static void stingAttack()
{
self->thinkTime--;
if (self->thinkTime == 0)
{
self->dirX = self->face == LEFT ? -24 : 24;
self->flags |= ATTACKING;
self->touch = &ramTouch;
}
else if (self->thinkTime < 0)
{
if (self->dirX == 0)
{
shakeScreen(MEDIUM, 15);
self->frameSpeed = 0;
self->flags &= ~FLY;
self->dirY = -4;
self->dirX = self->face == LEFT ? 4 : -4;
self->action = &stingAttackPause;
self->touch = &entityTouch;
setEntityAnimation(self, "ATTACK_2");
self->thinkTime = 180;
}
}
checkToMap(self);
}
static void stingAttackPause()
{
self->thinkTime--;
checkToMap(self);
if (self->flags & ON_GROUND)
{
self->dirX = 0;
}
if (self->thinkTime <= 0)
{
self->action = &attackFinished;
}
}
static void fallout()
{
if (self->environment == WATER)
{
self->flags |= HELPLESS;
self->dirX = 0;
self->action = &doNothing;
}
}
static void die()
{
self->damage = 0;
self->thinkTime = 120;
self->flags &= ~FLY;
self->action = &dieFinish;
}
static void dieFinish()
{
Entity *e;
self->thinkTime--;
if (self->thinkTime <= 0)
{
clearContinuePoint();
increaseKillCount();
freeBossHealthBar();
e = addKeyItem("item/heart_container", self->x + self->w / 2, self->y);
e->dirY = ITEM_JUMP_HEIGHT;
fadeBossMusic();
entityDieNoDrop();
}
}
static void slimePlayer(Entity *other)
{
if (other->type == PLAYER)
{
other->dirX = 0;
if (!(other->flags & HELPLESS))
{
setPlayerSlimed(180);
}
self->die();
}
}
static void selectRandomBottomTarget()
{
Target *t;
if (prand() % 2 == 0)
{
t = getTargetByName("FLY_BOSS_TARGET_BOTTOM_RIGHT");
}
else
{
t = getTargetByName("FLY_BOSS_TARGET_BOTTOM_LEFT");
}
if (t == NULL)
{
showErrorAndExit("Fly boss cannot find target");
}
self->targetX = t->x;
self->targetY = t->y;
calculatePath(self->x, self->y, self->targetX, self->targetY, &self->dirX, &self->dirY);
self->dirX *= self->speed;
self->dirY *= self->speed;
facePlayer();
}
static void reactToHeadButtBlock(Entity *other)
{
self->dirX = 0;
}
static void takeDamage(Entity *other, int damage)
{
int minHealth;
Entity *temp;
minHealth = self->maxHealth / 10;
if (!(self->flags & INVULNERABLE))
{
/* Take minimal damage from bombs */
if (other->type == EXPLOSION)
{
damage = 1;
}
self->health -= damage;
if (self->health <= minHealth)
{
self->health = minHealth;
}
setCustomAction(self, &flashWhite, 6, 0, 0);
setCustomAction(self, &invulnerableNoFlash, HIT_INVULNERABLE_TIME, 0, 0);
enemyPain();
if (other->type == PROJECTILE)
{
temp = self;
self = other;
self->die();
self = temp;
}
}
}
static void attackFinished()
{
int bottomY;
self->thinkTime--;
if (self->thinkTime <= 0)
{
self->frameSpeed = 1;
bottomY = self->y + self->h - 1;
self->frameSpeed = 1;
setEntityAnimation(self, "STAND");
self->y = bottomY - self->h - 1;
self->dirX = self->face == RIGHT ? -1 : 1;
self->dirY = 1;
self->startX = 0;
self->startY = self->y;
self->flags &= ~ATTACKING;
self->flags |= UNBLOCKABLE|FLY;
/* Stop the player from being hit when the animation changes */
self->damage = 0;
self->action = &flyToTopTarget;
self->reactToBlock = NULL;
self->thinkTime = 30;
}
checkToMap(self);
}
static void ramTouch(Entity *other)
{
int health = player.health;
entityTouch(other);
if (player.health < health)
{
reactToHeadButtBlock(other);
}
}
static void creditsMove()
{
setEntityAnimation(self, "STAND");
self->draw = &drawLoopingAnimationToMap;
self->creditsAction = &bossMoveToMiddle;
}
| 412 | 0.803418 | 1 | 0.803418 | game-dev | MEDIA | 0.844742 | game-dev | 0.973262 | 1 | 0.973262 |
ComodoSecurity/openedr | 18,108 | edrav2/eprj/boost/libs/msm/test/History.cpp | // Copyright 2010 Christophe Henry
// henry UNDERSCORE christophe AT hotmail DOT com
// This is an extended version of the state machine available in the boost::mpl library
// Distributed under the same license as the original.
// Copyright for the original version:
// Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed
// under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <iostream>
// back-end
#include <boost/msm/back/state_machine.hpp>
//front-end
#include <boost/msm/front/state_machine_def.hpp>
#ifndef BOOST_MSM_NONSTANDALONE_TEST
#define BOOST_TEST_MODULE MyTest
#endif
#include <boost/test/unit_test.hpp>
namespace msm = boost::msm;
namespace mpl = boost::mpl;
namespace
{
// events
struct play {};
struct end_pause {};
struct stop {};
struct pause {};
struct open_close {};
struct NextSong {};
struct PreviousSong {};
struct cd_detected
{
cd_detected(std::string name)
: name(name)
{}
std::string name;
};
// front-end: define the FSM structure
struct player_ : public msm::front::state_machine_def<player_>
{
unsigned int start_playback_counter;
unsigned int can_close_drawer_counter;
player_():
start_playback_counter(0),
can_close_drawer_counter(0)
{}
// The list of FSM states
struct Empty : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
struct Open : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
// sm_ptr still supported but deprecated as functors are a much better way to do the same thing
struct Stopped : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
struct Playing_ : public msm::front::state_machine_def<Playing_>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
unsigned int start_next_song_counter;
unsigned int start_prev_song_guard_counter;
Playing_():
start_next_song_counter(0),
start_prev_song_guard_counter(0)
{}
// The list of FSM states
struct Song1 : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
struct Song2 : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
struct Song3 : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
// the initial state. Must be defined
typedef Song1 initial_state;
// transition actions
void start_next_song(NextSong const&) {++start_next_song_counter; }
void start_prev_song(PreviousSong const&) { }
// guard conditions
bool start_prev_song_guard(PreviousSong const&) {++start_prev_song_guard_counter;return true; }
typedef Playing_ pl; // makes transition table cleaner
// Transition table for Playing
struct transition_table : mpl::vector4<
// Start Event Next Action Guard
// +---------+-------------+---------+---------------------+----------------------+
_row < Song1 , NextSong , Song2 >,
row < Song2 , PreviousSong, Song1 , &pl::start_prev_song,&pl::start_prev_song_guard>,
a_row < Song2 , NextSong , Song3 , &pl::start_next_song >,
g_row < Song3 , PreviousSong, Song2 ,&pl::start_prev_song_guard>
// +---------+-------------+---------+---------------------+----------------------+
> {};
// Replaces the default no-transition response.
template <class FSM,class Event>
void no_transition(Event const&, FSM&,int)
{
BOOST_FAIL("no_transition called!");
}
};
// back-end
typedef msm::back::state_machine<Playing_,msm::back::ShallowHistory<mpl::vector<end_pause> > > Playing;
// state not defining any entry or exit
struct Paused : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& ) {++entry_counter;}
template <class Event,class FSM>
void on_exit(Event const&,FSM& ) {++exit_counter;}
int entry_counter;
int exit_counter;
};
// the initial state of the player SM. Must be defined
typedef Empty initial_state;
// transition actions
void start_playback(play const&) {++start_playback_counter; }
void open_drawer(open_close const&) { }
void store_cd_info(cd_detected const&) { }
void stop_playback(stop const&) { }
void pause_playback(pause const&) { }
void resume_playback(end_pause const&) { }
void stop_and_open(open_close const&) { }
void stopped_again(stop const&){}
//guards
bool can_close_drawer(open_close const&)
{
++can_close_drawer_counter;
return true;
}
typedef player_ p; // makes transition table cleaner
// Transition table for player
struct transition_table : mpl::vector<
// Start Event Next Action Guard
// +---------+-------------+---------+---------------------+----------------------+
a_row < Stopped , play , Playing , &p::start_playback >,
a_row < Stopped , open_close , Open , &p::open_drawer >,
_row < Stopped , stop , Stopped >,
// +---------+-------------+---------+---------------------+----------------------+
g_row < Open , open_close , Empty , &p::can_close_drawer >,
// +---------+-------------+---------+---------------------+----------------------+
a_row < Empty , open_close , Open , &p::open_drawer >,
a_row < Empty , cd_detected , Stopped , &p::store_cd_info >,
// +---------+-------------+---------+---------------------+----------------------+
a_row < Playing , stop , Stopped , &p::stop_playback >,
a_row < Playing , pause , Paused , &p::pause_playback >,
a_row < Playing , open_close , Open , &p::stop_and_open >,
// +---------+-------------+---------+---------------------+----------------------+
a_row < Paused , end_pause , Playing , &p::resume_playback >,
a_row < Paused , stop , Stopped , &p::stop_playback >,
a_row < Paused , open_close , Open , &p::stop_and_open >
// +---------+-------------+---------+---------------------+----------------------+
> {};
// Replaces the default no-transition response.
template <class FSM,class Event>
void no_transition(Event const& , FSM&,int )
{
BOOST_FAIL("no_transition called!");
}
// init counters
template <class Event,class FSM>
void on_entry(Event const&,FSM& fsm)
{
fsm.template get_state<player_::Stopped&>().entry_counter=0;
fsm.template get_state<player_::Stopped&>().exit_counter=0;
fsm.template get_state<player_::Open&>().entry_counter=0;
fsm.template get_state<player_::Open&>().exit_counter=0;
fsm.template get_state<player_::Empty&>().entry_counter=0;
fsm.template get_state<player_::Empty&>().exit_counter=0;
fsm.template get_state<player_::Playing&>().entry_counter=0;
fsm.template get_state<player_::Playing&>().exit_counter=0;
fsm.template get_state<player_::Playing&>().template get_state<player_::Playing::Song1&>().entry_counter=0;
fsm.template get_state<player_::Playing&>().template get_state<player_::Playing::Song1&>().exit_counter=0;
fsm.template get_state<player_::Playing&>().template get_state<player_::Playing::Song2&>().entry_counter=0;
fsm.template get_state<player_::Playing&>().template get_state<player_::Playing::Song2&>().exit_counter=0;
fsm.template get_state<player_::Playing&>().template get_state<player_::Playing::Song3&>().entry_counter=0;
fsm.template get_state<player_::Playing&>().template get_state<player_::Playing::Song3&>().exit_counter=0;
fsm.template get_state<player_::Paused&>().entry_counter=0;
fsm.template get_state<player_::Paused&>().exit_counter=0;
}
};
// Pick a back-end
typedef msm::back::state_machine<player_> player;
// static char const* const state_names[] = { "Stopped", "Open", "Empty", "Playing", "Paused" };
BOOST_AUTO_TEST_CASE( my_test )
{
player p;
p.start();
BOOST_CHECK_MESSAGE(p.get_state<player_::Empty&>().entry_counter == 1,"Empty entry not called correctly");
p.process_event(open_close());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 1,"Open should be active"); //Open
BOOST_CHECK_MESSAGE(p.get_state<player_::Empty&>().exit_counter == 1,"Empty exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Open&>().entry_counter == 1,"Open entry not called correctly");
p.process_event(open_close());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 2,"Empty should be active"); //Empty
BOOST_CHECK_MESSAGE(p.get_state<player_::Open&>().exit_counter == 1,"Open exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Empty&>().entry_counter == 2,"Empty entry not called correctly");
BOOST_CHECK_MESSAGE(p.can_close_drawer_counter == 1,"guard not called correctly");
p.process_event(cd_detected("louie, louie"));
BOOST_CHECK_MESSAGE(p.current_state()[0] == 0,"Stopped should be active"); //Stopped
BOOST_CHECK_MESSAGE(p.get_state<player_::Empty&>().exit_counter == 2,"Empty exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Stopped&>().entry_counter == 1,"Stopped entry not called correctly");
p.process_event(play());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 3,"Playing should be active"); //Playing
BOOST_CHECK_MESSAGE(p.get_state<player_::Stopped&>().exit_counter == 1,"Stopped exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().entry_counter == 1,"Playing entry not called correctly");
BOOST_CHECK_MESSAGE(p.start_playback_counter == 1,"action not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().current_state()[0] == 0,"Song1 should be active");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song1&>().entry_counter == 1,
"Song1 entry not called correctly");
p.process_event(NextSong());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 3,"Playing should be active"); //Playing
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().current_state()[0] == 1,"Song2 should be active");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song2&>().entry_counter == 1,
"Song2 entry not called correctly");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song1&>().exit_counter == 1,
"Song1 exit not called correctly");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().start_next_song_counter == 0,
"submachine action not called correctly");
p.process_event(NextSong());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 3,"Playing should be active"); //Playing
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().current_state()[0] == 2,"Song3 should be active");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song3&>().entry_counter == 1,
"Song3 entry not called correctly");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song2&>().exit_counter == 1,
"Song2 exit not called correctly");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().start_next_song_counter == 1,
"submachine action not called correctly");
p.process_event(PreviousSong());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 3,"Playing should be active"); //Playing
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().current_state()[0] == 1,"Song2 should be active");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song2&>().entry_counter == 2,
"Song2 entry not called correctly");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song3&>().exit_counter == 1,
"Song3 exit not called correctly");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().start_prev_song_guard_counter == 1,
"submachine guard not called correctly");
p.process_event(pause());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 4,"Paused should be active"); //Paused
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().exit_counter == 1,"Playing exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Paused&>().entry_counter == 1,"Paused entry not called correctly");
// go back to Playing
p.process_event(end_pause());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 3,"Playing should be active"); //Playing
BOOST_CHECK_MESSAGE(p.get_state<player_::Paused&>().exit_counter == 1,"Paused exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().entry_counter == 2,"Playing entry not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().current_state()[0] == 1,"Song2 should be active");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song2&>().entry_counter == 3,
"Song2 entry not called correctly");
p.process_event(pause());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 4,"Paused should be active"); //Paused
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().exit_counter == 2,"Playing exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Paused&>().entry_counter == 2,"Paused entry not called correctly");
p.process_event(stop());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 0,"Stopped should be active"); //Stopped
BOOST_CHECK_MESSAGE(p.get_state<player_::Paused&>().exit_counter == 2,"Paused exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Stopped&>().entry_counter == 2,"Stopped entry not called correctly");
p.process_event(stop());
BOOST_CHECK_MESSAGE(p.current_state()[0] == 0,"Stopped should be active"); //Stopped
BOOST_CHECK_MESSAGE(p.get_state<player_::Stopped&>().exit_counter == 2,"Stopped exit not called correctly");
BOOST_CHECK_MESSAGE(p.get_state<player_::Stopped&>().entry_counter == 3,"Stopped entry not called correctly");
p.process_event(play());
BOOST_CHECK_MESSAGE(p.get_state<player_::Playing&>().current_state()[0] == 0,"Song1 should be active");
BOOST_CHECK_MESSAGE(
p.get_state<player_::Playing&>().get_state<player_::Playing::Song1&>().entry_counter == 2,
"Song1 entry not called correctly");
}
}
| 412 | 0.965845 | 1 | 0.965845 | game-dev | MEDIA | 0.302462 | game-dev | 0.917154 | 1 | 0.917154 |
Creators-of-Create/Create | 7,296 | src/main/java/com/simibubi/create/content/processing/basin/BasinRecipe.java | package com.simibubi.create.content.processing.basin;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.Nonnull;
import com.simibubi.create.AllRecipeTypes;
import com.simibubi.create.content.processing.burner.BlazeBurnerBlock.HeatLevel;
import com.simibubi.create.content.processing.recipe.ProcessingRecipe;
import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder.ProcessingRecipeParams;
import com.simibubi.create.foundation.blockEntity.behaviour.filtering.FilteringBehaviour;
import com.simibubi.create.foundation.blockEntity.behaviour.fluid.SmartFluidTankBehaviour;
import com.simibubi.create.foundation.blockEntity.behaviour.fluid.SmartFluidTankBehaviour.TankSegment;
import com.simibubi.create.foundation.fluid.FluidIngredient;
import com.simibubi.create.foundation.recipe.DummyCraftingContainer;
import com.simibubi.create.foundation.recipe.IRecipeTypeInfo;
import net.createmod.catnip.data.Iterate;
import net.minecraft.client.Minecraft;
import net.minecraft.world.Container;
import net.minecraft.world.inventory.CraftingContainer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.CraftingRecipe;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.level.Level;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.items.IItemHandler;
public class BasinRecipe extends ProcessingRecipe<Container> {
public static boolean match(BasinBlockEntity basin, Recipe<?> recipe) {
FilteringBehaviour filter = basin.getFilter();
if (filter == null)
return false;
boolean filterTest = filter.test(recipe.getResultItem(basin.getLevel()
.registryAccess()));
if (recipe instanceof BasinRecipe basinRecipe) {
if (basinRecipe.getRollableResults()
.isEmpty()
&& !basinRecipe.getFluidResults()
.isEmpty())
filterTest = filter.test(basinRecipe.getFluidResults()
.get(0));
}
if (!filterTest)
return false;
return apply(basin, recipe, true);
}
public static boolean apply(BasinBlockEntity basin, Recipe<?> recipe) {
return apply(basin, recipe, false);
}
private static boolean apply(BasinBlockEntity basin, Recipe<?> recipe, boolean test) {
boolean isBasinRecipe = recipe instanceof BasinRecipe;
IItemHandler availableItems = basin.getCapability(ForgeCapabilities.ITEM_HANDLER)
.orElse(null);
IFluidHandler availableFluids = basin.getCapability(ForgeCapabilities.FLUID_HANDLER)
.orElse(null);
if (availableItems == null || availableFluids == null)
return false;
HeatLevel heat = basin.getHeatLevel();
if (isBasinRecipe && !((BasinRecipe) recipe).getRequiredHeat()
.testBlazeBurner(heat))
return false;
List<ItemStack> recipeOutputItems = new ArrayList<>();
List<FluidStack> recipeOutputFluids = new ArrayList<>();
List<Ingredient> ingredients = new LinkedList<>(recipe.getIngredients());
List<FluidIngredient> fluidIngredients =
isBasinRecipe ? ((BasinRecipe) recipe).getFluidIngredients() : Collections.emptyList();
for (boolean simulate : Iterate.trueAndFalse) {
if (!simulate && test)
return true;
int[] extractedItemsFromSlot = new int[availableItems.getSlots()];
int[] extractedFluidsFromTank = new int[availableFluids.getTanks()];
Ingredients:
for (Ingredient ingredient : ingredients) {
for (int slot = 0; slot < availableItems.getSlots(); slot++) {
if (simulate && availableItems.getStackInSlot(slot)
.getCount() <= extractedItemsFromSlot[slot])
continue;
ItemStack extracted = availableItems.extractItem(slot, 1, true);
if (!ingredient.test(extracted))
continue;
if (!simulate)
availableItems.extractItem(slot, 1, false);
extractedItemsFromSlot[slot]++;
continue Ingredients;
}
// something wasn't found
return false;
}
boolean fluidsAffected = false;
FluidIngredients:
for (FluidIngredient fluidIngredient : fluidIngredients) {
int amountRequired = fluidIngredient.getRequiredAmount();
for (int tank = 0; tank < availableFluids.getTanks(); tank++) {
FluidStack fluidStack = availableFluids.getFluidInTank(tank);
if (simulate && fluidStack.getAmount() <= extractedFluidsFromTank[tank])
continue;
if (!fluidIngredient.test(fluidStack))
continue;
int drainedAmount = Math.min(amountRequired, fluidStack.getAmount());
if (!simulate) {
fluidStack.shrink(drainedAmount);
fluidsAffected = true;
}
amountRequired -= drainedAmount;
if (amountRequired != 0)
continue;
extractedFluidsFromTank[tank] += drainedAmount;
continue FluidIngredients;
}
// something wasn't found
return false;
}
if (fluidsAffected) {
basin.getBehaviour(SmartFluidTankBehaviour.INPUT)
.forEach(TankSegment::onFluidStackChanged);
basin.getBehaviour(SmartFluidTankBehaviour.OUTPUT)
.forEach(TankSegment::onFluidStackChanged);
}
if (simulate) {
CraftingContainer remainderContainer = new DummyCraftingContainer(availableItems, extractedItemsFromSlot);
if (recipe instanceof BasinRecipe basinRecipe) {
recipeOutputItems.addAll(basinRecipe.rollResults());
for (FluidStack fluidStack : basinRecipe.getFluidResults())
if (!fluidStack.isEmpty())
recipeOutputFluids.add(fluidStack);
for (ItemStack stack : basinRecipe.getRemainingItems(remainderContainer))
if (!stack.isEmpty())
recipeOutputItems.add(stack);
} else {
recipeOutputItems.add(recipe.getResultItem(basin.getLevel()
.registryAccess()));
if (recipe instanceof CraftingRecipe craftingRecipe) {
for (ItemStack stack : craftingRecipe.getRemainingItems(remainderContainer))
if (!stack.isEmpty())
recipeOutputItems.add(stack);
}
}
}
if (!basin.acceptOutputs(recipeOutputItems, recipeOutputFluids, simulate))
return false;
}
return true;
}
public static BasinRecipe convertShapeless(Recipe<?> recipe) {
BasinRecipe basinRecipe =
new ProcessingRecipeBuilder<>(BasinRecipe::new, recipe.getId()).withItemIngredients(recipe.getIngredients())
.withSingleItemOutput(recipe.getResultItem(Minecraft.getInstance().level.registryAccess()))
.build();
return basinRecipe;
}
protected BasinRecipe(IRecipeTypeInfo type, ProcessingRecipeParams params) {
super(type, params);
}
public BasinRecipe(ProcessingRecipeParams params) {
this(AllRecipeTypes.BASIN, params);
}
@Override
protected int getMaxInputCount() {
return 64;
}
@Override
protected int getMaxOutputCount() {
return 4;
}
@Override
protected int getMaxFluidInputCount() {
return 2;
}
@Override
protected int getMaxFluidOutputCount() {
return 2;
}
@Override
protected boolean canRequireHeat() {
return true;
}
@Override
protected boolean canSpecifyDuration() {
return true;
}
@Override
public boolean matches(Container inv, @Nonnull Level worldIn) {
return false;
}
}
| 412 | 0.949857 | 1 | 0.949857 | game-dev | MEDIA | 0.977213 | game-dev | 0.969062 | 1 | 0.969062 |
emileb/OpenGames | 5,962 | opengames/src/main/jni/OpenJK/code/icarus/taskmanager.h | /*
This file is part of Jedi Academy.
Jedi Academy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
Jedi Academy 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 Jedi Academy. If not, see <http://www.gnu.org/licenses/>.
*/
// Copyright 2001-2013 Raven Software
// Task Manager header file
#ifndef __TASK_MANAGER__
#define __TASK_MANAGER__
#include "../qcommon/q_shared.h"
#define MAX_TASK_NAME 64
#define TASKFLAG_NORMAL 0x00000000
const int RUNAWAY_LIMIT = 256;
enum
{
TASK_RETURN_COMPLETE,
TASK_RETURN_FAILED,
};
enum
{
TASK_OK,
TASK_FAILED,
TASK_START,
TASK_END,
};
// CTask
class CTask
{
public:
CTask();
~CTask();
static CTask *Create( int GUID, CBlock *block );
void Free( void );
unsigned int GetTimeStamp( void ) const { return m_timeStamp; }
CBlock *GetBlock( void ) const { return m_block; }
int GetGUID( void) const { return m_id; }
int GetID( void ) const { return m_block->GetBlockID(); }
void SetTimeStamp( unsigned int timeStamp ) { m_timeStamp = timeStamp; }
void SetBlock( CBlock *block ) { m_block = block; }
void SetGUID( int id ) { m_id = id; }
// Overloaded new operator.
inline void *operator new( size_t size )
{ // Allocate the memory.
return IGameInterface::GetGame()->Malloc( size );
}
// Overloaded delete operator.
inline void operator delete( void *pRawData )
{ // Free the Memory.
IGameInterface::GetGame()->Free( pRawData );
}
protected:
int m_id;
unsigned int m_timeStamp;
CBlock *m_block;
};
// CTaskGroup
class CTaskGroup
{
public:
typedef map < int, bool > taskCallback_m;
CTaskGroup( void );
~CTaskGroup( void );
void Init( void );
int Add( CTask *task );
void SetGUID( int GUID );
void SetParent( CTaskGroup *group ) { m_parent = group; }
bool Complete(void) const { return ( m_numCompleted == m_completedTasks.size() ); }
bool MarkTaskComplete( int id );
CTaskGroup *GetParent( void ) const { return m_parent; }
int GetGUID( void ) const { return m_GUID; }
// Overloaded new operator.
static void *operator new( size_t size )
{ // Allocate the memory.
return IGameInterface::GetGame()->Malloc( size );
}
// Overloaded delete operator.
static void operator delete( void *pRawData )
{ // Free the Memory.
IGameInterface::GetGame()->Free( pRawData );
}
//protected:
taskCallback_m m_completedTasks;
CTaskGroup *m_parent;
unsigned int m_numCompleted;
int m_GUID;
};
// CTaskManager
class CSequencer;
class CTaskManager
{
typedef map < int, CTask * > taskID_m;
typedef map < string, CTaskGroup * > taskGroupName_m;
typedef map < int, CTaskGroup * > taskGroupID_m;
typedef vector < CTaskGroup * > taskGroup_v;
typedef list < CTask *> tasks_l;
public:
CTaskManager();
~CTaskManager();
int GetID();
static CTaskManager *Create( void );
CBlock *GetCurrentTask( void );
int Init( CSequencer *owner );
int Free( void );
int Flush( void );
int SetCommand( CBlock *block, int type, CIcarus* icarus );
int Completed( int id );
int Update( CIcarus* icarus );
int IsRunning( void ) const { return(!m_tasks.empty()); };
bool IsResident( void ) const { return m_resident;};
CTaskGroup *AddTaskGroup( const char *name , CIcarus* icarus);
CTaskGroup *GetTaskGroup( const char *name, CIcarus* icarus);
CTaskGroup *GetTaskGroup( int id, CIcarus* icarus );
int MarkTask( int id, int operation, CIcarus* icarus );
CBlock *RecallTask( void );
void Save();
void Load( CIcarus* icarus );
// Overloaded new operator.
inline void* operator new( size_t size )
{ // Allocate the memory.
return IGameInterface::GetGame()->Malloc( size );
}
// Overloaded delete operator.
inline void operator delete( void *pRawData )
{ // Free the Memory.
IGameInterface::GetGame()->Free( pRawData );
}
protected:
int Go( CIcarus* icarus ); //Heartbeat function called once per game frame
int CallbackCommand( CTask *task, int returnCode, CIcarus* icarus );
inline bool Check( int targetID, CBlock *block, int memberNum ) const;
int GetVector( int entID, CBlock *block, int &memberNum, vec3_t &value, CIcarus* icarus );
int GetFloat( int entID, CBlock *block, int &memberNum, float &value, CIcarus* icarus );
int Get( int entID, CBlock *block, int &memberNum, char **value, CIcarus* icarus );
int PushTask( CTask *task, int flag );
CTask *PopTask( int flag );
// Task functions
int Rotate( CTask *task, CIcarus* icarus );
int Remove( CTask *task , CIcarus* icarus);
int Camera( CTask *task, CIcarus* icarus );
int Print( CTask *task , CIcarus* icarus);
int Sound( CTask *task, CIcarus* icarus );
int Move( CTask *task , CIcarus* icarus);
int Kill( CTask *task , CIcarus* icarus);
int Set( CTask *task, CIcarus* icarus );
int Use( CTask *task , CIcarus* icarus);
int DeclareVariable( CTask *task , CIcarus* icarus);
int FreeVariable( CTask *task, CIcarus* icarus );
int Signal( CTask *task , CIcarus* icarus);
int Play( CTask *task , CIcarus* icarus);
int Wait( CTask *task, bool &completed, CIcarus* icarus );
int WaitSignal( CTask *task, bool &completed, CIcarus* icarus);
int SaveCommand( CBlock *block );
// Variables
CSequencer *m_owner;
int m_ownerID;
CTaskGroup *m_curGroup;
taskGroup_v m_taskGroups;
tasks_l m_tasks;
int m_GUID;
int m_count;
taskGroupName_m m_taskGroupNameMap;
taskGroupID_m m_taskGroupIDMap;
bool m_resident;
int m_id;
//CTask *m_waitTask; //Global pointer to the current task that is waiting for callback completion
};
#endif //__TASK_MANAGER__
| 412 | 0.741998 | 1 | 0.741998 | game-dev | MEDIA | 0.833873 | game-dev | 0.556254 | 1 | 0.556254 |
klzgrad/naiveproxy | 1,575 | src/base/memory/protected_memory_nocompile.nc | // Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This is a "No Compile Test" suite.
// https://dev.chromium.org/developers/testing/no-compile-tests
#include <string>
#include <type_traits>
#include "base/memory/protected_memory.h"
namespace base {
namespace {
struct NonTriviallyDestructibleData1 {
std::string data;
};
static_assert(!std::is_trivially_destructible_v<NonTriviallyDestructibleData1>);
struct NonTriviallyDestructibleData2 {
~NonTriviallyDestructibleData2() { delete[] data; }
const char* const data = nullptr;
};
static_assert(!std::is_trivially_destructible_v<NonTriviallyDestructibleData2>);
} // namespace
void DoNotAcceptDataWhichIsNotTriviallyDestructibleData() {
base::ProtectedMemory<NonTriviallyDestructibleData1>
data_1; // expected-error@base/memory/protected_memory.h:* {{static assertion failed due to requirement 'std::is_trivially_destructible_v<base::(anonymous namespace)::NonTriviallyDestructibleData1>'}}
base::ProtectedMemory<NonTriviallyDestructibleData2>
data_2; // expected-error@base/memory/protected_memory.h:* {{static assertion failed due to requirement 'std::is_trivially_destructible_v<base::(anonymous namespace)::NonTriviallyDestructibleData2>'}}
}
void DoNotAcceptParametersForData() {
base::ProtectedMemory<int>
data(2); // expected-error@base/memory/protected_memory_nocompile.nc:* {{no matching constructor for initialization of 'base::ProtectedMemory<int>'}}
}
} // namespace base
| 412 | 0.915681 | 1 | 0.915681 | game-dev | MEDIA | 0.390258 | game-dev | 0.579532 | 1 | 0.579532 |
lunar-sway/minestuck | 2,229 | src/main/java/com/mraof/minestuck/command/argument/TitleLandTypeArgument.java | package com.mraof.minestuck.command.argument;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import com.mraof.minestuck.world.lands.LandTypes;
import com.mraof.minestuck.world.lands.title.TitleLandType;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class TitleLandTypeArgument implements ArgumentType<TitleLandType>
{
private static final List<String> EXAMPLES = Arrays.asList("minestuck:frost", "minestuck:shade");
public static final String INVALID = "argument.title_land_type.invalid";
public static final DynamicCommandExceptionType INVALID_TYPE = new DynamicCommandExceptionType(o -> Component.translatable(INVALID, o));
public static TitleLandTypeArgument titleLandType()
{
return new TitleLandTypeArgument();
}
@Override
public TitleLandType parse(StringReader reader) throws CommandSyntaxException
{
int start2 = reader.getCursor();
ResourceLocation gristName = ResourceLocation.read(reader);
if(!LandTypes.TITLE_REGISTRY.containsKey(gristName))
{
reader.setCursor(start2);
throw INVALID_TYPE.createWithContext(reader, gristName.toString());
}
return LandTypes.TITLE_REGISTRY.get(gristName);
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder)
{
return SharedSuggestionProvider.suggestResource(LandTypes.TITLE_REGISTRY.keySet(), builder);
}
@Override
public Collection<String> getExamples()
{
return EXAMPLES;
}
public static TitleLandType get(CommandContext<CommandSourceStack> context, String id)
{
return context.getArgument(id, TitleLandType.class);
}
}
| 412 | 0.83592 | 1 | 0.83592 | game-dev | MEDIA | 0.908476 | game-dev | 0.931906 | 1 | 0.931906 |
folgerwang/UnrealEngine | 9,297 | Engine/Source/Editor/MovieSceneTools/Private/FCPXML/FCPXMLExport.h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "FCPXML/FCPXMLNode.h"
#include "MovieScene.h"
#include "MovieSceneTranslator.h"
#include "Tracks/MovieSceneAudioTrack.h"
#include "Sections/MovieSceneCinematicShotSection.h"
#include "Tracks/MovieSceneCinematicShotTrack.h"
/** The FFCPXMLExportVisitor class exports from Sequencer data into the FCP 7 XML structure.
This class will eventually be used to merge the data with an existing XML structure
representing previously imported material. This is intended to preserve metadata
roundtrip between Sequencer and the FCP XML format.
Currently the VisitNode functions are mostly empty. This is where the
merge data functionality will be implemented. */
class FFCPXMLExportVisitor : public FFCPXMLNodeVisitor
{
public:
/** Constructor */
FFCPXMLExportVisitor(FString InSaveFilename, TSharedRef<FMovieSceneExportData> InExportData, TSharedRef<FMovieSceneTranslatorContext> InExportContext);
/** Destructor */
virtual ~FFCPXMLExportVisitor();
public:
/** Called when visiting a FFCPXMLBasicNode during visitor traversal. */
virtual bool VisitNode(TSharedRef<FFCPXMLBasicNode> InBasicNode) override final;
/** Called when visiting a FFCPXMLXmemlNode during visitor traversal. */
virtual bool VisitNode(TSharedRef<FFCPXMLXmemlNode> InXmemlNode) override final;
/** Called when visiting a FFCPXMLSequenceNode during visitor traversal. */
virtual bool VisitNode(TSharedRef<FFCPXMLSequenceNode> InSequenceNode) override final;
/** Called when visiting a FFCPXMLVideoNode during visitor traversal. */
virtual bool VisitNode(TSharedRef<FFCPXMLVideoNode> InVideoNode) override final;
/** Called when visiting a FFCPXMLAudioNode during visitor traversal. */
virtual bool VisitNode(TSharedRef<FFCPXMLAudioNode> InAudioNode) override final;
/** Called when visiting a FFCPXMLTrackNode during visitor traversal. */
virtual bool VisitNode(TSharedRef<FFCPXMLTrackNode> InTrackNode) override final;
/** Called when visiting a FFCPXMLClipNode during visitor traversal. */
virtual bool VisitNode(TSharedRef<FFCPXMLClipNode> InClipNode) override final;
/** Called when visiting a FFCPXMLClipItemNode during visitor traversal. */
virtual bool VisitNode(TSharedRef<FFCPXMLClipItemNode> InClipItemNode) override final;
/** Called when visiting a FFCPXMLFileNode during visitor traversal. */
virtual bool VisitNode(TSharedRef<FFCPXMLFileNode> InFileNode) override final;
public:
/** Creates project node. */
bool ConstructProjectNode(TSharedRef<FFCPXMLNode> InParentNode);
/** Creates master clip nodes. */
bool ConstructMasterClipNodes(TSharedRef<FFCPXMLNode> InParentNode);
/** Creates master clip node. */
bool ConstructMasterClipNode(TSharedRef<FFCPXMLNode> InParentNode, const TSharedPtr<FMovieSceneExportCinematicSectionData> InCinematicSectionData, const TSharedPtr<FMovieSceneExportCinematicMasterTrackData> InCinematicMasterTrackData);
/** Creates master clip node. */
bool ConstructMasterClipNode(TSharedRef<FFCPXMLNode> InParentNode, const TSharedPtr<FMovieSceneExportAudioSectionData> InAudioSectionData, const TSharedPtr<FMovieSceneExportAudioMasterTrackData> InCinematicMasterTrackData);
/** Creates colorinfo node. */
bool ConstructColorInfoNode(TSharedRef<FFCPXMLNode> InParentNode, const TSharedPtr<FMovieSceneExportSectionData> InSectionData);
/** Creates logginginfo node. */
bool ConstructLoggingInfoNode(TSharedRef<FFCPXMLNode> InParentNode, const TSharedPtr<FMovieSceneExportCinematicSectionData> InSectionData);
/** Creates logginginfo node. */
bool ConstructLoggingInfoNode(TSharedRef<FFCPXMLNode> InParentNode, const TSharedPtr<FMovieSceneExportAudioSectionData> InSectionData);
/** Creates sequence node. */
bool ConstructSequenceNode(TSharedRef<FFCPXMLNode> InParentNode);
/** Creates video node. */
bool ConstructVideoNode(TSharedRef<FFCPXMLNode> InParentNode);
/** Creates audio node. */
bool ConstructAudioNode(TSharedRef<FFCPXMLNode> InParentNode);
/** Creates video track node. */
bool ConstructVideoTrackNode(TSharedRef<FFCPXMLNode> InParentNode, const TSharedPtr<FMovieSceneExportCinematicTrackData> InCinematicTrackData, const TSharedPtr<FMovieSceneExportCinematicMasterTrackData> InCinematicMasterTrackData);
/** Creates audio track node. */
bool ConstructAudioTrackNode(TSharedRef<FFCPXMLNode> InParentNode, const TSharedPtr<FMovieSceneExportAudioTrackData> InAudioTrackData, const TSharedPtr<FMovieSceneExportAudioMasterTrackData> InAudioMasterTrackData, uint32 InTrackIndex, uint32 OutNumTracks);
/** Creates video clip item node. */
bool ConstructVideoClipItemNode(TSharedRef<FFCPXMLNode> InParentNode, const TSharedPtr<FMovieSceneExportCinematicSectionData> InCinematicSectionData, const TSharedPtr<FMovieSceneExportCinematicMasterTrackData> InCinematicMasterTrackData, bool bInMasterClip);
/** Creates audio clip item node. */
bool ConstructAudioClipItemNode(TSharedRef<FFCPXMLNode> InParentNode, const TSharedPtr<FMovieSceneExportAudioSectionData> InAudioSectionData,
const TSharedPtr<FMovieSceneExportAudioMasterTrackData> InAudioMasterTrackData, int32 InChannel, bool bInMasterClip,
const FString& InClipItemIdName1, const FString& InClipItemIdName2, int32 InClipIndex1, int32 InClipIndex2, int32 InTrackIndex1, int32 InTrackIndex2);
/** Creates video file node. */
bool ConstructVideoFileNode(TSharedRef<FFCPXMLNode> InParentNode, const TSharedPtr<FMovieSceneExportCinematicSectionData> InCinematicSectionData, int32 InDuration, bool bInMasterClip);
/** Creates audio file node. */
bool ConstructAudioFileNode(TSharedRef<FFCPXMLNode> InParentNode, const TSharedPtr<FMovieSceneExportAudioSectionData> InAudioSectionData, int32 InChannel);
/** Creates video sample characteristics node */
bool ConstructVideoSampleCharacteristicsNode(TSharedRef<FFCPXMLNode> InParentNode, int InWidth, int InHeight);
/** Creates audio video sample characteristics node */
bool ConstructAudioSampleCharacteristicsNode(TSharedRef<FFCPXMLNode> InParentNode, int InDepth, int InSampleRate);
/** Creates rate node. */
bool ConstructRateNode(TSharedRef<FFCPXMLNode> InParentNode);
/** Creates timecode node. */
bool ConstructTimecodeNode(TSharedRef<FFCPXMLNode> InParentNode);
/** Creates logginginfo elements. */
void ConstructLoggingInfoElements(TSharedRef<FFCPXMLNode> InLoggingInfoNode, const UObject* InObject = nullptr);
/** Set logginginfo element value. */
void SetLoggingInfoElementValue(TSharedPtr<FFCPXMLNode> InNode, const UObject* InObject, const FString& InElement);
/** Get cinematic duration, start, end, in, out frames for a given cinematic shot section */
bool GetCinematicSectionFrames(const TSharedPtr<FMovieSceneExportCinematicSectionData> InCinematicSectionData, int32& OutDuration, int32& OutStartFrame, int32& OutEndFrame, int32& OutInFrame, int32& OutOutFrame);
/** Get audio duration, start, end, in, out frames for a given cinematic shot section */
bool GetAudioSectionFrames(const TSharedPtr<FMovieSceneExportAudioSectionData> InAudioSectionData, int32& OutDuration, int32& OutStartFrame, int32& OutEndFrame, int32& OutInFrame, int32& OutOutFrame);
private:
/** Has master clip id for given section */
bool HasMasterClipIdName(const TSharedPtr<FMovieSceneExportSectionData> InSection, FString& OutName, bool& bOutMasterClipExists);
/** Get master clip id name for section */
bool GetMasterClipIdName(const TSharedPtr<FMovieSceneExportSectionData> InSection, FString& OutName);
/** Get file id name for section, adds to file map if a new id name is created */
bool GetFileIdName(const TSharedPtr<FMovieSceneExportSectionData> InSection, FString& OutName, bool& bFileExists);
/** Get next clip item name */
void GetNextClipItemIdName(FString& OutName);
/** Compose key for section file */
bool ComposeFileKey(const TSharedPtr<FMovieSceneExportSectionData> InSection, FString& OutName);
/** Returns true if audio track data contains sections with 2 channels */
bool HasStereoAudioSections(const TArray<TSharedPtr<FMovieSceneExportAudioSectionData>>& InAudioTrackData) const;
/** Get metadata section name from sequencer shot name - format is "[UE4Section=sectionobjectname]", whitespace ok. */
bool CreateCinematicSectionMetadata(const UMovieSceneCinematicShotSection* InSection, FString& OutMetadata) const;
/** Get metadata section name from sequencer shot name - format is "[UE4SoundWave=soundwaveobjectname]", whitespace ok. */
bool CreateSoundWaveMetadata(const USoundWave* InSoundWave, const TArray<const UMovieSceneAudioSection*> InAudioSections, FString& OutMetadata) const;
/** Get id for audio top level section */
static FString GetAudioSectionTopLevelName(const UMovieSceneAudioSection* InAudioSection);
/** Get audio section group name */
static FString GetAudioSectionName(const UMovieSceneSection* InAudioSection);
private:
TSharedRef<FMovieSceneExportData> ExportData;
TSharedRef<FMovieSceneTranslatorContext> ExportContext;
FString SaveFilePath;
uint32 SequenceId;
uint32 MasterClipId;
uint32 ClipItemId;
uint32 FileId;
/** Map section's unique key string to the id used for masterclip element names */
TMap<FString, uint32> MasterClipIdMap;
/** Map section's source file name to its file element name */
TMap<FString, uint32> FileIdMap;
};
| 412 | 0.854943 | 1 | 0.854943 | game-dev | MEDIA | 0.447194 | game-dev | 0.51325 | 1 | 0.51325 |
modded-factorio/bobsmods | 19,357 | bobclasses/prototypes/bodies.lua | local body_drop_move = {
filename = "__base__/sound/item/armor-large-inventory-move.ogg",
volume = 0.7,
}
local body_pick = {
filename = "__base__/sound/item/armor-large-inventory-pickup.ogg",
volume = 0.7,
}
data:extend({
{
type = "item",
name = "character",
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
subgroup = "bob-bodies",
order = "a[character]-1",
place_result = "character",
stack_size = 1,
drop_sound = body_drop_move,
inventory_move_sound = body_drop_move,
pick_sound = body_pick,
},
{
type = "item",
name = "bob-character-miner",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -5, 0 },
},
{
icon = "__bobclasses__/icons/crafter.png",
icon_size = 64,
scale = 0.25,
shift = { 8, 0 },
},
},
subgroup = "bob-bodies",
order = "a[character]-1-crafter",
place_result = "bob-character-miner",
stack_size = 1,
drop_sound = body_drop_move,
inventory_move_sound = body_drop_move,
pick_sound = body_pick,
},
{
type = "item",
name = "bob-character-fighter",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -5, 0 },
},
{
icon = "__bobclasses__/icons/fighter.png",
icon_size = 64,
scale = 0.25,
shift = { 8, 0 },
},
},
subgroup = "bob-bodies",
order = "a[character]-1-fighter",
place_result = "bob-character-fighter",
stack_size = 1,
drop_sound = body_drop_move,
inventory_move_sound = body_drop_move,
pick_sound = body_pick,
},
{
type = "item",
name = "bob-character-builder",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -5, 0 },
},
{
icon = "__bobclasses__/icons/builder.png",
icon_size = 64,
scale = 0.25,
shift = { 8, 0 },
},
},
subgroup = "bob-bodies",
order = "a[character]-1-builder",
place_result = "bob-character-builder",
stack_size = 1,
drop_sound = body_drop_move,
inventory_move_sound = body_drop_move,
pick_sound = body_pick,
},
{
type = "item",
name = "bob-character-balanced-2",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -5, 0 },
},
{
icon = "__bobclasses__/icons/2.png",
icon_size = 64,
scale = 0.25,
shift = { 8, 8 },
},
},
subgroup = "bob-bodies",
order = "a[character]-2",
place_result = "bob-character-balanced-2",
stack_size = 1,
drop_sound = body_drop_move,
inventory_move_sound = body_drop_move,
pick_sound = body_pick,
},
{
type = "item",
name = "bob-character-miner-2",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -5, 0 },
},
{
icon = "__bobclasses__/icons/crafter.png",
icon_size = 64,
scale = 0.25,
shift = { 8, -8 },
},
{
icon = "__bobclasses__/icons/2.png",
icon_size = 64,
scale = 0.25,
shift = { 8, 8 },
},
},
subgroup = "bob-bodies",
order = "a[character]-2-crafter",
place_result = "bob-character-miner-2",
stack_size = 1,
drop_sound = body_drop_move,
inventory_move_sound = body_drop_move,
pick_sound = body_pick,
},
{
type = "item",
name = "bob-character-fighter-2",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -5, 0 },
},
{
icon = "__bobclasses__/icons/fighter.png",
icon_size = 64,
scale = 0.25,
shift = { 8, -8 },
},
{
icon = "__bobclasses__/icons/2.png",
icon_size = 64,
scale = 0.25,
shift = { 8, 8 },
},
},
subgroup = "bob-bodies",
order = "a[character]-2-fighter",
place_result = "bob-character-fighter-2",
stack_size = 1,
drop_sound = body_drop_move,
inventory_move_sound = body_drop_move,
pick_sound = body_pick,
},
{
type = "item",
name = "bob-character-builder-2",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -5, 0 },
},
{
icon = "__bobclasses__/icons/builder.png",
icon_size = 64,
scale = 0.25,
shift = { 8, -8 },
},
{
icon = "__bobclasses__/icons/2.png",
icon_size = 64,
scale = 0.25,
shift = { 8, 8 },
},
},
subgroup = "bob-bodies",
order = "a[character]-2-builder",
place_result = "bob-character-builder-2",
stack_size = 1,
drop_sound = body_drop_move,
inventory_move_sound = body_drop_move,
pick_sound = body_pick,
},
{
type = "item",
name = "bob-character-engineer",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -5, 0 },
},
{
icon = "__bobclasses__/icons/engineer.png",
icon_size = 64,
scale = 0.25,
shift = { 8, 0 },
},
},
subgroup = "bob-bodies",
order = "a[character]-2-engineer",
place_result = "bob-character-engineer",
stack_size = 1,
drop_sound = body_drop_move,
inventory_move_sound = body_drop_move,
pick_sound = body_pick,
},
{
type = "item",
name = "bob-character-prospector",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -5, 0 },
},
{
icon = "__bobclasses__/icons/sapper.png",
icon_size = 64,
scale = 0.25,
shift = { 8, 0 },
},
},
subgroup = "bob-bodies",
order = "a[character]-2-sapper",
place_result = "bob-character-prospector",
stack_size = 1,
drop_sound = body_drop_move,
inventory_move_sound = body_drop_move,
pick_sound = body_pick,
},
})
data:extend({
{
type = "recipe",
name = "character",
energy_required = 10,
enabled = false,
ingredients = {
{ type = "item", name = "bob-player-frame", amount = 1 },
{ type = "item", name = "assembling-machine-2", amount = 1 },
},
results = { { type = "item", name = "character", amount = 1 } },
},
{
type = "recipe",
name = "bob-character-miner",
energy_required = 10,
enabled = false,
ingredients = {
{ type = "item", name = "bob-player-frame", amount = 1 },
{ type = "item", name = "assembling-machine-2", amount = 1 },
{ type = "item", name = "electric-furnace", amount = 1 },
},
results = { { type = "item", name = "bob-character-miner", amount = 1 } },
},
{
type = "recipe",
name = "bob-character-fighter",
energy_required = 10,
enabled = false,
ingredients = {
{ type = "item", name = "bob-player-frame", amount = 1 },
{ type = "item", name = "assembling-machine-2", amount = 1 },
{ type = "item", name = "exoskeleton-equipment", amount = 1 },
},
results = { { type = "item", name = "bob-character-fighter", amount = 1 } },
},
{
type = "recipe",
name = "bob-character-builder",
energy_required = 10,
enabled = false,
ingredients = {
{ type = "item", name = "bob-player-frame", amount = 1 },
{ type = "item", name = "assembling-machine-2", amount = 1 },
{ type = "item", name = "fast-inserter", amount = 2 },
},
results = { { type = "item", name = "bob-character-builder", amount = 1 } },
},
{
type = "recipe",
name = "bob-character-balanced-2",
energy_required = 10,
enabled = false,
ingredients = {
{ type = "item", name = "bob-player-frame-2", amount = 1 },
{ type = "item", name = "assembling-machine-3", amount = 1 },
},
results = { { type = "item", name = "bob-character-balanced-2", amount = 1 } },
},
{
type = "recipe",
name = "bob-character-miner-2",
energy_required = 10,
enabled = false,
ingredients = {
{ type = "item", name = "bob-player-frame-2", amount = 1 },
{ type = "item", name = "assembling-machine-3", amount = 1 },
{ type = "item", name = "electric-furnace", amount = 1 },
},
results = { { type = "item", name = "bob-character-miner-2", amount = 1 } },
},
{
type = "recipe",
name = "bob-character-fighter-2",
energy_required = 10,
enabled = false,
ingredients = {
{ type = "item", name = "bob-player-frame-2", amount = 1 },
{ type = "item", name = "assembling-machine-2", amount = 1 },
{ type = "item", name = "exoskeleton-equipment", amount = 1 },
},
results = { { type = "item", name = "bob-character-fighter-2", amount = 1 } },
},
{
type = "recipe",
name = "bob-character-builder-2",
energy_required = 10,
enabled = false,
ingredients = {
{ type = "item", name = "bob-player-frame-2", amount = 1 },
{ type = "item", name = "assembling-machine-3", amount = 1 },
{ type = "item", name = "bulk-inserter", amount = 2 },
},
results = { { type = "item", name = "bob-character-builder-2", amount = 1 } },
},
{
type = "recipe",
name = "bob-character-engineer",
energy_required = 10,
enabled = false,
ingredients = {
{ type = "item", name = "bob-player-frame-2", amount = 1 },
{ type = "item", name = "assembling-machine-3", amount = 1 },
{ type = "item", name = "electric-furnace", amount = 1 },
{ type = "item", name = "fast-inserter", amount = 2 },
},
results = { { type = "item", name = "bob-character-engineer", amount = 1 } },
},
{
type = "recipe",
name = "bob-character-prospector",
energy_required = 10,
enabled = false,
ingredients = {
{ type = "item", name = "bob-player-frame-2", amount = 1 },
{ type = "item", name = "assembling-machine-2", amount = 1 },
{ type = "item", name = "fast-inserter", amount = 2 },
{ type = "item", name = "exoskeleton-equipment", amount = 1 },
},
results = { { type = "item", name = "bob-character-prospector", amount = 1 } },
},
})
data:extend({
{
type = "technology",
name = "bob-bodies",
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
effects = {
{
type = "unlock-recipe",
recipe = "character",
},
{
type = "unlock-recipe",
recipe = "bob-player-brain",
},
{
type = "unlock-recipe",
recipe = "bob-player-head",
},
{
type = "unlock-recipe",
recipe = "bob-player-boots",
},
{
type = "unlock-recipe",
recipe = "bob-player-gloves",
},
{
type = "unlock-recipe",
recipe = "bob-player-power-core",
},
{
type = "unlock-recipe",
recipe = "bob-player-frame",
},
},
prerequisites = {
"robotics",
"advanced-circuit",
"automation-2",
},
unit = {
count = 250,
ingredients = {
{ "automation-science-pack", 1 },
{ "logistic-science-pack", 1 },
{ "chemical-science-pack", 1 },
},
time = 60,
},
},
{
type = "technology",
name = "bob-miner-body",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -20, 0 },
},
{
icon = "__bobclasses__/icons/crafter.png",
icon_size = 64,
scale = 0.8,
shift = { 40, 0 },
},
},
effects = {
{
type = "unlock-recipe",
recipe = "bob-character-miner",
},
},
prerequisites = {
"bob-bodies",
"automation-2",
"advanced-material-processing-2",
},
unit = {
count = 150,
ingredients = {
{ "automation-science-pack", 1 },
{ "logistic-science-pack", 1 },
{ "chemical-science-pack", 1 },
},
time = 30,
},
},
{
type = "technology",
name = "bob-fighter-body",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -20, 0 },
},
{
icon = "__bobclasses__/icons/fighter.png",
icon_size = 64,
scale = 0.8,
shift = { 40, 0 },
},
},
effects = {
{
type = "unlock-recipe",
recipe = "bob-character-fighter",
},
},
prerequisites = {
"bob-bodies",
"exoskeleton-equipment",
},
unit = {
count = 150,
ingredients = {
{ "automation-science-pack", 1 },
{ "logistic-science-pack", 1 },
{ "chemical-science-pack", 1 },
},
time = 30,
},
},
{
type = "technology",
name = "bob-builder-body",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -20, 0 },
},
{
icon = "__bobclasses__/icons/builder.png",
icon_size = 64,
scale = 0.8,
shift = { 40, 0 },
},
},
effects = {
{
type = "unlock-recipe",
recipe = "bob-character-builder",
},
},
prerequisites = {
"bob-bodies",
"fast-inserter",
},
unit = {
count = 150,
ingredients = {
{ "automation-science-pack", 1 },
{ "logistic-science-pack", 1 },
{ "chemical-science-pack", 1 },
},
time = 30,
},
},
{
type = "technology",
name = "bob-bodies-2",
localised_description = { "technology-description.bob-bodies2" },
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
},
{
icon = "__bobclasses__/icons/2.png",
icon_size = 64,
scale = 1,
shift = { 32, 32 },
},
},
effects = {
{
type = "unlock-recipe",
recipe = "bob-character-balanced-2",
},
{
type = "unlock-recipe",
recipe = "bob-player-brain-2",
},
{
type = "unlock-recipe",
recipe = "bob-player-head-2",
},
{
type = "unlock-recipe",
recipe = "bob-player-boots-2",
},
{
type = "unlock-recipe",
recipe = "bob-player-gloves-2",
},
{
type = "unlock-recipe",
recipe = "bob-player-frame-2",
},
},
prerequisites = {
"bob-bodies",
"production-science-pack",
"processing-unit",
"automation-3",
},
unit = {
count = 250,
ingredients = {
{ "automation-science-pack", 1 },
{ "logistic-science-pack", 1 },
{ "chemical-science-pack", 1 },
{ "production-science-pack", 1 },
},
time = 60,
},
},
{
type = "technology",
name = "bob-miner-body-2",
localised_description = { "technology-description.bob-miner-body2" },
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -20, 0 },
},
{
icon = "__bobclasses__/icons/crafter.png",
icon_size = 64,
scale = 0.8,
shift = { 40, 0 },
},
},
effects = {
{
type = "unlock-recipe",
recipe = "bob-character-miner-2",
},
},
prerequisites = {
"bob-bodies-2",
"bob-miner-body",
},
unit = {
count = 150,
ingredients = {
{ "automation-science-pack", 1 },
{ "logistic-science-pack", 1 },
{ "chemical-science-pack", 1 },
{ "production-science-pack", 1 },
},
time = 30,
},
},
{
type = "technology",
name = "bob-fighter-body-2",
localised_description = { "technology-description.bob-fighter-body2" },
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -20, 0 },
},
{
icon = "__bobclasses__/icons/fighter.png",
icon_size = 64,
scale = 0.8,
shift = { 40, 0 },
},
},
effects = {
{
type = "unlock-recipe",
recipe = "bob-character-fighter-2",
},
},
prerequisites = {
"bob-bodies-2",
"bob-fighter-body",
},
unit = {
count = 150,
ingredients = {
{ "automation-science-pack", 1 },
{ "logistic-science-pack", 1 },
{ "chemical-science-pack", 1 },
{ "production-science-pack", 1 },
},
time = 30,
},
},
{
type = "technology",
name = "bob-builder-body-2",
localised_description = { "technology-description.bob-builder-body2" },
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -20, 0 },
},
{
icon = "__bobclasses__/icons/builder.png",
icon_size = 64,
scale = 0.8,
shift = { 40, 0 },
},
},
effects = {
{
type = "unlock-recipe",
recipe = "bob-character-builder-2",
},
},
prerequisites = {
"bob-bodies-2",
"bob-builder-body",
"bulk-inserter",
},
unit = {
count = 150,
ingredients = {
{ "automation-science-pack", 1 },
{ "logistic-science-pack", 1 },
{ "chemical-science-pack", 1 },
{ "production-science-pack", 1 },
},
time = 30,
},
},
{
type = "technology",
name = "bob-engineer-body",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -20, 0 },
},
{
icon = "__bobclasses__/icons/engineer.png",
icon_size = 64,
scale = 0.8,
shift = { 40, 0 },
},
},
effects = {
{
type = "unlock-recipe",
recipe = "bob-character-engineer",
},
},
prerequisites = {
"bob-miner-body",
"bob-builder-body",
"bob-bodies-2",
},
unit = {
count = 150,
ingredients = {
{ "automation-science-pack", 1 },
{ "logistic-science-pack", 1 },
{ "chemical-science-pack", 1 },
{ "production-science-pack", 1 },
},
time = 30,
},
},
{
type = "technology",
name = "bob-prospector-body",
icons = {
{
icon = "__bobclasses__/icons/character.png",
icon_size = 128,
shift = { -20, 0 },
},
{
icon = "__bobclasses__/icons/sapper.png",
icon_size = 64,
scale = 0.8,
shift = { 40, 0 },
},
},
effects = {
{
type = "unlock-recipe",
recipe = "bob-character-prospector",
},
},
prerequisites = {
"bob-builder-body",
"bob-fighter-body",
"bob-bodies-2",
},
unit = {
count = 150,
ingredients = {
{ "automation-science-pack", 1 },
{ "logistic-science-pack", 1 },
{ "chemical-science-pack", 1 },
{ "production-science-pack", 1 },
},
time = 30,
},
},
})
| 412 | 0.608019 | 1 | 0.608019 | game-dev | MEDIA | 0.811433 | game-dev | 0.717214 | 1 | 0.717214 |
sahilrajpurkar03/nlp-pnp-robotic-arm | 15,791 | src/ur5_moveit_config/src/ur5_pick_place_cpp_s.cpp | #include <rclcpp/rclcpp.hpp>
#include <moveit/move_group_interface/move_group_interface.h>
#include <geometry_msgs/msg/pose.hpp>
#include <moveit_msgs/msg/robot_trajectory.hpp>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
#include <vector>
#include <thread>
#include <cmath>
#include <std_msgs/msg/float64_multi_array.hpp>
#include <mutex>
// --------------------- Function: Move to ready pose ---------------------
bool moveToNamedPose(moveit::planning_interface::MoveGroupInterface &move_group,
const std::string &target_name)
{
move_group.setStartStateToCurrentState();
move_group.setNamedTarget(target_name);
moveit::planning_interface::MoveGroupInterface::Plan plan;
auto success = (move_group.plan(plan) == moveit::core::MoveItErrorCode::SUCCESS);
if (success)
{
RCLCPP_INFO(rclcpp::get_logger("moveToNamedPose"), "Moving to '%s' pose...", target_name.c_str());
move_group.execute(plan);
// 🔎 Print current EE pose
geometry_msgs::msg::Pose ee_pose = move_group.getCurrentPose().pose;
RCLCPP_INFO(rclcpp::get_logger("moveToNamedPose"),
"EE Pose in world (base_link):\n Position -> x: %.3f, y: %.3f, z: %.3f\n Orientation -> x: %.3f, y: %.3f, z: %.3f, w: %.3f",
ee_pose.position.x,
ee_pose.position.y,
ee_pose.position.z,
ee_pose.orientation.x,
ee_pose.orientation.y,
ee_pose.orientation.z,
ee_pose.orientation.w);
return true;
}
else
{
RCLCPP_ERROR(rclcpp::get_logger("moveToNamedPose"), "Failed to plan to '%s' pose", target_name.c_str());
return false;
}
}
// --------------------- Function: Move EE to absolute (X,Y) in world ---------------------
bool moveToWorldXY(moveit::planning_interface::MoveGroupInterface &move_group,
double target_x, double target_y)
{
geometry_msgs::msg::Pose current_pose = move_group.getCurrentPose().pose;
geometry_msgs::msg::Pose target_pose = current_pose;
target_pose.position.x = target_x;
target_pose.position.y = target_y;
RCLCPP_INFO(rclcpp::get_logger("moveToWorldXY"),
"Target Pose in world:\n Position -> x: %.3f, y: %.3f, z: %.3f",
target_pose.position.x,
target_pose.position.y,
target_pose.position.z);
std::vector<geometry_msgs::msg::Pose> waypoints;
waypoints.push_back(target_pose);
moveit_msgs::msg::RobotTrajectory trajectory;
double fraction = move_group.computeCartesianPath(waypoints, 0.005, 0.0, trajectory);
if (fraction > 0.99)
{
move_group.execute(trajectory);
return true;
}
else
{
RCLCPP_ERROR(rclcpp::get_logger("moveToWorldXY"),
"Failed to compute Cartesian path. Fraction: %f", fraction);
return false;
}
}
// --------------------- Function: Rotate EE yaw ---------------------
bool rotateGripperYaw(moveit::planning_interface::MoveGroupInterface &move_group,
double yaw)
{
geometry_msgs::msg::Pose current_pose = move_group.getCurrentPose().pose;
// Convert current orientation to roll-pitch-yaw
tf2::Quaternion q_orig, q_rot;
tf2::fromMsg(current_pose.orientation, q_orig);
double roll, pitch, cur_yaw;
tf2::Matrix3x3(q_orig).getRPY(roll, pitch, cur_yaw);
// Build new quaternion with given yaw, keep roll/pitch
q_rot.setRPY(roll, pitch, yaw);
q_rot.normalize();
geometry_msgs::msg::Pose target_pose = current_pose;
geometry_msgs::msg::Quaternion q_msg = tf2::toMsg(q_rot);
target_pose.orientation = q_msg;
RCLCPP_INFO(rclcpp::get_logger("rotateGripperYaw"),
"Rotating gripper to yaw=%.3f rad (%.1f deg)", yaw, yaw * 180.0 / M_PI);
std::vector<geometry_msgs::msg::Pose> waypoints;
waypoints.push_back(target_pose);
moveit_msgs::msg::RobotTrajectory trajectory;
double fraction = move_group.computeCartesianPath(waypoints, 0.01, 0.0, trajectory);
if (fraction > 0.99)
{
move_group.execute(trajectory);
return true;
}
else
{
RCLCPP_ERROR(rclcpp::get_logger("rotateGripperYaw"),
"Failed to compute yaw rotation path. Fraction: %f", fraction);
return false;
}
}
// --------------------- Function: Move EE downward in Z ---------------------
bool moveDownZ(moveit::planning_interface::MoveGroupInterface &move_group,
double dz)
{
geometry_msgs::msg::Pose current_pose = move_group.getCurrentPose().pose;
geometry_msgs::msg::Pose target_pose = current_pose;
target_pose.position.z -= dz; // go down by dz
RCLCPP_INFO(rclcpp::get_logger("moveDownZ"),
"Target Pose going down:\n Position -> x: %.3f, y: %.3f, z: %.3f",
target_pose.position.x,
target_pose.position.y,
target_pose.position.z);
std::vector<geometry_msgs::msg::Pose> waypoints;
waypoints.push_back(target_pose);
moveit_msgs::msg::RobotTrajectory trajectory;
double fraction = move_group.computeCartesianPath(waypoints, 0.005, 0.0, trajectory);
if (fraction > 0.99)
{
move_group.execute(trajectory);
return true;
}
else
{
RCLCPP_ERROR(rclcpp::get_logger("moveDownZ"),
"Failed to compute Z downward path. Fraction: %f", fraction);
return false;
}
}
// --------------------- Function: Close gripper using MoveIt named target ---------------------
bool closeGripper(moveit::planning_interface::MoveGroupInterface &gripper_group)
{
gripper_group.setStartStateToCurrentState();
gripper_group.setNamedTarget("close");
moveit::planning_interface::MoveGroupInterface::Plan plan;
auto success = (gripper_group.plan(plan) == moveit::core::MoveItErrorCode::SUCCESS);
if (success)
{
RCLCPP_INFO(rclcpp::get_logger("closeGripper"), "Closing gripper (named target: close)...");
gripper_group.execute(plan);
return true;
}
else
{
RCLCPP_ERROR(rclcpp::get_logger("closeGripper"), "Failed to plan to gripper close pose");
return false;
}
}
// --------------------- Function: Move EE upward in Z ---------------------
bool moveUpZ(moveit::planning_interface::MoveGroupInterface &move_group,
double dz)
{
geometry_msgs::msg::Pose current_pose = move_group.getCurrentPose().pose;
geometry_msgs::msg::Pose target_pose = current_pose;
target_pose.position.z += dz; // go up by dz
RCLCPP_INFO(rclcpp::get_logger("moveUpZ"),
"Target Pose going up:\n Position -> x: %.3f, y: %.3f, z: %.3f",
target_pose.position.x,
target_pose.position.y,
target_pose.position.z);
std::vector<geometry_msgs::msg::Pose> waypoints;
waypoints.push_back(target_pose);
moveit_msgs::msg::RobotTrajectory trajectory;
double fraction = move_group.computeCartesianPath(waypoints, 0.005, 0.0, trajectory);
if (fraction > 0.99)
{
move_group.execute(trajectory);
return true;
}
else
{
RCLCPP_ERROR(rclcpp::get_logger("moveUpZ"),
"Failed to compute Z upward path. Fraction: %f", fraction);
return false;
}
}
// --------------------- Function: Rotate base joint ---------------------
bool rotateBase(moveit::planning_interface::MoveGroupInterface &move_group,
double delta_angle)
{
// Get current joint values
std::vector<double> joint_group_positions = move_group.getCurrentJointValues();
// Joint[0] = base rotation (shoulder_pan_joint)
double current_angle = joint_group_positions[0];
joint_group_positions[0] = current_angle + delta_angle; // add delta (e.g., M_PI for 180°)
move_group.setJointValueTarget(joint_group_positions);
moveit::planning_interface::MoveGroupInterface::Plan plan;
bool success = (move_group.plan(plan) == moveit::core::MoveItErrorCode::SUCCESS);
if (success)
{
RCLCPP_INFO(rclcpp::get_logger("rotateBase"),
"Rotating base joint by %.3f rad (%.1f deg)",
delta_angle, delta_angle * 180.0 / M_PI);
move_group.execute(plan);
return true;
}
else
{
RCLCPP_ERROR(rclcpp::get_logger("rotateBase"),
"Failed to plan base rotation");
return false;
}
}
// --------------------- Function: Open gripper using MoveIt named target ---------------------
bool openGripper(moveit::planning_interface::MoveGroupInterface &gripper_group)
{
gripper_group.setStartStateToCurrentState();
gripper_group.setNamedTarget("open");
moveit::planning_interface::MoveGroupInterface::Plan plan;
auto success = (gripper_group.plan(plan) == moveit::core::MoveItErrorCode::SUCCESS);
if (success)
{
RCLCPP_INFO(rclcpp::get_logger("openGripper"), "Opening gripper (named target: open)...");
gripper_group.execute(plan);
return true;
}
else
{
RCLCPP_ERROR(rclcpp::get_logger("openGripper"), "Failed to plan to gripper open pose");
return false;
}
}
// --------------------- Function: Execute pick & place sequence ---------------------
bool executePickAndPlace(moveit::planning_interface::MoveGroupInterface &move_group,
moveit::planning_interface::MoveGroupInterface &gripper_group,
double x, double y, double yaw,
rclcpp::Node::SharedPtr node,
long int delay, double box)
{
if (!moveToWorldXY(move_group, x, y)) return false;
rclcpp::sleep_for(std::chrono::seconds(delay));
if (!rotateGripperYaw(move_group, yaw)) return false;
rclcpp::sleep_for(std::chrono::seconds(delay));
if (!moveDownZ(move_group, 0.233)) return false;
rclcpp::sleep_for(std::chrono::seconds(delay));
if (!closeGripper(gripper_group)) return false;
rclcpp::sleep_for(std::chrono::seconds(delay));
if (!moveUpZ(move_group, 0.233)) return false;
rclcpp::sleep_for(std::chrono::seconds(delay));
// if (!rotateBase(move_group, M_PI)) return false;
// rclcpp::sleep_for(std::chrono::seconds(2));
double box_x, box_y;
if (box == 1){
box_x = 0.4;
box_y = -0.53;
}
else if (box == 2) {
box_x = 0.4;
box_y = 0.53;
}
if (!moveToWorldXY(move_group, box_x, box_y)) return false;
rclcpp::sleep_for(std::chrono::seconds(delay));
if (!moveDownZ(move_group, 0.24)) return false;
rclcpp::sleep_for(std::chrono::seconds(delay));
if (!openGripper(gripper_group)) return false;
rclcpp::sleep_for(std::chrono::seconds(delay));
if (!moveUpZ(move_group, 0.24)) return false;
rclcpp::sleep_for(std::chrono::seconds(delay));
if (!moveToNamedPose(move_group, "arm_ready")) return false;
rclcpp::sleep_for(std::chrono::seconds(delay));
RCLCPP_INFO(node->get_logger(), "✅ Completed pick & place cycle.");
return true;
}
// --------------------- Main ---------------------
int main(int argc, char **argv)
{
rclcpp::init(argc, argv);
auto node = rclcpp::Node::make_shared("ur5_xy_yaw_approach");
const std::string PLANNING_GROUP = "arm";
moveit::planning_interface::MoveGroupInterface move_group(node, PLANNING_GROUP);
const std::string GRIPPER_GROUP = "gripper";
moveit::planning_interface::MoveGroupInterface gripper_group(node, GRIPPER_GROUP);
RCLCPP_INFO(node->get_logger(), "Planning frame: %s", move_group.getPlanningFrame().c_str());
RCLCPP_INFO(node->get_logger(), "End effector link: %s", move_group.getEndEffectorLink().c_str());
// ---- Parameters for tolerance ----
node->declare_parameter("pos_tol", 0.001); // 1 mm default
node->declare_parameter("yaw_tol", 0.01); // 0.01 rad (~0.57°) default
double pos_tol = node->get_parameter("pos_tol").as_double();
double yaw_tol = node->get_parameter("yaw_tol").as_double();
// ---- Shared target variables ----
std::mutex mtx;
bool new_target_available = false;
double target_x = 0.0, target_y = 0.0, target_yaw = 0.0, target_box = -1.0;
// Store last accepted values
double last_x = 0.0, last_y = 0.0, last_yaw = 0.0;
// ---- Subscriber ----
auto sub = node->create_subscription<std_msgs::msg::Float64MultiArray>(
"/target_point", 10,
[&](const std_msgs::msg::Float64MultiArray::SharedPtr msg)
{
if (msg->data.size() < 4)
{
RCLCPP_ERROR(node->get_logger(),
"Received target_point with insufficient data. Expected [x, y, yaw, box].");
return;
}
double new_x = msg->data[0];
double new_y = msg->data[1];
double new_yaw = msg->data[2];
double new_box = msg->data[3];
if (std::fabs(new_x - last_x) > pos_tol ||
std::fabs(new_y - last_y) > pos_tol ||
std::fabs(new_yaw - last_yaw) > yaw_tol ||
new_box != target_box)
{
std::lock_guard<std::mutex> lock(mtx);
target_x = new_x;
target_y = new_y;
target_yaw = new_yaw;
target_box = new_box;
new_target_available = true;
last_x = new_x;
last_y = new_y;
last_yaw = new_yaw;
RCLCPP_INFO(node->get_logger(),
"Accepted new target_point -> x=%.3f, y=%.3f, yaw=%.3f, box=%.0f",
target_x, target_y, target_yaw, target_box);
}
else
{
RCLCPP_INFO(node->get_logger(),
"Ignored target_point (difference below tolerance).");
}
});
// ---- Executor and spinner ----
rclcpp::executors::SingleThreadedExecutor executor;
executor.add_node(node);
std::thread spinner([&executor]() { executor.spin(); });
// ---- Main loop to execute MoveIt motions ----
while (rclcpp::ok())
{
bool run_motion = false;
double x, y, yaw, box;
long int delay = 1; // seconds
// // ----------------- FOR DEBUG: Hardcoded target -----------------
// x = 0.566; // meters
// y = 0.053; // meters
// yaw = 3.14; // radians (45 deg)
// box = 1; // box number (1 or 2)
// run_motion = true;
// // ----------------------------------------------------------
// Original subscriber logic (keep it commented for debug)
{
std::lock_guard<std::mutex> lock(mtx);
if (new_target_available)
{
x = target_x;
y = target_y;
yaw = target_yaw;
box = target_box;
new_target_available = false;
run_motion = true;
}
}
if (run_motion)
{
if (!executePickAndPlace(move_group, gripper_group, x, y, yaw, node, delay, box))
{
RCLCPP_ERROR(node->get_logger(), "Pick & place failed. Exiting...");
break;
}
// // For debug, only run once
// break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
executor.cancel();
spinner.join();
rclcpp::shutdown();
return 0;
}
| 412 | 0.96181 | 1 | 0.96181 | game-dev | MEDIA | 0.347793 | game-dev | 0.957842 | 1 | 0.957842 |
JLChnToZ/BMP-U | 3,358 | Assets/unity-ui-extensions/Scripts/Utilities/UISelectableExtension.cs | /// Credit AriathTheWise, Sfyne
/// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/page-2#post-1796783
/// Additional disabled - https://bitbucket.org/ddreaper/unity-ui-extensions/issues/47/uiselectableextension-_pressed-bug
/// Extended to include a HELD state that continually fires while the button is held down.
/// Refactored so it can be added to any button and expose the events in the editor.
using UnityEngine.Events;
using UnityEngine.EventSystems;
namespace UnityEngine.UI.Extensions
{
/// <summary>
/// UIButton
/// </summary>
[AddComponentMenu("UI/Extensions/UI Selectable Extension")]
[RequireComponent(typeof(Selectable))]
public class UISelectableExtension : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
#region Sub-Classes
[System.Serializable]
public class UIButtonEvent : UnityEvent<PointerEventData.InputButton> { }
#endregion
#region Events
[Tooltip("Event that fires when a button is initially pressed down")]
public UIButtonEvent OnButtonPress;
[Tooltip("Event that fires when a button is released")]
public UIButtonEvent OnButtonRelease;
[Tooltip("Event that continually fires while a button is held down")]
public UIButtonEvent OnButtonHeld;
#endregion
private bool _pressed;
private PointerEventData _heldEventData;
void IPointerDownHandler.OnPointerDown(PointerEventData eventData)
{
//Can't set the state as it's too locked down.
//DoStateTransition(SelectionState.Pressed, false);
if (OnButtonPress != null)
{
OnButtonPress.Invoke(eventData.button);
}
_pressed = true;
_heldEventData = eventData;
}
void IPointerUpHandler.OnPointerUp(PointerEventData eventData)
{
//DoStateTransition(SelectionState.Normal, false);
if (OnButtonRelease != null)
{
OnButtonRelease.Invoke(eventData.button);
}
_pressed = false;
_heldEventData = null;
}
void Update()
{
if (!_pressed)
return;
if (OnButtonHeld != null)
{
OnButtonHeld.Invoke(_heldEventData.button);
}
}
/// <summary>
/// Test method to verify a control has been clicked
/// </summary>
public void TestClicked()
{
#if DEBUG || UNITY_EDITOR
Debug.Log("Control Clicked");
#endif
}
/// <summary>
/// Test method to verify a controll is pressed
/// </summary>
public void TestPressed()
{
#if DEBUG || UNITY_EDITOR
Debug.Log("Control Pressed");
#endif
}
/// <summary>
/// est method to verify if a control is released
/// </summary>
public void TestReleased()
{
#if DEBUG || UNITY_EDITOR
Debug.Log("Control Released");
#endif
}
/// <summary>
/// est method to verify if a control is being held
/// </summary>
public void TestHold()
{
#if DEBUG || UNITY_EDITOR
Debug.Log("Control Held");
#endif
}
//Fixed UISelectableExtension inactive bug (if gameObject becomes inactive while button is held down it never goes back to _pressed = false)
void OnDisable()
{
_pressed = false;
}
}
} | 412 | 0.870125 | 1 | 0.870125 | game-dev | MEDIA | 0.728907 | game-dev,desktop-app | 0.828827 | 1 | 0.828827 |
lua9520/source-engine-2018-cstrike15_src | 2,958 | engine/staticpropmgr.h | //===== Copyright 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $Revision: $
// $NoKeywords: $
//
// This file contains a little interface to deal with static prop collisions
//
//===========================================================================//
#ifndef STATICPROPMGR_H
#define STATICPROPMGR_H
#include "mathlib/vector.h"
#include "engine/IStaticPropMgr.h"
// FIXME: Remove! Only here for the test against old code
#include "enginetrace.h"
//-----------------------------------------------------------------------------
// foward declarations
//-----------------------------------------------------------------------------
class ICollideable;
FORWARD_DECLARE_HANDLE( LightCacheHandle_t );
class IPooledVBAllocator;
DECLARE_LOGGING_CHANNEL( LOG_StaticPropManager );
//-----------------------------------------------------------------------------
// The engine's static prop manager
//-----------------------------------------------------------------------------
abstract_class IStaticPropMgrEngine
{
public:
virtual bool Init() = 0;
virtual void Shutdown() = 0;
// Call at the beginning of the level, will unserialize all static
// props and add them to the main collision tree
virtual void LevelInit() = 0;
// Call this when there's a client, *after* LevelInit, and after the world entity is loaded
virtual void LevelInitClient() = 0;
// Call this when there's a client, *before* LevelShutdown
virtual void LevelShutdownClient() = 0;
// Call at the end of the level, cleans up the static props
virtual void LevelShutdown() = 0;
// Call this to recompute static prop lighting when necessary
virtual void RecomputeStaticLighting() = 0;
// Check if a static prop is in a particular PVS.
virtual bool IsPropInPVS( IHandleEntity *pHandleEntity, const byte *pVis ) const = 0;
// temp - loadtime setting of flag to disable CSM rendering for static prop.
virtual void DisableCSMRenderingForStaticProp( int staticPropIndex ) = 0;
// returns a collideable interface to static props
virtual ICollideable *GetStaticProp( IHandleEntity *pHandleEntity ) = 0;
// returns the lightcache handle associated with a static prop
virtual LightCacheHandle_t GetLightCacheHandleForStaticProp( IHandleEntity *pHandleEntity ) = 0;
// Is a base handle a static prop?
virtual bool IsStaticProp( IHandleEntity *pHandleEntity ) const = 0;
virtual bool IsStaticProp( CBaseHandle handle ) const = 0;
// Returns the static prop index (useful for networking)
virtual int GetStaticPropIndex( IHandleEntity *pHandleEntity ) const = 0;
virtual void ConfigureSystemLevel( int nCPULevel, int nGPULevel ) = 0;
virtual void RestoreStaticProps() = 0;
};
//-----------------------------------------------------------------------------
// Singleton access
//-----------------------------------------------------------------------------
IStaticPropMgrEngine* StaticPropMgr();
#endif // STATICPROPMGR_H
| 412 | 0.939084 | 1 | 0.939084 | game-dev | MEDIA | 0.783625 | game-dev | 0.574679 | 1 | 0.574679 |
ReikaKalseki/ChromatiCraft | 1,825 | Items/Tools/ItemWideCollector.java | package Reika.ChromatiCraft.Items.Tools;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import Reika.ChromatiCraft.Base.ItemWithItemFilter;
import Reika.ChromatiCraft.Items.OwnableItem;
import Reika.ChromatiCraft.TileEntity.AOE.TileEntityItemInserter;
import Reika.DragonAPI.Libraries.ReikaAABBHelper;
public class ItemWideCollector extends ItemWithItemFilter {
public ItemWideCollector(int index) {
super(index);
}
@Override
public boolean isCurrentlyEnabled(EntityPlayer ep, ItemStack tool) {
return true;
}
@Override
public boolean canBeReversed(EntityPlayer ep, ItemStack tool) {
return false;
}
@Override
public String getActionName(EntityPlayer ep, ItemStack tool) {
return "Collecting";
}
@Override
public void onUpdate(ItemStack is, World world, Entity e, int slot, boolean held) {
if (!world.isRemote && e instanceof EntityPlayer && is.stackTagCompound != null && world.getTotalWorldTime()%4 == 0) {
EntityPlayer ep = (EntityPlayer)e;
AxisAlignedBB box = ReikaAABBHelper.getEntityCenteredAABB(ep, 8);
List<EntityItem> li = world.getEntitiesWithinAABB(EntityItem.class, box);
for (EntityItem ei : li) {
if (ei.isDead || ei.delayBeforeCanPickup > 0 || ei.getEntityData().getBoolean(TileEntityItemInserter.DROP_TAG))
continue;
ItemStack in = ei.getEntityItem();
if (in == null || in.stackSize <= 0)
continue;
if (in.getItem() instanceof OwnableItem && !((OwnableItem)in.getItem()).isCollectableBy(ei, ep)) {
continue;
}
if (!this.matchesItem(ep, is, in))
continue;
ei.onCollideWithPlayer(ep);
}
}
}
}
| 412 | 0.846058 | 1 | 0.846058 | game-dev | MEDIA | 0.989047 | game-dev | 0.966974 | 1 | 0.966974 |
celeritas-project/celeritas | 3,059 | src/geocel/g4/GeantNavHistoryUpdater.cc | //------------------------------- -*- C++ -*- -------------------------------//
// Copyright Celeritas contributors: see top-level COPYRIGHT file for details
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
//---------------------------------------------------------------------------//
//! \file geocel/g4/GeantNavHistoryUpdater.cc
//---------------------------------------------------------------------------//
#include "GeantNavHistoryUpdater.hh"
#include <G4NavigationHistory.hh>
#include <G4VPhysicalVolume.hh>
#include "corecel/math/Algorithms.hh"
#include "geocel/GeantGeoParams.hh"
#include "geocel/detail/GeantVolumeInstanceMapper.hh"
using G4PV = G4VPhysicalVolume;
namespace celeritas
{
//---------------------------------------------------------------------------//
/*!
* Construct using geant geo params.
*/
GeantNavHistoryUpdater::GeantNavHistoryUpdater(GeantGeoParams const& geo)
: GeantNavHistoryUpdater{*geo.host_ref().vi_mapper}
{
}
//---------------------------------------------------------------------------//
/*!
* Update a nav history to match the given volume instance stack.
*/
void GeantNavHistoryUpdater::operator()(Span<VolumeInstanceId const> stack,
G4NavigationHistory* nav)
{
CELER_EXPECT(std::all_of(stack.begin(), stack.end(), Identity{}));
CELER_EXPECT(nav);
size_type level = 0;
auto nav_stack_size
= [nav] { return static_cast<size_type>(nav->GetDepth()) + 1; };
// Loop deeper until stack and nav disagree
for (auto end_level = std::min<size_type>(stack.size(), nav_stack_size());
level != end_level;
++level)
{
auto* pv = nav->GetVolume(level);
if (!pv || mapper_.geant_to_id(*pv) != stack[level])
{
break;
}
}
if (CELER_UNLIKELY(level == 0))
{
// Top level disagrees: this should likely only happen when we're
// outside (i.e. stack is empty)
nav->Reset();
if (!stack.empty())
{
auto& pv = mapper_.id_to_geant(stack[0]);
nav->SetFirstEntry(const_cast<G4PV*>(&pv));
++level;
}
else
{
nav->SetFirstEntry(nullptr);
}
}
else if (level < nav_stack_size())
{
// Decrease nav stack to the parent's level
nav->BackLevel(nav_stack_size() - level);
CELER_ASSERT(nav_stack_size() == level);
}
// Add all remaining levels: see G4Navigator::LocateGlobalPoint
// Note that the mapper's id_to_geant functionality updates the G4PV
// appropriately if a replica
for (auto end_level = stack.size(); level != end_level; ++level)
{
auto& pv = mapper_.id_to_geant(stack[level]);
nav->NewLevel(const_cast<G4PV*>(&pv), pv.VolumeType(), pv.GetCopyNo());
}
CELER_ENSURE(nav_stack_size() == stack.size()
|| (stack.empty() && nav->GetDepth() == 0));
}
//---------------------------------------------------------------------------//
} // namespace celeritas
| 412 | 0.871404 | 1 | 0.871404 | game-dev | MEDIA | 0.614575 | game-dev | 0.92894 | 1 | 0.92894 |
purefinance/mmb | 7,127 | core/src/infrastructure.rs | use anyhow::Result;
use futures::Future;
use mmb_utils::cancellation_token::CancellationToken;
use mmb_utils::infrastructure::FutureOutcome;
use mmb_utils::infrastructure::SpawnFutureFlags;
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
use std::panic;
use std::sync::Arc;
use std::time::Duration;
use crate::lifecycle::app_lifetime_manager::AppLifetimeManager;
static LIFETIME_MANAGER: OnceCell<Mutex<Option<Arc<AppLifetimeManager>>>> = OnceCell::new();
pub fn init_lifetime_manager() -> Arc<AppLifetimeManager> {
let manger = AppLifetimeManager::new(CancellationToken::new());
keep_lifetime_manager(manger.clone());
manger
}
pub(crate) fn keep_lifetime_manager(lifetime_manager: Arc<AppLifetimeManager>) {
let mut lifetime_manager_guard = LIFETIME_MANAGER
.get_or_init(|| Mutex::new(Some(lifetime_manager.clone())))
.lock();
*lifetime_manager_guard = Some(
lifetime_manager_guard
.as_ref()
.unwrap_or(&lifetime_manager)
.clone(),
);
}
pub(crate) fn unset_lifetime_manager() {
match LIFETIME_MANAGER.get() {
Some(lifetime_manager) => lifetime_manager.lock().take(),
None => panic!(
"Attempt to unset static application manager for spawn_future() before it has been set"
),
};
}
fn get_futures_cancellation_token() -> CancellationToken {
LIFETIME_MANAGER
.get()
.expect("Unable to get_futures_cancellation_token if AppLifetimeManager isn't set")
.lock()
.as_ref()
.expect("AppLifetimeManager is none")
.futures_cancellation_token
.clone()
}
/// Spawn future with timer. Error will be logged if times up before action completed
/// Other nuances are the same as spawn_future()
pub fn spawn_future_timed(
action_name: &str,
flags: SpawnFutureFlags,
duration: Duration,
action: impl Future<Output = Result<()>> + Send + 'static,
) -> tokio::task::JoinHandle<FutureOutcome> {
mmb_utils::infrastructure::spawn_future_timed(
action_name,
flags,
duration,
action,
spawn_graceful_shutdown,
get_futures_cancellation_token(),
)
}
/// Spawn future with timer. Other nuances are the same as spawn_future()
pub fn spawn_future_timed_ok(
action_name: &str,
flags: SpawnFutureFlags,
duration: Duration,
action: impl Future<Output = ()> + Send + 'static,
) -> tokio::task::JoinHandle<FutureOutcome> {
mmb_utils::infrastructure::spawn_future_timed(
action_name,
flags,
duration,
async move {
action.await;
Ok(())
},
spawn_graceful_shutdown,
get_futures_cancellation_token(),
)
}
pub fn spawn_future_ok(
action_name: &str,
flags: SpawnFutureFlags,
action: impl Future<Output = ()> + Send + 'static,
) -> tokio::task::JoinHandle<FutureOutcome> {
spawn_future(action_name, flags, async move {
action.await;
Ok(())
})
}
/// Spawn future with logging and error, panic and cancellation handling
/// Inside the crate prefer this function to all others
pub fn spawn_future(
action_name: &str,
flags: SpawnFutureFlags,
action: impl Future<Output = Result<()>> + Send + 'static,
) -> tokio::task::JoinHandle<FutureOutcome> {
mmb_utils::infrastructure::spawn_future(
action_name,
flags,
action,
spawn_graceful_shutdown,
get_futures_cancellation_token(),
)
}
/// Spawn standalone future with logging and error, panic and cancellation handling.
///
/// This fn is needed to call long-working synchronous code inside of a future,
/// and this fn calls this code in a separate thread,
/// to not affect other futures in a standard tokio threadpool.
pub fn spawn_future_standalone(
action_name: &str,
flags: SpawnFutureFlags,
action: impl Future<Output = Result<()>> + Send + 'static,
) -> std::thread::JoinHandle<FutureOutcome> {
mmb_utils::infrastructure::spawn_future_standalone(
action_name,
flags,
action,
spawn_graceful_shutdown,
get_futures_cancellation_token(),
)
}
fn spawn_graceful_shutdown(log_template: String, error_message: &str) {
match LIFETIME_MANAGER.get() {
Some(lifetime_manager) => {
match &*lifetime_manager.lock() {
Some(lifetime_manager) => {
lifetime_manager.spawn_graceful_shutdown(error_message);
}
None => log::error!("Unable to start graceful shutdown after panic inside {} because there are no application manager",
log_template),
}
}
None => log::error!("Unable to start graceful shutdown after panic inside {} because there are no application manager",
log_template),
}
}
/// This function spawn a future after waiting for some `delay`
/// and will repeat the `callback` endlessly with some `period`
pub fn spawn_by_timer<F, Fut>(
name: &str,
delay: Duration,
period: Duration,
flags: SpawnFutureFlags,
action: F,
) -> tokio::task::JoinHandle<FutureOutcome>
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
mmb_utils::infrastructure::spawn_by_timer(
name,
delay,
period,
flags,
get_futures_cancellation_token(),
spawn_graceful_shutdown,
action,
)
}
#[cfg(test)]
mod test {
use mmb_utils::{cancellation_token::CancellationToken, OPERATION_CANCELED_MSG};
use super::*;
use anyhow::Result;
use mmb_utils::infrastructure::init_infrastructure;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn panic_with_deny_cancellation() -> Result<()> {
init_infrastructure();
// Arrange
let manager = AppLifetimeManager::new(CancellationToken::new());
keep_lifetime_manager(manager);
// Act
let future_outcome = spawn_future(
"test_action_name",
SpawnFutureFlags::DENY_CANCELLATION | SpawnFutureFlags::STOP_BY_TOKEN,
async { panic!("{}", OPERATION_CANCELED_MSG) },
)
.await?
.into_result()
.expect_err("in test")
.to_string();
// Assert
assert!(future_outcome.contains("panicked"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn panic_without_deny_cancellation() -> Result<()> {
init_infrastructure();
// Arrange
let application_manager = AppLifetimeManager::new(CancellationToken::new());
keep_lifetime_manager(application_manager);
// Act
let future_outcome =
spawn_future("test_action_name", SpawnFutureFlags::STOP_BY_TOKEN, async {
panic!("{}", OPERATION_CANCELED_MSG)
})
.await?
.into_result()
.expect_err("in test")
.to_string();
// Assert
assert!(future_outcome.contains("canceled"));
Ok(())
}
}
| 412 | 0.970669 | 1 | 0.970669 | game-dev | MEDIA | 0.662497 | game-dev | 0.991793 | 1 | 0.991793 |
Moppu/SecretOfManaRandomizer | 14,277 | SoMRandomizer/config/settings/CommonSettings.cs | using SoMRandomizer.processing.common;
namespace SoMRandomizer.config.settings
{
/// <summary>
/// Enumeration of settings and defaults common to all modes.
/// </summary>
///
/// <remarks>Author: Moppleton</remarks>
public class CommonSettings : StringValueSettings
{
public const string PROPERTYNAME_ALL_ENTERED_OPTIONS = "allOptions";
public const string PROPERTYNAME_VERSION = "version";
public const string PROPERTYNAME_BUILD_DATE = "buildDate";
public const string PROPERTYNAME_DEBUG_LOG = "debugLoggingEnabled";
public const string PROPERTYNAME_MODE = "mode";
public const string PROPERTYNAME_CURRENT_PROGRESS = "currentGenerateProgress";
public const string PROPERTYNAME_TEST_ONLY = "testOnly";
public const string PROPERTYNAME_OVERCHARGE_FIX = "ovrchrgFix";
public const string PROPERTYNAME_SCROLL_FIX = "leavePlayersBehind";
public const string PROPERTYNAME_RANDOMIZE_CHAR_COLORS = "characterColors";
public const string PROPERTYNAME_FOOTSTEP_SOUND = "seReduction";
public const string PROPERTYNAME_AGGRESSIVE_BOSSES = "aggBosses";
public const string PROPERTYNAME_SPEEDUP_CHANGE = "funSpeedup";
public const string PROPERTYNAME_RABITE_COLOR_RANDOMIZER = "rainbowRabites";
public const string PROPERTYNAME_STATUS_LENGTHS = "longStatus";
public const string PROPERTYNAME_FASTER_CHESTS = "fasterChests";
public const string PROPERTYNAME_MAGIC_REBALANCE = "magicRebalance";
public const string PROPERTYNAME_LEVELUPS_RESTORE_MP = "mpAtLevel";
public const string PROPERTYNAME_FASTER_MAGIC_LEVELS = "fasterMagicLevel";
public const string PROPERTYNAME_FASTER_WEAPON_LEVELS = "fasterWeaponLevel";
public const string PROPERTYNAME_FASTER_TOP_SCREEN_DIALOGUE = "fasterMessages";
public const string PROPERTYNAME_MAX_7_ITEMS = "moreItems";
public const string PROPERTYNAME_STARTER_GEAR = "starterGear";
public const string PROPERTYNAME_HITTABLE_VAMPIRE = "noBsVampires";
public const string PROPERTYNAME_ORB_REWARD_FIX = "orbFix";
public const string PROPERTYNAME_BOSS_DEATH_FIX = "bossDeathFix";
public const string PROPERTYNAME_ENEMY_SPECIES_DAMAGE = "speciesDamage";
public const string PROPERTYNAME_WEAPON_ELEMENTAL_DAMAGE = "elemDamage";
public const string PROPERTYNAME_FAST_TRANSITIONS = "fastTransition";
public const string PROPERTYNAME_DAMAGE_PERCENT_FIX = "accuratePercent";
public const string PROPERTYNAME_NO_ENERGY_TO_RUN = "noStaminaRun";
public const string PROPERTYNAME_STATUSGLOW = "statusGlow";
public const string PROPERTYNAME_MODE7_EDGES_FIX = "mode7Fix";
public const string PROPERTYNAME_GIGAS_FIX = "noGigasSplit";
public const string PROPERTYNAME_WHIP_COORDINATE_CORRUPTION_FIX = "whipFix";
public const string PROPERTYNAME_EXTENDED_TARGETTING = "offscreenTarget";
public const string PROPERTYNAME_BUY_MULTIPLE_CONSUMABLES = "buyMultiple";
public const string PROPERTYNAME_MANAMAGIC_FIX = "manaMagicFix";
public const string PROPERTYNAME_OHKO = "ohko";
public const string PROPERTYNAME_SUMMONING_FIX = "noSummonDespawn";
public const string PROPERTYNAME_WALK_THROUGH_WALLS = "noclip";
public const string PROPERTYNAME_CONFUSION_FIX = "confusionFix";
public const string PROPERTYNAME_BEAK_DISABLE = "hittableBeaks";
public const string PROPERTYNAME_MECHRIDER_DEATH_FIX = "mechRiderDeathFix";
public const string PROPERTYNAME_ENEMY_POSITION_FIX = "adjustEnemyPos";
public const string PROPERTYNAME_NO_WEAPON_STAMINA_COST = "attacksForever";
public const string PROPERTYNAME_PERMANENT_POISON = "deathByPoison";
public const string PROPERTYNAME_PERCENTAGE_POISON = "percentPoison";
public const string PROPERTYNAME_AGGRESSIVE_ENEMIES = "aggEnemies";
public const string PROPERTYNAME_OBSCURE_DAMAGE = "obscureDamage";
public const string PROPERTYNAME_OBSCURE_OWN_HP = "obscureHp";
public const string PROPERTYNAME_OBSCURE_GOLD = "obscureGold";
public const string PROPERTYNAME_DEFENSE_REFACTOR = "defRefactor";
public const string PROPERTYNAME_MUTE_MUSIC = "muteMusic";
public const string PROPERTYNAME_SHOW_EVADES_AS_ZERO = "showEvades";
public const string PROPERTYNAME_BOSSES_AT_Z_0 = "bossFixedZ";
public const string PROPERTYNAME_BOSS_ELEMENT_RANDO = "bossElementRando";
public const string PROPERTYNAME_NAME_ENTRY_CHANGES = "nameEntryFix";
public const string PROPERTYNAME_ENEMY_INFINITE_MP = "enemyInfiniteMp";
public const string PROPERTYNAME_INCLUDE_TRASH_WEAPONS = "trashWeapons";
public const string PROPERTYNAME_DAMAGE_CANCEL_ALLOW_TYPE = "dmgCancelAllow";
public const string PROPERTYNAME_MINIMAP = "showMinimap";
public const string PROPERTYNAME_CUP_AT_ZERO_HP = "cupAtZeroHp";
public const string PROPERTYNAME_CANDY_HEALOUTS = "candyHealouts";
public const string PROPERTYNAME_MAGIC_ROPE_DEATH_FIX = "magicRopeDeathFix";
public const string PROPERTYNAME_SPOILER_LOG = "spoilerLog";
public const string PROPERTYNAME_RACE_MODE = "raceMode";
// used by MainForm and CharacterPaletteRandomizer to coordinate custom colors for characters
public const string PROPERTYNAME_PREFIX_CUSTOM_CHARACTER_COLORS = "CustomCharColor";
public CommonSettings()
{
// default common settings
// boolean settings
setInitial(PROPERTYNAME_DEBUG_LOG, false); // no debug logging by default
setInitial(PROPERTYNAME_OVERCHARGE_FIX, true); // don't allow overcharge glitch to be used
setInitial(PROPERTYNAME_SCROLL_FIX, true); // allow p2/p3 to be scrolled off screen and teleport back
setInitial(PROPERTYNAME_FOOTSTEP_SOUND, true); // mute a few less useful sound effects so you can hear the music better
setInitial(PROPERTYNAME_AGGRESSIVE_BOSSES, false); // boss AI runs way faster
setInitial(PROPERTYNAME_SPEEDUP_CHANGE, true); // gnome speedup spell is just straight-up haste instead of, well, nothing
setInitial(PROPERTYNAME_RABITE_COLOR_RANDOMIZER, true); // rabites get assigned a random r/g/b every spawn
setInitial(PROPERTYNAME_STATUS_LENGTHS, true); // status conditions last longer than in vanilla
setInitial(PROPERTYNAME_FASTER_CHESTS, true); // no shake animation for chests
setInitial(PROPERTYNAME_MAGIC_REBALANCE, true); // change a few mp costs and stuff
setInitial(PROPERTYNAME_LEVELUPS_RESTORE_MP, true); // vanilla only restores hp; this gives mp too
setInitial(PROPERTYNAME_FASTER_MAGIC_LEVELS, true); // spells level 4x faster than vanilla
setInitial(PROPERTYNAME_FASTER_WEAPON_LEVELS, true); // weapons level 4x faster than vanilla
setInitial(PROPERTYNAME_FASTER_TOP_SCREEN_DIALOGUE, true); // faster movement of status messages
setInitial(PROPERTYNAME_MAX_7_ITEMS, true); // max of a consumable 4 -> 7
setInitial(PROPERTYNAME_STARTER_GEAR, false); // start with gear in each slot
setInitial(PROPERTYNAME_HITTABLE_VAMPIRE, true); // vampire bosses are hittable with physicals when cloaked
setInitial(PROPERTYNAME_ORB_REWARD_FIX, true); // fix for a softlock related to gaining weapon orbs
setInitial(PROPERTYNAME_BOSS_DEATH_FIX, true); // fix for a softlock related to boss deaths
setInitial(PROPERTYNAME_ENEMY_SPECIES_DAMAGE, true); // species type on weapon grants bonus damage to matching enemies
setInitial(PROPERTYNAME_WEAPON_ELEMENTAL_DAMAGE, true); // elemental sabers and randomized elemental weapons deal more or less damage to enemies based on their def ele
setInitial(PROPERTYNAME_FAST_TRANSITIONS, false); // remove fades on transitions in favor of speed; sometimes gives some undesirable graphical artifacts
setInitial(PROPERTYNAME_DAMAGE_PERCENT_FIX, false); // make weapon stamina percents accurate; vanilla deals half if you aren't 100%
setInitial(PROPERTYNAME_NO_ENERGY_TO_RUN, false); // don't consume stamina when running
setInitial(PROPERTYNAME_STATUSGLOW, true); // glow character palettes to indicate certain statuses
setInitial(PROPERTYNAME_MODE7_EDGES_FIX, true); // fix a minor graphical artifact with flammie flight
setInitial(PROPERTYNAME_GIGAS_FIX, true); // gigases don't split up into sparkles to waste time, but also results in more aggresive behavior due to this
setInitial(PROPERTYNAME_WHIP_COORDINATE_CORRUPTION_FIX, true); // fix an issue that made whip posts sometimes have unpredictable behavior
setInitial(PROPERTYNAME_EXTENDED_TARGETTING, true); // allow offscreen enemies/allies (including element orbs, and mana beast) to be targetted for spells
setInitial(PROPERTYNAME_BUY_MULTIPLE_CONSUMABLES, true); // modify shops to allow you to buy multiple consumables at once
setInitial(PROPERTYNAME_MANAMAGIC_FIX, true); // mana magic gives a fixed charge level bonus of 6 instead of weird vanilla calculation
setInitial(PROPERTYNAME_OHKO, false); // you die in one hit
setInitial(PROPERTYNAME_SUMMONING_FIX, true); // don't allow certain npcs to despawn due to summoning enemies
setInitial(PROPERTYNAME_WALK_THROUGH_WALLS, false); // walk through walls
setInitial(PROPERTYNAME_CONFUSION_FIX, true); // fix issue where confusion inverted flammie controls and saving with confusion could result in permanent reversed controls
setInitial(PROPERTYNAME_BEAK_DISABLE, false); // disable beak shield on bird bosses
setInitial(PROPERTYNAME_MECHRIDER_DEATH_FIX, true); // mech rider doesn't speed away on death and sometimes take a layer of the map with him
setInitial(PROPERTYNAME_ENEMY_POSITION_FIX, true); // move a few enemies to be away from doorways to prevent frustration and autosave softlocks
setInitial(PROPERTYNAME_NO_WEAPON_STAMINA_COST, false); // weapon attacks do not cost stamina and are always 100% damage hits
setInitial(PROPERTYNAME_PERMANENT_POISON, false); // your characters are poisoned forever
setInitial(PROPERTYNAME_PERCENTAGE_POISON, false); // all poison deals a percent of max hp instead of 1/tick
setInitial(PROPERTYNAME_AGGRESSIVE_ENEMIES, false); // enemies are faster and more aggressive
setInitial(PROPERTYNAME_OBSCURE_DAMAGE, false); // show all damage numbers as zero
setInitial(PROPERTYNAME_OBSCURE_OWN_HP, false); // hide your own health
setInitial(PROPERTYNAME_OBSCURE_GOLD, false); // hide your gold amount
setInitial(PROPERTYNAME_DEFENSE_REFACTOR, false); // experimental refactor to damage formula
setInitial(PROPERTYNAME_MUTE_MUSIC, false); // mute all music but still load it for equivalent loadtimes
setInitial(PROPERTYNAME_SHOW_EVADES_AS_ZERO, true); // show zero for some evaded attacks where vanilla showed nothing
setInitial(PROPERTYNAME_BOSSES_AT_Z_0, false); // old method of making bosses work on all maps; only really provided for debugging
setInitial(PROPERTYNAME_BOSS_ELEMENT_RANDO, false); // bosses get random defense element/palette/spells; doesn't work on all bosses yet
setInitial(PROPERTYNAME_NAME_ENTRY_CHANGES, true); // allow 12 character name entries and fix the weird control delay when entering it
setInitial(PROPERTYNAME_ENEMY_INFINITE_MP, false); // enemies have infinite mp
setInitial(PROPERTYNAME_INCLUDE_TRASH_WEAPONS, true); // weapon rando rarely gives useless weapons
setInitial(PROPERTYNAME_MINIMAP, true); // show minimap on sprite layer when flying on flammie
setInitial(PROPERTYNAME_CUP_AT_ZERO_HP, true); // don't have to be fully dead to use cup wishes; just have 0 hp
setInitial(PROPERTYNAME_CANDY_HEALOUTS, true); // healing consumables can be used on still-alive 0 hp character
setInitial(PROPERTYNAME_MAGIC_ROPE_DEATH_FIX, true); // fix invulnerability when using magic rope
setInitial(PROPERTYNAME_SPOILER_LOG, true); // generate spoiler log
setInitial(PROPERTYNAME_RACE_MODE, false); // race mode
setInitial(PROPERTYNAME_TEST_ONLY, false); // for automated tests; changes how we log
// enumerations
setInitial(PROPERTYNAME_VERSION, new string[] { }, new string[] { }, RomGenerator.VERSION_NUMBER );
setInitial(PROPERTYNAME_BUILD_DATE, new string[] { }, new string[] { }, "unknown");
// selected game mode
setInitial(PROPERTYNAME_MODE, new string[] {
// keys
VanillaRandoSettings.MODE_KEY,
OpenWorldSettings.MODE_KEY,
AncientCaveSettings.MODE_KEY,
BossRushSettings.MODE_KEY,
ChaosSettings.MODE_KEY },
// display strings
new string[] {
VanillaRandoSettings.MODE_NAME,
OpenWorldSettings.MODE_NAME,
AncientCaveSettings.MODE_NAME,
BossRushSettings.MODE_NAME,
ChaosSettings.MODE_NAME },
// default
OpenWorldSettings.MODE_KEY);
// for custom, the UI pushes a set of custom keys in for each color that are read by the palette rando hack, prefixed by PROPERTYNAME_PREFIX_CUSTOM_CHARACTER_COLORS
setInitial(PROPERTYNAME_RANDOMIZE_CHAR_COLORS, new string[] { "none", "rando", "custom" }, new string[] { "No change", "Randomize", "Specify..." }, "rando");
setInitial(PROPERTYNAME_DAMAGE_CANCEL_ALLOW_TYPE, new string[] { "all", "consumables", "none" }, new string[] { "All", "Consumables", "None" }, "all");
// progress of longer running generation modes like ancient cave
setInitial(PROPERTYNAME_CURRENT_PROGRESS, 0);
}
}
}
| 412 | 0.803118 | 1 | 0.803118 | game-dev | MEDIA | 0.955543 | game-dev | 0.616066 | 1 | 0.616066 |
RCInet/LastEpoch_Mods | 5,013 | AssetBundleExport/Library/PackageCache/com.unity.visualscripting@1b53f46e931b/Runtime/VisualScripting.Core/Cloning/Cloning.cs | using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using UnityObject = UnityEngine.Object;
namespace Unity.VisualScripting
{
public static class Cloning
{
static Cloning()
{
cloners.Add(arrayCloner);
cloners.Add(dictionaryCloner);
cloners.Add(enumerableCloner);
cloners.Add(listCloner);
cloners.Add(animationCurveCloner);
cloners.Add(gradientCloner);
}
// Cloning has to be really fast, and skippable takes a while.
private static readonly Dictionary<Type, bool> skippable = new Dictionary<Type, bool>();
public static HashSet<ICloner> cloners { get; } = new HashSet<ICloner>();
public static ArrayCloner arrayCloner { get; } = new ArrayCloner();
public static DictionaryCloner dictionaryCloner { get; } = new DictionaryCloner();
public static EnumerableCloner enumerableCloner { get; } = new EnumerableCloner();
public static ListCloner listCloner { get; } = new ListCloner();
public static AnimationCurveCloner animationCurveCloner { get; } = new AnimationCurveCloner();
internal static GradientCloner gradientCloner { get; } = new GradientCloner();
public static FieldsCloner fieldsCloner { get; } = new FieldsCloner();
public static FakeSerializationCloner fakeSerializationCloner { get; } = new FakeSerializationCloner();
public static object Clone(this object original, ICloner fallbackCloner, bool tryPreserveInstances)
{
using (var context = CloningContext.New(fallbackCloner, tryPreserveInstances))
{
return Clone(context, original);
}
}
public static T Clone<T>(this T original, ICloner fallbackCloner, bool tryPreserveInstances)
{
return (T)Clone((object)original, fallbackCloner, tryPreserveInstances);
}
public static object CloneViaFakeSerialization(this object original)
{
return original.Clone(fakeSerializationCloner, true);
}
public static T CloneViaFakeSerialization<T>(this T original)
{
return (T)CloneViaFakeSerialization((object)original);
}
internal static object Clone(CloningContext context, object original)
{
object clone = null;
CloneInto(context, ref clone, original);
return clone;
}
internal static void CloneInto(CloningContext context, ref object clone, object original)
{
if (original == null)
{
clone = null;
return;
}
var type = original.GetType();
if (Skippable(type))
{
clone = original;
return;
}
if (context.clonings.ContainsKey(original))
{
clone = context.clonings[original];
return;
}
var cloner = GetCloner(original, type, context.fallbackCloner);
if (clone == null)
{
clone = cloner.ConstructClone(type, original);
}
context.clonings.Add(original, clone);
cloner.BeforeClone(type, original);
cloner.FillClone(type, ref clone, original, context);
cloner.AfterClone(type, clone);
context.clonings[original] = clone; // In case the reference changed, for example in arrays
}
[CanBeNull]
public static ICloner GetCloner(object original, Type type)
{
if (original is ISpecifiesCloner cloneableVia)
{
return cloneableVia.cloner;
}
return cloners.FirstOrDefault(cloner => cloner.Handles(type));
}
private static ICloner GetCloner(object original, Type type, ICloner fallbackCloner)
{
var cloner = GetCloner(original, type);
if (cloner != null)
return cloner;
Ensure.That(nameof(fallbackCloner)).IsNotNull(fallbackCloner);
return fallbackCloner;
}
private static bool Skippable(Type type)
{
bool result;
if (!skippable.TryGetValue(type, out result))
{
result = type.IsValueType || // Value types are copied on assignment, so no cloning is necessary
type == typeof(string) || // Strings have copy on write semantics as well, but aren't value types
typeof(Type).IsAssignableFrom(type) || // Types are guaranteed to be singletons. Using inheritance because MonoType/RuntimeType extend Type
typeof(UnityObject).IsAssignableFrom(type); // Unity objects act as pure references
skippable.Add(type, result);
}
return result;
}
}
}
| 412 | 0.626025 | 1 | 0.626025 | game-dev | MEDIA | 0.393844 | game-dev | 0.595946 | 1 | 0.595946 |
LC1332/Learn-Python-with-GPT | 4,354 | lesson6_Snake/baby_snake.py | import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (50, 153, 213)
# 设置屏幕大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
GRID_SIZE = 20 # 每个方格为20*20像素
GRID_WIDTH = SCREEN_WIDTH // GRID_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // GRID_SIZE
# 创建屏幕对象
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 设置字体
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)
# 定义蛇类
class Snake:
def __init__(self):
self.positions = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
self.direction = (0, -1)
self.grow = False
self.length = 1
def move(self):
head_x, head_y = self.positions[0]
new_x = head_x + self.direction[0]
new_y = head_y + self.direction[1]
# 如果蛇碰到边界则从另一边穿出
new_x %= GRID_WIDTH
new_y %= GRID_HEIGHT
new_position = (new_x, new_y)
# 插入新的头部位置
self.positions.insert(0, new_position)
if not self.grow and len(self.positions) > 30:
self.positions.pop()
self.grow = False
def change_direction(self, direction):
opposite_direction = (-self.direction[0], -self.direction[1])
if direction != opposite_direction:
self.direction = direction
def grow_snake(self):
self.grow = True
self.length += 1
def draw(self, screen):
rendered_pos = set()
for pos in self.positions:
if pos not in rendered_pos:
pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0] * GRID_SIZE, pos[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
rendered_pos.add(pos)
else:
# render into blue
pygame.draw.rect(screen, BLUE, pygame.Rect(pos[0] * GRID_SIZE, pos[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
# pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0] * GRID_SIZE, pos[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
# 定义食物类
class Food:
def __init__(self):
self.position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
def spawn(self):
self.position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
def draw(self, screen):
pygame.draw.rect(screen, RED, pygame.Rect(self.position[0] * GRID_SIZE, self.position[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
# 显示分数的函数
def display_score(score):
value = score_font.render("Score: " + str(score), True, WHITE)
screen.blit(value, [0, 0])
# 主游戏循环
def game_loop():
clock = pygame.time.Clock()
snake = Snake()
food = Food()
snake_speed = 10 # 控制蛇的移动速度
game_over = False
game_close = False
while not game_over:
while game_close:
screen.fill(BLUE)
mesg = font_style.render("You Lost! Press Q-Quit or C-Play Again", True, RED)
screen.blit(mesg, [SCREEN_WIDTH / 6, SCREEN_HEIGHT / 3])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.change_direction((0, -1))
elif event.key == pygame.K_DOWN:
snake.change_direction((0, 1))
elif event.key == pygame.K_LEFT:
snake.change_direction((-1, 0))
elif event.key == pygame.K_RIGHT:
snake.change_direction((1, 0))
# 移动蛇
snake.move()
# 检查是否吃到食物
if snake.positions[0] == food.position:
snake.grow_snake()
food.spawn()
# 绘制
screen.fill(BLACK)
snake.draw(screen)
food.draw(screen)
display_score(snake.length - 1)
pygame.display.update()
# 控制帧率
clock.tick(snake_speed)
pygame.quit()
if __name__ == "__main__":
game_loop()
| 412 | 0.627005 | 1 | 0.627005 | game-dev | MEDIA | 0.471422 | game-dev | 0.750729 | 1 | 0.750729 |
osm2pgsql-dev/osm2pgsql | 2,295 | src/flex-lua-wrapper.hpp | #ifndef OSM2PGSQL_FLEX_LUA_WRAPPER_HPP
#define OSM2PGSQL_FLEX_LUA_WRAPPER_HPP
/**
* SPDX-License-Identifier: GPL-2.0-or-later
*
* This file is part of osm2pgsql (https://osm2pgsql.org/).
*
* Copyright (C) 2006-2025 by the osm2pgsql developer community.
* For a full list of authors see the git log.
*/
#include "output-flex.hpp"
#include <cassert>
#include <exception>
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define TRAMPOLINE_WRAPPED_OBJECT(obj_name, func_name) \
int lua_trampoline_##obj_name##_##func_name(lua_State *lua_state) \
{ \
try { \
auto *flex = \
static_cast<output_flex_t *>(luaX_get_context(lua_state)); \
auto &obj = flex->get_##obj_name##_from_param(); \
return lua_wrapper_##obj_name##_t{lua_state, &obj}.func_name(); \
} catch (std::exception const &e) { \
return luaL_error(lua_state, "Error in '" #func_name "': %s\n", \
e.what()); \
} catch (...) { \
return luaL_error(lua_state, \
"Unknown error in '" #func_name "'.\n"); \
} \
}
struct lua_State;
/**
* Helper class for wrapping C++ classes in Lua "classes".
*/
template <typename WRAPPED>
class lua_wrapper_base_t
{
public:
lua_wrapper_base_t(lua_State *lua_state, WRAPPED *wrapped)
: m_lua_state(lua_state), m_self(wrapped)
{
assert(lua_state);
assert(wrapped);
}
protected:
lua_State *lua_state() const noexcept { return m_lua_state; }
WRAPPED const &self() const noexcept { return *m_self; }
WRAPPED &self() noexcept { return *m_self; }
private:
lua_State *m_lua_state;
WRAPPED *m_self;
}; // class lua_wrapper_base_t
#endif // OSM2PGSQL_FLEX_LUA_WRAPPER_HPP
| 412 | 0.848197 | 1 | 0.848197 | game-dev | MEDIA | 0.297543 | game-dev | 0.503031 | 1 | 0.503031 |
latte-soft/builtinplugins | 6,673 | src/BuiltInPlugins/EventEmulator/PluginLoader/PluginLoader.luau | local l_StudioService_0 = game:GetService("StudioService");
local v1 = {};
v1.__index = v1;
v1.new = function()
local v2 = {
_signal = Instance.new("BindableEvent"),
_handlers = {},
_eventsToFlush = {},
_connections = {}
};
setmetatable(v2, v1);
return v2;
end;
v1.Fire = function(v3, ...)
if #v3._handlers > 0 then
v3._signal:Fire(...);
return ;
else
table.insert(v3._eventsToFlush, {
...
});
return ;
end;
end;
v1.Connect = function(v4, v5)
if #v4._handlers == 0 then
for _, v7 in ipairs(v4._eventsToFlush) do
task.spawn(function()
v5(unpack(v7));
end);
end;
v4._eventsToFlush = {};
end;
local v8 = v4._signal.Event:Connect(v5);
table.insert(v4._handlers, v5);
table.insert(v4._connections, v8);
return v8;
end;
v1.Destroy = function(v9)
v9._handlers = {};
v9._eventsToFlush = {};
for _, v11 in ipairs(v9._connections) do
v11:Disconnect();
end;
v9._signal:Destroy();
end;
local v12 = {};
v12.__index = v12;
local function _(v13)
if v13 ~= nil then
return v13;
else
return l_StudioService_0.StudioLocaleId;
end;
end;
v12.new = function(v15)
local v16 = {
_connectedSignals = {},
_buttonConnections = {},
_widgetConnections = {},
_userHasInteracted = false,
_destroyed = false,
_userInteractionSignal = Instance.new("BindableEvent"),
_locale = nil,
_mainTranslator = nil,
_fallbackTranslator = nil,
_initArgs = v15
};
setmetatable(v16, v12);
if v16._initArgs.localizationNamespace == nil then
v16._initArgs.localizationNamespace = "Studio";
end;
local l_overrideLocaleId_0 = v15.overrideLocaleId;
v16._locale = if l_overrideLocaleId_0 ~= nil then l_overrideLocaleId_0 else l_StudioService_0.StudioLocaleId;
v16._mainTranslator = v15.translationResourceTable:GetTranslator(v16._locale);
v16._fallbackTranslator = v15.fallbackResourceTable:GetTranslator("en-us");
if not (not v15.shouldImmediatelyOpen or not v15.shouldImmediatelyOpen()) then
v16:_onUserInteracted();
end;
return v16;
end;
v12.Destroy = function(v18)
for _, v20 in pairs(v18._connectedSignals) do
v20[1]:Disconnect();
end;
for _, v22 in pairs(v18._buttonConnections) do
v22[1]:Disconnect();
end;
for _, v24 in pairs(v18._widgetConnections) do
v24[1]:Disconnect();
end;
v18._destroyed = true;
v18:_onUserInteracted();
v18._userInteractionSignal:Destroy();
v18._userInteractionSignal = nil;
end;
v12.getKeyNamespace = function(v25)
return v25._initArgs.localizationNamespace;
end;
v12.getPluginName = function(v26)
return v26._initArgs.pluginName;
end;
v12.getLocalizedText = function(v27, v28, v29, v30, v31)
local v32 = string.format("%s.%s.%s.%s", v28, v29, v30, v31);
local function _(v33)
if v33 then
local l_status_0, l_result_0 = pcall(function()
return v33:FormatByKey(v32);
end);
return l_status_0, l_result_0;
else
return false, nil;
end;
end;
local v37 = nil;
local v38 = nil;
if v27.locale == "en-us" then
local l__fallbackTranslator_0 = v27._fallbackTranslator;
local v40, v41;
if l__fallbackTranslator_0 then
local l_status_1, l_result_1 = pcall(function()
return l__fallbackTranslator_0:FormatByKey(v32);
end);
v40 = l_status_1;
v41 = l_result_1;
else
v40 = false;
v41 = nil;
end;
v37 = v40;
v38 = v41;
if v37 then
return v38;
end;
else
local l__mainTranslator_0 = v27._mainTranslator;
local v45, v46;
if l__mainTranslator_0 then
local l_l__mainTranslator_0_0 = l__mainTranslator_0 --[[ copy: 11 -> 14 ]];
local l_status_2, l_result_2 = pcall(function()
return l_l__mainTranslator_0_0:FormatByKey(v32);
end);
v45 = l_status_2;
v46 = l_result_2;
else
v45 = false;
v46 = nil;
end;
v37 = v45;
v38 = v46;
if not v37 then
l__mainTranslator_0 = v27._fallbackTranslator;
if l__mainTranslator_0 then
local l_status_3, l_result_3 = pcall(function()
return l__mainTranslator_0:FormatByKey(v32);
end);
v45 = l_status_3;
v46 = l_result_3;
else
v45 = false;
v46 = nil;
end;
v37 = v45;
v38 = v46;
if v37 then
return v38;
end;
else
return v38;
end;
end;
if not game:GetEngineFeature("RefactorTranslatorInstance") then
if not (not v37 or string.find(v38, "LocalizationTable or parent tables do not contain a translation")) then
warn(v38, debug.traceback());
end;
elseif not (not v37 or string.find(v38, "Key .* not found for locale")) then
warn(v38, debug.traceback());
return v32;
end;
return v32;
end;
v12._onUserInteracted = function(v52)
v52._userHasInteracted = true;
v52._userInteractionSignal:Fire();
end;
v12.registerButton = function(v53, v54)
local v55 = v1.new();
v53._buttonConnections[v54] = {
v54.Click:Connect(function()
v53:_onUserInteracted();
v55:Fire();
end),
v55
};
return v55;
end;
v12.registerWidget = function(v56, v57)
local v58 = v1.new();
v56._widgetConnections[v57] = {
v57:GetPropertyChangedSignal("Enabled"):Connect(function()
if v57.Enabled then
v56:_onUserInteracted();
end;
v58:Fire();
end),
v58
};
if v57.Enabled then
v56:_onUserInteracted();
end;
return v58;
end;
v12.registerSignal = function(v59, v60)
local v61 = v1.new();
v59._connectedSignals[v60] = {
v60:Connect(function(...)
v59:_onUserInteracted();
v61:Fire(...);
end),
v61
};
return v61;
end;
v12.waitForUserInteraction = function(v62)
if not v62._userHasInteracted then
v62._userInteractionConnection = v62._userInteractionSignal.Event:Wait();
end;
return not v62._destroyed;
end;
return v12;
| 412 | 0.917284 | 1 | 0.917284 | game-dev | MEDIA | 0.80145 | game-dev | 0.961688 | 1 | 0.961688 |
haggi/OpenMaya | 27,032 | src/mayaToThea/src/mtth_common/mtth_renderGlobals.cpp | #include "renderGlobals.h"
void RenderGlobals::setRendererUnit()
{
this->rendererUnit = MDistance::kMeters;
}
void RenderGlobals::setRendererAxis()
{
this->rendererAxis = ZUp;
}
//#include "maya/MSelectionList.h"
//#include "maya/MFnDependencyNode.h"
//
//#include "utilities/logging.h"
//#include "utilities/attrTools.h"
//
//static Logging logger;
//
//
//void mtth_RenderGlobals::setRendererUnit()
//{
// this->rendererUnit = MDistance::kMeters;
//}
//
//void mtth_RenderGlobals::setRendererAxis()
//{
// this->rendererAxis = ZUp;
//}
//mtth_RenderGlobals::mtth_RenderGlobals()
//{
// this->getMtTheaGlobals();
//
// this->setRendererAxis();
// this->setRendererUnit();
// this->defineGlobalConversionMatrix();
//}
//
//MString mtth_RenderGlobals::getImageExt()
//{
// return MString("ext");
//}
//
//bool mtth_RenderGlobals::getMtTheaGlobals()
//{
// Logging::debug("mtth_RenderGlobals::getTheaGlobals");
//
// MSelectionList TheaGlobalsList;
// TheaGlobalsList.add("theaGlobals");
//
// if( TheaGlobalsList.length() == 0 )
// {
// Logging::debug("TheaGlobals not found. Stopping.");
// return false;
// }
// MObject node;
// TheaGlobalsList.getDependNode(0, node);
// MFnDependencyNode TheaGlobals(node);
// renderGlobalsMobject = node;
//
// try{
//
// if(!getInt(MString("translatorVerbosity"), TheaGlobals, this->translatorVerbosity))
// throw("problem reading TheaGlobals.translatorVerbosity");
// switch(this->translatorVerbosity)
// {
// case 0:
// Logging::setLogLevel(Logging::Info);
// break;
// case 1:
// Logging::setLogLevel(Logging::Error);
// break;
// case 2:
// Logging::setLogLevel(Logging::Warning);
// break;
// case 3:
// Logging::setLogLevel(Logging::Progress);
// break;
// case 4:
// Logging::setLogLevel(Logging::Debug);
// break;
// }
//
//// ------------- automatically created attributes start ----------- //
// if(!getBool(MString("giChannel"), TheaGlobals, this->giChannel))
// throw("problem reading theaGlobals.giChannel");
//
// if(!getInt(MString("frameRate"), TheaGlobals, this->frameRate))
// throw("problem reading theaGlobals.frameRate");
//
// if(!getInt(MString("gatherRays"), TheaGlobals, this->gatherRays))
// throw("problem reading theaGlobals.gatherRays");
//
// if(!getBool(MString("normalChannel"), TheaGlobals, this->normalChannel))
// throw("problem reading theaGlobals.normalChannel");
//
// if(!getFloat(MString("clayReflectance"), TheaGlobals, this->clayReflectance))
// throw("problem reading theaGlobals.clayReflectance");
//
// if(!getString(MString("selectedFrames"), TheaGlobals, this->selectedFrames))
// throw("problem reading theaGlobals.selectedFrames");
//
// if(!getBool(MString("aoMultiply"), TheaGlobals, this->aoMultiply))
// throw("problem reading theaGlobals.aoMultiply");
//
// if(!getBool(MString("irradianceCacheForceInterpolation"), TheaGlobals, this->irradianceCacheForceInterpolation))
// throw("problem reading theaGlobals.irradianceCacheForceInterpolation");
//
// if(!getInt(MString("currentFrame"), TheaGlobals, this->currentFrame))
// throw("problem reading theaGlobals.currentFrame");
//
// if(!getFloat(MString("fieldMaxError"), TheaGlobals, this->fieldMaxError))
// throw("problem reading theaGlobals.fieldMaxError");
//
// if(!getFloat(MString("irradianceCacheSampleDensity"), TheaGlobals, this->irradianceCacheSampleDensity))
// throw("problem reading theaGlobals.irradianceCacheSampleDensity");
//
// if(!getFloat(MString("antialiasingMaxContrast"), TheaGlobals, this->antialiasingMaxContrast))
// throw("problem reading theaGlobals.antialiasingMaxContrast");
//
// if(!getFloat(MString("antialiasingClampLevel"), TheaGlobals, this->antialiasingClampLevel))
// throw("problem reading theaGlobals.antialiasingClampLevel");
//
// if(!getBool(MString("rayTraceDispersion"), TheaGlobals, this->rayTraceDispersion))
// throw("problem reading theaGlobals.rayTraceDispersion");
//
// if(!getInt(MString("progressiveRayTracingDepth"), TheaGlobals, this->progressiveRayTracingDepth))
// throw("problem reading theaGlobals.progressiveRayTracingDepth");
//
// if(!getBool(MString("rayTraceTransparencies"), TheaGlobals, this->rayTraceTransparencies))
// throw("problem reading theaGlobals.rayTraceTransparencies");
//
// if(!getInt(MString("irradianceCachePrepassSamples"), TheaGlobals, this->irradianceCachePrepassSamples))
// throw("problem reading theaGlobals.irradianceCachePrepassSamples");
//
// if(!getFloat(MString("irradianceCacheDensityBoost"), TheaGlobals, this->irradianceCacheDensityBoost))
// throw("problem reading theaGlobals.irradianceCacheDensityBoost");
//
// if(!getBool(MString("blurredEvaluateGI"), TheaGlobals, this->blurredEvaluateGI))
// throw("problem reading theaGlobals.blurredEvaluateGI");
//
// if(!getBool(MString("filmSaving"), TheaGlobals, this->filmSaving))
// throw("problem reading theaGlobals.filmSaving");
//
// if(!getInt(MString("walkthroughPrepassFrames"), TheaGlobals, this->walkthroughPrepassFrames))
// throw("problem reading theaGlobals.walkthroughPrepassFrames");
//
// if(!getBool(MString("repaint"), TheaGlobals, this->repaint))
// throw("problem reading theaGlobals.repaint");
//
// if(!getBool(MString("sssChannel"), TheaGlobals, this->sssChannel))
// throw("problem reading theaGlobals.sssChannel");
//
// if(!getBool(MString("gatherTraceReflections"), TheaGlobals, this->gatherTraceReflections))
// throw("problem reading theaGlobals.gatherTraceReflections");
//
// if(!getBool(MString("gatherTraceGlossyReflections"), TheaGlobals, this->gatherTraceGlossyReflections))
// throw("problem reading theaGlobals.gatherTraceGlossyReflections");
//
// if(!getBool(MString("depthChannel"), TheaGlobals, this->depthChannel))
// throw("problem reading theaGlobals.depthChannel");
//
// if(!getEnum(MString("renderFrames"), TheaGlobals, this->renderFrames))
// throw("problem reading theaGlobals.renderFrames");
//
// if(!getBool(MString("gatherTraceRefractions"), TheaGlobals, this->gatherTraceRefractions))
// throw("problem reading theaGlobals.gatherTraceRefractions");
//
// if(!getInt(MString("biasedGlossyTracingDepth"), TheaGlobals, this->biasedGlossyTracingDepth))
// throw("problem reading theaGlobals.biasedGlossyTracingDepth");
//
// if(!getString(MString("skyAnimationEnd"), TheaGlobals, this->skyAnimationEnd))
// throw("problem reading theaGlobals.skyAnimationEnd");
//
// if(!getBool(MString("blurredReflections"), TheaGlobals, this->blurredReflections))
// throw("problem reading theaGlobals.blurredReflections");
//
// if(!getBool(MString("transparentChannel"), TheaGlobals, this->transparentChannel))
// throw("problem reading theaGlobals.transparentChannel");
//
// if(!getBool(MString("alphaChannel"), TheaGlobals, this->alphaChannel))
// throw("problem reading theaGlobals.alphaChannel");
//
// if(!getColor(MString("aoLowColor"), TheaGlobals, this->aoLowColor))
// throw("problem reading theaGlobals.aoLowColor");
//
// if(!getBool(MString("displacement"), TheaGlobals, this->displacement))
// throw("problem reading theaGlobals.displacement");
//
// if(!getInt(MString("devices"), TheaGlobals, this->devices))
// throw("problem reading theaGlobals.devices");
//
// if(!getString(MString("animationOutputFilename"), TheaGlobals, this->animationOutputFilename))
// throw("problem reading theaGlobals.animationOutputFilename");
//
// if(!getBool(MString("irradianceCachePrepassOnly"), TheaGlobals, this->irradianceCachePrepassOnly))
// throw("problem reading theaGlobals.irradianceCachePrepassOnly");
//
// if(!getEnum(MString("network"), TheaGlobals, this->network))
// throw("problem reading theaGlobals.network");
//
// if(!getFloat(MString("progressiveClampLevel"), TheaGlobals, this->progressiveClampLevel))
// throw("problem reading theaGlobals.progressiveClampLevel");
//
// if(!getBool(MString("gatherTraceGlossyRefractions"), TheaGlobals, this->gatherTraceGlossyRefractions))
// throw("problem reading theaGlobals.gatherTraceGlossyRefractions");
//
// if(!getBool(MString("directAdaptiveSampling"), TheaGlobals, this->directAdaptiveSampling))
// throw("problem reading theaGlobals.directAdaptiveSampling");
//
// if(!getInt(MString("russianRouletteDepth"), TheaGlobals, this->russianRouletteDepth))
// throw("problem reading theaGlobals.russianRouletteDepth");
//
// if(!getInt(MString("causticPhotonsCaptured"), TheaGlobals, this->causticPhotonsCaptured))
// throw("problem reading theaGlobals.causticPhotonsCaptured");
//
// if(!getBool(MString("causticSharpening"), TheaGlobals, this->causticSharpening))
// throw("problem reading theaGlobals.causticSharpening");
//
// if(!getFloat(MString("gatherMaxError"), TheaGlobals, this->gatherMaxError))
// throw("problem reading theaGlobals.gatherMaxError");
//
// if(!getFloat(MString("irradianceCacheMaxConstrast"), TheaGlobals, this->irradianceCacheMaxConstrast))
// throw("problem reading theaGlobals.irradianceCacheMaxConstrast");
//
// if(!getFloat(MString("irradianceCacheMinPixelsDistance"), TheaGlobals, this->irradianceCacheMinPixelsDistance))
// throw("problem reading theaGlobals.irradianceCacheMinPixelsDistance");
//
// if(!getBool(MString("aoAffectGI"), TheaGlobals, this->aoAffectGI))
// throw("problem reading theaGlobals.aoAffectGI");
//
// if(!getInt(MString("aoSamples"), TheaGlobals, this->aoSamples))
// throw("problem reading theaGlobals.aoSamples");
//
// if(!getBool(MString("reflectionChannel"), TheaGlobals, this->reflectionChannel))
// throw("problem reading theaGlobals.reflectionChannel");
//
// if(!getFloat(MString("progressiveAmbientIntensity"), TheaGlobals, this->progressiveAmbientIntensity))
// throw("problem reading theaGlobals.progressiveAmbientIntensity");
//
// if(!getInt(MString("minAASubdivs"), TheaGlobals, this->minAASubdivs))
// throw("problem reading theaGlobals.minAASubdivs");
//
// if(!getInt(MString("deviceMask"), TheaGlobals, this->deviceMask))
// throw("problem reading theaGlobals.deviceMask");
//
// if(!getBool(MString("progressiveCaustics"), TheaGlobals, this->progressiveCaustics))
// throw("problem reading theaGlobals.progressiveCaustics");
//
// if(!getInt(MString("progressiveGlossyTracingDepth"), TheaGlobals, this->progressiveGlossyTracingDepth))
// throw("problem reading theaGlobals.progressiveGlossyTracingDepth");
//
// if(!getInt(MString("maxPasses"), TheaGlobals, this->maxPasses))
// throw("problem reading theaGlobals.maxPasses");
//
// if(!getBool(MString("animationOutputAlpha"), TheaGlobals, this->animationOutputAlpha))
// throw("problem reading theaGlobals.animationOutputAlpha");
//
// if(!getInt(MString("warmUpLevel"), TheaGlobals, this->warmUpLevel))
// throw("problem reading theaGlobals.warmUpLevel");
//
// if(!getBool(MString("aoChannel"), TheaGlobals, this->aoChannel))
// throw("problem reading theaGlobals.aoChannel");
//
// if(!getBool(MString("rayTraceRefractions"), TheaGlobals, this->rayTraceRefractions))
// throw("problem reading theaGlobals.rayTraceRefractions");
//
// if(!getInt(MString("maxBlurredSubdivs"), TheaGlobals, this->maxBlurredSubdivs))
// throw("problem reading theaGlobals.maxBlurredSubdivs");
//
// if(!getInt(MString("causticEstimationPhotons"), TheaGlobals, this->causticEstimationPhotons))
// throw("problem reading theaGlobals.causticEstimationPhotons");
//
// if(!getBool(MString("volumetricScattering"), TheaGlobals, this->volumetricScattering))
// throw("problem reading theaGlobals.volumetricScattering");
//
// if(!getBool(MString("antialiasingClampRadiance"), TheaGlobals, this->antialiasingClampRadiance))
// throw("problem reading theaGlobals.antialiasingClampRadiance");
//
// if(!getFloat(MString("aoDistance"), TheaGlobals, this->aoDistance))
// throw("problem reading theaGlobals.aoDistance");
//
// if(!getEnum(MString("priority"), TheaGlobals, this->priority))
// throw("problem reading theaGlobals.priority");
//
// if(!getString(MString("skyAnimationStart"), TheaGlobals, this->skyAnimationStart))
// throw("problem reading theaGlobals.skyAnimationStart");
//
// if(!getBool(MString("progressiveClampRadiance"), TheaGlobals, this->progressiveClampRadiance))
// throw("problem reading theaGlobals.progressiveClampRadiance");
//
// if(!getBool(MString("walkthroughAnimation"), TheaGlobals, this->walkthroughAnimation))
// throw("problem reading theaGlobals.walkthroughAnimation");
//
// if(!getBool(MString("russianRoulette"), TheaGlobals, this->russianRoulette))
// throw("problem reading theaGlobals.russianRoulette");
//
// if(!getFloat(MString("irradianceCacheMaxPixelsDistance"), TheaGlobals, this->irradianceCacheMaxPixelsDistance))
// throw("problem reading theaGlobals.irradianceCacheMaxPixelsDistance");
//
// if(!getBool(MString("brightnessTermination"), TheaGlobals, this->brightnessTermination))
// throw("problem reading theaGlobals.brightnessTermination");
//
// if(!getInt(MString("progressiveDiffuseTracingDepth"), TheaGlobals, this->progressiveDiffuseTracingDepth))
// throw("problem reading theaGlobals.progressiveDiffuseTracingDepth");
//
// if(!getBool(MString("progressiveAmbientOcclusion"), TheaGlobals, this->progressiveAmbientOcclusion))
// throw("problem reading theaGlobals.progressiveAmbientOcclusion");
//
// if(!getBool(MString("fieldMapping"), TheaGlobals, this->fieldMapping))
// throw("problem reading theaGlobals.fieldMapping");
//
// if(!getBool(MString("ambientOcclusion"), TheaGlobals, this->ambientOcclusion))
// throw("problem reading theaGlobals.ambientOcclusion");
//
// if(!getBool(MString("clayRender"), TheaGlobals, this->clayRender))
// throw("problem reading theaGlobals.clayRender");
//
// if(!getInt(MString("minBlurredSubdivs"), TheaGlobals, this->minBlurredSubdivs))
// throw("problem reading theaGlobals.minBlurredSubdivs");
//
// if(!getBool(MString("finalGathering"), TheaGlobals, this->finalGathering))
// throw("problem reading theaGlobals.finalGathering");
//
// if(!getInt(MString("maxAASubdivs"), TheaGlobals, this->maxAASubdivs))
// throw("problem reading theaGlobals.maxAASubdivs");
//
// if(!getBool(MString("biasedSupersampling"), TheaGlobals, this->biasedSupersampling))
// throw("problem reading theaGlobals.biasedSupersampling");
//
// if(!getBool(MString("irradianceCaching"), TheaGlobals, this->irradianceCaching))
// throw("problem reading theaGlobals.irradianceCaching");
//
// if(!getEnum(MString("supersampling"), TheaGlobals, this->supersampling))
// throw("problem reading theaGlobals.supersampling");
//
// if(!getInt(MString("fieldDensity"), TheaGlobals, this->fieldDensity))
// throw("problem reading theaGlobals.fieldDensity");
//
// if(!getEnum(MString("engine"), TheaGlobals, this->engine))
// throw("problem reading theaGlobals.engine");
//
// if(!getBool(MString("imageSaving"), TheaGlobals, this->imageSaving))
// throw("problem reading theaGlobals.imageSaving");
//
// if(!getFloat(MString("brightnessThreshold"), TheaGlobals, this->brightnessThreshold))
// throw("problem reading theaGlobals.brightnessThreshold");
//
// if(!getBool(MString("relight"), TheaGlobals, this->relight))
// throw("problem reading theaGlobals.relight");
//
// if(!getColor(MString("progressiveAmbientColor"), TheaGlobals, this->progressiveAmbientColor))
// throw("problem reading theaGlobals.progressiveAmbientColor");
//
// if(!getInt(MString("biasedRayTracingDepth"), TheaGlobals, this->biasedRayTracingDepth))
// throw("problem reading theaGlobals.biasedRayTracingDepth");
//
// if(!getBool(MString("irradianceCacheVisualize"), TheaGlobals, this->irradianceCacheVisualize))
// throw("problem reading theaGlobals.irradianceCacheVisualize");
//
// if(!getBool(MString("objectIdChannel"), TheaGlobals, this->objectIdChannel))
// throw("problem reading theaGlobals.objectIdChannel");
//
// if(!getBool(MString("directLighting"), TheaGlobals, this->directLighting))
// throw("problem reading theaGlobals.directLighting");
//
// if(!getInt(MString("gatherDiffuseDepth"), TheaGlobals, this->gatherDiffuseDepth))
// throw("problem reading theaGlobals.gatherDiffuseDepth");
//
// if(!getInt(MString("seed"), TheaGlobals, this->seed))
// throw("problem reading theaGlobals.seed");
//
// if(!getBool(MString("rayTraceReflections"), TheaGlobals, this->rayTraceReflections))
// throw("problem reading theaGlobals.rayTraceReflections");
//
// if(!getFloat(MString("adaptiveBias"), TheaGlobals, this->adaptiveBias))
// throw("problem reading theaGlobals.adaptiveBias");
//
// if(!getBool(MString("irradianceCacheAdaptiveDensity"), TheaGlobals, this->irradianceCacheAdaptiveDensity))
// throw("problem reading theaGlobals.irradianceCacheAdaptiveDensity");
//
// if(!getBool(MString("refractionChannel"), TheaGlobals, this->refractionChannel))
// throw("problem reading theaGlobals.refractionChannel");
//
// if(!getBool(MString("subsurfaceScattering"), TheaGlobals, this->subsurfaceScattering))
// throw("problem reading theaGlobals.subsurfaceScattering");
//
// if(!getBool(MString("fieldForceNearestCell"), TheaGlobals, this->fieldForceNearestCell))
// throw("problem reading theaGlobals.fieldForceNearestCell");
//
// if(!getBool(MString("materialIdChannel"), TheaGlobals, this->materialIdChannel))
// throw("problem reading theaGlobals.materialIdChannel");
//
// if(!getString(MString("serveraddress"), TheaGlobals, this->serveraddress))
// throw("problem reading theaGlobals.serveraddress");
//
// if(!getEnum(MString("networkCooperation"), TheaGlobals, this->networkCooperation))
// throw("problem reading theaGlobals.networkCooperation");
//
// if(!getBool(MString("motionBlur"), TheaGlobals, this->motionBlur))
// throw("problem reading theaGlobals.motionBlur");
//
// if(!getInt(MString("endFrame"), TheaGlobals, this->endFrame))
// throw("problem reading theaGlobals.endFrame");
//
// if(!getBool(MString("caustics"), TheaGlobals, this->caustics))
// throw("problem reading theaGlobals.caustics");
//
// if(!getInt(MString("maxRenderSeconds"), TheaGlobals, this->maxRenderSeconds))
// throw("problem reading theaGlobals.maxRenderSeconds");
//
// if(!getBool(MString("aoClamp"), TheaGlobals, this->aoClamp))
// throw("problem reading theaGlobals.aoClamp");
//
// if(!getBool(MString("irradianceChannel"), TheaGlobals, this->irradianceChannel))
// throw("problem reading theaGlobals.irradianceChannel");
//
// if(!getInt(MString("sssMaxSamples"), TheaGlobals, this->sssMaxSamples))
// throw("problem reading theaGlobals.sssMaxSamples");
//
// if(!getInt(MString("fieldCellSize"), TheaGlobals, this->fieldCellSize))
// throw("problem reading theaGlobals.fieldCellSize");
//
// if(!getBool(MString("directChannel"), TheaGlobals, this->directChannel))
// throw("problem reading theaGlobals.directChannel");
//
// if(!getFloat(MString("progressiveAmbientDistance"), TheaGlobals, this->progressiveAmbientDistance))
// throw("problem reading theaGlobals.progressiveAmbientDistance");
//
// if(!getInt(MString("irradianceCachePrepassPixels"), TheaGlobals, this->irradianceCachePrepassPixels))
// throw("problem reading theaGlobals.irradianceCachePrepassPixels");
//
// if(!getFloat(MString("directMaxError"), TheaGlobals, this->directMaxError))
// throw("problem reading theaGlobals.directMaxError");
//
// if(!getInt(MString("walkthroughPrepassSamples"), TheaGlobals, this->walkthroughPrepassSamples))
// throw("problem reading theaGlobals.walkthroughPrepassSamples");
//
// if(!getBool(MString("skyAnimation"), TheaGlobals, this->skyAnimation))
// throw("problem reading theaGlobals.skyAnimation");
//
// if(!getColor(MString("aoHighColor"), TheaGlobals, this->aoHighColor))
// throw("problem reading theaGlobals.aoHighColor");
//
// if(!getEnum(MString("illumination"), TheaGlobals, this->illumination))
// throw("problem reading theaGlobals.illumination");
//
// if(!getEnum(MString("sunDirectionType"), TheaGlobals, this->sunDirectionType))
// throw("problem reading theaGlobals.sunDirectionType");
//
// if(!getFloat(MString("turbidity"), TheaGlobals, this->turbidity))
// throw("problem reading theaGlobals.turbidity");
//
// if(!getFloat(MString("ozone"), TheaGlobals, this->ozone))
// throw("problem reading theaGlobals.ozone");
//
// if(!getFloat(MString("waterVapor"), TheaGlobals, this->waterVapor))
// throw("problem reading theaGlobals.waterVapor");
//
// if(!getFloat(MString("turbidityCoefficient"), TheaGlobals, this->turbidityCoefficient))
// throw("problem reading theaGlobals.turbidityCoefficient");
//
// if(!getFloat(MString("wavelengthExponent"), TheaGlobals, this->wavelengthExponent))
// throw("problem reading theaGlobals.wavelengthExponent");
//
// if(!getFloat(MString("albedo"), TheaGlobals, this->albedo))
// throw("problem reading theaGlobals.albedo");
//
// if(!getFloat(MString("latitude"), TheaGlobals, this->latitude))
// throw("problem reading theaGlobals.latitude");
//
// if(!getFloat(MString("longitude"), TheaGlobals, this->longitude))
// throw("problem reading theaGlobals.longitude");
//
// if(!getInt(MString("timezone"), TheaGlobals, this->timezone))
// throw("problem reading theaGlobals.timezone");
//
// if(!getString(MString("date"), TheaGlobals, this->date))
// throw("problem reading theaGlobals.date");
//
// if(!getString(MString("localtime"), TheaGlobals, this->localtime))
// throw("problem reading theaGlobals.localtime");
//
// if(!getString(MString("location"), TheaGlobals, this->location))
// throw("problem reading theaGlobals.location");
//
// if(!getFloat(MString("ior"), TheaGlobals, this->ior))
// throw("problem reading theaGlobals.ior");
//
// if(!getFloat(MString("sunPolarAngle"), TheaGlobals, this->sunPolarAngle))
// throw("problem reading theaGlobals.sunPolarAngle");
//
// if(!getFloat(MString("sunAzimuth"), TheaGlobals, this->sunAzimuth))
// throw("problem reading theaGlobals.sunAzimuth");
//
// if(!getVector(MString("sunDirection"), TheaGlobals, this->sunDirection))
// throw("problem reading theaGlobals.sunDirection");
//
// if(!getColor(MString("backgroundColor"), TheaGlobals, this->backgroundColor))
// throw("problem reading theaGlobals.backgroundColor");
//
// if(!getColor(MString("illuminationMap"), TheaGlobals, this->illuminationMap))
// throw("problem reading theaGlobals.illuminationMap");
//
// if(!getColor(MString("backgroundMap"), TheaGlobals, this->backgroundMap))
// throw("problem reading theaGlobals.backgroundMap");
//
// if(!getColor(MString("reflectionMap"), TheaGlobals, this->reflectionMap))
// throw("problem reading theaGlobals.reflectionMap");
//
// if(!getColor(MString("RefractionMap"), TheaGlobals, this->RefractionMap))
// throw("problem reading theaGlobals.RefractionMap");
//
//// ------------- automatically created attributes end ----------- //
//
// if(!getInt(MString("filtertype"), TheaGlobals, this->filterType))
// throw("problem reading TheaGlobals.filtertype");
//
// if(!getFloat(MString("filtersize"), TheaGlobals, this->filterSize))
// throw("problem reading TheaGlobals.filtersize");
//
// if(!getFloat(MString("gamma"), TheaGlobals, this->gamma))
// throw("problem reading TheaGlobals.gamma");
//
// if(!getInt(MString("samplesX"), TheaGlobals, this->samplesX))
// throw("problem reading TheaGlobals.samplesX");
//
// if(!getInt(MString("samplesY"), TheaGlobals, this->samplesY))
// throw("problem reading TheaGlobals.samplesY");
//
// if(!getInt(MString("minSamples"), TheaGlobals, this->minSamples))
// throw("problem reading TheaGlobals.minSamples");
//
// if(!getInt(MString("maxSamples"), TheaGlobals, this->maxSamples))
// throw("problem reading TheaGlobals.maxSamples");
//
// //if(!getInt(MString("bitdepth"), TheaGlobals, this->bitdepth))
// // throw("problem reading TheaGlobals.bitdepth");
//
// if(!getInt(MString("translatorVerbosity"), TheaGlobals, this->translatorVerbosity))
// throw("problem reading TheaGlobals.translatorVerbosity");
//
// if(!getInt(MString("rendererVerbosity"), TheaGlobals, this->rendererVerbosity))
// throw("problem reading TheaGlobals.rendererVerbosity");
//
// if(!getInt(MString("tilesize"), TheaGlobals, this->tilesize))
// throw("problem reading TheaGlobals.tilesize");
//
// if(!getInt(MString("threads"), TheaGlobals, this->threads))
// throw("problem reading TheaGlobals.threads");
//
// //if(!getInt(MString("geotimesamples"), TheaGlobals, this->geotimesamples))
// // throw("problem reading TheaGlobals.geotimesamples");
//
// //if(!getInt(MString("xftimesamples"), TheaGlobals, this->xftimesamples))
// // throw("problem reading TheaGlobals.xftimesamples");
//
// if(!getInt(MString("maxTraceDepth"), TheaGlobals, this->maxTraceDepth))
// throw("problem reading TheaGlobals.maxTraceDepth");
//
// //if(!getBool(MString("createDefaultLight"), TheaGlobals, this->createDefaultLight))
// // throw("problem reading TheaGlobals.createDefaultLight");
//
// if(!getBool(MString("detectShapeDeform"), TheaGlobals, this->detectShapeDeform))
// throw("problem reading TheaGlobals.detectShapeDeform");
//
// if(!getString(MString("optimizedTexturePath"), TheaGlobals, this->optimizedTexturePath))
// throw("problem reading TheaGlobals.optimizedTexturePath");
//
// if(!getString(MString("basePath"), TheaGlobals, this->basePath))
// throw("problem reading TheaGlobals.basePath");
//
// if(!getString(MString("imagePath"), TheaGlobals, this->imagePath))
// throw("problem reading TheaGlobals.imagePath");
//
// int id = 0;
// if(!getEnum(MString("imageFormat"), TheaGlobals, id, this->imageFormatString))
// throw("problem reading TheaGlobals.imageFormat");
//
// if(!getBool(MString("exportSceneFile"), TheaGlobals, this->exportSceneFile))
// throw("problem reading TheaGlobals.exportSceneFile");
//
// if(!getString(MString("exportSceneFileName"), TheaGlobals, this->exportSceneFileName))
// throw("problem reading TheaGlobals.exportSceneFileName");
//
// if(!getString(MString("imageName"), TheaGlobals, this->imageName))
// throw("problem reading TheaGlobals.imageName");
//
// if(!getBool(MString("adaptiveSampling"), TheaGlobals, this->adaptiveSampling))
// throw("problem reading TheaGlobals.adaptiveSampling");
//
// if(!getBool(MString("doMotionBlur"), TheaGlobals, this->doMb))
// throw("problem reading TheaGlobals.doMotionBlur");
//
// if(!getBool(MString("doDof"), TheaGlobals, this->doDof))
// throw("problem reading TheaGlobals.doDof");
//
// if(!getFloat(MString("sceneScale"), TheaGlobals, this->sceneScale))
// throw("problem reading TheaGlobals.sceneScale");
//
// this->sceneScaleMatrix.setToIdentity();
// this->sceneScaleMatrix.matrix[0][0] = this->sceneScale;
// this->sceneScaleMatrix.matrix[1][1] = this->sceneScale;
// this->sceneScaleMatrix.matrix[2][2] = this->sceneScale;
//
// }catch(char *errorMsg){
//
// Logging::error(errorMsg);
// this->good = false;
// return false;
// }
// return true;
//
//}
| 412 | 0.782979 | 1 | 0.782979 | game-dev | MEDIA | 0.630917 | game-dev | 0.746798 | 1 | 0.746798 |
mtytel/vital | 25,343 | src/interface/look_and_feel/skin.cpp | /* Copyright 2013-2019 Matt Tytel
*
* vital 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.
*
* vital 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 vital. If not, see <http://www.gnu.org/licenses/>.
*/
#include "skin.h"
#include "default_look_and_feel.h"
#include "full_interface.h"
#include "synth_constants.h"
#include "synth_section.h"
#include "wavetable_3d.h"
namespace {
const std::string kOverrideNames[Skin::kNumSectionOverrides] = {
"All",
"Logo",
"Header",
"Overlays",
"Oscillator",
"Sample",
"Sub",
"Filter",
"Envelope",
"Lfo",
"RandomLfo",
"Voice",
"Macro",
"Keyboard",
"All Effects",
"Chorus",
"Compressor",
"Delay",
"Distortion",
"Equalizer",
"Effects Filter",
"Flanger",
"Phaser",
"Reverb",
"Modulation Drag Drop",
"Modulation Matrix",
"Preset Browser",
"Popup Browser",
"Advanced",
"Wavetable Editor",
};
const std::string kValueNames[Skin::kNumSkinValueIds] = {
"Body Rounding",
"Label Height",
"Label Background Height",
"Label Rounding",
"Label Offset",
"Text Component Label Offset",
"Rotary Option X Offset",
"Rotary Option Y Offset",
"Rotary Option Width",
"Title Width",
"Padding",
"Large Padding",
"Slider Width",
"Text Component Height",
"Text Component Offset",
"Text Component Font Size",
"Text Button Height",
"Button Font Size",
"Knob Arc Size",
"Knob Arc Thickness",
"Knob Body Size",
"Knob Handle Length",
"Knob Mod Amount Arc Size",
"Knob Mod Amount Arc Thickness",
"Knob Mod Meter Arc Size",
"Knob Mod Meter Arc Thickness",
"Knob Offset",
"Knob Section Height",
"Knob Shadow Width",
"Knob Shadow Offset",
"Modulation Button Width",
"Modulation Font Size",
"Widget Margin",
"Widget Rounded Corner",
"Widget Line Width",
"Widget Line Boost",
"Widget Fill Center",
"Widget Fill Fade",
"Widget Fill Boost",
"Wavetable Horizontal Angle",
"Wavetable Vertical Angle",
"Wavetable Draw Width",
"Wavetable Draw Height",
"Wavetable Y Offset",
};
const std::string kColorNames[Skin::kNumColors] = {
"Background",
"Body",
"Body Heading Background",
"Heading Text",
"Preset Text",
"Body Text",
"Border",
"Label Background",
"Label Connection",
"Power Button On",
"Power Button Off",
"Overlay Screen",
"Lighten Screen",
"Shadow",
"Popup Selector Background",
"Popup Background",
"Popup Border",
"Text Component Background",
"Text Component Text",
"Rotary Arc",
"Rotary Arc Disabled",
"Rotary Arc Unselected",
"Rotary Arc Unselected Disabled",
"Rotary Hand",
"Rotary Body",
"Rotary Body Border",
"Linear Slider",
"Linear Slider Disabled",
"Linear Slider Unselected",
"Linear Slider Thumb",
"Linear Slider Thumb Disabled",
"Widget Center Line",
"Widget Primary 1",
"Widget Primary 2",
"Widget Primary Disabled",
"Widget Secondary 1",
"Widget Secondary 2",
"Widget Secondary Disabled",
"Widget Accent 1",
"Widget Accent 2",
"Widget Background",
"Modulation Meter",
"Modulation Meter Left",
"Modulation Meter Right",
"Modulation Meter Control",
"Modulation Button Selected",
"Modulation Button Dragging",
"Modulation Button Unselected",
"Icon Selector Icon",
"Icon Button Off",
"Icon Button Off Hover",
"Icon Button Off Pressed",
"Icon Button On",
"Icon Button On Hover",
"Icon Button On Pressed",
"UI Button",
"UI Button Text",
"UI Button Hover",
"UI Button Press",
"UI Action Button",
"UI Action Button Hover",
"UI Action Button Press",
"Text Editor Background",
"Text Editor Border",
"Text Editor Caret",
"Text Editor Selection"
};
} // namespace
bool Skin::shouldScaleValue(ValueId value_id) {
return value_id != kWidgetFillFade && value_id != kWidgetFillBoost &&
value_id != kWidgetLineBoost && value_id != kKnobHandleLength &&
value_id != kWidgetFillCenter && value_id != kFrequencyDisplay &&
value_id != kWavetableHorizontalAngle && value_id != kWavetableVerticalAngle;
}
Skin::Skin() {
File default_skin = LoadSave::getDefaultSkin();
if (default_skin.exists()) {
if (!loadFromFile(default_skin))
loadDefaultSkin();
}
else
loadDefaultSkin();
copyValuesToLookAndFeel(DefaultLookAndFeel::instance());
}
void Skin::clearSkin() {
for (int i = 0; i < kNumSectionOverrides; ++i)
color_overrides_[i].clear();
for (int i = 0; i < kNumSectionOverrides; ++i)
value_overrides_[i].clear();
}
void Skin::loadDefaultSkin() {
MemoryInputStream skin((const void*)BinaryData::default_vitalskin, BinaryData::default_vitalskinSize, false);
std::string skin_string = skin.readEntireStreamAsString().toStdString();
try {
json data = json::parse(skin_string, nullptr, false);
jsonToState(data);
}
catch (const json::exception& e) {
}
}
void Skin::setComponentColors(Component* component) const {
for (int i = 0; i < Skin::kNumColors; ++i) {
int color_id = i + Skin::kInitialColor;
Colour color = getColor(static_cast<Skin::ColorId>(color_id));
component->setColour(color_id, color);
}
}
void Skin::setComponentColors(Component* component, SectionOverride section_override, bool top_level) const {
if (top_level) {
setComponentColors(component);
return;
}
for (int i = kInitialColor; i < kFinalColor; ++i)
component->removeColour(i);
for (const auto& color : color_overrides_[section_override])
component->setColour(color.first, color.second);
}
void Skin::setComponentValues(SynthSection* component) const {
std::map<ValueId, float> values;
for (int i = 0; i < kNumSkinValueIds; ++i)
values[(ValueId)i] = values_[i];
component->setSkinValues(values);
}
void Skin::setComponentValues(SynthSection* component, SectionOverride section_override, bool top_level) const {
if (top_level) {
setComponentValues(component);
return;
}
component->setSkinValues(value_overrides_[section_override]);
}
bool Skin::overridesColor(int section, ColorId color_id) const {
if (section == kNone)
return true;
return color_overrides_[section].count(color_id) > 0;
}
bool Skin::overridesValue(int section, ValueId value_id) const {
if (section == kNone)
return true;
return value_overrides_[section].count(value_id) > 0;
}
void Skin::copyValuesToLookAndFeel(LookAndFeel* look_and_feel) const {
look_and_feel->setColour(PopupMenu::backgroundColourId, getColor(Skin::kPopupBackground));
look_and_feel->setColour(PopupMenu::textColourId, getColor(Skin::kBodyText));
look_and_feel->setColour(TooltipWindow::textColourId, getColor(Skin::kBodyText));
look_and_feel->setColour(BubbleComponent::backgroundColourId, getColor(Skin::kPopupBackground));
look_and_feel->setColour(BubbleComponent::outlineColourId, getColor(Skin::kPopupBorder));
for (int i = kInitialColor; i < kFinalColor; ++i)
look_and_feel->setColour(i, getColor(static_cast<Skin::ColorId>(i)));
}
Colour Skin::getColor(int section, ColorId color_id) const {
if (section == kNone)
return getColor(color_id);
if (color_overrides_[section].count(color_id))
return color_overrides_[section].at(color_id);
return Colours::black;
}
float Skin::getValue(int section, ValueId value_id) const {
if (value_overrides_[section].count(value_id))
return value_overrides_[section].at(value_id);
return getValue(value_id);
}
void Skin::addOverrideColor(int section, ColorId color_id, Colour color) {
if (section == kNone)
setColor(color_id, color);
else
color_overrides_[section][color_id] = color;
}
void Skin::removeOverrideColor(int section, ColorId color_id) {
if (section != kNone)
color_overrides_[section].erase(color_id);
}
void Skin::addOverrideValue(int section, ValueId value_id, float value) {
if (section == kNone)
setValue(value_id, value);
else
value_overrides_[section][value_id] = value;
}
void Skin::removeOverrideValue(int section, ValueId color_id) {
if (section != kNone)
value_overrides_[section].erase(color_id);
}
json Skin::stateToJson() {
json data;
for (int i = 0; i < kNumColors; ++i)
data[kColorNames[i]] = colors_[i].toString().toStdString();
for (int i = 0; i < kNumSkinValueIds; ++i)
data[kValueNames[i]] = values_[i];
json overrides;
for (int override_index = 0; override_index < kNumSectionOverrides; ++override_index) {
json override_section;
for (const auto& color : color_overrides_[override_index]) {
int index = color.first - Skin::kInitialColor;
override_section[kColorNames[index]] = color.second.toString().toStdString();
}
for (const auto& value : value_overrides_[override_index]) {
int index = value.first;
override_section[kValueNames[index]] = value.second;
}
overrides[kOverrideNames[override_index]] = override_section;
}
data["overrides"] = overrides;
data["synth_version"] = ProjectInfo::versionNumber;
return data;
}
String Skin::stateToString() {
return stateToJson().dump();
}
void Skin::saveToFile(File destination) {
destination.replaceWithText(stateToString());
}
json Skin::updateJson(json data) {
int version = 0;
if (data.count("synth_version"))
version = data["synth_version"];
if (version < 0x608) {
data["Knob Arc Size"] = data["Knob Size"];
data["Knob Arc Thickness"] = data["Knob Thickness"];
data["Knob Handle Length"] = data["Knob Handle Radial Amount"];
data["Knob Mod Amount Arc Size"] = data["Knob Mod Amount Size"];
data["Knob Mod Amount Arc Thickness"] = data["Knob Mod Amount Thickness"];
data["Knob Mod Meter Arc Size"] = data["Knob Mod Meter Size"];
data["Knob Mod Meter Arc Thickness"] = data["Knob Mod Meter Thickness"];
}
if (data.count("Widget Fill Boost") == 0)
data["Widget Fill Boost"] = 1.6f;
if (data.count("Widget Line Boost") == 0)
data["Widget Line Boost"] = 1.0f;
if (version < 0x609)
data["Modulation Meter"] = Colours::white.toString().toStdString();
return data;
}
void Skin::jsonToState(json data) {
clearSkin();
data = updateJson(data);
if (data.count("overrides")) {
json overrides = data["overrides"];
for (int override_index = 0; override_index < kNumSectionOverrides; ++override_index) {
std::string name = kOverrideNames[override_index];
color_overrides_[override_index].clear();
value_overrides_[override_index].clear();
if (overrides.count(name) == 0)
continue;
json override_section = overrides[name];
for (int i = 0; i < kNumColors; ++i) {
if (override_section.count(kColorNames[i])) {
ColorId color_id = static_cast<Skin::ColorId>(i + Skin::kInitialColor);
std::string color_string = override_section[kColorNames[i]];
color_overrides_[override_index][color_id] = Colour::fromString(color_string);
}
}
for (int i = 0; i < kNumSkinValueIds; ++i) {
if (override_section.count(kValueNames[i])) {
Skin::ValueId value_id = static_cast<Skin::ValueId>(i);
float value = override_section[kValueNames[i]];
value_overrides_[override_index][value_id] = value;
}
}
}
}
for (int i = 0; i < kNumColors; ++i) {
if (data.count(kColorNames[i])) {
std::string color_string = data[kColorNames[i]];
colors_[i] = Colour::fromString(color_string);
}
}
for (int i = 0; i < kNumSkinValueIds; ++i) {
if (data.count(kValueNames[i]))
values_[i] = data[kValueNames[i]];
else
values_[i] = 0.0f;
}
}
bool Skin::stringToState(String skin_string) {
try {
json data = json::parse(skin_string.toStdString(), nullptr, false);
jsonToState(data);
}
catch (const json::exception& e) {
return false;
}
return true;
}
bool Skin::loadFromFile(File source) {
return stringToState(source.loadFileAsString());
}
class SkinColorPicker : public Component, public Button::Listener, public Slider::Listener, public ChangeListener {
public:
static constexpr int kLoadSaveHeight = 20;
static constexpr int kButtonHeight = 30;
SkinColorPicker(String name, Skin* skin, FullInterface* full_interface) :
Component(name), load_button_("Load"), save_button_("Save"),
override_index_(0), editing_index_(0), skin_(skin), full_interface_(full_interface) {
addAndMakeVisible(&load_button_);
load_button_.addListener(this);
addAndMakeVisible(&save_button_);
save_button_.addListener(this);
for (int i = 0; i < Skin::kNumSectionOverrides; ++i)
addOverrideSection(i);
addAndMakeVisible(viewport_);
container_ = new Component("Container");
viewport_.setViewedComponent(container_);
for (int i = 0; i < Skin::kNumColors; ++i)
addColor(i);
for (int i = 0; i < Skin::kNumSkinValueIds; ++i)
addValueSlider(i);
setSliderValues();
setOverride(override_index_);
}
void setSliderValues() {
for (int i = 0; i < Skin::kNumSkinValueIds; ++i) {
float value = skin_->getValue(static_cast<Skin::ValueId>(i));
value_sliders_[i]->setValue(value, NotificationType::dontSendNotification);
}
}
void addOverrideSection(int override_index) {
override_buttons_.push_back(std::make_unique<TextButton>(kOverrideNames[override_index]));
size_t index = override_buttons_.size() - 1;
addAndMakeVisible(override_buttons_[index].get());
override_buttons_[index]->addListener(this);
}
void addColor(int color_index) {
color_buttons_.push_back(std::make_unique<TextButton>(kColorNames[color_index]));
size_t index = color_buttons_.size() - 1;
container_->addAndMakeVisible(color_buttons_[index].get());
color_buttons_[index]->addListener(this);
override_toggle_buttons_.push_back(std::make_unique<ToggleButton>(kColorNames[color_index] + " Override"));
container_->addAndMakeVisible(override_toggle_buttons_[index].get());
override_toggle_buttons_[index]->addListener(this);
override_toggle_buttons_[index]->setColour(ToggleButton::tickColourId, Colours::black);
override_toggle_buttons_[index]->setColour(ToggleButton::tickDisabledColourId, Colours::black);
}
void addValueSlider(int value_index) {
value_sliders_.push_back(std::make_unique<Slider>(kValueNames[value_index]));
size_t index = value_sliders_.size() - 1;
container_->addAndMakeVisible(value_sliders_[index].get());
value_sliders_[index]->setRange(-10000.0f, 10000.0f);
value_sliders_[index]->setValue(0.0f);
value_sliders_[index]->setScrollWheelEnabled(false);
value_sliders_[index]->setSliderStyle(Slider::IncDecButtons);
value_sliders_[index]->addListener(this);
value_override_toggle_buttons_.push_back(std::make_unique<ToggleButton>(kValueNames[value_index] + " Override"));
container_->addAndMakeVisible(value_override_toggle_buttons_[index].get());
value_override_toggle_buttons_[index]->addListener(this);
value_override_toggle_buttons_[index]->setColour(ToggleButton::tickColourId, Colours::black);
value_override_toggle_buttons_[index]->setColour(ToggleButton::tickDisabledColourId, Colours::black);
}
void paint(Graphics& g) override {
g.fillCheckerBoard(getLocalBounds().toFloat(), 20.0f, 20.0f, Colours::grey, Colours::white);
g.setColour(Colour(0xff444444));
int x = getWidth() / 3 + kButtonHeight;
int text_x = 2 * getWidth() / 3;
int y = -viewport_.getViewPositionY();
g.fillRect(x, y, 2 * getWidth() / 3, Skin::kNumSkinValueIds * kButtonHeight);
g.setColour(Colours::white);
int width = getWidth() / 2;
for (int i = 0; i < Skin::kNumSkinValueIds; ++i) {
g.drawText(kValueNames[i], text_x, y, width, kButtonHeight, Justification::centredLeft);
y += kButtonHeight;
}
}
void resized() override {
load_button_.setBounds(0, 0, getWidth() / 6, kLoadSaveHeight);
save_button_.setBounds(getWidth() / 6, 0, getWidth() / 6, kLoadSaveHeight);
float overrides_y = kLoadSaveHeight * 2;
float overrides_height = getHeight() - overrides_y;
float overrides_width = getWidth() / 3;
for (int i = 0; i < Skin::kNumSectionOverrides; ++i) {
int override_y = i * overrides_height / Skin::kNumSectionOverrides;
int override_height = (i + 1) * overrides_height / Skin::kNumSectionOverrides - override_y;
override_buttons_[i]->setBounds(0, override_y + overrides_y, overrides_width, override_height);
}
int y = 0;
int width = 2 * getWidth() / 3 - 2 * kButtonHeight;
int slider_height = kButtonHeight * 0.7f;
int slider_pad = 0.5f * (kButtonHeight - slider_height);
for (int i = 0; i < Skin::kNumSkinValueIds; ++i) {
value_sliders_[i]->setBounds(kButtonHeight, y + slider_pad, width / 2, slider_height);
value_sliders_[i]->setTextBoxStyle(Slider::TextBoxLeft, false, width / 2, slider_height);
value_override_toggle_buttons_[i]->setBounds(0, y, kButtonHeight, kButtonHeight);
y += kButtonHeight;
}
for (int i = 0; i < color_buttons_.size(); ++i) {
color_buttons_[i]->setBounds(kButtonHeight, y, width, kButtonHeight);
override_toggle_buttons_[i]->setBounds(0, y, kButtonHeight, kButtonHeight);
y += kButtonHeight;
}
container_->setBounds(getWidth() / 3, 0, 2 * getWidth() / 3 - 10, y);
viewport_.setBounds(getWidth() / 3, 0, 2 * getWidth() / 3, getHeight());
}
void setOverride(int override_index) {
override_index_ = override_index;
for (auto& override_button : override_buttons_)
override_button->setButtonText(override_button->getName());
bool show_override = override_index != Skin::kNone;
for (int i = 0; i < value_override_toggle_buttons_.size(); ++i) {
value_override_toggle_buttons_[i]->setVisible(show_override);
Skin::ValueId value_id = static_cast<Skin::ValueId>(i);
bool overrides = skin_->overridesValue(override_index_, value_id);
value_override_toggle_buttons_[i]->setToggleState(overrides, dontSendNotification);
}
for (int i = 0; i < value_sliders_.size(); ++i) {
Skin::ValueId value_id = static_cast<Skin::ValueId>(i);
value_sliders_[i]->setValue(skin_->getValue(override_index_, value_id), dontSendNotification);
}
for (int i = 0; i < override_toggle_buttons_.size(); ++i) {
override_toggle_buttons_[i]->setVisible(show_override);
Skin::ColorId color_id = static_cast<Skin::ColorId>(Skin::kInitialColor + i);
bool overrides = skin_->overridesColor(override_index_, color_id);
override_toggle_buttons_[i]->setToggleState(overrides, dontSendNotification);
}
for (int i = 0; i < color_buttons_.size(); ++i) {
Skin::ColorId color_id = static_cast<Skin::ColorId>(Skin::kInitialColor + i);
setButtonColor(i, skin_->getColor(override_index_, color_id));
}
String new_text = "------ " + override_buttons_[override_index_]->getName() + " ------";
override_buttons_[override_index_]->setButtonText(new_text);
}
void toggleOverride(int color_index) {
bool visible = override_toggle_buttons_[color_index]->isVisible();
bool on = override_toggle_buttons_[color_index]->getToggleState();
Skin::ColorId color_id = static_cast<Skin::ColorId>(Skin::kInitialColor + color_index);
Colour color = color_buttons_[color_index]->findColour(TextButton::buttonColourId);
if (on || !visible)
skin_->addOverrideColor(override_index_, color_id, color);
else
skin_->removeOverrideColor(override_index_, color_id);
repaintWithSettings();
}
void toggleValueOverride(int value_index) {
bool visible = value_override_toggle_buttons_[value_index]->isVisible();
bool on = value_override_toggle_buttons_[value_index]->getToggleState();
Skin::ValueId value_id = static_cast<Skin::ValueId>(value_index);
float value = value_sliders_[value_index]->getValue();
if (on || !visible)
skin_->addOverrideValue(override_index_, value_id, value);
else
skin_->removeOverrideValue(override_index_, value_id);
repaintWithSettings();
}
void buttonClicked(Button* clicked_button) override {
if (clicked_button == &load_button_) {
FileChooser open_box("Open Skin", File(), String("*.") + vital::kSkinExtension);
if (open_box.browseForFileToOpen()) {
if (!skin_->loadFromFile(open_box.getResult())) {
AlertWindow::showNativeDialogBox("Error opening skin", "Skin file is corrupted and won't load.", false);
return;
}
setSliderValues();
repaintWithSettings();
}
return;
}
if (clicked_button == &save_button_) {
FileChooser save_box("Save Skin", File(), String("*.") + vital::kSkinExtension);
if (save_box.browseForFileToSave(true))
skin_->saveToFile(save_box.getResult().withFileExtension(vital::kSkinExtension));
return;
}
for (int i = 0; i < override_buttons_.size(); ++i) {
if (clicked_button == override_buttons_[i].get()) {
setOverride(i);
return;
}
}
for (int i = 0; i < value_override_toggle_buttons_.size(); ++i) {
if (clicked_button == value_override_toggle_buttons_[i].get()) {
toggleValueOverride(i);
return;
}
}
for (int i = 0; i < color_buttons_.size(); ++i) {
if (clicked_button == override_toggle_buttons_[i].get()) {
toggleOverride(i);
return;
}
if (clicked_button == color_buttons_[i].get())
editing_index_ = i;
}
ColourSelector* color_selector = new ColourSelector();
color_selector->setCurrentColour(clicked_button->findColour(TextButton::buttonColourId));
color_selector->addChangeListener(this);
color_selector->setColour(ColourSelector::backgroundColourId, Colours::transparentBlack);
color_selector->setSize(300, 400);
CallOutBox::launchAsynchronously(std::unique_ptr<Component>(color_selector), clicked_button->getScreenBounds(), nullptr);
}
void sliderValueChanged(Slider* changed_slider) override {
for (int i = 0; i < Skin::kNumSkinValueIds; ++i) {
if (value_sliders_[i].get() == changed_slider) {
if (value_override_toggle_buttons_[i]->isVisible())
value_override_toggle_buttons_[i]->setToggleState(true, dontSendNotification);
toggleValueOverride(i);
}
}
}
void repaintWithSettings() {
full_interface_->reloadSkin(*skin_);
}
void setButtonColor(int index, Colour color) {
Colour text_color = color.contrasting(0.9f);
TextButton* button = color_buttons_[index].get();
button->setColour(TextButton::buttonColourId, color);
button->setColour(TextButton::textColourOnId, text_color);
button->setColour(TextButton::textColourOffId, text_color);
}
void changeListenerCallback(ChangeBroadcaster* source) override {
ColourSelector* selector = dynamic_cast<ColourSelector*>(source);
if (selector == nullptr)
return;
Colour color = selector->getCurrentColour();
setButtonColor(editing_index_, color);
if (override_toggle_buttons_[editing_index_]->isVisible())
override_toggle_buttons_[editing_index_]->setToggleState(true, dontSendNotification);
toggleOverride(editing_index_);
}
protected:
TextButton load_button_;
TextButton save_button_;
std::vector<std::unique_ptr<TextButton>> override_buttons_;
std::vector<std::unique_ptr<ToggleButton>> override_toggle_buttons_;
std::vector<std::unique_ptr<ToggleButton>> value_override_toggle_buttons_;
std::vector<std::unique_ptr<TextButton>> color_buttons_;
std::vector<std::unique_ptr<Slider>> value_sliders_;
std::vector<std::unique_ptr<Label>> value_labels_;
int override_index_;
int editing_index_;
Skin* skin_;
FullInterface* full_interface_;
Component* container_;
Viewport viewport_;
};
SkinDesigner::SkinDesigner(Skin* skin, FullInterface* full_interface) :
DocumentWindow("Skin Designer", Colours::grey, DocumentWindow::closeButton){
container_ = std::make_unique<SkinColorPicker>("Container", skin, full_interface);
setContentNonOwned(container_.get(), false);
}
SkinDesigner::~SkinDesigner() = default;
| 412 | 0.964769 | 1 | 0.964769 | game-dev | MEDIA | 0.570282 | game-dev | 0.883606 | 1 | 0.883606 |
EvaisaDev/noita.fairmod | 1,066 | files/content/scene_liquid_randomizer/hm_pools/append_hm.lua | dofile_once("mods/noita.fairmod/files/content/scene_liquid_randomizer/material_restrictions.lua")
-- Duplicated in temple_altar.lua, but the others don't have this
RegisterSpawnFunction( 0xff03deaf, "fairmod_spawn_liquid_converter" )
local function rand_material(x, y)
SetRandomSeed(x, y + GameGetFrameNum())
local liquids = HMMaterialsFilter(CellFactory_GetAllLiquids(false, false) or {}, true)
return liquids[Random(1, #liquids)]
end
function fairmod_spawn_liquid_converter(x, y)
local material = rand_material(x, y)
local converter = EntityLoad("mods/noita.fairmod/files/content/scene_liquid_randomizer/hm_pools/convert_materials.xml", x, y + 35)
EntityAddComponent2(converter, "MagicConvertMaterialComponent", {
radius = 90,
steps_per_frame = 100,
from_material = CellFactory_GetType("water"),
to_material = CellFactory_GetType(material),
extinguish_fire = true,
loop = true,
kill_when_finished = false,
})
end
local old_spawn_fish = spawn_fish
function spawn_fish(x, y)
fairmod_spawn_liquid_converter(x, y)
old_spawn_fish(x, y)
end
| 412 | 0.656478 | 1 | 0.656478 | game-dev | MEDIA | 0.995947 | game-dev | 0.946135 | 1 | 0.946135 |
EricDDK/billiards_cocos2d | 2,578 | Billiards/frameworks/cocos2d-x/external/chipmunk/include/chipmunk/constraints/cpDampedSpring.h | /* Copyright (c) 2007 Scott Lembcke
*
* 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.
*/
/// @defgroup cpDampedSpring cpDampedSpring
/// @{
typedef struct cpDampedSpring cpDampedSpring;
typedef cpFloat (*cpDampedSpringForceFunc)(cpConstraint *spring, cpFloat dist);
const cpConstraintClass *cpDampedSpringGetClass(void);
/// @private
struct cpDampedSpring {
cpConstraint constraint;
cpVect anchr1, anchr2;
cpFloat restLength;
cpFloat stiffness;
cpFloat damping;
cpDampedSpringForceFunc springForceFunc;
cpFloat target_vrn;
cpFloat v_coef;
cpVect r1, r2;
cpFloat nMass;
cpVect n;
cpFloat jAcc;
};
/// Allocate a damped spring.
cpDampedSpring* cpDampedSpringAlloc(void);
/// Initialize a damped spring.
cpDampedSpring* cpDampedSpringInit(cpDampedSpring *joint, cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiffness, cpFloat damping);
/// Allocate and initialize a damped spring.
cpConstraint* cpDampedSpringNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiffness, cpFloat damping);
CP_DefineConstraintProperty(cpDampedSpring, cpVect, anchr1, Anchr1)
CP_DefineConstraintProperty(cpDampedSpring, cpVect, anchr2, Anchr2)
CP_DefineConstraintProperty(cpDampedSpring, cpFloat, restLength, RestLength)
CP_DefineConstraintProperty(cpDampedSpring, cpFloat, stiffness, Stiffness)
CP_DefineConstraintProperty(cpDampedSpring, cpFloat, damping, Damping)
CP_DefineConstraintProperty(cpDampedSpring, cpDampedSpringForceFunc, springForceFunc, SpringForceFunc)
/// @}
| 412 | 0.655976 | 1 | 0.655976 | game-dev | MEDIA | 0.662574 | game-dev | 0.634005 | 1 | 0.634005 |
mhogrefe/malachite | 23,755 | malachite-base/src/tuples/random.rs | // Copyright © 2025 Mikhail Hogrefe
//
// This file is part of Malachite.
//
// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
use crate::random::Seed;
use std::cmp::Ordering::*;
use std::iter::{Repeat, repeat};
/// Generates random units; repeats `()`.
///
/// $P(()) = 1$.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use itertools::Itertools;
/// use malachite_base::tuples::random::random_units;
///
/// assert_eq!(random_units().take(10).collect_vec(), &[(); 10]);
/// ```
pub fn random_units() -> Repeat<()> {
repeat(())
}
// hack for macro
#[doc(hidden)]
#[inline]
pub fn next_helper<I: Iterator>(x: &mut I, _i: usize) -> Option<I::Item> {
x.next()
}
/// Defines random tuple generators.
///
/// Malachite provides [`random_pairs`] and [`random_pairs_from_single`], but you can also define
/// `random_triples`, `random_quadruples`, and so on, and `random_triples_from_single`,
/// `random_quadruples_from_single`, and so on, in your program using the code below. The
/// documentation for [`random_pairs`] and [`random_pairs_from_single`] describes these other
/// functions as well.
///
/// See usage examples [here](self#random_pairs) and [here](self#random_pairs_from_single).
///
/// ```
/// use malachite_base::random::Seed;
/// use malachite_base::random_tuples;
/// use malachite_base::tuples::random::next_helper;
///
/// random_tuples!(
/// (pub(crate)),
/// RandomTriples,
/// RandomTriplesFromSingle,
/// random_triples,
/// random_triples_from_single,
/// (I::Item, I::Item, I::Item),
/// [0, X, I, xs, xs_gen],
/// [1, Y, J, ys, ys_gen],
/// [2, Z, K, zs, zs_gen]
/// );
/// random_tuples!(
/// (pub(crate)),
/// RandomQuadruples,
/// RandomQuadruplesFromSingle,
/// random_quadruples,
/// random_quadruples_from_single,
/// (I::Item, I::Item, I::Item, I::Item),
/// [0, X, I, xs, xs_gen],
/// [1, Y, J, ys, ys_gen],
/// [2, Z, K, zs, zs_gen],
/// [3, W, L, ws, ws_gen]
/// );
/// random_tuples!(
/// (pub(crate)),
/// RandomQuintuples,
/// RandomQuintuplesFromSingle,
/// random_quintuples,
/// random_quintuples_from_single,
/// (I::Item, I::Item, I::Item, I::Item, I::Item),
/// [0, X, I, xs, xs_gen],
/// [1, Y, J, ys, ys_gen],
/// [2, Z, K, zs, zs_gen],
/// [3, W, L, ws, ws_gen],
/// [4, V, M, vs, vs_gen]
/// );
/// random_tuples!(
/// (pub(crate)),
/// RandomSextuples,
/// RandomSextuplesFromSingle,
/// random_sextuples,
/// random_sextuples_from_single,
/// (I::Item, I::Item, I::Item, I::Item, I::Item, I::Item),
/// [0, X, I, xs, xs_gen],
/// [1, Y, J, ys, ys_gen],
/// [2, Z, K, zs, zs_gen],
/// [3, W, L, ws, ws_gen],
/// [4, V, M, vs, vs_gen],
/// [5, U, N, us, us_gen]
/// );
/// random_tuples!(
/// (pub(crate)),
/// RandomSeptuples,
/// RandomSeptuplesFromSingle,
/// random_septuples,
/// random_septuples_from_single,
/// (
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item
/// ),
/// [0, X, I, xs, xs_gen],
/// [1, Y, J, ys, ys_gen],
/// [2, Z, K, zs, zs_gen],
/// [3, W, L, ws, ws_gen],
/// [4, V, M, vs, vs_gen],
/// [5, U, N, us, us_gen],
/// [6, T, O, ts, ts_gen]
/// );
/// random_tuples!(
/// (pub(crate)),
/// RandomOctuples,
/// RandomOctuplesFromSingle,
/// random_octuples,
/// random_octuples_from_single,
/// (
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item
/// ),
/// [0, X, I, xs, xs_gen],
/// [1, Y, J, ys, ys_gen],
/// [2, Z, K, zs, zs_gen],
/// [3, W, L, ws, ws_gen],
/// [4, V, M, vs, vs_gen],
/// [5, U, N, us, us_gen],
/// [6, T, O, ts, ts_gen],
/// [7, S, P, ss, ss_gen]
/// );
/// ```
#[macro_export]
macro_rules! random_tuples {
(
($($vis:tt)*),
$random_struct: ident,
$random_struct_from_single: ident,
$random_fn: ident,
$random_fn_from_single: ident,
$single_out: tt,
$([$i: expr, $t: ident, $it: ident, $xs: ident, $xs_gen:ident]),*
) => {
/// This documentation applies not only to `RandomPairs`, but also to `RandomTriples`,
/// `RandomQuadruples`, and so on. See [`random_tuples`] for more information.
///
/// Generates random $n$-tuples using elements from $n$ iterators.
#[derive(Clone, Debug)]
#[allow(dead_code)]
$($vis)* struct $random_struct<$($t: Clone, $it: Iterator<Item = $t>,)*> {
$($xs: $it,)*
}
impl<$($t: Clone, $it: Iterator<Item = $t>,)*> Iterator for $random_struct<$($t, $it,)*>
{
type Item = ($($t,)*);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
Some(($(self.$xs.next().unwrap()),*))
}
}
/// This documentation applies not only to `random_pairs`, but also to `random_triples`,
/// `random_quadruples`, and so on. See [`random_tuples`] for more information.
///
/// Generates random $n$-tuples with elements from $n$ iterators.
///
/// The probability of a particular $n$-tuple being generated is the product of the
/// probabilities of each of its elements.
///
/// `xs`, `ys`, `zs`, ... must be infinite.
///
/// # Examples
/// See [here](self#random_pairs).
#[allow(dead_code)]
$($vis)* fn $random_fn<$($t: Clone, $it: Iterator<Item = $t>,)*>(
seed: Seed,
$($xs_gen: &dyn Fn(Seed) -> $it,)*
) -> $random_struct<$($t, $it,)*> {
$random_struct {
$($xs: $xs_gen(seed.fork(stringify!($xs))),)*
}
}
/// This documentation applies not only to `RandomPairsFromSingle`, but also to
/// `RandomTriplesFromSingle`, `RandomQuadruplesFromSingle`, and so on. See
/// [`random_tuples`] for more information.
///
/// Generates random $n$-tuples using elements from a single iterator.
#[derive(Clone, Debug)]
#[allow(dead_code)]
$($vis)* struct $random_struct_from_single<I: Iterator> {
xs: I
}
impl<I: Iterator> Iterator for $random_struct_from_single<I> {
type Item = $single_out;
#[inline]
fn next(&mut self) -> Option<$single_out> {
Some(($(next_helper(&mut self.xs, $i).unwrap(),)*))
}
}
/// This documentation applies not only to `random_pairs_from_single`, but also to
/// `random_triples_from_single`, `random_quadruples_from_single`, and so on. See
/// [`random_tuples`] for more information.
///
/// Generates random $n$-tuples using elements from a single iterator.
///
/// The probability of a particular $n$-tuple being generated is the product of the
/// probabilities of each of its elements.
///
/// `xs` must be infinite.
///
/// # Examples
/// See [here](self#random_pairs_from_single).
#[allow(dead_code)]
#[inline]
$($vis)* const fn $random_fn_from_single<I: Iterator>(xs: I)
-> $random_struct_from_single<I> {
$random_struct_from_single { xs }
}
}
}
random_tuples!(
(pub),
RandomPairs,
RandomPairsFromSingle,
random_pairs,
random_pairs_from_single,
(I::Item, I::Item),
[0, X, I, xs, xs_gen],
[1, Y, J, ys, ys_gen]
);
/// Defines custom random tuple generators.
///
/// You can define custom tuple generators like `random_triples_xyx` in your program using the code
/// below.
///
/// See usage examples [here](self#random_triples_xyx).
///
/// ```
/// use malachite_base::random::Seed;
/// use malachite_base::random_custom_tuples;
///
/// random_custom_tuples!(
/// (pub(crate)),
/// RandomTriplesXXY,
/// (X, X, Y),
/// random_triples_xxy,
/// [X, I, xs, xs_gen, [x_0, x_0], [x_1, x_1]],
/// [Y, J, ys, ys_gen, [y_2, y_2]]
/// );
/// random_custom_tuples!(
/// (pub(crate)),
/// RandomTriplesXYX,
/// (X, Y, X),
/// random_triples_xyx,
/// [X, I, xs, xs_gen, [x_0, x_0], [x_2, y_1]],
/// [Y, J, ys, ys_gen, [y_1, x_2]]
/// );
/// random_custom_tuples!(
/// (pub(crate)),
/// RandomTriplesXYY,
/// (X, Y, Y),
/// random_triples_xyy,
/// [X, I, xs, xs_gen, [x_0, x_0]],
/// [Y, J, ys, ys_gen, [y_1, y_1], [y_2, y_2]]
/// );
/// random_custom_tuples!(
/// (pub(crate)),
/// RandomQuadruplesXXXY,
/// (X, X, X, Y),
/// random_quadruples_xxxy,
/// [X, I, xs, xs_gen, [x_0, x_0], [x_1, x_1], [x_2, x_2]],
/// [Y, J, ys, ys_gen, [y_3, y_3]]
/// );
/// random_custom_tuples!(
/// (pub(crate)),
/// RandomQuadruplesXXYX,
/// (X, X, Y, X),
/// random_quadruples_xxyx,
/// [X, I, xs, xs_gen, [x_0, x_0], [x_1, x_1], [x_3, y_2]],
/// [Y, J, ys, ys_gen, [y_2, x_3]]
/// );
/// random_custom_tuples!(
/// (pub(crate)),
/// RandomQuadruplesXXYZ,
/// (X, X, Y, Z),
/// random_quadruples_xxyz,
/// [X, I, xs, xs_gen, [x_0, x_0], [x_1, x_1]],
/// [Y, J, ys, ys_gen, [y_2, y_2]],
/// [Z, K, zs, zs_gen, [z_3, z_3]]
/// );
/// random_custom_tuples!(
/// (pub(crate)),
/// RandomQuadruplesXYXZ,
/// (X, Y, X, Z),
/// random_quadruples_xyxz,
/// [X, I, xs, xs_gen, [x_0, x_0], [x_2, y_1]],
/// [Y, J, ys, ys_gen, [y_1, x_2]],
/// [Z, K, zs, zs_gen, [z_3, z_3]]
/// );
/// random_custom_tuples!(
/// (pub(crate)),
/// RandomQuadruplesXYYX,
/// (X, Y, Y, X),
/// random_quadruples_xyyx,
/// [X, I, xs, xs_gen, [x_0, x_0], [x_3, y_1]],
/// [Y, J, ys, ys_gen, [y_1, y_2], [y_2, x_3]]
/// );
/// random_custom_tuples!(
/// (pub(crate)),
/// RandomQuadruplesXYYZ,
/// (X, Y, Y, Z),
/// random_quadruples_xyyz,
/// [X, I, xs, xs_gen, [x_0, x_0]],
/// [Y, J, ys, ys_gen, [y_1, y_1], [y_2, y_2]],
/// [Z, K, zs, zs_gen, [z_3, z_3]]
/// );
/// random_custom_tuples!(
/// (pub(crate)),
/// RandomQuadruplesXYZZ,
/// (X, Y, Z, Z),
/// random_quadruples_xyzz,
/// [X, I, xs, xs_gen, [x_0, x_0]],
/// [Y, J, ys, ys_gen, [y_1, y_1]],
/// [Z, K, zs, zs_gen, [z_2, z_2], [z_3, z_3]]
/// );
/// random_custom_tuples!(
/// (pub(crate)),
/// RandomQuintuplesXYYYZ,
/// (X, Y, Y, Y, Z),
/// random_quintuples_xyyyz,
/// [X, I, xs, xs_gen, [x_0, x_0]],
/// [Y, J, ys, ys_gen, [y_1, y_1], [y_2, y_2], [y_3, y_3]],
/// [Z, K, zs, zs_gen, [z_4, z_4]]
/// );
/// ```
#[macro_export]
macro_rules! random_custom_tuples {
(
($($vis:tt)*),
$random_struct: ident,
$out_t: ty,
$random_fn: ident,
$([$t: ident, $it: ident, $xs: ident, $xs_gen: ident, $([$x: ident, $x_ord: ident]),*]),*
) => {
// Generates random $n$-tuples with elements from $m$ iterators, where $m \leq n$.
//
// The mapping from iterators to tuple slots is indicated by the struct name; for example,
// in `RandomTriplesXYX` there are two iterators, `X`, and `Y`; `X` generates the elements
// in the first and third slots of the output triples, and `Y` generates the elements in the
// second slots.
#[derive(Clone, Debug)]
$($vis)* struct $random_struct<$($t: Clone, $it: Iterator<Item = $t>,)*> {
$($xs: $it,)*
}
impl<$($t: Clone, $it: Iterator<Item = $t>,)*> Iterator for $random_struct<$($t, $it,)*>
{
type Item = $out_t;
fn next(&mut self) -> Option<Self::Item> {
$(
$(
let $x = self.$xs.next().unwrap();
)*
)*
Some(($($($x_ord,)*)*))
}
}
// Generates random $n$-tuples with elements from $m$ iterators, where $m \leq n$.
//
// The mapping from iterators to tuple slots is indicated by the function name; for example,
// `random_triples_xyx` takes two iterators, `xs`, and `ys`; `xs` generates the elements in
// the first and third slots of the output triples, and `ys` generates the elements in the
// second slots.
//
// The probability of a particular $n$-tuple being generated is the product of the
// probabilities of each of its elements.
//
// `xs`, `ys`, `zs`, ... must be infinite.
//
// # Examples
// See [here](self#random_triples_xyx).
$($vis)* fn $random_fn<$($t: Clone, $it: Iterator<Item = $t>,)*>(
seed: Seed,
$($xs_gen: &dyn Fn(Seed) -> $it,)*
) -> $random_struct<$($t, $it,)*> {
$random_struct {
$($xs: $xs_gen(seed.fork(stringify!($xs))),)*
}
}
}
}
/// Generates random pairs using elements from a single iterator, where the first element is less
/// than the second.
#[derive(Clone, Debug)]
pub struct RandomOrderedUniquePairs<I: Iterator>
where
I::Item: Ord,
{
xs: I,
}
impl<I: Iterator> Iterator for RandomOrderedUniquePairs<I>
where
I::Item: Ord,
{
type Item = (I::Item, I::Item);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let mut out_0 = None;
let out_1;
loop {
let x = self.xs.next().unwrap();
if out_0.is_none() {
out_0 = Some(x);
} else {
match x.cmp(out_0.as_ref().unwrap()) {
Equal => {}
Greater => {
out_1 = x;
break;
}
Less => {
out_1 = out_0.unwrap();
out_0 = Some(x);
break;
}
}
}
}
Some((out_0.unwrap(), out_1))
}
}
/// Generates random pairs using elements from a single iterator, where the first element of each
/// pair is less than the second.
///
/// The input iterator must generate at least two distinct elements; otherwise, this iterator will
/// hang.
///
/// $$
/// P((x\_0, x\_1)) = 2P(x\_0)P(x\_1).
/// $$
///
/// The above formula assumes that the pair is valid, \emph{i.e.} its first element is less than its
/// second. The probability of an invalid pair is zero.
///
/// `xs` must be infinite.
#[inline]
pub const fn random_ordered_unique_pairs<I: Iterator>(xs: I) -> RandomOrderedUniquePairs<I>
where
I::Item: Ord,
{
RandomOrderedUniquePairs { xs }
}
/// Defines random ordered unique tuple generators.
///
/// Malachite provides [`random_ordered_unique_pairs`], but you can also define
/// `random_ordered_unique_triples`, `random_ordered_unique_quadruples`, and so on, in your program
/// using the code below.
///
/// See usage examples [here](self#random_ordered_unique_quadruples).
///
/// ```
/// use malachite_base::random_ordered_unique_tuples;
/// use malachite_base::sets::random::{
/// random_b_tree_sets_fixed_length, RandomBTreeSetsFixedLength,
/// };
///
/// random_ordered_unique_tuples!(
/// (pub(crate)),
/// RandomOrderedUniqueTriples,
/// 3,
/// (I::Item, I::Item, I::Item),
/// random_ordered_unique_triples,
/// [0, 1, 2]
/// );
/// random_ordered_unique_tuples!(
/// (pub(crate)),
/// RandomOrderedUniqueQuadruples,
/// 4,
/// (I::Item, I::Item, I::Item, I::Item),
/// random_ordered_unique_quadruples,
/// [0, 1, 2, 3]
/// );
/// random_ordered_unique_tuples!(
/// (pub(crate)),
/// RandomOrderedUniqueQuintuples,
/// 5,
/// (I::Item, I::Item, I::Item, I::Item, I::Item),
/// random_ordered_unique_quintuples,
/// [0, 1, 2, 3, 4]
/// );
/// random_ordered_unique_tuples!(
/// (pub(crate)),
/// RandomOrderedUniqueSextuples,
/// 6,
/// (I::Item, I::Item, I::Item, I::Item, I::Item, I::Item),
/// random_ordered_unique_sextuples,
/// [0, 1, 2, 3, 4, 5]
/// );
/// random_ordered_unique_tuples!(
/// (pub(crate)),
/// RandomOrderedUniqueSeptuples,
/// 7,
/// (
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item
/// ),
/// random_ordered_unique_septuples,
/// [0, 1, 2, 3, 4, 5, 6]
/// );
/// random_ordered_unique_tuples!(
/// (pub(crate)),
/// RandomOrderedUniqueOctuples,
/// 8,
/// (
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item
/// ),
/// random_ordered_unique_octuples,
/// [0, 1, 2, 3, 4, 5, 6, 7]
/// );
/// ```
#[macro_export]
macro_rules! random_ordered_unique_tuples {
(
($($vis:tt)*),
$struct: ident,
$k: expr,
$out_t: ty,
$fn: ident,
[$($i: expr),*]
) => {
// Generates random $n$-tuples using elements from a single iterator, where the tuples have
// no repeated elements, and the elements are in ascending order.
#[derive(Clone, Debug)]
$($vis)* struct $struct<I: Iterator> where I::Item: Ord {
xs: RandomBTreeSetsFixedLength<I>,
}
impl<I: Iterator> Iterator for $struct<I> where I::Item: Ord {
type Item = $out_t;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let mut elements = self.xs.next().unwrap().into_iter();
Some(($(((elements.next().unwrap(), $i).0)),*))
}
}
// Generates random $n$-tuples using elements from a single iterator, where the tuples have
// no repeated elements, and the elements are in ascending order.
//
// The input iterator must generate at least `len` distinct elements; otherwise, this
// iterator will hang.
//
// $$
// P((x\_i)\_{i=0}^{n-1}) = n!\prod\_{i=0}^{n-1}P(x\_i).
// $$
//
// The above formula assumes that the tuple is valid, \emph{i.e.} its elements are strictly
// increasing. The probability of an invalid tuple is zero.
//
// `xs` must be infinite.
//
// # Examples
// See [here](self#random_ordered_unique_quadruples).
#[inline]
$($vis)* fn $fn<I: Iterator>(xs: I) -> $struct<I>
where
I::Item: Ord,
{
$struct {
xs: random_b_tree_sets_fixed_length($k, xs),
}
}
}
}
/// Generates random pairs using elements from a single iterator, where the first element is not
/// equal to the second.
#[derive(Clone, Debug)]
pub struct RandomUniquePairs<I: Iterator>
where
I::Item: Eq,
{
xs: I,
}
impl<I: Iterator> Iterator for RandomUniquePairs<I>
where
I::Item: Eq,
{
type Item = (I::Item, I::Item);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let mut out_0 = None;
let out_1;
loop {
let x = self.xs.next().unwrap();
if let Some(out_0) = out_0.as_ref() {
if x != *out_0 {
out_1 = x;
break;
}
} else {
out_0 = Some(x);
}
}
Some((out_0.unwrap(), out_1))
}
}
/// Generates random pairs using elements from a single iterator, where the two elements of each
/// pair are unequal.
///
/// The input iterator must generate at least two distinct elements; otherwise, this iterator will
/// hang.
///
/// `xs` must be infinite.
#[inline]
pub const fn random_unique_pairs<I: Iterator>(xs: I) -> RandomUniquePairs<I>
where
I::Item: Eq,
{
RandomUniquePairs { xs }
}
/// Defines random unique tuple generators.
///
/// Malachite provides [`random_unique_pairs`], but you can also define `random_unique_triples`,
/// `random_unique_quadruples`, and so on, in your program using the code below.
///
/// See usage examples [here](self#random_unique_quadruples).
///
/// ```
/// use malachite_base::random_unique_tuples;
/// use std::collections::HashMap;
/// use std::hash::Hash;
///
/// random_unique_tuples!(
/// (pub(crate)),
/// RandomOrderedUniqueTriples,
/// 3,
/// (I::Item, I::Item, I::Item),
/// random_unique_triples,
/// [0, 1, 2]
/// );
/// random_unique_tuples!(
/// (pub(crate)),
/// RandomOrderedUniqueQuadruples,
/// 4,
/// (I::Item, I::Item, I::Item, I::Item),
/// random_unique_quadruples,
/// [0, 1, 2, 3]
/// );
/// random_unique_tuples!(
/// (pub(crate)),
/// RandomOrderedUniqueQuintuples,
/// 5,
/// (I::Item, I::Item, I::Item, I::Item, I::Item),
/// random_unique_quintuples,
/// [0, 1, 2, 3, 4]
/// );
/// random_unique_tuples!(
/// (pub(crate)),
/// RandomOrderedUniqueSextuples,
/// 6,
/// (I::Item, I::Item, I::Item, I::Item, I::Item, I::Item),
/// random_unique_sextuples,
/// [0, 1, 2, 3, 4, 5]
/// );
/// random_unique_tuples!(
/// (pub(crate)),
/// RandomOrderedUniqueSeptuples,
/// 7,
/// (
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item
/// ),
/// random_unique_septuples,
/// [0, 1, 2, 3, 4, 5, 6]
/// );
/// random_unique_tuples!(
/// (pub(crate)),
/// RandomOrderedUniqueOctuples,
/// 8,
/// (
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item,
/// I::Item
/// ),
/// random_unique_octuples,
/// [0, 1, 2, 3, 4, 5, 6, 7]
/// );
/// ```
#[macro_export]
macro_rules! random_unique_tuples {
(
($($vis:tt)*),
$struct: ident,
$k: expr,
$out_t: ty,
$fn: ident,
[$($i: tt),*]
) => {
#[derive(Clone, Debug)]
$($vis)* struct $struct<I: Iterator> where I::Item: Eq + Hash {
xs: I,
}
impl<I: Iterator> Iterator for $struct<I> where I::Item: Eq + Hash {
type Item = $out_t;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let mut xs_to_indices = HashMap::with_capacity($k);
let mut i = 0;
while i < $k {
xs_to_indices
.entry(self.xs.next().unwrap())
.or_insert_with(|| {
i += 1;
i - 1
});
}
let mut out = ($((None, $i).0),*);
for (x, i) in xs_to_indices {
match i {
$($i => {out.$i = Some(x)},)*
_ => {}
}
}
Some(($(out.$i.unwrap()),*))
}
}
#[inline]
$($vis)* fn $fn<I: Iterator>(xs: I) -> $struct<I> where I::Item: Eq + Hash,
{
$struct { xs }
}
}
}
| 412 | 0.771655 | 1 | 0.771655 | game-dev | MEDIA | 0.436131 | game-dev | 0.842132 | 1 | 0.842132 |
danielkrupinski/Osiris | 2,081 | Source/UI/Panorama/Tabs/VisualsTab/ViewmodelModPreviewPanel.h | #pragma once
template <typename HookContext>
class ViewmodelModPreviewPanel {
public:
using RawType = cs2::CUI_Item3dPanel;
ViewmodelModPreviewPanel(HookContext& hookContext, cs2::CUI_Item3dPanel* item3dPanel) noexcept
: hookContext{hookContext}
, item3dPanel{item3dPanel}
{
}
void setupPreviewModel() const
{
auto&& previewPanel = panel();
if (hookContext.template make<EntitySystem>().getEntityFromHandle2(state().previewWeaponHandle)) {
state().hadPreviewWeaponHandle = true;
if (state().recreatedPreviewWeapon) {
previewPanel.template as<UiItem3dPanel>().startWeaponLookAt();
state().recreatedPreviewWeapon = false;
}
return;
}
auto&& portraitWorld = previewPanel.portraitWorld();
if (state().hadPreviewWeaponHandle && portraitWorld.isMapLoaded()) {
previewPanel.template as<UiItem3dPanel>().createItem(17293822569129771516ull);
state().hadPreviewWeaponHandle = false;
state().recreatedPreviewWeapon = true;
}
state().previewWeaponHandle = portraitWorld.findPreviewWeapon().baseEntity().handle();
}
void setFov() const
{
panel().setFov(fovForPreview());
}
private:
[[nodiscard]] decltype(auto) panel() const
{
return hookContext.template make<Ui3dPanel>(item3dPanel);
}
[[nodiscard]] float fovForPreview() const
{
auto&& viewmodelMod = hookContext.template make<ViewmodelMod>();
if (viewmodelMod.fovModificationActive())
return viewmodelMod.viewmodelFov();
return viewmodelFovFromConVar();
}
[[nodiscard]] float viewmodelFovFromConVar() const
{
return GET_CONVAR_VALUE(cs2::viewmodel_fov).value_or(viewmodel_mod_params::kPreviewFallbackFov);
}
[[nodiscard]] auto& state() const
{
return hookContext.panoramaGuiState().viewmodelModPreviewPanelState;
}
HookContext& hookContext;
cs2::CUI_Item3dPanel* item3dPanel;
};
| 412 | 0.813012 | 1 | 0.813012 | game-dev | MEDIA | 0.535043 | game-dev | 0.629819 | 1 | 0.629819 |
ACGaming/UniversalTweaks | 2,018 | src/main/java/mod/acgaming/universaltweaks/tweaks/misc/narrator/mixin/UTNarratorMixin.java | package mod.acgaming.universaltweaks.tweaks.misc.narrator.mixin;
import net.minecraft.client.gui.chat.NarratorChatListener;
import net.minecraft.util.text.ChatType;
import net.minecraft.util.text.ITextComponent;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.mojang.text2speech.Narrator;
import com.mojang.text2speech.NarratorDummy;
import mod.acgaming.universaltweaks.config.UTConfigTweaks;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(NarratorChatListener.class)
public class UTNarratorMixin
{
/**
* @author WaitingIdly
* @reason disable the initialization of the narrator and the narrator thread by redirecting to use {@link NarratorDummy}
*/
@WrapOperation(method = "<init>", at = @At(value = "INVOKE", target = "Lcom/mojang/text2speech/Narrator;getNarrator()Lcom/mojang/text2speech/Narrator;", remap = false))
private Narrator utUseDummyNarrator(Operation<Narrator> original)
{
if (!UTConfigTweaks.MISC.utDisableNarratorToggle) return original.call();
return new NarratorDummy();
}
/**
* @author ACGaming
* @reason short circuit making the narrator say something
*/
@Inject(method = "say", at = @At("HEAD"), cancellable = true)
public void utNarratorSay(ChatType chatTypeIn, ITextComponent message, CallbackInfo ci)
{
if (UTConfigTweaks.MISC.utDisableNarratorToggle) ci.cancel();
}
/**
* @author ACGaming
* @reason short circuit making the narrator announce the mode (active/inactive)
*/
@Inject(method = "announceMode", at = @At("HEAD"), cancellable = true)
public void utNarratorAnnounceMode(int p_193641_1_, CallbackInfo ci)
{
if (UTConfigTweaks.MISC.utDisableNarratorToggle) ci.cancel();
}
} | 412 | 0.670448 | 1 | 0.670448 | game-dev | MEDIA | 0.896854 | game-dev | 0.689041 | 1 | 0.689041 |
randovania/randovania | 2,699 | test/games/prime_hunters/generator/test_prime_hunters_base_patches_factory.py | from __future__ import annotations
import dataclasses
from unittest.mock import MagicMock
from randovania.games.prime_hunters.generator.base_patches_factory import HuntersBasePatchesFactory
from randovania.games.prime_hunters.layout.force_field_configuration import LayoutForceFieldRequirement
def test_force_field_assignment_for_configuration_all_missile(
prime_hunters_game_description, prime_hunters_configuration
):
# Setup
factory = HuntersBasePatchesFactory()
force_field_configuration = prime_hunters_configuration.force_field_configuration
configuration = dataclasses.replace(
prime_hunters_configuration,
force_field_configuration=dataclasses.replace(
force_field_configuration,
force_field_requirement=dict.fromkeys(
force_field_configuration.force_field_requirement.keys(), LayoutForceFieldRequirement.MISSILE
),
),
)
rng = MagicMock()
# Run
results = factory.create_game_specific(configuration, prime_hunters_game_description, rng)
# Assert
assert list(results.keys()) == ["force_fields"]
associated_requirements = list(results["force_fields"].values())
assert associated_requirements == [LayoutForceFieldRequirement.MISSILE.value] * len(
force_field_configuration.force_field_requirement
)
def test_force_field_assignment_for_configuration_all_random(
prime_hunters_game_description, prime_hunters_configuration
):
# Setup
factory = HuntersBasePatchesFactory()
force_field_configuration = prime_hunters_configuration.force_field_configuration
configuration = dataclasses.replace(
prime_hunters_configuration,
force_field_configuration=force_field_configuration.with_full_random(),
)
requirements = [
LayoutForceFieldRequirement.JUDICATOR.value,
LayoutForceFieldRequirement.IMPERIALIST.value,
LayoutForceFieldRequirement.SHOCK_COIL.value,
]
requirements = requirements * len(force_field_configuration.force_field_requirement)
choices = [
LayoutForceFieldRequirement.JUDICATOR,
LayoutForceFieldRequirement.IMPERIALIST,
LayoutForceFieldRequirement.SHOCK_COIL,
]
rng = MagicMock()
rng.choice.side_effect = choices * len(force_field_configuration.force_field_requirement)
# Run
results = factory.create_game_specific(configuration, prime_hunters_game_description, rng)
# Assert
assert list(results.keys()) == ["force_fields"]
associated_requirements = list(results["force_fields"].values())
assert associated_requirements == requirements[: len(force_field_configuration.force_field_requirement)]
| 412 | 0.684789 | 1 | 0.684789 | game-dev | MEDIA | 0.645702 | game-dev,testing-qa | 0.702345 | 1 | 0.702345 |
redruin1/factorio-draftsman | 3,125 | draftsman/classes/spatial_like.py | # spatiallike.py
from draftsman.classes.collision_set import CollisionSet
from draftsman.classes.vector import Vector
from draftsman.utils import AABB
from abc import ABCMeta, abstractmethod
import copy
from typing import Optional
class SpatialLike(metaclass=ABCMeta):
"""
Abstract class that provides the necessary methods so that an object that
can be added to a :py:class:`~draftsman.classes.spatialhashmap.SpatialHashMap`.
"""
@property
@abstractmethod
def position(self) -> Vector: # pragma: no coverage
"""
Position of the object, expressed in local space. Local space can be
either global space (if the EntityLike exists in a Blueprint at a root
level) or local to it's parent Group.
"""
pass
@property
@abstractmethod
def global_position(self) -> Vector: # pragma: no coverage
"""
Position of the object, expressed in global space (world space). The sum
position of this object and all of its parent's positions combined.
"""
pass
@property
@abstractmethod
def collision_set(self) -> Optional[CollisionSet]: # pragma: no coverage
"""
Set of :py:class:`.CollisionShape` where the Entity's position acts as
their origin.
"""
pass
@property
@abstractmethod
def collision_mask(self) -> set[str]: # pragma: no coverage
"""
A set of strings representing the collision layers that this object
collides with.
"""
pass
def get_world_bounding_box(self) -> Optional[AABB]:
"""
Gets the world-space coordinates AABB that completely encompasses the
:py:attr:`.collision_set` of this :py:class:`.SpatialLike`. Returns
``None`` if the collision set of the target object is unknown.
"""
# `collision_set` may be None in the case where we're working with an
# unknown entity
if self.collision_set is None:
return None
# Get the (local) Axis-aligned bounding box
bounding_box = self.collision_set.get_bounding_box()
# Offset the bounding box by the global position of the SpatialLike to
# get the world-space box
if bounding_box is not None:
bounding_box.top_left[0] += self.global_position.x
bounding_box.top_left[1] += self.global_position.y
bounding_box.bot_right[0] += self.global_position.x
bounding_box.bot_right[1] += self.global_position.y
return bounding_box
def get_world_collision_set(self) -> CollisionSet:
"""
Get's the world-space coordinate :py:class:`.CollisionSet` of the object,
AKA the collection of all shapes that this EntityLike interacts with.
:returns: A copy of this objects :py:class:`.CollisionSet` with the
correct world-space location.
"""
# TODO: check if there's a way to not have to copy this
return CollisionSet(
copy.deepcopy(self.collision_set.shapes), self.global_position._data
)
| 412 | 0.87218 | 1 | 0.87218 | game-dev | MEDIA | 0.288345 | game-dev | 0.841867 | 1 | 0.841867 |
GarageGames/Torque3D | 16,676 | Engine/lib/bullet/src/BulletDynamics/Dynamics/btRigidBody.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btRigidBody.h"
#include "BulletCollision/CollisionShapes/btConvexShape.h"
#include "LinearMath/btMinMax.h"
#include "LinearMath/btTransformUtil.h"
#include "LinearMath/btMotionState.h"
#include "BulletDynamics/ConstraintSolver/btTypedConstraint.h"
#include "LinearMath/btSerializer.h"
//'temporarily' global variables
btScalar gDeactivationTime = btScalar(2.);
bool gDisableDeactivation = false;
static int uniqueId = 0;
btRigidBody::btRigidBody(const btRigidBody::btRigidBodyConstructionInfo& constructionInfo)
{
setupRigidBody(constructionInfo);
}
btRigidBody::btRigidBody(btScalar mass, btMotionState *motionState, btCollisionShape *collisionShape, const btVector3 &localInertia)
{
btRigidBodyConstructionInfo cinfo(mass,motionState,collisionShape,localInertia);
setupRigidBody(cinfo);
}
void btRigidBody::setupRigidBody(const btRigidBody::btRigidBodyConstructionInfo& constructionInfo)
{
m_internalType=CO_RIGID_BODY;
m_linearVelocity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
m_angularVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
m_angularFactor.setValue(1,1,1);
m_linearFactor.setValue(1,1,1);
m_gravity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
m_gravity_acceleration.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
m_totalForce.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
m_totalTorque.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)),
setDamping(constructionInfo.m_linearDamping, constructionInfo.m_angularDamping);
m_linearSleepingThreshold = constructionInfo.m_linearSleepingThreshold;
m_angularSleepingThreshold = constructionInfo.m_angularSleepingThreshold;
m_optionalMotionState = constructionInfo.m_motionState;
m_contactSolverType = 0;
m_frictionSolverType = 0;
m_additionalDamping = constructionInfo.m_additionalDamping;
m_additionalDampingFactor = constructionInfo.m_additionalDampingFactor;
m_additionalLinearDampingThresholdSqr = constructionInfo.m_additionalLinearDampingThresholdSqr;
m_additionalAngularDampingThresholdSqr = constructionInfo.m_additionalAngularDampingThresholdSqr;
m_additionalAngularDampingFactor = constructionInfo.m_additionalAngularDampingFactor;
if (m_optionalMotionState)
{
m_optionalMotionState->getWorldTransform(m_worldTransform);
} else
{
m_worldTransform = constructionInfo.m_startWorldTransform;
}
m_interpolationWorldTransform = m_worldTransform;
m_interpolationLinearVelocity.setValue(0,0,0);
m_interpolationAngularVelocity.setValue(0,0,0);
//moved to btCollisionObject
m_friction = constructionInfo.m_friction;
m_rollingFriction = constructionInfo.m_rollingFriction;
m_spinningFriction = constructionInfo.m_spinningFriction;
m_restitution = constructionInfo.m_restitution;
setCollisionShape( constructionInfo.m_collisionShape );
m_debugBodyId = uniqueId++;
setMassProps(constructionInfo.m_mass, constructionInfo.m_localInertia);
updateInertiaTensor();
m_rigidbodyFlags = BT_ENABLE_GYROSCOPIC_FORCE_IMPLICIT_BODY;
m_deltaLinearVelocity.setZero();
m_deltaAngularVelocity.setZero();
m_invMass = m_inverseMass*m_linearFactor;
m_pushVelocity.setZero();
m_turnVelocity.setZero();
}
void btRigidBody::predictIntegratedTransform(btScalar timeStep,btTransform& predictedTransform)
{
btTransformUtil::integrateTransform(m_worldTransform,m_linearVelocity,m_angularVelocity,timeStep,predictedTransform);
}
void btRigidBody::saveKinematicState(btScalar timeStep)
{
//todo: clamp to some (user definable) safe minimum timestep, to limit maximum angular/linear velocities
if (timeStep != btScalar(0.))
{
//if we use motionstate to synchronize world transforms, get the new kinematic/animated world transform
if (getMotionState())
getMotionState()->getWorldTransform(m_worldTransform);
btVector3 linVel,angVel;
btTransformUtil::calculateVelocity(m_interpolationWorldTransform,m_worldTransform,timeStep,m_linearVelocity,m_angularVelocity);
m_interpolationLinearVelocity = m_linearVelocity;
m_interpolationAngularVelocity = m_angularVelocity;
m_interpolationWorldTransform = m_worldTransform;
//printf("angular = %f %f %f\n",m_angularVelocity.getX(),m_angularVelocity.getY(),m_angularVelocity.getZ());
}
}
void btRigidBody::getAabb(btVector3& aabbMin,btVector3& aabbMax) const
{
getCollisionShape()->getAabb(m_worldTransform,aabbMin,aabbMax);
}
void btRigidBody::setGravity(const btVector3& acceleration)
{
if (m_inverseMass != btScalar(0.0))
{
m_gravity = acceleration * (btScalar(1.0) / m_inverseMass);
}
m_gravity_acceleration = acceleration;
}
void btRigidBody::setDamping(btScalar lin_damping, btScalar ang_damping)
{
m_linearDamping = btClamped(lin_damping, (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
m_angularDamping = btClamped(ang_damping, (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
}
///applyDamping damps the velocity, using the given m_linearDamping and m_angularDamping
void btRigidBody::applyDamping(btScalar timeStep)
{
//On new damping: see discussion/issue report here: http://code.google.com/p/bullet/issues/detail?id=74
//todo: do some performance comparisons (but other parts of the engine are probably bottleneck anyway
//#define USE_OLD_DAMPING_METHOD 1
#ifdef USE_OLD_DAMPING_METHOD
m_linearVelocity *= GEN_clamped((btScalar(1.) - timeStep * m_linearDamping), (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
m_angularVelocity *= GEN_clamped((btScalar(1.) - timeStep * m_angularDamping), (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
#else
m_linearVelocity *= btPow(btScalar(1)-m_linearDamping, timeStep);
m_angularVelocity *= btPow(btScalar(1)-m_angularDamping, timeStep);
#endif
if (m_additionalDamping)
{
//Additional damping can help avoiding lowpass jitter motion, help stability for ragdolls etc.
//Such damping is undesirable, so once the overall simulation quality of the rigid body dynamics system has improved, this should become obsolete
if ((m_angularVelocity.length2() < m_additionalAngularDampingThresholdSqr) &&
(m_linearVelocity.length2() < m_additionalLinearDampingThresholdSqr))
{
m_angularVelocity *= m_additionalDampingFactor;
m_linearVelocity *= m_additionalDampingFactor;
}
btScalar speed = m_linearVelocity.length();
if (speed < m_linearDamping)
{
btScalar dampVel = btScalar(0.005);
if (speed > dampVel)
{
btVector3 dir = m_linearVelocity.normalized();
m_linearVelocity -= dir * dampVel;
} else
{
m_linearVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
}
}
btScalar angSpeed = m_angularVelocity.length();
if (angSpeed < m_angularDamping)
{
btScalar angDampVel = btScalar(0.005);
if (angSpeed > angDampVel)
{
btVector3 dir = m_angularVelocity.normalized();
m_angularVelocity -= dir * angDampVel;
} else
{
m_angularVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
}
}
}
}
void btRigidBody::applyGravity()
{
if (isStaticOrKinematicObject())
return;
applyCentralForce(m_gravity);
}
void btRigidBody::proceedToTransform(const btTransform& newTrans)
{
setCenterOfMassTransform( newTrans );
}
void btRigidBody::setMassProps(btScalar mass, const btVector3& inertia)
{
if (mass == btScalar(0.))
{
m_collisionFlags |= btCollisionObject::CF_STATIC_OBJECT;
m_inverseMass = btScalar(0.);
} else
{
m_collisionFlags &= (~btCollisionObject::CF_STATIC_OBJECT);
m_inverseMass = btScalar(1.0) / mass;
}
//Fg = m * a
m_gravity = mass * m_gravity_acceleration;
m_invInertiaLocal.setValue(inertia.x() != btScalar(0.0) ? btScalar(1.0) / inertia.x(): btScalar(0.0),
inertia.y() != btScalar(0.0) ? btScalar(1.0) / inertia.y(): btScalar(0.0),
inertia.z() != btScalar(0.0) ? btScalar(1.0) / inertia.z(): btScalar(0.0));
m_invMass = m_linearFactor*m_inverseMass;
}
void btRigidBody::updateInertiaTensor()
{
m_invInertiaTensorWorld = m_worldTransform.getBasis().scaled(m_invInertiaLocal) * m_worldTransform.getBasis().transpose();
}
btVector3 btRigidBody::getLocalInertia() const
{
btVector3 inertiaLocal;
const btVector3 inertia = m_invInertiaLocal;
inertiaLocal.setValue(inertia.x() != btScalar(0.0) ? btScalar(1.0) / inertia.x() : btScalar(0.0),
inertia.y() != btScalar(0.0) ? btScalar(1.0) / inertia.y() : btScalar(0.0),
inertia.z() != btScalar(0.0) ? btScalar(1.0) / inertia.z() : btScalar(0.0));
return inertiaLocal;
}
inline btVector3 evalEulerEqn(const btVector3& w1, const btVector3& w0, const btVector3& T, const btScalar dt,
const btMatrix3x3 &I)
{
const btVector3 w2 = I*w1 + w1.cross(I*w1)*dt - (T*dt + I*w0);
return w2;
}
inline btMatrix3x3 evalEulerEqnDeriv(const btVector3& w1, const btVector3& w0, const btScalar dt,
const btMatrix3x3 &I)
{
btMatrix3x3 w1x, Iw1x;
const btVector3 Iwi = (I*w1);
w1.getSkewSymmetricMatrix(&w1x[0], &w1x[1], &w1x[2]);
Iwi.getSkewSymmetricMatrix(&Iw1x[0], &Iw1x[1], &Iw1x[2]);
const btMatrix3x3 dfw1 = I + (w1x*I - Iw1x)*dt;
return dfw1;
}
btVector3 btRigidBody::computeGyroscopicForceExplicit(btScalar maxGyroscopicForce) const
{
btVector3 inertiaLocal = getLocalInertia();
btMatrix3x3 inertiaTensorWorld = getWorldTransform().getBasis().scaled(inertiaLocal) * getWorldTransform().getBasis().transpose();
btVector3 tmp = inertiaTensorWorld*getAngularVelocity();
btVector3 gf = getAngularVelocity().cross(tmp);
btScalar l2 = gf.length2();
if (l2>maxGyroscopicForce*maxGyroscopicForce)
{
gf *= btScalar(1.)/btSqrt(l2)*maxGyroscopicForce;
}
return gf;
}
btVector3 btRigidBody::computeGyroscopicImpulseImplicit_Body(btScalar step) const
{
btVector3 idl = getLocalInertia();
btVector3 omega1 = getAngularVelocity();
btQuaternion q = getWorldTransform().getRotation();
// Convert to body coordinates
btVector3 omegab = quatRotate(q.inverse(), omega1);
btMatrix3x3 Ib;
Ib.setValue(idl.x(),0,0,
0,idl.y(),0,
0,0,idl.z());
btVector3 ibo = Ib*omegab;
// Residual vector
btVector3 f = step * omegab.cross(ibo);
btMatrix3x3 skew0;
omegab.getSkewSymmetricMatrix(&skew0[0], &skew0[1], &skew0[2]);
btVector3 om = Ib*omegab;
btMatrix3x3 skew1;
om.getSkewSymmetricMatrix(&skew1[0],&skew1[1],&skew1[2]);
// Jacobian
btMatrix3x3 J = Ib + (skew0*Ib - skew1)*step;
// btMatrix3x3 Jinv = J.inverse();
// btVector3 omega_div = Jinv*f;
btVector3 omega_div = J.solve33(f);
// Single Newton-Raphson update
omegab = omegab - omega_div;//Solve33(J, f);
// Back to world coordinates
btVector3 omega2 = quatRotate(q,omegab);
btVector3 gf = omega2-omega1;
return gf;
}
btVector3 btRigidBody::computeGyroscopicImpulseImplicit_World(btScalar step) const
{
// use full newton-euler equations. common practice to drop the wxIw term. want it for better tumbling behavior.
// calculate using implicit euler step so it's stable.
const btVector3 inertiaLocal = getLocalInertia();
const btVector3 w0 = getAngularVelocity();
btMatrix3x3 I;
I = m_worldTransform.getBasis().scaled(inertiaLocal) *
m_worldTransform.getBasis().transpose();
// use newtons method to find implicit solution for new angular velocity (w')
// f(w') = -(T*step + Iw) + Iw' + w' + w'xIw'*step = 0
// df/dw' = I + 1xIw'*step + w'xI*step
btVector3 w1 = w0;
// one step of newton's method
{
const btVector3 fw = evalEulerEqn(w1, w0, btVector3(0, 0, 0), step, I);
const btMatrix3x3 dfw = evalEulerEqnDeriv(w1, w0, step, I);
btVector3 dw;
dw = dfw.solve33(fw);
//const btMatrix3x3 dfw_inv = dfw.inverse();
//dw = dfw_inv*fw;
w1 -= dw;
}
btVector3 gf = (w1 - w0);
return gf;
}
void btRigidBody::integrateVelocities(btScalar step)
{
if (isStaticOrKinematicObject())
return;
m_linearVelocity += m_totalForce * (m_inverseMass * step);
m_angularVelocity += m_invInertiaTensorWorld * m_totalTorque * step;
#define MAX_ANGVEL SIMD_HALF_PI
/// clamp angular velocity. collision calculations will fail on higher angular velocities
btScalar angvel = m_angularVelocity.length();
if (angvel*step > MAX_ANGVEL)
{
m_angularVelocity *= (MAX_ANGVEL/step) /angvel;
}
}
btQuaternion btRigidBody::getOrientation() const
{
btQuaternion orn;
m_worldTransform.getBasis().getRotation(orn);
return orn;
}
void btRigidBody::setCenterOfMassTransform(const btTransform& xform)
{
if (isKinematicObject())
{
m_interpolationWorldTransform = m_worldTransform;
} else
{
m_interpolationWorldTransform = xform;
}
m_interpolationLinearVelocity = getLinearVelocity();
m_interpolationAngularVelocity = getAngularVelocity();
m_worldTransform = xform;
updateInertiaTensor();
}
void btRigidBody::addConstraintRef(btTypedConstraint* c)
{
///disable collision with the 'other' body
int index = m_constraintRefs.findLinearSearch(c);
//don't add constraints that are already referenced
//btAssert(index == m_constraintRefs.size());
if (index == m_constraintRefs.size())
{
m_constraintRefs.push_back(c);
btCollisionObject* colObjA = &c->getRigidBodyA();
btCollisionObject* colObjB = &c->getRigidBodyB();
if (colObjA == this)
{
colObjA->setIgnoreCollisionCheck(colObjB, true);
}
else
{
colObjB->setIgnoreCollisionCheck(colObjA, true);
}
}
}
void btRigidBody::removeConstraintRef(btTypedConstraint* c)
{
int index = m_constraintRefs.findLinearSearch(c);
//don't remove constraints that are not referenced
if(index < m_constraintRefs.size())
{
m_constraintRefs.remove(c);
btCollisionObject* colObjA = &c->getRigidBodyA();
btCollisionObject* colObjB = &c->getRigidBodyB();
if (colObjA == this)
{
colObjA->setIgnoreCollisionCheck(colObjB, false);
}
else
{
colObjB->setIgnoreCollisionCheck(colObjA, false);
}
}
}
int btRigidBody::calculateSerializeBufferSize() const
{
int sz = sizeof(btRigidBodyData);
return sz;
}
///fills the dataBuffer and returns the struct name (and 0 on failure)
const char* btRigidBody::serialize(void* dataBuffer, class btSerializer* serializer) const
{
btRigidBodyData* rbd = (btRigidBodyData*) dataBuffer;
btCollisionObject::serialize(&rbd->m_collisionObjectData, serializer);
m_invInertiaTensorWorld.serialize(rbd->m_invInertiaTensorWorld);
m_linearVelocity.serialize(rbd->m_linearVelocity);
m_angularVelocity.serialize(rbd->m_angularVelocity);
rbd->m_inverseMass = m_inverseMass;
m_angularFactor.serialize(rbd->m_angularFactor);
m_linearFactor.serialize(rbd->m_linearFactor);
m_gravity.serialize(rbd->m_gravity);
m_gravity_acceleration.serialize(rbd->m_gravity_acceleration);
m_invInertiaLocal.serialize(rbd->m_invInertiaLocal);
m_totalForce.serialize(rbd->m_totalForce);
m_totalTorque.serialize(rbd->m_totalTorque);
rbd->m_linearDamping = m_linearDamping;
rbd->m_angularDamping = m_angularDamping;
rbd->m_additionalDamping = m_additionalDamping;
rbd->m_additionalDampingFactor = m_additionalDampingFactor;
rbd->m_additionalLinearDampingThresholdSqr = m_additionalLinearDampingThresholdSqr;
rbd->m_additionalAngularDampingThresholdSqr = m_additionalAngularDampingThresholdSqr;
rbd->m_additionalAngularDampingFactor = m_additionalAngularDampingFactor;
rbd->m_linearSleepingThreshold=m_linearSleepingThreshold;
rbd->m_angularSleepingThreshold = m_angularSleepingThreshold;
// Fill padding with zeros to appease msan.
#ifdef BT_USE_DOUBLE_PRECISION
memset(rbd->m_padding, 0, sizeof(rbd->m_padding));
#endif
return btRigidBodyDataName;
}
void btRigidBody::serializeSingleObject(class btSerializer* serializer) const
{
btChunk* chunk = serializer->allocate(calculateSerializeBufferSize(),1);
const char* structType = serialize(chunk->m_oldPtr, serializer);
serializer->finalizeChunk(chunk,structType,BT_RIGIDBODY_CODE,(void*)this);
}
| 412 | 0.963961 | 1 | 0.963961 | game-dev | MEDIA | 0.990545 | game-dev | 0.990585 | 1 | 0.990585 |
PCGen/pcgen | 6,763 | code/src/java/pcgen/cdom/facet/EquippedEquipmentFacet.java | /*
* Copyright (c) Thomas Parker, 2009.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
package pcgen.cdom.facet;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
import pcgen.cdom.base.SetFacet;
import pcgen.cdom.enumeration.CharID;
import pcgen.cdom.facet.base.AbstractDataFacet;
import pcgen.cdom.facet.event.DataFacetChangeEvent;
import pcgen.core.Equipment;
import pcgen.output.publish.OutputDB;
/**
* EquippedEquipmentFacet is a Facet that tracks the Equipment that is Equipped
* by a Player Character.
*
*/
public class EquippedEquipmentFacet extends AbstractDataFacet<CharID, Equipment> implements SetFacet<CharID, Equipment>
{
private EquipmentFacet equipmentFacet;
/**
* Triggered ("manually") when the equipped equipment on a Player Character
* has changed. Evaluates all Equipment available to the Player Character
* and places the Equipped Equipment into this EquippedEquipmentFacet.
*
* @param id
* The CharID representing the Player Character for which the
* equipped Equipment should be updated
*/
public void reset(CharID id)
{
Set<Equipment> oldEquipped = (Set<Equipment>) removeCache(id);
Set<Equipment> currentEquipment = equipmentFacet.getSet(id);
Set<Equipment> newEquipped = Collections.newSetFromMap(new IdentityHashMap<>());
setCache(id, newEquipped);
if (oldEquipped != null)
{
// Delete items that the PC no longer has at all
for (Equipment e : oldEquipped)
{
if (!currentEquipment.contains(e))
{
fireDataFacetChangeEvent(id, e, DataFacetChangeEvent.DATA_REMOVED);
}
}
}
for (Equipment e : currentEquipment)
{
if (e.isEquipped())
{
newEquipped.add(e);
// If not old, it's added
if (oldEquipped == null || !oldEquipped.contains(e))
{
fireDataFacetChangeEvent(id, e, DataFacetChangeEvent.DATA_ADDED);
}
}
else
{
// If old, it's removed
if (oldEquipped != null && oldEquipped.contains(e))
{
fireDataFacetChangeEvent(id, e, DataFacetChangeEvent.DATA_REMOVED);
}
}
}
}
/**
* Returns a non-null copy of the Set of Equipment in this
* EquippedEquipmentFacet for the Player Character represented by the given
* CharID. This method returns an empty set if no objects are in this
* EquippedEquipmentFacet for the Player Character identified by the given
* CharID.
*
* This method is value-semantic in that ownership of the returned Set is
* transferred to the class calling this method. Modification of the
* returned Set will not modify this EquippedEquipmentFacet and modification
* of this EquippedEquipmentFacet will not modify the returned Set.
* Modifications to the returned Set will also not modify any future or
* previous objects returned by this (or other) methods on
* EquippedEquipmentFacet. If you wish to modify the information stored in
* this EquippedEquipmentFacet, you must use the add*() and remove*()
* methods of EquippedEquipmentFacet.
*
* @param id
* The CharID representing the Player Character for which the
* items in this EquippedEquipmentFacet should be returned
* @return A non-null copy of the Set of Equipment in this
* EquippedEquipmentFacet for the Player Character represented by
* the given CharID
*/
@Override
public Set<Equipment> getSet(CharID id)
{
Set<Equipment> set = (Set<Equipment>) getCache(id);
if (set == null)
{
return Collections.emptySet();
}
Set<Equipment> returnEquipped = Collections.newSetFromMap(new IdentityHashMap<>());
returnEquipped.addAll(set);
return returnEquipped;
}
/**
* Returns the count of the number of Equipment objects in this
* EquippedEquipmentFacet for the Player Character represented by the given
* CharID.
*
* @param id
* The CharID representing the Player Character for which the
* count of the number of items in this EquippedEquipmentFacet
* should be returned
* @return The count of the number of items in this EquippedEquipmentFacet
* for the Player Character represented by the given CharID
*/
@Override
public int getCount(CharID id)
{
Set<Equipment> set = (Set<Equipment>) getCache(id);
return (set == null) ? 0 : set.size();
}
public void setEquipmentFacet(EquipmentFacet equipmentFacet)
{
this.equipmentFacet = equipmentFacet;
}
/**
* Copies the contents of the EquippedEquipmentFacet from one Player
* Character to another Player Character, based on the given CharIDs
* representing those Player Characters.
*
* This is a method in EquippedEquipmentFacet in order to avoid exposing the
* mutable Map object to other classes. This should not be inlined, as the
* Map is internal information to EquippedEquipmentFacet and should not be
* exposed to other classes.
*
* Note also the copy is a one-time event and no references are maintained
* between the Player Characters represented by the given CharIDs (meaning
* once this copy takes place, any change to the EquippedEquipmentFacet of
* one Player Character will only impact the Player Character where the
* EquippedEquipmentFacet was changed).
*
* @param source
* The CharID representing the Player Character from which the
* information should be copied
* @param copy
* The CharID representing the Player Character to which the
* information should be copied
*/
@Override
public void copyContents(CharID source, CharID copy)
{
Set<Equipment> set = (Set<Equipment>) getCache(source);
if (set != null)
{
Set<Equipment> newEquipped = Collections.newSetFromMap(new IdentityHashMap<>());
newEquipped.addAll(set);
setCache(copy, newEquipped);
}
}
/**
* Remove all entries for a single character.
* @param id The CharID representing the Player Character.
*/
public void removeAll(CharID id)
{
removeCache(id);
}
public void init()
{
OutputDB.register("equipment.equipped", this);
}
}
| 412 | 0.864252 | 1 | 0.864252 | game-dev | MEDIA | 0.93873 | game-dev | 0.786066 | 1 | 0.786066 |
ramokz/phantom-camera | 2,889 | addons/phantom_camera/examples/scripts/3D/player_controller_third_person.gd | extends "player_controller.gd"
@onready var _player_pcam: PhantomCamera3D
@onready var _aim_pcam: PhantomCamera3D
@onready var _player_direction: Node3D = %PlayerDirection
@onready var _ceiling_pcam: PhantomCamera3D
@export var mouse_sensitivity: float = 0.05
@export var min_pitch: float = -89.9
@export var max_pitch: float = 50
@export var min_yaw: float = 0
@export var max_yaw: float = 360
func _ready() -> void:
super()
_player_pcam = owner.get_node("%PlayerPhantomCamera3D")
_aim_pcam = owner.get_node("%PlayerAimPhantomCamera3D")
_ceiling_pcam = owner.get_node("%CeilingPhantomCamera3D")
if _player_pcam.get_follow_mode() == _player_pcam.FollowMode.THIRD_PERSON:
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func _physics_process(delta: float) -> void:
super(delta)
if velocity.length() > 0.2:
var look_direction: Vector2 = Vector2(velocity.z, velocity.x)
_player_direction.rotation.y = look_direction.angle()
func _unhandled_input(event: InputEvent) -> void:
if _player_pcam.get_follow_mode() == _player_pcam.FollowMode.THIRD_PERSON:
var active_pcam: PhantomCamera3D
_set_pcam_rotation(_player_pcam, event)
_set_pcam_rotation(_aim_pcam, event)
if _player_pcam.get_priority() > _aim_pcam.get_priority():
_toggle_aim_pcam(event)
else:
_toggle_aim_pcam(event)
if event is InputEventKey and event.pressed:
if event.keycode == KEY_SPACE:
if _ceiling_pcam.get_priority() < 30 and _player_pcam.is_active():
_ceiling_pcam.set_priority(30)
else:
_ceiling_pcam.set_priority(1)
func _set_pcam_rotation(pcam: PhantomCamera3D, event: InputEvent) -> void:
if event is InputEventMouseMotion:
var pcam_rotation_degrees: Vector3
# Assigns the current 3D rotation of the SpringArm3D node - so it starts off where it is in the editor
pcam_rotation_degrees = pcam.get_third_person_rotation_degrees()
# Change the X rotation
pcam_rotation_degrees.x -= event.relative.y * mouse_sensitivity
# Clamp the rotation in the X axis so it go over or under the target
pcam_rotation_degrees.x = clampf(pcam_rotation_degrees.x, min_pitch, max_pitch)
# Change the Y rotation value
pcam_rotation_degrees.y -= event.relative.x * mouse_sensitivity
# Sets the rotation to fully loop around its target, but witout going below or exceeding 0 and 360 degrees respectively
pcam_rotation_degrees.y = wrapf(pcam_rotation_degrees.y, min_yaw, max_yaw)
# Change the SpringArm3D node's rotation and rotate around its target
pcam.set_third_person_rotation_degrees(pcam_rotation_degrees)
func _toggle_aim_pcam(event: InputEvent) -> void:
if event is InputEventMouseButton \
and event.is_pressed() \
and event.button_index == 2 \
and (_player_pcam.is_active() or _aim_pcam.is_active()):
if _player_pcam.get_priority() > _aim_pcam.get_priority():
_aim_pcam.set_priority(30)
else:
_aim_pcam.set_priority(0)
| 412 | 0.641514 | 1 | 0.641514 | game-dev | MEDIA | 0.567338 | game-dev | 0.890709 | 1 | 0.890709 |
MinecraftModdedClients/Resilience-Client-Source | 1,740 | net/minecraft/entity/monster/EntityCaveSpider.java | package net.minecraft.entity.monster;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.IEntityLivingData;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.World;
public class EntityCaveSpider extends EntitySpider
{
private static final String __OBFID = "CL_00001683";
public EntityCaveSpider(World par1World)
{
super(par1World);
this.setSize(0.7F, 0.5F);
}
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(12.0D);
}
public boolean attackEntityAsMob(Entity par1Entity)
{
if (super.attackEntityAsMob(par1Entity))
{
if (par1Entity instanceof EntityLivingBase)
{
byte var2 = 0;
if (this.worldObj.difficultySetting == EnumDifficulty.NORMAL)
{
var2 = 7;
}
else if (this.worldObj.difficultySetting == EnumDifficulty.HARD)
{
var2 = 15;
}
if (var2 > 0)
{
((EntityLivingBase)par1Entity).addPotionEffect(new PotionEffect(Potion.poison.id, var2 * 20, 0));
}
}
return true;
}
else
{
return false;
}
}
public IEntityLivingData onSpawnWithEgg(IEntityLivingData par1EntityLivingData)
{
return par1EntityLivingData;
}
}
| 412 | 0.620384 | 1 | 0.620384 | game-dev | MEDIA | 0.984095 | game-dev | 0.865416 | 1 | 0.865416 |
Arkania/ArkCORE-NG | 8,796 | src/server/game/AI/CreatureAI.cpp | /*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2011-2016 ArkCORE <http://www.arkania.net/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "CreatureAI.h"
#include "CreatureAIImpl.h"
#include "Creature.h"
#include "World.h"
#include "SpellMgr.h"
#include "Vehicle.h"
#include "Log.h"
#include "MapReference.h"
#include "Player.h"
#include "CreatureTextMgr.h"
//Disable CreatureAI when charmed
void CreatureAI::OnCharmed(bool /*apply*/)
{
//me->IsAIEnabled = !apply;*/
me->NeedChangeAI = true;
me->IsAIEnabled = false;
}
AISpellInfoType* UnitAI::AISpellInfo;
AISpellInfoType* GetAISpellInfo(uint32 i) { return &CreatureAI::AISpellInfo[i]; }
void CreatureAI::Talk(uint8 id, WorldObject const* whisperTarget /*= NULL*/)
{
sCreatureTextMgr->SendChat(me, id, whisperTarget);
}
void CreatureAI::DoZoneInCombat(Creature* creature /*= NULL*/, float maxRangeToNearestTarget /* = 50.0f*/)
{
if (!creature)
creature = me;
if (!creature->CanHaveThreatList())
return;
Map* map = creature->GetMap();
if (!map->IsDungeon()) //use IsDungeon instead of Instanceable, in case battlegrounds will be instantiated
{
TC_LOG_ERROR("misc", "DoZoneInCombat call for map that isn't an instance (creature entry = %d)", creature->GetTypeId() == TYPEID_UNIT ? creature->ToCreature()->GetEntry() : 0);
return;
}
if (!creature->HasReactState(REACT_PASSIVE) && !creature->GetVictim())
{
if (Unit* nearTarget = creature->SelectNearestTarget(maxRangeToNearestTarget))
creature->AI()->AttackStart(nearTarget);
else if (creature->IsSummon())
{
if (Unit* summoner = creature->ToTempSummon()->GetSummoner())
{
Unit* target = summoner->getAttackerForHelper();
if (!target && summoner->CanHaveThreatList() && !summoner->getThreatManager().isThreatListEmpty())
target = summoner->getThreatManager().getHostilTarget();
if (target && (creature->IsFriendlyTo(summoner) || creature->IsHostileTo(target)))
creature->AI()->AttackStart(target);
}
}
}
// Intended duplicated check, the code above this should select a victim
// If it can't find a suitable attack target then we should error out.
if (!creature->HasReactState(REACT_PASSIVE) && !creature->GetVictim())
{
TC_LOG_ERROR("misc", "DoZoneInCombat called for creature that has empty threat list (creature entry = %u)", creature->GetEntry());
return;
}
Map::PlayerList const& playerList = map->GetPlayers();
if (playerList.isEmpty())
return;
for (Map::PlayerList::const_iterator itr = playerList.begin(); itr != playerList.end(); ++itr)
{
if (Player* player = itr->GetSource())
{
if (player->IsGameMaster())
continue;
if (player->IsAlive())
{
creature->SetInCombatWith(player);
player->SetInCombatWith(creature);
creature->AddThreat(player, 0.0f);
}
/* Causes certain things to never leave the threat list (Priest Lightwell, etc):
for (Unit::ControlList::const_iterator itr = player->m_Controlled.begin(); itr != player->m_Controlled.end(); ++itr)
{
creature->SetInCombatWith(*itr);
(*itr)->SetInCombatWith(creature);
creature->AddThreat(*itr, 0.0f);
}*/
}
}
}
// scripts does not take care about MoveInLineOfSight loops
// MoveInLineOfSight can be called inside another MoveInLineOfSight and cause stack overflow
void CreatureAI::MoveInLineOfSight_Safe(Unit* who)
{
if (m_MoveInLineOfSight_locked == true)
return;
m_MoveInLineOfSight_locked = true;
MoveInLineOfSight(who);
m_MoveInLineOfSight_locked = false;
}
void CreatureAI::MoveInLineOfSight(Unit* who)
{
if (me->GetVictim())
return;
if (me->GetCreatureType() == CREATURE_TYPE_NON_COMBAT_PET) // non-combat pets should just stand there and look good;)
return;
if (me->CanStartAttack(who, false))
AttackStart(who);
//else if (who->GetVictim() && me->IsFriendlyTo(who)
// && me->IsWithinDistInMap(who, sWorld->getIntConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS))
// && me->CanStartAttack(who->GetVictim(), true)) /// @todo if we use true, it will not attack it when it arrives
// me->GetMotionMaster()->MoveChase(who->GetVictim());
}
void CreatureAI::CreatureMoveInLineOfSight(Unit* who)
{
TC_LOG_DEBUG("entities.unit", "Creature %u MoveInLineOfSight of %u.", who->GetEntry(), me->GetEntry());
}
void CreatureAI::EnterEvadeMode()
{
if (!_EnterEvadeMode())
return;
TC_LOG_DEBUG("entities.unit", "Creature %u enters evade mode.", me->GetEntry());
if (!me->GetVehicle()) // otherwise me will be in evade mode forever
{
if (Unit* owner = me->GetCharmerOrOwner())
{
me->GetMotionMaster()->Clear(false);
me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle(), MOTION_SLOT_ACTIVE);
}
else
{
// Required to prevent attacking creatures that are evading and cause them to reenter combat
// Does not apply to MoveFollow
me->AddUnitState(UNIT_STATE_EVADE);
me->GetMotionMaster()->MoveTargetedHome();
}
}
Reset();
if (me->IsVehicle()) // use the same sequence of addtoworld, aireset may remove all summons!
me->GetVehicleKit()->Reset(true);
}
/*void CreatureAI::AttackedBy(Unit* attacker)
{
if (!me->GetVictim())
AttackStart(attacker);
}*/
void CreatureAI::SetGazeOn(Unit* target)
{
if (me->IsValidAttackTarget(target))
{
AttackStart(target);
me->SetReactState(REACT_PASSIVE);
}
}
bool CreatureAI::UpdateVictimWithGaze()
{
if (!me->IsInCombat())
return false;
if (me->HasReactState(REACT_PASSIVE))
{
if (me->GetVictim())
return true;
else
me->SetReactState(REACT_AGGRESSIVE);
}
if (Unit* victim = me->SelectVictim())
AttackStart(victim);
return me->GetVictim() != nullptr;
}
bool CreatureAI::UpdateVictim()
{
if (!me->IsInCombat())
return false;
if (!me->HasReactState(REACT_PASSIVE))
{
if (Unit* victim = me->SelectVictim())
AttackStart(victim);
return me->GetVictim() != nullptr;
}
else if (me->getThreatManager().isThreatListEmpty())
{
EnterEvadeMode();
return false;
}
return true;
}
bool CreatureAI::_EnterEvadeMode()
{
if (!me->IsAlive())
return false;
// don't remove vehicle auras, passengers aren't supposed to drop off the vehicle
// don't remove clone caster on evade (to be verified)
me->RemoveAllAurasExceptType(SPELL_AURA_CONTROL_VEHICLE, SPELL_AURA_CLONE_CASTER);
// sometimes bosses stuck in combat?
me->DeleteThreatList();
me->CombatStop(true);
me->LoadCreaturesAddon();
me->SetLootRecipient(NULL);
me->ResetPlayerDamageReq();
me->SetLastDamagedTime(0);
if (me->IsInEvadeMode())
return false;
return true;
}
Creature* CreatureAI::DoSummon(uint32 entry, const Position& pos, uint32 despawnTime, TempSummonType summonType)
{
return me->SummonCreature(entry, pos, summonType, despawnTime);
}
Creature* CreatureAI::DoSummon(uint32 entry, WorldObject* obj, float radius, uint32 despawnTime, TempSummonType summonType)
{
Position pos = obj->GetRandomNearPosition(radius);
return me->SummonCreature(entry, pos, summonType, despawnTime);
}
Creature* CreatureAI::DoSummonFlyer(uint32 entry, WorldObject* obj, float flightZ, float radius, uint32 despawnTime, TempSummonType summonType)
{
Position pos = obj->GetRandomNearPosition(radius);
pos.m_positionZ += flightZ;
return me->SummonCreature(entry, pos, summonType, despawnTime);
}
| 412 | 0.97138 | 1 | 0.97138 | game-dev | MEDIA | 0.928072 | game-dev | 0.997782 | 1 | 0.997782 |
amethyst/rustrogueliketutorial | 2,921 | chapter-71-logging/src/map_builders/door_placement.rs | use super::{MetaMapBuilder, BuilderMap, TileType };
use rltk::RandomNumberGenerator;
pub struct DoorPlacement {}
impl MetaMapBuilder for DoorPlacement {
#[allow(dead_code)]
fn build_map(&mut self, rng: &mut rltk::RandomNumberGenerator, build_data : &mut BuilderMap) {
self.doors(rng, build_data);
}
}
impl DoorPlacement {
#[allow(dead_code)]
pub fn new() -> Box<DoorPlacement> {
Box::new(DoorPlacement{ })
}
fn door_possible(&self, build_data : &mut BuilderMap, idx : usize) -> bool {
let mut blocked = false;
for spawn in build_data.spawn_list.iter() {
if spawn.0 == idx { blocked = true; }
}
if blocked { return false; }
let x = (idx % build_data.map.width as usize) as i32;
let y = (idx / build_data.map.width as usize) as i32;
// Check for east-west door possibility
if build_data.map.tiles[idx] == TileType::Floor &&
(x > 1 && build_data.map.tiles[idx-1] == TileType::Floor) &&
(x < build_data.map.width-2 && build_data.map.tiles[idx+1] == TileType::Floor) &&
(y > 1 && build_data.map.tiles[idx - build_data.map.width as usize] == TileType::Wall) &&
(y < build_data.map.height-2 && build_data.map.tiles[idx + build_data.map.width as usize] == TileType::Wall)
{
return true;
}
// Check for north-south door possibility
if build_data.map.tiles[idx] == TileType::Floor &&
(x > 1 && build_data.map.tiles[idx-1] == TileType::Wall) &&
(x < build_data.map.width-2 && build_data.map.tiles[idx+1] == TileType::Wall) &&
(y > 1 && build_data.map.tiles[idx - build_data.map.width as usize] == TileType::Floor) &&
(y < build_data.map.height-2 && build_data.map.tiles[idx + build_data.map.width as usize] == TileType::Floor)
{
return true;
}
false
}
fn doors(&mut self, rng : &mut RandomNumberGenerator, build_data : &mut BuilderMap) {
if let Some(halls_original) = &build_data.corridors {
let halls = halls_original.clone(); // To avoid nested borrowing
for hall in halls.iter() {
if hall.len() > 2 { // We aren't interested in tiny corridors
if self.door_possible(build_data, hall[0]) {
build_data.spawn_list.push((hall[0], "Door".to_string()));
}
}
}
} else {
// There are no corridors - scan for possible places
let tiles = build_data.map.tiles.clone();
for (i, tile) in tiles.iter().enumerate() {
if *tile == TileType::Floor && self.door_possible(build_data, i) && rng.roll_dice(1,3)==1 {
build_data.spawn_list.push((i, "Door".to_string()));
}
}
}
}
}
| 412 | 0.888363 | 1 | 0.888363 | game-dev | MEDIA | 0.921091 | game-dev | 0.931168 | 1 | 0.931168 |
dieletro/tinjecttelegram_delphi | 2,916 | v1.3.3/TInjectTelegram/Packages/TInjectTelegramBotAPI.dpk | package TInjectTelegramBotAPI;
{$R *.res}
{$R *.dcr}
{$IFDEF IMPLICITBUILDING This IFDEF should not be used by users}
{$ALIGN 8}
{$ASSERTIONS ON}
{$BOOLEVAL OFF}
{$DEBUGINFO OFF}
{$EXTENDEDSYNTAX ON}
{$IMPORTEDDATA ON}
{$IOCHECKS ON}
{$LOCALSYMBOLS ON}
{$LONGSTRINGS ON}
{$OPENSTRINGS ON}
{$OPTIMIZATION OFF}
{$OVERFLOWCHECKS OFF}
{$RANGECHECKS OFF}
{$REFERENCEINFO ON}
{$SAFEDIVIDE OFF}
{$STACKFRAMES ON}
{$TYPEDADDRESS OFF}
{$VARSTRINGCHECKS ON}
{$WRITEABLECONST OFF}
{$MINENUMSIZE 1}
{$IMAGEBASE $400000}
{$DEFINE DEBUG}
{$ENDIF IMPLICITBUILDING}
{$IMPLICITBUILD ON}
requires
rtl,
RESTComponents,
vcl,
IndySystem,
IndyProtocols,
IndyCore,
FireDAC,
FireDACCommonDriver,
FireDACCommon,
CrossUrl;
contains
TinjectTelegram.Core in '..\Source\TinjectTelegram.Core.pas',
TInjectTelegram.Base in '..\Source\TInjectTelegram.Base.pas',
TinjectTelegram.Ext.Sessions in '..\Source\TinjectTelegram.Ext.Sessions.pas',
TinjectTelegram.Helpers in '..\Source\TinjectTelegram.Helpers.pas',
TinjectTelegram.Logger.Old in '..\Source\TinjectTelegram.Logger.Old.pas',
TinjectTelegram.Logger in '..\Source\TinjectTelegram.Logger.pas',
TinjectTelegram.Receiver.Base in '..\Source\TinjectTelegram.Receiver.Base.pas',
TinjectTelegram.Receiver.Console in '..\Source\TinjectTelegram.Receiver.Console.pas',
TinjectTelegram.Receiver.Service in '..\Source\TinjectTelegram.Receiver.Service.pas',
TinjectTelegram.Receiver.UI in '..\Source\TinjectTelegram.Receiver.UI.pas',
TinjectTelegram.Types.Enums in '..\Source\TinjectTelegram.Types.Enums.pas',
TinjectTelegram.Types.Impl in '..\Source\TinjectTelegram.Types.Impl.pas',
TinjectTelegram.Types.InlineQueryResults in '..\Source\TinjectTelegram.Types.InlineQueryResults.pas',
TinjectTelegram.Types.InputMessageContents in '..\Source\TinjectTelegram.Types.InputMessageContents.pas',
TinjectTelegram.Types in '..\Source\TinjectTelegram.Types.pas',
TinjectTelegram.Types.Passport in '..\Source\TinjectTelegram.Types.Passport.pas',
TinjectTelegram.Types.ReplyMarkups in '..\Source\TinjectTelegram.Types.ReplyMarkups.pas',
TinjectTelegram.UpdateParser in '..\Source\TinjectTelegram.UpdateParser.pas',
TinjectTelegram.Utils.Json in '..\Source\TinjectTelegram.Utils.Json.pas',
TinjectTelegram.Ph in '..\Source\TinjectTelegram.Ph.pas',
TinjectTelegram.Ph.Types in '..\Source\TinjectTelegram.Ph.Types.pas',
TinjectTelegram.RegisterIDE in '..\Source\TinjectTelegram.RegisterIDE.pas',
TinjectTelegram.Emoji in '..\Source\TinjectTelegram.Emoji.pas',
TinjectTelegram.Bot.Impl in '..\Source\TinjectTelegram.Bot.Impl.pas',
TinjectTelegram.Bot in '..\Source\TinjectTelegram.Bot.pas',
TInjectTelegram.Bot.Chat in '..\Source\TInjectTelegram.Bot.Chat.pas',
TInjectTelegram.Bot.Manager in '..\Source\TInjectTelegram.Bot.Manager.pas',
TinjectTelegram.Receiver.Manager.Base in '..\Source\TinjectTelegram.Receiver.Manager.Base.pas';
end.
| 412 | 0.56589 | 1 | 0.56589 | game-dev | MEDIA | 0.568078 | game-dev | 0.690486 | 1 | 0.690486 |
shit-ware/IW4 | 20,509 | maps/so_ac130_co_hunted.gsc | #include common_scripts\utility;
#include maps\_utility;
#include maps\_ac130;
#include maps\co_ac130_code;
#include maps\_hud_util;
#include maps\_specialops;
CONST_specop_difficulty = 50; // % of enemies seeking player's location, increased difficulty for spec op mission
CONST_laser_hint_timeout = 25; // seconds
main()
{
level.so_compass_zoom = "far";
set_custom_gameskill_func( maps\_gameskill::solo_player_in_coop_gameskill_settings );
// special ops character selection using dvar "start"
level.specops_character_selector = "";
if ( IsSplitScreen() || ( GetDvar( "coop" ) == "1" ) )
{
level.specops_character_selector = getdvar( "coop_start" );
}
default_start( ::start_specop );
set_default_start( "so" );
add_start( "so", ::start_specop, "[so] -> spec op gameplay" );
level.default_goalradius = 2048;
level.default_goalheight = 512;
setDvarIfUninitialized( "no_respawn", "1" );
setDvarIfUninitialized( "do_saves", "0" );
battlechatter_off( "allies" );
battlechatter_off( "axis" );
// lets the ac130 specific friendly fire warnings play uninterrupted .
friendlyfire_warnings_off();
precacheLevelStuff();
vehicleScripts();
if ( level.console )
level.hint_text_size = 1.6;
else
level.hint_text_size = 1.2;
precacheShader( "dpad_laser_designator" );
precacheShader( "waypoint_targetneutral" );
precacheShader( "waypoint_checkpoint_neutral_a" );
precacheShader( "waypoint_checkpoint_neutral_b" );
precacheShader( "waypoint_checkpoint_neutral_c" );
precacheShader( "waypoint_checkpoint_neutral_d" );
precacheShader( "waypoint_checkpoint_neutral_e" );
// Checkpoint A:
precachestring( &"CO_HUNTED_TIME_TILL_CHECKPOINT_A" );
// Checkpoint B:
precachestring( &"CO_HUNTED_TIME_TILL_CHECKPOINT_B" );
// Checkpoint C:
precachestring( &"CO_HUNTED_TIME_TILL_CHECKPOINT_C" );
// Checkpoint D:
precachestring( &"CO_HUNTED_TIME_TILL_CHECKPOINT_D" );
// Reach targe in:
precachestring( &"SO_AC130_HUNTED_SPECOP_TIMER" );
// Cross the bridge in:
precachestring( &"CO_HUNTED_TIME_TILL_EXPLOSION" );
// Mission failed. Enemy destroyed the bridge.
precachestring( &"CO_HUNTED_TIMER_EXPIRED" );
// Mission failed. You ran out of time.
precachestring( &"SO_AC130_CO_HUNTED_TIMER_EXPIRED_SPECOP" );
// Cross the bridge to safety before it is destroyed.
precachestring( &"CO_HUNTED_OBJ_CROSS_BRIDGE" );
// Reach the checkpoint at the barn.
precachestring( &"CO_HUNTED_OBJ_REACH_BARN" );
// Checkpoint A time expired.
precachestring( &"CO_HUNTED_MISSED_CHECKPOINT_A" );
// Checkpoint B time expired.
precachestring( &"CO_HUNTED_MISSED_CHECKPOINT_B" );
// Checkpoint C time expired.
precachestring( &"CO_HUNTED_MISSED_CHECKPOINT_C" );
// Checkpoint D time expired.
precachestring( &"CO_HUNTED_MISSED_CHECKPOINT_D" );
// Press ^3[{weapnext}]^7 to cycle through weapons.
precachestring( &"AC130_HINT_CYCLE_WEAPONS" );
// Press ^3[{+actionslot 4}]^7 to use toggle laser targeting device.
precachestring( &"CO_HUNTED_HINT_LASER" );
maps\_truck::main( "vehicle_pickup_roobars" );
level.weaponClipModels = [];
level.weaponClipModels[ 0 ] = "weapon_ak47_clip";
level.weaponClipModels[ 1 ] = "weapon_m16_clip";
// player 1 is ac130 gunner in coop games
//level.ac130gunner = level.player;
maps\co_hunted_fx::main();
maps\co_hunted_precache::main();
maps\_load::main();
maps\_compass::setupMiniMap( "compass_map_hunted" );
array_thread( getentarray( "noprone", "targetname" ), ::noprone );
// Press ^3[{weapnext}]^7 to cycle through weapons.
add_hint_string( "ac130_changed_weapons", &"AC130_HINT_CYCLE_WEAPONS", ::ShouldBreakAC130HintPrint );
// Press ^3[{+actionslot 4}]^7 to use toggle laser targeting device.
add_hint_string( "laser_hint", &"CO_HUNTED_HINT_LASER", ::ShouldBreakLaserHintPrint );
}
gameplay_logic( gametype )
{
if( !isdefined( gametype ) )
gametype = "default";
flag_init( "timer_expired" );
flag_init( "specop_challenge_completed" );
thread fade_challenge_in();
array_call( GetSpawnerTeamArray( "allies" ), ::delete );
array_call( GetAIArray("allies"), ::delete );
enemies = getspawnerteamarray( "axis" );
array_thread( enemies, ::add_spawn_function, ::set_thermal_LOD );
array_thread( enemies, ::add_spawn_function, ::kill_after_time, 60 );
maps\co_ac130_anim::main();
maps\co_ac130_snd::main();
level.ac130_flood_respawn = true;
maps\_nightvision::main( level.players );
maps\_ac130::init();// pops up the menu and sets who level.ac130gunner is
thread maps\co_hunted_amb::main();
if ( level.player == level.ac130gunner )
level.ground_player = level.player2;
else
level.ground_player = level.player;
level.ground_player thread add_beacon_effect();
level.ground_player thread hint_timeout();
level.ground_player ent_flag_init( "player_used_laser" );
level thread laser_targeting_device( level.ground_player );
level.ground_player thread display_hint( "laser_hint" );
// this removes the green arrow pointing to the ac130.
level.ground_player.noFriendlyHudIcon = true;
level.ground_player set_vision_set_player( "hunted", 0 );
move_ac130 = getentarray( "move_ac130", "targetname" );
array_thread( move_ac130, ::move_ac130_think );
level.ac130gunner laserForceOn();
thread ac130_change_weapon_hint();
wait 0.1;
flag_clear( "coop_revive" );
flag_set( "clear_to_engage" );
battlechatter_on( "allies" );
battlechatter_on( "axis" );
music_loop( "so_ac130_co_hunted_music", 167 );
// Start
saveGame( "levelstart", &"AUTOSAVE_LEVELSTART", "whatever", true );
thread open_all_doors();
thread enemy_monitor();
thread timer_start();
thread objective( gametype );
delete_vehicle_nodes = getentarray( "delete_vehicle", "script_noteworthy" );
array_thread( delete_vehicle_nodes, ::delete_vehicle_think );
thread move_enemies_to_closest_goal_radius( gametype );
thread initial_ac130_move();
}
// ****** Starts ****** //
start_ac130()
{
thread gameplay_logic( "default" );
}
start_specop()
{
thread gameplay_logic( "specop" );
flag_wait( "leaving_crash_site" );
// These enable the dialogue for the AC130 to begin
flag_set( "clear_to_engage" );
flag_set( "allow_context_sensative_dialog" );
}
initial_ac130_move()
{
level endon( "ac130_reposition" );
wait 5;
ent = getent( "initial_ac130_location", "targetname" );
thread movePlaneToPoint( ent.origin );
}
move_enemies_to_closest_goal_radius( gametype )
{
level endon( "specop_challenge_completed" );
goals = getentarray( "enemy_goal_radius", "targetname" );
level.current_goal = getclosest( level.ground_player.origin, goals );
level.hunter_enemies = [];
spawners = getspawnerarray();
array_thread( spawners, ::add_spawn_function, ::create_hunter_enemy );
if ( gametype == "specop" )
move_deadlier_hunters_to_new_goal( level.current_goal );
else
move_hunters_to_new_goal( level.current_goal );
while ( 1 )
{
closest_goal = getclosest( level.ground_player.origin, goals );
//only goal enemies to one of the players and assume they stay together
if ( level.current_goal != closest_goal )
{
level.current_goal = closest_goal;
if ( gametype == "specop" )
move_deadlier_hunters_to_new_goal( closest_goal );
else
move_hunters_to_new_goal( closest_goal );
}
wait 1;
}
}
create_hunter_enemy()
{
if ( self.team != "axis" )
return;
level.hunter_enemies[ self.unique_id ] = self;
self setgoalpos( level.current_goal.origin );
self waittill( "death" );
level.hunter_enemies[ self.unique_id ] = undefined;
}
move_hunters_to_new_goal( closest_goal )
{
waittillframeend;
//waittillframeend because you may be in the part of the frame that is before
//the script has received the "death" notify but after the AI has died.
foreach ( enemy in level.hunter_enemies )
enemy setgoalpos( closest_goal.origin );
}
move_deadlier_hunters_to_new_goal( closest_goal )
{
waittillframeend;
//Sent half the enemies to player, and the other half to set goal,
foreach ( enemy in level.hunter_enemies )
{
if ( RandomInt( 100 ) < CONST_specop_difficulty )
enemy setgoalpos( closest_goal.origin );
else
enemy setgoalentity( level.ground_player );
}
}
ShouldBreakAC130HintPrint()
{
return flag( "player_changed_weapons" );
}
hint_timeout()
{
//self is ground player
self.hint_timeout = CONST_laser_hint_timeout; // seconds
while ( self.hint_timeout > -1 )
{
self.hint_timeout--;
wait 1;
}
}
ShouldBreakLaserHintPrint()
{
if( !isdefined( level.ground_player ) )
return false;
else if( isdefined( level.ground_player.hint_timeout ) && level.ground_player.hint_timeout <= 0 )
return true;
else
return level.ground_player ent_flag( "player_used_laser" );
}
ac130_change_weapon_hint()
{
wait 12;
if ( !flag( "player_changed_weapons" ) )
level.ac130gunner thread display_hint( "ac130_changed_weapons" );
// Press ^3[{weapnext}]^7 to cycle through weapons.
//hintPrint_coop( &"AC130_HINT_CYCLE_WEAPONS" );
}
hintPrint_coop( string )
{
hint = hint_create( string, true, 0.8 );
wait 5;
hint hint_delete();
}
delete_vehicle_think()
{
while ( true )
{
self waittill( "trigger", vehicle );
vehicle delete();
}
}
move_ac130_think()
{
self waittill( "trigger" );
point = ( getent( self.target, "targetname" ) ).origin;
thread movePlaneToPoint( point );
}
open_all_doors()
{
array_thread( getentarray( "doorknob", "targetname" ), ::doorknob );
door = getent( "farmer_front_door", "targetname" );
door rotateyaw( 95, 0.7, 0.5, 0.2 );
door connectpaths();
gate = getent( "creek_gate", "targetname" );
gate hunted_style_door_open( "door_gate_chainlink_slow_open" );
}
doorknob()
{
ent = getent( self.target, "targetname" );
self linkto( ent );
}
enemy_monitor()
{
flag_wait( "leaving_crash_site" );
level.enemy_force = [];
level.enemy_force[ 0 ] = spawnstruct();
level.enemy_force[ 0 ].name = "lone_barn_spawners";
level.enemy_force[ 0 ].type = "spawners";
level.enemy_force[ 1 ] = spawnstruct();
level.enemy_force[ 1 ].name = "down_road_spawners";
level.enemy_force[ 1 ].type = "spawners";
level.enemy_force[ 2 ] = spawnstruct();
level.enemy_force[ 2 ].name = "first_field_heli_drop";
level.enemy_force[ 2 ].type = "multi_use_vehicle";
level.enemy_force[ 3 ] = spawnstruct();
level.enemy_force[ 3 ].name = "second_field_heli_drop";
level.enemy_force[ 3 ].type = "multi_use_vehicle";
level.enemy_force[ 4 ] = spawnstruct();
level.enemy_force[ 4 ].name = "pickup_rightside_bridge";
level.enemy_force[ 4 ].type = "one_use_vehicle";
level.enemy_force[ 4 ].drove = false;
level.enemy_force[ 5 ] = spawnstruct();
level.enemy_force[ 5 ].name = "pickup_leftside_starting_bridge";
level.enemy_force[ 5 ].type = "one_use_vehicle";
level.enemy_force[ 5 ].drove = false;
//respawns
level.enemy_force[ 6 ] = spawnstruct();
level.enemy_force[ 6 ].name = "farmers_house_spawners";
level.enemy_force[ 6 ].type = "spawners";
level.enemy_force = array_randomize( level.enemy_force );
// make sure farmers_house guys always spawn in first.
farmers_house_struct = spawnstruct();
farmers_house_struct.name = "farmers_house_spawners";
farmers_house_struct.type = "spawners";
level.enemy_force = array_insert( level.enemy_force, farmers_house_struct ,0 );
level.selection = 0;
thread enemy_monitor_loop();
flag_wait( "leaving_creek" );
level.enemy_force = [];
level.enemy_force[ 0 ] = spawnstruct();
level.enemy_force[ 0 ].name = "back_left_side_spawners";
level.enemy_force[ 0 ].type = "spawners";
level.enemy_force[ 1 ] = spawnstruct();
level.enemy_force[ 1 ].name = "front_left_side_spawners";
level.enemy_force[ 1 ].type = "spawners";
level.enemy_force[ 2 ] = spawnstruct();
level.enemy_force[ 2 ].name = "pickup_leftside_fields";
level.enemy_force[ 2 ].type = "one_use_vehicle";
level.enemy_force[ 2 ].drove = false;
level.enemy_force[ 3 ] = spawnstruct();
level.enemy_force[ 3 ].name = "cellar_field_heli_drop";
level.enemy_force[ 3 ].type = "multi_use_vehicle";
level.enemy_force = array_randomize( level.enemy_force );
// make sure cellar guys always spawn in first.
cellar_struct = spawnstruct();
cellar_struct.name = "cellar_house_spawners";
cellar_struct.type = "spawners";
level.enemy_force = array_insert( level.enemy_force, cellar_struct ,0 );
level.selection = 0;
flag_wait( "at_cellar" );
level.enemy_force = [];
level.enemy_force[ 0 ] = spawnstruct();
level.enemy_force[ 0 ].name = "work_shop_spawners";
level.enemy_force[ 0 ].type = "spawners";
level.enemy_force[ 1 ] = spawnstruct();
level.enemy_force[ 1 ].name = "garage_spawners";
level.enemy_force[ 1 ].type = "spawners";
level.enemy_force[ 2 ] = spawnstruct();
level.enemy_force[ 2 ].name = "shed_spawners";
level.enemy_force[ 2 ].type = "spawners";
level.enemy_force[ 3 ] = spawnstruct();
level.enemy_force[ 3 ].name = "over_creek_heli_drop";
level.enemy_force[ 3 ].type = "multi_use_vehicle";
level.enemy_force = array_randomize( level.enemy_force );
level.selection = 0;
spawn_enemy_group();
spawn_enemy_group();
flag_wait( "exit_work_shops" );
level.enemy_force = [];
level.enemy_force[ 0 ] = spawnstruct();
level.enemy_force[ 0 ].name = "pickup_leftside_greenhouses";
level.enemy_force[ 0 ].type = "one_use_vehicle";
level.enemy_force[ 0 ].drove = false;
level.enemy_force[ 1 ] = spawnstruct();
level.enemy_force[ 1 ].name = "windmill_field_heli_drop";
level.enemy_force[ 1 ].type = "multi_use_vehicle";
level.enemy_force[ 2 ] = spawnstruct();
level.enemy_force[ 2 ].name = "white_fence_heli_drop";
level.enemy_force[ 2 ].type = "multi_use_vehicle";
level.enemy_force[ 3 ] = spawnstruct();
level.enemy_force[ 3 ].name = "barn_spawners";
level.enemy_force[ 3 ].type = "spawners";
level.enemy_force[ 4 ] = spawnstruct();
level.enemy_force[ 4 ].name = "pickup_leftside_bridge";
level.enemy_force[ 4 ].type = "one_use_vehicle";
level.enemy_force[ 4 ].drove = false;
level.enemy_force[ 5 ] = spawnstruct();
level.enemy_force[ 5 ].name = "pickup_from_barn";
level.enemy_force[ 5 ].type = "one_use_vehicle";
level.enemy_force[ 5 ].drove = false;
level.enemy_force = array_randomize( level.enemy_force );
level.selection = 0;
spawn_enemy_group();
spawn_enemy_group();
flag_wait( "mid_wind_mill_field" );
level.enemy_force = [];
level.enemy_force[ 0 ] = spawnstruct();
level.enemy_force[ 0 ].name = "green_house_heli_drop";
level.enemy_force[ 0 ].type = "one_use_vehicle";
level.enemy_force[ 0 ].drove = false;
level.enemy_force[ 1 ] = spawnstruct();
level.enemy_force[ 1 ].name = "silo_spawners";
level.enemy_force[ 1 ].type = "spawners";
level.enemy_force[ 2 ] = spawnstruct();
level.enemy_force[ 2 ].name = "barn_spawners";
level.enemy_force[ 2 ].type = "spawners";
level.enemy_force[ 3 ] = spawnstruct();
level.enemy_force[ 3 ].name = "gas_station_spawners";
level.enemy_force[ 3 ].type = "spawners";
level.enemy_force = array_randomize( level.enemy_force );
level.selection = 0;
spawn_enemy_group();
spawn_enemy_group();
}
spawn_enemy_group()
{
if ( level.selection >= level.enemy_force.size )
{
if ( getdvar( "no_respawn", 1 ) == "1" )
return;
else
level.selection = 0;
}
s_name = level.enemy_force[ level.selection ].name;
s_number = level.selection;
level.selection++ ;
if ( level.enemy_force[ s_number ].type == "one_use_vehicle" )
{
if ( level.enemy_force[ s_number ].drove )
return;
vehicle = maps\_vehicle::spawn_vehicle_from_targetname_and_drive( s_name );
level.enemy_force[ s_number ].drove = true;
return;
}
if ( level.enemy_force[ s_number ].type == "multi_use_vehicle" )
{
vehicle = maps\_vehicle::spawn_vehicle_from_targetname_and_drive( s_name );
return;
}
enemy_spawners = getentarray( s_name, "targetname" );
for ( i = 0 ; i < enemy_spawners.size ; i++ )
guy = enemy_spawners[ i ] spawn_ai();
wait 1;// make sure the spawning is done before checking to see how many are spawned
}
enemy_monitor_loop()
{
while ( true )
{
enemies = getaiarray( "axis" );
total = enemies.size;
roaming = total;
for ( i = 0 ; i < enemies.size ; i++ )
if ( isdefined( enemies[ i ].script_noteworthy ) )
if ( enemies[ i ].script_noteworthy == "defender" )
roaming -- ;
println( " roaming/total: " + roaming + "/" + total );
if ( roaming < 13 )
spawn_enemy_group();
wait 1;
}
}
timer_start( gametype )
{
dialogue_line = undefined;
iSeconds = undefined;
switch( level.gameSkill )
{
case 0:// easy
case 1:// regular
level.challenge_time_limit = 210; //3:30 min
break;
case 2:// hardened
level.challenge_time_limit = 300; //5:00 min
break;
case 3:// veteran
level.challenge_time_limit = 420; //7:00 min
break;
}
assert( isdefined( level.challenge_time_limit ) );
// Causes the player monitor to short circuit and not allow them to toggle them on and off.
foreach ( player in level.players )
player.so_infohud_toggle_state = "none";
enable_challenge_timer( "leaving_crash_site", "specop_challenge_completed" );
// Offset the time so it doesn't interfere with the ac130 hud
level.ac130player.hud_so_timer_msg.x -= 50;
level.ac130player.hud_so_timer_time.x -= 50;
if ( IsSplitScreen() )
{
level.ac130player.hud_so_timer_msg.y = 0;
level.ac130player.hud_so_timer_time.y = 0;
}
}
player_death_effect()
{
player = level.player;
playfx( level._effect[ "player_death_explosion" ], player.origin );
earthquake( 1, 1, level.player.origin, 100 );
}
objective( gametype )
{
level endon( "special_op_terminated" );
assert( gametype == "specop" && is_coop() );
checkpoint_ent = undefined;
flag_name = undefined;
volume = undefined;
switch( level.gameskill )
{
case 2:
objective_add( 1, "current", &"SO_AC130_CO_HUNTED_OBJ_HARDENED" );
checkpoint_ent = getent( "checkpoint_c", "targetname" );
flag_name = "checkpoint_c";
break;
case 3:
objective_add( 1, "current", &"SO_AC130_CO_HUNTED_OBJ_VETERAN" );
checkpoint_ent = getent( "checkpoint_barn", "targetname" );
flag_name = "checkpoint_barn";
break;
default:
objective_add( 1, "current", &"SO_AC130_CO_HUNTED_OBJ_REGULAR" );
checkpoint_ent = getent( "checkpoint_b", "targetname" );
flag_name = "checkpoint_b";
break;
}
objective_position( 1, checkpoint_ent.origin );
flag_wait( flag_name );
objective_state( 1, "done" );
level notify( "specop_challenge_completed" );
flag_set( "specop_challenge_completed" );
array_call( GetAIArray(), ::delete );
flag_clear( "allow_context_sensative_dialog" );
thread fade_challenge_out();
}
threeD_objective_hint( shader, destroyer_msg )
{
self.icon = NewHudElem();
//self.icon SetShader( "waypoint_targetneutral", 1, 1 );
self.icon SetShader( shader, 1, 1 );
self.icon.alpha = .5;
self.icon.color = ( 1, 1, 1 );
//comm_center.icon SetTargetEnt( comm_center );
origin = self getOrigin();
self.icon.x = origin[ 0 ];
self.icon.y = origin[ 1 ];
self.icon.z = origin[ 2 ];
self.icon SetWayPoint( false, true );
if ( isdefined( destroyer_msg ) )
{
level waittill( destroyer_msg );
self.icon destroy();
}
}
kill_after_time( time )
{
wait( time );
if ( isalive( self ) )
self kill();
}
set_thermal_LOD()
{
self ThermalDrawEnable();
}
draw_ground_player_facing()
{
color = ( 1, 1, 1 );
while ( 1 )
{
forward = AnglesToForward( level.ground_player.angles );
forwardfar = vector_multiply( forward, 200 );
forwardclose = vector_multiply( forward, 100 );
start = forwardclose + level.ground_player.origin;
end = forwardfar + level.ground_player.origin;
draw_arrow_ac130( start, end, color );
wait .05;
}
}
draw_arrow_ac130( start, end, color )
{
pts = [];
angles = vectortoangles( start - end );
right = anglestoright( angles );
forward = anglestoforward( angles );
dist = distance( start, end );
arrow = [];
range = 0.5;
arrow[ 0 ] = start;
arrow[ 1 ] = start + vector_multiply( right, dist * ( range ) ) + vector_multiply( forward, dist * - 0.2 );
arrow[ 2 ] = end;
arrow[ 3 ] = start + vector_multiply( right, dist * ( -1 * range ) ) + vector_multiply( forward, dist * - 0.2 );
line( arrow[ 0 ], arrow[ 2 ], color, 1.0 );
line( arrow[ 2 ], arrow[ 1 ], color, 1.0 );
line( arrow[ 2 ], arrow[ 3 ], color, 1.0 );
}
noprone()
{
while ( true )
{
self waittill( "trigger", player );
if ( !isdefined( player ) )
continue;
if ( !isplayer( player ) )
continue;
while ( player IsTouching( self ) )
{
player AllowProne( false );
wait( 0.05 );
}
player AllowProne( true );
}
} | 412 | 0.948556 | 1 | 0.948556 | game-dev | MEDIA | 0.998155 | game-dev | 0.958513 | 1 | 0.958513 |
Kirin0v0/ARPG-Demo | 1,750 | Assets/Scripts/Player/StateMachine/Base/PlayerStateMachine.cs | using System.Collections.Generic;
using Framework.Common.StateMachine;
using UnityEngine;
namespace Player.StateMachine.Base
{
public abstract class PlayerStateMachine<TState> : StateMachine<TState>, IPlayerState
where TState : MonoBehaviour, IState, IPlayerState
{
public bool ControlRootMotionBySelf()
{
if (CurrentState)
{
return CurrentState.ControlRootMotionBySelf();
}
return false;
}
public (Vector3? deltaPosition, Quaternion? deltaRotation, bool useCharacterController)
CalculateRootMotionDelta(Animator animator)
{
if (CurrentState)
{
return CurrentState.CalculateRootMotionDelta(animator);
}
return (null, null, false);
}
public void HandleAnimatorIK(Animator animator)
{
if (CurrentState)
{
CurrentState.HandleAnimatorIK(animator);
}
}
public void ShowStateName(string stateName)
{
if (CurrentState)
{
CurrentState.ShowStateName(stateName);
}
}
public void ShowTransition(PlayerStateTransition transition)
{
if (CurrentState)
{
CurrentState.ShowTransition(transition);
}
}
public string GetStateName()
{
return CurrentState ? CurrentState.GetStateName() : "";
}
public List<PlayerStateTransition> GetStateTransitions()
{
return CurrentState ? CurrentState.GetStateTransitions() : new List<PlayerStateTransition>();
}
}
} | 412 | 0.940785 | 1 | 0.940785 | game-dev | MEDIA | 0.947957 | game-dev | 0.722026 | 1 | 0.722026 |
Slimefun/Slimefun4 | 9,466 | src/main/java/io/github/thebusybiscuit/slimefun4/implementation/items/electric/machines/AutoBrewer.java | package io.github.thebusybiscuit.slimefun4.implementation.items.electric.machines;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import io.github.thebusybiscuit.slimefun4.implementation.Slimefun;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionType;
import io.github.bakedlibs.dough.inventory.InvUtils;
import io.github.thebusybiscuit.slimefun4.api.items.ItemGroup;
import io.github.thebusybiscuit.slimefun4.api.items.SlimefunItemStack;
import io.github.thebusybiscuit.slimefun4.api.recipes.RecipeType;
import io.github.thebusybiscuit.slimefun4.core.attributes.NotHopperable;
import io.github.thebusybiscuit.slimefun4.utils.compatibility.VersionedPotionType;
import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.abstractItems.AContainer;
import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.abstractItems.MachineRecipe;
import me.mrCookieSlime.Slimefun.api.inventory.BlockMenu;
/**
*
* The {@link AutoBrewer} machine with most if not all potion recipes.
*
* @author Linox
*
*/
public class AutoBrewer extends AContainer implements NotHopperable {
private static final Map<Material, PotionType> potionRecipes = new HashMap<>();
private static final Map<PotionType, PotionType> fermentations = new HashMap<>();
static {
potionRecipes.put(Material.SUGAR, VersionedPotionType.SWIFTNESS);
potionRecipes.put(Material.RABBIT_FOOT, VersionedPotionType.LEAPING);
potionRecipes.put(Material.BLAZE_POWDER, PotionType.STRENGTH);
potionRecipes.put(Material.GLISTERING_MELON_SLICE, VersionedPotionType.HEALING);
potionRecipes.put(Material.SPIDER_EYE, PotionType.POISON);
potionRecipes.put(Material.GHAST_TEAR, VersionedPotionType.REGENERATION);
potionRecipes.put(Material.MAGMA_CREAM, PotionType.FIRE_RESISTANCE);
potionRecipes.put(Material.PUFFERFISH, PotionType.WATER_BREATHING);
potionRecipes.put(Material.GOLDEN_CARROT, PotionType.NIGHT_VISION);
potionRecipes.put(Material.TURTLE_HELMET, PotionType.TURTLE_MASTER);
potionRecipes.put(Material.PHANTOM_MEMBRANE, PotionType.SLOW_FALLING);
fermentations.put(VersionedPotionType.SWIFTNESS, PotionType.SLOWNESS);
fermentations.put(VersionedPotionType.LEAPING, PotionType.SLOWNESS);
fermentations.put(VersionedPotionType.HEALING, VersionedPotionType.HARMING);
fermentations.put(PotionType.POISON, VersionedPotionType.HARMING);
fermentations.put(PotionType.NIGHT_VISION, PotionType.INVISIBILITY);
}
@ParametersAreNonnullByDefault
public AutoBrewer(ItemGroup itemGroup, SlimefunItemStack item, RecipeType recipeType, ItemStack[] recipe) {
super(itemGroup, item, recipeType, recipe);
}
@Override
protected @Nullable MachineRecipe findNextRecipe(BlockMenu menu) {
ItemStack input1 = menu.getItemInSlot(getInputSlots()[0]);
ItemStack input2 = menu.getItemInSlot(getInputSlots()[1]);
if (input1 == null || input2 == null) {
return null;
}
if (isPotion(input1.getType()) || isPotion(input2.getType())) {
boolean isPotionInFirstSlot = isPotion(input1.getType());
ItemStack ingredient = isPotionInFirstSlot ? input2 : input1;
// Reject any named items
if (ingredient.hasItemMeta()) {
return null;
}
ItemStack potionItem = isPotionInFirstSlot ? input1 : input2;
PotionMeta potion = (PotionMeta) potionItem.getItemMeta();
ItemStack output = brew(ingredient.getType(), potionItem.getType(), potion);
if (output == null) {
return null;
}
output.setItemMeta(potion);
if (!InvUtils.fits(menu.toInventory(), output, getOutputSlots())) {
return null;
}
for (int slot : getInputSlots()) {
menu.consumeItem(slot);
}
return new MachineRecipe(30, new ItemStack[] { input1, input2 }, new ItemStack[] { output });
} else {
return null;
}
}
@ParametersAreNonnullByDefault
private @Nullable ItemStack brew(Material input, Material potionType, PotionMeta potion) {
if (Slimefun.getMinecraftVersion().isBefore(20,2)) {
return brewPreBasePotionType(input, potionType, potion);
}
PotionType type = potion.getBasePotionType();
if (type == PotionType.WATER) {
if (input == Material.FERMENTED_SPIDER_EYE) {
potion.setBasePotionType(PotionType.WEAKNESS);
return new ItemStack(potionType);
} else if (input == Material.NETHER_WART) {
potion.setBasePotionType(PotionType.AWKWARD);
return new ItemStack(potionType);
} else if (potionType == Material.POTION && input == Material.GUNPOWDER) {
return new ItemStack(Material.SPLASH_POTION);
} else if (potionType == Material.SPLASH_POTION && input == Material.DRAGON_BREATH) {
return new ItemStack(Material.LINGERING_POTION);
}
} else if (input == Material.FERMENTED_SPIDER_EYE) {
PotionType fermented = fermentations.get(type);
if (fermented != null) {
potion.setBasePotionType(fermented);
return new ItemStack(potionType);
}
} else if (input == Material.REDSTONE && type.isExtendable() && !type.isUpgradeable()) {
// Fixes #3390 - Potions can only be either extended or upgraded. Not both.
potion.setBasePotionType(type);
return new ItemStack(potionType);
} else if (input == Material.GLOWSTONE_DUST && type.isUpgradeable() && !type.isExtendable()) {
// Fixes #3390 - Potions can only be either extended or upgraded. Not both.
potion.setBasePotionType(type);
return new ItemStack(potionType);
} else if (type == PotionType.AWKWARD) {
PotionType potionRecipe = potionRecipes.get(input);
if (potionRecipe != null) {
potion.setBasePotionType(potionRecipe);
return new ItemStack(potionType);
}
}
return null;
}
@ParametersAreNonnullByDefault
@SuppressWarnings("deprecration")
private ItemStack brewPreBasePotionType(Material input, Material potionType, PotionMeta potion) {
PotionData data = potion.getBasePotionData();
PotionType type = data.getType();
if (type == PotionType.WATER) {
if (input == Material.FERMENTED_SPIDER_EYE) {
potion.setBasePotionData(new PotionData(PotionType.WEAKNESS, false, false));
return new ItemStack(potionType);
} else if (input == Material.NETHER_WART) {
potion.setBasePotionData(new PotionData(PotionType.AWKWARD, false, false));
return new ItemStack(potionType);
} else if (potionType == Material.POTION && input == Material.GUNPOWDER) {
return new ItemStack(Material.SPLASH_POTION);
} else if (potionType == Material.SPLASH_POTION && input == Material.DRAGON_BREATH) {
return new ItemStack(Material.LINGERING_POTION);
}
} else if (input == Material.FERMENTED_SPIDER_EYE) {
PotionType fermented = fermentations.get(type);
if (fermented != null) {
potion.setBasePotionData(new PotionData(fermented, data.isExtended(), data.isUpgraded()));
return new ItemStack(potionType);
}
} else if (input == Material.REDSTONE && type.isExtendable() && !data.isUpgraded()) {
// Fixes #3390 - Potions can only be either extended or upgraded. Not both.
potion.setBasePotionData(new PotionData(type, true, false));
return new ItemStack(potionType);
} else if (input == Material.GLOWSTONE_DUST && type.isUpgradeable() && !data.isExtended()) {
// Fixes #3390 - Potions can only be either extended or upgraded. Not both.
potion.setBasePotionData(new PotionData(type, false, true));
return new ItemStack(potionType);
} else if (type == PotionType.AWKWARD) {
PotionType potionRecipe = potionRecipes.get(input);
if (potionRecipe != null) {
potion.setBasePotionData(new PotionData(potionRecipe, false, false));
return new ItemStack(potionType);
}
}
return null;
}
/**
* Checks whether a given {@link Material} is a valid Potion material.
*
* @param mat
* The {@link Material} to check
*
* @return Whether this {@link Material} is a valid potion
*/
private boolean isPotion(@Nonnull Material mat) {
return mat == Material.POTION || mat == Material.SPLASH_POTION || mat == Material.LINGERING_POTION;
}
@Override
public @Nonnull ItemStack getProgressBar() {
return new ItemStack(Material.FISHING_ROD);
}
@Override
public @Nonnull String getMachineIdentifier() {
return "AUTO_BREWER";
}
}
| 412 | 0.734235 | 1 | 0.734235 | game-dev | MEDIA | 0.911392 | game-dev | 0.785962 | 1 | 0.785962 |
ProjectIgnis/CardScripts | 1,690 | rush/c160320014.lua | --放浪の勇者 フリード
--Freed the Brave Wanderer (Rush)
--Scripted by YoshiDuels
local s,id=GetID()
function s.initial_effect(c)
--Destroy 1 face-up monster on the field
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:SetCost(s.cost)
e1:SetTarget(s.target)
e1:SetOperation(s.operation)
c:RegisterEffect(e1)
end
function s.cfilter(c)
return c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsAbleToDeckOrExtraAsCost()
end
function s.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.cfilter,tp,LOCATION_GRAVE,0,2,nil) end
end
function s.filter(c,atk)
return c:IsMonster() and c:IsFaceup() and c:GetAttack()>atk and not c:IsMaximumModeSide()
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
local dg=Duel.GetMatchingGroup(s.filter,tp,LOCATION_MZONE,LOCATION_MZONE,nil,e:GetHandler():GetAttack())
if chk==0 then return #dg>0 end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,dg,1,0,0)
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.cfilter,tp,LOCATION_GRAVE,0,2,2,nil)
Duel.HintSelection(g)
Duel.SendtoDeck(g,nil,SEQ_DECKBOTTOM,REASON_EFFECT)
local g2=Duel.GetOperatedGroup():Filter(Card.IsLocation,nil,LOCATION_DECK)
if #g2>1 then
Duel.SortDeckbottom(tp,tp,#g2)
end
--Effect
local dg=Duel.GetMatchingGroup(s.filter,tp,LOCATION_MZONE,LOCATION_MZONE,nil,e:GetHandler():GetAttack())
if #dg>0 then
local sg=dg:Select(tp,1,1,nil)
sg=sg:AddMaximumCheck()
Duel.HintSelection(sg)
Duel.Destroy(sg,REASON_EFFECT)
end
end | 412 | 0.910498 | 1 | 0.910498 | game-dev | MEDIA | 0.989059 | game-dev | 0.964673 | 1 | 0.964673 |
Keeperorowner/NagramX_Fork | 2,969 | TMessagesProj/jni/voip/webrtc/base/time/time_override.h | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_TIME_TIME_OVERRIDE_H_
#define BASE_TIME_TIME_OVERRIDE_H_
#include "base/base_export.h"
#include "base/time/time.h"
namespace base {
using TimeNowFunction = decltype(&Time::Now);
using TimeTicksNowFunction = decltype(&TimeTicks::Now);
using ThreadTicksNowFunction = decltype(&ThreadTicks::Now);
// Time overrides should be used with extreme caution. Discuss with //base/time
// OWNERS before adding a new one.
namespace subtle {
// Override the return value of Time::Now and Time::NowFromSystemTime /
// TimeTicks::Now / ThreadTicks::Now to emulate time, e.g. for tests or to
// modify progression of time. Note that the override should be set while
// single-threaded and before the first call to Now() to avoid threading issues
// and inconsistencies in returned values. Nested overrides are not allowed.
class BASE_EXPORT ScopedTimeClockOverrides {
public:
// Pass |nullptr| for any override if it shouldn't be overriden.
ScopedTimeClockOverrides(TimeNowFunction time_override,
TimeTicksNowFunction time_ticks_override,
ThreadTicksNowFunction thread_ticks_override);
// Restores the platform default Now() functions.
~ScopedTimeClockOverrides();
static bool overrides_active() { return overrides_active_; }
private:
static bool overrides_active_;
DISALLOW_COPY_AND_ASSIGN(ScopedTimeClockOverrides);
};
// These methods return the platform default Time::Now / TimeTicks::Now /
// ThreadTicks::Now values even while an override is in place. These methods
// should only be used in places where emulated time should be disregarded. For
// example, they can be used to implement test timeouts for tests that may
// override time.
BASE_EXPORT Time TimeNowIgnoringOverride();
BASE_EXPORT Time TimeNowFromSystemTimeIgnoringOverride();
BASE_EXPORT TimeTicks TimeTicksNowIgnoringOverride();
BASE_EXPORT ThreadTicks ThreadTicksNowIgnoringOverride();
} // namespace subtle
namespace internal {
// These function pointers are used by platform-independent implementations of
// the Now() methods and ScopedTimeClockOverrides. They are set to point to the
// respective NowIgnoringOverride functions by default, but can also be set by
// platform-specific code to select a default implementation at runtime, thereby
// avoiding the indirection via the NowIgnoringOverride functions. Note that the
// pointers can be overridden and later reset to the NowIgnoringOverride
// functions by ScopedTimeClockOverrides.
extern TimeNowFunction g_time_now_function;
extern TimeNowFunction g_time_now_from_system_time_function;
extern TimeTicksNowFunction g_time_ticks_now_function;
extern ThreadTicksNowFunction g_thread_ticks_now_function;
} // namespace internal
} // namespace base
#endif // BASE_TIME_TIME_OVERRIDE_H_
| 412 | 0.831077 | 1 | 0.831077 | game-dev | MEDIA | 0.381388 | game-dev | 0.693979 | 1 | 0.693979 |
eyza-cod2/zpam3 | 1,063 | source/ui_mp/scriptmenus/serverinfo_ctf.menu | #include "ui_mp/menudef.h"
#include "ui_mp/macros.h"
{
menuDef
{
name "serverinfo_ctf"
rect 0 0 640 480
focuscolor GLOBAL_FOCUSED_COLOR
style WINDOW_STYLE_EMPTY
blurWorld 5.0
onOpen
{
exec "vstr server16;" // server16 contains string with player's settings;
}
onEsc
{
scriptMenuResponse "close";
}
// Keys
execKeyInt 32 { play "mouse_click"; close ingame; open main; } // space
// Background
DRAW_MAP_BACKGROUND_IF_BLACKOUT
DRAW_BLUISH_BACKGROUND
DRAW_GRADIENT_LEFT_TO_RIGHT
DRAW_BARS
// Header: Teams
ITEM_TEXT_HEADING("@MPUI_CAPTURE_THE_FLAG")
// INSTRUCTIONS
SERVERINFO_DRAW_OBJECTIVE("@MP_CTF_OBJ_TEXT_NOSCORE")
// SERVER SETTINGS
SERVERINFO_DRAW_PARAMETERS
// MESSAGE OF THE DAY
SERVERINFO_DRAW_MOTD
// Clickable quit button all over the screen
SERVERINFO_DRAW_QUIT
// Close menu
ITEM_BAR_BOTTOM_BUTTON("^9[ESC]^7 Close", 40, 70, scriptMenuResponse "close")
// Main menu
ITEM_BAR_BOTTOM_BUTTON("^9[SPACE]^7 Main Menu", 135, 120, close serverinfo_ctf; open main)
}
}
| 412 | 0.851537 | 1 | 0.851537 | game-dev | MEDIA | 0.586816 | game-dev | 0.818351 | 1 | 0.818351 |
Straw1997/UnityCustomShaderGUI | 22,647 | CustomShaderGUI/Library/PackageCache/com.unity.textmeshpro@3.0.1/Scripts/Runtime/TMP_SpriteAsset.cs | using UnityEngine;
using UnityEngine.TextCore;
using System.Collections.Generic;
using System.Linq;
namespace TMPro
{
[ExcludeFromPresetAttribute]
public class TMP_SpriteAsset : TMP_Asset
{
internal Dictionary<int, int> m_NameLookup;
internal Dictionary<uint, int> m_GlyphIndexLookup;
/// <summary>
/// The version of the sprite asset class.
/// Version 1.1.0 updates the asset data structure to be compatible with new font asset structure.
/// </summary>
public string version
{
get { return m_Version; }
internal set { m_Version = value; }
}
[SerializeField]
private string m_Version;
/// <summary>
/// Information about the sprite asset's face.
/// </summary>
public FaceInfo faceInfo
{
get { return m_FaceInfo; }
internal set { m_FaceInfo = value; }
}
[SerializeField]
internal FaceInfo m_FaceInfo;
// The texture which contains the sprites.
public Texture spriteSheet;
/// <summary>
///
/// </summary>
public List<TMP_SpriteCharacter> spriteCharacterTable
{
get
{
if (m_GlyphIndexLookup == null)
UpdateLookupTables();
return m_SpriteCharacterTable;
}
internal set { m_SpriteCharacterTable = value; }
}
[SerializeField]
private List<TMP_SpriteCharacter> m_SpriteCharacterTable = new List<TMP_SpriteCharacter>();
/// <summary>
/// Dictionary used to lookup sprite characters by their unicode value.
/// </summary>
public Dictionary<uint, TMP_SpriteCharacter> spriteCharacterLookupTable
{
get
{
if (m_SpriteCharacterLookup == null)
UpdateLookupTables();
return m_SpriteCharacterLookup;
}
internal set { m_SpriteCharacterLookup = value; }
}
internal Dictionary<uint, TMP_SpriteCharacter> m_SpriteCharacterLookup;
public List<TMP_SpriteGlyph> spriteGlyphTable
{
get { return m_SpriteGlyphTable; }
internal set { m_SpriteGlyphTable = value; }
}
[SerializeField]
private List<TMP_SpriteGlyph> m_SpriteGlyphTable = new List<TMP_SpriteGlyph>();
internal Dictionary<uint, TMP_SpriteGlyph> m_SpriteGlyphLookup;
// List which contains the SpriteInfo for the sprites contained in the sprite sheet.
public List<TMP_Sprite> spriteInfoList;
/// <summary>
/// List which contains the Fallback font assets for this font.
/// </summary>
[SerializeField]
public List<TMP_SpriteAsset> fallbackSpriteAssets;
internal bool m_IsSpriteAssetLookupTablesDirty = false;
void Awake()
{
// Check version number of sprite asset to see if it needs to be upgraded.
if (this.material != null && string.IsNullOrEmpty(m_Version))
UpgradeSpriteAsset();
}
/// <summary>
/// Create a material for the sprite asset.
/// </summary>
/// <returns></returns>
Material GetDefaultSpriteMaterial()
{
//isEditingAsset = true;
ShaderUtilities.GetShaderPropertyIDs();
// Add a new material
Shader shader = Shader.Find("TextMeshPro/Sprite");
Material tempMaterial = new Material(shader);
tempMaterial.SetTexture(ShaderUtilities.ID_MainTex, spriteSheet);
tempMaterial.hideFlags = HideFlags.HideInHierarchy;
#if UNITY_EDITOR
UnityEditor.AssetDatabase.AddObjectToAsset(tempMaterial, this);
UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(this));
#endif
//isEditingAsset = false;
return tempMaterial;
}
/// <summary>
/// Function to update the sprite name and unicode lookup tables.
/// This function should be called when a sprite's name or unicode value changes or when a new sprite is added.
/// </summary>
public void UpdateLookupTables()
{
//Debug.Log("Updating [" + this.name + "] Lookup tables.");
// Check version number of sprite asset to see if it needs to be upgraded.
if (this.material != null && string.IsNullOrEmpty(m_Version))
UpgradeSpriteAsset();
// Initialize / Clear glyph index lookup dictionary.
if (m_GlyphIndexLookup == null)
m_GlyphIndexLookup = new Dictionary<uint, int>();
else
m_GlyphIndexLookup.Clear();
//
if (m_SpriteGlyphLookup == null)
m_SpriteGlyphLookup = new Dictionary<uint, TMP_SpriteGlyph>();
else
m_SpriteGlyphLookup.Clear();
// Initialize SpriteGlyphLookup
for (int i = 0; i < m_SpriteGlyphTable.Count; i++)
{
TMP_SpriteGlyph spriteGlyph = m_SpriteGlyphTable[i];
uint glyphIndex = spriteGlyph.index;
if (m_GlyphIndexLookup.ContainsKey(glyphIndex) == false)
m_GlyphIndexLookup.Add(glyphIndex, i);
if (m_SpriteGlyphLookup.ContainsKey(glyphIndex) == false)
m_SpriteGlyphLookup.Add(glyphIndex, spriteGlyph);
}
// Initialize name lookup
if (m_NameLookup == null)
m_NameLookup = new Dictionary<int, int>();
else
m_NameLookup.Clear();
// Initialize character lookup
if (m_SpriteCharacterLookup == null)
m_SpriteCharacterLookup = new Dictionary<uint, TMP_SpriteCharacter>();
else
m_SpriteCharacterLookup.Clear();
// Populate Sprite Character lookup tables
for (int i = 0; i < m_SpriteCharacterTable.Count; i++)
{
TMP_SpriteCharacter spriteCharacter = m_SpriteCharacterTable[i];
// Make sure sprite character is valid
if (spriteCharacter == null)
continue;
uint glyphIndex = spriteCharacter.glyphIndex;
// Lookup the glyph for this character
if (m_SpriteGlyphLookup.ContainsKey(glyphIndex) == false)
continue;
// Assign glyph and text asset to this character
spriteCharacter.glyph = m_SpriteGlyphLookup[glyphIndex];
spriteCharacter.textAsset = this;
int nameHashCode = m_SpriteCharacterTable[i].hashCode;
if (m_NameLookup.ContainsKey(nameHashCode) == false)
m_NameLookup.Add(nameHashCode, i);
uint unicode = m_SpriteCharacterTable[i].unicode;
if (unicode != 0xFFFE && m_SpriteCharacterLookup.ContainsKey(unicode) == false)
m_SpriteCharacterLookup.Add(unicode, spriteCharacter);
}
m_IsSpriteAssetLookupTablesDirty = false;
}
/// <summary>
/// Function which returns the sprite index using the hashcode of the name
/// </summary>
/// <param name="hashCode"></param>
/// <returns></returns>
public int GetSpriteIndexFromHashcode(int hashCode)
{
if (m_NameLookup == null)
UpdateLookupTables();
int index;
if (m_NameLookup.TryGetValue(hashCode, out index))
return index;
return -1;
}
/// <summary>
/// Returns the index of the sprite for the given unicode value.
/// </summary>
/// <param name="unicode"></param>
/// <returns></returns>
public int GetSpriteIndexFromUnicode (uint unicode)
{
if (m_SpriteCharacterLookup == null)
UpdateLookupTables();
TMP_SpriteCharacter spriteCharacter;
if (m_SpriteCharacterLookup.TryGetValue(unicode, out spriteCharacter))
return (int)spriteCharacter.glyphIndex;
return -1;
}
/// <summary>
/// Returns the index of the sprite for the given name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public int GetSpriteIndexFromName (string name)
{
if (m_NameLookup == null)
UpdateLookupTables();
int hashCode = TMP_TextUtilities.GetSimpleHashCode(name);
return GetSpriteIndexFromHashcode(hashCode);
}
/// <summary>
/// Used to keep track of which Sprite Assets have been searched.
/// </summary>
private static HashSet<int> k_searchedSpriteAssets;
/// <summary>
/// Search through the given sprite asset and its fallbacks for the specified sprite matching the given unicode character.
/// </summary>
/// <param name="spriteAsset">The font asset to search for the given character.</param>
/// <param name="unicode">The character to find.</param>
/// <param name="glyph">out parameter containing the glyph for the specified character (if found).</param>
/// <returns></returns>
public static TMP_SpriteAsset SearchForSpriteByUnicode(TMP_SpriteAsset spriteAsset, uint unicode, bool includeFallbacks, out int spriteIndex)
{
// Check to make sure sprite asset is not null
if (spriteAsset == null) { spriteIndex = -1; return null; }
// Get sprite index for the given unicode
spriteIndex = spriteAsset.GetSpriteIndexFromUnicode(unicode);
if (spriteIndex != -1)
return spriteAsset;
// Initialize list to track instance of Sprite Assets that have already been searched.
if (k_searchedSpriteAssets == null)
k_searchedSpriteAssets = new HashSet<int>();
else
k_searchedSpriteAssets.Clear();
// Get instance ID of sprite asset and add to list.
int id = spriteAsset.GetInstanceID();
k_searchedSpriteAssets.Add(id);
// Search potential fallback sprite assets if includeFallbacks is true.
if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0)
return SearchForSpriteByUnicodeInternal(spriteAsset.fallbackSpriteAssets, unicode, true, out spriteIndex);
// Search default sprite asset potentially assigned in the TMP Settings.
if (includeFallbacks && TMP_Settings.defaultSpriteAsset != null)
return SearchForSpriteByUnicodeInternal(TMP_Settings.defaultSpriteAsset, unicode, true, out spriteIndex);
spriteIndex = -1;
return null;
}
/// <summary>
/// Search through the given list of sprite assets and fallbacks for a sprite whose unicode value matches the target unicode.
/// </summary>
/// <param name="spriteAssets"></param>
/// <param name="unicode"></param>
/// <param name="includeFallbacks"></param>
/// <param name="spriteIndex"></param>
/// <returns></returns>
private static TMP_SpriteAsset SearchForSpriteByUnicodeInternal(List<TMP_SpriteAsset> spriteAssets, uint unicode, bool includeFallbacks, out int spriteIndex)
{
for (int i = 0; i < spriteAssets.Count; i++)
{
TMP_SpriteAsset temp = spriteAssets[i];
if (temp == null) continue;
int id = temp.GetInstanceID();
// Skip sprite asset if it has already been searched.
if (k_searchedSpriteAssets.Add(id) == false)
continue;
temp = SearchForSpriteByUnicodeInternal(temp, unicode, includeFallbacks, out spriteIndex);
if (temp != null)
return temp;
}
spriteIndex = -1;
return null;
}
/// <summary>
/// Search the given sprite asset and fallbacks for a sprite whose unicode value matches the target unicode.
/// </summary>
/// <param name="spriteAsset"></param>
/// <param name="unicode"></param>
/// <param name="includeFallbacks"></param>
/// <param name="spriteIndex"></param>
/// <returns></returns>
private static TMP_SpriteAsset SearchForSpriteByUnicodeInternal(TMP_SpriteAsset spriteAsset, uint unicode, bool includeFallbacks, out int spriteIndex)
{
// Get sprite index for the given unicode
spriteIndex = spriteAsset.GetSpriteIndexFromUnicode(unicode);
if (spriteIndex != -1)
return spriteAsset;
if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0)
return SearchForSpriteByUnicodeInternal(spriteAsset.fallbackSpriteAssets, unicode, true, out spriteIndex);
spriteIndex = -1;
return null;
}
/// <summary>
/// Search the given sprite asset and fallbacks for a sprite whose hash code value of its name matches the target hash code.
/// </summary>
/// <param name="spriteAsset">The Sprite Asset to search for the given sprite whose name matches the hashcode value</param>
/// <param name="hashCode">The hash code value matching the name of the sprite</param>
/// <param name="includeFallbacks">Include fallback sprite assets in the search</param>
/// <param name="spriteIndex">The index of the sprite matching the provided hash code</param>
/// <returns>The Sprite Asset that contains the sprite</returns>
public static TMP_SpriteAsset SearchForSpriteByHashCode(TMP_SpriteAsset spriteAsset, int hashCode, bool includeFallbacks, out int spriteIndex)
{
// Make sure sprite asset is not null
if (spriteAsset == null) { spriteIndex = -1; return null; }
spriteIndex = spriteAsset.GetSpriteIndexFromHashcode(hashCode);
if (spriteIndex != -1)
return spriteAsset;
// Initialize or clear list to Sprite Assets that have already been searched.
if (k_searchedSpriteAssets == null)
k_searchedSpriteAssets = new HashSet<int>();
else
k_searchedSpriteAssets.Clear();
int id = spriteAsset.instanceID;
// Add to list of font assets already searched.
k_searchedSpriteAssets.Add(id);
TMP_SpriteAsset tempSpriteAsset;
// Search potential fallbacks assigned to local sprite asset.
if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0)
{
tempSpriteAsset = SearchForSpriteByHashCodeInternal(spriteAsset.fallbackSpriteAssets, hashCode, true, out spriteIndex);
if (spriteIndex != -1)
return tempSpriteAsset;
}
// Search default sprite asset potentially assigned in the TMP Settings.
if (includeFallbacks && TMP_Settings.defaultSpriteAsset != null)
{
tempSpriteAsset = SearchForSpriteByHashCodeInternal(TMP_Settings.defaultSpriteAsset, hashCode, true, out spriteIndex);
if (spriteIndex != -1)
return tempSpriteAsset;
}
// Clear search list since we are now looking for the missing sprite character.
k_searchedSpriteAssets.Clear();
uint missingSpriteCharacterUnicode = TMP_Settings.missingCharacterSpriteUnicode;
// Get sprite index for the given unicode
spriteIndex = spriteAsset.GetSpriteIndexFromUnicode(missingSpriteCharacterUnicode);
if (spriteIndex != -1)
return spriteAsset;
// Add current sprite asset to list of assets already searched.
k_searchedSpriteAssets.Add(id);
// Search for the missing sprite character in the local sprite asset and potential fallbacks.
if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0)
{
tempSpriteAsset = SearchForSpriteByUnicodeInternal(spriteAsset.fallbackSpriteAssets, missingSpriteCharacterUnicode, true, out spriteIndex);
if (spriteIndex != -1)
return tempSpriteAsset;
}
// Search for the missing sprite character in the default sprite asset and potential fallbacks.
if (includeFallbacks && TMP_Settings.defaultSpriteAsset != null)
{
tempSpriteAsset = SearchForSpriteByUnicodeInternal(TMP_Settings.defaultSpriteAsset, missingSpriteCharacterUnicode, true, out spriteIndex);
if (spriteIndex != -1)
return tempSpriteAsset;
}
spriteIndex = -1;
return null;
}
/// <summary>
/// Search through the given list of sprite assets and fallbacks for a sprite whose hash code value of its name matches the target hash code.
/// </summary>
/// <param name="spriteAssets"></param>
/// <param name="hashCode"></param>
/// <param name="searchFallbacks"></param>
/// <param name="spriteIndex"></param>
/// <returns></returns>
private static TMP_SpriteAsset SearchForSpriteByHashCodeInternal(List<TMP_SpriteAsset> spriteAssets, int hashCode, bool searchFallbacks, out int spriteIndex)
{
// Search through the list of sprite assets
for (int i = 0; i < spriteAssets.Count; i++)
{
TMP_SpriteAsset temp = spriteAssets[i];
if (temp == null) continue;
int id = temp.instanceID;
// Skip sprite asset if it has already been searched.
if (k_searchedSpriteAssets.Add(id) == false)
continue;
temp = SearchForSpriteByHashCodeInternal(temp, hashCode, searchFallbacks, out spriteIndex);
if (temp != null)
return temp;
}
spriteIndex = -1;
return null;
}
/// <summary>
/// Search through the given sprite asset and fallbacks for a sprite whose hash code value of its name matches the target hash code.
/// </summary>
/// <param name="spriteAsset"></param>
/// <param name="hashCode"></param>
/// <param name="searchFallbacks"></param>
/// <param name="spriteIndex"></param>
/// <returns></returns>
private static TMP_SpriteAsset SearchForSpriteByHashCodeInternal(TMP_SpriteAsset spriteAsset, int hashCode, bool searchFallbacks, out int spriteIndex)
{
// Get the sprite for the given hash code.
spriteIndex = spriteAsset.GetSpriteIndexFromHashcode(hashCode);
if (spriteIndex != -1)
return spriteAsset;
if (searchFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0)
return SearchForSpriteByHashCodeInternal(spriteAsset.fallbackSpriteAssets, hashCode, true, out spriteIndex);
spriteIndex = -1;
return null;
}
/// <summary>
/// Sort the sprite glyph table by glyph index.
/// </summary>
public void SortGlyphTable()
{
if (m_SpriteGlyphTable == null || m_SpriteGlyphTable.Count == 0) return;
m_SpriteGlyphTable = m_SpriteGlyphTable.OrderBy(item => item.index).ToList();
}
/// <summary>
/// Sort the sprite character table by Unicode values.
/// </summary>
internal void SortCharacterTable()
{
if (m_SpriteCharacterTable != null && m_SpriteCharacterTable.Count > 0)
m_SpriteCharacterTable = m_SpriteCharacterTable.OrderBy(c => c.unicode).ToList();
}
/// <summary>
/// Sort both sprite glyph and character tables.
/// </summary>
internal void SortGlyphAndCharacterTables()
{
SortGlyphTable();
SortCharacterTable();
}
/// <summary>
/// Internal method used to upgrade sprite asset.
/// </summary>
private void UpgradeSpriteAsset()
{
m_Version = "1.1.0";
Debug.Log("Upgrading sprite asset [" + this.name + "] to version " + m_Version + ".", this);
// Convert legacy glyph and character tables to new format
m_SpriteCharacterTable.Clear();
m_SpriteGlyphTable.Clear();
for (int i = 0; i < spriteInfoList.Count; i++)
{
TMP_Sprite oldSprite = spriteInfoList[i];
TMP_SpriteGlyph spriteGlyph = new TMP_SpriteGlyph();
spriteGlyph.index = (uint)i;
spriteGlyph.sprite = oldSprite.sprite;
spriteGlyph.metrics = new GlyphMetrics(oldSprite.width, oldSprite.height, oldSprite.xOffset, oldSprite.yOffset, oldSprite.xAdvance);
spriteGlyph.glyphRect = new GlyphRect((int)oldSprite.x, (int)oldSprite.y, (int)oldSprite.width, (int)oldSprite.height);
spriteGlyph.scale = 1.0f;
spriteGlyph.atlasIndex = 0;
m_SpriteGlyphTable.Add(spriteGlyph);
TMP_SpriteCharacter spriteCharacter = new TMP_SpriteCharacter();
spriteCharacter.glyph = spriteGlyph;
spriteCharacter.unicode = oldSprite.unicode == 0x0 ? 0xFFFE : (uint)oldSprite.unicode;
spriteCharacter.name = oldSprite.name;
spriteCharacter.scale = oldSprite.scale;
m_SpriteCharacterTable.Add(spriteCharacter);
}
// Clear legacy glyph info list.
//spriteInfoList.Clear();
UpdateLookupTables();
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
UnityEditor.AssetDatabase.SaveAssets();
#endif
}
}
}
| 412 | 0.860971 | 1 | 0.860971 | game-dev | MEDIA | 0.847028 | game-dev | 0.871563 | 1 | 0.871563 |
jcs090218/JCSUnity | 3,674 | Assets/_RunningCrush/Scripts/RC_WebcamHandler.cs | /**
* $File: RC_WebcamHandler.cs $
* $Date: $
* $Revision: $
* $Creator: Jen-Chieh Shen $
* $Notice: See LICENSE.txt for modification and distribution information
* Copyright (c) 2016 by Shen, Jen-Chieh $
*/
using UnityEngine;
using JCSUnity;
[RequireComponent(typeof(RectTransform))]
public class RC_WebcamHandler : MonoBehaviour
{
/* Variables */
[SerializeField]
private RectTransform mRectTransform = null;
[SerializeField] private RectTransform[] mWebcamPanel = null;
[SerializeField] private JCS_Webcam mWebcam = null;
[SerializeField] private RectTransform mStartGameButton = null;
[SerializeField] private float mTimeBeforeDisable = 0;
[SerializeField] private float mTimeAfterDisable = 0;
private float mTimer = 0;
private JCS_IncDec mType = JCS_IncDec.INCREASE;
private bool mStartTimer = false;
private bool mCloseTimer = false;
private int mPanelIndex = 0;
/* Setter & Getter */
/* Functions */
private void Start()
{
mRectTransform = this.GetComponent<RectTransform>();
// try to get the object
if (mWebcam == null)
mWebcam = JCS_Util.FindObjectByType(typeof(JCS_Webcam)) as JCS_Webcam;
}
private void Update()
{
if (mCloseTimer)
{
mTimer += Time.deltaTime;
if (mTimeAfterDisable < mTimer)
{
PluseAppRect();
mWebcam.GetImage().enabled = true;
mCloseTimer = false;
}
}
if (mStartTimer)
{
mTimer += Time.deltaTime;
if (mTimeBeforeDisable < mTimer)
{
mWebcam.GetImage().enabled = false;
mCloseTimer = true;
mTimer = 0;
mStartTimer = false;
}
}
}
public void RC_SetActiveInTime(int way)
{
if (mStartTimer)
return;
mType = (JCS_IncDec)way;
mStartTimer = true;
}
public void PluseAppRect()
{
if (mType == JCS_IncDec.INCREASE)
++mPanelIndex;
else
--mPanelIndex;
// check length
if (mWebcamPanel.Length < mPanelIndex || mPanelIndex < 0)
{
Debug.LogError("Out of range index");
return;
}
// check object
if (mWebcamPanel[mPanelIndex] == null)
{
Debug.LogError("Call the function but does not assign panel at [" + mPanelIndex + "]...");
return;
}
RectTransform appRectTransform = JCS_Canvas.GuessCanvas().appRect;
Vector2 appRect = appRectTransform.sizeDelta;
Vector3 newPosButton = mRectTransform.localPosition;
Vector3 newPosWebcam = mWebcam.GetRectTransform().localPosition;
Vector3 newStartGameButtonPos = mStartGameButton.localPosition;
newPosButton.x += appRect.x;
newPosWebcam.x += appRect.x;
newStartGameButtonPos.x += appRect.x;
if ((mPanelIndex) == RC_GameSettings.FirstInstance().PLAYER_IN_GAME)
{
RC_GameSettings.FirstInstance().READY_TO_START_GAME = true;
}
else
{
mRectTransform.localPosition = newPosButton;
mWebcam.GetRectTransform().localPosition = newPosWebcam;
mWebcam.transform.SetParent(mWebcamPanel[mPanelIndex].transform);
this.transform.SetParent(mWebcamPanel[mPanelIndex].transform);
}
mStartGameButton.localPosition = newStartGameButtonPos;
mStartGameButton.SetParent(mWebcamPanel[mPanelIndex].transform);
}
}
| 412 | 0.847988 | 1 | 0.847988 | game-dev | MEDIA | 0.662474 | game-dev | 0.948837 | 1 | 0.948837 |
Team-Beef-Studios/Doom3Quest | 13,166 | app/src/main/jni/d3es-multithread-master/neo/tools/radiant/Z.CPP | /*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "tools/edit_gui_common.h"
#include "qe3.h"
#define PAGEFLIPS 2
z_t z;
/*
=======================================================================================================================
Z_Init
=======================================================================================================================
*/
void Z_Init(void) {
z.origin[0] = 0;
z.origin[1] = 20;
z.origin[2] = 46;
z.scale = 1;
}
/* MOUSE ACTIONS */
static int cursorx, cursory;
/*
=======================================================================================================================
Z_MouseDown
=======================================================================================================================
*/
void Z_MouseDown(int x, int y, int buttons) {
idVec3 org, dir, vup, vright;
brush_t *b;
Sys_GetCursorPos(&cursorx, &cursory);
vup[0] = 0;
vup[1] = 0;
vup[2] = 1 / z.scale;
VectorCopy(z.origin, org);
org[2] += (y - (z.height / 2)) / z.scale;
org[1] = MIN_WORLD_COORD;
b = selected_brushes.next;
if (b != &selected_brushes) {
org[0] = (b->mins[0] + b->maxs[0]) / 2;
}
dir[0] = 0;
dir[1] = 1;
dir[2] = 0;
vright[0] = 0;
vright[1] = 0;
vright[2] = 0;
// new mouse code for ZClip, I'll do this stuff before falling through into the standard ZWindow mouse code...
//
if (g_pParentWnd->GetZWnd()->m_pZClip) // should always be the case I think, but this is safer
{
bool bToggle = false;
bool bSetTop = false;
bool bSetBot = false;
bool bReset = false;
if (g_PrefsDlg.m_nMouseButtons == 2)
{
// 2 button mice...
//
bToggle = (GetKeyState(VK_F1) & 0x8000) != 0;
bSetTop = (GetKeyState(VK_F2) & 0x8000) != 0;
bSetBot = (GetKeyState(VK_F3) & 0x8000) != 0;
bReset = (GetKeyState(VK_F4) & 0x8000) != 0;
}
else
{
// 3 button mice...
//
bToggle = (buttons == (MK_RBUTTON|MK_SHIFT|MK_CONTROL));
bSetTop = (buttons == (MK_RBUTTON|MK_SHIFT));
bSetBot = (buttons == (MK_RBUTTON|MK_CONTROL));
bReset = (GetKeyState(VK_F4) & 0x8000) != 0;
}
if (bToggle)
{
g_pParentWnd->GetZWnd()->m_pZClip->Enable(!(g_pParentWnd->GetZWnd()->m_pZClip->IsEnabled()));
Sys_UpdateWindows (W_ALL);
return;
}
if (bSetTop)
{
g_pParentWnd->GetZWnd()->m_pZClip->SetTop(org[2]);
Sys_UpdateWindows (W_ALL);
return;
}
if (bSetBot)
{
g_pParentWnd->GetZWnd()->m_pZClip->SetBottom(org[2]);
Sys_UpdateWindows (W_ALL);
return;
}
if (bReset)
{
g_pParentWnd->GetZWnd()->m_pZClip->Reset();
Sys_UpdateWindows (W_ALL);
return;
}
}
//
// LBUTTON = manipulate selection shift-LBUTTON = select middle button = grab
// texture ctrl-middle button = set entire brush to texture ctrl-shift-middle
// button = set single face to texture
//
// see code above for these next 3, I just commented them here as well for clarity...
//
// ctrl-shift-RIGHT button = toggle ZClip on/off
// shift-RIGHT button = set ZClip top marker
// ctrl-RIGHT button = set ZClip bottom marker
int nMouseButton = g_PrefsDlg.m_nMouseButtons == 2 ? MK_RBUTTON : MK_MBUTTON;
if
(
(buttons == MK_LBUTTON) ||
(buttons == (MK_LBUTTON | MK_SHIFT)) ||
(buttons == MK_MBUTTON) // || (buttons == (MK_MBUTTON|MK_CONTROL))
||
(buttons == (nMouseButton | MK_SHIFT | MK_CONTROL))
) {
Drag_Begin(x, y, buttons, vright, vup, org, dir);
return;
}
// control mbutton = move camera
if ((buttons == (MK_CONTROL | nMouseButton)) || (buttons == (MK_CONTROL | MK_LBUTTON))) {
g_pParentWnd->GetCamera()->Camera().origin[2] = org[2];
Sys_UpdateWindows(W_CAMERA | W_XY_OVERLAY | W_Z);
}
}
/*
=======================================================================================================================
Z_MouseUp
=======================================================================================================================
*/
void Z_MouseUp(int x, int y, int buttons) {
Drag_MouseUp();
}
/*
=======================================================================================================================
Z_MouseMoved
=======================================================================================================================
*/
void Z_MouseMoved(int x, int y, int buttons) {
if (!buttons) {
return;
}
if (buttons == MK_LBUTTON) {
Drag_MouseMoved(x, y, buttons);
Sys_UpdateWindows(W_Z | W_CAMERA_IFON | W_XY);
return;
}
// rbutton = drag z origin
if (buttons == MK_RBUTTON) {
Sys_GetCursorPos(&x, &y);
if (y != cursory) {
z.origin[2] += y - cursory;
Sys_SetCursorPos(cursorx, cursory);
Sys_UpdateWindows(W_Z);
}
return;
}
// control mbutton = move camera
int nMouseButton = g_PrefsDlg.m_nMouseButtons == 2 ? MK_RBUTTON : MK_MBUTTON;
if ((buttons == (MK_CONTROL | nMouseButton)) || (buttons == (MK_CONTROL | MK_LBUTTON))) {
g_pParentWnd->GetCamera()->Camera().origin[2] = z.origin[2] + (y - (z.height / 2)) / z.scale;
Sys_UpdateWindows(W_CAMERA | W_XY_OVERLAY | W_Z);
}
}
/*
=======================================================================================================================
DRAWING
Z_DrawGrid
=======================================================================================================================
*/
void Z_DrawGrid(void) {
float zz, zb, ze;
int w, h;
char text[32];
w = z.width / 2 / z.scale;
h = z.height / 2 / z.scale;
zb = z.origin[2] - h;
if (zb < region_mins[2]) {
zb = region_mins[2];
}
zb = 64 * floor(zb / 64);
ze = z.origin[2] + h;
if (ze > region_maxs[2]) {
ze = region_maxs[2];
}
ze = 64 * ceil(ze / 64);
// draw major blocks
qglColor3fv( g_qeglobals.d_savedinfo.colors[COLOR_GRIDMAJOR].ToFloatPtr() );
qglBegin(GL_LINES);
qglVertex2f(0, zb);
qglVertex2f(0, ze);
for (zz = zb; zz < ze; zz += 64) {
qglVertex2f(-w, zz);
qglVertex2f(w, zz);
}
qglEnd();
// draw minor blocks
if ( g_qeglobals.d_showgrid &&
g_qeglobals.d_gridsize * z.scale >= 4 &&
!g_qeglobals.d_savedinfo.colors[COLOR_GRIDMINOR].Compare( g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK] ) ) {
qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_GRIDMINOR].ToFloatPtr());
qglBegin(GL_LINES);
for (zz = zb; zz < ze; zz += g_qeglobals.d_gridsize) {
if (!((int)zz & 63)) {
continue;
}
qglVertex2f(-w, zz);
qglVertex2f(w, zz);
}
qglEnd();
}
// draw coordinate text if needed
qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_GRIDTEXT].ToFloatPtr());
for (zz = zb; zz < ze; zz += 64) {
qglRasterPos2f(-w + 1, zz);
sprintf(text, "%i", (int)zz);
qglCallLists(strlen(text), GL_UNSIGNED_BYTE, text);
}
}
#define CAM_HEIGHT 48 // height of main part
#define CAM_GIZMO 8 // height of the gizmo
/*
=======================================================================================================================
=======================================================================================================================
*/
void ZDrawCameraIcon(void) {
float x, y;
int xCam = z.width / 4;
x = 0;
y = g_pParentWnd->GetCamera()->Camera().origin[2];
qglColor3f(0.0, 0.0, 1.0);
qglBegin(GL_LINE_STRIP);
qglVertex3f(x - xCam, y, 0);
qglVertex3f(x, y + CAM_GIZMO, 0);
qglVertex3f(x + xCam, y, 0);
qglVertex3f(x, y - CAM_GIZMO, 0);
qglVertex3f(x - xCam, y, 0);
qglVertex3f(x + xCam, y, 0);
qglVertex3f(x + xCam, y - CAM_HEIGHT, 0);
qglVertex3f(x - xCam, y - CAM_HEIGHT, 0);
qglVertex3f(x - xCam, y, 0);
qglEnd();
}
void ZDrawZClip()
{
float x,y;
x = 0;
y = g_pParentWnd->GetCamera()->Camera().origin[2];
if (g_pParentWnd->GetZWnd()->m_pZClip) // should always be the case I think
g_pParentWnd->GetZWnd()->m_pZClip->Paint();
}
GLbitfield glbitClear = GL_COLOR_BUFFER_BIT; // HACK
/*
=======================================================================================================================
Z_Draw
=======================================================================================================================
*/
void Z_Draw(void) {
brush_t *brush;
float w, h;
float top, bottom;
idVec3 org_top, org_bottom, dir_up, dir_down;
int xCam = z.width / 3;
if (!active_brushes.next) {
return; // not valid yet
}
// clear
qglViewport(0, 0, z.width, z.height);
qglScissor(0, 0, z.width, z.height);
qglClearColor
(
g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][0],
g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][1],
g_qeglobals.d_savedinfo.colors[COLOR_GRIDBACK][2],
0
);
/*
* GL Bug
* When not using hw acceleration, gl will fault if we clear the depth buffer bit
* on the first pass. The hack fix is to set the GL_DEPTH_BUFFER_BIT only after
* Z_Draw() has been called once. Yeah, right.
* qglClear(glbitClear);
*/
qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//
// glbitClear |= GL_DEPTH_BUFFER_BIT;
// qglClear(GL_DEPTH_BUFFER_BIT);
//
qglMatrixMode(GL_PROJECTION);
qglLoadIdentity();
w = z.width / 2 / z.scale;
h = z.height / 2 / z.scale;
qglOrtho(-w, w, z.origin[2] - h, z.origin[2] + h, -8, 8);
globalImages->BindNull();
qglDisable(GL_DEPTH_TEST);
qglDisable(GL_BLEND);
// now draw the grid
Z_DrawGrid();
// draw stuff
qglDisable(GL_CULL_FACE);
qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
globalImages->BindNull();
// draw filled interiors and edges
dir_up[0] = 0;
dir_up[1] = 0;
dir_up[2] = 1;
dir_down[0] = 0;
dir_down[1] = 0;
dir_down[2] = -1;
VectorCopy(z.origin, org_top);
org_top[2] = 4096;
VectorCopy(z.origin, org_bottom);
org_bottom[2] = -4096;
for (brush = active_brushes.next; brush != &active_brushes; brush = brush->next) {
if
(
brush->mins[0] >= z.origin[0] ||
brush->maxs[0] <= z.origin[0] ||
brush->mins[1] >= z.origin[1] ||
brush->maxs[1] <= z.origin[1]
) {
continue;
}
if (!Brush_Ray(org_top, dir_down, brush, &top)) {
continue;
}
top = org_top[2] - top;
if (!Brush_Ray(org_bottom, dir_up, brush, &bottom)) {
continue;
}
bottom = org_bottom[2] + bottom;
//q = declManager->FindMaterial(brush->brush_faces->texdef.name);
qglColor3f(brush->owner->eclass->color.x, brush->owner->eclass->color.y, brush->owner->eclass->color.z);
qglBegin(GL_QUADS);
qglVertex2f(-xCam, bottom);
qglVertex2f(xCam, bottom);
qglVertex2f(xCam, top);
qglVertex2f(-xCam, top);
qglEnd();
qglColor3f(1, 1, 1);
qglBegin(GL_LINE_LOOP);
qglVertex2f(-xCam, bottom);
qglVertex2f(xCam, bottom);
qglVertex2f(xCam, top);
qglVertex2f(-xCam, top);
qglEnd();
}
// now draw selected brushes
for (brush = selected_brushes.next; brush != &selected_brushes; brush = brush->next) {
if
(
!(
brush->mins[0] >= z.origin[0] ||
brush->maxs[0] <= z.origin[0] ||
brush->mins[1] >= z.origin[1] ||
brush->maxs[1] <= z.origin[1]
)
) {
if (Brush_Ray(org_top, dir_down, brush, &top)) {
top = org_top[2] - top;
if (Brush_Ray(org_bottom, dir_up, brush, &bottom)) {
bottom = org_bottom[2] + bottom;
//q = declManager->FindMaterial(brush->brush_faces->texdef.name);
qglColor3f(brush->owner->eclass->color.x, brush->owner->eclass->color.y, brush->owner->eclass->color.z);
qglBegin(GL_QUADS);
qglVertex2f(-xCam, bottom);
qglVertex2f(xCam, bottom);
qglVertex2f(xCam, top);
qglVertex2f(-xCam, top);
qglEnd();
}
}
}
qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES].ToFloatPtr());
qglBegin(GL_LINE_LOOP);
qglVertex2f(-xCam, brush->mins[2]);
qglVertex2f(xCam, brush->mins[2]);
qglVertex2f(xCam, brush->maxs[2]);
qglVertex2f(-xCam, brush->maxs[2]);
qglEnd();
}
ZDrawCameraIcon();
ZDrawZClip();
qglFinish();
QE_CheckOpenGLForErrors();
}
| 412 | 0.904919 | 1 | 0.904919 | game-dev | MEDIA | 0.809892 | game-dev | 0.75567 | 1 | 0.75567 |
historicalsource/plunderedhearts | 32,576 | hero.zil | "HERO for
PLUNDERED HEARTS
(c) Copyright 1987 Infocom, Inc. All Rights Reserved."
<OBJECT HERO ;"MUNGBIT: unconscious."
(IN CAPT-QUARTERS)
(DESC "Captain Jamison")
(DESCFCN HERO-F)
(SYNONYM HERO PIRATE JAMISON CAPTAIN)
(ADJECTIVE NICHOLAS NICK CAPTAIN FALCON)
(SIZE 10)
(FLAGS ACTORBIT NARTICLEBIT CONTBIT OPENBIT SEARCHBIT)
(GENERIC GEN-PIRATE)
(ACTION HERO-F)>
<GLOBAL HERO-CTR 1>
<GLOBAL HDAD-SPEECH <>> ;"You've told him about freeing Dad,"
;"(which you can do by NICK, FOLLOW ME - dance)"
;"OR he's answered your question about Dad."
;"(To prevent his dance speech happening twice)"
<ROUTINE HERO-F ("OPTIONAL" (OARG <>))
<COND (.OARG
<COND (<EQUAL? .OARG ,M-DESC?>
<RTRUE>)>
<COND (<NOT <EQUAL? ,HERE ,FOLLY>>
<TELL ,INDENT>)> ;"To prevent indent in folly"
<COND (<EQUAL? ,HERE ,CABIN>
<TELL ,CTHE-PIRATE-CAPTAIN "is studying you">)
(<EQUAL? ,HERE ,DEUX-DECK>
<TELL ,CTHE-PIRATE-CAPTAIN
"stands protectively a few steps behind you">)
(<EQUAL? ,HERE ,CAPT-QUARTERS>
<TELL D ,HERO " is adjusting his clothes">)
(<RUNNING? ,I-DUEL>
<TELL
"Battered and bruised, Nicholas can hardly stand">)
;(<IN? ,HERO ,MANACLES>
<RTRUE>) ;"TOLD in MANACLES-DESC"
(<FSET? ,HERO ,DEADBIT>
<TELL ,HERO-EYES-CLOSED>)
(<EQUAL? ,HERE ,BEACH>
<TELL "Nicholas ">
<COND (<FSET? ,LAFOND ,DEADBIT>
<TELL "walks toward you, smiling wearily">)
(<G? ,LAFOND-CTR <- ,FIGHTING 1>>
<TELL "and Lafond are fighting">)
(T
<TELL
"stands alone at one edge of the beach">)>)
(<QUEUED? ,I-ENDGAME>
<TELL
"Nicholas stands, half-supported by Lucy and" T ,DAD>)
(<EQUAL? ,HERE ,BALLROOM>
<TELL
"Nicholas looks quite rakish, in red velvet and white,
his rapier flashing in the light of the " D ,CHANDELIER>)
(T
<RFALSE>)>
<TELL ".">)
(<EQUAL? ,HERO ,WINNER>
<COND (<AND <RUNNING? ,I-DUEL>
<EQUAL? ,HERE ,GALLERY ,STAIRTOP>>
<TELL ,SPEECHLESS>)
(<AND <EQUAL? ,HERE ,BEACH>
<RUNNING? ,I-ENDGAME>>
<COND (<AND <NOT <FSET? ,LAFOND ,DEADBIT>>
<G? ,LAFOND-CTR <- ,FIGHTING 1>>>
<TELL ,SPEECHLESS>)
(<VERB? HALT LOOK-INSIDE WALK CLIMB-DOWN>
<H-JIGS-UP
"Nicholas stops at your cry, and turns, curious, to face Crulley
just as the pistol sprays shot into his chest.">)
(T
<FAILS-TO-NOTICE>)>)
(<FSET? ,HERO ,DEADBIT>
<TELL ,DOESNT-RESPOND>)
(<AND <VERB? FOLLOW>
<PRSO? ,ME>
<RUNNING? ,I-HDANCE> ;"Dad told you to"
<FSET? ,DAD ,TOUCHBIT>> ;" fetch Nick"
<SETG HDAD-SPEECH T>
<TELL
"\"I will follow you anywhere you please,
but first I must kill Lafond.\"" CR>)
(<VERB? I-LOVE-YOU>
<COND (<PRSO? ,MAN ,HERO>
<TELL
"He smiles at you warmly, his eyes full of passion." CR>)
(<PRSO? ,LAFOND>
<COND (<OR <RUNNING? ,I-HFOLLY>
<RUNNING? ,I-HDANCE>>
<REMOVE ,HERO>
<STOP-QUEUES>
<TELL
"He looks at you in disgust and walks away." CR>)
(T
<TELL "\"Don't jest,\" he says." CR>)>)
(T
<TELL "He isn't all that interested." CR>)>)
(<VERB? LEAVE>
<COND (<FSET? ,BEACH ,TOUCHBIT>
<SETG AWAITING-REPLY 4>
<QUEUE I-REPLY 2>
<TELL
"He catches your arm, \"Nay, can you mean that?\"" CR>)
(T
<TELL
"\"I have business to attend to here,
and have no intention of leaving.\"" CR>)>
<RTRUE>)
(<AND <VERB? READ>
<PRSO? ,LETTER>>
<PERFORM ,V?TELL-ABOUT ,ME ,LETTER>
<RTRUE>)
(<AND <VERB? TELL-ABOUT>
<PRSO? ,ME>>
<COND (<PRSI? ,LETTER>
<TELL "\"Your father wrote it for you.\"" CR>)
(<PRSI? ,HRING>
<SETG WINNER ,PROTAGONIST>
<PERFORM ,V?TAKE ,HRING>
<RTRUE>)
(<PRSI? ,LAFOND>
<TELL
"\"I abhor the fiend.\" He clenches a fist." CR>)
(<PRSI? ,DAD>
<COND (<RUNNING? ,I-HDANCE>
<SETG HDAD-SPEECH T>
<TELL <GET ,HERO-SPEECHES 0> ,PCR>)
(<RUNNING? ,I-HFOLLY>
<TELL
"\"Let's not discuss" T ,DAD " just now,\"
he says, kissing your neck" ,PCR>)
(T
<TELL
"\"I admire and respect your father greatly.\"" CR>)>)
(T
<FAILS-TO-NOTICE>)>
<STOP>)
;(<AND <VERB? RAISE>
<PRSO? ,ME>
<EQUAL? <LOC ,PROTAGONIST> ,TREE-HOLE ,CLOSET>>
<SETG WINNER ,PROTAGONIST>
<PERFORM ,V?CLIMB-ON ,SIDEKICK>
<SETG WINNER ,SIDEKICK>
<RTRUE>)
(<AND <VERB? TAKE>
<PRSO? ,FLOWER>>
<SETG WINNER ,PROTAGONIST>
<PERFORM ,V?GIVE ,FLOWER ,HERO>
<SET WINNER ,HERO>
<RTRUE>)
(<SET OARG <COM-CHECK ,HERO>>
<COND (<==? .OARG ,M-FATAL>
<RFALSE>)
(T
<RTRUE>)>)
;(T
<FAILS-TO-NOTICE>
<STOP>)>)
(<VERB? EXAMINE>
<COND (<FSET? ,HERO ,DEADBIT>
<COND (<RUNNING? ,I-DUEL>
<TELL "He lies in a pool of blood." CR>)
(T
<TELL ,HERO-EYES-CLOSED>)>)
(<AND <EQUAL? ,HERE ,CAPT-QUARTERS ,BALLROOM ,FOLLY>
<NOT ,ENDGAME>>
<TELL
"Jamison is finely dressed, in red velvet coat and full breeches, with a
long gold embroidered vest and waterfalls of white lace at his neck, wrists
and boottops. His rapier is bedecked with a fringed gold ribbon. He wears no
wig, his unpowdered hair tied neatly at the back of his neck" ,PCR>)
(T
<TELL
"Jamison carries an aura of power unusual in men so slim and tall,
the strength of a willow in his hard seaworn body, straight shouldered and
resilient. " ,NUTBROWN "A jagged scar etches one cheek, harsh against
the warmth of his limpid blue eyes" ,PCR>)>)
(<AND <VERB? SAVE-SOMETHING ROLL>
<RUNNING? ,I-ENDGAME>>
<SETG WINNER ,HERO>
<PERFORM ,V?HALT ,ROOMS>
<SETG WINNER ,PROTAGONIST>
<RTRUE>)
(<FSET? ,HERO ,DEADBIT>
<COND (<AND <VERB? GIVE>
<PRSO? ,SALTS>>
<REVIVE-HERO>)
(<AND <VERB? BLOW PUT-ON THROW-AT>
<PRSO? ,SPICES>>
<TELL "He sneezes involuntarily, unconscious." CR>)
(<VERB? KILL KICK MUNG>
<MAN-IS-DOWN>)
(<VERB? MOVE>
<TELL "He's too heavy." CR>)
(<VERB? KISS EMBRACE>
<TELL
"You press your lips to his cold mouth. " ,DOESNT-RESPOND>)
(<OR <AND <VERB? TELL TELL-ABOUT ASK-ABOUT>
<NOT <PRSO? ,HERO>>>
<TOUCHING? ,HERO>>
<TELL ,DOESNT-RESPOND>)
(T
<RFALSE>)>)
(<VERB? GIVE>
<COND (<PRSO? ,SALTS>
<REVIVE-HERO>)
(<PRSO? ,BANKNOTE>
<TELL D ,HERO " returns" T ,BANKNOTE " to you" ,PCR>)
(<PRSO? ,FLOWER>
<TELL
"He prevents you, smiling. \"It looks much
too pretty against your hair. Keep it.\"" CR>)
(<PRSO? ,COFFER>
<FAILS-TO-NOTICE>)
(T
<RFALSE>)>)
(<VERB? ALARM>
<COND ;(<NOT ,PRSI>
<PROPOSE>)
(<NOT <PRSI? SALTS>>
<TELL ,YOU-CANT "revive him with that!" CR>)
(<HELD? ,SALTS>
<REVIVE-HERO>)
;(<HELD? ,QUILL>
<PERFORM ,V?ALARM ,HERO ,QUILL>
<RTRUE>)
(T
<TELL D ,HERO " is not asleep" ,PCR>)>)
(<AND <VERB? UNTIE>
<EQUAL? ,P-PRSA-WORD ,W?FREE>>
<COND (<IN? ,HERO ,MANACLES>
<SETG AWAITING-REPLY 2>
<QUEUE I-REPLY 2>
<TELL "You have the key, maybe?" CR>)
(T
<TELL "Jamison is free enough as it is" ,PCR>)>)
(<VERB? KILL KICK MUNG>
<TELL "\"Please, I'm not trying to hurt you,\"">
<COND (<EQUAL? ,HERE ,CABIN>
<TELL " the stranger">)
(T
<TELL T ,HERO>)>
<TELL " says, casually deflecting the blow" ,PCR>)
(<AND <VERB? KISS>
<EQUAL? ,WINNER ,PROTAGONIST>>
<COND (<EQUAL? ,HERE ,CABIN ,DEUX-DECK>
<TELL
"You are not so pert as to kiss a stranger, and a pirate, at that!">
<CRLF>)
(<SHIP-BOARD ,HERE>
<TELL
"That thought has occurred to you before,
but now does not seem appropriate" ,PCR>)
(<EQUAL? ,HERE ,FOLLY>
<SETG REACTION ,REACTION-POSITIVE>
<TELL "You lean into his arms, face lifted" ,PCR>)
(<OR <RUNNING? ,I-DUEL>
<RUNNING? ,I-ENDGAME>>
<TELL "You would only distract" TR ,HERO>)
(<RUNNING? ,I-HDANCE>
<TELL
"In view of all" T ,DANCERS "s, you exchange
only a peck on the cheek" ,PCR>)
(T
<TELL "He kisses you back" ,PCR>)>)
(<VERB? TELL-ABOUT>
<COND ;(<EQUAL? ,WINNER ,PROTAGONIST>
<TELL ,DOESNT-RESPOND>)
(<OR <NOUN-USED ,W?LIBRARY ,HOUSE>
<NOUN-USED ,W?CELL ,CELL-4>
<PRSI? ,PORTRAIT ,DUNGEON>>
<TELL "He nods. \"That area is guarded well.\"" CR>)
(<PRSI? ,DAD>
<COND (<IN? ,DAD ,CELL-4>
<TELL
"He smiles fondly at your reminiscing.
\"I never knew my father -- he died when I was a boy.\"" CR>)
(T
<SET HDAD-SPEECH T>
<TELL
"\"Such bravery joined with such beauty!\"" CR>)>)
(<AND <PRSI? ,CRULLEY>
<FSET? ,BEACH ,TOUCHBIT>>
<TELL "\"Crulley?! God's blood!\"" CR>)
(T
<RFALSE>)>)
(<AND <VERB? EMBRACE TOUCH>
<EQUAL? ,HERE ,FOLLY>>
<PERFORM ,V?KISS ,HERO>
<RTRUE>)
;(<AND <VERB? WALK FOLLOW>
<EQUAL? ,HERE ,CABIN>
<IN? ,HERO ,HERE>>
<TELL D ,HERO " guides you through" TR ,DOOR CR>
<GOTO ,DEUX-DECK>)
(<VERB? DANCE>
<COND (<AND <EQUAL? ,HERE ,BALLROOM>
<EQUAL? ,PARTNER ,HERO>>
<TELL ,PACE>)
(<RUNNING? ,I-HDANCE>
<MOVE ,PROTAGONIST ,BALLROOM>
<MOVE ,HERO ,BALLROOM>
<SETG PARTNER ,HERO>
<TELL "You whirl back out to" ,DANCE-FLOOR ,PCR>)
(T
<RFALSE>)>)
(<AND <VERB? SHOW>
<PRSO? ,JEWEL>
<IN? ,HERO ,MANACLES>>
<TELL
"Nick smiles dazzlingly, \"Of course! Now pick the locks.\"" CR>)>>
<GLOBAL NUTBROWN
"Chestnut hair, tousled by the wind, frames the tanned oval of his face. ">
<ROUTINE GEN-PIRATE ()
<COND (<AND ,ENDGAME
<EQUAL? ,HERE ,BALLROOM>>
,CREW)
(<FSET? ,CAPT-QUARTERS ,TOUCHBIT>
,CRULLEY)
(T
<RFALSE>)>>
;<GLOBAL HEROS-NAME " Captain Nicholas Brent Charles Lancelot Richard
Blaise Peaceable Jamison -- a mouthful, so my friends call me Nick">
<GLOBAL CTHE-PIRATE-CAPTAIN "The pirate captain ">
<GLOBAL HERO-EYES-CLOSED
"Eyes closed, his skin with the pallor of death, Nick looks entirely spent.|">
;"1st meeting with hero in Cabin, (14-11-86)"
<ROUTINE I-MEET-HERO ()
<SETG AWAITING-REPLY 5>
<QUEUE I-REPLY 1>
<SETG QUESTIONER ,HERO>
<TELL ,INDENT>
<COND (<EQUAL? ,HERO-CTR 1>
<MOVE ,HERO ,HERE>
<QUEUE I-MEET-HERO -1>
<COND (<L? ,ATTACK-C 2>
<DEQUEUE I-CRULLEY>
<FSET ,CRULLEY ,DEADBIT>
<TELL
D ,CRULLEY " drags you, despite your resistance, to">
<COND (<EQUAL? <LOC ,PROTAGONIST> ,CABIN-BED>
<MOVE ,PROTAGONIST ,HERE>
<TELL " your feet">)
(T
<TELL "wards him">)>
<TELL
". Then suddenly he grunts, stiffens and slumps into your arms. "
,STUNNED-THE-SAILOR ".|
A tall form blocks the shattered door, one fist still raised from
striking your attacker">)
(T
<TELL CTHE ,DOOR " creaks slightly as a tall
form bends through its smashed remains. \"You seem to have this situation
well in hand,\" timbers a well-bred voice">)>
<TELL
". You catch a glimpse of the hard masculinity of his broad shoulders,
the implied power in the scar that etches the stranger's jaw,
and feel tremors course through your veins. Then you realize how ragged are
his shirt, patched breeches and high boots. Intuitively, you understand -- he
is the dreaded Falcon, scourge of the sea! Alas, your fate is sealed.
Resigned, you meet his sea-blue eyes." CR>)
;[Under the impact of his gaze, the hard masculinity
of his broad shoulders, the implied power in the scar that etches his
jaw, you discover yourself blind to the dangers of this infamous pirate,
aware only of the tremors that course your veins, of that flutter deep
in your stomach as he draws near you. In this most unlikely of places,
you have met the man you have been waiting for all these years.]
(<EQUAL? ,HERO-CTR 2>
<MOVE ,LETTER ,PROTAGONIST>
<THIS-IS-IT ,LETTER>
<TELL ,SURPRISE
"the stranger bows. \"Well met, my lady.\" His accent
is cultured, his smile vibrant. \"I am Captain Nicholas Jamison, known
in these waters as 'The Falcon'. Your father has sent me.\" He chuckles
at your glare of distrust. \"Yes, you are like your sire. You needn't
believe me untried -- I carry this.\" He hands you" AR ,LETTER>
;<TELL
"To your surprise, the stranger bows. \"My lady, thank God I have found you.\"
His accent is cultured, his smile vibrant. \"I am Captain Nicholas Jamison,
known in these waters as 'The Falcon'. Your father sent me.\" He chuckles
at your glare of distrust. \"Yes, you are like your sire. You needn't believe
me untried -- I carry this.\" He hands you" AR ,LETTER>)
(<EQUAL? ,HERO-CTR 3>
<FSET ,DOOR ,OPENBIT>
<TELL ,CTHE-PIRATE-CAPTAIN
"glances around the empty room, then notices the coffer">
<COND ;(<IN? ,COFFER ,RETICULE>
<TELL ", outlined in" T ,RETICULE>)
(<IN? ,COFFER ,PROTAGONIST>
<TELL " in your arms">)>
<MOVE ,COFFER ,HERO>
<TELL
". \"Davis's safety box -- my men were hoping I'd
find it.\" He takes it and nudges the unconscious man on the floor, \"I
wonder how " D ,CRULLEY " knew you were here? Just his bad luck? He'll
be flogged when he wakes.\"|
The pirate bows. \"My lady, may I offer my protection and my
ship until your father is free?\"" CR>)
(<EQUAL? ,HERO-CTR 4 5>
<COND (<AND <EQUAL? ,HERO-CTR 4>
<EQUAL? ,REACTION ,REACTION-NEUTRAL>>
<SETG QUESTIONER ,HERO>
<TELL
"\"We haven't time to waste. Will you come willingly or not?\"
says" TR ,HERO>)
(T
<DEQUEUE I-MEET-HERO>
<DEQUEUE I-PIRATE-ATTACK>
<COND (<EQUAL? ,REACTION ,REACTION-POSITIVE>
<TELL
"He chuckles. \"Brave lady, to trust a stranger -- and a pirate.
Who knows, perhaps I forged your father's signature? Keep by my
side as we go to my ship -- few sailors respect a lady's dignity.\"
He helps you through" TR ,DOOR CR>)
(T
<TELL "He sighs, \"You share" T ,DAD "'s
stubborn streak. I wished not to do this.\" He leaps to your side,
hauling you up onto his shoulder, and carries you out of the room." T
,HERO " sets you on your feet again on the horror of the deck" ,PCR CR>)>
<FSET ,HERO ,NDESCBIT>
<MOVE ,HERO ,DEUX-DECK>
<GOTO ,DEUX-DECK>)>)>
<SETG HERO-CTR <+ ,HERO-CTR 1>>>
;"2nd meeting, in his quarters. Covers three turns."
<ROUTINE I-HSHIP ()
<TELL ,INDENT <GET ,HERO-SHIP-SPEECHES ,HERO-CTR> CR>
<COND (<EQUAL? ,HERO-CTR 2>
<REMOVE ,HERO>
<QUEUE I-HSECOND-BYE 8>)
(T
<QUEUE I-HSHIP 1>)>
<SETG HERO-CTR <+ ,HERO-CTR 1>>>
<GLOBAL HERO-SHIP-SPEECHES
<TABLE
"\"We have anchored off St. Sinistra,\" says Captain Jamison,
\"and I must look like a guest at Lafond's dance tonight. I will find and
free your father, and then finally wreak my revenge on Lafond.\" He half
draws his rapier from its scabbard."
"\"I am sorry you have been confined down here, but I don't trust my
lonely crew with such beauty. Crulley isn't the only man aboard with
few principles.\" He smiles at you, eyes lingering, and takes your hand. You
feel your color rising. \"If anything goes wrong, turn to Cookie. He is quite
deaf, but capable. He'll see you through.\""
"His look darkens. \"You should know why I hate Lafond:
Some years ago, as my brother and his bride sailed to a new life in
Virginia, pirates struck. Their ship was boarded, looted and burned, the
women taken, never to be seen again. A sailor, the one survivor, watched
as a man of Lafond's description shot my brother in the back as he tried
to save the women. Lafond has now bought respectability, but he shall
never buy peace.\" Jamison straightens resolutely, bows, and departs.">>
;<ROUTINE I-HSHIP ()
<COND (<EQUAL? ,HERO-CTR 1>
<QUEUE I-HSHIP 1>
<TELL ,INDENT
"\"We have anchored off " D ,ISLAND ",\" says " D ,HERO ", \"and I am
inviting myself to the ball at Lafond's mansion tonight. I hope to find and
rescue your father, and then to wreak final revenge against Lafond.\" He
half draws his rapier from its scabbard" ,PCR>)
(<EQUAL? ,HERO-CTR 2>
<QUEUE I-HSHIP 1>
<TELL ,INDENT
"\"I am sorry you have been confined down here, but I don't trust my
lonely crew with such beauty. " D ,CRULLEY " isn't the only man aboard with
few principles.\" He smiles at you, eyes lingering, \"Perhaps I just wanted
to keep the sight of you to myself.\"|
He takes " D ,HANDS ". \"I should return in a few hours with your
father. If all should not go well, turn to Rodney --" T ,COOKIE ", as he is
known to the men. He is gruff, but trustworthy. He'll see you through.\"" CR>)
(<EQUAL? ,HERO-CTR 3>
<REMOVE ,HERO>
<QUEUE I-HSECOND-BYE 8>
<TELL ,INDENT
"Jamison bows and deftly twists " D ,HANDS " so his lips brush hotly
against the inside of your wrist. As he leaves, he pushes" A ,CUPBOARD-OBJECT
" up against the doorway, one corner jutting somewhat through
the curtain. You hear a soft, \"Fare thee well,\" and he climbs the
steps to the quarterdeck" ,PCR>)
(T
<RFALSE>)>
<SETG HERO-CTR <+ ,HERO-CTR 1>>>
<ROUTINE I-HSECOND-BYE ()
<COND (<OR <RUNNING? ,I-OVERHEAR-CRULLEY>
<EQUAL? ,HERE ,SLEEPING-CUPBOARD>>
<QUEUE I-HSECOND-BYE 2>)
(T
<MOVE ,JEWEL ,PROTAGONIST>
<TELL ,INDENT "You hear">
<COND (<EQUAL? ,HERE ,CAPT-QUARTERS>
<TELL T ,CUPBOARD-OBJECT " scrape">)
(<EQUAL? ,HERE ,LANDING>
<TELL T ,DOOR " being unbarred">)
(T
<TELL " a footstep">)>
<TELL ", ">
<COND (<NOT <FSET? ,CHEMISE ,EVERYBIT>>
<TELL
"turn, and cover " D ,ME " as best you can with what you are holding,
for Jamison stands there, his eyes burning through your lightweight chemise.
He chuckles, \"I am not sorry in the least that I surprised you.">)
(,BOY-DRESS?
<TELL
"and" T ,HERO "'s startled laugh. \"For a moment I thought you were Matthew,
the boy who used to sleep in the cupboard. He ran off last port.">)
(T
<TELL
"and turn to see" T ,HERO ". \"Hello!">)>
<COND (<NOT <EQUAL? ,HERE ,CAPT-QUARTERS>>
<TELL
" How did you escape? Don't stutter, I won't lock you up again -- you are
safe as long as you remain below-decks.">)>
<TELL
" I came down to give you this -- my allotment from" T ,COFFER ".\" He nods
at the box in his arms.|
Jamison starts to pin" A ,JEWEL " on your clothes, but, \"Devil take it,
the clasp is broken. I'll have it repaired.\" He folds the pretty thing into "
D ,HANDS ". \"And I meant to reassure you that if the men suddenly abandon
ship, they are off to help me. Rodney will stay behind with you.\" He ">
;[He takes a white card from" T ,COFFER "]
<COND (<EQUAL? ,HERE ,CAPT-QUARTERS>
<MOVE ,COFFER ,HERE>
<TELL
"drops" T ,COFFER " on the floor, smiling in farewell,">)
(T
<MOVE ,COFFER ,PROTAGONIST>
<TELL
"hands" T ,COFFER " to you. \"Please return
this to my quarters for me, will you?\"">)>
<TELL " and walks swiftly ">
<COND (<EQUAL? ,HERE ,LANDING>
<TELL
"up the stairs to the deck, barring the door a moment later">)
(T
<TELL "away">)>
<TELL ,PCR>
<QUEUE I-SMELL-SMOKE 3>
<QUEUE I-HERO-TO-ISLAND 5>
<RFATAL>)>>
<GLOBAL PARTNER <>>
<ROUTINE I-HDANCE ()
<COND (<AND <EQUAL? ,HERO-CTR 1>
<EQUAL? ,BALLROOM ,HERE>>
<MOVE ,HERO ,HERE>
<SETG LAFOND-CTR 1>
<QUEUE I-LDANCE 7>
<SETG PARTNER ,HERO>
<SETG QUESTIONER ,HERO>
<SETG AWAITING-REPLY 14>
<QUEUE I-REPLY 2>
<SETG DANCED-WITH ,HERO>
<TELL
,INDENT D ,HERO " moves up to you, saying, \"May I have this dance?\"
He doesn't await an answer, sweeping you out onto" ,DANCE-FLOOR ,PCR>)
(<EQUAL? ,HERO-CTR 2>
<SETG QUESTIONER ,HERO>
<COND (<NOT ,MET-ALREADY>
<SETG MET-ALREADY T>
<TELL ,INDENT "\"" ,FIRST-SIGHTING
"smiles suddenly. \"Why should I complain? You are quite safe, since
no one expects you here. And you are looking lovely.\"" CR>)
(T
<HERO-TALKS>)>
<COND (<EQUAL? ,HERE ,BALLROOM>
<TELL ,INDENT
"The steps of the dance separate you a moment, as you twirl around and
curtsey to another dancer. You glide back into the captain's arms" ,PCR>)>)
(<EQUAL? ,HERO-CTR 3>
<SETG QUESTIONER ,HERO>
<HERO-TALKS>
<COND (<EQUAL? ,HERE ,BALLROOM>
<TELL ,INDENT
"Your hands linked tightly with his and held high over " D ,HEAD "s, a
line of dancers files between you and Jamison" ,PCR>)>)
(<EQUAL? ,HERO-CTR 4>
<SETG QUESTIONER ,HERO>
<HERO-TALKS>
<COND (<EQUAL? ,HERE ,BALLROOM>
<TELL ,INDENT
"Together you whirl around the ballroom, his arm snug around your waist,
leading you gracefully, masterfully.|
Nicholas's grip tenses as he nods to a bewigged man staring at you.
You turn, and the man moves on" ,PCR>)>)
(<EQUAL? ,HERO-CTR 5>
<REMOVE ,HERO>
<SETG PARTNER <>>
<DEQUEUE I-HDANCE>
<HERO-TALKS>
<TELL ,INDENT
"The music ends with a flourish">
<COND (<EQUAL? ,HERE ,BALLROOM>
<TELL
" and you pirouette once more before curtseying to Jamison. As you move">)
(T
<TELL ". As he guides you back">)>
<TELL " to the side of" ,DANCE-FLOOR ", Nick adds, \"We
should separate -- I'm sure I am being watched. You would be safer
aboard" T ,SHIP ". If you slip out the veranda doors, no one will notice
you leaving.\" He touches " D ,HANDS " and dissolves into the crowd" ,PCR>
<COND (<NOT <EQUAL? ,HERE ,BALLROOM>>
<GOTO ,BALLROOM>)>)
(T
<RFALSE>)>
<SETG HERO-CTR <+ ,HERO-CTR 1>>>
<ROUTINE I-HARRESTED ("OPTIONAL" (FROM-LDANCE <>))
<SETG HERO-ARRESTED T>
<TELL ,INDENT
"There is a commotion from the west. A woman screams and a man yells,
\"Stop, Pirate!\" ">
<COND (<AND <NOT .FROM-LDANCE>
<NOT <EQUAL? ,HERE ,FOYER>>>
<COND (<HELD? ,HAT>
<FCLEAR ,HAT ,WORNBIT>
<MOVE ,HAT ,LIBRARY>)>
<TELL
"You run to the foyer in time to see two dragoons dragging out
the battered frame of" T ,HERO>)
(T
<TELL
"and Jamison is dragged out of the ballroom by two burly dragoons">)>
<TELL ,PCR
" An officer quiets the guests, \"This is the buccaneer who has been
pirating our ships. He had the audacity to come here tonight intending
to assassinate our dear governor. Do not worry, ladies, he was arrogant
enough to come alone.\" The officer marches after his men. "
CTHE ,DANCERS "s return to their banal conversations" ,PCR>
<COND (<NOT .FROM-LDANCE>
<CRLF>
<GOTO ,FOYER>)
(T
<QUEUE I-LDANCE 1>
<SETG PARTNER ,LAFOND>
<TELL ,INDENT
"Only the painful grip" T ,LAFOND " has on your arm prevents you from
swooning away. \"Ah, so that's the way of it,\" he purrs, noticing your
sudden pallor. \"All the better for me.\" He pulls you unresisting into
a dance." CR>)>>
<GLOBAL MET-ALREADY <>> ;"gets set by first meeting on land."
<GLOBAL FIRST-SIGHTING "What the devil are you doing here!
Lafond is a dangerous man to play with!\" Jamison ">
<GLOBAL HERO-LEAVES-FOLLY
" With an engaging smile he bows and leaves the folly.|">
<ROUTINE I-HFOLLY ("OPTIONAL" (CALLED-BY-HERO-F <>))
<COND (<NOT <EQUAL? ,HERE ,FOLLY>>
<RFALSE>)
(T
<SETG QUESTIONER ,HERO>
<COND (<NOT .CALLED-BY-HERO-F>
<TELL ,INDENT>)>
<COND (<EQUAL? ,HERO-CTR 1>
<QUEUE I-HFOLLY -1>
<MOVE ,HERO ,FOLLY>
<TELL D ,HERO
" enters" T ,FOLLY-OBJECT ", stooping to avoid the flowers dangling over
the door. \"I thought I heard someone.">
<COND (<NOT ,MET-ALREADY>
<SETG MET-ALREADY T>
<TELL " " ,FIRST-SIGHTING>)
(T
<TELL "\" Jamison ">)>
<TELL
"sighs. \"What an astonishing girl you are, my dear. ">
<COND (<NOT <FSET? ,CHEMISE ,EVERYBIT>>
<TELL
"If --\"" ,EYES-RAKE ", \"somewhat underdressed">)
(,BOY-DRESS?
<TELL "And so ingeniously dressed">)
(T
<TELL "And looking more lovely than ever">)>
<TELL
".\" He plucks" A ,FLOWER " from the tangle above the door, and sets it
in your hair. \"The beauty of this blossom is nothing to yours.\"" CR>
<MOVE ,FLOWER ,PROTAGONIST>
<FCLEAR ,FLOWER ,NDESCBIT>
<FSET ,FLOWER ,TAKEBIT>)
(<AND <OR <EQUAL? ,REACTION ,REACTION-NEGATIVE>
<EQUAL? ,HERO-CTR 6>>
<IN? ,HERO ,HERE>>
<DEQUEUE I-HFOLLY>
<SETG QUESTIONER <>>
<REMOVE ,HERO>
<TELL
"Jamison backs away from you, smiling wistfully">
<TELL "." ,HERO-LEAVES-FOLLY>)
(<EQUAL? ,HERO-CTR 2>
<TELL
"Catching his breath, Jamison pulls you against
him, his hands circling your waist">
<COND (<IN? ,FLOWER ,PROTAGONIST>
<TELL
", crushing" T ,FLOWER " between you">)>
<TELL
". \"Darling,\" he whispers, leaning over you, \"oh, my angel ...\"" CR>)
(<EQUAL? ,HERO-CTR 3>
<SETG AWAITING-REPLY 15>
<QUEUE I-REPLY 2>
<TELL
"\"My lovely,\" Jamison says huskily. His eyes burn intently, their blue
like the sea on a summer day. A shiver of warmth flows through you, and
you tremble at his touch. The pirate's hands, warm and exciting, caress
you, searing through the thin linen of your chemise. His lips
near yours, his breath softly scented. \"May I kiss you?\"" CR>
;<COND (,BOY-DRESS?
<TELL "inside the loose shirt">)
(<OR <FSET? ,GOWN ,WORNBIT>
<FSET? ,DRESS ,WORNBIT>>
<TELL "into your bodice">)
(T
<TELL "up">)>)
(<EQUAL? ,HERO-CTR 4>
<TELL
"Tender is his kiss, soft his lips as his body presses hard against you.
You drown in the tide of your passion, swept like the sea against the rocks
of the shore." CR>)
(<EQUAL? ,HERO-CTR 5>
<REMOVE ,HERO>
;<SETG QUESTIONER <>>
;<DEQUEUE I-HFOLLY>
<TELL
"With a pent-up sigh, Nicholas forces himself away from you. \"Now is not the
time or the place to advance my suit,\" he says, wistfully. \"But the night
is still young and you are so beautiful! I must be gone, lest I lose my soul
in you.\"" ,HERO-LEAVES-FOLLY>)>)>
<SETG HERO-CTR <+ ,HERO-CTR 1>>>
;<ROUTINE I-HFOLLY ("OPTIONAL" (CALLED-BY-HERO-F <>))
<COND (<NOT <EQUAL? ,HERE ,FOLLY>>
<RFALSE>)
(T
<SETG QUESTIONER ,HERO>
<COND (<NOT .CALLED-BY-HERO-F>
<TELL ,INDENT>)>
<COND (<EQUAL? ,HERO-CTR 1>
<QUEUE I-HFOLLY -1>
<MOVE ,HERO ,FOLLY>
<TELL D ,HERO
" enters the folly, stooping to avoid the flowers dangling over the door.
\"I thought I heard someone.">
<COND (<NOT ,MET-ALREADY>
<SETG MET-ALREADY T>
<TELL " "
,FIRST-SIGHTING " Jamison sighs. \"What an astonishing girl you are, my dear.
And ">
<COND (,BOY-DRESS?
<TELL "rather ingeniously dressed, too">)
(<FSET? ,GOWN ,WORNBIT>
<TELL "looking more lovely than ever">)
(<NOT <FSET? ,CHEMISE ,EVERYBIT>>
<TELL
"--\"" ,EYES-RAKE ", \"ahem, somewhat underdressed">)
(T
<TELL "that is that">)>
<TELL ".\" " <PICK-ONE ,MANNERISMS> ,PCR>)
(T
<MOVE ,FLOWER ,PROTAGONIST>
<FCLEAR ,FLOWER ,NDESCBIT>
<FSET ,FLOWER ,TAKEBIT>
<TELL
"\" He plucks" A ,FLOWER " from the tangle above the door, and sets it in your
hair. \"The beauty of this " D ,FLOWER " is nothing to yours.\"" CR>)>)
(<EQUAL? ,REACTION ,REACTION-NEGATIVE>
<TELL
"Jamison backs away from you, smiling wistfully">
<COND (<EQUAL? ,HERO-CTR 5>
<REMOVE ,HERO>
<TELL "." ,HERO-LEAVES-FOLLY>)
(T
<TELL ,PCR>)>)
(<EQUAL? ,HERO-CTR 2>
<TELL
"Catching his breath, Jamison pulls you against
him, his hands circling your waist">
<COND (<IN? ,FLOWER ,PROTAGONIST>
<TELL
", crushing" T ,FLOWER " between you">)>
<TELL
". \"Darling,\" he whispers, leaning over you, \"oh, my angel ...\"" CR>)
(<EQUAL? ,HERO-CTR 3>
<SETG AWAITING-REPLY 15>
<QUEUE I-REPLY 2>
<TELL
"\"My lovely,\" Jamison says huskily. His eyes burn intently, their blue
like the sea on a summer day. A shiver of warmth flows through you, and
you tremble at his touch. The pirate's hands, warm and exciting, caress
you, searing through the thin linen of your chemise. His lips
near yours, his breath softly scented. \"May I kiss you?\"" CR>
;<COND (,BOY-DRESS?
<TELL "inside the loose shirt">)
(<OR <FSET? ,GOWN ,WORNBIT>
<FSET? ,DRESS ,WORNBIT>>
<TELL "into your bodice">)
(T
<TELL "up">)>)
(<EQUAL? ,HERO-CTR 4>
<TELL
"Tender is his kiss, soft his lips, yet his body presses hard against you.
You drown in the tide of your passion, swept like the sea against the rocks
of the shore." CR>)
(<EQUAL? ,HERO-CTR 5>
<REMOVE ,HERO>
<SETG QUESTIONER <>>
<DEQUEUE I-HFOLLY>
<TELL
"With a pent-up sigh, Nicholas forces himself away from you. \"Now is not the
time or the place to advance my suit,\" he says, wistfully. \"But the night
is still young and you are so beautiful! I must be gone, lest I lose my soul
in you.\"" ,HERO-LEAVES-FOLLY>)>)>
<SETG HERO-CTR <+ ,HERO-CTR 1>>>
<ROUTINE HERO-TALKS ()
<TELL ,INDENT>
<COND (<AND <PROB 65>
<L? ,WHAT-HERO-SAYS 3>>
<COND (<AND <EQUAL? ,WHAT-HERO-SAYS 0>
,HDAD-SPEECH>
<TELL <PICK-ONE ,MANNERISMS> ,PCR>)
(T
<TELL <GET ,HERO-SPEECHES ,WHAT-HERO-SAYS> ,PCR>
<SETG WHAT-HERO-SAYS <+ ,WHAT-HERO-SAYS 1>>)>)
(T
<TELL <PICK-ONE ,MANNERISMS> ,PCR>)>>
<GLOBAL WHAT-HERO-SAYS 0>
<GLOBAL HERO-SPEECHES
<TABLE
"\"I haven't found your father. We've long suspected a passage
under the library, but I cannot find an entrance,\" says Jamison"
"\"If there is any trouble, and I am unable to help -- a signal from
an upstairs seaward window will bring my men. They can be here in moments,\"
the Captain says"
"\"I wish you would call me 'Nicholas' -- I feel I know you much
better than our brief acquaintance would allow.\" He presses your hand">>
<GLOBAL MANNERISMS
<LTABLE
0
"Jamison touches your hair softly"
"Jamison grins down at you, a dazzling white smile"
"The blue of the captain's eyes seems to deepen, looking at you"
"His eyes twinkle, like moonlight on the sea"
"Nicholas's hands are smooth and cool">>
<OBJECT RAPIER
(IN HERO)
(DESC "rapier")
(DESCFCN RAPIER-F)
(SYNONYM SWORD RAPIER)
(ADJECTIVE SHARP)
(FLAGS TRYTAKEBIT TAKEBIT)
(ACTION RAPIER-F)>
<ROUTINE RAPIER-F ("OPTIONAL" (OARG <>))
<COND (.OARG
<COND (<EQUAL? ,HERE ,DUNGEON>
<COND (<EQUAL? .OARG ,M-DESC?>
<RTRUE>)>
<TELL ,INDENT
"A rapier lies in the half-dark of a corner.">)
(T
<RFALSE>)>)
(<VERB? TAKE>
<COND (<AND <NOT <FSET? ,HERO ,DEADBIT>>
<IN? ,HERO ,HERE>>
<TELL
"Jamison prevents you, \"This is not a weapon for ladies.\"" CR>)
(<AND <EQUAL? ,HERE ,DUNGEON>
<IN? ,CRULLEY ,DUNGEON>
<NOT <FSET? ,RAPIER ,TOUCHBIT>>
<NOT <EQUAL? <ITAKE <>> ,M-FATAL <>>>>
<TELL "Taken. "
D ,CRULLEY " snorts, \"Be careful, you might hurt yer dearie.\"" CR>)
(<IN? ,RAPIER ,COOKIE>
<TELL D ,COOKIE
" objects. \"It ain't fer a lady.\"" CR>)>)
(<AND <VERB? THROW PUT PUT-THROUGH>
<OR <PRSI? ,TRAP>
<AND <PRSI? ,CRULLEY>
<FSET? ,CRULLEY ,MUNGBIT>>>>
<TELL "But you might need it later!" CR>)
(<VERB? EXAMINE>
<TELL
"Jamison's rapier is a dangerous looking sword with a narrow pointed blade">
<COND (<NOT <EQUAL? ,HERE ,CABIN ,DEUX-DECK>>
<TELL ". It is decorated with a big floppy ribbon">)>
<TELL ,PCR>)>>
| 412 | 0.663661 | 1 | 0.663661 | game-dev | MEDIA | 0.982306 | game-dev | 0.505056 | 1 | 0.505056 |
Kaedrin/nwn2cc | 1,612 | Source/KaedPRCPack_v1.42.1_Override_Dialogtlk/Scripts/cmi_s2_elemshield.nss | //::///////////////////////////////////////////////
//:: Elemental Shield
//:: cmi_s2_elemshield
//:: Purpose:
//:: Created By: Kaedrin (Matt)
//:: Created On: May 13, 2008
//:://////////////////////////////////////////////
#include "nwn2_inc_spells"
#include "cmi_ginc_chars"
#include "cmi_ginc_spells"
void main()
{
int nSpellID = ELEM_ARCHER_ELEM_SHIELD;
int nDamageType = 0;
int nLevel = GetLevelByClass(CLASS_ELEM_ARCHER, OBJECT_SELF);
RemoveSpellEffects(nSpellID, OBJECT_SELF, OBJECT_SELF);
if (GetHasFeat(FEAT_ELEM_ARCHER_PATH_AIR))
nDamageType = DAMAGE_TYPE_ELECTRICAL;
else
if (GetHasFeat(FEAT_ELEM_ARCHER_PATH_EARTH))
nDamageType = DAMAGE_TYPE_ACID;
else
if (GetHasFeat(FEAT_ELEM_ARCHER_PATH_FIRE))
nDamageType = DAMAGE_TYPE_FIRE;
else
if (GetHasFeat(FEAT_ELEM_ARCHER_PATH_WATER))
nDamageType = DAMAGE_TYPE_COLD;
int nDuration = GetAbilityModifier(ABILITY_CONSTITUTION);
if (nDuration < 0)
nDuration = 0;
nDuration += nLevel;
int nBonus = nLevel/2;
if (nLevel == 5)
nBonus = 3;
if (GetHasFeat(FEAT_ELEM_ARCHER_IMP_ELEM_SHIELD))
{
nBonus = nLevel;
nDuration = nDuration * 2;
}
effect eDS = EffectDamageShield(nBonus, DAMAGE_BONUS_1d4, nDamageType);
effect eAC = EffectACIncrease(nBonus);
effect eDur = EffectVisualEffect(VFX_DUR_ELEMENTAL_SHIELD);
effect eLink = EffectLinkEffects(eAC, eDS);
eLink = EffectLinkEffects(eDur, eLink);
eLink = SupernaturalEffect(eLink);
eLink = SetEffectSpellId(eLink, nSpellID);
DelayCommand(0.1f, ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eLink, OBJECT_SELF, RoundsToSeconds(nDuration)));
} | 412 | 0.835968 | 1 | 0.835968 | game-dev | MEDIA | 0.767583 | game-dev | 0.909093 | 1 | 0.909093 |
motorsep/StormEngine2 | 40,643 | neo/swf/SWF_SpriteInstance.cpp | /*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
Copyright (C) 2014-2016 Robert Beckebans
Copyright (C) 2014-2016 Kot in Action Creative Artel
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#pragma hdrstop
#include "precompiled.h"
idSWFScriptObject_SpriteInstancePrototype spriteInstanceScriptObjectPrototype;
/*
========================
idSWFSpriteInstance::idSWFSpriteInstance
========================
*/
idSWFSpriteInstance::idSWFSpriteInstance() :
isPlaying( true ),
isVisible( true ),
childrenRunning( true ),
firstRun( false ),
currentFrame( 0 ),
frameCount( 0 ),
sprite( NULL ),
parent( NULL ),
depth( 0 ),
itemIndex( 0 ),
materialOverride( NULL ),
materialWidth( 0 ),
materialHeight( 0 ),
xOffset( 0.0f ),
yOffset( 0.0f ),
moveToXScale( 1.0f ),
moveToYScale( 1.0f ),
moveToSpeed( 1.0f ),
stereoDepth( 0 )
{
}
/*
========================
idSWFSpriteInstance::Init
========================
*/
void idSWFSpriteInstance::Init( idSWFSprite* _sprite, idSWFSpriteInstance* _parent, int _depth )
{
sprite = _sprite;
parent = _parent;
depth = _depth;
frameCount = sprite->frameCount;
scriptObject = idSWFScriptObject::Alloc();
scriptObject->SetPrototype( &spriteInstanceScriptObjectPrototype );
scriptObject->SetSprite( this );
firstRun = true;
actionScript = idSWFScriptFunction_Script::Alloc();
idList<idSWFScriptObject*, TAG_SWF> scope;
scope.Append( sprite->swf->globals );
scope.Append( scriptObject );
actionScript->SetScope( scope );
actionScript->SetDefaultSprite( this );
for( int i = 0; i < sprite->doInitActions.Num(); i++ )
{
actionScript->SetData( sprite->doInitActions[i].Ptr(), sprite->doInitActions[i].Length() );
actionScript->Call( scriptObject, idSWFParmList() );
}
Play();
}
/*
========================
idSWFSpriteInstance::~idSWFSpriteInstance
========================
*/
idSWFSpriteInstance::~idSWFSpriteInstance()
{
if( parent != NULL )
{
parent->scriptObject->Set( name, idSWFScriptVar() );
}
FreeDisplayList();
displayList.Clear();
scriptObject->SetSprite( NULL );
scriptObject->Clear();
scriptObject->Release();
actionScript->Release();
}
/*
========================
idSWFSpriteInstance::FreeDisplayList
========================
*/
void idSWFSpriteInstance::FreeDisplayList()
{
for( int i = 0; i < displayList.Num(); i++ )
{
sprite->swf->spriteInstanceAllocator.Free( displayList[i].spriteInstance );
sprite->swf->textInstanceAllocator.Free( displayList[i].textInstance );
}
displayList.SetNum( 0 ); // not calling Clear() so we don't continuously re-allocate memory
currentFrame = 0;
}
/*
========================
idSWFSpriteInstance::FindDisplayEntry
========================
*/
swfDisplayEntry_t* idSWFSpriteInstance::FindDisplayEntry( int depth )
{
int len = displayList.Num();
int mid = len;
int offset = 0;
while( mid > 0 )
{
mid = len >> 1;
if( displayList[offset + mid].depth <= depth )
{
offset += mid;
}
len -= mid;
}
if( displayList[offset].depth == depth )
{
return &displayList[offset];
}
return NULL;
}
/*
========================
idSWFSpriteInstance::AddDisplayEntry
========================
*/
swfDisplayEntry_t* idSWFSpriteInstance::AddDisplayEntry( int depth, int characterID )
{
int i = 0;
for( ; i < displayList.Num(); i++ )
{
if( displayList[i].depth == depth )
{
return NULL;
}
if( displayList[i].depth > depth )
{
break;
}
}
swfDisplayEntry_t& display = displayList[ displayList.Insert( swfDisplayEntry_t(), i ) ];
display.depth = depth;
display.characterID = characterID;
idSWFDictionaryEntry* dictEntry = sprite->swf->FindDictionaryEntry( characterID );
if( dictEntry != NULL )
{
if( dictEntry->type == SWF_DICT_SPRITE )
{
display.spriteInstance = sprite->swf->spriteInstanceAllocator.Alloc();
display.spriteInstance->Init( dictEntry->sprite, this, depth );
display.spriteInstance->RunTo( 1 );
}
else if( dictEntry->type == SWF_DICT_EDITTEXT )
{
display.textInstance = sprite->swf->textInstanceAllocator.Alloc();
display.textInstance->Init( dictEntry->edittext, sprite->GetSWF() );
}
}
return &display;
}
/*
========================
idSWFSpriteInstance::RemoveDisplayEntry
========================
*/
void idSWFSpriteInstance::RemoveDisplayEntry( int depth )
{
swfDisplayEntry_t* entry = FindDisplayEntry( depth );
if( entry != NULL )
{
sprite->swf->spriteInstanceAllocator.Free( entry->spriteInstance );
sprite->swf->textInstanceAllocator.Free( entry->textInstance );
displayList.RemoveIndex( displayList.IndexOf( entry ) );
}
}
/*
================================================
idSort_SpriteDepth
================================================
*/
class idSort_SpriteDepth : public idSort_Quick< swfDisplayEntry_t, idSort_SpriteDepth >
{
public:
int Compare( const swfDisplayEntry_t& a, const swfDisplayEntry_t& b ) const
{
return a.depth - b.depth;
}
};
/*
========================
idSWFSpriteInstance::SwapDepths
========================
*/
void idSWFSpriteInstance::SwapDepths( int depth1, int depth2 )
{
for( int i = 0; i < displayList.Num(); i++ )
{
if( displayList[i].depth == depth1 )
{
displayList[i].depth = depth2;
}
else if( displayList[i].depth == depth2 )
{
displayList[i].depth = depth1;
}
if( displayList[i].spriteInstance != NULL )
{
displayList[i].spriteInstance->depth = displayList[i].depth;
}
}
displayList.SortWithTemplate( idSort_SpriteDepth() );
}
/*
===================
idSWFSpriteInstance::Run
===================
*/
bool idSWFSpriteInstance::Run()
{
if( !isVisible )
{
return false;
}
if( childrenRunning )
{
childrenRunning = false;
for( int i = 0; i < displayList.Num(); i++ )
{
if( displayList[i].spriteInstance != NULL )
{
Prefetch( displayList[i].spriteInstance, 0 );
}
}
for( int i = 0; i < displayList.Num(); i++ )
{
if( displayList[i].spriteInstance != NULL )
{
childrenRunning |= displayList[i].spriteInstance->Run();
}
}
}
if( isPlaying )
{
if( currentFrame == frameCount )
{
if( frameCount > 1 )
{
FreeDisplayList();
RunTo( 1 );
}
}
else
{
RunTo( currentFrame + 1 );
}
}
return childrenRunning || isPlaying;
}
/*
===================
idSWFSpriteInstance::RunActions
===================
*/
bool idSWFSpriteInstance::RunActions()
{
if( !isVisible )
{
actions.SetNum( 0 );
return false;
}
if( firstRun && scriptObject->HasProperty( "onLoad" ) )
{
firstRun = false;
idSWFScriptVar onLoad = scriptObject->Get( "onLoad" );
onLoad.GetFunction()->Call( scriptObject, idSWFParmList() );
}
if( onEnterFrame.IsFunction() )
{
onEnterFrame.GetFunction()->Call( scriptObject, idSWFParmList() );
}
for( int i = 0; i < actions.Num(); i++ )
{
actionScript->SetData( actions[i].data, actions[i].dataLength );
actionScript->Call( scriptObject, idSWFParmList() );
}
actions.SetNum( 0 );
for( int i = 0; i < displayList.Num(); i++ )
{
if( displayList[i].spriteInstance != NULL )
{
Prefetch( displayList[i].spriteInstance, 0 );
}
}
for( int i = 0; i < displayList.Num(); i++ )
{
if( displayList[i].spriteInstance != NULL )
{
displayList[i].spriteInstance->RunActions();
}
}
return true;
}
/*
===================
idSWFSpriteInstance::NextFrame
===================
*/
void idSWFSpriteInstance::NextFrame()
{
if( currentFrame < frameCount )
{
RunTo( currentFrame + 1 );
}
}
/*
===================
idSWFSpriteInstance::PrevFrame
===================
*/
void idSWFSpriteInstance::PrevFrame()
{
if( currentFrame > 1 )
{
RunTo( currentFrame - 1 );
}
}
/*
===================
idSWFSpriteInstance::Play
===================
*/
void idSWFSpriteInstance::Play()
{
for( idSWFSpriteInstance* p = parent; p != NULL; p = p->parent )
{
p->childrenRunning = true;
}
isPlaying = true;
}
/*
===================
idSWFSpriteInstance::Stop
===================
*/
void idSWFSpriteInstance::Stop()
{
isPlaying = false;
}
/*
===================
idSWFSpriteInstance::RunTo
===================
*/
void idSWFSpriteInstance::RunTo( int targetFrame )
{
if( targetFrame == currentFrame )
{
return; // otherwise we'll re-run the current frame
}
if( targetFrame < currentFrame )
{
FreeDisplayList();
}
if( targetFrame < 1 )
{
return;
}
if( targetFrame > sprite->frameOffsets.Num() - 1 )
{
targetFrame = sprite->frameOffsets.Num() - 1;
}
//actions.Clear();
uint32 firstActionCommand = sprite->frameOffsets[ targetFrame - 1 ];
for( uint32 c = sprite->frameOffsets[ currentFrame ]; c < sprite->frameOffsets[ targetFrame ]; c++ )
{
idSWFSprite::swfSpriteCommand_t& command = sprite->commands[ c ];
if( command.tag == Tag_DoAction && c < firstActionCommand )
{
// Skip DoAction up to the firstActionCommand
// This is to properly support skipping to a specific frame
// for example if we're on frame 3 and skipping to frame 10, we want
// to run all the commands PlaceObject commands for frames 4-10 but
// only the DoAction commands for frame 10
continue;
}
command.stream.Rewind();
switch( command.tag )
{
#define HANDLE_SWF_TAG( x ) case Tag_##x: x( command.stream ); break;
HANDLE_SWF_TAG( PlaceObject2 );
HANDLE_SWF_TAG( PlaceObject3 );
HANDLE_SWF_TAG( RemoveObject2 );
HANDLE_SWF_TAG( StartSound );
HANDLE_SWF_TAG( DoAction );
#undef HANDLE_SWF_TAG
default:
idLib::Printf( "Run Sprite: Unhandled tag %s\n", idSWF::GetTagName( command.tag ) );
}
}
currentFrame = targetFrame;
}
/*
========================
idSWFSpriteInstance::DoAction
========================
*/
void idSWFSpriteInstance::DoAction( idSWFBitStream& bitstream )
{
swfAction_t& action = actions.Alloc();
action.data = bitstream.ReadData( bitstream.Length() );
action.dataLength = bitstream.Length();
}
/*
========================
idSWFSpriteInstance::FindChildSprite
========================
*/
idSWFSpriteInstance* idSWFSpriteInstance::FindChildSprite( const char* targetName )
{
for( int i = 0; i < displayList.Num(); i++ )
{
if( displayList[i].spriteInstance != NULL )
{
if( displayList[i].spriteInstance->name.Icmp( targetName ) == 0 )
{
return displayList[i].spriteInstance;
}
}
}
return NULL;
}
/*
========================
idSWFSpriteInstance::ResolveTarget
Gets the sprite instance for names like:
../foo/bar
/foo/bar
foo/bar
========================
*/
idSWFSpriteInstance* idSWFSpriteInstance::ResolveTarget( const char* targetName )
{
if( targetName[0] == 0 )
{
return this;
}
idSWFSpriteInstance* target = this;
const char* c = targetName;
if( c[0] == '/' )
{
while( target->parent != NULL )
{
target = target->parent;
}
c++;
}
idStrList spriteNames;
spriteNames.Append( c );
for( int index = 0, ofs = spriteNames[index].Find( '/' ); ofs != -1; index++, ofs = spriteNames[index].Find( '/' ) )
{
spriteNames.Append( spriteNames[index].c_str() + ofs + 1 );
spriteNames[index].CapLength( ofs );
}
for( int i = 0; i < spriteNames.Num(); i++ )
{
if( spriteNames[i] == ".." )
{
target = target->parent;
}
else
{
target = target->FindChildSprite( spriteNames[i] );
}
if( target == NULL )
{
// Everything is likely to fail after this point
idLib::Warning( "SWF: Could not resolve %s, %s not found", targetName, spriteNames[i].c_str() );
return this;
}
}
return target;
}
/*
========================
idSWFSpriteInstance::FindFrame
========================
*/
uint32 idSWFSpriteInstance::FindFrame( const char* labelName ) const
{
int frameNum = atoi( labelName );
if( frameNum > 0 )
{
return frameNum;
}
for( int i = 0; i < sprite->frameLabels.Num(); i++ )
{
if( sprite->frameLabels[i].frameLabel.Icmp( labelName ) == 0 )
{
return sprite->frameLabels[i].frameNum;
}
}
idLib::Warning( "Could not find frame '%s' in sprite '%s'", labelName, GetName() );
return currentFrame;
}
/*
========================
idSWFSpriteInstance::FrameExists
========================
*/
bool idSWFSpriteInstance::FrameExists( const char* labelName ) const
{
int frameNum = atoi( labelName );
if( frameNum > 0 )
{
return frameNum <= sprite->frameCount;
}
for( int i = 0; i < sprite->frameLabels.Num(); i++ )
{
if( sprite->frameLabels[i].frameLabel.Icmp( labelName ) == 0 )
{
return true;
}
}
return false;
}
/*
========================
idSWFSpriteInstance::IsBetweenFrames
Checks if the current frame is between the given inclusive range.
========================
*/
bool idSWFSpriteInstance::IsBetweenFrames( const char* frameLabel1, const char* frameLabel2 ) const
{
return currentFrame >= FindFrame( frameLabel1 ) && currentFrame <= FindFrame( frameLabel2 );
}
/*
========================
idSWFSpriteInstance::SetMaterial
========================
*/
void idSWFSpriteInstance::SetMaterial( const idMaterial* material, int width, int height )
{
materialOverride = material;
if( materialOverride != NULL )
{
// Converting this to a short should be safe since we don't support images larger than 8k anyway
if( materialOverride->GetStage( 0 ) != NULL && materialOverride->GetStage( 0 )->texture.cinematic != NULL )
{
materialWidth = 256;
materialHeight = 256;
}
else
{
assert( materialOverride->GetImageWidth() > 0 && materialOverride->GetImageHeight() > 0 );
assert( materialOverride->GetImageWidth() <= 8192 && materialOverride->GetImageHeight() <= 8192 );
materialWidth = ( uint16 )materialOverride->GetImageWidth();
materialHeight = ( uint16 )materialOverride->GetImageHeight();
}
}
else
{
materialWidth = 0;
materialHeight = 0;
}
if( width >= 0 )
{
materialWidth = ( uint16 )width;
}
if( height >= 0 )
{
materialHeight = ( uint16 )height;
}
}
/*
========================
idSWFSpriteInstance::SetVisible
========================
*/
void idSWFSpriteInstance::SetVisible( bool visible )
{
isVisible = visible;
if( isVisible )
{
for( idSWFSpriteInstance* p = parent; p != NULL; p = p->parent )
{
p->childrenRunning = true;
}
}
}
/*
========================
idSWFSpriteInstance::PlayFrame
========================
*/
void idSWFSpriteInstance::PlayFrame( const idSWFParmList& parms )
{
if( parms.Num() > 0 )
{
actions.Clear();
RunTo( FindFrame( parms[0].ToString() ) );
Play();
}
else
{
idLib::Warning( "gotoAndPlay: expected 1 paramater" );
}
}
/*
========================
idSWFSpriteInstance::StopFrame
========================
*/
void idSWFSpriteInstance::StopFrame( const idSWFParmList& parms )
{
if( parms.Num() > 0 )
{
if( parms[0].IsNumeric() && parms[0].ToInteger() < 1 )
{
RunTo( FindFrame( "1" ) );
}
else
{
RunTo( FindFrame( parms[0].ToString() ) );
}
Stop();
}
else
{
idLib::Warning( "gotoAndStop: expected 1 paramater" );
}
}
/*
========================
idSWFSpriteInstance::GetXPos
========================
*/
float idSWFSpriteInstance::GetXPos() const
{
if( parent == NULL )
{
return 0.0f;
}
swfDisplayEntry_t* thisDisplayEntry = parent->FindDisplayEntry( depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != this )
{
idLib::Warning( "GetXPos: Couldn't find our display entry in our parent's display list for depth %d", depth );
return 0.0f;
}
return thisDisplayEntry->matrix.tx;
}
/*
========================
idSWFSpriteInstance::GetYPos
========================
*/
float idSWFSpriteInstance::GetYPos( bool overallPos ) const
{
if( parent == NULL )
{
return 0.0f;
}
swfDisplayEntry_t* thisDisplayEntry = parent->FindDisplayEntry( depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != this )
{
idLib::Warning( "GetYPos: Couldn't find our display entry in our parents display list for depth %d", depth );
return 0.0f;
}
return thisDisplayEntry->matrix.ty;
}
/*
========================
idSWFSpriteInstance::SetXPos
========================
*/
void idSWFSpriteInstance::SetXPos( float xPos )
{
if( parent == NULL )
{
return;
}
swfDisplayEntry_t* thisDisplayEntry = parent->FindDisplayEntry( depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != this )
{
idLib::Warning( "_y: Couldn't find our display entry in our parents display list" );
return;
}
thisDisplayEntry->matrix.tx = xPos;
}
/*
========================
idSWFSpriteInstance::SetYPos
========================
*/
void idSWFSpriteInstance::SetYPos( float yPos )
{
if( parent == NULL )
{
return;
}
swfDisplayEntry_t* thisDisplayEntry = parent->FindDisplayEntry( depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != this )
{
idLib::Warning( "_y: Couldn't find our display entry in our parents display list" );
return;
}
thisDisplayEntry->matrix.ty = yPos;
}
/*
========================
idSWFSpriteInstance::SetPos
========================
*/
void idSWFSpriteInstance::SetPos( float xPos, float yPos )
{
if( parent == NULL )
{
return;
}
swfDisplayEntry_t* thisDisplayEntry = parent->FindDisplayEntry( depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != this )
{
idLib::Warning( "_y: Couldn't find our display entry in our parents display list" );
return;
}
thisDisplayEntry->matrix.tx = xPos;
thisDisplayEntry->matrix.ty = yPos;
}
/*
========================
idSWFSpriteInstance::SetRotation
========================
*/
void idSWFSpriteInstance::SetRotation( float rot )
{
if( parent == NULL )
{
return;
}
swfDisplayEntry_t* thisDisplayEntry = parent->FindDisplayEntry( depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != this )
{
idLib::Warning( "_rotation: Couldn't find our display entry in our parents display list" );
return;
}
swfMatrix_t& matrix = thisDisplayEntry->matrix;
float xscale = matrix.Scale( idVec2( 1.0f, 0.0f ) ).Length();
float yscale = matrix.Scale( idVec2( 0.0f, 1.0f ) ).Length();
float s, c;
idMath::SinCos( DEG2RAD( rot ), s, c );
matrix.xx = c * xscale;
matrix.yx = s * xscale;
matrix.xy = -s * yscale;
matrix.yy = c * yscale;
}
/*
========================
idSWFSpriteInstance::SetScale
========================
*/
void idSWFSpriteInstance::SetScale( float x, float y )
{
if( parent == NULL )
{
return;
}
swfDisplayEntry_t* thisDisplayEntry = parent->FindDisplayEntry( depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != this )
{
idLib::Warning( "scale: Couldn't find our display entry in our parents display list" );
return;
}
float newScale = x / 100.0f;
// this is done funky to maintain the current rotation
idVec2 currentScale = thisDisplayEntry->matrix.Scale( idVec2( 1.0f, 0.0f ) );
if( currentScale.Normalize() == 0.0f )
{
thisDisplayEntry->matrix.xx = newScale;
thisDisplayEntry->matrix.yx = 0.0f;
}
else
{
thisDisplayEntry->matrix.xx = currentScale.x * newScale;
thisDisplayEntry->matrix.yx = currentScale.y * newScale;
}
newScale = y / 100.0f;
// this is done funky to maintain the current rotation
currentScale = thisDisplayEntry->matrix.Scale( idVec2( 0.0f, 1.0f ) );
if( currentScale.Normalize() == 0.0f )
{
thisDisplayEntry->matrix.yy = newScale;
thisDisplayEntry->matrix.xy = 0.0f;
}
else
{
thisDisplayEntry->matrix.yy = currentScale.y * newScale;
thisDisplayEntry->matrix.xy = currentScale.x * newScale;
}
}
/*
========================
idSWFSpriteInstance::SetMoveToScale
========================
*/
void idSWFSpriteInstance::SetMoveToScale( float x, float y )
{
moveToXScale = x;
moveToYScale = y;
}
/*
========================
idSWFSpriteInstance::SetMoveToScale
========================
*/
bool idSWFSpriteInstance::UpdateMoveToScale( float speed )
{
if( parent == NULL )
{
return false;
}
swfDisplayEntry_t* thisDisplayEntry = parent->FindDisplayEntry( depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != this )
{
idLib::Warning( "SetMoveToScale: Couldn't find our display entry in our parents display list" );
return false;
}
swfMatrix_t& matrix = thisDisplayEntry->matrix;
float xscale = matrix.Scale( idVec2( 1.0f, 0.0f ) ).Length() * 100.0f;
float yscale = matrix.Scale( idVec2( 0.0f, 1.0f ) ).Length() * 100.0f;
float toX = xscale;
if( moveToXScale >= 0.0f )
{
toX = moveToXScale * 100.0f;
}
float toY = yscale;
if( moveToYScale >= 0.0f )
{
toY = moveToYScale * 100.0f;
}
int rXTo = idMath::Ftoi( toX + 0.5f );
int rYTo = idMath::Ftoi( toY + 0.5f );
int rXScale = idMath::Ftoi( xscale + 0.5f );
int rYScale = idMath::Ftoi( yscale + 0.5f );
if( rXTo == rXScale && rYTo == rYScale )
{
return false;
}
float newXScale = xscale;
float newYScale = yscale;
if( rXTo != rXScale && toX >= 0.0f )
{
if( toX < xscale )
{
newXScale -= speed;
newXScale = idMath::ClampFloat( toX, 100.0f, newXScale );
}
else if( toX > xscale )
{
newXScale += speed;
newXScale = idMath::ClampFloat( 0.0f, toX, newXScale );
}
}
if( rYTo != rYScale && toY >= 0.0f )
{
if( toY < yscale )
{
newYScale -= speed;
newYScale = idMath::ClampFloat( toY, 100.0f, newYScale );
}
else if( toY > yscale )
{
newYScale += speed;
newYScale = idMath::ClampFloat( 0.0f, toY, newYScale );
}
}
SetScale( newXScale, newYScale );
return true;
}
/*
========================
idSWFSpriteInstance::SetAlpha
========================
*/
void idSWFSpriteInstance::SetAlpha( float val )
{
if( parent == NULL )
{
return;
}
swfDisplayEntry_t* thisDisplayEntry = parent->FindDisplayEntry( depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != this )
{
idLib::Warning( "_alpha: Couldn't find our display entry in our parents display list" );
return;
}
thisDisplayEntry->cxf.mul.w = val;
}
/*
========================
idSWFScriptObject_SpriteInstancePrototype
========================
*/
#define SWF_SPRITE_FUNCTION_DEFINE( x ) idSWFScriptVar idSWFScriptObject_SpriteInstancePrototype::idSWFScriptFunction_##x::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms )
#define SWF_SPRITE_NATIVE_VAR_DEFINE_GET( x ) idSWFScriptVar idSWFScriptObject_SpriteInstancePrototype::idSWFScriptNativeVar_##x::Get( class idSWFScriptObject * object )
#define SWF_SPRITE_NATIVE_VAR_DEFINE_SET( x ) void idSWFScriptObject_SpriteInstancePrototype::idSWFScriptNativeVar_##x::Set( class idSWFScriptObject * object, const idSWFScriptVar & value )
#define SWF_SPRITE_PTHIS_FUNC( x ) idSWFSpriteInstance * pThis = thisObject ? thisObject->GetSprite() : NULL; if ( !verify( pThis != NULL ) ) { idLib::Warning( "SWF: tried to call " x " on NULL sprite" ); return idSWFScriptVar(); }
#define SWF_SPRITE_PTHIS_GET( x ) idSWFSpriteInstance * pThis = object ? object->GetSprite() : NULL; if ( pThis == NULL ) { return idSWFScriptVar(); }
#define SWF_SPRITE_PTHIS_SET( x ) idSWFSpriteInstance * pThis = object ? object->GetSprite() : NULL; if ( pThis == NULL ) { return; }
#define SWF_SPRITE_FUNCTION_SET( x ) scriptFunction_##x.AddRef(); Set( #x, &scriptFunction_##x );
#define SWF_SPRITE_NATIVE_VAR_SET( x ) SetNative( #x, &swfScriptVar_##x );
idSWFScriptObject_SpriteInstancePrototype::idSWFScriptObject_SpriteInstancePrototype()
{
SWF_SPRITE_FUNCTION_SET( duplicateMovieClip );
SWF_SPRITE_FUNCTION_SET( gotoAndPlay );
SWF_SPRITE_FUNCTION_SET( gotoAndStop );
SWF_SPRITE_FUNCTION_SET( swapDepths );
SWF_SPRITE_FUNCTION_SET( nextFrame );
SWF_SPRITE_FUNCTION_SET( prevFrame );
SWF_SPRITE_FUNCTION_SET( play );
SWF_SPRITE_FUNCTION_SET( stop );
SWF_SPRITE_NATIVE_VAR_SET( _x );
SWF_SPRITE_NATIVE_VAR_SET( _y );
SWF_SPRITE_NATIVE_VAR_SET( _xscale );
SWF_SPRITE_NATIVE_VAR_SET( _yscale );
SWF_SPRITE_NATIVE_VAR_SET( _alpha );
SWF_SPRITE_NATIVE_VAR_SET( _brightness );
SWF_SPRITE_NATIVE_VAR_SET( _visible );
SWF_SPRITE_NATIVE_VAR_SET( _width );
SWF_SPRITE_NATIVE_VAR_SET( _height );
SWF_SPRITE_NATIVE_VAR_SET( _rotation );
SWF_SPRITE_NATIVE_VAR_SET( _name );
SWF_SPRITE_NATIVE_VAR_SET( _currentframe );
SWF_SPRITE_NATIVE_VAR_SET( _totalframes );
SWF_SPRITE_NATIVE_VAR_SET( _target );
SWF_SPRITE_NATIVE_VAR_SET( _framesloaded );
SWF_SPRITE_NATIVE_VAR_SET( _droptarget );
SWF_SPRITE_NATIVE_VAR_SET( _url );
SWF_SPRITE_NATIVE_VAR_SET( _highquality );
SWF_SPRITE_NATIVE_VAR_SET( _focusrect );
SWF_SPRITE_NATIVE_VAR_SET( _soundbuftime );
SWF_SPRITE_NATIVE_VAR_SET( _quality );
SWF_SPRITE_NATIVE_VAR_SET( _mousex );
SWF_SPRITE_NATIVE_VAR_SET( _mousey );
SWF_SPRITE_NATIVE_VAR_SET( _stereoDepth );
SWF_SPRITE_NATIVE_VAR_SET( _itemindex );
SWF_SPRITE_NATIVE_VAR_SET( material );
SWF_SPRITE_NATIVE_VAR_SET( materialWidth );
SWF_SPRITE_NATIVE_VAR_SET( materialHeight );
SWF_SPRITE_NATIVE_VAR_SET( xOffset );
SWF_SPRITE_NATIVE_VAR_SET( onEnterFrame );
//SWF_SPRITE_NATIVE_VAR_SET( onLoad );
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _target )
{
return "";
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _droptarget )
{
return "";
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _url )
{
return "";
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _highquality )
{
return 2;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _focusrect )
{
return true;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _soundbuftime )
{
return 0;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _quality )
{
return "BEST";
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _width )
{
return 0.0f;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( _width ) { }
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _height )
{
return 0.0f;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( _height ) { }
SWF_SPRITE_FUNCTION_DEFINE( duplicateMovieClip )
{
SWF_SPRITE_PTHIS_FUNC( "duplicateMovieClip" );
if( pThis->parent == NULL )
{
idLib::Warning( "Tried to duplicate root movie clip" );
return idSWFScriptVar();
}
if( parms.Num() < 2 )
{
idLib::Warning( "duplicateMovieClip: expected 2 parameters" );
return idSWFScriptVar();
}
swfDisplayEntry_t* thisDisplayEntry = pThis->parent->FindDisplayEntry( pThis->depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != pThis )
{
idLib::Warning( "duplicateMovieClip: Couldn't find our display entry in our parents display list" );
return idSWFScriptVar();
}
swfMatrix_t matrix = thisDisplayEntry->matrix;
swfColorXform_t cxf = thisDisplayEntry->cxf;
swfDisplayEntry_t* display = pThis->parent->AddDisplayEntry( 16384 + parms[1].ToInteger(), thisDisplayEntry->characterID );
if( display == NULL )
{
return idSWFScriptVar();
}
display->matrix = matrix;
display->cxf = cxf;
idStr name = parms[0].ToString();
pThis->parent->scriptObject->Set( name, display->spriteInstance->scriptObject );
display->spriteInstance->name = name;
display->spriteInstance->RunTo( 1 );
return display->spriteInstance->scriptObject;
}
SWF_SPRITE_FUNCTION_DEFINE( gotoAndPlay )
{
SWF_SPRITE_PTHIS_FUNC( "gotoAndPlay" );
if( parms.Num() > 0 )
{
pThis->actions.Clear();
pThis->RunTo( pThis->FindFrame( parms[0].ToString() ) );
pThis->Play();
}
else
{
idLib::Warning( "gotoAndPlay: expected 1 paramater" );
}
return idSWFScriptVar();
}
SWF_SPRITE_FUNCTION_DEFINE( gotoAndStop )
{
SWF_SPRITE_PTHIS_FUNC( "gotoAndStop" );
if( parms.Num() > 0 )
{
// Flash forces frames values less than 1 to 1.
if( parms[0].IsNumeric() && parms[0].ToInteger() < 1 )
{
pThis->RunTo( pThis->FindFrame( "1" ) );
}
else
{
pThis->RunTo( pThis->FindFrame( parms[0].ToString() ) );
}
pThis->Stop();
}
else
{
idLib::Warning( "gotoAndStop: expected 1 paramater" );
}
return idSWFScriptVar();
}
SWF_SPRITE_FUNCTION_DEFINE( swapDepths )
{
SWF_SPRITE_PTHIS_FUNC( "swapDepths" );
if( pThis->parent == NULL )
{
idLib::Warning( "Tried to swap depths on root movie clip" );
return idSWFScriptVar();
}
if( parms.Num() < 1 )
{
idLib::Warning( "swapDepths: expected 1 parameters" );
return idSWFScriptVar();
}
pThis->parent->SwapDepths( pThis->depth, parms[0].ToInteger() );
return idSWFScriptVar();
}
SWF_SPRITE_FUNCTION_DEFINE( nextFrame )
{
SWF_SPRITE_PTHIS_FUNC( "nextFrame" );
pThis->NextFrame();
return idSWFScriptVar();
}
SWF_SPRITE_FUNCTION_DEFINE( prevFrame )
{
SWF_SPRITE_PTHIS_FUNC( "prevFrame" );
pThis->PrevFrame();
return idSWFScriptVar();
}
SWF_SPRITE_FUNCTION_DEFINE( play )
{
SWF_SPRITE_PTHIS_FUNC( "play" );
pThis->Play();
return idSWFScriptVar();
}
SWF_SPRITE_FUNCTION_DEFINE( stop )
{
SWF_SPRITE_PTHIS_FUNC( "stop" );
pThis->Stop();
return idSWFScriptVar();
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _x )
{
SWF_SPRITE_PTHIS_GET( "_x" );
return pThis->GetXPos();
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( _x )
{
SWF_SPRITE_PTHIS_SET( "_x" );
pThis->SetXPos( value.ToFloat() );
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _y )
{
SWF_SPRITE_PTHIS_GET( "_y" );
return pThis->GetYPos();
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( _y )
{
SWF_SPRITE_PTHIS_SET( "_y" );
pThis->SetYPos( value.ToFloat() );
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _xscale )
{
SWF_SPRITE_PTHIS_GET( "_xscale" );
if( pThis->parent == NULL )
{
return 1.0f;
}
swfDisplayEntry_t* thisDisplayEntry = pThis->parent->FindDisplayEntry( pThis->depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != pThis )
{
idLib::Warning( "_xscale: Couldn't find our display entry in our parents display list" );
return 1.0f;
}
return thisDisplayEntry->matrix.Scale( idVec2( 1.0f, 0.0f ) ).Length() * 100.0f;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( _xscale )
{
SWF_SPRITE_PTHIS_SET( "_xscale" );
if( pThis->parent == NULL )
{
return;
}
swfDisplayEntry_t* thisDisplayEntry = pThis->parent->FindDisplayEntry( pThis->depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != pThis )
{
idLib::Warning( "_xscale: Couldn't find our display entry in our parents display list" );
return;
}
float newScale = value.ToFloat() / 100.0f;
// this is done funky to maintain the current rotation
idVec2 currentScale = thisDisplayEntry->matrix.Scale( idVec2( 1.0f, 0.0f ) );
if( currentScale.Normalize() == 0.0f )
{
thisDisplayEntry->matrix.xx = newScale;
thisDisplayEntry->matrix.yx = 0.0f;
}
else
{
thisDisplayEntry->matrix.xx = currentScale.x * newScale;
thisDisplayEntry->matrix.yx = currentScale.y * newScale;
}
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _yscale )
{
SWF_SPRITE_PTHIS_GET( "_yscale" );
if( pThis->parent == NULL )
{
return 1.0f;
}
swfDisplayEntry_t* thisDisplayEntry = pThis->parent->FindDisplayEntry( pThis->depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != pThis )
{
idLib::Warning( "_yscale: Couldn't find our display entry in our parents display list" );
return 1.0f;
}
return thisDisplayEntry->matrix.Scale( idVec2( 0.0f, 1.0f ) ).Length() * 100.0f;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( _yscale )
{
SWF_SPRITE_PTHIS_SET( "_yscale" );
if( pThis->parent == NULL )
{
return;
}
swfDisplayEntry_t* thisDisplayEntry = pThis->parent->FindDisplayEntry( pThis->depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != pThis )
{
idLib::Warning( "_yscale: Couldn't find our display entry in our parents display list" );
return;
}
float newScale = value.ToFloat() / 100.0f;
// this is done funky to maintain the current rotation
idVec2 currentScale = thisDisplayEntry->matrix.Scale( idVec2( 0.0f, 1.0f ) );
if( currentScale.Normalize() == 0.0f )
{
thisDisplayEntry->matrix.yy = newScale;
thisDisplayEntry->matrix.xy = 0.0f;
}
else
{
thisDisplayEntry->matrix.yy = currentScale.y * newScale;
thisDisplayEntry->matrix.xy = currentScale.x * newScale;
}
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _alpha )
{
SWF_SPRITE_PTHIS_GET( "_alpha" );
if( pThis->parent == NULL )
{
return 1.0f;
}
swfDisplayEntry_t* thisDisplayEntry = pThis->parent->FindDisplayEntry( pThis->depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != pThis )
{
idLib::Warning( "_alpha: Couldn't find our display entry in our parents display list" );
return 1.0f;
}
return thisDisplayEntry->cxf.mul.w;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( _alpha )
{
SWF_SPRITE_PTHIS_SET( "_alpha" );
pThis->SetAlpha( value.ToFloat() );
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _brightness )
{
SWF_SPRITE_PTHIS_GET( "_brightness" );
if( pThis->parent == NULL )
{
return 1.0f;
}
swfDisplayEntry_t* thisDisplayEntry = pThis->parent->FindDisplayEntry( pThis->depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != pThis )
{
idLib::Warning( "_brightness: Couldn't find our display entry in our parents display list" );
return 1.0f;
}
// This works as long as the user only used the "brightess" control in the editor
// If they used anything else (tint/advanced) then this will return fairly random values
const idVec4& mul = thisDisplayEntry->cxf.mul;
const idVec4& add = thisDisplayEntry->cxf.add;
float avgMul = ( mul.x + mul.y + mul.z ) / 3.0f;
float avgAdd = ( add.x + add.y + add.z ) / 3.0f;
if( avgAdd > 1.0f )
{
return avgAdd;
}
else
{
return avgMul - 1.0f;
}
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( _brightness )
{
SWF_SPRITE_PTHIS_SET( "_brightness" );
if( pThis->parent == NULL )
{
return;
}
swfDisplayEntry_t* thisDisplayEntry = pThis->parent->FindDisplayEntry( pThis->depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != pThis )
{
idLib::Warning( "_brightness: Couldn't find our display entry in our parents display list" );
return;
}
// This emulates adjusting the "brightness" slider in the editor
// Although the editor forces alpha to 100%
float b = value.ToFloat();
float c = 1.0f - b;
if( b < 0.0f )
{
c = 1.0f + b;
b = 0.0f;
}
thisDisplayEntry->cxf.add.Set( b, b, b, thisDisplayEntry->cxf.add.w );
thisDisplayEntry->cxf.mul.Set( c, c, c, thisDisplayEntry->cxf.mul.w );
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _visible )
{
SWF_SPRITE_PTHIS_GET( "_visible" );
return pThis->isVisible;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( _visible )
{
SWF_SPRITE_PTHIS_SET( "_visible" );
pThis->isVisible = value.ToBool();
if( pThis->isVisible )
{
for( idSWFSpriteInstance* p = pThis->parent; p != NULL; p = p->parent )
{
p->childrenRunning = true;
}
}
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _rotation )
{
SWF_SPRITE_PTHIS_GET( "_rotation" );
if( pThis->parent == NULL )
{
return 0.0f;
}
swfDisplayEntry_t* thisDisplayEntry = pThis->parent->FindDisplayEntry( pThis->depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != pThis )
{
idLib::Warning( "_rotation: Couldn't find our display entry in our parents display list" );
return 0.0f;
}
idVec2 scale = thisDisplayEntry->matrix.Scale( idVec2( 0.0f, 1.0f ) );
scale.Normalize();
float rotation = RAD2DEG( idMath::ACos( scale.y ) );
if( scale.x < 0.0f )
{
rotation = -rotation;
}
return rotation;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( _rotation )
{
SWF_SPRITE_PTHIS_SET( "_rotation" );
if( pThis->parent == NULL )
{
return;
}
swfDisplayEntry_t* thisDisplayEntry = pThis->parent->FindDisplayEntry( pThis->depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != pThis )
{
idLib::Warning( "_rotation: Couldn't find our display entry in our parents display list" );
return;
}
swfMatrix_t& matrix = thisDisplayEntry->matrix;
float xscale = matrix.Scale( idVec2( 1.0f, 0.0f ) ).Length();
float yscale = matrix.Scale( idVec2( 0.0f, 1.0f ) ).Length();
float s, c;
idMath::SinCos( DEG2RAD( value.ToFloat() ), s, c );
matrix.xx = c * xscale;
matrix.yx = s * xscale;
matrix.xy = -s * yscale;
matrix.yy = c * yscale;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _name )
{
SWF_SPRITE_PTHIS_GET( "_name" );
return pThis->name.c_str();
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _currentframe )
{
SWF_SPRITE_PTHIS_GET( "_currentframe" );
return pThis->currentFrame;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _totalframes )
{
SWF_SPRITE_PTHIS_GET( "_totalframes" );
return pThis->frameCount;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _framesloaded )
{
SWF_SPRITE_PTHIS_GET( "_framesloaded" );
return pThis->frameCount;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _mousex )
{
SWF_SPRITE_PTHIS_GET( "_mousex" );
if( pThis->parent == NULL )
{
return pThis->sprite->GetSWF()->GetMouseX();
}
swfDisplayEntry_t* thisDisplayEntry = pThis->parent->FindDisplayEntry( pThis->depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != pThis )
{
idLib::Warning( "_mousex: Couldn't find our display entry in our parents display list" );
return pThis->sprite->GetSWF()->GetMouseX();
}
return pThis->sprite->GetSWF()->GetMouseX() - thisDisplayEntry->matrix.ty;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _mousey )
{
SWF_SPRITE_PTHIS_GET( "_mousey" );
if( pThis->parent == NULL )
{
return pThis->sprite->GetSWF()->GetMouseY();
}
swfDisplayEntry_t* thisDisplayEntry = pThis->parent->FindDisplayEntry( pThis->depth );
if( thisDisplayEntry == NULL || thisDisplayEntry->spriteInstance != pThis )
{
idLib::Warning( "_mousey: Couldn't find our display entry in our parents display list" );
return pThis->sprite->GetSWF()->GetMouseY();
}
return pThis->sprite->GetSWF()->GetMouseY() - thisDisplayEntry->matrix.ty;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _itemindex )
{
SWF_SPRITE_PTHIS_GET( "_itemindex" );
return pThis->itemIndex;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( _itemindex )
{
SWF_SPRITE_PTHIS_SET( "_itemindex" );
pThis->itemIndex = value.ToInteger();
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( _stereoDepth )
{
SWF_SPRITE_PTHIS_SET( "_stereoDepth" );
pThis->stereoDepth = value.ToInteger();
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( _stereoDepth )
{
SWF_SPRITE_PTHIS_GET( "_stereoDepth" );
return pThis->stereoDepth;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( material )
{
SWF_SPRITE_PTHIS_GET( "material" );
if( pThis->materialOverride == NULL )
{
return idSWFScriptVar();
}
else
{
return pThis->materialOverride->GetName();
}
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( material )
{
SWF_SPRITE_PTHIS_SET( "material" );
if( !value.IsString() )
{
pThis->materialOverride = NULL;
}
else
{
// God I hope this material was referenced during map load
pThis->SetMaterial( declManager->FindMaterial( value.ToString(), false ) );
}
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( materialWidth )
{
SWF_SPRITE_PTHIS_GET( "materialWidth" );
return pThis->materialWidth;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( materialWidth )
{
SWF_SPRITE_PTHIS_SET( "materialWidth" );
assert( value.ToInteger() > 0 );
assert( value.ToInteger() <= 8192 );
pThis->materialWidth = ( uint16 )value.ToInteger();
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( materialHeight )
{
SWF_SPRITE_PTHIS_GET( "materialHeight" );
return pThis->materialHeight;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( materialHeight )
{
SWF_SPRITE_PTHIS_SET( "materialHeight" );
assert( value.ToInteger() > 0 );
assert( value.ToInteger() <= 8192 );
pThis->materialHeight = ( uint16 )value.ToInteger();
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( xOffset )
{
SWF_SPRITE_PTHIS_GET( "xOffset" );
return pThis->xOffset;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( xOffset )
{
SWF_SPRITE_PTHIS_SET( "xOffset" );
pThis->xOffset = value.ToFloat();
}
SWF_SPRITE_NATIVE_VAR_DEFINE_GET( onEnterFrame )
{
SWF_SPRITE_PTHIS_GET( "onEnterFrame" );
return pThis->onEnterFrame;
}
SWF_SPRITE_NATIVE_VAR_DEFINE_SET( onEnterFrame )
{
SWF_SPRITE_PTHIS_SET( "onEnterFrame" );
pThis->onEnterFrame = value;
}
| 412 | 0.862225 | 1 | 0.862225 | game-dev | MEDIA | 0.891775 | game-dev | 0.950849 | 1 | 0.950849 |
cmangos/mangos-tbc | 10,537 | src/game/AI/ScriptDevAI/scripts/kalimdor/azuremyst_isle.cpp | /* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Azuremyst_Isle
SD%Complete: 75
SDComment: Quest support: 9283, 9528, Injured Draenei cosmetic only
SDCategory: Azuremyst Isle
EndScriptData */
/* ContentData
npc_draenei_survivor
npc_magwin
EndContentData */
#include "AI/ScriptDevAI/include/sc_common.h"
#include "AI/ScriptDevAI/base/escort_ai.h"
/*######
## npc_draenei_survivor
######*/
enum
{
SAY_HEAL1 = -1001216,
SAY_HEAL2 = -1001217,
SAY_HEAL3 = -1001218,
SAY_HEAL4 = -1001219,
SAY_HEAL5 = -1001220,
SAY_HEAL6 = -1001221,
SAY_HELP1 = -1001222,
SAY_HELP2 = -1001223,
SAY_HELP3 = -1001224,
SAY_HELP4 = -1001225,
SPELL_IRRIDATION = 35046,
SPELL_STUNNED = 28630
};
struct npc_draenei_survivorAI : public ScriptedAI
{
npc_draenei_survivorAI(Creature* pCreature) : ScriptedAI(pCreature) {Reset();}
ObjectGuid m_casterGuid;
uint32 m_uiSayThanksTimer;
uint32 m_uiRunAwayTimer;
uint32 m_uiSayHelpTimer;
bool m_bCanSayHelp;
void Reset() override
{
m_casterGuid.Clear();
m_uiSayThanksTimer = 0;
m_uiRunAwayTimer = 0;
m_uiSayHelpTimer = 10000;
m_bCanSayHelp = true;
m_creature->CastSpell(m_creature, SPELL_IRRIDATION, TRIGGERED_OLD_TRIGGERED);
m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP);
m_creature->SetHealth(int(m_creature->GetMaxHealth()*.1));
m_creature->SetStandState(UNIT_STAND_STATE_SLEEP);
}
void MoveInLineOfSight(Unit* pWho) override
{
if (m_bCanSayHelp && pWho->GetTypeId() == TYPEID_PLAYER && pWho->CanAssist(m_creature) &&
m_creature->IsWithinDistInMap(pWho, 25.0f))
{
// Random switch between 4 texts
switch (urand(0, 3))
{
case 0: DoScriptText(SAY_HELP1, m_creature, pWho); break;
case 1: DoScriptText(SAY_HELP2, m_creature, pWho); break;
case 2: DoScriptText(SAY_HELP3, m_creature, pWho); break;
case 3: DoScriptText(SAY_HELP4, m_creature, pWho); break;
}
m_uiSayHelpTimer = 20000;
m_bCanSayHelp = false;
}
}
void SpellHit(Unit* pCaster, const SpellEntry* pSpell) override
{
if (pSpell->Id == 28880)
{
m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP);
m_creature->SetStandState(UNIT_STAND_STATE_STAND);
m_creature->CastSpell(m_creature, SPELL_STUNNED, TRIGGERED_OLD_TRIGGERED);
m_casterGuid = pCaster->GetObjectGuid();
m_uiSayThanksTimer = 5000;
}
}
void UpdateAI(const uint32 uiDiff) override
{
if (m_uiSayThanksTimer)
{
if (m_uiSayThanksTimer <= uiDiff)
{
m_creature->RemoveAurasDueToSpell(SPELL_IRRIDATION);
if (Player* pPlayer = m_creature->GetMap()->GetPlayer(m_casterGuid))
{
if (pPlayer->GetTypeId() != TYPEID_PLAYER)
return;
switch (urand(0, 6))
{
case 0: DoScriptText(SAY_HEAL1, m_creature, pPlayer); break;
case 1: DoScriptText(SAY_HEAL2, m_creature, pPlayer); break;
case 2: DoScriptText(SAY_HEAL3, m_creature, pPlayer); break;
case 3: DoScriptText(SAY_HEAL4, m_creature, pPlayer); break;
case 4: DoScriptText(SAY_HEAL5, m_creature, pPlayer); break;
case 5: DoScriptText(SAY_HEAL6, m_creature, pPlayer); break;
case 6: break; // say nothing
}
pPlayer->TalkedToCreature(m_creature->GetEntry(), m_creature->GetObjectGuid());
}
m_creature->GetMotionMaster()->Clear();
m_creature->GetMotionMaster()->MovePoint(0, -4115.053711f, -13754.831055f, 73.508949f);
m_uiRunAwayTimer = 10000;
m_uiSayThanksTimer = 0;
}
else m_uiSayThanksTimer -= uiDiff;
return;
}
if (m_uiRunAwayTimer)
{
if (m_uiRunAwayTimer <= uiDiff)
m_creature->ForcedDespawn();
else
m_uiRunAwayTimer -= uiDiff;
return;
}
if (m_uiSayHelpTimer < uiDiff)
{
m_bCanSayHelp = true;
m_uiSayHelpTimer = 20000;
}
else m_uiSayHelpTimer -= uiDiff;
}
};
UnitAI* GetAI_npc_draenei_survivor(Creature* pCreature)
{
return new npc_draenei_survivorAI(pCreature);
}
/*######
## npc_magwin
######*/
enum
{
SAY_START = -1000111,
SAY_AGGRO = -1000112,
SAY_PROGRESS = -1000113,
SAY_END1 = -1000114,
SAY_END2 = -1000115,
EMOTE_HUG = -1000116,
SAY_DAUGHTER = -1000184,
NPC_COWLEN = 17311,
QUEST_A_CRY_FOR_HELP = 9528
};
struct npc_magwinAI : public npc_escortAI
{
npc_magwinAI(Creature* pCreature) : npc_escortAI(pCreature) { Reset(); }
void Reset() override
{
if (!HasEscortState(STATE_ESCORT_ESCORTING))
m_creature->SetStandState(UNIT_STAND_STATE_KNEEL);
}
void Aggro(Unit* /*pWho*/) override
{
if (urand(0, 1))
DoScriptText(SAY_AGGRO, m_creature);
}
void WaypointReached(uint32 uiPointId) override
{
switch (uiPointId)
{
case 1:
m_creature->SetStandState(UNIT_STAND_STATE_STAND);
DoScriptText(SAY_START, m_creature);
if (Player* pPlayer = GetPlayerForEscort())
m_creature->SetFacingToObject(pPlayer);
break;
case 21:
DoScriptText(SAY_PROGRESS, m_creature);
break;
case 34:
SetRun();
DoScriptText(SAY_END1, m_creature);
if (Player* pPlayer = GetPlayerForEscort())
pPlayer->RewardPlayerAndGroupAtEventExplored(QUEST_A_CRY_FOR_HELP, m_creature);
if (Creature* pFather = GetClosestCreatureWithEntry(m_creature, NPC_COWLEN, 30.0f))
{
pFather->SetStandState(UNIT_STAND_STATE_STAND);
pFather->SetFacingToObject(m_creature);
}
break;
case 35:
if (Creature* pFather = GetClosestCreatureWithEntry(m_creature, NPC_COWLEN, 30.0f))
DoScriptText(SAY_DAUGHTER, pFather);
break;
case 36:
DoScriptText(EMOTE_HUG, m_creature);
break;
case 37:
if (Player* pPlayer = GetPlayerForEscort())
DoScriptText(SAY_END2, m_creature, pPlayer);
break;
case 38:
if (Creature* pFather = GetClosestCreatureWithEntry(m_creature, NPC_COWLEN, 30.0f))
{
pFather->SetStandState(UNIT_STAND_STATE_SIT);
pFather->GetMotionMaster()->MoveTargetedHome();
}
SetEscortPaused(true);
m_creature->ForcedDespawn(10000);
m_creature->GetMotionMaster()->MoveRandomAroundPoint(m_creature->GetPositionX(), m_creature->GetPositionY(), m_creature->GetPositionZ(), 3.0f);
break;
}
}
void StartEvent(Player* player, Quest const* quest)
{
m_creature->SetFactionTemporary(FACTION_ESCORT_A_NEUTRAL_ACTIVE, TEMPFACTION_RESTORE_RESPAWN | TEMPFACTION_TOGGLE_IMMUNE_TO_NPC);
Start(false, player, quest);
}
};
bool QuestAccept_npc_magwin(Player* pPlayer, Creature* pCreature, const Quest* pQuest)
{
if (pQuest->GetQuestId() == QUEST_A_CRY_FOR_HELP)
if (npc_magwinAI* ai = dynamic_cast<npc_magwinAI*>(pCreature->AI()))
ai->StartEvent(pPlayer, pQuest);
return true;
}
enum
{
NPC_OWLKIN = 16518,
NPC_OWLKIN_INOC = 16534,
};
// 29528 - Inoculate Nestlewood Owlkin
struct InoculateNestlewoodOwlkin : public SpellScript, public AuraScript
{
SpellCastResult OnCheckCast(Spell* spell, bool /*strict*/) const override
{
Unit* target = spell->m_targets.getUnitTarget();
if (!target || target->GetEntry() != NPC_OWLKIN)
return SPELL_FAILED_BAD_TARGETS;
return SPELL_CAST_OK;
}
void OnPeriodicTrigger(Aura* aura, PeriodicTriggerData& /*data*/) const
{
Creature* target = static_cast<Creature*>(aura->GetTarget());
target->UpdateEntry(NPC_OWLKIN_INOC);
target->AIM_Initialize();
if (aura->GetCasterGuid().IsPlayer())
if (Player* caster = static_cast<Player*>(aura->GetCaster()))
caster->KilledMonsterCredit(NPC_OWLKIN_INOC);
// set despawn timer, since we want to remove creature after a short time
target->ForcedDespawn(15000);
}
};
void AddSC_azuremyst_isle()
{
Script* pNewScript = new Script;
pNewScript->Name = "npc_draenei_survivor";
pNewScript->GetAI = &GetAI_npc_draenei_survivor;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "npc_magwin";
pNewScript->GetAI = &GetNewAIInstance<npc_magwinAI>;
pNewScript->pQuestAcceptNPC = &QuestAccept_npc_magwin;
pNewScript->RegisterSelf();
RegisterSpellScript<InoculateNestlewoodOwlkin>("spell_inoculate_nestlewood_owlkin");
}
| 412 | 0.987395 | 1 | 0.987395 | game-dev | MEDIA | 0.986737 | game-dev | 0.995072 | 1 | 0.995072 |
rlf/uSkyBlock | 56,648 | uSkyBlock-Core/src/main/java/us/talabrek/ultimateskyblock/menu/SkyBlockMenu.java | package us.talabrek.ultimateskyblock.menu;
import dk.lockfuglsang.minecraft.util.ItemStackUtil;
import dk.lockfuglsang.minecraft.util.TimeUtil;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.scheduler.BukkitTask;
import us.talabrek.ultimateskyblock.challenge.ChallengeLogic;
import us.talabrek.ultimateskyblock.command.island.BiomeCommand;
import us.talabrek.ultimateskyblock.island.IslandInfo;
import us.talabrek.ultimateskyblock.player.IslandPerk;
import us.talabrek.ultimateskyblock.player.PlayerInfo;
import us.talabrek.ultimateskyblock.player.UltimateHolder;
import us.talabrek.ultimateskyblock.player.UltimateHolder.MenuType;
import us.talabrek.ultimateskyblock.uSkyBlock;
import us.talabrek.ultimateskyblock.util.GuiItemUtil;
import us.talabrek.ultimateskyblock.util.PlayerUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static dk.lockfuglsang.minecraft.po.I18nUtil.pre;
import static dk.lockfuglsang.minecraft.po.I18nUtil.tr;
import static dk.lockfuglsang.minecraft.util.FormatUtil.stripFormatting;
import static us.talabrek.ultimateskyblock.challenge.ChallengeLogic.CHALLENGE_PAGESIZE;
import static us.talabrek.ultimateskyblock.challenge.ChallengeLogic.COLS_PER_ROW;
import static us.talabrek.ultimateskyblock.util.LogUtil.log;
// TODO: Move all the texts to resource-files (translatable).
/**
* The UI menu of uSkyBlock (using the inventory UI).
*/
public class SkyBlockMenu {
private final Pattern PERM_VALUE_PATTERN = Pattern.compile("(\\[(?<perm>(?<not>[!])?[^\\]]+)\\])?(?<value>.*)");
private final Pattern CHALLENGE_PAGE_HEADER = Pattern.compile(tr("Challenge Menu") + ".*\\((?<p>[0-9]+)/(?<max>[0-9]+)\\)");
private uSkyBlock plugin;
private final ChallengeLogic challengeLogic;
private ItemStack sign = new ItemStack(Material.OAK_SIGN, 1);
private ItemStack biome = new ItemStack(Material.JUNGLE_SAPLING, 1);
private ItemStack lock = new ItemStack(Material.IRON_BARS, 1);
private ItemStack warpset = new ItemStack(Material.END_PORTAL_FRAME, 1);
private ItemStack warptoggle = new ItemStack(Material.LEVER, 1);
private ItemStack invite = new ItemStack(Material.CARROT_ON_A_STICK, 1);
private ItemStack kick = new ItemStack(Material.LEATHER_BOOTS, 1);
private List<PartyPermissionMenuItem> permissionMenuItems = Arrays.asList(
new PartyPermissionMenuItem(biome, "canChangeBiome", tr("Change Biome"),
tr("change the island''s biome.")),
new PartyPermissionMenuItem(lock, "canToggleLock", tr("Toggle Island Lock"),
tr("toggle the island''s lock.")),
new PartyPermissionMenuItem(warpset, "canChangeWarp", tr("Set Island Warp"),
tr("set the island''s warp."),
tr("set the island''s warp,\nwhich allows non-group\nmembers to teleport to\nthe island.")),
new PartyPermissionMenuItem(warptoggle, "canToggleWarp", tr("Toggle Island Warp"),
tr("toggle the island''s warp."),
tr("toggle the island''s warp,\nallowing them to turn it\non or off at anytime, but\nnot set the location.")),
new PartyPermissionMenuItem(invite, "canInviteOthers", tr("Invite Players"),
tr("invite others to the island."),
tr("invite\n" +
"other players to the island if\n" +
"there is enough room for more\n" +
"members")),
new PartyPermissionMenuItem(kick, "canKickOthers", tr("Kick Players"),
tr("kick others from the island."),
tr("kick\n" +
"other players from the island,\n" +
"but they are unable to kick\n" +
"the island leader."))
);
private List<BiomeMenuItem> biomeMenus = Arrays.asList(
new BiomeMenuItem(new ItemStack(Material.TROPICAL_FISH, 1),
"ocean", tr("Ocean"),
tr("The ocean biome is the basic\nstarting biome for all islands.\npassive mobs like animals will\nnot spawn. Hostile mobs will\nspawn normally.")
),
new BiomeMenuItem(new ItemStack(Material.SPRUCE_SAPLING, 1),
"forest", tr("Forest"),
tr("The forest biome will allow\nyour island to spawn passive.\nmobs like animals (including\nwolves). Hostile mobs will\nspawn normally.")
),
new BiomeMenuItem(new ItemStack(Material.SAND, 1),
"desert", tr("Desert"),
tr("The desert biome makes it so\nthat there is no rain or snow\non your island. Passive mobs\nwon't spawn. Hostile mobs will\nspawn normally.")
),
new BiomeMenuItem(new ItemStack(Material.JUNGLE_SAPLING, 1),
"jungle", tr("Jungle"),
tr("The jungle biome is bright\nand colorful. Passive mobs\n(including ocelots) will\nspawn. Hostile mobs will\nspawn normally.")
),
new BiomeMenuItem(new ItemStack(Material.LILY_PAD, 1),
"swamp", tr("Swampland"),
tr("The swamp biome is dark\nand dull. Passive mobs\nwill spawn normally and\nslimes have a small chance\nto spawn at night depending\non the moon phase.")
),
new BiomeMenuItem(new ItemStack(Material.SNOW, 1),
"taiga", tr("Taiga"),
tr("The taiga biome has snow\ninstead of rain. Passive\nmobs will spawn normally\n(including wolves) and\nhostile mobs will spawn.")
),
new BiomeMenuItem(new ItemStack(Material.RED_MUSHROOM, 1),
"mushroom_fields", tr("Mushroom"),
tr("The mushroom biome is\nbright and colorful.\nMooshrooms are the only\nmobs that will spawn.\nNo other passive or\nhostile mobs will spawn.")
),
new BiomeMenuItem(new ItemStack(Material.NETHER_BRICK, 1),
"nether_wastes", tr("Hell"),
tr("The hell biome looks\ndark and dead. Some\nmobs from the nether will\nspawn in this biome\n(excluding ghasts and\nblazes).")
),
new BiomeMenuItem(new ItemStack(Material.ENDER_EYE, 1),
"the_end", tr("Sky"),
tr("The sky biome gives your\nisland a special dark sky.\nOnly endermen will spawn\nin this biome.")
),
new BiomeMenuItem(new ItemStack(Material.TALL_GRASS, 1),
"plains", tr("Plains"),
tr("The plains biome has rain\ninstead of snow. Passive\nmobs will spawn normally\n(including horses) and\nhostile mobs will spawn.")
),
new BiomeMenuItem(new ItemStack(Material.EMERALD_ORE, 1),
"windswept_hills", tr("Extreme Hills"),
tr("The extreme hills biome.\nPassive mobs will spawn \nnormally and hostile\nmobs will spawn.")
),
new BiomeMenuItem(new ItemStack(Material.ROSE_BUSH, 1),
"flower_forest", tr("Flower Forest"),
tr("The flower forest biome.\nPassive mobs will spawn \nnormally and hostile\nmobs will spawn.")
),
new BiomeMenuItem(new ItemStack(Material.PRISMARINE_SHARD, 1),
"deep_ocean", tr("Deep Ocean"),
tr("The deep-ocean biome is an advanced\n" +
"biome. Passive mobs like animals will\n" +
"not spawn. Hostile mobs \n" +
"(including Guardians) will\n" +
"spawn normally.")
),
new BiomeMenuItem(new ItemStack(Material.PACKED_ICE, 1),
"snowy_plains", tr("Ice Plains"),
tr("The ice-plains biome is an advanced biome.\nMobs will spawn naturally.\nincluding polar-bears")
)
);
public SkyBlockMenu(uSkyBlock plugin, ChallengeLogic challengeLogic) {
this.plugin = plugin;
this.challengeLogic = challengeLogic;
}
public Inventory displayPartyPlayerGUI(final Player player, final String pname) {
List<String> lores = new ArrayList<>();
String emptyTitle = tr("{0} <{1}>", "", tr("Permissions"));
String title = tr("{0} <{1}>", pname.substring(0, Math.min(32 - emptyTitle.length(), pname.length())), tr("Permissions"));
Inventory menu = Bukkit.createInventory(new UltimateHolder(player, title, MenuType.DEFAULT), 9, title);
final ItemStack pHead = new ItemStack(Material.PLAYER_HEAD, 1);
final SkullMeta meta3 = (SkullMeta) pHead.getItemMeta();
ItemMeta meta2 = sign.getItemMeta();
meta2.setDisplayName(tr("\u00a79Player Permissions"));
addLore(lores, tr("\u00a7eClick here to return to\n\u00a7eyour island group''s info."));
meta2.setLore(lores);
sign.setItemMeta(meta2);
menu.addItem(sign);
lores.clear();
meta3.setOwner(pname);
meta3.setDisplayName(tr("\u00a7e{0}''\u00a79s Permissions", pname));
addLore(lores, tr("\u00a7eHover over an icon to view\n\u00a7ea permission. Change the\n\u00a7epermission by clicking it."));
meta3.setLore(lores);
pHead.setItemMeta(meta3);
menu.addItem(pHead);
lores.clear();
IslandInfo islandInfo = plugin.getIslandInfo(player);
boolean isLeader = islandInfo.isLeader(player);
for (PartyPermissionMenuItem menuItem : permissionMenuItems) {
ItemStack itemStack = menuItem.getIcon();
meta2 = itemStack.getItemMeta();
if (islandInfo.hasPerm(pname, menuItem.getPerm())) {
meta2.setDisplayName("\u00a7a" + menuItem.getTitle());
lores.add(tr("\u00a7fThis player \u00a7acan"));
addLore(lores, "\u00a7f", menuItem.getDescription());
if (isLeader) {
addLore(lores, "\u00a7f", tr("Click here to remove this permission."));
}
} else {
meta2.setDisplayName("\u00a7c" + menuItem.getTitle());
lores.add(tr("\u00a7fThis player \u00a7ccannot"));
addLore(lores, "\u00a7f", menuItem.getDescription());
if (isLeader) {
addLore(lores, "\u00a7f", tr("Click here to grant this permission."));
}
}
meta2.setLore(lores);
itemStack.setItemMeta(meta2);
menu.addItem(itemStack);
lores.clear();
}
return menu;
}
private void addLore(List<String> lores, String format, String multiLine) {
for (String line : multiLine.split("\n")) {
lores.add(format + line);
}
}
private void addLore(List<String> lores, String multiLine) {
addLore(lores, "", multiLine);
}
public Inventory displayPartyGUI(final Player player) {
List<String> lores = new ArrayList<>();
String title = "\u00a79" + tr("Island Group Members");
Inventory menu = Bukkit.createInventory(new UltimateHolder(player, title, MenuType.DEFAULT), 18, title);
IslandInfo islandInfo = plugin.getIslandInfo(player);
final Set<String> memberList = islandInfo.getMembers();
final ItemMeta meta2 = sign.getItemMeta();
meta2.setDisplayName("\u00a7a" + tr("Island Group Members"));
lores.add(tr("Group Members: \u00a72{0}\u00a77/\u00a7e{1}", islandInfo.getPartySize(), islandInfo.getMaxPartySize()));
if (islandInfo.getPartySize() < islandInfo.getMaxPartySize()) {
addLore(lores, tr("\u00a7aMore players can be invited to this island."));
} else {
addLore(lores, tr("\u00a7cThis island is full."));
}
addLore(lores, tr("\u00a7eHover over a player''s icon to\n\u00a7eview their permissions. The\n\u00a7eleader can change permissions\n\u00a7eby clicking a player''s icon."));
meta2.setLore(lores);
sign.setItemMeta(meta2);
menu.addItem(sign.clone());
lores.clear();
for (String temp : memberList) {
ItemStack headItem = new ItemStack(Material.PLAYER_HEAD, 1);
SkullMeta meta3 = (SkullMeta) headItem.getItemMeta();
meta3.setDisplayName(tr("\u00a7e{0}''s\u00a79 Permissions", temp));
meta3.setOwner(temp);
boolean isLeader = islandInfo.isLeader(temp);
if (isLeader) {
addLore(lores, "\u00a7a\u00a7l", tr("Leader"));
} else {
addLore(lores, "\u00a7e\u00a7l", tr("Member"));
}
for (PartyPermissionMenuItem perm : permissionMenuItems) {
if (isLeader || islandInfo.hasPerm(temp, perm.getPerm())) {
lores.add("\u00a7a" + tr("Can {0}", "\u00a7f" + perm.getShortDescription()));
} else {
lores.add("\u00a7c" + tr("Cannot {0}", "\u00a7f" + perm.getShortDescription()));
}
}
if (islandInfo.isLeader(player.getName())) {
addLore(lores, tr("\u00a7e<Click to change this player''s permissions>"));
}
meta3.setLore(lores);
headItem.setItemMeta(meta3);
menu.addItem(headItem);
lores.clear();
}
return menu;
}
public Inventory displayLogGUI(final Player player) {
List<String> lores = new ArrayList<>();
String title = "\u00a79" + tr("Island Log");
Inventory menu = Bukkit.createInventory(new UltimateHolder(player, title, MenuType.DEFAULT), 9, title);
ItemMeta meta4 = sign.getItemMeta();
meta4.setDisplayName("\u00a79\u00a7l" + tr("Island Log"));
addLore(lores, tr("\u00a7eClick here to return to\n\u00a7ethe main island screen."));
meta4.setLore(lores);
sign.setItemMeta(meta4);
menu.addItem(new ItemStack[]{sign});
lores.clear();
ItemStack menuItem = new ItemStack(Material.WRITABLE_BOOK, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7e\u00a7lIsland Log"));
for (String log : plugin.getIslandInfo(player).getLog()) {
lores.add(log);
}
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.setItem(8, menuItem);
lores.clear();
return menu;
}
public Inventory displayBiomeGUI(final Player player) {
List<String> lores = new ArrayList<>();
String title = "\u00a79" + tr("Island Biome");
Inventory menu = Bukkit.createInventory(new UltimateHolder(player, title, MenuType.DEFAULT), 27, title);
ItemMeta meta4 = sign.getItemMeta();
meta4.setDisplayName("\u00a7h" + tr("Island Biome"));
addLore(lores, tr("\u00a7eClick here to return to\n\u00a7ethe main island screen."));
meta4.setLore(lores);
sign.setItemMeta(meta4);
menu.addItem(new ItemStack[]{sign});
lores.clear();
String currentBiome = plugin.getIslandInfo(player).getBiome();
for (BiomeMenuItem biomeMenu : biomeMenus) {
if (!BiomeCommand.biomeExists(biomeMenu.getId())) {
continue; // Skip it
}
ItemStack menuItem = biomeMenu.getIcon();
meta4 = menuItem.getItemMeta();
if (player.hasPermission("usb.biome." + biomeMenu.getId())) {
meta4.setDisplayName("\u00a7a" + tr("Biome: {0}", biomeMenu.getTitle()));
addLore(lores, "\u00a7f", biomeMenu.getDescription());
if (biomeMenu.getId().equalsIgnoreCase(currentBiome)) {
addLore(lores, tr("\u00a72\u00a7lThis is your current biome."));
} else {
addLore(lores, tr("\u00a7e\u00a7lClick to change to this biome."));
}
} else {
meta4.setDisplayName("\u00a78" + tr("Biome: {0}", biomeMenu.getTitle()));
lores.add("\u00a7c" + tr("You cannot use this biome."));
addLore(lores, "\u00a77", biomeMenu.getDescription());
}
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.addItem(menuItem);
lores.clear();
}
updateBiomeRadius(player, menu);
return menu;
}
private void updateBiomeRadius(Player player, Inventory menu) {
String radius = PlayerUtil.getMetadata(player, "biome.radius", "all");
String radiusDisplay;
switch (radius) {
case "chunk":
radiusDisplay = tr("\u00a72chunk");
break;
case "all":
radiusDisplay = tr("\u00a7call");
break;
default:
radiusDisplay = tr("\u00a7e{0}", radius);
}
List<String> lores = new ArrayList<>();
ItemStack menuItem = new ItemStack(Material.RED_CARPET);
ItemMeta itemMeta = menuItem.getItemMeta();
itemMeta.setDisplayName(tr("\u00a7c-"));
lores.add(tr("Decrease radius of biome-change"));
lores.add(tr(tr("Current radius: {0}", radiusDisplay)));
itemMeta.setLore(lores);
menuItem.setItemMeta(itemMeta);
menu.setItem(21, menuItem);
lores.clear();
menuItem = new ItemStack(Material.GRASS_BLOCK);
if (radius.matches("[0-9]+")) {
int radiusInt = Integer.parseInt(radius, 10);
if (radiusInt <= menuItem.getType().getMaxStackSize()) {
menuItem.setAmount(radiusInt);
} else {
menuItem.setAmount(1);
}
} else {
menuItem.setAmount(1);
}
itemMeta = menuItem.getItemMeta();
itemMeta.setDisplayName(tr("Current radius: {0}", radiusDisplay));
itemMeta.setLore(lores);
menuItem.setItemMeta(itemMeta);
menu.setItem(22, menuItem);
lores.clear();
menuItem = new ItemStack(Material.GREEN_CARPET);
itemMeta = menuItem.getItemMeta();
itemMeta.setDisplayName(tr("\u00a72+"));
lores.add(tr("Increase radius of biome-change"));
lores.add(tr(tr("Current radius: {0}", radiusDisplay)));
itemMeta.setLore(lores);
menuItem.setItemMeta(itemMeta);
menu.setItem(23, menuItem);
}
private void addExtraMenus(Player player, Inventory menu) {
ConfigurationSection extras = plugin.getConfig().getConfigurationSection("options.extra-menus");
if (extras == null) {
return;
}
for (String sIndex : extras.getKeys(false)) {
ConfigurationSection menuSection = extras.getConfigurationSection(sIndex);
if (menuSection == null) {
continue;
}
try {
int index = Integer.parseInt(sIndex, 10);
String title = menuSection.getString("title", "\u00a9Unknown");
String icon = menuSection.getString("displayItem", "CHEST");
List<String> lores = new ArrayList<>();
for (String l : menuSection.getStringList("lore")) {
Matcher matcher = PERM_VALUE_PATTERN.matcher(l);
if (matcher.matches()) {
String perm = matcher.group("perm");
String lore = matcher.group("value");
boolean not = matcher.group("not") != null;
if (perm != null) {
boolean hasPerm = player.hasPermission(perm);
if ((hasPerm && !not) || (!hasPerm && not)) {
lores.add(lore);
}
} else {
lores.add(lore);
}
}
}
// Only SIMPLE icons supported...
ItemStack item = GuiItemUtil.createGuiDisplayItem(icon, title);
ItemMeta meta = item.getItemMeta();
meta.setLore(lores);
item.setItemMeta(meta);
menu.setItem(index, item);
} catch (Exception e) {
log(Level.INFO, "\u00a79[uSkyBlock]\u00a7r Unable to add extra-menu " + sIndex + ": " + e);
}
}
}
private boolean isExtraMenuAction(Player player, ItemStack currentItem) {
ConfigurationSection extras = plugin.getConfig().getConfigurationSection("options.extra-menus");
if (extras == null || currentItem == null || currentItem.getItemMeta() == null) {
return false;
}
Material itemType = currentItem.getType();
String itemTitle = currentItem.getItemMeta().getDisplayName();
for (String sIndex : extras.getKeys(false)) {
ConfigurationSection menuSection = extras.getConfigurationSection(sIndex);
if (menuSection == null) {
continue;
}
try {
String title = menuSection.getString("title", "\u00a9Unknown");
String icon = menuSection.getString("displayItem", "CHEST");
Material material = Material.matchMaterial(icon);
if (title.equals(itemTitle) && material == itemType) {
for (String command : menuSection.getStringList("commands")) {
Matcher matcher = PERM_VALUE_PATTERN.matcher(command);
if (matcher.matches()) {
String perm = matcher.group("perm");
String cmd = matcher.group("value");
boolean not = matcher.group("not") != null;
if (perm != null) {
boolean hasPerm = player.hasPermission(perm);
if ((hasPerm && !not) || (!hasPerm && not)) {
plugin.execCommand(player, cmd, false);
}
} else {
plugin.execCommand(player, cmd, false);
}
} else {
log(Level.INFO, "\u00a7a[uSkyBlock] Malformed menu " + title + ", invalid command : " + command);
}
}
return true;
}
} catch (Exception e) {
log(Level.INFO, "\u00a79[uSkyBlock]\u00a7r Unable to execute commands for extra-menu " + sIndex + ": " + e);
}
}
return false;
}
public Inventory displayChallengeGUI(final Player player, int page, String playerName) {
int total = challengeLogic.getTotalPages();
String title = "\u00a79" + pre("{0} ({1}/{2})", tr("Challenge Menu"), page, total);
Inventory menu = Bukkit.createInventory(new UltimateHolder(player, title, MenuType.DEFAULT), CHALLENGE_PAGESIZE + COLS_PER_ROW, title);
final PlayerInfo pi = playerName == null ? plugin.getPlayerInfo(player) : plugin.getPlayerInfo(playerName);
challengeLogic.populateChallengeRank(menu, pi, page, playerName != null && player.hasPermission("usb.mod.bypassrestriction"));
int[] pages = new int[9];
pages[0] = 1;
pages[8] = total;
int startOffset = 2;
if (page > 5) {
startOffset = (int) ((Math.round(page / 2d)) - 1);
if (startOffset > total - 7) {
startOffset = total - 7;
}
}
for (int i = 0; i < 7; i++) {
pages[i + 1] = startOffset + i;
}
for (int i = 0; i < pages.length; i++) {
int p = pages[i];
if (p >= 1 && p <= total) {
ItemStack pageItem;
if (p == page) {
pageItem = GuiItemUtil.createGuiDisplayItem(Material.WRITABLE_BOOK, tr("\u00a77Current page"));
} else {
pageItem = GuiItemUtil.createGuiDisplayItem(Material.BOOK, tr("\u00a77Page {0}", p));
}
if (i == 0) {
pageItem = ItemStackUtil.builder(pageItem)
.displayName(tr("\u00a77First Page"))
.lore(playerName != null ? playerName : "")
.build();
} else if (i == 8) {
pageItem = ItemStackUtil.builder(pageItem).displayName(tr("\u00a77Last Page")).build();
}
pageItem.setAmount(p);
menu.setItem(i + CHALLENGE_PAGESIZE, pageItem);
}
}
return menu;
}
public Inventory displayIslandGUI(final Player player) {
if (plugin.hasIsland(player)) {
return createMainMenu(player);
} else {
return createInitMenu(player);
}
}
private Inventory createInitMenu(Player player) {
List<String> schemeNames = plugin.getIslandGenerator().getSchemeNames();
int menuSize = (int) Math.ceil(getMaxSchemeIndex(schemeNames) / 9d) * 9;
String title = "\u00a79" + tr("Island Create Menu");
Inventory menu = Bukkit.createInventory(new UltimateHolder(player, title, MenuType.DEFAULT), menuSize, title);
List<String> lores = new ArrayList<>();
ItemStack menuItem = new ItemStack(Material.OAK_SAPLING, 1);
ItemMeta meta = menuItem.getItemMeta();
meta.setDisplayName(tr("\u00a7a\u00a7lStart an Island"));
addLore(lores, "\u00a7f", tr("Start your skyblock journey\nby starting your own island.\nComplete challenges to earn\nitems and skybucks to help\nexpand your skyblock. You can\ninvite others to join in\nbuilding your island empire!\n\u00a7e\u00a7lClick here to start!"));
meta.setLore(lores);
menuItem.setItemMeta(meta);
menu.addItem(menuItem);
lores.clear();
if (plugin.getConfig().getBoolean("island-schemes-enabled", true) && schemeNames.size() > 1) {
int index = 1;
for (String schemeName : schemeNames) {
IslandPerk islandPerk = plugin.getPerkLogic().getIslandPerk(schemeName);
boolean enabled = plugin.getConfig().getBoolean("island-schemes." + islandPerk.getSchemeName() + ".enabled", true);
if (!enabled) {
continue; // Skip
}
index = Math.max(plugin.getConfig().getInt("island-schemes." + islandPerk.getSchemeName() + ".index", index), 1);
menuItem = islandPerk.getDisplayItem();
meta = menuItem.getItemMeta();
lores = meta.getLore();
if (lores == null) {
lores = new ArrayList<>();
}
if (player.hasPermission(islandPerk.getPermission())) {
addLore(lores, tr("\u00a7aClick to create!"));
} else {
addLore(lores, tr("\u00a7cNo access!\n\u00a77({0})", islandPerk.getPermission()));
}
meta.setLore(lores);
menuItem.setItemMeta(meta);
menu.setItem(index++, menuItem);
}
}
lores.clear();
menuItem = new ItemStack(Material.SHORT_GRASS, 1);
meta = menuItem.getItemMeta();
meta.setDisplayName(tr("\u00a7a\u00a7lReturn to Spawn"));
addLore(lores, "\u00a7f", tr("Teleport to the spawn area."));
meta.setLore(lores);
menuItem.setItemMeta(meta);
menu.setItem(menuSize - 2, menuItem);
lores.clear();
menuItem = new ItemStack(Material.PLAYER_HEAD, 1);
final SkullMeta meta2 = (SkullMeta) menuItem.getItemMeta();
meta2.setDisplayName(tr("\u00a7a\u00a7lJoin an Island"));
addLore(lores, "\u00a7f", tr("Want to join another player''s\nisland instead of starting\nyour own? If another player\ninvites you to their island\nyou can click here or use\n\u00a7e/island accept\u00a7f to join them.\n\u00a7e\u00a7lClick here to accept an invite!\n\u00a7e\u00a7l(You must be invited first)"));
meta2.setLore(lores);
menuItem.setItemMeta(meta2);
menu.setItem(menuSize - 1, menuItem);
return menu;
}
private int getMaxSchemeIndex(List<String> schemeNames) {
int index = 1;
for (String schemeName : schemeNames) {
int nextIndex = plugin.getConfig().getInt("island-schemes." + schemeName + ".index", index);
if (nextIndex > index) {
index = nextIndex;
} else {
index++;
}
}
return index + 3;
}
private Inventory createMainMenu(Player player) {
String title = "\u00a79" + tr("Island Menu");
Inventory menu = Bukkit.createInventory(new UltimateHolder(player, title, MenuType.DEFAULT), 18, title);
List<String> lores = new ArrayList<>();
ItemStack menuItem = new ItemStack(Material.OAK_DOOR, 1);
ItemMeta meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7a\u00a7lReturn Home"));
addLore(lores, "\u00a7f", tr("Return to your island''s home\npoint. You can change your home\npoint to any location on your\nisland using \u00a7b/island sethome\n\u00a7e\u00a7lClick here to return home."));
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.addItem(menuItem);
lores.clear();
IslandInfo islandInfo = plugin.getIslandInfo(player);
menuItem = new ItemStack(Material.DIAMOND_ORE, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7a\u00a7lChallenges"));
addLore(lores, "\u00a7f", tr("View a list of \u00a79challenges that\nyou can complete on your island\nto earn skybucks, items, perks,\nand titles."));
if (plugin.getChallengeLogic().isEnabled()) {
addLore(lores, tr("\u00a7e\u00a7lClick here to view challenges."));
} else {
addLore(lores, tr("\u00a74\u00a7lChallenges disabled."));
}
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.addItem(menuItem);
lores.clear();
menuItem = new ItemStack(Material.EXPERIENCE_BOTTLE, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7a\u00a7lIsland Level"));
addLore(lores, tr("\u00a7eCurrent Level: \u00a7a{0,number,##.#}", islandInfo.getLevel()));
addLore(lores, plugin.getLimitLogic().getSummary(islandInfo));
addLore(lores, "\u00a7f", tr("Gain island levels by expanding\nyour skyblock and completing\ncertain challenges. Rarer blocks\nwill add more to your level.\n\u00a7e\u00a7lClick here to refresh.\n\u00a7e\u00a7l(must be on island)"));
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.addItem(menuItem);
lores.clear();
menuItem = new ItemStack(Material.PLAYER_HEAD, 1);
final SkullMeta meta2 = (SkullMeta) menuItem.getItemMeta();
meta2.setDisplayName("\u00a7a\u00a7l" + tr("Island Group"));
lores.add(tr("\u00a7eMembers: \u00a72{0}/{1}", islandInfo.getPartySize(), islandInfo.getMaxPartySize()));
addLore(lores, "\u00a7f", tr("View the members of your island\ngroup and their permissions. If\nyou are the island leader, you\ncan change the member permissions.\n\u00a7e\u00a7lClick here to view or change."));
meta2.setLore(lores);
menuItem.setItemMeta(meta2);
menu.addItem(menuItem);
lores.clear();
menuItem = new ItemStack(Material.JUNGLE_SAPLING, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName("\u00a7a\u00a7l" + tr("Change Island Biome"));
lores.add(tr("\u00a7eCurrent Biome: \u00a7b{0}", islandInfo.getBiome()));
addLore(lores, "\u00a7f", tr("The island biome affects things\nlike grass color and spawning\nof both animals and monsters."));
if (islandInfo.hasPerm(player, "canChangeBiome")) {
addLore(lores, tr("\u00a7e\u00a7lClick here to change biomes."));
} else {
addLore(lores, tr("\u00a7c\u00a7lYou can't change the biome."));
}
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.addItem(menuItem);
lores.clear();
menuItem = new ItemStack(Material.IRON_BARS, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7a\u00a7lIsland Lock"));
if (plugin.getIslandInfo(player).isLocked()) {
addLore(lores, tr("\u00a7eLock Status: \u00a7aActive\n\u00a7fYour island is currently \u00a7clocked.\n\u00a7fPlayers outside of your group\n\u00a7fare unable to enter your island."));
if (islandInfo.hasPerm(player, "canToggleLock") && player.hasPermission("usb.island.lock")) {
addLore(lores, tr("\u00a7e\u00a7lClick here to unlock your island."));
} else {
addLore(lores, tr("\u00a7c\u00a7lYou can't change the lock."));
}
} else {
addLore(lores, tr("\u00a7eLock Status: \u00a78Inactive\n\u00a7fYour island is currently \u00a7aunlocked.\n\u00a7fAll players are able to enter your\n\u00a7fisland, but only you and your group\n\u00a7fmembers may build there."));
if (islandInfo.hasPerm(player, "canToggleLock") && player.hasPermission("usb.island.lock")) {
addLore(lores, tr("\u00a7e\u00a7lClick here to lock your island."));
} else {
addLore(lores, tr("\u00a7c\u00a7lYou can't change the lock."));
}
}
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.addItem(menuItem);
lores.clear();
if (plugin.getIslandInfo(player).hasWarp()) {
menuItem = new ItemStack(Material.END_PORTAL_FRAME, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7a\u00a7lIsland Warp"));
addLore(lores, tr("\u00a7eWarp Status: \u00a7aActive\n\u00a7fOther players may warp to your\n\u00a7fisland at anytime to the point\n\u00a7fyou set using \u00a7d/island setwarp."));
if (islandInfo.hasPerm(player, "canToggleWarp") && player.hasPermission("usb.island.togglewarp")) {
addLore(lores, tr("\u00a7e\u00a7lClick here to deactivate."));
} else {
addLore(lores, tr("\u00a7c\u00a7lYou can't change the warp."));
}
} else {
menuItem = new ItemStack(Material.END_STONE, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7a\u00a7lIsland Warp"));
addLore(lores, tr("\u00a7eWarp Status: \u00a78Inactive\n\u00a7fOther players can't warp to your\n\u00a7fisland. Set a warp point using\n\u00a7d/island setwarp \u00a7fbefore activating."));
if (islandInfo.hasPerm(player, "canToggleWarp") && player.hasPermission("usb.island.togglewarp")) {
addLore(lores, tr("\u00a7e\u00a7lClick here to activate."));
} else {
addLore(lores, tr("\u00a7c\u00a7lYou can't change the warp."));
}
}
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.addItem(menuItem);
lores.clear();
menuItem = new ItemStack(Material.SHORT_GRASS, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7a\u00a7lReturn to Spawn"));
addLore(lores, "\u00a7f", tr("Teleport to the spawn area."));
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.addItem(menuItem);
lores.clear();
menuItem = new ItemStack(Material.WRITABLE_BOOK, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7a\u00a7lIsland Log"));
addLore(lores, "\u00a7f", tr("View a log of events from\nyour island such as member,\nbiome, and warp changes.\n\u00a7e\u00a7lClick to view the log."));
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.setItem(8, menuItem); // Last item, first line
lores.clear();
menuItem = new ItemStack(Material.RED_BED, 1); // red bed
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7a\u00a7lChange Home Location"));
addLore(lores, "\u00a7f", tr("When you teleport to your\nisland you will be taken to\nthis location.\n\u00a7e\u00a7lClick here to change."));
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.setItem(9, menuItem); // First item, 2nd line
lores.clear();
menuItem = new ItemStack(Material.HOPPER, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7a\u00a7lChange Warp Location"));
addLore(lores, "\u00a7f", tr("When your warp is activated,\nother players will be taken to\nthis point when they teleport\nto your island."));
if (islandInfo.hasPerm(player, "canChangeWarp") && player.hasPermission("usb.island.setwarp")) {
addLore(lores, tr("\u00a7e\u00a7lClick here to change."));
} else {
addLore(lores, tr("\u00a7c\u00a7lYou can't change the warp."));
}
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.setItem(15, menuItem);
lores.clear();
if (islandInfo.isLeader(player)) {
if (plugin.getConfig().getBoolean("island-schemes-enabled", true)) {
menuItem = new ItemStack(Material.PODZOL, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7c\u00a7lRestart Island"));
addLore(lores, "\u00a7f", tr("Restarts your island.\n\u00a74WARNING! \u00a7cwill remove your items and island!"));
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.setItem(17, menuItem);
lores.clear();
}
} else {
menuItem = new ItemStack(Material.IRON_DOOR, 1);
meta4 = menuItem.getItemMeta();
meta4.setDisplayName(tr("\u00a7c\u00a7lLeave Island"));
addLore(lores, "\u00a7f", tr("Leaves your island.\n\u00a74WARNING! \u00a7cwill remove all your items!"));
addLore(lores, tr("\u00a7cClick to leave"));
meta4.setLore(lores);
menuItem.setItemMeta(meta4);
menu.setItem(17, menuItem);
lores.clear();
long millisLeft = plugin.getConfirmHandler().millisLeft(player, "/is leave");
if (millisLeft > 0) {
updateLeaveMenuItemTimer(player, menu, menuItem);
}
}
addExtraMenus(player, menu);
return menu;
}
public void onClick(InventoryClickEvent event) {
ItemStack currentItem = event != null ? event.getCurrentItem() : null;
if (event == null || currentItem == null) {
return; // Bail out, nothing we can do anyway
}
Player p = (Player) event.getWhoClicked();
ItemMeta meta = currentItem.getItemMeta();
SkullMeta skull = meta instanceof SkullMeta ? (SkullMeta) meta : null;
if (!(event.getInventory().getHolder() instanceof UltimateHolder))
return;
String inventoryName = stripFormatting(((UltimateHolder) event.getInventory().getHolder()).getTitle());
int slotIndex = event.getSlot();
int menuSize = event.getInventory().getSize();
if (inventoryName.equalsIgnoreCase(stripFormatting(tr("Island Group Members")))) {
onClickPartyMenu(event, currentItem, p, meta, skull, slotIndex);
} else if (inventoryName.contains(stripFormatting(tr("Permissions")))) {
onClickPermissionMenu(event, currentItem, p, inventoryName, slotIndex);
} else if (inventoryName.equalsIgnoreCase(stripFormatting(tr("Island Biome")))) {
onClickBiomeMenu(event, currentItem, p, slotIndex);
} else if (inventoryName.contains(stripFormatting(tr("Challenge Menu")))) {
onClickChallengeMenu(event, currentItem, p, inventoryName);
} else if (inventoryName.equalsIgnoreCase(stripFormatting(tr("Island Log")))) {
onClickLogMenu(event, p, slotIndex);
} else if (inventoryName.equalsIgnoreCase(stripFormatting(tr("Island Menu")))) {
onClickMainMenu(event, currentItem, p, slotIndex);
} else if (inventoryName.equalsIgnoreCase(stripFormatting(tr("Island Create Menu")))) {
onClickCreateMenu(event, p, meta, slotIndex, menuSize);
} else if (inventoryName.equalsIgnoreCase(stripFormatting(tr("Island Restart Menu")))) {
onClickRestartMenu(event, p, meta, slotIndex, currentItem);
} else if (inventoryName.startsWith(stripFormatting(tr("Config:"))) && event.getWhoClicked() instanceof Player) {
plugin.getConfigMenu().onClick(event);
}
}
private void onClickRestartMenu(final InventoryClickEvent event, final Player p, ItemMeta meta, int slotIndex, ItemStack currentItem) {
event.setCancelled(true);
if (slotIndex == 0) {
p.openInventory(createMainMenu(p));
} else if (currentItem != null && meta != null && meta.getDisplayName() != null) {
String schemeName = stripFormatting(meta.getDisplayName());
IslandPerk islandPerk = plugin.getPerkLogic().getIslandPerk(schemeName);
if (plugin.getPerkLogic().getSchemes(p).contains(schemeName) && p.hasPermission(islandPerk.getPermission())) {
if (plugin.getConfirmHandler().millisLeft(p, "/is restart") > 0) {
p.performCommand("island restart " + schemeName);
} else {
p.performCommand("island restart " + schemeName);
updateRestartMenuTimer(p, event.getInventory());
}
}
}
}
private void updateRestartMenuTimer(final Player p, final Inventory inventory) {
final BukkitTask[] hackySharing = new BukkitTask[1];
hackySharing[0] = plugin.sync(() -> {
if (inventory.getViewers().contains(p)) {
updateRestartMenu(inventory, p, plugin.getIslandGenerator().getSchemeNames());
}
if (plugin.getConfirmHandler().millisLeft(p, "/is restart") <= 0 || !inventory.getViewers().contains(p)) {
if (hackySharing.length > 0 && hackySharing[0] != null) {
hackySharing[0].cancel();
}
}
}, 0, 1000);
}
private void onClickCreateMenu(InventoryClickEvent event, Player p, ItemMeta meta, int slotIndex, int menuSize) {
event.setCancelled(true);
if (slotIndex == 0) {
p.performCommand("island create");
} else if (slotIndex == menuSize - 2) {
p.performCommand("island spawn");
} else if (slotIndex == menuSize - 1) {
p.performCommand("island accept");
} else if (meta != null && meta.getDisplayName() != null) {
String schemeName = stripFormatting(meta.getDisplayName());
if (plugin.getPerkLogic().getSchemes(p).contains(schemeName)) {
p.performCommand("island create " + schemeName);
} else {
p.sendMessage(tr("\u00a7eYou do not have access to that island-schematic!"));
}
}
}
private void onClickMainMenu(InventoryClickEvent event, ItemStack currentItem, Player p, int slotIndex) {
event.setCancelled(true);
if (slotIndex < 0 || slotIndex > 35) {
return;
}
PlayerInfo playerInfo = plugin.getPlayerInfo(p);
IslandInfo islandInfo = plugin.getIslandInfo(playerInfo);
if (currentItem.getType() == Material.JUNGLE_SAPLING) {
p.performCommand("island biome");
} else if (currentItem.getType() == Material.PLAYER_HEAD) {
p.performCommand("island party");
} else if (currentItem.getType() == Material.RED_BED) {
p.performCommand("island sethome");
p.performCommand("island");
} else if (currentItem.getType() == Material.SHORT_GRASS) {
p.performCommand("island spawn");
} else if (currentItem.getType() == Material.HOPPER) {
p.performCommand("island setwarp");
p.performCommand("island");
} else if (currentItem.getType() == Material.WRITABLE_BOOK) {
p.performCommand("island log");
} else if (currentItem.getType() == Material.OAK_DOOR) {
p.performCommand("island home");
} else if (currentItem.getType() == Material.EXPERIENCE_BOTTLE) {
p.performCommand("island level");
} else if (currentItem.getType() == Material.DIAMOND_ORE) {
p.performCommand("c");
} else if (currentItem.getType() == Material.END_STONE || currentItem.getType() == Material.END_PORTAL_FRAME) {
p.performCommand("island togglewarp");
p.performCommand("island");
} else if (currentItem.getType() == Material.IRON_BARS && islandInfo.isLocked()) {
p.performCommand("island unlock");
p.performCommand("island");
} else if (currentItem.getType() == Material.IRON_BARS && !islandInfo.isLocked()) {
p.performCommand("island lock");
p.performCommand("island");
} else if (slotIndex == 17) {
if (islandInfo.isLeader(p) && plugin.getConfig().getBoolean("island-schemes-enabled", true)) {
p.openInventory(createRestartGUI(p));
} else {
if (plugin.getConfirmHandler().millisLeft(p, "/is leave") > 0) {
p.performCommand("island leave");
} else {
p.performCommand("island leave");
updateLeaveMenuItemTimer(p, event.getInventory(), currentItem);
}
}
} else {
if (!isExtraMenuAction(p, currentItem)) {
p.performCommand("island");
}
}
}
private void updateLeaveMenuItemTimer(final Player p, final Inventory inventory, final ItemStack currentItem) {
final BukkitTask[] hackySharing = new BukkitTask[1];
hackySharing[0] = plugin.sync(() -> {
long millisLeft = plugin.getConfirmHandler().millisLeft(p, "/is leave");
if (inventory.getViewers().contains(p)) {
updateLeaveMenuItem(inventory, currentItem, millisLeft);
}
if (millisLeft <= 0 || !inventory.getViewers().contains(p)) {
if (hackySharing.length > 0 && hackySharing[0] != null) {
hackySharing[0].cancel();
}
}
}, 0, 1000);
}
private void updateLeaveMenuItem(Inventory inventory, ItemStack currentItem, long millisLeft) {
if (currentItem == null || currentItem.getItemMeta() == null || currentItem.getItemMeta().getLore() == null) {
return;
}
ItemMeta meta = currentItem.getItemMeta();
List<String> lore = meta.getLore();
if (millisLeft >= 0) {
lore.set(lore.size() - 1, tr("\u00a7cClick within \u00a79{0}\u00a7c to leave!", TimeUtil.millisAsString(millisLeft)));
} else {
lore.set(lore.size() - 1, tr("\u00a7cClick to leave"));
}
meta.setLore(lore);
currentItem.setItemMeta(meta);
inventory.setItem(17, currentItem);
}
public Inventory createRestartGUI(Player player) {
List<String> schemeNames = plugin.getIslandGenerator().getSchemeNames();
int menuSize = (int) Math.ceil(getMaxSchemeIndex(schemeNames) / 9d) * 9;
String title = "\u00a79" + tr("Island Restart Menu");
Inventory menu = Bukkit.createInventory(new UltimateHolder(player, title, MenuType.DEFAULT), menuSize, title);
List<String> lores = new ArrayList<>();
ItemStack menuItem = new ItemStack(Material.OAK_SIGN, 1);
ItemMeta meta = menuItem.getItemMeta();
meta.setDisplayName(tr("\u00a7a\u00a7lReturn to the main menu"));
meta.setLore(lores);
menuItem.setItemMeta(meta);
menu.addItem(menuItem);
lores.clear();
updateRestartMenu(menu, player, schemeNames);
if (plugin.getConfirmHandler().millisLeft(player, "/is restart") > 0) {
updateRestartMenuTimer(player, menu);
}
return menu;
}
private void updateRestartMenu(Inventory menu, Player player, List<String> schemeNames) {
ItemStack menuItem;
ItemMeta meta;
List<String> lores;
int index = 1;
for (String schemeName : schemeNames) {
IslandPerk islandPerk = plugin.getPerkLogic().getIslandPerk(schemeName);
boolean enabled = plugin.getConfig().getBoolean("island-schemes." + islandPerk.getSchemeName() + ".enabled", true);
if (!enabled) {
continue; // Skip
}
index = plugin.getConfig().getInt("island-schemes." + islandPerk.getSchemeName() + ".index", index);
menuItem = islandPerk.getDisplayItem();
meta = menuItem.getItemMeta();
lores = meta.getLore();
if (lores == null) {
lores = new ArrayList<>();
}
if (player.hasPermission(islandPerk.getPermission())) {
long millisLeft = plugin.getConfirmHandler().millisLeft(player, "/is restart");
if (millisLeft > 0) {
addLore(lores, tr("\u00a7cClick within \u00a79{0}\u00a7c to restart!", TimeUtil.millisAsString(millisLeft)));
} else {
addLore(lores, tr("\u00a7aClick to restart!"));
}
} else {
addLore(lores, tr("\u00a7cNo access!\n\u00a77({0})", islandPerk.getPermission()));
}
meta.setLore(lores);
menuItem.setItemMeta(meta);
menu.setItem(index++, menuItem);
}
player.updateInventory();
}
private void onClickLogMenu(InventoryClickEvent event, Player p, int slotIndex) {
event.setCancelled(true);
if (slotIndex < 0 || slotIndex > 35) {
return;
}
p.performCommand("island");
}
private void onClickChallengeMenu(InventoryClickEvent event, ItemStack currentItem, Player p, String inventoryName) {
int slotIndex = event.getRawSlot();
event.setCancelled(true);
Matcher m = CHALLENGE_PAGE_HEADER.matcher(inventoryName);
int page = 1;
int max = challengeLogic.getTotalPages();
if (m.find()) {
page = Integer.parseInt(m.group("p"));
max = Integer.parseInt(m.group("max"));
}
ItemStack item = event.getInventory().getItem(event.getInventory().getSize() - 9);
String playerName = item != null && item.hasItemMeta() && item.getItemMeta().getLore() != null
&& item.getItemMeta().getLore().size() > 0
? item.getItemMeta().getLore().get(0)
: null;
if (playerName != null && playerName.trim().isEmpty()) {
playerName = null;
}
// Last row is pagination
if (slotIndex >= CHALLENGE_PAGESIZE && slotIndex < CHALLENGE_PAGESIZE + COLS_PER_ROW
&& currentItem != null && currentItem.getType() != Material.AIR) {
// Pagination
p.openInventory(displayChallengeGUI(p, currentItem.getAmount(), playerName));
return;
}
// If in action bar or anywhere else, just bail out
if (slotIndex < 0 || slotIndex > CHALLENGE_PAGESIZE || isAirOrLocked(currentItem)) {
return;
}
if ((slotIndex % 9) > 0) { // 0,9... are the rank-headers...
if (currentItem.getItemMeta() != null) {
String challenge = currentItem.getItemMeta().getDisplayName();
String challengeName = stripFormatting(challenge);
p.performCommand("c c " + challengeName);
}
p.openInventory(displayChallengeGUI(p, page, playerName));
} else {
if (slotIndex < (CHALLENGE_PAGESIZE / 2)) { // Upper half
if (page > 1) {
p.openInventory(displayChallengeGUI(p, page - 1, playerName));
} else {
p.performCommand("island");
}
} else if (page < max) {
p.openInventory(displayChallengeGUI(p, page + 1, playerName));
} else {
p.performCommand("island");
}
}
}
private boolean isAirOrLocked(ItemStack currentItem) {
return currentItem != null && currentItem.getType() == Material.AIR ||
currentItem != null && currentItem.getItemMeta() != null && currentItem.getItemMeta().getDisplayName().equals(tr("\u00a74\u00a7lLocked Challenge"));
}
private void onClickBiomeMenu(InventoryClickEvent event, ItemStack currentItem, Player p, int slotIndex) {
event.setCancelled(true);
if (slotIndex < 0 || slotIndex > 35) {
return;
}
if (slotIndex == 0 && currentItem.getType() == Material.OAK_SIGN) {
p.performCommand("island");
return;
}
if (slotIndex >= 21 && slotIndex <= 23) {
List<String> radii = Arrays.asList("10", "chunk", "20", "30", "40", "50", "60", "70", "80", "90", "100", "all");
String radius = PlayerUtil.getMetadata(p, "biome.radius", "all");
int ix = radii.indexOf(radius);
if (ix == -1) {
ix = 1;
}
if (currentItem.getType() == Material.RED_CARPET && ix > 0) {
ix--;
} else if (currentItem.getType() == Material.GREEN_CARPET && ix < radii.size() - 1) {
ix++;
}
radius = radii.get(ix);
PlayerUtil.setMetadata(p, "biome.radius", radius);
updateBiomeRadius(p, event.getInventory());
event.setCancelled(true);
return;
}
for (BiomeMenuItem biomeMenu : biomeMenus) {
ItemStack menuIcon = biomeMenu.getIcon();
if (currentItem.getType() == menuIcon.getType()) {
String radius = PlayerUtil.getMetadata(p, "biome.radius", "all");
p.performCommand("island biome " + biomeMenu.getId() + " " + radius);
return;
}
}
}
private void onClickPermissionMenu(InventoryClickEvent event, ItemStack currentItem, Player p, String inventoryName, int slotIndex) {
event.setCancelled(true);
if (slotIndex < 0 || slotIndex > 35) {
return;
}
IslandInfo islandInfo = plugin.getIslandInfo(p);
if (!plugin.getIslandInfo(p).isLeader(p)) {
p.openInventory(displayPartyGUI(p));
}
String[] playerPerm = inventoryName.split(" ");
String pname = playerPerm[0];
ItemStack skullItem = event.getInventory().getItem(1);
if (skullItem != null && skullItem.getType().equals(Material.PLAYER_HEAD)) {
ItemMeta meta = skullItem.getItemMeta();
if (meta instanceof SkullMeta) {
pname = ((SkullMeta) meta).getOwner();
}
}
for (PartyPermissionMenuItem item : permissionMenuItems) {
if (currentItem.getType() == item.getIcon().getType()) {
islandInfo.togglePerm(pname, item.getPerm());
p.openInventory(displayPartyPlayerGUI(p, pname));
return;
}
}
if (currentItem.getType() == Material.OAK_SIGN) {
p.openInventory(displayPartyGUI(p));
} else {
p.openInventory(displayPartyPlayerGUI(p, pname));
}
}
private void onClickPartyMenu(InventoryClickEvent event, ItemStack currentItem, Player p, ItemMeta meta, SkullMeta skull, int slotIndex) {
event.setCancelled(true);
if (slotIndex < 0 || slotIndex > 35) {
return;
}
if (meta == null || currentItem.getType() == Material.OAK_SIGN) {
p.performCommand("island");
} else if (skull != null && plugin.getIslandInfo(p).isLeader(p)) {
p.openInventory(displayPartyPlayerGUI(p, skull.getOwner()));
}
}
public List<PartyPermissionMenuItem> getPermissionMenuItems() {
return permissionMenuItems;
}
}
| 412 | 0.990532 | 1 | 0.990532 | game-dev | MEDIA | 0.98562 | game-dev | 0.923647 | 1 | 0.923647 |
OpenRA/OpenRA | 4,563 | mods/cnc/maps/gdi04a/gdi04a.lua | --[[
Copyright (c) The OpenRA Developers and Contributors
This file is part of OpenRA, which is free software. It is made
available to you 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. For more
information, see COPYING.
]]
AutoTrigger = { CPos.New(51, 47), CPos.New(52, 47), CPos.New(53, 47), CPos.New(54, 47) }
GDIHeliTrigger = { CPos.New(27, 55), CPos.New(27, 56), CPos.New(28, 56), CPos.New(28, 57), CPos.New(28, 58), CPos.New(28, 59)}
NodUnits = { "e1", "e1", "e3", "e3" }
AutoUnits = { "e1", "e1", "e3" }
KillsUntilReinforcements = 12
HeliDelay = { 83, 137, 211 }
GDIReinforcements = { "e2", "e2", "e2", "e2", "e2" }
GDIReinforcementsWaypoints = { GDIReinforcementsEntry.Location, GDIReinforcementsWP1.Location }
GDIReinforcementsLeft = 3
NodHelis =
{
{ delay = DateTime.Seconds(HeliDelay[1]), entry = { NodHeliEntry.Location, NodHeliLZ1.Location }, types = { "e1", "e1", "e3" } },
{ delay = DateTime.Seconds(HeliDelay[2]), entry = { NodHeliEntry.Location, NodHeliLZ2.Location }, types = { "e1", "e1", "e1", "e1" } },
{ delay = DateTime.Seconds(HeliDelay[3]), entry = { NodHeliEntry.Location, NodHeliLZ3.Location }, types = { "e1", "e1", "e3" } }
}
Kills = 0
NodUnitKilled = function()
Kills = Kills + 1
if Kills == KillsUntilReinforcements then
GDI.MarkCompletedObjective(ReinforcementsObjective)
SendGDIReinforcements()
end
end
SendHeli = function(heli)
local units = Reinforcements.ReinforceWithTransport(Nod, "tran", heli.types, heli.entry, { heli.entry[1] })
Utils.Do(units[2], function(actor)
IdleHunt(actor)
Trigger.OnKilled(actor, NodUnitKilled)
end)
Trigger.AfterDelay(heli.delay, function() SendHeli(heli) end)
end
SendGDIReinforcements = function()
Media.PlaySpeechNotification(GDI, "Reinforce")
Reinforcements.ReinforceWithTransport(GDI, "apc", GDIReinforcements, GDIReinforcementsWaypoints, nil, function(apc, team)
table.insert(team, apc)
Trigger.OnAllKilled(team, function()
if GDIReinforcementsLeft > 0 then
GDIReinforcementsLeft = GDIReinforcementsLeft - 1
Trigger.AfterDelay(DateTime.Seconds(5), function()
Media.DisplayMessage(UserInterface.GetFluentMessage("apcs-left", { ["apcs"] = GDIReinforcementsLeft }), UserInterface.GetFluentMessage("battlefield-control"))
SendGDIReinforcements()
end)
end
end)
end)
end
BuildNod = function()
local after = function(team)
Utils.Do(team, function(actor)
Trigger.OnIdle(actor, actor.Hunt)
Trigger.OnKilled(actor, NodUnitKilled)
end)
Trigger.OnAllKilled(team, BuildNod)
end
ProduceUnits(Nod, HandOfNod, nil, function() return NodUnits end, after)
end
BuildAuto = function()
local after = function(team)
Utils.Do(team, function(actor)
Trigger.OnIdle(actor, actor.Hunt)
Trigger.OnKilled(actor, NodUnitKilled)
end)
end
local delay = function() return DateTime.Seconds(5) end
ProduceUnits(Nod, HandOfNod, delay, function() return AutoUnits end, after)
end
Tick = function()
Nod.Cash = 1000
if (GDIReinforcementsLeft == 0 or not GDI.IsObjectiveCompleted(ReinforcementsObjective)) and GDI.HasNoRequiredUnits() then
GDI.MarkFailedObjective(GDIObjective)
end
end
SetupWorld = function()
Utils.Do(Nod.GetGroundAttackers(), function(unit)
Trigger.OnKilled(unit, NodUnitKilled)
end)
Hunter1.Hunt()
Hunter2.Hunt()
Trigger.OnRemovedFromWorld(crate, function() GDI.MarkCompletedObjective(GDIObjective) end)
end
WorldLoaded = function()
GDI = Player.GetPlayer("GDI")
Nod = Player.GetPlayer("Nod")
SetupWorld()
InitObjectives(GDI)
GDIObjective = AddPrimaryObjective(GDI, "retrieve-rods")
local eliminateReinforcements = UserInterface.GetFluentMessage("eliminate-reinforcements", { ["kills"] = KillsUntilReinforcements })
ReinforcementsObjective = AddSecondaryObjective(GDI, eliminateReinforcements)
BuildNod()
Utils.Do(NodHelis, function(heli)
Trigger.AfterDelay(heli.delay, function() SendHeli(heli) end)
end)
Trigger.OnEnteredFootprint(AutoTrigger, function(a, id)
if not AutoTriggered and a.Owner == GDI then
AutoTriggered = true
Trigger.RemoveFootprintTrigger(id)
BuildAuto()
end
end)
Trigger.OnEnteredFootprint(GDIHeliTrigger, function(a, id)
if not GDIHeliTriggered and a.Owner == GDI then
GDIHeliTriggered = true
Trigger.RemoveFootprintTrigger(id)
Reinforcements.ReinforceWithTransport(GDI, "tran", nil, { GDIHeliEntry.Location, GDIHeliLZ.Location })
end
end)
Camera.Position = Actor56.CenterPosition
end
| 412 | 0.914514 | 1 | 0.914514 | game-dev | MEDIA | 0.967386 | game-dev | 0.945388 | 1 | 0.945388 |
ValveSoftware/halflife | 7,517 | dlls/items.cpp | /***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
/*
===== items.cpp ========================================================
functions governing the selection/use of weapons for players
*/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "weapons.h"
#include "player.h"
#include "skill.h"
#include "items.h"
#include "gamerules.h"
extern int gmsgItemPickup;
class CWorldItem : public CBaseEntity
{
public:
void KeyValue(KeyValueData *pkvd );
void Spawn( void );
int m_iType;
};
LINK_ENTITY_TO_CLASS(world_items, CWorldItem);
void CWorldItem::KeyValue(KeyValueData *pkvd)
{
if (FStrEq(pkvd->szKeyName, "type"))
{
m_iType = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else
CBaseEntity::KeyValue( pkvd );
}
void CWorldItem::Spawn( void )
{
CBaseEntity *pEntity = NULL;
switch (m_iType)
{
case 44: // ITEM_BATTERY:
pEntity = CBaseEntity::Create( "item_battery", pev->origin, pev->angles );
break;
case 42: // ITEM_ANTIDOTE:
pEntity = CBaseEntity::Create( "item_antidote", pev->origin, pev->angles );
break;
case 43: // ITEM_SECURITY:
pEntity = CBaseEntity::Create( "item_security", pev->origin, pev->angles );
break;
case 45: // ITEM_SUIT:
pEntity = CBaseEntity::Create( "item_suit", pev->origin, pev->angles );
break;
}
if (!pEntity)
{
ALERT( at_console, "unable to create world_item %d\n", m_iType );
}
else
{
pEntity->pev->target = pev->target;
pEntity->pev->targetname = pev->targetname;
pEntity->pev->spawnflags = pev->spawnflags;
}
REMOVE_ENTITY(edict());
}
void CItem::Spawn( void )
{
pev->movetype = MOVETYPE_TOSS;
pev->solid = SOLID_TRIGGER;
UTIL_SetOrigin( pev, pev->origin );
UTIL_SetSize(pev, Vector(-16, -16, 0), Vector(16, 16, 16));
SetTouch(&CItem::ItemTouch);
if (DROP_TO_FLOOR(ENT(pev)) == 0)
{
ALERT(at_error, "Item %s fell out of level at %f,%f,%f", STRING( pev->classname ), pev->origin.x, pev->origin.y, pev->origin.z);
UTIL_Remove( this );
return;
}
}
extern int gEvilImpulse101;
void CItem::ItemTouch( CBaseEntity *pOther )
{
// if it's not a player, ignore
if ( !pOther->IsPlayer() )
{
return;
}
CBasePlayer *pPlayer = (CBasePlayer *)pOther;
// ok, a player is touching this item, but can he have it?
if ( !g_pGameRules->CanHaveItem( pPlayer, this ) )
{
// no? Ignore the touch.
return;
}
if (MyTouch( pPlayer ))
{
SUB_UseTargets( pOther, USE_TOGGLE, 0 );
SetTouch( NULL );
// player grabbed the item.
g_pGameRules->PlayerGotItem( pPlayer, this );
if ( g_pGameRules->ItemShouldRespawn( this ) == GR_ITEM_RESPAWN_YES )
{
Respawn();
}
else
{
UTIL_Remove( this );
}
}
else if (gEvilImpulse101)
{
UTIL_Remove( this );
}
}
CBaseEntity* CItem::Respawn( void )
{
SetTouch( NULL );
pev->effects |= EF_NODRAW;
UTIL_SetOrigin( pev, g_pGameRules->VecItemRespawnSpot( this ) );// blip to whereever you should respawn.
SetThink ( &CItem::Materialize );
pev->nextthink = g_pGameRules->FlItemRespawnTime( this );
return this;
}
void CItem::Materialize( void )
{
if ( pev->effects & EF_NODRAW )
{
// changing from invisible state to visible.
EMIT_SOUND_DYN( ENT(pev), CHAN_WEAPON, "items/suitchargeok1.wav", 1, ATTN_NORM, 0, 150 );
pev->effects &= ~EF_NODRAW;
pev->effects |= EF_MUZZLEFLASH;
}
SetTouch( &CItem::ItemTouch );
}
#define SF_SUIT_SHORTLOGON 0x0001
class CItemSuit : public CItem
{
void Spawn( void )
{
Precache( );
SET_MODEL(ENT(pev), "models/w_suit.mdl");
CItem::Spawn( );
}
void Precache( void )
{
PRECACHE_MODEL ("models/w_suit.mdl");
}
BOOL MyTouch( CBasePlayer *pPlayer )
{
if ( pPlayer->pev->weapons & (1<<WEAPON_SUIT) )
return FALSE;
if ( pev->spawnflags & SF_SUIT_SHORTLOGON )
EMIT_SOUND_SUIT(pPlayer->edict(), "!HEV_A0"); // short version of suit logon,
else
EMIT_SOUND_SUIT(pPlayer->edict(), "!HEV_AAx"); // long version of suit logon
pPlayer->pev->weapons |= (1<<WEAPON_SUIT);
return TRUE;
}
};
LINK_ENTITY_TO_CLASS(item_suit, CItemSuit);
class CItemBattery : public CItem
{
void Spawn( void )
{
Precache( );
SET_MODEL(ENT(pev), "models/w_battery.mdl");
CItem::Spawn( );
}
void Precache( void )
{
PRECACHE_MODEL ("models/w_battery.mdl");
PRECACHE_SOUND( "items/gunpickup2.wav" );
}
BOOL MyTouch( CBasePlayer *pPlayer )
{
if ( pPlayer->pev->deadflag != DEAD_NO )
{
return FALSE;
}
if ((pPlayer->pev->armorvalue < MAX_NORMAL_BATTERY) &&
(pPlayer->pev->weapons & (1<<WEAPON_SUIT)))
{
int pct;
char szcharge[64];
pPlayer->pev->armorvalue += gSkillData.batteryCapacity;
pPlayer->pev->armorvalue = min<float>(pPlayer->pev->armorvalue, MAX_NORMAL_BATTERY);
EMIT_SOUND( pPlayer->edict(), CHAN_ITEM, "items/gunpickup2.wav", 1, ATTN_NORM );
MESSAGE_BEGIN( MSG_ONE, gmsgItemPickup, NULL, pPlayer->pev );
WRITE_STRING( STRING(pev->classname) );
MESSAGE_END();
// Suit reports new power level
// For some reason this wasn't working in release build -- round it.
pct = (int)( (float)(pPlayer->pev->armorvalue * 100.0) * (1.0/MAX_NORMAL_BATTERY) + 0.5);
pct = (pct / 5);
if (pct > 0)
pct--;
sprintf( szcharge,"!HEV_%1dP", pct );
//EMIT_SOUND_SUIT(ENT(pev), szcharge);
pPlayer->SetSuitUpdate(szcharge, FALSE, SUIT_NEXT_IN_30SEC);
return TRUE;
}
return FALSE;
}
};
LINK_ENTITY_TO_CLASS(item_battery, CItemBattery);
class CItemAntidote : public CItem
{
void Spawn( void )
{
Precache( );
SET_MODEL(ENT(pev), "models/w_antidote.mdl");
CItem::Spawn( );
}
void Precache( void )
{
PRECACHE_MODEL ("models/w_antidote.mdl");
}
BOOL MyTouch( CBasePlayer *pPlayer )
{
pPlayer->SetSuitUpdate("!HEV_DET4", FALSE, SUIT_NEXT_IN_1MIN);
pPlayer->m_rgItems[ITEM_ANTIDOTE] += 1;
return TRUE;
}
};
LINK_ENTITY_TO_CLASS(item_antidote, CItemAntidote);
class CItemSecurity : public CItem
{
void Spawn( void )
{
Precache( );
SET_MODEL(ENT(pev), "models/w_security.mdl");
CItem::Spawn( );
}
void Precache( void )
{
PRECACHE_MODEL ("models/w_security.mdl");
}
BOOL MyTouch( CBasePlayer *pPlayer )
{
pPlayer->m_rgItems[ITEM_SECURITY] += 1;
return TRUE;
}
};
LINK_ENTITY_TO_CLASS(item_security, CItemSecurity);
class CItemLongJump : public CItem
{
void Spawn( void )
{
Precache( );
SET_MODEL(ENT(pev), "models/w_longjump.mdl");
CItem::Spawn( );
}
void Precache( void )
{
PRECACHE_MODEL ("models/w_longjump.mdl");
}
BOOL MyTouch( CBasePlayer *pPlayer )
{
if ( pPlayer->m_fLongJump )
{
return FALSE;
}
if ( ( pPlayer->pev->weapons & (1<<WEAPON_SUIT) ) )
{
pPlayer->m_fLongJump = TRUE;// player now has longjump module
g_engfuncs.pfnSetPhysicsKeyValue( pPlayer->edict(), "slj", "1" );
MESSAGE_BEGIN( MSG_ONE, gmsgItemPickup, NULL, pPlayer->pev );
WRITE_STRING( STRING(pev->classname) );
MESSAGE_END();
EMIT_SOUND_SUIT( pPlayer->edict(), "!HEV_A1" ); // Play the longjump sound UNDONE: Kelly? correct sound?
return TRUE;
}
return FALSE;
}
};
LINK_ENTITY_TO_CLASS( item_longjump, CItemLongJump );
| 412 | 0.880765 | 1 | 0.880765 | game-dev | MEDIA | 0.985651 | game-dev | 0.81002 | 1 | 0.81002 |
opentibia/yatc | 7,007 | ui/uitrade.cpp | //////////////////////////////////////////////////////////////////////
// Yet Another Tibia Client
//////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//////////////////////////////////////////////////////////////////////
#include "uitrade.h"
#include "../gm_gameworld.h"
#include "../net/protocolgame.h"
#include "../skin.h"
#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif
#if defined(HAVE_LIBINTL_H)
#include <libintl.h>
#else
#define gettext(x) (x)
#endif
winTrade_t::winTrade_t()
{
window.SetCaption(gettext("Trade"));
window.SetHeight(GetDefaultHeight());
#if (GLICT_APIREV >= 76)
window.AddTitlebarObject(&pnlIcon);
pnlIcon.SetWidth(12);
pnlIcon.SetHeight(12);
pnlIcon.SetPos(2, 2);
pnlIcon.SetOnPaint(iconOnPaint);
#endif
window.AddObject(&lblNameLeft);
lblNameLeft.SetPos(3, 2);
lblNameLeft.SetWidth(70);
lblNameLeft.SetHeight(8);
lblNameLeft.SetFont("aafont");
lblNameLeft.SetBGActiveness(false);
window.AddObject(&lblNameRight);
lblNameRight.SetPos(82, 2);
lblNameRight.SetWidth(70);
lblNameRight.SetHeight(8);
lblNameRight.SetFont("aafont");
lblNameRight.SetBGActiveness(false);
window.AddObject(&pnlSepTop);
pnlSepTop.SetPos(0, 10);
pnlSepTop.SetWidth(160);
pnlSepTop.SetHeight(2);
pnlSepTop.SetBGColor(.2,.2,.2,1.);
pnlSepTop.SetSkin(&g_skin.chk);
window.AddObject(&pnlContainerLeft);
pnlContainerLeft.SetBGActiveness(false);
pnlContainerLeft.SetPos(0, 12);
pnlContainerLeft.SetWidth(80);
pnlContainerLeft.SetHeight(75);
pnlContainerLeft.SetVirtualSize(80, 75);
window.AddObject(&pnlContainerRight);
pnlContainerRight.SetBGActiveness(false);
pnlContainerRight.SetPos(80, 12);
pnlContainerRight.SetWidth(80);
pnlContainerRight.SetHeight(75);
pnlContainerRight.SetVirtualSize(80, 75);
window.AddObject(&pnlSepMiddle);
pnlSepMiddle.SetPos(80, 13);
pnlSepMiddle.SetWidth(2);
pnlSepMiddle.SetHeight(75);
pnlSepMiddle.SetBGColor(.2,.2,.2,1.);
pnlSepMiddle.SetSkin(&g_skin.chk);
window.AddObject(&pnlSepBottom);
pnlSepBottom.SetPos(0, 88);
pnlSepBottom.SetWidth(160);
pnlSepBottom.SetHeight(2);
pnlSepBottom.SetBGColor(.2,.2,.2,1.);
pnlSepBottom.SetSkin(&g_skin.chk);
window.AddObject(&lblWait);
lblWait.SetFont("minifont");
lblWait.SetPos(10, 92);
lblWait.SetWidth(100);
lblWait.SetHeight(20);
lblWait.SetBGActiveness(false);
window.AddObject(&btnAccept);
btnAccept.SetSkin(&g_skin.btnn[BUTTON_43]);
btnAccept.SetHighlightSkin(&g_skin.btnh[BUTTON_43]);
btnAccept.SetFont("minifont",8);
btnAccept.SetCaption(gettext("Accept"));
btnAccept.SetPos(67, 92);
btnAccept.SetWidth(43);
btnAccept.SetHeight(20);
btnAccept.SetOnClick(tradeOnAccept);
window.AddObject(&btnReject);
btnReject.SetSkin(&g_skin.btnn[BUTTON_43]);
btnReject.SetHighlightSkin(&g_skin.btnh[BUTTON_43]);
btnReject.SetFont("minifont",8);
btnReject.SetCaption(gettext("Reject"));
btnReject.SetPos(115, 92);
btnReject.SetWidth(43);
btnReject.SetHeight(20);
btnReject.SetOnClick(tradeOnReject);
m_rightSideSet = false;
m_leftSideSet = false;
}
winTrade_t::~winTrade_t()
{
//
}
void winTrade_t::onTradeUpdate(bool ack)
{
Container* container;
glictContainer* pnlContainer;
PanelList* pnlList;
uint32_t flag;
if(ack){ //left side
container = Containers::getInstance().getTradeContainerAck();
lblNameLeft.SetCaption(container->getName());
pnlContainer = &pnlContainerLeft;
pnlList = &pnlItemsLeft;
m_leftSideSet = true;
flag = 1;
}
else{ //right side
container = Containers::getInstance().getTradeContainer();
lblNameRight.SetCaption(container->getName());
pnlContainer = &pnlContainerRight;
pnlList = &pnlItemsRight;
m_rightSideSet = true;
flag = 0;
}
float height = 4 + (36*ceil(container->getCapacity()/2.));
pnlContainer->SetVirtualSize(80, height);
pnlContainer->SetHeight(72);
for(uint32_t i = 0; i != container->getCapacity(); ++i)
{
ItemPanel* panel = new ItemPanel(container, i, Position(0,0,0), i);
panel->SetPos(5 + ((i % 2) * 36), 4 + (std::floor(i / 2.0f) * 36));
panel->SetOnClick(tradeItemOnClick);
//panel->SetOnPaint(tradeItemOnPaint);
panel->SetOnMouseUp(NULL);
panel->SetOnMouseDown(NULL);
panel->SetCustomData((void*)(i*2 | flag));
pnlContainer->AddObject(panel);
pnlList->push_back(panel);
}
//update buttons
if(m_leftSideSet && !m_rightSideSet){
btnReject.SetVisible(true);
btnReject.SetCaption(gettext("Cancel"));
btnAccept.SetVisible(false);
lblWait.SetCaption(gettext("Wait for a counter offer."));
lblWait.SetVisible(true);
}
else if(m_rightSideSet){
btnReject.SetVisible(true);
btnReject.SetCaption("Reject");
btnAccept.SetVisible(true);
lblWait.SetVisible(false);
}
}
void winTrade_t::onTradeCompleted()
{
PanelList::iterator it = pnlItemsLeft.begin();
for(;it != pnlItemsLeft.end(); ++it)
{
pnlContainerLeft.RemoveObject((*it));
delete (*it);
}
pnlItemsLeft.clear();
for(it = pnlItemsRight.begin(); it != pnlItemsRight.end(); ++it)
{
pnlContainerRight.RemoveObject((*it));
delete (*it);
}
pnlItemsRight.clear();
m_rightSideSet = false;
m_leftSideSet = false;
}
void winTrade_t::tradeItemOnClick(glictPos* relmousepos, glictContainer* caller)
{
GM_Gameworld *gw = (GM_Gameworld*)g_game;
void* data = caller->GetCustomData();
bool flag = (long)data & 1;
int slot = (long)data >> 1;
gw->m_protocol->sendLookInTrade(flag, slot);
}
void winTrade_t::onClose()
{
GM_Gameworld *gw = (GM_Gameworld*)g_game;
gw->m_protocol->sendRejectTrade();
}
void winTrade_t::tradeOnAccept(glictPos* relmousepos, glictContainer* caller)
{
GM_Gameworld *gw = (GM_Gameworld*)g_game;
winTrade_t& window = gw->winTrade;
window.btnAccept.SetVisible(false);
window.lblWait.SetCaption(gettext("Please wait for your \npartner to accept."));
window.lblWait.SetVisible(true);
gw->m_protocol->sendAcceptTrade();
}
void winTrade_t::tradeOnReject(glictPos* relmousepos, glictContainer* caller)
{
GM_Gameworld *gw = (GM_Gameworld*)g_game;
gw->m_protocol->sendRejectTrade();
}
void winTrade_t::iconOnPaint(glictRect* real, glictRect* clipped, glictContainer* caller)
{
g_engine->getUISprite()->Blit((int)real->left, (int)real->top, 325, 60, 12, 12);
}
| 412 | 0.863389 | 1 | 0.863389 | game-dev | MEDIA | 0.505907 | game-dev,desktop-app | 0.947554 | 1 | 0.947554 |
Monkestation/Monkestation2.0 | 15,716 | code/modules/clothing/under/_under.dm | /obj/item/clothing/under
name = "under"
icon = 'icons/obj/clothing/under/default.dmi'
worn_icon = 'icons/mob/clothing/under/default.dmi'
lefthand_file = 'icons/mob/inhands/clothing/suits_lefthand.dmi'
righthand_file = 'icons/mob/inhands/clothing/suits_righthand.dmi'
body_parts_covered = CHEST|GROIN|LEGS|ARMS
slot_flags = ITEM_SLOT_ICLOTHING
interaction_flags_click = NEED_DEXTERITY|ALLOW_RESTING
armor_type = /datum/armor/clothing_under
equip_sound = 'sound/items/equip/jumpsuit_equip.ogg'
drop_sound = 'sound/items/handling/cloth_drop.ogg'
pickup_sound = 'sound/items/handling/cloth_pickup.ogg'
limb_integrity = 30
blood_overlay_type = "uniform"
/// Has this undersuit been freshly laundered and, as such, imparts a mood bonus for wearing
var/freshly_laundered = FALSE
// Alt style handling
/// Can this suit be adjustd up or down to an alt style
var/can_adjust = TRUE
/// If adjusted what style are we currently using?
var/adjusted = NORMAL_STYLE
/// For adjusted/rolled-down jumpsuits. FALSE = exposes chest and arms, TRUE = exposes arms only
var/alt_covers_chest = FALSE
/// The variable containing the flags for how the woman uniform cropping is supposed to interact with the sprite.
var/female_sprite_flags = FEMALE_UNIFORM_FULL
// Sensor handling
/// Does this undersuit have suit sensors in general
var/has_sensor = HAS_SENSORS
/// Does this undersuit spawn with a random sensor value
var/random_sensor = TRUE
/// What is the active sensor mode of this udnersuit
var/sensor_mode = NO_SENSORS
// Accessory handling (Can be componentized eventually)
/// The max number of accessories we can have on this suit.
var/max_number_of_accessories = 5
/// A list of all accessories attached to us.
var/list/obj/item/clothing/accessory/attached_accessories
/// The overlay of the accessory we're demonstrating. Only index 1 will show up.
/// This is the overlay on the MOB, not the item itself.
var/mutable_appearance/accessory_overlay
supports_variations_flags = CLOTHING_DIGITIGRADE_VARIATION
/datum/armor/clothing_under
bio = 10
wound = 5
/obj/item/clothing/under/Initialize(mapload)
. = ..()
if(random_sensor)
//make the sensor mode favor higher levels, except coords.
sensor_mode = pick(SENSOR_VITALS, SENSOR_VITALS, SENSOR_VITALS, SENSOR_LIVING, SENSOR_LIVING, SENSOR_COORDS, SENSOR_COORDS, SENSOR_OFF)
register_context()
// MONKESTATION EDIT START
// AddElement(/datum/element/update_icon_updates_onmob, flags = ITEM_SLOT_ICLOTHING|ITEM_SLOT_OCLOTHING, body = TRUE) - original
AddElement(/datum/element/update_icon_updates_onmob, flags = ITEM_SLOT_ICLOTHING|ITEM_SLOT_OCLOTHING|ITEM_SLOT_NECK, body = TRUE)
// MONKESTATION EDIT END
/obj/item/clothing/under/setup_reskinning()
if(!check_setup_reskinning())
return
// We already register context in Initialize.
RegisterSignal(src, COMSIG_CLICK_ALT, PROC_REF(on_click_alt_reskin))
/obj/item/clothing/under/add_context(atom/source, list/context, obj/item/held_item, mob/living/user)
. = NONE
if(isnull(held_item) && has_sensor == HAS_SENSORS)
context[SCREENTIP_CONTEXT_RMB] = "Toggle suit sensors"
context[SCREENTIP_CONTEXT_CTRL_LMB] = "Set suit sensors to tracking"
. = CONTEXTUAL_SCREENTIP_SET
if(istype(held_item, /obj/item/clothing/accessory) && length(attached_accessories) < max_number_of_accessories)
context[SCREENTIP_CONTEXT_LMB] = "Attach accessory"
. = CONTEXTUAL_SCREENTIP_SET
if(LAZYLEN(attached_accessories))
context[SCREENTIP_CONTEXT_ALT_RMB] = "Remove accessory"
. = CONTEXTUAL_SCREENTIP_SET
if(istype(held_item, /obj/item/stack/cable_coil) && has_sensor == BROKEN_SENSORS)
context[SCREENTIP_CONTEXT_LMB] = "Repair suit sensors"
. = CONTEXTUAL_SCREENTIP_SET
if(can_adjust)
context[SCREENTIP_CONTEXT_ALT_LMB] = "Wear [adjusted == ALT_STYLE ? "normally" : "casually"]"
. = CONTEXTUAL_SCREENTIP_SET
return .
/obj/item/clothing/under/worn_overlays(mutable_appearance/standing, isinhands = FALSE)
. = ..()
if(isinhands)
return
if(damaged_clothes)
. += mutable_appearance('icons/effects/item_damage.dmi', "damageduniform")
if(accessory_overlay)
. += accessory_overlay
/obj/item/clothing/under/attackby(obj/item/attacking_item, mob/user, list/modifiers, list/attack_modifiers)
if(has_sensor == BROKEN_SENSORS && istype(attacking_item, /obj/item/stack/cable_coil))
var/obj/item/stack/cable_coil/cabling = attacking_item
to_chat(user, span_notice("You repair the suit sensors on [src] with [cabling]."))
cabling.use(1)
has_sensor = HAS_SENSORS
update_wearer_status()
return TRUE
if(istype(attacking_item, /obj/item/clothing/accessory))
return attach_accessory(attacking_item, user)
return ..()
/obj/item/clothing/under/attack_hand_secondary(mob/user, params)
. = ..()
if(. == SECONDARY_ATTACK_CANCEL_ATTACK_CHAIN)
return
toggle()
return SECONDARY_ATTACK_CANCEL_ATTACK_CHAIN
/obj/item/clothing/under/update_clothes_damaged_state(damaged_state = CLOTHING_DAMAGED)
. = ..()
if(damaged_state == CLOTHING_SHREDDED && has_sensor > NO_SENSORS)
has_sensor = BROKEN_SENSORS
else if(damaged_state == CLOTHING_PRISTINE && has_sensor == BROKEN_SENSORS)
has_sensor = HAS_SENSORS
update_wearer_status()
update_appearance()
/obj/item/clothing/under/emp_act(severity)
. = ..()
if(. & EMP_PROTECT_SELF)
return
if(has_sensor == NO_SENSORS || has_sensor == BROKEN_SENSORS)
return
if(severity <= EMP_HEAVY)
has_sensor = BROKEN_SENSORS
if(ismob(loc))
var/mob/M = loc
to_chat(M,span_warning("[src]'s sensors short out!"))
else
sensor_mode = pick(SENSOR_OFF, SENSOR_OFF, SENSOR_OFF, SENSOR_LIVING, SENSOR_LIVING, SENSOR_VITALS, SENSOR_VITALS, SENSOR_COORDS)
if(ismob(loc))
var/mob/M = loc
to_chat(M,span_warning("The sensors on the [src] change rapidly!"))
update_wearer_status()
/obj/item/clothing/under/visual_equipped(mob/user, slot)
. = ..()
if(adjusted == ALT_STYLE)
adjust_to_normal()
/* MONKESTATION EDIT
if((supports_variations_flags & CLOTHING_DIGITIGRADE_VARIATION) && ishuman(user))
var/mob/living/carbon/human/wearer = user
if(wearer.dna.species.bodytype & BODYTYPE_DIGITIGRADE)
adjusted = DIGITIGRADE_STYLE
update_appearance()
*/
/obj/item/clothing/under/equipped(mob/living/user, slot)
..()
if((slot & ITEM_SLOT_ICLOTHING) && freshly_laundered)
freshly_laundered = FALSE
user.add_mood_event("fresh_laundry", /datum/mood_event/fresh_laundry)
/obj/item/clothing/under/proc/update_wearer_status()
if(!ishuman(loc))
return
var/mob/living/carbon/human/ooman = loc
ooman.update_suit_sensors()
ooman.med_hud_set_status()
/mob/living/carbon/human/update_suit_sensors()
. = ..()
update_sensor_list()
/mob/living/carbon/human/proc/update_sensor_list()
var/obj/item/clothing/under/uniform = w_uniform
if(!QDELETED(src) && istype(uniform) && uniform.has_sensor > NO_SENSORS && uniform.sensor_mode)
GLOB.suit_sensors_list |= src
else
GLOB.suit_sensors_list -= src
/mob/living/carbon/human/dummy/update_sensor_list()
return
// End suit sensor handling
/// Attach the passed accessory to the clothing item
/obj/item/clothing/under/proc/attach_accessory(obj/item/clothing/accessory/accessory, mob/living/user, attach_message = TRUE)
if(!istype(accessory))
return
if(!accessory.can_attach_accessory(src, user))
return
if(user && !user.temporarilyRemoveItemFromInventory(accessory))
return
if(!accessory.attach(src, user))
return
LAZYADD(attached_accessories, accessory)
accessory.forceMove(src)
// Allow for accessories to react to the acccessory list now
accessory.successful_attach(src)
if(user && attach_message)
balloon_alert(user, "accessory attached")
if(isnull(accessory_overlay))
create_accessory_overlay()
update_appearance()
return TRUE
/// Removes (pops) the topmost accessory from the accessories list and puts it in the user's hands if supplied
/obj/item/clothing/under/proc/pop_accessory(mob/living/user, attach_message = TRUE)
var/obj/item/clothing/accessory/popped_accessory = attached_accessories[1]
remove_accessory(popped_accessory)
if(!user)
return
user.put_in_hands(popped_accessory)
if(attach_message)
popped_accessory.balloon_alert(user, "accessory removed")
/// Removes the passed accesory from our accessories list
/obj/item/clothing/under/proc/remove_accessory(obj/item/clothing/accessory/removed)
if(removed == attached_accessories[1])
accessory_overlay = null
// Remove it from the list before detaching
LAZYREMOVE(attached_accessories, removed)
removed.detach(src)
if(isnull(accessory_overlay) && LAZYLEN(attached_accessories))
create_accessory_overlay()
update_appearance()
/// Handles creating the worn overlay mutable appearance
/// Only the first accessory attached is displayed (currently)
/obj/item/clothing/under/proc/create_accessory_overlay()
var/obj/item/clothing/accessory/prime_accessory = attached_accessories[1]
accessory_overlay = mutable_appearance(prime_accessory.worn_icon, prime_accessory.icon_state)
accessory_overlay.alpha = prime_accessory.alpha
accessory_overlay.color = prime_accessory.color
/// Updates the accessory's worn overlay mutable appearance
/obj/item/clothing/under/proc/update_accessory_overlay()
if(isnull(accessory_overlay))
return
cut_overlay(accessory_overlay)
create_accessory_overlay()
update_appearance() // so we update the suit inventory overlay too
/obj/item/clothing/under/Exited(atom/movable/gone, direction)
. = ..()
// If one of our accessories was moved out, handle it
if(gone in attached_accessories)
remove_accessory(gone)
/// Helper to remove all attachments to the passed location
/obj/item/clothing/under/proc/dump_attachments(atom/drop_to = drop_location())
for(var/obj/item/clothing/accessory/worn_accessory as anything in attached_accessories)
remove_accessory(worn_accessory)
worn_accessory.forceMove(drop_to)
/obj/item/clothing/under/atom_destruction(damage_flag)
dump_attachments()
return ..()
/obj/item/clothing/under/Destroy()
QDEL_LAZYLIST(attached_accessories)
return ..()
/obj/item/clothing/under/examine(mob/user)
. = ..()
if(can_adjust)
. += "Alt-click on [src] to wear it [adjusted == ALT_STYLE ? "normally" : "casually"]."
if(has_sensor == BROKEN_SENSORS)
. += "Its sensors appear to be shorted out. You could repair it with some cabling."
else if(has_sensor > NO_SENSORS)
switch(sensor_mode)
if(SENSOR_OFF)
. += "Its sensors appear to be disabled."
if(SENSOR_LIVING)
. += "Its binary life sensors appear to be enabled."
if(SENSOR_VITALS)
. += "Its vital tracker appears to be enabled."
if(SENSOR_COORDS)
. += "Its vital tracker and tracking beacon appear to be enabled."
if(LAZYLEN(attached_accessories))
var/list/accessories = list_accessories_with_icon(user)
. += "It has [english_list(accessories)] attached."
. += "Alt-Right-Click to remove [attached_accessories[1]]."
/// Helper to list out all accessories with an icon besides it, for use in examine
/obj/item/clothing/under/proc/list_accessories_with_icon(mob/user)
var/list/all_accessories = list()
for(var/obj/item/clothing/accessory/attached as anything in attached_accessories)
all_accessories += attached.get_examine_string(user)
return all_accessories
/obj/item/clothing/under/verb/toggle()
set name = "Adjust Suit Sensors"
set category = "Object"
set src in usr
var/mob/user_mob = usr
if(!can_toggle_sensors(user_mob))
return
var/list/modes = list("Off", "Binary vitals", "Exact vitals", "Tracking beacon")
var/switchMode = tgui_input_list(user_mob, "Select a sensor mode", "Suit Sensors", modes, modes[sensor_mode + 1])
if(isnull(switchMode))
return
if(!can_toggle_sensors(user_mob))
return
sensor_mode = modes.Find(switchMode) - 1
if (loc == user_mob)
switch(sensor_mode)
if(SENSOR_OFF)
to_chat(user_mob, span_notice("You disable your suit's remote sensing equipment."))
if(SENSOR_LIVING)
to_chat(user_mob, span_notice("Your suit will now only report whether you are alive or dead."))
if(SENSOR_VITALS)
to_chat(user_mob, span_notice("Your suit will now only report your exact vital lifesigns."))
if(SENSOR_COORDS)
to_chat(user_mob, span_notice("Your suit will now report your exact vital lifesigns as well as your coordinate position."))
update_wearer_status()
/obj/item/clothing/under/item_ctrl_click(mob/user)
if(!can_toggle_sensors(user))
return CLICK_ACTION_BLOCKING
sensor_mode = SENSOR_COORDS
balloon_alert(user, "set to tracking")
update_wearer_status()
return CLICK_ACTION_SUCCESS
/// Checks if the toggler is allowed to toggle suit sensors currently
/obj/item/clothing/under/proc/can_toggle_sensors(mob/toggler)
if(!can_use(toggler) || toggler.stat == DEAD) //make sure they didn't hold the window open.
return FALSE
if(get_dist(toggler, src) > 1)
balloon_alert(toggler, "too far!")
return FALSE
switch(has_sensor)
if(LOCKED_SENSORS)
balloon_alert(toggler, "sensor controls locked!")
return FALSE
if(BROKEN_SENSORS)
balloon_alert(toggler, "sensors shorted!")
return FALSE
if(NO_SENSORS)
balloon_alert(toggler, "no sensors to ajdust!")
return FALSE
return TRUE
/obj/item/clothing/under/click_alt(mob/living/user)
if(!can_adjust)
balloon_alert(user, "can't be adjusted!")
return CLICK_ACTION_BLOCKING
if(!can_use(user))
return NONE
rolldown()
return CLICK_ACTION_SUCCESS
/obj/item/clothing/under/click_alt_secondary(mob/user)
. = ..()
if(.)
return
if(!LAZYLEN(attached_accessories))
balloon_alert(user, "no accessories to remove!")
return
if(!user.can_perform_action(src, NEED_DEXTERITY))
return
pop_accessory(user)
/obj/item/clothing/under/verb/jumpsuit_adjust()
set name = "Adjust Jumpsuit Style"
set category = null
set src in usr
if(!can_adjust)
balloon_alert(usr, "can't be adjusted!")
return
if(!can_use(usr))
return
rolldown()
/obj/item/clothing/under/proc/rolldown()
if(toggle_jumpsuit_adjust())
to_chat(usr, span_notice("You adjust the suit to wear it more casually."))
else
to_chat(usr, span_notice("You adjust the suit back to normal."))
update_appearance()
/// Helper to toggle the jumpsuit style, if possible
/// Returns the new state
/obj/item/clothing/under/proc/toggle_jumpsuit_adjust()
switch(adjusted)
/* MONKESTATION EDIT
if(DIGITIGRADE_STYLE)
return
*/
if(NORMAL_STYLE)
adjust_to_alt()
if(ALT_STYLE)
adjust_to_normal()
SEND_SIGNAL(src, COMSIG_CLOTHING_UNDER_ADJUSTED)
return adjusted
/// Helper to reset to normal jumpsuit state
/obj/item/clothing/under/proc/adjust_to_normal()
adjusted = NORMAL_STYLE
female_sprite_flags = initial(female_sprite_flags)
if(!alt_covers_chest)
body_parts_covered |= CHEST
body_parts_covered |= ARMS
if(LAZYLEN(damage_by_parts))
// ugly check to make sure we don't reenable protection on a disabled part
for(var/zone in list(BODY_ZONE_CHEST, BODY_ZONE_L_ARM, BODY_ZONE_R_ARM))
if(damage_by_parts[zone] > limb_integrity)
body_parts_covered &= body_zone2cover_flags(zone)
/// Helper to adjust to alt jumpsuit state
/obj/item/clothing/under/proc/adjust_to_alt()
adjusted = ALT_STYLE
if(alt_covers_chest) //For snowflake suits that do NOT expose the chest. //MONKESTATION EDIT
return
if(!(female_sprite_flags & FEMALE_UNIFORM_TOP_ONLY))
female_sprite_flags = NO_FEMALE_UNIFORM
if(!alt_covers_chest) // for the special snowflake suits that expose the chest when adjusted (and also the arms, realistically)
body_parts_covered &= ~CHEST
body_parts_covered &= ~ARMS
/obj/item/clothing/under/can_use(mob/user)
if(ismob(user) && !user.can_perform_action(src, NEED_DEXTERITY|NEED_HANDS|ALLOW_RESTING))
return FALSE
return ..()
/obj/item/clothing/under/rank
dying_key = DYE_REGISTRY_UNDER
| 412 | 0.938637 | 1 | 0.938637 | game-dev | MEDIA | 0.932452 | game-dev | 0.843218 | 1 | 0.843218 |
RattlingSnow353/Familiar | 1,870 | Items/Consumable Types/Memento/Naked Singularity.lua | local naked_singularity = {
object_type = "Consumable",
key = 'naked_singularity',
set = 'Familiar_Spectrals',
config = { },
atlas = 'Consumables',
soul_set = 'Familiar_Spectrals',
soul_rate = 0.003,
can_repeat_soul = true,
pos = { x = 9, y = 3 },
order = 18,
loc_vars = function(self, info_queue, card)
return { vars = { } }
end,
can_use = function(self, card, area, copier)
return true
end,
use = function(self, card)
update_hand_text({sound = 'button', volume = 0.7, pitch = 0.8, delay = 0.3}, {handname=localize('k_all_hands'),chips = '...', mult = '...', level=''})
G.E_MANAGER:add_event(Event({trigger = 'after', delay = 0.2, func = function()
play_sound('tarot1')
card:juice_up(0.8, 0.5)
G.TAROT_INTERRUPT_PULSE = true
return true end }))
update_hand_text({delay = 0}, {mult = '*', StatusText = true})
G.E_MANAGER:add_event(Event({trigger = 'after', delay = 0.9, func = function()
play_sound('tarot1')
card:juice_up(0.8, 0.5)
return true end }))
update_hand_text({delay = 0}, {chips = '*', StatusText = true})
G.E_MANAGER:add_event(Event({trigger = 'after', delay = 0.9, func = function()
play_sound('tarot1')
card:juice_up(0.8, 0.5)
G.TAROT_INTERRUPT_PULSE = nil
return true end }))
update_hand_text({sound = 'button', volume = 0.7, pitch = 0.9, delay = 0}, {level='+1+i'})
delay(1.3)
for k, v in pairs(i_hands) do
mult_level_up_hand(card, k, true, 1)
end
update_hand_text({sound = 'button', volume = 0.7, pitch = 1.1, delay = 0}, {mult = 0, chips = 0, handname = '', level = ''})
end,
}
return {name = "Memento Cards", items = {naked_singularity}} | 412 | 0.751158 | 1 | 0.751158 | game-dev | MEDIA | 0.67162 | game-dev | 0.969111 | 1 | 0.969111 |
juce-framework/JUCE | 29,129 | modules/juce_box2d/box2d/Dynamics/b2World.cpp | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "b2World.h"
#include "b2Body.h"
#include "b2Fixture.h"
#include "b2Island.h"
#include "Joints/b2PulleyJoint.h"
#include "Contacts/b2Contact.h"
#include "Contacts/b2ContactSolver.h"
#include "../Collision/b2Collision.h"
#include "../Collision/b2BroadPhase.h"
#include "../Collision/Shapes/b2CircleShape.h"
#include "../Collision/Shapes/b2EdgeShape.h"
#include "../Collision/Shapes/b2ChainShape.h"
#include "../Collision/Shapes/b2PolygonShape.h"
#include "../Collision/b2TimeOfImpact.h"
#include "../Common/b2Draw.h"
#include "../Common/b2Timer.h"
#include <new>
b2World::b2World(const b2Vec2& gravity)
{
m_destructionListener = NULL;
m_debugDraw = NULL;
m_bodyList = NULL;
m_jointList = NULL;
m_bodyCount = 0;
m_jointCount = 0;
m_warmStarting = true;
m_continuousPhysics = true;
m_subStepping = false;
m_stepComplete = true;
m_allowSleep = true;
m_gravity = gravity;
m_flags = e_clearForces;
m_inv_dt0 = 0.0f;
m_contactManager.m_allocator = &m_blockAllocator;
memset(&m_profile, 0, sizeof(b2Profile));
}
b2World::~b2World()
{
// Some shapes allocate using b2Alloc.
b2Body* b = m_bodyList;
while (b)
{
b2Body* bNext = b->m_next;
b2Fixture* f = b->m_fixtureList;
while (f)
{
b2Fixture* fNext = f->m_next;
f->m_proxyCount = 0;
f->Destroy(&m_blockAllocator);
f = fNext;
}
b = bNext;
}
}
void b2World::SetDestructionListener(b2DestructionListener* listener)
{
m_destructionListener = listener;
}
void b2World::SetContactFilter(b2ContactFilter* filter)
{
m_contactManager.m_contactFilter = filter;
}
void b2World::SetContactListener(b2ContactListener* listener)
{
m_contactManager.m_contactListener = listener;
}
void b2World::SetDebugDraw(b2Draw* debugDraw)
{
m_debugDraw = debugDraw;
}
b2Body* b2World::CreateBody(const b2BodyDef* def)
{
b2Assert(IsLocked() == false);
if (IsLocked())
{
return NULL;
}
void* mem = m_blockAllocator.Allocate(sizeof(b2Body));
b2Body* b = new (mem) b2Body(def, this);
// Add to world doubly linked list.
b->m_prev = NULL;
b->m_next = m_bodyList;
if (m_bodyList)
{
m_bodyList->m_prev = b;
}
m_bodyList = b;
++m_bodyCount;
return b;
}
void b2World::DestroyBody(b2Body* b)
{
b2Assert(m_bodyCount > 0);
b2Assert(IsLocked() == false);
if (IsLocked())
{
return;
}
// Delete the attached joints.
b2JointEdge* je = b->m_jointList;
while (je)
{
b2JointEdge* je0 = je;
je = je->next;
if (m_destructionListener)
{
m_destructionListener->SayGoodbye(je0->joint);
}
DestroyJoint(je0->joint);
b->m_jointList = je;
}
b->m_jointList = NULL;
// Delete the attached contacts.
b2ContactEdge* ce = b->m_contactList;
while (ce)
{
b2ContactEdge* ce0 = ce;
ce = ce->next;
m_contactManager.Destroy(ce0->contact);
}
b->m_contactList = NULL;
// Delete the attached fixtures. This destroys broad-phase proxies.
b2Fixture* f = b->m_fixtureList;
while (f)
{
b2Fixture* f0 = f;
f = f->m_next;
if (m_destructionListener)
{
m_destructionListener->SayGoodbye(f0);
}
f0->DestroyProxies(&m_contactManager.m_broadPhase);
f0->Destroy(&m_blockAllocator);
f0->~b2Fixture();
m_blockAllocator.Free(f0, sizeof(b2Fixture));
b->m_fixtureList = f;
b->m_fixtureCount -= 1;
}
b->m_fixtureList = NULL;
b->m_fixtureCount = 0;
// Remove world body list.
if (b->m_prev)
{
b->m_prev->m_next = b->m_next;
}
if (b->m_next)
{
b->m_next->m_prev = b->m_prev;
}
if (b == m_bodyList)
{
m_bodyList = b->m_next;
}
--m_bodyCount;
b->~b2Body();
m_blockAllocator.Free(b, sizeof(b2Body));
}
b2Joint* b2World::CreateJoint(const b2JointDef* def)
{
b2Assert(IsLocked() == false);
if (IsLocked())
{
return NULL;
}
b2Joint* j = b2Joint::Create(def, &m_blockAllocator);
// Connect to the world list.
j->m_prev = NULL;
j->m_next = m_jointList;
if (m_jointList)
{
m_jointList->m_prev = j;
}
m_jointList = j;
++m_jointCount;
// Connect to the bodies' doubly linked lists.
j->m_edgeA.joint = j;
j->m_edgeA.other = j->m_bodyB;
j->m_edgeA.prev = NULL;
j->m_edgeA.next = j->m_bodyA->m_jointList;
if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA;
j->m_bodyA->m_jointList = &j->m_edgeA;
j->m_edgeB.joint = j;
j->m_edgeB.other = j->m_bodyA;
j->m_edgeB.prev = NULL;
j->m_edgeB.next = j->m_bodyB->m_jointList;
if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB;
j->m_bodyB->m_jointList = &j->m_edgeB;
b2Body* bodyA = def->bodyA;
b2Body* bodyB = def->bodyB;
// If the joint prevents collisions, then flag any contacts for filtering.
if (def->collideConnected == false)
{
b2ContactEdge* edge = bodyB->GetContactList();
while (edge)
{
if (edge->other == bodyA)
{
// Flag the contact for filtering at the next time step (where either
// body is awake).
edge->contact->FlagForFiltering();
}
edge = edge->next;
}
}
// Note: creating a joint doesn't wake the bodies.
return j;
}
void b2World::DestroyJoint(b2Joint* j)
{
b2Assert(IsLocked() == false);
if (IsLocked())
{
return;
}
bool collideConnected = j->m_collideConnected;
// Remove from the doubly linked list.
if (j->m_prev)
{
j->m_prev->m_next = j->m_next;
}
if (j->m_next)
{
j->m_next->m_prev = j->m_prev;
}
if (j == m_jointList)
{
m_jointList = j->m_next;
}
// Disconnect from island graph.
b2Body* bodyA = j->m_bodyA;
b2Body* bodyB = j->m_bodyB;
// Wake up connected bodies.
bodyA->SetAwake(true);
bodyB->SetAwake(true);
// Remove from body 1.
if (j->m_edgeA.prev)
{
j->m_edgeA.prev->next = j->m_edgeA.next;
}
if (j->m_edgeA.next)
{
j->m_edgeA.next->prev = j->m_edgeA.prev;
}
if (&j->m_edgeA == bodyA->m_jointList)
{
bodyA->m_jointList = j->m_edgeA.next;
}
j->m_edgeA.prev = NULL;
j->m_edgeA.next = NULL;
// Remove from body 2
if (j->m_edgeB.prev)
{
j->m_edgeB.prev->next = j->m_edgeB.next;
}
if (j->m_edgeB.next)
{
j->m_edgeB.next->prev = j->m_edgeB.prev;
}
if (&j->m_edgeB == bodyB->m_jointList)
{
bodyB->m_jointList = j->m_edgeB.next;
}
j->m_edgeB.prev = NULL;
j->m_edgeB.next = NULL;
b2Joint::Destroy(j, &m_blockAllocator);
b2Assert(m_jointCount > 0);
--m_jointCount;
// If the joint prevents collisions, then flag any contacts for filtering.
if (collideConnected == false)
{
b2ContactEdge* edge = bodyB->GetContactList();
while (edge)
{
if (edge->other == bodyA)
{
// Flag the contact for filtering at the next time step (where either
// body is awake).
edge->contact->FlagForFiltering();
}
edge = edge->next;
}
}
}
//
void b2World::SetAllowSleeping(bool flag)
{
if (flag == m_allowSleep)
{
return;
}
m_allowSleep = flag;
if (m_allowSleep == false)
{
for (b2Body* b = m_bodyList; b; b = b->m_next)
{
b->SetAwake(true);
}
}
}
// Find islands, integrate and solve constraints, solve position constraints
void b2World::Solve(const b2TimeStep& step)
{
m_profile.solveInit = 0.0f;
m_profile.solveVelocity = 0.0f;
m_profile.solvePosition = 0.0f;
// Size the island for the worst case.
b2Island island(m_bodyCount,
m_contactManager.m_contactCount,
m_jointCount,
&m_stackAllocator,
m_contactManager.m_contactListener);
// Clear all the island flags.
for (b2Body* b = m_bodyList; b; b = b->m_next)
{
b->m_flags &= ~b2Body::e_islandFlag;
}
for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next)
{
c->m_flags &= ~b2Contact::e_islandFlag;
}
for (b2Joint* j = m_jointList; j; j = j->m_next)
{
j->m_islandFlag = false;
}
// Build and simulate all awake islands.
int32 stackSize = m_bodyCount;
b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*));
for (b2Body* seed = m_bodyList; seed; seed = seed->m_next)
{
if (seed->m_flags & b2Body::e_islandFlag)
{
continue;
}
if (seed->IsAwake() == false || seed->IsActive() == false)
{
continue;
}
// The seed can be dynamic or kinematic.
if (seed->GetType() == b2_staticBody)
{
continue;
}
// Reset island and stack.
island.Clear();
int32 stackCount = 0;
stack[stackCount++] = seed;
seed->m_flags |= b2Body::e_islandFlag;
// Perform a depth first search (DFS) on the constraint graph.
while (stackCount > 0)
{
// Grab the next body off the stack and add it to the island.
b2Body* b = stack[--stackCount];
b2Assert(b->IsActive() == true);
island.Add(b);
// Make sure the body is awake.
b->SetAwake(true);
// To keep islands as small as possible, we don't
// propagate islands across static bodies.
if (b->GetType() == b2_staticBody)
{
continue;
}
// Search all contacts connected to this body.
for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next)
{
b2Contact* contact = ce->contact;
// Has this contact already been added to an island?
if (contact->m_flags & b2Contact::e_islandFlag)
{
continue;
}
// Is this contact solid and touching?
if (contact->IsEnabled() == false ||
contact->IsTouching() == false)
{
continue;
}
// Skip sensors.
bool sensorA = contact->m_fixtureA->m_isSensor;
bool sensorB = contact->m_fixtureB->m_isSensor;
if (sensorA || sensorB)
{
continue;
}
island.Add(contact);
contact->m_flags |= b2Contact::e_islandFlag;
b2Body* other = ce->other;
// Was the other body already added to this island?
if (other->m_flags & b2Body::e_islandFlag)
{
continue;
}
b2Assert(stackCount < stackSize);
stack[stackCount++] = other;
other->m_flags |= b2Body::e_islandFlag;
}
// Search all joints connect to this body.
for (b2JointEdge* je = b->m_jointList; je; je = je->next)
{
if (je->joint->m_islandFlag == true)
{
continue;
}
b2Body* other = je->other;
// Don't simulate joints connected to inactive bodies.
if (other->IsActive() == false)
{
continue;
}
island.Add(je->joint);
je->joint->m_islandFlag = true;
if (other->m_flags & b2Body::e_islandFlag)
{
continue;
}
b2Assert(stackCount < stackSize);
stack[stackCount++] = other;
other->m_flags |= b2Body::e_islandFlag;
}
}
b2Profile profile;
island.Solve(&profile, step, m_gravity, m_allowSleep);
m_profile.solveInit += profile.solveInit;
m_profile.solveVelocity += profile.solveVelocity;
m_profile.solvePosition += profile.solvePosition;
// Post solve cleanup.
for (int32 i = 0; i < island.m_bodyCount; ++i)
{
// Allow static bodies to participate in other islands.
b2Body* b = island.m_bodies[i];
if (b->GetType() == b2_staticBody)
{
b->m_flags &= ~b2Body::e_islandFlag;
}
}
}
m_stackAllocator.Free(stack);
{
b2Timer timer;
// Synchronize fixtures, check for out of range bodies.
for (b2Body* b = m_bodyList; b; b = b->GetNext())
{
// If a body was not in an island then it did not move.
if ((b->m_flags & b2Body::e_islandFlag) == 0)
{
continue;
}
if (b->GetType() == b2_staticBody)
{
continue;
}
// Update fixtures (for broad-phase).
b->SynchronizeFixtures();
}
// Look for new contacts.
m_contactManager.FindNewContacts();
m_profile.broadphase = timer.GetMilliseconds();
}
}
// Find TOI contacts and solve them.
void b2World::SolveTOI(const b2TimeStep& step)
{
b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener);
if (m_stepComplete)
{
for (b2Body* b = m_bodyList; b; b = b->m_next)
{
b->m_flags &= ~b2Body::e_islandFlag;
b->m_sweep.alpha0 = 0.0f;
}
for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next)
{
// Invalidate TOI
c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag);
c->m_toiCount = 0;
c->m_toi = 1.0f;
}
}
// Find TOI events and solve them.
for (;;)
{
// Find the first TOI.
b2Contact* minContact = NULL;
float32 minAlpha = 1.0f;
for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next)
{
// Is this contact disabled?
if (c->IsEnabled() == false)
{
continue;
}
// Prevent excessive sub-stepping.
if (c->m_toiCount > b2_maxSubSteps)
{
continue;
}
float32 alpha = 1.0f;
if (c->m_flags & b2Contact::e_toiFlag)
{
// This contact has a valid cached TOI.
alpha = c->m_toi;
}
else
{
b2Fixture* fA = c->GetFixtureA();
b2Fixture* fB = c->GetFixtureB();
// Is there a sensor?
if (fA->IsSensor() || fB->IsSensor())
{
continue;
}
b2Body* bA = fA->GetBody();
b2Body* bB = fB->GetBody();
b2BodyType typeA = bA->m_type;
b2BodyType typeB = bB->m_type;
b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody);
bool activeA = bA->IsAwake() && typeA != b2_staticBody;
bool activeB = bB->IsAwake() && typeB != b2_staticBody;
// Is at least one body active (awake and dynamic or kinematic)?
if (activeA == false && activeB == false)
{
continue;
}
bool collideA = bA->IsBullet() || typeA != b2_dynamicBody;
bool collideB = bB->IsBullet() || typeB != b2_dynamicBody;
// Are these two non-bullet dynamic bodies?
if (collideA == false && collideB == false)
{
continue;
}
// Compute the TOI for this contact.
// Put the sweeps onto the same time interval.
float32 alpha0 = bA->m_sweep.alpha0;
if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0)
{
alpha0 = bB->m_sweep.alpha0;
bA->m_sweep.Advance(alpha0);
}
else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0)
{
alpha0 = bA->m_sweep.alpha0;
bB->m_sweep.Advance(alpha0);
}
b2Assert(alpha0 < 1.0f);
int32 indexA = c->GetChildIndexA();
int32 indexB = c->GetChildIndexB();
// Compute the time of impact in interval [0, minTOI]
b2TOIInput input;
input.proxyA.Set(fA->GetShape(), indexA);
input.proxyB.Set(fB->GetShape(), indexB);
input.sweepA = bA->m_sweep;
input.sweepB = bB->m_sweep;
input.tMax = 1.0f;
b2TOIOutput output;
b2TimeOfImpact(&output, &input);
// Beta is the fraction of the remaining portion of the .
float32 beta = output.t;
if (output.state == b2TOIOutput::e_touching)
{
alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f);
}
else
{
alpha = 1.0f;
}
c->m_toi = alpha;
c->m_flags |= b2Contact::e_toiFlag;
}
if (alpha < minAlpha)
{
// This is the minimum TOI found so far.
minContact = c;
minAlpha = alpha;
}
}
if (minContact == NULL || 1.0f - 10.0f * b2_epsilon < minAlpha)
{
// No more TOI events. Done!
m_stepComplete = true;
break;
}
// Advance the bodies to the TOI.
b2Fixture* fA = minContact->GetFixtureA();
b2Fixture* fB = minContact->GetFixtureB();
b2Body* bA = fA->GetBody();
b2Body* bB = fB->GetBody();
b2Sweep backup1 = bA->m_sweep;
b2Sweep backup2 = bB->m_sweep;
bA->Advance(minAlpha);
bB->Advance(minAlpha);
// The TOI contact likely has some new contact points.
minContact->Update(m_contactManager.m_contactListener);
minContact->m_flags &= ~b2Contact::e_toiFlag;
++minContact->m_toiCount;
// Is the contact solid?
if (minContact->IsEnabled() == false || minContact->IsTouching() == false)
{
// Restore the sweeps.
minContact->SetEnabled(false);
bA->m_sweep = backup1;
bB->m_sweep = backup2;
bA->SynchronizeTransform();
bB->SynchronizeTransform();
continue;
}
bA->SetAwake(true);
bB->SetAwake(true);
// Build the island
island.Clear();
island.Add(bA);
island.Add(bB);
island.Add(minContact);
bA->m_flags |= b2Body::e_islandFlag;
bB->m_flags |= b2Body::e_islandFlag;
minContact->m_flags |= b2Contact::e_islandFlag;
// Get contacts on bodyA and bodyB.
b2Body* bodies[2] = {bA, bB};
for (int32 i = 0; i < 2; ++i)
{
b2Body* body = bodies[i];
if (body->m_type == b2_dynamicBody)
{
for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next)
{
if (island.m_bodyCount == island.m_bodyCapacity)
{
break;
}
if (island.m_contactCount == island.m_contactCapacity)
{
break;
}
b2Contact* contact = ce->contact;
// Has this contact already been added to the island?
if (contact->m_flags & b2Contact::e_islandFlag)
{
continue;
}
// Only add static, kinematic, or bullet bodies.
b2Body* other = ce->other;
if (other->m_type == b2_dynamicBody &&
body->IsBullet() == false && other->IsBullet() == false)
{
continue;
}
// Skip sensors.
bool sensorA = contact->m_fixtureA->m_isSensor;
bool sensorB = contact->m_fixtureB->m_isSensor;
if (sensorA || sensorB)
{
continue;
}
// Tentatively advance the body to the TOI.
b2Sweep backup = other->m_sweep;
if ((other->m_flags & b2Body::e_islandFlag) == 0)
{
other->Advance(minAlpha);
}
// Update the contact points
contact->Update(m_contactManager.m_contactListener);
// Was the contact disabled by the user?
if (contact->IsEnabled() == false)
{
other->m_sweep = backup;
other->SynchronizeTransform();
continue;
}
// Are there contact points?
if (contact->IsTouching() == false)
{
other->m_sweep = backup;
other->SynchronizeTransform();
continue;
}
// Add the contact to the island
contact->m_flags |= b2Contact::e_islandFlag;
island.Add(contact);
// Has the other body already been added to the island?
if (other->m_flags & b2Body::e_islandFlag)
{
continue;
}
// Add the other body to the island.
other->m_flags |= b2Body::e_islandFlag;
if (other->m_type != b2_staticBody)
{
other->SetAwake(true);
}
island.Add(other);
}
}
}
b2TimeStep subStep;
subStep.dt = (1.0f - minAlpha) * step.dt;
subStep.inv_dt = 1.0f / subStep.dt;
subStep.dtRatio = 1.0f;
subStep.positionIterations = 20;
subStep.velocityIterations = step.velocityIterations;
subStep.warmStarting = false;
island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex);
// Reset island flags and synchronize broad-phase proxies.
for (int32 i = 0; i < island.m_bodyCount; ++i)
{
b2Body* body = island.m_bodies[i];
body->m_flags &= ~b2Body::e_islandFlag;
if (body->m_type != b2_dynamicBody)
{
continue;
}
body->SynchronizeFixtures();
// Invalidate all contact TOIs on this displaced body.
for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next)
{
ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag);
}
}
// Commit fixture proxy movements to the broad-phase so that new contacts are created.
// Also, some contacts can be destroyed.
m_contactManager.FindNewContacts();
if (m_subStepping)
{
m_stepComplete = false;
break;
}
}
}
void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations)
{
b2Timer stepTimer;
// If new fixtures were added, we need to find the new contacts.
if (m_flags & e_newFixture)
{
m_contactManager.FindNewContacts();
m_flags &= ~e_newFixture;
}
m_flags |= e_locked;
b2TimeStep step;
step.dt = dt;
step.velocityIterations = velocityIterations;
step.positionIterations = positionIterations;
if (dt > 0.0f)
{
step.inv_dt = 1.0f / dt;
}
else
{
step.inv_dt = 0.0f;
}
step.dtRatio = m_inv_dt0 * dt;
step.warmStarting = m_warmStarting;
// Update contacts. This is where some contacts are destroyed.
{
b2Timer timer;
m_contactManager.Collide();
m_profile.collide = timer.GetMilliseconds();
}
// Integrate velocities, solve velocity constraints, and integrate positions.
if (m_stepComplete && step.dt > 0.0f)
{
b2Timer timer;
Solve(step);
m_profile.solve = timer.GetMilliseconds();
}
// Handle TOI events.
if (m_continuousPhysics && step.dt > 0.0f)
{
b2Timer timer;
SolveTOI(step);
m_profile.solveTOI = timer.GetMilliseconds();
}
if (step.dt > 0.0f)
{
m_inv_dt0 = step.inv_dt;
}
if (m_flags & e_clearForces)
{
ClearForces();
}
m_flags &= ~e_locked;
m_profile.step = stepTimer.GetMilliseconds();
}
void b2World::ClearForces()
{
for (b2Body* body = m_bodyList; body; body = body->GetNext())
{
body->m_force.SetZero();
body->m_torque = 0.0f;
}
}
struct b2WorldQueryWrapper
{
bool QueryCallback(int32 proxyId)
{
b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId);
return callback->ReportFixture(proxy->fixture);
}
const b2BroadPhase* broadPhase;
b2QueryCallback* callback;
};
void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const
{
b2WorldQueryWrapper wrapper;
wrapper.broadPhase = &m_contactManager.m_broadPhase;
wrapper.callback = callback;
m_contactManager.m_broadPhase.Query(&wrapper, aabb);
}
struct b2WorldRayCastWrapper
{
float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId)
{
void* userData = broadPhase->GetUserData(proxyId);
b2FixtureProxy* proxy = (b2FixtureProxy*)userData;
b2Fixture* fixture = proxy->fixture;
int32 index = proxy->childIndex;
b2RayCastOutput output;
bool hit = fixture->RayCast(&output, input, index);
if (hit)
{
float32 fraction = output.fraction;
b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2;
return callback->ReportFixture(fixture, point, output.normal, fraction);
}
return input.maxFraction;
}
const b2BroadPhase* broadPhase;
b2RayCastCallback* callback;
};
void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const
{
b2WorldRayCastWrapper wrapper;
wrapper.broadPhase = &m_contactManager.m_broadPhase;
wrapper.callback = callback;
b2RayCastInput input;
input.maxFraction = 1.0f;
input.p1 = point1;
input.p2 = point2;
m_contactManager.m_broadPhase.RayCast(&wrapper, input);
}
void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color)
{
switch (fixture->GetType())
{
case b2Shape::e_circle:
{
b2CircleShape* circle = (b2CircleShape*)fixture->GetShape();
b2Vec2 center = b2Mul(xf, circle->m_p);
float32 radius = circle->m_radius;
b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f));
m_debugDraw->DrawSolidCircle(center, radius, axis, color);
}
break;
case b2Shape::e_edge:
{
b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape();
b2Vec2 v1 = b2Mul(xf, edge->m_vertex1);
b2Vec2 v2 = b2Mul(xf, edge->m_vertex2);
m_debugDraw->DrawSegment(v1, v2, color);
}
break;
case b2Shape::e_chain:
{
b2ChainShape* chain = (b2ChainShape*)fixture->GetShape();
int32 count = chain->m_count;
const b2Vec2* vertices = chain->m_vertices;
b2Vec2 v1 = b2Mul(xf, vertices[0]);
for (int32 i = 1; i < count; ++i)
{
b2Vec2 v2 = b2Mul(xf, vertices[i]);
m_debugDraw->DrawSegment(v1, v2, color);
m_debugDraw->DrawCircle(v1, 0.05f, color);
v1 = v2;
}
}
break;
case b2Shape::e_polygon:
{
b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape();
int32 vertexCount = poly->m_vertexCount;
b2Assert(vertexCount <= b2_maxPolygonVertices);
b2Vec2 vertices[b2_maxPolygonVertices];
for (int32 i = 0; i < vertexCount; ++i)
{
vertices[i] = b2Mul(xf, poly->m_vertices[i]);
}
m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color);
}
break;
default:
break;
}
}
void b2World::DrawJoint(b2Joint* joint)
{
b2Body* bodyA = joint->GetBodyA();
b2Body* bodyB = joint->GetBodyB();
const b2Transform& xf1 = bodyA->GetTransform();
const b2Transform& xf2 = bodyB->GetTransform();
b2Vec2 x1 = xf1.p;
b2Vec2 x2 = xf2.p;
b2Vec2 p1 = joint->GetAnchorA();
b2Vec2 p2 = joint->GetAnchorB();
b2Color color(0.5f, 0.8f, 0.8f);
switch (joint->GetType())
{
case e_distanceJoint:
m_debugDraw->DrawSegment(p1, p2, color);
break;
case e_pulleyJoint:
{
b2PulleyJoint* pulley = (b2PulleyJoint*)joint;
b2Vec2 s1 = pulley->GetGroundAnchorA();
b2Vec2 s2 = pulley->GetGroundAnchorB();
m_debugDraw->DrawSegment(s1, p1, color);
m_debugDraw->DrawSegment(s2, p2, color);
m_debugDraw->DrawSegment(s1, s2, color);
}
break;
case e_mouseJoint:
// don't draw this
break;
default:
m_debugDraw->DrawSegment(x1, p1, color);
m_debugDraw->DrawSegment(p1, p2, color);
m_debugDraw->DrawSegment(x2, p2, color);
}
}
void b2World::DrawDebugData()
{
if (m_debugDraw == NULL)
{
return;
}
uint32 flags = m_debugDraw->GetFlags();
if (flags & b2Draw::e_shapeBit)
{
for (b2Body* b = m_bodyList; b; b = b->GetNext())
{
const b2Transform& xf = b->GetTransform();
for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext())
{
if (b->IsActive() == false)
{
DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f));
}
else if (b->GetType() == b2_staticBody)
{
DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f));
}
else if (b->GetType() == b2_kinematicBody)
{
DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f));
}
else if (b->IsAwake() == false)
{
DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f));
}
else
{
DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f));
}
}
}
}
if (flags & b2Draw::e_jointBit)
{
for (b2Joint* j = m_jointList; j; j = j->GetNext())
{
DrawJoint(j);
}
}
if (flags & b2Draw::e_pairBit)
{
b2Color color(0.3f, 0.9f, 0.9f);
for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext())
{
//b2Fixture* fixtureA = c->GetFixtureA();
//b2Fixture* fixtureB = c->GetFixtureB();
//b2Vec2 cA = fixtureA->GetAABB().GetCenter();
//b2Vec2 cB = fixtureB->GetAABB().GetCenter();
//m_debugDraw->DrawSegment(cA, cB, color);
}
}
if (flags & b2Draw::e_aabbBit)
{
b2Color color(0.9f, 0.3f, 0.9f);
b2BroadPhase* bp = &m_contactManager.m_broadPhase;
for (b2Body* b = m_bodyList; b; b = b->GetNext())
{
if (b->IsActive() == false)
{
continue;
}
for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext())
{
for (int32 i = 0; i < f->m_proxyCount; ++i)
{
b2FixtureProxy* proxy = f->m_proxies + i;
b2AABB aabb = bp->GetFatAABB(proxy->proxyId);
b2Vec2 vs[4];
vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y);
vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y);
vs[2].Set(aabb.upperBound.x, aabb.upperBound.y);
vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y);
m_debugDraw->DrawPolygon(vs, 4, color);
}
}
}
}
if (flags & b2Draw::e_centerOfMassBit)
{
for (b2Body* b = m_bodyList; b; b = b->GetNext())
{
b2Transform xf = b->GetTransform();
xf.p = b->GetWorldCenter();
m_debugDraw->DrawTransform(xf);
}
}
}
int32 b2World::GetProxyCount() const
{
return m_contactManager.m_broadPhase.GetProxyCount();
}
int32 b2World::GetTreeHeight() const
{
return m_contactManager.m_broadPhase.GetTreeHeight();
}
int32 b2World::GetTreeBalance() const
{
return m_contactManager.m_broadPhase.GetTreeBalance();
}
float32 b2World::GetTreeQuality() const
{
return m_contactManager.m_broadPhase.GetTreeQuality();
}
void b2World::Dump()
{
if ((m_flags & e_locked) == e_locked)
{
return;
}
b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y);
b2Log("m_world->SetGravity(g);\n");
b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount);
b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount);
int32 i = 0;
for (b2Body* b = m_bodyList; b; b = b->m_next)
{
b->m_islandIndex = i;
b->Dump();
++i;
}
i = 0;
for (b2Joint* j = m_jointList; j; j = j->m_next)
{
j->m_index = i;
++i;
}
// First pass on joints, skip gear joints.
for (b2Joint* j = m_jointList; j; j = j->m_next)
{
if (j->m_type == e_gearJoint)
{
continue;
}
b2Log("{\n");
j->Dump();
b2Log("}\n");
}
// Second pass on joints, only gear joints.
for (b2Joint* j = m_jointList; j; j = j->m_next)
{
if (j->m_type != e_gearJoint)
{
continue;
}
b2Log("{\n");
j->Dump();
b2Log("}\n");
}
b2Log("b2Free(joints);\n");
b2Log("b2Free(bodies);\n");
b2Log("joints = NULL;\n");
b2Log("bodies = NULL;\n");
}
| 412 | 0.972715 | 1 | 0.972715 | game-dev | MEDIA | 0.863419 | game-dev | 0.988995 | 1 | 0.988995 |
rh-hideout-chinese/pokemon-engine | 13,036 | Plugins/Following Pokemon EX/New Event Type/Following Event.rb | #-------------------------------------------------------------------------------
# Defining a new method for base Essentials followers to show dust animation
#-------------------------------------------------------------------------------
class Game_Follower
def update_move
was_jumping = jumping?
super
show_dust_animation if was_jumping && !jumping?
end
if !method_defined?(:show_dust_animation)
def show_dust_animation
spriteset = $scene.spriteset(map_id)
spriteset&.addUserAnimation(Settings::DUST_ANIMATION_ID, self.x, self.y, true, 1)
end
end
end
#-------------------------------------------------------------------------------
# Defining a new class for Following Pokemon event which has several additions
# to make it more robust as a Following Pokemon
#-------------------------------------------------------------------------------
class Game_FollowingPkmn < Game_Follower
#-----------------------------------------------------------------------------
# Update pattern at a constant rate independent of move speed
#-----------------------------------------------------------------------------
def update_pattern
return if @lock_pattern
if @moved_last_frame && !@moved_this_frame && !@step_anime
@pattern = @original_pattern
@anime_count = 0
return
end
if !@moved_last_frame && @moved_this_frame && !@step_anime
@pattern = (@pattern + 1) % 4 if @walk_anime
@anime_count = 0
return
end
pattern_time = pattern_update_speed / 4 # 4 frames per cycle in a charset
return if @anime_count < pattern_time
# Advance to the next animation frame
@pattern = (@pattern + 1) % 4
@anime_count -= pattern_time
end
#-----------------------------------------------------------------------------
# Don't turn off walk animation when sliding on ice if the following pokemon
# is airborne.
#-----------------------------------------------------------------------------
alias __followingpkmn__walk_anime walk_anime= unless method_defined?(:__followingpkmn__walk_anime)
def walk_anime=(value)
return if $PokemonGlobal.ice_sliding && (!FollowingPkmn.active? || FollowingPkmn.airborne_follower?)
__followingpkmn__walk_anime(value)
end
#-----------------------------------------------------------------------------
# Don't reset walk animation when sliding on ice if the following pokemon is
# airborne.
#-----------------------------------------------------------------------------
alias __followingpkmn__straighten straighten unless method_defined?(:__followingpkmn__straighten)
def straighten
return if $PokemonGlobal.ice_sliding && (!FollowingPkmn.active? || FollowingPkmn.airborne_follower?)
__followingpkmn__straighten
end
#-----------------------------------------------------------------------------
# Don't show dust animation if Following Pokemon isn't active or is airborne
#-----------------------------------------------------------------------------
def show_dust_animation
return if !FollowingPkmn.active? || FollowingPkmn.airborne_follower?
super
end
#-----------------------------------------------------------------------------
# Allow following pokemon to freely walk on water
#-----------------------------------------------------------------------------
def location_passable?(x, y, direction)
this_map = self.map
return false if !this_map || !this_map.valid?(x, y)
return true if @through
passed_tile_checks = false
bit = (1 << ((direction / 2) - 1)) & 0x0f
# Check all events for ones using tiles as graphics, and see if they're passable
this_map.events.each_value do |event|
next if event.tile_id < 0 || event.through || !event.at_coordinate?(x, y)
tile_data = GameData::TerrainTag.try_get(this_map.terrain_tags[event.tile_id])
next if tile_data.ignore_passability
next if tile_data.bridge && $PokemonGlobal.bridge == 0
return false if tile_data.ledge
# Allow Folllowers to surf if they can travel on water
return true if tile_data.can_surf && FollowingPkmn.waterborne_follower?
passage = this_map.passages[event.tile_id] || 0
return false if passage & bit != 0
passed_tile_checks = true if (tile_data.bridge && $PokemonGlobal.bridge > 0) ||
(this_map.priorities[event.tile_id] || -1) == 0
break if passed_tile_checks
end
# Check if tiles at (x, y) allow passage for follower
if !passed_tile_checks
[2, 1, 0].each do |i|
tile_id = this_map.data[x, y, i] || 0
next if tile_id == 0
tile_data = GameData::TerrainTag.try_get(this_map.terrain_tags[tile_id])
next if tile_data.ignore_passability
next if tile_data.bridge && $PokemonGlobal.bridge == 0
return false if tile_data.ledge
# Allow Folllowers to surf if they can travel on water
return true if tile_data.can_surf && FollowingPkmn.waterborne_follower?
passage = this_map.passages[tile_id] || 0
return false if passage & bit != 0
break if tile_data.bridge && $PokemonGlobal.bridge > 0
break if (this_map.priorities[tile_id] || -1) == 0
end
end
# Check all events on the map to see if any are in the way
this_map.events.values.each do |event|
next if !event.at_coordinate?(x, y)
return false if !event.through && event.character_name != ""
end
return true
end
#-----------------------------------------------------------------------------
# Updating the event turning to prevent following Pokemon from changing it's
# direction with the player
#-----------------------------------------------------------------------------
def turn_towards_leader(leader)
return if FollowingPkmn.active? && !FollowingPkmn::ALWAYS_FACE_PLAYER
pbTurnTowardEvent(self, leader)
end
#-----------------------------------------------------------------------------
# Updating the method which controls event position to includes changes to
# work with Marin and Boonzeets side stairs
#-----------------------------------------------------------------------------
def follow_leader(leader, instant = false, leaderIsTrueLeader = true)
return if @move_route_forcing
end_movement
maps_connected = $map_factory.areConnected?(leader.map.map_id, self.map.map_id)
target = nil
# Get the target tile that self wants to move to
if maps_connected
behind_direction = 10 - leader.direction
target = $map_factory.getFacingTile(behind_direction, leader)
if target && $map_factory.getTerrainTag(target[0], target[1], target[2]).ledge
# Get the tile above the ledge (where the leader jumped from)
target = $map_factory.getFacingTileFromPos(target[0], target[1], target[2], behind_direction)
end
target = [leader.map.map_id, leader.x, leader.y] if !target
if GameData::TerrainTag.exists?(:StairLeft)
currentTag = $map_factory.getTerrainTag(self.map.map_id, self.x, self.y)
if currentTag == :StairLeft
target[2] += (target[1] > $game_player.x ? -1 : 1)
elsif currentTag == :StairRight
target[2] += (target[1] < $game_player.x ? -1 : 1)
end
end
# Added
if defined?(on_stair?) && on_stair?
if leader.on_stair?
if leader.stair_start_x != self.stair_start_x
# Leader stepped on other side so start/end swapped, but not for follower yet
target[2] = self.y
elsif leader.stair_start_x < leader.stair_end_x
# Left to Right
if leader.x < leader.stair_start_x && self.x != self.stair_start_x
# Leader stepped off
target[2] = self.y
end
elsif leader.stair_end_x < leader.stair_start_x
# Right to Left
if leader.x > leader.stair_start_x && self.x != self.stair_start_x
# Leader stepped off
target[2] = self.y
end
end
elsif self.on_middle_of_stair?
# Leader is no longer on stair but follower is, so player moved up or down at the start or end of the stair
if leader.y < self.stair_end_y - self.stair_y_height + 1 || leader.y > self.stair_end_y
target[2] = self.y
end
end
end
else
# Map transfer to an unconnected map
target = [leader.map.map_id, leader.x, leader.y]
end
# Move self to the target
if self.map.map_id != target[0]
vector = $map_factory.getRelativePos(target[0], 0, 0, self.map.map_id, @x, @y)
@map = $map_factory.getMap(target[0])
# NOTE: Can't use moveto because vector is outside the boundaries of the
# map, and moveto doesn't allow setting invalid coordinates.
@x = vector[0]
@y = vector[1]
@real_x = @x * Game_Map::REAL_RES_X
@real_y = @y * Game_Map::REAL_RES_Y
end
if instant || !maps_connected
moveto(target[1], target[2])
else
fancy_moveto(target[1], target[2], leader)
end
end
#-----------------------------------------------------------------------------
# Make Follower Appear above player
#-----------------------------------------------------------------------------
def screen_z(height = 0)
ret = super
return ret + 1
end
#-----------------------------------------------------------------------------
end
class FollowerData
#-----------------------------------------------------------------------------
# Shorthand for checking whether the data is for a Following Pokemon event
#-----------------------------------------------------------------------------
def following_pkmn?; return name[/FollowingPkmn/]; end
#-----------------------------------------------------------------------------
# Updating the FollowerData interact method to allow Following Pokemon to
# interact with the player without needing a common event
#-----------------------------------------------------------------------------
alias __followingpkmn__interact interact unless method_defined?(:__followingpkmn__interact)
def interact(*args)
return __followingpkmn__interact(*args) if !following_pkmn?
if !@common_event_id
event = args[0]
$game_map.refresh if $game_map.need_refresh
event.lock
FollowingPkmn.talk
event.unlock
elsif FollowingPkmn.can_talk?
return __followingpkmn__interact(*args)
end
end
#-----------------------------------------------------------------------------
end
class Game_FollowerFactory
#-----------------------------------------------------------------------------
# Define the Following as a different class from Game_Follower ie
# Game_FollowingPkmn
#-----------------------------------------------------------------------------
alias __followingpkmn__create_follower_object create_follower_object unless private_method_defined?(:__followingpkmn__create_follower_object)
def create_follower_object(*args)
return Game_FollowingPkmn.new(args[0]) if args[0].following_pkmn?
return __followingpkmn__create_follower_object(*args)
end
#-----------------------------------------------------------------------------
# Following Pokemon shouldn't be a leader if it is inactive.
#-----------------------------------------------------------------------------
def move_followers
leader = $game_player
$PokemonGlobal.followers.each_with_index do |follower, i|
event = @events[i]
event.follow_leader(leader, false, (i == 0))
follower.x = event.x
follower.y = event.y
follower.current_map_id = event.map.map_id
follower.direction = event.direction
leader = event if !event.is_a?(Game_FollowingPkmn) || FollowingPkmn.active?
end
end
#-----------------------------------------------------------------------------
# Following Pokemon shouldn't be a leader if it is inactive.
#-----------------------------------------------------------------------------
def turn_followers
leader = $game_player
$PokemonGlobal.followers.each_with_index do |follower, i|
event = @events[i]
event.turn_towards_leader(leader)
follower.direction = event.direction
leader = event if !event.is_a?(Game_FollowingPkmn) || FollowingPkmn.active?
end
end
#-----------------------------------------------------------------------------
# Method to remove all Followers except Following Pokemon
#-----------------------------------------------------------------------------
def remove_all_except_following_pkmn
followers = $PokemonGlobal.followers
followers.each_with_index do |follower, i|
next if follower.following_pkmn?
followers[i] = nil
@events[i] = nil
@last_update += 1
end
followers.compact!
@events.compact!
end
#-----------------------------------------------------------------------------
end
| 412 | 0.865283 | 1 | 0.865283 | game-dev | MEDIA | 0.927281 | game-dev | 0.576595 | 1 | 0.576595 |
SonicEraZoR/Portal-Base | 122,361 | sp/src/game/server/hl2/npc_playercompanion.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "npc_playercompanion.h"
#include "combine_mine.h"
#include "fire.h"
#include "func_tank.h"
#include "globalstate.h"
#include "npcevent.h"
#include "props.h"
#include "BasePropDoor.h"
#include "ai_hint.h"
#include "ai_localnavigator.h"
#include "ai_memory.h"
#include "ai_pathfinder.h"
#include "ai_route.h"
#include "ai_senses.h"
#include "ai_squad.h"
#include "ai_squadslot.h"
#include "ai_tacticalservices.h"
#include "ai_interactions.h"
#include "filesystem.h"
#include "collisionutils.h"
#include "grenade_frag.h"
#include <KeyValues.h>
#include "physics_npc_solver.h"
ConVar ai_debug_readiness("ai_debug_readiness", "0" );
ConVar ai_use_readiness("ai_use_readiness", "1" ); // 0 = off, 1 = on, 2 = on for player squad only
ConVar ai_readiness_decay( "ai_readiness_decay", "120" );// How many seconds it takes to relax completely
ConVar ai_new_aiming( "ai_new_aiming", "1" );
#define GetReadinessUse() ai_use_readiness.GetInt()
extern ConVar g_debug_transitions;
#define PLAYERCOMPANION_TRANSITION_SEARCH_DISTANCE (100*12)
int AE_COMPANION_PRODUCE_FLARE;
int AE_COMPANION_LIGHT_FLARE;
int AE_COMPANION_RELEASE_FLARE;
#define MAX_TIME_BETWEEN_BARRELS_EXPLODING 5.0f
#define MAX_TIME_BETWEEN_CONSECUTIVE_PLAYER_KILLS 3.0f
//-----------------------------------------------------------------------------
// An aimtarget becomes invalid if it gets this close
//-----------------------------------------------------------------------------
#define COMPANION_AIMTARGET_NEAREST 24.0f
#define COMPANION_AIMTARGET_NEAREST_SQR 576.0f
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
BEGIN_DATADESC( CNPC_PlayerCompanion )
DEFINE_FIELD( m_bMovingAwayFromPlayer, FIELD_BOOLEAN ),
DEFINE_EMBEDDED( m_SpeechWatch_PlayerLooking ),
DEFINE_EMBEDDED( m_FakeOutMortarTimer ),
// (recomputed)
// m_bWeightPathsInCover
// These are auto-saved by AI
// DEFINE_FIELD( m_AssaultBehavior, CAI_AssaultBehavior ),
// DEFINE_FIELD( m_FollowBehavior, CAI_FollowBehavior ),
// DEFINE_FIELD( m_StandoffBehavior, CAI_StandoffBehavior ),
// DEFINE_FIELD( m_LeadBehavior, CAI_LeadBehavior ),
// DEFINE_FIELD( m_OperatorBehavior, FIELD_EMBEDDED ),
// m_ActBusyBehavior
// m_PassengerBehavior
// m_FearBehavior
DEFINE_INPUTFUNC( FIELD_VOID, "OutsideTransition", InputOutsideTransition ),
DEFINE_INPUTFUNC( FIELD_VOID, "SetReadinessPanic", InputSetReadinessPanic ),
DEFINE_INPUTFUNC( FIELD_VOID, "SetReadinessStealth", InputSetReadinessStealth ),
DEFINE_INPUTFUNC( FIELD_VOID, "SetReadinessLow", InputSetReadinessLow ),
DEFINE_INPUTFUNC( FIELD_VOID, "SetReadinessMedium", InputSetReadinessMedium ),
DEFINE_INPUTFUNC( FIELD_VOID, "SetReadinessHigh", InputSetReadinessHigh ),
DEFINE_INPUTFUNC( FIELD_FLOAT, "LockReadiness", InputLockReadiness ),
//------------------------------------------------------------------------------
#ifdef HL2_EPISODIC
DEFINE_FIELD( m_hFlare, FIELD_EHANDLE ),
DEFINE_INPUTFUNC( FIELD_STRING, "EnterVehicle", InputEnterVehicle ),
DEFINE_INPUTFUNC( FIELD_STRING, "EnterVehicleImmediately", InputEnterVehicleImmediately ),
DEFINE_INPUTFUNC( FIELD_VOID, "ExitVehicle", InputExitVehicle ),
DEFINE_INPUTFUNC( FIELD_VOID, "CancelEnterVehicle", InputCancelEnterVehicle ),
#endif // HL2_EPISODIC
//------------------------------------------------------------------------------
DEFINE_INPUTFUNC( FIELD_STRING, "GiveWeapon", InputGiveWeapon ),
DEFINE_FIELD( m_flReadiness, FIELD_FLOAT ),
DEFINE_FIELD( m_flReadinessSensitivity, FIELD_FLOAT ),
DEFINE_FIELD( m_bReadinessCapable, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flReadinessLockedUntil, FIELD_TIME ),
DEFINE_FIELD( m_fLastBarrelExploded, FIELD_TIME ),
DEFINE_FIELD( m_iNumConsecutiveBarrelsExploded, FIELD_INTEGER ),
DEFINE_FIELD( m_fLastPlayerKill, FIELD_TIME ),
DEFINE_FIELD( m_iNumConsecutivePlayerKills, FIELD_INTEGER ),
// m_flBoostSpeed (recomputed)
DEFINE_EMBEDDED( m_AnnounceAttackTimer ),
DEFINE_FIELD( m_hAimTarget, FIELD_EHANDLE ),
DEFINE_KEYFIELD( m_bAlwaysTransition, FIELD_BOOLEAN, "AlwaysTransition" ),
DEFINE_KEYFIELD( m_bDontPickupWeapons, FIELD_BOOLEAN, "DontPickupWeapons" ),
DEFINE_INPUTFUNC( FIELD_VOID, "EnableAlwaysTransition", InputEnableAlwaysTransition ),
DEFINE_INPUTFUNC( FIELD_VOID, "DisableAlwaysTransition", InputDisableAlwaysTransition ),
DEFINE_INPUTFUNC( FIELD_VOID, "EnableWeaponPickup", InputEnableWeaponPickup ),
DEFINE_INPUTFUNC( FIELD_VOID, "DisableWeaponPickup", InputDisableWeaponPickup ),
#if HL2_EPISODIC
DEFINE_INPUTFUNC( FIELD_VOID, "ClearAllOutputs", InputClearAllOuputs ),
#endif
DEFINE_OUTPUT( m_OnWeaponPickup, "OnWeaponPickup" ),
END_DATADESC()
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
CNPC_PlayerCompanion::eCoverType CNPC_PlayerCompanion::gm_fCoverSearchType;
bool CNPC_PlayerCompanion::gm_bFindingCoverFromAllEnemies;
string_t CNPC_PlayerCompanion::gm_iszMortarClassname;
string_t CNPC_PlayerCompanion::gm_iszFloorTurretClassname;
string_t CNPC_PlayerCompanion::gm_iszGroundTurretClassname;
string_t CNPC_PlayerCompanion::gm_iszShotgunClassname;
string_t CNPC_PlayerCompanion::gm_iszRollerMineClassname;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::CreateBehaviors()
{
#ifdef HL2_EPISODIC
AddBehavior( &m_FearBehavior );
AddBehavior( &m_PassengerBehavior );
#endif // HL2_EPISODIC
AddBehavior( &m_ActBusyBehavior );
#ifdef HL2_EPISODIC
AddBehavior( &m_OperatorBehavior );
AddBehavior( &m_StandoffBehavior );
AddBehavior( &m_AssaultBehavior );
AddBehavior( &m_FollowBehavior );
AddBehavior( &m_LeadBehavior );
#else
AddBehavior( &m_AssaultBehavior );
AddBehavior( &m_StandoffBehavior );
AddBehavior( &m_FollowBehavior );
AddBehavior( &m_LeadBehavior );
#endif//HL2_EPISODIC
return BaseClass::CreateBehaviors();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::Precache()
{
gm_iszMortarClassname = AllocPooledString( "func_tankmortar" );
gm_iszFloorTurretClassname = AllocPooledString( "npc_turret_floor" );
gm_iszGroundTurretClassname = AllocPooledString( "npc_turret_ground" );
gm_iszShotgunClassname = AllocPooledString( "weapon_shotgun" );
gm_iszRollerMineClassname = AllocPooledString( "npc_rollermine" );
PrecacheModel( STRING( GetModelName() ) );
#ifdef HL2_EPISODIC
// The flare we're able to pull out
PrecacheModel( "models/props_junk/flare.mdl" );
#endif // HL2_EPISODIC
BaseClass::Precache();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::Spawn()
{
SelectModel();
Precache();
SetModel( STRING( GetModelName() ) );
SetHullType(HULL_HUMAN);
SetHullSizeNormal();
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_NOT_STANDABLE );
SetBloodColor( BLOOD_COLOR_RED );
m_flFieldOfView = 0.02;
m_NPCState = NPC_STATE_NONE;
CapabilitiesClear();
CapabilitiesAdd( bits_CAP_SQUAD );
if ( !HasSpawnFlags( SF_NPC_START_EFFICIENT ) )
{
CapabilitiesAdd( bits_CAP_ANIMATEDFACE | bits_CAP_TURN_HEAD );
CapabilitiesAdd( bits_CAP_USE_WEAPONS | bits_CAP_AIM_GUN | bits_CAP_MOVE_SHOOT );
CapabilitiesAdd( bits_CAP_DUCK | bits_CAP_DOORS_GROUP );
CapabilitiesAdd( bits_CAP_USE_SHOT_REGULATOR );
}
CapabilitiesAdd( bits_CAP_NO_HIT_PLAYER | bits_CAP_NO_HIT_SQUADMATES | bits_CAP_FRIENDLY_DMG_IMMUNE );
CapabilitiesAdd( bits_CAP_MOVE_GROUND );
SetMoveType( MOVETYPE_STEP );
m_HackedGunPos = Vector( 0, 0, 55 );
SetAimTarget(NULL);
m_bReadinessCapable = IsReadinessCapable();
SetReadinessValue( 0.0f );
SetReadinessSensitivity( random->RandomFloat( 0.7, 1.3 ) );
m_flReadinessLockedUntil = 0.0f;
m_AnnounceAttackTimer.Set( 10, 30 );
#ifdef HL2_EPISODIC
// We strip this flag because it's been made obsolete by the StartScripting behavior
if ( HasSpawnFlags( SF_NPC_ALTCOLLISION ) )
{
Warning( "NPC %s using alternate collision! -- DISABLED\n", STRING( GetEntityName() ) );
RemoveSpawnFlags( SF_NPC_ALTCOLLISION );
}
m_hFlare = NULL;
#endif // HL2_EPISODIC
BaseClass::Spawn();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CNPC_PlayerCompanion::Restore( IRestore &restore )
{
int baseResult = BaseClass::Restore( restore );
if ( gpGlobals->eLoadType == MapLoad_Transition )
{
m_StandoffBehavior.SetActive( false );
}
#ifdef HL2_EPISODIC
// We strip this flag because it's been made obsolete by the StartScripting behavior
if ( HasSpawnFlags( SF_NPC_ALTCOLLISION ) )
{
Warning( "NPC %s using alternate collision! -- DISABLED\n", STRING( GetEntityName() ) );
RemoveSpawnFlags( SF_NPC_ALTCOLLISION );
}
#endif // HL2_EPISODIC
return baseResult;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CNPC_PlayerCompanion::ObjectCaps()
{
int caps = UsableNPCObjectCaps( BaseClass::ObjectCaps() );
return caps;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::ShouldAlwaysThink()
{
return ( BaseClass::ShouldAlwaysThink() || ( GetFollowBehavior().GetFollowTarget() && GetFollowBehavior().GetFollowTarget()->IsPlayer() ) );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
Disposition_t CNPC_PlayerCompanion::IRelationType( CBaseEntity *pTarget )
{
if ( !pTarget )
return D_NU;
Disposition_t baseRelationship = BaseClass::IRelationType( pTarget );
if ( baseRelationship != D_LI )
{
if ( IsTurret( pTarget ) )
{
// Citizens are afeared of turrets, so long as the turret
// is active... that is, not classifying itself as CLASS_NONE
if( pTarget->Classify() != CLASS_NONE )
{
if( !hl2_episodic.GetBool() && IsSafeFromFloorTurret(GetAbsOrigin(), pTarget) )
{
return D_NU;
}
return D_FR;
}
}
else if ( baseRelationship == D_HT &&
pTarget->IsNPC() &&
((CAI_BaseNPC *)pTarget)->GetActiveWeapon() &&
((CAI_BaseNPC *)pTarget)->GetActiveWeapon()->ClassMatches( gm_iszShotgunClassname ) &&
( !GetActiveWeapon() || !GetActiveWeapon()->ClassMatches( gm_iszShotgunClassname ) ) )
{
if ( (pTarget->GetAbsOrigin() - GetAbsOrigin()).LengthSqr() < Square( 25 * 12 ) )
{
// Ignore enemies on the floor above us
if ( fabs(pTarget->GetAbsOrigin().z - GetAbsOrigin().z) < 100 )
return D_FR;
}
}
}
return baseRelationship;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsSilentSquadMember() const
{
if ( (const_cast<CNPC_PlayerCompanion *>(this))->Classify() == CLASS_PLAYER_ALLY_VITAL && m_pSquad && MAKE_STRING(m_pSquad->GetName()) == GetPlayerSquadName() )
{
return true;
}
return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::GatherConditions()
{
BaseClass::GatherConditions();
if ( AI_IsSinglePlayer() )
{
CBasePlayer *pPlayer = UTIL_GetLocalPlayer();
if ( Classify() == CLASS_PLAYER_ALLY_VITAL )
{
bool bInPlayerSquad = ( m_pSquad && MAKE_STRING(m_pSquad->GetName()) == GetPlayerSquadName() );
if ( bInPlayerSquad )
{
if ( GetState() == NPC_STATE_SCRIPT || ( !HasCondition( COND_SEE_PLAYER ) && (GetAbsOrigin() - pPlayer->GetAbsOrigin()).LengthSqr() > Square(50 * 12) ) )
{
RemoveFromSquad();
}
}
else if ( GetState() != NPC_STATE_SCRIPT )
{
if ( HasCondition( COND_SEE_PLAYER ) && (GetAbsOrigin() - pPlayer->GetAbsOrigin()).LengthSqr() < Square(25 * 12) )
{
if ( hl2_episodic.GetBool() )
{
// Don't stomp our squad if we're in one
if ( GetSquad() == NULL )
{
AddToSquad( GetPlayerSquadName() );
}
}
else
{
AddToSquad( GetPlayerSquadName() );
}
}
}
}
m_flBoostSpeed = 0;
if ( m_AnnounceAttackTimer.Expired() &&
( GetLastEnemyTime() == 0.0 || gpGlobals->curtime - GetLastEnemyTime() > 20 ) )
{
// Always delay when an encounter begins
m_AnnounceAttackTimer.Set( 4, 8 );
}
if ( GetFollowBehavior().GetFollowTarget() &&
( GetFollowBehavior().GetFollowTarget()->IsPlayer() || GetCommandGoal() != vec3_invalid ) &&
GetFollowBehavior().IsMovingToFollowTarget() &&
GetFollowBehavior().GetGoalRange() > 0.1 &&
BaseClass::GetIdealSpeed() > 0.1 )
{
Vector vPlayerToFollower = GetAbsOrigin() - pPlayer->GetAbsOrigin();
float dist = vPlayerToFollower.NormalizeInPlace();
bool bDoSpeedBoost = false;
if ( !HasCondition( COND_IN_PVS ) )
bDoSpeedBoost = true;
else if ( GetFollowBehavior().GetFollowTarget()->IsPlayer() )
{
if ( dist > GetFollowBehavior().GetGoalRange() * 2 )
{
float dot = vPlayerToFollower.Dot( pPlayer->EyeDirection3D() );
if ( dot < 0 )
{
bDoSpeedBoost = true;
}
}
}
if ( bDoSpeedBoost )
{
float lag = dist / GetFollowBehavior().GetGoalRange();
float mult;
if ( lag > 10.0 )
mult = 2.0;
else if ( lag > 5.0 )
mult = 1.5;
else if ( lag > 3.0 )
mult = 1.25;
else
mult = 1.1;
m_flBoostSpeed = pPlayer->GetSmoothedVelocity().Length();
if ( m_flBoostSpeed < BaseClass::GetIdealSpeed() )
m_flBoostSpeed = BaseClass::GetIdealSpeed();
m_flBoostSpeed *= mult;
}
}
}
// Update our readiness if we're
if ( IsReadinessCapable() )
{
UpdateReadiness();
}
PredictPlayerPush();
// Grovel through memories, don't forget enemies parented to func_tankmortar entities.
// !!!LATER - this should really call out and ask if I want to forget the enemy in question.
AIEnemiesIter_t iter;
for( AI_EnemyInfo_t *pMemory = GetEnemies()->GetFirst(&iter); pMemory != NULL; pMemory = GetEnemies()->GetNext(&iter) )
{
if ( IsMortar( pMemory->hEnemy ) || IsSniper( pMemory->hEnemy ) )
{
pMemory->bUnforgettable = ( IRelationType( pMemory->hEnemy ) < D_LI );
pMemory->bEludedMe = false;
}
}
if ( GetMotor()->IsDeceleratingToGoal() && IsCurTaskContinuousMove() &&
HasCondition( COND_PLAYER_PUSHING) && IsCurSchedule( SCHED_MOVE_AWAY ) )
{
ClearSchedule( "Being pushed by player" );
}
CBaseEntity *pEnemy = GetEnemy();
m_bWeightPathsInCover = false;
if ( pEnemy )
{
if ( IsMortar( pEnemy ) || IsSniper( pEnemy ) )
{
m_bWeightPathsInCover = true;
}
}
ClearCondition( COND_PC_SAFE_FROM_MORTAR );
if ( IsCurSchedule( SCHED_TAKE_COVER_FROM_BEST_SOUND ) )
{
CSound *pSound = GetBestSound( SOUND_DANGER );
if ( pSound && (pSound->SoundType() & SOUND_CONTEXT_MORTAR) )
{
float flDistSq = (pSound->GetSoundOrigin() - GetAbsOrigin() ).LengthSqr();
if ( flDistSq > Square( MORTAR_BLAST_RADIUS + GetHullWidth() * 2 ) )
SetCondition( COND_PC_SAFE_FROM_MORTAR );
}
}
// Handle speech AI. Don't do AI speech if we're in scripts unless permitted by the EnableSpeakWhileScripting input.
if ( m_NPCState == NPC_STATE_IDLE || m_NPCState == NPC_STATE_ALERT || m_NPCState == NPC_STATE_COMBAT ||
( ( m_NPCState == NPC_STATE_SCRIPT ) && CanSpeakWhileScripting() ) )
{
DoCustomSpeechAI();
}
if ( AI_IsSinglePlayer() && hl2_episodic.GetBool() && !GetEnemy() && HasCondition( COND_HEAR_PLAYER ) )
{
Vector los = ( UTIL_GetLocalPlayer()->EyePosition() - EyePosition() );
los.z = 0;
VectorNormalize( los );
if ( DotProduct( los, EyeDirection2D() ) > DOT_45DEGREE )
{
ClearCondition( COND_HEAR_PLAYER );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::DoCustomSpeechAI( void )
{
CBasePlayer *pPlayer = AI_GetSinglePlayer();
// Don't allow this when we're getting in the car
#ifdef HL2_EPISODIC
bool bPassengerInTransition = ( IsInAVehicle() && ( m_PassengerBehavior.GetPassengerState() == PASSENGER_STATE_ENTERING || m_PassengerBehavior.GetPassengerState() == PASSENGER_STATE_EXITING ) );
#else
bool bPassengerInTransition = false;
#endif
Vector vecEyePosition = EyePosition();
if ( bPassengerInTransition == false && pPlayer && pPlayer->FInViewCone( vecEyePosition ) && pPlayer->FVisible( vecEyePosition ) )
{
if ( m_SpeechWatch_PlayerLooking.Expired() )
{
SpeakIfAllowed( TLK_LOOK );
m_SpeechWatch_PlayerLooking.Stop();
}
}
else
{
m_SpeechWatch_PlayerLooking.Start( 1.0f );
}
// Mention the player is dead
if ( HasCondition( COND_TALKER_PLAYER_DEAD ) )
{
SpeakIfAllowed( TLK_PLDEAD );
}
}
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::PredictPlayerPush()
{
CBasePlayer *pPlayer = AI_GetSinglePlayer();
if ( pPlayer && pPlayer->GetSmoothedVelocity().LengthSqr() >= Square(140))
{
Vector predictedPosition = pPlayer->WorldSpaceCenter() + pPlayer->GetSmoothedVelocity() * .4;
Vector delta = WorldSpaceCenter() - predictedPosition;
if ( delta.z < GetHullHeight() * .5 && delta.Length2DSqr() < Square(GetHullWidth() * 1.414) )
TestPlayerPushing( pPlayer );
}
}
//-----------------------------------------------------------------------------
// Purpose: Allows for modification of the interrupt mask for the current schedule.
// In the most cases the base implementation should be called first.
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::BuildScheduleTestBits()
{
BaseClass::BuildScheduleTestBits();
// Always interrupt to get into the car
SetCustomInterruptCondition( COND_PC_BECOMING_PASSENGER );
if ( IsCurSchedule(SCHED_RANGE_ATTACK1) )
{
SetCustomInterruptCondition( COND_PLAYER_PUSHING );
}
if ( ( ConditionInterruptsCurSchedule( COND_GIVE_WAY ) ||
IsCurSchedule(SCHED_HIDE_AND_RELOAD ) ||
IsCurSchedule(SCHED_RELOAD ) ||
IsCurSchedule(SCHED_STANDOFF ) ||
IsCurSchedule(SCHED_TAKE_COVER_FROM_ENEMY ) ||
IsCurSchedule(SCHED_COMBAT_FACE ) ||
IsCurSchedule(SCHED_ALERT_FACE ) ||
IsCurSchedule(SCHED_COMBAT_STAND ) ||
IsCurSchedule(SCHED_ALERT_FACE_BESTSOUND) ||
IsCurSchedule(SCHED_ALERT_STAND) ) )
{
SetCustomInterruptCondition( COND_HEAR_MOVE_AWAY );
SetCustomInterruptCondition( COND_PLAYER_PUSHING );
SetCustomInterruptCondition( COND_PC_HURTBYFIRE );
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
CSound *CNPC_PlayerCompanion::GetBestSound( int validTypes )
{
AISoundIter_t iter;
CSound *pCurrentSound = GetSenses()->GetFirstHeardSound( &iter );
while ( pCurrentSound )
{
// the npc cares about this sound, and it's close enough to hear.
if ( pCurrentSound->FIsSound() )
{
if( pCurrentSound->SoundContext() & SOUND_CONTEXT_MORTAR )
{
return pCurrentSound;
}
}
pCurrentSound = GetSenses()->GetNextHeardSound( &iter );
}
return BaseClass::GetBestSound( validTypes );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::QueryHearSound( CSound *pSound )
{
if( !BaseClass::QueryHearSound(pSound) )
return false;
switch( pSound->SoundTypeNoContext() )
{
case SOUND_READINESS_LOW:
SetReadinessLevel( AIRL_RELAXED, false, true );
return false;
case SOUND_READINESS_MEDIUM:
SetReadinessLevel( AIRL_STIMULATED, false, true );
return false;
case SOUND_READINESS_HIGH:
SetReadinessLevel( AIRL_AGITATED, false, true );
return false;
default:
return true;
}
}
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::QuerySeeEntity( CBaseEntity *pEntity, bool bOnlyHateOrFearIfNPC )
{
CAI_BaseNPC *pOther = pEntity->MyNPCPointer();
if ( pOther &&
( pOther->GetState() == NPC_STATE_ALERT || GetState() == NPC_STATE_ALERT || pOther->GetState() == NPC_STATE_COMBAT || GetState() == NPC_STATE_COMBAT ) &&
pOther->IsPlayerAlly() )
{
return true;
}
return BaseClass::QuerySeeEntity( pEntity, bOnlyHateOrFearIfNPC );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::ShouldIgnoreSound( CSound *pSound )
{
if ( !BaseClass::ShouldIgnoreSound( pSound ) )
{
if ( pSound->IsSoundType( SOUND_DANGER ) && !SoundIsVisible(pSound) )
return true;
#ifdef HL2_EPISODIC
// Ignore vehicle sounds when we're driving in them
if ( pSound->m_hOwner && pSound->m_hOwner->GetServerVehicle() != NULL )
{
if ( m_PassengerBehavior.GetPassengerState() == PASSENGER_STATE_INSIDE &&
m_PassengerBehavior.GetTargetVehicle() == pSound->m_hOwner->GetServerVehicle()->GetVehicleEnt() )
return true;
}
#endif // HL2_EPISODIC
}
return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CNPC_PlayerCompanion::SelectSchedule()
{
m_bMovingAwayFromPlayer = false;
#ifdef HL2_EPISODIC
// Always defer to passenger if it's running
if ( ShouldDeferToPassengerBehavior() )
{
DeferSchedulingToBehavior( &m_PassengerBehavior );
return BaseClass::SelectSchedule();
}
#endif // HL2_EPISODIC
if ( m_ActBusyBehavior.IsRunning() && m_ActBusyBehavior.NeedsToPlayExitAnim() )
{
trace_t tr;
Vector vUp = GetAbsOrigin();
vUp.z += .25;
AI_TraceHull( GetAbsOrigin(), vUp, GetHullMins(),
GetHullMaxs(), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );
if ( tr.startsolid )
{
if ( HasCondition( COND_HEAR_DANGER ) )
{
m_ActBusyBehavior.StopBusying();
}
DeferSchedulingToBehavior( &m_ActBusyBehavior );
return BaseClass::SelectSchedule();
}
}
int nSched = SelectFlinchSchedule();
if ( nSched != SCHED_NONE )
return nSched;
int schedule = SelectScheduleDanger();
if ( schedule != SCHED_NONE )
return schedule;
schedule = SelectSchedulePriorityAction();
if ( schedule != SCHED_NONE )
return schedule;
if ( ShouldDeferToFollowBehavior() )
{
DeferSchedulingToBehavior( &(GetFollowBehavior()) );
}
else if ( !BehaviorSelectSchedule() )
{
if ( m_NPCState == NPC_STATE_IDLE || m_NPCState == NPC_STATE_ALERT )
{
schedule = SelectScheduleNonCombat();
if ( schedule != SCHED_NONE )
return schedule;
}
else if ( m_NPCState == NPC_STATE_COMBAT )
{
schedule = SelectScheduleCombat();
if ( schedule != SCHED_NONE )
return schedule;
}
}
return BaseClass::SelectSchedule();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CNPC_PlayerCompanion::SelectScheduleDanger()
{
if( HasCondition( COND_HEAR_DANGER ) )
{
CSound *pSound;
pSound = GetBestSound( SOUND_DANGER );
ASSERT( pSound != NULL );
if ( pSound && (pSound->m_iType & SOUND_DANGER) )
{
if ( !(pSound->SoundContext() & (SOUND_CONTEXT_MORTAR|SOUND_CONTEXT_FROM_SNIPER)) || IsOkToCombatSpeak() )
SpeakIfAllowed( TLK_DANGER );
if ( HasCondition( COND_PC_SAFE_FROM_MORTAR ) )
{
// Just duck and cover if far away from the explosion, or in cover.
return SCHED_COWER;
}
#if 1
else if( pSound && (pSound->m_iType & SOUND_CONTEXT_FROM_SNIPER) )
{
return SCHED_COWER;
}
#endif
return SCHED_TAKE_COVER_FROM_BEST_SOUND;
}
}
if ( GetEnemy() &&
m_FakeOutMortarTimer.Expired() &&
GetFollowBehavior().GetFollowTarget() &&
IsMortar( GetEnemy() ) &&
assert_cast<CAI_BaseNPC *>(GetEnemy())->GetEnemy() == this &&
assert_cast<CAI_BaseNPC *>(GetEnemy())->FInViewCone( this ) &&
assert_cast<CAI_BaseNPC *>(GetEnemy())->FVisible( this ) )
{
m_FakeOutMortarTimer.Set( 7 );
return SCHED_PC_FAKEOUT_MORTAR;
}
if ( HasCondition( COND_HEAR_MOVE_AWAY ) )
return SCHED_MOVE_AWAY;
if ( HasCondition( COND_PC_HURTBYFIRE ) )
{
ClearCondition( COND_PC_HURTBYFIRE );
return SCHED_MOVE_AWAY;
}
return SCHED_NONE;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CNPC_PlayerCompanion::SelectSchedulePriorityAction()
{
if ( GetGroundEntity() && !IsInAScript() )
{
if ( GetGroundEntity()->IsPlayer() )
{
return SCHED_PC_GET_OFF_COMPANION;
}
if ( GetGroundEntity()->IsNPC() &&
IRelationType( GetGroundEntity() ) == D_LI &&
WorldSpaceCenter().z - GetGroundEntity()->WorldSpaceCenter().z > GetHullHeight() * .5 )
{
return SCHED_PC_GET_OFF_COMPANION;
}
}
int schedule = SelectSchedulePlayerPush();
if ( schedule != SCHED_NONE )
{
if ( GetFollowBehavior().IsRunning() )
KeepRunningBehavior();
return schedule;
}
return SCHED_NONE;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CNPC_PlayerCompanion::SelectSchedulePlayerPush()
{
if ( HasCondition( COND_PLAYER_PUSHING ) && !IsInAScript() && !IgnorePlayerPushing() )
{
// Ignore move away before gordon becomes the man
if ( GlobalEntity_GetState("gordon_precriminal") != GLOBAL_ON )
{
m_bMovingAwayFromPlayer = true;
return SCHED_MOVE_AWAY;
}
}
return SCHED_NONE;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IgnorePlayerPushing( void )
{
if ( hl2_episodic.GetBool() )
{
// Ignore player pushes if we're leading him
if ( m_LeadBehavior.IsRunning() && m_LeadBehavior.HasGoal() )
return true;
if ( m_AssaultBehavior.IsRunning() && m_AssaultBehavior.OnStrictAssault() )
return true;
}
return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CNPC_PlayerCompanion::SelectScheduleCombat()
{
if ( CanReload() && (HasCondition ( COND_NO_PRIMARY_AMMO ) || HasCondition(COND_LOW_PRIMARY_AMMO)) )
{
return SCHED_HIDE_AND_RELOAD;
}
return SCHED_NONE;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::CanReload( void )
{
if ( IsRunningDynamicInteraction() )
return false;
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::ShouldDeferToFollowBehavior()
{
if ( !GetFollowBehavior().CanSelectSchedule() || !GetFollowBehavior().FarFromFollowTarget() )
return false;
if ( m_StandoffBehavior.CanSelectSchedule() && !m_StandoffBehavior.IsBehindBattleLines( GetFollowBehavior().GetFollowTarget()->GetAbsOrigin() ) )
return false;
if ( HasCondition(COND_BETTER_WEAPON_AVAILABLE) && !GetActiveWeapon() )
{
// Unarmed allies should arm themselves as soon as the opportunity presents itself.
return false;
}
// Even though assault and act busy are placed ahead of the follow behavior in precedence, the below
// code is necessary because we call ShouldDeferToFollowBehavior BEFORE we call the generic
// BehaviorSelectSchedule, which tries the behaviors in priority order.
if ( m_AssaultBehavior.CanSelectSchedule() && hl2_episodic.GetBool() )
{
return false;
}
if ( hl2_episodic.GetBool() )
{
if ( m_ActBusyBehavior.CanSelectSchedule() && m_ActBusyBehavior.IsCombatActBusy() )
{
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
// CalcReasonableFacing() is asking us if there's any reason why we wouldn't
// want to look in this direction.
//
// Right now this is used to help prevent citizens aiming their guns at each other
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsValidReasonableFacing( const Vector &vecSightDir, float sightDist )
{
if( !GetActiveWeapon() )
{
// If I'm not armed, it doesn't matter if I'm looking at another citizen.
return true;
}
if( ai_new_aiming.GetBool() )
{
Vector vecEyePositionCentered = GetAbsOrigin();
vecEyePositionCentered.z = EyePosition().z;
if( IsSquadmateInSpread(vecEyePositionCentered, vecEyePositionCentered + vecSightDir * 240.0f, VECTOR_CONE_15DEGREES.x, 12.0f * 3.0f) )
{
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CNPC_PlayerCompanion::TranslateSchedule( int scheduleType )
{
switch( scheduleType )
{
case SCHED_IDLE_STAND:
case SCHED_ALERT_STAND:
if( GetActiveWeapon() )
{
// Everyone with less than half a clip takes turns reloading when not fighting.
CBaseCombatWeapon *pWeapon = GetActiveWeapon();
if( CanReload() && pWeapon->UsesClipsForAmmo1() && pWeapon->Clip1() < ( pWeapon->GetMaxClip1() * .5 ) && OccupyStrategySlot( SQUAD_SLOT_EXCLUSIVE_RELOAD ) )
{
if ( AI_IsSinglePlayer() )
{
CBasePlayer *pPlayer = UTIL_GetLocalPlayer();
pWeapon = pPlayer->GetActiveWeapon();
if( pWeapon && pWeapon->UsesClipsForAmmo1() &&
pWeapon->Clip1() < ( pWeapon->GetMaxClip1() * .75 ) &&
pPlayer->GetAmmoCount( pWeapon->GetPrimaryAmmoType() ) )
{
SpeakIfAllowed( TLK_PLRELOAD );
}
}
return SCHED_RELOAD;
}
}
break;
case SCHED_COWER:
return SCHED_PC_COWER;
case SCHED_TAKE_COVER_FROM_BEST_SOUND:
{
CSound *pSound = GetBestSound(SOUND_DANGER);
if( pSound && pSound->m_hOwner )
{
if( pSound->m_hOwner->IsNPC() && FClassnameIs( pSound->m_hOwner, "npc_zombine" ) )
{
// Run fully away from a Zombine with a grenade.
return SCHED_PC_TAKE_COVER_FROM_BEST_SOUND;
}
}
return SCHED_PC_MOVE_TOWARDS_COVER_FROM_BEST_SOUND;
}
case SCHED_FLEE_FROM_BEST_SOUND:
return SCHED_PC_FLEE_FROM_BEST_SOUND;
case SCHED_ESTABLISH_LINE_OF_FIRE:
case SCHED_MOVE_TO_WEAPON_RANGE:
if ( IsMortar( GetEnemy() ) )
return SCHED_TAKE_COVER_FROM_ENEMY;
break;
case SCHED_CHASE_ENEMY:
if ( IsMortar( GetEnemy() ) )
return SCHED_TAKE_COVER_FROM_ENEMY;
if ( GetEnemy() && FClassnameIs( GetEnemy(), "npc_combinegunship" ) )
return SCHED_ESTABLISH_LINE_OF_FIRE;
break;
case SCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK:
// If we're fighting a gunship, try again
if ( GetEnemy() && FClassnameIs( GetEnemy(), "npc_combinegunship" ) )
return SCHED_ESTABLISH_LINE_OF_FIRE;
break;
case SCHED_RANGE_ATTACK1:
if ( IsMortar( GetEnemy() ) )
return SCHED_TAKE_COVER_FROM_ENEMY;
if ( GetShotRegulator()->IsInRestInterval() )
return SCHED_STANDOFF;
if( !OccupyStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) )
return SCHED_STANDOFF;
break;
case SCHED_FAIL_TAKE_COVER:
if ( IsEnemyTurret() )
{
return SCHED_PC_FAIL_TAKE_COVER_TURRET;
}
break;
case SCHED_RUN_FROM_ENEMY_FALLBACK:
{
if ( HasCondition( COND_CAN_RANGE_ATTACK1 ) )
{
return SCHED_RANGE_ATTACK1;
}
break;
}
}
return BaseClass::TranslateSchedule( scheduleType );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::StartTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_SOUND_WAKE:
LocateEnemySound();
SetWait( 0.5 );
break;
case TASK_ANNOUNCE_ATTACK:
{
if ( GetActiveWeapon() && m_AnnounceAttackTimer.Expired() )
{
if ( SpeakIfAllowed( TLK_ATTACKING, UTIL_VarArgs("attacking_with_weapon:%s", GetActiveWeapon()->GetClassname()) ) )
{
m_AnnounceAttackTimer.Set( 10, 30 );
}
}
BaseClass::StartTask( pTask );
break;
}
case TASK_PC_WAITOUT_MORTAR:
if ( HasCondition( COND_NO_HEAR_DANGER ) )
TaskComplete();
break;
case TASK_MOVE_AWAY_PATH:
{
if ( m_bMovingAwayFromPlayer )
SpeakIfAllowed( TLK_PLPUSH );
BaseClass::StartTask( pTask );
}
break;
case TASK_PC_GET_PATH_OFF_COMPANION:
{
Assert( ( GetGroundEntity() && ( GetGroundEntity()->IsPlayer() || ( GetGroundEntity()->IsNPC() && IRelationType( GetGroundEntity() ) == D_LI ) ) ) );
GetNavigator()->SetAllowBigStep( GetGroundEntity() );
ChainStartTask( TASK_MOVE_AWAY_PATH, 48 );
/*
trace_t tr;
UTIL_TraceHull( GetAbsOrigin(), GetAbsOrigin(), GetHullMins(), GetHullMaxs(), MASK_NPCSOLID, this, COLLISION_GROUP_NONE, &tr );
if ( tr.startsolid && tr.m_pEnt == GetGroundEntity() )
{
// Allow us to move through the entity for a short time
NPCPhysics_CreateSolver( this, GetGroundEntity(), true, 2.0f );
}
*/
}
break;
default:
BaseClass::StartTask( pTask );
break;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::RunTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_SOUND_WAKE:
if( IsWaitFinished() )
{
TaskComplete();
}
break;
case TASK_PC_WAITOUT_MORTAR:
{
if ( HasCondition( COND_NO_HEAR_DANGER ) )
TaskComplete();
}
break;
case TASK_MOVE_AWAY_PATH:
{
BaseClass::RunTask( pTask );
if ( GetNavigator()->IsGoalActive() && !GetEnemy() )
{
AddFacingTarget( EyePosition() + BodyDirection2D() * 240, 1.0, 2.0 );
}
}
break;
case TASK_PC_GET_PATH_OFF_COMPANION:
{
if ( AI_IsSinglePlayer() )
{
GetNavigator()->SetAllowBigStep( UTIL_GetLocalPlayer() );
}
ChainRunTask( TASK_MOVE_AWAY_PATH, 48 );
}
break;
default:
BaseClass::RunTask( pTask );
break;
}
}
//-----------------------------------------------------------------------------
// Parses this NPC's activity remap from the actremap.txt file
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::PrepareReadinessRemap( void )
{
CUtlVector< CActivityRemap > entries;
UTIL_LoadActivityRemapFile( "scripts/actremap.txt", "npc_playercompanion", entries );
for ( int i = 0; i < entries.Count(); i++ )
{
CCompanionActivityRemap ActRemap;
Q_memcpy( &ActRemap, &entries[i], sizeof( CActivityRemap ) );
KeyValues *pExtraBlock = ActRemap.GetExtraKeyValueBlock();
if ( pExtraBlock )
{
KeyValues *pKey = pExtraBlock->GetFirstSubKey();
while ( pKey )
{
const char *pKeyName = pKey->GetName();
const char *pKeyValue = pKey->GetString();
if ( !stricmp( pKeyName, "readiness" ) )
{
ActRemap.m_fUsageBits |= bits_REMAP_READINESS;
if ( !stricmp( pKeyValue, "AIRL_PANIC" ) )
{
ActRemap.m_readiness = AIRL_PANIC;
}
else if ( !stricmp( pKeyValue, "AIRL_STEALTH" ) )
{
ActRemap.m_readiness = AIRL_STEALTH;
}
else if ( !stricmp( pKeyValue, "AIRL_RELAXED" ) )
{
ActRemap.m_readiness = AIRL_RELAXED;
}
else if ( !stricmp( pKeyValue, "AIRL_STIMULATED" ) )
{
ActRemap.m_readiness = AIRL_STIMULATED;
}
else if ( !stricmp( pKeyValue, "AIRL_AGITATED" ) )
{
ActRemap.m_readiness = AIRL_AGITATED;
}
}
else if ( !stricmp( pKeyName, "aiming" ) )
{
ActRemap.m_fUsageBits |= bits_REMAP_AIMING;
if ( !stricmp( pKeyValue, "TRS_NONE" ) )
{
// This is the new way to say that we don't care, the tri-state was abandoned (jdw)
ActRemap.m_fUsageBits &= ~bits_REMAP_AIMING;
}
else if ( !stricmp( pKeyValue, "TRS_FALSE" ) || !stricmp( pKeyValue, "FALSE" ) )
{
ActRemap.m_bAiming = false;
}
else if ( !stricmp( pKeyValue, "TRS_TRUE" ) || !stricmp( pKeyValue, "TRUE" ) )
{
ActRemap.m_bAiming = true;
}
}
else if ( !stricmp( pKeyName, "weaponrequired" ) )
{
ActRemap.m_fUsageBits |= bits_REMAP_WEAPON_REQUIRED;
if ( !stricmp( pKeyValue, "TRUE" ) )
{
ActRemap.m_bWeaponRequired = true;
}
else if ( !stricmp( pKeyValue, "FALSE" ) )
{
ActRemap.m_bWeaponRequired = false;
}
}
else if ( !stricmp( pKeyName, "invehicle" ) )
{
ActRemap.m_fUsageBits |= bits_REMAP_IN_VEHICLE;
if ( !stricmp( pKeyValue, "TRUE" ) )
{
ActRemap.m_bInVehicle = true;
}
else if ( !stricmp( pKeyValue, "FALSE" ) )
{
ActRemap.m_bInVehicle = false;
}
}
pKey = pKey->GetNextKey();
}
}
const char *pActName = ActivityList_NameForIndex( (int)ActRemap.mappedActivity );
if ( GetActivityID( pActName ) == ACT_INVALID )
{
AddActivityToSR( pActName, (int)ActRemap.mappedActivity );
}
m_activityMappings.AddToTail( ActRemap );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::Activate( void )
{
BaseClass::Activate();
PrepareReadinessRemap();
}
//-----------------------------------------------------------------------------
// Purpose: Translate an activity given a list of criteria
//-----------------------------------------------------------------------------
Activity CNPC_PlayerCompanion::TranslateActivityReadiness( Activity activity )
{
// If we're in an actbusy, we don't want to mess with this
if ( m_ActBusyBehavior.IsActive() )
return activity;
if ( m_bReadinessCapable &&
( GetReadinessUse() == AIRU_ALWAYS ||
( GetReadinessUse() == AIRU_ONLY_PLAYER_SQUADMATES && (IsInPlayerSquad()||Classify()==CLASS_PLAYER_ALLY_VITAL) ) ) )
{
bool bShouldAim = ShouldBeAiming();
for ( int i = 0; i < m_activityMappings.Count(); i++ )
{
// Get our activity remap
CCompanionActivityRemap actremap = m_activityMappings[i];
// Activity must match
if ( activity != actremap.activity )
continue;
// Readiness must match
if ( ( actremap.m_fUsageBits & bits_REMAP_READINESS ) && GetReadinessLevel() != actremap.m_readiness )
continue;
// Deal with weapon state
if ( ( actremap.m_fUsageBits & bits_REMAP_WEAPON_REQUIRED ) && actremap.m_bWeaponRequired )
{
// Must have a weapon
if ( GetActiveWeapon() == NULL )
continue;
// Must either not care about aiming, or agree on aiming
if ( actremap.m_fUsageBits & bits_REMAP_AIMING )
{
if ( bShouldAim && actremap.m_bAiming == false )
continue;
if ( bShouldAim == false && actremap.m_bAiming )
continue;
}
}
// Must care about vehicle status
if ( actremap.m_fUsageBits & bits_REMAP_IN_VEHICLE )
{
// Deal with the two vehicle states
if ( actremap.m_bInVehicle && IsInAVehicle() == false )
continue;
if ( actremap.m_bInVehicle == false && IsInAVehicle() )
continue;
}
// We've successfully passed all criteria for remapping this
return actremap.mappedActivity;
}
}
return activity;
}
//-----------------------------------------------------------------------------
// Purpose: Override base class activiites
//-----------------------------------------------------------------------------
Activity CNPC_PlayerCompanion::NPC_TranslateActivity( Activity activity )
{
if ( activity == ACT_COWER )
return ACT_COVER_LOW;
if ( activity == ACT_RUN && ( IsCurSchedule( SCHED_TAKE_COVER_FROM_BEST_SOUND ) || IsCurSchedule( SCHED_FLEE_FROM_BEST_SOUND ) ) )
{
if ( random->RandomInt( 0, 1 ) && HaveSequenceForActivity( ACT_RUN_PROTECTED ) )
activity = ACT_RUN_PROTECTED;
}
activity = BaseClass::NPC_TranslateActivity( activity );
if ( activity == ACT_IDLE )
{
if ( (m_NPCState == NPC_STATE_COMBAT || m_NPCState == NPC_STATE_ALERT) && gpGlobals->curtime - m_flLastAttackTime < 3)
{
activity = ACT_IDLE_ANGRY;
}
}
return TranslateActivityReadiness( activity );
}
//------------------------------------------------------------------------------
// Purpose: Handle animation events
//------------------------------------------------------------------------------
void CNPC_PlayerCompanion::HandleAnimEvent( animevent_t *pEvent )
{
#ifdef HL2_EPISODIC
// Create a flare and parent to our hand
if ( pEvent->event == AE_COMPANION_PRODUCE_FLARE )
{
m_hFlare = static_cast<CPhysicsProp *>(CreateEntityByName( "prop_physics" ));
if ( m_hFlare != NULL )
{
// Set the model
m_hFlare->SetModel( "models/props_junk/flare.mdl" );
// Set the parent attachment
m_hFlare->SetParent( this );
m_hFlare->SetParentAttachment( "SetParentAttachment", pEvent->options, false );
}
return;
}
// Start the flare up with proper fanfare
if ( pEvent->event == AE_COMPANION_LIGHT_FLARE )
{
if ( m_hFlare != NULL )
{
m_hFlare->CreateFlare( 5*60.0f );
}
return;
}
// Drop the flare to the ground
if ( pEvent->event == AE_COMPANION_RELEASE_FLARE )
{
// Detach
m_hFlare->SetParent( NULL );
m_hFlare->Spawn();
m_hFlare->RemoveInteraction( PROPINTER_PHYSGUN_CREATE_FLARE );
// Disable collisions between the NPC and the flare
PhysDisableEntityCollisions( this, m_hFlare );
// TODO: Find the velocity of the attachment point, at this time, in the animation cycle
// Construct a toss velocity
Vector vecToss;
AngleVectors( GetAbsAngles(), &vecToss );
VectorNormalize( vecToss );
vecToss *= random->RandomFloat( 64.0f, 72.0f );
vecToss[2] += 64.0f;
// Throw it
IPhysicsObject *pObj = m_hFlare->VPhysicsGetObject();
pObj->ApplyForceCenter( vecToss );
// Forget about the flare at this point
m_hFlare = NULL;
return;
}
#endif // HL2_EPISODIC
switch( pEvent->event )
{
case EVENT_WEAPON_RELOAD:
if ( GetActiveWeapon() )
{
GetActiveWeapon()->WeaponSound( RELOAD_NPC );
GetActiveWeapon()->m_iClip1 = GetActiveWeapon()->GetMaxClip1();
ClearCondition(COND_LOW_PRIMARY_AMMO);
ClearCondition(COND_NO_PRIMARY_AMMO);
ClearCondition(COND_NO_SECONDARY_AMMO);
}
break;
default:
BaseClass::HandleAnimEvent( pEvent );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose: This is a generic function (to be implemented by sub-classes) to
// handle specific interactions between different types of characters
// (For example the barnacle grabbing an NPC)
// Input : Constant for the type of interaction
// Output : true - if sub-class has a response for the interaction
// false - if sub-class has no response
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt)
{
if (interactionType == g_interactionHitByPlayerThrownPhysObj )
{
if ( IsOkToSpeakInResponseToPlayer() )
{
Speak( TLK_PLYR_PHYSATK );
}
return true;
}
return BaseClass::HandleInteraction( interactionType, data, sourceEnt );
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
int CNPC_PlayerCompanion::GetSoundInterests()
{
return SOUND_WORLD |
SOUND_COMBAT |
SOUND_PLAYER |
SOUND_DANGER |
SOUND_BULLET_IMPACT |
SOUND_MOVE_AWAY |
SOUND_READINESS_LOW |
SOUND_READINESS_MEDIUM |
SOUND_READINESS_HIGH;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CNPC_PlayerCompanion::Touch( CBaseEntity *pOther )
{
BaseClass::Touch( pOther );
// Did the player touch me?
if ( pOther->IsPlayer() || ( pOther->VPhysicsGetObject() && (pOther->VPhysicsGetObject()->GetGameFlags() & FVPHYSICS_PLAYER_HELD ) ) )
{
// Ignore if pissed at player
if ( m_afMemory & bits_MEMORY_PROVOKED )
return;
TestPlayerPushing( ( pOther->IsPlayer() ) ? pOther : AI_GetSinglePlayer() );
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::ModifyOrAppendCriteria( AI_CriteriaSet& set )
{
BaseClass::ModifyOrAppendCriteria( set );
if ( GetEnemy() && IsMortar( GetEnemy() ) )
{
set.RemoveCriteria( "enemy" );
set.AppendCriteria( "enemy", STRING(gm_iszMortarClassname) );
}
if ( HasCondition( COND_PC_HURTBYFIRE ) )
{
set.AppendCriteria( "hurt_by_fire", "1" );
}
if ( m_bReadinessCapable )
{
switch( GetReadinessLevel() )
{
case AIRL_PANIC:
set.AppendCriteria( "readiness", "panic" );
break;
case AIRL_STEALTH:
set.AppendCriteria( "readiness", "stealth" );
break;
case AIRL_RELAXED:
set.AppendCriteria( "readiness", "relaxed" );
break;
case AIRL_STIMULATED:
set.AppendCriteria( "readiness", "stimulated" );
break;
case AIRL_AGITATED:
set.AppendCriteria( "readiness", "agitated" );
break;
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsReadinessCapable()
{
if ( GlobalEntity_GetState("gordon_precriminal") == GLOBAL_ON )
return false;
#ifndef HL2_EPISODIC
// Allow episodic companions to use readiness even if unarmed. This allows for the panicked
// citizens in ep1_c17_05 (sjb)
if( !GetActiveWeapon() )
return false;
#endif
if( GetActiveWeapon() && LookupActivity("ACT_IDLE_AIM_RIFLE_STIMULATED") == ACT_INVALID )
return false;
if( GetActiveWeapon() && FClassnameIs( GetActiveWeapon(), "weapon_rpg" ) )
return false;
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::AddReadiness( float flAdd, bool bOverrideLock )
{
if( IsReadinessLocked() && !bOverrideLock )
return;
SetReadinessValue( GetReadinessValue() + flAdd );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::SubtractReadiness( float flSub, bool bOverrideLock )
{
if( IsReadinessLocked() && !bOverrideLock )
return;
// Prevent readiness from going below 0 (below 0 is only for scripted states)
SetReadinessValue( MAX(GetReadinessValue() - flSub, 0) );
}
//-----------------------------------------------------------------------------
// This method returns false if the NPC is not allowed to change readiness at this point.
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::AllowReadinessValueChange( void )
{
if ( GetIdealActivity() == ACT_IDLE || GetIdealActivity() == ACT_WALK || GetIdealActivity() == ACT_RUN )
return true;
if ( HasActiveLayer() == true )
return false;
return false;
}
//-----------------------------------------------------------------------------
// NOTE: This function ignores the lock. Use the interface functions.
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::SetReadinessValue( float flSet )
{
if ( AllowReadinessValueChange() == false )
return;
int priorReadiness = GetReadinessLevel();
flSet = MIN( 1.0f, flSet );
flSet = MAX( READINESS_MIN_VALUE, flSet );
m_flReadiness = flSet;
if( GetReadinessLevel() != priorReadiness )
{
// We've been bumped up into a different readiness level.
// Interrupt IDLE schedules (if we're playing one) so that
// we can pick the proper animation.
SetCondition( COND_IDLE_INTERRUPT );
// Force us to recalculate our animation. If we don't do this,
// our translated activity may change, but not our root activity,
// and then we won't actually visually change anims.
ResetActivity();
//Force the NPC to recalculate it's arrival sequence since it'll most likely be wrong now that we changed readiness level.
GetNavigator()->SetArrivalSequence( ACT_INVALID );
ReadinessLevelChanged( priorReadiness );
}
}
//-----------------------------------------------------------------------------
// if bOverrideLock, you'll change the readiness level even if we're within
// a time period during which someone else has locked the level.
//
// if bSlam, you'll allow the readiness level to be set lower than current.
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::SetReadinessLevel( int iLevel, bool bOverrideLock, bool bSlam )
{
if( IsReadinessLocked() && !bOverrideLock )
return;
switch( iLevel )
{
case AIRL_PANIC:
if( bSlam )
SetReadinessValue( READINESS_MODE_PANIC );
break;
case AIRL_STEALTH:
if( bSlam )
SetReadinessValue( READINESS_MODE_STEALTH );
break;
case AIRL_RELAXED:
if( bSlam || GetReadinessValue() < READINESS_VALUE_RELAXED )
SetReadinessValue( READINESS_VALUE_RELAXED );
break;
case AIRL_STIMULATED:
if( bSlam || GetReadinessValue() < READINESS_VALUE_STIMULATED )
SetReadinessValue( READINESS_VALUE_STIMULATED );
break;
case AIRL_AGITATED:
if( bSlam || GetReadinessValue() < READINESS_VALUE_AGITATED )
SetReadinessValue( READINESS_VALUE_AGITATED );
break;
default:
DevMsg("ERROR: Bad readiness level\n");
break;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CNPC_PlayerCompanion::GetReadinessLevel()
{
if ( m_bReadinessCapable == false )
return AIRL_RELAXED;
if( m_flReadiness == READINESS_MODE_PANIC )
{
return AIRL_PANIC;
}
if( m_flReadiness == READINESS_MODE_STEALTH )
{
return AIRL_STEALTH;
}
if( m_flReadiness <= READINESS_VALUE_RELAXED )
{
return AIRL_RELAXED;
}
if( m_flReadiness <= READINESS_VALUE_STIMULATED )
{
return AIRL_STIMULATED;
}
return AIRL_AGITATED;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::UpdateReadiness()
{
// Only update readiness if it's not in a scripted state
if ( !IsInScriptedReadinessState() )
{
if( HasCondition(COND_HEAR_COMBAT) || HasCondition(COND_HEAR_BULLET_IMPACT) )
SetReadinessLevel( AIRL_STIMULATED, false, false );
if( HasCondition(COND_HEAR_DANGER) || HasCondition(COND_SEE_ENEMY) )
SetReadinessLevel( AIRL_AGITATED, false, false );
if( m_flReadiness > 0.0f && GetReadinessDecay() > 0 )
{
// Decay.
SubtractReadiness( ( 0.1 * (1.0f/GetReadinessDecay())) * m_flReadinessSensitivity );
}
}
if( ai_debug_readiness.GetBool() && AI_IsSinglePlayer() )
{
// Draw the readiness-o-meter
Vector vecSpot;
Vector vecOffset( 0, 0, 12 );
const float BARLENGTH = 12.0f;
const float GRADLENGTH = 4.0f;
Vector right;
UTIL_PlayerByIndex( 1 )->GetVectors( NULL, &right, NULL );
if ( IsInScriptedReadinessState() )
{
// Just print the name of the scripted state
vecSpot = EyePosition() + vecOffset;
if( GetReadinessLevel() == AIRL_STEALTH )
{
NDebugOverlay::Text( vecSpot, "Stealth", true, 0.1 );
}
else if( GetReadinessLevel() == AIRL_PANIC )
{
NDebugOverlay::Text( vecSpot, "Panic", true, 0.1 );
}
else
{
NDebugOverlay::Text( vecSpot, "Unspecified", true, 0.1 );
}
}
else
{
vecSpot = EyePosition() + vecOffset;
NDebugOverlay::Line( vecSpot, vecSpot + right * GRADLENGTH, 255, 255, 255, false, 0.1 );
vecSpot = EyePosition() + vecOffset + Vector( 0, 0, BARLENGTH * READINESS_VALUE_RELAXED );
NDebugOverlay::Line( vecSpot, vecSpot + right * GRADLENGTH, 0, 255, 0, false, 0.1 );
vecSpot = EyePosition() + vecOffset + Vector( 0, 0, BARLENGTH * READINESS_VALUE_STIMULATED );
NDebugOverlay::Line( vecSpot, vecSpot + right * GRADLENGTH, 255, 255, 0, false, 0.1 );
vecSpot = EyePosition() + vecOffset + Vector( 0, 0, BARLENGTH * READINESS_VALUE_AGITATED );
NDebugOverlay::Line( vecSpot, vecSpot + right * GRADLENGTH, 255, 0, 0, false, 0.1 );
vecSpot = EyePosition() + vecOffset;
NDebugOverlay::Line( vecSpot, vecSpot + Vector( 0, 0, BARLENGTH * GetReadinessValue() ), 255, 255, 0, false, 0.1 );
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
float CNPC_PlayerCompanion::GetReadinessDecay()
{
return ai_readiness_decay.GetFloat();
}
//-----------------------------------------------------------------------------
// Passing NULL to clear the aim target is acceptible.
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::SetAimTarget( CBaseEntity *pTarget )
{
if( pTarget != NULL && IsAllowedToAim() )
{
m_hAimTarget = pTarget;
}
else
{
m_hAimTarget = NULL;
}
Activity NewActivity = NPC_TranslateActivity(GetActivity());
//Don't set the ideal activity to an activity that might not be there.
if ( SelectWeightedSequence( NewActivity ) == ACT_INVALID )
return;
if (NewActivity != GetActivity() )
{
SetIdealActivity( NewActivity );
}
#if 0
if( m_hAimTarget )
{
Msg("New Aim Target: %s\n", m_hAimTarget->GetClassname() );
NDebugOverlay::Line(EyePosition(), m_hAimTarget->WorldSpaceCenter(), 255, 255, 0, false, 0.1 );
}
#endif
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::StopAiming( char *pszReason )
{
#if 0
if( pszReason )
{
Msg("Stopped aiming because %s\n", pszReason );
}
#endif
SetAimTarget(NULL);
Activity NewActivity = NPC_TranslateActivity(GetActivity());
if (NewActivity != GetActivity())
{
SetIdealActivity( NewActivity );
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#define COMPANION_MAX_LOOK_TIME 3.0f
#define COMPANION_MIN_LOOK_TIME 1.0f
#define COMPANION_MAX_TACTICAL_TARGET_DIST 1800.0f // 150 feet
bool CNPC_PlayerCompanion::PickTacticalLookTarget( AILookTargetArgs_t *pArgs )
{
if( HasCondition( COND_SEE_ENEMY ) )
{
// Don't bother. We're dealing with our enemy.
return false;
}
float flMinLookTime;
float flMaxLookTime;
// Excited companions will look at each target only briefly and then find something else to look at.
flMinLookTime = COMPANION_MIN_LOOK_TIME + ((COMPANION_MAX_LOOK_TIME-COMPANION_MIN_LOOK_TIME) * (1.0f - GetReadinessValue()) );
switch( GetReadinessLevel() )
{
case AIRL_RELAXED:
// Linger on targets, look at them for quite a while.
flMinLookTime = COMPANION_MAX_LOOK_TIME + random->RandomFloat( 0.0f, 2.0f );
break;
case AIRL_STIMULATED:
// Look around a little quicker.
flMinLookTime = COMPANION_MIN_LOOK_TIME + random->RandomFloat( 0.0f, COMPANION_MAX_LOOK_TIME - 1.0f );
break;
case AIRL_AGITATED:
// Look around very quickly
flMinLookTime = COMPANION_MIN_LOOK_TIME;
break;
}
flMaxLookTime = flMinLookTime + random->RandomFloat( 0.0f, 0.5f );
pArgs->flDuration = random->RandomFloat( flMinLookTime, flMaxLookTime );
if( HasCondition(COND_SEE_PLAYER) && hl2_episodic.GetBool() )
{
// 1/3rd chance to authoritatively look at player
if( random->RandomInt( 0, 2 ) == 0 )
{
pArgs->hTarget = AI_GetSinglePlayer();
return true;
}
}
// Use hint nodes
CAI_Hint *pHint;
CHintCriteria hintCriteria;
hintCriteria.AddHintType( HINT_WORLD_VISUALLY_INTERESTING );
hintCriteria.AddHintType( HINT_WORLD_VISUALLY_INTERESTING_DONT_AIM );
hintCriteria.AddHintType( HINT_WORLD_VISUALLY_INTERESTING_STEALTH );
hintCriteria.SetFlag( bits_HINT_NODE_VISIBLE | bits_HINT_NODE_IN_VIEWCONE | bits_HINT_NPC_IN_NODE_FOV );
hintCriteria.AddIncludePosition( GetAbsOrigin(), COMPANION_MAX_TACTICAL_TARGET_DIST );
{
AI_PROFILE_SCOPE( CNPC_PlayerCompanion_FindHint_PickTacticalLookTarget );
pHint = CAI_HintManager::FindHint( this, hintCriteria );
}
if( pHint )
{
pArgs->hTarget = pHint;
// Turn this node off for a few seconds to stop others aiming at the same thing (except for stealth nodes)
if ( pHint->HintType() != HINT_WORLD_VISUALLY_INTERESTING_STEALTH )
{
pHint->DisableForSeconds( 5.0f );
}
return true;
}
// See what the base class thinks.
return BaseClass::PickTacticalLookTarget( pArgs );
}
//-----------------------------------------------------------------------------
// Returns true if changing target.
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::FindNewAimTarget()
{
if( GetEnemy() )
{
// Don't bother. Aim at enemy.
return false;
}
if( !m_bReadinessCapable || GetReadinessLevel() == AIRL_RELAXED )
{
// If I'm relaxed (don't want to aim), or physically incapable,
// don't run this hint node searching code.
return false;
}
CAI_Hint *pHint;
CHintCriteria hintCriteria;
CBaseEntity *pPriorAimTarget = GetAimTarget();
hintCriteria.SetHintType( HINT_WORLD_VISUALLY_INTERESTING );
hintCriteria.SetFlag( bits_HINT_NODE_VISIBLE | bits_HINT_NODE_IN_VIEWCONE | bits_HINT_NPC_IN_NODE_FOV );
hintCriteria.AddIncludePosition( GetAbsOrigin(), COMPANION_MAX_TACTICAL_TARGET_DIST );
pHint = CAI_HintManager::FindHint( this, hintCriteria );
if( pHint )
{
if( (pHint->GetAbsOrigin() - GetAbsOrigin()).Length2D() < COMPANION_AIMTARGET_NEAREST )
{
// Too close!
return false;
}
if( !HasAimLOS(pHint) )
{
// No LOS
return false;
}
if( pHint != pPriorAimTarget )
{
// Notify of the change.
SetAimTarget( pHint );
return true;
}
}
// Didn't find an aim target, or found the same one.
return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::OnNewLookTarget()
{
if( ai_new_aiming.GetBool() )
{
if( GetLooktarget() )
{
// See if our looktarget is a reasonable aim target.
CAI_Hint *pHint = dynamic_cast<CAI_Hint*>( GetLooktarget() );
if( pHint )
{
if( pHint->HintType() == HINT_WORLD_VISUALLY_INTERESTING &&
(pHint->GetAbsOrigin() - GetAbsOrigin()).Length2D() > COMPANION_AIMTARGET_NEAREST &&
FInAimCone(pHint->GetAbsOrigin()) &&
HasAimLOS(pHint) )
{
SetAimTarget( pHint );
return;
}
}
}
// Search for something else.
FindNewAimTarget();
}
else
{
if( GetLooktarget() )
{
// Have picked a new entity to look at. Should we copy it to the aim target?
if( IRelationType( GetLooktarget() ) == D_LI )
{
// Don't aim at friends, just keep the old target (if any)
return;
}
if( (GetLooktarget()->GetAbsOrigin() - GetAbsOrigin()).Length2D() < COMPANION_AIMTARGET_NEAREST )
{
// Too close!
return;
}
if( !HasAimLOS( GetLooktarget() ) )
{
// No LOS
return;
}
SetAimTarget( GetLooktarget() );
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::ShouldBeAiming()
{
if( !IsAllowedToAim() )
{
return false;
}
if( !GetEnemy() && !GetAimTarget() )
{
return false;
}
if( GetEnemy() && !HasCondition(COND_SEE_ENEMY) )
{
return false;
}
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#define PC_MAX_ALLOWED_AIM 2
bool CNPC_PlayerCompanion::IsAllowedToAim()
{
if( !m_pSquad )
return true;
if( GetReadinessLevel() == AIRL_AGITATED )
{
// Agitated companions can always aim. This makes the squad look
// more alert as a whole when something very serious/dangerous has happened.
return true;
}
int count = 0;
// If I'm in a squad, only a certain number of us can aim.
AISquadIter_t iter;
for ( CAI_BaseNPC *pSquadmate = m_pSquad->GetFirstMember(&iter); pSquadmate; pSquadmate = m_pSquad->GetNextMember(&iter) )
{
CNPC_PlayerCompanion *pCompanion = dynamic_cast<CNPC_PlayerCompanion*>(pSquadmate);
if( pCompanion && pCompanion != this && pCompanion->GetAimTarget() != NULL )
{
count++;
}
}
if( count < PC_MAX_ALLOWED_AIM )
{
return true;
}
return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::HasAimLOS( CBaseEntity *pAimTarget )
{
trace_t tr;
UTIL_TraceLine( Weapon_ShootPosition(), pAimTarget->WorldSpaceCenter(), MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );
if( tr.fraction < 0.5 || (tr.m_pEnt && (tr.m_pEnt->IsNPC()||tr.m_pEnt->IsPlayer())) )
{
return false;
}
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::AimGun()
{
Vector vecAimDir;
if( !GetEnemy() )
{
if( GetAimTarget() && FInViewCone(GetAimTarget()) )
{
float flDist;
Vector vecAimTargetLoc = GetAimTarget()->WorldSpaceCenter();
flDist = (vecAimTargetLoc - GetAbsOrigin()).Length2DSqr();
// Throw away a looktarget if it gets too close. We don't want guys turning around as
// they walk through doorways which contain a looktarget.
if( flDist < COMPANION_AIMTARGET_NEAREST_SQR )
{
StopAiming("Target too near");
return;
}
// Aim at my target if it's in my cone
vecAimDir = vecAimTargetLoc - Weapon_ShootPosition();;
VectorNormalize( vecAimDir );
SetAim( vecAimDir);
if( !HasAimLOS(GetAimTarget()) )
{
// LOS is broken.
if( !FindNewAimTarget() )
{
// No alternative available right now. Stop aiming.
StopAiming("No LOS");
}
}
return;
}
else
{
if( GetAimTarget() )
{
// We're aiming at something, but we're about to stop because it's out of viewcone.
// Try to find something else.
if( FindNewAimTarget() )
{
// Found something else to aim at.
return;
}
else
{
// ditch the aim target, it's gone out of view.
StopAiming("Went out of view cone");
}
}
if( GetReadinessLevel() == AIRL_AGITATED )
{
// Aim down! Agitated animations don't have non-aiming versions, so
// just point the weapon down.
Vector vecSpot = EyePosition();
Vector forward, up;
GetVectors( &forward, NULL, &up );
vecSpot += forward * 128 + up * -64;
vecAimDir = vecSpot - Weapon_ShootPosition();
VectorNormalize( vecAimDir );
SetAim( vecAimDir);
return;
}
}
}
BaseClass::AimGun();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
CBaseEntity *CNPC_PlayerCompanion::GetAlternateMoveShootTarget()
{
if( GetAimTarget() && !GetAimTarget()->IsNPC() && GetReadinessLevel() != AIRL_RELAXED )
{
return GetAimTarget();
}
return BaseClass::GetAlternateMoveShootTarget();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsValidEnemy( CBaseEntity *pEnemy )
{
if ( GetFollowBehavior().GetFollowTarget() && GetFollowBehavior().GetFollowTarget()->IsPlayer() && IsSniper( pEnemy ) )
{
AI_EnemyInfo_t *pInfo = GetEnemies()->Find( pEnemy );
if ( pInfo )
{
if ( gpGlobals->curtime - pInfo->timeLastSeen > 10 )
{
if ( !((CAI_BaseNPC*)pEnemy)->HasCondition( COND_IN_PVS ) )
return false;
}
}
}
return BaseClass::IsValidEnemy( pEnemy );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsSafeFromFloorTurret( const Vector &vecLocation, CBaseEntity *pTurret )
{
float dist = ( vecLocation - pTurret->EyePosition() ).LengthSqr();
if ( dist > Square( 4.0*12.0 ) )
{
if ( !pTurret->MyNPCPointer()->FInViewCone( vecLocation ) )
{
#if 0 // Draws a green line to turrets I'm safe from
NDebugOverlay::Line( vecLocation, pTurret->WorldSpaceCenter(), 0, 255, 0, false, 0.1 );
#endif
return true;
}
}
#if 0 // Draws a red lines to ones I'm not safe from.
NDebugOverlay::Line( vecLocation, pTurret->WorldSpaceCenter(), 255, 0, 0, false, 0.1 );
#endif
return false;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
bool CNPC_PlayerCompanion::ShouldMoveAndShoot( void )
{
return BaseClass::ShouldMoveAndShoot();
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#define PC_LARGER_BURST_RANGE (12.0f * 10.0f) // If an enemy is this close, player companions fire larger continuous bursts.
void CNPC_PlayerCompanion::OnUpdateShotRegulator()
{
BaseClass::OnUpdateShotRegulator();
if( GetEnemy() && HasCondition(COND_CAN_RANGE_ATTACK1) )
{
if( GetAbsOrigin().DistTo( GetEnemy()->GetAbsOrigin() ) <= PC_LARGER_BURST_RANGE )
{
if( hl2_episodic.GetBool() )
{
// Longer burst
int longBurst = random->RandomInt( 10, 15 );
GetShotRegulator()->SetBurstShotsRemaining( longBurst );
GetShotRegulator()->SetRestInterval( 0.1, 0.2 );
}
else
{
// Longer burst
GetShotRegulator()->SetBurstShotsRemaining( GetShotRegulator()->GetBurstShotsRemaining() * 2 );
// Shorter Rest interval
float flMinInterval, flMaxInterval;
GetShotRegulator()->GetRestInterval( &flMinInterval, &flMaxInterval );
GetShotRegulator()->SetRestInterval( flMinInterval * 0.6f, flMaxInterval * 0.6f );
}
}
}
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CNPC_PlayerCompanion::DecalTrace( trace_t *pTrace, char const *decalName )
{
// Do not decal a player companion's head or face, no matter what.
if( pTrace->hitgroup == HITGROUP_HEAD )
return;
BaseClass::DecalTrace( pTrace, decalName );
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
bool CNPC_PlayerCompanion::FCanCheckAttacks()
{
if( GetEnemy() && ( IsSniper(GetEnemy()) || IsMortar(GetEnemy()) || IsTurret(GetEnemy()) ) )
{
// Don't attack the sniper or the mortar.
return false;
}
return BaseClass::FCanCheckAttacks();
}
//-----------------------------------------------------------------------------
// Purpose: Return the actual position the NPC wants to fire at when it's trying
// to hit it's current enemy.
//-----------------------------------------------------------------------------
#define CITIZEN_HEADSHOT_FREQUENCY 3 // one in this many shots at a zombie will be aimed at the zombie's head
Vector CNPC_PlayerCompanion::GetActualShootPosition( const Vector &shootOrigin )
{
if( GetEnemy() && GetEnemy()->Classify() == CLASS_ZOMBIE && random->RandomInt( 1, CITIZEN_HEADSHOT_FREQUENCY ) == 1 )
{
return GetEnemy()->HeadTarget( shootOrigin );
}
return BaseClass::GetActualShootPosition( shootOrigin );
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
WeaponProficiency_t CNPC_PlayerCompanion::CalcWeaponProficiency( CBaseCombatWeapon *pWeapon )
{
if( FClassnameIs( pWeapon, "weapon_ar2" ) )
{
return WEAPON_PROFICIENCY_VERY_GOOD;
}
return WEAPON_PROFICIENCY_PERFECT;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::Weapon_CanUse( CBaseCombatWeapon *pWeapon )
{
if( BaseClass::Weapon_CanUse( pWeapon ) )
{
// If this weapon is a shotgun, take measures to control how many
// are being used in this squad. Don't allow a companion to pick up
// a shotgun if a squadmate already has one.
if( pWeapon->ClassMatches( gm_iszShotgunClassname ) )
{
return (NumWeaponsInSquad("weapon_shotgun") < 1 );
}
else
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::ShouldLookForBetterWeapon()
{
if ( m_bDontPickupWeapons )
return false;
return BaseClass::ShouldLookForBetterWeapon();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::Weapon_Equip( CBaseCombatWeapon *pWeapon )
{
BaseClass::Weapon_Equip( pWeapon );
m_bReadinessCapable = IsReadinessCapable();
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CNPC_PlayerCompanion::PickupWeapon( CBaseCombatWeapon *pWeapon )
{
BaseClass::PickupWeapon( pWeapon );
SpeakIfAllowed( TLK_NEWWEAPON );
m_OnWeaponPickup.FireOutput( this, this );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
const int MAX_NON_SPECIAL_MULTICOVER = 2;
CUtlVector<AI_EnemyInfo_t *> g_MultiCoverSearchEnemies;
CNPC_PlayerCompanion * g_pMultiCoverSearcher;
//-------------------------------------
int __cdecl MultiCoverCompare( AI_EnemyInfo_t * const *ppLeft, AI_EnemyInfo_t * const *ppRight )
{
const AI_EnemyInfo_t *pLeft = *ppLeft;
const AI_EnemyInfo_t *pRight = *ppRight;
if ( !pLeft->hEnemy && !pRight->hEnemy)
return 0;
if ( !pLeft->hEnemy )
return 1;
if ( !pRight->hEnemy )
return -1;
if ( pLeft->hEnemy == g_pMultiCoverSearcher->GetEnemy() )
return -1;
if ( pRight->hEnemy == g_pMultiCoverSearcher->GetEnemy() )
return 1;
bool bLeftIsSpecial = ( CNPC_PlayerCompanion::IsMortar( pLeft->hEnemy ) || CNPC_PlayerCompanion::IsSniper( pLeft->hEnemy ) );
bool bRightIsSpecial = ( CNPC_PlayerCompanion::IsMortar( pLeft->hEnemy ) || CNPC_PlayerCompanion::IsSniper( pLeft->hEnemy ) );
if ( !bLeftIsSpecial && bRightIsSpecial )
return 1;
if ( bLeftIsSpecial && !bRightIsSpecial )
return -1;
float leftRelevantTime = ( pLeft->timeLastSeen == AI_INVALID_TIME || pLeft->timeLastSeen == 0 ) ? -99999 : pLeft->timeLastSeen;
if ( pLeft->timeLastReceivedDamageFrom != AI_INVALID_TIME && pLeft->timeLastReceivedDamageFrom > leftRelevantTime )
leftRelevantTime = pLeft->timeLastReceivedDamageFrom;
float rightRelevantTime = ( pRight->timeLastSeen == AI_INVALID_TIME || pRight->timeLastSeen == 0 ) ? -99999 : pRight->timeLastSeen;
if ( pRight->timeLastReceivedDamageFrom != AI_INVALID_TIME && pRight->timeLastReceivedDamageFrom > rightRelevantTime )
rightRelevantTime = pRight->timeLastReceivedDamageFrom;
if ( leftRelevantTime < rightRelevantTime )
return -1;
if ( leftRelevantTime > rightRelevantTime )
return 1;
float leftDistSq = g_pMultiCoverSearcher->GetAbsOrigin().DistToSqr( pLeft->hEnemy->GetAbsOrigin() );
float rightDistSq = g_pMultiCoverSearcher->GetAbsOrigin().DistToSqr( pRight->hEnemy->GetAbsOrigin() );
if ( leftDistSq < rightDistSq )
return -1;
if ( leftDistSq > rightDistSq )
return 1;
return 0;
}
//-------------------------------------
void CNPC_PlayerCompanion::SetupCoverSearch( CBaseEntity *pEntity )
{
if ( IsTurret( pEntity ) )
gm_fCoverSearchType = CT_TURRET;
gm_bFindingCoverFromAllEnemies = false;
g_pMultiCoverSearcher = this;
if ( Classify() == CLASS_PLAYER_ALLY_VITAL || IsInPlayerSquad() )
{
if ( GetEnemy() )
{
if ( !pEntity || GetEnemies()->NumEnemies() > 1 )
{
if ( !pEntity ) // if pEntity is NULL, test is against a point in space, so always to search against current enemy too
gm_bFindingCoverFromAllEnemies = true;
AIEnemiesIter_t iter;
for ( AI_EnemyInfo_t *pEnemyInfo = GetEnemies()->GetFirst(&iter); pEnemyInfo != NULL; pEnemyInfo = GetEnemies()->GetNext(&iter) )
{
CBaseEntity *pEnemy = pEnemyInfo->hEnemy;
if ( pEnemy )
{
if ( pEnemy != GetEnemy() )
{
if ( pEnemyInfo->timeAtFirstHand == AI_INVALID_TIME || gpGlobals->curtime - pEnemyInfo->timeLastSeen > 10.0 )
continue;
gm_bFindingCoverFromAllEnemies = true;
}
g_MultiCoverSearchEnemies.AddToTail( pEnemyInfo );
}
}
if ( g_MultiCoverSearchEnemies.Count() == 0 )
{
gm_bFindingCoverFromAllEnemies = false;
}
else if ( gm_bFindingCoverFromAllEnemies )
{
g_MultiCoverSearchEnemies.Sort( MultiCoverCompare );
Assert( g_MultiCoverSearchEnemies[0]->hEnemy == GetEnemy() );
}
}
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::CleanupCoverSearch()
{
gm_fCoverSearchType = CT_NORMAL;
g_MultiCoverSearchEnemies.RemoveAll();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::FindCoverPos( CBaseEntity *pEntity, Vector *pResult)
{
AI_PROFILE_SCOPE(CNPC_PlayerCompanion_FindCoverPos);
ASSERT_NO_REENTRY();
bool result = false;
SetupCoverSearch( pEntity );
if ( gm_bFindingCoverFromAllEnemies )
{
result = BaseClass::FindCoverPos( pEntity, pResult );
gm_bFindingCoverFromAllEnemies = false;
}
if ( !result )
result = BaseClass::FindCoverPos( pEntity, pResult );
CleanupCoverSearch();
return result;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::FindCoverPosInRadius( CBaseEntity *pEntity, const Vector &goalPos, float coverRadius, Vector *pResult )
{
AI_PROFILE_SCOPE(CNPC_PlayerCompanion_FindCoverPosInRadius);
ASSERT_NO_REENTRY();
bool result = false;
SetupCoverSearch( pEntity );
if ( gm_bFindingCoverFromAllEnemies )
{
result = BaseClass::FindCoverPosInRadius( pEntity, goalPos, coverRadius, pResult );
gm_bFindingCoverFromAllEnemies = false;
}
if ( !result )
{
result = BaseClass::FindCoverPosInRadius( pEntity, goalPos, coverRadius, pResult );
}
CleanupCoverSearch();
return result;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::FindCoverPos( CSound *pSound, Vector *pResult )
{
AI_PROFILE_SCOPE(CNPC_PlayerCompanion_FindCoverPos);
bool result = false;
bool bIsMortar = ( pSound->SoundContext() == SOUND_CONTEXT_MORTAR );
SetupCoverSearch( NULL );
if ( gm_bFindingCoverFromAllEnemies )
{
result = ( bIsMortar ) ? FindMortarCoverPos( pSound, pResult ) :
BaseClass::FindCoverPos( pSound, pResult );
gm_bFindingCoverFromAllEnemies = false;
}
if ( !result )
{
result = ( bIsMortar ) ? FindMortarCoverPos( pSound, pResult ) :
BaseClass::FindCoverPos( pSound, pResult );
}
CleanupCoverSearch();
return result;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::FindMortarCoverPos( CSound *pSound, Vector *pResult )
{
bool result = false;
Assert( pSound->SoundContext() == SOUND_CONTEXT_MORTAR );
gm_fCoverSearchType = CT_MORTAR;
result = GetTacticalServices()->FindLateralCover( pSound->GetSoundOrigin(), 0, pResult );
if ( !result )
{
result = GetTacticalServices()->FindCoverPos( pSound->GetSoundOrigin(),
pSound->GetSoundOrigin(),
0,
CoverRadius(),
pResult );
}
gm_fCoverSearchType = CT_NORMAL;
return result;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsCoverPosition( const Vector &vecThreat, const Vector &vecPosition )
{
if ( gm_bFindingCoverFromAllEnemies )
{
for ( int i = 0; i < g_MultiCoverSearchEnemies.Count(); i++ )
{
// @TODO (toml 07-27-04): Should skip checking points near already checked points
AI_EnemyInfo_t *pEnemyInfo = g_MultiCoverSearchEnemies[i];
Vector testPos;
CBaseEntity *pEnemy = pEnemyInfo->hEnemy;
if ( !pEnemy )
continue;
if ( pEnemy == GetEnemy() || IsMortar( pEnemy ) || IsSniper( pEnemy ) || i < MAX_NON_SPECIAL_MULTICOVER )
{
testPos = pEnemyInfo->vLastKnownLocation + pEnemy->GetViewOffset();
}
else
break;
gm_bFindingCoverFromAllEnemies = false;
bool result = IsCoverPosition( testPos, vecPosition );
gm_bFindingCoverFromAllEnemies = true;
if ( !result )
return false;
}
if ( gm_fCoverSearchType != CT_MORTAR && GetEnemy() && vecThreat.DistToSqr( GetEnemy()->EyePosition() ) < 1 )
return true;
// else fall through
}
if ( gm_fCoverSearchType == CT_TURRET && GetEnemy() && IsSafeFromFloorTurret( vecPosition, GetEnemy() ) )
{
return true;
}
if ( gm_fCoverSearchType == CT_MORTAR )
{
CSound *pSound = GetBestSound( SOUND_DANGER );
Assert ( pSound && pSound->SoundContext() == SOUND_CONTEXT_MORTAR );
if( pSound )
{
// Don't get closer to the shell
Vector vecToSound = vecThreat - GetAbsOrigin();
Vector vecToPosition = vecPosition - GetAbsOrigin();
VectorNormalize( vecToPosition );
VectorNormalize( vecToSound );
if ( vecToPosition.AsVector2D().Dot( vecToSound.AsVector2D() ) > 0 )
return false;
// Anything outside the radius is okay
float flDistSqr = (vecPosition - vecThreat).Length2DSqr();
float radiusSq = Square( pSound->Volume() );
if( flDistSqr > radiusSq )
{
return true;
}
}
}
return BaseClass::IsCoverPosition( vecThreat, vecPosition );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsMortar( CBaseEntity *pEntity )
{
if ( !pEntity )
return false;
CBaseEntity *pEntityParent = pEntity->GetParent();
return ( pEntityParent && pEntityParent->GetClassname() == STRING(gm_iszMortarClassname) );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsSniper( CBaseEntity *pEntity )
{
if ( !pEntity )
return false;
return ( pEntity->Classify() == CLASS_PROTOSNIPER );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsTurret( CBaseEntity *pEntity )
{
if ( !pEntity )
return false;
const char *pszClassname = pEntity->GetClassname();
return ( pszClassname == STRING(gm_iszFloorTurretClassname) || pszClassname == STRING(gm_iszGroundTurretClassname) );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsGunship( CBaseEntity *pEntity )
{
if( !pEntity )
return false;
return (pEntity->Classify() == CLASS_COMBINE_GUNSHIP );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CNPC_PlayerCompanion::OnTakeDamage_Alive( const CTakeDamageInfo &info )
{
if( info.GetAttacker() )
{
bool bIsEnvFire;
if( ( bIsEnvFire = FClassnameIs( info.GetAttacker(), "env_fire" ) ) != false || FClassnameIs( info.GetAttacker(), "entityflame" ) || FClassnameIs( info.GetAttacker(), "env_entity_igniter" ) )
{
GetMotor()->SetIdealYawToTarget( info.GetAttacker()->GetAbsOrigin() );
SetCondition( COND_PC_HURTBYFIRE );
}
// @Note (toml 07-25-04): there isn't a good solution to player companions getting injured by
// fires that have huge damage radii that extend outside the rendered
// fire. Recovery from being injured by fire will also not be done
// before we ship/ Here we trade one bug (guys standing around dying
// from flames they appear to not be near), for a lesser one
// this guy was standing in a fire and didn't react. Since
// the levels are supposed to have the centers of all the fires
// npc clipped, this latter case should be rare.
if ( bIsEnvFire )
{
if ( ( GetAbsOrigin() - info.GetAttacker()->GetAbsOrigin() ).Length2DSqr() > Square(12 + GetHullWidth() * .5 ) )
{
return 0;
}
}
}
return BaseClass::OnTakeDamage_Alive( info );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::OnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttackerEnt )
{
AI_PROFILE_SCOPE( CNPC_PlayerCompanion_OnFriendDamaged );
BaseClass::OnFriendDamaged( pSquadmate, pAttackerEnt );
CAI_BaseNPC *pAttacker = pAttackerEnt->MyNPCPointer();
if ( pAttacker )
{
bool bDirect = ( pSquadmate->FInViewCone(pAttacker) &&
( ( pSquadmate->IsPlayer() && HasCondition(COND_SEE_PLAYER) ) ||
( pSquadmate->MyNPCPointer() && pSquadmate->MyNPCPointer()->IsPlayerAlly() &&
GetSenses()->DidSeeEntity( pSquadmate ) ) ) );
if ( bDirect )
{
UpdateEnemyMemory( pAttacker, pAttacker->GetAbsOrigin(), pSquadmate );
}
else
{
if ( FVisible( pSquadmate ) )
{
AI_EnemyInfo_t *pInfo = GetEnemies()->Find( pAttacker );
if ( !pInfo || ( gpGlobals->curtime - pInfo->timeLastSeen ) > 15.0 )
UpdateEnemyMemory( pAttacker, pSquadmate->GetAbsOrigin(), pSquadmate );
}
}
CBasePlayer *pPlayer = AI_GetSinglePlayer();
if ( pPlayer && IsInPlayerSquad() && ( pPlayer->GetAbsOrigin().AsVector2D() - GetAbsOrigin().AsVector2D() ).LengthSqr() < Square( 25*12 ) && IsAllowedToSpeak( TLK_WATCHOUT ) )
{
if ( !pPlayer->FInViewCone( pAttacker ) )
{
Vector2D vPlayerDir = pPlayer->EyeDirection2D().AsVector2D();
Vector2D vEnemyDir = pAttacker->EyePosition().AsVector2D() - pPlayer->EyePosition().AsVector2D();
vEnemyDir.NormalizeInPlace();
float dot = vPlayerDir.Dot( vEnemyDir );
if ( dot < 0 )
Speak( TLK_WATCHOUT, "dangerloc:behind" );
else if ( ( pPlayer->GetAbsOrigin().AsVector2D() - pAttacker->GetAbsOrigin().AsVector2D() ).LengthSqr() > Square( 40*12 ) )
Speak( TLK_WATCHOUT, "dangerloc:far" );
}
else if ( pAttacker->GetAbsOrigin().z - pPlayer->GetAbsOrigin().z > 128 )
{
Speak( TLK_WATCHOUT, "dangerloc:above" );
}
else if ( pAttacker->GetHullType() <= HULL_TINY && ( pPlayer->GetAbsOrigin().AsVector2D() - pAttacker->GetAbsOrigin().AsVector2D() ).LengthSqr() > Square( 100*12 ) )
{
Speak( TLK_WATCHOUT, "dangerloc:far" );
}
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsValidMoveAwayDest( const Vector &vecDest )
{
// Don't care what the destination is unless I have an enemy and
// that enemy is a sniper (for now).
if( !GetEnemy() )
{
return true;
}
if( GetEnemy()->Classify() != CLASS_PROTOSNIPER )
{
return true;
}
if( IsCoverPosition( GetEnemy()->EyePosition(), vecDest + GetViewOffset() ) )
{
return true;
}
return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::FValidateHintType( CAI_Hint *pHint )
{
switch( pHint->HintType() )
{
case HINT_PLAYER_SQUAD_TRANSITON_POINT:
case HINT_WORLD_VISUALLY_INTERESTING_DONT_AIM:
case HINT_PLAYER_ALLY_MOVE_AWAY_DEST:
case HINT_PLAYER_ALLY_FEAR_DEST:
return true;
break;
default:
break;
}
return BaseClass::FValidateHintType( pHint );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::ValidateNavGoal()
{
bool result;
if ( GetNavigator()->GetGoalType() == GOALTYPE_COVER )
{
if ( IsEnemyTurret() )
gm_fCoverSearchType = CT_TURRET;
}
result = BaseClass::ValidateNavGoal();
gm_fCoverSearchType = CT_NORMAL;
return result;
}
const float AVOID_TEST_DIST = 18.0f*12.0f;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#define COMPANION_EPISODIC_AVOID_ENTITY_FLAME_RADIUS 18.0f
bool CNPC_PlayerCompanion::OverrideMove( float flInterval )
{
bool overrode = BaseClass::OverrideMove( flInterval );
if ( !overrode && GetNavigator()->GetGoalType() != GOALTYPE_NONE )
{
string_t iszEnvFire = AllocPooledString( "env_fire" );
string_t iszBounceBomb = AllocPooledString( "combine_mine" );
#ifdef HL2_EPISODIC
string_t iszNPCTurretFloor = AllocPooledString( "npc_turret_floor" );
string_t iszEntityFlame = AllocPooledString( "entityflame" );
#endif // HL2_EPISODIC
if ( IsCurSchedule( SCHED_TAKE_COVER_FROM_BEST_SOUND ) )
{
CSound *pSound = GetBestSound( SOUND_DANGER );
if( pSound && pSound->SoundContext() == SOUND_CONTEXT_MORTAR )
{
// Try not to get any closer to the center
GetLocalNavigator()->AddObstacle( pSound->GetSoundOrigin(), (pSound->GetSoundOrigin() - GetAbsOrigin()).Length2D() * 0.5, AIMST_AVOID_DANGER );
}
}
CBaseEntity *pEntity = NULL;
trace_t tr;
// For each possible entity, compare our known interesting classnames to its classname, via ID
while( ( pEntity = OverrideMoveCache_FindTargetsInRadius( pEntity, GetAbsOrigin(), AVOID_TEST_DIST ) ) != NULL )
{
// Handle each type
if ( pEntity->m_iClassname == iszEnvFire )
{
Vector vMins, vMaxs;
if ( FireSystem_GetFireDamageDimensions( pEntity, &vMins, &vMaxs ) )
{
UTIL_TraceLine( WorldSpaceCenter(), pEntity->WorldSpaceCenter(), MASK_FIRE_SOLID, pEntity, COLLISION_GROUP_NONE, &tr );
if (tr.fraction == 1.0 && !tr.startsolid)
{
GetLocalNavigator()->AddObstacle( pEntity->GetAbsOrigin(), ( ( vMaxs.x - vMins.x ) * 1.414 * 0.5 ) + 6.0, AIMST_AVOID_DANGER );
}
}
}
#ifdef HL2_EPISODIC
else if ( pEntity->m_iClassname == iszNPCTurretFloor )
{
UTIL_TraceLine( WorldSpaceCenter(), pEntity->WorldSpaceCenter(), MASK_BLOCKLOS, pEntity, COLLISION_GROUP_NONE, &tr );
if (tr.fraction == 1.0 && !tr.startsolid)
{
float radius = 1.4 * pEntity->CollisionProp()->BoundingRadius2D();
GetLocalNavigator()->AddObstacle( pEntity->WorldSpaceCenter(), radius, AIMST_AVOID_OBJECT );
}
}
else if( pEntity->m_iClassname == iszEntityFlame && pEntity->GetParent() && !pEntity->GetParent()->IsNPC() )
{
float flDist = pEntity->WorldSpaceCenter().DistTo( WorldSpaceCenter() );
if( flDist > COMPANION_EPISODIC_AVOID_ENTITY_FLAME_RADIUS )
{
// If I'm not in the flame, prevent me from getting close to it.
// If I AM in the flame, avoid placing an obstacle until the flame frightens me away from itself.
UTIL_TraceLine( WorldSpaceCenter(), pEntity->WorldSpaceCenter(), MASK_BLOCKLOS, pEntity, COLLISION_GROUP_NONE, &tr );
if (tr.fraction == 1.0 && !tr.startsolid)
{
GetLocalNavigator()->AddObstacle( pEntity->WorldSpaceCenter(), COMPANION_EPISODIC_AVOID_ENTITY_FLAME_RADIUS, AIMST_AVOID_OBJECT );
}
}
}
#endif // HL2_EPISODIC
else if ( pEntity->m_iClassname == iszBounceBomb )
{
CBounceBomb *pBomb = static_cast<CBounceBomb *>(pEntity);
if ( pBomb && !pBomb->IsPlayerPlaced() && pBomb->IsAwake() )
{
UTIL_TraceLine( WorldSpaceCenter(), pEntity->WorldSpaceCenter(), MASK_BLOCKLOS, pEntity, COLLISION_GROUP_NONE, &tr );
if (tr.fraction == 1.0 && !tr.startsolid)
{
GetLocalNavigator()->AddObstacle( pEntity->GetAbsOrigin(), BOUNCEBOMB_DETONATE_RADIUS * .8, AIMST_AVOID_DANGER );
}
}
}
}
}
return overrode;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::MovementCost( int moveType, const Vector &vecStart, const Vector &vecEnd, float *pCost )
{
bool bResult = BaseClass::MovementCost( moveType, vecStart, vecEnd, pCost );
if ( moveType == bits_CAP_MOVE_GROUND )
{
if ( IsCurSchedule( SCHED_TAKE_COVER_FROM_BEST_SOUND ) )
{
CSound *pSound = GetBestSound( SOUND_DANGER );
if( pSound && (pSound->SoundContext() & (SOUND_CONTEXT_MORTAR|SOUND_CONTEXT_FROM_SNIPER)) )
{
Vector vecToSound = pSound->GetSoundReactOrigin() - GetAbsOrigin();
Vector vecToPosition = vecEnd - GetAbsOrigin();
VectorNormalize( vecToPosition );
VectorNormalize( vecToSound );
if ( vecToPosition.AsVector2D().Dot( vecToSound.AsVector2D() ) > 0 )
{
*pCost *= 1.5;
bResult = true;
}
}
}
if ( m_bWeightPathsInCover && GetEnemy() )
{
if ( BaseClass::IsCoverPosition( GetEnemy()->EyePosition(), vecEnd ) )
{
*pCost *= 0.1;
bResult = true;
}
}
}
return bResult;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
float CNPC_PlayerCompanion::GetIdealSpeed() const
{
float baseSpeed = BaseClass::GetIdealSpeed();
if ( baseSpeed < m_flBoostSpeed )
return m_flBoostSpeed;
return baseSpeed;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
float CNPC_PlayerCompanion::GetIdealAccel() const
{
float multiplier = 1.0;
if ( AI_IsSinglePlayer() )
{
if ( m_bMovingAwayFromPlayer && (UTIL_PlayerByIndex(1)->GetAbsOrigin() - GetAbsOrigin()).Length2DSqr() < Square(3.0*12.0) )
multiplier = 2.0;
}
return BaseClass::GetIdealAccel() * multiplier;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::OnObstructionPreSteer( AILocalMoveGoal_t *pMoveGoal, float distClear, AIMoveResult_t *pResult )
{
if ( pMoveGoal->directTrace.flTotalDist - pMoveGoal->directTrace.flDistObstructed < GetHullWidth() * 1.5 )
{
CAI_BaseNPC *pBlocker = pMoveGoal->directTrace.pObstruction->MyNPCPointer();
if ( pBlocker && pBlocker->IsPlayerAlly() && !pBlocker->IsMoving() && !pBlocker->IsInAScript() &&
( IsCurSchedule( SCHED_NEW_WEAPON ) ||
IsCurSchedule( SCHED_GET_HEALTHKIT ) ||
pBlocker->IsCurSchedule( SCHED_FAIL ) ||
( IsInPlayerSquad() && !pBlocker->IsInPlayerSquad() ) ||
Classify() == CLASS_PLAYER_ALLY_VITAL ||
IsInAScript() ) )
{
if ( pBlocker->ConditionInterruptsCurSchedule( COND_GIVE_WAY ) ||
pBlocker->ConditionInterruptsCurSchedule( COND_PLAYER_PUSHING ) )
{
// HACKHACK
pBlocker->GetMotor()->SetIdealYawToTarget( WorldSpaceCenter() );
pBlocker->SetSchedule( SCHED_MOVE_AWAY );
}
}
}
if ( pMoveGoal->directTrace.pObstruction )
{
}
return BaseClass::OnObstructionPreSteer( pMoveGoal, distClear, pResult );
}
//-----------------------------------------------------------------------------
// Purpose: Whether or not we should always transition with the player
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::ShouldAlwaysTransition( void )
{
// No matter what, come through
if ( m_bAlwaysTransition )
return true;
// Squadmates always come with
if ( IsInPlayerSquad() )
return true;
// If we're following the player, then come along
if ( GetFollowBehavior().GetFollowTarget() && GetFollowBehavior().GetFollowTarget()->IsPlayer() )
return true;
return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputOutsideTransition( inputdata_t &inputdata )
{
if ( !AI_IsSinglePlayer() )
return;
// Must want to do this
if ( ShouldAlwaysTransition() == false )
return;
// If we're in a vehicle, that vehicle will transition with us still inside (which is preferable)
if ( IsInAVehicle() )
return;
CBaseEntity *pPlayer = UTIL_GetLocalPlayer();
const Vector &playerPos = pPlayer->GetAbsOrigin();
// Mark us as already having succeeded if we're vital or always meant to come with the player
bool bAlwaysTransition = ( ( Classify() == CLASS_PLAYER_ALLY_VITAL ) || m_bAlwaysTransition );
bool bPathToPlayer = bAlwaysTransition;
if ( bAlwaysTransition == false )
{
AI_Waypoint_t *pPathToPlayer = GetPathfinder()->BuildRoute( GetAbsOrigin(), playerPos, pPlayer, 0 );
if ( pPathToPlayer )
{
bPathToPlayer = true;
CAI_Path tempPath;
tempPath.SetWaypoints( pPathToPlayer ); // path object will delete waypoints
GetPathfinder()->UnlockRouteNodes( pPathToPlayer );
}
}
#ifdef USE_PATHING_LENGTH_REQUIREMENT_FOR_TELEPORT
float pathLength = tempPath.GetPathDistanceToGoal( GetAbsOrigin() );
if ( pathLength > 150 * 12 )
return;
#endif
bool bMadeIt = false;
Vector teleportLocation;
CAI_Hint *pHint = CAI_HintManager::FindHint( this, HINT_PLAYER_SQUAD_TRANSITON_POINT, bits_HINT_NODE_NEAREST, PLAYERCOMPANION_TRANSITION_SEARCH_DISTANCE, &playerPos );
while ( pHint )
{
pHint->Lock(this);
pHint->Unlock(0.5); // prevent other squadmates and self from using during transition.
pHint->GetPosition( GetHullType(), &teleportLocation );
if ( GetNavigator()->CanFitAtPosition( teleportLocation, MASK_NPCSOLID ) )
{
bMadeIt = true;
if ( !bPathToPlayer && ( playerPos - GetAbsOrigin() ).LengthSqr() > Square(40*12) )
{
AI_Waypoint_t *pPathToTeleport = GetPathfinder()->BuildRoute( GetAbsOrigin(), teleportLocation, pPlayer, 0 );
if ( !pPathToTeleport )
{
DevMsg( 2, "NPC \"%s\" failed to teleport to transition a point because there is no path\n", STRING(GetEntityName()) );
bMadeIt = false;
}
else
{
CAI_Path tempPath;
GetPathfinder()->UnlockRouteNodes( pPathToTeleport );
tempPath.SetWaypoints( pPathToTeleport ); // path object will delete waypoints
}
}
if ( bMadeIt )
{
DevMsg( 2, "NPC \"%s\" teleported to transition point %d\n", STRING(GetEntityName()), pHint->GetNodeId() );
break;
}
}
else
{
if ( g_debug_transitions.GetBool() )
{
NDebugOverlay::Box( teleportLocation, GetHullMins(), GetHullMaxs(), 255,0,0, 8, 999 );
}
}
pHint = CAI_HintManager::FindHint( this, HINT_PLAYER_SQUAD_TRANSITON_POINT, bits_HINT_NODE_NEAREST, PLAYERCOMPANION_TRANSITION_SEARCH_DISTANCE, &playerPos );
}
if ( !bMadeIt )
{
// Force us if we didn't find a normal route
if ( bAlwaysTransition )
{
bMadeIt = FindSpotForNPCInRadius( &teleportLocation, pPlayer->GetAbsOrigin(), this, 32.0*1.414, true );
if ( !bMadeIt )
bMadeIt = FindSpotForNPCInRadius( &teleportLocation, pPlayer->GetAbsOrigin(), this, 32.0*1.414, false );
}
}
if ( bMadeIt )
{
Teleport( &teleportLocation, NULL, NULL );
}
else
{
DevMsg( 2, "NPC \"%s\" failed to find a suitable transition a point\n", STRING(GetEntityName()) );
}
BaseClass::InputOutsideTransition( inputdata );
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputSetReadinessPanic( inputdata_t &inputdata )
{
SetReadinessLevel( AIRL_PANIC, true, true );
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputSetReadinessStealth( inputdata_t &inputdata )
{
SetReadinessLevel( AIRL_STEALTH, true, true );
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputSetReadinessLow( inputdata_t &inputdata )
{
SetReadinessLevel( AIRL_RELAXED, true, true );
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputSetReadinessMedium( inputdata_t &inputdata )
{
SetReadinessLevel( AIRL_STIMULATED, true, true );
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputSetReadinessHigh( inputdata_t &inputdata )
{
SetReadinessLevel( AIRL_AGITATED, true, true );
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputLockReadiness( inputdata_t &inputdata )
{
float value = inputdata.value.Float();
LockReadiness( value );
}
//-----------------------------------------------------------------------------
// Purpose: Locks the readiness state of the NCP
// Input : time - if -1, the lock is effectively infinite
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::LockReadiness( float duration )
{
if ( duration == -1.0f )
{
m_flReadinessLockedUntil = FLT_MAX;
}
else
{
m_flReadinessLockedUntil = gpGlobals->curtime + duration;
}
}
//-----------------------------------------------------------------------------
// Purpose: Unlocks the readiness state
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::UnlockReadiness( void )
{
// Set to the past
m_flReadinessLockedUntil = gpGlobals->curtime - 0.1f;
}
//------------------------------------------------------------------------------
#ifdef HL2_EPISODIC
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::ShouldDeferToPassengerBehavior( void )
{
if ( m_PassengerBehavior.CanSelectSchedule() )
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Determines if this player companion is capable of entering a vehicle
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::CanEnterVehicle( void )
{
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::CanExitVehicle( void )
{
// See if we can exit our vehicle
CPropJeepEpisodic *pVehicle = dynamic_cast<CPropJeepEpisodic *>(m_PassengerBehavior.GetTargetVehicle());
if ( pVehicle != NULL && pVehicle->NPC_CanExitVehicle( this, true ) == false )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *lpszVehicleName -
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::EnterVehicle( CBaseEntity *pEntityVehicle, bool bImmediately )
{
// Must be allowed to do this
if ( CanEnterVehicle() == false )
return;
// Find the target vehicle
CPropJeepEpisodic *pVehicle = dynamic_cast<CPropJeepEpisodic *>(pEntityVehicle);
// Get in the car if it's valid
if ( pVehicle != NULL && pVehicle->NPC_CanEnterVehicle( this, true ) )
{
// Set her into a "passenger" behavior
m_PassengerBehavior.Enable( pVehicle, bImmediately );
m_PassengerBehavior.EnterVehicle();
// Only do this if we're outside the vehicle
if ( m_PassengerBehavior.GetPassengerState() == PASSENGER_STATE_OUTSIDE )
{
SetCondition( COND_PC_BECOMING_PASSENGER );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Get into the requested vehicle
// Input : &inputdata - contains the entity name of the vehicle to enter
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputEnterVehicle( inputdata_t &inputdata )
{
CBaseEntity *pEntity = FindNamedEntity( inputdata.value.String() );
EnterVehicle( pEntity, false );
}
//-----------------------------------------------------------------------------
// Purpose: Get into the requested vehicle immediately (no animation, pop)
// Input : &inputdata - contains the entity name of the vehicle to enter
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputEnterVehicleImmediately( inputdata_t &inputdata )
{
CBaseEntity *pEntity = FindNamedEntity( inputdata.value.String() );
EnterVehicle( pEntity, true );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputExitVehicle( inputdata_t &inputdata )
{
// See if we're allowed to exit the vehicle
if ( CanExitVehicle() == false )
return;
m_PassengerBehavior.ExitVehicle();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputCancelEnterVehicle( inputdata_t &inputdata )
{
m_PassengerBehavior.CancelEnterVehicle();
}
//-----------------------------------------------------------------------------
// Purpose: Forces the NPC out of the vehicle they're riding in
// Input : bImmediate - If we need to exit immediately, teleport to any exit location
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::ExitVehicle( void )
{
// For now just get out
m_PassengerBehavior.ExitVehicle();
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsInAVehicle( void ) const
{
// Must be active and getting in/out of vehicle
if ( m_PassengerBehavior.IsEnabled() && m_PassengerBehavior.GetPassengerState() != PASSENGER_STATE_OUTSIDE )
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : IServerVehicle -
//-----------------------------------------------------------------------------
IServerVehicle *CNPC_PlayerCompanion::GetVehicle( void )
{
if ( IsInAVehicle() )
{
CPropVehicleDriveable *pDriveableVehicle = m_PassengerBehavior.GetTargetVehicle();
if ( pDriveableVehicle != NULL )
return pDriveableVehicle->GetServerVehicle();
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : CBaseEntity
//-----------------------------------------------------------------------------
CBaseEntity *CNPC_PlayerCompanion::GetVehicleEntity( void )
{
if ( IsInAVehicle() )
{
CPropVehicleDriveable *pDriveableVehicle = m_PassengerBehavior.GetTargetVehicle();
return pDriveableVehicle;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Override our efficiency so that we don't jitter when we're in the middle
// of our enter/exit animations.
// Input : bInPVS - Whether we're in the PVS or not
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::UpdateEfficiency( bool bInPVS )
{
// If we're transitioning and in the PVS, we override our efficiency
if ( IsInAVehicle() && bInPVS )
{
PassengerState_e nState = m_PassengerBehavior.GetPassengerState();
if ( nState == PASSENGER_STATE_ENTERING || nState == PASSENGER_STATE_EXITING )
{
SetEfficiency( AIE_NORMAL );
return;
}
}
// Do the default behavior
BaseClass::UpdateEfficiency( bInPVS );
}
//-----------------------------------------------------------------------------
// Purpose: Whether or not we can dynamically interact with another NPC
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::CanRunAScriptedNPCInteraction( bool bForced /*= false*/ )
{
// TODO: Allow this but only for interactions who stem from being in a vehicle?
if ( IsInAVehicle() )
return false;
return BaseClass::CanRunAScriptedNPCInteraction( bForced );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsAllowedToDodge( void )
{
// TODO: Allow this but only for interactions who stem from being in a vehicle?
if ( IsInAVehicle() )
return false;
return BaseClass::IsAllowedToDodge();
}
#endif //HL2_EPISODIC
//------------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Purpose: Always transition along with the player
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputEnableAlwaysTransition( inputdata_t &inputdata )
{
m_bAlwaysTransition = true;
}
//-----------------------------------------------------------------------------
// Purpose: Stop always transitioning along with the player
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputDisableAlwaysTransition( inputdata_t &inputdata )
{
m_bAlwaysTransition = false;
}
//-----------------------------------------------------------------------------
// Purpose: Stop picking up weapons from the ground
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputEnableWeaponPickup( inputdata_t &inputdata )
{
m_bDontPickupWeapons = false;
}
//-----------------------------------------------------------------------------
// Purpose: Return to default behavior of picking up better weapons on the ground
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputDisableWeaponPickup( inputdata_t &inputdata )
{
m_bDontPickupWeapons = true;
}
//------------------------------------------------------------------------------
// Purpose: Give the NPC in question the weapon specified
//------------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputGiveWeapon( inputdata_t &inputdata )
{
// Give the NPC the specified weapon
string_t iszWeaponName = inputdata.value.StringID();
if ( iszWeaponName != NULL_STRING )
{
if( Classify() == CLASS_PLAYER_ALLY_VITAL )
{
m_iszPendingWeapon = iszWeaponName;
}
else
{
GiveWeapon( iszWeaponName );
}
}
}
#if HL2_EPISODIC
//------------------------------------------------------------------------------
// Purpose: Delete all outputs from this NPC.
//------------------------------------------------------------------------------
void CNPC_PlayerCompanion::InputClearAllOuputs( inputdata_t &inputdata )
{
datamap_t *dmap = GetDataDescMap();
while ( dmap )
{
int fields = dmap->dataNumFields;
for ( int i = 0; i < fields; i++ )
{
typedescription_t *dataDesc = &dmap->dataDesc[i];
if ( ( dataDesc->fieldType == FIELD_CUSTOM ) && ( dataDesc->flags & FTYPEDESC_OUTPUT ) )
{
CBaseEntityOutput *pOutput = (CBaseEntityOutput *)((int)this + (int)dataDesc->fieldOffset[0]);
pOutput->DeleteAllElements();
/*
int nConnections = pOutput->NumberOfElements();
for ( int j = 0; j < nConnections; j++ )
{
}
*/
}
}
dmap = dmap->baseMap;
}
}
#endif
//-----------------------------------------------------------------------------
// Purpose: Player in our squad killed something
// Input : *pVictim - Who he killed
// &info - How they died
//-----------------------------------------------------------------------------
void CNPC_PlayerCompanion::OnPlayerKilledOther( CBaseEntity *pVictim, const CTakeDamageInfo &info )
{
// filter everything that comes in here that isn't an NPC
CAI_BaseNPC *pCombatVictim = dynamic_cast<CAI_BaseNPC *>( pVictim );
if ( !pCombatVictim )
{
return;
}
CBaseEntity *pInflictor = info.GetInflictor();
int iNumBarrels = 0;
int iConsecutivePlayerKills = 0;
bool bPuntedGrenade = false;
bool bVictimWasEnemy = false;
bool bVictimWasMob = false;
bool bVictimWasAttacker = false;
bool bHeadshot = false;
bool bOneShot = false;
if ( dynamic_cast<CBreakableProp *>( pInflictor ) && ( info.GetDamageType() & DMG_BLAST ) )
{
// if a barrel explodes that was initiated by the player within a few seconds of the previous one,
// increment a counter to keep track of how many have exploded in a row.
if ( gpGlobals->curtime - m_fLastBarrelExploded >= MAX_TIME_BETWEEN_BARRELS_EXPLODING )
{
m_iNumConsecutiveBarrelsExploded = 0;
}
m_iNumConsecutiveBarrelsExploded++;
m_fLastBarrelExploded = gpGlobals->curtime;
iNumBarrels = m_iNumConsecutiveBarrelsExploded;
}
else
{
// if player kills an NPC within a few seconds of the previous kill,
// increment a counter to keep track of how many he's killed in a row.
if ( gpGlobals->curtime - m_fLastPlayerKill >= MAX_TIME_BETWEEN_CONSECUTIVE_PLAYER_KILLS )
{
m_iNumConsecutivePlayerKills = 0;
}
m_iNumConsecutivePlayerKills++;
m_fLastPlayerKill = gpGlobals->curtime;
iConsecutivePlayerKills = m_iNumConsecutivePlayerKills;
}
// don't comment on kills when she can't see the victim
if ( !FVisible( pVictim ) )
{
return;
}
// check if the player killed an enemy by punting a grenade
if ( pInflictor && Fraggrenade_WasPunted( pInflictor ) && Fraggrenade_WasCreatedByCombine( pInflictor ) )
{
bPuntedGrenade = true;
}
// check if the victim was Alyx's enemy
if ( GetEnemy() == pVictim )
{
bVictimWasEnemy = true;
}
AI_EnemyInfo_t *pEMemory = GetEnemies()->Find( pVictim );
if ( pEMemory != NULL )
{
// was Alyx being mobbed by this enemy?
bVictimWasMob = pEMemory->bMobbedMe;
// has Alyx recieved damage from this enemy?
if ( pEMemory->timeLastReceivedDamageFrom > 0 ) {
bVictimWasAttacker = true;
}
}
// Was it a headshot?
if ( ( pCombatVictim->LastHitGroup() == HITGROUP_HEAD ) && ( info.GetDamageType() & DMG_BULLET ) )
{
bHeadshot = true;
}
// Did the player kill the enemy with 1 shot?
if ( ( pCombatVictim->GetDamageCount() == 1 ) && ( info.GetDamageType() & DMG_BULLET ) )
{
bOneShot = true;
}
// set up the speech modifiers
CFmtStrN<512> modifiers( "num_barrels:%d,distancetoplayerenemy:%f,playerAmmo:%s,consecutive_player_kills:%d,"
"punted_grenade:%d,victim_was_enemy:%d,victim_was_mob:%d,victim_was_attacker:%d,headshot:%d,oneshot:%d",
iNumBarrels, EnemyDistance( pVictim ), info.GetAmmoName(), iConsecutivePlayerKills,
bPuntedGrenade, bVictimWasEnemy, bVictimWasMob, bVictimWasAttacker, bHeadshot, bOneShot );
SpeakIfAllowed( TLK_PLAYER_KILLED_NPC, modifiers );
BaseClass::OnPlayerKilledOther( pVictim, info );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_PlayerCompanion::IsNavigationUrgent( void )
{
bool bBase = BaseClass::IsNavigationUrgent();
// Consider follow & assault behaviour urgent
if ( !bBase && (m_FollowBehavior.IsActive() || ( m_AssaultBehavior.IsRunning() && m_AssaultBehavior.IsUrgent() )) && Classify() == CLASS_PLAYER_ALLY_VITAL )
{
// But only if the blocker isn't the player, and isn't a physics object that's still moving
CBaseEntity *pBlocker = GetNavigator()->GetBlockingEntity();
if ( pBlocker && !pBlocker->IsPlayer() )
{
IPhysicsObject *pPhysObject = pBlocker->VPhysicsGetObject();
if ( pPhysObject && !pPhysObject->IsAsleep() )
return false;
if ( pBlocker->IsNPC() )
return false;
}
// If we're within the player's viewcone, then don't teleport.
// This test was made more general because previous iterations had cases where characters
// could not see the player but the player could in fact see them. Now the NPC's facing is
// irrelevant and the player's viewcone is more authorative. -- jdw
CBasePlayer *pLocalPlayer = AI_GetSinglePlayer();
if ( pLocalPlayer->FInViewCone( EyePosition() ) )
return false;
return true;
}
return bBase;
}
//-----------------------------------------------------------------------------
//
// Schedules
//
//-----------------------------------------------------------------------------
AI_BEGIN_CUSTOM_NPC( player_companion_base, CNPC_PlayerCompanion )
// AI Interaction for being hit by a physics object
DECLARE_INTERACTION(g_interactionHitByPlayerThrownPhysObj)
DECLARE_INTERACTION(g_interactionPlayerPuntedHeavyObject)
DECLARE_CONDITION( COND_PC_HURTBYFIRE )
DECLARE_CONDITION( COND_PC_SAFE_FROM_MORTAR )
DECLARE_CONDITION( COND_PC_BECOMING_PASSENGER )
DECLARE_TASK( TASK_PC_WAITOUT_MORTAR )
DECLARE_TASK( TASK_PC_GET_PATH_OFF_COMPANION )
DECLARE_ANIMEVENT( AE_COMPANION_PRODUCE_FLARE )
DECLARE_ANIMEVENT( AE_COMPANION_LIGHT_FLARE )
DECLARE_ANIMEVENT( AE_COMPANION_RELEASE_FLARE )
//=========================================================
// > TakeCoverFromBestSound
//
// Find cover and move towards it, but only do so for a short
// time. This is appropriate when the dangerous item is going
// to detonate very soon. This way our NPC doesn't run a great
// distance from an object that explodes shortly after the NPC
// gets underway.
//=========================================================
DEFINE_SCHEDULE
(
SCHED_PC_MOVE_TOWARDS_COVER_FROM_BEST_SOUND,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_FLEE_FROM_BEST_SOUND"
" TASK_STOP_MOVING 0"
" TASK_SET_TOLERANCE_DISTANCE 24"
" TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION 0"
" TASK_FIND_COVER_FROM_BEST_SOUND 0"
" TASK_RUN_PATH_TIMED 1.0"
" TASK_STOP_MOVING 0"
" TASK_FACE_SAVEPOSITION 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" // Translated to cover
""
" Interrupts"
" COND_PC_SAFE_FROM_MORTAR"
)
DEFINE_SCHEDULE
(
SCHED_PC_TAKE_COVER_FROM_BEST_SOUND,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_FLEE_FROM_BEST_SOUND"
" TASK_STOP_MOVING 0"
" TASK_SET_TOLERANCE_DISTANCE 24"
" TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION 0"
" TASK_FIND_COVER_FROM_BEST_SOUND 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_STOP_MOVING 0"
" TASK_FACE_SAVEPOSITION 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" // Translated to cover
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_PC_SAFE_FROM_MORTAR"
)
DEFINE_SCHEDULE
(
SCHED_PC_COWER,
" Tasks"
" TASK_WAIT_RANDOM 0.1"
" TASK_SET_ACTIVITY ACTIVITY:ACT_COWER"
" TASK_PC_WAITOUT_MORTAR 0"
" TASK_WAIT 0.1"
" TASK_WAIT_RANDOM 0.5"
""
" Interrupts"
" "
)
//=========================================================
//
//=========================================================
DEFINE_SCHEDULE
(
SCHED_PC_FLEE_FROM_BEST_SOUND,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COWER"
" TASK_GET_PATH_AWAY_FROM_BEST_SOUND 600"
" TASK_RUN_PATH_TIMED 1.5"
" TASK_STOP_MOVING 0"
" TASK_TURN_LEFT 179"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_PC_SAFE_FROM_MORTAR"
)
//=========================================================
DEFINE_SCHEDULE
(
SCHED_PC_FAIL_TAKE_COVER_TURRET,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COWER"
" TASK_STOP_MOVING 0"
" TASK_MOVE_AWAY_PATH 600"
" TASK_RUN_PATH_FLEE 100"
" TASK_STOP_MOVING 0"
" TASK_TURN_LEFT 179"
""
" Interrupts"
" COND_NEW_ENEMY"
)
//=========================================================
DEFINE_SCHEDULE
(
SCHED_PC_FAKEOUT_MORTAR,
" Tasks"
" TASK_MOVE_AWAY_PATH 300"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
""
" Interrupts"
" COND_HEAR_DANGER"
)
//=========================================================
DEFINE_SCHEDULE
(
SCHED_PC_GET_OFF_COMPANION,
" Tasks"
" TASK_PC_GET_PATH_OFF_COMPANION 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
""
" Interrupts"
""
)
AI_END_CUSTOM_NPC()
//
// Special movement overrides for player companions
//
#define NUM_OVERRIDE_MOVE_CLASSNAMES 4
class COverrideMoveCache : public IEntityListener
{
public:
void LevelInitPreEntity( void )
{
CacheClassnames();
gEntList.AddListenerEntity( this );
Clear();
}
void LevelShutdownPostEntity( void )
{
gEntList.RemoveListenerEntity( this );
Clear();
}
inline void Clear( void )
{
m_Cache.Purge();
}
inline bool MatchesCriteria( CBaseEntity *pEntity )
{
for ( int i = 0; i < NUM_OVERRIDE_MOVE_CLASSNAMES; i++ )
{
if ( pEntity->m_iClassname == m_Classname[i] )
return true;
}
return false;
}
virtual void OnEntitySpawned( CBaseEntity *pEntity )
{
if ( MatchesCriteria( pEntity ) )
{
m_Cache.AddToTail( pEntity );
}
};
virtual void OnEntityDeleted( CBaseEntity *pEntity )
{
if ( !m_Cache.Count() )
return;
if ( MatchesCriteria( pEntity ) )
{
m_Cache.FindAndRemove( pEntity );
}
};
CBaseEntity *FindTargetsInRadius( CBaseEntity *pFirstEntity, const Vector &vecOrigin, float flRadius )
{
if ( !m_Cache.Count() )
return NULL;
int nIndex = m_Cache.InvalidIndex();
// If we're starting with an entity, start there and move past it
if ( pFirstEntity != NULL )
{
nIndex = m_Cache.Find( pFirstEntity );
nIndex = m_Cache.Next( nIndex );
if ( nIndex == m_Cache.InvalidIndex() )
return NULL;
}
else
{
nIndex = m_Cache.Head();
}
CBaseEntity *pTarget = NULL;
const float flRadiusSqr = Square( flRadius );
// Look through each cached target, looking for one in our range
while ( nIndex != m_Cache.InvalidIndex() )
{
pTarget = m_Cache[nIndex];
if ( pTarget && ( pTarget->GetAbsOrigin() - vecOrigin ).LengthSqr() < flRadiusSqr )
return pTarget;
nIndex = m_Cache.Next( nIndex );
}
return NULL;
}
void ForceRepopulateList( void )
{
Clear();
CacheClassnames();
CBaseEntity *pEnt = gEntList.FirstEnt();
while( pEnt )
{
if( MatchesCriteria( pEnt ) )
{
m_Cache.AddToTail( pEnt );
}
pEnt = gEntList.NextEnt( pEnt );
}
}
private:
inline void CacheClassnames( void )
{
m_Classname[0] = AllocPooledString( "env_fire" );
m_Classname[1] = AllocPooledString( "combine_mine" );
m_Classname[2] = AllocPooledString( "npc_turret_floor" );
m_Classname[3] = AllocPooledString( "entityflame" );
}
CUtlLinkedList<EHANDLE> m_Cache;
string_t m_Classname[NUM_OVERRIDE_MOVE_CLASSNAMES];
};
// Singleton for access
COverrideMoveCache g_OverrideMoveCache;
COverrideMoveCache *OverrideMoveCache( void ) { return &g_OverrideMoveCache; }
CBaseEntity *OverrideMoveCache_FindTargetsInRadius( CBaseEntity *pFirstEntity, const Vector &vecOrigin, float flRadius )
{
return g_OverrideMoveCache.FindTargetsInRadius( pFirstEntity, vecOrigin, flRadius );
}
void OverrideMoveCache_ForceRepopulateList( void )
{
g_OverrideMoveCache.ForceRepopulateList();
}
void OverrideMoveCache_LevelInitPreEntity( void )
{
g_OverrideMoveCache.LevelInitPreEntity();
}
void OverrideMoveCache_LevelShutdownPostEntity( void )
{
g_OverrideMoveCache.LevelShutdownPostEntity();
}
| 412 | 0.989633 | 1 | 0.989633 | game-dev | MEDIA | 0.989939 | game-dev | 0.825436 | 1 | 0.825436 |
magefree/mage | 7,710 | Mage.Sets/src/mage/sets/AetherRevoltPromos.java | package mage.sets;
import mage.cards.ExpansionSet;
import mage.constants.Rarity;
import mage.constants.SetType;
/**
* https://scryfall.com/sets/paer
*/
public class AetherRevoltPromos extends ExpansionSet {
private static final AetherRevoltPromos instance = new AetherRevoltPromos();
public static AetherRevoltPromos getInstance() {
return instance;
}
private AetherRevoltPromos() {
super("Aether Revolt Promos", "PAER", ExpansionSet.buildDate(2017, 1, 21), SetType.PROMOTIONAL);
this.hasBoosters = false;
this.hasBasicLands = false;
cards.add(new SetCardInfo("Aethergeode Miner", "4s", Rarity.RARE, mage.cards.a.AethergeodeMiner.class));
cards.add(new SetCardInfo("Aethersphere Harvester", "142s", Rarity.RARE, mage.cards.a.AethersphereHarvester.class));
cards.add(new SetCardInfo("Aethertide Whale", "27s", Rarity.RARE, mage.cards.a.AethertideWhale.class));
cards.add(new SetCardInfo("Aetherwind Basker", "104s", Rarity.MYTHIC, mage.cards.a.AetherwindBasker.class));
cards.add(new SetCardInfo("Aid from the Cowl", "105s", Rarity.RARE, mage.cards.a.AidFromTheCowl.class));
cards.add(new SetCardInfo("Ajani Unyielding", "127s", Rarity.MYTHIC, mage.cards.a.AjaniUnyielding.class));
cards.add(new SetCardInfo("Baral's Expertise", "29s", Rarity.RARE, mage.cards.b.BaralsExpertise.class));
cards.add(new SetCardInfo("Baral, Chief of Compliance", "28s", Rarity.RARE, mage.cards.b.BaralChiefOfCompliance.class));
cards.add(new SetCardInfo("Battle at the Bridge", "53s", Rarity.RARE, mage.cards.b.BattleAtTheBridge.class));
cards.add(new SetCardInfo("Call for Unity", "9s", Rarity.RARE, mage.cards.c.CallForUnity.class));
cards.add(new SetCardInfo("Consulate Crackdown", "11s", Rarity.RARE, mage.cards.c.ConsulateCrackdown.class));
cards.add(new SetCardInfo("Dark Intimations", "128s", Rarity.RARE, mage.cards.d.DarkIntimations.class));
cards.add(new SetCardInfo("Disallow", "31p", Rarity.RARE, mage.cards.d.Disallow.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Disallow", "31s", Rarity.RARE, mage.cards.d.Disallow.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Exquisite Archangel", "18s", Rarity.MYTHIC, mage.cards.e.ExquisiteArchangel.class));
cards.add(new SetCardInfo("Freejam Regent", "81s", Rarity.RARE, mage.cards.f.FreejamRegent.class));
cards.add(new SetCardInfo("Glint-Sleeve Siphoner", "62s", Rarity.RARE, mage.cards.g.GlintSleeveSiphoner.class));
cards.add(new SetCardInfo("Gonti's Aether Heart", "152s", Rarity.MYTHIC, mage.cards.g.GontisAetherHeart.class));
cards.add(new SetCardInfo("Greenbelt Rampager", "107s", Rarity.RARE, mage.cards.g.GreenbeltRampager.class));
cards.add(new SetCardInfo("Greenwheel Liberator", "108s", Rarity.RARE, mage.cards.g.GreenwheelLiberator.class));
cards.add(new SetCardInfo("Heart of Kiran", "153s", Rarity.MYTHIC, mage.cards.h.HeartOfKiran.class));
cards.add(new SetCardInfo("Herald of Anguish", "64s", Rarity.MYTHIC, mage.cards.h.HeraldOfAnguish.class));
cards.add(new SetCardInfo("Heroic Intervention", "109p", Rarity.RARE, mage.cards.h.HeroicIntervention.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Heroic Intervention", "109s", Rarity.RARE, mage.cards.h.HeroicIntervention.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Hope of Ghirapur", "154s", Rarity.RARE, mage.cards.h.HopeOfGhirapur.class));
cards.add(new SetCardInfo("Indomitable Creativity", "85s", Rarity.MYTHIC, mage.cards.i.IndomitableCreativity.class));
cards.add(new SetCardInfo("Inspiring Statuary", "160s", Rarity.RARE, mage.cards.i.InspiringStatuary.class));
cards.add(new SetCardInfo("Kari Zev's Expertise", "88s", Rarity.RARE, mage.cards.k.KariZevsExpertise.class));
cards.add(new SetCardInfo("Kari Zev, Skyship Raider", "87s", Rarity.RARE, mage.cards.k.KariZevSkyshipRaider.class));
cards.add(new SetCardInfo("Lifecrafter's Bestiary", "162s", Rarity.RARE, mage.cards.l.LifecraftersBestiary.class));
cards.add(new SetCardInfo("Lightning Runner", "90s", Rarity.MYTHIC, mage.cards.l.LightningRunner.class));
cards.add(new SetCardInfo("Mechanized Production", "38s", Rarity.MYTHIC, mage.cards.m.MechanizedProduction.class));
cards.add(new SetCardInfo("Merchant's Dockhand", "163s", Rarity.RARE, mage.cards.m.MerchantsDockhand.class));
cards.add(new SetCardInfo("Metallic Mimic", "164s", Rarity.RARE, mage.cards.m.MetallicMimic.class));
cards.add(new SetCardInfo("Midnight Entourage", "66s", Rarity.RARE, mage.cards.m.MidnightEntourage.class));
cards.add(new SetCardInfo("Oath of Ajani", "131s", Rarity.RARE, mage.cards.o.OathOfAjani.class));
cards.add(new SetCardInfo("Paradox Engine", "169s", Rarity.MYTHIC, mage.cards.p.ParadoxEngine.class));
cards.add(new SetCardInfo("Peacewalker Colossus", "170s", Rarity.RARE, mage.cards.p.PeacewalkerColossus.class));
cards.add(new SetCardInfo("Pia's Revolution", "91s", Rarity.RARE, mage.cards.p.PiasRevolution.class));
cards.add(new SetCardInfo("Planar Bridge", "171s", Rarity.MYTHIC, mage.cards.p.PlanarBridge.class));
cards.add(new SetCardInfo("Quicksmith Rebel", 93, Rarity.RARE, mage.cards.q.QuicksmithRebel.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Quicksmith Rebel", "93s", Rarity.RARE, mage.cards.q.QuicksmithRebel.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Quicksmith Spy", "41s", Rarity.RARE, mage.cards.q.QuicksmithSpy.class));
cards.add(new SetCardInfo("Release the Gremlins", "96s", Rarity.RARE, mage.cards.r.ReleaseTheGremlins.class));
cards.add(new SetCardInfo("Rishkar's Expertise", "123s", Rarity.RARE, mage.cards.r.RishkarsExpertise.class));
cards.add(new SetCardInfo("Rishkar, Peema Renegade", "122s", Rarity.RARE, mage.cards.r.RishkarPeemaRenegade.class));
cards.add(new SetCardInfo("Scrap Trawler", 175, Rarity.RARE, mage.cards.s.ScrapTrawler.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Scrap Trawler", "175s", Rarity.RARE, mage.cards.s.ScrapTrawler.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Secret Salvage", "71s", Rarity.RARE, mage.cards.s.SecretSalvage.class));
cards.add(new SetCardInfo("Solemn Recruit", "22s", Rarity.RARE, mage.cards.s.SolemnRecruit.class));
cards.add(new SetCardInfo("Spire of Industry", "184s", Rarity.RARE, mage.cards.s.SpireOfIndustry.class));
cards.add(new SetCardInfo("Sram's Expertise", "24s", Rarity.RARE, mage.cards.s.SramsExpertise.class));
cards.add(new SetCardInfo("Sram, Senior Edificer", "23s", Rarity.RARE, mage.cards.s.SramSeniorEdificer.class));
cards.add(new SetCardInfo("Tezzeret the Schemer", "137s", Rarity.MYTHIC, mage.cards.t.TezzeretTheSchemer.class));
cards.add(new SetCardInfo("Trophy Mage", 48, Rarity.UNCOMMON, mage.cards.t.TrophyMage.class));
cards.add(new SetCardInfo("Walking Ballista", "181s", Rarity.RARE, mage.cards.w.WalkingBallista.class));
cards.add(new SetCardInfo("Whir of Invention", "49s", Rarity.RARE, mage.cards.w.WhirOfInvention.class));
cards.add(new SetCardInfo("Yahenni's Expertise", 75, Rarity.RARE, mage.cards.y.YahennisExpertise.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Yahenni's Expertise", "75s", Rarity.RARE, mage.cards.y.YahennisExpertise.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Yahenni, Undying Partisan", "74s", Rarity.RARE, mage.cards.y.YahenniUndyingPartisan.class));
}
}
| 412 | 0.697026 | 1 | 0.697026 | game-dev | MEDIA | 0.905007 | game-dev | 0.687046 | 1 | 0.687046 |
CleanroomMC/GroovyScript | 3,092 | src/main/java/com/cleanroommc/groovyscript/compat/mods/essentialcraft/MagicianTable.java | package com.cleanroommc.groovyscript.compat.mods.essentialcraft;
import com.cleanroommc.groovyscript.api.GroovyLog;
import com.cleanroommc.groovyscript.api.IIngredient;
import com.cleanroommc.groovyscript.api.documentation.annotations.*;
import com.cleanroommc.groovyscript.compat.mods.ModSupport;
import com.cleanroommc.groovyscript.helper.recipe.AbstractRecipeBuilder;
import com.cleanroommc.groovyscript.registry.StandardListRegistry;
import essentialcraft.api.MagicianTableRecipe;
import essentialcraft.api.MagicianTableRecipes;
import net.minecraft.item.crafting.Ingredient;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
@RegistryDescription(admonition = @Admonition(value = "groovyscript.wiki.essentialcraft.magician_table.note0", type = Admonition.Type.WARNING))
public class MagicianTable extends StandardListRegistry<MagicianTableRecipe> {
@RecipeBuilderDescription(example = @Example(".input(item('minecraft:diamond'), ore('ingotGold'), ore('ingotGold'), ore('stickWood'), ore('stickWood')).output(item('minecraft:iron_ingot')).mru(500)"))
public MagicianTable.RecipeBuilder recipeBuilder() {
return new MagicianTable.RecipeBuilder();
}
@Override
public Collection<MagicianTableRecipe> getRecipes() {
return MagicianTableRecipes.RECIPES;
}
@MethodDescription(example = @Example("item('essentialcraft:genitem')"))
public boolean removeByOutput(IIngredient x) {
return getRecipes().removeIf(r -> {
if (x.test(r.getRecipeOutput())) {
addBackup(r);
return true;
}
return false;
});
}
@Property(property = "input", comp = @Comp(gte = 1, lte = 5))
@Property(property = "output", comp = @Comp(eq = 1))
public static class RecipeBuilder extends AbstractRecipeBuilder<MagicianTableRecipe> {
@Property(comp = @Comp(gte = 1))
private int mru;
@RecipeBuilderMethodDescription
public RecipeBuilder mru(int cost) {
mru = cost;
return this;
}
@Override
protected int getMaxItemInput() {
return 1;
}
@Override
public String getErrorMsg() {
return "Error adding Magician Table Recipe";
}
@Override
public void validate(GroovyLog.Msg msg) {
validateItems(msg, 1, 5, 1, 1);
validateFluids(msg);
msg.add(mru < 1, "mru cost must be 1 or greater, got {}", mru);
}
@Override
@RecipeBuilderRegistrationMethod
public @Nullable MagicianTableRecipe register() {
if (!validate()) return null;
Ingredient[] inputIngredient = input.stream().map(IIngredient::toMcIngredient).toArray(Ingredient[]::new);
MagicianTableRecipe recipe = new MagicianTableRecipe(inputIngredient, output.get(0), mru);
ModSupport.ESSENTIALCRAFT.get().magicianTable.addScripted(recipe);
MagicianTableRecipes.addRecipe(recipe);
return recipe;
}
}
}
| 412 | 0.925885 | 1 | 0.925885 | game-dev | MEDIA | 0.74938 | game-dev | 0.883044 | 1 | 0.883044 |
ProtocolSupport/ProtocolSupport | 1,905 | src/protocolsupport/protocol/storage/netcache/NetworkEntityCache.java | package protocolsupport.protocol.storage.netcache;
import java.util.ArrayList;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import protocolsupport.protocol.types.networkentity.NetworkEntity;
import protocolsupport.utils.reflection.ReflectionUtils;
public class NetworkEntityCache {
protected final Int2ObjectMap<NetworkEntity> entities = new Int2ObjectOpenHashMap<>();
protected NetworkEntity player;
public void setSelf(NetworkEntity player) {
this.player = player;
addEntity(player);
}
public NetworkEntity getSelf() {
return player;
}
public int getSelfId() {
return player != null ? player.getId() : -1;
}
public void addEntity(NetworkEntity entity) {
entities.put(entity.getId(), entity);
}
public NetworkEntity getEntity(int entityId) {
return entities.get(entityId);
}
public ArrayList<NetworkEntity> getEntities(int... entityIds) {
if (entityIds.length == 0) {
return new ArrayList<>();
}
ArrayList<NetworkEntity> result = new ArrayList<>(entityIds.length);
for (int entityId : entityIds) {
NetworkEntity entity = entities.get(entityId);
if (entity != null) {
result.add(entity);
}
}
return result;
}
public ArrayList<NetworkEntity> removeEntities(int... entityIds) {
if (entityIds.length == 0) {
return new ArrayList<>();
}
ArrayList<NetworkEntity> result = new ArrayList<>(entityIds.length);
for (int entityId : entityIds) {
if (entityId == getSelfId()) {
continue;
}
NetworkEntity entity = entities.remove(entityId);
if (entity != null) {
result.add(entity);
}
}
return result;
}
public void clearEntities() {
entities.clear();
readdSelf();
}
private void readdSelf() {
if (player != null) {
addEntity(player);
}
}
@Override
public String toString() {
return ReflectionUtils.toStringAllFields(this);
}
}
| 412 | 0.770772 | 1 | 0.770772 | game-dev | MEDIA | 0.497114 | game-dev | 0.899638 | 1 | 0.899638 |
proletariatgames/unreal.hx | 7,803 | Haxe/Externs/UE4.19/unreal/UPhysicsSettings.hx | /**
*
* WARNING! This file was autogenerated by:
* _ _ _ _ __ __
* | | | | | | |\ \ / /
* | | | | |_| | \ V /
* | | | | _ | / \
* | |_| | | | |/ /^\ \
* \___/\_| |_/\/ \/
*
* This file was autogenerated by UnrealHxGenerator using UHT definitions.
* It only includes UPROPERTYs and UFUNCTIONs. Do not modify it!
* In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix
**/
package unreal;
/**
Default physics settings.
**/
@:glueCppIncludes("PhysicsEngine/PhysicsSettings.h")
@:uextern @:uclass extern class UPhysicsSettings extends unreal.UDeveloperSettings {
/**
PhysicalMaterial Surface Types
**/
@:uproperty public var PhysicalSurfaces : unreal.TArray<unreal.FPhysicalSurfaceName>;
/**
The number of frames it takes to rebuild the PhysX scene query AABB tree. The bigger the number, the smaller fetchResults takes per frame, but the more the tree deteriorates until a new tree is built
**/
@:uproperty public var PhysXTreeRebuildRate : unreal.Int32;
/**
Physics delta time initial average.
**/
@:uproperty public var InitialAverageFrameRate : unreal.Float32;
/**
Physics delta time smoothing factor for async scene.
**/
@:uproperty public var AsyncSceneSmoothingFactor : unreal.Float32;
/**
Physics delta time smoothing factor for sync scene.
**/
@:uproperty public var SyncSceneSmoothingFactor : unreal.Float32;
/**
Max number of substeps for physics simulation.
**/
@:uproperty public var MaxSubsteps : unreal.Int32;
/**
Max delta time (in seconds) for an individual simulation substep.
**/
@:uproperty public var MaxSubstepDeltaTime : unreal.Float32;
/**
Whether to substep the async physics simulation. This feature is still experimental. Certain functionality might not work correctly
**/
@:uproperty public var bSubsteppingAsync : Bool;
/**
Whether to substep the physics simulation. This feature is still experimental. Certain functionality might not work correctly
**/
@:uproperty public var bSubstepping : Bool;
/**
Max Physics Delta Time to be clamped.
**/
@:uproperty public var MaxPhysicsDeltaTime : unreal.Float32;
/**
If set to true, the scene will use enhanced determinism at the cost of a bit more resources. See eENABLE_ENHANCED_DETERMINISM to learn about the specifics
**/
@:uproperty public var bEnableEnhancedDeterminism : Bool;
/**
If true CCD will be ignored. This is an optimization when CCD is never used which removes the need for physx to check it internally.
**/
@:uproperty public var bDisableCCD : Bool;
/**
If true, physx will not update unreal with any bodies that have moved during the simulation. This should only be used if you have no physx simulation or you are manually updating the unreal data via polling physx.
**/
@:uproperty public var bDisableActiveActors : Bool;
/**
If true, store extra information to allow FindCollisionUV to derive UV info from a line trace hit result, using the FindCollisionUV utility
**/
@:uproperty public var bSupportUVFromHitResults : Bool;
/**
If true, the internal physx face to UE face mapping will not be generated. This is a memory optimization available if you do not rely on face indices returned by scene queries.
**/
@:uproperty public var bSuppressFaceRemapTable : Bool;
/**
If true, static meshes will use per poly collision as complex collision by default. If false the default behavior is the same as UseSimpleAsComplex.
**/
@:deprecated @:uproperty public var bDefaultHasComplexCollision_DEPRECATED : Bool;
/**
Determines the default physics shape complexity.
**/
@:uproperty public var DefaultShapeComplexity : unreal.ECollisionTraceFlag;
/**
If true, simulate physics for this component on a dedicated server.
This should be set if simulating physics and replicating with a dedicated server.
**/
@:uproperty public var bSimulateSkeletalMeshOnDedicatedServer : Bool;
/**
Max Contact offset.
**/
@:uproperty public var MaxContactOffset : unreal.Float32;
/**
Min Contact offset.
**/
@:uproperty public var MinContactOffset : unreal.Float32;
/**
Contact offset multiplier. When creating a physics shape we look at its bounding volume and multiply its minimum value by this multiplier. A bigger number will generate contact points earlier which results in higher stability at the cost of performance.
**/
@:uproperty public var ContactOffsetMultiplier : unreal.Float32;
/**
Max velocity which may be used to depenetrate simulated physics objects. 0 means no maximum.
**/
@:uproperty public var MaxDepenetrationVelocity : unreal.Float32;
/**
Max angular velocity that a simulated object can achieve.
**/
@:uproperty public var MaxAngularVelocity : unreal.Float32;
/**
Restitution combine mode, controls how restitution is computed for multiple materials.
**/
@:uproperty public var RestitutionCombineMode : unreal.EFrictionCombineMode;
/**
Friction combine mode, controls how friction is computed for multiple materials.
**/
@:uproperty public var FrictionCombineMode : unreal.EFrictionCombineMode;
/**
Minimum relative velocity required for an object to bounce. A typical value for simulation stability is about 0.2 * gravity
**/
@:uproperty public var BounceThresholdVelocity : unreal.Float32;
/**
Useful for constraining all objects in the world, for example if you are making a 2D game using 3D environments.
**/
@:uproperty public var DefaultDegreesOfFreedom : unreal.ESettingsDOF;
@:deprecated @:uproperty public var LockedAxis_DEPRECATED : unreal.ESettingsLockedAxis;
/**
Can 2D physics be used (Box2D)?
**/
@:uproperty public var bEnable2DPhysics : Bool;
/**
Whether to warn when physics locks are used incorrectly. Turning this off is not recommended and should only be used by very advanced users.
**/
@:uproperty public var bWarnMissingLocks : Bool;
/**
Enables stabilization of contacts for slow moving bodies. This will help improve the stability of stacking.
**/
@:uproperty public var bEnableStabilization : Bool;
/**
Enables persistent contact manifolds. This will generate fewer contact points, but with more accuracy. Reduces stability of stacking, but can help energy conservation.
**/
@:uproperty public var bEnablePCM : Bool;
/**
Enables shape sharing between sync and async scene for static rigid actors
**/
@:uproperty public var bEnableShapeSharing : Bool;
/**
Enables the use of an async scene
**/
@:uproperty public var bEnableAsyncScene : Bool;
/**
Triangles from triangle meshes (BSP) with an area less than or equal to this value will be removed from physics collision data. Set to less than 0 to disable.
**/
@:uproperty public var TriangleMeshTriangleMinAreaThreshold : unreal.Float32;
/**
Threshold for ragdoll bodies above which they will be added to an aggregate before being added to the scene
**/
@:uproperty public var RagdollAggregateThreshold : unreal.Int32;
/**
Amount of memory to reserve for PhysX simulate(), this is per pxscene and will be rounded up to the next 16K boundary
**/
@:uproperty public var SimulateScratchMemorySize : unreal.Int32;
/**
Default fluid friction for Physics Volumes.
**/
@:uproperty public var DefaultFluidFriction : unreal.Float32;
/**
Default terminal velocity for Physics Volumes.
**/
@:uproperty public var DefaultTerminalVelocity : unreal.Float32;
/**
Default gravity.
**/
@:uproperty public var DefaultGravityZ : unreal.Float32;
}
| 412 | 0.796597 | 1 | 0.796597 | game-dev | MEDIA | 0.96601 | game-dev | 0.540783 | 1 | 0.540783 |
bobzhuyb/ns3-rdma | 7,937 | src/propagation/model/itu-r-1411-nlos-over-rooftop-propagation-loss-model.cc | /* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2011, 2012 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Marco Miozzo <marco.miozzo@cttc.es>,
* Nicola Baldo <nbaldo@cttc.es>
*
*/
#include "ns3/log.h"
#include "ns3/double.h"
#include "ns3/enum.h"
#include "ns3/mobility-model.h"
#include <cmath>
#include "itu-r-1411-nlos-over-rooftop-propagation-loss-model.h"
NS_LOG_COMPONENT_DEFINE ("ItuR1411NlosOverRooftopPropagationLossModel");
namespace ns3 {
NS_OBJECT_ENSURE_REGISTERED (ItuR1411NlosOverRooftopPropagationLossModel);
TypeId
ItuR1411NlosOverRooftopPropagationLossModel::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::ItuR1411NlosOverRooftopPropagationLossModel")
.SetParent<PropagationLossModel> ()
.AddAttribute ("Frequency",
"The Frequency (default is 2.106 GHz).",
DoubleValue (2160e6),
MakeDoubleAccessor (&ItuR1411NlosOverRooftopPropagationLossModel::SetFrequency),
MakeDoubleChecker<double> ())
.AddAttribute ("Environment",
"Environment Scenario",
EnumValue (UrbanEnvironment),
MakeEnumAccessor (&ItuR1411NlosOverRooftopPropagationLossModel::m_environment),
MakeEnumChecker (UrbanEnvironment, "Urban",
SubUrbanEnvironment, "SubUrban",
OpenAreasEnvironment, "OpenAreas"))
.AddAttribute ("CitySize",
"Dimension of the city",
EnumValue (LargeCity),
MakeEnumAccessor (&ItuR1411NlosOverRooftopPropagationLossModel::m_citySize),
MakeEnumChecker (SmallCity, "Small",
MediumCity, "Medium",
LargeCity, "Large"))
.AddAttribute ("RooftopLevel",
"The height of the rooftop level in meters",
DoubleValue (20.0),
MakeDoubleAccessor (&ItuR1411NlosOverRooftopPropagationLossModel::m_rooftopHeight),
MakeDoubleChecker<double> (0.0, 90.0))
.AddAttribute ("StreetsOrientation",
"The orientation of streets in degrees [0,90] with respect to the direction of propagation",
DoubleValue (45.0),
MakeDoubleAccessor (&ItuR1411NlosOverRooftopPropagationLossModel::m_streetsOrientation),
MakeDoubleChecker<double> (0.0, 90.0))
.AddAttribute ("StreetsWidth",
"The width of streets",
DoubleValue (20.0),
MakeDoubleAccessor (&ItuR1411NlosOverRooftopPropagationLossModel::m_streetsWidth),
MakeDoubleChecker<double> (0.0, 1000.0))
.AddAttribute ("BuildingsExtend",
"The distance over which the buildings extend",
DoubleValue (80.0),
MakeDoubleAccessor (&ItuR1411NlosOverRooftopPropagationLossModel::m_buildingsExtend),
MakeDoubleChecker<double> ())
.AddAttribute ("BuildingSeparation",
"The separation between buildings",
DoubleValue (50.0),
MakeDoubleAccessor (&ItuR1411NlosOverRooftopPropagationLossModel::m_buildingSeparation),
MakeDoubleChecker<double> ());
return tid;
}
double
ItuR1411NlosOverRooftopPropagationLossModel::GetLoss (Ptr<MobilityModel> a, Ptr<MobilityModel> b) const
{
NS_LOG_FUNCTION (this << a << b);
double Lori = 0.0;
double fmhz = m_frequency / 1e6;
NS_ASSERT_MSG (((m_streetsOrientation >= 0) && (m_streetsOrientation <= 90)),
" Street Orientation must be in [0,90]");
if (m_streetsOrientation < 35)
{
Lori = -10.0 + 0.354 * m_streetsOrientation;
}
else if ((m_streetsOrientation >= 35)&&(m_streetsOrientation < 55))
{
Lori = 2.5 + 0.075 * (m_streetsOrientation - 35);
}
else // m_streetsOrientation >= 55
{
Lori = 2.5 + 0.075 * (m_streetsOrientation - 55);
}
double distance = a->GetDistanceFrom (b);
double hb = (a->GetPosition ().z > b->GetPosition ().z ? a->GetPosition ().z : b->GetPosition ().z);
double hm = (a->GetPosition ().z < b->GetPosition ().z ? a->GetPosition ().z : b->GetPosition ().z);
NS_ASSERT_MSG (hm > 0 && hb > 0, "nodes' height must be greater then 0");
double Dhb = hb - m_rooftopHeight;
double ds = (m_lambda * distance * distance) / (Dhb * Dhb);
double Lmsd = 0.0;
NS_LOG_LOGIC (this << " build " << m_buildingsExtend << " ds " << ds << " roof " << m_rooftopHeight << " hb " << hb << " lambda " << m_lambda);
if (ds < m_buildingsExtend)
{
double Lbsh = 0.0;
double ka = 0.0;
double kd = 0.0;
double kf = 0.0;
if (hb > m_rooftopHeight)
{
Lbsh = -18 * log10 (1 + Dhb);
ka = (fmhz > 2000 ? 71.4 : 54.0);
kd = 18.0;
}
else
{
Lbsh = 0;
kd = 18.0 - 15 * Dhb / a->GetPosition ().z;
if (distance < 500)
{
ka = 54.0 - 1.6 * Dhb * distance / 1000;
}
else
{
ka = 54.0 - 0.8 * Dhb;
}
}
if (fmhz > 2000)
{
kf = -8;
}
else if ((m_environment == UrbanEnvironment)&&(m_citySize == LargeCity))
{
kf = -4 + 0.7 * (fmhz / 925.0 - 1);
}
else
{
kf = -4 + 1.5 * (fmhz / 925.0 - 1);
}
Lmsd = Lbsh + ka + kd*log10 (distance / 1000.0) + kf*log10 (fmhz) - 9.0 * log10 (m_buildingSeparation);
}
else
{
double theta = atan (Dhb / m_buildingSeparation);
double rho = sqrt (Dhb * Dhb + m_buildingSeparation * m_buildingSeparation);
double Qm = 0.0;
if ((hb > m_rooftopHeight - 1.0) && (hb < m_rooftopHeight + 1.0))
{
Qm = m_buildingSeparation / distance;
}
else if (hb > m_rooftopHeight)
{
Qm = 2.35 * pow (Dhb / distance * sqrt (m_buildingSeparation / m_lambda), 0.9);
}
else
{
Qm = m_buildingSeparation / (2 * M_PI * distance) * sqrt (m_lambda / rho) * (1 / theta - (1 / (2 * M_PI + theta)));
}
Lmsd = -10 * log10 (Qm * Qm);
}
double Lbf = 32.4 + 20 * log10 (distance / 1000) + 20 * log10 (fmhz);
double Dhm = m_rooftopHeight - hm;
double Lrts = -8.2 - 10 * log10 (m_streetsWidth) + 10 * log10 (fmhz) + 20 * log10 (Dhm) + Lori;
NS_LOG_LOGIC (this << " Lbf " << Lbf << " Lrts " << Lrts << " Dhm" << Dhm << " Lmsd " << Lmsd);
double loss = 0.0;
if (Lrts + Lmsd > 0)
{
loss = Lbf + Lrts + Lmsd;
}
else
{
loss = Lbf;
}
return loss;
}
void
ItuR1411NlosOverRooftopPropagationLossModel::SetFrequency (double freq)
{
m_frequency = freq;
m_lambda = 299792458.0 / freq;
}
double
ItuR1411NlosOverRooftopPropagationLossModel::DoCalcRxPower (double txPowerDbm,
Ptr<MobilityModel> a,
Ptr<MobilityModel> b) const
{
return (txPowerDbm - GetLoss (a, b));
}
int64_t
ItuR1411NlosOverRooftopPropagationLossModel::DoAssignStreams (int64_t stream)
{
return 0;
}
} // namespace ns3
| 412 | 0.936748 | 1 | 0.936748 | game-dev | MEDIA | 0.211445 | game-dev | 0.984384 | 1 | 0.984384 |
AngelsJinx/Godot-Things | 1,256 | MicroManager/Game/UI/JobWidget.gd | extends VBoxContainer
class_name JobWidget
export var key := "Q"
export var background_nodepath : NodePath
export var button_nodepath : NodePath
export var counter_nodepath : NodePath
export var state_name : String
export var texture_normal : Texture
var _counter : Label
func _ready():
var button = get_node(button_nodepath) as TextureButton
var conn = button.connect("pressed", self, "activate_job")
assert(conn == OK)
conn = GameManager.connect("player_mode_changed", self, "deactivate_job")
assert(conn == OK)
button.texture_normal = texture_normal
$KeyLabel.text = key
_counter = get_node(counter_nodepath) as Label
conn = GameManager.connect("job_count_changed", self, "_on_job_count_changed")
func activate_job():
get_node(background_nodepath).color = Color.white
GameManager.set_player_mode(state_name)
func deactivate_job(new_state : String):
if new_state != state_name:
get_node(background_nodepath).color = Color("776663")
func _on_job_count_changed(job_changed):
if state_name == job_changed:
var count := 0
match state_name:
"Blocker":
count = GameManager.blocker_count
"Digger":
count = GameManager.digger_count
"LadderBuilder":
count = GameManager.ladder_count
_counter.text = String(count)
| 412 | 0.738028 | 1 | 0.738028 | game-dev | MEDIA | 0.864082 | game-dev | 0.892119 | 1 | 0.892119 |
foundryvtt/dnd5e | 2,022 | module/canvas/detection-modes/blindsight.mjs | /**
* The detection mode for Blindsight.
*/
export class DetectionModeBlindsight extends foundry.canvas.perception.DetectionMode {
constructor() {
super({
id: "blindsight",
label: "DND5E.SenseBlindsight",
type: (foundry.canvas?.perception?.DetectionMode ?? DetectionMode).DETECTION_TYPES.OTHER,
walls: true,
angle: false
});
}
/* -------------------------------------------- */
/** @override */
static getDetectionFilter() {
return this._detectionFilter ??= OutlineOverlayFilter.create({
outlineColor: [1, 1, 1, 1],
knockout: true,
wave: true
});
}
/* -------------------------------------------- */
/** @override */
_canDetect(visionSource, target) {
if ( visionSource.object.document.hasStatusEffect(CONFIG.specialStatusEffects.BURROW) ) return false;
if ( target instanceof foundry.canvas.placeables.Token ) {
if ( target.document.hasStatusEffect(CONFIG.specialStatusEffects.BURROW) ) return false;
}
return true;
}
/* -------------------------------------------- */
/** @override */
_testLOS(visionSource, mode, target, test) {
return !CONFIG.Canvas.polygonBackends.sight.testCollision(
{ x: visionSource.x, y: visionSource.y },
test.point,
{
type: "sight",
mode: "any",
source: visionSource,
// Blindsight is restricted by total cover and therefore cannot see
// through windows. So we do not want blindsight to see through
// a window as we get close to it. That's why we ignore thresholds.
// We make the assumption that all windows are configured as threshold
// walls. A move-based visibility check would also be an option to check
// for total cover, but this would have the undesirable side effect that
// blindsight wouldn't work through fences, portcullises, etc.
useThreshold: false
}
);
}
}
CONFIG.Canvas.detectionModes.blindsight = new DetectionModeBlindsight();
| 412 | 0.82598 | 1 | 0.82598 | game-dev | MEDIA | 0.325148 | game-dev | 0.698207 | 1 | 0.698207 |
CloudburstMC/Protocol | 3,290 | bedrock-codec/src/main/java/org/cloudburstmc/protocol/bedrock/codec/v766/serializer/ResourcePacksInfoSerializer_v766.java | package org.cloudburstmc.protocol.bedrock.codec.v766.serializer;
import io.netty.buffer.ByteBuf;
import org.cloudburstmc.protocol.bedrock.codec.BedrockCodecHelper;
import org.cloudburstmc.protocol.bedrock.codec.v748.serializer.ResourcePacksInfoSerializer_v748;
import org.cloudburstmc.protocol.bedrock.packet.ResourcePacksInfoPacket;
import java.util.Objects;
import java.util.UUID;
public class ResourcePacksInfoSerializer_v766 extends ResourcePacksInfoSerializer_v748 {
public static final ResourcePacksInfoSerializer_v766 INSTANCE = new ResourcePacksInfoSerializer_v766();
@Override
public void serialize(ByteBuf buffer, BedrockCodecHelper helper, ResourcePacksInfoPacket packet) {
buffer.writeBoolean(packet.isForcedToAccept());
buffer.writeBoolean(packet.isHasAddonPacks());
buffer.writeBoolean(packet.isScriptingEnabled());
helper.writeUuid(buffer, packet.getWorldTemplateId());
helper.writeString(buffer, packet.getWorldTemplateVersion());
writePacks(buffer, packet.getResourcePackInfos(), helper, true);
}
@Override
public void deserialize(ByteBuf buffer, BedrockCodecHelper helper, ResourcePacksInfoPacket packet) {
packet.setForcedToAccept(buffer.readBoolean());
packet.setHasAddonPacks(buffer.readBoolean());
packet.setScriptingEnabled(buffer.readBoolean());
packet.setWorldTemplateId(helper.readUuid(buffer));
packet.setWorldTemplateVersion(helper.readString(buffer));
readPacks(buffer, packet.getResourcePackInfos(), helper, true);
}
@Override
public void writeEntry(ByteBuf buffer, BedrockCodecHelper helper, ResourcePacksInfoPacket.Entry entry, boolean resource) {
Objects.requireNonNull(entry, "ResourcePacketInfoPacket entry was null");
helper.writeUuid(buffer, entry.getPackId());
helper.writeString(buffer, entry.getPackVersion());
buffer.writeLongLE(entry.getPackSize());
helper.writeString(buffer, entry.getContentKey());
helper.writeString(buffer, entry.getSubPackName());
helper.writeString(buffer, entry.getContentId());
buffer.writeBoolean(entry.isScripting());
buffer.writeBoolean(entry.isAddonPack());
if (resource) {
buffer.writeBoolean(entry.isRaytracingCapable());
}
helper.writeString(buffer, entry.getCdnUrl() == null ? "" : entry.getCdnUrl());
}
@Override
public ResourcePacksInfoPacket.Entry readEntry(ByteBuf buffer, BedrockCodecHelper helper, boolean resource) {
UUID packId = helper.readUuid(buffer);
String packVersion = helper.readString(buffer);
long packSize = buffer.readLongLE();
String contentKey = helper.readString(buffer);
String subPackName = helper.readString(buffer);
String contentId = helper.readString(buffer);
boolean isScripting = buffer.readBoolean();
boolean isAddonPack = buffer.readBoolean();
boolean raytracingCapable = resource && buffer.readBoolean();
String cdnUrl = helper.readString(buffer);
return new ResourcePacksInfoPacket.Entry(packId, packVersion, packSize, contentKey, subPackName, contentId,
isScripting, raytracingCapable, isAddonPack, cdnUrl);
}
} | 412 | 0.878417 | 1 | 0.878417 | game-dev | MEDIA | 0.690827 | game-dev | 0.898438 | 1 | 0.898438 |
OSPreservProject/sprite | 2,668 | man/cmds.fmt/xgone.man |
XGONE User Commands XGONE
NNAAMMEE
xgone - lock the screen under the X window system
SSYYNNOOPPSSIISS
xxggoonnee _a_r_g_s
DDEESSCCRRIIPPTTIIOONN
_X_g_o_n_e locks the screen until a keypress is entered. While
waiting, it displays a message telling where the person went
and when they started the program and moves this text around
the screen to avoid burning them in at a particular loca-
tion.
If no _a_r_g_s _a_r_e _p_r_o_v_i_d_e_d, _t_h_e _p_r_o_g_r_a_m _d_i_s_p_l_a_y_s time. If _a_r_g_s
are provided, then the concatenation of the arguments,
separated by spaces, is displayed instead of the default
string.
To leave _x_g_o_n_e, press any mouse key. If password checking
is enabled, it will prompt you for your password, which will
not be echoed on the display. End the password with
``Return.'' As an accelerator, you may simply type your
password. Password checking is disabled by default, so any
input will then cause _x_g_o_n_e to exit.
OOPPTTIIOONNSS
-font Specify the font to use for text on the screen.
-sleep Specify the interval between moves of the block of
text on the screen.
-delay Make the program drop in the background and delay
starting for a few seconds. This is helpful when
invoking _x_g_o_n_e from a menu inside window managers
like _t_w_m which don't allow a "grab" of mouse for a
short time right at startup.
-passwd Enable password checking.
DDEEFFAAUULLTTSS
xgone.Font: fontname (same as -font)
xgone.Text: default text to use instead of "X Gone"
xgone.Sleep: sleeptime in seconds (same as -sleep)
xgone.Update: interval between updates (same as -update)
xgone.Delay: boolean (same as -delay)
xgone.Passwd: boolean, with true indicating password
checking should be done.
FFIILLEESS
/etc/passwd
SSEEEE AALLSSOO
lockscreen(1), xlock(l)
Sprite v1.0 25 February 1987 1
XGONE User Commands XGONE
AAUUTTHHOORR
Originally written for X10 by Tim Morgan at UCI.
Modified and extended for X11 by Richard Johnson also at
UCI.
Modified by Fred Douglis for Sprite.
Sprite v1.0 25 February 1987 2
| 412 | 0.740935 | 1 | 0.740935 | game-dev | MEDIA | 0.384167 | game-dev | 0.820057 | 1 | 0.820057 |
moo-man/WFRP4e-FoundryVTT | 1,749 | scripts/hhv7PrRdlf9sfC82.js | let characteristics = {
"ws" : 5,
"bs" : 0,
"s" : 5,
"t" : 5,
"i" : 10,
"ag" : 0,
"dex" : 0,
"int" : 0,
"wp" : 0,
"fel" : 0
}
let skills = ["Cool", "Dodge"]
let skillAdvancements = [10, 10]
let talents = ["Combat Reflexes"]
let trappings = ["Leather Jack", "Leather Skullcap", "Leather Leggings", "Shield"]
let items = []
let updateObj = this.actor.toObject();
for (let ch in characteristics)
{
updateObj.system.characteristics[ch].modifier += characteristics[ch];
}
for (let index = 0; index < skills.length; index++)
{
let skill = skills[index]
let skillItem;
skillItem = updateObj.items.find(i => i.name == skill && i.type == "skill")
if (skillItem)
skillItem.system.advances.value += skillAdvancements[index]
else
{
skillItem = await game.wfrp4e.utility.findSkill(skill)
skillItem = skillItem.toObject();
skillItem.system.advances.value = skillAdvancements[index];
items.push(skillItem);
}
}
for (let talent of talents)
{
let talentItem = await game.wfrp4e.utility.findTalent(talent)
if (talentItem)
{
items.push(talentItem.toObject());
}
else
{
ui.notifications.warn(`Could not find ${talent}`, {permanent : true})
}
}
for (let trapping of trappings)
{
let trappingItem = await game.wfrp4e.utility.findItem(trapping)
if (trappingItem)
{
trappingItem = trappingItem.toObject()
trappingItem.system.equipped.value = true;
items.push(trappingItem);
}
else
{
ui.notifications.warn(`Could not find ${trapping}`, {permanent : true})
}
}
await this.actor.update(updateObj)
this.actor.createEmbeddedDocuments("Item", items); | 412 | 0.546966 | 1 | 0.546966 | game-dev | MEDIA | 0.86725 | game-dev | 0.79183 | 1 | 0.79183 |
UchuServer/Uchu | 33,715 | Uchu.World/Objects/Components/ReplicaComponents/RacingControlComponent.cs | // Thanks to Simon Nitzsche for his research into racing
// https://github.com/SimonNitzsche/OpCrux-Server/
// https://www.youtube.com/watch?v=X5qvEDmtE5U
//
// Thanks to Darkflame Universe for releasing the source code
// of their server. https://github.com/DarkflameUniverse/
// https://www.darkflameuniverse.org/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using InfectedRose.Luz;
using Microsoft.Scripting.Utils;
using RakDotNet.IO;
using Uchu.Api;
using Uchu.Api.Models;
using Uchu.Core;
using Uchu.Core.Client;
using Uchu.Physics;
using Uchu.World.Filters;
namespace Uchu.World
{
public class RacingControlComponent : ScriptedActivityComponent
{
public override ComponentId Id => ComponentId.RacingControlComponent;
public List<RacingPlayerInfo> Players = new();
public Event<RacingPlayerInfo> OnPlayerLap { get; set; }
private RaceInfo _raceInfo = new();
private RacingStatus _racingStatus = RacingStatus.None;
private LuzPathData _path;
private int _deathPlaneHeight;
private MainWorldReturnData _returnData;
private uint _rankCounter = 0;
public RacingControlComponent()
{
OnPlayerLap = new Event<RacingPlayerInfo>();
_raceInfo.LapCount = 3;
_raceInfo.PathName = "MainPath"; // MainPath
Listen(OnStart, async () => await LoadAsync());
}
private async Task LoadAsync()
{
UchuServer.Api.RegisterCommandCollection<RacingMatchCommands>(this);
_path = Zone.ZoneInfo.LuzFile.PathData.FirstOrDefault(path => path.PathName == "MainPath");
// In live this was done with zone specific scripts
switch (Zone.ZoneId)
{
case 1203:
_deathPlaneHeight = 100;
await SetupActivityInfo(42);
_returnData = new MainWorldReturnData
{
ZoneId = 1200,
Position = new Vector3(248.8f, 287.4f, 186.9f),
Rotation = new Quaternion(0, 0.7f, 0, 0.7f),
};
break;
case 1303:
_deathPlaneHeight = 0;
await SetupActivityInfo(39);
_returnData = new MainWorldReturnData
{
ZoneId = 1300,
Position = new Vector3(63.5f, 314.8f, 493.1f),
Rotation = new Quaternion(0, 0.45f, 0, 0.89f),
};
break;
case 1403:
_deathPlaneHeight = 300;
await SetupActivityInfo(54);
_returnData = new MainWorldReturnData
{
ZoneId = 1400,
Position = new Vector3(775.4f, 238.4f, 455.2f),
Rotation = new Quaternion(0, 0.59f, 0, 0.8f),
};
break;
default:
_deathPlaneHeight = 0;
_returnData = new MainWorldReturnData
{
ZoneId = 1200,
Position = new Vector3(248.8f, 287.4f, 186.9f),
Rotation = new Quaternion(0, 0.7f, 0, 0.7f),
};
break;
}
if (_path == default)
throw new Exception("Path not found");
Listen(GameObject.OnMessageBoxRespond, OnMessageBoxRespond);
Listen(Zone.OnPlayerLoad, player =>
{
Listen(player.OnWorldLoad, () => OnPlayerLoad(player));
Listen(player.OnRequestDie, (msg) => OnPlayerRequestDie(player));
Listen(player.OnRacingPlayerInfoResetFinished, () => OnRacingPlayerInfoResetFinished(player));
Listen(player.OnAcknowledgePossession, vehicle => OnAcknowledgePossession(player, vehicle));
});
Listen(Zone.OnPlayerLeave, player => RemoveRacingPlayer(player));
}
/// <summary>
/// Message box response handler
/// </summary>
/// <param name="player"></param>
/// <param name="message"></param>
private async Task OnMessageBoxRespond(Player player, MessageBoxRespondMessage message)
{
Logger.Information($"Button - {message.Button} {message.Identifier} {message.UserData}");
if (message.Identifier == "ACT_RACE_EXIT_THE_RACE?" && message.Button == 1 || message.Identifier == "Exit")
{
player.Message(new NotifyRacingClientMessage
{
Associate = GameObject,
EventType = RacingClientNotificationType.Exit,
SingleClient = player,
});
await SendPlayerToMainWorldAsync(player);
}
else if (message.Identifier == "rewardButton")
{
await this.DropLootAsync(player, true, true);
player.Message(new NotifyRacingClientMessage
{
Associate = GameObject,
EventType = RacingClientNotificationType.RewardPlayer,
SingleClient = player,
});
}
}
private void AddExpectedPlayer(ulong objectId) {
Logger.Information("PreLoad Player " + objectId);
var fakePlayer = GameObject.Instantiate<Player>(
Zone,
position: Zone.SpawnPosition,
rotation: Zone.SpawnRotation,
scale: 1,
objectId: new ObjectId(objectId),
lot: 1
);
if (!IsPlayerRegistered(fakePlayer)) {
Players.Add(new RacingPlayerInfo
{
Player = fakePlayer,
PlayerLoaded = false,
PlayerIndex = (uint)Players.Count + 1,
NoSmashOnReload = true,
RaceTime = new Stopwatch(),
LapTime = new Stopwatch(),
BestLapTime = default,
ResetTimer = new SimpleTimer(6000),
});
}
}
private bool IsPlayerRegistered(Player player) {
foreach (var info in Players) {
if (info.Player.Id == player.Id)
return true;
}
return false;
}
private bool AllRegisteredPlayersReady() {
foreach (var info in Players) {
if (!info.PlayerLoaded)
return false;
}
return true;
}
/// <summary>
/// This runs when the player loads into the world, it registers the player
/// </summary>
/// <param name="player"></param>
private async Task OnPlayerLoad(Player player)
{
Logger.Information($"{player} loaded into racing");
// If race has already started return player to main world
if (_racingStatus != RacingStatus.None)
{
await SendPlayerToMainWorldAsync(player);
return;
}
// Set respawn point so when the players leave unexpectedly
// and relogin they don't spawn in a racing world
if (player.TryGetComponent<CharacterComponent>(out var characterComponent))
{
characterComponent.LastZone = _returnData.ZoneId;
characterComponent.SpawnPosition = _returnData.Position;
characterComponent.SpawnRotation = _returnData.Rotation;
}
await player.GetComponent<SaveComponent>().SaveAsync();
// Disable render distance filter
player.Perspective.GetFilter<RenderDistanceFilter>().Distance = 10000;
if (player.TryGetComponent<MissionInventoryComponent>(out var missionInventoryComponent))
await missionInventoryComponent.RacingEnterWorld(GameObject.Zone.ZoneId);
RacingPlayerInfo playerInfo;
if (IsPlayerRegistered(player)) {
var playerInfoIndex = Players.FindIndex(info => info.Player.Id == player.Id);
playerInfo = Players[playerInfoIndex];
playerInfo.Player = player;
playerInfo.PlayerLoaded = true;
Players[playerInfoIndex] = playerInfo;
} else {
playerInfo = new RacingPlayerInfo
{
Player = player,
PlayerLoaded = true,
PlayerIndex = (uint)Players.Count + 1,
NoSmashOnReload = true,
RaceTime = new Stopwatch(),
LapTime = new Stopwatch(),
BestLapTime = default,
ResetTimer = new SimpleTimer(6000),
};
Players.Add(playerInfo);
}
LoadPlayerCar(player);
Listen(playerInfo.ResetTimer.OnElapsed, () => ResetPlayer(player));
Listen(player.OnPositionUpdate, (position, rotation) =>
{
if (!(position.Y < _deathPlaneHeight) || _racingStatus != RacingStatus.Started) return;
var car = Players.First(i => i.Player == player).Vehicle;
Zone.BroadcastMessage(new DieMessage
{
Associate = car,
Killer = GameObject,
//KillType = KillType.Violent,
//ClientDeath = true,
SpawnLoot = false,
});
OnPlayerRequestDie(player);
});
// Wait for players to join
// If all players from the queue are loaded wait
// another 10 seconds max
// NOTE: This code schedules 'InitRace' multiple times
// but 'InitRace' will only do it's thing once. There is
// room for improvement here...
if (AllRegisteredPlayersReady())
Zone.Schedule(InitRace, 10000);
else
Zone.Schedule(InitRace, 30000);
}
/// <summary>
/// Send the player back to the world he came from
/// </summary>
/// <param name="player"></param>
private async Task SendPlayerToMainWorldAsync(Player player)
{
await player.SendToWorldAsync(_returnData.ZoneId, _returnData.Position, _returnData.Rotation);
RemoveRacingPlayer(player);
}
private void RemoveRacingPlayer(Player player)
{
Players.RemoveAll(info => info.Player == player);
if (Players.Count == 0)
{
Zone.Schedule(async () => await this.GameObject.UchuServer.StopAsync(), 10000);
Logger.Information("No players left in racing world. Closing instance");
}
}
/// <summary>
/// Set up the player's car
/// </summary>
/// <param name="player"></param>
/// <exception cref="Exception"></exception>
private void LoadPlayerCar(Player player)
{
// Get position and rotation
var waypoint = (LuzRaceWaypoint)_path.Waypoints.First();
var startPosition = waypoint.Position;
var startRotation = waypoint.Rotation;
var spacing = 15;
var positionOffset = startRotation.VectorMultiply(Vector3.UnitX) * Players.Count * spacing;
startPosition += positionOffset + Vector3.UnitY * 3;
// Create car
player.Teleport(startPosition, startRotation);
var car = GameObject.Instantiate(this.GameObject.Zone.ZoneControlObject, 8092, startPosition, startRotation);
// Setup imagination
var destroyableComponent = car.GetComponent<DestroyableComponent>();
destroyableComponent.MaxImagination = 60;
destroyableComponent.Imagination = 0;
// Let the player posses the car
// Listen(player.OnAcknowledgePossession, this.OnAcknowledgePossession);
var possessableComponent = car.GetComponent<PossessableComponent>();
possessableComponent.Driver = player;
var characterComponent = player.GetComponent<CharacterComponent>();
characterComponent.VehicleObject = car;
// Get custom parts
var inventory = player.GetComponent<InventoryManagerComponent>();
var carItem = inventory.FindItem(Lot.ModularCar);
var moduleAssemblyComponent = car.GetComponent<ModuleAssemblyComponent>();
moduleAssemblyComponent.SetAssembly(carItem == null
? "1:8129;1:8130;1:13513;1:13512;1:13515;1:13516;1:13514;"
: carItem.Settings["assemblyPartLOTs"].ToString());
Start(car);
GameObject.Construct(car);
GameObject.Serialize(player);
AddPlayer(player);
Zone.BroadcastMessage(new RacingSetPlayerResetInfoMessage
{
Associate = this.GameObject,
CurrentLap = 0,
FurthestResetPlane = 0,
PlayerId = player,
RespawnPos = startPosition,
UpcomingPlane = 1,
});
// TODO Set Jetpack mode?
Zone.BroadcastMessage(new NotifyVehicleOfRacingObjectMessage
{
Associate = car,
RacingObjectId = this.GameObject, // zonecontrol
});
Zone.BroadcastMessage(new VehicleSetWheelLockStateMessage
{
Associate = car,
ExtraFriction = false,
Locked = true
});
Zone.BroadcastMessage(new RacingPlayerLoadedMessage
{
Associate = this.GameObject,
PlayerId = player,
VehicleId = car,
});
var playerInfoIndex = Players.FindIndex(info => info.Player.Id == player.Id);
var tempInfo = Players[playerInfoIndex];
tempInfo.Vehicle = car;
Players[playerInfoIndex] = tempInfo;
}
private void InitRace()
{
if (_racingStatus != RacingStatus.None)
return;
// Remove all players that aren't loaded yet
for (var i = Players.Count - 1; i > 0; i--) {
if (!Players[i].PlayerLoaded)
Players.RemoveAt(i);
}
_racingStatus = RacingStatus.Loaded;
this.Zone.Server.SetMaxPlayerCount((uint)Players.Count);
// Start imagination spawners
var minSpawner = Zone.SpawnerNetworks.FirstOrDefault(gameObject => gameObject.Name == "ImaginationSpawn_Min");
var medSpawner = Zone.SpawnerNetworks.FirstOrDefault(gameObject => gameObject.Name == "ImaginationSpawn_Med");
var maxSpawner = Zone.SpawnerNetworks.FirstOrDefault(gameObject => gameObject.Name == "ImaginationSpawn_Max");
minSpawner?.Activate();
minSpawner?.SpawnAll();
if (Players.Count > 2)
{
medSpawner?.Activate();
medSpawner?.SpawnAll();
}
if (Players.Count > 4)
{
maxSpawner?.Activate();
maxSpawner?.SpawnAll();
}
// Respawn points
// This is not the most efficient way to do this.
// This checks the distance to every respawn point every physics tick,
// but we only really need to check the next one (or nearest few).
for (uint i = 0; i < _path.Waypoints.Length; i++)
{
var proximityObject = GameObject.Instantiate(GameObject.Zone);
var physics = proximityObject.AddComponent<PhysicsComponent>();
var physicsObject = SphereBody.Create(
GameObject.Zone.Simulation,
_path.Waypoints[i].Position,
50f);
physics.SetPhysics(physicsObject);
// Listen for players entering and leaving.
var playersInPhysicsObject = new List<Player>();
var index = i;
Listen(physics.OnEnter, async component =>
{
if (component.GameObject is not Player player) return;
if (playersInPhysicsObject.Contains(player)) return;
playersInPhysicsObject.Add(player);
// TODO: Check for players driving in the wrong direction
await PlayerReachedCheckpoint(player, index);
});
Listen(physics.OnLeave, component =>
{
if (component.GameObject is not Player player) return;
if (!playersInPhysicsObject.Contains(player)) return;
playersInPhysicsObject.Remove(player);
});
}
Zone.BroadcastMessage(new NotifyRacingClientMessage
{
Associate = this.GameObject,
EventType = RacingClientNotificationType.ActivityStart,
});
// Start after 7 seconds
Task.Run(async () =>
{
await Task.Delay(7000);
this.StartRace();
});
}
private void StartRace()
{
if (_racingStatus != RacingStatus.Loaded)
return;
_racingStatus = RacingStatus.Started;
// Go!
foreach (var info in Players)
{
info.RaceTime.Start();
info.LapTime.Start();
Zone.BroadcastMessage(new VehicleUnlockInputMessage
{
Associate = info.Vehicle,
LockWheels = false,
});
}
Zone.BroadcastMessage(new ActivityStartMessage
{
Associate = this.GameObject,
});
GameObject.Serialize(this.GameObject);
}
public void OnAcknowledgePossession(Player player, GameObject vehicle)
{
}
/// <summary>
/// Respawns the player's car after a crash
/// </summary>
/// <param name="player"></param>
private void OnRacingPlayerInfoResetFinished(Player player)
{
var playerInfoIndex = Players.FindIndex(x => x.Player == player);
if (playerInfoIndex < 0 || playerInfoIndex >= Players.Count) {
Logger.Warning("Invalid playerInfoIndex");
return;
}
var playerInfo = Players[playerInfoIndex];
var car = playerInfo.Vehicle;
if (!playerInfo.NoSmashOnReload)
{
Zone.BroadcastMessage(new DieMessage
{
Associate = car,
DeathType = "violent",
Killer = player,
SpawnLoot = false,
});
player.Message(new VehicleUnlockInputMessage
{
Associate = car,
LockWheels = false,
});
player.Message(new VehicleSetWheelLockStateMessage
{
Associate = car,
ExtraFriction = false,
Locked = false,
});
Zone.BroadcastMessage(new ResurrectMessage
{
Associate = car,
});
}
playerInfo.NoSmashOnReload = false;
Players[playerInfoIndex] = playerInfo;
}
/// <summary>
/// Handler for when the client tells the server that the car crashed
/// </summary>
/// <param name="player"></param>
public void OnPlayerRequestDie(Player player)
{
var racingPlayer = Players.Find(info => info.Player == player);
racingPlayer.SmashedTimes++;
racingPlayer.ResetTimer.Stop();
Logger.Information($"{player} requested death - respawning to {racingPlayer.RespawnPosition}");
if (racingPlayer.RespawnPosition == Vector3.Zero)
racingPlayer.RespawnPosition = _path.Waypoints.First().Position;
player.Zone.ExcludingMessage(new VehicleRemovePassiveBoostAction
{
Associate = racingPlayer.Vehicle,
}, player);
Zone.Schedule(() =>
{
Zone.BroadcastMessage(new RacingSetPlayerResetInfoMessage
{
Associate = GameObject,
CurrentLap = (int)racingPlayer.Lap,
FurthestResetPlane = racingPlayer.RespawnIndex,
PlayerId = player,
RespawnPos = racingPlayer.RespawnPosition + Vector3.UnitY * 3,
UpcomingPlane = racingPlayer.RespawnIndex + 1,
});
Zone.BroadcastMessage(new RacingResetPlayerToLastResetMessage
{
Associate = GameObject,
PlayerId = player,
});
}, 2000);
}
private async Task PlayerReachedCheckpoint(Player player, uint index)
{
Logger.Information($"Player reached checkpoint: {index}");
var waypoint = _path.Waypoints[index];
var playerInfoIndex = Players.FindIndex(x => x.Player == player);
var playerInfo = Players[playerInfoIndex];
// Only count up
if (!IsCheckpointValid(playerInfo.RespawnIndex, index))
{
// Don't reset player after respawning
if (playerInfo.RespawnIndex == index)
{
playerInfo.ResetTimer.Stop();
return;
}
// Don't restart timer if it's already running
if (!playerInfo.ResetTimer.IsRunning)
playerInfo.ResetTimer.Start();
return;
}
playerInfo.ResetTimer.Stop();
playerInfo.RespawnIndex = index;
playerInfo.RespawnPosition = waypoint.Position;
playerInfo.RespawnRotation = player.Transform.Rotation;
// If start point is reached (with 40 sec cheat protection)
if (index == 0 && playerInfo.LapTime.ElapsedMilliseconds > 40000)
{
var lapTime = (int)playerInfo.LapTime.ElapsedMilliseconds;
playerInfo.LapTime.Restart();
playerInfo.Lap++;
OnPlayerLap.Invoke(playerInfo);
Logger.Information($"{playerInfo.Player} now in lap {playerInfo.Lap}");
// Set new best lap if applicable
if (playerInfo.BestLapTime == default || lapTime < playerInfo.BestLapTime.Milliseconds)
{
playerInfo.BestLapTime = new TimeSpan(0, 0, 0, 0, lapTime);
if (playerInfo.Player.TryGetComponent<MissionInventoryComponent>(out MissionInventoryComponent missionInventoryComponent))
await missionInventoryComponent.RacingLaptimeAsync(Zone.ZoneId, lapTime);
}
// If player finished race
if (playerInfo.Lap >= _raceInfo.LapCount)
{
playerInfo.RaceTime.Stop();
playerInfo.Finished = ++_rankCounter;
// Progress missions
if (playerInfo.Player.TryGetComponent<MissionInventoryComponent>(out MissionInventoryComponent missionInventoryComponent))
await missionInventoryComponent.RaceFinishedAsync(Zone.ZoneId, playerInfo.Finished, playerInfo.RaceTime.ElapsedMilliseconds, playerInfo.SmashedTimes, Players.Count);
// Set player score and leaderboard
SetParameter(playerInfo.Player, 1, Players.Count * 10 + playerInfo.Finished);
UpdateLeaderboard(playerInfo);
Logger.Information($"Race finished: {playerInfo.Player}, place {playerInfo.Finished}, time: {playerInfo.RaceTime.ElapsedMilliseconds}, smashed: {playerInfo.SmashedTimes}, best lap: {playerInfo.BestLapTime.TotalMilliseconds}");
}
}
Players[playerInfoIndex] = playerInfo;
GameObject.Serialize(this.GameObject);
}
private void ResetPlayer(Player player)
{
Logger.Information("Reset Player");
var racingPlayer = Players.Find(info => info.Player == player);
if (racingPlayer.RespawnPosition == Vector3.Zero)
racingPlayer.RespawnPosition = _path.Waypoints.First().Position;
player.Zone.ExcludingMessage(new VehicleRemovePassiveBoostAction
{
Associate = racingPlayer.Vehicle,
}, player);
Zone.BroadcastMessage(new RacingSetPlayerResetInfoMessage
{
Associate = GameObject,
CurrentLap = (int)racingPlayer.Lap,
FurthestResetPlane = racingPlayer.RespawnIndex,
PlayerId = player,
RespawnPos = racingPlayer.RespawnPosition + Vector3.UnitY * 5,
UpcomingPlane = racingPlayer.RespawnIndex + 1,
});
Zone.BroadcastMessage(new RacingResetPlayerToLastResetMessage
{
Associate = GameObject,
PlayerId = player,
});
}
private bool IsCheckpointValid(uint oldIndex, uint newIndex)
{
// Only allow forward (with a bit of tolerance)
if (newIndex > oldIndex && (newIndex - oldIndex) < 10)
return true;
// Only go from last checkpoint to first (with a bit of tolerance)
if (newIndex == 0 && (_path.Waypoints.Length - oldIndex) < 10)
return true;
return false;
}
private void UpdateLeaderboard(RacingPlayerInfo playerInfo)
{
var player = playerInfo.Player;
int lapTime = (int)(playerInfo.BestLapTime.TotalMilliseconds / 1000d);
int raceTime = (int)(playerInfo.RaceTime.ElapsedMilliseconds / 1000d);
var rank = playerInfo.Finished;
Logger.Debug("RaceTime: " + raceTime + " LapTime: " + lapTime);
var yearAndWeek = ISOWeek.GetYear(DateTime.Now) * 100 + ISOWeek.GetWeekOfYear(DateTime.Now);
using var ctx = new UchuContext();
var existingWeekly = ctx.ActivityScores.FirstOrDefault(entry =>
entry.Activity == this.ActivityInfo.ActivityID
&& entry.Zone == Convert.ToInt32(player.Zone.ZoneId)
&& entry.CharacterId == (long)player.Id
&& entry.Week == yearAndWeek);
var existingAllTime = ctx.ActivityScores.FirstOrDefault(entry =>
entry.Activity == this.ActivityInfo.ActivityID
&& entry.Zone == Convert.ToInt32(player.Zone.ZoneId)
&& entry.CharacterId == (long)player.Id
&& entry.Week == 0);
// Update existing weekly leaderboard entry
if (existingWeekly != null)
{
existingWeekly.Time = Math.Min(existingWeekly.Time, raceTime);
existingWeekly.BestLapTime = Math.Min(existingWeekly.BestLapTime, lapTime);
existingWeekly.Wins += rank == 1 ? 1 : 0;
Logger.Debug("Weekly: " + existingWeekly.Time + " Lap: " + existingWeekly.BestLapTime);
ctx.ActivityScores.Update(existingWeekly);
}
// Add new entry
else
{
ctx.ActivityScores.Add(new ActivityScore
{
Activity = this.ActivityInfo.ActivityID ?? 0,
Zone = player.Zone.ZoneId,
CharacterId = player.Id,
Time = raceTime,
BestLapTime = lapTime,
Wins = rank == 1 ? 1 : 0,
Week = yearAndWeek,
});
}
// Update existing all-time leaderboard entry.
if (existingAllTime != null)
{
existingAllTime.NumPlayed++;
existingAllTime.Time = Math.Min(existingAllTime.Time, raceTime);
existingAllTime.BestLapTime = Math.Min(existingAllTime.BestLapTime, lapTime);
existingAllTime.Wins += rank == 1 ? 1 : 0;
existingAllTime.LastPlayed = DateTimeOffset.Now.ToUnixTimeSeconds();
Logger.Debug("AllTime: " + existingAllTime.Time + " Lap: " + existingAllTime.BestLapTime);
ctx.ActivityScores.Update(existingAllTime);
}
// Add new entry.
else
{
ctx.ActivityScores.Add(new ActivityScore
{
Activity = this.ActivityInfo.ActivityID ?? 0,
Zone = player.Zone.ZoneId,
CharacterId = player.Id,
Time = raceTime,
BestLapTime = lapTime,
Wins = rank == 1 ? 1 : 0,
LastPlayed = DateTimeOffset.Now.ToUnixTimeSeconds(),
NumPlayed = 1,
Week = 0,
});
}
ctx.SaveChanges();
}
public override void Construct(BitWriter writer)
{
this.Serialize(writer);
}
// override to be able to use ScriptedActivityComponent as base
public override void Serialize(BitWriter writer)
{
base.Serialize(writer);
StructPacketParser.WritePacket(this.GetSerializePacket(), writer);
}
public new RacingControlSerialization GetSerializePacket()
{
var packet = this.GetPacket<RacingControlSerialization>();
packet.ExpectedPlayerCount = (ushort)this.Participants.Count;
packet.PreRacePlayerInfos = this.Players.Select(info => new PreRacePlayerInfo
{
Player = info.Player,
Vehicle = info.Vehicle,
StartingPosition = info.PlayerIndex,
IsReady = info.PlayerLoaded,
}).ToArray();
packet.RaceInfo = _raceInfo;
packet.DuringRacePlayerInfos = this.Players.Select(info => new DuringRacePlayerInfo
{
Player = info.Player,
BestLapTime = (float)info.BestLapTime.TotalSeconds,
RaceTime = (float)info.RaceTime.Elapsed.TotalSeconds,
}).ToArray();
packet.PostRacePlayerInfos = this.Players.Select(info => new PostRacePlayerInfo
{
Player = info.Player,
CurrentRank = info.Finished
}).ToArray();
return packet;
}
private enum RacingStatus
{
None,
Loaded,
Started,
}
private struct MainWorldReturnData
{
public ZoneId ZoneId { get; set; }
public Vector3 Position { get; set; }
public Quaternion Rotation { get; set; }
}
public struct RacingPlayerInfo
{
public Player Player { get; set; }
public GameObject Vehicle { get; set; }
public uint PlayerIndex { get; set; }
public bool PlayerLoaded { get; set; }
public float[] Data { get; set; }
public Vector3 RespawnPosition { get; set; }
public Quaternion RespawnRotation { get; set; }
public uint RespawnIndex { get; set; }
public uint Lap { get; set; }
public uint Finished { get; set; }
public uint ReachedPoints { get; set; }
public TimeSpan BestLapTime { get; set; }
public Stopwatch LapTime { get; set; }
public uint SmashedTimes { get; set; }
public bool NoSmashOnReload { get; set; }
public bool CollectedRewards { get; set; }
public Stopwatch RaceTime { get; set; }
public SimpleTimer ResetTimer { get; set; }
};
public class RacingMatchCommands {
RacingControlComponent RacingControl;
public RacingMatchCommands(RacingControlComponent racingControl) {
this.RacingControl = racingControl;
}
[ApiCommand("match/addMatchPlayer")]
public object AddMatchPlayer(string id)
{
var response = new BaseResponse();
if (ulong.TryParse(id, out var objectId))
{
RacingControl.AddExpectedPlayer(objectId);
response.Success = true;
return response;
}
response.FailedReason = "invalid id";
return response;
}
}
}
}
| 412 | 0.949573 | 1 | 0.949573 | game-dev | MEDIA | 0.692573 | game-dev | 0.921089 | 1 | 0.921089 |
ddf8196/FakePlayer | 11,773 | src/main/java/com/ddf/fakeplayer/level/chunk/LevelChunk.java | package com.ddf.fakeplayer.level.chunk;
import com.ddf.fakeplayer.block.BedrockBlocks;
import com.ddf.fakeplayer.block.Block;
import com.ddf.fakeplayer.block.BlockPos;
import com.ddf.fakeplayer.blockactor.BlockActor;
import com.ddf.fakeplayer.level.DirtyTicksCounter;
import com.ddf.fakeplayer.level.Level;
import com.ddf.fakeplayer.level.chunk.subchunk.SubChunk;
import com.ddf.fakeplayer.level.chunk.subchunk.SubChunkBlockPos;
import com.ddf.fakeplayer.level.chunk.subchunk.SubChunkInitMode;
import com.ddf.fakeplayer.level.dimension.Dimension;
import com.ddf.fakeplayer.nbt.CompoundTag;
import com.ddf.fakeplayer.nbt.NbtIo;
import com.ddf.fakeplayer.util.*;
import com.ddf.fakeplayer.util.mc.SharedConstants;
import com.ddf.fakeplayer.util.threading.SpinLock;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class LevelChunk {
private Level mLevel;
private Dimension mDimension;
private BlockPos mMin;
private BlockPos mMax;
private ChunkPos mPosition;
private boolean mLightingFixupDone;
private AtomicBoolean mLightingTaskActive;
private boolean mReadOnly;
private ChunkSource mGenerator;
private LevelChunkFormat mLoadedFormat;
private String mSerializedEntitiesBuffer;
private AtomicReference<ChunkState> mLoadState;
private ChunkTerrainDataState mTerrainDataState;
private ChunkDebugDisplaySavedState mDebugDisplaySavedState;
private ChunkCachedDataState mCachedDataState;
private SpinLock mCachedDataStateSpinLock;
private long mLastTick;
// std::unique_ptr<BlockTickingQueue,std::default_delete<BlockTickingQueue> > mTickQueue;
// std::unique_ptr<BlockTickingQueue,std::default_delete<BlockTickingQueue> > mRandomTickQueue;
/*AppendOnlyAtomicLookupTable<SubChunk,16>*/
private List<SubChunk> mSubChunks = Collections.synchronizedList(new ArrayList<>(16));
private SpinLock[] mSubChunkSpinLocks = new SpinLock[16];
private byte[] mBiomes = new byte[256];
// std::array<ColumnCachedData,256> mCachedData;
private short[] mHeightmap = new short[256];
// std::unique_ptr<std::vector<short,std::allocator<short> >,std::default_delete<std::vector<short,std::allocator<short> > > > mPreWorldGenHeightmap;
private HashMap<Byte, BiomeChunkState> mBiomeStates = new HashMap<>();
private boolean mHasCachedTemperatureNoise;
private byte[] mBorderBlockMap = new byte[256];
private LevelChunk.Finalization mFinalized;
private boolean mIsRedstoneLoaded;
private boolean mOwnedByTickingThread;
private DirtyTicksCounter[] mFullChunkDirtyTicksCounters = new DirtyTicksCounter[6];
private short[] mRainHeights = new short[256];
// OwnedActorSet mEntities;
// LevelChunk::OwnedBlockActorMap mBlockEntities;
// LevelChunk::BlockActorVector mDeletedBlockEntities;
private BrightnessPair mDefaultBrightness;
private ArrayList<LevelChunk.HardcodedSpawningArea> mHardcodedSpawningAreas;
/*uint8_t*/byte[][] mbChunkInterpolants = new byte[2][2];
private boolean mbChunkHasConverterTag;
private boolean mDBChunkSurroundedByNeighbors;
public LevelChunk(Dimension dimension, final ChunkPos cp, boolean readOnly) {
this.mLevel = dimension.getLevel();
this.mDimension = dimension;
this.mMin = new BlockPos(cp, 0);
this.mMax = new BlockPos(cp, 0).addAndSet(15, dimension.getHeight() - 1, 15);
this.mPosition = new ChunkPos(cp);
this.mLightingFixupDone = false;
this.mLightingTaskActive = new AtomicBoolean(false);
this.mReadOnly = readOnly;
this.mGenerator = null;
this.mLoadedFormat = SharedConstants.CurrentLevelChunkFormat;
this.mSerializedEntitiesBuffer = "";
this.mLoadState = new AtomicReference<>(ChunkState.Unloaded);
this.mTerrainDataState = ChunkTerrainDataState.NoData_0;
this.mDebugDisplaySavedState = ChunkDebugDisplaySavedState.Generated_1;
this.mCachedDataState = ChunkCachedDataState.NotGenerated;
this.mCachedDataStateSpinLock = new SpinLock();
this.mLastTick = 0;
// this.mTickQueue = new BlockTickingQueue();
// this.mRandomTickQueue = new BlockTickingQueue();
// this.mSubChunkSpinLocks = new SpinLock[16];
// this.mPreWorldGenHeightmap = new ArrayList<>();
// this.mBiomeStates = new HashMap<>();
this.mHasCachedTemperatureNoise = false;
this.mFinalized = Finalization.NeedsInstaticking;
this.mIsRedstoneLoaded = false;
this.mOwnedByTickingThread = false;
for (int index = 0; index < this.mFullChunkDirtyTicksCounters.length; index++) {
this.mFullChunkDirtyTicksCounters[index] = new DirtyTicksCounter();
}
// this.mEntities = new ArrayList<>(0);
// this.mBlockEntities = new HashMap<>();
// this.mDeletedBlockEntities = new ArrayList<>();
this.mDefaultBrightness = dimension.getDefaultBrightness();
this.mHardcodedSpawningAreas = new ArrayList<>();
this.mbChunkHasConverterTag = false;
this.mDBChunkSurroundedByNeighbors = false;
Arrays.fill(this.mHeightmap, (short) 0);
/*unsigned __int8 BiomeChunkData*/int zeroBiomeChunkData = dimension.getDefaultBiome();
Arrays.fill(this.mBiomes, (byte) zeroBiomeChunkData);
Arrays.fill(this.mBorderBlockMap, (byte) 0);
Arrays.fill(this.mRainHeights, (short) -999);
}
public static LevelChunk createNew(Dimension dimension, ChunkPos cp, boolean readOnly) {
return new LevelChunk(dimension, cp, readOnly);
}
private SubChunk _createSubChunk(/*size_t*/int idx, boolean initSkyLight, SubChunkInitMode initBlocks) {
SubChunk subChunk = null;
for (int currentIdx = this.mSubChunks.size(); currentIdx <= idx; ++currentIdx) {
Block defaultBlock = null;
if (initBlocks == SubChunkInitMode.All) {
defaultBlock = BedrockBlocks.mAir;
} else if (initBlocks == SubChunkInitMode.AllButLast && currentIdx != idx) {
defaultBlock = BedrockBlocks.mAir;
}
subChunk = new SubChunk(defaultBlock, initSkyLight && this.mDefaultBrightness.sky > Brightness.MIN, false, this.mSubChunkSpinLocks[this.mSubChunks.size()]);
this.mSubChunks.add(subChunk);
}
return subChunk;
}
public final Block getBlock(final ChunkBlockPos pos) {
SubChunk sc = this.mSubChunks.get(pos.y >> 4);
if (sc == null)
return BedrockBlocks.mAir;
short blockIdx = new SubChunkBlockPos(pos).index();
return sc.getBlock(blockIdx);
}
public final Block getExtraBlock(ChunkBlockPos localPos) {
SubChunk sc = this.mSubChunks.get(localPos.y >> 4);
if (sc == null)
return BedrockBlocks.mAir;
short blockIdx = new SubChunkBlockPos(localPos).index();
return sc.getExtraBlock(blockIdx);
}
public boolean getBorder(final ChunkBlockPos pos) {
return this.mBorderBlockMap[pos.index2D()] != 0;
}
public final ChunkPos getPosition() {
return this.mPosition;
}
public final AtomicReference<ChunkState> getState() {
return this.mLoadState;
}
public final List<SubChunk> getSubChunks() {
return this.mSubChunks;
}
public final boolean isReadOnly() {
return this.mReadOnly;
}
private short findHighestNonAirBlock(Block[] blocks, short sourceColumnHeight) {
short highest = 0;
int basePtr = 0;
int end = blocks.length;
while (basePtr < end) {
for (int j = sourceColumnHeight - 1; j > highest; --j) {
if (blocks[basePtr + j] != BedrockBlocks.mAir )
highest = (short) j;
}
basePtr += sourceColumnHeight;
}
return highest;
}
public final void setAllBlocks(Block[] blocks, short sourceColumnHeight) {
int hidx = findHighestNonAirBlock(blocks, sourceColumnHeight);
if (hidx != 0) {
this._createSubChunk(hidx >> 4, false, SubChunkInitMode.None_12);
int offset = 0;
for (SubChunk sc : this.getSubChunks()) {
sc.setAllBlocks(blocks, offset, sourceColumnHeight);
offset += 16;
}
}
}
public final void changeState(ChunkState from, ChunkState to) {
this.tryChangeState(from, to);
}
public final boolean tryChangeState(ChunkState from, ChunkState to) {
return this.mLoadState.compareAndSet(from, to);
}
public final void deserializeSubChunk(/*uint8_t*/int idx, IDataInput stream) {
SubChunk subChunk = this._createSubChunk(idx, false, SubChunkInitMode.AllButLast);
subChunk.deserialize(stream, this.mLevel.getGlobalBlockPalette());
}
public final void deserializeBiomes(IDataInput stream) {
stream.readBytes(this.mBiomes, 0, 256);
this.checkBiomeStates();
}
public final void deserializeBorderBlocks(IDataInput stream) {
for (byte count = stream.readByte(); count != 0; --count ) {
byte index = stream.readByte();
this.mBorderBlockMap[index] = 1;
}
}
@NotImplemented
public final void deserializeBlockEntities(IDataInput stream) {
// DefaultDataLoadHelper dataLoadHelper = new DefaultDataLoadHelper();
while (stream.numBytesLeft() > 0) {
BlockActor e = null;
CompoundTag et = NbtIo.read(stream);
// if (et != null) {
// e = BlockActor.loadStatic(this.mLevel, et, dataLoadHelper);
// }
//
}
}
@NotImplemented
private void checkBiomeStates() {
// Map<Byte, BiomeChunkState> oldBiomeStates = new HashMap<>(this.mBiomeStates);
// this.mBiomeStates.clear();
// for (int id : this.mBiomes) {
// Biome biome = this.mLevel.getBiomeRegistry().lookupById(id);
// if (biome == null) {
// BiomeIdCompatibility.isReserved(id);
// id = (*((__int64 (__fastcall **)(Dimension *))this->mDimension->_vptr$BlockSourceListener + 48))(this->mDimension);
// biome = this.mLevel.getBiomeRegistry().lookupById(id);
// }
// if (biome.canHaveSnowfall()) {
// if (oldBiomeStates.containsKey(biome.mId)) {
// this.mBiomeStates[biome.mId].snowLevel = oldBiomeStates.get(biome.mId).snowLevel;
// } else {
// this.mBiomeStates[biome.mId].snowLevel = 0;
// }
// }
// }
}
private void _enableBlockEntityAccessForThisThread() {
}
public final void onTickingStarted() {
this._enableBlockEntityAccessForThisThread();
this.mOwnedByTickingThread = true;
}
public static class HardcodedSpawningArea {
BoundingBox aabb;
HardcodedSpawnAreaType type;
}
public enum Tag {
Data2D(0x2D),
Data2DLegacy(0x2E),
SubChunkPrefix(0x2F),
LegacyTerrain(0x30),
BlockEntity_1(0x31),
Entity_6(0x32),
PendingTicks_0(0x33),
LegacyBlockExtraData(0x34),
BiomeState_0(0x35),
FinalizedState(0x36),
ConversionData(0x37),
BorderBlocks_0(0x38),
HardcodedSpawners(0x39),
RandomTicks_0(0x3A),
Version(0x76);
private final int tag;
Tag(int tag) {
this.tag = tag;
}
public int getTag() {
return tag;
}
}
public enum Finalization {
NeedsInstaticking,
NeedsPopulation,
Done
}
}
| 412 | 0.886653 | 1 | 0.886653 | game-dev | MEDIA | 0.913139 | game-dev | 0.748862 | 1 | 0.748862 |
GarageGames/Qt | 4,400 | qt-5/qtwebkit/Source/JavaScriptCore/bytecompiler/LabelScope.h | /*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LabelScope_h
#define LabelScope_h
#include <wtf/PassRefPtr.h>
#include "Label.h"
namespace JSC {
class Identifier;
class LabelScope {
public:
enum Type { Loop, Switch, NamedLabel };
LabelScope(Type type, const Identifier* name, int scopeDepth, PassRefPtr<Label> breakTarget, PassRefPtr<Label> continueTarget)
: m_refCount(0)
, m_type(type)
, m_name(name)
, m_scopeDepth(scopeDepth)
, m_breakTarget(breakTarget)
, m_continueTarget(continueTarget)
{
}
int refCount() const { return m_refCount; }
Label* breakTarget() const { return m_breakTarget.get(); }
Label* continueTarget() const { return m_continueTarget.get(); }
Type type() const { return m_type; }
const Identifier* name() const { return m_name; }
int scopeDepth() const { return m_scopeDepth; }
private:
friend class LabelScopePtr;
void ref() { ++m_refCount; }
void deref()
{
--m_refCount;
ASSERT(m_refCount >= 0);
}
int m_refCount;
Type m_type;
const Identifier* m_name;
int m_scopeDepth;
RefPtr<Label> m_breakTarget;
RefPtr<Label> m_continueTarget;
};
typedef Vector<LabelScope, 8> LabelScopeStore;
class LabelScopePtr {
public:
LabelScopePtr()
: m_owner(0)
, m_index(0)
{
}
LabelScopePtr(LabelScopeStore* owner, size_t index)
: m_owner(owner)
, m_index(index)
{
m_owner->at(index).ref();
}
LabelScopePtr(const LabelScopePtr& other)
: m_owner(other.m_owner)
, m_index(other.m_index)
{
if (m_owner)
m_owner->at(m_index).ref();
}
const LabelScopePtr& operator=(const LabelScopePtr& other)
{
if (other.m_owner)
other.m_owner->at(other.m_index).ref();
if (m_owner)
m_owner->at(m_index).deref();
m_owner = other.m_owner;
m_index = other.m_index;
return *this;
}
~LabelScopePtr()
{
if (m_owner)
m_owner->at(m_index).deref();
}
LabelScope& operator*() { ASSERT(m_owner); return m_owner->at(m_index); }
LabelScope* operator->() { ASSERT(m_owner); return &m_owner->at(m_index); }
const LabelScope& operator*() const { ASSERT(m_owner); return m_owner->at(m_index); }
const LabelScope* operator->() const { ASSERT(m_owner); return &m_owner->at(m_index); }
private:
LabelScopeStore* m_owner;
size_t m_index;
};
} // namespace JSC
#endif // LabelScope_h
| 412 | 0.886128 | 1 | 0.886128 | game-dev | MEDIA | 0.144079 | game-dev | 0.501778 | 1 | 0.501778 |
CCBlueX/LiquidBounce | 1,558 | src/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/movement/noslow/modes/blocking/NoSlowBlockingInteract.kt | package net.ccbluex.liquidbounce.features.module.modules.movement.noslow.modes.blocking
import net.ccbluex.liquidbounce.config.types.nesting.Choice
import net.ccbluex.liquidbounce.config.types.nesting.ChoiceConfigurable
import net.ccbluex.liquidbounce.event.EventState
import net.ccbluex.liquidbounce.event.events.PlayerNetworkMovementTickEvent
import net.ccbluex.liquidbounce.event.handler
import net.ccbluex.liquidbounce.features.module.modules.movement.noslow.modes.blocking.NoSlowBlock.modes
import net.ccbluex.liquidbounce.utils.client.InteractionTracker.blockingHand
import net.ccbluex.liquidbounce.utils.client.InteractionTracker.isBlocking
import net.ccbluex.liquidbounce.utils.client.InteractionTracker.untracked
import net.minecraft.network.packet.c2s.play.PlayerInteractItemC2SPacket
import net.minecraft.network.packet.c2s.play.UpdateSelectedSlotC2SPacket
internal object NoSlowBlockingInteract : Choice("Interact") {
override val parent: ChoiceConfigurable<Choice>
get() = modes
@Suppress("unused")
val onNetworkTick = handler<PlayerNetworkMovementTickEvent> { event ->
if (isBlocking) {
if (event.state == EventState.POST) {
untracked {
network.sendPacket(UpdateSelectedSlotC2SPacket(player.inventory.selectedSlot))
interaction.sendSequencedPacket(world) { sequence ->
PlayerInteractItemC2SPacket(blockingHand, sequence, player.yaw, player.pitch)
}
}
}
}
}
}
| 412 | 0.734403 | 1 | 0.734403 | game-dev | MEDIA | 0.565518 | game-dev | 0.545325 | 1 | 0.545325 |
keijiro/SlicerFx | 4,996 | Assets/Reaktion/Editor/Utility/ConstantMotionEditor.cs | //
// Reaktion - An audio reactive animation toolkit for Unity.
//
// Copyright (C) 2013, 2014 Keijiro Takahashi
//
// 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.
//
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace Reaktion {
// Custom property drawer for TransformElement.
[CustomPropertyDrawer(typeof(ConstantMotion.TransformElement))]
class ConstantMotionElementDrawer : PropertyDrawer
{
// Labels and values for TransformMode.
static GUIContent[] modeLabels = {
new GUIContent("Off"),
new GUIContent("X Axis"),
new GUIContent("Y Axis"),
new GUIContent("Z Axis"),
new GUIContent("Arbitrary Vector"),
new GUIContent("Random Vector")
};
static int[] modeValues = { 0, 1, 2, 3, 4, 5 };
static int GetExpansionLevel(SerializedProperty property)
{
var mode = property.FindPropertyRelative("mode");
// Fully expand if it has different values.
if (mode.hasMultipleDifferentValues) return 2;
// "Off"
if (mode.enumValueIndex == 0) return 0;
// Fully expand if it's in Arbitrary mode.
if (mode.enumValueIndex == (int)ConstantMotion.TransformMode.Arbitrary) return 2;
// Expand one level.
return 1;
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
int rows = new int[]{1, 3, 4}[GetExpansionLevel(property)];
return EditorGUIUtility.singleLineHeight * rows +
EditorGUIUtility.standardVerticalSpacing * (rows - 1);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
position.height = EditorGUIUtility.singleLineHeight;
var rowHeight = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
// Transform mode selector drop-down.
EditorGUI.IntPopup(position, property.FindPropertyRelative("mode"), modeLabels, modeValues, label);
position.y += rowHeight;
var expansion = GetExpansionLevel(property);
if (expansion > 0)
{
// Insert an indent.
position.x += 16;
position.width -= 16;
EditorGUIUtility.labelWidth -= 16;
if (expansion == 2)
{
// Vector box.
EditorGUI.PropertyField(position, property.FindPropertyRelative("arbitraryVector"), GUIContent.none);
position.y += rowHeight;
}
// Velocity box.
EditorGUI.PropertyField(position, property.FindPropertyRelative("velocity"), new GUIContent("Velocity"));
position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
// Randomness slider.
EditorGUI.Slider(position, property.FindPropertyRelative("randomness"), 0, 1, new GUIContent("Randomness"));
}
EditorGUI.EndProperty();
}
}
[CustomEditor(typeof(ConstantMotion)), CanEditMultipleObjects]
public class ConstantMotionEditor : Editor
{
SerializedProperty propPosition;
SerializedProperty propRotation;
SerializedProperty propUseLocalCoordinate;
GUIContent labelLocalCoordinate;
void OnEnable()
{
propPosition = serializedObject.FindProperty("position");
propRotation = serializedObject.FindProperty("rotation");
propUseLocalCoordinate = serializedObject.FindProperty("useLocalCoordinate");
labelLocalCoordinate = new GUIContent("Local Coordinate");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(propPosition);
EditorGUILayout.PropertyField(propRotation);
EditorGUILayout.PropertyField(propUseLocalCoordinate, labelLocalCoordinate);
serializedObject.ApplyModifiedProperties();
}
}
} // namespace Reaktion
| 412 | 0.88215 | 1 | 0.88215 | game-dev | MEDIA | 0.848201 | game-dev | 0.915933 | 1 | 0.915933 |
quiverteam/Engine | 33,584 | src/common/staticlink/system.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: static link master include
//
// $NoKeywords: $
//=============================================================================//
#ifndef SYSTEM_H
#define SYSTEM_H
#pragma once
#define UID_PREFIX generated_id_
#define UID_CAT1(a,c) a ## c
#define UID_CAT2(a,c) UID_CAT1(a,c)
#define EXPAND_CONCAT(a,c) UID_CAT1(a,c)
#define UNIQUE_ID UID_CAT2(UID_PREFIX,__LINE__)
// helper atom macros - force preprocessor symbol expansion
#define SYMBOL_TO_STRING(token1) #token1
#define EXPAND_SYMBOL_TO_STRING(token1) SYMBOL_TO_STRING(token1)
#define EXPAND_SYMBOL(token) token
#if defined(_STATIC_LINKED)
// for platforms built with static linking, the dll interface gets spoofed
// Contains each published subsystem's 'CreateInterface'
typedef void* (*createFn)(const char *pName, int *pReturnCode);
class DynamicLibraryList
{
public:
DynamicLibraryList(const char* subSystemName, createFn createFunction);
const char *m_subSystemName;
createFn m_createFn;
DynamicLibraryList *m_next;
static DynamicLibraryList *s_DynamicLibraryList;
};
// creates the unique dll subsystem class symbol
// class constructor handles the list population
#define MAKE_DLL_CLASS(subSystem) static DynamicLibraryList __g_##subSystem##_DynamicLibrary(EXPAND_SYMBOL_TO_STRING(_SUBSYSTEM), CreateInterface);
#if defined(_SUBSYSTEM)
#define PUBLISH_DLL_SUBSYSTEM() MAKE_DLL_CLASS(_SUBSYSTEM)
#else
// must define _SUBSYSTEM
#define PUBLISH_DLL_SUBSYSTEM() Project error ... Missing _SUBSYSTEM=<name>
#endif
#endif
#if !defined(_STATIC_LINKED) && !defined(PUBLISH_DLL_SUBSYSTEM)
// for platforms built with dynamic linking, the dll interface does not need spoofing
#define PUBLISH_DLL_SUBSYSTEM()
#endif
#if defined(_STATIC_LINKED)
#define PRIVATE static
#else
#define PRIVATE
#endif
#define MAKE_NAME_UNIQUE(identifier) EXPAND_CONCAT(EXPAND_CONCAT(_SUBSYSTEM,_),identifier)
// the low tech solution
#if defined(_STATIC_LINKED)
#define ActivityDataOps MAKE_NAME_UNIQUE(ActivityDataOps)
#define ActivityList_Free MAKE_NAME_UNIQUE(ActivityList_Free)
#define ActivityList_IndexForName MAKE_NAME_UNIQUE(ActivityList_IndexForName)
#define ActivityList_Init MAKE_NAME_UNIQUE(ActivityList_Init)
#define ActivityList_NameForIndex MAKE_NAME_UNIQUE(ActivityList_NameForIndex)
#define ActivityList_RegisterPrivateActivity MAKE_NAME_UNIQUE(ActivityList_RegisterPrivateActivity)
#define ActivityList_RegisterSharedActivities MAKE_NAME_UNIQUE(ActivityList_RegisterSharedActivities)
#define ActivityList_RegisterSharedActivity MAKE_NAME_UNIQUE(ActivityList_RegisterSharedActivity)
#define activitylist_t MAKE_NAME_UNIQUE(activitylist_t)
#define AddSurfacepropFile MAKE_NAME_UNIQUE(AddSurfacepropFile)
#define AllocateStringHelper MAKE_NAME_UNIQUE(AllocateStringHelper)
#define AllocateStringHelper2 MAKE_NAME_UNIQUE(AllocateStringHelper2)
#define AllocateUniqueDataTableName MAKE_NAME_UNIQUE(AllocateUniqueDataTableName)
#define andomVector MAKE_NAME_UNIQUE(andomVector)
#define ApplyMultiDamage MAKE_NAME_UNIQUE(ApplyMultiDamage)
#define BlendBones MAKE_NAME_UNIQUE(BlendBones)
#define BreakModelList MAKE_NAME_UNIQUE(BreakModelList)
#define BuildAllAnimationEventIndexes MAKE_NAME_UNIQUE(BuildAllAnimationEventIndexes)
#define BuildBoneChain MAKE_NAME_UNIQUE(BuildBoneChain)
#define CActivityDataOps MAKE_NAME_UNIQUE(CActivityDataOps)
#define CalcBoneAdj MAKE_NAME_UNIQUE(CalcBoneAdj)
#define CalcBoneDerivatives MAKE_NAME_UNIQUE(CalcBoneDerivatives)
#define CalcBonePosition MAKE_NAME_UNIQUE(CalcBonePosition)
#define CalcBoneQuaternion MAKE_NAME_UNIQUE(CalcBoneQuaternion)
#define CalcBoneVelocityFromDerivative MAKE_NAME_UNIQUE(CalcBoneVelocityFromDerivative)
#define CalcPoseSingle MAKE_NAME_UNIQUE(CalcPoseSingle)
#define CalcProceduralBone MAKE_NAME_UNIQUE(CalcProceduralBone)
#define CalcRopeStartingConditions MAKE_NAME_UNIQUE(CalcRopeStartingConditions)
#define CAmmoDef MAKE_NAME_UNIQUE(CAmmoDef)
#define CAutoGameSystem MAKE_NAME_UNIQUE(CAutoGameSystem)
#define CAutoGameSystemPerFrame MAKE_NAME_UNIQUE(CAutoGameSystemPerFrame)
#define CBaseEntityList MAKE_NAME_UNIQUE(CBaseEntityList)
#define CBaseGameSystem MAKE_NAME_UNIQUE(CBaseGameSystem)
#define CBaseGameSystemPerFrame MAKE_NAME_UNIQUE(CBaseGameSystemPerFrame)
#define CBaseHandle MAKE_NAME_UNIQUE(CBaseHandle)
#define CBasePanel MAKE_NAME_UNIQUE(CBasePanel)
#define CBasePlayerAnimState MAKE_NAME_UNIQUE(CBasePlayerAnimState)
#define CBaseRopePhysics MAKE_NAME_UNIQUE(CBaseRopePhysics)
#define CBoneCache MAKE_NAME_UNIQUE(CBoneCache)
#define CCollisionEvent MAKE_NAME_UNIQUE(CCollisionEvent)
#define CCollisionProperty MAKE_NAME_UNIQUE(CCollisionProperty)
#define CCopyRecipientFilter MAKE_NAME_UNIQUE(CCopyRecipientFilter)
#define CPASFilter MAKE_NAME_UNIQUE(CPASFilter)
#define CPVSFilter MAKE_NAME_UNIQUE(CPVSFilter)
#define CPASAttenuationFilter MAKE_NAME_UNIQUE(CPASAttenuationFilter)
#define CDataObjectAccessSystem MAKE_NAME_UNIQUE(CDataObjectAccessSystem)
#define CDecalEmitterSystem MAKE_NAME_UNIQUE(CDecalEmitterSystem)
#define CDirtySpatialPartitionEntityList MAKE_NAME_UNIQUE(CDirtySpatialPartitionEntityList)
#define CEntInfo MAKE_NAME_UNIQUE(CEntInfo)
#define CEntityMapData MAKE_NAME_UNIQUE(CEntityMapData)
#define CEntitySaveRestoreBlockHandler MAKE_NAME_UNIQUE(CEntitySaveRestoreBlockHandler)
#define CEntitySaveUtils MAKE_NAME_UNIQUE(CEntitySaveUtils)
#define CEntitySphereQuery MAKE_NAME_UNIQUE(CEntitySphereQuery)
#define CEnvHeadcrabCanisterShared MAKE_NAME_UNIQUE(CEnvHeadcrabCanisterShared)
#define CEnvWindShared MAKE_NAME_UNIQUE(CEnvWindShared)
#define CFlaggedEntitiesEnum MAKE_NAME_UNIQUE(CFlaggedEntitiesEnum)
#define CFlexSceneFileManager MAKE_NAME_UNIQUE(CFlexSceneFileManager)
#define CGameMovement MAKE_NAME_UNIQUE(CGameMovement)
#define CGameRulesRegister MAKE_NAME_UNIQUE(CGameRulesRegister)
#define CGameSaveRestoreInfo MAKE_NAME_UNIQUE(CGameSaveRestoreInfo)
#define CGameStringPool MAKE_NAME_UNIQUE(CGameStringPool)
#define CGameTrace MAKE_NAME_UNIQUE(CGameTrace)
#define CGameUI MAKE_NAME_UNIQUE(CGameUI)
#define CGameWeaponManager MAKE_NAME_UNIQUE(CGameWeaponManager)
#define CHL2GameMovement MAKE_NAME_UNIQUE(CHL2GameMovement)
#define CIKContext MAKE_NAME_UNIQUE(CIKContext)
#define CIKTarget MAKE_NAME_UNIQUE(CIKTarget)
#define CIterativeSheetSimulator MAKE_NAME_UNIQUE(CIterativeSheetSimulator)
#define ClearMultiDamage MAKE_NAME_UNIQUE(ClearMultiDamage)
#define CMessage MAKE_NAME_UNIQUE(CMessage)
#define CMultiDamage MAKE_NAME_UNIQUE(CMultiDamage)
#define CObjectsFileLoad MAKE_NAME_UNIQUE(CObjectsFileLoad)
#define ComputeSurroundingBox MAKE_NAME_UNIQUE(ComputeSurroundingBox)
#define CountdownTimer MAKE_NAME_UNIQUE(CountdownTimer)
#define CPhysicsGameTrace MAKE_NAME_UNIQUE(CPhysicsGameTrace)
#define CPhysicsSpring MAKE_NAME_UNIQUE(CPhysicsSpring)
#define CPhysObjSaveRestoreOps MAKE_NAME_UNIQUE(CPhysObjSaveRestoreOps)
#define CPhysSaveRestoreBlockHandler MAKE_NAME_UNIQUE(CPhysSaveRestoreBlockHandler)
#define CPlayerLocalData MAKE_NAME_UNIQUE(CPlayerLocalData)
#define CPlayerState MAKE_NAME_UNIQUE(CPlayerState)
#define CPositionWatcherList MAKE_NAME_UNIQUE(CPositionWatcherList)
#define CPrecacheRegister MAKE_NAME_UNIQUE(CPrecacheRegister)
#define CPredictableId MAKE_NAME_UNIQUE(CPredictableId)
#define CPredictableList MAKE_NAME_UNIQUE(CPredictableList)
#define CPropData MAKE_NAME_UNIQUE(CPropData)
#define CRagdollLowViolenceManager MAKE_NAME_UNIQUE(CRagdollLowViolenceManager)
#define CRagdollLRURetirement MAKE_NAME_UNIQUE(CRagdollLRURetirement)
#define CreateInterface MAKE_NAME_UNIQUE(CreateInterface)
#define CRestore MAKE_NAME_UNIQUE(CRestore)
#define CSave MAKE_NAME_UNIQUE(CSave)
#define CSaveRestoreBlockSet MAKE_NAME_UNIQUE(CSaveRestoreBlockSet)
#define CSaveRestoreData MAKE_NAME_UNIQUE(CSaveRestoreData)
#define CSaveRestoreSegment MAKE_NAME_UNIQUE(CSaveRestoreSegment)
#define CSceneTokenProcessor MAKE_NAME_UNIQUE(CSceneTokenProcessor)
#define CSheetSimulator MAKE_NAME_UNIQUE(CSheetSimulator)
#define CSimplePhysics MAKE_NAME_UNIQUE(CSimplePhysics)
#define CSolidSetDefaults MAKE_NAME_UNIQUE(CSolidSetDefaults)
#define CSoundControllerImp MAKE_NAME_UNIQUE(CSoundControllerImp)
#define CSoundEmitterSystem MAKE_NAME_UNIQUE(CSoundEmitterSystem)
#define CSoundEmitterSystemBase MAKE_NAME_UNIQUE(CSoundEmitterSystemBase)
#define CSoundEnvelope MAKE_NAME_UNIQUE(CSoundEnvelope)
#define CSoundEnvelopeController MAKE_NAME_UNIQUE(CSoundEnvelopeController)
#define CSoundPatch MAKE_NAME_UNIQUE(CSoundPatch)
#define CSoundPatchSaveRestoreOps MAKE_NAME_UNIQUE(CSoundPatchSaveRestoreOps)
#define CStudioBoneCache MAKE_NAME_UNIQUE(CStudioBoneCache)
#define CStudioHdr MAKE_NAME_UNIQUE(CStudioHdr)
#define CTakeDamageInfo MAKE_NAME_UNIQUE(CTakeDamageInfo)
#define CTraceFilterEntity MAKE_NAME_UNIQUE(CTraceFilterEntity)
#define CTraceFilterEntityIgnoreOther MAKE_NAME_UNIQUE(CTraceFilterEntityIgnoreOther)
#define CTraceFilterLOS MAKE_NAME_UNIQUE(CTraceFilterLOS)
#define CTraceFilterNoNPCsOrPlayer MAKE_NAME_UNIQUE(CTraceFilterNoNPCsOrPlayer)
#define CTraceFilterOnlyNPCsAndPlayer MAKE_NAME_UNIQUE(CTraceFilterOnlyNPCsAndPlayer)
#define CTraceFilterSimple MAKE_NAME_UNIQUE(CTraceFilterSimple)
#define CTraceFilterSimpleList MAKE_NAME_UNIQUE(CTraceFilterSimpleList)
#define CTraceFilterSkipNPCs MAKE_NAME_UNIQUE(CTraceFilterSkipNPCs)
#define CTraceFilterSkipTwoEntities MAKE_NAME_UNIQUE(CTraceFilterSkipTwoEntities)
#define CurrentViewOrigin MAKE_NAME_UNIQUE(CurrentViewOrigin)
#define CurrentViewForward MAKE_NAME_UNIQUE(CurrentViewForward)
#define CurrentViewRight MAKE_NAME_UNIQUE(CurrentViewRight)
#define CurrentViewUp MAKE_NAME_UNIQUE(CurrentViewUp)
#define CUserMessages MAKE_NAME_UNIQUE(CUserMessages)
#define cvar MAKE_NAME_UNIQUE(cvar)
#define datacache MAKE_NAME_UNIQUE(datacache)
#define DataTableRecvProxy_LengthProxy MAKE_NAME_UNIQUE(DataTableRecvProxy_LengthProxy)
#define DebugDrawLine MAKE_NAME_UNIQUE(DebugDrawLine)
#define debugoverlay MAKE_NAME_UNIQUE(debugoverlay)
#define decalsystem MAKE_NAME_UNIQUE(decalsystem)
#define DispatchEffect MAKE_NAME_UNIQUE(DispatchEffect)
#define DoAxisInterpBone MAKE_NAME_UNIQUE(DoAxisInterpBone)
#define DoQuatInterpBone MAKE_NAME_UNIQUE(DoQuatInterpBone)
#define engine MAKE_NAME_UNIQUE(engine)
#define engineCache MAKE_NAME_UNIQUE(engineCache)
#define enginesound MAKE_NAME_UNIQUE(enginesound)
#define enginetrace MAKE_NAME_UNIQUE(enginetrace)
#define enginevgui MAKE_NAME_UNIQUE(enginevgui)
#define EntityFromEntityHandle MAKE_NAME_UNIQUE(EntityFromEntityHandle)
#define EntityParticleTrailInfo_t MAKE_NAME_UNIQUE(EntityParticleTrailInfo_t)
#define entitytable_t MAKE_NAME_UNIQUE(entitytable_t)
#define EventList_AddEventEntry MAKE_NAME_UNIQUE(EventList_AddEventEntry)
#define EventList_Free MAKE_NAME_UNIQUE(EventList_Free)
#define EventList_GetEventType MAKE_NAME_UNIQUE(EventList_GetEventType)
#define EventList_IndexForName MAKE_NAME_UNIQUE(EventList_IndexForName)
#define EventList_Init MAKE_NAME_UNIQUE(EventList_Init)
#define EventList_NameForIndex MAKE_NAME_UNIQUE(EventList_NameForIndex)
#define EventList_RegisterPrivateEvent MAKE_NAME_UNIQUE(EventList_RegisterPrivateEvent)
#define EventList_RegisterSharedEvent MAKE_NAME_UNIQUE(EventList_RegisterSharedEvent)
#define EventList_RegisterSharedEvents MAKE_NAME_UNIQUE(EventList_RegisterSharedEvents)
#define ExtractAnimValue MAKE_NAME_UNIQUE(ExtractAnimValue)
#define ExtractBbox MAKE_NAME_UNIQUE(ExtractBbox)
#define FactoryList_Retrieve MAKE_NAME_UNIQUE(FactoryList_Retrieve)
#define FactoryList_Store MAKE_NAME_UNIQUE(FactoryList_Store)
#define FileSystem_LoadModule MAKE_NAME_UNIQUE(FileSystem_LoadModule)
#define FileSystem_Shutdown MAKE_NAME_UNIQUE(FileSystem_Shutdown)
#define FileSystem_UnloadModule MAKE_NAME_UNIQUE(FileSystem_UnloadModule)
#define FileWeaponInfo_t MAKE_NAME_UNIQUE(FileWeaponInfo_t)
#define FindBodygroupByName MAKE_NAME_UNIQUE(FindBodygroupByName)
#define FindHitboxSetByName MAKE_NAME_UNIQUE(FindHitboxSetByName)
#define FindTransitionSequence MAKE_NAME_UNIQUE(FindTransitionSequence)
#define fluidevent_t MAKE_NAME_UNIQUE(fluidevent_t)
#define g_ActivityStrings MAKE_NAME_UNIQUE(g_ActivityStrings)
#define g_bMovementOptimizations MAKE_NAME_UNIQUE(g_bMovementOptimizations)
#define g_bTextMode MAKE_NAME_UNIQUE(g_bTextMode)
#define g_bUsedWeaponSlots MAKE_NAME_UNIQUE(g_bUsedWeaponSlots)
#define g_EntityCollisionHash MAKE_NAME_UNIQUE(g_EntityCollisionHash)
#define g_EventList MAKE_NAME_UNIQUE(g_EventList)
#define g_EventStrings MAKE_NAME_UNIQUE(g_EventStrings)
#define g_FileSystemFactory MAKE_NAME_UNIQUE(g_FileSystemFactory)
#define g_flLastBodyPitch MAKE_NAME_UNIQUE(g_flLastBodyPitch)
#define g_flLastBodyYaw MAKE_NAME_UNIQUE(g_flLastBodyYaw)
#define g_lateralBob MAKE_NAME_UNIQUE(g_lateralBob)
#define g_nActivityListVersion MAKE_NAME_UNIQUE(g_nActivityListVersion)
#define g_nEventListVersion MAKE_NAME_UNIQUE(g_nEventListVersion)
#define g_pDataCache MAKE_NAME_UNIQUE(g_pDataCache)
#define g_pEffects MAKE_NAME_UNIQUE(g_pEffects)
#define g_pFileSystem MAKE_NAME_UNIQUE(g_pFileSystem)
#define g_pGameMovement MAKE_NAME_UNIQUE(g_pGameMovement)
#define g_pGameSaveRestoreBlockSet MAKE_NAME_UNIQUE(g_pGameSaveRestoreBlockSet)
#define g_PhysDefaultObjectParams MAKE_NAME_UNIQUE(g_PhysDefaultObjectParams)
#define g_PhysGameTrace MAKE_NAME_UNIQUE(g_PhysGameTrace)
#define g_PhysObjSaveRestoreOps MAKE_NAME_UNIQUE(g_PhysObjSaveRestoreOps)
#define g_PhysSaveRestoreBlockHandler MAKE_NAME_UNIQUE(g_PhysSaveRestoreBlockHandler)
#define g_PhysWorldObject MAKE_NAME_UNIQUE(g_PhysWorldObject)
#define g_pMaterialSystemHardwareConfig MAKE_NAME_UNIQUE(g_pMaterialSystemHardwareConfig)
#define g_pMatSystemSurface MAKE_NAME_UNIQUE(g_pMatSystemSurface)
#define g_pMDLCache MAKE_NAME_UNIQUE(g_pMDLCache)
#define g_pModelNameLaser MAKE_NAME_UNIQUE(g_pModelNameLaser)
#define g_pMoveData MAKE_NAME_UNIQUE(g_pMoveData)
#define g_pPhysSaveRestoreManager MAKE_NAME_UNIQUE(g_pPhysSaveRestoreManager)
#define g_pPredictionSystems MAKE_NAME_UNIQUE(g_pPredictionSystems)
#define g_pShaderUtil MAKE_NAME_UNIQUE(g_pShaderUtil)
#define g_pStringTableClientSideChoreoScenes MAKE_NAME_UNIQUE(g_pStringTableClientSideChoreoScenes)
#define g_pStringTableInfoPanel MAKE_NAME_UNIQUE(g_pStringTableInfoPanel)
#define g_pStringTableMaterials MAKE_NAME_UNIQUE(g_pStringTableMaterials)
#define g_sModelIndexBloodDrop MAKE_NAME_UNIQUE(g_sModelIndexBloodDrop)
#define g_sModelIndexBloodSpray MAKE_NAME_UNIQUE(g_sModelIndexBloodSpray)
#define g_sModelIndexBubbles MAKE_NAME_UNIQUE(g_sModelIndexBubbles)
#define g_sModelIndexFireball MAKE_NAME_UNIQUE(g_sModelIndexFireball)
#define g_sModelIndexLaser MAKE_NAME_UNIQUE(g_sModelIndexLaser)
#define g_sModelIndexLaserDot MAKE_NAME_UNIQUE(g_sModelIndexLaserDot)
#define g_sModelIndexSmoke MAKE_NAME_UNIQUE(g_sModelIndexSmoke)
#define g_sModelIndexWExplosion MAKE_NAME_UNIQUE(g_sModelIndexWExplosion)
#define g_SolidSetup MAKE_NAME_UNIQUE(g_SolidSetup)
#define g_StringTableGameRules MAKE_NAME_UNIQUE(g_StringTableGameRules)
#define g_verticalBob MAKE_NAME_UNIQUE(g_verticalBob)
#define gameeventmanager MAKE_NAME_UNIQUE(gameeventmanager)
#define GameStringSystem MAKE_NAME_UNIQUE(GameStringSystem)
#define gameuifuncs MAKE_NAME_UNIQUE(gameuifuncs)
#define GetAnimationEvent MAKE_NAME_UNIQUE(GetAnimationEvent)
#define GetAttachmentLocalSpace MAKE_NAME_UNIQUE(GetAttachmentLocalSpace)
#define GetBodygroup MAKE_NAME_UNIQUE(GetBodygroup)
#define GetBodygroupCount MAKE_NAME_UNIQUE(GetBodygroupCount)
#define GetBodygroupName MAKE_NAME_UNIQUE(GetBodygroupName)
#define GetEntitySaveRestoreBlockHandler MAKE_NAME_UNIQUE(GetEntitySaveRestoreBlockHandler)
#define GetEntitySaveUtils MAKE_NAME_UNIQUE(GetEntitySaveUtils)
#define GetEventIndexForSequence MAKE_NAME_UNIQUE(GetEventIndexForSequence)
#define GetEyePosition MAKE_NAME_UNIQUE(GetEyePosition)
#define GetHitboxSetCount MAKE_NAME_UNIQUE(GetHitboxSetCount)
#define GetHitboxSetName MAKE_NAME_UNIQUE(GetHitboxSetName)
#define GetInvalidWeaponInfoHandle MAKE_NAME_UNIQUE(GetInvalidWeaponInfoHandle)
#define GetMaterialIndex MAKE_NAME_UNIQUE(GetMaterialIndex)
#define GetMaterialNameFromIndex MAKE_NAME_UNIQUE(GetMaterialNameFromIndex)
#define GetNumBodyGroups MAKE_NAME_UNIQUE(GetNumBodyGroups)
#define GetPhysObjSaveRestoreOps MAKE_NAME_UNIQUE(GetPhysObjSaveRestoreOps)
#define GetPhysSaveRestoreBlockHandler MAKE_NAME_UNIQUE(GetPhysSaveRestoreBlockHandler)
#define GetSequenceActivity MAKE_NAME_UNIQUE(GetSequenceActivity)
#define GetSequenceActivityName MAKE_NAME_UNIQUE(GetSequenceActivityName)
#define GetSequenceFlags MAKE_NAME_UNIQUE(GetSequenceFlags)
#define GetSequenceLinearMotion MAKE_NAME_UNIQUE(GetSequenceLinearMotion)
#define GetSequenceName MAKE_NAME_UNIQUE(GetSequenceName)
#define GetSoundSaveRestoreOps MAKE_NAME_UNIQUE(GetSoundSaveRestoreOps)
#define GetWindspeedAtTime MAKE_NAME_UNIQUE(GetWindspeedAtTime)
#define groundlinksallocated MAKE_NAME_UNIQUE(groundlinksallocated)
#define HasAnimationEventOfType MAKE_NAME_UNIQUE(HasAnimationEventOfType)
#define IGameSystem MAKE_NAME_UNIQUE(IGameSystem)
#define IGameSystemPerFrame MAKE_NAME_UNIQUE(IGameSystemPerFrame)
#define ik MAKE_NAME_UNIQUE(ik)
#define IMoveHelper MAKE_NAME_UNIQUE(IMoveHelper)
#define ImpulseScale MAKE_NAME_UNIQUE(ImpulseScale)
#define IndexModelSequences MAKE_NAME_UNIQUE(IndexModelSequences)
#define InitPose MAKE_NAME_UNIQUE(InitPose)
#define InterfaceReg MAKE_NAME_UNIQUE(InterfaceReg)
#define IntervalDistance MAKE_NAME_UNIQUE(IntervalDistance)
#define IntervalTimer MAKE_NAME_UNIQUE(IntervalTimer)
#define IsInPrediction MAKE_NAME_UNIQUE(IsInPrediction)
#define IsValidEntityPointer MAKE_NAME_UNIQUE(IsValidEntityPointer)
#define linksallocated MAKE_NAME_UNIQUE(linksallocated)
#define LookupActivity MAKE_NAME_UNIQUE(LookupActivity)
#define LookupSequence MAKE_NAME_UNIQUE(LookupSequence)
#define LookupWeaponInfoSlot MAKE_NAME_UNIQUE(LookupWeaponInfoSlot)
#define m_flLastMoveYaw MAKE_NAME_UNIQUE(m_flLastMoveYaw)
#define MainViewOrigin MAKE_NAME_UNIQUE(MainViewOrigin)
#define MainViewForward MAKE_NAME_UNIQUE(MainViewForward)
#define MainViewRight MAKE_NAME_UNIQUE(MainViewRight)
#define MainViewUp MAKE_NAME_UNIQUE(MainViewUp)
#if !defined(_SHARED_LIB)
#define materials MAKE_NAME_UNIQUE(materials)
#else
#define materials VguiMatSurface_materials // shared lib has no materials of own
#endif
#define mdlcache MAKE_NAME_UNIQUE(mdlcache)
#define modelinfo MAKE_NAME_UNIQUE(modelinfo)
#define modelrender MAKE_NAME_UNIQUE(modelrender)
#define mstudioanimdesc_t MAKE_NAME_UNIQUE(mstudioanimdesc_t)
#define mstudiomodel_t MAKE_NAME_UNIQUE(mstudiomodel_t)
#define NDebugOverlay MAKE_NAME_UNIQUE(NDebugOverlay)
#define networkstringtable MAKE_NAME_UNIQUE(networkstringtable)
#define nexttoken MAKE_NAME_UNIQUE(nexttoken)
#define partition MAKE_NAME_UNIQUE(partition)
#define PassServerEntityFilter MAKE_NAME_UNIQUE(PassServerEntityFilter)
#define PhysBlockHeader_t MAKE_NAME_UNIQUE(PhysBlockHeader_t)
#define physcollision MAKE_NAME_UNIQUE(physcollision)
#define PhysComputeSlideDirection MAKE_NAME_UNIQUE(PhysComputeSlideDirection)
#define PhysCreateBbox MAKE_NAME_UNIQUE(PhysCreateBbox)
#define PhysDisableEntityCollisions MAKE_NAME_UNIQUE(PhysDisableEntityCollisions)
#define PhysDisableObjectCollisions MAKE_NAME_UNIQUE(PhysDisableObjectCollisions)
#define PhysEnableEntityCollisions MAKE_NAME_UNIQUE(PhysEnableEntityCollisions)
#define PhysEnableObjectCollisions MAKE_NAME_UNIQUE(PhysEnableObjectCollisions)
#define physenv MAKE_NAME_UNIQUE(physenv)
#define PhysForceClearVelocity MAKE_NAME_UNIQUE(PhysForceClearVelocity)
#define PhysFrictionEffect MAKE_NAME_UNIQUE(PhysFrictionEffect)
#define physgametrace MAKE_NAME_UNIQUE(physgametrace)
#define PhysGetDefaultAABBSolid MAKE_NAME_UNIQUE(PhysGetDefaultAABBSolid)
#define PhysHasContactWithOtherInDirection MAKE_NAME_UNIQUE(PhysHasContactWithOtherInDirection)
#define physics MAKE_NAME_UNIQUE(physics)
#define PhysicsGameSystem MAKE_NAME_UNIQUE(PhysicsGameSystem)
#define physicssound MAKE_NAME_UNIQUE(physicssound)
#define PhysObjectHeader_t MAKE_NAME_UNIQUE(PhysObjectHeader_t)
#define PhysParseSurfaceData MAKE_NAME_UNIQUE(PhysParseSurfaceData)
#define physprops MAKE_NAME_UNIQUE(physprops)
#define PhysRecheckObjectPair MAKE_NAME_UNIQUE(PhysRecheckObjectPair)
#define PrecacheFileWeaponInfoDatabase MAKE_NAME_UNIQUE(PrecacheFileWeaponInfoDatabase)
#define PrecacheMaterial MAKE_NAME_UNIQUE(PrecacheMaterial)
#define predictables MAKE_NAME_UNIQUE(predictables)
#define QuaternionAccumulate MAKE_NAME_UNIQUE(QuaternionAccumulate)
#define QuaternionMA MAKE_NAME_UNIQUE(QuaternionMA)
#define QuaternionSM MAKE_NAME_UNIQUE(QuaternionSM)
#define RagdollActivate MAKE_NAME_UNIQUE(RagdollActivate)
#define RagdollApplyAnimationAsVelocity MAKE_NAME_UNIQUE(RagdollApplyAnimationAsVelocity)
#define RagdollComputeExactBbox MAKE_NAME_UNIQUE(RagdollComputeExactBbox)
#define RagdollCreate MAKE_NAME_UNIQUE(RagdollCreate)
#define RagdollDestroy MAKE_NAME_UNIQUE(RagdollDestroy)
#define RagdollExtractBoneIndices MAKE_NAME_UNIQUE(RagdollExtractBoneIndices)
#define RagdollGetBoneMatrix MAKE_NAME_UNIQUE(RagdollGetBoneMatrix)
#define RagdollIsAsleep MAKE_NAME_UNIQUE(RagdollIsAsleep)
#define RagdollSetupAnimatedFriction MAKE_NAME_UNIQUE(RagdollSetupAnimatedFriction)
#define RagdollSetupCollisions MAKE_NAME_UNIQUE(RagdollSetupCollisions)
#define CopyPackedAnimatedFriction MAKE_NAME_UNIQUE(CopyPackedAnimatedFriction)
#define random MAKE_NAME_UNIQUE(random)
#define RandomInterval MAKE_NAME_UNIQUE(RandomInterval)
#define ReadEncryptedKVFile MAKE_NAME_UNIQUE(ReadEncryptedKVFile)
#define ReadInterval MAKE_NAME_UNIQUE(ReadInterval)
#define ReadUsercmd MAKE_NAME_UNIQUE(ReadUsercmd)
#define ReadWeaponDataFromFileForSlot MAKE_NAME_UNIQUE(ReadWeaponDataFromFileForSlot)
#define RecvPropUtlVector MAKE_NAME_UNIQUE(RecvPropUtlVector)
#define RecvProxy_UtlVectorElement MAKE_NAME_UNIQUE(RecvProxy_UtlVectorElement)
#define RecvProxy_UtlVectorElement_DataTable MAKE_NAME_UNIQUE(RecvProxy_UtlVectorElement_DataTable)
#define RecvProxy_UtlVectorLength MAKE_NAME_UNIQUE(RecvProxy_UtlVectorLength)
#define RegisterUserMessages MAKE_NAME_UNIQUE(RegisterUserMessages)
#define RemapAngleRange MAKE_NAME_UNIQUE(RemapAngleRange)
#define ResetActivityIndexes MAKE_NAME_UNIQUE(ResetActivityIndexes)
#define ResetEventIndexes MAKE_NAME_UNIQUE(ResetEventIndexes)
#define ResetWindspeed MAKE_NAME_UNIQUE(ResetWindspeed)
#define s_pInterfaceRegs MAKE_NAME_UNIQUE(s_pInterfaceRegs)
#define SaveInit MAKE_NAME_UNIQUE(SaveInit)
#define SaveRestoreBlockHeader_t MAKE_NAME_UNIQUE(SaveRestoreBlockHeader_t)
#define ScaleBones MAKE_NAME_UNIQUE(ScaleBones)
#define Scene_Printf MAKE_NAME_UNIQUE(Scene_Printf)
#define SelectHeaviestSequence MAKE_NAME_UNIQUE(SelectHeaviestSequence)
#define SelectWeightedSequence MAKE_NAME_UNIQUE(SelectWeightedSequence)
#define SendPropUtlVector MAKE_NAME_UNIQUE(SendPropUtlVector)
#define SendProxy_LengthTable MAKE_NAME_UNIQUE(SendProxy_LengthTable)
#define SendProxy_UtlVectorElement MAKE_NAME_UNIQUE(SendProxy_UtlVectorElement)
#define SendProxy_UtlVectorElement_DataTable MAKE_NAME_UNIQUE(SendProxy_UtlVectorElement_DataTable)
#define SendProxy_UtlVectorLength MAKE_NAME_UNIQUE(SendProxy_UtlVectorLength)
#define SENTENCEG_Lookup MAKE_NAME_UNIQUE(SENTENCEG_Lookup)
#define SetActivityForSequence MAKE_NAME_UNIQUE(SetActivityForSequence)
#define SetBodygroup MAKE_NAME_UNIQUE(SetBodygroup)
#define SetEventIndexForSequence MAKE_NAME_UNIQUE(SetEventIndexForSequence)
#define SetupSingleBoneMatrix MAKE_NAME_UNIQUE(SetupSingleBoneMatrix)
#define SharedRandomAngle MAKE_NAME_UNIQUE(SharedRandomAngle)
#define SharedRandomFloat MAKE_NAME_UNIQUE(SharedRandomFloat)
#define SharedRandomInt MAKE_NAME_UNIQUE(SharedRandomInt)
#define SharedRandomVector MAKE_NAME_UNIQUE(SharedRandomVector)
#define SlerpBones MAKE_NAME_UNIQUE(SlerpBones)
#define SolveBone MAKE_NAME_UNIQUE(SolveBone)
#define SoundCommand_t MAKE_NAME_UNIQUE(SoundCommand_t)
#define soundemitterbase MAKE_NAME_UNIQUE(soundemitterbase)
#define SpawnBlood MAKE_NAME_UNIQUE(SpawnBlood)
#define StandardFilterRules MAKE_NAME_UNIQUE(StandardFilterRules)
#define Studio_AlignIKMatrix MAKE_NAME_UNIQUE(Studio_AlignIKMatrix)
#define Studio_AnimMovement MAKE_NAME_UNIQUE(Studio_AnimMovement)
#define Studio_AnimPosition MAKE_NAME_UNIQUE(Studio_AnimPosition)
#define Studio_AnimVelocity MAKE_NAME_UNIQUE(Studio_AnimVelocity)
#define Studio_BoneIndexByName MAKE_NAME_UNIQUE(Studio_BoneIndexByName)
#define Studio_BuildMatrices MAKE_NAME_UNIQUE(Studio_BuildMatrices)
#define Studio_CalcBoneToBoneTransform MAKE_NAME_UNIQUE(Studio_CalcBoneToBoneTransform)
#define Studio_CPS MAKE_NAME_UNIQUE(Studio_CPS)
#define Studio_CreateBoneCache MAKE_NAME_UNIQUE(Studio_CreateBoneCache)
#define Studio_DestroyBoneCache MAKE_NAME_UNIQUE(Studio_DestroyBoneCache)
#define Studio_Duration MAKE_NAME_UNIQUE(Studio_Duration)
#define Studio_FindAnimDistance MAKE_NAME_UNIQUE(Studio_FindAnimDistance)
#define Studio_FindAttachment MAKE_NAME_UNIQUE(Studio_FindAttachment)
#define Studio_FindRandomAttachment MAKE_NAME_UNIQUE(Studio_FindRandomAttachment)
#define Studio_FindSeqDistance MAKE_NAME_UNIQUE(Studio_FindSeqDistance)
#define Studio_FPS MAKE_NAME_UNIQUE(Studio_FPS)
#define Studio_GetController MAKE_NAME_UNIQUE(Studio_GetController)
#define Studio_GetDefaultSurfaceProps MAKE_NAME_UNIQUE(Studio_GetDefaultSurfaceProps)
#define Studio_GetKeyValueText MAKE_NAME_UNIQUE(Studio_GetKeyValueText)
#define Studio_GetMass MAKE_NAME_UNIQUE(Studio_GetMass)
#define Studio_GetPoseParameter MAKE_NAME_UNIQUE(Studio_GetPoseParameter)
#define Studio_IKRuleWeight MAKE_NAME_UNIQUE(Studio_IKRuleWeight)
#define Studio_IKShouldLatch MAKE_NAME_UNIQUE(Studio_IKShouldLatch)
#define Studio_IKTail MAKE_NAME_UNIQUE(Studio_IKTail)
#define Studio_InvalidateBoneCache MAKE_NAME_UNIQUE(Studio_InvalidateBoneCache)
#define Studio_LocalPoseParameter MAKE_NAME_UNIQUE(Studio_LocalPoseParameter)
#define Studio_MaxFrame MAKE_NAME_UNIQUE(Studio_MaxFrame)
#define Studio_SeqMovement MAKE_NAME_UNIQUE(Studio_SeqMovement)
#define Studio_SeqVelocity MAKE_NAME_UNIQUE(Studio_SeqVelocity)
#define Studio_SetController MAKE_NAME_UNIQUE(Studio_SetController)
#define Studio_SetPoseParameter MAKE_NAME_UNIQUE(Studio_SetPoseParameter)
#define Studio_SolveIK MAKE_NAME_UNIQUE(Studio_SolveIK)
#define studiohdr_t MAKE_NAME_UNIQUE(studiohdr_t)
#define SURFACEPROP_MANIFEST_FILE MAKE_NAME_UNIQUE(SURFACEPROP_MANIFEST_FILE)
#define Sys_GetFactory MAKE_NAME_UNIQUE(Sys_GetFactory)
#define Sys_GetFactoryThis MAKE_NAME_UNIQUE(Sys_GetFactoryThis)
#define Sys_LoadInterface MAKE_NAME_UNIQUE(Sys_LoadInterface)
#define Sys_LoadModule MAKE_NAME_UNIQUE(Sys_LoadModule)
#define Sys_UnloadModule MAKE_NAME_UNIQUE(Sys_UnloadModule)
#define te MAKE_NAME_UNIQUE(te)
#define TE_ArmorRicochet MAKE_NAME_UNIQUE(TE_ArmorRicochet)
#define TE_BeamEntPoint MAKE_NAME_UNIQUE(TE_BeamEntPoint)
#define TE_BeamEnts MAKE_NAME_UNIQUE(TE_BeamEnts)
#define TE_BeamFollow MAKE_NAME_UNIQUE(TE_BeamFollow)
#define TE_BeamLaser MAKE_NAME_UNIQUE(TE_BeamLaser)
#define TE_BeamPoints MAKE_NAME_UNIQUE(TE_BeamPoints)
#define TE_BeamRing MAKE_NAME_UNIQUE(TE_BeamRing)
#define TE_BeamRingPoint MAKE_NAME_UNIQUE(TE_BeamRingPoint)
#define TE_BeamSpline MAKE_NAME_UNIQUE(TE_BeamSpline)
#define TE_BloodSprite MAKE_NAME_UNIQUE(TE_BloodSprite)
#define TE_BloodStream MAKE_NAME_UNIQUE(TE_BloodStream)
#define TE_BreakModel MAKE_NAME_UNIQUE(TE_BreakModel)
#define TE_BSPDecal MAKE_NAME_UNIQUE(TE_BSPDecal)
#define TE_Bubbles MAKE_NAME_UNIQUE(TE_Bubbles)
#define TE_BubbleTrail MAKE_NAME_UNIQUE(TE_BubbleTrail)
#define TE_Decal MAKE_NAME_UNIQUE(TE_Decal)
#define TE_DispatchEffect MAKE_NAME_UNIQUE(TE_DispatchEffect)
#define TE_Dust MAKE_NAME_UNIQUE(TE_Dust)
#define TE_DynamicLight MAKE_NAME_UNIQUE(TE_DynamicLight)
#define TE_EnergySplash MAKE_NAME_UNIQUE(TE_EnergySplash)
#define TE_Explosion MAKE_NAME_UNIQUE(TE_Explosion)
#define TE_FootprintDecal MAKE_NAME_UNIQUE(TE_FootprintDecal)
#define TE_GaussExplosion MAKE_NAME_UNIQUE(TE_GaussExplosion)
#define TE_GlowSprite MAKE_NAME_UNIQUE(TE_GlowSprite)
#define TE_KillPlayerAttachments MAKE_NAME_UNIQUE(TE_KillPlayerAttachments)
#define TE_LargeFunnel MAKE_NAME_UNIQUE(TE_LargeFunnel)
#define TE_MetalSparks MAKE_NAME_UNIQUE(TE_MetalSparks)
#define TE_MuzzleFlash MAKE_NAME_UNIQUE(TE_MuzzleFlash)
#define TE_PlayerDecal MAKE_NAME_UNIQUE(TE_PlayerDecal)
#define TE_ProjectDecal MAKE_NAME_UNIQUE(TE_ProjectDecal)
#define TE_ShatterSurface MAKE_NAME_UNIQUE(TE_ShatterSurface)
#define TE_ShowLine MAKE_NAME_UNIQUE(TE_ShowLine)
#define TE_Smoke MAKE_NAME_UNIQUE(TE_Smoke)
#define TE_Sparks MAKE_NAME_UNIQUE(TE_Sparks)
#define TE_Sprite MAKE_NAME_UNIQUE(TE_Sprite)
#define TE_SpriteSpray MAKE_NAME_UNIQUE(TE_SpriteSpray)
#define TE_WorldDecal MAKE_NAME_UNIQUE(TE_WorldDecal)
#define TempCreateInterface MAKE_NAME_UNIQUE(TempCreateInterface)
#define touchevent_t MAKE_NAME_UNIQUE(touchevent_t)
#define touchlink_t MAKE_NAME_UNIQUE(touchlink_t)
#define UTIL_AngleDiff MAKE_NAME_UNIQUE(UTIL_AngleDiff)
#define UTIL_BloodDrips MAKE_NAME_UNIQUE(UTIL_BloodDrips)
#define UTIL_BloodImpact MAKE_NAME_UNIQUE(UTIL_BloodImpact)
#define UTIL_Bubbles MAKE_NAME_UNIQUE(UTIL_Bubbles)
#define UTIL_EmitAmbientSound MAKE_NAME_UNIQUE(UTIL_EmitAmbientSound)
#define UTIL_FreeFile MAKE_NAME_UNIQUE(UTIL_FreeFile)
#define UTIL_FunctionFromName MAKE_NAME_UNIQUE(UTIL_FunctionFromName)
#define UTIL_FunctionToName MAKE_NAME_UNIQUE(UTIL_FunctionToName)
#define UTIL_IsLowViolence MAKE_NAME_UNIQUE(UTIL_IsLowViolence)
#define UTIL_LoadActivityRemapFile MAKE_NAME_UNIQUE(UTIL_LoadActivityRemapFile)
#define UTIL_LoadFileForMe MAKE_NAME_UNIQUE(UTIL_LoadFileForMe)
#define UTIL_PrecacheDecal MAKE_NAME_UNIQUE(UTIL_PrecacheDecal)
#define UTIL_ScreenShake MAKE_NAME_UNIQUE(UTIL_ScreenShake)
#define UTIL_ShouldShowBlood MAKE_NAME_UNIQUE(UTIL_ShouldShowBlood)
#define UTIL_Smoke MAKE_NAME_UNIQUE(UTIL_Smoke)
#define UTIL_StringToColor32 MAKE_NAME_UNIQUE(UTIL_StringToColor32)
#define UTIL_StringToFloatArray MAKE_NAME_UNIQUE(UTIL_StringToFloatArray)
#define UTIL_StringToIntArray MAKE_NAME_UNIQUE(UTIL_StringToIntArray)
#define UTIL_StringToVector MAKE_NAME_UNIQUE(UTIL_StringToVector)
#define UTIL_Tracer MAKE_NAME_UNIQUE(UTIL_Tracer)
#define UTIL_TranslateSoundName MAKE_NAME_UNIQUE(UTIL_TranslateSoundName)
#define UTIL_VecToPitch MAKE_NAME_UNIQUE(UTIL_VecToPitch)
#define UTIL_VecToYaw MAKE_NAME_UNIQUE(UTIL_VecToYaw)
#define UTIL_WaterLevel MAKE_NAME_UNIQUE(UTIL_WaterLevel)
#define UTIL_YawToVector MAKE_NAME_UNIQUE(UTIL_YawToVector)
#define VerifySequenceIndex MAKE_NAME_UNIQUE(VerifySequenceIndex)
#define VGui_CreateGlobalPanels MAKE_NAME_UNIQUE(VGui_CreateGlobalPanels)
#define VGui_PostInit MAKE_NAME_UNIQUE(VGui_PostInit)
#define VGui_Shutdown MAKE_NAME_UNIQUE(VGui_Shutdown)
#define VGui_Startup MAKE_NAME_UNIQUE(VGui_Startup)
#define W_Precache MAKE_NAME_UNIQUE(W_Precache)
#define WriteUsercmd MAKE_NAME_UNIQUE(WriteUsercmd)
#endif
#if defined(_STATIC_LINKED) && defined(_VGUI_DLL)
// unique these overloaded symbols to avoid static linking clash
// ensures locality to vguidll lib
#define scheme vguidll_scheme
#define surface vguidll_surface
#define system vguidll_system
#define ivgui vguidll_ivgui
#define filesystem vguidll_filesystem
#define localize vguidll_localize
#define ipanel vguidll_ipanel
#endif
#endif | 412 | 0.87294 | 1 | 0.87294 | game-dev | MEDIA | 0.310003 | game-dev | 0.566568 | 1 | 0.566568 |
rehlds/Metamod-R | 9,061 | metamod/include/dlls/maprules.h | /*
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game Engine ("HL
* Engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL Engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#pragma once
#define MAX_EQUIP 32
#define SF_SCORE_NEGATIVE 0x0001
#define SF_SCORE_TEAM 0x0002
#define SF_ENVTEXT_ALLPLAYERS 0x0001
#define SF_TEAMMASTER_FIREONCE 0x0001
#define SF_TEAMMASTER_ANYTEAM 0x0002
#define SF_TEAMSET_FIREONCE 0x0001
#define SF_TEAMSET_CLEARTEAM 0x0002
#define SF_PKILL_FIREONCE 0x0001
#define SF_GAMECOUNT_FIREONCE 0x0001
#define SF_GAMECOUNT_RESET 0x0002
#define SF_GAMECOUNTSET_FIREONCE 0x0001
#define SF_PLAYEREQUIP_USEONLY 0x0001
#define SF_PTEAM_FIREONCE 0x0001
#define SF_PTEAM_KILL 0x0002
#define SF_PTEAM_GIB 0x0004
class CRuleEntity: public CBaseEntity {
public:
virtual void Spawn() = 0;
virtual void KeyValue(KeyValueData *pkvd) = 0;
virtual int Save(CSave &save) = 0;
virtual int Restore(CRestore &restore) = 0;
public:
void SetMaster(int iszMaster) { m_iszMaster = iszMaster; }
private:
string_t m_iszMaster;
};
// CRulePointEntity -- base class for all rule "point" entities (not brushes)
class CRulePointEntity: public CRuleEntity {
public:
virtual void Spawn() = 0;
};
// CRuleBrushEntity -- base class for all rule "brush" entities (not brushes)
// Default behavior is to set up like a trigger, invisible, but keep the model for volume testing
class CRuleBrushEntity: public CRuleEntity {
public:
virtual void Spawn() = 0;
};
// CGameScore / game_score -- award points to player / team
// Points +/- total
// Flag: Allow negative scores SF_SCORE_NEGATIVE
// Flag: Award points to team in teamplay SF_SCORE_TEAM
class CGameScore: public CRulePointEntity {
public:
virtual void Spawn() = 0;
virtual void KeyValue(KeyValueData *pkvd) = 0;
virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0;
public:
int Points() const { return int(pev->frags); }
BOOL AllowNegativeScore() { return pev->spawnflags & SF_SCORE_NEGATIVE; }
BOOL AwardToTeam() const { return pev->spawnflags & SF_SCORE_TEAM; }
void SetPoints(int points) { pev->frags = points; }
};
// CGameEnd / game_end -- Ends the game in MP
class CGameEnd: public CRulePointEntity {
public:
virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0;
};
// CGameText / game_text -- NON-Localized HUD Message (use env_message to display a titles.txt message)
// Flag: All players SF_ENVTEXT_ALLPLAYERS
class CGameText: public CRulePointEntity {
public:
virtual void KeyValue(KeyValueData *pkvd) = 0;
virtual int Save(CSave &save) = 0;
virtual int Restore(CRestore &restore) = 0;
virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0;
public:
BOOL MessageToAll() const { return (pev->spawnflags & SF_ENVTEXT_ALLPLAYERS) == SF_ENVTEXT_ALLPLAYERS; }
void MessageSet(const char *pMessage) { pev->message = ALLOC_STRING(pMessage); }
const char *MessageGet() const { return STRING(pev->message); }
private:
hudtextparms_t m_textParms;
};
// CGameTeamMaster / game_team_master -- "Masters" like multisource, but based on the team of the activator
// Only allows mastered entity to fire if the team matches my team
//
// team index (pulled from server team list "mp_teamlist"
// Flag: Remove on Fire
// Flag: Any team until set? -- Any team can use this until the team is set (otherwise no teams can use it)
class CGameTeamMaster: public CRulePointEntity {
public:
virtual void KeyValue(KeyValueData *pkvd) = 0;
virtual int ObjectCaps() = 0;
virtual BOOL IsTriggered(CBaseEntity *pActivator) = 0;
virtual const char *TeamID() = 0;
virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0;
public:
BOOL RemoveOnFire() const { return (pev->spawnflags & SF_TEAMMASTER_FIREONCE) == SF_TEAMMASTER_FIREONCE; }
BOOL AnyTeam() const { return (pev->spawnflags & SF_TEAMMASTER_ANYTEAM) == SF_TEAMMASTER_ANYTEAM; }
public:
int m_teamIndex;
USE_TYPE triggerType;
};
// CGameTeamSet / game_team_set -- Changes the team of the entity it targets to the activator's team
// Flag: Fire once
// Flag: Clear team -- Sets the team to "NONE" instead of activator
class CGameTeamSet: public CRulePointEntity {
public:
virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0;
public:
BOOL RemoveOnFire() const { return (pev->spawnflags & SF_TEAMSET_FIREONCE) == SF_TEAMSET_FIREONCE; }
BOOL ShouldClearTeam() const { return (pev->spawnflags & SF_TEAMSET_CLEARTEAM) == SF_TEAMSET_CLEARTEAM; }
};
// CGamePlayerZone / game_player_zone -- players in the zone fire my target when I'm fired
// Needs master?
class CGamePlayerZone: public CRuleBrushEntity {
public:
virtual void KeyValue(KeyValueData *pkvd) = 0;
virtual int Save(CSave &save) = 0;
virtual int Restore(CRestore &restore) = 0;
virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0;
private:
string_t m_iszInTarget;
string_t m_iszOutTarget;
string_t m_iszInCount;
string_t m_iszOutCount;
};
// CGamePlayerHurt / game_player_hurt -- Damages the player who fires it
// Flag: Fire once
class CGamePlayerHurt: public CRulePointEntity {
public:
virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0;
public:
BOOL RemoveOnFire() const { return (pev->spawnflags & SF_PKILL_FIREONCE) == SF_PKILL_FIREONCE; }
};
// CGameCounter / game_counter -- Counts events and fires target
// Flag: Fire once
// Flag: Reset on Fire
class CGameCounter: public CRulePointEntity {
public:
virtual void Spawn() = 0;
virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0;
public:
BOOL RemoveOnFire() const { return (pev->spawnflags & SF_GAMECOUNT_FIREONCE) == SF_GAMECOUNT_FIREONCE; }
BOOL ResetOnFire() const { return (pev->spawnflags & SF_GAMECOUNT_RESET) == SF_GAMECOUNT_RESET; }
void CountUp() { pev->frags++; }
void CountDown() { pev->frags--; }
void ResetCount() { pev->frags = pev->dmg; }
int CountValue() const { return int(pev->frags); }
int LimitValue() const { return int(pev->health); }
BOOL HitLimit() const { return CountValue() == LimitValue(); }
private:
void SetCountValue(int value) { pev->frags = value; }
void SetInitialValue(int value) { pev->dmg = value; }
};
// CGameCounterSet / game_counter_set -- Sets the counter's value
// Flag: Fire once
class CGameCounterSet: public CRulePointEntity {
public:
virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0;
public:
BOOL RemoveOnFire() const { return (pev->spawnflags & SF_GAMECOUNTSET_FIREONCE) == SF_GAMECOUNTSET_FIREONCE; }
};
// CGamePlayerEquip / game_playerequip -- Sets the default player equipment
// Flag: USE Only
class CGamePlayerEquip: public CRulePointEntity {
public:
virtual void KeyValue(KeyValueData *pkvd) = 0;
virtual void Touch(CBaseEntity *pOther) = 0;
virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0;
public:
BOOL UseOnly() const { return (pev->spawnflags & SF_PLAYEREQUIP_USEONLY) == SF_PLAYEREQUIP_USEONLY; }
public:
string_t m_weaponNames[ MAX_EQUIP ];
int m_weaponCount[ MAX_EQUIP ];
};
// CGamePlayerTeam / game_player_team -- Changes the team of the player who fired it
// Flag: Fire once
// Flag: Kill Player
// Flag: Gib Player
class CGamePlayerTeam: public CRulePointEntity {
public:
virtual void Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) = 0;
private:
BOOL RemoveOnFire() const { return (pev->spawnflags & SF_PTEAM_FIREONCE) == SF_PTEAM_FIREONCE; }
BOOL ShouldKillPlayer() const { return (pev->spawnflags & SF_PTEAM_KILL) == SF_PTEAM_KILL; }
BOOL ShouldGibPlayer() const { return (pev->spawnflags & SF_PTEAM_GIB) == SF_PTEAM_GIB; }
};
| 412 | 0.914183 | 1 | 0.914183 | game-dev | MEDIA | 0.980513 | game-dev | 0.669772 | 1 | 0.669772 |
splintchecker/splint | 2,704 | src/mtreader.c | /*
** Splint - annotation-assisted static program checker
** Copyright (C) 1994-2003 University of Virginia,
** Massachusetts Institute of Technology
**
** This program is free software; you can redistribute it and/or modify it
** under the terms of the GNU General Public License as published by the
** Free Software Foundation; either version 2 of the License, or (at your
** option) any later version.
**
** This program is distributed in the hope that it will be useful, but
** WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** The GNU General Public License is available from http://www.gnu.org/ or
** the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
** MA 02111-1307, USA.
**
** For information on splint: info@splint.org
** To report a bug: splint-bug@splint.org
** For more information: http://www.splint.org
*/
/*
** mtreader.c
**
** Controls reading of .mts files.
*/
# include "splintMacros.nf"
# include "basic.h"
# include "mtgrammar.h"
# include "mtscanner.h"
void mtreader_readFile (cstring infile)
{
inputStream sourceFile;
fileId fid;
cstring fname;
sourceFile = inputStream_create (infile, cstring_undefined, FALSE);
if (!inputStream_getPath (context_getLarchPath (), sourceFile))
{
lldiagmsg
(message ("Cannot find metastate file: %s", inputStream_fileName (sourceFile)));
inputStream_free (sourceFile);
return;
}
if (!inputStream_open (sourceFile))
{
lldiagmsg
(message ("Cannot open metastate file: %s",
inputStream_fileName (sourceFile)));
inputStream_free (sourceFile);
return;
}
fname = inputStream_fileName (sourceFile);
if (fileTable_exists (context_fileTable (), fname))
{
fid = fileTable_lookup (context_fileTable (), fname);
}
else
{
fid = fileTable_addMetastateFile (context_fileTable (), fname);
}
context_setFileId (fid);
displayScan (message ("reading metastate %s", fname));
mtscanner_reset (sourceFile);
context_enterMTfile ();
(void) mtparse ();
context_exitMTfile ();
check (inputStream_close (sourceFile));
inputStream_free (sourceFile);
}
void mtreader_processDeclaration (mtDeclarationNode decl)
{
DPRINTF (("Processing state %s", mtDeclarationNode_unparse (decl)));
mtDeclarationNode_process (decl, FALSE);
mtDeclarationNode_free (decl);
}
void mtreader_processGlobalDeclaration (mtDeclarationNode decl)
{
DPRINTF (("Processing state %s", mtDeclarationNode_unparse (decl)));
mtDeclarationNode_process (decl, TRUE);
mtDeclarationNode_free (decl);
}
| 412 | 0.943041 | 1 | 0.943041 | game-dev | MEDIA | 0.246831 | game-dev | 0.78842 | 1 | 0.78842 |
KDE/kmail | 2,835 | agents/mailfilteragent/dummykernel.cpp | #include "dummykernel.h"
#include <Akonadi/ChangeRecorder>
#include <Akonadi/EntityMimeTypeFilterModel>
#include <Akonadi/EntityTreeModel>
#include <Akonadi/Session>
#include <KIdentityManagementCore/IdentityManager>
#include <KSharedConfig>
#include <MailCommon/FolderCollectionMonitor>
#include <MessageComposer/AkonadiSender>
DummyKernel::DummyKernel(QObject *parent)
: QObject(parent)
, mMessageSender(new MessageComposer::AkonadiSender(this))
, mIdentityManager(new KIdentityManagementCore::IdentityManager(true, this))
, mCollectionModel(new Akonadi::EntityMimeTypeFilterModel(this))
{
auto session = new Akonadi::Session(QByteArrayLiteral("MailFilter Kernel ETM"), this);
mFolderCollectionMonitor = new MailCommon::FolderCollectionMonitor(session, this);
mEntityTreeModel = new Akonadi::EntityTreeModel(folderCollectionMonitor(), this);
mEntityTreeModel->setListFilter(Akonadi::CollectionFetchScope::Enabled);
mEntityTreeModel->setItemPopulationStrategy(Akonadi::EntityTreeModel::LazyPopulation);
mCollectionModel->setSourceModel(mEntityTreeModel);
mCollectionModel->addMimeTypeInclusionFilter(Akonadi::Collection::mimeType());
mCollectionModel->setHeaderGroup(Akonadi::EntityTreeModel::CollectionTreeHeaders);
mCollectionModel->setSortCaseSensitivity(Qt::CaseInsensitive);
}
KIdentityManagementCore::IdentityManager *DummyKernel::identityManager()
{
return mIdentityManager;
}
MessageComposer::MessageSender *DummyKernel::msgSender()
{
return mMessageSender;
}
Akonadi::EntityMimeTypeFilterModel *DummyKernel::collectionModel() const
{
return mCollectionModel;
}
KSharedConfig::Ptr DummyKernel::config()
{
return KSharedConfig::openConfig();
}
void DummyKernel::syncConfig()
{
Q_ASSERT(false);
}
MailCommon::JobScheduler *DummyKernel::jobScheduler() const
{
Q_ASSERT(false);
return nullptr;
}
Akonadi::ChangeRecorder *DummyKernel::folderCollectionMonitor() const
{
return mFolderCollectionMonitor->monitor();
}
void DummyKernel::updateSystemTray()
{
Q_ASSERT(false);
}
bool DummyKernel::showPopupAfterDnD()
{
return false;
}
qreal DummyKernel::closeToQuotaThreshold()
{
return 80;
}
QStringList DummyKernel::customTemplates()
{
Q_ASSERT(false);
return {};
}
bool DummyKernel::excludeImportantMailFromExpiry()
{
Q_ASSERT(false);
return true;
}
Akonadi::Collection::Id DummyKernel::lastSelectedFolder()
{
Q_ASSERT(false);
return Akonadi::Collection::Id();
}
void DummyKernel::setLastSelectedFolder(Akonadi::Collection::Id col)
{
Q_UNUSED(col)
}
void DummyKernel::expunge(Akonadi::Collection::Id id, bool sync)
{
Akonadi::Collection col(id);
if (col.isValid()) {
mFolderCollectionMonitor->expunge(Akonadi::Collection(col), sync);
}
}
#include "moc_dummykernel.cpp"
| 412 | 0.912495 | 1 | 0.912495 | game-dev | MEDIA | 0.312198 | game-dev | 0.789114 | 1 | 0.789114 |
jeremy46231/axon | 2,609 | src/client/java/app/jer/axon/service/MeteorService.java | package app.jer.axon.service;
import meteordevelopment.meteorclient.settings.Setting;
import meteordevelopment.meteorclient.systems.config.Config;
import meteordevelopment.meteorclient.systems.modules.Module;
import meteordevelopment.meteorclient.systems.modules.Modules;
import meteordevelopment.meteorclient.systems.modules.combat.*;
import meteordevelopment.meteorclient.systems.modules.movement.Velocity;
import meteordevelopment.meteorclient.systems.modules.player.*;
import meteordevelopment.meteorclient.systems.modules.render.Fullbright;
import meteordevelopment.meteorclient.systems.modules.world.EndermanLook;
import meteordevelopment.meteorclient.utils.entity.SortPriority;
public class MeteorService {
public static void initialize() {
// Combat Modules
KillAura killAura = runModule(KillAura.class);
setSetting(killAura, "auto-switch", true);
setSetting(killAura, "swap-back", true);
setSettingString(killAura, "entities", "monster");
setSetting(killAura, "priority", SortPriority.LowestDistance);
runModule(ArrowDodge.class);
runModule(AutoArmor.class);
runModule(AutoTotem.class);
runModule(AutoWeapon.class);
runModule(EndermanLook.class);
// Item Modules
AutoReplenish autoReplenish = runModule(AutoReplenish.class);
setSetting(autoReplenish, "search-hotbar", true);
runModule(AutoTool.class);
runModule(AutoEat.class);
// Movement Modules
runModule(AntiHunger.class);
runModule(Multitask.class);
runModule(Velocity.class);
// Render Modules
runModule(Fullbright.class);
// Config
Config config = Config.get();
config.titleScreenCredits.set(false);
config.titleScreenSplashes.set(false);
}
private static <T extends Module> T runModule(Class<T> moduleClass) {
T module = Modules.get().get(moduleClass);
if (!module.isActive()) module.toggle();
return module;
}
@SuppressWarnings("unchecked")
private static <T> Setting<T> getSetting(Module module, String name) {
Setting<T> setting = (Setting<T>) module.settings.get(name);
if (setting == null) throw new NullPointerException("Setting not found: " + name);
return setting;
}
private static <T> void setSetting(Module module, String name, T value) {
getSetting(module, name).set(value);
}
private static void setSettingString(Module module, String name, String value) {
getSetting(module, name).parse(value);
}
}
| 412 | 0.861518 | 1 | 0.861518 | game-dev | MEDIA | 0.445309 | game-dev | 0.853368 | 1 | 0.853368 |
gameflorist/dunedynasty | 56,396 | src/scenario.c | /** @file src/scenario.c %Scenario handling routines. */
#define _XOPEN_SOURCE
#define _XOPEN_SOURCE_EXTENDED
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "types.h"
#include "os/common.h"
#include "os/math.h"
#include "os/strings.h"
#include "scenario.h"
#include "enhancement.h"
#include "file.h"
#include "gfx.h"
#include "house.h"
#include "ini.h"
#include "map.h"
#include "mods/landscape.h"
#include "newui/mentat.h"
#include "opendune.h"
#include "pool/pool.h"
#include "pool/pool_house.h"
#include "pool/pool_structure.h"
#include "pool/pool_unit.h"
#include "shape.h"
#include "enum_string.h"
#include "sprites.h"
#include "string.h"
#include "structure.h"
#include "team.h"
#include "timer/timer.h"
#include "tools/coord.h"
#include "unit.h"
#include "gui/gui.h"
Campaign *g_campaign_list;
int g_campaign_total;
int g_campaign_selected;
Scenario g_scenario;
static void *s_scenarioBuffer = NULL;
/*--------------------------------------------------------------*/
Campaign *
Campaign_Alloc(const char *dir_name)
{
Campaign *camp;
g_campaign_list = realloc(g_campaign_list, (g_campaign_total + 1) * sizeof(g_campaign_list[0]));
g_campaign_total++;
assert(g_campaign_list != NULL);
camp = &g_campaign_list[g_campaign_total - 1];
if (dir_name == NULL) { /* Dune II */
camp->dir_name[0] = '\0';
} else {
snprintf(camp->dir_name, sizeof(camp->dir_name), "%s/", dir_name);
}
camp->house[0] = HOUSE_INVALID;
camp->house[1] = HOUSE_INVALID;
camp->house[2] = HOUSE_INVALID;
camp->intermission = false;
camp->fame_cps[HOUSE_HARKONNEN] = camp->fame_cps[HOUSE_SARDAUKAR] = 0;
camp->fame_cps[HOUSE_ATREIDES] = camp->fame_cps[HOUSE_FREMEN] = 1;
camp->fame_cps[HOUSE_ORDOS] = camp->fame_cps[HOUSE_MERCENARY] = 2;
camp->mapmach_cps[HOUSE_HARKONNEN] = camp->mapmach_cps[HOUSE_SARDAUKAR] = 0;
camp->mapmach_cps[HOUSE_ATREIDES] = camp->mapmach_cps[HOUSE_FREMEN] = 1;
camp->mapmach_cps[HOUSE_ORDOS] = camp->mapmach_cps[HOUSE_MERCENARY] = 2;
camp->misc_cps[HOUSE_HARKONNEN] = camp->misc_cps[HOUSE_SARDAUKAR] = 0;
camp->misc_cps[HOUSE_ATREIDES] = camp->misc_cps[HOUSE_FREMEN] = 1;
camp->misc_cps[HOUSE_ORDOS] = camp->misc_cps[HOUSE_MERCENARY] = 2;
camp->completion[0] = 0;
camp->completion[1] = 0;
camp->completion[2] = 0;
return camp;
}
static void
Campaign_AddFileInPAK(const char *filename, int parent)
{
FileInfo *fi;
if (FileHash_FindIndex(filename) != (unsigned int)-1)
return;
fi = FileHash_Store(filename);
fi->filename = strdup(filename);
fi->parentIndex = parent;
fi->flags.inPAKFile = true;
}
static void
Campaign_ReadCPSTweaks(char *source, const char *key, char *value, size_t size,
unsigned int *dest)
{
unsigned int tmp[HOUSE_NEUTRAL];
Ini_GetString("CPS", key, NULL, value, size, source);
if (sscanf(value, "%u,%u,%u,%u,%u,%u",
&tmp[HOUSE_HARKONNEN], &tmp[HOUSE_ATREIDES], &tmp[HOUSE_ORDOS],
&tmp[HOUSE_FREMEN], &tmp[HOUSE_SARDAUKAR], &tmp[HOUSE_MERCENARY]) == 6) {
for (enum HouseType houseID = HOUSE_HARKONNEN; houseID < HOUSE_NEUTRAL; houseID++) {
dest[houseID] = min(tmp[houseID], HOUSE_NEUTRAL);
}
}
}
static void
Campaign_ResetAlliances(void)
{
memset(g_table_houseAlliance, 0, sizeof(g_table_houseAlliance));
for (enum HouseType h = HOUSE_HARKONNEN; h < HOUSE_NEUTRAL; h++) {
g_table_houseAlliance[h][h] = HOUSEALLIANCE_ALLIES;
}
g_table_houseAlliance[HOUSE_ATREIDES][HOUSE_FREMEN] = HOUSEALLIANCE_ALLIES;
g_table_houseAlliance[HOUSE_FREMEN][HOUSE_ATREIDES] = HOUSEALLIANCE_ALLIES;
}
static void
Campaign_ResetEnhancements(void)
{
if (g_campaign_selected == CAMPAIGNID_DUNE_II) {
enhancement_fix_scenario_typos = true;
enhancement_read_scenario_structure_health = false;
} else {
enhancement_fix_scenario_typos = false;
enhancement_read_scenario_structure_health = true;
}
if (g_campaign_selected == CAMPAIGNID_SKIRMISH
|| g_campaign_selected == CAMPAIGNID_MULTIPLAYER) {
enhancement_true_unit_movement_speed = true;
enhancement_undelay_ordos_siege_tank_tech = true;
} else {
enhancement_true_unit_movement_speed = false;
enhancement_undelay_ordos_siege_tank_tech = false;
}
enhancement_infantry_mini_rockets = false;
enhancement_repair_cost_formula = REPAIR_COST_v107_HIGH_HP_FIX;
enhancement_special_trooper_portaits = true;
}
static void
Campaign_ReadEnhancements(char *source, char *keys)
{
char value[1024];
Ini_GetString("ENHANCEMENT", NULL, NULL, keys, 2000, source);
for (char *key = keys; *key != '\0'; key += strlen(key) + 1) {
Ini_GetString("ENHANCEMENT", key, NULL, value, sizeof(value), source);
if (strcasecmp(key, "repair_cost") == 0) {
if (strcmp(value, "1.0") == 0) enhancement_repair_cost_formula = REPAIR_COST_v100;
else if (strcmp(value, "1.07") == 0) enhancement_repair_cost_formula = REPAIR_COST_v107_HIGH_HP_FIX;
} else if (strcasecmp(key, "infantry_mini_rockets") == 0) {
String_GetBool(value, &enhancement_infantry_mini_rockets);
} else if (strcasecmp(key, "special_trooper_portraits") == 0) {
String_GetBool(value, &enhancement_special_trooper_portaits);
} else if (strcasecmp(key, "true_unit_movement_speed") == 0) {
String_GetBool(value, &enhancement_true_unit_movement_speed);
}
}
}
static void
Campaign_ReadMetaData(Campaign *camp)
{
Campaign_ResetEnhancements();
if (camp->dir_name[0] == '\0') /* Dune II */
return;
if (!File_Exists_Ex(SEARCHDIR_CAMPAIGN_DIR, "META.INI"))
return;
char value[1024];
char *source = GFX_Screen_Get_ByIndex(SCREEN_1);
memset(source, 0, 32000);
File_ReadBlockFile_Ex(SEARCHDIR_CAMPAIGN_DIR, "META.INI", source, GFX_Screen_GetSize_ByIndex(SCREEN_1));
camp->intermission = Ini_GetInteger("CAMPAIGN", "Intermission", 0, source);
char *keys = source + strlen(source) + 5000;
*keys = '\0';
/* Read tweaks. */
Campaign_ReadCPSTweaks(source, "FAME.CPS", value, sizeof(value), camp->fame_cps);
Campaign_ReadCPSTweaks(source, "MAPMACH.CPS", value, sizeof(value), camp->mapmach_cps);
Campaign_ReadCPSTweaks(source, "MISC.CPS", value, sizeof(value), camp->misc_cps);
Campaign_ReadEnhancements(source, keys);
/* Add PAK file entries. */
int i = snprintf(value, sizeof(value), "%s", camp->dir_name);
*keys = '\0';
Ini_GetString("PAK", NULL, NULL, keys, 2000, source);
FileInfo *fi;
unsigned int parent;
for (char *key = keys; *key != '\0'; key += strlen(key) + 1) {
if (strcasecmp(key, "Scenarios") == 0) {
/* Shortcut for all regions and scenarios. */
Ini_GetString("PAK", "Scenarios", NULL, value + i, sizeof(value) - i, source);
/* Handle white-space. */
int j = i;
while ((value[j] != '\0') && isspace(value[j])) j++;
if (i != j) memmove(value + i, value + j, strlen(value + j) + 1);
/* Already indexed this file. */
parent = FileHash_FindIndex(value);
if (parent != (unsigned int)-1)
continue;
fi = FileHash_Store(value);
fi->filename = strdup(value);
parent = FileHash_FindIndex(value);
for (int h = 0; h < 3; h++) {
if (camp->house[h] == HOUSE_INVALID)
continue;
snprintf(value + i, sizeof(value) - i, "REGION%c.INI", g_table_houseInfo[camp->house[h]].name[0]);
Campaign_AddFileInPAK(value, parent);
for (int scen = 0; scen <= 22; scen++) {
snprintf(value + i, sizeof(value) - i, "SCEN%c%03d.INI", g_table_houseInfo[camp->house[h]].name[0], scen);
Campaign_AddFileInPAK(value, parent);
}
}
} else {
/* PAK file content lists. */
snprintf(value + i, sizeof(value) - i, "%s", key);
/* Already indexed this file. */
parent = FileHash_FindIndex(value);
if (parent != (unsigned int)-1)
continue;
fi = FileHash_Store(value);
fi->filename = strdup(value);
parent = FileHash_FindIndex(value);
/* Get content list: file1,file2,... */
Ini_GetString("PAK", key, NULL, value + i, sizeof(value) - i, source);
char *start = value + i;
char *end = start + strlen(start);
while (start < end) {
while (isspace(*start)) start++;
char *sep = strchr(start, ',');
if (sep == NULL) {
sep = end;
} else {
*sep = '\0';
}
memmove(value + i, start, sep - start + 1);
String_Trim(value + i);
if (strlen(value + i) > 0)
Campaign_AddFileInPAK(value, parent);
start = sep + 1;
}
}
}
}
bool
Campaign_CustomCampaignsAvailable(void)
{
/* No additional campaigns installed. Only
* CAMPAIGNID_DUNE_II, CAMPAIGNID_SKIRMISH, CAMPAIGNID_MULTIPLAYER.
*/
return g_campaign_total > CAMPAIGNID_MULTIPLAYER + 1;
}
static enum MusicID
Campaign_MusicFromString(const char *str, enum MusicID def)
{
const char *names[MUSICID_MAX] = {
"None",
"Logos",
"Intro",
"Menu",
"Conquest",
"Cutscene",
"Credits",
"Brief Harkonnen", "Brief Atreides", "Brief Ordos",
"Win Harkonnen", "Win Atreides", "Win Ordos",
"Lose Harkonnen", "Lose Atreides", "Lose Ordos",
"Finale Harkonnen", "Finale Atreides", "Finale Ordos",
"Idle 1", "Idle 2", "Idle 3", "Idle 4", "Idle 5",
"Idle 6", "Idle 7", "Idle 8", "Idle 9", NULL,
"Bonus",
"Attack 1", "Attack 2", "Attack 3", "Attack 4", "Attack 5",
"Attack 6"
};
if (strcasecmp(str, "Idle") == 0)
return MUSIC_RANDOM_IDLE;
if (strcasecmp(str, "Attack") == 0)
return MUSIC_RANDOM_ATTACK;
for (enum MusicID m = MUSIC_STOP; m < MUSICID_MAX; m++) {
if ((names[m] != NULL) && (strcasecmp(str, names[m]) == 0))
return m;
}
return def;
}
static uint16
ObjectInfo_FlagsToUint16(const ObjectInfo *oi)
{
uint16 flags = 0;
/* Note: Read/write flags as they appear in the original executable. */
if (oi->flags.hasShadow) flags |= 0x0001;
if (oi->flags.factory) flags |= 0x0002;
/* 0x0004 unused. */
if (oi->flags.notOnConcrete) flags |= 0x0008;
if (oi->flags.busyStateIsIncoming) flags |= 0x0010;
if (oi->flags.blurTile) flags |= 0x0020;
if (oi->flags.hasTurret) flags |= 0x0040;
if (oi->flags.conquerable) flags |= 0x0080;
if (oi->flags.canBePickedUp) flags |= 0x0100;
if (oi->flags.noMessageOnDeath) flags |= 0x0200;
if (oi->flags.tabSelectable) flags |= 0x0400;
if (oi->flags.scriptNoSlowdown) flags |= 0x0800;
if (oi->flags.targetAir) flags |= 0x1000;
if (oi->flags.priority) flags |= 0x2000;
return flags;
}
static uint16
UnitInfo_FlagsToUint16(const UnitInfo *ui)
{
uint16 flags = 0;
/* Note: Read/write flags as they appear in the original executable. */
/* 0x0001 unused. */
if (ui->flags.isBullet) flags |= 0x0002;
if (ui->flags.explodeOnDeath) flags |= 0x0004;
if (ui->flags.sonicProtection) flags |= 0x0008;
if (ui->flags.canWobble) flags |= 0x0010;
if (ui->flags.isTracked) flags |= 0x0020;
if (ui->flags.isGroundUnit) flags |= 0x0040;
if (ui->flags.mustStayInMap) flags |= 0x0080;
/* 0x0100 unused. */
/* 0x0200 unused. */
if (ui->flags.firesTwice) flags |= 0x0400;
if (ui->flags.impactOnSand) flags |= 0x0800;
if (ui->flags.isNotDeviatable) flags |= 0x1000;
if (ui->flags.hasAnimationSet) flags |= 0x2000;
if (ui->flags.notAccurate) flags |= 0x4000;
if (ui->flags.isNormalUnit) flags |= 0x8000;
return flags;
}
static void
Campaign_ApplyDefaultHouseTraits(void)
{
for (enum StructureType s = STRUCTURE_PALACE; s < STRUCTURE_MAX; s++) {
const StructureInfo *original = &g_table_structureInfo_original[s];
StructureInfo *si = &g_table_structureInfo[s];
const enum HouseType ref =
(s == STRUCTURE_LIGHT_VEHICLE) ? HOUSE_HARKONNEN : HOUSE_MERCENARY;
for (enum HouseType h = HOUSE_HARKONNEN; h < HOUSE_NEUTRAL; h++) {
if (si->o.availableCampaign[h] & 0x8000) {
const int delta = original->o.availableCampaign[h] - original->o.availableCampaign[ref];
si->o.availableCampaign[h] = clamp(0, (si->o.availableCampaign[h] & 0xFF) + delta, 99);
}
for (int i = 0; i < 3; i++) {
if ((si->upgradeCampaign[i][h] & 0x8000) == 0)
continue;
/* ENHANCEMENT -- Ordos siege tanks used to arrive one level late. */
if (enhancement_undelay_ordos_siege_tank_tech && (s == STRUCTURE_HEAVY_VEHICLE) && (h == HOUSE_ORDOS) && (i == 2)) {
si->upgradeCampaign[i][h] = (si->upgradeCampaign[i][h] & 0xFF);
} else if (original->upgradeCampaign[i][h] == 0) {
si->upgradeCampaign[i][h] = 0;
} else {
const int delta = original->upgradeCampaign[i][h] - original->upgradeCampaign[i][HOUSE_MERCENARY];
si->upgradeCampaign[i][h] = clamp(0, (si->upgradeCampaign[i][h] & 0xFF) + delta, 99);
}
}
}
}
}
static void
Campaign_ReadHouseIni(void)
{
char *source;
char *key;
char *keys;
char buffer[120];
if (!File_Exists_Ex(SEARCHDIR_CAMPAIGN_DIR, "HOUSE.INI"))
return;
source = GFX_Screen_Get_ByIndex(SCREEN_1);
memset(source, 0, 32000);
File_ReadBlockFile_Ex(SEARCHDIR_CAMPAIGN_DIR, "HOUSE.INI", source, GFX_Screen_GetSize_ByIndex(SCREEN_1));
keys = source + strlen(source) + 5000;
*keys = '\0';
for (enum HouseType houseID = HOUSE_HARKONNEN; houseID < HOUSE_NEUTRAL; houseID++) {
const char *category = g_table_houseInfo_original[houseID].name;
const HouseInfo *original = &g_table_houseInfo_original[houseID];
HouseInfo *hi = &g_table_houseInfo[houseID];
Ini_GetString(category, NULL, NULL, keys, 2000, source);
for (key = keys; *key != '\0'; key += strlen(key) + 1) {
/* Weakness, LemonFactor, Decay, Recharge, Frigate, Special, Voice. */
if (strncasecmp(key, "Weakness", 8) == 0) {
hi->toughness = Ini_GetInteger(category, key, original->toughness, source);
} else if (strncasecmp(key, "LemonFactor", 11) == 0) {
hi->degradingChance = Ini_GetInteger(category, key, original->degradingChance, source);
} else if (strncasecmp(key, "Decay", 5) == 0) {
hi->degradingAmount = Ini_GetInteger(category, key, original->degradingAmount, source);
} else if ((strcasecmp(key, "Recharge") == 0)
|| (strncasecmp(key, "Palace recharge", 15) == 0)) {
hi->specialCountDown = Ini_GetInteger(category, key, original->specialCountDown, source);
} else if (strncasecmp(key, "Frigate", 7) == 0) {
hi->starportDeliveryTime = Ini_GetInteger(category, key, original->starportDeliveryTime, source);
} else if ((strcasecmp(key, "Special") == 0)
|| (strncasecmp(key, "Palace special", 14) == 0)) {
Ini_GetString(category, key, NULL, buffer, sizeof(buffer), source);
char *buf = buffer;
while (*buf == ' ' || *buf == '\t') buf++;
if ('a' <= buf[0] && buf[0] <= 'z')
buf[0] += 'A' - 'a';
if (buf[0] == 'M' || buf[0] == 'D') {
hi->specialWeapon = HOUSE_WEAPON_MISSILE;
hi->superWeapon.deathhand = NULL;
} else if (buf[0] == 'F') {
hi->specialWeapon = HOUSE_WEAPON_FREMEN;
hi->superWeapon.fremen.owner = HOUSE_FREMEN;
hi->superWeapon.fremen.unit75 = UNIT_TROOPERS;
hi->superWeapon.fremen.unit25 = UNIT_TROOPER;
} else if (buf[0] == 'S') {
hi->specialWeapon = HOUSE_WEAPON_SABOTEUR;
hi->superWeapon.saboteur.owner = houseID;
hi->superWeapon.saboteur.unit = UNIT_SABOTEUR;
}
} else if (strncasecmp(key, "Voice", 5) == 0) {
Ini_GetString(category, key, NULL, buffer, sizeof(buffer), source);
char *buf = buffer;
while (*buf == ' ' || *buf == '\t') buf++;
if ('a' <= buf[0] && buf[0] <= 'z')
buf[0] += 'A' - 'a';
if (buf[0] == 'H') hi->sampleSet = SAMPLESET_HARKONNEN;
else if (buf[0] == 'A') hi->sampleSet = SAMPLESET_ATREIDES;
else if (buf[0] == 'O') hi->sampleSet = SAMPLESET_ORDOS;
}
}
}
/* Dune Dynasty extensions. */
*keys = '\0';
Ini_GetString("Alliance", NULL, NULL, keys, 2000, source);
for (key = keys; *key != '\0'; key += strlen(key) + 1) {
Ini_GetString("Alliance", key, NULL, buffer, sizeof(buffer), source);
char *snd = strchr(key, '-');
if (snd == NULL)
continue;
snd++;
enum HouseType h1 = HOUSE_INVALID;
enum HouseType h2 = HOUSE_INVALID;
for (enum HouseType houseID = HOUSE_HARKONNEN; houseID < HOUSE_NEUTRAL; houseID++) {
if (*key == g_table_houseInfo_original[houseID].name[0])
h1 = houseID;
if (*snd == g_table_houseInfo_original[houseID].name[0])
h2 = houseID;
}
if ((h1 != HOUSE_INVALID && h2 != HOUSE_INVALID) && (h1 != h2)) {
enum HouseAlliance allied = HOUSEALLIANCE_BRAIN;
if (buffer[0] == 'a' || buffer[0] == 'A') allied = HOUSEALLIANCE_ALLIES;
else if (buffer[0] == 'e' || buffer[0] == 'E') allied = HOUSEALLIANCE_ENEMIES;
g_table_houseAlliance[h1][h2] = allied;
g_table_houseAlliance[h2][h1] = allied;
}
}
for (enum HouseType houseID = HOUSE_HARKONNEN; houseID < HOUSE_NEUTRAL; houseID++) {
HouseInfo *hi = &g_table_houseInfo[houseID];
char category[32];
snprintf(category, sizeof(category), "%s Extra", g_table_houseInfo_original[houseID].name);
*keys = '\0';
Ini_GetString(category, NULL, NULL, keys, 2000, source);
for (key = keys; *key != '\0'; key += strlen(key) + 1) {
Ini_GetString(category, key, NULL, buffer, sizeof(buffer), source);
if (strcasecmp(key, "Mentat") == 0) {
hi->mentat = Mentat_InitFromString(buffer, houseID);
} else if (strcasecmp(key, "Win music") == 0) {
hi->musicWin = Campaign_MusicFromString(buffer, g_table_houseInfo_original[houseID].musicWin);
} else if (strcasecmp(key, "Lose music") == 0) {
hi->musicLose = Campaign_MusicFromString(buffer, g_table_houseInfo_original[houseID].musicLose);
} else if (strcasecmp(key, "Mentat music") == 0) {
hi->musicBriefing = Campaign_MusicFromString(buffer, g_table_houseInfo_original[houseID].musicBriefing);
} else if (strcasecmp(key, "Superweapon") == 0) {
if (hi->specialWeapon == HOUSE_WEAPON_MISSILE) {
hi->superWeapon.deathhand = NULL;
} else if (hi->specialWeapon == HOUSE_WEAPON_FREMEN) {
uint16 owner, unit75, unit25;
const int count = sscanf(buffer, "%hu,%hu,%hu", &owner, &unit75, &unit25);
if (count != 3) {
fprintf(stderr, "[%s] %s=%d,%d,%d\n", category, key,
hi->superWeapon.fremen.owner, hi->superWeapon.fremen.unit75, hi->superWeapon.fremen.unit25);
continue;
}
hi->superWeapon.fremen.owner = (owner < HOUSE_NEUTRAL) ? owner : houseID;
hi->superWeapon.fremen.unit75 = (unit75 <= UNIT_MCV || unit75 == UNIT_SANDWORM) ? unit75 : UNIT_TROOPERS;
hi->superWeapon.fremen.unit25 = (unit25 <= UNIT_MAX || unit25 == UNIT_SANDWORM) ? unit25 : UNIT_TROOPER;
} else if (hi->specialWeapon == HOUSE_WEAPON_SABOTEUR) {
uint16 owner, unit;
const int count = sscanf(buffer, "%hu,%hu", &owner, &unit);
if (count != 2) {
fprintf(stderr, "[%s] %s=%d,%d\n", category, key,
hi->superWeapon.saboteur.owner, hi->superWeapon.saboteur.unit);
continue;
}
hi->superWeapon.saboteur.owner = (owner < HOUSE_NEUTRAL) ? owner : houseID;
hi->superWeapon.saboteur.unit = (unit <= UNIT_MCV || unit == UNIT_SANDWORM) ? unit : UNIT_SABOTEUR;
}
}
}
snprintf(category, sizeof(category), "%s Traits", g_table_houseInfo_original[houseID].name);
*keys = '\0';
Ini_GetString(category, NULL, NULL, keys, 2000, source);
for (key = keys; *key != '\0'; key += strlen(key) + 1) {
ObjectInfo *oi = NULL;
StructureInfo *si = NULL;
uint8 type;
type = Unit_StringToType(key);
if (type != UNIT_INVALID) {
oi = &g_table_unitInfo[type].o;
} else {
type = Structure_StringToType(key);
if (type != STRUCTURE_INVALID) {
si = &g_table_structureInfo[type];
oi = &g_table_structureInfo[type].o;
}
}
if (oi == NULL)
continue;
const enum HouseType ref = (type == STRUCTURE_LIGHT_VEHICLE) ? HOUSE_HARKONNEN : HOUSE_MERCENARY;
Ini_GetString(category, key, NULL, buffer, sizeof(buffer), source);
int16 availableCampaign;
int16 upgradeLevelRequired;
int16 upgradeCampaign[3];
const int count = sscanf(buffer, "%hd,%hd,%hd,%hd,%hd",
&availableCampaign, &upgradeLevelRequired,
&upgradeCampaign[0], &upgradeCampaign[1], &upgradeCampaign[2]);
if (count >= 2) {
oi->availableCampaign[houseID] = clamp(0, (oi->availableCampaign[houseID] & 0xFF) + availableCampaign, 99);
oi->upgradeLevelRequired[houseID] = clamp(0, (oi->upgradeLevelRequired[houseID] & 0xFF) + upgradeLevelRequired, 99);
}
if ((count == 5) && (si != NULL) && oi->flags.factory) {
si->upgradeCampaign[0][houseID] = clamp(0, (si->upgradeCampaign[0][houseID] & 0xFF) + upgradeCampaign[0], 99);
si->upgradeCampaign[1][houseID] = clamp(0, (si->upgradeCampaign[1][houseID] & 0xFF) + upgradeCampaign[1], 99);
si->upgradeCampaign[2][houseID] = clamp(0, (si->upgradeCampaign[2][houseID] & 0xFF) + upgradeCampaign[2], 99);
} else if (count >= 2) {
} else if ((si != NULL) && oi->flags.factory) {
const StructureInfo *original = &g_table_structureInfo_original[type];
fprintf(stderr, "[%s] %s=%d,%d,%d,%d,%d\n", category, key,
original->o.availableCampaign[houseID] - original->o.availableCampaign[ref],
original->o.upgradeLevelRequired[houseID] - original->o.upgradeLevelRequired[HOUSE_MERCENARY],
original->upgradeCampaign[0][houseID] - original->upgradeCampaign[0][HOUSE_MERCENARY],
original->upgradeCampaign[1][houseID] - original->upgradeCampaign[1][HOUSE_MERCENARY],
original->upgradeCampaign[2][houseID] - original->upgradeCampaign[2][HOUSE_MERCENARY]);
} else {
const ObjectInfo *original = (si == NULL) ? &g_table_unitInfo_original[type].o : &g_table_structureInfo_original[type].o;
fprintf(stderr, "[%s] %s=%d,%d\n", category, key,
original->availableCampaign[houseID] - original->availableCampaign[ref],
original->upgradeLevelRequired[houseID] - original->upgradeLevelRequired[HOUSE_MERCENARY]);
}
}
}
}
static void
Campaign_ReadProfileIni(void)
{
struct {
char type; /* unit, structure, or objects. */
const char *category;
} scandata[] = {
/* Dune II. */
{ 'O', "Construct" },
{ 'U', "Combat" },
/* Dune Dynasty extensions. */
{ 'O', "Availability" },
{ 'S', "Factory" },
{ 'S', "StructureInfo" },
{ 'U', "UnitObjectInfo" },
{ 'U', "UnitInfo" },
{ 'U', "UnitGFX" },
{ 'U', "UnitName" },
};
if (!File_Exists_Ex(SEARCHDIR_CAMPAIGN_DIR, "PROFILE.INI"))
return;
char *source = GFX_Screen_Get_ByIndex(SCREEN_1);
memset(source, 0, 32000);
File_ReadBlockFile_Ex(SEARCHDIR_CAMPAIGN_DIR, "PROFILE.INI", source, GFX_Screen_GetSize_ByIndex(SCREEN_1));
char *keys = source + strlen(source) + 5000;
char buffer[120];
for (unsigned int x = 0; x < lengthof(scandata); x++) {
const char *category = scandata[x].category;
*keys = '\0';
Ini_GetString(category, NULL, NULL, keys, 2000, source);
for (char *key = keys; *key != '\0'; key += strlen(key) + 1) {
ObjectInfo *oi = NULL;
StructureInfo *si = NULL;
UnitInfo *ui = NULL;
uint8 type = 0;
if (scandata[x].type == 'U' || scandata[x].type == 'O') {
type = Unit_StringToType(key);
if (type != UNIT_INVALID) {
ui = &g_table_unitInfo[type];
oi = &g_table_unitInfo[type].o;
}
}
if (scandata[x].type == 'S' || (scandata[x].type == 'O' && oi == NULL)) {
type = Structure_StringToType(key);
if (type != STRUCTURE_INVALID) {
si = &g_table_structureInfo[type];
oi = &g_table_structureInfo[type].o;
}
}
if (oi == NULL)
continue;
Ini_GetString(category, key, NULL, buffer, sizeof(buffer), source);
switch (x) {
case 0: /* Construct: buildCredits, buildTime, hitpoints, fogUncoverRadius, availableCampaign, priorityBuild, priorityTarget, sortPriority. */
{
ObjectInfo ot;
uint16 availableCampaign;
uint16 sortPriority; /* (uint8) concrete/concrete4 are 100/101 respectively. */
/* Gak, Dune II uses Harkonnen light factory as the reference point,
* even though they clearly have the deficiency.
*/
const enum HouseType ref =
(si == &g_table_structureInfo[STRUCTURE_LIGHT_VEHICLE]) ? HOUSE_HARKONNEN : HOUSE_MERCENARY;
const int count = sscanf(buffer, "%hu,%hu,%hu,%hu,%hu,%hu,%hu,%hu",
&ot.buildCredits, &ot.buildTime, &ot.hitpoints, &ot.fogUncoverRadius,
&availableCampaign, &ot.priorityBuild, &ot.priorityTarget, &sortPriority);
if (count < 7) {
fprintf(stderr, "[%s] %s=%u,%u,%u,%u,%u,%u,%u,%u\n", category, key,
oi->buildCredits, oi->buildTime, oi->hitpoints, oi->fogUncoverRadius,
oi->availableCampaign[ref], oi->priorityBuild, oi->priorityTarget, oi->sortPriority);
break;
}
oi->buildCredits = ot.buildCredits;
oi->buildTime = ot.buildTime;
oi->hitpoints = ot.hitpoints;
oi->fogUncoverRadius = ot.fogUncoverRadius;
oi->priorityBuild = ot.priorityBuild;
oi->priorityTarget = ot.priorityTarget;
const ObjectInfo *original = (ui != NULL) ? &g_table_unitInfo_original[type].o : &g_table_structureInfo_original[type].o;
for (enum HouseType h = HOUSE_HARKONNEN; h < HOUSE_NEUTRAL; h++) {
oi->availableCampaign[h] = min(availableCampaign, 99);
if (original->availableCampaign[h] - original->availableCampaign[ref] != 0)
oi->availableCampaign[h] |= 0x8000;
}
if (count >= 8) {
if ((si != &g_table_structureInfo[STRUCTURE_SLAB_1x1]) &&
(si != &g_table_structureInfo[STRUCTURE_SLAB_2x2])) {
oi->sortPriority = sortPriority;
}
}
}
break;
case 1: /* Combat: fireDistance, damage, fireDelay, movingSpeedFactor. */
{
UnitInfo ut;
const int count = sscanf(buffer, "%hu,%hu,%hu,%hu",
&ut.fireDistance, &ut.damage, &ut.fireDelay, &ut.movingSpeedFactor);
if (count < 4) {
fprintf(stderr, "[%s] %s=%u,%u,%u,%u\n", category, key,
ui->fireDistance, ui->damage, ui->fireDelay, ui->movingSpeedFactor);
break;
}
ui->damage = ut.damage;
ui->movingSpeedFactor = ut.movingSpeedFactor;
ui->fireDelay = ut.fireDelay;
ui->fireDistance = ut.fireDistance;
}
break;
case 2: /* Availability: availableHouse, structuresRequired, upgradeLevelRequired. */
{
uint16 availableHouse; /* (uint8) enum HouseFlag. */
uint32 structuresRequired; /* 0xFFFFFFFF or StructureFlag. */
uint16 upgradeLevelRequired; /* (uint8) 0 .. 3. */
const int count = sscanf(buffer, "%hX,%X,%hu",
&availableHouse, &structuresRequired, &upgradeLevelRequired);
if (count < 3) {
fprintf(stderr, "[%s] %s=0x%02X,0x%06X,%u\n", category, key,
oi->availableHouse, oi->structuresRequired, oi->upgradeLevelRequired[HOUSE_MERCENARY]);
break;
}
oi->availableHouse = availableHouse;
oi->structuresRequired = structuresRequired;
for (enum HouseType h = HOUSE_HARKONNEN; h < HOUSE_NEUTRAL; h++) {
oi->upgradeLevelRequired[h] = upgradeLevelRequired;
}
}
break;
case 3: /* Factory: buildableUnits[1..8], upgradeCampaign[1..3]. */
{
int16 buildableUnits[8]; /* -1 or enum UnitType. */
uint16 upgradeCampaign[3]; /* 0 .. 9. */
/* Use Dune II Mercenary upgrade levels as reference point for levels,
* since those are never modified.
*/
const int count = sscanf(buffer, "%hd,%hd,%hd,%hd,%hd,%hd,%hd,%hd,%hu,%hu,%hu",
&buildableUnits[0], &buildableUnits[1], &buildableUnits[2], &buildableUnits[3],
&buildableUnits[4], &buildableUnits[5], &buildableUnits[6], &buildableUnits[7],
&upgradeCampaign[0], &upgradeCampaign[1], &upgradeCampaign[2]);
if (count < 11) {
fprintf(stderr, "[%s] %s=%d,%d,%d,%d,%d,%d,%d,%d,%u,%u,%u\n", category, key,
si->buildableUnits[0], si->buildableUnits[1], si->buildableUnits[2], si->buildableUnits[3],
si->buildableUnits[4], si->buildableUnits[5], si->buildableUnits[6], si->buildableUnits[7],
si->upgradeCampaign[0][HOUSE_MERCENARY], si->upgradeCampaign[1][HOUSE_MERCENARY], si->upgradeCampaign[2][HOUSE_MERCENARY]);
break;
}
for (int i = 0; i < 8; i++) {
si->buildableUnits[i] = (0 <= buildableUnits[i] && buildableUnits[i] < UNIT_MAX) ? buildableUnits[i] : -1;
}
const StructureInfo *original = &g_table_structureInfo_original[type];
for (int i = 0; i < 3; i++) {
for (enum HouseType h = HOUSE_HARKONNEN; h < HOUSE_NEUTRAL; h++) {
si->upgradeCampaign[i][h] = min(upgradeCampaign[i], 99);
if (original->upgradeCampaign[i][h] - original->upgradeCampaign[i][HOUSE_MERCENARY] != 0)
si->upgradeCampaign[i][h] |= 0x8000;
}
}
}
break;
case 4: /* StructureInfo: objectFlags, spawnChance, enterFilter, creditsStorage, powerUsage. */
{
StructureInfo st;
uint16 flags;
const int count = sscanf(buffer, "%hX,%hu,%X,%hu,%hd",
&flags, &st.o.spawnChance, &st.enterFilter, &st.creditsStorage, &st.powerUsage);
if (count < 5) {
fprintf(stderr, "[%s] %s=0x%04X,%u,0x%06X,%u,%d\n", category, key,
ObjectInfo_FlagsToUint16(oi), si->o.spawnChance,
si->enterFilter, si->creditsStorage, si->powerUsage);
break;
}
oi->flags.hasShadow = (flags & 0x0001) ? 1 : 0;
oi->flags.factory = (flags & 0x0002) ? 1 : 0;
oi->flags.notOnConcrete = (flags & 0x0008) ? 1 : 0;
oi->flags.busyStateIsIncoming = (flags & 0x0010) ? 1 : 0;
/* oi->flags.blurTile = (flags & 0x0020) ? 1 : 0; */
/* oi->flags.hasTurret = (flags & 0x0040) ? 1 : 0; */
oi->flags.conquerable = (flags & 0x0080) ? 1 : 0;
/* oi->flags.canBePickedUp = (flags & 0x0100) ? 1 : 0; */
/* oi->flags.noMessageOnDeath = (flags & 0x0200) ? 1 : 0; */
/* oi->flags.tabSelectable = (flags & 0x0400) ? 1 : 0; */
/* oi->flags.scriptNoSlowdown = (flags & 0x0800) ? 1 : 0; */
/* oi->flags.targetAir = (flags & 0x1000) ? 1 : 0; */
/* oi->flags.priority = (flags & 0x2000) ? 1 : 0; */
si->o.spawnChance = st.o.spawnChance;
si->enterFilter = st.enterFilter;
si->creditsStorage = st.creditsStorage;
si->powerUsage = st.powerUsage;
}
break;
case 5: /* UnitObjectInfo: objectFlags, spawnChance, actionsPlayer[1..4]. */
{
ObjectInfo ot;
uint16 flags;
const int count = sscanf(buffer, "%hX,%hu,%hu,%hu,%hu,%hu",
&flags, &ot.spawnChance,
&ot.actionsPlayer[0], &ot.actionsPlayer[1], &ot.actionsPlayer[2], &ot.actionsPlayer[3]);
if (count < 6) {
fprintf(stderr, "[%s] %s=0x%04X,%u,%u,%u,%u,%u\n", category, key,
ObjectInfo_FlagsToUint16(oi), oi->spawnChance,
oi->actionsPlayer[0], oi->actionsPlayer[1], oi->actionsPlayer[2], oi->actionsPlayer[3]);
break;
}
oi->flags.hasShadow = (flags & 0x0001) ? 1 : 0;
/* oi->flags.factory = (flags & 0x0002) ? 1 : 0; */
/* oi->flags.notOnConcrete = (flags & 0x0008) ? 1 : 0; */
/* oi->flags.busyStateIsIncoming= (flags & 0x0010) ? 1 : 0; */
oi->flags.blurTile = (flags & 0x0020) ? 1 : 0;
oi->flags.hasTurret = (flags & 0x0040) ? 1 : 0;
/* oi->flags.conquerable = (flags & 0x0080) ? 1 : 0; */
oi->flags.canBePickedUp = (flags & 0x0100) ? 1 : 0;
oi->flags.noMessageOnDeath = (flags & 0x0200) ? 1 : 0;
/* oi->flags.tabSelectable = (flags & 0x0400) ? 1 : 0; */
/* oi->flags.scriptNoSlowdown = (flags & 0x0800) ? 1 : 0; */
oi->flags.targetAir = (flags & 0x1000) ? 1 : 0;
oi->flags.priority = (flags & 0x2000) ? 1 : 0;
oi->spawnChance = ot.spawnChance;
for (int i = 0; i < 4; i++) {
oi->actionsPlayer[i] = (ot.actionsPlayer[i] < ACTION_MAX) ? ot.actionsPlayer[i] : ACTION_ATTACK;
}
}
break;
case 6: /* UnitInfo: unitFlags, movementType, turningSpeed, explosionType, bulletType, bulletSound. */
{
uint16 flags;
uint16 movementType; /* enum UnitMovementType. */
uint16 turningSpeed; /* (uint8). */
int16 explosionType; /* -1 or 0 .. 19. */
int16 bulletType; /* UNIT_MISSILE_HOUSE .. UNIT_SANDWORM. */
int16 bulletSound; /* -1 or enum SoundID. */
const int count = sscanf(buffer, "%hX,%hu,%hu,%hd,%hd,%hd",
&flags, &movementType, &turningSpeed, &explosionType, &bulletType, &bulletSound);
if (count < 6) {
fprintf(stderr, "[%s] %s=0x%04X,%u,%u,%d,%d,%d\n", category, key,
UnitInfo_FlagsToUint16(ui), ui->movementType, ui->turningSpeed,
ui->explosionType, ui->bulletType, ui->bulletSound);
break;
}
ui->flags.isBullet = (flags & 0x0002) ? 1 : 0;
ui->flags.explodeOnDeath = (flags & 0x0004) ? 1 : 0;
ui->flags.sonicProtection = (flags & 0x0008) ? 1 : 0;
ui->flags.canWobble = (flags & 0x0010) ? 1 : 0;
ui->flags.isTracked = (flags & 0x0020) ? 1 : 0;
ui->flags.isGroundUnit = (flags & 0x0040) ? 1 : 0;
ui->flags.mustStayInMap = (flags & 0x0080) ? 1 : 0;
ui->flags.firesTwice = (flags & 0x0400) ? 1 : 0;
ui->flags.impactOnSand = (flags & 0x0800) ? 1 : 0;
ui->flags.isNotDeviatable = (flags & 0x1000) ? 1 : 0;
ui->flags.hasAnimationSet = (flags & 0x2000) ? 1 : 0;
ui->flags.notAccurate = (flags & 0x4000) ? 1 : 0;
ui->flags.isNormalUnit = (flags & 0x8000) ? 1 : 0;
ui->movementType = (movementType < MOVEMENT_MAX) ? movementType : MOVEMENT_FOOT;
ui->turningSpeed = turningSpeed;
ui->explosionType = (0 <= explosionType && explosionType < 20) ? explosionType : -1;
ui->bulletType = (UNIT_MISSILE_HOUSE <= bulletType && bulletType <= UNIT_SANDWORM) ? bulletType : -1;
ui->bulletSound = (0 <= bulletSound && bulletSound < SOUNDID_MAX) ? bulletSound : -1;
}
break;
case 7: /* UnitGFX: spriteID, groundSprites (base unit), turretSpriteID (base unit), animationSpeed. */
{
uint16 spriteID; /* SHAPE_CONCRETE_SLAB .. SHAPE_FREMEN. */
uint16 baseUnit; /* enum UnitType. */
int16 baseTurret; /* -1 or enum UnitType. */
uint16 animationSpeed;
const int count = sscanf(buffer, "%hu,%hu,%hd,%hu",
&spriteID, &baseUnit, &baseTurret, &animationSpeed);
if ((count < 4) || (baseUnit >= UNIT_MAX)) {
fprintf(stderr, "[%s] %s=%u,%u,%d,%u\n", category, key,
ui->o.spriteID, type, ((int16)ui->turretSpriteID == -1) ? -1 : type, ui->animationSpeed);
break;
}
ui->o.spriteID = clamp(SHAPE_CONCRETE_SLAB, spriteID, SHAPE_FREMEN);
ui->groundSpriteID = g_table_unitInfo_original[baseUnit].groundSpriteID;
ui->displayMode = g_table_unitInfo_original[baseUnit].displayMode;
ui->destroyedSpriteID = g_table_unitInfo_original[baseUnit].destroyedSpriteID;
ui->turretSpriteID = (0 <= baseTurret && baseTurret <= UNIT_MAX) ? g_table_unitInfo_original[baseTurret].turretSpriteID : -1;
ui->animationSpeed = animationSpeed;
}
break;
case 8: /* UnitName: stringIdAbbrev, stringIdFull. */
{
uint16 stringIdAbbrev;
uint16 stringIdFull;
const int count = sscanf(buffer, "%hu,%hu",
&stringIdAbbrev, &stringIdFull);
if ((count < 2)) {
fprintf(stderr, "[%s] %s=%u,%u\n", category, key,
ui->o.stringID_abbrev, ui->o.stringID_full);
break;
}
ui->o.stringID_abbrev = clamp(STR_CARRYALL, stringIdAbbrev, STR_MOBILE_CONST_VEHICLE);
ui->o.stringID_full = clamp(STR_CARRYALL, stringIdFull, STR_MOBILE_CONST_VEHICLE);
}
break;
default:
assert(false);
}
}
}
}
void
Campaign_Load(void)
{
static int l_campaign_selected = -1;
if (g_campaign_selected == l_campaign_selected
&& g_campaign_selected != CAMPAIGNID_SKIRMISH
&& g_campaign_selected != CAMPAIGNID_MULTIPLAYER)
return;
Campaign *camp = &g_campaign_list[g_campaign_selected];
Campaign_ResetAlliances();
memcpy(g_table_houseInfo, g_table_houseInfo_original, sizeof(g_table_houseInfo_original));
memcpy(g_table_structureInfo, g_table_structureInfo_original, sizeof(g_table_structureInfo_original));
memcpy(g_table_unitInfo, g_table_unitInfo_original, sizeof(g_table_unitInfo_original));
Campaign_ReadMetaData(camp);
Campaign_ReadProfileIni();
Campaign_ReadHouseIni();
Campaign_ApplyDefaultHouseTraits();
String_ReloadCampaignStrings();
l_campaign_selected = g_campaign_selected;
}
/*--------------------------------------------------------------*/
static void Scenario_Load_General(void)
{
g_scenario.winFlags = Ini_GetInteger("BASIC", "WinFlags", 0, s_scenarioBuffer);
g_scenario.loseFlags = Ini_GetInteger("BASIC", "LoseFlags", 0, s_scenarioBuffer);
g_scenario.mapSeed = Ini_GetInteger("MAP", "Seed", 0, s_scenarioBuffer);
g_scenario.timeOut = Ini_GetInteger("BASIC", "TimeOut", 0, s_scenarioBuffer);
g_viewportPosition = Ini_GetInteger("BASIC", "TacticalPos", g_viewportPosition, s_scenarioBuffer);
g_selectionRectanglePosition = Ini_GetInteger("BASIC", "CursorPos", g_selectionRectanglePosition, s_scenarioBuffer);
g_scenario.mapScale = Ini_GetInteger("BASIC", "MapScale", 0, s_scenarioBuffer);
Ini_GetString("BASIC", "BriefPicture", "HARVEST.WSA", g_scenario.pictureBriefing, 14, s_scenarioBuffer);
Ini_GetString("BASIC", "WinPicture", "WIN1.WSA", g_scenario.pictureWin, 14, s_scenarioBuffer);
Ini_GetString("BASIC", "LosePicture", "LOSTBILD.WSA", g_scenario.pictureLose, 14, s_scenarioBuffer);
g_selectionPosition = g_selectionRectanglePosition;
Map_MoveDirection(0, 0);
}
static void Scenario_Load_House(uint8 houseID)
{
const char *houseName = g_table_houseInfo[houseID].name;
char *houseType;
char buf[128];
char *b;
/* Get the type of the House (CPU / Human) */
Ini_GetString(houseName, "Brain", "NONE", buf, 127, s_scenarioBuffer);
for (b = buf; *b != '\0'; b++) if (*b >= 'a' && *b <= 'z') *b += 'A' - 'a';
houseType = strstr("HUMAN$CPU", buf);
if (houseType == NULL) return;
enum Brain brain = (*houseType == 'H') ? BRAIN_HUMAN : BRAIN_CPU;
uint16 credits;
uint16 creditsQuota;
uint16 unitCountMax;
credits = Ini_GetInteger(houseName, "Credits", 0, s_scenarioBuffer);
creditsQuota = Ini_GetInteger(houseName, "Quota", 0, s_scenarioBuffer);
unitCountMax = Ini_GetInteger(houseName, "MaxUnit", 39, s_scenarioBuffer);
/* ENHANCEMENT -- "MaxUnits" instead of MaxUnit. */
if (enhancement_fix_scenario_typos || enhancement_raise_unit_cap) {
if (unitCountMax == 0)
unitCountMax = Ini_GetInteger(houseName, "MaxUnits", 39, s_scenarioBuffer);
}
Scenario_Create_House(houseID, brain, credits, creditsQuota, unitCountMax);
}
House *
Scenario_Create_House(enum HouseType houseID, enum Brain brain,
uint16 credits, uint16 creditsQuota, uint16 unitCountMax)
{
House *h;
/* Create the house */
h = House_Allocate(houseID);
h->credits = credits;
h->creditsQuota = creditsQuota;
h->unitCountMax = unitCountMax;
/* For 'Brain = Human' we have to set a few additional things */
if (brain != BRAIN_HUMAN) return h;
h->flags.human = true;
g_playerHouseID = houseID;
g_playerHouse = h;
h->creditsStorageNoSilo = h->credits;
return h;
}
static void Scenario_Load_Houses(void)
{
House *h;
uint8 houseID;
for (houseID = 0; houseID < HOUSE_NEUTRAL; houseID++) {
Scenario_Load_House(houseID);
}
h = g_playerHouse;
/* In case there was no unitCountMax in the scenario, calculate
* it based on values used for the AI controlled houses. */
if (h->unitCountMax == 0) {
PoolFindStruct find;
uint8 max = 80;
for (const House *h2 = House_FindFirst(&find, HOUSE_INVALID);
h2 != NULL;
h2 = House_FindNext(&find)) {
/* Skip the human controlled house */
if (h2->flags.human) continue;
max -= h2->unitCountMax;
}
h->unitCountMax = max;
}
if (enhancement_raise_unit_cap) {
for (houseID = 0; houseID < HOUSE_NEUTRAL; houseID++) {
House *h2 = House_Get_ByIndex(houseID);
if (h2->unitCountMax > 0)
h2->unitCountMax = UNIT_MAX_PER_HOUSE_RAISED;
}
}
}
static void Scenario_Load_Unit(const char *key, char *settings)
{
uint8 houseType, unitType, actionType;
int8 orientation;
uint16 hitpoints;
tile32 position;
char *split;
VARIABLE_NOT_USED(key);
/* The value should have 6 values separated by a ',' */
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* First value is the House type */
houseType = House_StringToType(settings);
if (houseType == HOUSE_INVALID) return;
/* Find the next value in the ',' separated list */
settings = split + 1;
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* Second value is the Unit type */
unitType = Unit_StringToType(settings);
if (unitType == UNIT_INVALID) return;
/* Find the next value in the ',' separated list */
settings = split + 1;
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* Third value is the Hitpoints in percent (in base 256) */
hitpoints = atoi(settings);
/* Find the next value in the ',' separated list */
settings = split + 1;
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* Fourth value is the position on the map */
position = Tile_UnpackTile(atoi(settings));
/* Find the next value in the ',' separated list */
settings = split + 1;
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* Fifth value is orientation */
orientation = (int8)((uint8)atoi(settings));
/* Sixth value is the current state of the unit */
settings = split + 1;
actionType = Unit_ActionStringToType(settings);
if (actionType == ACTION_INVALID) return;
Scenario_Create_Unit(houseType, unitType, hitpoints, position, orientation, actionType);
}
void
Scenario_Create_Unit(enum HouseType houseType, enum UnitType unitType,
uint16 hitpoints, tile32 position, int8 orientation, enum UnitActionType actionType)
{
Unit *u;
u = Unit_Allocate(UNIT_INDEX_INVALID, unitType, houseType);
if (u == NULL) return;
u->o.flags.s.byScenario = true;
u->o.hitpoints = hitpoints * g_table_unitInfo[unitType].o.hitpoints / 256;
u->o.position = position;
u->orientation[0].current = orientation;
u->actionID = actionType;
u->nextActionID = ACTION_INVALID;
/* In case the above function failed and we are passed campaign 2, don't add the unit */
if (!Map_IsValidPosition(Tile_PackTile(u->o.position)) && g_campaignID > 2) {
Unit_Free(u);
return;
}
/* XXX -- There is no way this is ever possible, as the beingBuilt flag is unset by Unit_Allocate() */
if (!u->o.flags.s.isNotOnMap)
Unit_Server_SetAction(u, u->actionID);
u->o.seenByHouses = 0x00;
Unit_HouseUnitCount_Add(u, u->o.houseID);
Unit_SetOrientation(u, u->orientation[0].current, true, 0);
Unit_SetOrientation(u, u->orientation[0].current, true, 1);
Unit_SetSpeed(u, 0);
}
static void Scenario_Load_Structure(const char *key, char *settings)
{
uint8 index, houseType, structureType;
uint16 hitpoints, position;
char *split;
/* 'GEN' marked keys are Slabs and Walls, where the number following indicates the position on the map */
if (strncasecmp(key, "GEN", 3) == 0) {
/* Position on the map is in the key */
position = atoi(key + 3);
/* The value should have two values separated by a ',' */
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* First value is the House type */
houseType = House_StringToType(settings);
if (houseType == HOUSE_INVALID) return;
/* Second value is the Structure type */
settings = split + 1;
structureType = Structure_StringToType(settings);
if (structureType == STRUCTURE_INVALID) return;
Structure_Create(STRUCTURE_INDEX_INVALID, structureType, houseType, position);
return;
}
/* The key should start with 'ID', followed by the index */
index = atoi(key + 2);
/* The value should have four values separated by a ',' */
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* First value is the House type */
houseType = House_StringToType(settings);
if (houseType == HOUSE_INVALID) return;
/* Find the next value in the ',' separated list */
settings = split + 1;
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* Second value is the Structure type */
structureType = Structure_StringToType(settings);
if (structureType == STRUCTURE_INVALID) return;
/* Find the next value in the ',' separated list */
settings = split + 1;
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* Third value is the Hitpoints in percent (in base 256) */
/* ENHANCEMENT -- Dune2 ignores the % hitpoints read from the scenario */
if (enhancement_read_scenario_structure_health) {
if (enhancement_fix_scenario_typos) {
hitpoints = clamp(0, atoi(settings), 256);
} else {
hitpoints = atoi(settings);
}
} else {
hitpoints = 256;
}
/* Fourth value is the position of the structure */
settings = split + 1;
position = atoi(settings);
/* Ensure nothing is already on the tile */
/* XXX -- DUNE2 BUG? -- This only checks the top-left corner? Not really a safety, is it? */
if (Structure_Get_ByPackedTile(position) != NULL) return;
{
Structure *s;
/* ENHANCEMENT -- Atreides shouldn't get WOR since they can't do anything with it. */
if (enhancement_fix_scenario_typos) {
if ((houseType == HOUSE_ATREIDES && structureType == STRUCTURE_WOR_TROOPER) &&
((g_table_unitInfo[UNIT_TROOPER].o.availableHouse & FLAG_HOUSE_ATREIDES) == 0) &&
((g_table_unitInfo[UNIT_TROOPERS].o.availableHouse & FLAG_HOUSE_ATREIDES) == 0)) {
structureType = STRUCTURE_BARRACKS;
}
}
s = Structure_Create(index, structureType, houseType, position);
if (s == NULL) return;
s->o.hitpoints = hitpoints * g_table_structureInfo[s->o.type].o.hitpoints / 256;
s->o.flags.s.degrades = false;
s->state = STRUCTURE_STATE_IDLE;
}
}
static void Scenario_Load_Map(const char *key, char *settings)
{
Tile *t;
uint16 packed;
uint16 value;
char *s;
char posY[3];
if (*key != 'C') return;
memcpy(posY, key + 4, 2);
posY[2] = '\0';
packed = Tile_PackXY(atoi(posY), atoi(key + 6)) & 0xFFF;
t = &g_map[packed];
FogOfWarTile *f = &g_mapVisible[packed];
s = strtok(settings, ",\r\n");
value = atoi(s);
t->houseID = value & 0x07;
bool isUnveiled = (value & 0x08) != 0 ? true : false;
t->isUnveiled_ = false;
t->hasUnit = (value & 0x10) != 0 ? true : false;
t->hasStructure = (value & 0x20) != 0 ? true : false;
t->hasAnimation = (value & 0x40) != 0 ? true : false;
t->hasExplosion = (value & 0x80) != 0 ? true : false;
s = strtok(NULL, ",\r\n");
t->groundSpriteID = atoi(s) & 0x01FF;
if (g_mapSpriteID[packed] != t->groundSpriteID) g_mapSpriteID[packed] |= 0x8000;
if (isUnveiled) {
f->isUnveiled = (1 << g_playerHouseID);
f->fogSpriteID = 0;
} else {
f->fogSpriteID = g_veiledSpriteID;
}
}
void Scenario_Load_Map_Bloom(uint16 packed, Tile *t)
{
if (enhancement_fix_scenario_typos) {
/* SCENA005: spice bloom is found in rock. */
if (packed == 1364 && Map_GetLandscapeType(packed) == LST_ENTIRELY_ROCK) {
packed = 1360;
t = &g_map[packed];
}
}
t->groundSpriteID = g_bloomSpriteID;
g_mapSpriteID[packed] |= 0x8000;
}
void Scenario_Load_Map_Field(uint16 packed, Tile *t)
{
Map_Bloom_ExplodeSpice(packed, 0);
/* Show where a field started in the preview mode by making it an odd looking sprite */
if (g_debugScenario) {
t->groundSpriteID = 0x01FF;
}
}
void Scenario_Load_Map_Special(uint16 packed, Tile *t)
{
t->groundSpriteID = g_bloomSpriteID + 1;
g_mapSpriteID[packed] |= 0x8000;
}
static void Scenario_Load_Reinforcement(const char *key, char *settings)
{
uint8 index, houseType, unitType, locationID;
uint16 timeBetween;
bool repeat;
char *split;
/* There is a bug here: keys beginning with ';' are not ignored
* but read as index 0. This means that up to 10 units are
* created, and the final unit is delivered. The other indices
* are unusable. This only occurs in SCENA002,SCENA003,SCENA004.
*/
index = atoi(key);
/* The value should have 4 values separated by a ',' */
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* First value is the House type */
houseType = House_StringToType(settings);
if (houseType == HOUSE_INVALID) return;
/* Find the next value in the ',' separated list */
settings = split + 1;
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* Second value is the Unit type */
unitType = Unit_StringToType(settings);
if (unitType == UNIT_INVALID) return;
/* Find the next value in the ',' separated list */
settings = split + 1;
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* Third value is the location of the reinforcement */
if (strcasecmp(settings, "NORTH") == 0) locationID = 0;
else if (strcasecmp(settings, "EAST") == 0) locationID = 1;
else if (strcasecmp(settings, "SOUTH") == 0) locationID = 2;
else if (strcasecmp(settings, "WEST") == 0) locationID = 3;
else if (strcasecmp(settings, "AIR") == 0) locationID = 4;
else if (strcasecmp(settings, "VISIBLE") == 0) locationID = 5;
else if (strcasecmp(settings, "ENEMYBASE") == 0) locationID = 6;
else if (strcasecmp(settings, "HOMEBASE") == 0) locationID = 7;
else return;
/* Fourth value is the time between reinforcement */
settings = split + 1;
timeBetween = atoi(settings) * 6 + 1;
repeat = (settings[strlen(settings) - 1] == '+') ? true : false;
/* ENHANCEMENT -- Dune2 makes a mistake in reading the '+', causing repeat to be always false */
if (!enhancement_repeat_reinforcements) repeat = false;
Scenario_Create_Reinforcement(index, houseType, unitType, locationID, timeBetween, repeat);
}
void
Scenario_Create_Reinforcement(uint8 index, enum HouseType houseType,
enum UnitType unitType, uint8 locationID, uint16 timeBetween, bool repeat)
{
tile32 position;
Unit *u;
position.x = 0xFFFF;
position.y = 0xFFFF;
u = Unit_Create(UNIT_INDEX_INVALID, unitType, houseType, position, 0);
if (u == NULL) return;
g_scenario.reinforcement[index].unitID = u->o.index;
g_scenario.reinforcement[index].locationID = locationID;
g_scenario.reinforcement[index].timeLeft = timeBetween;
g_scenario.reinforcement[index].timeBetween = timeBetween;
g_scenario.reinforcement[index].repeat = repeat ? 1 : 0;
}
static void Scenario_Load_Team(const char *key, char *settings)
{
uint8 houseType, teamActionType, movementType;
uint16 minMembers, maxMembers;
char *split;
VARIABLE_NOT_USED(key);
/* The value should have 5 values separated by a ',' */
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* First value is the House type */
houseType = House_StringToType(settings);
if (houseType == HOUSE_INVALID) return;
/* Find the next value in the ',' separated list */
settings = split + 1;
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* Second value is the teamAction type */
teamActionType = Team_ActionStringToType(settings);
if (teamActionType == TEAM_ACTION_INVALID) return;
/* Find the next value in the ',' separated list */
settings = split + 1;
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* Third value is the movement type */
movementType = Unit_MovementStringToType(settings);
if (movementType == MOVEMENT_INVALID) return;
/* Find the next value in the ',' separated list */
settings = split + 1;
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* Fourth value is minimum amount of members in team */
minMembers = atoi(settings);
/* Find the next value in the ',' separated list */
settings = split + 1;
split = strchr(settings, ',');
if (split == NULL) return;
*split = '\0';
/* Fifth value is maximum amount of members in team */
maxMembers = atoi(settings);
Team_Create(houseType, teamActionType, movementType, minMembers, maxMembers);
}
/**
* Initialize a unit count of the starport.
* @param key Unit type to set.
* @param settings Count to set.
*/
static void Scenario_Load_Choam(const char *key, char *settings)
{
uint8 unitType;
unitType = Unit_StringToType(key);
if (unitType == UNIT_INVALID) return;
g_starportAvailable[unitType] = atoi(settings);
}
static void Scenario_Load_MapParts(const char *key, void (*ptr)(uint16 packed, Tile *t))
{
char *s;
char buf[128];
Ini_GetString("MAP", key, '\0', buf, 127, s_scenarioBuffer);
s = strtok(buf, ",\r\n");
while (s != NULL) {
uint16 packed;
Tile *t;
packed = atoi(s);
t = &g_map[packed];
(*ptr)(packed, t);
s = strtok(NULL, ",\r\n");
}
}
static void Scenario_Load_Chunk(const char *category, void (*ptr)(const char *key, char *settings))
{
char *buffer = g_readBuffer;
Ini_GetString(category, NULL, NULL, g_readBuffer, g_readBufferSize, s_scenarioBuffer);
while (true) {
char buf[127];
if (*buffer == '\0') break;
Ini_GetString(category, buffer, NULL, buf, 127, s_scenarioBuffer);
(*ptr)(buffer, buf);
buffer += strlen(buffer) + 1;
}
}
void Scenario_CentreViewport(uint8 houseID)
{
PoolFindStruct find;
const Structure *s = Structure_FindFirst(&find, houseID, STRUCTURE_CONSTRUCTION_YARD);
if (s != NULL) {
Map_CentreViewport((s->o.position.x >> 4) + TILE_SIZE, (s->o.position.y >> 4) + TILE_SIZE);
return;
}
/* ENHANCEMENT -- centre on MCV. */
const Unit *u = Unit_FindFirst(&find, houseID, UNIT_MCV);
if (u != NULL) {
Map_CentreViewport(u->o.position.x >> 4, u->o.position.y >> 4);
}
}
bool Scenario_Load(uint16 scenarioID, uint8 houseID)
{
char filename[14];
int i;
if (houseID >= HOUSE_NEUTRAL) return false;
g_scenarioID = scenarioID;
/* Load scenario file */
snprintf(filename, sizeof(filename), "SCEN%c%03d.INI", g_table_houseInfo[houseID].name[0], scenarioID);
if (!File_Exists_Ex(SEARCHDIR_CAMPAIGN_DIR, filename))
return false;
s_scenarioBuffer = File_ReadWholeFile_Ex(SEARCHDIR_CAMPAIGN_DIR, filename);
memset(&g_scenario, 0, sizeof(Scenario));
Scenario_Load_General();
Sprites_LoadTiles();
Map_CreateLandscape(g_scenario.mapSeed, NULL, g_map);
for (i = 0; i < 16; i++) {
g_scenario.reinforcement[i].unitID = UNIT_INDEX_INVALID;
}
Scenario_Load_Houses();
Scenario_Load_Chunk("UNITS", &Scenario_Load_Unit);
Scenario_Load_Chunk("STRUCTURES", &Scenario_Load_Structure);
Scenario_Load_Chunk("MAP", &Scenario_Load_Map);
Scenario_Load_Chunk("REINFORCEMENTS", &Scenario_Load_Reinforcement);
Scenario_Load_Chunk("TEAMS", &Scenario_Load_Team);
Scenario_Load_Chunk("CHOAM", &Scenario_Load_Choam);
Scenario_Load_MapParts("Bloom", Scenario_Load_Map_Bloom);
Scenario_Load_MapParts("Field", Scenario_Load_Map_Field);
Scenario_Load_MapParts("Special", Scenario_Load_Map_Special);
Scenario_CentreViewport(houseID);
g_tickScenarioStart = g_timerGame;
free(s_scenarioBuffer); s_scenarioBuffer = NULL;
return true;
}
/*--------------------------------------------------------------*/
void
Scenario_GetOldStats(enum HouseType houseID, OldScenarioStats *stats)
{
stats->score = 0;
stats->killedAllied = 0;
stats->killedEnemy = 0;
stats->destroyedAllied = 0;
stats->destroyedEnemy = 0;
stats->harvestedAllied = 0;
stats->harvestedEnemy = 0;
for (enum HouseType h = HOUSE_HARKONNEN; h < HOUSE_NEUTRAL; h++) {
if (House_AreAllied(houseID, h)) {
stats->score += g_scenario.score[h];
stats->killedAllied += g_scenario.unitsLost[h];
stats->destroyedAllied += g_scenario.structuresLost[h];
stats->harvestedAllied = min(65000, stats->harvestedAllied + g_scenario.spiceHarvested[h]);
} else {
stats->score -= g_scenario.score[h];
stats->killedEnemy += g_scenario.unitsLost[h];
stats->destroyedEnemy += g_scenario.structuresLost[h];
stats->harvestedEnemy = min(65000, stats->harvestedEnemy + g_scenario.spiceHarvested[h]);
}
}
}
| 412 | 0.919465 | 1 | 0.919465 | game-dev | MEDIA | 0.872191 | game-dev | 0.900675 | 1 | 0.900675 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.