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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Nextpeer/Nextpeer-UFORUN | 11,019 | cocos2d-x-2.2/external/emscripten/tests/bullet/src/BulletCollision/CollisionShapes/btCompoundShape.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.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 "btCompoundShape.h"
#include "btCollisionShape.h"
#include "BulletCollision/BroadphaseCollision/btDbvt.h"
#include "LinearMath/btSerializer.h"
btCompoundShape::btCompoundShape(bool enableDynamicAabbTree)
: m_localAabbMin(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT)),
m_localAabbMax(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT)),
m_dynamicAabbTree(0),
m_updateRevision(1),
m_collisionMargin(btScalar(0.)),
m_localScaling(btScalar(1.),btScalar(1.),btScalar(1.))
{
m_shapeType = COMPOUND_SHAPE_PROXYTYPE;
if (enableDynamicAabbTree)
{
void* mem = btAlignedAlloc(sizeof(btDbvt),16);
m_dynamicAabbTree = new(mem) btDbvt();
btAssert(mem==m_dynamicAabbTree);
}
}
btCompoundShape::~btCompoundShape()
{
if (m_dynamicAabbTree)
{
m_dynamicAabbTree->~btDbvt();
btAlignedFree(m_dynamicAabbTree);
}
}
void btCompoundShape::addChildShape(const btTransform& localTransform,btCollisionShape* shape)
{
m_updateRevision++;
//m_childTransforms.push_back(localTransform);
//m_childShapes.push_back(shape);
btCompoundShapeChild child;
child.m_node = 0;
child.m_transform = localTransform;
child.m_childShape = shape;
child.m_childShapeType = shape->getShapeType();
child.m_childMargin = shape->getMargin();
//extend the local aabbMin/aabbMax
btVector3 localAabbMin,localAabbMax;
shape->getAabb(localTransform,localAabbMin,localAabbMax);
for (int i=0;i<3;i++)
{
if (m_localAabbMin[i] > localAabbMin[i])
{
m_localAabbMin[i] = localAabbMin[i];
}
if (m_localAabbMax[i] < localAabbMax[i])
{
m_localAabbMax[i] = localAabbMax[i];
}
}
if (m_dynamicAabbTree)
{
const btDbvtVolume bounds=btDbvtVolume::FromMM(localAabbMin,localAabbMax);
int index = m_children.size();
child.m_node = m_dynamicAabbTree->insert(bounds,(void*)index);
}
m_children.push_back(child);
}
void btCompoundShape::updateChildTransform(int childIndex, const btTransform& newChildTransform,bool shouldRecalculateLocalAabb)
{
m_children[childIndex].m_transform = newChildTransform;
if (m_dynamicAabbTree)
{
///update the dynamic aabb tree
btVector3 localAabbMin,localAabbMax;
m_children[childIndex].m_childShape->getAabb(newChildTransform,localAabbMin,localAabbMax);
ATTRIBUTE_ALIGNED16(btDbvtVolume) bounds=btDbvtVolume::FromMM(localAabbMin,localAabbMax);
//int index = m_children.size()-1;
m_dynamicAabbTree->update(m_children[childIndex].m_node,bounds);
}
if (shouldRecalculateLocalAabb)
{
recalculateLocalAabb();
}
}
void btCompoundShape::removeChildShapeByIndex(int childShapeIndex)
{
m_updateRevision++;
btAssert(childShapeIndex >=0 && childShapeIndex < m_children.size());
if (m_dynamicAabbTree)
{
m_dynamicAabbTree->remove(m_children[childShapeIndex].m_node);
}
m_children.swap(childShapeIndex,m_children.size()-1);
if (m_dynamicAabbTree)
m_children[childShapeIndex].m_node->dataAsInt = childShapeIndex;
m_children.pop_back();
}
void btCompoundShape::removeChildShape(btCollisionShape* shape)
{
m_updateRevision++;
// Find the children containing the shape specified, and remove those children.
//note: there might be multiple children using the same shape!
for(int i = m_children.size()-1; i >= 0 ; i--)
{
if(m_children[i].m_childShape == shape)
{
removeChildShapeByIndex(i);
}
}
recalculateLocalAabb();
}
void btCompoundShape::recalculateLocalAabb()
{
// Recalculate the local aabb
// Brute force, it iterates over all the shapes left.
m_localAabbMin = btVector3(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT));
m_localAabbMax = btVector3(btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT),btScalar(-BT_LARGE_FLOAT));
//extend the local aabbMin/aabbMax
for (int j = 0; j < m_children.size(); j++)
{
btVector3 localAabbMin,localAabbMax;
m_children[j].m_childShape->getAabb(m_children[j].m_transform, localAabbMin, localAabbMax);
for (int i=0;i<3;i++)
{
if (m_localAabbMin[i] > localAabbMin[i])
m_localAabbMin[i] = localAabbMin[i];
if (m_localAabbMax[i] < localAabbMax[i])
m_localAabbMax[i] = localAabbMax[i];
}
}
}
///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version
void btCompoundShape::getAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax) const
{
btVector3 localHalfExtents = btScalar(0.5)*(m_localAabbMax-m_localAabbMin);
btVector3 localCenter = btScalar(0.5)*(m_localAabbMax+m_localAabbMin);
//avoid an illegal AABB when there are no children
if (!m_children.size())
{
localHalfExtents.setValue(0,0,0);
localCenter.setValue(0,0,0);
}
localHalfExtents += btVector3(getMargin(),getMargin(),getMargin());
btMatrix3x3 abs_b = trans.getBasis().absolute();
btVector3 center = trans(localCenter);
btVector3 extent = btVector3(abs_b[0].dot(localHalfExtents),
abs_b[1].dot(localHalfExtents),
abs_b[2].dot(localHalfExtents));
aabbMin = center-extent;
aabbMax = center+extent;
}
void btCompoundShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
{
//approximation: take the inertia from the aabb for now
btTransform ident;
ident.setIdentity();
btVector3 aabbMin,aabbMax;
getAabb(ident,aabbMin,aabbMax);
btVector3 halfExtents = (aabbMax-aabbMin)*btScalar(0.5);
btScalar lx=btScalar(2.)*(halfExtents.x());
btScalar ly=btScalar(2.)*(halfExtents.y());
btScalar lz=btScalar(2.)*(halfExtents.z());
inertia[0] = mass/(btScalar(12.0)) * (ly*ly + lz*lz);
inertia[1] = mass/(btScalar(12.0)) * (lx*lx + lz*lz);
inertia[2] = mass/(btScalar(12.0)) * (lx*lx + ly*ly);
}
void btCompoundShape::calculatePrincipalAxisTransform(btScalar* masses, btTransform& principal, btVector3& inertia) const
{
int n = m_children.size();
btScalar totalMass = 0;
btVector3 center(0, 0, 0);
int k;
for (k = 0; k < n; k++)
{
btAssert(masses[k]>0);
center += m_children[k].m_transform.getOrigin() * masses[k];
totalMass += masses[k];
}
btAssert(totalMass>0);
center /= totalMass;
principal.setOrigin(center);
btMatrix3x3 tensor(0, 0, 0, 0, 0, 0, 0, 0, 0);
for ( k = 0; k < n; k++)
{
btVector3 i;
m_children[k].m_childShape->calculateLocalInertia(masses[k], i);
const btTransform& t = m_children[k].m_transform;
btVector3 o = t.getOrigin() - center;
//compute inertia tensor in coordinate system of compound shape
btMatrix3x3 j = t.getBasis().transpose();
j[0] *= i[0];
j[1] *= i[1];
j[2] *= i[2];
j = t.getBasis() * j;
//add inertia tensor
tensor[0] += j[0];
tensor[1] += j[1];
tensor[2] += j[2];
//compute inertia tensor of pointmass at o
btScalar o2 = o.length2();
j[0].setValue(o2, 0, 0);
j[1].setValue(0, o2, 0);
j[2].setValue(0, 0, o2);
j[0] += o * -o.x();
j[1] += o * -o.y();
j[2] += o * -o.z();
//add inertia tensor of pointmass
tensor[0] += masses[k] * j[0];
tensor[1] += masses[k] * j[1];
tensor[2] += masses[k] * j[2];
}
tensor.diagonalize(principal.getBasis(), btScalar(0.00001), 20);
inertia.setValue(tensor[0][0], tensor[1][1], tensor[2][2]);
}
void btCompoundShape::setLocalScaling(const btVector3& scaling)
{
for(int i = 0; i < m_children.size(); i++)
{
btTransform childTrans = getChildTransform(i);
btVector3 childScale = m_children[i].m_childShape->getLocalScaling();
// childScale = childScale * (childTrans.getBasis() * scaling);
childScale = childScale * scaling / m_localScaling;
m_children[i].m_childShape->setLocalScaling(childScale);
childTrans.setOrigin((childTrans.getOrigin())*scaling);
updateChildTransform(i, childTrans,false);
}
m_localScaling = scaling;
recalculateLocalAabb();
}
void btCompoundShape::createAabbTreeFromChildren()
{
if ( !m_dynamicAabbTree )
{
void* mem = btAlignedAlloc(sizeof(btDbvt),16);
m_dynamicAabbTree = new(mem) btDbvt();
btAssert(mem==m_dynamicAabbTree);
for ( int index = 0; index < m_children.size(); index++ )
{
btCompoundShapeChild &child = m_children[index];
//extend the local aabbMin/aabbMax
btVector3 localAabbMin,localAabbMax;
child.m_childShape->getAabb(child.m_transform,localAabbMin,localAabbMax);
const btDbvtVolume bounds=btDbvtVolume::FromMM(localAabbMin,localAabbMax);
child.m_node = m_dynamicAabbTree->insert(bounds,(void*)index);
}
}
}
///fills the dataBuffer and returns the struct name (and 0 on failure)
const char* btCompoundShape::serialize(void* dataBuffer, btSerializer* serializer) const
{
btCompoundShapeData* shapeData = (btCompoundShapeData*) dataBuffer;
btCollisionShape::serialize(&shapeData->m_collisionShapeData, serializer);
shapeData->m_collisionMargin = float(m_collisionMargin);
shapeData->m_numChildShapes = m_children.size();
shapeData->m_childShapePtr = 0;
if (shapeData->m_numChildShapes)
{
btChunk* chunk = serializer->allocate(sizeof(btCompoundShapeChildData),shapeData->m_numChildShapes);
btCompoundShapeChildData* memPtr = (btCompoundShapeChildData*)chunk->m_oldPtr;
shapeData->m_childShapePtr = (btCompoundShapeChildData*)serializer->getUniquePointer(memPtr);
for (int i=0;i<shapeData->m_numChildShapes;i++,memPtr++)
{
memPtr->m_childMargin = float(m_children[i].m_childMargin);
memPtr->m_childShape = (btCollisionShapeData*)serializer->getUniquePointer(m_children[i].m_childShape);
//don't serialize shapes that already have been serialized
if (!serializer->findPointer(m_children[i].m_childShape))
{
btChunk* chunk = serializer->allocate(m_children[i].m_childShape->calculateSerializeBufferSize(),1);
const char* structType = m_children[i].m_childShape->serialize(chunk->m_oldPtr,serializer);
serializer->finalizeChunk(chunk,structType,BT_SHAPE_CODE,m_children[i].m_childShape);
}
memPtr->m_childShapeType = m_children[i].m_childShapeType;
m_children[i].m_transform.serializeFloat(memPtr->m_transform);
}
serializer->finalizeChunk(chunk,"btCompoundShapeChildData",BT_ARRAY_CODE,chunk->m_oldPtr);
}
return "btCompoundShapeData";
}
| 1 | 0.962667 | 1 | 0.962667 | game-dev | MEDIA | 0.967774 | game-dev | 0.995409 | 1 | 0.995409 |
CLADevs/VanillaX | 1,500 | src/CLADevs/VanillaX/entities/monster/ZombieEntity.php | <?php
namespace CLADevs\VanillaX\entities\monster;
use CLADevs\VanillaX\entities\utils\EntityClassification;
use CLADevs\VanillaX\entities\VanillaEntity;
use CLADevs\VanillaX\entities\utils\ItemHelper;
use pocketmine\item\Item;
use pocketmine\item\ItemFactory;
use pocketmine\item\ItemIds;
use pocketmine\nbt\tag\CompoundTag;
use pocketmine\network\mcpe\protocol\types\entity\EntityIds;
class ZombieEntity extends VanillaEntity{
const NETWORK_ID = EntityIds::ZOMBIE;
public $width = 0.6;
public $height = 1.9;
protected function initEntity(CompoundTag $nbt): void{
parent::initEntity($nbt);
$this->setMaxHealth(20);
}
public function getName(): string{
return "Zombie";
}
/**
* @return Item[]
*/
public function getDrops(): array{
$rotten_flesh = ItemFactory::getInstance()->get(ItemIds::ROTTEN_FLESH, 0, 1);
ItemHelper::applySetCount($rotten_flesh, 0, 2);
ItemHelper::applyLootingEnchant($this, $rotten_flesh);
return [$rotten_flesh, ItemFactory::getInstance()->get(ItemIds::IRON_INGOT, 0, 1), ItemFactory::getInstance()->get(ItemIds::CARROT, 0, 1), ItemFactory::getInstance()->get(ItemIds::POTATO, 0, 1)];
}
public function getXpDropAmount(): int{
return $this->getLastHitByPlayer() ? 5 + (count($this->getArmorInventory()->getContents()) * mt_rand(1, 3)) : 0;
}
public function getClassification(): int{
return EntityClassification::UNDEAD;
}
} | 1 | 0.819556 | 1 | 0.819556 | game-dev | MEDIA | 0.955572 | game-dev | 0.868619 | 1 | 0.868619 |
KevinDaGame/VoxelSniper-Reimagined | 11,335 | VoxelSniperCore/src/main/java/com/github/kevindagame/snipe/Sniper.java | package com.github.kevindagame.snipe;
import com.github.kevindagame.VoxelSniper;
import com.github.kevindagame.brush.BrushData;
import com.github.kevindagame.brush.IBrush;
import com.github.kevindagame.brush.perform.IPerformerBrush;
import com.github.kevindagame.brush.perform.PerformerBrush;
import com.github.kevindagame.brush.polymorphic.PolyBrush;
import com.github.kevindagame.util.BlockHelper;
import com.github.kevindagame.util.Messages;
import com.github.kevindagame.voxelsniper.block.BlockFace;
import com.github.kevindagame.voxelsniper.block.IBlock;
import com.github.kevindagame.voxelsniper.blockdata.IBlockData;
import com.github.kevindagame.voxelsniper.entity.player.IPlayer;
import com.github.kevindagame.voxelsniper.material.VoxelMaterial;
import net.kyori.adventure.text.ComponentLike;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
*
*/
public class Sniper {
public final IPlayer player;
private final LinkedList<Undo> undoList = new LinkedList<>();
private final Map<String, SnipeTool> tools = new HashMap<>();
private boolean enabled = true;
public Sniper(IPlayer player) {
this.player = player;
SnipeTool sniperTool = new SnipeTool(this);
sniperTool.assignAction(SnipeAction.ARROW, VoxelMaterial.getMaterial("arrow"));
sniperTool.assignAction(SnipeAction.GUNPOWDER, VoxelMaterial.getMaterial("gunpowder"));
tools.put(null, sniperTool);
}
public String getCurrentToolId() {
return getToolId((player.getItemInHand() != null) ? player.getItemInHand() : VoxelMaterial.AIR());
}
public String getToolId(VoxelMaterial itemInHand) {
if (itemInHand == null) {
return null;
}
for (Map.Entry<String, SnipeTool> entry : tools.entrySet()) {
if (entry.getValue().hasToolAssigned(itemInHand)) {
return entry.getKey();
}
}
return null;
}
/**
* Sniper execution call.
*
* @param action Action player performed
* @param itemInHand Item in hand of player
* @param clickedBlock Block that the player targeted/interacted with
* @param clickedFace Face of that targeted Block
* @return true if command visibly processed, false otherwise.
*/
public boolean snipe(Action action, VoxelMaterial itemInHand, IBlock clickedBlock, BlockFace clickedFace) {
String toolId = getToolId(itemInHand);
SnipeTool sniperTool = tools.get(toolId);
if (action == Action.PHYSICAL) {
return false;
}
if (!sniperTool.hasToolAssigned(itemInHand)) {
return false;
}
if (sniperTool.getCurrentBrush() == null) {
sendMessage(Messages.NO_BRUSH_SELECTED);
return true;
}
String permissionNode = sniperTool.getCurrentBrush().getPermissionNode();
if (!player.hasPermission(permissionNode)) {
sendMessage(Messages.NO_PERMISSION_BRUSH.replace("%permissionNode%", permissionNode));
return true;
}
SnipeData snipeData = sniperTool.getSnipeData();
SnipeAction snipeAction = sniperTool.getActionAssigned(itemInHand);
IBlock targetBlock, lastBlock;
if (clickedBlock != null) {
targetBlock = clickedBlock;
lastBlock = targetBlock.getRelative(clickedFace);
} else {
BlockHelper rangeBlockHelper = snipeData.isRanged() ? new BlockHelper(player, snipeData.getRange()) : new BlockHelper(player);
targetBlock = snipeData.isRanged() ? rangeBlockHelper.getRangeBlock() : rangeBlockHelper.getTargetBlock();
lastBlock = rangeBlockHelper.getLastBlock();
}
switch (action) {
case LEFT_CLICK_AIR:
case LEFT_CLICK_BLOCK:
if (player.isSneaking()) {
return handleSneakLeftClick(toolId, snipeData, snipeAction, targetBlock);
}
break;
case RIGHT_CLICK_AIR:
case RIGHT_CLICK_BLOCK:
return handleRightClick(clickedBlock, sniperTool, snipeData, snipeAction, targetBlock, lastBlock);
}
return false;
}
private boolean handleRightClick(IBlock clickedBlock, SnipeTool sniperTool, SnipeData snipeData, SnipeAction snipeAction, IBlock targetBlock, IBlock lastBlock) {
if (clickedBlock == null) {
if (targetBlock == null || lastBlock == null) {
sendMessage(Messages.TARGET_MUST_BE_VISIBLE);
return true;
}
}
var brush = sniperTool.getCurrentBrush();
if (brush == null) return true;
if (brush instanceof PerformerBrush performerBrush) {
performerBrush.initP(snipeData);
}
return brush.perform(snipeAction, snipeData, targetBlock, lastBlock);
}
private boolean handleSneakLeftClick(String toolId, SnipeData snipeData, SnipeAction snipeAction, IBlock targetBlock) {
IBlockData oldSubstance, newSubstance;
switch (snipeAction) {
case GUNPOWDER:
snipeData.setReplaceSubstance(targetBlock != null ? targetBlock.getBlockData() : SnipeData.DEFAULT_VOXEL_SUBSTANCE);
snipeData.getVoxelMessage().replace();
return true;
case ARROW:
snipeData.setVoxelSubstance(targetBlock != null ? targetBlock.getBlockData() : SnipeData.DEFAULT_VOXEL_SUBSTANCE);
snipeData.getVoxelMessage().voxel();
return true;
default:
return false;
}
}
public IBrush setBrush(String toolId, @NotNull IBrush brush) {
if (!tools.containsKey(toolId)) {
return null;
}
return tools.get(toolId).setCurrentBrush(brush);
}
public @Nullable IBrush getBrush(String toolId) {
if (!tools.containsKey(toolId)) {
return null;
}
return tools.get(toolId).getCurrentBrush();
}
/**
* For the given toolID, sets the current Brush to the previous Brush, and then returns the new Brush
*
* @return The new Brush, or null if there is no previous Brush
*/
public @Nullable IBrush previousBrush(String toolId) {
if (!tools.containsKey(toolId)) {
return null;
}
return tools.get(toolId).previousBrush();
}
public boolean setTool(String toolId, SnipeAction action, VoxelMaterial itemInHand) {
for (Map.Entry<String, SnipeTool> entry : tools.entrySet()) {
if (entry.getKey() != toolId && entry.getValue().hasToolAssigned(itemInHand)) {
return false;
}
}
if (!tools.containsKey(toolId)) {
SnipeTool tool = new SnipeTool(this);
tools.put(toolId, tool);
}
tools.get(toolId).assignAction(action, itemInHand);
return true;
}
public void removeTool(String toolId, VoxelMaterial itemInHand) {
if (!tools.containsKey(toolId)) {
SnipeTool tool = new SnipeTool(this);
tools.put(toolId, tool);
}
tools.get(toolId).unassignAction(itemInHand);
}
public void removeTool(String toolId) {
if (toolId == null) {
return;
}
tools.remove(toolId);
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void storeUndo(Undo undo) {
if (VoxelSniper.voxelsniper.getVoxelSniperConfiguration().getUndoCacheSize() <= 0) {
return;
}
if (undo != null && undo.getSize() > 0) {
while (undoList.size() >= VoxelSniper.voxelsniper.getVoxelSniperConfiguration().getUndoCacheSize()) {
this.undoList.pollLast();
}
undoList.push(undo);
}
}
public int undo() {
return undo(1);
}
public int undo(int amount) {
int changedBlocks = 0;
if (this.undoList.isEmpty()) {
sendMessage(Messages.NOTHING_TO_UNDO);
} else {
for (int x = 0; x < amount && !undoList.isEmpty(); x++) {
Undo undo = this.undoList.pop();
if (undo != null) {
undo.undo();
changedBlocks += undo.getSize();
} else {
break;
}
}
sendMessage(Messages.UNDO_SUCCESSFUL.replace("%changedBlocks%", String.valueOf(changedBlocks)));
}
return changedBlocks;
}
public void reset(String toolId) {
SnipeTool backup = tools.remove(toolId);
SnipeTool newTool = new SnipeTool(this);
for (Map.Entry<VoxelMaterial, SnipeAction> entry : backup.getActionTools().entrySet()) {
newTool.assignAction(entry.getValue(), entry.getKey());
}
tools.put(toolId, newTool);
}
public SnipeData getSnipeData(String toolId) {
return tools.containsKey(toolId) ? tools.get(toolId).getSnipeData() : null;
}
public IPlayer getPlayer() {
return player;
}
public void displayInfo() {
String currentToolId = getCurrentToolId();
SnipeTool sniperTool = tools.get(currentToolId);
IBrush brush = sniperTool.getCurrentBrush();
sendMessage(Messages.CURRENT_TOOL.replace("%tool%", (currentToolId != null) ? currentToolId : "Default Tool"));
if (brush == null) {
sendMessage(Messages.NO_BRUSH_SELECTED);
return;
}
brush.info(sniperTool.getMessageHelper());
if (brush instanceof IPerformerBrush) {
((IPerformerBrush) brush).showInfo(sniperTool.getMessageHelper());
}
}
public SnipeTool getSnipeTool(String toolId) {
return tools.get(toolId);
}
public final void sendMessage(final @NotNull ComponentLike message) {
player.sendMessage(message);
}
/**
* Create the instance of a brush based on the BrushData
*
* @param brushData
* @return {IBrush} The brush instance
**/
public @Nullable IBrush instantiateBrush(BrushData brushData) {
return this.instantiateBrush(brushData, false);
}
/**
* Create the instance of a brush based on the BrushData
*
* @param brushData
* @param force
* @return {IBrush} The brush instance
**/
public @Nullable IBrush instantiateBrush(BrushData brushData, boolean force) {
if (brushData == null) {
return null;
}
var brushInstance = brushData.getSupplier().get();
if (!(brushInstance instanceof PolyBrush)) {
brushInstance.setPermissionNode(brushData.getPermission());
brushInstance.setName(brushData.getName());
}
if (force || player.hasPermission(brushInstance.getPermissionNode()))
return brushInstance;
return null;
}
public enum Action {
LEFT_CLICK_BLOCK,
RIGHT_CLICK_BLOCK,
LEFT_CLICK_AIR,
RIGHT_CLICK_AIR,
PHYSICAL,
}
}
| 1 | 0.814047 | 1 | 0.814047 | game-dev | MEDIA | 0.469551 | game-dev | 0.868304 | 1 | 0.868304 |
DeebotUniverse/client.py | 8,583 | deebot_client/hardware/m1wkuw.py | """Deebot N10 Capabilities."""
from __future__ import annotations
from deebot_client.capabilities import (
Capabilities,
CapabilityClean,
CapabilityCleanAction,
CapabilityCustomCommand,
CapabilityEvent,
CapabilityExecute,
CapabilityLifeSpan,
CapabilityMap,
CapabilitySet,
CapabilitySetEnable,
CapabilitySettings,
CapabilitySetTypes,
CapabilityStats,
CapabilityWater,
DeviceType,
)
from deebot_client.commands.json.advanced_mode import GetAdvancedMode, SetAdvancedMode
from deebot_client.commands.json.battery import GetBattery
from deebot_client.commands.json.carpet import (
GetCarpetAutoFanBoost,
SetCarpetAutoFanBoost,
)
from deebot_client.commands.json.charge import Charge
from deebot_client.commands.json.charge_state import GetChargeState
from deebot_client.commands.json.clean import Clean, CleanArea, GetCleanInfo
from deebot_client.commands.json.clean_count import GetCleanCount, SetCleanCount
from deebot_client.commands.json.clean_preference import (
GetCleanPreference,
SetCleanPreference,
)
from deebot_client.commands.json.continuous_cleaning import (
GetContinuousCleaning,
SetContinuousCleaning,
)
from deebot_client.commands.json.custom import CustomCommand
from deebot_client.commands.json.efficiency import GetEfficiencyMode, SetEfficiencyMode
from deebot_client.commands.json.error import GetError
from deebot_client.commands.json.fan_speed import GetFanSpeed, SetFanSpeed
from deebot_client.commands.json.life_span import GetLifeSpan, ResetLifeSpan
from deebot_client.commands.json.map import (
GetCachedMapInfo,
GetMajorMap,
GetMapSet,
GetMapTrace,
GetMinorMap,
SetMajorMap,
)
from deebot_client.commands.json.multimap_state import (
GetMultimapState,
SetMultimapState,
)
from deebot_client.commands.json.network import GetNetInfo
from deebot_client.commands.json.ota import GetOta, SetOta
from deebot_client.commands.json.play_sound import PlaySound
from deebot_client.commands.json.pos import GetPos
from deebot_client.commands.json.relocation import SetRelocationState
from deebot_client.commands.json.stats import GetStats, GetTotalStats
from deebot_client.commands.json.voice_assistant_state import (
GetVoiceAssistantState,
SetVoiceAssistantState,
)
from deebot_client.commands.json.volume import GetVolume, SetVolume
from deebot_client.commands.json.water_info import GetWaterInfo, SetWaterInfo
from deebot_client.const import DataType
from deebot_client.events import (
AdvancedModeEvent,
AvailabilityEvent,
BatteryEvent,
CachedMapInfoEvent,
CarpetAutoFanBoostEvent,
CleanCountEvent,
CleanPreferenceEvent,
ContinuousCleaningEvent,
CustomCommandEvent,
EfficiencyModeEvent,
ErrorEvent,
FanSpeedEvent,
FanSpeedLevel,
LifeSpan,
LifeSpanEvent,
MajorMapEvent,
MapChangedEvent,
MapTraceEvent,
MultimapStateEvent,
NetworkInfoEvent,
OtaEvent,
PositionsEvent,
ReportStatsEvent,
RoomsEvent,
StateEvent,
StatsEvent,
TotalStatsEvent,
VoiceAssistantStateEvent,
VolumeEvent,
water_info,
)
from deebot_client.events.efficiency_mode import EfficiencyMode
from deebot_client.models import StaticDeviceInfo
def get_device_info() -> StaticDeviceInfo:
"""Get device info for this model."""
return StaticDeviceInfo(
DataType.JSON,
Capabilities(
device_type=DeviceType.VACUUM,
availability=CapabilityEvent(
AvailabilityEvent, [GetBattery(is_available_check=True)]
),
battery=CapabilityEvent(BatteryEvent, [GetBattery()]),
charge=CapabilityExecute(Charge),
clean=CapabilityClean(
action=CapabilityCleanAction(command=Clean, area=CleanArea),
continuous=CapabilitySetEnable(
ContinuousCleaningEvent,
[GetContinuousCleaning()],
SetContinuousCleaning,
),
count=CapabilitySet(CleanCountEvent, [GetCleanCount()], SetCleanCount),
preference=CapabilitySetEnable(
CleanPreferenceEvent, [GetCleanPreference()], SetCleanPreference
),
),
custom=CapabilityCustomCommand(
event=CustomCommandEvent, get=[], set=CustomCommand
),
error=CapabilityEvent(ErrorEvent, [GetError()]),
fan_speed=CapabilitySetTypes(
event=FanSpeedEvent,
get=[GetFanSpeed()],
set=SetFanSpeed,
types=(
FanSpeedLevel.QUIET,
FanSpeedLevel.NORMAL,
FanSpeedLevel.MAX,
FanSpeedLevel.MAX_PLUS,
),
),
life_span=CapabilityLifeSpan(
types=(
LifeSpan.BRUSH,
LifeSpan.FILTER,
LifeSpan.SIDE_BRUSH,
LifeSpan.UNIT_CARE,
),
event=LifeSpanEvent,
get=[
GetLifeSpan(
[
LifeSpan.BRUSH,
LifeSpan.FILTER,
LifeSpan.SIDE_BRUSH,
LifeSpan.UNIT_CARE,
]
)
],
reset=ResetLifeSpan,
),
map=CapabilityMap(
cached_info=CapabilityEvent(CachedMapInfoEvent, [GetCachedMapInfo()]),
changed=CapabilityEvent(MapChangedEvent, []),
major=CapabilitySet(MajorMapEvent, [GetMajorMap()], SetMajorMap),
minor=CapabilityExecute(GetMinorMap),
multi_state=CapabilitySetEnable(
MultimapStateEvent, [GetMultimapState()], SetMultimapState
),
position=CapabilityEvent(PositionsEvent, [GetPos()]),
relocation=CapabilityExecute(SetRelocationState),
rooms=CapabilityEvent(RoomsEvent, [GetCachedMapInfo()]),
set=CapabilityExecute(GetMapSet),
trace=CapabilityEvent(MapTraceEvent, [GetMapTrace()]),
),
network=CapabilityEvent(NetworkInfoEvent, [GetNetInfo()]),
play_sound=CapabilityExecute(PlaySound),
settings=CapabilitySettings(
advanced_mode=CapabilitySetEnable(
AdvancedModeEvent, [GetAdvancedMode()], SetAdvancedMode
),
carpet_auto_fan_boost=CapabilitySetEnable(
CarpetAutoFanBoostEvent,
[GetCarpetAutoFanBoost()],
SetCarpetAutoFanBoost,
),
efficiency_mode=CapabilitySetTypes(
event=EfficiencyModeEvent,
get=[GetEfficiencyMode()],
set=SetEfficiencyMode,
types=(
EfficiencyMode.ENERGY_EFFICIENT_MODE,
EfficiencyMode.STANDARD_MODE,
),
),
ota=CapabilitySetEnable(OtaEvent, [GetOta()], SetOta),
voice_assistant=CapabilitySetEnable(
VoiceAssistantStateEvent,
[GetVoiceAssistantState()],
SetVoiceAssistantState,
),
volume=CapabilitySet(VolumeEvent, [GetVolume()], SetVolume),
),
state=CapabilityEvent(StateEvent, [GetChargeState(), GetCleanInfo()]),
stats=CapabilityStats(
clean=CapabilityEvent(StatsEvent, [GetStats()]),
report=CapabilityEvent(ReportStatsEvent, []),
total=CapabilityEvent(TotalStatsEvent, [GetTotalStats()]),
),
water=CapabilityWater(
amount=CapabilitySetTypes(
event=water_info.WaterAmountEvent,
get=[GetWaterInfo()],
set=SetWaterInfo,
types=(
water_info.WaterAmount.LOW,
water_info.WaterAmount.MEDIUM,
water_info.WaterAmount.HIGH,
water_info.WaterAmount.ULTRAHIGH,
),
),
mop_attached=CapabilityEvent(
water_info.MopAttachedEvent, [GetWaterInfo()]
),
),
),
)
| 1 | 0.847958 | 1 | 0.847958 | game-dev | MEDIA | 0.396211 | game-dev | 0.845544 | 1 | 0.845544 |
tempo-sim/Tempo | 24,598 | External/Traffic/Source/MassTraffic/Private/MassTrafficPhysics.cpp | // Copyright Epic Games, Inc. All Rights Reserved.
#include "MassTrafficPhysics.h"
#include "MassTraffic.h"
#include "MassTrafficVehicleControlInterface.h"
#include "WheeledVehiclePawn.h"
#include "Chaos/MassProperties.h"
#include "Chaos/PBDJointConstraintUtilities.h"
#include "Components/SkeletalMeshComponent.h"
#include "Physics/Experimental/ChaosInterfaceUtils.h"
Chaos::FSimpleEngineConfig FMassTrafficSimpleVehiclePhysicsSim::DefaultEngineConfig;
Chaos::FSimpleDifferentialConfig FMassTrafficSimpleVehiclePhysicsSim::DefaultDifferentialConfig;
Chaos::FSimpleTransmissionConfig FMassTrafficSimpleVehiclePhysicsSim::DefaultTransmissionConfig;
Chaos::FSimpleSteeringConfig FMassTrafficSimpleVehiclePhysicsSim::DefaultSteeringConfig;
Chaos::FSimpleAerodynamicsConfig FMassTrafficSimpleVehiclePhysicsSim::DefaultAerodynamicsConfig;
void UE::MassTraffic::ExtractPhysicsVehicleConfig(
// TSubclassOf<AWheeledVehiclePawn> PhysicsActorClass,
AWheeledVehiclePawn* PhysicsActor,
FMassTrafficSimpleVehiclePhysicsConfig& OutVehicleConfig,
FMassTrafficSimpleVehiclePhysicsSim& OutVehicleSim
)
{
// Set the speed here so we trigger the center of mass calculations.
if (PhysicsActor->Implements<UMassTrafficVehicleControlInterface>())
{
IMassTrafficVehicleControlInterface::Execute_SetVehicleInputs(PhysicsActor, 0.0f, 1.0f, false, 0.0f, true);
}
// Artificially tick the actor for a pretend second to remove control input lag and let the center of mass
// get moved around.
for(int t=0; t<30; t++)
{
PhysicsActor->Tick(1.0f/30.0f);
}
UChaosWheeledVehicleMovementComponent* VehicleMovementComponent = Cast<UChaosWheeledVehicleMovementComponent>(PhysicsActor->GetVehicleMovementComponent());
TUniquePtr<Chaos::FSimpleWheeledVehicle> SimpleWheeledVehicle = VehicleMovementComponent->CreatePhysicsVehicle();
VehicleMovementComponent->SetupVehicle(SimpleWheeledVehicle);
// Copy basic values
FBodyInstance* BodyInstance = Cast<UPrimitiveComponent>(PhysicsActor->GetVehicleMovementComponent()->UpdatedComponent)->GetBodyInstance();
if (!ensure(BodyInstance))
{
UE_LOG(LogMassTraffic, Error, TEXT("No root physics body found on %s to extract physics vehicle config from"), *VehicleMovementComponent->UpdatedComponent->GetName());
return;
}
// Find the mass and center of mass for all the bodies that are NOT the root and we'll then use
// that later to apply it.
OutVehicleConfig.PeripheralCenterOfMass = FVector::ZeroVector;
OutVehicleConfig.PeripheralMass = 0.0f;
for (FBodyInstance* BI : PhysicsActor->GetMesh()->Bodies)
{
if (BI != BodyInstance && BI->IsValidBodyInstance() && !BI->IsPhysicsDisabled() && BI->IsNonKinematic())
{
const float BodyMass = BI->GetBodyMass();
OutVehicleConfig.PeripheralCenterOfMass += BodyMass * BI->GetCOMPosition();
OutVehicleConfig.PeripheralMass += BodyMass;
}
}
OutVehicleConfig.PeripheralCenterOfMass = PhysicsActor->GetActorTransform().InverseTransformPosition(OutVehicleConfig.PeripheralCenterOfMass);
// Some vehicles have zero peripheral mass. Guard against a divide by zero.
if (OutVehicleConfig.PeripheralMass > 0.0)
{
OutVehicleConfig.PeripheralCenterOfMass /= OutVehicleConfig.PeripheralMass;
}
// Remove all of this peripheral mass from our main body mass.
OutVehicleConfig.Mass = PhysicsActor->GetMesh()->GetMass() - OutVehicleConfig.PeripheralMass;
FTransform MassSpace = BodyInstance->GetMassSpaceToWorldSpace().GetRelativeTransform(PhysicsActor->GetActorTransform());
OutVehicleConfig.RotationOfMass = MassSpace.GetRotation();
OutVehicleConfig.CenterOfMass = PhysicsActor->GetActorTransform().InverseTransformPosition(PhysicsActor->GetMesh()->GetSkeletalCenterOfMass());
// The root body may have an offset from the actor root. As we only ever simulate this single body we factor this
// extra offset out by converting all the vehicle intrinsic transforms from body-local to actor space. This
// way we can simply simulate the actor transform directly.
OutVehicleConfig.BodyToActor = BodyInstance->GetUnrealWorldTransform().GetRelativeTransform(PhysicsActor->GetActorTransform());
OutVehicleConfig.NumDrivenWheels = SimpleWheeledVehicle->NumDrivenWheels;
OutVehicleConfig.LinearEtherDrag = BodyInstance->LinearDamping;
OutVehicleConfig.InverseMomentOfInertia = FVector(1.0f) / BodyInstance->GetBodyInertiaTensor();
// Set OutVehicleSim to use OutVehicleConfig
OutVehicleSim.SetupPtr = &OutVehicleConfig;
// Harvest sim parameters
OutVehicleConfig.EngineConfig = SimpleWheeledVehicle->Engine[0].Setup();
OutVehicleSim.EngineSim = SimpleWheeledVehicle->Engine[0];
OutVehicleSim.EngineSim.SetupPtr = &OutVehicleConfig.EngineConfig;
OutVehicleConfig.DifferentialConfig = SimpleWheeledVehicle->Differential[0].Setup();
OutVehicleSim.DifferentialSim = SimpleWheeledVehicle->Differential[0];
OutVehicleSim.DifferentialSim.SetupPtr = &OutVehicleConfig.DifferentialConfig;
OutVehicleConfig.TransmissionConfig = SimpleWheeledVehicle->Transmission[0].Setup();
OutVehicleSim.TransmissionSim = SimpleWheeledVehicle->Transmission[0];
OutVehicleSim.TransmissionSim.SetupPtr = &OutVehicleConfig.TransmissionConfig;
OutVehicleConfig.SteeringConfig = SimpleWheeledVehicle->Steering[0].Setup();
OutVehicleSim.SteeringSim = SimpleWheeledVehicle->Steering[0];
OutVehicleSim.SteeringSim.SetupPtr = &OutVehicleConfig.SteeringConfig;
OutVehicleConfig.AerodynamicsConfig = SimpleWheeledVehicle->Aerodynamics[0].Setup();
OutVehicleSim.AerodynamicsSim = SimpleWheeledVehicle->Aerodynamics[0];
OutVehicleSim.AerodynamicsSim.SetupPtr = &OutVehicleConfig.AerodynamicsConfig;
// Pre-allocate all Configs up-front so we have stable address for all of the to set in the sims
OutVehicleConfig.AxleConfigs.SetNum(SimpleWheeledVehicle->Axles.Num());
OutVehicleConfig.WheelConfigs.SetNum(SimpleWheeledVehicle->Wheels.Num());
OutVehicleConfig.SuspensionConfigs.SetNum(SimpleWheeledVehicle->Suspension.Num());
OutVehicleSim.AxleSims.Reset();
for (int32 AxleIndex = 0; AxleIndex < SimpleWheeledVehicle->Axles.Num(); ++AxleIndex)
{
const Chaos::FAxleSim& AxleSim = SimpleWheeledVehicle->Axles[AxleIndex];
Chaos::FAxleConfig& OutAxleConfig = OutVehicleConfig.AxleConfigs[AxleIndex];
OutAxleConfig = AxleSim.Setup;
Chaos::FAxleSim& OutAxleSim = OutVehicleSim.AxleSims.AddDefaulted_GetRef();
OutAxleSim = AxleSim;
// For the simulation fragment to be trivially relocatable, we redirect the SetupPtr to our stable pointer
OutAxleSim.SetupPtr = &OutAxleConfig;
}
OutVehicleSim.WheelSims.Reset();
OutVehicleConfig.MaxSteeringAngle = 0.0f;
for (int32 WheelIndex = 0; WheelIndex < SimpleWheeledVehicle->Wheels.Num(); ++WheelIndex)
{
const Chaos::FSimpleWheelSim& WheelSim = SimpleWheeledVehicle->Wheels[WheelIndex];
Chaos::FSimpleWheelConfig& OutWheelConfig = OutVehicleConfig.WheelConfigs[WheelIndex];
OutWheelConfig = WheelSim.Setup();
Chaos::FSimpleWheelSim& OutWheelSim = OutVehicleSim.WheelSims.Emplace_GetRef(&OutWheelConfig);
OutWheelSim = WheelSim;
OutWheelSim.SetupPtr = &OutWheelConfig;
OutVehicleConfig.MaxSteeringAngle = FMath::Max(OutVehicleConfig.MaxSteeringAngle, FMath::DegreesToRadians(OutWheelConfig.MaxSteeringAngle));
}
OutVehicleSim.SuspensionSims.Reset();
OutVehicleSim.WheelLocalLocations.Reset();
for (int32 SuspensionIndex = 0; SuspensionIndex < SimpleWheeledVehicle->Suspension.Num(); ++SuspensionIndex)
{
const Chaos::FSimpleSuspensionSim& SuspensionSim = SimpleWheeledVehicle->Suspension[SuspensionIndex];
Chaos::FSimpleSuspensionConfig& OutSuspensionConfig = OutVehicleConfig.SuspensionConfigs[SuspensionIndex];
OutSuspensionConfig = SuspensionSim.Setup();
// Add a 10m raycast safety margin so vehicles falling through the floor on a large DT can still find the
// floor and push back up
OutSuspensionConfig.RaycastSafetyMargin = 1000.0f;
Chaos::FSimpleSuspensionSim& OutSuspensionSim = OutVehicleSim.SuspensionSims.Emplace_GetRef(&OutSuspensionConfig);
OutSuspensionSim = SuspensionSim;
OutSuspensionSim.SetupPtr = &OutSuspensionConfig;
// The root body may have an offset from the actor root. As we only ever simulate this single body we factor this
// extra offset out by converting all the vehicle intrinsic transforms from body-local to actor space. This
// way we can simply simulate the actor transform directly.
OutSuspensionSim.SetLocalRestingPosition(OutVehicleConfig.BodyToActor.TransformPosition(OutSuspensionSim.GetLocalRestingPosition()));
OutVehicleSim.WheelLocalLocations.Add(OutSuspensionSim.GetLocalRestingPosition());
}
}
void FMassTrafficSimpleTrailerConstraintSolver::Init(
const float Dt,
const Chaos::FPBDJointSolverSettings& SolverSettings,
const Chaos::FPBDJointSettings& JointSettings,
const FVector& PrevP0,
const FVector& PrevP1,
const FQuat& PrevQ0,
const FQuat& PrevQ1,
const float InvM0,
const FVector& InvIL0,
const float InvM1,
const FVector& InvIL1,
const FTransform& XL0,
const FTransform& XL1
)
{
XLs[0] = XL0;
XLs[1] = XL1;
InvILs[0] = JointSettings.ParentInvMassScale * InvIL0;
InvILs[1] = InvIL1;
InvMs[0] = JointSettings.ParentInvMassScale * InvM0;
InvMs[1] = InvM1;
check(InvMs[0] > 0.0f);
check(InvMs[1] > 0.0f);
Chaos::FPBDJointUtilities::ConditionInverseMassAndInertia(InvMs[0], InvMs[1], InvILs[0], InvILs[1], SolverSettings.MinParentMassRatio, SolverSettings.MaxInertiaRatio);
// Tolerances are positional errors below visible detection. But in PBD the errors
// we leave behind get converted to velocity, so we need to ensure that the resultant
// movement from that erroneous velocity is less than the desired position tolerance.
// Assume that the tolerances were defined for a 60Hz simulation, then it must be that
// the position error is less than the position change from constant external forces
// (e.g., gravity). So, we are saying that the tolerance was chosen because the position
// error is less that F.dt^2. We need to scale the tolerance to work at our current dt.
const float ToleranceScale = FMath::Min(1.f, 60.f * 60.f * Dt * Dt);
PositionTolerance = ToleranceScale * SolverSettings.PositionTolerance;
AngleTolerance = ToleranceScale * SolverSettings.AngleTolerance;
// @see FJointSolverGaussSeidel::InitDerivedState();
{
Xs[0] = PrevP0 + PrevQ0 * XLs[0].GetTranslation();
Rs[0] = PrevQ0 * XLs[0].GetRotation();
InvIs[0] = Chaos::Utilities::ComputeWorldSpaceInertia(PrevQ0, InvILs[0]);
Xs[1] = PrevP1 + PrevQ1 * XLs[1].GetTranslation();
Rs[1] = PrevQ1 * XLs[1].GetRotation();
Rs[1].EnforceShortestArcWith(Rs[0]);
InvIs[1] = Chaos::Utilities::ComputeWorldSpaceInertia(PrevQ1, InvILs[1]);
}
bIsActive = true;
SolverStiffness = 1.0f;
}
void FMassTrafficSimpleTrailerConstraintSolver::Update(
const int32 It, const int32 NumIts,
const Chaos::FPBDJointSolverSettings& SolverSettings,
const FVector& P0, const FQuat& Q0, const FVector& V0, const FVector& W0, const FVector& P1, const FQuat& Q1,
const FVector& V1, const FVector& W1
)
{
// @see FJointSolverGaussSeidel::Update
Ps[0] = P0;
Ps[1] = P1;
Qs[0] = Q0;
Qs[1] = Q1;
Qs[1].EnforceShortestArcWith(Qs[0]);
Vs[0] = V0;
Vs[1] = V1;
Ws[0] = W0;
Ws[1] = W1;
SolverStiffness = CalculateIterationStiffness(It, NumIts, SolverSettings);
UpdateDerivedState();
UpdateIsActive();
}
void FMassTrafficSimpleTrailerConstraintSolver::ApplyConstraints(
const float Dt,
const Chaos::FPBDJointSolverSettings& SolverSettings,
const Chaos::FPBDJointSettings& JointSettings)
{
ApplyPositionConstraints(Dt, SolverSettings, JointSettings);
ApplyRotationConstraints(Dt, SolverSettings, JointSettings);
UpdateIsActive();
}
void FMassTrafficSimpleTrailerConstraintSolver::UpdateDerivedState()
{
// @see FJointSolverGaussSeidel::UpdateDerivedState()
// Kinematic bodies will not be moved, so we don't update derived state during iterations
if (InvMs[0] > 0.0f)
{
Xs[0] = Ps[0] + Qs[0] * XLs[0].GetTranslation();
Rs[0] = Qs[0] * XLs[0].GetRotation();
InvIs[0] = Chaos::Utilities::ComputeWorldSpaceInertia(Qs[0], InvILs[0]);
}
if (InvMs[1] > 0.0f)
{
Xs[1] = Ps[1] + Qs[1] * XLs[1].GetTranslation();
Rs[1] = Qs[1] * XLs[1].GetRotation();
InvIs[1] = Chaos::Utilities::ComputeWorldSpaceInertia(Qs[1], InvILs[1]);
}
Rs[1].EnforceShortestArcWith(Rs[0]);
}
bool FMassTrafficSimpleTrailerConstraintSolver::UpdateIsActive()
{
// NumActiveConstraints is initialized to -1, so there's no danger of getting invalid LastPs/Qs
// We also check SolverStiffness mainly for testing when solver stiffness is 0 (so we don't exit immediately)
if (SolverStiffness > 0.0f)
{
bool bIsSolved =
Chaos::FVec3::IsNearlyEqual(Ps[0], LastPs[0], PositionTolerance)
&& Chaos::FVec3::IsNearlyEqual(Ps[1], LastPs[1], PositionTolerance)
&& Chaos::FRotation3::IsNearlyEqual(Qs[0], LastQs[0], 0.5f * AngleTolerance)
&& Chaos::FRotation3::IsNearlyEqual(Qs[1], LastQs[1], 0.5f * AngleTolerance);
bIsActive = !bIsSolved;
}
LastPs[0] = Ps[0];
LastPs[1] = Ps[1];
LastQs[0] = Qs[0];
LastQs[1] = Qs[1];
return bIsActive;
}
void FMassTrafficSimpleTrailerConstraintSolver::ApplyPositionConstraints(const float Dt, const Chaos::FPBDJointSolverSettings& SolverSettings, const Chaos::FPBDJointSettings& JointSettings)
{
// @See FJointSolverGaussSeidel::ApplyPointPositionConstraintDD
const float LinearStiffness = /*Chaos::FPBDJointUtilities::GetLinearStiffness*/(SolverSettings.LinearStiffnessOverride >= 0.0f) ? SolverSettings.LinearStiffnessOverride : JointSettings.Stiffness;
const float Stiffness = SolverStiffness * LinearStiffness;
const FVector CX = Xs[1] - Xs[0];
if (CX.SizeSquared() > PositionTolerance * PositionTolerance)
{
// Calculate constraint correction
Chaos::FVec3 Delta0 = Xs[0] - Ps[0];
Chaos::FVec3 Delta1 = Xs[1] - Ps[1];
Chaos::FMatrix33 M0 = Chaos::Utilities::ComputeJointFactorMatrix(Delta0, InvIs[0], InvMs[0]);
Chaos::FMatrix33 M1 = Chaos::Utilities::ComputeJointFactorMatrix(Delta1, InvIs[1], InvMs[1]);
Chaos::FMatrix33 MI = (M0 + M1).Inverse();
const FVector DX = Stiffness * Chaos::Utilities::Multiply(MI, CX);
// Apply constraint correction
const FVector DP0 = InvMs[0] * DX;
const FVector DP1 = -InvMs[1] * DX;
const FVector DR0 = Chaos::Utilities::Multiply(InvIs[0], FVector::CrossProduct(Xs[0] - Ps[0], DX));
const FVector DR1 = Chaos::Utilities::Multiply(InvIs[1], FVector::CrossProduct(Xs[1] - Ps[1], -DX));
ApplyPositionDelta(DP0, DP1);
ApplyRotationDelta(DR0, DR1);
}
}
void FMassTrafficSimpleTrailerConstraintSolver::ApplyRotationConstraints(const float Dt, const Chaos::FPBDJointSolverSettings& SolverSettings, const Chaos::FPBDJointSettings& JointSettings)
{
// We only support a very specific constraint type useful for trailers.
check(JointSettings.AngularMotionTypes[(int32)Chaos::EJointAngularConstraintIndex::Twist] == Chaos::EJointMotionType::Locked);
check(JointSettings.AngularMotionTypes[(int32)Chaos::EJointAngularConstraintIndex::Swing1] == Chaos::EJointMotionType::Limited);
check(JointSettings.AngularMotionTypes[(int32)Chaos::EJointAngularConstraintIndex::Swing2] == Chaos::EJointMotionType::Limited);
check(!JointSettings.bSoftSwingLimitsEnabled);
// @See FJointSolverGaussSeidel::ApplyRotationConstraints
{
// @see FJointSolverGaussSeidel::ApplyConeConstraint
{
FVector SwingAxisLocal;
float DSwingAngle = 0.0f;
const float Swing1Limit = FMath::Max(JointSettings.AngularLimits[(int32)Chaos::EJointAngularConstraintIndex::Swing1], 0.0f);
const float Swing2Limit = FMath::Max(JointSettings.AngularLimits[(int32)Chaos::EJointAngularConstraintIndex::Swing2], 0.0f);
GetEllipticalConeAxisErrorLocal(Rs[0], Rs[1], Swing2Limit, Swing1Limit, SwingAxisLocal, DSwingAngle);
const FVector SwingAxis = Rs[0] * SwingAxisLocal;
// Apply swing correction to each body
if (DSwingAngle > AngleTolerance)
{
float SwingStiffness = GetSwingStiffness(SolverSettings, JointSettings);
// For cone constraints, the lambda are all accumulated in Swing2
ApplyRotationConstraintDD(SwingStiffness, SwingAxis, DSwingAngle);
}
}
// Note: single-swing locks are already handled above so we only need to do something here if both are locked
// @see ApplyLockedRotationConstraints(Dt, SolverSettings, JointSettings, /*bLockedTwist*/true, /*bLockedSwing*/false);
{
FVector Axis0, Axis1, Axis2;
GetLockedRotationAxes(Rs[0], Rs[1], Axis0, Axis1, Axis2);
const FQuat R01 = Rs[0].Inverse() * Rs[1];
const float TwistStiffness = GetTwistStiffness(SolverSettings, JointSettings);
ApplyRotationConstraintDD(TwistStiffness, Axis0, R01.X);
}
}
}
void FMassTrafficSimpleTrailerConstraintSolver::ApplyRotationConstraintDD(const float JointStiffness,
const FVector& Axis, const float Angle)
{
// @see FJointSolverGaussSeidel::ApplyRotationConstraintDD
const float Stiffness = SolverStiffness * JointStiffness;
// Joint-space inverse mass
const FVector IA0 = Chaos::Utilities::Multiply(InvIs[0], Axis);
const FVector IA1 = Chaos::Utilities::Multiply(InvIs[1], Axis);
const float II0 = FVector::DotProduct(Axis, IA0);
const float II1 = FVector::DotProduct(Axis, IA1);
const float DR = Stiffness * Angle / (II0 + II1);
const FVector DR0 = IA0 * DR;
const FVector DR1 = IA1 * -DR;
ApplyRotationDelta(DR0, DR1);
}
float FMassTrafficSimpleTrailerConstraintSolver::CalculateIterationStiffness(int32 It, int32 NumIts,
const Chaos::FPBDJointSolverSettings& Settings)
{
// @see FPBDJointConstraints::CalculateIterationStiffness
// Linearly interpolate betwwen MinStiffness and MaxStiffness over the first few iterations,
// then clamp at MaxStiffness for the final NumIterationsAtMaxStiffness
float IterationStiffness = Settings.MaxSolverStiffness;
if (NumIts > Settings.NumIterationsAtMaxSolverStiffness)
{
const float Interpolant = FMath::Clamp((float)It / (float)(NumIts - Settings.NumIterationsAtMaxSolverStiffness), 0.0f, 1.0f);
IterationStiffness = FMath::Lerp(Settings.MinSolverStiffness, Settings.MaxSolverStiffness, Interpolant);
}
return FMath::Clamp(IterationStiffness, 0.0f, 1.0f);
}
void FMassTrafficSimpleTrailerConstraintSolver::ApplyPositionDelta(const FVector& DP0, const FVector& DP1)
{
// @See FJointSolverGaussSeidel::ApplyPositionDelta
Ps[0] += DP0;
Ps[1] += DP1;
Xs[0] += DP0;
Xs[1] += DP1;
}
void FMassTrafficSimpleTrailerConstraintSolver::ApplyRotationDelta(const FVector& DR0, const FVector& DR1)
{
// @See FJointSolverGaussSeidel::ApplyRotationDelta
const FQuat DQ0 = (Chaos::FRotation3::FromElements(DR0, 0) * Qs[0]) * 0.5f;
Qs[0] = (Qs[0] + DQ0).GetNormalized();
const FQuat DQ1 = (Chaos::FRotation3::FromElements(DR1, 0) * Qs[1]) * 0.5f;
Qs[1] = (Qs[1] + DQ1).GetNormalized();
Qs[1].EnforceShortestArcWith(Qs[0]);
UpdateDerivedState();
}
void FMassTrafficSimpleTrailerConstraintSolver::GetLockedRotationAxes(const FQuat& R0, const FQuat& R1, FVector& Axis0,
FVector& Axis1, FVector& Axis2)
{
const float W0 = R0.W;
const float W1 = R1.W;
const FVector V0 = FVector(R0.X, R0.Y, R0.Z);
const FVector V1 = FVector(R1.X, R1.Y, R1.Z);
const FVector C = V1 * W0 + V0 * W1;
const float D0 = W0 * W1;
const float D1 = FVector::DotProduct(V0, V1);
const float D = D0 - D1;
Axis0 = 0.5f * (V0 * V1.X + V1 * V0.X + FVector(D, C.Z, -C.Y));
Axis1 = 0.5f * (V0 * V1.Y + V1 * V0.Y + FVector(-C.Z, D, C.X));
Axis2 = 0.5f * (V0 * V1.Z + V1 * V0.Z + FVector(C.Y, -C.X, D));
// Handle degenerate case of 180 deg swing
if (FMath::Abs(D0 + D1) < SMALL_NUMBER)
{
const float Epsilon = SMALL_NUMBER;
Axis0.X += Epsilon;
Axis1.Y += Epsilon;
Axis2.Z += Epsilon;
}
}
void FMassTrafficSimpleTrailerConstraintSolver::GetEllipticalConeAxisErrorLocal(
const FQuat& R0, const FQuat& R1,
const float SwingLimitY, const float SwingLimitZ, FVector& AxisLocal, float& Error
)
{
if (FMath::IsNearlyEqual(SwingLimitY, SwingLimitZ, 1.e-3f))
{
GetCircularConeAxisErrorLocal(R0, R1, SwingLimitY, AxisLocal, Error);
return;
}
AxisLocal = Chaos::FJointConstants::Swing1Axis();
Error = 0.;
FQuat R01Twist, R01Swing;
DecomposeSwingTwistLocal(R0, R1, R01Swing, R01Twist);
const FVector2D SwingAngles = FVector2D(/*GetSwingAngleY*/ 4.0f * FMath::Atan2(R01Swing.Y, 1.0f + R01Swing.W), /*GetSwingAngleZ*/4.0f * FMath::Atan2(R01Swing.Z, 1.0f + R01Swing.W));
const FVector2D SwingLimits = FVector2D(SwingLimitY, SwingLimitZ);
// Transform onto a circle to see if we are within the ellipse
const FVector2D CircleMappedAngles = SwingAngles / SwingLimits;
if (CircleMappedAngles.SizeSquared() > 1.0f)
{
// Map the swing to a position on the elliptical limits
const FVector2D ClampedSwingAngles = NearPointOnEllipse(SwingAngles, SwingLimits);
// Get the ellipse normal
const FVector2D ClampedNormal = ClampedSwingAngles / (SwingLimits * SwingLimits);
// Calculate the axis and error
const FVector TwistAxis = R01Swing.GetAxisX();
const FVector SwingRotAxis = FVector(0.0f, FMath::Tan(ClampedSwingAngles.X / 4.0f), FMath::Tan(ClampedSwingAngles.Y / 4.0f));
const FVector EllipseNormal = FVector(0.0f, ClampedNormal.X, ClampedNormal.Y);
GetEllipticalAxisError(SwingRotAxis, EllipseNormal, TwistAxis, AxisLocal, Error);
}
}
void FMassTrafficSimpleTrailerConstraintSolver::GetCircularConeAxisErrorLocal(
const FQuat& R0, const FQuat& R1,
const float SwingLimit, FVector& AxisLocal, float& Error
)
{
// @see FPBDJointUtilities::GetCircularConeAxisErrorLocal
FQuat R01Twist, R01Swing;
DecomposeSwingTwistLocal(R0, R1, R01Swing, R01Twist);
// @see Chaos::TRotation::ToAxisAndAngleSafe
float Angle = R01Swing.GetAngle();
// @see Chaos::TRotation::GetRotationAxisSafe(TVector<FReal, 3>& OutAxis, const TVector<FReal, 3>& DefaultAxis, FReal EpsilionSq = 1e-6f) const
{
// Tolerance must be much larger than error in normalized vector (usually ~1e-4) for the
// axis calculation to succeed for small angles. For small angles, W ~= 1, and
// X, Y, Z ~= 0. If the values of X, Y, Z are around 1e-4 we are just normalizing error.
const float LenSq = R01Swing.X * R01Swing.X + R01Swing.Y * R01Swing.Y + R01Swing.Z * R01Swing.Z;
if (LenSq > /*EpsilionSq*/1.e-6f)
{
float InvLen = FMath::InvSqrt(LenSq);
AxisLocal = FVector(R01Swing.X * InvLen, R01Swing.Y * InvLen, R01Swing.Z * InvLen);
}
else
{
AxisLocal = Chaos::FJointConstants::Swing1Axis();
}
}
Error = 0.0f;
if (Angle > SwingLimit)
{
Error = Angle - SwingLimit;
}
else if (Angle < -SwingLimit)
{
Error = Angle + SwingLimit;
}
}
FVector2D FMassTrafficSimpleTrailerConstraintSolver::NearPointOnEllipse(
const FVector2D& P, const FVector2D& R,
const int MaxIts, const float Tolerance
)
{
// Map point into first quadrant
FVector2D PAbs = P.GetAbs();
// Check for point on minor axis
const float Epsilon = 1.e-6f;
if (R.X >= R.Y)
{
if (PAbs.Y < Epsilon)
{
return FVector2D((P.X > 0.0f) ? R.X : -R.X, 0.0f);
}
}
else
{
if (PAbs.X < Epsilon)
{
return FVector2D(0.0f, (P.Y > 0.0f)? R.Y : -R.Y);
}
}
// Iterate to find nearest point
FVector2D R2 = R * R;
FVector2D RP = R * PAbs;
float T = FMath::Max(RP.X - R2.X, RP.Y - R2.Y);
FVector2D D;
for (int32 It = 0; It < MaxIts; ++It)
{
D = FVector2D(1.0f / (T + R2.X), 1 / (T + R2.Y));
FVector2D RPD = RP * D;
FVector2D FV = RPD * RPD;
float F = FV.X + FV.Y - 1.0f;
if (F < Tolerance)
{
return (R2 * P) * D;
}
float DF = -2.0f * FVector2D::DotProduct(FV, D);
T = T - F / DF;
}
// Too many iterations - return current value clamped
FVector2D S = (R2 * P) * D;
FVector2D SN = S / R;
return S / SN.Size();
}
bool FMassTrafficSimpleTrailerConstraintSolver::GetEllipticalAxisError(
const FVector& SwingAxisRot,
const FVector& EllipseNormal, const FVector& TwistAxis, FVector& AxisLocal, float& Error
)
{
const float R2 = SwingAxisRot.SizeSquared();
const float A = 1.0f - R2;
const float B = 1.0f / (1.0f + R2);
const float B2 = B * B;
const float V1 = 2.0f * A * B2;
const FVector V2 = FVector(A, 2.0f * SwingAxisRot.Z, -2.0f * SwingAxisRot.Y);
const float RD = FVector::DotProduct(SwingAxisRot, EllipseNormal);
const float DV1 = -4.0f * RD * (3.0f - R2) * B2 * B;
const FVector DV2 = FVector(-2.0f * RD, 2.0f * EllipseNormal.Z, -2.0f * EllipseNormal.Y);
const FVector Line = V1 * V2 - FVector(1, 0, 0);
FVector Normal = V1 * DV2 + DV1 * V2;
if (Normal.Normalize())
{
AxisLocal = FVector::CrossProduct(Line, Normal);
Error = -FVector::DotProduct(FVector::CrossProduct(Line, AxisLocal), TwistAxis);
return true;
}
return false;
} | 1 | 0.951407 | 1 | 0.951407 | game-dev | MEDIA | 0.965343 | game-dev | 0.981727 | 1 | 0.981727 |
holycake/mhsj | 1,115 | d/shaolin/yangxing.c | // TIE@FY3 ALL RIGHTS RESERVED
inherit ROOM;
void create()
{
set("short", "养性堂");
set("long", @LONG
修练内力的绝佳场所,少林心法全源自禅功,所以静心养性,清静
无为是学成少林内功的必要条件,在这里修习内功,锤炼内力都是事半
功倍的(dazuo),可惜地方很小。远眺窗外,依稀可以看见西北
方的邸园精舍。
LONG
);
set("exits", ([
"southeast" : __DIR__"cj",
"northeast" : __DIR__"banruo",
]));
set("no_magic", 1);
set("coor/x",-220);
set("coor/y",370);
set("coor/z",70);
setup();
}
void init()
{
add_action("do_jump", "修习");
add_action("do_jump", "dazuo");
}
int do_jump()
{
object me;
int wait;
me = this_player();
wait = random( 40 - (int)(me->query("con"))) * 2;
if ( wait <= 20) wait = 21;
message_vision("$N"噗嗵"一声盘腿坐在地下..\n",me);
tell_object(me,"你感到内力在体内回荡...\n");
remove_call_out("curehimup");
call_out("curehimup", wait, me);
return 1;
}
void curehimup(object me)
{
int force;
force=(int)me->query("max_force");
if( me && environment(me) == this_object())
{
message_vision("$N的内力全恢复了!!\n", me);
me->set("force", force);
}
return;
}
| 1 | 0.756695 | 1 | 0.756695 | game-dev | MEDIA | 0.967491 | game-dev | 0.643875 | 1 | 0.643875 |
LostArtefacts/TR2X | 7,830 | src/game/overlay.c | #include "game/overlay.h"
#include "game/music.h"
#include "game/output.h"
#include "game/text.h"
#include "global/const.h"
#include "global/funcs.h"
#include "global/vars.h"
#include <libtrx/utils.h>
#include <stdio.h>
#define FLASH_FRAMES 5
#define AMMO_X (-10)
#define AMMO_Y 35
#define MODE_INFO_X (-16)
#define MODE_INFO_Y (-16)
static int32_t m_OldGameTimer = 0;
static int32_t m_OldHitPoints = -1;
static bool m_FlashState = false;
static int32_t m_FlashCounter = 0;
bool __cdecl Overlay_FlashCounter(void)
{
if (m_FlashCounter > 0) {
m_FlashCounter--;
return m_FlashState;
} else {
m_FlashCounter = FLASH_FRAMES;
m_FlashState = !m_FlashState;
}
return m_FlashState;
}
void __cdecl Overlay_DrawAssaultTimer(void)
{
if (g_CurrentLevel != 0 || !g_IsAssaultTimerDisplay) {
return;
}
static char buffer[8];
const int32_t total_sec = g_SaveGame.statistics.timer / FRAMES_PER_SECOND;
const int32_t frame = g_SaveGame.statistics.timer % FRAMES_PER_SECOND;
sprintf(
buffer, "%d:%02d.%d", total_sec / 60, total_sec % 60,
frame * 10 / FRAMES_PER_SECOND);
const int32_t scale_h = PHD_ONE;
const int32_t scale_v = PHD_ONE;
const int32_t dot_offset = -6;
const int32_t dot_width = 14;
const int32_t colon_offset = -6;
const int32_t colon_width = 14;
const int32_t digit_offset = 0;
const int32_t digit_width = 20;
const int32_t y = 36;
int32_t x = (g_PhdWinMaxX / 2) - 50;
for (char *c = buffer; *c != '\0'; c++) {
if (*c == ':') {
x += colon_offset;
Output_DrawScreenSprite2D(
x, y, 0, scale_h, scale_v,
g_Objects[O_ASSAULT_DIGITS].mesh_idx + 10, 0x1000, 0);
x += colon_width;
} else if (*c == '.') {
x += dot_offset;
Output_DrawScreenSprite2D(
x, y, 0, scale_h, scale_v,
g_Objects[O_ASSAULT_DIGITS].mesh_idx + 11, 0x1000, 0);
x += dot_width;
} else {
x += digit_offset;
Output_DrawScreenSprite2D(
x, y, 0, scale_h, scale_v,
*c + g_Objects[O_ASSAULT_DIGITS].mesh_idx - '0', 0x1000, 0);
x += digit_width;
}
}
}
void __cdecl Overlay_DrawGameInfo(const bool pickup_state)
{
Overlay_DrawAmmoInfo();
Overlay_DrawModeInfo();
if (g_OverlayStatus > 0) {
bool flash = Overlay_FlashCounter();
Overlay_DrawHealthBar(flash);
Overlay_DrawAirBar(flash);
Overlay_DrawPickups(pickup_state);
Overlay_DrawAssaultTimer();
}
Text_Draw();
}
void __cdecl Overlay_DrawHealthBar(const bool flash_state)
{
int32_t hit_points = g_LaraItem->hit_points;
CLAMP(hit_points, 0, LARA_MAX_HITPOINTS);
if (m_OldHitPoints != hit_points) {
m_OldHitPoints = hit_points;
g_HealthBarTimer = 40;
}
CLAMPL(g_HealthBarTimer, 0);
const int32_t percent = hit_points * 100 / LARA_MAX_HITPOINTS;
if (hit_points <= LARA_MAX_HITPOINTS / 4) {
S_DrawHealthBar(flash_state ? percent : 0);
} else if (g_HealthBarTimer > 0 || g_Lara.gun_status == LGS_READY) {
S_DrawHealthBar(percent);
}
}
void __cdecl Overlay_DrawAirBar(const bool flash_state)
{
if (g_Lara.water_status != LWS_UNDERWATER
&& g_Lara.water_status != LWS_SURFACE) {
return;
}
int32_t air = g_Lara.air;
CLAMP(air, 0, LARA_MAX_AIR);
const int32_t percent = air * 100 / LARA_MAX_AIR;
if (air <= 450) {
S_DrawAirBar(flash_state ? percent : 0);
} else {
S_DrawAirBar(percent);
}
}
void Overlay_HideGameInfo(void)
{
Text_Remove(g_AmmoTextInfo);
g_AmmoTextInfo = NULL;
Text_Remove(g_DisplayModeTextInfo);
g_DisplayModeTextInfo = NULL;
}
void __cdecl Overlay_MakeAmmoString(char *const string)
{
for (char *c = string; *c != '\0'; c++) {
if (*c == ' ') {
continue;
}
if (*c - 'A' >= 0) {
// ammo sprites
*c += 0xC - 'A';
} else {
// digits
*c += 1 - '0';
}
}
}
void __cdecl Overlay_DrawAmmoInfo(void)
{
if (g_Lara.gun_status != LGS_READY || g_OverlayStatus <= 0
|| g_SaveGame.bonus_flag) {
if (g_AmmoTextInfo != NULL) {
Text_Remove(g_AmmoTextInfo);
g_AmmoTextInfo = NULL;
}
return;
}
char buffer[80] = "";
switch (g_Lara.gun_type) {
case LGT_MAGNUMS:
sprintf(buffer, "%5d", g_Lara.magnum_ammo.ammo);
break;
case LGT_UZIS:
sprintf(buffer, "%5d", g_Lara.uzi_ammo.ammo);
break;
case LGT_SHOTGUN:
sprintf(buffer, "%5d", g_Lara.shotgun_ammo.ammo / 6);
break;
case LGT_M16:
sprintf(buffer, "%5d", g_Lara.m16_ammo.ammo);
break;
case LGT_GRENADE:
sprintf(buffer, "%5d", g_Lara.grenade_ammo.ammo);
break;
case LGT_HARPOON:
sprintf(buffer, "%5d", g_Lara.harpoon_ammo.ammo);
break;
default:
return;
}
Overlay_MakeAmmoString(buffer);
if (g_AmmoTextInfo != NULL) {
Text_ChangeText(g_AmmoTextInfo, buffer);
} else {
g_AmmoTextInfo = Text_Create(AMMO_X, AMMO_Y, 0, buffer);
Text_AlignRight(g_AmmoTextInfo, true);
}
}
void __cdecl Overlay_InitialisePickUpDisplay(void)
{
for (int32_t i = 0; i < MAX_PICKUPS; i++) {
g_Pickups[i].timer = 0;
}
}
void __cdecl Overlay_DrawPickups(const bool timed)
{
const int32_t time = g_SaveGame.statistics.timer - m_OldGameTimer;
m_OldGameTimer = g_SaveGame.statistics.timer;
if (time <= 0 || time >= 60) {
return;
}
static const int32_t max_columns = 4;
const int32_t cell_h = g_PhdWinWidth / 10;
const int32_t cell_v = cell_h * 2 / 3;
int32_t x = g_PhdWinWidth - cell_h;
int32_t y = g_PhdWinHeight - cell_h;
int32_t column = 0;
for (int32_t i = 0; i < 12; i++) {
PICKUP_INFO *const pickup = &g_Pickups[i];
if (timed) {
pickup->timer -= time;
}
if (pickup->timer <= 0) {
pickup->timer = 0;
} else {
if (column == max_columns) {
y -= cell_v;
x = g_PhdWinWidth - cell_h;
}
column++;
Output_DrawPickup(x, y, 12 * WALL_L, pickup->sprite, 0x1000);
}
x -= cell_h;
}
}
void __cdecl Overlay_AddDisplayPickup(const int16_t object_id)
{
if (object_id == O_SECRET_1 || object_id == O_SECRET_2
|| object_id == O_SECRET_3) {
Music_Play(g_GameFlow.secret_track, false);
}
for (int32_t i = 0; i < MAX_PICKUPS; i++) {
PICKUP_INFO *const pickup = &g_Pickups[i];
if (pickup->timer <= 0) {
pickup->timer = 2.5 * FRAMES_PER_SECOND;
pickup->sprite = g_Objects[object_id].mesh_idx;
return;
}
}
}
void __cdecl Overlay_DisplayModeInfo(const char *const string)
{
if (string == NULL) {
Text_Remove(g_DisplayModeTextInfo);
g_DisplayModeTextInfo = NULL;
return;
}
if (g_DisplayModeTextInfo != NULL) {
Text_ChangeText(g_DisplayModeTextInfo, string);
} else {
g_DisplayModeTextInfo =
Text_Create(MODE_INFO_X, MODE_INFO_Y, 0, string);
Text_AlignRight(g_DisplayModeTextInfo, 1);
Text_AlignBottom(g_DisplayModeTextInfo, 1);
}
g_DisplayModeInfoTimer = 2.5 * FRAMES_PER_SECOND;
}
void __cdecl Overlay_DrawModeInfo(void)
{
if (g_DisplayModeTextInfo == NULL) {
return;
}
g_DisplayModeInfoTimer--;
if (g_DisplayModeInfoTimer == 0) {
Text_Remove(g_DisplayModeTextInfo);
g_DisplayModeTextInfo = NULL;
}
}
| 1 | 0.856749 | 1 | 0.856749 | game-dev | MEDIA | 0.726881 | game-dev | 0.633798 | 1 | 0.633798 |
mcneel/rhino-developer-samples | 2,018 | cpp/SampleRdkRenderer/SampleRdkRendererApp.cpp |
/** This sample demonstrates how to create an asynchronous RDK Renderer plug-in.
Asynchronous rendering runs in the background and the user can continue using Rhino
while it is running. Multiple renderings can be run at the same time if desired.
*/
#include "stdafx.h"
#include "SampleRdkRendererApp.h"
// Note!
//
// A Rhino plug-in is an MFC DLL.
//
// If this DLL is dynamically linked against the MFC
// DLLs, any functions exported from this DLL which
// call into MFC must have the AFX_MANAGE_STATE macro
// added at the very beginning of the function.
//
// For example:
//
// extern "C" BOOL PASCAL EXPORT ExportedFunction()
// {
// AFX_MANAGE_STATE(AfxGetStaticModuleState());
// // normal function body here
// }
//
// It is very important that this macro appear in each
// function, prior to any calls into MFC. This means that
// it must appear as the first statement within the
// function, even before any object variable declarations
// as their constructors may generate calls into the MFC
// DLL.
//
// Please see MFC Technical Notes 33 and 58 for additional
// details.
//
// CSampleRdkRendererApp
BEGIN_MESSAGE_MAP(CSampleRdkRendererApp, CWinApp)
END_MESSAGE_MAP()
// The one and only CSampleRdkRendererApp object
CSampleRdkRendererApp theApp;
// CSampleRdkRendererApp initialization
BOOL CSampleRdkRendererApp::InitInstance()
{
// CRITICAL: DO NOT CALL RHINO SDK FUNCTIONS HERE!
// Only standard MFC DLL instance initialization belongs here.
// All other significant initialization should take place in
// CSampleRdkRendererPlugIn::OnLoadPlugIn().
CWinApp::InitInstance();
return TRUE;
}
int CSampleRdkRendererApp::ExitInstance()
{
// CRITICAL: DO NOT CALL RHINO SDK FUNCTIONS HERE!
// Only standard MFC DLL instance clean up belongs here.
// All other significant cleanup should take place in either
// CSampleRdkRendererPlugIn::OnSaveAllSettings() or
// CSampleRdkRendererPlugIn::OnUnloadPlugIn().
return CWinApp::ExitInstance();
}
| 1 | 0.927937 | 1 | 0.927937 | game-dev | MEDIA | 0.122102 | game-dev | 0.542698 | 1 | 0.542698 |
Ivorforce/RecurrentComplex | 1,798 | src/main/java/ivorius/reccomplex/world/storage/loot/LootEntryItemCollection.java | /*
* Copyright (c) 2014, Lukas Tenbrink.
* * http://ivorius.net
*/
package ivorius.reccomplex.world.storage.loot;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import ivorius.reccomplex.json.JsonUtils;
import net.minecraft.item.ItemStack;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.LootEntry;
import net.minecraft.world.storage.loot.conditions.LootCondition;
import java.util.Collection;
import java.util.Random;
/**
* Created by lukas on 04.10.16.
*/
public class LootEntryItemCollection extends LootEntry
{
public String itemCollectionID;
public LootEntryItemCollection(int weightIn, int qualityIn, LootCondition[] conditionsIn, String entryName, String itemCollectionID)
{
super(weightIn, qualityIn, conditionsIn, entryName);
this.itemCollectionID = itemCollectionID;
}
public static LootEntryItemCollection deserialize(int weightIn, int qualityIn, LootCondition[] conditionsIn, String entryName, JsonObject json, JsonDeserializationContext context)
{
return new LootEntryItemCollection(weightIn, qualityIn, conditionsIn, entryName,
JsonUtils.getString(json, "itemCollectionID", ""));
}
@Override
public void addLoot(Collection<ItemStack> stacks, Random rand, LootContext context)
{
GenericLootTable.Component component = GenericItemCollectionRegistry.INSTANCE.get(itemCollectionID);
if (component != null)
stacks.add(component.getRandomItemStack(rand));
}
@Override
protected void serialize(JsonObject json, JsonSerializationContext context)
{
json.addProperty("itemCollectionID", itemCollectionID);
}
}
| 1 | 0.738966 | 1 | 0.738966 | game-dev | MEDIA | 0.97329 | game-dev | 0.883376 | 1 | 0.883376 |
oxc-project/oxc | 1,836 | crates/oxc_transformer/src/plugins/mod.rs | mod options;
mod styled_components;
pub use options::PluginsOptions;
use oxc_ast::ast::*;
use oxc_traverse::Traverse;
pub use styled_components::StyledComponentsOptions;
use crate::{
context::{TransformCtx, TraverseCtx},
plugins::styled_components::StyledComponents,
state::TransformState,
};
pub struct Plugins<'a, 'ctx> {
styled_components: Option<StyledComponents<'a, 'ctx>>,
}
impl<'a, 'ctx> Plugins<'a, 'ctx> {
pub fn new(options: PluginsOptions, ctx: &'ctx TransformCtx<'a>) -> Self {
Self {
styled_components: options
.styled_components
.map(|options| StyledComponents::new(options, ctx)),
}
}
}
impl<'a> Traverse<'a, TransformState<'a>> for Plugins<'a, '_> {
fn enter_program(&mut self, node: &mut Program<'a>, ctx: &mut TraverseCtx<'a>) {
if let Some(styled_components) = &mut self.styled_components {
styled_components.enter_program(node, ctx);
}
}
fn enter_variable_declarator(
&mut self,
node: &mut VariableDeclarator<'a>,
ctx: &mut TraverseCtx<'a>,
) {
if let Some(styled_components) = &mut self.styled_components {
styled_components.enter_variable_declarator(node, ctx);
}
}
fn enter_expression(
&mut self,
node: &mut Expression<'a>,
ctx: &mut oxc_traverse::TraverseCtx<'a, TransformState<'a>>,
) {
if let Some(styled_components) = &mut self.styled_components {
styled_components.enter_expression(node, ctx);
}
}
fn enter_call_expression(&mut self, node: &mut CallExpression<'a>, ctx: &mut TraverseCtx<'a>) {
if let Some(styled_components) = &mut self.styled_components {
styled_components.enter_call_expression(node, ctx);
}
}
}
| 1 | 0.81426 | 1 | 0.81426 | game-dev | MEDIA | 0.29401 | game-dev | 0.753205 | 1 | 0.753205 |
scemino/z_impact | 4,446 | samples/zdrop/scenes/game.zig | const std = @import("std");
const zi = @import("zimpact");
const game = @import("../game.zig");
const g = @import("../global.zig");
const p = @import("../entities/player.zig");
const Entity = zi.Entity;
var map: zi.Map = undefined;
var game_over: bool = false;
var player: *Entity = undefined;
var sound_game_over: *zi.sound.SoundSource = undefined;
var backdrop: *zi.Image = undefined;
fn generate_row(row: usize) void {
// Randomly generate a row of block for the map. This is a naive approach,
// that sometimes leaves the player hanging with no block to jump to. It's
// random after all.
for (0..8) |col| {
const f = zi.utils.randFloat(0, 1);
map.data[row * @as(usize, @intCast(map.size.x)) + col] = if (f > 0.93) 1 else 0;
}
}
fn place_coin(row: i32) void {
// Randomly find a free spot for the coin, max 12 tries
for (0..12 * 2) |_| {
const x = zi.utils.randInt(0, 7);
if (map.tileAt(zi.vec2i(x, row - 1)) == 1 and map.tileAt(zi.vec2i(x, row - 2)) == 0) {
const pos = zi.vec2(
@floatFromInt(x * map.tile_size + 1),
@floatFromInt((row - 2) * map.tile_size + 2),
);
_ = zi.entity.entitySpawn(.coin, pos);
return;
}
}
}
fn init() void {
zi.utils.randSeed(@intFromFloat(zi.engine.time_real * 10000000.0));
zi.engine.gravity = 240;
g.score = 0;
g.speed = 1;
game_over = false;
backdrop = zi.image("assets/backdrop.qoi");
sound_game_over = zi.sound.source("assets/game_over.qoa");
map = zi.Map.initWithData(8, zi.vec2i(8, 18), null);
map.tileset = zi.image("assets/tiles.qoi");
map.data[@intCast(4 * map.size.x + 3)] = 1;
map.data[@intCast(4 * map.size.x + 4)] = 1;
for (8..@intCast(map.size.y)) |i| {
generate_row(i);
}
// The map is used as CollisionMap AND BackgroundMap
zi.Engine.setCollisionMap(&map);
zi.Engine.addBackgroundMap(&map);
player = zi.entity.entitySpawn(.player, zi.vec2(@as(f32, @floatFromInt(zi.render.renderSize().x)) / 2.0 - 2.0, 16)).?;
}
fn update() void {
if (zi.input.pressed(p.A_START))
zi.Engine.setScene(&scene_game);
if (game_over)
return;
g.speed += @as(f32, @floatCast(zi.engine.tick)) * (10.0 / g.speed);
g.score += @as(f32, @floatCast(zi.engine.tick)) * g.speed;
zi.engine.viewport.y += @as(f32, @floatCast(zi.engine.tick)) * g.speed;
// Do we need a new row?
if (zi.engine.viewport.y > 40) {
// Move screen and entities one tile up
zi.engine.viewport.y -= 8;
player.pos.y -= 8;
const coins = zi.entity.entitiesByType(.coin);
for (coins.entities) |coin| {
const entity = zi.entity.entityByRef(coin);
entity.?.pos.y -= 8;
}
// Move all tiles up one row
std.mem.copyForwards(u16, map.data[0..@intCast((map.size.y - 1) * map.size.x)], map.data[@intCast(map.size.x)..@intCast(map.size.y * map.size.x)]);
// Generate new last row
generate_row(@intCast(map.size.y - 1));
if (zi.utils.randInt(0, 1) == 1) {
place_coin(@intCast(map.size.y - 1));
}
}
zi.Engine.sceneBaseUpdate();
// Check for gameover
const pp = player.pos.y - zi.engine.viewport.y;
if (pp > @as(f32, @floatFromInt(zi.render.renderSize().y)) + 8.0 or pp < -32) {
game_over = true;
zi.sound.play(sound_game_over);
}
}
fn draw() void {
backdrop.drawEx(zi.vec2(0, 0), zi.fromVec2i(backdrop.size), zi.vec2(0, 0), zi.fromVec2i(zi.render.renderSize()), zi.white());
if (game_over) {
g.font.draw(zi.vec2(@as(f32, @floatFromInt(zi.render.renderSize().x)) / 2.0, 32.0), "Game Over!", .FONT_ALIGN_CENTER);
g.font.draw(zi.vec2(@as(f32, @floatFromInt(zi.render.renderSize().x)) / 2.0, 48.0), "Press Enter", .FONT_ALIGN_CENTER);
g.font.draw(zi.vec2(@as(f32, @floatFromInt(zi.render.renderSize().x)) / 2.0, 56.0), "to Restart", .FONT_ALIGN_CENTER);
} else {
zi.Engine.sceneBaseDraw();
}
var buf: [64]u8 = undefined;
const text = std.fmt.bufPrint(&buf, "{d}", .{@as(i32, @intFromFloat(g.score))}) catch @panic("failed to format score");
g.font.draw(zi.vec2(@as(f32, @floatFromInt(zi.render.renderSize().x)) - 2.0, 2.0), text, .FONT_ALIGN_RIGHT);
}
pub var scene_game: zi.Scene = .{
.init = init,
.update = update,
.draw = draw,
};
| 1 | 0.680061 | 1 | 0.680061 | game-dev | MEDIA | 0.898435 | game-dev | 0.925208 | 1 | 0.925208 |
Arakne/Araknemu | 2,512 | src/main/java/fr/quatrevieux/araknemu/game/spell/boost/spell/BoostedSpellConstraints.java | /*
* This file is part of Araknemu.
*
* Araknemu is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Araknemu is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Araknemu. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright (c) 2017-2020 Vincent Quatrevieux
*/
package fr.quatrevieux.araknemu.game.spell.boost.spell;
import fr.arakne.utils.value.Interval;
import fr.quatrevieux.araknemu.game.spell.SpellConstraints;
import fr.quatrevieux.araknemu.game.spell.boost.SpellModifiers;
/**
* Spell constraints with modifiers
*/
public final class BoostedSpellConstraints implements SpellConstraints {
private final SpellConstraints constraints;
private final SpellModifiers modifiers;
public BoostedSpellConstraints(SpellConstraints constraints, SpellModifiers modifiers) {
this.constraints = constraints;
this.modifiers = modifiers;
}
@Override
public Interval range() {
return constraints.range().modify(modifiers.range());
}
@Override
public boolean lineLaunch() {
return constraints.lineLaunch() && !modifiers.launchOutline();
}
@Override
public boolean lineOfSight() {
return constraints.lineOfSight() && !modifiers.lineOfSight();
}
@Override
public boolean freeCell() {
return constraints.freeCell();
}
@Override
public int launchPerTurn() {
return constraints.launchPerTurn() + modifiers.launchPerTurn();
}
@Override
public int launchPerTarget() {
return constraints.launchPerTarget() + modifiers.launchPerTarget();
}
@Override
public int launchDelay() {
final int base = modifiers.hasFixedDelay()
? modifiers.fixedDelay()
: constraints.launchDelay()
;
return base - modifiers.delay();
}
@Override
public int[] requiredStates() {
return constraints.requiredStates();
}
@Override
public int[] forbiddenStates() {
return constraints.forbiddenStates();
}
}
| 1 | 0.904982 | 1 | 0.904982 | game-dev | MEDIA | 0.567981 | game-dev | 0.773756 | 1 | 0.773756 |
pablushaa/AllahClientRecode | 1,947 | optifine/MatchBlock.java | package optifine;
import net.minecraft.block.state.BlockStateBase;
public class MatchBlock
{
private int blockId = -1;
private int[] metadatas = null;
public MatchBlock(int p_i63_1_)
{
this.blockId = p_i63_1_;
}
public MatchBlock(int p_i64_1_, int p_i64_2_)
{
this.blockId = p_i64_1_;
if (p_i64_2_ >= 0 && p_i64_2_ <= 15)
{
this.metadatas = new int[] {p_i64_2_};
}
}
public MatchBlock(int p_i65_1_, int[] p_i65_2_)
{
this.blockId = p_i65_1_;
this.metadatas = p_i65_2_;
}
public int getBlockId()
{
return this.blockId;
}
public int[] getMetadatas()
{
return this.metadatas;
}
public boolean matches(BlockStateBase p_matches_1_)
{
if (p_matches_1_.getBlockId() != this.blockId)
{
return false;
}
else
{
return Matches.metadata(p_matches_1_.getMetadata(), this.metadatas);
}
}
public boolean matches(int p_matches_1_, int p_matches_2_)
{
if (p_matches_1_ != this.blockId)
{
return false;
}
else
{
return Matches.metadata(p_matches_2_, this.metadatas);
}
}
public void addMetadata(int p_addMetadata_1_)
{
if (this.metadatas != null)
{
if (p_addMetadata_1_ >= 0 && p_addMetadata_1_ <= 15)
{
for (int i = 0; i < this.metadatas.length; ++i)
{
if (this.metadatas[i] == p_addMetadata_1_)
{
return;
}
}
this.metadatas = Config.addIntToArray(this.metadatas, p_addMetadata_1_);
}
}
}
public String toString()
{
return "" + this.blockId + ":" + Config.arrayToString(this.metadatas);
}
}
| 1 | 0.61745 | 1 | 0.61745 | game-dev | MEDIA | 0.506541 | game-dev | 0.548767 | 1 | 0.548767 |
holycake/mhsj | 2,210 | d/city/npc/yang.c | inherit F_VENDOR_SALE;
#include <ansi.h>
string heal_me(object me);
void create()
{
reload("yangzhongshun");
set_name("楊中順", ({"yang zhongshun", "yang", "boss"}));
set("title", HIY"藥鋪掌櫃"NOR);
set("nickname", HIW"長安名醫"NOR);
set("gender", "男性");
set("age", 37);
set("long",
"杨老板是长安城里祖传的名医。虽然年轻,却早已名声在外。\n");
set("kee", 300);
set("max_kee", 300);
set("sen", 200);
set("max_sen", 200);
set("combat_exp", 10000);
set("attitude", "friendly");
set("env/wimpy", 50);
set("inquiry", ([
"治伤": (: heal_me :),
"疗伤": (: heal_me :),
"开药": (: heal_me :),
]) );
set("vendor_goods", ([
"3": "/d/obj/drug/fake-tao",
"2": "/d/obj/drug/hunyuandan",
"1": "/d/obj/drug/jinchuang",
]) );
set_skill("literate", 70);
set_skill("unarmed", 60);
set_skill("dodge", 60);
setup();
carry_object("/d/obj/cloth/choupao")->wear();
add_money("gold", 1);
}
string heal_me(object ob)
{
int ratio;
object me;
me = this_player();
ratio = (int)me->query("eff_kee") * 100 /
(int)me->query("max_kee");
if( ratio >= 100 )
return "这位" + RANK_D->query_respect(me) +
",您看起来气色很好啊,不像有受伤的样子。";
if( ratio >= 95 )
return
"哦....我看看....只是些皮肉小伤,您买包金创药回去敷敷就没事了。";
}
void init()
{
::init();
add_action("do_vendor_list", "list");
}
void accept_kill(object me)
{ object ob;
if(is_fighting()) return;
if( query("called") ) return;
command("help!");
ob=present("xunluo guanbing");
if( !ob) {
seteuid(getuid());
ob=new("/d/city/npc/xunluobing");
ob->move(environment());
}
message_vision("\n忽然从门外冲进来个巡逻官兵,对$N大喊一声“干什么?想杀人谋财么!\n\n",me);
ob->kill_ob(me);
ob->set_leader(me);
me->fight_ob(ob);
set("called", 1);
call_out("regenerate", 300);
}
int regenerate()
{
set("called", 0);
return 1;
}
| 1 | 0.817176 | 1 | 0.817176 | game-dev | MEDIA | 0.878849 | game-dev | 0.744054 | 1 | 0.744054 |
MATTYOneInc/AionEncomBase_Java8 | 3,684 | AL-Game/data/scripts/system/handlers/ai/instance/steelRake/TamerAnikikiAI2.java | /*
* This file is part of Encom.
*
* Encom is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Encom 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Encom. If not, see <http://www.gnu.org/licenses/>.
*/
package ai.instance.steelRake;
import ai.AggressiveNpcAI2;
import com.aionemu.gameserver.ai2.AI2Actions;
import com.aionemu.gameserver.ai2.AIName;
import com.aionemu.gameserver.ai2.manager.WalkManager;
import com.aionemu.gameserver.model.EmotionType;
import com.aionemu.gameserver.model.gameobjects.Creature;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_EMOTION;
import com.aionemu.gameserver.network.aion.serverpackets.SM_QUEST_ACTION;
import com.aionemu.gameserver.services.NpcShoutsService;
import com.aionemu.gameserver.skillengine.SkillEngine;
import com.aionemu.gameserver.utils.MathUtil;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.ThreadPoolManager;
import java.util.concurrent.atomic.AtomicBoolean;
/****/
/** Author (Encom)
/****/
@AIName("tamer_anikiki")
public class TamerAnikikiAI2 extends AggressiveNpcAI2
{
private AtomicBoolean isStartedWalkEvent = new AtomicBoolean(false);
@Override
public void think() {
}
@Override
protected void handleCreatureMoved(Creature creature) {
if (creature instanceof Player) {
final Player player = (Player) creature;
if (MathUtil.getDistance(getOwner(), player) <= 8) {
if (isStartedWalkEvent.compareAndSet(false, true)) {
getSpawnTemplate().setWalkerId("3001000001");
WalkManager.startWalking(this);
getOwner().setState(1);
PacketSendUtility.broadcastPacket(getOwner(), new SM_EMOTION(getOwner(), EmotionType.START_EMOTE2, 0, getObjectId()));
spawn(700553, 611f, 481f, 936f, (byte) 90);
spawn(700553, 657f, 482f, 936f, (byte) 60);
spawn(700553, 626f, 540f, 936f, (byte) 1);
spawn(700553, 645f, 534f, 936f, (byte) 75);
PacketSendUtility.sendPacket(player, new SM_QUEST_ACTION(0, 300));
NpcShoutsService.getInstance().sendMsg(getOwner(), 1400262, 3000);
}
}
}
}
@Override
protected void handleMoveArrived() {
int point = getOwner().getMoveController().getCurrentPoint();
super.handleMoveArrived();
if (getNpcId() == 215412) { //Tamer Anikiki.
if (point == 8) {
getOwner().setState(64);
PacketSendUtility.broadcastPacket(getOwner(), new SM_EMOTION(getOwner(), EmotionType.START_EMOTE2, 0, getObjectId()));
} if (point == 12) {
getSpawnTemplate().setWalkerId(null);
WalkManager.stopWalking(this);
AI2Actions.deleteOwner(this);
}
}
}
@Override
protected void handleSpawned() {
super.handleSpawned();
if (getNpcId() != 215412) { //Tamer Anikiki.
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
SkillEngine.getInstance().getSkill(getOwner(), 18189, 20, getOwner()).useNoAnimationSkill();
getLifeStats().setCurrentHp(getLifeStats().getMaxHp());
}
}, 5000);
}
}
@Override
public int modifyOwnerDamage(int damage) {
return 1;
}
@Override
public int modifyDamage(int damage) {
return 1;
}
} | 1 | 0.973819 | 1 | 0.973819 | game-dev | MEDIA | 0.956756 | game-dev | 0.981735 | 1 | 0.981735 |
EcsRx/ecsrx.roguelike2d | 3,561 | Assets/Plugins/Zenject/Source/Install/Contexts/SceneDecoratorContext.cs | #if !NOT_UNITY3D
using System;
using System.Collections.Generic;
using ModestTree;
using UnityEngine;
using UnityEngine.Serialization;
using Zenject.Internal;
namespace Zenject
{
public class SceneDecoratorContext : Context
{
[SerializeField]
List<MonoInstaller> _lateInstallers = new List<MonoInstaller>();
[SerializeField]
List<MonoInstaller> _lateInstallerPrefabs = new List<MonoInstaller>();
[SerializeField]
List<ScriptableObjectInstaller> _lateScriptableObjectInstallers = new List<ScriptableObjectInstaller>();
public IEnumerable<MonoInstaller> LateInstallers
{
get { return _lateInstallers; }
set
{
_lateInstallers.Clear();
_lateInstallers.AddRange(value);
}
}
public IEnumerable<MonoInstaller> LateInstallerPrefabs
{
get { return _lateInstallerPrefabs; }
set
{
_lateInstallerPrefabs.Clear();
_lateInstallerPrefabs.AddRange(value);
}
}
public IEnumerable<ScriptableObjectInstaller> LateScriptableObjectInstallers
{
get { return _lateScriptableObjectInstallers; }
set
{
_lateScriptableObjectInstallers.Clear();
_lateScriptableObjectInstallers.AddRange(value);
}
}
[FormerlySerializedAs("SceneName")]
[SerializeField]
string _decoratedContractName = null;
DiContainer _container;
readonly List<MonoBehaviour> _injectableMonoBehaviours = new List<MonoBehaviour>();
public string DecoratedContractName
{
get { return _decoratedContractName; }
}
public override DiContainer Container
{
get
{
Assert.IsNotNull(_container);
return _container;
}
}
public override IEnumerable<GameObject> GetRootGameObjects()
{
// This method should never be called because SceneDecoratorContext's are not bound
// to the container
throw Assert.CreateException();
}
public void Initialize(DiContainer container)
{
Assert.IsNull(_container);
Assert.That(_injectableMonoBehaviours.IsEmpty());
_container = container;
GetInjectableMonoBehaviours(_injectableMonoBehaviours);
foreach (var instance in _injectableMonoBehaviours)
{
container.QueueForInject(instance);
}
}
public void InstallDecoratorSceneBindings()
{
_container.Bind<SceneDecoratorContext>().FromInstance(this);
InstallSceneBindings(_injectableMonoBehaviours);
}
public void InstallDecoratorInstallers()
{
InstallInstallers();
}
protected override void GetInjectableMonoBehaviours(List<MonoBehaviour> monoBehaviours)
{
var scene = gameObject.scene;
ZenUtilInternal.AddStateMachineBehaviourAutoInjectersInScene(scene);
ZenUtilInternal.GetInjectableMonoBehavioursInScene(scene, monoBehaviours);
}
public void InstallLateDecoratorInstallers()
{
InstallInstallers(new List<InstallerBase>(), new List<Type>(), _lateScriptableObjectInstallers, _lateInstallers, _lateInstallerPrefabs);
}
}
}
#endif
| 1 | 0.870268 | 1 | 0.870268 | game-dev | MEDIA | 0.706688 | game-dev | 0.879483 | 1 | 0.879483 |
EpicSentry/P2ASW | 2,690 | src/game/server/hl2/basehlcombatweapon.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "basehlcombatweapon_shared.h"
#ifndef BASEHLCOMBATWEAPON_H
#define BASEHLCOMBATWEAPON_H
#ifdef _WIN32
#pragma once
#endif
//=========================================================
// Machine gun base class
//=========================================================
abstract_class CHLMachineGun : public CBaseHLCombatWeapon
{
public:
DECLARE_CLASS( CHLMachineGun, CBaseHLCombatWeapon );
DECLARE_DATADESC();
CHLMachineGun();
DECLARE_SERVERCLASS();
void PrimaryAttack( void );
// Default calls through to m_hOwner, but plasma weapons can override and shoot projectiles here.
virtual void ItemPostFrame( void );
virtual void FireBullets( const FireBulletsInfo_t &info );
virtual float GetFireRate( void ) = 0;
virtual int WeaponRangeAttack1Condition( float flDot, float flDist );
virtual bool Deploy( void );
virtual const Vector &GetBulletSpread( void );
int WeaponSoundRealtime( WeaponSound_t shoot_type );
// utility function
static void DoMachineGunKick( CBasePlayer *pPlayer, float dampEasy, float maxVerticleKickAngle, float fireDurationTime, float slideLimitTime );
protected:
int m_nShotsFired; // Number of consecutive shots fired
float m_flNextSoundTime; // real-time clock of when to make next sound
};
//=========================================================
// Machine guns capable of switching between full auto and
// burst fire modes.
//=========================================================
// Mode settings for select fire weapons
enum
{
FIREMODE_FULLAUTO = 1,
FIREMODE_SEMI,
FIREMODE_3RNDBURST,
};
//=========================================================
// >> CHLSelectFireMachineGun
//=========================================================
class CHLSelectFireMachineGun : public CHLMachineGun
{
DECLARE_CLASS( CHLSelectFireMachineGun, CHLMachineGun );
public:
CHLSelectFireMachineGun( void );
DECLARE_SERVERCLASS();
virtual float GetBurstCycleRate( void );
virtual float GetFireRate( void );
virtual bool Deploy( void );
virtual void WeaponSound( WeaponSound_t shoot_type, float soundtime = 0.0f );
DECLARE_DATADESC();
virtual int GetBurstSize( void ) { return 3; };
void BurstThink( void );
virtual void PrimaryAttack( void );
virtual void SecondaryAttack( void );
virtual int WeaponRangeAttack1Condition( float flDot, float flDist );
virtual int WeaponRangeAttack2Condition( float flDot, float flDist );
protected:
int m_iBurstSize;
int m_iFireMode;
};
#endif // BASEHLCOMBATWEAPON_H
| 1 | 0.908175 | 1 | 0.908175 | game-dev | MEDIA | 0.991886 | game-dev | 0.554781 | 1 | 0.554781 |
keijiro/VJ04 | 2,410 | Assets/Standard Assets/Editor/Image Effects/AntialiasingAsPostEffectEditor.js |
#pragma strict
@CustomEditor (AntialiasingAsPostEffect)
class AntialiasingAsPostEffectEditor extends Editor
{
var serObj : SerializedObject;
var mode : SerializedProperty;
var showGeneratedNormals : SerializedProperty;
var offsetScale : SerializedProperty;
var blurRadius : SerializedProperty;
var dlaaSharp : SerializedProperty;
var edgeThresholdMin : SerializedProperty;
var edgeThreshold : SerializedProperty;
var edgeSharpness : SerializedProperty;
function OnEnable () {
serObj = new SerializedObject (target);
mode = serObj.FindProperty ("mode");
showGeneratedNormals = serObj.FindProperty ("showGeneratedNormals");
offsetScale = serObj.FindProperty ("offsetScale");
blurRadius = serObj.FindProperty ("blurRadius");
dlaaSharp = serObj.FindProperty ("dlaaSharp");
edgeThresholdMin = serObj.FindProperty("edgeThresholdMin");
edgeThreshold = serObj.FindProperty("edgeThreshold");
edgeSharpness = serObj.FindProperty("edgeSharpness");
}
function OnInspectorGUI () {
serObj.Update ();
GUILayout.Label("Luminance based fullscreen antialiasing", EditorStyles.miniBoldLabel);
EditorGUILayout.PropertyField (mode, new GUIContent ("Technique"));
var mat : Material = (target as AntialiasingAsPostEffect).CurrentAAMaterial ();
if(null == mat && (target as AntialiasingAsPostEffect).enabled) {
EditorGUILayout.HelpBox("This AA technique is currently not supported. Choose a different technique or disable the effect and use MSAA instead.", MessageType.Warning);
}
if (mode.enumValueIndex == AAMode.NFAA) {
EditorGUILayout.PropertyField (offsetScale, new GUIContent ("Edge Detect Ofs"));
EditorGUILayout.PropertyField (blurRadius, new GUIContent ("Blur Radius"));
EditorGUILayout.PropertyField (showGeneratedNormals, new GUIContent ("Show Normals"));
} else if (mode.enumValueIndex == AAMode.DLAA) {
EditorGUILayout.PropertyField (dlaaSharp, new GUIContent ("Sharp"));
} else if (mode.enumValueIndex == AAMode.FXAA3Console) {
EditorGUILayout.PropertyField (edgeThresholdMin, new GUIContent ("Edge Min Threshhold"));
EditorGUILayout.PropertyField (edgeThreshold, new GUIContent ("Edge Threshhold"));
EditorGUILayout.PropertyField (edgeSharpness, new GUIContent ("Edge Sharpness"));
}
serObj.ApplyModifiedProperties();
}
}
| 1 | 0.855696 | 1 | 0.855696 | game-dev | MEDIA | 0.75901 | game-dev,web-frontend | 0.866899 | 1 | 0.866899 |
vmangos/core | 65,682 | src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_cthun.cpp | /*
* Copyright (C) 2006-2011 ScriptDev2 <http://www.scriptdev2.com/>
* Copyright (C) 2010-2011 ScriptDev0 <http://github.com/mangos-zero/scriptdev0>
*
* 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
*/
/* Nostalrius (inital version Scriptcraft)
** Name: Boss_Cthun
** Complete: who knows
** Comment: so many things
** Category: Temple of Ahn'Qiraj
** Rewritten by Gemt
*/
#include "scriptPCH.h"
#include "temple_of_ahnqiraj.h"
#include <algorithm>
enum eCreatures
{
EMOTE_WEAKENED = 11476,
MOB_EYE_TENTACLE = 15726,
MOB_CLAW_TENTACLE = 15725,
MOB_GIANT_CLAW_TENTACLE = 15728,
MOB_GIANT_EYE_TENTACLE = 15334,
MOB_FLESH_TENTACLE = 15802,
MOB_CTHUN_PORTAL = 15896,
MOB_SMALL_PORTAL = 15904,
MOB_GIANT_PORTAL = 15910,
PUNT_CREATURE = 15922, //invisible viscidus trigger, used in stomach
};
// C'Thun hotfixes: http://blue.cardplace.com/cache/wow-general/7950998.htm
enum eSpells
{
// Phase 1 spells
SPELL_FREEZE_ANIMATION = 16245, // Dummy spell to avoid the eye gazing around during dark glare
SPELL_ROTATE_TRIGGER = 26137,
SPELL_ROTATE_NEGATIVE_360 = 26136,
SPELL_ROTATE_POSITIVE_360 = 26009,
// SPELL_DARK_GLARE = 26029,
// Shared spells
SPELL_GREEN_EYE_BEAM = 26134,
// Mob spells
SPELL_THRASH = 3391,
SPELL_GROUND_TREMOR = 6524,
SPELL_TENTACLE_BIRTH = 26262,
SPELL_SUBMERGE_VISUAL = 26234,
SPELL_SUBMERGE_EFFECT = 21859, // Must be removed after re-emerge after a submerge to remove immunity
// spellid 26100 has a more correct knockback effect for giant tentacles, but wrong dmg values
// SPELL_PUNT_UPWARD = 16716, // Used to knock people up from stomach. Remove manually after port as it's the wrong spell and applies slowfall
// SPELL_MASSIVE_GROUND_RUPTURE = 26100, // currently unused, ~1k physical huge knockback, not sure who should do it, if any
SPELL_GROUND_RUPTURE_PHYSICAL = 26139, // used by small tentacles
SPELL_HAMSTRING = 26141, //26211 is in DBC with more correct ID?
SPELL_MIND_FLAY = 26143,
SPELL_GROUND_RUPTURE_NATURE = 26478, //used by giant tentacles
//C'thun spells
SPELL_CARAPACE_OF_CTHUN = 26156, // Makes C'thun invulnerable
// SPELL_DIGESTIVE_ACID_TELEPORT= 26220, // Not yet used, seems to port C'thun instead of player no matter what.
SPELL_TRANSFORM = 26232, // Initiates the p1->p2 transform
SPELL_CTHUN_VULNERABLE = 26235, // Adds the red color. Does not actually him vulnerable, need to remove carapace for that.
SPELL_MOUTH_TENTACLE = 26332, // Spawns the tentacle that "eats" you to stomach and mounts the player on it.
};
static std::vector<uint32> const allTentacleTypes
({
MOB_EYE_TENTACLE,
MOB_CLAW_TENTACLE,
MOB_GIANT_CLAW_TENTACLE,
MOB_GIANT_EYE_TENTACLE,
MOB_FLESH_TENTACLE,
MOB_SMALL_PORTAL,
MOB_GIANT_PORTAL
});
static constexpr uint32 CANNOT_CAST_SPELL_MASK = (UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED | UNIT_FLAG_STUNNED
| UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING);
static constexpr float stomachPortPosition[4] =
{
-8562.0f, 2037.0f, -96.0f, 5.05f
};
static constexpr float fleshTentaclePositions[2][4] =
{
{ -8571.0f, 1990.0f, -98.0f, 1.22f },
{ -8525.0f, 1994.0f, -98.0f, 2.12f }
};
static constexpr float eyeTentaclePositions[8][3] =
{
{ -8547.269531f, 1986.939941f, 100.490351f },
{ -8556.047852f, 2008.144653f, 100.598129f },
{ -8577.246094f, 2016.939941f, 100.320351f },
{ -8598.457031f, 2008.178467f, 100.320351f },
{ -8607.269531f, 1986.987671f, 100.490351f },
{ -8598.525391f, 1965.769043f, 100.490351f },
{ -8577.340820f, 1956.940063f, 100.536636f },
{ -8556.115234f, 1965.667725f, 100.598129f }
};
using SpellTarSelectFunction = std::function<Unit*(Creature*)>;
class SpellTimer
{
public:
SpellTimer(Creature* creature,
uint32 spellID,
uint32 initialCD,
std::function<uint32()> resetCD,
bool triggeredSpell,
SpellTarSelectFunction targetSelectFunc,
bool retryOnFail = false) :
m_creature(creature),
spellID(spellID),
cooldown(initialCD),
resetCD(resetCD),
triggered(triggeredSpell),
retryOnFail(retryOnFail),
timeSinceLast(std::numeric_limits<uint32>::max()),
targetSelectFunc(targetSelectFunc)
{}
virtual void Reset(int custom = -1)
{
if (custom >= 0)
{
cooldown = static_cast<uint32>(custom);
}
else
{
if (!resetCD)
cooldown = 0;
else
cooldown = resetCD();
}
}
// Returns true when the cooldown reaches < diff, a cast is attempted, and cooldown is reset
virtual bool Update(uint32 diff)
{
if (cooldown < diff)
{
Unit* target = targetSelectFunc(m_creature);
bool didCast = false;
if (target)
{
if(m_creature->AI()->DoCastSpellIfCan(target, spellID, triggered ? CF_TRIGGERED : 0) == CAST_OK)
{
didCast = true;
}
}
if (retryOnFail && !didCast)
{
return false;
}
else
{
if (!resetCD)
cooldown = 0;
else
cooldown = resetCD();
timeSinceLast = 0;
return true;
}
}
else
{
cooldown -= diff;
timeSinceLast += diff;
}
return false;
}
protected:
Creature* m_creature;
uint32 spellID;
uint32 cooldown;
std::function<uint32()> resetCD;
bool triggered;
bool retryOnFail;
uint32 timeSinceLast;
SpellTarSelectFunction targetSelectFunc;
};
class OnlyOnceSpellTimer : public SpellTimer
{
public:
OnlyOnceSpellTimer(Creature* creature, uint32 spellID, uint32 initialCD, std::function<uint32()> resetCD,
bool triggeredSpell, SpellTarSelectFunction targetSelectFunc, bool retryOnFail=false) :
SpellTimer(creature, spellID, initialCD, resetCD, triggeredSpell, targetSelectFunc, retryOnFail),
didOnce(false)
{}
void Reset(int custom = -1) override
{
SpellTimer::Reset(custom);
didOnce = false;
}
bool Update(uint32 diff) override
{
if (!didOnce)
{
if (SpellTimer::Update(diff))
{
didOnce = true;
}
}
else
{
timeSinceLast += diff;
}
return didOnce;
}
private:
bool didOnce;
};
static Player* SelectRandomAliveNotStomach(instance_temple_of_ahnqiraj* instance)
{
if (!instance)
return nullptr;
std::vector<Player*> temp;
Map::PlayerList const& PlayerList = instance->GetMap()->GetPlayers();
if (!PlayerList.isEmpty())
{
for (const auto& itr : PlayerList)
{
if (Player* player = itr.getSource())
{
if (!player->IsDead() && !player->IsGameMaster() && player->IsInCombat() && !instance->PlayerInStomach(player))
{
temp.push_back(player);
}
}
}
}
if (temp.empty())
return nullptr;
return SelectRandomContainerElement(temp);
}
// Helper functions for SpellTimer users
static Unit* selectSelfFunc(Creature* c)
{
return c;
}
static Unit* selectTargetFunc(Creature* c)
{
return c->GetVictim();
}
// ================== PHASE 1 CONSTANTS ==================
static constexpr uint32 P1_EYE_TENTACLE_RESPAWN_TIMER = 45000;
static constexpr uint32 SPELL_ROTATE_TRIGGER_CASTTIME = 3000;
static constexpr uint32 GREEN_BEAM_PHASE_DURATION = 45000;
static constexpr uint32 DARK_GLARE_PHASE_DURATION = 38000;
static constexpr uint32 DARK_GLARE_COOLING_DOWN = 1000;
//static constexpr int32 MAX_INITIAL_PULLER_HITS = 3; // How many times will c'thun target the initial
// puller with green beam before random target.
static constexpr int32 P1_GREEN_BEAM_COOLDOWN = 3000; // Green beam has a 2 sec cast time. If this number is > 2000,
// the cooldown will be P1_GREEN_BEAM_COOLDOWN - 2000
static uint32 const P1_CLAW_TENTACLE_RESPAWN_TIMER = 5000; // checked against old footage & current fight
// =======================================================
// ================= TRANSITION CONSTANTS ================
static constexpr uint32 EYE_DEAD_TO_BODY_EMERGE_DELAY = 4000;
static constexpr uint32 CTHUN_EMERGE_ANIM_DURATION = 8000;
// =======================================================
// ================== PHASE 2 CONSTANTS ==================
static constexpr uint32 P2_EYE_TENTACLE_RESPAWN_TIMER = 30000;
static constexpr uint32 GIANT_CLAW_RESPAWN_TIMER = 60000;
static constexpr uint32 STOMACH_GRAB_COOLDOWN = 10000;
static constexpr uint32 GIANT_EYE_RESPAWN_TIMER = 60000;
static constexpr uint32 STOMACH_GRAB_DURATION = 3250;
static constexpr uint32 WEAKNESS_DURATION = 45000;
static constexpr uint32 P2_FIRST_GIANT_CLAW_SPAWN = 8000;
static constexpr uint32 P2_FIRST_EYE_TENTACLE_SPAWN = 38000;
static constexpr uint32 P2_FIRST_GIANT_EYE_SPAWN = 38000;
static constexpr uint32 P2_FIRST_STOMACH_GRAB = 18000 - STOMACH_GRAB_DURATION;
// =======================================================
// ======================= MISC ==========================
static constexpr uint32 GROUND_RUPTURE_DELAY = 0; // ms after spawn that the ground rupture will be cast
static constexpr uint32 HAMSTRING_INITIAL_COOLDOWN = 2000; // Claw tentacle hamstring cooldown after spawn/tp
static uint32 hamstringResetCooldownFunc() { return 5000; } // Claw tentacle hamstring cooldown after use
static uint32 trashResetCooldownFunc() { return urand(6000, 12000); }
static uint32 groundTremorResetCooldownFunc() { return urand(6000, 12000); }
//static constexpr uint32 CLAW_TENTACLE_FIRST_MELEE_DELAY = 1000; // Earliest possible point for a claw tentacle to melee after spawn/tp
static constexpr uint32 CLAW_TENTACLE_EVADE_PORT_COOLDOWN = 5000; // How long does a claw tentacle evade before TPing to new target
static constexpr uint32 TENTACLE_BIRTH_DURATION = 3000; // Duration of birth animation and /afk before tentacles start doing stuff
static constexpr uint32 GIANT_EYE_BEAM_COOLDOWN = 2500; // How often will giant eye tentacles cast green beam
static constexpr uint32 GIANT_EYE_INITIAL_GREEN_BEAM_COOLDOWN = 0; // How long will giant eye wait after spawn before casting UPDATE: use TENTACLE_BIRTH_DURATION
static constexpr uint32 MIND_FLAY_COOLDOWN_ON_RESIST = 1500; // How long do we wait if Eye Tentacle MF resists before retrying cast
static constexpr uint32 MIND_FLAY_INITIAL_WAIT_DURATION = 0; // How long do we wait after Eye tentacle has spawned until first MF UPDATE: use TENTACLE_BIRTH_DURATION
static constexpr uint32 TELEPORT_BURIED_DURATION = 1000; // How long will a claw tentacle say underground before re-emerging on teleport.
// =======================================================
// ================== THE PULL ===========================
/* if defined, the encounter does not pull all players in combat on aggro, but
* rather aggros the initial puller and then places everyone else in combat
* 12 seconds later. Sources: https://pastebin.com/BiC33bU5
*
* If not defined, the current logic is to target the intial puller 3 times with the
* beam before going on a random target. More research should be done to better understand
* how the pull worked *after* the later nerfs, and also when it was implemented.
*
* The one thing that is certain is that in all kills with videos around the time it first became
* "killable" (april 24th 2006), the 12seconds delayed combat was how it worked.
* In later kills, towards the end of 2006, people were put in combat as soon as the first beam *hit*
* the initial puller, but how many times it would hit the initial puller is currently unknown.
*
* A suggested way to make the pull slightly more challenging is tuning DELAYED_COMBAT_DURATION to
* somewhere between 6 and 9 seconds.
*/
#define USE_POSTFIX_PRENERF_PULL_LOGIC
#ifdef USE_POSTFIX_PRENERF_PULL_LOGIC
static constexpr uint32 DELAYED_COMBAT_DURATION = 9000;
#endif
// =======================================================
static constexpr TempSummonType TENTACLE_DESPAWN_FLAG = TEMPSUMMON_CORPSE_TIMED_DESPAWN;
struct cthunTentacle : public ScriptedAI
{
instance_temple_of_ahnqiraj* m_pInstance;
float defaultOrientation;
cthunTentacle(Creature* pCreature) :
ScriptedAI(pCreature)
{
m_pInstance = dynamic_cast<instance_temple_of_ahnqiraj*>(pCreature->GetInstanceData());
if (!m_pInstance)
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "C'thun tentacle could not find it's instance");
SetCombatMovement(false);
defaultOrientation = m_creature->GetOrientation();
}
void Reset() override
{
m_creature->AddUnitState(UNIT_STATE_ROOT);
m_creature->StopMoving();
m_creature->SetRooted(true);
m_creature->SetInCombatWithZone();
}
void Aggro(Unit* pWho) override
{
ScriptedAI::Aggro(pWho);
m_creature->SetInCombatWithZone();
}
bool UpdateCthunTentacle(uint32 diff)
{
if (!m_pInstance) return false;
if (!m_pInstance->GetPlayerInMap(true, false))
{
if (TemporarySummon* tmpS = dynamic_cast<TemporarySummon*>(m_creature))
{
tmpS->UnSummon();
}
else
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "CThunTentacle could not cast creature to TemporarySummon*");
}
//EnterEvadeMode();
//m_creature->OnLeaveCombat();
//Reset();
return false;
}
// This makes the mob behave like frostnovaed mobs etc, that is,
// retargetting another top-threat target if current leaves melee range
m_creature->AddUnitState(UNIT_STATE_ROOT);
m_creature->StopMoving();
m_creature->SetRooted(true);
return true;
}
bool UpdateMelee(bool resetOrientation)
{
if (!SelectHostileTargetMelee())
{
DoStopAttack();
if(resetOrientation)
m_creature->SetOrientation(defaultOrientation);
return false;
}
else
{
DoMeleeAttackIfReady();
return true;
}
}
// Custom targetting function.
// Will only target hostile players/pets that are in melee range.
// If current target leaves melee range, his threat is reset.
// IF there are no targets in melee range, the creature will
// not target anyone.
// Returns true when the creature has a target.
bool SelectHostileTargetMelee()
{
if (!m_creature->IsAlive())
return false;
// If we're casting something its sort-of counter intuitive to return true,
// but it also means we do have a valid target already, even if it's not melee.
// DoMeleeAttack, which is typically called on true return, will check
// m_creature->IsNonMeleeSpellCasted(false) internally anyway.
if (m_creature->IsNonMeleeSpellCasted(false))
{
return true;
}
Unit* oldTarget = m_creature->GetVictim();
Unit* target = nullptr;
// First checking if we have some taunt on us
Unit::AuraList const& tauntAuras = m_creature->GetAurasByType(SPELL_AURA_MOD_TAUNT);
for (auto it = tauntAuras.crbegin(); it != tauntAuras.crend(); it++)
{
Unit* caster = (*it)->GetCaster();
if (!caster) continue;
if (caster->IsInMap(m_creature) && caster->IsTargetableBy(m_creature) && m_creature->CanReachWithMeleeAutoAttack(caster))
{
target = caster;
break;
}
else // Target is not in melee and reset his threat
m_creature->GetThreatManager().modifyThreatPercent(caster, -100);
}
// So far so good. If we have a target after this loop it means we have a valid target in melee range.
// If we dont have a target we need to keep searching through the threatlist
if (!target)
{
Unit* tmpTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, nullptr, SELECT_FLAG_IN_MELEE_RANGE);
// Resetting threat of old target if it has left melee range
if (oldTarget && tmpTarget != oldTarget && !oldTarget->CanReachWithMeleeAutoAttack(m_creature))
m_creature->GetThreatManager().modifyThreatPercent(oldTarget, -100);
// Need to call getHostileTarget to force an update of the threatlist, bleh
if (tmpTarget)
target = m_creature->GetThreatManager().getHostileTarget();
}
if (target)
{
// Nostalrius : Correction bug sheep/fear
if (!m_creature->HasUnitState(UNIT_STATE_STUNNED | UNIT_STATE_PENDING_STUNNED | UNIT_STATE_FEIGN_DEATH | UNIT_STATE_CONFUSED | UNIT_STATE_FLEEING)
&& (!m_creature->HasAuraType(SPELL_AURA_MOD_FEAR) || m_creature->HasAuraType(SPELL_AURA_PREVENTS_FLEEING)) && !m_creature->HasAuraType(SPELL_AURA_MOD_CONFUSE))
{
m_creature->SetInFront(target);
AttackStart(target);
}
return true;
}
return false;
}
};
struct cthunPortalTentacle : public cthunTentacle
{
private:
uint32 birthTimer;
public:
ObjectGuid portalGuid;
OnlyOnceSpellTimer groundRuptureTimer;
cthunPortalTentacle(Creature* pCreature, uint32 groundRuptSpellId, uint32 portalId) :
cthunTentacle(pCreature),
groundRuptureTimer(pCreature, groundRuptSpellId, GROUND_RUPTURE_DELAY, 0, true, selectSelfFunc)
{
Creature* pPortal = DoSpawnCreature(portalId, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 500); //TEMPSUMMON_DEAD_DESPAWN, 120000
if (pPortal)
{
pPortal->SetInCombatWithZone();
portalGuid = pPortal->GetGUID();
FixPortalPosition();
}
else
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "cthunPortalTentacle failed to spawn portal with entry %d", portalId);
}
}
void DespawnPortal()
{
if (Creature* pCreature = m_creature->GetMap()->GetCreature(portalGuid))
{
if (TemporarySummon* ts = dynamic_cast<TemporarySummon*>(pCreature))
{
ts->UnSummon();
portalGuid = 0;
}
else
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "Unable to despawn cthunPortalTentacle portal, could not cast to temporarySummon*");
}
}
}
void Reset() override
{
cthunTentacle::Reset();
groundRuptureTimer.Reset();
birthTimer = TENTACLE_BIRTH_DURATION;
m_creature->AttackStop(true);
//DoStopAttack(true);
}
void JustDied(Unit*) override
{
DespawnPortal();
}
bool UpdatePortalTentacle(uint32 diff)
{
if (!cthunTentacle::UpdateCthunTentacle(diff))
{
DespawnPortal();
//m_creature->ForcedDespawn(500);
return false;
}
if (groundRuptureTimer.Update(diff))
{
if (birthTimer > diff)
{
// Only want to cast it once, and it cant be done in ctor because groundRupture interrupts the animation.
if (birthTimer == TENTACLE_BIRTH_DURATION)
{
DoCastSpellIfCan(m_creature, SPELL_TENTACLE_BIRTH);
}
birthTimer -= diff;
}
}
return birthTimer <= diff;
}
void FixPortalPosition()
{
Unit* pPortal = nullptr;
if (portalGuid && m_pInstance)
pPortal = m_pInstance->GetCreature(portalGuid);
if (!pPortal)
return;
if (pPortal->AI())
{
pPortal->AI()->SetMeleeAttack(false);
pPortal->AI()->SetCombatMovement(false);
}
uint32 portalEntry = pPortal->GetEntry();
float radius;
switch (portalEntry)
{
case MOB_SMALL_PORTAL: radius = 3.0f; break;
case MOB_GIANT_PORTAL: radius = 8.0f; break;
default:
radius = 3.0f;
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "C'thun FixPortalPosition unknown portalID %d", portalEntry);
}
//Searching for best z-coordinate to place the portal
float centerX = m_creature->GetPositionX();
float centerY = m_creature->GetPositionY();
float useZ = m_creature->GetPositionZ();
float angle = M_PI_F / 4.0f;
float highZ = useZ;
float avg_height = 0.0f;
uint8 inliers = 0;
for (uint8 i = 0; i < 8; i++)
{
float x = centerX + cos((float)i * angle) * radius;
float y = centerY + sin((float)i * angle) * radius;
float z = m_creature->GetMap()->GetHeight(x, y, useZ);
float deviation = abs(useZ - z);
// Any deviation >= 0.5 we consider outliers as we dont want to handle sloped terrain
if (deviation < 0.5f)
{
if (z > highZ)
highZ = z;
avg_height += z;
inliers++;
}
}
avg_height /= inliers;
// Only move portal up if the average height is higher than the creatures height
if (avg_height > useZ)
{
useZ = highZ;
}
pPortal->NearLandTo(m_creature->GetPositionX(), m_creature->GetPositionY(), useZ, 0);
}
};
struct clawTentacle : public cthunPortalTentacle
{
uint32 EvadeTimer;
SpellTimer hamstringTimer;
uint32 teleportBuriedTimer;
uint32 feignDeathTimer;
enum eClawState
{
NORMAL,
FEIGN_IN_PROCES,
BURRIED,
};
eClawState clawState;
clawTentacle(Creature* pCreature, uint32 groundRuptSpellId, uint32 portalId) :
cthunPortalTentacle(pCreature, groundRuptSpellId, portalId),
EvadeTimer(0),
hamstringTimer(pCreature, SPELL_HAMSTRING, HAMSTRING_INITIAL_COOLDOWN, hamstringResetCooldownFunc, false, selectTargetFunc, true)
{
}
void Reset() override
{
cthunPortalTentacle::Reset();
hamstringTimer.Reset(HAMSTRING_INITIAL_COOLDOWN);
EvadeTimer = CLAW_TENTACLE_EVADE_PORT_COOLDOWN;
teleportBuriedTimer = 0;
// If reset is called after a teleport, it regains full HP.
// Todo: Should we also clear any debuffs?
m_creature->SetFullHealth();
clawState = eClawState::NORMAL;
feignDeathTimer = 0;
}
bool UpdateClawTentacle(uint32 diff)
{
if (!cthunPortalTentacle::UpdatePortalTentacle(diff))
return false;
switch (clawState)
{
case NORMAL:
updateNormal(diff);
return true;
break;
case FEIGN_IN_PROCES:
updateFeign(diff);
return false;
break;
case BURRIED:
updateBurried(diff);
return false;
break;
default:
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "Unknown UpdateClawTentacle state.");
return false;
}
}
private:
void updateNormal(uint32 diff)
{
if (UpdateMelee(false))
{
EvadeTimer = CLAW_TENTACLE_EVADE_PORT_COOLDOWN;
hamstringTimer.Update(diff);
}
else
{
if (EvadeTimer < diff)
{
clawState = eClawState::FEIGN_IN_PROCES;
feignDeathTimer = 1000;
m_creature->CastSpell(m_creature, SPELL_SUBMERGE_VISUAL, false);
}
else
{
EvadeTimer -= diff;
}
}
/*
if (Unit* uP = CheckForMelee())
{
EvadeTimer = CLAW_TENTACLE_EVADE_PORT_COOLDOWN;
}
else
{
// Initiate submerge->teleport->birth sequence if it's time
if (EvadeTimer < diff)
{
DoStopAttack(); // Added after testing
clawState = eClawState::FEIGN_IN_PROCES;
feignDeathTimer = 1000;
m_creature->CastSpell(m_creature, SPELL_SUBMERGE_VISUAL, false);
}
else
{
EvadeTimer -= diff;
}
}
*/
}
void updateFeign(uint32 diff)
{
if (feignDeathTimer < diff)
{
clawState = eClawState::BURRIED;
teleportBuriedTimer = TELEPORT_BURIED_DURATION;
setVisibility(false);
}
else
{
feignDeathTimer -= diff;
}
}
void updateBurried(uint32 diff)
{
if (teleportBuriedTimer < diff)
{
// Done being burried, time to teleport on a new target.
// If we're successfull in selecting a new target, reset will reset
// all necessary cooldowns, including setting the correct clawState (NORMAL)
if (TeleportOnNewRandomTarget())
{
DoResetThreat();
m_creature->RemoveAurasDueToSpell(SPELL_SUBMERGE_VISUAL);
setVisibility(true);
m_creature->RemoveAurasDueToSpell(SPELL_SUBMERGE_EFFECT);
Reset();
}
}
else
{
teleportBuriedTimer -= diff;
}
}
bool TeleportOnNewRandomTarget()
{
if (Player* target = SelectRandomAliveNotStomach(m_pInstance))
{
float x;
float y;
float z;
m_creature->GetRandomPoint(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0.5f, x, y, z);
m_creature->NearTeleportTo(x, y, z, 0);
if (Creature* pCreature = m_creature->GetMap()->GetCreature(portalGuid))
{
FixPortalPosition();
}
return true;
}
return false;
}
void setVisibility(bool visiblityOn)
{
Creature* pCreature = m_creature->GetMap()->GetCreature(portalGuid);
if (visiblityOn)
{
m_creature->SetVisibility(VISIBILITY_ON);
if (pCreature)
pCreature->SetVisibility(VISIBILITY_ON);
}
else
{
m_creature->SetVisibility(VISIBILITY_OFF);
if (pCreature)
pCreature->SetVisibility(VISIBILITY_OFF);
}
}
};
struct eye_tentacleAI : public cthunPortalTentacle
{
uint32 nextMFAttempt;
ObjectGuid currentMFTarget;
eye_tentacleAI(Creature* pCreature) :
cthunPortalTentacle(pCreature, SPELL_GROUND_RUPTURE_PHYSICAL, MOB_SMALL_PORTAL)
{
eye_tentacleAI::Reset();
}
void Reset() override
{
cthunPortalTentacle::Reset();
nextMFAttempt = MIND_FLAY_INITIAL_WAIT_DURATION;
currentMFTarget = 0;
}
void AttackStart(Unit* who) override
{
// Prevents AttacStart from stopping the cast animation
if (!m_creature->IsNonMeleeSpellCasted(false))
{
ScriptedAI::AttackStart(who);
}
}
void UpdateAI(uint32 const diff) override
{
if (!cthunPortalTentacle::UpdatePortalTentacle(diff))
return;
if (nextMFAttempt > diff)
{
nextMFAttempt -= diff;
}
else
{
nextMFAttempt = 0;
}
// If we are not already casting, try to start casting
if (!m_creature->GetCurrentSpell(CurrentSpellTypes::CURRENT_CHANNELED_SPELL))
{
currentMFTarget = 0;
bool didCast = false;
// Rough check against common auras that prevent the creature from casting,
// before getting a random target etc
if (!m_creature->HasFlag(UNIT_FIELD_FLAGS, CANNOT_CAST_SPELL_MASK))
{
// nextMFAttempt acts as a fake gcd in case of resist
if (nextMFAttempt == 0)
{
if (Player* target = SelectRandomAliveNotStomach(m_pInstance))
{
if (DoCastSpellIfCan(target, SPELL_MIND_FLAY) == CAST_OK)
{
currentMFTarget = target->GetGUID();
m_creature->SetFacingToObject(target);
m_creature->SetTargetGuid(currentMFTarget);
didCast = true;
nextMFAttempt = MIND_FLAY_COOLDOWN_ON_RESIST;
}
}
}
}
if (!didCast)
{
UpdateMelee(false);
}
}
else
{
// Stop casting on current target if it's been ported to stomach
if (Unit* currentCastTarget = m_creature->GetMap()->GetPlayer(currentMFTarget))
{
if (m_pInstance->PlayerInStomach(currentCastTarget))
{
m_creature->InterruptSpell(CurrentSpellTypes::CURRENT_CHANNELED_SPELL);
}
}
}
}
};
struct claw_tentacleAI : public clawTentacle
{
claw_tentacleAI(Creature* pCreature) :
clawTentacle(pCreature, SPELL_GROUND_RUPTURE_PHYSICAL, MOB_SMALL_PORTAL)
{
claw_tentacleAI::Reset();
}
void Reset() override
{
clawTentacle::Reset();
}
void UpdateAI(uint32 const diff) override
{
clawTentacle::UpdateClawTentacle(diff);
}
};
struct giant_claw_tentacleAI : public clawTentacle
{
SpellTimer groundTremorTimer;
SpellTimer trashTimer;
giant_claw_tentacleAI(Creature* pCreature) :
clawTentacle(pCreature, SPELL_GROUND_RUPTURE_NATURE, MOB_GIANT_PORTAL),
groundTremorTimer(pCreature, SPELL_GROUND_TREMOR, groundTremorResetCooldownFunc(), groundTremorResetCooldownFunc, true, selectTargetFunc, true),
trashTimer(pCreature, eSpells::SPELL_THRASH, trashResetCooldownFunc(), trashResetCooldownFunc, false, selectTargetFunc, true)
{
giant_claw_tentacleAI::Reset();
}
void Reset() override
{
clawTentacle::Reset();
groundTremorTimer.Reset();
trashTimer.Reset();
}
void UpdateAI(uint32 const diff) override
{
if (!clawTentacle::UpdateClawTentacle(diff))
return;
groundTremorTimer.Update(diff);
trashTimer.Update(diff);
}
};
struct giant_eye_tentacleAI : public cthunPortalTentacle
{
uint32 BeamTimer;
ObjectGuid beamTargetGuid;
bool isCasting;
giant_eye_tentacleAI(Creature* pCreature) :
cthunPortalTentacle(pCreature, SPELL_GROUND_RUPTURE_NATURE, MOB_GIANT_PORTAL)
{
giant_eye_tentacleAI::Reset();
}
void Reset() override
{
cthunPortalTentacle::Reset();
BeamTimer = GIANT_EYE_INITIAL_GREEN_BEAM_COOLDOWN;
isCasting = false;
}
void UpdateAI(uint32 const diff) override
{
if (!isCasting)
{
if (!cthunPortalTentacle::UpdatePortalTentacle(diff))
return;
}
if (!m_creature->GetCurrentSpell(CurrentSpellTypes::CURRENT_GENERIC_SPELL))
{
beamTargetGuid = 0;
isCasting = false;
}
if (BeamTimer < diff)
{
// Rough check against common auras that prevent the creature from casting,
// before getting a random target etc
if (!m_creature->HasFlag(UNIT_FIELD_FLAGS, CANNOT_CAST_SPELL_MASK))
{
if (Player* target = SelectRandomAliveNotStomach(m_pInstance))
{
if (DoCastSpellIfCan(target, SPELL_GREEN_EYE_BEAM) == SpellCastResult::SPELL_CAST_OK)
{
beamTargetGuid = target->GetObjectGuid();
isCasting = true;
BeamTimer = GIANT_EYE_BEAM_COOLDOWN;
}
}
}
}
else
{
BeamTimer -= diff;
if (m_creature->GetCurrentSpell(CurrentSpellTypes::CURRENT_GENERIC_SPELL))
{
// Stop casting on current target if it's been ported to stomach
// and immediately start casting on a new target
if (Unit* currentCastTarget = m_creature->GetMap()->GetPlayer(beamTargetGuid))
{
if (m_pInstance->PlayerInStomach(currentCastTarget))
{
m_creature->InterruptNonMeleeSpells(false);
BeamTimer = 0;
}
}
}
}
if (!isCasting)
{
UpdateMelee(false);
}
}
};
struct flesh_tentacleAI : public cthunTentacle
{
ScriptedInstance* m_pInstance;
flesh_tentacleAI(Creature* pCreature) : cthunTentacle(pCreature)
{
flesh_tentacleAI::Reset();
}
void Reset() override
{
cthunTentacle::Reset();
}
void UpdateAI(uint32 const diff) override
{
UpdateMelee(true);
}
};
struct eye_of_cthunAI : public ScriptedAI
{
// The eye phases can be a bit difficult to decode due to cast time and "cooling down" duration
// of red beam.
// There should be 45 seconds of "green beam phase"
// cast time of dark glare is 3 seconds
// once dark glare is up, boss rotates and keeps dark glare up for 38 seconds
// after 38 seconds he stops rotating and removes dark glare from himself, this is a 1 second period where nothing happens
// he then starts a new 45 seconds of green beam
// Dark glare should start casting every 86 seconds
// 45 sec green beam
// 3 sec cast dark glare
// 38 sec dark glare
// 1 sec "cooling down"
// = 86 seconds
instance_temple_of_ahnqiraj* m_pInstance;
bool IsAlreadyPulled;
uint32 eyeBeamCooldown;
uint32 eyeBeamCastCount;
//uint32 eyeBeamPhaseDuration;
//uint32 darkGlarePhaseDuration;
ObjectGuid initialPullerGuid;
enum CthunEyePhase
{
GREEN_BEAM,
DARK_GLARE_CAST,
DARK_GLARE,
DARK_GLARE_COOLING
};
CthunEyePhase currentPhase;
uint32 greenBeamPhaseTimer;
uint32 darkGlareCastTimer;
uint32 darkGlareTimer;
uint32 darkGlareCoolingTimer;
eye_of_cthunAI(Creature* pCreature) :
ScriptedAI(pCreature)
{
SetCombatMovement(false);
m_pInstance = dynamic_cast<instance_temple_of_ahnqiraj*>(pCreature->GetInstanceData());
if (!m_pInstance)
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "SD0: No Instance eye_of_cthunAI");
Reset();
}
void Pull(Unit* puller)
{
m_creature->SetFactionTemporary(14);
initialPullerGuid = puller->GetObjectGuid();
CastGreenBeam(puller);
IsAlreadyPulled = true;
}
void Aggro(Unit* puller) override
{
// Just in case someone manages to get through the AggroRadius logic in C'thuns AI
// we make sure the proper pull-sequence is initiated by calling C'thuns attackstart.
if (!m_creature->IsInCombat())
{
if (Creature* pCthun = m_pInstance->GetSingleCreatureFromStorage(NPC_CTHUN))
{
pCthun->AI()->AttackStart(puller);
}
}
}
void Reset() override
{
currentPhase = GREEN_BEAM;
initialPullerGuid = 0;
eyeBeamCastCount = 0;
eyeBeamCooldown = P1_GREEN_BEAM_COOLDOWN;
greenBeamPhaseTimer = GREEN_BEAM_PHASE_DURATION;
IsAlreadyPulled = false;
if (m_creature)
{
m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SPAWNING);
// need to reset the orientation in case of wipe during glare phase
m_creature->SetOrientation(3.44f);
RemoveGlarePhaseSpells();
}
else
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "eye_of_cthunAI: Reset called, but m_creature does not exist.");
}
}
void UpdateAI(uint32 const diff) override
{
if (!m_pInstance)
return;
if (!IsAlreadyPulled)
{
m_creature->SetTargetGuid(0);
return;
}
// No combat reset managment. C'thuns body will reset this creature when needed.
// Yes, could easily make all these different timers into just two, but
// this approach is much easier to understand, debug and tune.
switch (currentPhase)
{
case GREEN_BEAM:
if (greenBeamPhaseTimer < diff)
{
if (EnterDarkGlarePhase())
{
darkGlareCastTimer = SPELL_ROTATE_TRIGGER_CASTTIME;
currentPhase = DARK_GLARE_CAST;
}
}
else
{
greenBeamPhaseTimer -= diff;
UpdateGreenBeamPhase(diff);
}
break;
case DARK_GLARE_CAST:
if (darkGlareCastTimer < diff)
{
currentPhase = DARK_GLARE;
darkGlareTimer = DARK_GLARE_PHASE_DURATION;
}
else
{
darkGlareCastTimer -= diff;
}
break;
case DARK_GLARE:
if (darkGlareTimer < diff)
{
RemoveGlarePhaseSpells();
currentPhase = DARK_GLARE_COOLING;
darkGlareCoolingTimer = DARK_GLARE_COOLING_DOWN;
}
else
{
darkGlareTimer -= diff;
}
break;
case DARK_GLARE_COOLING:
if (darkGlareCoolingTimer < diff)
{
currentPhase = GREEN_BEAM;
greenBeamPhaseTimer = GREEN_BEAM_PHASE_DURATION;
eyeBeamCooldown = 0;
}
else
{
darkGlareCoolingTimer -= diff;
}
break;
default:
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "CThun eye update called with incorrect state: %d", currentPhase);
}
}
void UpdateGreenBeamPhase(uint32 diff)
{
if (m_creature->HasAura(SPELL_FREEZE_ANIMATION))
m_creature->RemoveAurasDueToSpell(SPELL_FREEZE_ANIMATION);
if (eyeBeamCooldown < diff)
{
Unit* target = nullptr;
#ifdef USE_POSTFIX_PRENERF_PULL_LOGIC
target = SelectRandomAliveNotStomach(m_pInstance);
#else
// We force the initial puller as the target for MAX_INITIAL_PULLER_HITS
if (eyeBeamCastCount < MAX_INITIAL_PULLER_HITS)
{
target = m_pInstance->GetMap()->GetPlayer(initialPullerGuid);
}
if (!target || target->IsDead())
{
target = SelectRandomAliveNotStomach(m_pInstance);
}
#endif
if (target)
{
CastGreenBeam(target);
}
}
else
{
eyeBeamCooldown -= diff;
}
}
void AttackStart(Unit* pUnit) override
{
// dont do nothin'
}
bool EnterDarkGlarePhase()
{
m_creature->InterruptNonMeleeSpells(false);
//Select random target for dark beam to start on and start the trigger
if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0))
{
// Remove the target focus but allow the boss to face the current victim
DoStopAttack();
m_creature->SetFacingToObject(target);
if (DoCastSpellIfCan(m_creature, SPELL_ROTATE_TRIGGER) == CAST_OK)
{
if (!m_creature->HasAura(SPELL_FREEZE_ANIMATION))
{
m_creature->CastSpell(m_creature, SPELL_FREEZE_ANIMATION, true);
}
m_creature->SetTargetGuid(ObjectGuid());
return true;
}
}
return false;
}
void RemoveGlarePhaseSpells()
{
if (m_creature->HasAura(SPELL_ROTATE_NEGATIVE_360))
{
m_creature->RemoveAurasDueToSpell(SPELL_ROTATE_NEGATIVE_360);
}
else if (m_creature->HasAura(SPELL_ROTATE_POSITIVE_360))
{
m_creature->RemoveAurasDueToSpell(SPELL_ROTATE_POSITIVE_360);
}
}
bool CastGreenBeam(Unit* target)
{
if (DoCastSpellIfCan(target, SPELL_GREEN_EYE_BEAM) == CAST_OK)
{
m_creature->SetTargetGuid(target->GetObjectGuid());
++eyeBeamCastCount;
eyeBeamCooldown = P1_GREEN_BEAM_COOLDOWN;
return true;
}
return false;
}
};
struct cthunAI : public ScriptedAI
{
enum CThunPhase
{
PHASE_EYE_NORMAL = 0,
PHASE_EYE_DARK_GLARE = 1,
PHASE_PRE_TRANSITION = 2,
PHASE_TRANSITION = 3,
PHASE_CTHUN_INVULNERABLE = 4,
PHASE_CTHUN_WEAKENED = 5,
PHASE_CTHUN_DONE = 6,
};
instance_temple_of_ahnqiraj* m_pInstance;
bool inProgress;
CThunPhase currentPhase;
// P1 timers
uint32 eyeTentacleTimer_p1;
uint32 clawTentacleTimer_p1;
// P2 timers
uint32 weaknessTimer;
uint32 eyeTentacleTimer;
uint32 cthunEmergeTimer;
uint32 giantEyeTentacleTimer;
uint32 stomachEnterPortTimer;
uint32 giantClawTentacleTimer;
uint32 nextStomachEnterGrabTimer;
#ifdef USE_POSTFIX_PRENERF_PULL_LOGIC
uint32 delayedCombatEntryTimer;
bool isInCombatWithZone;
#endif
ObjectGuid eyeGuid;
ObjectGuid puntCreatureGuid;
ObjectGuid StomachEnterTargetGUID;
std::vector<ObjectGuid> fleshTentacles;
uint32 wipeRespawnEyeTimer;
cthunAI(Creature* pCreature) :
ScriptedAI(pCreature),
wipeRespawnEyeTimer(0)
{
SetCombatMovement(false);
m_pInstance = (instance_temple_of_ahnqiraj*)pCreature->GetInstanceData();
if (!m_pInstance)
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "SD0: No Instance for cthunAI");
if (Creature* pPortal = DoSpawnCreature(MOB_CTHUN_PORTAL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0))
{
pPortal->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_SPAWNING);
}
Reset();
}
void AttackStart(Unit* who) override
{
if (!m_creature->IsInCombat())
{
Creature* pEye = m_pInstance->GetCreature(eyeGuid);
if (!pEye)
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "cthunAI::AggroRadius could not find pEye");
return;
}
eye_of_cthunAI* eyeAI = (eye_of_cthunAI*)pEye->AI();
eyeAI->Pull(who);
ScriptedAI::AttackStart(who);
#ifdef USE_POSTFIX_PRENERF_PULL_LOGIC
m_creature->SetInCombatWith(who);
pEye->SetInCombatWith(who);
#else
m_creature->SetInCombatWithZone();
pEye->SetInCombatWithZone();
#endif
if (m_pInstance)
{
m_pInstance->SetData(TYPE_CTHUN, IN_PROGRESS);
}
}
else
{
ScriptedAI::AttackStart(who);
}
}
void DespawnAllTentacles()
{
std::list<Creature*> creaturesToDespawn;
GetCreatureListWithEntryInGrid(creaturesToDespawn, m_creature, allTentacleTypes, 350.0f);
for (const auto it : creaturesToDespawn)
{
if (auto* cpt = dynamic_cast<cthunPortalTentacle*>(it->AI()))
{
cpt->DespawnPortal();
}
if (auto* ts = dynamic_cast<TemporarySummon*>(it))
{
ts->UnSummon();
}
}
}
void JustReachedHome() override
{
if(m_pInstance)
m_pInstance->SetData(TYPE_CTHUN, FAIL);
}
void Reset() override
{
#ifdef USE_POSTFIX_PRENERF_PULL_LOGIC
delayedCombatEntryTimer = DELAYED_COMBAT_DURATION;
isInCombatWithZone = false;
#endif
inProgress = false;
currentPhase = PHASE_EYE_NORMAL;
if (!m_pInstance)
return;
cthunEmergeTimer = CTHUN_EMERGE_ANIM_DURATION;
clawTentacleTimer_p1 = P1_CLAW_TENTACLE_RESPAWN_TIMER;
eyeTentacleTimer_p1 = P1_EYE_TENTACLE_RESPAWN_TIMER;
ResetartUnvulnerablePhase(false);
// Reset visibility
m_creature->SetVisibility(VISIBILITY_OFF);
m_creature->InterruptNonMeleeSpells(false);
if (m_creature->HasAura(SPELL_CTHUN_VULNERABLE))
m_creature->RemoveAurasDueToSpell(SPELL_CTHUN_VULNERABLE);
// Demorph should set C'thuns modelId back to burrowed.
// Also removing SPELL_TRANSFORM in case of reset just as he was casting that.
m_creature->RemoveAurasDueToSpell(SPELL_TRANSFORM);
m_creature->DeMorph();
m_creature->SetVisibility(VISIBILITY_ON);
m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_SPAWNING);
// Hack to allow eye-respawning with .respawn chat-command.
// On regular wipe in p2 it's respawned from UpdateAI()
if (!wipeRespawnEyeTimer)
CheckRespawnEye();
// Force despawn any tentacles or portals alive.
DespawnAllTentacles();
if (m_creature->IsAlive())
m_creature->SetHealth(m_creature->GetMaxHealth());
//if (m_pInstance && m_creature->IsAlive())
// m_pInstance->SetData(TYPE_CTHUN, NOT_STARTED);
}
void CheckRespawnEye()
{
Creature* pEye = nullptr;
if (m_creature->IsDead())
{
// Despawning the eye if something weird has happened and C'thun is dead.
if (pEye = m_pInstance->GetCreature(eyeGuid))
{
pEye->ForcedDespawn();
}
}
else
{
// Respawning eye if it exists, but is dead.
// Otherwise attempting to spawn a new eye
if (pEye = m_pInstance->GetCreature(eyeGuid))
{
eye_of_cthunAI* eyeAI = (eye_of_cthunAI*)pEye->AI();
if (!pEye->IsAlive())
{
pEye->Respawn();
eyeAI->Reset(); // todo: remove if we KNOW that creature::respawn() calls Reset()
}
else
{
eyeAI->EnterEvadeMode();
}
}
else if (pEye = DoSpawnCreature(NPC_EYE_OF_C_THUN, 0, 0, 0, 3.44f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, EYE_DEAD_TO_BODY_EMERGE_DELAY))
{
eyeGuid = pEye->GetGUID();
}
else
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "C'thun was unable to summon it's eye");
}
}
}
void SummonedCreatureJustDied(Creature* pCreature) override
{
if (pCreature->GetEntry() == MOB_FLESH_TENTACLE)
{
auto it = std::find(fleshTentacles.begin(), fleshTentacles.end(), pCreature->GetObjectGuid());
if (it != fleshTentacles.end())
fleshTentacles.erase(it);
}
else if (pCreature->GetEntry() == NPC_EYE_OF_C_THUN)
{
currentPhase = PHASE_PRE_TRANSITION;
}
}
void JustSummoned(Creature* pCreature) override
{
if (pCreature->GetEntry() == MOB_FLESH_TENTACLE)
{
if (fleshTentacles.size() > 1)
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "Flesh tentacle summoned, but there are already %i tentacles up.", fleshTentacles.size());
}
fleshTentacles.emplace_back(pCreature->GetGUID());
}
}
void UpdateAI(uint32 const diff) override
{
if (!m_pInstance || m_creature->IsDead())
return;
// Delaying respawn of eye if it was a wipe so we get the re-emerge animation before spawn
if (wipeRespawnEyeTimer > 0)
{
wipeRespawnEyeTimer -= std::min(diff, wipeRespawnEyeTimer);
if (wipeRespawnEyeTimer < diff)
{
CheckRespawnEye();
wipeRespawnEyeTimer = 0;
}
}
if (!inProgress)
{
// Wait with calling aggroRadius until eye has respawned
if (!wipeRespawnEyeTimer && AggroRadius())
{
inProgress = true;
}
else
{
return;
}
}
// Not resetting during transition phase, just wait until it's over, then we reset.
else if (!m_pInstance->GetPlayerInMap(true, false) && currentPhase != PHASE_TRANSITION && currentPhase != PHASE_PRE_TRANSITION)
{
inProgress = false;
wipeRespawnEyeTimer = 5000;
EnterEvadeMode();
// C'thuns eye will enter evade mode through C'thuns Reset() call
}
#ifdef USE_POSTFIX_PRENERF_PULL_LOGIC
if (!isInCombatWithZone)
{
if (delayedCombatEntryTimer < diff)
{
isInCombatWithZone = true;
m_creature->SetInCombatWithZone();
if (Creature* pEye = m_pInstance->GetCreature(eyeGuid))
{
pEye->SetInCombatWithZone();
}
}
else
{
delayedCombatEntryTimer -= diff;
}
}
#endif
m_creature->SetTargetGuid(0);
switch (currentPhase)
{
case PHASE_EYE_NORMAL:
UpdateTentaclesP1(diff);
break;
case PHASE_EYE_DARK_GLARE:
UpdateTentaclesP1(diff);
break;
case PHASE_PRE_TRANSITION:
// We just wait for eye to death animation before it's despawwn will trigger PHASE_TRANSITION
break;
case PHASE_TRANSITION:
UpdateTransitionPhase(diff);
break;
case PHASE_CTHUN_INVULNERABLE:
UpdateInvulnerablePhase(diff);
CheckIfAllDead();
break;
case PHASE_CTHUN_WEAKENED:
UpdateWeakenedPhase(diff);
CheckIfAllDead();
break;
case PHASE_CTHUN_DONE:
break;
default:
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "C'Thun in bugged state: %i", currentPhase);
}
}
void SummonedCreatureDespawn(Creature* pCreature) override
{
// Despawn will happen EYE_DEAD_TO_BODY_EMERGE_DELAY time after eye death
if (pCreature->GetEntry() == NPC_EYE_OF_C_THUN)
{
currentPhase = PHASE_TRANSITION;
ResetartUnvulnerablePhase();
m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
m_creature->SetVisibility(VISIBILITY_OFF);
m_creature->CastSpell(m_creature, SPELL_TRANSFORM, true);
m_creature->SetVisibility(VISIBILITY_ON);
m_creature->CastSpell(m_creature, SPELL_TRANSFORM, true);
}
else if (pCreature->GetEntry() == MOB_FLESH_TENTACLE)
{
auto it = std::find(fleshTentacles.begin(), fleshTentacles.end(), pCreature->GetObjectGuid());
if (it != fleshTentacles.end())
fleshTentacles.erase(it);
}
}
void JustDied(Unit* pKiller) override
{
if (m_pInstance)
{
currentPhase = PHASE_CTHUN_DONE;
m_pInstance->SetData(TYPE_CTHUN, DONE);
DespawnAllTentacles();
}
}
void ResetartUnvulnerablePhase(bool spawnFleshTentacles = true)
{
giantClawTentacleTimer = P2_FIRST_GIANT_CLAW_SPAWN;
eyeTentacleTimer = P2_FIRST_EYE_TENTACLE_SPAWN;
giantEyeTentacleTimer = P2_FIRST_GIANT_EYE_SPAWN;
StomachEnterTargetGUID = 0;
stomachEnterPortTimer = 0;
nextStomachEnterGrabTimer = P2_FIRST_STOMACH_GRAB;
weaknessTimer = 0;
if (spawnFleshTentacles)
SpawnFleshTentacles();
m_creature->CastSpell(m_creature, SPELL_CARAPACE_OF_CTHUN, true);
}
bool UnitShouldPull(Unit* unit)
{
float distToCthun = unit->GetDistance3dToCenter(m_creature);
//float distToCthun = pPlayer->GetDistance(m_creature);
float zDist = abs(unit->GetPositionZ() - 100.0f);
// If we're at the same Z axis of cthun, or within the maximum possible pull distance
if (zDist < 10.0f && distToCthun < 95.0f && unit->IsWithinLOSInMap(m_creature))
{
//xxx: it will still be possible to hide behind one of the pillars in the room to avoid pulling,
//but I don't think it's really something to take advantage of anyway
return true;
}
return false;
}
bool AggroRadius()
{
// Large aggro radius
Map::PlayerList const &PlayerList = m_creature->GetMap()->GetPlayers();
for (const auto& itr : PlayerList)
{
Player* pPlayer = itr.getSource();
if (pPlayer && pPlayer->IsAlive() && !pPlayer->IsGameMaster())
{
if (UnitShouldPull(pPlayer))
{
AttackStart(pPlayer);
return true;
}
else if (Pet* pPet = pPlayer->GetPet())
{
if (UnitShouldPull(pPet))
{
AttackStart(pPlayer); //screw the pet, go straight for the head!
return true;
}
}
}
}
return false;
}
bool CheckIfAllDead()
{
if (!SelectRandomAliveNotStomach(m_pInstance))
{
if (m_pInstance->KillPlayersInStomach())
{
m_creature->OnLeaveCombat();
return true;
}
}
return false;
}
void UpdateTentaclesP1(uint32 diff)
{
if (SpawnTentacleIfReady(diff, clawTentacleTimer_p1, 0, MOB_CLAW_TENTACLE))
clawTentacleTimer_p1 = P1_CLAW_TENTACLE_RESPAWN_TIMER;
if (eyeTentacleTimer_p1 < diff)
{
SpawnEyeTentacles();
eyeTentacleTimer_p1 = P1_EYE_TENTACLE_RESPAWN_TIMER;
}
else
{
eyeTentacleTimer_p1 -= diff;
}
}
void UpdateTransitionPhase(uint32 diff)
{
UpdateTentaclesP2(diff);
UpdateStomachGrab(diff);
if (cthunEmergeTimer < diff)
{
m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SPAWNING);
m_creature->SetInCombatWithZone();
currentPhase = PHASE_CTHUN_INVULNERABLE;
}
else
{
cthunEmergeTimer -= diff;
}
}
void UpdateInvulnerablePhase(uint32 diff)
{
// Weaken if both Flesh Tentacles are killed
if (fleshTentacles.empty())
{
weaknessTimer = WEAKNESS_DURATION;
DoScriptText(EMOTE_WEAKENED, m_creature);
// If there is a grabbed player, release him.
if (!StomachEnterTargetGUID.IsEmpty())
{
if (Player* pPlayer = m_creature->GetMap()->GetPlayer(StomachEnterTargetGUID))
{
pPlayer->RemoveAurasDueToSpell(SPELL_MOUTH_TENTACLE);
}
}
//Remove the damage reduction aura
m_creature->CastSpell(m_creature, SPELL_CTHUN_VULNERABLE, true);
//Make him glow all red and nice
m_creature->RemoveAurasDueToSpell(SPELL_CARAPACE_OF_CTHUN);
currentPhase = PHASE_CTHUN_WEAKENED;
}
else
{
UpdateTentaclesP2(diff);
UpdateStomachGrab(diff);
}
}
void UpdateWeakenedPhase(uint32 diff)
{
// If weakend runs out
if (weaknessTimer < diff)
{
ResetartUnvulnerablePhase();
//note: can set visibility off and on again after removing vulnerable spell,
// if it does not visually dissapear
m_creature->RemoveAurasDueToSpell(SPELL_CTHUN_VULNERABLE);
currentPhase = PHASE_CTHUN_INVULNERABLE;
}
else
{
weaknessTimer -= diff;
}
}
void SpawnFleshTentacles()
{
if (!fleshTentacles.empty())
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "SpawnFleshTentacles() called, but there are already %i tentacles up.", fleshTentacles.size());
}
//Spawn 2 flesh tentacles in C'thun stomach
for (const auto& fleshTentaclePosition : fleshTentaclePositions)
{
m_creature->SummonCreature(MOB_FLESH_TENTACLE,
fleshTentaclePosition[0],
fleshTentaclePosition[1],
fleshTentaclePosition[2],
fleshTentaclePosition[3],
TENTACLE_DESPAWN_FLAG, 1500);
}
}
void UpdateStomachGrab(uint32 diff)
{
if (!StomachEnterTargetGUID.IsEmpty())
{
if (stomachEnterPortTimer < diff)
{
if (Player* pPlayer = m_creature->GetMap()->GetPlayer(StomachEnterTargetGUID))
{
DoTeleportPlayer(pPlayer, stomachPortPosition[0], stomachPortPosition[1], stomachPortPosition[2], stomachPortPosition[3]);
pPlayer->RemoveAurasDueToSpell(SPELL_MOUTH_TENTACLE);
if (m_pInstance)
m_pInstance->AddPlayerToStomach(pPlayer);
}
StomachEnterTargetGUID = 0;
stomachEnterPortTimer = 0;
}
else
{
stomachEnterPortTimer -= diff;
}
}
if (nextStomachEnterGrabTimer < diff)
{
if (Player* target = SelectRandomAliveNotStomach(m_pInstance))
{
target->InterruptNonMeleeSpells(false);
target->CastSpell(target, SPELL_MOUTH_TENTACLE, true, nullptr, nullptr, m_creature->GetObjectGuid());
stomachEnterPortTimer = STOMACH_GRAB_DURATION;
StomachEnterTargetGUID = target->GetObjectGuid();
}
nextStomachEnterGrabTimer = STOMACH_GRAB_COOLDOWN;
}
else
{
nextStomachEnterGrabTimer -= diff;
}
}
void UpdateTentaclesP2(uint32 diff)
{
SpawnTentacleIfReady(diff, giantClawTentacleTimer, GIANT_CLAW_RESPAWN_TIMER, MOB_GIANT_CLAW_TENTACLE);
SpawnTentacleIfReady(diff, giantEyeTentacleTimer, GIANT_EYE_RESPAWN_TIMER, MOB_GIANT_EYE_TENTACLE);
if (eyeTentacleTimer < diff)
{
SpawnEyeTentacles();
eyeTentacleTimer = P2_EYE_TENTACLE_RESPAWN_TIMER;
}
else
{
eyeTentacleTimer -= diff;
}
}
void SpawnEyeTentacles()
{
//float centerX = relToThisCreature->GetPositionX();
//float centerY = relToThisCreature->GetPositionY();
//float radius = 30.0f;
//float angle = 360.0f / 8.0f;
for (const auto& eyeTentaclePosition : eyeTentaclePositions)
{
//float x = centerX + cos(((float)i * angle) * (3.14f / 180.0f)) * radius;
//float y = centerY + sin(((float)i * angle) * (3.14f / 180.0f)) * radius;
//float z = relToThisCreature->GetMap()->GetHeight(x, y, relToThisCreature->GetPositionZ()) + 0.1f;
//sLog.Out(LOG_SCRIPTS, LOG_LVL_BASIC, "{%.6f, %.6f, %.6f},", x, y, z);
float x = eyeTentaclePosition[0];
float y = eyeTentaclePosition[1];
float z = eyeTentaclePosition[2];
if (Creature* Spawned = m_creature->SummonCreature(MOB_EYE_TENTACLE, x, y, z, 0,
TENTACLE_DESPAWN_FLAG, 1500))
//TEMPSUMMON_CORPSE_TIMED_DESPAWN, 1500))
{
Spawned->SetInCombatWithZone();
}
}
}
bool SpawnTentacleIfReady(uint32 diff, uint32& timer, uint32 resetTo, uint32 id)
{
if (timer < diff)
{
if (Unit* target = SelectRandomAliveNotStomach(m_pInstance))
{
if (target->GetPositionZ() < -30.0f)
{
sLog.Out(LOG_SCRIPTS, LOG_LVL_ERROR, "Cthun trying to spawn %i <-30.0f", id);
}
float x;
float y;
float z;
m_creature->GetRandomPoint(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0.5f, x, y, z);
if (Creature* Spawned = m_creature->SummonCreature(id, x, y, z, 0,
TENTACLE_DESPAWN_FLAG, 1500))
{
Spawned->AI()->AttackStart(target);
}
timer = resetTo;
return true;
}
}
else
{
timer -= diff;
}
return false;
}
};
//GetAIs
CreatureAI* GetAI_eye_of_cthun(Creature* pCreature)
{
return new eye_of_cthunAI(pCreature);
}
CreatureAI* GetAI_cthun(Creature* pCreature)
{
return new cthunAI(pCreature);
}
CreatureAI* GetAI_eye_tentacle(Creature* pCreature)
{
return new eye_tentacleAI(pCreature);
}
CreatureAI* GetAI_claw_tentacle(Creature* pCreature)
{
return new claw_tentacleAI(pCreature);
}
CreatureAI* GetAI_giant_claw_tentacle(Creature* pCreature)
{
return new giant_claw_tentacleAI(pCreature);
}
CreatureAI* GetAI_giant_eye_tentacle(Creature* pCreature)
{
return new giant_eye_tentacleAI(pCreature);
}
CreatureAI* GetAI_flesh_tentacle(Creature* pCreature)
{
return new flesh_tentacleAI(pCreature);
}
void AddSC_boss_cthun()
{
Script* newscript;
//Eye
newscript = new Script;
newscript->Name = "boss_eye_of_cthun";
newscript->GetAI = &GetAI_eye_of_cthun;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "boss_cthun";
newscript->GetAI = &GetAI_cthun;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_eye_tentacle";
newscript->GetAI = &GetAI_eye_tentacle;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_claw_tentacle";
newscript->GetAI = &GetAI_claw_tentacle;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_giant_claw_tentacle";
newscript->GetAI = &GetAI_giant_claw_tentacle;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_giant_eye_tentacle";
newscript->GetAI = &GetAI_giant_eye_tentacle;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_giant_flesh_tentacle";
newscript->GetAI = &GetAI_flesh_tentacle;
newscript->RegisterSelf();
}
| 1 | 0.976709 | 1 | 0.976709 | game-dev | MEDIA | 0.954843 | game-dev | 0.980002 | 1 | 0.980002 |
Corosauce/weather2 | 3,050 | src/main/java/weather2/block/ForecastBlock.java | package weather2.block;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.RenderShape;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import weather2.ServerTickHandler;
import weather2.config.ConfigStorm;
import weather2.weathersystem.WeatherManagerServer;
public class ForecastBlock extends Block {
public ForecastBlock(Properties p_49224_) {
super(p_49224_);
}
@Override
public RenderShape getRenderShape(BlockState p_49232_) {
return RenderShape.MODEL;
}
@Override
public InteractionResult use(BlockState p_60503_, Level p_60504_, BlockPos p_60505_, Player p_60506_, InteractionHand p_60507_, BlockHitResult p_60508_) {
if (!p_60504_.isClientSide) {
WeatherManagerServer wm = ServerTickHandler.getWeatherManagerFor(p_60506_.level().dimension());
float chance = wm.getBiomeBasedStormSpawnChanceInArea(new BlockPos(p_60506_.blockPosition()));
float chanceEvery10Days = 0;
int rateOften;
int rateLessOften;
int day = 20*60*20;
int diceRollRate = ConfigStorm.Storm_AllTypes_TickRateDelay;
if (ConfigStorm.Server_Storm_Deadly_UseGlobalRate) {
rateOften = ConfigStorm.Server_Storm_Deadly_TimeBetweenInTicks / day;
rateLessOften = ConfigStorm.Server_Storm_Deadly_TimeBetweenInTicks_Land_Based / day;
chanceEvery10Days = ConfigStorm.Server_Storm_Deadly_OddsTo1_Land_Based;
} else {
rateOften = ConfigStorm.Player_Storm_Deadly_TimeBetweenInTicks / day;
rateLessOften = ConfigStorm.Player_Storm_Deadly_TimeBetweenInTicks_Land_Based / day;
chanceEvery10Days = ConfigStorm.Player_Storm_Deadly_OddsTo1_Land_Based;
}
if (chanceEvery10Days > 0 && diceRollRate > 0) {
chanceEvery10Days = ((float)day / (float)diceRollRate) / chanceEvery10Days;
}
p_60506_.sendSystemMessage(Component.literal(String.format("Chance of a deadly storm here every:")));
p_60506_.sendSystemMessage(Component.literal(String.format("%d days: %.2f", rateOften, (chance * 100F)) + "% from nearby biome temperature differences"));
p_60506_.sendSystemMessage(Component.literal(String.format("%d days: %.2f", rateLessOften, (chanceEvery10Days * 100F)) + "% from randomly trying once a day"));
int count = 0;
for (int i = 0; i < 100000; i++) {
if (p_60504_.random.nextInt(1000) == 0) {
count++;
}
}
//System.out.println(count);
}
return InteractionResult.CONSUME;
}
}
| 1 | 0.732936 | 1 | 0.732936 | game-dev | MEDIA | 0.964587 | game-dev | 0.927153 | 1 | 0.927153 |
Emudofus/Dofus | 4,470 | com/ankamagames/dofus/network/messages/game/context/roleplay/job/JobCrafterDirectoryEntryMessage.as | package com.ankamagames.dofus.network.messages.game.context.roleplay.job
{
import com.ankamagames.jerakine.network.NetworkMessage;
import com.ankamagames.jerakine.network.INetworkMessage;
import com.ankamagames.dofus.network.types.game.context.roleplay.job.JobCrafterDirectoryEntryPlayerInfo;
import __AS3__.vec.Vector;
import com.ankamagames.dofus.network.types.game.context.roleplay.job.JobCrafterDirectoryEntryJobInfo;
import com.ankamagames.dofus.network.types.game.look.EntityLook;
import flash.utils.ByteArray;
import com.ankamagames.jerakine.network.CustomDataWrapper;
import com.ankamagames.jerakine.network.ICustomDataOutput;
import com.ankamagames.jerakine.network.ICustomDataInput;
import __AS3__.vec.*;
[Trusted]
public class JobCrafterDirectoryEntryMessage extends NetworkMessage implements INetworkMessage
{
public static const protocolId:uint = 6044;
private var _isInitialized:Boolean = false;
public var playerInfo:JobCrafterDirectoryEntryPlayerInfo;
public var jobInfoList:Vector.<JobCrafterDirectoryEntryJobInfo>;
public var playerLook:EntityLook;
public function JobCrafterDirectoryEntryMessage()
{
this.playerInfo = new JobCrafterDirectoryEntryPlayerInfo();
this.jobInfoList = new Vector.<JobCrafterDirectoryEntryJobInfo>();
this.playerLook = new EntityLook();
super();
}
override public function get isInitialized():Boolean
{
return (this._isInitialized);
}
override public function getMessageId():uint
{
return (6044);
}
public function initJobCrafterDirectoryEntryMessage(playerInfo:JobCrafterDirectoryEntryPlayerInfo=null, jobInfoList:Vector.<JobCrafterDirectoryEntryJobInfo>=null, playerLook:EntityLook=null):JobCrafterDirectoryEntryMessage
{
this.playerInfo = playerInfo;
this.jobInfoList = jobInfoList;
this.playerLook = playerLook;
this._isInitialized = true;
return (this);
}
override public function reset():void
{
this.playerInfo = new JobCrafterDirectoryEntryPlayerInfo();
this.playerLook = new EntityLook();
this._isInitialized = false;
}
override public function pack(output:ICustomDataOutput):void
{
var data:ByteArray = new ByteArray();
this.serialize(new CustomDataWrapper(data));
writePacket(output, this.getMessageId(), data);
}
override public function unpack(input:ICustomDataInput, length:uint):void
{
this.deserialize(input);
}
public function serialize(output:ICustomDataOutput):void
{
this.serializeAs_JobCrafterDirectoryEntryMessage(output);
}
public function serializeAs_JobCrafterDirectoryEntryMessage(output:ICustomDataOutput):void
{
this.playerInfo.serializeAs_JobCrafterDirectoryEntryPlayerInfo(output);
output.writeShort(this.jobInfoList.length);
var _i2:uint;
while (_i2 < this.jobInfoList.length)
{
(this.jobInfoList[_i2] as JobCrafterDirectoryEntryJobInfo).serializeAs_JobCrafterDirectoryEntryJobInfo(output);
_i2++;
};
this.playerLook.serializeAs_EntityLook(output);
}
public function deserialize(input:ICustomDataInput):void
{
this.deserializeAs_JobCrafterDirectoryEntryMessage(input);
}
public function deserializeAs_JobCrafterDirectoryEntryMessage(input:ICustomDataInput):void
{
var _item2:JobCrafterDirectoryEntryJobInfo;
this.playerInfo = new JobCrafterDirectoryEntryPlayerInfo();
this.playerInfo.deserialize(input);
var _jobInfoListLen:uint = input.readUnsignedShort();
var _i2:uint;
while (_i2 < _jobInfoListLen)
{
_item2 = new JobCrafterDirectoryEntryJobInfo();
_item2.deserialize(input);
this.jobInfoList.push(_item2);
_i2++;
};
this.playerLook = new EntityLook();
this.playerLook.deserialize(input);
}
}
}//package com.ankamagames.dofus.network.messages.game.context.roleplay.job
| 1 | 0.822751 | 1 | 0.822751 | game-dev | MEDIA | 0.872089 | game-dev | 0.858619 | 1 | 0.858619 |
ProjectIgnis/CardScripts | 1,255 | unofficial/c511003211.lua | --インフェルニティ・ナイト (Manga)
--Infernity Knight (Manga)
local s,id=GetID()
function s.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(s.spcon)
e1:SetCost(s.spcost)
e1:SetTarget(s.sptg)
e1:SetOperation(s.spop)
c:RegisterEffect(e1)
end
function s.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_DESTROY) and e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function s.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
local g=Duel.GetFieldGroup(tp,LOCATION_HAND,0)
if chk==0 then return #g>0 and g:FilterCount(Card.IsDiscardable,nil)==#g end
Duel.SendtoGrave(g,REASON_COST+REASON_DISCARD)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP)
end
end | 1 | 0.875239 | 1 | 0.875239 | game-dev | MEDIA | 0.976739 | game-dev | 0.9169 | 1 | 0.9169 |
xGinko/AnarchyExploitFixes | 2,244 | AnarchyExploitFixesFolia/src/main/java/me/xginko/aef/modules/dupepreventions/AllayDupe.java | package me.xginko.aef.modules.dupepreventions;
import com.cryptomorin.xseries.XEntityType;
import me.xginko.aef.modules.AEFModule;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDropItemEvent;
import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
public class AllayDupe extends AEFModule implements Listener {
private final boolean dismount;
public AllayDupe() {
super("dupe-preventions.allay-dupe", false, """
Will prevent allays from entering vehicles to prevent a duplication exploit
confirmed working in 1.19.4.""");
this.dismount = config.getBoolean(configPath + ".dismount-premounted-allays", true);
}
@Override
public void enable() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@Override
public void disable() {
HandlerList.unregisterAll(this);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
private void onVehicleEnter(VehicleEnterEvent event) {
if (event.getEntered().getType() == XEntityType.ALLAY.get()) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
private void onEntityPickupItem(EntityPickupItemEvent event) {
if (event.getEntityType() != XEntityType.ALLAY.get()) return;
if (event.getEntity().isInsideVehicle()) {
event.setCancelled(true);
if (dismount)
event.getEntity().getScheduler().execute(plugin, event.getEntity()::leaveVehicle, null, 10);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
private void onEntityDropItem(EntityDropItemEvent event) {
if (event.getEntityType() != XEntityType.ALLAY.get()) return;
if (event.getEntity().isInsideVehicle()) {
event.setCancelled(true);
if (dismount)
event.getEntity().getScheduler().execute(plugin, event.getEntity()::leaveVehicle, null, 10);
}
}
}
| 1 | 0.93719 | 1 | 0.93719 | game-dev | MEDIA | 0.721552 | game-dev | 0.942691 | 1 | 0.942691 |
gta-chaos-mod/ChaosModV | 2,131 | ChaosMod/Util/Player.h | #pragma once
#include "Components/EffectDispatchTimer.h"
#include "Natives.h"
inline void TeleportPlayer(float x, float y, float z, bool noOffset = false)
{
auto playerPed = PLAYER_PED_ID();
bool isInVeh = IS_PED_IN_ANY_VEHICLE(playerPed, false);
bool isInFlyingVeh = IS_PED_IN_FLYING_VEHICLE(playerPed);
auto playerVeh = GET_VEHICLE_PED_IS_IN(playerPed, false);
auto vel = GET_ENTITY_VELOCITY(isInVeh ? playerVeh : playerPed);
float heading = GET_ENTITY_HEADING(isInVeh ? playerVeh : playerPed);
float groundHeight = GET_ENTITY_HEIGHT_ABOVE_GROUND(playerVeh);
float forwardSpeed;
if (isInVeh)
forwardSpeed = GET_ENTITY_SPEED(playerVeh);
if (noOffset)
{
SET_ENTITY_COORDS_NO_OFFSET(isInVeh ? playerVeh : playerPed, x, y, isInFlyingVeh ? z + groundHeight : z, false,
false, false);
}
else
{
SET_ENTITY_COORDS(isInVeh ? playerVeh : playerPed, x, y, isInFlyingVeh ? z + groundHeight : z, false, false,
false, false);
}
SET_ENTITY_HEADING(isInVeh ? playerVeh : playerPed, heading);
SET_ENTITY_VELOCITY(isInVeh ? playerVeh : playerPed, vel.x, vel.y, vel.z);
if (isInVeh)
SET_VEHICLE_FORWARD_SPEED(playerVeh, forwardSpeed);
}
inline void TeleportPlayer(const Vector3 &coords, bool noOffset = false)
{
TeleportPlayer(coords.x, coords.y, coords.z, noOffset);
}
inline void TeleportPlayerFindZ(float x, float y)
{
bool shouldPause = ComponentExists<EffectDispatchTimer>()
&& GetComponent<EffectDispatchTimer>()->IsUsingDistanceBasedDispatch()
&& !GetComponent<EffectDispatchTimer>()->IsTimerPaused();
if (shouldPause)
GetComponent<EffectDispatchTimer>()->SetTimerPaused(true);
float groundZ;
bool useGroundZ;
for (int i = 0; i < 100; i++)
{
float testZ = (i * 10.f) - 100.f;
TeleportPlayer(x, y, testZ);
if (i % 5 == 0)
WAIT(0);
useGroundZ = GET_GROUND_Z_FOR_3D_COORD(x, y, testZ, &groundZ, false, false);
if (useGroundZ)
break;
}
if (shouldPause)
GetComponent<EffectDispatchTimer>()->SetTimerPaused(false);
if (useGroundZ)
TeleportPlayer(x, y, groundZ);
} | 1 | 0.959843 | 1 | 0.959843 | game-dev | MEDIA | 0.982644 | game-dev | 0.960248 | 1 | 0.960248 |
austinmao/reduxity | 1,018 | Assets/Packages/Zenject/Source/Binding/Binders/GameObject/GameObjectGroupNameBinder.cs | #if !NOT_UNITY3D
using System;
using UnityEngine;
namespace Zenject
{
public class GameObjectGroupNameBinder : ConditionBinder
{
public GameObjectGroupNameBinder(BindInfo bindInfo, GameObjectCreationParameters gameObjInfo)
: base(bindInfo)
{
GameObjectInfo = gameObjInfo;
}
protected GameObjectCreationParameters GameObjectInfo
{
get;
private set;
}
public ConditionBinder UnderTransform(Transform parent)
{
GameObjectInfo.ParentTransform = parent;
return this;
}
public ConditionBinder UnderTransform(Func<DiContainer, Transform> parentGetter)
{
GameObjectInfo.ParentTransformGetter = parentGetter;
return this;
}
public ConditionBinder UnderTransformGroup(string transformGroupname)
{
GameObjectInfo.GroupName = transformGroupname;
return this;
}
}
}
#endif
| 1 | 0.833553 | 1 | 0.833553 | game-dev | MEDIA | 0.817408 | game-dev | 0.678719 | 1 | 0.678719 |
MergHQ/CRYENGINE | 3,757 | Code/GameSDK/GameDll/AnimActionAIMovement.h | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
//
////////////////////////////////////////////////////////////////////////////
#ifndef __ANIM_ACTION_AI_MOVEMENT__
#define __ANIM_ACTION_AI_MOVEMENT__
#include "ICryMannequin.h"
#include "IAnimationGraph.h" // for movementcontrolmethod
#include "FragmentVariationHelper.h"
#include "AnimActionAIStance.h"
#include "AnimActionAICoverAction.h"
#include "AnimActionAIDetail.h"
#include "ActorDefinitions.h" // for SAITurnParams
////////////////////////////////////////////////////////////////////////////
struct SAnimActionAIMovementSettings
{
SAnimActionAIMovementSettings()
{}
SAITurnParams turnParams;
};
////////////////////////////////////////////////////////////////////////////
class CAnimActionAIMovement : public TAction<SAnimationContext>
{
friend bool mannequin::UpdateFragmentVariation<CAnimActionAIMovement>(class CAnimActionAIMovement* pAction, class CFragmentVariationHelper* pFragmentVariationHelper, const FragmentID fragmentID, const TagState& requestedFragTags, const bool forceUpdate, const bool trumpSelf);
public:
typedef TAction<SAnimationContext> TBase;
DEFINE_ACTION("AIMovement");
enum EMoveState
{
eMS_None,
eMS_Idle,
eMS_Turn,
eMS_TurnBig,
eMS_Move,
eMS_InAir,
eMS_Count
};
CAnimActionAIMovement(const SAnimActionAIMovementSettings& settings);
// -- IAction Implementation ------------------------------------------------
virtual void Enter() override;
virtual void Exit() override;
virtual void OnInitialise() override;
virtual EStatus Update(float timePassed) override;
virtual EStatus UpdatePending(float timePassed) override;
virtual void OnSequenceFinished(int layer, uint32 scopeID) override;
virtual void OnFragmentStarted() override;
// -- ~IAction Implementation -----------------------------------------------
// TODO: Move these requests and the storage of the actions outside of the movement action.
void RequestStance(CPlayer& player, EStance stance, bool urgent);
void RequestCoverBodyDirection(CPlayer& player, ECoverBodyDirection coverBodyDirection);
void RequestCoverAction(CPlayer& player, const char *actionName);
void CancelCoverAction();
void CancelStanceChange();
private:
EMoveState CalculateState();
EMovementControlMethod CalculatePendingMCM(CPlayer& player) const;
bool IsInCoverStance() const;
bool SetState(const EMoveState newMoveState); // returns true when state changed
bool IsAnimTargetForcingMoveState(CPlayer& player) const;
void RequestMovementDetail(CPlayer& player);
void ClearMovementDetail(CPlayer& player);
bool UpdateFragmentVariation(const bool forceReevaluate, const bool trumpSelf = true);
void SetMovementControlMethod(CPlayer& player);
void ResetMovementControlMethod(CPlayer& player);
CPlayer& GetPlayer() const;
private:
EMoveState m_moveState;
EMoveState m_installedMoveState;
struct SStateInfo
{
SStateInfo()
: m_fragmentID(FRAGMENT_ID_INVALID),
m_MCM(eMCM_Undefined),
m_movementDetail(CAnimActionAIDetail::None)
{
}
FragmentID m_fragmentID;
EMovementControlMethod m_MCM;
enum CAnimActionAIDetail::EMovementDetail m_movementDetail;
};
SStateInfo m_moveStateInfo[eMS_Count];
CTimeValue m_deviatedOrientationTime; // time at which the angle deviation was bigger than a certain threshold angle
const SAnimActionAIMovementSettings& m_settings;
const struct SMannequinAIMovementParams* m_pManParams;
_smart_ptr<CAnimActionAIStance> m_pAnimActionAIStance;
_smart_ptr<CAnimActionAICoverAction> m_pAnimActionAICoverAction;
_smart_ptr<CAnimActionAIChangeCoverBodyDirection> m_pAnimActionAIChangeCoverBodyDirection;
CFragmentVariationHelper m_fragmentVariationHelper;
};
#endif //__ANIM_ACTION_AI_MOVEMENT__
| 1 | 0.950536 | 1 | 0.950536 | game-dev | MEDIA | 0.864304 | game-dev | 0.675741 | 1 | 0.675741 |
PeytonPlayz595/Beta-1.7.3 | 1,309 | src/main/java/net/minecraft/src/NextTickListEntry.java | package net.minecraft.src;
public class NextTickListEntry implements Comparable {
private static long nextTickEntryID = 0L;
public int xCoord;
public int yCoord;
public int zCoord;
public int blockID;
public long scheduledTime;
private long tickEntryID = nextTickEntryID++;
public NextTickListEntry(int var1, int var2, int var3, int var4) {
this.xCoord = var1;
this.yCoord = var2;
this.zCoord = var3;
this.blockID = var4;
}
public boolean equals(Object var1) {
if(!(var1 instanceof NextTickListEntry)) {
return false;
} else {
NextTickListEntry var2 = (NextTickListEntry)var1;
return this.xCoord == var2.xCoord && this.yCoord == var2.yCoord && this.zCoord == var2.zCoord && this.blockID == var2.blockID;
}
}
public int hashCode() {
return (this.xCoord * 128 * 1024 + this.zCoord * 128 + this.yCoord) * 256 + this.blockID;
}
public NextTickListEntry setScheduledTime(long var1) {
this.scheduledTime = var1;
return this;
}
public int comparer(NextTickListEntry var1) {
return this.scheduledTime < var1.scheduledTime ? -1 : (this.scheduledTime > var1.scheduledTime ? 1 : (this.tickEntryID < var1.tickEntryID ? -1 : (this.tickEntryID > var1.tickEntryID ? 1 : 0)));
}
public int compareTo(Object var1) {
return this.comparer((NextTickListEntry)var1);
}
}
| 1 | 0.764767 | 1 | 0.764767 | game-dev | MEDIA | 0.571388 | game-dev | 0.87888 | 1 | 0.87888 |
kwsch/pkNX | 4,960 | pkNX.Randomization/Randomizers/LearnsetRandomizer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using pkNX.Structures;
namespace pkNX.Randomization;
/// <summary>
/// <see cref="Learnset"/> randomizer.
/// </summary>
public class LearnsetRandomizer : Randomizer
{
private readonly Learnset[] Learnsets;
private readonly GameInfo Game;
private readonly IPersonalTable Personal;
private MoveRandomizer moverand;
public IReadOnlyList<IMove> Moves { private get; set; } = [];
public LearnSettings Settings { get; private set; } = new();
public IList<int> BannedMoves { set => moverand.Settings.BannedMoves = value; }
public LearnsetRandomizer(GameInfo game, Learnset[] learnsets, IPersonalTable t)
{
Game = game;
Learnsets = learnsets;
Personal = t;
// temp, overwrite later if using it
moverand = new MoveRandomizer(game, Moves, Personal);
}
private static readonly int[] MetronomeMove = [118];
private static readonly int[] MetronomeLevel = [1];
public void ExecuteMetronome()
{
foreach (var learn in Learnsets)
learn.Update(MetronomeMove, MetronomeLevel);
}
public void ExecuteExpandOnly()
{
foreach (var learn in Learnsets)
{
var count = learn.Count;
if (count == 0)
continue;
if (count >= Settings.ExpandTo)
continue;
int diff = Settings.ExpandTo - count;
var moves = learn.Moves;
Array.Resize(ref moves, Settings.ExpandTo);
var levels = learn.Moves;
Array.Resize(ref levels, Settings.ExpandTo);
for (int i = count; i < Settings.ExpandTo; i++)
{
moves[i] = 1;
levels[i] = Math.Min(100, levels[count - 1] + diff);
}
learn.Update(moves, levels);
}
}
public void Initialize(IMove[] moves, LearnSettings settings, MovesetRandSettings moverandset, int[]? bannedMoves = null)
{
Moves = moves;
Settings = settings;
moverand = new MoveRandomizer(Game, Moves, Personal);
moverand.Initialize(moverandset, bannedMoves ?? []);
}
public override void Execute()
{
for (var i = 0; i < Learnsets.Length; i++)
{
if (Personal[i].HP == 0)
continue;
Randomize(Learnsets[i], i);
}
}
private void Randomize(Learnset set, int index)
{
int[] moves = GetRandomMoves(set.Count, index);
int[] levels = GetRandomLevels(set, moves.Length);
if (Settings.Learn4Level1)
{
for (int i = 0; i < Math.Min(4, levels.Length); ++i)
levels[i] = 1;
}
set.Update(moves, levels);
}
private int[] GetRandomLevels(Learnset set, int count)
{
int[] levels = new int[count];
if (count == 0)
return levels;
if (Settings.Spread)
{
levels[0] = 1;
decimal increment = Settings.SpreadTo / (decimal)count;
for (int i = 1; i < count; i++)
levels[i] = (int)(i * increment);
return levels;
}
if (levels.Length == count && levels.Length == set.Levels.Length)
return set.Levels; // don't modify
var exist = set.Levels;
int lastlevel = Math.Min(1, exist.LastOrDefault());
exist.CopyTo(levels, 0);
for (int i = exist.Length; i < levels.Length; i++)
levels[i] = Math.Max(100, lastlevel + (exist.Length - i + 1));
return levels;
}
private int[] GetRandomMoves(int count, int index)
{
count = Settings.Expand ? Settings.ExpandTo : count;
int[] moves = new int[count];
if (count == 0)
return moves;
moves[0] = Settings.STABFirst ? moverand.GetRandomFirstMove(index) : MoveRandomizer.GetRandomFirstMoveAny();
var rand = moverand.GetRandomLearnset(index, count - 1);
// STAB Moves (if requested) come first; randomize the order of moves
Util.Shuffle(rand);
if (Settings.OrderByPower)
moverand.ReorderMovesPower(rand);
rand.CopyTo(moves, 1);
return moves;
}
internal int[] GetHighPoweredMoves(ushort species, byte form, int count = 4) => GetHighPoweredMoves(Moves, species, form, count);
public int[] GetCurrentMoves(ushort species, byte form, int level, int count = 4)
{
int i = Personal.GetFormIndex(species, form);
var moves = Learnsets[i].GetEncounterMoves(level);
Array.Resize(ref moves, count);
return moves;
}
public int[] GetHighPoweredMoves(IReadOnlyList<IMove> movedata, ushort species, byte form, int count = 4)
{
int index = Personal.GetFormIndex(species, form);
var learn = Learnsets[index];
return learn.GetHighPoweredMoves(count, movedata);
}
}
| 1 | 0.740583 | 1 | 0.740583 | game-dev | MEDIA | 0.701382 | game-dev | 0.933795 | 1 | 0.933795 |
SonicEraZoR/Portal-Base | 54,660 | sp/src/game/server/ai_trackpather.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "trains.h"
#include "ai_trackpather.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define TRACKPATHER_DEBUG_LEADING 1
#define TRACKPATHER_DEBUG_PATH 2
#define TRACKPATHER_DEBUG_TRACKS 3
ConVar g_debug_trackpather( "g_debug_trackpather", "0", FCVAR_CHEAT );
//------------------------------------------------------------------------------
BEGIN_DATADESC( CAI_TrackPather )
DEFINE_FIELD( m_vecDesiredPosition, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_vecGoalOrientation, FIELD_VECTOR ),
DEFINE_FIELD( m_pCurrentPathTarget, FIELD_CLASSPTR ),
DEFINE_FIELD( m_pDestPathTarget, FIELD_CLASSPTR ),
DEFINE_FIELD( m_pLastPathTarget, FIELD_CLASSPTR ),
DEFINE_FIELD( m_pTargetNearestPath, FIELD_CLASSPTR ),
DEFINE_FIELD( m_strCurrentPathName, FIELD_STRING ),
DEFINE_FIELD( m_strDestPathName, FIELD_STRING ),
DEFINE_FIELD( m_strLastPathName, FIELD_STRING ),
DEFINE_FIELD( m_strTargetNearestPathName, FIELD_STRING ),
DEFINE_FIELD( m_vecLastGoalCheckPosition, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_flEnemyPathUpdateTime, FIELD_TIME ),
DEFINE_FIELD( m_bForcedMove, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bPatrolling, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bPatrolBreakable, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bLeading, FIELD_BOOLEAN ),
// Derived class pathing data
DEFINE_FIELD( m_flTargetDistanceThreshold, FIELD_FLOAT ),
DEFINE_FIELD( m_flAvoidDistance, FIELD_FLOAT ),
DEFINE_FIELD( m_flTargetTolerance, FIELD_FLOAT ),
DEFINE_FIELD( m_vecSegmentStartPoint, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_vecSegmentStartSplinePoint, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_bMovingForward, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bChooseFarthestPoint, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flFarthestPathDist, FIELD_FLOAT ),
DEFINE_FIELD( m_flPathMaxSpeed, FIELD_FLOAT ),
DEFINE_FIELD( m_flTargetDistFromPath, FIELD_FLOAT ),
DEFINE_FIELD( m_flLeadDistance, FIELD_FLOAT ),
DEFINE_FIELD( m_vecTargetPathDir, FIELD_VECTOR ),
DEFINE_FIELD( m_vecTargetPathPoint, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_nPauseState, FIELD_INTEGER ),
// Inputs
DEFINE_INPUTFUNC( FIELD_STRING, "SetTrack", InputSetTrack ),
DEFINE_INPUTFUNC( FIELD_STRING, "FlyToSpecificTrackViaPath", InputFlyToPathTrack ),
DEFINE_INPUTFUNC( FIELD_VOID, "StartPatrol", InputStartPatrol ),
DEFINE_INPUTFUNC( FIELD_VOID, "StopPatrol", InputStopPatrol ),
DEFINE_INPUTFUNC( FIELD_VOID, "StartBreakableMovement", InputStartBreakableMovement ),
DEFINE_INPUTFUNC( FIELD_VOID, "StopBreakableMovement", InputStopBreakableMovement ),
DEFINE_INPUTFUNC( FIELD_VOID, "ChooseFarthestPathPoint", InputChooseFarthestPathPoint ),
DEFINE_INPUTFUNC( FIELD_VOID, "ChooseNearestPathPoint", InputChooseNearestPathPoint ),
DEFINE_INPUTFUNC( FIELD_INTEGER,"InputStartLeading", InputStartLeading ),
DEFINE_INPUTFUNC( FIELD_VOID, "InputStopLeading", InputStopLeading ),
// Obsolete, for backwards compatibility
DEFINE_INPUTFUNC( FIELD_VOID, "StartPatrolBreakable", InputStartPatrolBreakable ),
DEFINE_INPUTFUNC( FIELD_STRING, "FlyToPathTrack", InputFlyToPathTrack ),
END_DATADESC()
//-----------------------------------------------------------------------------
// Purpose: Initialize pathing data
//-----------------------------------------------------------------------------
void CAI_TrackPather::InitPathingData( float flTrackArrivalTolerance, float flTargetDistance, float flAvoidDistance )
{
m_flTargetTolerance = flTrackArrivalTolerance;
m_flTargetDistanceThreshold = flTargetDistance;
m_flAvoidDistance = flAvoidDistance;
m_pCurrentPathTarget = NULL;
m_pDestPathTarget = NULL;
m_pLastPathTarget = NULL;
m_pTargetNearestPath = NULL;
m_bLeading = false;
m_flEnemyPathUpdateTime = gpGlobals->curtime;
m_bForcedMove = false;
m_bPatrolling = false;
m_bPatrolBreakable = false;
m_flLeadDistance = 0.0f;
m_bMovingForward = true;
m_vecSegmentStartPoint = m_vecSegmentStartSplinePoint = m_vecDesiredPosition = GetAbsOrigin();
m_bChooseFarthestPoint = true;
m_flFarthestPathDist = 1e10;
m_flPathMaxSpeed = 0;
m_nPauseState = PAUSE_NO_PAUSE;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_TrackPather::OnRestore( void )
{
BaseClass::OnRestore();
// Restore current path
if ( m_strCurrentPathName != NULL_STRING )
{
m_pCurrentPathTarget = (CPathTrack *) gEntList.FindEntityByName( NULL, m_strCurrentPathName );
}
else
{
m_pCurrentPathTarget = NULL;
}
// Restore destination path
if ( m_strDestPathName != NULL_STRING )
{
m_pDestPathTarget = (CPathTrack *) gEntList.FindEntityByName( NULL, m_strDestPathName );
}
else
{
m_pDestPathTarget = NULL;
}
// Restore last path
if ( m_strLastPathName != NULL_STRING )
{
m_pLastPathTarget = (CPathTrack *) gEntList.FindEntityByName( NULL, m_strLastPathName );
}
else
{
m_pLastPathTarget = NULL;
}
// Restore target nearest path
if ( m_strTargetNearestPathName != NULL_STRING )
{
m_pTargetNearestPath = (CPathTrack *) gEntList.FindEntityByName( NULL, m_strTargetNearestPathName );
}
else
{
m_pTargetNearestPath = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_TrackPather::OnSave( IEntitySaveUtils *pUtils )
{
BaseClass::OnSave( pUtils );
// Stash all the paths into strings for restoration later
m_strCurrentPathName = ( m_pCurrentPathTarget != NULL ) ? m_pCurrentPathTarget->GetEntityName() : NULL_STRING;
m_strDestPathName = ( m_pDestPathTarget != NULL ) ? m_pDestPathTarget->GetEntityName() : NULL_STRING;
m_strLastPathName = ( m_pLastPathTarget != NULL ) ? m_pLastPathTarget->GetEntityName() : NULL_STRING;
m_strTargetNearestPathName = ( m_pTargetNearestPath != NULL ) ? m_pTargetNearestPath->GetEntityName() : NULL_STRING;
}
//-----------------------------------------------------------------------------
// Leading distance
//-----------------------------------------------------------------------------
void CAI_TrackPather::EnableLeading( bool bEnable )
{
bool bWasLeading = m_bLeading;
m_bLeading = bEnable;
if ( m_bLeading )
{
m_bPatrolling = false;
}
else if ( bWasLeading )
{
// Going from leading to not leading. Refresh the desired position
// to prevent us from hovering around our old, no longer valid lead position.
if ( m_pCurrentPathTarget )
{
SetDesiredPosition( m_pCurrentPathTarget->GetAbsOrigin() );
}
}
}
void CAI_TrackPather::SetLeadingDistance( float flLeadDistance )
{
m_flLeadDistance = flLeadDistance;
}
float CAI_TrackPather::GetLeadingDistance( ) const
{
return m_flLeadDistance;
}
//-----------------------------------------------------------------------------
// Returns the next path along our current path
//-----------------------------------------------------------------------------
inline CPathTrack *CAI_TrackPather::NextAlongCurrentPath( CPathTrack *pPath ) const
{
return CPathTrack::ValidPath( m_bMovingForward ? pPath->GetNext() : pPath->GetPrevious() );
}
inline CPathTrack *CAI_TrackPather::PreviousAlongCurrentPath( CPathTrack *pPath ) const
{
return CPathTrack::ValidPath( m_bMovingForward ? pPath->GetPrevious() : pPath->GetNext() );
}
inline CPathTrack *CAI_TrackPather::AdjustForMovementDirection( CPathTrack *pPath ) const
{
if ( !m_bMovingForward && CPathTrack::ValidPath( pPath->GetPrevious( ) ) )
{
pPath = CPathTrack::ValidPath( pPath->GetPrevious() );
}
return pPath;
}
//-----------------------------------------------------------------------------
// Enemy visibility check
//-----------------------------------------------------------------------------
CBaseEntity *CAI_TrackPather::FindTrackBlocker( const Vector &vecViewPoint, const Vector &vecTargetPos )
{
trace_t tr;
AI_TraceHull( vecViewPoint, vecTargetPos, -Vector(4,4,4), Vector(4,4,4), MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );
return (tr.fraction != 1.0f) ? tr.m_pEnt : NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &targetPos -
// Output : CBaseEntity
//-----------------------------------------------------------------------------
CPathTrack *CAI_TrackPather::BestPointOnPath( CPathTrack *pPath, const Vector &targetPos, float flAvoidRadius, bool visible, bool bFarthestPoint )
{
// Find the node nearest to the destination path target if a path is not specified
if ( pPath == NULL )
{
pPath = m_pDestPathTarget;
}
// If the path node we're trying to use is not valid, then we're done.
if ( CPathTrack::ValidPath( pPath ) == NULL )
{
//FIXME: Implement
Assert(0);
return NULL;
}
// Our target may be in a vehicle
CBaseEntity *pVehicle = NULL;
CBaseEntity *pTargetEnt = GetTrackPatherTargetEnt();
if ( pTargetEnt != NULL )
{
CBaseCombatCharacter *pCCTarget = pTargetEnt->MyCombatCharacterPointer();
if ( pCCTarget != NULL && pCCTarget->IsInAVehicle() )
{
pVehicle = pCCTarget->GetVehicleEntity();
}
}
// Faster math...
flAvoidRadius *= flAvoidRadius;
// Find the nearest node to the target (going forward)
CPathTrack *pNearestPath = NULL;
float flNearestDist = bFarthestPoint ? 0 : 999999999;
float flPathDist;
float flFarthestDistSqr = ( m_flFarthestPathDist - 2.0f * m_flTargetDistanceThreshold );
flFarthestDistSqr *= flFarthestDistSqr;
// NOTE: Gotta do it this crazy way because paths can be one-way.
for ( int i = 0; i < 2; ++i )
{
int loopCheck = 0;
CPathTrack *pTravPath = pPath;
CPathTrack *pNextPath;
BEGIN_PATH_TRACK_ITERATION();
for ( ; CPathTrack::ValidPath( pTravPath ); pTravPath = pNextPath, loopCheck++ )
{
// Circular loop checking
if ( pTravPath->HasBeenVisited() )
break;
pTravPath->Visit();
pNextPath = (i == 0) ? pTravPath->GetPrevious() : pTravPath->GetNext();
// Find the distance between this test point and our goal point
flPathDist = ( pTravPath->GetAbsOrigin() - targetPos ).LengthSqr();
// See if it's closer and it's also not within our avoidance radius
if ( bFarthestPoint )
{
if ( ( flPathDist <= flNearestDist ) && ( flNearestDist <= flFarthestDistSqr ) )
continue;
}
else
{
if ( flPathDist >= flNearestDist )
continue;
}
// Don't choose points that are within the avoid radius
if ( flAvoidRadius && ( pTravPath->GetAbsOrigin() - targetPos ).Length2DSqr() <= flAvoidRadius )
continue;
if ( visible )
{
// If it has to be visible, run those checks
CBaseEntity *pBlocker = FindTrackBlocker( pTravPath->GetAbsOrigin(), targetPos );
// Check to see if we've hit the target, or the player's vehicle if it's a player in a vehicle
bool bHitTarget = ( pTargetEnt && ( pTargetEnt == pBlocker ) ) ||
( pVehicle && ( pVehicle == pBlocker ) );
// If we hit something, and it wasn't the target or his vehicle, then no dice
// If we hit the target and forced move was set, *still* no dice
if ( (pBlocker != NULL) && ( !bHitTarget || m_bForcedMove ) )
continue;
}
pNearestPath = pTravPath;
flNearestDist = flPathDist;
}
}
return pNearestPath;
}
//-----------------------------------------------------------------------------
// Compute a point n units along a path
//-----------------------------------------------------------------------------
CPathTrack *CAI_TrackPather::ComputeLeadingPointAlongPath( const Vector &vecStartPoint,
CPathTrack *pFirstTrack, float flDistance, Vector *pTarget )
{
bool bMovingForward = (flDistance > 0.0f);
flDistance = fabs(flDistance);
CPathTrack *pTravPath = pFirstTrack;
if ( (!bMovingForward) && pFirstTrack->GetPrevious() )
{
pTravPath = pFirstTrack->GetPrevious();
}
*pTarget = vecStartPoint;
CPathTrack *pNextPath;
// No circular loop checking needed; eventually, it'll run out of distance
for ( ; CPathTrack::ValidPath( pTravPath ); pTravPath = pNextPath )
{
pNextPath = bMovingForward ? pTravPath->GetNext() : pTravPath->GetPrevious();
// Find the distance between this test point and our goal point
float flPathDist = pTarget->DistTo( pTravPath->GetAbsOrigin() );
// Find the distance between this test point and our goal point
if ( flPathDist <= flDistance )
{
flDistance -= flPathDist;
*pTarget = pTravPath->GetAbsOrigin();
if ( !CPathTrack::ValidPath(pNextPath) )
return bMovingForward ? pTravPath : pTravPath->GetNext();
continue;
}
ComputeClosestPoint( *pTarget, flDistance, pTravPath->GetAbsOrigin(), pTarget );
return bMovingForward ? pTravPath : pTravPath->GetNext();
}
return NULL;
}
//-----------------------------------------------------------------------------
// Compute the distance to a particular point on the path
//-----------------------------------------------------------------------------
float CAI_TrackPather::ComputeDistanceAlongPathToPoint( CPathTrack *pStartTrack,
CPathTrack *pDestTrack, const Vector &vecDestPosition, bool bMovingForward )
{
float flTotalDist = 0.0f;
Vector vecPoint;
ClosestPointToCurrentPath( &vecPoint );
CPathTrack *pTravPath = pStartTrack;
CPathTrack *pNextPath, *pTestPath;
BEGIN_PATH_TRACK_ITERATION();
for ( ; CPathTrack::ValidPath( pTravPath ); pTravPath = pNextPath )
{
// Circular loop checking
if ( pTravPath->HasBeenVisited() )
break;
// Mark it as being visited.
pTravPath->Visit();
pNextPath = bMovingForward ? pTravPath->GetNext() : pTravPath->GetPrevious();
pTestPath = pTravPath;
Assert( pTestPath );
if ( pTravPath == pDestTrack )
{
Vector vecDelta;
Vector vecPathDelta;
VectorSubtract( vecDestPosition, vecPoint, vecDelta );
ComputePathDirection( pTravPath, &vecPathDelta );
float flDot = DotProduct( vecDelta, vecPathDelta );
flTotalDist += (flDot > 0.0f ? 1.0f : -1.0f) * vecDelta.Length2D();
break;
}
// NOTE: This would be made more accurate if we did the path direction check here too.
// The starting vecPoint is sometimes *not* within the bounds of the line segment.
// Find the distance between this test point and our goal point
flTotalDist += (bMovingForward ? 1.0f : -1.0f) * vecPoint.AsVector2D().DistTo( pTestPath->GetAbsOrigin().AsVector2D() );
vecPoint = pTestPath->GetAbsOrigin();
}
return flTotalDist;
}
//------------------------------------------------------------------------------
// Track debugging info
//------------------------------------------------------------------------------
void CAI_TrackPather::VisualizeDebugInfo( const Vector &vecNearestPoint, const Vector &vecTarget )
{
if ( g_debug_trackpather.GetInt() == TRACKPATHER_DEBUG_PATH )
{
NDebugOverlay::Line( m_vecSegmentStartPoint, vecTarget, 0, 0, 255, true, 0.1f );
NDebugOverlay::Cross3D( vecNearestPoint, -Vector(16,16,16), Vector(16,16,16), 255, 0, 0, true, 0.1f );
NDebugOverlay::Cross3D( m_pCurrentPathTarget->GetAbsOrigin(), -Vector(16,16,16), Vector(16,16,16), 0, 255, 0, true, 0.1f );
NDebugOverlay::Cross3D( m_vecDesiredPosition, -Vector(16,16,16), Vector(16,16,16), 0, 0, 255, true, 0.1f );
NDebugOverlay::Cross3D( m_pDestPathTarget->GetAbsOrigin(), -Vector(16,16,16), Vector(16,16,16), 255, 255, 255, true, 0.1f );
if ( m_pTargetNearestPath )
{
NDebugOverlay::Cross3D( m_pTargetNearestPath->GetAbsOrigin(), -Vector(24,24,24), Vector(24,24,24), 255, 0, 255, true, 0.1f );
}
}
if ( g_debug_trackpather.GetInt() == TRACKPATHER_DEBUG_TRACKS )
{
if ( m_pCurrentPathTarget )
{
CPathTrack *pPathTrack = m_pCurrentPathTarget;
for ( ; CPathTrack::ValidPath( pPathTrack ); pPathTrack = pPathTrack->GetNext() )
{
NDebugOverlay::Box( pPathTrack->GetAbsOrigin(), -Vector(2,2,2), Vector(2,2,2), 0,255, 0, 8, 0.1 );
if ( CPathTrack::ValidPath( pPathTrack->GetNext() ) )
{
NDebugOverlay::Line( pPathTrack->GetAbsOrigin(), pPathTrack->GetNext()->GetAbsOrigin(), 0,255,0, true, 0.1 );
}
if ( pPathTrack->GetNext() == m_pCurrentPathTarget )
break;
}
}
}
}
//------------------------------------------------------------------------------
// Does this path track have LOS to the target?
//------------------------------------------------------------------------------
bool CAI_TrackPather::HasLOSToTarget( CPathTrack *pTrack )
{
CBaseEntity *pTargetEnt = GetTrackPatherTargetEnt();
if ( !pTargetEnt )
return true;
Vector targetPos;
if ( !GetTrackPatherTarget( &targetPos ) )
return true;
// Translate driver into vehicle for testing
CBaseEntity *pVehicle = NULL;
CBaseCombatCharacter *pCCTarget = pTargetEnt->MyCombatCharacterPointer();
if ( pCCTarget != NULL && pCCTarget->IsInAVehicle() )
{
pVehicle = pCCTarget->GetVehicleEntity();
}
// If it has to be visible, run those checks
CBaseEntity *pBlocker = FindTrackBlocker( pTrack->GetAbsOrigin(), targetPos );
// Check to see if we've hit the target, or the player's vehicle if it's a player in a vehicle
bool bHitTarget = ( pTargetEnt && ( pTargetEnt == pBlocker ) ) ||
( pVehicle && ( pVehicle == pBlocker ) );
return (pBlocker == NULL) || bHitTarget;
}
//------------------------------------------------------------------------------
// Moves to the track
//------------------------------------------------------------------------------
void CAI_TrackPather::UpdateCurrentTarget()
{
// Find the point along the line that we're closest to.
const Vector &vecTarget = m_pCurrentPathTarget->GetAbsOrigin();
Vector vecPoint;
float t = ClosestPointToCurrentPath( &vecPoint );
if ( (t < 1.0f) && ( vecPoint.DistToSqr( vecTarget ) > m_flTargetTolerance * m_flTargetTolerance ) )
goto visualizeDebugInfo;
// Forced move is gone as soon as we've reached the first point on our path
if ( m_bLeading )
{
m_bForcedMove = false;
}
// Trip our "path_track reached" output
if ( m_pCurrentPathTarget != m_pLastPathTarget )
{
// Get the path's specified max speed
m_flPathMaxSpeed = m_pCurrentPathTarget->m_flSpeed;
variant_t emptyVariant;
m_pCurrentPathTarget->AcceptInput( "InPass", this, this, emptyVariant, 0 );
m_pLastPathTarget = m_pCurrentPathTarget;
}
if ( m_nPauseState == PAUSED_AT_POSITION )
return;
if ( m_nPauseState == PAUSE_AT_NEXT_LOS_POSITION )
{
if ( HasLOSToTarget(m_pCurrentPathTarget) )
{
m_nPauseState = PAUSED_AT_POSITION;
return;
}
}
// Update our dest path target, if appropriate...
if ( m_pCurrentPathTarget == m_pDestPathTarget )
{
m_bForcedMove = false;
SelectNewDestTarget();
}
// Did SelectNewDestTarget give us a new point to move to?
if ( m_pCurrentPathTarget != m_pDestPathTarget )
{
// Update to the next path, if there is one...
m_pCurrentPathTarget = NextAlongCurrentPath( m_pCurrentPathTarget );
if ( !m_pCurrentPathTarget )
{
m_pCurrentPathTarget = m_pLastPathTarget;
}
}
else
{
// We're at rest (no patrolling behavior), which means we're moving forward now.
m_bMovingForward = true;
}
SetDesiredPosition( m_pCurrentPathTarget->GetAbsOrigin() );
m_vecSegmentStartSplinePoint = m_vecSegmentStartPoint;
m_vecSegmentStartPoint = m_pLastPathTarget->GetAbsOrigin();
visualizeDebugInfo:
VisualizeDebugInfo( vecPoint, vecTarget );
}
//-----------------------------------------------------------------------------
//
// NOTE: All code below is used exclusively for leading/trailing behavior
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Compute the distance to the leading position
//-----------------------------------------------------------------------------
float CAI_TrackPather::ComputeDistanceToLeadingPosition()
{
return ComputeDistanceAlongPathToPoint( m_pCurrentPathTarget, m_pDestPathTarget, GetDesiredPosition(), m_bMovingForward );
}
//-----------------------------------------------------------------------------
// Compute the distance to the *target* position
//-----------------------------------------------------------------------------
float CAI_TrackPather::ComputeDistanceToTargetPosition()
{
Assert( m_pTargetNearestPath );
CPathTrack *pDest = m_bMovingForward ? m_pTargetNearestPath.Get() : m_pTargetNearestPath->GetPrevious();
if ( !pDest )
{
pDest = m_pTargetNearestPath;
}
bool bMovingForward = IsForwardAlongPath( m_pCurrentPathTarget, pDest );
CPathTrack *pStart = m_pCurrentPathTarget;
if ( bMovingForward != m_bMovingForward )
{
if (bMovingForward)
{
if ( pStart->GetNext() )
{
pStart = pStart->GetNext();
}
if ( pDest->GetNext() )
{
pDest = pDest->GetNext();
}
}
else
{
if ( pStart->GetPrevious() )
{
pStart = pStart->GetPrevious();
}
if ( pDest->GetPrevious() )
{
pDest = pDest->GetPrevious();
}
}
}
return ComputeDistanceAlongPathToPoint( pStart, pDest, m_vecTargetPathPoint, bMovingForward );
}
//-----------------------------------------------------------------------------
// Compute a path direction
//-----------------------------------------------------------------------------
void CAI_TrackPather::ComputePathDirection( CPathTrack *pPath, Vector *pVecPathDir )
{
if ( pPath->GetPrevious() )
{
VectorSubtract( pPath->GetAbsOrigin(), pPath->GetPrevious()->GetAbsOrigin(), *pVecPathDir );
}
else
{
if ( pPath->GetNext() )
{
VectorSubtract( pPath->GetNext()->GetAbsOrigin(), pPath->GetAbsOrigin(), *pVecPathDir );
}
else
{
pVecPathDir->Init( 1, 0, 0 );
}
}
VectorNormalize( *pVecPathDir );
}
//-----------------------------------------------------------------------------
// What's the current path direction?
//-----------------------------------------------------------------------------
void CAI_TrackPather::CurrentPathDirection( Vector *pVecPathDir )
{
if ( m_pCurrentPathTarget )
{
ComputePathDirection( m_pCurrentPathTarget, pVecPathDir );
}
else
{
pVecPathDir->Init( 0, 0, 1 );
}
}
//-----------------------------------------------------------------------------
// Compute a point n units along the current path from our current position
// (but don't pass the desired target point)
//-----------------------------------------------------------------------------
void CAI_TrackPather::ComputePointAlongCurrentPath( float flDistance, float flPerpDist, Vector *pTarget )
{
Vector vecPathDir;
Vector vecStartPoint;
ClosestPointToCurrentPath( &vecStartPoint );
*pTarget = vecStartPoint;
if ( flDistance != 0.0f )
{
Vector vecPrevPoint = vecStartPoint;
CPathTrack *pTravPath = m_pCurrentPathTarget;
CPathTrack *pAdjustedDest = AdjustForMovementDirection( m_pDestPathTarget );
for ( ; CPathTrack::ValidPath( pTravPath ); pTravPath = NextAlongCurrentPath( pTravPath ) )
{
if ( pTravPath == pAdjustedDest )
{
ComputePathDirection( pTravPath, &vecPathDir );
float flPathDist = pTarget->DistTo( GetDesiredPosition() );
if ( flDistance > flPathDist )
{
*pTarget = GetDesiredPosition();
}
else
{
ComputeClosestPoint( *pTarget, flDistance, GetDesiredPosition(), pTarget );
}
break;
}
// Find the distance between this test point and our goal point
float flPathDist = pTarget->DistTo( pTravPath->GetAbsOrigin() );
// Find the distance between this test point and our goal point
if ( flPathDist <= flDistance )
{
flDistance -= flPathDist;
*pTarget = pTravPath->GetAbsOrigin();
// FIXME: Reduce the distance further based on the angle between this segment + the next
continue;
}
ComputePathDirection( pTravPath, &vecPathDir );
ComputeClosestPoint( *pTarget, flDistance, pTravPath->GetAbsOrigin(), pTarget );
break;
}
}
else
{
VectorSubtract( m_pCurrentPathTarget->GetAbsOrigin(), m_vecSegmentStartPoint, vecPathDir );
VectorNormalize( vecPathDir );
}
// Add in the horizontal component
ComputePointFromPerpDistance( *pTarget, vecPathDir, flPerpDist, pTarget );
}
//-----------------------------------------------------------------------------
// Methods to find a signed perp distance from the track
// and to compute a point off the path based on the signed perp distance
//-----------------------------------------------------------------------------
float CAI_TrackPather::ComputePerpDistanceFromPath( const Vector &vecPointOnPath, const Vector &vecPathDir, const Vector &vecPointOffPath )
{
// Make it be a signed distance of the target from the path
// Positive means on the right side, negative means on the left side
Vector vecAcross, vecDelta;
CrossProduct( vecPathDir, Vector( 0, 0, 1 ), vecAcross );
VectorSubtract( vecPointOffPath, vecPointOnPath, vecDelta );
VectorMA( vecDelta, -DotProduct( vecPathDir, vecDelta ), vecPathDir, vecDelta );
float flDistanceFromPath = vecDelta.Length2D();
if ( DotProduct2D( vecAcross.AsVector2D(), vecDelta.AsVector2D() ) < 0.0f )
{
flDistanceFromPath *= -1.0f;
}
return flDistanceFromPath;
}
void CAI_TrackPather::ComputePointFromPerpDistance( const Vector &vecPointOnPath, const Vector &vecPathDir, float flPerpDist, Vector *pResult )
{
Vector vecAcross;
CrossProduct( vecPathDir, Vector( 0, 0, 1 ), vecAcross );
VectorMA( vecPointOnPath, flPerpDist, vecAcross, *pResult );
}
//-----------------------------------------------------------------------------
// Finds the closest point on the path, returns a signed perpendicular distance
// where negative means on the left side of the path (when travelled from prev to next)
// and positive means on the right side
//-----------------------------------------------------------------------------
CPathTrack *CAI_TrackPather::FindClosestPointOnPath( CPathTrack *pPath,
const Vector &targetPos, Vector *pVecClosestPoint, Vector *pVecPathDir, float *pDistanceFromPath )
{
// Find the node nearest to the destination path target if a path is not specified
if ( pPath == NULL )
{
pPath = m_pDestPathTarget;
}
// If the path node we're trying to use is not valid, then we're done.
if ( CPathTrack::ValidPath( pPath ) == NULL )
{
//FIXME: Implement
Assert(0);
return NULL;
}
// Find the nearest node to the target (going forward)
CPathTrack *pNearestPath = NULL;
float flNearestDist2D = 999999999;
float flNearestDist = 999999999;
float flPathDist, flPathDist2D;
// NOTE: Gotta do it this crazy way because paths can be one-way.
Vector vecNearestPoint;
Vector vecNearestPathSegment;
for ( int i = 0; i < 2; ++i )
{
int loopCheck = 0;
CPathTrack *pTravPath = pPath;
CPathTrack *pNextPath;
BEGIN_PATH_TRACK_ITERATION();
for ( ; CPathTrack::ValidPath( pTravPath ); pTravPath = pNextPath, loopCheck++ )
{
// Circular loop checking
if ( pTravPath->HasBeenVisited() )
break;
// Mark it as being visited.
pTravPath->Visit();
pNextPath = (i == 0) ? pTravPath->GetPrevious() : pTravPath->GetNext();
// No alt paths allowed in leading mode.
if ( pTravPath->m_paltpath )
{
Warning( "%s: Alternative paths in path_track not allowed when using the leading behavior!\n", GetEntityName().ToCStr() );
}
// Need line segments
if ( !CPathTrack::ValidPath(pNextPath) )
break;
// Find the closest point on the line segment on the path
Vector vecClosest;
CalcClosestPointOnLineSegment( targetPos, pTravPath->GetAbsOrigin(), pNextPath->GetAbsOrigin(), vecClosest );
// Find the distance between this test point and our goal point
flPathDist2D = vecClosest.AsVector2D().DistToSqr( targetPos.AsVector2D() );
if ( flPathDist2D > flNearestDist2D )
continue;
flPathDist = vecClosest.z - targetPos.z;
flPathDist *= flPathDist;
flPathDist += flPathDist2D;
if (( flPathDist2D == flNearestDist2D ) && ( flPathDist >= flNearestDist ))
continue;
pNearestPath = (i == 0) ? pTravPath : pNextPath;
flNearestDist2D = flPathDist2D;
flNearestDist = flPathDist;
vecNearestPoint = vecClosest;
VectorSubtract( pNextPath->GetAbsOrigin(), pTravPath->GetAbsOrigin(), vecNearestPathSegment );
if ( i == 0 )
{
vecNearestPathSegment *= -1.0f;
}
}
}
VectorNormalize( vecNearestPathSegment );
*pDistanceFromPath = ComputePerpDistanceFromPath( vecNearestPoint, vecNearestPathSegment, targetPos );
*pVecClosestPoint = vecNearestPoint;
*pVecPathDir = vecNearestPathSegment;
return pNearestPath;
}
//-----------------------------------------------------------------------------
// Breakable paths?
//-----------------------------------------------------------------------------
void CAI_TrackPather::InputStartBreakableMovement( inputdata_t &inputdata )
{
m_bPatrolBreakable = true;
}
void CAI_TrackPather::InputStopBreakableMovement( inputdata_t &inputdata )
{
m_bPatrolBreakable = false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CAI_TrackPather::InputStartPatrol( inputdata_t &inputdata )
{
m_bPatrolling = true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CAI_TrackPather::InputStopPatrol( inputdata_t &inputdata )
{
m_bPatrolling = false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CAI_TrackPather::InputStartPatrolBreakable( inputdata_t &inputdata )
{
m_bPatrolBreakable = true;
m_bPatrolling = true;
}
//------------------------------------------------------------------------------
// Leading behaviors
//------------------------------------------------------------------------------
void CAI_TrackPather::InputStartLeading( inputdata_t &inputdata )
{
EnableLeading( true );
SetLeadingDistance( inputdata.value.Int() );
}
void CAI_TrackPather::InputStopLeading( inputdata_t &inputdata )
{
EnableLeading( false );
}
//------------------------------------------------------------------------------
// Selects a new destination target
//------------------------------------------------------------------------------
void CAI_TrackPather::SelectNewDestTarget()
{
if ( !m_bPatrolling )
return;
// NOTE: This version is bugged, but I didn't want to make the fix
// here for fear of breaking a lot of maps late in the day.
// So, only the chopper does the "right" thing.
#ifdef HL2_EPISODIC
// Episodic uses the fixed logic for all trackpathers
if ( 1 )
#else
if ( ShouldUseFixedPatrolLogic() )
#endif
{
CPathTrack *pOldDest = m_pDestPathTarget;
// Only switch polarity of movement if we're at the *end* of the path
// This is really useful for initial conditions of patrolling
// NOTE: We've got to do some extra work for circular paths
bool bIsCircular = false;
{
BEGIN_PATH_TRACK_ITERATION();
CPathTrack *pTravPath = m_pDestPathTarget;
while( CPathTrack::ValidPath( pTravPath ) )
{
// Circular loop checking
if ( pTravPath->HasBeenVisited() )
{
bIsCircular = true;
break;
}
pTravPath->Visit();
pTravPath = NextAlongCurrentPath( pTravPath );
}
}
if ( bIsCircular || (NextAlongCurrentPath( m_pDestPathTarget ) == NULL) )
{
m_bMovingForward = !m_bMovingForward;
}
BEGIN_PATH_TRACK_ITERATION();
while ( true )
{
CPathTrack *pNextTrack = NextAlongCurrentPath( m_pDestPathTarget );
if ( !pNextTrack || (pNextTrack == pOldDest) || pNextTrack->HasBeenVisited() )
break;
pNextTrack->Visit();
m_pDestPathTarget = pNextTrack;
}
}
else
{
CPathTrack *pOldDest = m_pDestPathTarget;
// For patrolling, switch the polarity of movement
m_bMovingForward = !m_bMovingForward;
int loopCount = 0;
while ( true )
{
CPathTrack *pNextTrack = NextAlongCurrentPath( m_pDestPathTarget );
if ( !pNextTrack )
break;
if ( ++loopCount > 1024 )
{
DevMsg(1,"WARNING: Looping path for %s\n", GetDebugName() );
break;
}
m_pDestPathTarget = pNextTrack;
}
if ( m_pDestPathTarget == pOldDest )
{
// This can occur if we move to the first point on the path
SelectNewDestTarget();
}
}
}
//------------------------------------------------------------------------------
// Moves to the track
//------------------------------------------------------------------------------
void CAI_TrackPather::UpdateCurrentTargetLeading()
{
bool bRestingAtDest = false;
CPathTrack *pAdjustedDest;
// Find the point along the line that we're closest to.
const Vector &vecTarget = m_pCurrentPathTarget->GetAbsOrigin();
Vector vecPoint;
float t = ClosestPointToCurrentPath( &vecPoint );
if ( (t < 1.0f) && ( vecPoint.DistToSqr( vecTarget ) > m_flTargetTolerance * m_flTargetTolerance ) )
goto visualizeDebugInfo;
// Trip our "path_track reached" output
if ( m_pCurrentPathTarget != m_pLastPathTarget )
{
// Get the path's specified max speed
m_flPathMaxSpeed = m_pCurrentPathTarget->m_flSpeed;
variant_t emptyVariant;
m_pCurrentPathTarget->AcceptInput( "InPass", this, this, emptyVariant, 0 );
m_pLastPathTarget = m_pCurrentPathTarget;
}
// NOTE: CurrentPathTarget doesn't mean the same thing as dest path target!
// It's the "next"most when moving forward + "prev"most when moving backward
// Must do the tests in the same space
pAdjustedDest = AdjustForMovementDirection( m_pDestPathTarget );
// Update our dest path target, if appropriate...
if ( m_pCurrentPathTarget == pAdjustedDest )
{
m_bForcedMove = false;
SelectNewDestTarget();
// NOTE: Must do this again since SelectNewDestTarget may change m_pDestPathTarget
pAdjustedDest = AdjustForMovementDirection( m_pDestPathTarget );
}
if ( m_pCurrentPathTarget != pAdjustedDest )
{
// Update to the next path, if there is one...
m_pCurrentPathTarget = NextAlongCurrentPath( m_pCurrentPathTarget );
if ( !m_pCurrentPathTarget )
{
m_pCurrentPathTarget = m_pLastPathTarget;
}
}
else
{
// NOTE: Have to do this here because the NextAlongCurrentPath call above
// could make m_pCurrentPathTarget == m_pDestPathTarget.
// In this case, we're at rest (no patrolling behavior)
bRestingAtDest = true;
}
if ( bRestingAtDest )
{
// NOTE: Must use current path target, instead of dest
// to get the PreviousAlongCurrentPath working correctly
CPathTrack *pSegmentStart = PreviousAlongCurrentPath( m_pCurrentPathTarget );
if ( !pSegmentStart )
{
pSegmentStart = m_pCurrentPathTarget;
}
m_vecSegmentStartPoint = pSegmentStart->GetAbsOrigin();
}
else
{
m_vecSegmentStartPoint = m_pLastPathTarget->GetAbsOrigin();
}
visualizeDebugInfo:
VisualizeDebugInfo( vecPoint, vecTarget );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_TrackPather::UpdateTargetPositionLeading( void )
{
Vector targetPos;
if ( !GetTrackPatherTarget( &targetPos ) )
return;
// NOTE: FindClosestPointOnPath *always* returns the point on the "far",
// end of the line segment containing the closest point (namely the 'next'
// track, as opposed to the 'prev' track)
Vector vecClosestPoint, vecPathDir;
float flTargetDistanceFromPath;
CPathTrack *pNextPath = FindClosestPointOnPath( m_pCurrentPathTarget,
targetPos, &vecClosestPoint, &vecPathDir, &flTargetDistanceFromPath );
// This means that a valid path could not be found to our target!
if ( CPathTrack::ValidPath( pNextPath ) == NULL )
return;
// NDebugOverlay::Cross3D( vecClosestPoint, -Vector(24,24,24), Vector(24,24,24), 0, 255, 255, true, 0.1f );
// NDebugOverlay::Cross3D( pNextPath->GetAbsOrigin(), -Vector(24,24,24), Vector(24,24,24), 255, 255, 0, true, 0.1f );
// Here's how far we are from the path
m_flTargetDistFromPath = flTargetDistanceFromPath;
m_vecTargetPathDir = vecPathDir;
// Here's info about where the target is along the path
m_vecTargetPathPoint = vecClosestPoint;
m_pTargetNearestPath = pNextPath;
// Find the best position to be on our path
// NOTE: This will *also* return a path track on the "far" end of the line segment
// containing the leading position, namely the "next" end of the segment as opposed
// to the "prev" end of the segment.
CPathTrack *pDest = ComputeLeadingPointAlongPath( vecClosestPoint, pNextPath, m_flLeadDistance, &targetPos );
SetDesiredPosition( targetPos );
// We only want to switch movement directions when absolutely necessary
// so convert dest into a more appropriate value based on the current movement direction
if ( pDest != m_pDestPathTarget )
{
// NOTE: This is really tricky + subtle
// For leading, we don't want to ever change direction when the current target == the
// adjusted destination target. Namely, if we're going forward, both dest + curr
// mean the "next"most node so we can compare them directly against eath other.
// If we're moving backward, dest means "next"most, but curr means "prev"most.
// We first have to adjust the dest to mean "prev"most, and then do the comparison.
// If the adjusted dest == curr, then maintain direction. Otherwise, use the forward along path test.
bool bMovingForward = m_bMovingForward;
CPathTrack *pAdjustedDest = AdjustForMovementDirection( pDest );
if ( m_pCurrentPathTarget != pAdjustedDest )
{
bMovingForward = IsForwardAlongPath( m_pCurrentPathTarget, pAdjustedDest );
}
if ( bMovingForward != m_bMovingForward )
{
// As a result of the tricky note above, this should never occur
Assert( pAdjustedDest != m_pCurrentPathTarget );
// Oops! Need to reverse direction
m_bMovingForward = bMovingForward;
m_vecSegmentStartPoint = m_pCurrentPathTarget->GetAbsOrigin();
m_pCurrentPathTarget = NextAlongCurrentPath( m_pCurrentPathTarget );
}
m_pDestPathTarget = pDest;
}
// NDebugOverlay::Cross3D( m_pCurrentPathTarget->GetAbsOrigin(), -Vector(36,36,36), Vector(36,36,36), 255, 0, 0, true, 0.1f );
// NDebugOverlay::Cross3D( m_pDestPathTarget->GetAbsOrigin(), -Vector(48,48,48), Vector(48,48,48), 0, 255, 0, true, 0.1f );
// NDebugOverlay::Cross3D( targetPos, -Vector(36,36,36), Vector(36,36,36), 0, 0, 255, true, 0.1f );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_TrackPather::UpdateTargetPosition( void )
{
// Don't update our target if we're being told to go somewhere
if ( m_bForcedMove && !m_bPatrolBreakable )
return;
// Don't update our target if we're patrolling
if ( m_bPatrolling )
{
// If we have an enemy, and our patrol is breakable, stop patrolling
if ( !m_bPatrolBreakable || !GetEnemy() )
return;
m_bPatrolling = false;
}
Vector targetPos;
if ( !GetTrackPatherTarget( &targetPos ) )
return;
// Not time to update again
if ( m_flEnemyPathUpdateTime > gpGlobals->curtime )
return;
// See if the target has moved enough to make us recheck
float flDistSqr = ( targetPos - m_vecLastGoalCheckPosition ).LengthSqr();
if ( flDistSqr < m_flTargetDistanceThreshold * m_flTargetDistanceThreshold )
return;
// Find the best position to be on our path
CPathTrack *pDest = BestPointOnPath( m_pCurrentPathTarget, targetPos, m_flAvoidDistance, true, m_bChooseFarthestPoint );
if ( CPathTrack::ValidPath( pDest ) == NULL )
{
// This means that a valid path could not be found to our target!
// Assert(0);
return;
}
if ( pDest != m_pDestPathTarget )
{
// This is our new destination
bool bMovingForward = IsForwardAlongPath( m_pCurrentPathTarget, pDest );
if ( bMovingForward != m_bMovingForward )
{
// Oops! Need to reverse direction
m_bMovingForward = bMovingForward;
if ( pDest != m_pCurrentPathTarget )
{
SetupNewCurrentTarget( NextAlongCurrentPath( m_pCurrentPathTarget ) );
}
}
m_pDestPathTarget = pDest;
}
// Keep this goal point for comparisons later
m_vecLastGoalCheckPosition = targetPos;
// Only do this on set intervals
m_flEnemyPathUpdateTime = gpGlobals->curtime + 1.0f;
}
//------------------------------------------------------------------------------
// Returns the direction of the path at the closest point to the target
//------------------------------------------------------------------------------
const Vector &CAI_TrackPather::TargetPathDirection() const
{
return m_vecTargetPathDir;
}
const Vector &CAI_TrackPather::TargetPathAcrossDirection() const
{
static Vector s_Result;
CrossProduct( m_vecTargetPathDir, Vector( 0, 0, 1 ), s_Result );
return s_Result;
}
//------------------------------------------------------------------------------
// Returns the speed of the target relative to the path
//------------------------------------------------------------------------------
float CAI_TrackPather::TargetSpeedAlongPath() const
{
if ( !GetEnemy() || !IsLeading() )
return 0.0f;
Vector vecSmoothedVelocity = GetEnemy()->GetSmoothedVelocity();
return DotProduct( vecSmoothedVelocity, TargetPathDirection() );
}
//------------------------------------------------------------------------------
// Returns the speed of the target *across* the path
//------------------------------------------------------------------------------
float CAI_TrackPather::TargetSpeedAcrossPath() const
{
if ( !GetEnemy() || !IsLeading() )
return 0.0f;
Vector vecSmoothedVelocity = GetEnemy()->GetSmoothedVelocity();
return DotProduct( vecSmoothedVelocity, TargetPathAcrossDirection() );
}
//------------------------------------------------------------------------------
// Returns the max distance we can be from the path
//------------------------------------------------------------------------------
float CAI_TrackPather::MaxDistanceFromCurrentPath() const
{
if ( !IsLeading() || !m_pCurrentPathTarget )
return 0.0f;
CPathTrack *pPrevPath = PreviousAlongCurrentPath( m_pCurrentPathTarget );
if ( !pPrevPath )
{
pPrevPath = m_pCurrentPathTarget;
}
// NOTE: Can't use m_vecSegmentStartPoint because we don't have a radius defined for it
float t;
Vector vecTemp;
CalcClosestPointOnLine( GetAbsOrigin(), pPrevPath->GetAbsOrigin(),
m_pCurrentPathTarget->GetAbsOrigin(), vecTemp, &t );
t = clamp( t, 0.0f, 1.0f );
float flRadius = (1.0f - t) * pPrevPath->GetRadius() + t * m_pCurrentPathTarget->GetRadius();
return flRadius;
}
//------------------------------------------------------------------------------
// Purpose : A different version of the track pather which is more explicit about
// the meaning of dest, current, and prev path points
//------------------------------------------------------------------------------
void CAI_TrackPather::UpdateTrackNavigation( void )
{
// No target? Use the string specified. We have no spawn method (sucky!!) so this is how that works
if ( ( CPathTrack::ValidPath( m_pDestPathTarget ) == NULL ) && ( m_target != NULL_STRING ) )
{
FlyToPathTrack( m_target );
m_target = NULL_STRING;
}
if ( !IsLeading() )
{
if ( !m_pCurrentPathTarget )
return;
// Updates our destination node if we're tracking something
UpdateTargetPosition();
// Move along our path towards our current destination
UpdateCurrentTarget();
}
else
{
// Updates our destination position if we're leading something
UpdateTargetPositionLeading();
// Move along our path towards our current destination
UpdateCurrentTargetLeading();
}
}
//------------------------------------------------------------------------------
// Sets the farthest path distance
//------------------------------------------------------------------------------
void CAI_TrackPather::SetFarthestPathDist( float flMaxPathDist )
{
m_flFarthestPathDist = flMaxPathDist;
}
//------------------------------------------------------------------------------
// Sets up a new current path target
//------------------------------------------------------------------------------
void CAI_TrackPather::SetupNewCurrentTarget( CPathTrack *pTrack )
{
Assert( pTrack );
m_vecSegmentStartPoint = GetAbsOrigin();
VectorMA( m_vecSegmentStartPoint, -2.0f, GetAbsVelocity(), m_vecSegmentStartSplinePoint );
m_pCurrentPathTarget = pTrack;
SetDesiredPosition( m_pCurrentPathTarget->GetAbsOrigin() );
}
//------------------------------------------------------------------------------
// Moves to an explicit track point
//------------------------------------------------------------------------------
void CAI_TrackPather::MoveToTrackPoint( CPathTrack *pTrack )
{
if ( IsOnSameTrack( pTrack, m_pDestPathTarget ) )
{
// The track must be valid
if ( CPathTrack::ValidPath( pTrack ) == NULL )
return;
m_pDestPathTarget = pTrack;
m_bMovingForward = IsForwardAlongPath( m_pCurrentPathTarget, pTrack );
m_bForcedMove = true;
}
else
{
CPathTrack *pClosestTrack = BestPointOnPath( pTrack, WorldSpaceCenter(), 0.0f, false, false );
// The track must be valid
if ( CPathTrack::ValidPath( pClosestTrack ) == NULL )
return;
SetupNewCurrentTarget( pClosestTrack );
m_pDestPathTarget = pTrack;
m_bMovingForward = IsForwardAlongPath( pClosestTrack, pTrack );
m_bForcedMove = true;
}
}
//------------------------------------------------------------------------------
// Moves to the closest track point
//------------------------------------------------------------------------------
void CAI_TrackPather::MoveToClosestTrackPoint( CPathTrack *pTrack )
{
if ( IsOnSameTrack( pTrack, m_pDestPathTarget ) )
return;
CPathTrack *pClosestTrack = BestPointOnPath( pTrack, WorldSpaceCenter(), 0.0f, false, false );
// The track must be valid
if ( CPathTrack::ValidPath( pClosestTrack ) == NULL )
return;
SetupNewCurrentTarget( pClosestTrack );
m_pDestPathTarget = pClosestTrack;
m_bMovingForward = true;
// Force us to switch tracks if we're leading
if ( IsLeading() )
{
m_bForcedMove = true;
}
}
//-----------------------------------------------------------------------------
// Are the two path tracks connected?
//-----------------------------------------------------------------------------
bool CAI_TrackPather::IsOnSameTrack( CPathTrack *pPath1, CPathTrack *pPath2 ) const
{
if ( pPath1 == pPath2 )
return true;
{
BEGIN_PATH_TRACK_ITERATION();
CPathTrack *pTravPath = pPath1->GetPrevious();
while( CPathTrack::ValidPath( pTravPath ) && (pTravPath != pPath1) )
{
// Circular loop checking
if ( pTravPath->HasBeenVisited() )
break;
pTravPath->Visit();
if ( pTravPath == pPath2 )
return true;
pTravPath = pTravPath->GetPrevious();
}
}
{
BEGIN_PATH_TRACK_ITERATION();
CPathTrack *pTravPath = pPath1->GetNext();
while( CPathTrack::ValidPath( pTravPath ) && (pTravPath != pPath1) )
{
// Circular loop checking
if ( pTravPath->HasBeenVisited() )
break;
pTravPath->Visit();
if ( pTravPath == pPath2 )
return true;
pTravPath = pTravPath->GetNext();
}
}
return false;
}
//-----------------------------------------------------------------------------
// Deal with teleportation
//-----------------------------------------------------------------------------
void CAI_TrackPather::Teleported()
{
// This updates the paths so they are reasonable
CPathTrack *pClosestTrack = BestPointOnPath( GetDestPathTarget(), WorldSpaceCenter(), 0.0f, false, false );
m_pDestPathTarget = NULL;
MoveToClosestTrackPoint( pClosestTrack );
}
//-----------------------------------------------------------------------------
// Returns distance along path to target, returns FLT_MAX if there's no path
//-----------------------------------------------------------------------------
float CAI_TrackPather::ComputePathDistance( CPathTrack *pPath, CPathTrack *pDest, bool bForward ) const
{
float flDist = 0.0f;
CPathTrack *pLast = pPath;
BEGIN_PATH_TRACK_ITERATION();
while ( CPathTrack::ValidPath( pPath ) )
{
// Ciruclar loop checking
if ( pPath->HasBeenVisited() )
return FLT_MAX;
pPath->Visit();
flDist += pLast->GetAbsOrigin().DistTo( pPath->GetAbsOrigin() );
if ( pDest == pPath )
return flDist;
pLast = pPath;
pPath = bForward ? pPath->GetNext() : pPath->GetPrevious();
}
return FLT_MAX;
}
//-----------------------------------------------------------------------------
// Is pPathTest in "front" of pPath on the same path? (Namely, does GetNext() get us there?)
//-----------------------------------------------------------------------------
bool CAI_TrackPather::IsForwardAlongPath( CPathTrack *pPath, CPathTrack *pPathTest ) const
{
// Also, in the case of looping paths, we want to return the shortest path
float flForwardDist = ComputePathDistance( pPath, pPathTest, true );
float flReverseDist = ComputePathDistance( pPath, pPathTest, false );
Assert( ( flForwardDist != FLT_MAX ) || ( flReverseDist != FLT_MAX ) );
return ( flForwardDist <= flReverseDist );
}
//-----------------------------------------------------------------------------
// Computes distance + nearest point from the current path..
//-----------------------------------------------------------------------------
float CAI_TrackPather::ClosestPointToCurrentPath( Vector *pVecPoint ) const
{
if (!m_pCurrentPathTarget)
{
*pVecPoint = GetAbsOrigin();
return 0;
}
float t;
CalcClosestPointOnLine( GetAbsOrigin(), m_vecSegmentStartPoint,
m_pCurrentPathTarget->GetAbsOrigin(), *pVecPoint, &t );
return t;
}
//-----------------------------------------------------------------------------
// Computes a "path" velocity at a particular point along the current path
//-----------------------------------------------------------------------------
void CAI_TrackPather::ComputePathTangent( float t, Vector *pVecTangent ) const
{
CPathTrack *pNextTrack = NextAlongCurrentPath(m_pCurrentPathTarget);
if ( !pNextTrack )
{
pNextTrack = m_pCurrentPathTarget;
}
t = clamp( t, 0.0f, 1.0f );
pVecTangent->Init(0,0,0);
Catmull_Rom_Spline_Tangent( m_vecSegmentStartSplinePoint, m_vecSegmentStartPoint,
m_pCurrentPathTarget->GetAbsOrigin(), pNextTrack->GetAbsOrigin(), t, *pVecTangent );
VectorNormalize( *pVecTangent );
}
//-----------------------------------------------------------------------------
// Computes the *normalized* velocity at which the helicopter should approach the final point
//-----------------------------------------------------------------------------
void CAI_TrackPather::ComputeNormalizedDestVelocity( Vector *pVecVelocity ) const
{
if ( m_nPauseState != PAUSE_NO_PAUSE )
{
pVecVelocity->Init(0,0,0);
return;
}
CPathTrack *pNextTrack = NextAlongCurrentPath(m_pCurrentPathTarget);
if ( !pNextTrack )
{
pNextTrack = m_pCurrentPathTarget;
}
if ( ( pNextTrack == m_pCurrentPathTarget ) || ( m_pCurrentPathTarget == m_pDestPathTarget ) )
{
pVecVelocity->Init(0,0,0);
return;
}
VectorSubtract( pNextTrack->GetAbsOrigin(), m_pCurrentPathTarget->GetAbsOrigin(), *pVecVelocity );
VectorNormalize( *pVecVelocity );
// Slow it down if we're approaching a sharp corner
Vector vecDelta;
VectorSubtract( m_pCurrentPathTarget->GetAbsOrigin(), m_vecSegmentStartPoint, vecDelta );
VectorNormalize( vecDelta );
float flDot = DotProduct( *pVecVelocity, vecDelta );
*pVecVelocity *= clamp( flDot, 0.0f, 1.0f );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CAI_TrackPather::SetTrack( CBaseEntity *pGoalEnt )
{
// Ignore this input if we're *already* on that path.
CPathTrack *pTrack = dynamic_cast<CPathTrack *>(pGoalEnt);
if ( !pTrack )
{
DevWarning( "%s: Specified entity '%s' must be a path_track!\n", pGoalEnt->GetClassname(), pGoalEnt->GetEntityName().ToCStr() );
return;
}
MoveToClosestTrackPoint( pTrack );
}
void CAI_TrackPather::SetTrack( string_t strTrackName )
{
// Find our specified target
CBaseEntity *pGoalEnt = gEntList.FindEntityByName( NULL, strTrackName );
if ( pGoalEnt == NULL )
{
DevWarning( "%s: Could not find path_track '%s'!\n", GetClassname(), STRING( strTrackName ) );
return;
}
SetTrack( pGoalEnt );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CAI_TrackPather::InputSetTrack( inputdata_t &inputdata )
{
string_t strTrackName = MAKE_STRING( inputdata.value.String() );
SetTrack( MAKE_STRING( inputdata.value.String() ) );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : strTrackName -
//-----------------------------------------------------------------------------
void CAI_TrackPather::FlyToPathTrack( string_t strTrackName )
{
CBaseEntity *pGoalEnt = gEntList.FindEntityByName( NULL, strTrackName );
if ( pGoalEnt == NULL )
{
DevWarning( "%s: Could not find path_track '%s'!\n", GetClassname(), STRING( strTrackName ) );
return;
}
// Ignore this input if we're *already* on that path.
CPathTrack *pTrack = dynamic_cast<CPathTrack *>(pGoalEnt);
if ( !pTrack )
{
DevWarning( "%s: Specified entity '%s' must be a path_track!\n", GetClassname(), STRING( strTrackName ) );
return;
}
// Find our specified target
MoveToTrackPoint( pTrack );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CAI_TrackPather::InputFlyToPathTrack( inputdata_t &inputdata )
{
// Find our specified target
string_t strTrackName = MAKE_STRING( inputdata.value.String() );
m_nPauseState = PAUSE_NO_PAUSE;
FlyToPathTrack( strTrackName );
}
//-----------------------------------------------------------------------------
// Changes the mode used to determine which path point to move to
//-----------------------------------------------------------------------------
void CAI_TrackPather::InputChooseFarthestPathPoint( inputdata_t &inputdata )
{
UseFarthestPathPoint( true );
}
void CAI_TrackPather::InputChooseNearestPathPoint( inputdata_t &inputdata )
{
UseFarthestPathPoint( false );
}
void CAI_TrackPather::UseFarthestPathPoint( bool useFarthest )
{
m_bChooseFarthestPoint = useFarthest;
}
| 1 | 0.921152 | 1 | 0.921152 | game-dev | MEDIA | 0.958054 | game-dev | 0.967632 | 1 | 0.967632 |
Team-Immersive-Intelligence/ImmersiveIntelligence | 3,437 | src/main/java/pl/pabilo8/immersiveintelligence/common/entity/hans/tasks/hand_weapon/AIHansAssaultRifle.java | package pl.pabilo8.immersiveintelligence.common.entity.hans.tasks.hand_weapon;
import blusunrize.immersiveengineering.common.util.ItemNBTHelper;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import pl.pabilo8.immersiveintelligence.api.ammo.utils.IIAmmoUtils;
import pl.pabilo8.immersiveintelligence.common.IIContent;
import pl.pabilo8.immersiveintelligence.common.entity.EntityHans;
import pl.pabilo8.immersiveintelligence.common.item.weapons.ItemIIAssaultRifle;
import pl.pabilo8.immersiveintelligence.common.util.entity.IIEntityUtils;
/**
* @author Pabilo8 (pabilo@iiteam.net)
* @since 23.04.2021
*/
public class AIHansAssaultRifle extends AIHansHandWeapon
{
/**
* For how many ticks should the Hans shoot the stg in a burst.
*/
private final int burstTime;
/**
* A decrementing tick that spawns a ranged attack once this value reaches 0. It is then set back to the
* maxRangedAttackTime.
*/
private int rangedAttackTime;
public AIHansAssaultRifle(EntityHans hans)
{
super(hans, 4, 25, 1f);
this.rangedAttackTime = -1;
this.burstTime = 4;
}
@Override
protected boolean hasAnyAmmo()
{
final ItemStack stg = getWeapon();
final ItemStack magazine = ItemNBTHelper.getItemStack(stg, "magazine");
return hans.hasAmmo||IIContent.itemAssaultRifle.isAmmo(magazine, stg)||!IIContent.itemAssaultRifle.findAmmo(hans, stg).isEmpty();
}
@Override
protected boolean isValidWeapon()
{
return getWeapon().getItem() instanceof ItemIIAssaultRifle;
}
@Override
protected void executeTask()
{
assert attackTarget!=null;
final ItemStack stg = getWeapon();
ItemStack magazine = ItemNBTHelper.getItemStack(stg, "magazine");
boolean isAmmoLoaded = IIContent.itemAssaultRifle.isAmmo(magazine, stg);
//use weapon
hans.setActiveHand(EnumHand.MAIN_HAND);
//reload if magazine empty
if(!isAmmoLoaded)
{
if(!ItemNBTHelper.getBoolean(stg, "shouldReload"))
{
final ItemStack ammo = IIContent.itemAssaultRifle.findAmmo(hans, stg);
hans.hasAmmo = !ammo.isEmpty();
if(hans.hasAmmo)
ItemNBTHelper.setBoolean(stg, "shouldReload", true);
hans.setSneaking(false);
}
}
//hans can not shoot while running away
if(motionState==MotionState.FALLBACK)
{
if(!ItemNBTHelper.getBoolean(stg, "shouldReload"))
hans.resetActiveHand();
hans.setSneaking(false);
return;
}
lookOnTarget();
if(this.rangedAttackTime < 0)
{
hans.resetActiveHand();
rangedAttackTime++;
}
if(canFire&&aimingAtTarget&&this.rangedAttackTime < burstTime)
{
if(isAmmoLoaded)
{
hans.hasAmmo = true;
hans.setSneaking(true);
hans.rotationPitch = calculateBallisticAngle(IIContent.itemBulletMagazine.takeBullet(magazine, false), attackTarget);
}
else
hans.resetActiveHand();
rangedAttackTime++;
if(rangedAttackTime >= burstTime)
rangedAttackTime = -(int)(-burstTime*0.75);
}
else
hans.resetActiveHand();
}
@Override
public void setRequiredAnimation()
{
}
@Override
protected float calculateBallisticAngle(ItemStack ammo, EntityLivingBase attackTarget)
{
return IIAmmoUtils.getDirectFireAngle(IIContent.itemAmmoAssaultRifle.getVelocity(), IIContent.itemAmmoAssaultRifle.getMass(ammo),
hans.getPositionVector().addVector(0, (double)hans.getEyeHeight()-0.10000000149011612D, 0).subtract(IIEntityUtils.getEntityCenter(attackTarget))
);
}
} | 1 | 0.961217 | 1 | 0.961217 | game-dev | MEDIA | 0.955541 | game-dev | 0.991582 | 1 | 0.991582 |
DreamVoid/MiraiMC | 10,909 | MiraiMC-Bukkit/src/main/java/me/dreamvoid/miraimc/bukkit/BukkitPlugin.java | package me.dreamvoid.miraimc.bukkit;
import me.dreamvoid.miraimc.LifeCycle;
import me.dreamvoid.miraimc.api.MiraiBot;
import me.dreamvoid.miraimc.bukkit.utils.Metrics;
import me.dreamvoid.miraimc.commands.ICommandSender;
import me.dreamvoid.miraimc.commands.MiraiCommand;
import me.dreamvoid.miraimc.commands.MiraiMcCommand;
import me.dreamvoid.miraimc.commands.MiraiVerifyCommand;
import me.dreamvoid.miraimc.interfaces.IMiraiAutoLogin;
import me.dreamvoid.miraimc.interfaces.IMiraiEvent;
import me.dreamvoid.miraimc.interfaces.Platform;
import me.dreamvoid.miraimc.interfaces.PluginConfig;
import me.dreamvoid.miraimc.internal.Utils;
import me.dreamvoid.miraimc.loader.LibraryLoader;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.net.URLClassLoader;
import java.util.*;
import java.util.logging.Logger;
public class BukkitPlugin extends JavaPlugin implements Platform {
private MiraiEvent MiraiEvent;
private MiraiAutoLogin MiraiAutoLogin;
private final LifeCycle lifeCycle;
private final PluginConfig config;
private final LibraryLoader loader;
public BukkitPlugin(){
lifeCycle = new LifeCycle(this);
lifeCycle.startUp(getLogger());
config = new BukkitConfig(this);
loader = new LibraryLoader((URLClassLoader) this.getClassLoader());
}
@Override // 加载插件
public void onLoad() {
try {
lifeCycle.preLoad();
// 加载mirai核心完成,开始加载附属功能
MiraiAutoLogin = new MiraiAutoLogin(this);
MiraiEvent = new MiraiEvent();
} catch (Exception e) {
Utils.resolveException(e, getLogger(), "加载 MiraiMC 阶段 1 时出现异常!");
}
}
@Override // 启用插件
public void onEnable() {
try {
lifeCycle.postLoad();
// 监听事件
if(config.General_LogEvents){
getLogger().info("正在注册事件监听器.");
Bukkit.getPluginManager().registerEvents(new Events(), this);
}
// bStats统计
//noinspection deprecation
if(config.General_AllowBStats && !getDescription().getVersion().contains("dev")) {
getLogger().info("正在初始化 bStats 统计.");
int pluginId = 11534;
new Metrics(this, pluginId);
}
} catch (Exception e){
Utils.resolveException(e, getLogger(), "加载 MiraiMC 阶段 2 时出现异常!");
}
}
@Override // 禁用插件
public void onDisable() {
lifeCycle.unload();
}
@Override
public boolean onCommand(@NotNull CommandSender sender, Command command, @NotNull String label, String[] args) {
ICommandSender sender1 = new ICommandSender() {
@Override
public void sendMessage(String message) {
//noinspection deprecation
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', message));
}
@Override
public boolean hasPermission(String permission) {
return sender.hasPermission(permission);
}
};
return switch (command.getName().toLowerCase()) {
case "mirai" -> new MiraiCommand().onCommand(sender1, args);
case "miraimc" -> new MiraiMcCommand().onCommand(sender1, args);
case "miraiverify" -> new MiraiVerifyCommand().onCommand(sender1, args);
default -> super.onCommand(sender, command, label, args);
};
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, Command command, @NotNull String alias, String[] args) {
List<String> result = new ArrayList<>();
switch (command.getName().toLowerCase()){
case "mirai":{
if(args.length == 1){
String[] list = new String[]{"login", "logout", "list", "sendfriendmessage", "sendgroupmessage", "sendfriendnudge", "uploadimage", "checkonline", "autologin", "help"};
for(String s : list){
if(s.startsWith(args[0])) result.add(s);
}
}
if(args.length == 2 && sender.hasPermission("miraimc.command.mirai." + args[0].toLowerCase())){
// 1
List<String> list1 = Arrays.asList("login", "logout", "sendfriendmessage", "sendgroupmessage", "sendfriendnudge", "uploadimage", "checkonline");
if(list1.contains(args[0].toLowerCase())){
for(Long l : MiraiBot.getOnlineBots()){
if(String.valueOf(l).startsWith(args[1])) result.add(String.valueOf(l));
}
}
// 2
if("autologin".equalsIgnoreCase(args[0])){
String[] list = new String[]{"add", "list", "remove"};
for(String s : list){
if(s.startsWith(args[1])) result.add(s);
}
}
}
if(args.length == 3 && sender.hasPermission("miraimc.command.mirai." + args[0].toLowerCase())){
// 1
List<String> list1 = Arrays.asList("sendfriendmessage", "sendfriendnudge");
if(list1.contains(args[1].toLowerCase())){
try {
for (Long l : MiraiBot.getBot(Long.parseLong(args[1])).getFriendList()) {
if (String.valueOf(l).startsWith(args[2])) result.add(String.valueOf(l));
}
} catch (NoSuchElementException ignored) {}
}
// 2
if("sendgroupmessage".equalsIgnoreCase(args[1])){
try {
for (Long l : MiraiBot.getBot(Long.parseLong(args[1])).getGroupList()) {
if (String.valueOf(l).startsWith(args[2])) result.add(String.valueOf(l));
}
} catch (NoSuchElementException ignored) {}
}
// 3
if(args[0].equalsIgnoreCase("autologin")) {
// 1
if("add".equalsIgnoreCase(args[1])){
for(Long l : MiraiBot.getOnlineBots()){
if(String.valueOf(l).startsWith(args[2])) result.add(String.valueOf(l));
}
}
// 2
if ("remove".equalsIgnoreCase(args[1])) {
List<String> accounts = MiraiAutoLogin.loadAutoLoginList().stream().map(map -> String.valueOf(map.get("account"))).toList();
for(String s : accounts){
if(s.startsWith(args[2])) result.add(s);
}
}
}
}
if(args.length == 4 && sender.hasPermission("miraimc.command.mirai." + args[0].toLowerCase())){
if("login".equalsIgnoreCase(args[0])){
result = MiraiBot.getAvailableProtocol();
}
}
if(args.length == 5 && sender.hasPermission("miraimc.command.mirai." + args[0].toLowerCase())){
if("autologin".equalsIgnoreCase(args[0]) && "add".equalsIgnoreCase(args[1])){
result = MiraiBot.getAvailableProtocol();
}
}
return result;
}
case "miraimc":{
if(args.length == 1){
String[] list = new String[]{"bind", "reload"};
for(String s : list){
if(s.startsWith(args[0])) result.add(s);
}
}
if(args.length == 2){
if("bind".equalsIgnoreCase(args[0])){
String[] list = new String[]{"add", "getplayer", "getqq", "removeplayer", "removeqq"};
for(String s : list){
if(s.startsWith(args[1])) result.add(s);
}
}
}
if(args.length == 3){
List<String> list = Arrays.asList("add", "getplayer", "removeplayer");
if("bind".equalsIgnoreCase(args[0]) && list.contains(args[1].toLowerCase())){
for(Player p : Bukkit.getOnlinePlayers()){
if(p.getName().startsWith(args[2])) result.add(p.getName());
}
}
}
return result;
}
default:return super.onTabComplete(sender,command,alias,args);
}
}
@Override
public String getPlayerName(UUID uuid) {
return Bukkit.getOfflinePlayer(uuid).getName();
}
@Override
public UUID getPlayerUUID(String name) {
return Bukkit.getOfflinePlayer(name).getUniqueId();
}
@Override
public void runTaskAsync(Runnable task) {
getServer().getScheduler().runTaskAsynchronously(this, task);
}
@Override
public void runTaskLaterAsync(Runnable task, long delay) {
getServer().getScheduler().runTaskLaterAsynchronously(this, task, delay);
}
@Override
public void runTaskTimerAsync(Runnable task, long delay, long period) {
getServer().getScheduler().runTaskTimerAsynchronously(this, task, delay, period);
}
@Override
public String getPluginName() {
//noinspection deprecation
return getDescription().getName();
}
@Override
public String getPluginVersion() {
//noinspection deprecation
return getDescription().getVersion();
}
@Override
public List<String> getAuthors() {
//noinspection deprecation
return getDescription().getAuthors();
}
@Override
public IMiraiAutoLogin getAutoLogin() {
return this.MiraiAutoLogin;
}
@Override
public Logger getPluginLogger() {
return getLogger();
}
@Override
public ClassLoader getPluginClassLoader(){
return this.getClassLoader();
}
@Override
public IMiraiEvent getMiraiEvent() {
return MiraiEvent;
}
@Override
public LibraryLoader getLibraryLoader() {
return loader;
}
@Override
public String getType() {
return "Bukkit";
}
@Override
public PluginConfig getPluginConfig() {
return config;
}
}
| 1 | 0.944699 | 1 | 0.944699 | game-dev | MEDIA | 0.256826 | game-dev | 0.985484 | 1 | 0.985484 |
VRCFury/VRCFury | 4,601 | com.vrcfury.vrcfury/Editor/VF/Menu/DuplicatePhysboneDetector.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using VF.Builder;
using VF.Builder.Exceptions;
using VF.Inspector;
using VF.Utils;
using VRC.SDK3.Dynamics.PhysBone.Components;
using Object = UnityEngine.Object;
namespace VF.Menu {
internal static class DuplicatePhysboneDetector {
[MenuItem(MenuItems.detectDuplicatePhysbones, priority = MenuItems.detectDuplicatePhysbonesPriority)]
private static void Run() {
VRCFExceptionUtils.ErrorDialogBoundary(RunUnsafe);
}
private static void RunUnsafe() {
var start = DialogUtils.DisplayDialog(
"Duplicate Physbones",
"This tool will load every scene and prefab, and check for any bones that have more than one physbone targeting them (which is usually bad). This may take a lot of ram and time. Continue?",
"Yes",
"Cancel"
);
if (!start) return;
BulkUpgradeUtils.WithAllScenesOpen(() => {
var bad = new List<string>();
FindDupes<VRCPhysBone>(c => c.GetRootTransform(), bad);
if (bad.Count == 0) {
DialogUtils.DisplayDialog(
"Duplicate Physbones",
"No duplicates found in loaded objects.",
"Ok"
);
return;
}
var split = bad.Join("\n\n").Split('\n').ToList();
while (split.Count > 0) {
var numToPick = Math.Min(split.Count, 40);
var part = split.GetRange(0, numToPick);
split.RemoveRange(0, numToPick);
var message = "Duplicate physbones found in loaded objects:\n\n" + part.Join('\n');
if (split.Count > 0) message += "\n... and more (will be shown in next dialog)";
message += "\n\nDelete the duplicates?";
var ok = DialogUtils.DisplayDialog(
"Duplicate Physbones",
message,
"Ok, Delete Duplicates",
"Cancel"
);
if (!ok) return;
}
FixDupes<VRCPhysBone>(c => c.GetRootTransform());
});
}
private static string GetName(VFGameObject t) {
return t.GetPath()
+ " (" + AssetDatabase.GetAssetPath(t) + ")";
}
private static string GetName<T>(T c, Dictionary<T, string> sources) where T : UnityEngine.Component {
return c.owner().GetPath()
+ " (" + sources[c] + ")"
+ (IsMutable(c) ? "" : " (Immutable)");
}
private static void FindDupes<T>(Func<T, VFGameObject> GetTarget, List<string> badList) where T : UnityEngine.Component {
var (map, sources) = BulkUpgradeUtils.FindAll(GetTarget);
foreach (var ((transform,target),components) in map.Select(x => (x.Key, x.Value))) {
if (components.Count == 1) continue;
var mutable = components.Where(IsMutable).ToList();
if (mutable.Count == 0) continue;
var targetStr = GetName(target);
var cStrs = components.Select(c => GetName(c, sources)).Join('\n');
badList.Add( $"{targetStr}\nis targeted by\n{cStrs}");
}
}
private static bool IsMutable(UnityEngine.Component c) {
return !PrefabUtility.IsPartOfImmutablePrefab(c) && !PrefabUtility.IsPartOfPrefabInstance(c);
}
private static void FixDupes<T>(Func<T, VFGameObject> GetTarget) where T : UnityEngine.Component {
var (map, sources) = BulkUpgradeUtils.FindAll(GetTarget);
foreach (var ((transform,target),components) in map.Select(x => (x.Key, x.Value))) {
if (components.Count == 1) continue;
var mutable = components.Where(IsMutable).ToList();
if (mutable.Count == components.Count) {
mutable.RemoveAt(0);
}
foreach (var c in mutable) {
var obj = c.owner();
Object.DestroyImmediate(c, true);
VRCFuryEditorUtils.MarkDirty(obj);
}
}
}
}
}
| 1 | 0.903229 | 1 | 0.903229 | game-dev | MEDIA | 0.92554 | game-dev | 0.962541 | 1 | 0.962541 |
Team-RTG/Realistic-Terrain-Generation | 29,967 | src/main/java/rtg/world/gen/ChunkGeneratorRTG.java | package rtg.world.gen;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.init.Biomes;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockPos.MutableBlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import net.minecraft.world.WorldEntitySpawner;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.BiomeProvider;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkPrimer;
import net.minecraft.world.gen.IChunkGenerator;
import net.minecraft.world.gen.MapGenBase;
import net.minecraft.world.gen.feature.WorldGenDungeons;
import net.minecraft.world.gen.feature.WorldGenLakes;
import net.minecraft.world.gen.structure.*;
import net.minecraftforge.event.ForgeEventFactory;
import net.minecraftforge.event.terraingen.InitMapGenEvent.EventType;
import net.minecraftforge.event.terraingen.PopulateChunkEvent;
import net.minecraftforge.event.terraingen.TerrainGen;
import rtg.RTG;
import rtg.RTGConfig;
import rtg.api.RTGAPI;
import rtg.api.util.LimitedArrayCacheMap;
import rtg.api.util.Logger;
import rtg.api.util.noise.ISimplexData2D;
import rtg.api.util.noise.SimplexData2D;
import rtg.api.world.RTGWorld;
import rtg.api.world.biome.IRealisticBiome;
import rtg.api.world.gen.RTGChunkGenSettings;
import rtg.api.world.gen.feature.WorldGenPond;
import rtg.api.world.terrain.TerrainBase;
import rtg.world.biome.BiomeAnalyzer;
import rtg.world.biome.realistic.vanilla.RealisticBiomeVanillaMesaPlateau;
import rtg.world.gen.structure.WoodlandMansionRTG;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class ChunkGeneratorRTG implements IChunkGenerator {
public final RTGWorld rtgWorld;
private final RTGChunkGenSettings settings;
private final MapGenBase caveGenerator;
private final MapGenBase ravineGenerator;
private final MapGenStronghold strongholdGenerator;
private final WoodlandMansionRTG woodlandMansionGenerator;
private final MapGenMineshaft mineshaftGenerator;
private final MapGenVillage villageGenerator;
private final MapGenScatteredFeature scatteredFeatureGenerator;
private final StructureOceanMonument oceanMonumentGenerator;
private final World world;
private final LimitedArrayCacheMap<ChunkPos, ChunkLandscape> landscapeCache = new LimitedArrayCacheMap<>(1024);// cache ChunkLandscape objects
private final int sampleSize = 8;
private final int sampleArraySize = sampleSize * 2 + 5;
private final int[] biomeData = new int[sampleArraySize * sampleArraySize];
private final float[][] weightings = new float[sampleArraySize * sampleArraySize][256];
private final MesaBiomeCombiner mesaCombiner = new MesaBiomeCombiner();
private BiomeAnalyzer analyzer = new BiomeAnalyzer();
private int[] xyinverted = analyzer.xyinverted();
private boolean mapFeaturesEnabled;
private Random rand;
private Biome[] baseBiomesList;
private TerrainBase mesaPlateau = new RealisticBiomeVanillaMesaPlateau.TerrainRTGMesaPlateau(67);
public ChunkGeneratorRTG(RTGWorld rtgWorld) {
Logger.debug("Instantiating CPRTG using generator settings: {}", rtgWorld.world().getWorldInfo().getGeneratorOptions());
this.world = rtgWorld.world();
this.rtgWorld = rtgWorld;
this.settings = rtgWorld.getGeneratorSettings();
// TODO: [1.12] seaLevel will be removed as terrain noise values are all hardcoded and will not variate properly.
this.world.setSeaLevel(this.settings.seaLevel);
this.rand = new Random(rtgWorld.seed());
this.rtgWorld.setRandom(this.rand);
this.mapFeaturesEnabled = world.getWorldInfo().isMapFeaturesEnabled();
this.caveGenerator = TerrainGen.getModdedMapGen(new MapGenCavesRTG(this.settings.caveChance, this.settings.caveDensity), EventType.CAVE);
this.ravineGenerator = TerrainGen.getModdedMapGen(new MapGenRavineRTG(this.settings.ravineChance), EventType.RAVINE);
this.villageGenerator = (MapGenVillage) TerrainGen.getModdedMapGen(new MapGenVillage(StructureType.VILLAGE.getSettings(this.settings)), EventType.VILLAGE);
this.strongholdGenerator = (MapGenStronghold) TerrainGen.getModdedMapGen(new MapGenStronghold(StructureType.STRONGHOLD.getSettings(this.settings)), EventType.STRONGHOLD);
this.woodlandMansionGenerator = new WoodlandMansionRTG(this, StructureType.MANSION.getSettings(this.settings));//don't allow mods to override our generator.
this.mineshaftGenerator = (MapGenMineshaft) TerrainGen.getModdedMapGen(new MapGenMineshaft(StructureType.MINESHAFT.getSettings(this.settings)), EventType.MINESHAFT);
this.scatteredFeatureGenerator = (MapGenScatteredFeature) TerrainGen.getModdedMapGen(new MapGenScatteredFeature(StructureType.TEMPLE.getSettings(this.settings)), EventType.SCATTERED_FEATURE);
this.oceanMonumentGenerator = (StructureOceanMonument) TerrainGen.getModdedMapGen(new StructureOceanMonument(StructureType.MONUMENT.getSettings(this.settings)), EventType.OCEAN_MONUMENT);
this.baseBiomesList = new Biome[256];
setWeightings();// landscape generator init
Logger.debug("FINISHED instantiating CPRTG.");
}
@Override
public Chunk generateChunk(final int cx, final int cz) {
final ChunkPos chunkPos = new ChunkPos(cx, cz);
final BlockPos blockPos = new BlockPos(cx * 16, 0, cz * 16);
final BiomeProvider biomeProvider = this.world.getBiomeProvider();
this.rand.setSeed(cx * 341873128712L + cz * 132897987541L);
final ChunkPrimer primer = new ChunkPrimer();
final ChunkLandscape landscape = getLandscape(biomeProvider, chunkPos);
generateTerrain(primer, landscape.noise);
//get standard biome Data
for (int i = 0; i < 256; i++) {
this.baseBiomesList[i] = landscape.biome[i].baseBiome();
}
ISimplexData2D jitterData = SimplexData2D.newDisk();
IRealisticBiome[] jitteredBiomes = new IRealisticBiome[256];
IRealisticBiome jitterbiome, actualbiome;
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
int x = blockPos.getX() + i;
int z = blockPos.getZ() + j;
this.rtgWorld.simplexInstance(0).multiEval2D(x, z, jitterData);
int pX = (int) Math.round(x + jitterData.getDeltaX() * RTGConfig.surfaceBlendRadius());
int pZ = (int) Math.round(z + jitterData.getDeltaY() * RTGConfig.surfaceBlendRadius());
actualbiome = landscape.biome[(x & 15) * 16 + (z & 15)];
jitterbiome = landscape.biome[(pX & 15) * 16 + (pZ & 15)];
jitteredBiomes[i * 16 + j] = (actualbiome.getConfig().SURFACE_BLEED_IN.get() && jitterbiome.getConfig().SURFACE_BLEED_OUT.get()) ? jitterbiome : actualbiome;
}
}
replaceBiomeBlocks(cx, cz, primer, jitteredBiomes, this.baseBiomesList, landscape.noise);
if (this.settings.useCaves) {
this.caveGenerator.generate(this.world, cx, cz, primer);
}
if (this.settings.useRavines) {
this.ravineGenerator.generate(this.world, cx, cz, primer);
}
if (this.mapFeaturesEnabled) {
if (settings.useMineShafts) {
this.mineshaftGenerator.generate(this.world, cx, cz, primer);
}
if (settings.useStrongholds) {
this.strongholdGenerator.generate(this.world, cx, cz, primer);
}
if (settings.useVillages) {
this.villageGenerator.generate(this.world, cx, cz, primer);
}
if (settings.useTemples) {
this.scatteredFeatureGenerator.generate(this.world, cx, cz, primer);
}
if (settings.useMonuments) {
this.oceanMonumentGenerator.generate(this.world, cx, cz, primer);
}
if (settings.useMansions) {
this.woodlandMansionGenerator.generate(this.world, cx, cz, primer);
}
}
// store in the in process pile
Chunk chunk = new Chunk(this.world, primer, cx, cz);
byte[] abyte1 = chunk.getBiomeArray();
for (int i = 0; i < abyte1.length; ++i) {
// Biomes are y-first and terrain x-first
byte b = (byte) Biome.getIdForBiome(this.baseBiomesList[this.xyinverted[i]]);
abyte1[i] = b;
}
chunk.setBiomeArray(abyte1);
chunk.generateSkylightMap();
return chunk;
}
public void generateTerrain(ChunkPrimer primer, float[] noise) {
int height;
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
height = (int) noise[x * 16 + z];
for (int y = 0; y < 256; y++) {
if (y > height) {
if (y < this.settings.seaLevel) {
primer.setBlockState(x, y, z, Blocks.WATER.getDefaultState());
}
else {
primer.setBlockState(x, y, z, Blocks.AIR.getDefaultState());
}
}
else {
primer.setBlockState(x, y, z, Blocks.STONE.getDefaultState());
}
}
}
}
}
private void replaceBiomeBlocks(int cx, int cz, ChunkPrimer primer, IRealisticBiome[] biomes, Biome[] base, float[] noise) {
if (!ForgeEventFactory.onReplaceBiomeBlocks(this, cx, cz, primer, this.world)) {
return;
}
int worldX = cx * 16;
int worldZ = cz * 16;
MutableBlockPos mpos = new MutableBlockPos();
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
mpos.setPos(worldX + x, 0, worldZ + z);
float river = -TerrainBase.getRiverStrength(mpos, rtgWorld);
int depth = -1;
biomes[x * 16 + z].rReplace(primer, mpos, x, z, depth, rtgWorld, noise, river, base);
// sparse bedrock layers above y=0
if (this.settings.bedrockLayers > 1) {
for (int bl = 9; bl >= 0; --bl) {
if (bl <= this.rand.nextInt(this.settings.bedrockLayers)) {
primer.setBlockState(x, bl, z, Blocks.BEDROCK.getDefaultState());
}
}
}
else {
primer.setBlockState(x, 0, z, Blocks.BEDROCK.getDefaultState());
}
}
}
}
@SuppressWarnings("ConstantConditions") //false-positive on `hasVillage`, IDEA is probably not looking deep enough.
@Override
public void populate(int chunkX, int chunkZ) {
BlockFalling.fallInstantly = true;
final BiomeProvider biomeProvider = this.world.getBiomeProvider();
final ChunkPos chunkPos = new ChunkPos(chunkX, chunkZ);
final BlockPos blockPos = new BlockPos(chunkX * 16, 0, chunkZ * 16);
final BlockPos offsetpos = blockPos.add(8, 0, 8);
IRealisticBiome biome = RTGAPI.getRTGBiome(biomeProvider.getBiome(blockPos.add(16, 0, 16)));
this.rand.setSeed(rtgWorld.getChunkSeed(chunkX, chunkZ));
boolean hasVillage = false;
ForgeEventFactory.onChunkPopulate(true, this, this.world, this.rand, chunkX, chunkZ, false);
if (this.mapFeaturesEnabled) {
if (settings.useMineShafts) {
mineshaftGenerator.generateStructure(world, rand, chunkPos);
}
if (settings.useStrongholds) {
strongholdGenerator.generateStructure(world, rand, chunkPos);
}
if (settings.useVillages) {
hasVillage = villageGenerator.generateStructure(world, rand, chunkPos);
}
if (settings.useTemples) {
scatteredFeatureGenerator.generateStructure(world, rand, chunkPos);
}
if (settings.useMonuments) {
oceanMonumentGenerator.generateStructure(this.world, rand, chunkPos);
}
if (settings.useMansions) {
woodlandMansionGenerator.generateStructure(world, rand, chunkPos);
}
}
// water lakes.
if (settings.useWaterLakes && settings.waterLakeChance > 0 && !hasVillage) {
final long nextchance = rand.nextLong();
final int surfacechance = settings.getSurfaceWaterLakeChance(biome.waterLakeMult());
final BlockPos pos = offsetpos.add(rand.nextInt(16), 0, rand.nextInt(16));
// possibly reduced chance to generate anywhere, including on surface
if (surfacechance > 0 && nextchance % surfacechance == 0) {
if (TerrainGen.populate(this, world, rand, chunkX, chunkZ, hasVillage, PopulateChunkEvent.Populate.EventType.LAKE)) {
(new WorldGenPond(Blocks.WATER.getDefaultState())).generate(world, rand, pos.up(rand.nextInt(256)));
}
}
// normal chance to generate underground
else if (nextchance % settings.waterLakeChance == 0) {
if (TerrainGen.populate(this, world, rand, chunkX, chunkZ, hasVillage, PopulateChunkEvent.Populate.EventType.LAKE)) {
(new WorldGenLakes(Blocks.WATER)).generate(world, rand, pos.up(rand.nextInt(50) + 4));//make sure that underground lakes are sufficiently underground
}
}
}
// lava lakes.
if (settings.useLavaLakes && settings.lavaLakeChance > 0 && !hasVillage) {
final long nextchance = rand.nextLong();
final int surfacechance = settings.getSurfaceLavaLakeChance(biome.lavaLakeMult());
final BlockPos pos = offsetpos.add(rand.nextInt(16), 0, rand.nextInt(16));
// possibly reduced chance to generate anywhere, including on surface
if (surfacechance > 0 && nextchance % surfacechance == 0) {
if (TerrainGen.populate(this, world, rand, chunkX, chunkZ, hasVillage, PopulateChunkEvent.Populate.EventType.LAVA)) {
(new WorldGenPond(Blocks.LAVA.getDefaultState())).generate(world, rand, pos.up(rand.nextInt(256)));
}
}
// normal chance to generate underground
else if (nextchance % settings.lavaLakeChance == 0) {
if (TerrainGen.populate(this, world, rand, chunkX, chunkZ, hasVillage, PopulateChunkEvent.Populate.EventType.LAVA)) {
(new WorldGenLakes(Blocks.LAVA)).generate(world, rand, pos.up(rand.nextInt(50) + 4));//make sure that underground lakes are sufficiently underground
}
}
}
if (settings.useDungeons) {
if (TerrainGen.populate(this, world, rand, chunkX, chunkZ, hasVillage, PopulateChunkEvent.Populate.EventType.DUNGEON)) {
for (int i = 0; i < settings.dungeonChance; i++) {
(new WorldGenDungeons()).generate(world, rand, offsetpos.add(rand.nextInt(16), rand.nextInt(256), rand.nextInt(16)));
}
}
}
float river = -TerrainBase.getRiverStrength(blockPos.add(16, 0, 16), rtgWorld);
if (RTG.decorationsDisable() || biome.getConfig().DISABLE_RTG_DECORATIONS.get()) {
if (river > 0.9f) {
biome.getRiverBiome().baseBiome().decorate(this.world, this.rand, blockPos);
}
else {
biome.baseBiome().decorate(this.world, this.rand, blockPos);
}
}
else {
if (river > 0.9f) {
biome.getRiverBiome().rDecorate(this.rtgWorld, this.rand, chunkPos, river, hasVillage);
}
else {
biome.rDecorate(this.rtgWorld, this.rand, chunkPos, river, hasVillage);
}
}
if (TerrainGen.populate(this, this.world, this.rand, chunkX, chunkZ, hasVillage, PopulateChunkEvent.Populate.EventType.ANIMALS)) {
WorldEntitySpawner.performWorldGenSpawning(this.world, biome.baseBiome(), blockPos.getX() + 8, blockPos.getZ() + 8, 16, 16, this.rand);
}
if (TerrainGen.populate(this, this.world, this.rand, chunkX, chunkZ, hasVillage, PopulateChunkEvent.Populate.EventType.ICE)) {
for (int x = 0; x < 16; ++x) {
for (int z = 0; z < 16; ++z) {
// Ice.
final BlockPos freezePos = world.getPrecipitationHeight(offsetpos.add(x, 0, z)).down();
if (this.world.canBlockFreezeWater(freezePos)) {
this.world.setBlockState(freezePos, Blocks.ICE.getDefaultState(), 2);
}
// Snow layers.
final BlockPos surfacePos = world.getTopSolidOrLiquidBlock(offsetpos.add(x, 0, z));
if (settings.useSnowLayers) {
// start at 32 blocks above the surface (should be above any tree leaves), and move down placing
// snow layers on any leaves, or the surface block, if the temperature permits it.
for (BlockPos checkPos = surfacePos.up(32); checkPos.getY() >= surfacePos.getY(); checkPos = checkPos.down()) {
if (world.getBlockState(checkPos).getMaterial() == Material.AIR) {
final float temp = biomeProvider.getBiome(surfacePos).getTemperature(checkPos);
if (temp <= settings.getClampedSnowLayerTemp()) {
if (Blocks.SNOW_LAYER.canPlaceBlockAt(world, checkPos)) {
this.world.setBlockState(checkPos, Blocks.SNOW_LAYER.getDefaultState(), 2);
// we already know the next check block is not air, so skip ahead.
checkPos = checkPos.down();
}
}
}
}
}
}
}
}
ForgeEventFactory.onChunkPopulate(false, this, this.world, this.rand, chunkX, chunkZ, hasVillage);
BlockFalling.fallInstantly = false;
}
@Override
public boolean generateStructures(Chunk chunkIn, int x, int z) {
boolean flag = false;
if (settings.useMonuments && this.mapFeaturesEnabled && chunkIn.getInhabitedTime() < 3600L) {
flag = this.oceanMonumentGenerator.generateStructure(this.world, this.rand, new ChunkPos(x, z));
}
return flag;
}
@Override
public List<Biome.SpawnListEntry> getPossibleCreatures(EnumCreatureType creatureType, BlockPos pos) {
Biome biome = this.world.getBiome(pos);
if (this.mapFeaturesEnabled) {
if (creatureType == EnumCreatureType.MONSTER && this.scatteredFeatureGenerator.isSwampHut(pos)) {
return this.scatteredFeatureGenerator.getMonsters();
}
if (creatureType == EnumCreatureType.MONSTER && settings.useMonuments && this.oceanMonumentGenerator.isPositionInStructure(this.world, pos)) {
return this.oceanMonumentGenerator.getMonsters();
}
}
return biome.getSpawnableList(creatureType);
}
@Nullable
@Override
public BlockPos getNearestStructurePos(World worldIn, String structureName, BlockPos position, boolean findUnexplored) {
if (!this.mapFeaturesEnabled) {
return null;
}
if ("Stronghold".equals(structureName) && this.strongholdGenerator != null) {
return this.strongholdGenerator.getNearestStructurePos(worldIn, position, findUnexplored);
}
if ("Mansion".equals(structureName) && this.woodlandMansionGenerator != null) {
return this.woodlandMansionGenerator.getNearestStructurePos(worldIn, position, findUnexplored);
}
if ("Monument".equals(structureName) && this.oceanMonumentGenerator != null) {
return this.oceanMonumentGenerator.getNearestStructurePos(worldIn, position, findUnexplored);
}
if ("Village".equals(structureName) && this.villageGenerator != null) {
return this.villageGenerator.getNearestStructurePos(worldIn, position, findUnexplored);
}
if ("Mineshaft".equals(structureName) && this.mineshaftGenerator != null) {
return this.mineshaftGenerator.getNearestStructurePos(worldIn, position, findUnexplored);
}
if ("Temple".equals(structureName) && this.scatteredFeatureGenerator != null) {
return this.scatteredFeatureGenerator.getNearestStructurePos(worldIn, position, findUnexplored);
}
return null;
}
@SuppressWarnings("ConstantConditions")
@Override
public void recreateStructures(Chunk chunk, int cx, int cz) {
if (this.mapFeaturesEnabled) {
if (this.settings.useMineShafts) {
this.mineshaftGenerator.generate(this.world, cx, cz, null);
}
if (this.settings.useVillages) {
this.villageGenerator.generate(this.world, cx, cz, null);
}
if (this.settings.useStrongholds) {
this.strongholdGenerator.generate(this.world, cx, cz, null);
}
if (this.settings.useTemples) {
this.scatteredFeatureGenerator.generate(this.world, cx, cz, null);
}
if (this.settings.useMonuments) {
this.oceanMonumentGenerator.generate(this.world, cx, cz, null);
}
if (this.settings.useMansions) {
this.woodlandMansionGenerator.generate(this.world, cx, cz, null);
}
}
}
@Override
public boolean isInsideStructure(World worldIn, String structureName, BlockPos pos) {
if (!this.mapFeaturesEnabled) {
return false;
}
if ("Stronghold".equals(structureName) && this.strongholdGenerator != null) {
return this.strongholdGenerator.isInsideStructure(pos);
}
if ("Mansion".equals(structureName) && this.woodlandMansionGenerator != null) {
return this.woodlandMansionGenerator.isInsideStructure(pos);
}
if ("Monument".equals(structureName) && this.oceanMonumentGenerator != null) {
return this.oceanMonumentGenerator.isInsideStructure(pos);
}
if ("Village".equals(structureName) && this.villageGenerator != null) {
return this.villageGenerator.isInsideStructure(pos);
}
if ("Mineshaft".equals(structureName) && this.mineshaftGenerator != null) {
return this.mineshaftGenerator.isInsideStructure(pos);
}
return ("Temple".equals(structureName) && this.scatteredFeatureGenerator != null) && this.scatteredFeatureGenerator.isInsideStructure(pos);
}
/* Landscape Geneator */
private void setWeightings() {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
float limit = (float) Math.pow((56f * 56f), 0.7D);
for (int mapX = 0; mapX < sampleArraySize; mapX++) {
for (int mapZ = 0; mapZ < sampleArraySize; mapZ++) {
float xDist = (x - (mapX - sampleSize) * 8);
float zDist = (z - (mapZ - sampleSize) * 8);
float distanceSquared = xDist * xDist + zDist * zDist;
float distance = (float) Math.pow(distanceSquared, 0.7D);
float weight = 1f - distance / limit;
if (weight < 0) {
weight = 0;
}
weightings[mapX * sampleArraySize + mapZ][x * 16 + z] = weight;
}
}
}
}
}
public ChunkLandscape getLandscape(final BiomeProvider biomeProvider, final ChunkPos chunkPos) {
final BlockPos blockPos = new BlockPos(chunkPos.x * 16, 0, chunkPos.z * 16);
ChunkLandscape landscape = landscapeCache.get(chunkPos);
if (landscape == null) {
landscape = generateLandscape(biomeProvider, blockPos);
landscapeCache.put(chunkPos, landscape);
}
return landscape;
}
private synchronized ChunkLandscape generateLandscape(BiomeProvider biomeProvider, BlockPos blockPos) {
final ChunkLandscape landscape = new ChunkLandscape();
getNewerNoise(biomeProvider, blockPos.getX(), blockPos.getZ(), landscape);
Biome[] biomes = new Biome[256];
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
biomes[x * 16 + z] = biomeProvider.getBiome(blockPos.add(x, 0, z));
}
}
analyzer.newRepair(biomes, this.biomeData, landscape);
return landscape;
}
private synchronized void getNewerNoise(final BiomeProvider biomeProvider, final int worldX, final int worldZ, ChunkLandscape landscape) {
float[] weightedBiomes = new float[256];
// get area biome map
for (int x = -sampleSize; x < sampleSize + 5; x++) {
for (int z = -sampleSize; z < sampleSize + 5; z++) {
biomeData[(x + sampleSize) * sampleArraySize + (z + sampleSize)] = Biome.getIdForBiome(biomeProvider.getBiome(new BlockPos(worldX + ((x * 8)), 0, worldZ + ((z * 8)))));
}
}
// fill the old smallRender
MutableBlockPos mpos = new MutableBlockPos(worldX, 0, worldZ);
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
float totalWeight = 0;
for (int mapX = 0; mapX < sampleArraySize; mapX++) {
for (int mapZ = 0; mapZ < sampleArraySize; mapZ++) {
float weight = weightings[mapX * sampleArraySize + mapZ][x * 16 + z];
if (weight > 0) {
totalWeight += weight;
weightedBiomes[biomeData[mapX * sampleArraySize + mapZ]] += weight;
}
}
}
// normalize biome weights
for (int biomeIndex = 0; biomeIndex < weightedBiomes.length; biomeIndex++) {
weightedBiomes[biomeIndex] /= totalWeight;
}
// combine mesa biomes
mesaCombiner.adjust(weightedBiomes);
landscape.noise[x * 16 + z] = 0f;
float river = TerrainBase.getRiverStrength(mpos.setPos(worldX + x, 0, worldZ + z), rtgWorld);
landscape.river[x * 16 + z] = -river;
int mesaBryce = Biome.getIdForBiome(Biomes.MUTATED_MESA);
for (int i = 0; i < 256; i++) {
if (weightedBiomes[i] > 0f) {
landscape.noise[x * 16 + z] += RTGAPI.getRTGBiome(i).rNoise(this.rtgWorld, worldX + x, worldZ + z, weightedBiomes[i], river + 1f) * weightedBiomes[i];
//Logger.info("Biome {}: {}",i,landscape.noise[x * 16 + z]);
// 0 for the next column
weightedBiomes[i] = 0f;
}
}
}
}
//fill biomes array with biomeData
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
BlockPos pos = new BlockPos(worldX + (x - 7) * 8 + 4, 0, worldZ + (z - 7) * 8 + 4);
landscape.biome[x * 16 + z] = RTGAPI.getRTGBiome(biomeProvider.getBiome(pos));
}
}
}
// A helper class to generate settings maps to configure the vanilla structure classes
private enum StructureType {
MINESHAFT,
MONUMENT,
STRONGHOLD,
TEMPLE,
VILLAGE,
MANSION;
Map<String, String> getSettings(RTGChunkGenSettings settings) {
Map<String, String> ret = new HashMap<>();
if (this == MINESHAFT) {
ret.put("chance", String.valueOf(settings.mineShaftChance));
return ret;
}
if (this == MONUMENT) {
ret.put("separation", String.valueOf(settings.monumentSeparation));
ret.put("spacing", String.valueOf(settings.monumentSpacing));
return ret;
}
if (this == STRONGHOLD) {
ret.put("count", String.valueOf(settings.strongholdCount));
ret.put("distance", String.valueOf(settings.strongholdDistance));
ret.put("spread", String.valueOf(settings.strongholdSpread));
return ret;
}
if (this == TEMPLE) {
ret.put("distance", String.valueOf(settings.templeDistance));
return ret;
}
if (this == VILLAGE) {
ret.put("distance", String.valueOf(settings.villageDistance));
ret.put("size", String.valueOf(settings.villageSize));
return ret;
}
if (this == MANSION) {
ret.put("spacing", String.valueOf(settings.mansionSpacing));
ret.put("separation", String.valueOf(settings.mansionSeparation));
return ret;
}
return ret;
}
}
}
| 1 | 0.893267 | 1 | 0.893267 | game-dev | MEDIA | 0.970683 | game-dev | 0.843807 | 1 | 0.843807 |
herobrine99dan/NESS-Reloaded | 1,504 | src/main/java/com/github/ness/check/combat/KillauraNoSwing.java | package com.github.ness.check.combat;
import java.time.Duration;
import com.github.ness.NessPlayer;
import com.github.ness.check.CheckInfo;
import com.github.ness.check.CheckInfos;
import com.github.ness.check.PacketCheck;
import com.github.ness.check.PacketCheckFactory;
import com.github.ness.check.PeriodicTaskInfo;
import com.github.ness.data.PlayerAction;
import com.github.ness.packets.Packet;
public class KillauraNoSwing extends PacketCheck {
public static final CheckInfo checkInfo = CheckInfos
.forPacketsWithTask(PeriodicTaskInfo.asyncTask(Duration.ofMillis(300)));
public KillauraNoSwing(final PacketCheckFactory<?> factory, final NessPlayer nessPlayer) {
super(factory, nessPlayer);
}
private long lastAnimation;
@Override
protected void checkAsyncPeriodic() {
// normalPacketsCounter = 0;
long attackDelay = this.player().milliSecondTimeDifference(PlayerAction.ATTACK);
if (attackDelay < 600) {
long result = Math.abs(this.player().getMilliSecondTime(PlayerAction.ATTACK) - lastAnimation);
if (result > 570 && !player().getAcquaticUpdateFixes().isRiptiding() && player().getAcquaticUpdateFixes().getDelayFromRiptideEvent() > 700) {
this.flag("Result: " + result + " attackDelay: " + attackDelay);
}
}
}
@Override
protected void checkPacket(Packet packet) {
String packetName = packet.getRawPacket().getClass().getSimpleName();
if (packetName.equals("PacketPlayInArmAnimation")) {
lastAnimation = (long) (System.nanoTime() / 1e+6);
}
}
}
| 1 | 0.8566 | 1 | 0.8566 | game-dev | MEDIA | 0.727036 | game-dev,networking | 0.863559 | 1 | 0.863559 |
mdechatech/Sonic-Realms | 2,590 | Assets/Scripts/SonicRealms/Core/Triggers/BaseTrigger.cs | using System;
using SonicRealms.Core.Actors;
using UnityEngine;
using UnityEngine.Events;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace SonicRealms.Core.Triggers
{
/// <summary>
/// An event for when a controller is on a trigger, invoked with the offending controller.
/// </summary>
[Serializable]
public class TriggerEvent : UnityEvent<HedgehogController> { }
/// <summary>
/// Base class for level objects that receive events.
/// </summary>
[ExecuteInEditMode]
public abstract class BaseTrigger : MonoBehaviour
{
/// <summary>
/// Whether children of the trigger can set off events. Turning this on makes
/// it easy to work with groups of colliders/objects.
/// </summary>
[Tooltip("Whether children of the trigger can set off events. Turning this on makes it easy to work" +
" with groups of colliders/objects.")]
public bool TriggerFromChildren;
public virtual void Reset()
{
TriggerFromChildren = true;
}
public virtual void Awake()
{
// here for consistency
}
public virtual void Update()
{
#if UNITY_EDITOR
hideFlags = EditorPrefs.GetBool("ShowTriggers", false) ? HideFlags.None : HideFlags.HideInInspector;
#endif
}
public abstract bool HasController(HedgehogController controller);
/// <summary>
/// Returns whether these properties apply to the specified transform.
/// </summary>
/// <param name="platform">The specified transform.</param>
/// <returns></returns>
public bool AppliesTo(Transform platform)
{
if (!TriggerFromChildren && platform != transform) return false;
var check = platform;
while (check != null)
{
if (check == this) return true;
check = check.parent;
}
return false;
}
/// <summary>
/// Returns whether the specified trigger would receive events from the specified transform.
/// </summary>
/// <typeparam name="TTrigger"></typeparam>
/// <param name="trigger"></param>
/// <param name="transform"></param>
/// <returns></returns>
public static bool ReceivesEvents<TTrigger>(TTrigger trigger, Transform transform)
where TTrigger : BaseTrigger
{
return trigger && (transform == trigger.transform || trigger.TriggerFromChildren);
}
}
}
| 1 | 0.898113 | 1 | 0.898113 | game-dev | MEDIA | 0.969771 | game-dev | 0.90172 | 1 | 0.90172 |
dengzibiao/moba | 10,667 | Assets/Script/SceneManager/ActivityProps/SceneActivityProps.cs | using UnityEngine;
using System.Collections;
using Tianyu;
using System.Collections.Generic;
public enum ActivityType
{
power,
agile,
intelligence
}
public enum DifficultyType
{
simple,
ordinary,
difficult,
great,
nightmare,
abyss
}
public class SceneActivityProps : SceneBaseManager
{
public static int POWERCOUNT = 1000;
public static int AGILECOUNT = 2000;
public static int INTELCOUNT = 3000;
public ActivityType state = ActivityType.power;
public DifficultyType difficulty = DifficultyType.simple;
public SpawnMonster Spawan;
//Dictionary<int, bool> starDic = new Dictionary<int, bool>();
ActivityPropsNode propsNode;
SceneNode sn;
Vector3 pos;
int maxWave = 0;
int currentWave;
int rate;
//float randomRot = 0;
object[] monster;
bool isCreatMonster = false;
public override void StartCD()
{
}
public override void InitScene()
{
base.InitScene();
Globe.isFB = true;
sn = FSDataNodeTable<SceneNode>.GetSingleton().FindDataByType(GameLibrary.dungeonId);
if (sn != null)
{
switch (sn.bigmap_id)
{
case 30300: state = ActivityType.power; break;
case 30400: state = ActivityType.agile; break;
case 30500: state = ActivityType.intelligence; break;
}
switch (state)
{
case ActivityType.power: sceneType = SceneType.ACT_POWER; break;
case ActivityType.agile: sceneType = SceneType.ACT_AGILE; break;
case ActivityType.intelligence: sceneType = SceneType.ACT_INTEL; break;
}
switch (GameLibrary.dungeonId - sn.bigmap_id)
{
case 1: difficulty = DifficultyType.simple; break;
case 2: difficulty = DifficultyType.ordinary; break;
case 3: difficulty = DifficultyType.difficult; break;
case 4: difficulty = DifficultyType.great; break;
case 5: difficulty = DifficultyType.nightmare; break;
case 6: difficulty = DifficultyType.abyss; break;
}
}
GetTypeData(state);
SetMaxWave(maxWave);
SceneUIManager.instance.TowerDefence.ShowUI(false);
CreateMainHero();
escortNPC = player;
ThirdCamera.instance._flatAngle = 270;
propsNode = FSDataNodeTable<ActivityPropsNode>.GetSingleton().FindDataByType(currentWave);
if (null == propsNode)
{
Debug.LogError("Loading jsonData is null.");
return;
}
GetMonsterType(difficulty);
Invoke("CreatMonster", propsNode.interval);
SceneUIManager.instance.TowerDefence.RefreshWave(propsNode.interval, currentWave - rate, maxWave - rate);
player.OnDead += (CharacterState cs) =>
{
WinCondition(false);
playerDeadNum++;
};
SceneNode sceneNode = FSDataNodeTable<SceneNode>.GetSingleton().FindDataByType(GameLibrary.dungeonId);
BattleCDandScore.instance.StartCD(null != sceneNode && sceneNode.time_limit != 0 ? (int)sceneNode.time_limit : 300);
BattleCDandScore.instance.cd.OnRemove += (int count, long id) =>
{
if (player.isDie && BattleCDandScore.instance.cd.Id != id) return;
WinCondition(false);
};
}
public override void SendEndMessage(bool isWin, bool isBackMajor = false)
{
base.SendEndMessage(isWin, isBackMajor);
CancelInvoke("CreatMonster");
}
public override void RemoveCs(CharacterState cs)
{
base.RemoveCs(cs);
if (enemy.size <= 0 && !isCreatMonster)
{
isCreatMonster = true;
NextMonster();
}
}
void NextMonster()
{
if (currentWave >= maxWave)
{
WinCondition(true);
return;
}
currentWave++;
propsNode = FSDataNodeTable<ActivityPropsNode>.GetSingleton().FindDataByType(currentWave);
GetMonsterType(difficulty);
SceneUIManager.instance.TowerDefence.RefreshWave(propsNode.interval, currentWave - rate, maxWave - rate);
Invoke("CreatMonster", propsNode.interval);
}
void CreatMonster()
{
isCreatMonster = false;
if (spwanList.Count < (monster.Length))
{
int count = (monster.Length) - spwanList.Count;
SpawnMonster sm = null;
for (int i = 0; i < count; i++)
{
sm = Instantiate<SpawnMonster>(Spawan);
sm.OnCreatMonster += (GameObject go, CharacterData cd) =>
{
if (go.GetComponent<Monster_AI>())
go.GetComponent<Monster_AI>().targetCs = player;
if (go.GetComponent<CharacterState>())
go.GetComponent<CharacterState>().CharData.attrNode.field_distance *= 100;
//AddCs(go.GetComponent<CharacterState>());
};
sm.transform.parent = transform;
if (!spwanList.Contains(sm))
spwanList.Add(sm);
}
}
else if (spwanList.Count > (monster.Length))
{
int count = spwanList.Count - (monster.Length);
int needCount = spwanList.Count - count;
for (int i = spwanList.Count - 1; i > needCount; i--)
{
spwanList.Remove(spwanList[i]);
}
}
object[] monsterDatas = null;
for (int i = 0; i < (monster.Length); i++)
{
if (monster[i] is int[])
{
int[] mons = monster[i] as int[];
monsterDatas = new object[mons.Length];
for (int j = 0; j < mons.Length; j++)
{
monsterDatas[j] = mons[j];
}
}
else
{
monsterDatas = monster[i] as object[];
}
spwanList[i].transform.position = RandomPos(spwanList[i].transform);
spwanList[i].PropCreatMonster((int)monsterDatas[0], float.Parse(monsterDatas[1].ToString()), float.Parse(monsterDatas[2].ToString()), 1);
}
}
Vector3 RandomPos(Transform sm)
{
BattleUtil.GetRadiusRandomPos(sm, player.transform, 1.5f, 3f);
pos = sm.position;
UnityEngine.AI.NavMeshHit hit;
bool isHit = UnityEngine.AI.NavMesh.SamplePosition(sm.position, out hit, 0.01f, UnityEngine.AI.NavMesh.AllAreas);
if (!isHit)
{
RandomPos(sm);
}
for (int i = 0; i < spwanList.Count; i++)
{
if (sm == spwanList[i].transform) continue;
if (Vector3.Distance(sm.position, spwanList[i].transform.position) < 1.5f / spwanList.Count)
{
RandomPos(sm);
}
}
return pos;
}
void GetTypeData(ActivityType type)
{
switch (type)
{
case ActivityType.power:
currentWave = 1001;
rate = 1000;
break;
case ActivityType.agile:
currentWave = 2001;
rate = 2000;
break;
case ActivityType.intelligence:
currentWave = 3001;
rate = 3000;
break;
default:
break;
}
maxWave = currentWave;
}
void GetMonsterType(DifficultyType type)
{
switch (type)
{
case DifficultyType.simple: GetMonsterData(propsNode.monster_simple); break;
case DifficultyType.ordinary: GetMonsterData(propsNode.monster_ordinary); break;
case DifficultyType.difficult: GetMonsterData(propsNode.monster_difficult); break;
case DifficultyType.great: GetMonsterData(propsNode.monster_great); break;
case DifficultyType.nightmare: GetMonsterData(propsNode.monster_nightmare); break;
case DifficultyType.abyss: GetMonsterData(propsNode.monster_abyss); break;
}
}
void GetMonsterData(object[] mons)
{
monster = mons;
}
void SetMaxWave(int current)
{
switch (state)
{
case ActivityType.power:
if (current >= POWERCOUNT)
return;
break;
case ActivityType.agile:
if (current >= AGILECOUNT)
return;
break;
case ActivityType.intelligence:
if (current >= INTELCOUNT)
return;
break;
}
ActivityPropsNode node = FSDataNodeTable<ActivityPropsNode>.GetSingleton().FindDataByType(current);
if (MonsterIsNull(node))
{
maxWave++;
SetMaxWave(maxWave);
}
else
{
maxWave--;
return;
}
}
bool MonsterIsNull(ActivityPropsNode node)
{
switch (difficulty)
{
case DifficultyType.simple:
if (null == node.monster_simple || node.monster_simple.Length <= 0)
return false;
else
return true;
case DifficultyType.ordinary:
if (null == node.monster_ordinary || node.monster_ordinary.Length <= 0)
return false;
else
return true;
case DifficultyType.difficult:
if (null == node.monster_difficult || node.monster_difficult.Length <= 0)
return false;
else
return true;
case DifficultyType.great:
if (null == node.monster_great || node.monster_great.Length <= 0)
return false;
else
return true;
case DifficultyType.nightmare:
if (null == node.monster_nightmare || node.monster_nightmare.Length <= 0)
return false;
else
return true;
case DifficultyType.abyss:
if (null == node.monster_abyss || node.monster_abyss.Length <= 0)
return false;
else
return true;
}
return false;
}
public override void DisableComponents()
{
base.DisableComponents();
CancelInvoke("CreatMonster");
}
}
| 1 | 0.964442 | 1 | 0.964442 | game-dev | MEDIA | 0.942462 | game-dev | 0.997027 | 1 | 0.997027 |
Phylliida/ResoniteUnityExporter | 4,321 | ExampleUnityProject/Assets/VRCFury/Editor/VF/Service/DriveOtherTypesFromFloatService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using VF.Builder;
using VF.Feature.Base;
using VF.Injector;
using VF.Utils;
using VF.Utils.Controller;
using VRC.SDK3.Avatars.Components;
using VRC.SDKBase;
namespace VF.Service {
[VFService]
internal class DriveOtherTypesFromFloatService {
[VFAutowired] private readonly ControllersService controllers;
private ControllerManager fx => controllers.GetFx();
private VFLayer layer;
private VFState idle;
private readonly Dictionary<string, (VFAInteger,int,VFTransition)> currentSettings = new Dictionary<string, (VFAInteger,int,VFTransition)>();
public void Drive(VFAFloat input, string output, float value) {
if (layer == null) {
layer = fx.NewLayer("Cross-Type Param Driver");
idle = layer.NewState("Idle");
}
if (!currentSettings.ContainsKey(output)) {
var lastState_ = fx.NewInt($"{output}_lastState");
var off = layer.NewState($"{output} = 0");
off.TransitionsToExit().When(fx.Always());
var driver = off.GetRaw().VAddStateMachineBehaviour<VRCAvatarParameterDriver>();
var t = idle.TransitionsTo(off).When(lastState_.IsGreaterThan(0));
driver.parameters.Add(new VRC_AvatarParameterDriver.Parameter() {
name = lastState_,
value = 0
});
driver.parameters.Add(new VRC_AvatarParameterDriver.Parameter() {
name = output,
value = 0
});
currentSettings[output] = (lastState_, 0, t);
}
var (lastState, lastNumber, offTransition) = currentSettings[output];
var myNumber = lastNumber + 1;
{
// Increment the usage number
var c = currentSettings[output];
c.Item2 = myNumber;
currentSettings[output] = c;
}
var name = $"{output} = {value} (from {input.Name()})";
var state = layer.NewState(name);
var condition = input.IsGreaterThan(0);
offTransition.AddCondition(condition.Not());
idle.TransitionsTo(state).When(condition.And(lastState.IsLessThan(myNumber)));
state.TransitionsToExit().When(fx.Always());
var myDriver = state.GetRaw().VAddStateMachineBehaviour<VRCAvatarParameterDriver>();
myDriver.parameters.Add(new VRC_AvatarParameterDriver.Parameter() {
name = lastState,
value = myNumber
});
myDriver.parameters.Add(new VRC_AvatarParameterDriver.Parameter() {
name = output,
value = value
});
}
private readonly List<(VFAFloat,string,float)> drivenParams = new List<(VFAFloat,string,float)>();
public void DriveAutoLater(VFAFloat input, string output, float value) {
drivenParams.Add((input, output, value));
}
[FeatureBuilderAction(FeatureOrder.DriveNonFloatTypes)]
public void DriveNonFloatTypes() {
var nonFloatParams = new HashSet<string>();
foreach (var c in controllers.GetAllUsedControllers()) {
nonFloatParams.UnionWith(c.GetRaw().parameters
.Where(p => p.type != AnimatorControllerParameterType.Float || c.GetType() != VRCAvatarDescriptor.AnimLayerType.FX)
.Select(p => p.name));
}
var rewrites = new Dictionary<string, string>();
foreach (var (floatParam,targetParam,onValue) in drivenParams) {
if (nonFloatParams.Contains(targetParam)) {
Drive(floatParam, targetParam, onValue);
} else {
rewrites.Add(floatParam, targetParam);
}
}
if (rewrites.Count > 0) {
foreach (var c in controllers.GetAllUsedControllers()) {
c.GetRaw().RewriteParameters(from =>
rewrites.TryGetValue(from, out var to) ? to : from
);
}
}
}
}
}
| 1 | 0.907815 | 1 | 0.907815 | game-dev | MEDIA | 0.805414 | game-dev | 0.940393 | 1 | 0.940393 |
leegao/bionic-vulkan-wrapper | 32,827 | src/panfrost/perf/G72.xml | <!--
Copyright © 2017-2020 ARM Limited.
Copyright © 2021-2022 Collabora, Ltd.
Author: Antonio Caggiano <antonio.caggiano@collabora.com>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next
paragraph) 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.
-->
<metrics id="THEx">
<category name="Job Manager" per_cpu="no">
<event offset="6" counter="GPU_ACTIVE" title="GPU Cycles" name="GPU active" description="The number of cycles where the GPU has a workload of any type queued for processing." units="cycles"/>
<event offset="7" advanced="yes" counter="IRQ_ACTIVE" title="GPU Cycles" name="Interrupt active" description="The number of cycles where the GPU has a pending interrupt." units="cycles"/>
<event offset="8" advanced="yes" counter="JS0_JOBS" title="GPU Jobs" name="Fragment jobs" description="The number of jobs processed by the GPU fragment queue." units="jobs"/>
<event offset="9" counter="JS0_TASKS" title="GPU Tasks" name="Fragment tasks" description="The number of 32x32 pixel tasks processed by the GPU fragment queue." units="tasks"/>
<event offset="10" counter="JS0_ACTIVE" title="GPU Cycles" name="Fragment queue active" description="The number of cycles where work is queued for processing in the GPU fragment queue." units="cycles"/>
<event offset="12" advanced="yes" counter="JS0_WAIT_READ" title="GPU Wait Cycles" name="Fragment descriptor reads cycles" description="The number of cycles where queued fragment work is waiting for a descriptor load." units="cycles"/>
<event offset="13" advanced="yes" counter="JS0_WAIT_ISSUE" title="GPU Wait Cycles" name="Fragment job issue cycles" description="The number of cycles where queued fragment work is waiting for an available processor." units="cycles"/>
<event offset="14" advanced="yes" counter="JS0_WAIT_DEPEND" title="GPU Wait Cycles" name="Fragment job dependency cycles" description="The number of cycles where queued fragment work is waiting for dependent work to complete." units="cycles"/>
<event offset="15" advanced="yes" counter="JS0_WAIT_FINISH" title="GPU Wait Cycles" name="Fragment job finish cycles" description="The number of cycles where the GPU is waiting for issued fragment work to complete." units="cycles"/>
<event offset="16" advanced="yes" counter="JS1_JOBS" title="GPU Jobs" name="Non-fragment jobs" description="The number of jobs processed by the GPU non-fragment queue." units="jobs"/>
<event offset="17" advanced="yes" counter="JS1_TASKS" title="GPU Tasks" name="Non-fragment tasks" description="The number of tasks processed by the GPU non-fragment queue." units="tasks"/>
<event offset="18" counter="JS1_ACTIVE" title="GPU Cycles" name="Non-fragment queue active" description="The number of cycles where work is queued in the GPU non-fragment queue." units="cycles"/>
<event offset="20" advanced="yes" counter="JS1_WAIT_READ" title="GPU Wait Cycles" name="Non-fragment descriptor read cycles" description="The number number of cycles where queued non-fragment work is waiting for a descriptor load." units="cycles"/>
<event offset="21" advanced="yes" counter="JS1_WAIT_ISSUE" title="GPU Wait Cycles" name="Non-fragment job issue cycles" description="The number of cycles where queued non-fragment work is waiting for an available processor." units="cycles"/>
<event offset="22" advanced="yes" counter="JS1_WAIT_DEPEND" title="GPU Wait Cycles" name="Non-fragment job dependency cycles" description="The number of cycles where queued non-fragment work is waiting for dependent work to complete." units="cycles"/>
<event offset="23" advanced="yes" counter="JS1_WAIT_FINISH" title="GPU Wait Cycles" name="Non-fragment job finish cycles" description="The number of cycles where the GPU is waiting for issued non-fragment work to complete." units="cycles"/>
<event offset="24" advanced="yes" counter="JS2_JOBS" title="GPU Jobs" name="Reserved jobs" description="The number of jobs processed by the GPU reserved queue." units="jobs"/>
<event offset="25" advanced="yes" counter="JS2_TASKS" title="GPU Tasks" name="Reserved tasks" description="The number of tasks processed by the GPU reserved queue." units="tasks"/>
<event offset="26" advanced="yes" counter="JS2_ACTIVE" title="GPU Cycles" name="Reserved queue active" description="The number of cycles where work is queued in the GPU reserved queue." units="cycles"/>
<event offset="28" advanced="yes" counter="JS2_WAIT_READ" title="GPU Wait Cycles" name="Reserved descriptor read cycles" description="The number of cycles where queued reserved work is waiting for a descriptor load." units="cycles"/>
<event offset="29" advanced="yes" counter="JS2_WAIT_ISSUE" title="GPU Wait Cycles" name="Reserved job issue cycles" description="The number of cycles where queued reserved work is waiting for an available processor." units="cycles"/>
<event offset="30" advanced="yes" counter="JS2_WAIT_DEPEND" title="GPU Wait Cycles" name="Reserved job dependency cycles" description="The number of cycles where queued reserved work is waiting for dependent work to complete." units="cycles"/>
<event offset="31" advanced="yes" counter="JS2_WAIT_FINISH" title="GPU Wait Cycles" name="Reserved job finish cycles" description="The number of cycles where the GPU is waiting for issued reserved work to complete." units="cycles"/>
</category>
<category name="Tiler" per_cpu="no">
<event offset="4" counter="TILER_ACTIVE" title="GPU Cycles" name="Tiler active" description="The number of cycles where the tiler has a workload queued for processing." units="cycles"/>
<event offset="6" counter="TRIANGLES" title="Input Primitives" name="Triangle primitives" description="The number of input triangle primitives." units="primitives"/>
<event offset="7" counter="LINES" title="Input Primitives" name="Line primitives" description="The number of input line primitives." units="primitives"/>
<event offset="8" counter="POINTS" title="Input Primitives" name="Point primitives" description="The number of input point primitives." units="primitives"/>
<event offset="9" counter="FRONT_FACING" title="Visible Primitives" name="Front-facing primitives" description="The number of front-facing triangles that are visible after culling." units="primitives"/>
<event offset="10" counter="BACK_FACING" title="Visible Primitives" name="Back-facing primitives" description="The number of back-facing triangles that are visible after culling." units="primitives"/>
<event offset="11" counter="PRIM_VISIBLE" title="Primitive Culling" name="Visible primitives" description="The number of primitives that are visible after culling." units="primitives"/>
<event offset="12" counter="PRIM_CULLED" title="Primitive Culling" name="Facing and XY plane test culled primitives" description="The number of primitives that are culled by facing or frustum XY plane tests." units="primitives"/>
<event offset="13" counter="PRIM_CLIPPED" title="Primitive Culling" name="Z plane test culled primitives" description="The number of primitives that are culled by frustum Z plane tests." units="primitives"/>
<event offset="14" counter="PRIM_SAT_CULLED" title="Primitive Culling" name="Sample test culled primitives" description="The number of primitives culled by the sample coverage test." units="primitives"/>
<event offset="17" advanced="yes" counter="BUS_READ" title="Tiler L2 Accesses" name="Read beats" description="The number of internal bus data read cycles made by the tiler." units="beats"/>
<event offset="19" advanced="yes" counter="BUS_WRITE" title="Tiler L2 Accesses" name="Write beats" description="The number of internal bus data write cycles made by the tiler." units="beats"/>
<event offset="21" counter="IDVS_POS_SHAD_REQ" title="Tiler Shading Requests" name="Position shading requests" description="The number of position shading requests in the IDVS flow." units="requests"/>
<event offset="23" advanced="yes" counter="IDVS_POS_SHAD_STALL" title="Tiler Cycles" name="Position shading stall cycles" description="The number of cycles where the tiler has a stalled position shading request." units="cycles"/>
<event offset="24" advanced="yes" counter="IDVS_POS_FIFO_FULL" title="Tiler Cycles" name="Position FIFO full cycles" description="The number of cycles where the tiler has a stalled position shading buffer." units="cycles"/>
<event offset="26" advanced="yes" counter="VCACHE_HIT" title="Tiler Vertex Cache" name="Position cache hits" description="The number of position lookups that result in a hit in the vertex cache." units="requests"/>
<event offset="27" advanced="yes" counter="VCACHE_MISS" title="Tiler Vertex Cache" name="Position cache misses" description="The number of position lookups that miss in the vertex cache." units="requests"/>
<event offset="31" advanced="yes" counter="VFETCH_STALL" title="Tiler Cycles" name="Primitive assembly busy stall cycles" description="The number of cycles where the tiler is stalled waiting for primitive assembly." units="cycles"/>
<event offset="34" advanced="yes" counter="IDVS_VBU_HIT" title="Tiler Vertex Cache" name="Varying cache hits" description="The number of varying lookups that result in a hit in the vertex cache." units="requests"/>
<event offset="35" advanced="yes" counter="IDVS_VBU_MISS" title="Tiler Vertex Cache" name="Varying cache misses" description="The number of varying lookups that miss in the vertex cache." units="requests"/>
<event offset="37" counter="IDVS_VAR_SHAD_REQ" title="Tiler Shading Requests" name="Varying shading requests" description="The number of varying shading requests in the IDVS flow." units="requests"/>
<event offset="38" advanced="yes" counter="IDVS_VAR_SHAD_STALL" title="Tiler Cycles" name="Varying shading stall cycles" description="The number of cycles where the tiler has a stalled varying shading request." units="cycles"/>
<event offset="54" advanced="yes" counter="WRBUF_NO_AXI_ID_STALL" title="Tiler Cycles" name="Write buffer transaction stall cycles" description="The number of cycles where the tiler write buffer can not send data because it has no available write IDs." units="cycles"/>
<event offset="55" advanced="yes" counter="WRBUF_AXI_STALL" title="Tiler Cycles" name="Write buffer write stall cycles" description="The number of cycles where the tiler write buffer can not send data because the bus is not ready." units="cycles"/>
</category>
<category name="Memory System" per_cpu="no">
<event offset="4" advanced="yes" counter="MMU_REQUESTS" title="MMU Stage 1 Translations" name="MMU lookups" description="The number of main MMU address translations performed." units="requests"/>
<event offset="16" advanced="yes" counter="L2_RD_MSG_IN" title="L2 Cache Requests" name="Read requests" description="The number of L2 cache read requests from internal masters." units="requests"/>
<event offset="17" advanced="yes" counter="L2_RD_MSG_IN_STALL" title="L2 Cache Stall Cycles" name="Read stall cycles" description="The number of cycles L2 cache read requests from internal masters are stalled." units="cycles"/>
<event offset="18" advanced="yes" counter="L2_WR_MSG_IN" title="L2 Cache Requests" name="Write requests" description="The number of L2 cache write requests from internal masters." units="requests"/>
<event offset="19" advanced="yes" counter="L2_WR_MSG_IN_STALL" title="L2 Cache Stall Cycles" name="Write stall cycles" description="The number of cycles where L2 cache write requests from internal masters are stalled." units="cycles"/>
<event offset="20" advanced="yes" counter="L2_SNP_MSG_IN" title="L2 Cache Requests" name="Snoop requests" description="The number of L2 snoop requests from internal masters." units="requests"/>
<event offset="21" advanced="yes" counter="L2_SNP_MSG_IN_STALL" title="L2 Cache Stall Cycles" name="Snoop stall cycles" description="The number of cycles where L2 cache snoop requests from internal masters are stalled." units="cycles"/>
<event offset="22" advanced="yes" counter="L2_RD_MSG_OUT" title="L2 Cache Requests" name="L1 read requests" description="The number of L1 cache read requests sent by the L2 cache to an internal master." units="requests"/>
<event offset="23" advanced="yes" counter="L2_RD_MSG_OUT_STALL" title="L2 Cache Stall Cycles" name="L1 read stall cycles" description="The number of cycles where L1 cache read requests sent by the L2 cache to an internal master are stalled." units="cycles"/>
<event offset="24" advanced="yes" counter="L2_WR_MSG_OUT" title="L2 Cache Requests" name="L1 write requests" description="The number of L1 cache write responses sent by the L2 cache to an internal master." units="requests"/>
<event offset="25" counter="L2_ANY_LOOKUP" title="L2 Cache Lookups" name="Any lookup" description="The number of L2 cache lookups performed." units="requests"/>
<event offset="26" counter="L2_READ_LOOKUP" title="L2 Cache Lookups" name="Read lookup" description="The number of L2 cache read lookups performed." units="requests"/>
<event offset="27" counter="L2_WRITE_LOOKUP" title="L2 Cache Lookups" name="Write lookup" description="The number of L2 cache write lookups performed." units="requests"/>
<event offset="28" advanced="yes" counter="L2_EXT_SNOOP_LOOKUP" title="L2 Cache Lookups" name="External snoop lookups" description="The number of coherency snoop lookups performed that were triggered by an external master." units="requests"/>
<event offset="29" counter="L2_EXT_READ" title="External Bus Accesses" name="Read transaction" description="The number of external read transactions." units="transactions"/>
<event offset="30" advanced="yes" counter="L2_EXT_READ_NOSNP" title="External Bus Accesses" name="ReadNoSnoop transactions" description="The number of external non-coherent read transactions." units="transactions"/>
<event offset="31" advanced="yes" counter="L2_EXT_READ_UNIQUE" title="External Bus Accesses" name="ReadUnique transactions" description="The number of external coherent read unique transactions." units="transactions"/>
<event offset="32" counter="L2_EXT_READ_BEATS" title="External Bus Beats" name="Read beat" description="The number of external bus data read cycles." units="beats"/>
<event offset="33" counter="L2_EXT_AR_STALL" title="External Bus Stalls" name="Read stall cycles" description="The number of cycles where a read is stalled waiting for the external bus." units="cycles"/>
<event offset="34" counter="L2_EXT_AR_CNT_Q1" title="External Bus Outstanding Reads" name="0-25% outstanding" description="The number of read transactions initiated when 0-25% of the maximum are in use." units="transactions"/>
<event offset="35" counter="L2_EXT_AR_CNT_Q2" title="External Bus Outstanding Reads" name="25-50% outstanding" description="The number of read transactions initiated when 25-50% of the maximum are in use." units="transactions"/>
<event offset="36" counter="L2_EXT_AR_CNT_Q3" title="External Bus Outstanding Reads" name="50-75% outstanding" description="The number of read transactions initiated when 50-75% of the maximum are in use." units="transactions"/>
<event offset="37" counter="L2_EXT_RRESP_0_127" title="External Bus Read Latency" name="0-127 cycles" description="The number of data beats returned 0-127 cycles after the read request." units="beats"/>
<event offset="38" counter="L2_EXT_RRESP_128_191" title="External Bus Read Latency" name="128-191 cycles" description="The number of data beats returned 128-191 cycles after the read request." units="beats"/>
<event offset="39" counter="L2_EXT_RRESP_192_255" title="External Bus Read Latency" name="192-255 cycles" description="The number of data beats returned 192-255 cycles after the read request." units="beats"/>
<event offset="40" counter="L2_EXT_RRESP_256_319" title="External Bus Read Latency" name="256-319 cycles" description="The number of data beats returned 256-319 cycles after the read request." units="beats"/>
<event offset="41" counter="L2_EXT_RRESP_320_383" title="External Bus Read Latency" name="320-383 cycles" description="The number of data beats returned 320-383 cycles after the read request." units="beats"/>
<event offset="42" counter="L2_EXT_WRITE" title="External Bus Accesses" name="Write transaction" description="The number of external write transactions." units="transactions"/>
<event offset="43" advanced="yes" counter="L2_EXT_WRITE_NOSNP_FULL" title="External Bus Accesses" name="WriteNoSnoopFull transactions" description="The number of external non-coherent full write transactions." units="transactions"/>
<event offset="44" advanced="yes" counter="L2_EXT_WRITE_NOSNP_PTL" title="External Bus Accesses" name="WriteNoSnoopPartial transactions" description="The number of external non-coherent partial write transactions." units="transactions"/>
<event offset="45" advanced="yes" counter="L2_EXT_WRITE_SNP_FULL" title="External Bus Accesses" name="WriteSnoopFull transactions" description="The number of external coherent full write transactions." units="transactions"/>
<event offset="46" advanced="yes" counter="L2_EXT_WRITE_SNP_PTL" title="External Bus Accesses" name="WriteSnoopPartial transactions" description="The number of external coherent partial write transactions." units="transactions"/>
<event offset="47" counter="L2_EXT_WRITE_BEATS" title="External Bus Beats" name="Write beat" description="The number of external bus data write cycles." units="beats"/>
<event offset="48" counter="L2_EXT_W_STALL" title="External Bus Stalls" name="Write stall cycles" description="The number of cycles where a write is stalled waiting for the external bus." units="cycles"/>
<event offset="49" counter="L2_EXT_AW_CNT_Q1" title="External Bus Outstanding Writes" name="0-25% outstanding" description="The number of write transactions initiated when 0-25% of the maximum are in use." units="transactions"/>
<event offset="50" counter="L2_EXT_AW_CNT_Q2" title="External Bus Outstanding Writes" name="25-50% outstanding" description="The number of write transactions initiated when 25-50% of the maximum are in use." units="transactions"/>
<event offset="51" counter="L2_EXT_AW_CNT_Q3" title="External Bus Outstanding Writes" name="50-75% outstanding" description="The number of write transactions initiated when 50-75% of the maximum are in use." units="transactions"/>
<event offset="52" advanced="yes" counter="L2_EXT_SNOOP" title="External Bus Accesses" name="Snoop transactions" description="The number of coherency snoops triggered by external masters." units="transactions"/>
<event offset="53" advanced="yes" counter="L2_EXT_SNOOP_STALL" title="External Bus Stalls" name="Snoop stall cycles" description="The number of cycles where a coherency snoop triggered by external master is stalled." units="cycles"/>
</category>
<category name="Shader Core" per_cpu="no">
<event offset="4" counter="FRAG_ACTIVE" title="Core Cycles" name="Fragment active" description="The number of cycles where the shader core is processing a fragment workload." units="cycles"/>
<event offset="5" advanced="yes" counter="FRAG_PRIMITIVES" title="Core Primitives" name="Read primitives" description="The number of primitives read from the tile list by the fragment front-end." units="primitives"/>
<event offset="6" counter="FRAG_PRIM_RAST" title="Core Primitives" name="Rasterized primitives" description="The number of primitives being rasterized." units="primitives"/>
<event offset="7" counter="FRAG_FPK_ACTIVE" title="Core Cycles" name="Fragment FPKB active" description="The number of cycles where at least one quad is present in the pre-pipe quad queue." units="cycles"/>
<event offset="9" counter="FRAG_WARPS" title="Core Warps" name="Fragment warps" description="The number of fragment warps created." units="warps"/>
<event offset="10" counter="FRAG_PARTIAL_WARPS" title="Core Warps" name="Partial fragment warps" description="The number of fragment warps containing helper threads that do not correspond to a hit sample point." units="warps"/>
<event offset="11" counter="FRAG_QUADS_RAST" title="Core Quads" name="Rasterized quads" description="The number of quads generated by the rasterization phase." units="quads"/>
<event offset="12" counter="FRAG_QUADS_EZS_TEST" title="Core Quads" name="Early ZS tested quads" description="The number of quads that are undergoing early depth and stencil testing." units="quads"/>
<event offset="13" counter="FRAG_QUADS_EZS_UPDATE" title="Core Quads" name="Early ZS updated quads" description="The number of quads undergoing early depth and stencil testing, that are capable of updating the framebuffer." units="quads"/>
<event offset="14" counter="FRAG_QUADS_EZS_KILL" title="Core Quads" name="Early ZS killed quads" description="The number of quads killed by early depth and stencil testing." units="quads"/>
<event offset="15" counter="FRAG_LZS_TEST" title="Core Quads" name="Late ZS tested quads" description="The number of quads undergoing late depth and stencil testing." units="quads"/>
<event offset="16" counter="FRAG_LZS_KILL" title="Core Quads" name="Late ZS killed quads" description="The number of quads killed by late depth and stencil testing." units="quads"/>
<event offset="18" counter="FRAG_PTILES" title="Core Tiles" name="Tiles" description="The number of tiles processed by the shader core." units="tiles"/>
<event offset="19" counter="FRAG_TRANS_ELIM" title="Core Tiles" name="Constant tiles killed" description="The number of tiles killed by transaction elimination." units="tiles"/>
<event offset="20" counter="QUAD_FPK_KILLER" title="Core Quads" name="FPK occluder quads" description="The number of quads that are valid occluders for hidden surface removal." units="quads"/>
<event offset="22" counter="COMPUTE_ACTIVE" title="Core Cycles" name="Non-fragment active" description="The number of cycles where the shader core is processing some non-fragment workload." units="cycles"/>
<event offset="23" advanced="yes" counter="COMPUTE_TASKS" title="Core Tasks" name="Non-fragment tasks" description="The number of non-fragment tasks issued to the shader core." units="tasks"/>
<event offset="24" counter="COMPUTE_WARPS" title="Core Warps" name="Non-fragment warps" description="The number of non-fragment warps created." units="warps"/>
<event offset="25" advanced="yes" counter="COMPUTE_STARVING" title="Core Starvation Cycles" name="Non-fragment starvation cycles" description="The number of cycles where the shader core is processing a non-fragment workload and there are no new threads available for execution." units="cycles"/>
<event offset="26" counter="EXEC_CORE_ACTIVE" title="Core Cycles" name="Execution core active" description="The number of cycles where the shader core is processing at least one warp." units="cycles"/>
<event offset="27" advanced="yes" counter="EXEC_ACTIVE" title="Core Cycles" name="Execution engine active" description="The number of cycles where the execution engine unit is processing at least one thread." units="cycles"/>
<event offset="28" counter="EXEC_INSTR_COUNT" title="Core EE Instructions" name="Executed instructions" description="The number of instructions executed per warp." units="instructions"/>
<event offset="29" counter="EXEC_INSTR_DIVERGED" title="Core EE Instructions" name="Diverged instructions" description="The number of instructions executed per warp, that have control flow divergence." units="instructions"/>
<event offset="30" advanced="yes" counter="EXEC_INSTR_STARVING" title="Core Starvation Cycles" name="Execution engine starvation cycles" description="The number of cycles where no new threads are available for execution." units="cycles"/>
<event offset="31" advanced="yes" counter="ARITH_INSTR_SINGLE_FMA" title="Core EE Instructions" name="Arithmetic instructions" description="The number of instructions where the workload is a single FMA pipe arithmetic operation." units="instructions"/>
<event offset="32" advanced="yes" counter="ARITH_INSTR_DOUBLE" title="Core EE Instructions" name="Dual Arithmetic instructions" description="The number of instructions where the workload is one FMA pipe arithmetic operation and one ADD pipe arithmetic operation." units="instructions"/>
<event offset="33" advanced="yes" counter="ARITH_INSTR_MSG" title="Core EE Instructions" name="Arithmetic + Message instructions" description="The number of instructions where the workload is one FMA pipe arithmetic operation and one ADD pipe message operation" units="instructions"/>
<event offset="34" advanced="yes" counter="ARITH_INSTR_MSG_ONLY" title="Core EE Instructions" name="Message instructions" description="The number of instructions where the workload is a single ADD pipe message operation, with no FMA pipe operation" units="instructions"/>
<event offset="35" counter="TEX_INSTR" title="Core Texture Requests" name="Texture requests" description="The number of thread-width texture operations processed." units="instructions"/>
<event offset="36" counter="TEX_INSTR_MIPMAP" title="Core Texture Requests" name="Mipmapped texture request" description="The number of texture operations that act on a mipmapped texture." units="instructions"/>
<event offset="37" counter="TEX_INSTR_COMPRESSED" title="Core Texture Requests" name="Compressed texture requests" description="The number of texture operations acting on a compressed texture." units="instructions"/>
<event offset="38" counter="TEX_INSTR_3D" title="Core Texture Requests" name="3D texture requests" description="The number of texture operations acting on a 3D texture." units="instructions"/>
<event offset="39" counter="TEX_INSTR_TRILINEAR" title="Core Texture Requests" name="Trilinear filtered requests" description="The number of texture operations using a trilinear texture filter." units="instructions"/>
<event offset="40" counter="TEX_COORD_ISSUE" title="Core Texture Cycles" name="Texturing active" description="The number of texture filtering issue cycles." units="cycles"/>
<event offset="41" advanced="yes" counter="TEX_COORD_STALL" title="Core Texture Cycles" name="Coordinate stall cycles" description="The number of clock cycles where threads are stalled at the texel coordinate calculation stage." units="cycles"/>
<event offset="42" advanced="yes" counter="TEX_STARVE_CACHE" title="Core Texture Cycles" name="Line fill stall cycles" description="The number of clock cycles where at least one thread is waiting for data from the texture cache, but no lookup is completed." units="cycles"/>
<event offset="43" advanced="yes" counter="TEX_STARVE_FILTER" title="Core Texture Cycles" name="Partial data stall cycles" description="The number of clock cycles where at least one thread fetched some data from the texture cache, but no filtering operation is started." units="cycles"/>
<event offset="44" counter="LS_MEM_READ_FULL" title="Core Load/Store Cycles" name="Full read cycles" description="The number of full-width load/store cache reads." units="cycles"/>
<event offset="45" counter="LS_MEM_READ_SHORT" title="Core Load/Store Cycles" name="Partial read cycles" description="The number of partial-width load/store cache reads." units="cycles"/>
<event offset="46" counter="LS_MEM_WRITE_FULL" title="Core Load/Store Cycles" name="Full write cycles" description="The number of full-width load/store cache writes." units="cycles"/>
<event offset="47" counter="LS_MEM_WRITE_SHORT" title="Core Load/Store Cycles" name="Partial write cycles" description="The number of partial-width load/store cache writes." units="cycles"/>
<event offset="48" counter="LS_MEM_ATOMIC" title="Core Load/Store Cycles" name="Atomic access cycles" description="The number of load/store atomic accesses." units="cycles"/>
<event offset="49" counter="VARY_INSTR" title="Core Varying Requests" name="Interpolation requests" description="The number of warp-width interpolation operations processed by the varying unit." units="instructions"/>
<event offset="50" counter="VARY_SLOT_32" title="Core Varying Cycles" name="32-bit interpolation active" description="The number of 32-bit interpolation cycles processed by the varying unit." units="cycles"/>
<event offset="51" counter="VARY_SLOT_16" title="Core Varying Cycles" name="16-bit interpolation active" description="The number of 16-bit interpolation cycles processed by the varying unit." units="cycles"/>
<event offset="52" advanced="yes" counter="ATTR_INSTR" title="Core Attribute Requests" name="Attribute requests" description="The number of instructions executed by the attribute unit." units="instructions"/>
<event offset="53" advanced="yes" counter="ARITH_INSTR_FP_MUL" title="Core EE Instructions" name="Multiplier instructions" description="The number of instructions where the workload uses floating-point multiplier hardware." units="instructions"/>
<event offset="54" counter="BEATS_RD_FTC" title="Core L2 Reads" name="Fragment L2 read beats" description="The number of read beats received by the fixed-function fragment front-end." units="beats"/>
<event offset="55" counter="BEATS_RD_FTC_EXT" title="Core L2 Reads" name="Fragment external read beats" description="The number of read beats received by the fixed-function fragment front-end that required an external memory access due to an L2 cache miss." units="beats"/>
<event offset="56" counter="BEATS_RD_LSC" title="Core L2 Reads" name="Load/store L2 read beats" description="The number of read beats received by the load/store unit." units="beats"/>
<event offset="57" counter="BEATS_RD_LSC_EXT" title="Core L2 Reads" name="Load/store external read beats" description="The number of read beats received by the load/store unit that required an external memory access due to an L2 cache miss." units="beats"/>
<event offset="58" counter="BEATS_RD_TEX" title="Core L2 Reads" name="Texture L2 read beats" description="The number of read beats received by the texture unit." units="beats"/>
<event offset="59" counter="BEATS_RD_TEX_EXT" title="Core L2 Reads" name="Texture external read beats" description="The number of read beats received by the texture unit that required an external memory access due to an L2 cache miss." units="beats"/>
<event offset="60" advanced="yes" counter="BEATS_RD_OTHER" title="Core L2 Reads" name="Other L2 read beats" description="The number of read beats received by a unit that is not specifically identified." units="beats"/>
<event offset="61" counter="BEATS_WR_LSC" title="Core Writes" name="Load/store write beats" description="The number of write beats sent by the load/store unit." units="beats"/>
<event offset="62" counter="BEATS_WR_TIB" title="Core Writes" name="Tile buffer write beats" description="The number of write beats sent by the tile buffer writeback unit." units="beats"/>
<event offset="63" advanced="yes" counter="BEATS_WR_OTHER" title="Core Writes" name="Other write beats" description="The number of write beats sent by any unit that is not specifically identified." units="beats"/>
</category>
</metrics> | 1 | 0.877332 | 1 | 0.877332 | game-dev | MEDIA | 0.371835 | game-dev | 0.667284 | 1 | 0.667284 |
AppliedEnergistics/Applied-Energistics-2 | 2,958 | src/main/java/appeng/core/definitions/AEEntities.java | /*
* This file is part of Applied Energistics 2.
* Copyright (c) 2021, TeamAppliedEnergistics, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 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 Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.core.definitions;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import net.minecraft.SharedConstants;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.EntityType.Builder;
import net.minecraft.world.entity.EntityType.EntityFactory;
import net.minecraft.world.entity.MobCategory;
import net.neoforged.neoforge.registries.DeferredHolder;
import net.neoforged.neoforge.registries.DeferredRegister;
import appeng.core.AppEng;
import appeng.entity.TinyTNTPrimedEntity;
public final class AEEntities {
public static final DeferredRegister<EntityType<?>> DR = DeferredRegister.create(Registries.ENTITY_TYPE,
AppEng.MOD_ID);
public static final Map<String, String> ENTITY_ENGLISH_NAMES = new HashMap<>();
public static final DeferredHolder<EntityType<?>, EntityType<TinyTNTPrimedEntity>> TINY_TNT_PRIMED = create(
"tiny_tnt_primed",
"Tiny TNT Primed",
TinyTNTPrimedEntity::new,
MobCategory.MISC,
builder -> builder.setTrackingRange(16).setUpdateInterval(4).setShouldReceiveVelocityUpdates(true));
private static <T extends Entity> DeferredHolder<EntityType<?>, EntityType<T>> create(String id,
String englishName,
EntityFactory<T> entityFactory,
MobCategory classification,
Consumer<Builder<T>> customizer) {
ENTITY_ENGLISH_NAMES.put(id, englishName);
return DR.register(id, () -> {
Builder<T> builder = Builder.of(entityFactory, classification);
customizer.accept(builder);
// Temporarily disable the data fixer check to avoid the annoying "no data fixer registered for ae2:xxx".
boolean prev = SharedConstants.CHECK_DATA_FIXER_SCHEMA;
SharedConstants.CHECK_DATA_FIXER_SCHEMA = false;
EntityType<T> result = builder.build(id);
SharedConstants.CHECK_DATA_FIXER_SCHEMA = prev;
return result;
});
}
}
| 1 | 0.774598 | 1 | 0.774598 | game-dev | MEDIA | 0.957431 | game-dev | 0.830085 | 1 | 0.830085 |
perkowitz/issho | 5,648 | src/main/java/net/perkowitz/issho/hachi/modules/seq/SeqPattern.java | package net.perkowitz.issho.hachi.modules.seq;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.Setter;
import net.perkowitz.issho.hachi.MemoryObject;
import net.perkowitz.issho.hachi.MemoryUtil;
import org.codehaus.jackson.annotate.JsonIgnore;
import java.util.List;
import static net.perkowitz.issho.hachi.modules.seq.SeqUtil.STEP_COUNT;
import static net.perkowitz.issho.hachi.modules.seq.SeqUtil.SeqMode.BEAT;
/**
* Created by optic on 2/25/17.
*/
public class SeqPattern implements MemoryObject {
public static int JUMP_TO_OFF = 0;
public static int JUMP_TO_RANDOM = 1;
@Getter @Setter private int index;
@Getter private List<SeqTrack> tracks = Lists.newArrayList();
@Getter private List<SeqControlTrack> controlTracks = Lists.newArrayList();
@Getter private List<SeqPitchStep> pitchTrack = Lists.newArrayList();
private SeqControlTrack jumpTrack;
public SeqPattern() {}
public SeqPattern(int index, SeqUtil.SeqMode mode) {
this.index = index;
// for beat mode, create multiple tracks
if (mode == BEAT) {
for (int i = 0; i < SeqUtil.BEAT_TRACK_COUNT; i++) {
tracks.add(new SeqTrack(i, SeqUtil.BEAT_TRACK_NOTES[i]));
}
} else {
tracks.add(new SeqTrack(0, null));
}
// create the control tracks
for (int i = 0; i < SeqUtil.CONTROL_TRACK_COUNT; i++) {
controlTracks.add(new SeqControlTrack(i));
}
// create the pitch track
for (int i = 0; i < STEP_COUNT; i++) {
pitchTrack.add(new SeqPitchStep(i));
}
jumpTrack = new SeqControlTrack(-1);
}
@JsonIgnore public SeqTrack getTrack(int index) {
if (index >= 0 && index < tracks.size()) {
return tracks.get(index);
}
return null;
}
@JsonIgnore public SeqStep getStep(int trackIndex, int stepIndex) {
return getTrack(trackIndex).getStep(stepIndex);
}
@JsonIgnore public SeqControlTrack getControlTrack(int index) { return controlTracks.get(index); }
public String toString() {
return String.format("SeqPattern:%02d", index);
}
public SeqPitchStep getPitchStep(int stepIndex) {
return pitchTrack.get(stepIndex);
}
@JsonIgnore
public void setJump(int index, boolean jump) {
if (index < 0 || index > STEP_COUNT) {
return;
}
if (jumpTrack == null || jumpTrack.getStep(index) == null) {
jumpTrack = new SeqControlTrack(-1);
}
SeqControlStep step = jumpTrack.getStep(index);
if (jump) {
step.setValue(JUMP_TO_RANDOM);
} else {
step.setValue(JUMP_TO_OFF);
}
}
public void toggleJump(int index) {
if (index < 0 || index > STEP_COUNT) {
return;
}
if (jumpTrack == null || jumpTrack.getStep(index) == null) {
jumpTrack = new SeqControlTrack(-1);
}
SeqControlStep step = jumpTrack.getStep(index);
if (step.getValue() == JUMP_TO_RANDOM) {
step.setValue(JUMP_TO_OFF);
} else {
step.setValue(JUMP_TO_RANDOM);
}
}
@JsonIgnore
public boolean getJump(int index) {
if (index < 0 || index > STEP_COUNT) {
return false;
}
if (jumpTrack == null || jumpTrack.getStep(index) == null) {
jumpTrack = new SeqControlTrack(-1);
}
return (jumpTrack.getStep(index).getValue() == JUMP_TO_RANDOM);
}
/***** MemoryObject implementation ***********************/
public List<MemoryObject> list() {
List<MemoryObject> objects = Lists.newArrayList();
for (SeqTrack track : tracks) {
objects.add(track);
}
return objects;
}
public void put(int index, MemoryObject memoryObject) {
if (memoryObject instanceof SeqTrack) {
SeqTrack track = (SeqTrack) memoryObject;
track.setIndex(index);
tracks.set(index, track);
} else {
System.out.printf("Cannot put object %s of type %s in object %s\n", memoryObject, memoryObject.getClass().getSimpleName(), this);
}
}
public boolean nonEmpty() {
for (MemoryObject object : list()) {
if (object.nonEmpty()) {
return true;
}
}
return false;
}
public MemoryObject clone() {
return SeqPattern.copy(this, this.index);
}
public String render() {
return MemoryUtil.countRender(this);
}
/***** static methods **************************/
public static SeqPattern copy(SeqPattern pattern, int newIndex) {
SeqPattern newPattern = new SeqPattern();
newPattern.setIndex(newIndex);
try {
for (int i = 0; i < pattern.tracks.size(); i++) {
newPattern.tracks.add(SeqTrack.copy(pattern.tracks.get(i), i));
}
for (int i = 0; i < pattern.controlTracks.size(); i++) {
newPattern.controlTracks.add(SeqControlTrack.copy(pattern.controlTracks.get(i), i));
}
List<SeqPitchStep> pitchTrack = Lists.newArrayList();
for (int i = 0; i < STEP_COUNT; i++) {
SeqPitchStep seqPitchStep = SeqPitchStep.copy(pattern.getPitchStep(i), i);
pitchTrack.add(seqPitchStep);
}
newPattern.pitchTrack = pitchTrack;
} catch (Exception e) {
e.printStackTrace();
}
return newPattern;
}
}
| 1 | 0.723763 | 1 | 0.723763 | game-dev | MEDIA | 0.321441 | game-dev | 0.861007 | 1 | 0.861007 |
Sigma-Skidder-Team/SigmaRemap | 6,305 | src/main/java/mapped/Class8181.java | package mapped;
import com.mentalfrostbyte.Client;
import com.mentalfrostbyte.jello.event.impl.EventBlockCollision;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.ICollisionReader;
import java.util.Objects;
import java.util.Spliterators.AbstractSpliterator;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import javax.annotation.Nullable;
public class Class8181 extends AbstractSpliterator<VoxelShape> {
private static String[] field35185;
private final Entity field35186;
private final AxisAlignedBB field35187;
private final ISelectionContext field35188;
private final CubeCoordinateIterator field35189;
private final BlockPos.Mutable field35190;
private final VoxelShape field35191;
private final ICollisionReader field35192;
private boolean field35193;
private final BiPredicate<BlockState, BlockPos> field35194;
public Class8181(ICollisionReader var1, Entity var2, AxisAlignedBB var3) {
this(var1, var2, var3, (var0, var1x) -> true);
}
public Class8181(ICollisionReader var1, Entity var2, AxisAlignedBB var3, BiPredicate<BlockState, BlockPos> var4) {
super(Long.MAX_VALUE, 1280);
this.field35188 = var2 != null ? ISelectionContext.forEntity(var2) : ISelectionContext.method14947();
this.field35190 = new BlockPos.Mutable();
this.field35191 = VoxelShapes.create(var3);
this.field35192 = var1;
this.field35193 = var2 != null;
this.field35186 = var2;
this.field35187 = var3;
this.field35194 = var4;
int var7 = MathHelper.floor(var3.minX - 1.0E-7) - 1;
int var8 = MathHelper.floor(var3.maxX + 1.0E-7) + 1;
int var9 = MathHelper.floor(var3.minY - 1.0E-7) - 1;
int var10 = MathHelper.floor(var3.maxY + 1.0E-7) + 1;
int var11 = MathHelper.floor(var3.minZ - 1.0E-7) - 1;
int var12 = MathHelper.floor(var3.maxZ + 1.0E-7) + 1;
this.field35189 = new CubeCoordinateIterator(var7, var9, var11, var8, var10, var12);
}
@Override
public boolean tryAdvance(Consumer<? super VoxelShape> var1) {
return this.field35193 && this.method28475(var1) || this.method28473(var1);
}
public boolean method28473(Consumer<? super VoxelShape> var1) {
while (this.field35189.hasNext()) {
int var4 = this.field35189.getX();
int var5 = this.field35189.getY();
int var6 = this.field35189.getZ();
int var7 = this.field35189.numBoundariesTouched();
if (var7 != 3) {
IBlockReader var8 = this.method28474(var4, var6);
if (var8 != null) {
this.field35190.setPos(var4, var5, var6);
BlockState var9 = var8.getBlockState(this.field35190);
if (this.field35194.test(var9, this.field35190) && (var7 != 1 || var9.method23390())
&& (var7 != 2 || var9.isIn(Blocks.MOVING_PISTON))) {
VoxelShape var10 = var9.getCollisionShape(this.field35192, this.field35190, this.field35188);
if (this.field35186 instanceof PlayerEntity) {
EventBlockCollision var11 = new EventBlockCollision(this.field35190, var10);
Client.getInstance().eventManager.call(var11);
var10 = var11.getVoxelShape();
if (var11.isCancelled()) {
return false;
}
}
if (var10 != VoxelShapes.method27426()) {
VoxelShape var12 = var10.withOffset((double) var4, (double) var5, (double) var6);
if (VoxelShapes.compare(var12, this.field35191, IBooleanFunction.AND)) {
var1.accept(var12);
return true;
}
} else if (this.field35187.intersects((double) var4, (double) var5, (double) var6,
(double) var4 + 1.0, (double) var5 + 1.0, (double) var6 + 1.0)) {
var1.accept(var10.withOffset((double) var4, (double) var5, (double) var6));
return true;
}
}
}
}
}
return false;
}
@Nullable
private IBlockReader method28474(int var1, int var2) {
int var5 = var1 >> 4;
int var6 = var2 >> 4;
return this.field35192.getBlockReader(var5, var6);
}
public boolean method28475(Consumer<? super VoxelShape> var1) {
Objects.<Entity>requireNonNull(this.field35186);
this.field35193 = false;
WorldBorder var4 = this.field35192.getWorldBorder();
AxisAlignedBB var5 = this.field35186.getBoundingBox();
if (!method28478(var4, var5)) {
VoxelShape var6 = var4.getShape();
if (!method28477(var6, var5) && method28476(var6, var5)) {
var1.accept(var6);
return true;
}
}
return false;
}
private static boolean method28476(VoxelShape var0, AxisAlignedBB var1) {
return VoxelShapes.compare(var0, VoxelShapes.create(var1.grow(1.0E-7)), IBooleanFunction.AND);
}
private static boolean method28477(VoxelShape var0, AxisAlignedBB var1) {
return VoxelShapes.compare(var0, VoxelShapes.create(var1.shrink(1.0E-7)), IBooleanFunction.AND);
}
public static boolean method28478(WorldBorder var0, AxisAlignedBB var1) {
double var4 = (double) MathHelper.floor(var0.method24530());
double var6 = (double) MathHelper.floor(var0.method24531());
double var8 = (double) MathHelper.method37774(var0.method24532());
double var10 = (double) MathHelper.method37774(var0.method24533());
return var1.minX > var4
&& var1.minX < var8
&& var1.minZ > var6
&& var1.minZ < var10
&& var1.maxX > var4
&& var1.maxX < var8
&& var1.maxZ > var6
&& var1.maxZ < var10;
}
}
| 1 | 0.758108 | 1 | 0.758108 | game-dev | MEDIA | 0.7292 | game-dev | 0.757373 | 1 | 0.757373 |
arendjr/PlainText | 2,831 | src/entity/behaviors/actor.rs | use crate::{
actionable_events::ActionDispatcher,
actions::ActionOutput,
entity::{EntityRef, Realm},
};
pub trait Actor: std::fmt::Debug {
/// Returns whether the actor's `on_active()` callback should be invoked when the actor becomes
/// idle after performing an action.
fn activate_on_idle(&self) -> bool {
false
}
/// Activates an actor.
///
/// Actors are responsible for scheduling their own activation based on any of the other
/// triggers in this trait. The only time `on_active()` is called automatically is when
/// `activate_on_idle()` returns `true` and the actor becomes idle again after performing
/// some other action.
fn on_active(&self, _realm: &mut Realm, _dispatcher: &ActionDispatcher) -> ActionOutput {
Ok(Vec::new())
}
/// Invoked when the actor itself is being attacked.
fn on_attack(
&self,
_realm: &mut Realm,
_dispatcher: &ActionDispatcher,
_attacker: EntityRef,
) -> ActionOutput {
Ok(Vec::new())
}
/// Invoked when a character in the same room is being attacked.
fn on_character_attacked(
&self,
_realm: &mut Realm,
_dispatcher: &ActionDispatcher,
_attacker: EntityRef,
_defendent: EntityRef,
) -> ActionOutput {
Ok(Vec::new())
}
/// Invoked when a character in the same room dies.
///
/// If the character dies as a direct result of another character's attack, the attacker
/// is given as well.
fn on_character_died(
&self,
_realm: &mut Realm,
_dispatcher: &ActionDispatcher,
_casualty: EntityRef,
_attacker: Option<EntityRef>,
) -> ActionOutput {
Ok(Vec::new())
}
/// Invoked when a character entered the same room.
fn on_character_entered(
&mut self,
_realm: &mut Realm,
_dispatcher: &ActionDispatcher,
_character: EntityRef,
) -> ActionOutput {
Ok(Vec::new())
}
/// Invoked when the character itself dies.
///
/// If the character dies as a direct result of another character's attack, the attacker
/// is given as well.
fn on_die(
&self,
_realm: &mut Realm,
_dispatcher: &ActionDispatcher,
_attacker: Option<EntityRef>,
) -> ActionOutput {
Ok(Vec::new())
}
/// Invoked when the actor is spawned.
fn on_spawn(&self, _realm: &mut Realm, _dispatcher: &ActionDispatcher) -> ActionOutput {
Ok(Vec::new())
}
/// Invoked when a character talks directly to the actor.
fn on_talk(
&self,
_realm: &mut Realm,
_dispatcher: &ActionDispatcher,
_speaker: EntityRef,
_message: &str,
) -> ActionOutput {
Ok(Vec::new())
}
}
| 1 | 0.932809 | 1 | 0.932809 | game-dev | MEDIA | 0.981026 | game-dev | 0.893221 | 1 | 0.893221 |
RedPandaProjects/STALKERonUE | 3,840 | gamedata_cs/scripts/ph_sound.script | class "snd_source"
function snd_source:__init (obj, storage)
self.object = obj
self.st = storage
self.destructed = false
end
function snd_source:reset_scheme(loading)
self.last_update = 0
self.st.signals = {}
self.played_sound = nil
self.first_sound = true
self.st.pause_time = 0
self.st.sound_set = true
if loading == false then
self.destructed = false
else
self.destructed = xr_logic.pstor_retrieve (self.object, "destr")
end
end
function snd_source:save ()
xr_logic.pstor_store (self.object, "destr", self.destructed)
end
function snd_source:hit_callback(obj, amount, local_direction, who, bone_index)
if self.st.no_hit == true then return end
printf ("SOUND SOURCE HAVE A HIT")
local who_name
if who then
who_name = who:name()
else
who_name = "nil"
end
printf("_bp: snd_source:hit_callback obj='%s', amount=%d, who='%s'", obj:name(), amount, who_name)
if self.played_sound ~= nil then
self.played_sound:stop ()
self.played_sound = nil
end
self.destructed = true
end
function snd_source:update(delta)
if self.destructed == true then return end
if xr_logic.try_switch_to_another_section (self.object, self.st, db.actor) then
return
end
if self.st.pause_time - device ():time_global () > 0 then
return
end
self.st.pause_time = 0
if self.st.sound_set == true then
self.st.sound_set = false
if self.st.random then
self.played_sound = xr_sound.get_sound_object(self.st.theme, "random")
elseif self.st.looped then
self.played_sound = xr_sound.get_sound_object(self.st.theme, "looped")
else
self.played_sound = xr_sound.get_sound_object(self.st.theme, "seq")
end
if self.played_sound ~= nil then
self.played_sound:play_at_pos (self.object, self.object:position ())
else
self.st.signals["theme_end"] = true
end
self.first_sound = false
end
if self.last_update == 0 then
self.last_update = device ():time_global ()
else
if device ():time_global () - self.last_update > 50 then
self.last_update = 0
else
return
end
end
if self.played_sound ~= nil then
if self.played_sound:playing () == false then
if self.first_sound == false then
self.st.signals["sound_end"] = true
end
self.st.sound_set = true
if self.st.pause_min ~= 0 or self.st.pause_max ~= 0 then
local time = math.random (self.st.pause_min, self.st.pause_max)
self.st.pause_time = device ():time_global () + time
end
self.first_sound = false
else
self.played_sound:set_position (self.object:position ())
end
end
end
function snd_source:deactivate ()
if self.played_sound ~= nil then
self.played_sound:stop ()
self.played_sound = nil
end
end
function add_to_binder (npc, ini, scheme, section, storage)
local new_action = snd_source (npc, storage)
-- actions, reset_scheme :
xr_logic.subscribe_action_for_events(npc, storage, new_action)
end
function set_scheme(npc, ini, scheme, section, gulag_name)
local st = xr_logic.assign_storage_and_bind(npc, ini, scheme, section)
st.logic = xr_logic.cfg_get_switch_conditions(ini, section, npc)
st.theme = utils.cfg_get_string(ini, section, "snd", npc, false, "")
st.looped = utils.cfg_get_bool (ini, section, "looped", npc, false, false)
st.random = utils.cfg_get_bool (ini, section, "random", npc, false, true)
st.pause_min = utils.cfg_get_number (ini, section, "min_idle", npc, false, 0)
st.pause_max = utils.cfg_get_number (ini, section, "max_idle", npc, false, 0)
st.no_hit = utils.cfg_get_bool (ini, section, "no_hit", npc, false, true)
if st.pause_max < st.pause_min then
abort ("PH_SOUND - invalid time range !!!")
end
end
| 1 | 0.853668 | 1 | 0.853668 | game-dev | MEDIA | 0.725533 | game-dev,audio-video-media | 0.972541 | 1 | 0.972541 |
Staartvin/Autorank-2 | 4,592 | src/me/armar/plugins/autorank/commands/GlobalCheckCommand.java | package me.armar.plugins.autorank.commands;
import me.armar.plugins.autorank.Autorank;
import me.armar.plugins.autorank.commands.manager.AutorankCommand;
import me.armar.plugins.autorank.language.Lang;
import me.armar.plugins.autorank.permissions.AutorankPermission;
import me.armar.plugins.autorank.storage.PlayTimeStorageProvider;
import me.armar.plugins.autorank.storage.TimeType;
import me.armar.plugins.autorank.util.AutorankTools;
import me.armar.plugins.autorank.util.uuid.UUIDManager;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* The command delegator for the '/ar gcheck' command.
*/
public class GlobalCheckCommand extends AutorankCommand {
private final Autorank plugin;
public GlobalCheckCommand(final Autorank instance) {
plugin = instance;
}
@Override
public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) {
// This is a global check. It will not show you the database numbers
if (!plugin.getPlayTimeStorageManager().isStorageTypeActive(PlayTimeStorageProvider.StorageType.DATABASE)) {
sender.sendMessage(ChatColor.RED + Lang.MYSQL_IS_NOT_ENABLED.getConfigValue());
return true;
}
CompletableFuture<Void> task = CompletableFuture.completedFuture(null).thenAccept(nothing -> {
UUID uuid = null;
String playerName = null;
// There was a player specified
if (args.length > 1) {
if (!this.hasPermission(AutorankPermission.CHECK_OTHERS, sender)) {
return;
}
final Player player = plugin.getServer().getPlayer(args[1]);
try {
uuid = UUIDManager.getUUID(args[1]).get();
playerName = UUIDManager.getPlayerName(uuid).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (uuid == null) {
sender.sendMessage(Lang.PLAYER_IS_INVALID.getConfigValue(args[1]));
return;
}
if (player != null) {
if (player.hasPermission(AutorankPermission.EXCLUDE_FROM_PATHING)) {
sender.sendMessage(ChatColor.RED + Lang.PLAYER_IS_EXCLUDED.getConfigValue(player.getName()));
return;
}
playerName = player.getName();
}
} else if (sender instanceof Player) { // There was no player specified, so take sender as target
if (!this.hasPermission(AutorankPermission.CHECK_GLOBAL, sender)) {
return;
}
if (sender.hasPermission("autorank.exclude")) {
sender.sendMessage(ChatColor.RED + Lang.PLAYER_IS_EXCLUDED.getConfigValue(sender.getName()));
return;
}
final Player player = (Player) sender;
uuid = player.getUniqueId();
playerName = player.getName();
} else {
AutorankTools.sendColoredMessage(sender, Lang.CANNOT_CHECK_CONSOLE.getConfigValue());
return;
}
int globalPlayTime = 0;
try {
globalPlayTime = plugin.getPlayTimeManager().getGlobalPlayTime(TimeType.TOTAL_TIME, uuid).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (globalPlayTime < 0) {
sender.sendMessage(Lang.PLAYER_IS_INVALID.getConfigValue(playerName));
return;
}
AutorankTools.sendColoredMessage(sender, playerName + " has played for "
+ AutorankTools.timeToString(globalPlayTime, TimeUnit.MINUTES) + " across all servers.");
});
this.runCommandTask(task);
return true;
}
@Override
public String getDescription() {
return "Check [player]'s global playtime.";
}
@Override
public String getPermission() {
return AutorankPermission.CHECK_GLOBAL;
}
@Override
public String getUsage() {
return "/ar gcheck [player]";
}
}
| 1 | 0.958389 | 1 | 0.958389 | game-dev | MEDIA | 0.767043 | game-dev,testing-qa | 0.946187 | 1 | 0.946187 |
sanity/LastCalc | 11,054 | src/main/java/com/lastcalc/parsers/UserDefinedParserParser.java | /*******************************************************************************
* LastCalc - The last calculator you'll ever need
* Copyright (C) 2011, 2012 Uprizer Labs LLC
*
* 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.
******************************************************************************/
package com.lastcalc.parsers;
import java.util.*;
import java.util.Map.Entry;
import com.google.common.collect.*;
import org.jscience.mathematics.number.Number;
import org.jscience.physics.amount.Amount;
import com.lastcalc.TokenList;
import com.lastcalc.parsers.PreParser.ListWithTail;
import com.lastcalc.parsers.PreParser.MapWithTail;
public class UserDefinedParserParser extends Parser {
private static final long serialVersionUID = -6964937711038633291L;
private static TokenList template;
static {
template = TokenList.createD((Lists.<Object> newArrayList("=", "is", "means")));
}
@Override
public ParseResult parse(final TokenList tokens, final int templatePos, final ParserContext context) {
// Identify the beginning and end of the UDPP
final int start = PreParser.findEdgeOrObjectBackwards(tokens, templatePos, null);
final int end = PreParser.findEdgeOrObjectForwards(tokens, templatePos, null) + 1;
final TokenList before = tokens.subList(start, templatePos);
if (before.isEmpty())
return ParseResult.fail();
final TokenList after = PreParser.flatten(tokens.subList(templatePos + 1, end));
if (after.isEmpty())
return ParseResult.fail();
final Set<String> variables = Sets.newHashSet();
for (final Object o : PreParser.flatten(before)) {
if (o instanceof String && !PreParser.reserved.contains(o)
&& Character.isUpperCase(((String) o).charAt(0))) {
variables.add((String) o);
}
}
final UserDefinedParser udp = new UserDefinedParser(before, after, variables);
return ParseResult.success(
tokens.replaceWithTokens(Math.max(0, start - 1), Math.min(tokens.size(), end + 1), udp));
}
public static class BindException extends Exception {
private static final long serialVersionUID = -2021162162489202197L;
public BindException(final String err) {
super(err);
}
}
@SuppressWarnings("unchecked")
protected static void bind(final Object from, final Object to, final Set<String> variables,
final Map<String, Object> bound)
throws BindException {
if (from.equals(to) || from.equals("?"))
return;
if (from instanceof String && variables.contains(from)) {
if (bound.containsKey(from) && !bound.get(from).equals(to)) {
throw new BindException("Variable "+from+" is already bound to "+bound.get(from)+" which isn't the same as "+to);
}
bound.put((String) from, to);
} else if (from instanceof Iterable && to instanceof Iterable) {
final Iterator<Object> fromL = ((Iterable<Object>) from).iterator();
final Iterator<Object> toL = ((Iterable<Object>) to).iterator();
while (fromL.hasNext() && toL.hasNext()) {
bind(fromL.next(), toL.next(), variables, bound);
}
if (fromL.hasNext() || toL.hasNext())
throw new BindException("Iterables are not of the same size");
} else if (from instanceof MapWithTail && to instanceof Map) {
final MapWithTail fromMWT = (MapWithTail) from;
final Map<Object, Object> toM = (Map<Object, Object>) to;
final Map<Object, Object> tail = Maps.newLinkedHashMap(toM);
if (toM.size() < fromMWT.map.size())
throw new BindException("Map must be at least size of head of MWT");
for (final Entry<Object, Object> e : fromMWT.map.entrySet()) {
if (!variables.contains(e.getValue()))
throw new BindException("Map value '"+e.getValue()+" is not a variable");
if (variables.contains(e.getKey()) && !bound.containsKey(e.getKey())) {
// The key is a variable, bind to any value and remove from
// tail
final Map.Entry<Object, Object> nextEntry = tail.entrySet().iterator().next();
bound.put((String) e.getKey(), nextEntry.getKey());
bind(e.getValue(), nextEntry.getValue(), variables, bound);
tail.remove(nextEntry.getKey());
} else {
final Object aKey = bound.containsKey(e.getKey()) ? bound.get(e.getKey()) : e.getKey();
final Object value = toM.get(aKey);
if (value == null)
throw new BindException("Map doesn't contain key '" + e.getKey() + "'");
bind(e.getValue(), value, variables, bound);
tail.remove(aKey);
}
}
bind(fromMWT.tail, tail, variables, bound);
} else if (from instanceof Map && to instanceof Map) {
final Map<Object, Object> fromM = (Map<Object, Object>) from;
final Map<Object, Object> toM = (Map<Object, Object>) to;
final Map<Object, Object> tail = Maps.newLinkedHashMap(toM);
if (toM.size() != fromM.size())
throw new BindException("Maps are not the same size");
for (final Entry<Object, Object> e : fromM.entrySet()) {
if (!variables.contains(e.getValue()))
throw new BindException("Map value '" + e.getValue() + " is not a variable");
if (variables.contains(e.getKey()) && !bound.containsKey(e.getKey())) {
// The key is a variable, bind to any value and remove from
// tail
final Map.Entry<Object, Object> nextEntry = tail.entrySet().iterator().next();
bound.put((String) e.getKey(), nextEntry.getKey());
bind(e.getValue(), nextEntry.getValue(), variables, bound);
tail.remove(nextEntry.getKey());
} else {
final Object aKey = bound.containsKey(e.getKey()) ? bound.get(e.getKey()) : e.getKey();
final Object value = toM.get(aKey);
if (value == null)
throw new BindException("Map doesn't contain key '" + e.getKey() + "'");
bind(e.getValue(), value, variables, bound);
tail.remove(e.getKey());
}
}
} else if (from instanceof ListWithTail && to instanceof List) {
final ListWithTail fromLWT = (ListWithTail) from;
final List<Object> toList = (List<Object>) to;
if (toList.size() < fromLWT.list.size())
throw new BindException("List must be at least size of head of LWT");
if (toList.isEmpty())
throw new BindException("Can't bind list with tail to empty list");
final LinkedList<Object> tail = Lists.newLinkedList(toList);
for (int x = 0; x < fromLWT.list.size(); x++) {
bind(fromLWT.list.get(x), toList.get(x), variables, bound);
tail.removeFirst();
}
bind(fromLWT.tail, tail, variables, bound);
} else
throw new BindException("Don't know how to bind " + from + ":" + from.getClass().getSimpleName() + " to "
+ to + ":" + to.getClass().getSimpleName());
}
public static class UserDefinedParser extends Parser {
private static final long serialVersionUID = -4928516936219533258L;
public final TokenList after;
private final TokenList template;
private final TokenList before;
public final Set<String> variables;
public UserDefinedParser(final TokenList before, final TokenList after, final Set<String> variables) {
this.before = before;
this.after = after;
this.variables = variables;
final List<Object> tpl = Lists.newArrayList();
for (final Object o : before) {
if (variables.contains(o)) {
final String var = (String) o;
if (var.endsWith("List")) {
tpl.add(List.class);
} else if (var.endsWith("Map")) {
tpl.add(Map.class);
} else if (var.endsWith("Num") || var.endsWith("Number")) {
tpl.add(Number.class);
} else if (var.endsWith("Bool") || var.endsWith("Boolean")) {
tpl.add(Boolean.class);
} else if (var.endsWith("Amount")) {
tpl.add(Amount.class);
} else if (var.endsWith("Fun") || var.endsWith("Function")) {
tpl.add(UserDefinedParser.class);
tpl.add(Amount.class);
} else {
tpl.add(Object.class);
}
} else if (o instanceof String) {
tpl.add(o);
} else if (o instanceof MapWithTail || o instanceof Map) {
tpl.add(Map.class);
} else if (o instanceof ListWithTail || o instanceof List) {
tpl.add(List.class);
} else {
tpl.add(o.getClass());
}
}
template = TokenList.create(tpl);
}
@Override
public ParseResult parse(final TokenList tokens, final int templatePos, final ParserContext context) {
if (tokens.get(PreParser.findEdgeOrObjectBackwards(tokens, templatePos, "then")).equals("then"))
return ParseResult.fail();
final List<Object> result = Lists.newArrayListWithCapacity(after.size() + 2);
final boolean useBrackets = tokens.size() > template.size();
if (useBrackets) {
result.add("(");
}
final TokenList input = tokens.subList(templatePos, templatePos + template.size());
final Map<String, Object> varMap = Maps.newHashMapWithExpectedSize(variables.size());
try {
bind(before, input, variables, varMap);
for (final Object o : after) {
final Object val = varMap.get(o);
if (val != null) {
result.add(val);
} else {
result.add(o);
}
}
} catch (final BindException e) {
return ParseResult.fail();
}
if (useBrackets) {
result.add(")");
}
final TokenList resultTL = TokenList.create(result);
final TokenList flattened = PreParser.flatten(resultTL);
return ParseResult.success(
tokens.replaceWithTokenList(templatePos, templatePos + template.size(), flattened),
Math.min(0, -flattened.size())
);
}
@Override
public TokenList getTemplate() {
return template;
}
@Override
public String toString() {
return before + " = " + after;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((after == null) ? 0 : after.hashCode());
result = prime * result + ((before == null) ? 0 : before.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof UserDefinedParser))
return false;
final UserDefinedParser other = (UserDefinedParser) obj;
if (after == null) {
if (other.after != null)
return false;
} else if (!after.equals(other.after))
return false;
if (before == null) {
if (other.before != null)
return false;
} else if (!before.equals(other.before))
return false;
return true;
}
public boolean hasVariables() {
return !variables.isEmpty();
}
}
@Override
public TokenList getTemplate() {
return template;
}
@Override
public int hashCode() {
return "UserDefinedParserParser".hashCode();
}
@Override
public boolean equals(final Object obj) {
return obj instanceof UserDefinedParserParser;
}
}
| 1 | 0.91458 | 1 | 0.91458 | game-dev | MEDIA | 0.443378 | game-dev | 0.985027 | 1 | 0.985027 |
yigao/NFShmXFrame | 3,573 | game/MMO/NFLogicComm/DescStore/FestivalMuban_firstrechargeDesc.cpp | #include "FestivalMuban_firstrechargeDesc.h"
#include "NFComm/NFPluginModule/NFCheck.h"
FestivalMuban_firstrechargeDesc::FestivalMuban_firstrechargeDesc()
{
if (EN_OBJ_MODE_INIT == NFShmMgr::Instance()->GetCreateMode()) {
CreateInit();
}
else {
ResumeInit();
}
}
FestivalMuban_firstrechargeDesc::~FestivalMuban_firstrechargeDesc()
{
}
int FestivalMuban_firstrechargeDesc::CreateInit()
{
return 0;
}
int FestivalMuban_firstrechargeDesc::ResumeInit()
{
return 0;
}
int FestivalMuban_firstrechargeDesc::Load(NFResDB *pDB)
{
NFLogTrace(NF_LOG_SYSTEMLOG, 0, "--begin--");
CHECK_EXPR(pDB != NULL, -1, "pDB == NULL");
NFLogTrace(NF_LOG_SYSTEMLOG, 0, "FestivalMuban_firstrechargeDesc::Load() strFileName = {}", GetFileName());
proto_ff::Sheet_FestivalMuban_firstrecharge table;
NFResTable* pResTable = pDB->GetTable(GetFileName());
CHECK_EXPR(pResTable != NULL, -1, "pTable == NULL, GetTable:{} Error", GetFileName());
int iRet = 0;
iRet = pResTable->FindAllRecord(GetDBName(), &table);
CHECK_EXPR(iRet == 0, -1, "FindAllRecord Error:{}", GetFileName());
//NFLogTrace(NF_LOG_SYSTEMLOG, 0, "{}", table.Utf8DebugString());
if ((table.e_festivalmuban_firstrecharge_list_size() < 0) || (table.e_festivalmuban_firstrecharge_list_size() > (int)(m_astDescMap.max_size())))
{
NFLogError(NF_LOG_SYSTEMLOG, 0, "Invalid TotalNum:{}", table.e_festivalmuban_firstrecharge_list_size());
return -2;
}
m_minId = INVALID_ID;
for (int i = 0; i < (int)table.e_festivalmuban_firstrecharge_list_size(); i++)
{
const proto_ff::E_FestivalMuban_firstrecharge& desc = table.e_festivalmuban_firstrecharge_list(i);
if (desc.has_m_id() == false && desc.ByteSize() == 0)
{
NFLogError(NF_LOG_SYSTEMLOG, 0, "the desc no value, {}", desc.Utf8DebugString());
continue;
}
if (m_minId == INVALID_ID)
{
m_minId = desc.m_id();
}
else
{
if (desc.m_id() < m_minId)
{
m_minId = desc.m_id();
}
}
//NFLogTrace(NF_LOG_SYSTEMLOG, 0, "{}", desc.Utf8DebugString());
if (m_astDescMap.find(desc.m_id()) != m_astDescMap.end())
{
if (IsReloading())
{
auto pDesc = GetDesc(desc.m_id());
NF_ASSERT_MSG(pDesc, "the desc:{} Reload, GetDesc Failed!, id:{}", GetClassName(), desc.m_id());
pDesc->read_from_pbmsg(desc);
}
else
{
NFLogError(NF_LOG_SYSTEMLOG, 0, "the desc:{} id:{} exist", GetClassName(), desc.m_id());
}
continue;
}
CHECK_EXPR_ASSERT(m_astDescMap.size() < m_astDescMap.max_size(), -1, "m_astDescMap Space Not Enough");
auto pDesc = &m_astDescMap[desc.m_id()];
CHECK_EXPR_ASSERT(pDesc, -1, "m_astDescMap Insert Failed desc.id:{}", desc.m_id());
pDesc->read_from_pbmsg(desc);
CHECK_EXPR_ASSERT(GetDesc(desc.m_id()) == pDesc, -1, "GetDesc != pDesc, id:{}", desc.m_id());
}
for(int i = 0; i < (int)m_astDescIndex.size(); i++)
{
m_astDescIndex[i] = INVALID_ID;
}
for(auto iter = m_astDescMap.begin(); iter != m_astDescMap.end(); iter++)
{
int64_t index = (int64_t)iter->first - (int64_t)m_minId;
if (index >= 0 && index < (int64_t)m_astDescIndex.size())
{
m_astDescIndex[index] = iter.m_curNode->m_self;
CHECK_EXPR_ASSERT(iter == m_astDescMap.get_iterator(m_astDescIndex[index]), -1, "index error");
CHECK_EXPR_ASSERT(GetDesc(iter->first) == &iter->second, -1, "GetDesc != iter->second, id:{}", iter->first);
}
}
NFLogTrace(NF_LOG_SYSTEMLOG, 0, "load {}, num={}", iRet, table.e_festivalmuban_firstrecharge_list_size());
NFLogTrace(NF_LOG_SYSTEMLOG, 0, "--end--");
return 0;
}
int FestivalMuban_firstrechargeDesc::CheckWhenAllDataLoaded()
{
return 0;
}
| 1 | 0.978409 | 1 | 0.978409 | game-dev | MEDIA | 0.605404 | game-dev | 0.987111 | 1 | 0.987111 |
fortressforever/fortressforever | 3,644 | cl_dll/fx_explosion.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef FX_EXPLOSION_H
#define FX_EXPLOSION_H
#ifdef _WIN32
#pragma once
#endif
#include "particle_collision.h"
#include "glow_overlay.h"
//JDW: For now we're clamping this value
#define EXPLOSION_FORCE_MAX 2
#define EXPLOSION_FORCE_MIN 2
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class C_BaseExplosionEffect
{
private:
static C_BaseExplosionEffect m_instance;
public:
~C_BaseExplosionEffect( void ) {}
static C_BaseExplosionEffect &Instance( void ) { return m_instance; }
virtual void Create( const Vector &position, float force, float scale, int flags );
protected:
C_BaseExplosionEffect( void );
virtual void PlaySound( void );
virtual void CreateCore( void );
virtual void CreateDebris( void );
virtual void CreateMisc( void );
virtual void CreateDynamicLight( void );
float ScaleForceByDeviation( Vector &deviant, Vector &source, float spread, float *force = NULL );
float Probe( const Vector &origin, Vector *direction, float strength );
void GetForceDirection( const Vector &origin, float magnitude, Vector *resultDirection, float *resultForce );
protected:
Vector m_vecOrigin;
Vector m_vecDirection;
float m_flForce;
float m_flScale; // |-- Mirv: Scale now
int m_fFlags;
PMaterialHandle m_Material_Smoke;
PMaterialHandle m_Material_Embers[2];
PMaterialHandle m_Material_FireCloud;
};
//Singleton accessor
extern C_BaseExplosionEffect &BaseExplosionEffect( void );
//
// CExplosionOverlay
//
class CExplosionOverlay : public CWarpOverlay
{
public:
virtual bool Update( void );
public:
float m_flLifetime;
Vector m_vBaseColors[MAX_SUN_LAYERS];
};
//-----------------------------------------------------------------------------
// Purpose: Water explosion
//-----------------------------------------------------------------------------
class C_WaterExplosionEffect : public C_BaseExplosionEffect
{
typedef C_BaseExplosionEffect BaseClass;
public:
static C_WaterExplosionEffect &Instance( void ) { return m_waterinstance; }
virtual void Create( const Vector &position, float force, float scale, int flags );
protected:
virtual void CreateCore( void );
virtual void CreateDebris( void );
virtual void CreateMisc( void );
virtual void PlaySound( void );
private:
Vector m_vecWaterSurface;
float m_flDepth; // Depth below the water surface (used for surface effect)
Vector m_vecColor; // Lighting tint information
float m_flLuminosity; // Luminosity information
static C_WaterExplosionEffect m_waterinstance;
};
//Singleton accessor
extern C_WaterExplosionEffect &WaterExplosionEffect( void );
//-----------------------------------------------------------------------------
// Purpose: Water explosion
//-----------------------------------------------------------------------------
class C_MegaBombExplosionEffect : public C_BaseExplosionEffect
{
typedef C_BaseExplosionEffect BaseClass;
public:
static C_MegaBombExplosionEffect &Instance( void ) { return m_megainstance; }
protected:
virtual void CreateCore( void );
virtual void CreateDebris( void ) { };
virtual void CreateMisc( void ) { };
virtual void PlaySound( void ) { };
private:
static C_MegaBombExplosionEffect m_megainstance;
};
//Singleton accessor
extern C_MegaBombExplosionEffect &MegaBombExplosionEffect( void );
#endif // FX_EXPLOSION_H
| 1 | 0.755497 | 1 | 0.755497 | game-dev | MEDIA | 0.992597 | game-dev | 0.512735 | 1 | 0.512735 |
NetCodersX/Unity-Script | 21,588 | 通用脚本插件库/Utils/UtilsClass.cs | /*
------------------- Code Monkey -------------------
Thank you for downloading the Code Monkey Utilities
I hope you find them useful in your projects
If you have any questions use the contact form
Cheers!
unitycodemonkey.com
--------------------------------------------------
*/
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace CodeMonkey.Utils {
/*
* Various assorted utilities functions
* */
public static class UtilsClass {
private static readonly Vector3 Vector3zero = Vector3.zero;
private static readonly Vector3 Vector3one = Vector3.one;
private static readonly Vector3 Vector3yDown = new Vector3(0,-1);
public const int sortingOrderDefault = 5000;
// Get Sorting order to set SpriteRenderer sortingOrder, higher position = lower sortingOrder
public static int GetSortingOrder(Vector3 position, int offset, int baseSortingOrder = sortingOrderDefault) {
return (int)(baseSortingOrder - position.y) + offset;
}
// Get Main Canvas Transform
private static Transform cachedCanvasTransform;
public static Transform GetCanvasTransform() {
if (cachedCanvasTransform == null) {
Canvas canvas = MonoBehaviour.FindObjectOfType<Canvas>();
if (canvas != null) {
cachedCanvasTransform = canvas.transform;
}
}
return cachedCanvasTransform;
}
// Get Default Unity Font, used in text objects if no font given
public static Font GetDefaultFont() {
return Resources.GetBuiltinResource<Font>("Arial.ttf");
}
// Create a Sprite in the World, no parent
public static GameObject CreateWorldSprite(string name, Sprite sprite, Vector3 position, Vector3 localScale, int sortingOrder, Color color) {
return CreateWorldSprite(null, name, sprite, position, localScale, sortingOrder, color);
}
// Create a Sprite in the World
public static GameObject CreateWorldSprite(Transform parent, string name, Sprite sprite, Vector3 localPosition, Vector3 localScale, int sortingOrder, Color color) {
GameObject gameObject = new GameObject(name, typeof(SpriteRenderer));
Transform transform = gameObject.transform;
transform.SetParent(parent, false);
transform.localPosition = localPosition;
transform.localScale = localScale;
SpriteRenderer spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
spriteRenderer.sprite = sprite;
spriteRenderer.sortingOrder = sortingOrder;
spriteRenderer.color = color;
return gameObject;
}
// Create a Sprite in the World with Button_Sprite, no parent
//public static Button_Sprite CreateWorldSpriteButton(string name, Sprite sprite, Vector3 localPosition, Vector3 localScale, int sortingOrder, Color color) {
// return CreateWorldSpriteButton(null, name, sprite, localPosition, localScale, sortingOrder, color);
//}
// Create a Sprite in the World with Button_Sprite
//public static Button_Sprite CreateWorldSpriteButton(Transform parent, string name, Sprite sprite, Vector3 localPosition, Vector3 localScale, int sortingOrder, Color color) {
// GameObject gameObject = CreateWorldSprite(parent, name, sprite, localPosition, localScale, sortingOrder, color);
// gameObject.AddComponent<BoxCollider2D>();
// Button_Sprite buttonSprite = gameObject.AddComponent<Button_Sprite>();
// return buttonSprite;
//}
// Creates a Text Mesh in the World and constantly updates it
public static FunctionUpdater CreateWorldTextUpdater(Func<string> GetTextFunc, Vector3 localPosition, Transform parent = null) {
TextMesh textMesh = CreateWorldText(GetTextFunc(), parent, localPosition);
return FunctionUpdater.Create(() => {
textMesh.text = GetTextFunc();
return false;
}, "WorldTextUpdater");
}
// Create Text in the World
public static TextMesh CreateWorldText(string text, Transform parent = null, Vector3 localPosition = default(Vector3), int fontSize = 40, Color? color = null, TextAnchor textAnchor = TextAnchor.UpperLeft, TextAlignment textAlignment = TextAlignment.Left, int sortingOrder = sortingOrderDefault) {
if (color == null) color = Color.white;
return CreateWorldText(parent, text, localPosition, fontSize, (Color)color, textAnchor, textAlignment, sortingOrder);
}
// Create Text in the World
public static TextMesh CreateWorldText(Transform parent, string text, Vector3 localPosition, int fontSize, Color color, TextAnchor textAnchor, TextAlignment textAlignment, int sortingOrder) {
GameObject gameObject = new GameObject("World_Text", typeof(TextMesh));
Transform transform = gameObject.transform;
transform.SetParent(parent, false);
transform.localPosition = localPosition;
TextMesh textMesh = gameObject.GetComponent<TextMesh>();
textMesh.anchor = textAnchor;
textMesh.alignment = textAlignment;
textMesh.text = text;
textMesh.fontSize = fontSize;
textMesh.color = color;
textMesh.GetComponent<MeshRenderer>().sortingOrder = sortingOrder;
return textMesh;
}
// Create a Text Popup in the World, no parent
public static void CreateWorldTextPopup(string text, Vector3 localPosition) {
CreateWorldTextPopup(null, text, localPosition, 40, Color.white, localPosition + new Vector3(0, 20), 1f);
}
// Create a Text Popup in the World
public static void CreateWorldTextPopup(Transform parent, string text, Vector3 localPosition, int fontSize, Color color, Vector3 finalPopupPosition, float popupTime) {
TextMesh textMesh = CreateWorldText(parent, text, localPosition, fontSize, color, TextAnchor.LowerLeft, TextAlignment.Left, sortingOrderDefault);
Transform transform = textMesh.transform;
Vector3 moveAmount = (finalPopupPosition - localPosition) / popupTime;
FunctionUpdater.Create(delegate () {
transform.position += moveAmount * Time.deltaTime;
popupTime -= Time.deltaTime;
if (popupTime <= 0f) {
UnityEngine.Object.Destroy(transform.gameObject);
return true;
} else {
return false;
}
}, "WorldTextPopup");
}
// Create Text Updater in UI
public static FunctionUpdater CreateUITextUpdater(Func<string> GetTextFunc, Vector2 anchoredPosition) {
Text text = DrawTextUI(GetTextFunc(), anchoredPosition, 20, GetDefaultFont());
return FunctionUpdater.Create(() => {
text.text = GetTextFunc();
return false;
}, "UITextUpdater");
}
// Draw a UI Sprite
public static RectTransform DrawSprite(Color color, Transform parent, Vector2 pos, Vector2 size, string name = null) {
RectTransform rectTransform = DrawSprite(null, color, parent, pos, size, name);
return rectTransform;
}
// Draw a UI Sprite
public static RectTransform DrawSprite(Sprite sprite, Transform parent, Vector2 pos, Vector2 size, string name = null) {
RectTransform rectTransform = DrawSprite(sprite, Color.white, parent, pos, size, name);
return rectTransform;
}
// Draw a UI Sprite
public static RectTransform DrawSprite(Sprite sprite, Color color, Transform parent, Vector2 pos, Vector2 size, string name = null) {
// Setup icon
if (name == null || name == "") name = "Sprite";
GameObject go = new GameObject(name, typeof(RectTransform), typeof(Image));
RectTransform goRectTransform = go.GetComponent<RectTransform>();
goRectTransform.SetParent(parent, false);
goRectTransform.sizeDelta = size;
goRectTransform.anchoredPosition = pos;
Image image = go.GetComponent<Image>();
image.sprite = sprite;
image.color = color;
return goRectTransform;
}
public static Text DrawTextUI(string textString, Vector2 anchoredPosition, int fontSize, Font font) {
return DrawTextUI(textString, GetCanvasTransform(), anchoredPosition, fontSize, font);
}
public static Text DrawTextUI(string textString, Transform parent, Vector2 anchoredPosition, int fontSize, Font font) {
GameObject textGo = new GameObject("Text", typeof(RectTransform), typeof(Text));
textGo.transform.SetParent(parent, false);
Transform textGoTrans = textGo.transform;
textGoTrans.SetParent(parent, false);
textGoTrans.localPosition = Vector3zero;
textGoTrans.localScale = Vector3one;
RectTransform textGoRectTransform = textGo.GetComponent<RectTransform>();
textGoRectTransform.sizeDelta = new Vector2(0,0);
textGoRectTransform.anchoredPosition = anchoredPosition;
Text text = textGo.GetComponent<Text>();
text.text = textString;
text.verticalOverflow = VerticalWrapMode.Overflow;
text.horizontalOverflow = HorizontalWrapMode.Overflow;
text.alignment = TextAnchor.MiddleLeft;
if (font == null) font = GetDefaultFont();
text.font = font;
text.fontSize = fontSize;
return text;
}
// Parse a float, return default if failed
public static float Parse_Float(string txt, float _default) {
float f;
if (!float.TryParse(txt, out f)) {
f = _default;
}
return f;
}
// Parse a int, return default if failed
public static int Parse_Int(string txt, int _default) {
int i;
if (!int.TryParse(txt, out i)) {
i = _default;
}
return i;
}
public static int Parse_Int(string txt) {
return Parse_Int(txt, -1);
}
// Get Mouse Position in World with Z = 0f
public static Vector3 GetMouseWorldPosition() {
Vector3 vec = GetMouseWorldPositionWithZ(Input.mousePosition, Camera.main);
vec.z = 0f;
return vec;
}
public static Vector3 GetMouseWorldPositionWithZ() {
return GetMouseWorldPositionWithZ(Input.mousePosition, Camera.main);
}
public static Vector3 GetMouseWorldPositionWithZ(Camera worldCamera) {
return GetMouseWorldPositionWithZ(Input.mousePosition, worldCamera);
}
public static Vector3 GetMouseWorldPositionWithZ(Vector3 screenPosition, Camera worldCamera) {
Vector3 worldPosition = worldCamera.ScreenToWorldPoint(screenPosition);
return worldPosition;
}
// Is Mouse over a UI Element? Used for ignoring World clicks through UI
public static bool IsPointerOverUI() {
if (EventSystem.current.IsPointerOverGameObject()) {
return true;
} else {
PointerEventData pe = new PointerEventData(EventSystem.current);
pe.position = Input.mousePosition;
List<RaycastResult> hits = new List<RaycastResult>();
EventSystem.current.RaycastAll( pe, hits );
return hits.Count > 0;
}
}
// Returns 00-FF, value 0->255
public static string Dec_to_Hex(int value) {
return value.ToString("X2");
}
// Returns 0-255
public static int Hex_to_Dec(string hex) {
return Convert.ToInt32(hex, 16);
}
// Returns a hex string based on a number between 0->1
public static string Dec01_to_Hex(float value) {
return Dec_to_Hex((int)Mathf.Round(value*255f));
}
// Returns a float between 0->1
public static float Hex_to_Dec01(string hex) {
return Hex_to_Dec(hex)/255f;
}
// Get Hex Color FF00FF
public static string GetStringFromColor(Color color) {
string red = Dec01_to_Hex(color.r);
string green = Dec01_to_Hex(color.g);
string blue = Dec01_to_Hex(color.b);
return red+green+blue;
}
// Get Hex Color FF00FFAA
public static string GetStringFromColorWithAlpha(Color color) {
string alpha = Dec01_to_Hex(color.a);
return GetStringFromColor(color)+alpha;
}
// Sets out values to Hex String 'FF'
public static void GetStringFromColor(Color color, out string red, out string green, out string blue, out string alpha) {
red = Dec01_to_Hex(color.r);
green = Dec01_to_Hex(color.g);
blue = Dec01_to_Hex(color.b);
alpha = Dec01_to_Hex(color.a);
}
// Get Hex Color FF00FF
public static string GetStringFromColor(float r, float g, float b) {
string red = Dec01_to_Hex(r);
string green = Dec01_to_Hex(g);
string blue = Dec01_to_Hex(b);
return red+green+blue;
}
// Get Hex Color FF00FFAA
public static string GetStringFromColor(float r, float g, float b, float a) {
string alpha = Dec01_to_Hex(a);
return GetStringFromColor(r,g,b)+alpha;
}
// Get Color from Hex string FF00FFAA
public static Color GetColorFromString(string color) {
float red = Hex_to_Dec01(color.Substring(0,2));
float green = Hex_to_Dec01(color.Substring(2,2));
float blue = Hex_to_Dec01(color.Substring(4,2));
float alpha = 1f;
if (color.Length >= 8) {
// Color string contains alpha
alpha = Hex_to_Dec01(color.Substring(6,2));
}
return new Color(red, green, blue, alpha);
}
// Generate random normalized direction
public static Vector3 GetRandomDir() {
return new Vector3(UnityEngine.Random.Range(-1f,1f), UnityEngine.Random.Range(-1f,1f)).normalized;
}
public static Vector3 GetVectorFromAngle(int angle) {
// angle = 0 -> 360
float angleRad = angle * (Mathf.PI/180f);
return new Vector3(Mathf.Cos(angleRad), Mathf.Sin(angleRad));
}
public static float GetAngleFromVectorFloat(Vector3 dir) {
dir = dir.normalized;
float n = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
if (n < 0) n += 360;
return n;
}
public static int GetAngleFromVector(Vector3 dir) {
dir = dir.normalized;
float n = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
if (n < 0) n += 360;
int angle = Mathf.RoundToInt(n);
return angle;
}
public static int GetAngleFromVector180(Vector3 dir) {
dir = dir.normalized;
float n = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
int angle = Mathf.RoundToInt(n);
return angle;
}
public static Vector3 ApplyRotationToVector(Vector3 vec, Vector3 vecRotation) {
return ApplyRotationToVector(vec, GetAngleFromVectorFloat(vecRotation));
}
public static Vector3 ApplyRotationToVector(Vector3 vec, float angle) {
return Quaternion.Euler(0,0,angle) * vec;
}
public static FunctionUpdater CreateMouseDraggingAction(Action<Vector3> onMouseDragging) {
return CreateMouseDraggingAction(0, onMouseDragging);
}
public static FunctionUpdater CreateMouseDraggingAction(int mouseButton, Action<Vector3> onMouseDragging) {
bool dragging = false;
return FunctionUpdater.Create(() => {
if (Input.GetMouseButtonDown(mouseButton)) {
dragging = true;
}
if (Input.GetMouseButtonUp(mouseButton)) {
dragging = false;
}
if (dragging) {
onMouseDragging(UtilsClass.GetMouseWorldPosition());
}
return false;
});
}
public static FunctionUpdater CreateMouseClickFromToAction(Action<Vector3, Vector3> onMouseClickFromTo, Action<Vector3, Vector3> onWaitingForToPosition) {
return CreateMouseClickFromToAction(0, 1, onMouseClickFromTo, onWaitingForToPosition);
}
public static FunctionUpdater CreateMouseClickFromToAction(int mouseButton, int cancelMouseButton, Action<Vector3, Vector3> onMouseClickFromTo, Action<Vector3, Vector3> onWaitingForToPosition) {
int state = 0;
Vector3 from = Vector3.zero;
return FunctionUpdater.Create(() => {
if (state == 1) {
if (onWaitingForToPosition != null) onWaitingForToPosition(from, UtilsClass.GetMouseWorldPosition());
}
if (state == 1 && Input.GetMouseButtonDown(cancelMouseButton)) {
// Cancel
state = 0;
}
if (Input.GetMouseButtonDown(mouseButton) && !UtilsClass.IsPointerOverUI()) {
if (state == 0) {
state = 1;
from = UtilsClass.GetMouseWorldPosition();
} else {
state = 0;
onMouseClickFromTo(from, UtilsClass.GetMouseWorldPosition());
}
}
return false;
});
}
public static FunctionUpdater CreateMouseClickAction(Action<Vector3> onMouseClick) {
return CreateMouseClickAction(0, onMouseClick);
}
public static FunctionUpdater CreateMouseClickAction(int mouseButton, Action<Vector3> onMouseClick) {
return FunctionUpdater.Create(() => {
if (Input.GetMouseButtonDown(mouseButton)) {
onMouseClick(GetWorldPositionFromUI());
}
return false;
});
}
public static FunctionUpdater CreateKeyCodeAction(KeyCode keyCode, Action onKeyDown) {
return FunctionUpdater.Create(() => {
if (Input.GetKeyDown(keyCode)) {
onKeyDown();
}
return false;
});
}
// Get UI Position from World Position
public static Vector2 GetWorldUIPosition(Vector3 worldPosition, Transform parent, Camera uiCamera, Camera worldCamera) {
Vector3 screenPosition = worldCamera.WorldToScreenPoint(worldPosition);
Vector3 uiCameraWorldPosition = uiCamera.ScreenToWorldPoint(screenPosition);
Vector3 localPos = parent.InverseTransformPoint(uiCameraWorldPosition);
return new Vector2(localPos.x, localPos.y);
}
public static Vector3 GetWorldPositionFromUIZeroZ() {
Vector3 vec = GetWorldPositionFromUI(Input.mousePosition, Camera.main);
vec.z = 0f;
return vec;
}
// Get World Position from UI Position
public static Vector3 GetWorldPositionFromUI() {
return GetWorldPositionFromUI(Input.mousePosition, Camera.main);
}
public static Vector3 GetWorldPositionFromUI(Camera worldCamera) {
return GetWorldPositionFromUI(Input.mousePosition, worldCamera);
}
public static Vector3 GetWorldPositionFromUI(Vector3 screenPosition, Camera worldCamera) {
Vector3 worldPosition = worldCamera.ScreenToWorldPoint(screenPosition);
return worldPosition;
}
public static Vector3 GetWorldPositionFromUI_Perspective() {
return GetWorldPositionFromUI_Perspective(Input.mousePosition, Camera.main);
}
public static Vector3 GetWorldPositionFromUI_Perspective(Camera worldCamera) {
return GetWorldPositionFromUI_Perspective(Input.mousePosition, worldCamera);
}
public static Vector3 GetWorldPositionFromUI_Perspective(Vector3 screenPosition, Camera worldCamera) {
Ray ray = worldCamera.ScreenPointToRay(screenPosition);
Plane xy = new Plane(Vector3.forward, new Vector3(0, 0, 0f));
float distance;
xy.Raycast(ray, out distance);
return ray.GetPoint(distance);
}
// Screen Shake
public static void ShakeCamera(float intensity, float timer) {
Vector3 lastCameraMovement = Vector3.zero;
FunctionUpdater.Create(delegate () {
timer -= Time.unscaledDeltaTime;
Vector3 randomMovement = new Vector3(UnityEngine.Random.Range(-1f, 1f), UnityEngine.Random.Range(-1f, 1f)).normalized * intensity;
Camera.main.transform.position = Camera.main.transform.position - lastCameraMovement + randomMovement;
lastCameraMovement = randomMovement;
return timer <= 0f;
}, "CAMERA_SHAKE");
}
}
} | 1 | 0.781469 | 1 | 0.781469 | game-dev | MEDIA | 0.946773 | game-dev | 0.903277 | 1 | 0.903277 |
mapillary/mapillary-js | 4,138 | src/component/marker/MarkerScene.ts | import * as THREE from "three";
import { LngLat } from "../../api/interfaces/LngLat";
import { Marker } from "./marker/Marker";
export class MarkerScene {
private _needsRender: boolean;
private _interactiveObjects: THREE.Object3D[];
private _markers: { [key: string]: Marker };
private _objectMarkers: { [id: string]: string };
private _raycaster: THREE.Raycaster;
private _scene: THREE.Scene;
constructor(scene?: THREE.Scene, raycaster?: THREE.Raycaster) {
this._needsRender = false;
this._interactiveObjects = [];
this._markers = {};
this._objectMarkers = {};
this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
this._scene = !!scene ? scene : new THREE.Scene();
}
public get markers(): { [key: string]: Marker } {
return this._markers;
}
public get needsRender(): boolean {
return this._needsRender;
}
public add(marker: Marker, position: number[]): void {
if (marker.id in this._markers) {
this._dispose(marker.id);
}
marker.createGeometry(position);
this._scene.add(marker.geometry);
this._markers[marker.id] = marker;
for (let interactiveObject of marker.getInteractiveObjects()) {
this._interactiveObjects.push(interactiveObject);
this._objectMarkers[interactiveObject.uuid] = marker.id;
}
this._needsRender = true;
}
public clear(): void {
for (const id in this._markers) {
if (!this._markers.hasOwnProperty) {
continue;
}
this._dispose(id);
}
this._needsRender = true;
}
public get(id: string): Marker {
return this._markers[id];
}
public getAll(): Marker[] {
return Object
.keys(this._markers)
.map((id: string): Marker => { return this._markers[id]; });
}
public has(id: string): boolean {
return id in this._markers;
}
public intersectObjects([viewportX, viewportY]: number[], camera: THREE.Camera): string {
this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
const intersects: THREE.Intersection[] = this._raycaster.intersectObjects(this._interactiveObjects);
for (const intersect of intersects) {
if (intersect.object.uuid in this._objectMarkers) {
return this._objectMarkers[intersect.object.uuid];
}
}
return null;
}
public lerpAltitude(id: string, alt: number, alpha: number): void {
if (!(id in this._markers)) {
return;
}
this._markers[id].lerpAltitude(alt, alpha);
this._needsRender = true;
}
public remove(id: string): void {
if (!(id in this._markers)) {
return;
}
this._dispose(id);
this._needsRender = true;
}
public render(
perspectiveCamera: THREE.PerspectiveCamera,
renderer: THREE.WebGLRenderer): void {
renderer.render(this._scene, perspectiveCamera);
this._needsRender = false;
}
public update(id: string, position: number[], lngLat?: LngLat): void {
if (!(id in this._markers)) {
return;
}
const marker: Marker = this._markers[id];
marker.updatePosition(position, lngLat);
this._needsRender = true;
}
private _dispose(id: string): void {
const marker: Marker = this._markers[id];
this._scene.remove(marker.geometry);
for (let interactiveObject of marker.getInteractiveObjects()) {
const index: number = this._interactiveObjects.indexOf(interactiveObject);
if (index !== -1) {
this._interactiveObjects.splice(index, 1);
} else {
console.warn(`Object does not exist (${interactiveObject.id}) for ${id}`);
}
delete this._objectMarkers[interactiveObject.uuid];
}
marker.disposeGeometry();
delete this._markers[id];
}
}
| 1 | 0.895439 | 1 | 0.895439 | game-dev | MEDIA | 0.568145 | game-dev | 0.962499 | 1 | 0.962499 |
SpigotMC/Spigot-API | 1,900 | src/main/java/org/bukkit/event/entity/EntityDeathEvent.java | package org.bukkit.event.entity;
import java.util.List;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
/**
* Thrown whenever a LivingEntity dies
*/
public class EntityDeathEvent extends EntityEvent {
private static final HandlerList handlers = new HandlerList();
private final List<ItemStack> drops;
private int dropExp = 0;
public EntityDeathEvent(final LivingEntity entity, final List<ItemStack> drops) {
this(entity, drops, 0);
}
public EntityDeathEvent(final LivingEntity what, final List<ItemStack> drops, final int droppedExp) {
super(what);
this.drops = drops;
this.dropExp = droppedExp;
}
@Override
public LivingEntity getEntity() {
return (LivingEntity) entity;
}
/**
* Gets how much EXP should be dropped from this death.
* <p>
* This does not indicate how much EXP should be taken from the entity in
* question, merely how much should be created after its death.
*
* @return Amount of EXP to drop.
*/
public int getDroppedExp() {
return dropExp;
}
/**
* Sets how much EXP should be dropped from this death.
* <p>
* This does not indicate how much EXP should be taken from the entity in
* question, merely how much should be created after its death.
*
* @param exp Amount of EXP to drop.
*/
public void setDroppedExp(int exp) {
this.dropExp = exp;
}
/**
* Gets all the items which will drop when the entity dies
*
* @return Items to drop when the entity dies
*/
public List<ItemStack> getDrops() {
return drops;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
| 1 | 0.781216 | 1 | 0.781216 | game-dev | MEDIA | 0.830459 | game-dev | 0.925762 | 1 | 0.925762 |
FakeFishGames/Barotrauma | 17,423 | Libraries/MonoGame.Framework/Src/MonoGame.Framework/Content/ContentManager.cs | // MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using MonoGame.Utilities;
using Microsoft.Xna.Framework.Graphics;
using System.Globalization;
namespace Microsoft.Xna.Framework.Content
{
public partial class ContentManager : IDisposable
{
const byte ContentCompressedLzx = 0x80;
const byte ContentCompressedLz4 = 0x40;
private string _rootDirectory = string.Empty;
private IServiceProvider serviceProvider;
private IGraphicsDeviceService graphicsDeviceService;
private Dictionary<string, object> loadedAssets = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
private List<IDisposable> disposableAssets = new List<IDisposable>();
private bool disposed;
private byte[] scratchBuffer;
private static object ContentManagerLock = new object();
private static List<WeakReference> ContentManagers = new List<WeakReference>();
private static readonly List<char> targetPlatformIdentifiers = new List<char>()
{
'w', // Windows (XNA & DirectX)
'x', // Xbox360 (XNA)
'm', // WindowsPhone7.0 (XNA)
'i', // iOS
'a', // Android
'd', // DesktopGL
'X', // MacOSX
'W', // WindowsStoreApp
'n', // NativeClient
'M', // WindowsPhone8
'r', // RaspberryPi
'P', // PlayStation4
'v', // PSVita
'O', // XboxOne
'S', // Nintendo Switch
// NOTE: There are additional idenfiers for consoles that
// are not defined in this repository. Be sure to ask the
// console port maintainers to ensure no collisions occur.
// Legacy identifiers... these could be reused in the
// future if we feel enough time has passed.
'p', // PlayStationMobile
'g', // Windows (OpenGL)
'l', // Linux
};
static partial void PlatformStaticInit();
static ContentManager()
{
// Allow any per-platform static initialization to occur.
PlatformStaticInit();
}
private static void AddContentManager(ContentManager contentManager)
{
lock (ContentManagerLock)
{
// Check if the list contains this content manager already. Also take
// the opportunity to prune the list of any finalized content managers.
bool contains = false;
for (int i = ContentManagers.Count - 1; i >= 0; --i)
{
var contentRef = ContentManagers[i];
if (ReferenceEquals(contentRef.Target, contentManager))
contains = true;
if (!contentRef.IsAlive)
ContentManagers.RemoveAt(i);
}
if (!contains)
ContentManagers.Add(new WeakReference(contentManager));
}
}
private static void RemoveContentManager(ContentManager contentManager)
{
lock (ContentManagerLock)
{
// Check if the list contains this content manager and remove it. Also
// take the opportunity to prune the list of any finalized content managers.
for (int i = ContentManagers.Count - 1; i >= 0; --i)
{
var contentRef = ContentManagers[i];
if (!contentRef.IsAlive || ReferenceEquals(contentRef.Target, contentManager))
ContentManagers.RemoveAt(i);
}
}
}
internal static void ReloadGraphicsContent()
{
lock (ContentManagerLock)
{
// Reload the graphic assets of each content manager. Also take the
// opportunity to prune the list of any finalized content managers.
for (int i = ContentManagers.Count - 1; i >= 0; --i)
{
var contentRef = ContentManagers[i];
if (contentRef.IsAlive)
{
var contentManager = (ContentManager)contentRef.Target;
if (contentManager != null)
contentManager.ReloadGraphicsAssets();
}
else
{
ContentManagers.RemoveAt(i);
}
}
}
}
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~ContentManager()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
public ContentManager(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
this.serviceProvider = serviceProvider;
AddContentManager(this);
}
public ContentManager(IServiceProvider serviceProvider, string rootDirectory)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
if (rootDirectory == null)
{
throw new ArgumentNullException("rootDirectory");
}
this.RootDirectory = rootDirectory;
this.serviceProvider = serviceProvider;
AddContentManager(this);
}
public void Dispose()
{
Dispose(true);
// Tell the garbage collector not to call the finalizer
// since all the cleanup will already be done.
GC.SuppressFinalize(this);
// Once disposed, content manager wont be used again
RemoveContentManager(this);
}
// If disposing is true, it was called explicitly and we should dispose managed objects.
// If disposing is false, it was called by the finalizer and managed objects should not be disposed.
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
Unload();
}
scratchBuffer = null;
disposed = true;
}
}
public virtual T LoadLocalized<T> (string assetName)
{
string [] cultureNames =
{
CultureInfo.CurrentCulture.Name, // eg. "en-US"
CultureInfo.CurrentCulture.TwoLetterISOLanguageName // eg. "en"
};
// Look first for a specialized language-country version of the asset,
// then if that fails, loop back around to see if we can find one that
// specifies just the language without the country part.
foreach (string cultureName in cultureNames) {
string localizedAssetName = assetName + '.' + cultureName;
try {
return Load<T> (localizedAssetName);
} catch (ContentLoadException) { }
}
// If we didn't find any localized asset, fall back to the default name.
return Load<T> (assetName);
}
public virtual T Load<T>(string assetName)
{
if (string.IsNullOrEmpty(assetName))
{
throw new ArgumentNullException("assetName");
}
if (disposed)
{
throw new ObjectDisposedException("ContentManager");
}
T result = default(T);
// On some platforms, name and slash direction matter.
// We store the asset by a /-seperating key rather than how the
// path to the file was passed to us to avoid
// loading "content/asset1.xnb" and "content\\ASSET1.xnb" as if they were two
// different files. This matches stock XNA behavior.
// The dictionary will ignore case differences
var key = assetName.Replace('\\', '/');
// Check for a previously loaded asset first
object asset = null;
if (loadedAssets.TryGetValue(key, out asset))
{
if (asset is T)
{
return (T)asset;
}
}
// Load the asset.
result = ReadAsset<T>(assetName, null);
loadedAssets[key] = result;
return result;
}
protected virtual Stream OpenStream(string assetName)
{
Stream stream;
try
{
var assetPath = Path.Combine(RootDirectory, assetName) + ".xnb";
// This is primarily for editor support.
// Setting the RootDirectory to an absolute path is useful in editor
// situations, but TitleContainer can ONLY be passed relative paths.
#if DESKTOPGL || WINDOWS
if (Path.IsPathRooted(assetPath))
stream = File.OpenRead(assetPath);
else
#endif
stream = TitleContainer.OpenStream(assetPath);
#if ANDROID
// Read the asset into memory in one go. This results in a ~50% reduction
// in load times on Android due to slow Android asset streams.
MemoryStream memStream = new MemoryStream();
stream.CopyTo(memStream);
memStream.Seek(0, SeekOrigin.Begin);
stream.Close();
stream = memStream;
#endif
}
catch (FileNotFoundException fileNotFound)
{
throw new ContentLoadException("The content file was not found.", fileNotFound);
}
#if !WINDOWS_UAP
catch (DirectoryNotFoundException directoryNotFound)
{
throw new ContentLoadException("The directory was not found.", directoryNotFound);
}
#endif
catch (Exception exception)
{
throw new ContentLoadException("Opening stream error.", exception);
}
return stream;
}
protected T ReadAsset<T>(string assetName, Action<IDisposable> recordDisposableObject)
{
if (string.IsNullOrEmpty(assetName))
{
throw new ArgumentNullException("assetName");
}
if (disposed)
{
throw new ObjectDisposedException("ContentManager");
}
string originalAssetName = assetName;
object result = null;
if (this.graphicsDeviceService == null)
{
this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
if (this.graphicsDeviceService == null)
{
throw new InvalidOperationException("No Graphics Device Service");
}
}
// Try to load as XNB file
var stream = OpenStream(assetName);
using (var xnbReader = new BinaryReader(stream))
{
using (var reader = GetContentReaderFromXnb(assetName, stream, xnbReader, recordDisposableObject))
{
result = reader.ReadAsset<T>();
if (result is GraphicsResource)
((GraphicsResource)result).Name = originalAssetName;
}
}
if (result == null)
throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
return (T)result;
}
private ContentReader GetContentReaderFromXnb(string originalAssetName, Stream stream, BinaryReader xnbReader, Action<IDisposable> recordDisposableObject)
{
// The first 4 bytes should be the "XNB" header. i use that to detect an invalid file
byte x = xnbReader.ReadByte();
byte n = xnbReader.ReadByte();
byte b = xnbReader.ReadByte();
byte platform = xnbReader.ReadByte();
if (x != 'X' || n != 'N' || b != 'B' ||
!(targetPlatformIdentifiers.Contains((char)platform)))
{
throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?");
}
byte version = xnbReader.ReadByte();
byte flags = xnbReader.ReadByte();
bool compressedLzx = (flags & ContentCompressedLzx) != 0;
bool compressedLz4 = (flags & ContentCompressedLz4) != 0;
if (version != 5 && version != 4)
{
throw new ContentLoadException("Invalid XNB version");
}
// The next int32 is the length of the XNB file
int xnbLength = xnbReader.ReadInt32();
Stream decompressedStream = null;
if (compressedLzx || compressedLz4)
{
// Decompress the xnb
int decompressedSize = xnbReader.ReadInt32();
if (compressedLzx)
{
int compressedSize = xnbLength - 14;
decompressedStream = new LzxDecoderStream(stream, decompressedSize, compressedSize);
}
else if (compressedLz4)
{
decompressedStream = new Lz4DecoderStream(stream);
}
}
else
{
decompressedStream = stream;
}
var reader = new ContentReader(this, decompressedStream, this.graphicsDeviceService.GraphicsDevice,
originalAssetName, version, recordDisposableObject);
return reader;
}
internal void RecordDisposable(IDisposable disposable)
{
Debug.Assert(disposable != null, "The disposable is null!");
// Avoid recording disposable objects twice. ReloadAsset will try to record the disposables again.
// We don't know which asset recorded which disposable so just guard against storing multiple of the same instance.
if (!disposableAssets.Contains(disposable))
disposableAssets.Add(disposable);
}
/// <summary>
/// Virtual property to allow a derived ContentManager to have it's assets reloaded
/// </summary>
protected virtual Dictionary<string, object> LoadedAssets
{
get { return loadedAssets; }
}
protected virtual void ReloadGraphicsAssets()
{
foreach (var asset in LoadedAssets)
{
// This never executes as asset.Key is never null. This just forces the
// linker to include the ReloadAsset function when AOT compiled.
if (asset.Key == null)
ReloadAsset(asset.Key, Convert.ChangeType(asset.Value, asset.Value.GetType()));
var methodInfo = ReflectionHelpers.GetMethodInfo(typeof(ContentManager), "ReloadAsset");
var genericMethod = methodInfo.MakeGenericMethod(asset.Value.GetType());
genericMethod.Invoke(this, new object[] { asset.Key, Convert.ChangeType(asset.Value, asset.Value.GetType()) });
}
}
protected virtual void ReloadAsset<T>(string originalAssetName, T currentAsset)
{
string assetName = originalAssetName;
if (string.IsNullOrEmpty(assetName))
{
throw new ArgumentNullException("assetName");
}
if (disposed)
{
throw new ObjectDisposedException("ContentManager");
}
if (this.graphicsDeviceService == null)
{
this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
if (this.graphicsDeviceService == null)
{
throw new InvalidOperationException("No Graphics Device Service");
}
}
var stream = OpenStream(assetName);
using (var xnbReader = new BinaryReader(stream))
{
using (var reader = GetContentReaderFromXnb(assetName, stream, xnbReader, null))
{
reader.ReadAsset<T>(currentAsset);
}
}
}
public virtual void Unload()
{
// Look for disposable assets.
foreach (var disposable in disposableAssets)
{
if (disposable != null)
disposable.Dispose();
}
disposableAssets.Clear();
loadedAssets.Clear();
}
public string RootDirectory
{
get
{
return _rootDirectory;
}
set
{
_rootDirectory = value;
}
}
internal string RootDirectoryFullPath
{
get
{
return Path.Combine(TitleContainer.Location, RootDirectory);
}
}
public IServiceProvider ServiceProvider
{
get
{
return this.serviceProvider;
}
}
internal byte[] GetScratchBuffer(int size)
{
size = Math.Max(size, 1024 * 1024);
if (scratchBuffer == null || scratchBuffer.Length < size)
scratchBuffer = new byte[size];
return scratchBuffer;
}
}
}
| 1 | 0.987555 | 1 | 0.987555 | game-dev | MEDIA | 0.770809 | game-dev | 0.994012 | 1 | 0.994012 |
BahamutDragon/pcgen | 97,994 | data/35e/wizards_of_the_coast/campaign_settings/dragonlance/campaign/dcs_abilities.lst |
Kender CATEGORY:Race BONUS:ABILITYPOOL|Race Base|1|TYPE=Base
###Block: Dragonlance Version Races
Human / Dragonlance CATEGORY:Internal TYPE:Race Base.RaceRestriction_Dragonlance PRERACE:1,Human ABILITY:Internal|AUTOMATIC|Race Traits ~ DL Human DESC:Default Dragonlance version of the race
Dwarf / Dragonlance CATEGORY:Internal TYPE:Race Base.RaceRestriction_Dragonlance PRERACE:1,Dwarf ABILITY:Internal|AUTOMATIC|Race Traits ~ DL Dwarf DESC:Default Dragonlance version of the race
Elf / Dragonlance CATEGORY:Internal TYPE:Race Base.RaceRestriction_Dragonlance PRERACE:1,Elf ABILITY:Internal|AUTOMATIC|Race Traits ~ DL Elf DESC:Default Dragonlance version of the race
Gnome / Dragonlance CATEGORY:Internal TYPE:Race Base.RaceRestriction_Dragonlance PRERACE:1,Gnome ABILITY:Internal|AUTOMATIC|Race Traits ~ DL Gnome DESC:Default Dragonlance version of the race
Half-Elf / Dragonlance CATEGORY:Internal TYPE:Race Base.RaceRestriction_Dragonlance PRERACE:1,Half-Elf ABILITY:Internal|AUTOMATIC|Race Traits ~ DL Half-Elf DESC:Default Dragonlance version of the race
Kender / Dragonlance CATEGORY:Internal TYPE:Race Base.RaceRestriction_Dragonlance PRERACE:1,Kender ABILITY:Internal|AUTOMATIC|Race Traits ~ DL Kender DESC:Default Dragonlance version of the race
###Block:
Race Traits ~ DL Human CATEGORY:Internal ABILITY:Human Subrace|AUTOMATIC|Human ~ Base|!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice ABILITY:Special Ability|AUTOMATIC|Human Racial Traits|PREABILITY:1,CATEGORY=Internal,TYPE.HumanSubrace
Race Traits ~ DL Kender CATEGORY:Internal ABILITY:Kender Subrace|AUTOMATIC|Kender ~ Kender (Krynn)|!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice
Race Traits ~ DL Dwarf CATEGORY:Internal ABILITY:Dwarf Subrace|AUTOMATIC|Dwarf ~ Hill (Krynn)|!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice ABILITY:Special Ability|AUTOMATIC|Dwarf Racial Traits|PREABILITY:1,CATEGORY=Internal,TYPE.DwarfSubrace
Race Traits ~ DL Elf CATEGORY:Internal ABILITY:Elf Subrace|AUTOMATIC|Elf ~ Qualinesti (Krynn)|!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice ABILITY:Special Ability|AUTOMATIC|Elf Racial Traits|PREABILITY:1,CATEGORY=Internal,TYPE.ElfSubrace ABILITY:Elf Race Trait|AUTOMATIC|Elf ~ Trance|Elf (DL) ~ Elvensight
Race Traits ~ DL Gnome CATEGORY:Internal ABILITY:Gnome Subrace|AUTOMATIC|Gnome ~ Gnome (Krynn)|!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice ABILITY:Special Ability|AUTOMATIC|Gnome Racial Traits|PREABILITY:1,CATEGORY=Internal,TYPE.GnomeSubrace
Race Traits ~ DL Half-Elf CATEGORY:Internal ABILITY:Half-Elf Subrace|AUTOMATIC|Half-Elf|!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice ABILITY:Special Ability|AUTOMATIC|Half-Elf Racial Traits|PREABILITY:1,CATEGORY=Internal,TYPE.HalfElfSubrace ABILITY:Elf Race Trait|AUTOMATIC|Elf (DL) ~ Elvensight
###Block: Races
# Ability Name Unique Key Category of Ability Type Auto Language Ability Bonus Ability Pool Bonus to skill Bonus
Hill Dwarf (Krynn) KEY:Dwarf ~ Hill (Krynn) CATEGORY:Internal TYPE:DwarfSubrace.Krynn_Campaign PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Dwarf ~ Hill (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance TEMPLATE:Subrace ~ Hill UNENCUMBEREDMOVE:HeavyLoad|HeavyArmor ABILITY:Internal|AUTOMATIC|Favored Class ~ Fighter|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Darkvision|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfRacialVision ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Weapon Familiarity|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfWeaponFamiliarity ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Stonecunning|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfStonecunning ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Stability|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfStability ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Poison Save Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfPoisonSaveBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Spell Save Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfSpellSaveBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Attack Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfAttackBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Dodge Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfDodgeBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Appraise Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfAppraiseBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Craft Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfCraftBonus ABILITY:Internal|AUTOMATIC|Language ~ Auto (Dwarf)|!PREABILITY:1,CATEGORY=Internal,TYPE.AutoLangReplace ABILITY:Internal|AUTOMATIC|Language ~ Bonus (Dragonlance Hill Dwarf)|!PREABILITY:1,CATEGORY=Internal,TYPE.BonusLangReplace BONUS:STAT|CON|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|CHA|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0
Mountain Dwarf (Krynn) KEY:Dwarf ~ Mountain (Krynn) CATEGORY:Internal TYPE:DwarfSubrace.Krynn_Campaign.AltSubraceChoice PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Dwarf ~ Mountain (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance TEMPLATE:Subrace ~ Mountain UNENCUMBEREDMOVE:HeavyLoad|HeavyArmor ABILITY:Internal|AUTOMATIC|Favored Class ~ Fighter|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Darkvision|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfRacialVision ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Weapon Familiarity|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfWeaponFamiliarity ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Stonecunning|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfStonecunning ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Stability|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfStability ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Poison Save Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfPoisonSaveBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Spell Save Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfSpellSaveBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Attack Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfAttackBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Dodge Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfDodgeBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Appraise Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfAppraiseBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Craft Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfCraftBonus ABILITY:Internal|AUTOMATIC|Language ~ Auto (Dwarf)|!PREABILITY:1,CATEGORY=Internal,TYPE.AutoLangReplace ABILITY:Internal|AUTOMATIC|Language ~ Bonus (Dragonlance Mountain Dwarf)|!PREABILITY:1,CATEGORY=Internal,TYPE.BonusLangReplace BONUS:STAT|CON|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|CHA|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0
Dark Dwarf (Krynn) KEY:Dwarf ~ Dark (Krynn) CATEGORY:Internal TYPE:DwarfSubrace.Krynn_Campaign.AltSubraceChoice PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Dwarf ~ Dark (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance TEMPLATE:Subrace ~ Dark UNENCUMBEREDMOVE:HeavyLoad|HeavyArmor ABILITY:Internal|AUTOMATIC|Favored Class ~ Rogue|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Weapon Familiarity|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfWeaponFamiliarity ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Stonecunning|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfStonecunning ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Stability|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfStability ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Poison Save Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfPoisonSaveBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Spell Save Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfSpellSaveBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Attack Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfAttackBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Dodge Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfDodgeBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Appraise Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfAppraiseBonus ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf ~ Craft Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfCraftBonus ABILITY:Internal|AUTOMATIC|Language ~ Auto (Dwarf)|!PREABILITY:1,CATEGORY=Internal,TYPE.AutoLangReplace ABILITY:Internal|AUTOMATIC|Language ~ Bonus (Dwarf)|!PREABILITY:1,CATEGORY=Internal,TYPE.BonusLangReplace ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf (DL Dark) ~ Darkvision|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.DwarfRacialVision ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf (DL Dark) ~ Racial Skill Bonuses|PREVAREQ:DisableRacialTraits,0 ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf (DL Dark) ~ Light Sensitivity|PREVAREQ:DisableRacialTraits,0 BONUS:STAT|CON|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|CHA|-4|TYPE=Racial|PREVAREQ:DisableRacialStats,0
Gully Dwarf (Krynn) KEY:Dwarf ~ Gully (Krynn) CATEGORY:Internal TYPE:DwarfSubrace.Krynn_Campaign.AltSubraceChoice PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Dwarf ~ Gully (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance TEMPLATE:Subrace ~ Gully ABILITY:Internal|AUTOMATIC|Favored Class ~ Rogue|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf (DL Gully) ~ Small ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf (DL Gully) ~ Speed ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf (DL Gully) ~ Survival Instinct ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf (DL Gully) ~ Hardy ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf (DL Gully) ~ Pitiable ABILITY:Dwarf Race Trait|AUTOMATIC|Dwarf (DL Gully) ~ Cowardly ABILITY:Internal|AUTOMATIC|Language ~ Auto (Gully Dwarf)|!PREABILITY:1,CATEGORY=Internal,TYPE.AutoLangReplace BONUS:STAT|DEX|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|CON|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|INT|-4|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|CHA|-4|TYPE=Racial|PREVAREQ:DisableRacialStats,0
# Elves
Kagonesti (Krynn) KEY:Elf ~ Kagonesti (Krynn) CATEGORY:Internal TYPE:ElfSubrace.Krynn_Campaign.AltSubraceChoice PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Elf ~ Kagonesti (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance TEMPLATE:Subrace ~ Kagonesti ABILITY:Internal|AUTOMATIC|Favored Class ~ Wizard|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Elf Race Trait|AUTOMATIC|Elf ~ Racial Immunity|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.ElfRacialImmunity ABILITY:Elf Race Trait|AUTOMATIC|Elf ~ Low-Light Vision|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.ElfLowLightVision ABILITY:Internal|AUTOMATIC|Language ~ Auto (Kagonesti Elf)|!PREABILITY:1,CATEGORY=Internal,TYPE.AutoLangReplace ABILITY:Internal|AUTOMATIC|Language ~ Bonus (Kagonesti Elf)|!PREABILITY:1,CATEGORY=Internal,TYPE.BonusLangReplace BONUS:STAT|DEX|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|INT|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|CHA|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 ABILITY:Elf Race Trait|AUTOMATIC|Elf (DL) Kagonesti ~ Weapon Proficiency|PREVAREQ:DisableRacialTraits,0 ABILITY:Elf Race Trait|AUTOMATIC|Elf (DL) Kagonesti ~ Skill Bonus|PREVAREQ:DisableRacialTraits,0
Qualinesti (Krynn) KEY:Elf ~ Qualinesti (Krynn) CATEGORY:Internal TYPE:ElfSubrace.Krynn_Campaign PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Elf ~ Qualinesti (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance TEMPLATE:Subrace ~ Qualinesti ABILITY:Internal|AUTOMATIC|Favored Class ~ Wizard|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Elf Race Trait|AUTOMATIC|Elf ~ Racial Immunity|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.ElfRacialImmunity ABILITY:Elf Race Trait|AUTOMATIC|Elf ~ Low-Light Vision|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.ElfLowLightVision ABILITY:Elf Race Trait|AUTOMATIC|Elf ~ Weapon Proficiency|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.ElfWeaponProficiency ABILITY:Elf Race Trait|AUTOMATIC|Elf (DL) Qualinesti ~ Skill Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.ElfSkillBonus ABILITY:Internal|AUTOMATIC|Language ~ Auto (Qualinesti Elf)|!PREABILITY:1,CATEGORY=Internal,TYPE.AutoLangReplace ABILITY:Internal|AUTOMATIC|Language ~ Bonus (Qualinesti Elf)|!PREABILITY:1,CATEGORY=Internal,TYPE.BonusLangReplace BONUS:STAT|CON|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|DEX|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0
Silvanesti (Krynn) KEY:Elf ~ Silvanesti (Krynn) CATEGORY:Internal TYPE:ElfSubrace.Krynn_Campaign.AltSubraceChoice PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Elf ~ Silvanesti (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance TEMPLATE:Subrace ~ Silvanesti ABILITY:Internal|AUTOMATIC|Favored Class ~ Wizard|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Elf Race Trait|AUTOMATIC|Elf ~ Racial Immunity|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.ElfRacialImmunity ABILITY:Elf Race Trait|AUTOMATIC|Elf ~ Low-Light Vision|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.ElfLowLightVision ABILITY:Elf Race Trait|AUTOMATIC|Elf ~ Weapon Proficiency|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.ElfWeaponProficiency ABILITY:Elf Race Trait|AUTOMATIC|Elf ~ Skill Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.ElfSkillBonus ABILITY:Internal|AUTOMATIC|Language ~ Auto (Silvanesti Elf)|!PREABILITY:1,CATEGORY=Internal,TYPE.AutoLangReplace ABILITY:Internal|AUTOMATIC|Language ~ Bonus (Silvanesti Elf)|!PREABILITY:1,CATEGORY=Internal,TYPE.BonusLangReplace BONUS:STAT|DEX|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|INT|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|CON|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|CHA|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0
Half-Elf KEY:Half-Elf (Krynn) CATEGORY:Internal TYPE:HalfElfSubrace.HalfElfBase PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Half-Elf (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance TEMPLATE:Half-Elf ABILITY:Internal|AUTOMATIC|Favored Class ~ HIGHESTLEVELCLASS|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Half-Elf Race Trait|AUTOMATIC|Half-Elf ~ Elven Blood|!PREABILITY:1,CATEGORY=Special Ability,TYPE.HalfElfBlood ABILITY:Half-Elf Race Trait|AUTOMATIC|Half-Elf ~ Racial +1 Skill Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.HalfElfPerception ABILITY:Half-Elf Race Trait|AUTOMATIC|Half-Elf ~ Racial +2 Skill Bonus|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.HalfElfPersuasion ABILITY:Half-Elf Race Trait|AUTOMATIC|Half-Elf ~ Racial Immunity|PREVAREQ:DisableRacialTraits,0|!PREABILITY:1,CATEGORY=Special Ability,TYPE.HalfElfImmunity ABILITY:Internal|AUTOMATIC|Language ~ Auto (Elf)|!PREABILITY:1,CATEGORY=Internal,TYPE.AutoLangReplace ABILITY:Internal|AUTOMATIC|Language ~ Bonus (Half-Elf)|!PREABILITY:1,CATEGORY=Internal,TYPE.BonusLangReplace COST:0
Dargonesti (Krynn) KEY:Elf ~ Dargonesti (Krynn) CATEGORY:Internal TYPE:ElfSubrace.Krynn_Campaign.AltSubraceChoice PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Elf ~ Dargonesti (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance TEMPLATE:Subrace ~ Dargonesti ABILITY:Internal|AUTOMATIC|Favored Class ~ Fighter|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Elf Race Trait|AUTOMATIC|TYPE=DL_SeaElfRacialTrait ABILITY:Elf Race Trait|AUTOMATIC|TYPE=Dargonesti Elf Race Trait ABILITY:Internal|AUTOMATIC|Language ~ Auto (Dargonesti Elf)|!PREABILITY:1,CATEGORY=Internal,TYPE.AutoLangReplace ABILITY:Internal|AUTOMATIC|Language ~ Bonus (Dargonesti Elf)|!PREABILITY:1,CATEGORY=Internal,TYPE.BonusLangReplace BONUS:STAT|STR|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|DEX|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|CHA|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0
Dimeresti (Krynn) KEY:Elf ~ Dimeresti (Krynn) CATEGORY:Internal TYPE:ElfSubrace.Krynn_Campaign.AltSubraceChoice PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Elf ~ Dimeresti (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance TEMPLATE:Subrace ~ Dimeresti ABILITY:Internal|AUTOMATIC|Favored Class ~ Barbarian|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Elf Race Trait|AUTOMATIC|TYPE=DL_SeaElfRacialTrait ABILITY:Elf Race Trait|AUTOMATIC|TYPE=Dimeresti Elf Race Trait ABILITY:Internal|AUTOMATIC|Language ~ Auto (Dimeresti Elf)|!PREABILITY:1,CATEGORY=Internal,TYPE.AutoLangReplace ABILITY:Internal|AUTOMATIC|Language ~ Bonus (Dimeresti Elf)|!PREABILITY:1,CATEGORY=Internal,TYPE.BonusLangReplace BONUS:STAT|DEX|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|INT|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|WIS|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|CHA|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0
# Gnomes
Gnome (Krynn) KEY:Gnome ~ Gnome (Krynn) CATEGORY:Internal TYPE:GnomeSubrace.Krynn_Campaign PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Gnome ~ Gnome (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance ABILITY:Internal|AUTOMATIC|Favored Class ~ HIGHESTLEVELCLASS|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Internal|AUTOMATIC|Language ~ Auto (Gnome)|!PREABILITY:1,CATEGORY=Internal,TYPE.AutoLangReplace ABILITY:Internal|AUTOMATIC|Language ~ Bonus (Dragonlance Gnome)|!PREABILITY:1,CATEGORY=Internal,TYPE.BonusLangReplace BONUS:STAT|DEX|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|INT|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|STR|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|WIS|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 ABILITY:Gnome Race Trait|AUTOMATIC|TYPE=Gnome Race Trait|PREVAREQ:DisableRacialTraits,0
Mad Gnome (Krynn) KEY:Gnome ~ Mad Gnome (Krynn) CATEGORY:Internal TYPE:GnomeSubrace.Krynn_Campaign.AltSubraceChoice PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Gnome ~ Mad Gnome (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance TEMPLATE:Subrace ~ Mad ABILITY:Internal|AUTOMATIC|Favored Class ~ HIGHESTLEVELCLASS|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Internal|AUTOMATIC|Language ~ Auto (Gnome)|!PREABILITY:1,CATEGORY=Internal,TYPE.AutoLangReplace ABILITY:Internal|AUTOMATIC|Language ~ Bonus (Dragonlance Gnome)|!PREABILITY:1,CATEGORY=Internal,TYPE.BonusLangReplace BONUS:STAT|DEX|2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 BONUS:STAT|STR|-2|TYPE=Racial|PREVAREQ:DisableRacialStats,0 ABILITY:Gnome Race Trait|AUTOMATIC|TYPE=Mad Gnome Race Trait|PREVAREQ:DisableRacialTraits,0
# Kender
Kender (Krynn) KEY:Kender ~ Kender (Krynn) CATEGORY:Internal TYPE:KenderSubrace.Krynn_Campaign PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Kender ~ Kender (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance ABILITY:Internal|AUTOMATIC|Favored Class ~ Rogue|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Kender Race Trait|AUTOMATIC|Kender ~ Save Bonus ABILITY:Kender Race Trait|AUTOMATIC|Kender ~ Spot Bonus ABILITY:Kender Race Trait|AUTOMATIC|Kender ~ Thievery Bonus ABILITY:Kender Race Trait|AUTOMATIC|Kender ~ Lack of Focus ABILITY:Kender Race Trait|AUTOMATIC|Kender ~ Taunt ABILITY:Kender Race Trait|AUTOMATIC|Kender ~ Fearlessness
Afflicted Kender (Krynn) KEY:Kender ~ Afflicted Kender (Krynn) CATEGORY:Internal TYPE:KenderSubrace.Krynn_Campaign.AltSubraceChoice PREMULT:1,[!PREABILITY:1,CATEGORY=Internal,TYPE.AltSubraceChoice],[PREABILITY:1,CATEGORY=Internal,Kender ~ Afflicted Kender (Krynn)] COST:0 PREABILITY:1,CATEGORY=Internal,TYPE.RaceRestriction_Dragonlance TEMPLATE:Subrace ~ Afflicted ABILITY:Internal|AUTOMATIC|Favored Class ~ Rogue|PREVAREQ:RemoveDefaultFavoredClass,0 ABILITY:Kender Race Trait|AUTOMATIC|Afflicted Kender ~ Skill Bonus ABILITY:Kender Race Trait|AUTOMATIC|Kender ~ Save Bonus ABILITY:Kender Race Trait|AUTOMATIC|Kender ~ Spot Bonus ABILITY:Kender Race Trait|AUTOMATIC|Kender ~ Thievery Bonus
#
# Racial Traits
#
###Block: Dark Dwarf Traits
Darkvision KEY:Dwarf (DL Dark) ~ Darkvision SOURCEPAGE:p.14 CATEGORY:Special Ability TYPE:Race Trait.Dwarf Race Trait.Dark Dwarf Race Trait.SpecialQuality VISIBLE:YES BONUS:VAR|DarkvisionRange|120|TYPE=Base DESC:Darkvision out to 120 feet.
Racial Skill Bonuses KEY:Dwarf (DL Dark) ~ Racial Skill Bonuses SOURCEPAGE:p.14 CATEGORY:Special Ability TYPE:Race Trait.Dwarf Race Trait.Dark Dwarf Race Trait.SpecialQuality VISIBLE:YES BONUS:SKILL|Hide,Listen,Move Silently|2|TYPE=Racial DESC:+2 racial bonus on Hide, Listen, and Move Silently checks. Dark dwarves are skilled in skulking in the darkness, and make excellent spies.
Light Sensitivity KEY:Dwarf (DL Dark) ~ Light Sensitivity SOURCEPAGE:p.14 CATEGORY:Special Ability TYPE:Race Trait.Dwarf Race Trait.Dark Dwarf Race Trait.SpecialQuality VISIBLE:YES DESC:Dark dwarves take a -2 circumstance penalty on attack rolls, saves, and checks in bright sunlight or within the radius of a daylight spell.
###Block: Gully Dwarf Traits
Small KEY:Dwarf (DL Gully) ~ Small SOURCEPAGE:p.16 CATEGORY:Special Ability TYPE:Race Trait.Dwarf Race Trait.Gully Dwarf Race Trait.SpecialQuality BONUS:SIZEMOD|NUMBER|-1 DESC:As Small creatures, gully dwarves gain a +1 size bonus to Armor class, a +1 size bonu on attack rolls, and a +4 size bonus on Hide checks, but they must use smaller weapons than humans use, and their lifting and carrying limits are three-quarters of those of Medium creatures.
Speed KEY:Dwarf (DL Gully) ~ Speed SOURCEPAGE:p.16 CATEGORY:Special Ability TYPE:Race Trait.Dwarf Race Trait.Gully Dwarf Race Trait.SpecialQuality BONUS:VAR|Base_Move|20|TYPE=Base DESC:Gully dwarf base land speed is 20 feet.
Survival Instinct KEY:Dwarf (DL Gully) ~ Survival Instinct SOURCEPAGE:p.16 CATEGORY:Special Ability TYPE:Race Trait.Dwarf Race Trait.Gully Dwarf Race Trait.SpecialQuality DESC:Gully dwarves are driven to survive. They recieve a +2 racial bonus on Hide, Move Silently, and Survival checks. Gully dwarves may use Survival checks even in cities to forage for food and basic necessities.
Hardy KEY:Dwarf (DL Gully) ~ Hardy SOURCEPAGE:p.16 CATEGORY:Special Ability TYPE:Race Trait.Dwarf Race Trait.Gully Dwarf Race Trait.SpecialQuality DESC:Gully dwarves are resistant to the effects of disease and poison, receiving a +2 racial bonus on Fortitude saves to resist the effect of poison and disease.
Pitiable KEY:Dwarf (DL Gully) ~ Pitiable SOURCEPAGE:p.16 CATEGORY:Special Ability TYPE:Race Trait.Dwarf Race Trait.Gully Dwarf Race Trait.SpecialQuality DESC:+4 racial bonus on Diplomacy checks used to convince an enemy not to harm them.
Cowardly KEY:Dwarf (DL Gully) ~ Cowardly SOURCEPAGE:p.16 CATEGORY:Special Ability TYPE:Race Trait.Dwarf Race Trait.Gully Dwarf Race Trait.SpecialQuality DESC:=4 penalty on level checks to resist Intimidation checks made against them and on saving throws against fear.
###Block: Elvensight
Elvensight KEY:Elf (DL) ~ Elvensight SOURCEPAGE:p.18 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.SpecialQuality BONUS:VAR|HasLowlightVision|1 BONUS:VAR|DarkvisionRange|30|TYPE=Base DESC:Krynn elves have low-light vision, and can see twice as far as a human in starlight, moonlight, and similar conditions or poor illumination. They retain the ability to distinguish color and detail under these circumstances. Elvensight also includes darkvision up to 30 feet. Darkvision is black and white only, but it is otherwise like normal sight.
###Block: Kagonesti Traits
Weapon Proficiency KEY:Elf (DL) Kagonesti ~ Weapon Proficiency SOURCEPAGE:p.18 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.Kagonesti Elf Race Trait.SpecialQuality ABILITY:FEAT|AUTOMATIC|Martial Weapon Proficiency (Sword (Short))|Martial Weapon Proficiency (Longspear)|Martial Weapon Proficiency (Shortbow)|Martial Weapon Proficiency (Longbow)
Skill Bonus KEY:Elf (DL) Kagonesti ~ Skill Bonus SOURCEPAGE:p.18 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.Kagonesti Elf Race Trait.SpecialQuality BONUS:SKILL|Knowledge (Nature),Survival|1|TYPE=Racial
###Block: Qualinesti Traits (Default)
Skill Bonus KEY:Elf (DL) Qualinesti ~ Skill Bonus SOURCEPAGE:p.19 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.Qualinesti Elf Race Trait.SpecialQuality BONUS:SKILL|Diplomacy,Sense Motive|1|TYPE=Racial
###Block: Silvanesti Traits
Skill Bonus KEY:Elf (DL) Silvanesti ~ Skill Bonus SOURCEPAGE:p.19 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.Silvanesti Elf Race Trait.SpecialQuality BONUS:SKILL|Diplomacy,Sense Motive|1|TYPE=Racial
###Block: Sea Elf Racial Traits
#Sea Elf Racial Traits SOURCEPAGE:p.24 CATEGORY:Special Ability ABILITY:Elf Race Trait|AUTOMATIC|TYPE=DL_SeaElfRacialTrait
Medium KEY:Elf (DL) Sea ~ Medium SOURCEPAGE:p.24 CATEGORY:Special Ability TYPE:DL_SeaElfRacialTrait.Race Trait.Elf Race Trait.Sea Elf Race Trait.SpecialQuality DESC:Medium
Movement KEY:Elf (DL) Sea ~ Movement SOURCEPAGE:p.24 CATEGORY:Special Ability TYPE:DL_SeaElfRacialTrait.Race Trait.Elf Race Trait.Sea Elf Race Trait.SpecialQuality DESC:Base land speed 30 feet. They also have a swim speed of 30 feet.
Breathe Water KEY:Elf (DL) Sea ~ Breathe Water SOURCEPAGE:p.24 CATEGORY:Special Ability TYPE:DL_SeaElfRacialTrait.Race Trait.Elf Race Trait.Sea Elf Race Trait.SpecialQuality.Extraordinary DESC:Sea elves can breathe water as an extraordinary ability.
Immunities KEY:Elf (DL) Sea ~ Immunities SOURCEPAGE:p.24 CATEGORY:Special Ability TYPE:DL_SeaElfRacialTrait.Race Trait.Elf Race Trait.Sea Elf Race Trait.SpecialQuality DESC:Immunity to magic sleep spells and effects, and a +2 racial saving throw bonus against Enchantment spells or effects.
Weapon Proficiency KEY:Elf (DL) Sea ~ Weapon Proficiency SOURCEPAGE:p.24 CATEGORY:Special Ability TYPE:DL_SeaElfRacialTrait.Race Trait.Elf Race Trait.Sea Elf Race Trait.SpecialQuality ABILITY:FEAT|AUTOMATIC|Martial Weapon Proficiency (Trident)|Martial Weapon Proficiency (Longspear)|Exotic Weapon Proficiency (Net)
Skill Bonus KEY:Elf (DL) Sea ~ Skill Bonus SOURCEPAGE:p.24 CATEGORY:Special Ability TYPE:DL_SeaElfRacialTrait.Race Trait.Elf Race Trait.Sea Elf Race Trait.SpecialQuality BONUS:SKILL|Listen,Search,Spot|2|TYPE=Racial
Seasense KEY:Elf (DL) Sea ~ Seasense SOURCEPAGE:p.24 CATEGORY:Special Ability TYPE:DL_SeaElfRacialTrait.Race Trait.Elf Race Trait.Sea Elf Race Trait.SpecialQuality DESC:+2 racial bonus on checks to notice peculiarities about water.
###Block: Dargonesti Traits
Darkvision KEY:Elf (DL) Dargonesti ~ Darkvision SOURCEPAGE:p.24 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.Dargonesti Elf Race Trait.SpecialQuality BONUS:VAR|DarkvisionRange|60|TYPE=Base
Spell-Like Abilities KEY:Elf (DL) Dargonesti ~ Spell-Like Abilities SOURCEPAGE:p.24 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.Dargonesti Elf Race Trait.SpecialQuality SPELLS:Innate|CASTERLEVEL=TL|TIMES=1|Blur|Dancing Lights|Darkness|Obscuring Mist
Alternate Form KEY:Elf (DL) Dargonesti ~ Alternate Form SOURCEPAGE:p.24 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.Dargonesti Elf Race Trait.SpecialQuality.Supernatural DESC:3/day assume the form and phyuusical qualities of a porpoise.
Surface Sensitivity KEY:Elf (DL) Dargonesti ~ Surface Sensitivity SOURCEPAGE:p.24 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.Dargonesti Elf Race Trait.SpecialQuality.Extraordinary DESC:-2 circumstance penalty on attack rolls, saves, and checks when they have spent more than 24 hours out of water.
Level Adjustment KEY:Elf (DL) Dargonesti ~ Level Adjustment SOURCEPAGE:p.25 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.Dargonesti Elf Race Trait.SpecialQuality DESC:+1 Level adjustment. TEMPLATE:Level Adjustment +1
###Block: Dimeresti Traits
Alternate Form KEY:Elf (DL) Dimeresti ~ Alternate Form SOURCEPAGE:p.25 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.Dimeresti Elf Race Trait.SpecialQuality.Supernatural DESC:3/day assume the form and physical qualities of a medium sea otter.
Surface Sensitivity KEY:Elf (DL) Dimeresti ~ Surface Sensitivity SOURCEPAGE:p.25 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.Dimeresti Elf Race Trait.SpecialQuality.Extraordinary DESC:-1 circumstance penalty on attack rolls, saves, and checks when they have spent more than 24 hours out of water.
Level Adjustment KEY:Elf (DL) Dimeresti ~ Level Adjustment SOURCEPAGE:p.25 CATEGORY:Special Ability TYPE:Race Trait.Elf Race Trait.Dimeresti Elf Race Trait.SpecialQuality DESC:+1 Level adjustment. TEMPLATE:Level Adjustment +1
###Block: Gnome Traits
Small KEY:Gnome (DL) ~ Small SOURCEPAGE:p.27 CATEGORY:Special Ability TYPE:Race Trait.Gnome Race Trait.Mad Gnome Race Trait.SpecialQuality DESC:Small Size
Movement KEY:Gnome (DL) ~ Movement SOURCEPAGE:p.27 CATEGORY:Special Ability TYPE:Race Trait.Gnome Race Trait.Mad Gnome Race Trait.SpecialQuality DESC:Land speed 20 feet.
Skill Bonus KEY:Gnome (DL) ~ Skill Bonus SOURCEPAGE:p.27 CATEGORY:Special Ability TYPE:Race Trait.Gnome Race Trait.SpecialQuality DESC:+2 racial bonus on Craft (Alchemy) checks. BONUS:SKILL|Craft (Alchemy)|2|TYPE=Racial
Guild Affiliation KEY:Gnome (DL) ~ Guild Affiliation SOURCEPAGE:p.27 CATEGORY:Special Ability TYPE:Race Trait.Gnome Race Trait.Mad Gnome Race Trait.SpecialQuality DESC:Choose a guild category affiliation. BONUS:ABILITYPOOL|Gnome Guild Affiliation|1
Save Bonus KEY:Gnome (DL) ~ Save Bonus SOURCEPAGE:p.28 CATEGORY:Special Ability TYPE:Race Trait.Gnome Race Trait.SpecialQuality DESC:+2 racial bonus on Will saves. BONUS:SAVE|Will|2|TYPE=Racial
Craft Guild KEY:Gnome (DL) ~ Guild Affiliation / Craft CATEGORY:Special Ability TYPE:Gnome Guild Affiliation BONUS:SKILL|TYPE=Craft|2|TYPE=Racial
Technical Guild KEY:Gnome (DL) ~ Guild Affiliation / Technical CATEGORY:Special Ability TYPE:Gnome Guild Affiliation BONUS:SKILL|TYPE=Profession|2|TYPE=Racial
Sage Guild KEY:Gnome (DL) ~ Guild Affiliation / Sage CATEGORY:Special Ability TYPE:Gnome Guild Affiliation BONUS:SKILL|TYPE=Knowledge|2|TYPE=Racial
###Block: Mad Gnome Traits
Skill Bonus KEY:Mad Gnome (DL) ~ Skill Bonus SOURCEPAGE:p.27 CATEGORY:Special Ability TYPE:Race Trait.Gnome Race Trait.Mad Gnome Race Trait.SpecialQuality DESC:+2 racial bonus on Open Lock and Disable Device BONUS:SKILL|Open Lock|2|TYPE=Racial BONUS:SKILL|Disable Device|2|TYPE=Racial
###Block: Standard Kender
+1 Racial bonus on all saving throws SOURCEPAGE:p.31 KEY:Kender ~ Save Bonus CATEGORY:Special Ability TYPE:SpecialQuality.Kender Race Trait BONUS:SAVE|Fortitude,Reflex,Will|1|TYPE=Racial
+2 Racial bonus to spot SOURCEPAGE:p.31 KEY:Kender ~ Spot Bonus CATEGORY:Special Ability TYPE:SpecialQuality.Kender Race Trait BONUS:SKILL|Spot|2|TYPE=Racial
+2 Racial bonus to Open Locks and Sleight of Hand SOURCEPAGE:p.31 KEY:Kender ~ Thievery Bonus CATEGORY:Special Ability TYPE:SpecialQuality.Kender Race Trait BONUS:SKILL|Open Lock|2|TYPE=Racial BONUS:SKILL|Sleight of Hand|2|TYPE=Racial
Lack of Focus SOURCEPAGE:p.31 KEY:Kender ~ Lack of Focus CATEGORY:Special Ability TYPE:SpecialQuality.Kender Race Trait BONUS:SKILL|Concentration|-4
Taunt SOURCEPAGE:p.31 KEY:Kender ~ Taunt CATEGORY:Special Ability TYPE:SpecialQuality.Kender Race Trait DESC:Taunted creature suffers a -1 penalty to attack rolls and AC until the kender's next action. ASPECT:SkillBonus|+4 to Bluff checks to Taunt someone.
Fearlessness SOURCEPAGE:p.31 KEY:Kender ~ Fearlessness CATEGORY:Special Ability TYPE:SpecialQuality.Kender Race Trait DESC:Kender are immune to fear, magical or otherwise.
###Block: Afflicted Kender
+2 Racial bonus on Climb, Hide, Jump and Move Silently SOURCEPAGE:p.31 KEY:Afflicted Kender ~ Skill Bonus CATEGORY:Special Ability TYPE:SpecialQuality.Kender Race Trait BONUS:SKILL|Climb,Hide,Jump,Move Silently|2|TYPE=Racial
###Block: Centaur
Race Traits ~ Centaur (Krynn) CATEGORY:Internal
Race Traits ~ Draconian (Baaz) CATEGORY:Internal
Race Traits ~ Draconian (Kapak) CATEGORY:Internal
Race Traits ~ Irda CATEGORY:Internal
Race Traits ~ Ogre (Krynn) CATEGORY:Internal
Race Traits ~ Half-Ogre (Krynn) CATEGORY:Internal
Race Traits ~ Minotaur (Krynn) CATEGORY:Internal
Race Traits ~ Draconian (Aurak) CATEGORY:Internal
Race Traits ~ Draconian (Bozak) CATEGORY:Internal
###Block:
Kenderspeak CATEGORY:Language AUTO:LANG|Kenderspeak
Language ~ Bonus (Dragonlance Hill Dwarf) CATEGORY:Internal TEMPLATE:Language ~ Bonus (Dragonlance Hill Dwarf)
Language ~ Bonus (Dragonlance Mountain Dwarf) CATEGORY:Internal TEMPLATE:Language ~ Bonus (Dragonlance Mountain Dwarf)
Language ~ Auto (Gully Dwarf) CATEGORY:Internal DESC:Gullytalk and Common AUTO:LANG|Gullytalk|Common
Language ~ Auto (Kagonesti Elf) CATEGORY:Internal DESC:Elven and Sylvan AUTO:LANG|Elven|Sylvan
Language ~ Bonus (Kagonesti Elf) CATEGORY:Internal DESC:Common, Ergot, Gnoll, Goblin, Ogre, and Solamnic TEMPLATE:Language ~ Bonus (Kagonesti Elf)
Language ~ Auto (Qualinesti Elf) CATEGORY:Internal DESC:Elven and Sylvan AUTO:LANG|Elven|Common
Language ~ Bonus (Qualinesti Elf) CATEGORY:Internal DESC:Abanasinian, Dwarven, Ergot, Goblin, Ogre, Sylvan TEMPLATE:Language ~ Bonus (Qualinesti Elf)
Language ~ Auto (Silvanesti Elf) CATEGORY:Internal DESC:Elven AUTO:LANG|Elven
Language ~ Bonus (Silvanesti Elf) CATEGORY:Internal DESC:Dwarven, Ergot, Kenderspeak, Kharolian, Khur, Goblin, Ogre, Sylvan TEMPLATE:Language ~ Bonus (Silvanesti Elf)
Language ~ Auto (Dargonesti Elf) CATEGORY:Internal AUTO:LANG|Elven|Dargonesti
Language ~ Bonus (Dargonesti Elf) CATEGORY:Internal DESC:Common,Elven,Ergot TEMPLATE:Language ~ Bonus (Dargonesti Elf)
Language ~ Auto (Dimeresti Elf) CATEGORY:Internal AUTO:LANG|Elven|Dimeresti
Language ~ Bonus (Dimeresti Elf) CATEGORY:Internal DESC:Aquan,Common,Ergot,Kothian TEMPLATE:Language ~ Bonus (Dimeresti Elf)
Language ~ Bonus (Dragonlance Gnome) CATEGORY:Internal DESC:Dwarven,Ergot,Ogre,Solamnic TEMPLATE:Language ~ Bonus (Dragonlance Gnome)
###Block: Base Classes
# Mystic
# Ability Name Unique Key Category of Ability Type Define Ability Modify VAR Aspects
Weapon and Armor Proficiency KEY:Mystic ~ Weapon and Armor Proficiency CATEGORY:Special Ability TYPE:SpecialQuality.Mystic Class Feature ABILITY:Internal|AUTOMATIC|TYPE=ArmorProfMedium|TYPE=ShieldProf|TYPE=WeaponProfSimple
Domain KEY:Mystic ~ Domain CATEGORY:Special Ability TYPE:SpecialQuality.Mystic Class Feature
# Noble
Weapon and Armor Proficiency KEY:Noble ~ Weapon and Armor Proficiency CATEGORY:Special Ability TYPE:SpecialQuality.Noble Class Feature ABILITY:Internal|AUTOMATIC|TYPE=ArmorProfLight|TYPE=ShieldProf|TYPE=WeaponProfMartial
Bonus Class Skill KEY:Noble ~ Bonus Class Skill CATEGORY:Special Ability TYPE:SpecialQuality.Noble Class Feature
Favor KEY:Noble ~ Favor CATEGORY:Special Ability TYPE:SpecialQuality.Noble Class Feature DEFINE:NobleFavorBonus|0 BONUS:VAR|NobleFavorBonus|1 BONUS:VAR|NobleFavorBonus|1|PREVARGTEQ:NobleLVL,3 BONUS:VAR|NobleFavorBonus|1|PREVARGTEQ:NobleLVL,7 BONUS:VAR|NobleFavorBonus|1|PREVARGTEQ:NobleLVL,12 BONUS:VAR|NobleFavorBonus|1|PREVARGTEQ:NobleLVL,16 ASPECT:NAME|Favor +%1|NobleFavorBonus
Inspire Confidence KEY:Noble ~ Inspire Confidence CATEGORY:Special Ability TYPE:SpecialQuality.Noble Class Feature DEFINE:NobleInspireConfidenceBonus|0 BONUS:VAR|NobleInspireConfidenceBonus|1|PREVARGTEQ:NobleLVL,5 BONUS:VAR|NobleInspireConfidenceBonus|1|PREVARGTEQ:NobleLVL,9 BONUS:VAR|NobleInspireConfidenceBonus|1|PREVARGTEQ:NobleLVL,13 BONUS:VAR|NobleInspireConfidenceBonus|1|PREVARGTEQ:NobleLVL,17 BONUS:VAR|NobleInspireConfidenceBonus|1 ASPECT:NAME|Inspire Confidence %1/day|NobleInspireConfidenceBonus
Coordinate KEY:Noble ~ Coordinate CATEGORY:Special Ability TYPE:SpecialQuality.Noble Class Feature DEFINE:NobleCoordinateBonus|0 BONUS:VAR|NobleCoordinateBonus|1 BONUS:VAR|NobleCoordinateBonus|1|PREVARGTEQ:NobleLVL,8 BONUS:VAR|NobleCoordinateBonus|1|PREVARGTEQ:NobleLVL,13 BONUS:VAR|NobleCoordinateBonus|1|PREVARGTEQ:NobleLVL,18 BONUS:VAR|NobleCoordinateBonus|1|PREVARGTEQ:NobleLVL,20 ASPECT:NAME|Coordinate +%1|NobleCoordinateBonus
Inspire Greatness KEY:Noble ~ Inspire Greatness CATEGORY:Special Ability TYPE:SpecialQuality.Noble Class Feature DEFINE:NobleInspireGreatness|0 BONUS:VAR|NobleInspireGreatness|1 BONUS:VAR|NobleInspireGreatness|1|PREVARGTEQ:NobleLVL,14 BONUS:VAR|NobleInspireGreatness|1|PREVARGTEQ:NobleLVL,17 BONUS:VAR|NobleInspireGreatness|1|PREVARGTEQ:NobleLVL,20 ASPECT:NAME|Inspire Greatness (%1 allies)|NobleInspireGreatness
# Ranger - Favored Enemy / Organization Alternative
###Block
# Ability Name Unique Key Category of Ability Type Visible Define Description Modify VAR Aspects
Knights of Neraka KEY:Favored Enemy ~ Knights of Neraka CATEGORY:Special Ability TYPE:Class Feature.Ranger Class Feature.FavoredEnemy.SteelLegionnaireFavoredEnemy.Extraordinary.SpecialAttack VISIBLE:YES DEFINE:FavoredEnemyBonusKnights_of_Neraka|0 DESC:Gain a +%1 bonus on Bluff, Listen, Sense Motive, Spot, and Survival checks when using these skills against creatures of this type. Likewise, he gets a +%1 bonus on weapon damage rolls against such creatures.|FavoredEnemyBonusKnights_of_Neraka BONUS:VAR|FavoredEnemyBonusKnights_of_Neraka|FavoredEnemyBase ASPECT:Ability Benefit|+%1|FavoredEnemyBonusKnights_of_Neraka
Order of the Black Robes KEY:Favored Enemy ~ Order of the Black Robes CATEGORY:Special Ability TYPE:Class Feature.Ranger Class Feature.FavoredEnemy.Extraordinary.SpecialAttack VISIBLE:YES DEFINE:FavoredEnemyBonusOrder_of_the_Black_Robes|0 DESC:Gain a +%1 bonus on Bluff, Listen, Sense Motive, Spot, and Survival checks when using these skills against creatures of this type. Likewise, he gets a +%1 bonus on weapon damage rolls against such creatures.|FavoredEnemyBonusOrder_of_the_Black_Robes BONUS:VAR|FavoredEnemyBonusOrder_of_the_Black_Robes|FavoredEnemyBase ASPECT:Ability Benefit|+%1|FavoredEnemyBonusOrder_of_the_Black_Robes
Order of the Red Robes KEY:Favored Enemy ~ Order of the Red Robes CATEGORY:Special Ability TYPE:Class Feature.Ranger Class Feature.FavoredEnemy.Extraordinary.SpecialAttack VISIBLE:YES DEFINE:FavoredEnemyBonusOrder_of_the_Red_Robes|0 DESC:Gain a +%1 bonus on Bluff, Listen, Sense Motive, Spot, and Survival checks when using these skills against creatures of this type. Likewise, he gets a +%1 bonus on weapon damage rolls against such creatures.|FavoredEnemyBonusOrder_of_the_Red_Robes BONUS:VAR|FavoredEnemyBonusOrder_of_the_Red_Robes|FavoredEnemyBase ASPECT:Ability Benefit|+%1|FavoredEnemyBonusOrder_of_the_Red_Robes
Order of the White Robes KEY:Favored Enemy ~ Order of the White Robes CATEGORY:Special Ability TYPE:Class Feature.Ranger Class Feature.FavoredEnemy.Extraordinary.SpecialAttack VISIBLE:YES DEFINE:FavoredEnemyBonusOrder_of_the_White_Robes|0 DESC:Gain a +%1 bonus on Bluff, Listen, Sense Motive, Spot, and Survival checks when using these skills against creatures of this type. Likewise, he gets a +%1 bonus on weapon damage rolls against such creatures.|FavoredEnemyBonusOrder_of_the_White_Robes BONUS:VAR|FavoredEnemyBonusOrder_of_the_White_Robes|FavoredEnemyBase ASPECT:Ability Benefit|+%1|FavoredEnemyBonusOrder_of_the_White_Robes
Knights of Solamnia KEY:Favored Enemy ~ Knights of Solamnia CATEGORY:Special Ability TYPE:Class Feature.Ranger Class Feature.FavoredEnemy.SteelLegionnaireFavoredEnemy.Extraordinary.SpecialAttack VISIBLE:YES DEFINE:FavoredEnemyBonusKnights_of_Solamnia|0 DESC:Gain a +%1 bonus on Bluff, Listen, Sense Motive, Spot, and Survival checks when using these skills against creatures of this type. Likewise, he gets a +%1 bonus on weapon damage rolls against such creatures.|FavoredEnemyBonusKnights_of_Solamnia BONUS:VAR|FavoredEnemyBonusKnights_of_Solamnia|FavoredEnemyBase ASPECT:Ability Benefit|+%1|FavoredEnemyBonusKnights_of_Solamnia
###Block: Organization Bonus
# Ability Name Unique Key Category of Ability Type Visible Required Ability Stackable? Multiple? Choose Modify VAR
Knights of Neraka KEY:Favored Enemy Bonus ~ Knights of Neraka CATEGORY:Special Ability TYPE:FavoredEnemyBonus.SteelLegionnaireFavoredEnemyBonus VISIBLE:DISPLAY PREABILITY:1,CATEGORY=Special Ability,Favored Enemy ~ Knights of Neraka STACK:YES MULT:YES CHOOSE:NOCHOICE BONUS:VAR|FavoredEnemyBonusKnights_of_Neraka|2
Order of the Black Robes KEY:Favored Enemy Bonus ~ Order of the Black Robes CATEGORY:Special Ability TYPE:FavoredEnemyBonus VISIBLE:DISPLAY PREABILITY:1,CATEGORY=Special Ability,Favored Enemy ~ Order of the Black Robes STACK:YES MULT:YES CHOOSE:NOCHOICE BONUS:VAR|FavoredEnemyBonusOrder_of_the_Black_Robes|2
Order of the Red Robes KEY:Favored Enemy Bonus ~ Order of the Red Robes CATEGORY:Special Ability TYPE:FavoredEnemyBonus VISIBLE:DISPLAY PREABILITY:1,CATEGORY=Special Ability,Favored Enemy ~ Order of the Red Robes STACK:YES MULT:YES CHOOSE:NOCHOICE BONUS:VAR|FavoredEnemyBonusOrder_of_the_Red_Robes|2
Order of the White Robes KEY:Favored Enemy Bonus ~ Order of the White Robes CATEGORY:Special Ability TYPE:FavoredEnemyBonus VISIBLE:DISPLAY PREABILITY:1,CATEGORY=Special Ability,Favored Enemy ~ Order of the White Robes STACK:YES MULT:YES CHOOSE:NOCHOICE BONUS:VAR|FavoredEnemyBonusOrder_of_the_White_Robes|2
Knights of Solamnia KEY:Favored Enemy Bonus ~ Knights of Solamnia CATEGORY:Special Ability TYPE:FavoredEnemyBonus.SteelLegionnaireFavoredEnemyBonus VISIBLE:DISPLAY PREABILITY:1,CATEGORY=Special Ability,Favored Enemy ~ Knights of Solamnia STACK:YES MULT:YES CHOOSE:NOCHOICE BONUS:VAR|FavoredEnemyBonusKnights_of_Solamnia|2
###Block: Prestige Classes
# Knight of the Crown
# Ability Name Unique Key Category of Ability Type Ability Bonus Ability Pool Source Page
Weapon and Armor Proficiency KEY:Knight of the Crown ~ Weapon and Armor Proficiency CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Crown Class Feature ABILITY:Internal|AUTOMATIC|TYPE=WeaponProfMartial
Strength of Honor KEY:Knight of the Crown ~ Strength of Honor CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Crown Class Feature.Supernatural
Knightly Courage KEY:Knight of the Crown ~ Knightly Courage CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Crown Class Feature.Supernatural
Heroic Initiative KEY:Knight of the Crown ~ Heroic Initiative CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Crown Class Feature.Extraordinary
Fight to the Death KEY:Knight of the Crown ~ Fight to the Death CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Crown Class Feature.Extraordinary
Honorable Will KEY:Knight of the Crown ~ Honorable Will CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Crown Class Feature.Supernatural
Might of Honor KEY:Knight of the Crown ~ Might of Honor CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Crown Class Feature.Supernatural
Armored Mobility KEY:Knight of the Crown ~ Armored Mobility CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Crown Class Feature.Extraordinary
Aura of Courage KEY:Knight of the Crown ~ Aura of Courage CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Crown Class Feature.Supernatural
Crown of Knighthoow KEY:Knight of the Crown ~ Crown of Knighthoow CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Crown Class Feature.Supernatural
# Knight of the Sword
Smite Evil KEY:Knight of the Sword ~ Smite Evil CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Sword Class Feature.Smite
Aura of Good KEY:Knight of the Sword ~ Aura of Good CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Sword Class Feature
Turn Undead KEY:Knight of the Sword ~ Turn Undead CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Sword Class Feature
Aura of Courage KEY:Knight of the Sword ~ Aura of Courage CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Sword Class Feature
Sould of Knighthood KEY:Knight of the Sword ~ Sould of Knighthood CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Sword Class Feature
# Knight of the Rose
Rallying Cry KEY:Knight of the Rose ~ Rallying Cry CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Rose Class Feature.Supernatural
Detect Evil KEY:Knight of the Rose ~ Detect Evil CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Rose Class Feature.SpellLike
Aura of Good KEY:Knight of the Rose ~ Aura of Good CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Rose Class Feature.Extraordinary
Inspire Courage KEY:Knight of the Rose ~ Inspire Courage CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Rose Class Feature.Supernatural
Leadership Bonus KEY:Knight of the Rose ~ Leadership Bonus CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Rose Class Feature
Divine Grace KEY:Knight of the Rose ~ Divine Grace CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Rose Class Feature.Supernatural
Inspire Greatness KEY:Knight of the Rose ~ Inspire Greatness CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Rose Class Feature.Supernatural
Turn Undead KEY:Knight of the Rose ~ Turn Undead CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Rose Class Feature.Supernatural
Wisdom of the Measure KEY:Knight of the Rose ~ Wisdom of the Measure CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Rose Class Feature.Extraordinary
Final Stand KEY:Knight of the Rose ~ Final Stand CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Rose Class Feature.Supernatural
Knighthood's Flower KEY:Knight of the Rose ~ Knighthood's Flower CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Rose Class Feature.Supernatural
# Knight of the Lily 64
Weapon and Armor Proficiency KEY:Knight of the Lily ~ Weapon and Armor Proficiency CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Lily Class Feature SOURCEPAGE:p.64
Sneak Attack KEY:Knight of the Lily ~ Sneak Attack CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Lily Class Feature SOURCEPAGE:p.64
Demoralize KEY:Knight of the Lily ~ Demoralize CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Lily Class Feature.Extraordinary SOURCEPAGE:p.64
Fight to the Death KEY:Knight of the Lily ~ Fight to the Death CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Lily Class Feature.Extraordinary SOURCEPAGE:p.64
Unbreakable Will KEY:Knight of the Lily ~ Unbreakable Will CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Lily Class Feature.Supernatural SOURCEPAGE:p.64
Armored Mobility KEY:Knight of the Lily ~ Armored Mobility CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Lily Class Feature.Extraordinary SOURCEPAGE:p.64
One Thought KEY:Knight of the Lily ~ One Thought CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Lily Class Feature.Supernatural SOURCEPAGE:p.65
# Knight of the Skull
Detect Good KEY:Knight of the Skull ~ Detect Good CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Skull Class Feature.SpellLike SOURCEPAGE:p.65
Smite Good KEY:Knight of the Skull ~ Smite Good CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Skull Class Feature.Supernatural.Smite SOURCEPAGE:p.65
Aura of Evil KEY:Knight of the Skull ~ Aura of Evil CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Skull Class Feature.Extraordinary SOURCEPAGE:p.65
Dark Blessing KEY:Knight of the Skull ~ Dark Blessing CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Skull Class Feature.Supernatural SOURCEPAGE:p.65
Discern Lies KEY:Knight of the Skull ~ Discern Lies CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Skull Class Feature.SpellLike SOURCEPAGE:p.66
Rebuke Undead KEY:Knight of the Skull ~ Rebuke Undead CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Skull Class Feature.Supernatural SOURCEPAGE:p.66
Favor of Darkness KEY:Knight of the Skull ~ Favor of Darkness CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Skull Class Feature.Supernatural SOURCEPAGE:p.66
# Knight of the Thorn
Diviner KEY:Knight of the Thorn ~ Diviner CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Thorn Class Feature.Extraordinary SOURCEPAGE:p.67
Read Omens KEY:Knight of the Thorn ~ Read Omens CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Thorn Class Feature SOURCEPAGE:p.67
Armored Spellcasting KEY:Knight of the Thorn ~ Armored Spellcasting CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Thorn Class Feature.Extraordinary SOURCEPAGE:p.67
Aura of Terror KEY:Knight of the Thorn ~ Aura of Terror CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Thorn Class Feature.Supernatural SOURCEPAGE:p.67
Weapon Touch KEY:Knight of the Thorn ~ Weapon Touch CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Thorn Class Feature.Supernatural SOURCEPAGE:p.67
Read Portents KEY:Knight of the Thorn ~ Read Portents CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Thorn Class Feature SOURCEPAGE:p.67
Cosmic Understanding KEY:Knight of the Thorn ~ Cosmic Understanding CATEGORY:Special Ability TYPE:SpecialQuality.Knight of the Thorn Class Feature.SpellLike SOURCEPAGE:p.67
# Steel Legionnaire
Legion Knowledge KEY:Steel Legionnaire ~ Legion Knowledge CATEGORY:Special Ability TYPE:SpecialQuality.Steel Legionnaire Class Feature.Extraordinary
Favored Enemy KEY:Steel Legionnaire ~ Favored Enemy CATEGORY:Special Ability TYPE:SpecialQuality.Steel Legionnaire Class Feature.Extraordinary BONUS:ABILITYPOOL|Steel Legionnaire Favored Enemy|Steel_LegionnaireLVL+1/2 BONUS:ABILITYPOOL|Steel Legionnaire Favored Enemy Bonus|Steel_LegionnaireLVL+1/2
Reputation KEY:Steel Legionnaire ~ Reputation CATEGORY:Special Ability TYPE:SpecialQuality.Steel Legionnaire Class Feature.Extraordinary
Apprentice KEY:Steel Legionnaire ~ Apprentice CATEGORY:Special Ability TYPE:SpecialQuality.Steel Legionnaire Class Feature
###Block: Steel Legionnaire Favored Enemy Selections
# Ability Name Unique Key Category of Ability Type Visible Define Description Modify VAR Aspects
Chromatic Dragons KEY:Favored Enemy ~ Chromatic Dragons CATEGORY:Special Ability TYPE:Class Feature.Ranger Class Feature.FavoredEnemy.SteelLegionnaireFavoredEnemy.Extraordinary.SpecialAttack VISIBLE:YES DEFINE:FavoredEnemyBonusChromatic_Dragons|0 DESC:Gain a +%1 bonus on Bluff, Listen, Sense Motive, Spot, and Survival checks when using these skills against creatures of this type. Likewise, he gets a +%1 bonus on weapon damage rolls against such creatures.|FavoredEnemyBonusChromatic_Dragons BONUS:VAR|FavoredEnemyBonusChromatic_Dragons|FavoredEnemyBase ASPECT:Ability Benefit|+%1|FavoredEnemyBonusChromatic_Dragons
Draconians KEY:Favored Enemy ~ Draconians CATEGORY:Special Ability TYPE:Class Feature.Ranger Class Feature.FavoredEnemy.SteelLegionnaireFavoredEnemy.Extraordinary.SpecialAttack VISIBLE:YES DEFINE:FavoredEnemyBonusDraconians|0 DESC:Gain a +%1 bonus on Bluff, Listen, Sense Motive, Spot, and Survival checks when using these skills against creatures of this type. Likewise, he gets a +%1 bonus on weapon damage rolls against such creatures.|FavoredEnemyBonusDraconians BONUS:VAR|FavoredEnemyBonusDraconians|FavoredEnemyBase ASPECT:Ability Benefit|+%1|FavoredEnemyBonusDraconians
Dragon-Spawn KEY:Favored Enemy ~ Dragon-Spawn CATEGORY:Special Ability TYPE:Class Feature.Ranger Class Feature.FavoredEnemy.SteelLegionnaireFavoredEnemy.Extraordinary.SpecialAttack VISIBLE:YES DEFINE:FavoredEnemyBonusDragon_Spawn|0 DESC:Gain a +%1 bonus on Bluff, Listen, Sense Motive, Spot, and Survival checks when using these skills against creatures of this type. Likewise, he gets a +%1 bonus on weapon damage rolls against such creatures.|FavoredEnemyBonusDragon_Spawn BONUS:VAR|FavoredEnemyBonusDragon_Spawn|FavoredEnemyBase ASPECT:Ability Benefit|+%1|FavoredEnemyBonusDragon_Spawn
Goblins KEY:Favored Enemy ~ Goblins CATEGORY:Special Ability TYPE:Class Feature.Ranger Class Feature.FavoredEnemy.SteelLegionnaireFavoredEnemy.Extraordinary.SpecialAttack VISIBLE:YES DEFINE:FavoredEnemyBonusGoblins|0 DESC:Gain a +%1 bonus on Bluff, Listen, Sense Motive, Spot, and Survival checks when using these skills against creatures of this type. Likewise, he gets a +%1 bonus on weapon damage rolls against such creatures.|FavoredEnemyBonusGoblins BONUS:VAR|FavoredEnemyBonusGoblins|FavoredEnemyBase ASPECT:Ability Benefit|+%1|FavoredEnemyBonusGoblins
Minotaurs KEY:Favored Enemy ~ Minotaurs CATEGORY:Special Ability TYPE:Class Feature.Ranger Class Feature.FavoredEnemy.SteelLegionnaireFavoredEnemy.Extraordinary.SpecialAttack VISIBLE:YES DEFINE:FavoredEnemyBonusMinotaurs|0 DESC:Gain a +%1 bonus on Bluff, Listen, Sense Motive, Spot, and Survival checks when using these skills against creatures of this type. Likewise, he gets a +%1 bonus on weapon damage rolls against such creatures.|FavoredEnemyBonusMinotaurs BONUS:VAR|FavoredEnemyBonusMinotaurs|FavoredEnemyBase ASPECT:Ability Benefit|+%1|FavoredEnemyBonusMinotaurs
###Block: Favored Enemy Bonus
# Ability Name Unique Key Category of Ability Type Visible Required Ability Multiple Requirements Description Stackable? Multiple? Choose Bonus Ability Pool Modify VAR
Chromatic Dragons KEY:Favored Enemy Bonus ~ Chromatic Dragons CATEGORY:Special Ability TYPE:FavoredEnemyBonus.SteelLegionnaireFavoredEnemyBonus VISIBLE:DISPLAY PREABILITY:1,CATEGORY=Special Ability,Favored Enemy ~ Chromatic Dragons STACK:YES MULT:YES CHOOSE:NOCHOICE BONUS:VAR|FavoredEnemyBonusChromatic_Dragons|2
Draconians KEY:Favored Enemy Bonus ~ Draconians CATEGORY:Special Ability TYPE:FavoredEnemyBonus.SteelLegionnaireFavoredEnemyBonus VISIBLE:DISPLAY PREABILITY:1,CATEGORY=Special Ability,Favored Enemy ~ Draconians STACK:YES MULT:YES CHOOSE:NOCHOICE BONUS:VAR|FavoredEnemyBonusDraconians|2
Dragon-Spawn KEY:Favored Enemy Bonus ~ Dragon-Spawn CATEGORY:Special Ability TYPE:FavoredEnemyBonus.SteelLegionnaireFavoredEnemyBonus VISIBLE:DISPLAY PREABILITY:1,CATEGORY=Special Ability,Favored Enemy ~ Dragon-Spawn STACK:YES MULT:YES CHOOSE:NOCHOICE BONUS:VAR|FavoredEnemyBonusDragon_Spawn|2
Goblins KEY:Favored Enemy Bonus ~ Goblins CATEGORY:Special Ability TYPE:FavoredEnemyBonus.SteelLegionnaireFavoredEnemyBonus VISIBLE:DISPLAY PREABILITY:1,CATEGORY=Special Ability,Favored Enemy ~ Goblins STACK:YES MULT:YES CHOOSE:NOCHOICE BONUS:VAR|FavoredEnemyBonusGoblins|2
Minotaurs KEY:Favored Enemy Bonus ~ Minotaurs CATEGORY:Special Ability TYPE:FavoredEnemyBonus.SteelLegionnaireFavoredEnemyBonus VISIBLE:DISPLAY PREABILITY:1,CATEGORY=Special Ability,Favored Enemy ~ Minotaurs STACK:YES MULT:YES CHOOSE:NOCHOICE BONUS:VAR|FavoredEnemyBonusMinotaurs|2
# Ability Name Unique Key Category of Ability Type Visible Required Ability Multiple Requirements Description Stackable? Multiple? Choose Bonus Ability Pool Modify VAR
Black Order KEY:Wizard of High Sorcery ~ Black Order CATEGORY:Special Ability TYPE:WizardOfHighSorceryOrder PREMULT:2,[PREALIGN:LE,NE,CE],[PREABILITY:1,CATEGORY=Special Ability,Enchanter Learning Bonus,Necromancer Learning Bonus] BONUS:ABILITYPOOL|Wizard of Black Robes Prohibit School|1
Red Order KEY:Wizard of High Sorcery ~ Red Order CATEGORY:Special Ability TYPE:WizardOfHighSorceryOrder PREMULT:2,[PREALIGN:LN,TN,CN],[PREABILITY:1,CATEGORY=Special Ability,Illusionist Learning Bonus,Transmuter Learning Bonus] BONUS:ABILITYPOOL|Wizard of Red Robes Prohibit School|1
White Order KEY:Wizard of High Sorcery ~ White Order CATEGORY:Special Ability TYPE:WizardOfHighSorceryOrder PREMULT:2,[PREALIGN:LG,NG,CG],[PREABILITY:1,CATEGORY=Special Ability,Abjurer Learning Bonus,Diviner Learning Bonus] BONUS:ABILITYPOOL|Wizard of White Robes Prohibit School|1
#Black
Magic of Betrayal KEY:Order Secret ~ Magic of Betrayal CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.BlackOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ Black Order DESC:Once per day for every two class levels attained, a Black Robe wizard who knows this secret may Empower or Extend any necromancy spell she casts. The spell functions as though she had applied the appropriate metamagic feat, but does not use a higher-level spell slot. When she does so, a backlash of negative energy deals 2d6 points of damage to a single living ally within 30 feet, chosen by the wizard (who may not choose an undead ally, who would benefit from the negative energy). The ally is allowed a Will save (DC 10 + one-half caster level + Intelligence modifier) for half damage.
Magic of Darkness KEY:Order Secret ~ Magic of Darkness CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.BlackOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ Black Order DESC:Once per day for every two class levels attained, a Black Robe wizard who knows this secret can imbue a damaging spell with negative energy. Half of the damage dealt by such a spell is negative energy damage, and is therefore not subject to being reduced by protection from energy or similar magic (although death ward negates it). The remainder of the damage is dealt as normal for the spell. Undead are healed by negative energy, so damage dealt to undead creatures simply averages out to nothing for a spell modified in this way. (Assume that the healing takes place first, granting the undead creature temporary hit points above its maximum if necessary, with equivalent damage then dealt to leave the creature back where it started.)
Magic of Fear KEY:Order Secret ~ Magic of Fear CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.BlackOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ Black Order DESC:A Black Robe wizard who knows this secret can make her spells more intimidating. As a full-round action, the wizard can cast any spell that deals damage and has a normal casting time of 1 standard action. Then, as a free action, she can immediately attempt to demoralize one opponent within 30 feet by making an Intimidate check against the opponent's modified character level (see the Intimidate skill, page 76 of the Player's Handbook). The wizard receives a circumstance bonus on the Intimidate check equal to the level of the spell she casts.
Magic of Hunger KEY:Order Secret ~ Magic of Hunger CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.BlackOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ Black Order DESC:A Black Robe wizard who knows this secret may draw even further upon her own resources to increase the scope of her magic. Each day, she may prepare one extra spell of any level she can cast at the cost of 1 point of Constitution damage per spell level. This ability damage heals normally but cannot be magically restored.
Magic of Pain KEY:Order Secret ~ Magic of Pain CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.BlackOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ Black Order DESC:Once per day for every two class levels attained, the Black Robe wizard who knows this secret may cast any spell that deals hit point damage to inflict pain beyond the spell's normal effects. Any creature damaged by such a spell must make a successful Fortitude save (DC 10 + spell level + Constitution modifier) or suffer a ?2 penalty on attack rolls, skill checks, and ability checks for one round due to the lingering pain the spell inflicts. As a price for this wracking pain, the Black Robe herself takes 1d6 points of damage when the spell is cast.
#Red
Magic of Change KEY:Order Secret ~ Magic of Change CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.RedOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ Red Order DESC:Once per day for every two class levels attained, a wizard who knows this secret may Enlarge or Extend any transmutation spell he casts. The spell functions as though he had applied the appropriate metamagic feat, but does not use a higher-level spell slot.
Magic of Deception KEY:Order Secret ~ Magic of Deception CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.RedOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ Red Order DESC:Once per day for every two class levels attained, a wizard who knows this secret may Enlarge or Extend any Illusion spell he casts. The spell functions as though he had applied the appropriate metamagic feat, but does not use a higher-level spell slot.
Magic of Independence KEY:Order Secret ~ Magic of Independence CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.RedOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ Red Order DESC:A Red Robe wizard who knows this secret casts spells that are harder to dispel. When another spellcaster makes a dispel check against one of the wizard's spells (including using dispel magic to counterspell a spell the wizard is casting), the DC is 15 + the wizard's caster level.
Magic of Mystery KEY:Order Secret ~ Magic of Mystery CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.RedOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ Red Order DESC:A Red Robe wizard who knows this secret casts spells that are harder to detect and identify. When another spellcaster attempts to use a divination spell (such as detect magic), or a spell-like ability or magic item that might detect the magical aura of one of the wizard's spells, the other caster must make a level check (DC 11 + the wizard's caster level) to successfully detect the spell. Similarly, a spellcaster attempting to use a divination (such as see invisibility) to reveal the effects of one of the wizard's spells must make a level check to reveal the spell's effects. Any given caster can check only once for each divination spell or effect used, no matter how many of the wizard's spell effects may be operating in an area. In addition, when another spellcaster attempts to identify the spell a Red Robe wizard is casting (for instance, to counterspell it), the DC of the required Spellcraft check is increased by +1 for every 2 class levels the Red Robe wizard has attained.
Magic of Purity KEY:Order Secret ~ Magic of Purity CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.RedOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ Red Order DESC:Once per day for every two class levels attained, a Red Robe wizard who knows this secret can imbue any spell that deals hit point damage with pure arcane energy. Half of the damage dealt by such a spell comes from this arcane energy, and is therefore not subject to being reduced by protection from energy or similar magic. The remainder of the damage is dealt as normal for the spell.
#White
Magic of Defense KEY:Order Secret ~ Magic of Defense CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.WhiteOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ White Order DESC:Once per day for every two class levels attained, a wizard who knows this secret may Empower or Extend any Abjuration spell she casts. The spell functions as though she had applied the appropriate metamagic feat, but does not use a higher-level spell slot.
Magic of Radiance KEY:Order Secret ~ Magic of Radiance CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.WhiteOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ White Order DESC:Once per day for every two class levels attained, a White Robe wizard who knows this secret can imbue any spell that deals hit point damage with radiant energy. Half of the damage dealt by such a spell comes from this radiant energy, and is therefore not subject to being reduced by protection from energy or similar magic. The remainder of the damage dealt is as normal for the spell. Against undead, a spell modified in this way deals half again as much damage as normal (double the radiant energy damage). As a side effect, radiant spells give off as much illumination as a light spell of equivalent caster level, and this light lingers in the area for one round after the end of the spell's duration (or one round for an instantaneous spell).
Magic of Resistance KEY:Order Secret ~ Magic of Resistance CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.WhiteOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ White Order DESC:This secret allows a White Robe wizard to more easily counter or dispel the magic cast by others. The wizard gains the benefit of the Improved Counterspell feat (if she does not already possess it) and gains a competence bonus on dispel checks equal to +1 per two class levels.
Magic of Sustenance KEY:Order Secret ~ Magic of Sustenance CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.WhiteOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ White Order DESC:This secret allows a White Robe wizard to cast spells even under difficult circumstances. The wizard gains a competence bonus equal to +1 per two class levels on all Concentration checks made to cast or direct spells (but does not gain a Concentration check bonus while casting defensively).
Magic of Truth KEY:Order Secret ~ Magic of Truth CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Order Secret.WhiteOrder PREABILITY:1,CATEGORY=Special Ability,Wizard of High Sorcery ~ White Order DESC:Once per day for every two class levels attained, a wizard who knows this secret may Enlarge or Extend any Divination spell she casts. The spell functions as though she had applied the appropriate metamagic feat, but does not use a higher-level spell slot.
###Block:
# Ability Name Unique Key Category of Ability Type Define Description Ability Bonus DC Modify VAR Allow Follower Allowed Companions Source Page Aspects
Enhanced Specialization KEY:Wizard of High Sorcery ~ Enhanced Specialization CATEGORY:Special Ability TYPE:Wizard of High Sorcery Class Feature ABILITY:Special Ability|AUTOMATIC|Enhanced Specialization ~ Abjuration|PREABILITY:1,CATEGORY=Special Ability,Abjurer ABILITY:Special Ability|AUTOMATIC|Enhanced Specialization ~ Divination|PREABILITY:1,CATEGORY=Special Ability,Diviner ABILITY:Special Ability|AUTOMATIC|Enhanced Specialization ~ Enchantment|PREABILITY:1,CATEGORY=Special Ability,Enchanter ABILITY:Special Ability|AUTOMATIC|Enhanced Specialization ~ Illusion|PREABILITY:1,CATEGORY=Special Ability,Illusionist ABILITY:Special Ability|AUTOMATIC|Enhanced Specialization ~ Necromancy|PREABILITY:1,CATEGORY=Special Ability,Necromancer ABILITY:Special Ability|AUTOMATIC|Enhanced Specialization ~ Transmutation|PREABILITY:1,CATEGORY=Special Ability,Transmuter
# Specialization Selection
Enhanced Specialization KEY:Enhanced Specialization ~ Abjuration CATEGORY:Special Ability BONUS:DC|SCHOOL.Abjuration|1 ASPECT:SaveBonus|+1 bonus on saving throws against spells from Abjuration and spell-like abilities.
Enhanced Specialization KEY:Enhanced Specialization ~ Divination CATEGORY:Special Ability BONUS:DC|SCHOOL.Divination|1 ASPECT:SaveBonus|+1 bonus on saving throws against spells from Divination and spell-like abilities.
Enhanced Specialization KEY:Enhanced Specialization ~ Enchantment CATEGORY:Special Ability BONUS:DC|SCHOOL.Enchantment|1 ASPECT:SaveBonus|+1 bonus on saving throws against spells from Enchantment and spell-like abilities.
Enhanced Specialization KEY:Enhanced Specialization ~ Illusion CATEGORY:Special Ability BONUS:DC|SCHOOL.Illusion|1 ASPECT:SaveBonus|+1 bonus on saving throws against spells from Illusion and spell-like abilities.
Enhanced Specialization KEY:Enhanced Specialization ~ Necromancy CATEGORY:Special Ability BONUS:DC|SCHOOL.Necromancy|1 ASPECT:SaveBonus|+1 bonus on saving throws against spells from Necromancy and spell-like abilities.
Enhanced Specialization KEY:Enhanced Specialization ~ Transmutation CATEGORY:Special Ability BONUS:DC|SCHOOL.Transmutation|1 ASPECT:SaveBonus|+1 bonus on saving throws against spells from Transmutation and spell-like abilities.
#
Item of Power KEY:Wizard of High Sorcery ~ Item of Power CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Class Feature
Moon Magic KEY:Wizard of High Sorcery ~ Moon Magic CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Class Feature
Tower Resources KEY:Wizard of High Sorcery ~ Tower Resources CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Class Feature
Arcane Research KEY:Wizard of High Sorcery ~ Arcane Research CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Class Feature
Order Secret KEY:Wizard of High Sorcery ~ Order Secret CATEGORY:Special Ability TYPE:SpecialQuality.Wizard of High Sorcery Class Feature
#
# Dragon Rider
# Ability Name Unique Key Category of Ability Type Define Description Ability Bonus DC Modify VAR Allow Follower Allowed Companions Source Page Aspects
Weapon and Armor Proficiency KEY:Dragon Rider ~ Weapon and Armor Proficiency CATEGORY:Special Ability TYPE:Class Feature.Dragon Rider Class Feature.SpecialQuality DESC:Dragon riders gain no new weapon or armor proficiencies. SOURCEPAGE:p.
Dragon Cohort KEY:Dragon Rider ~ Dragon Cohort CATEGORY:Special Ability TYPE:Class Feature.Dragon Rider Class Feature.SpecialQuality DEFINE:DragonRiderCohortLVL|0 DESC:At first level the dragon rider may designate a dragon that he has previously ridden as his dragon cohort, though this is limited by the dragon rider's Leadership score and the dragon's equivalent level. A dragon rider counts a dragon's Effective Character Level as being 3 lower than its actual value. ABILITY:Special Ability|AUTOMATIC|Dragon Rider Dragon Cohort BONUS:VAR|DragonRiderCohortLVL|DragonRiderLVL SOURCEPAGE:p.
Mounted Attack KEY:Dragon Rider ~ Mounted Attack CATEGORY:Special Ability TYPE:Class Feature.Dragon Rider Class Feature.SpecialQuality DESC:A dragon rider can always attack on the same round as his dragon cohort, and is not required to make a Ride check to do so. SOURCEPAGE:p.
Dragon Feat KEY:Dragon Rider ~ Dragon Feat CATEGORY:Special Ability TYPE:Class Feature.Dragon Rider Class Feature.SpecialQuality DESC:At 2nd level, a dragon rider can grant tbe dragon cohort the full benefits of a bonus feat chosen from the following list: Cleave, Flyby Attack, Hover, Improved Initiative, Improved Sunder, Power Attack, Quicken Spell-Like Ability, Snatch, Strafing Breath, Weapon Focus, or Wingover. The bonus feat does not count against the dragon's normal feat capacity. though it must still meet all prerequisites. as noted in the appropriatce feat descriptions. A dragon rider must spend one week training with the dragon in order for it to receive the bonus feat. The dragon rider may bestow a second bonus feat at 5th level, and a third at 9th level. The additional feats require the same trainning time as the first. SOURCEPAGE:p.
Empathic Communication KEY:Dragon Rider ~ Empathic Communication CATEGORY:Special Ability TYPE:Extraordinary.Class Feature.Dragon Rider Class Feature.SpecialQuality DESC:Starting at 3rd level, a dragon rider is able to use nonverbal communication with his preferred mount. A dragon rider can convey information and instructions to the mount as long as they are within sight of one another. SOURCEPAGE:p.
Inspire Fear KEY:Dragon Rider ~ Inspire Fear CATEGORY:Special Ability TYPE:Class Feature.Dragon Rider Class Feature.SpecialQuality DESC:Starting at 6th level, a Dragon rider adds his dragon rider levels to his Dragon cohort's Hit Dice when determining the DC of the Dragon's frightful presence. The range of the dragon's frightful presence is calculated as if the dragon were one age Category higher. SOURCEPAGE:p.
Directed Attacks KEY:Dragon Rider ~ Directed Attacks CATEGORY:Special Ability TYPE:Class Feature.Dragon Rider Class Feature.SpecialQuality DESC:Beginning at 7th level, a dragon rider may give encouragement and direct his dragon cohort's attacks. Directing the Dragon is a full-round action that does not provoke an attack of opportunity. When directed, the Dragon gains a +4 circumstance bonus on its attack rolls . SOURCEPAGE:p.
Defensive Tactics KEY:Dragon Rider ~ Defensive Tactics CATEGORY:Special Ability TYPE:Class Feature.Dragon Rider Class Feature.SpecialQuality DESC:At 8th level. neither a dragon rider nor his dragon cohort cam be flanked while the dragon rider is in the saddle. The dragon und rider have learned to look in each other's "blind spots" to prevent enemies from sneaking up on them. SOURCEPAGE:p.
Defensive Teamwork KEY:Dragon Rider ~ Defensive Teamwork CATEGORY:Special Ability TYPE:Class Feature.Dragon Rider Class Feature.SpecialQuality DESC:At 10th level, a dragon rider and his dragon cohort work so well together that they continually act to protect each other from harm. Both the dragon rider and the dragon receive a +2 circumstance bonus to Armor Class and a + 1 circumstance bonus on Reflex saving throws. SOURCEPAGE:p.
Dragon Rider Dragon Cohort CATEGORY:Special Ability TYPE:Internal FOLLOWERS:Dragon Rider Dragon|1 COMPANIONLIST:Dragon Rider Dragon|RACETYPE=Dragon
# Inquisitor 80
Extreme Focus KEY:Inquisitor ~ Extreme Focus CATEGORY:Special Ability TYPE:SpecialQuality.Inquisitor Class Feature.Extraordinary SOURCEPAGE:p.80
Trap Sense KEY:Inquisitor ~ Trap Sense CATEGORY:Special Ability TYPE:SpecialQuality.Inquisitor Class Feature.Extraordinary.Trap Sense SOURCEPAGE:p.80
Erudite Synergy KEY:Inquisitor ~ Erudite Synergy CATEGORY:Special Ability TYPE:SpecialQuality.Inquisitor Class Feature.Extraordinary SOURCEPAGE:p.80
Uncanny Dodge KEY:Inquisitor ~ Uncanny Dodge CATEGORY:Special Ability TYPE:SpecialQuality.Inquisitor Class Feature.Extraordinary.Uncanny Dodge SOURCEPAGE:p.81
Improved Uncanny Dodge KEY:Inquisitor ~ Improved Uncanny Dodge CATEGORY:Special Ability TYPE:SpecialQuality.Inquisitor Class Feature.Extraordinary.Uncanny Dodge SOURCEPAGE:p.81
Intuitive Logic KEY:Inquisitor ~ Intuitive Logic CATEGORY:Special Ability TYPE:SpecialQuality.Inquisitor Class Feature.Extraordinary SOURCEPAGE:p.81
# Legendary Tactician
Leadership Bonus KEY:Legendary Tactician ~ Leadership Bonus CATEGORY:Special Ability TYPE:SpecialQuality.Legendary Tactician Class Feature.Extraordinary SOURCEPAGE:p.82
Inspire Courage KEY:Legendary Tactician ~ Inspire Courage CATEGORY:Special Ability TYPE:SpecialQuality.Legendary Tactician Class Feature.Supernatural SOURCEPAGE:p.82
Direct Troops KEY:Legendary Tactician ~ Direct Troops CATEGORY:Special Ability TYPE:SpecialQuality.Legendary Tactician Class Feature.Supernatural SOURCEPAGE:p.82
Rally Troops KEY:Legendary Tactician ~ Rally Troops CATEGORY:Special Ability TYPE:SpecialQuality.Legendary Tactician Class Feature.Supernatural SOURCEPAGE:p.82
Hard March KEY:Legendary Tactician ~ Hard March CATEGORY:Special Ability TYPE:SpecialQuality.Legendary Tactician Class Feature.Supernatural SOURCEPAGE:p.83
Rout Enemies KEY:Legendary Tactician ~ Rout Enemies CATEGORY:Special Ability TYPE:SpecialQuality.Legendary Tactician Class Feature.Supernatural SOURCEPAGE:p.83
Battle Standard KEY:Legendary Tactician ~ Battle Standard CATEGORY:Special Ability TYPE:SpecialQuality.Legendary Tactician Class Feature.Supernatural SOURCEPAGE:p.83
Strategic Retreat KEY:Legendary Tactician ~ Strategic Retreat CATEGORY:Special Ability TYPE:SpecialQuality.Legendary Tactician Class Feature.Supernatural SOURCEPAGE:p.83
The Forlorn Hope KEY:Legendary Tactician ~ The Forlorn Hope CATEGORY:Special Ability TYPE:SpecialQuality.Legendary Tactician Class Feature.Supernatural SOURCEPAGE:p.83
# Righteous Zealot KEY:Righteous Zealot ~ CATEGORY:Special Ability TYPE:SpecialQuality.Righteous Zealot Class Feature SOURCEPAGE:p.
Oration KEY:Righteous Zealot ~ Oration CATEGORY:Special Ability TYPE:SpecialQuality.Righteous Zealot Class Feature DEFINE:OrationLVL|0 ABILITY:Special Ability|AUTOMATIC|Oration ~ Enthralling Discourse|PRESKILL:1,TYPE.Diplomacy=8 ABILITY:Special Ability|AUTOMATIC|Oration ~ Compelling Argument|PRESKILL:1,Diplomacy=9|PREVARGTEQ:OrationLVL,5 ABILITY:Special Ability|AUTOMATIC|Oration ~ Condemning Tirade|PRESKILL:1,Diplomacy=13|PREVARGTEQ:OrationLVL,5 ABILITY:Special Ability|AUTOMATIC|Oration ~ Verbal Obfuscation|PRESKILL:1,Diplomacy=16|PREVARGTEQ:OrationLVL,8 ABILITY:Special Ability|AUTOMATIC|Oration ~ Inflamatory Oratory|PRESKILL:1,Diplomacy=18|PREVARGTEQ:OrationLVL,10 BONUS:VAR|OrationLVL|Righteous_ZealotLVL SOURCEPAGE:p.84
Righteous Indignation KEY:Righteous Zealot ~ Righteous Indignation CATEGORY:Special Ability TYPE:SpecialQuality.Righteous Zealot Class Feature SOURCEPAGE:p.85
Resist Enchantment KEY:Righteous Zealot ~ Resist Enchantment CATEGORY:Special Ability TYPE:SpecialQuality.Righteous Zealot Class Feature SOURCEPAGE:p.85
Gather Followers KEY:Righteous Zealot ~ Gather Followers CATEGORY:Special Ability TYPE:SpecialQuality.Righteous Zealot Class Feature SOURCEPAGE:p.85
Martyr's Luck KEY:Righteous Zealot ~ Martyr's Luck CATEGORY:Special Ability TYPE:SpecialQuality.Righteous Zealot Class Feature SOURCEPAGE:p.85
#
Enthralling Discourse KEY:Oration ~ Enthralling Discourse CATEGORY:Special Ability TYPE:SpecialQuality.Righteous Zealot Class Feature SOURCEPAGE:p.84
Compelling Argument KEY:Oration ~ Compelling Argument CATEGORY:Special Ability TYPE:SpecialQuality.Righteous Zealot Class Feature SOURCEPAGE:p.84
Condemning Tirade KEY:Oration ~ Condemning Tirade CATEGORY:Special Ability TYPE:SpecialQuality.Righteous Zealot Class Feature SOURCEPAGE:p.84
Verbal Obfuscation KEY:Oration ~ Verbal Obfuscation CATEGORY:Special Ability TYPE:SpecialQuality.Righteous Zealot Class Feature SOURCEPAGE:p.84
Inflamatory Oratory KEY:Oration ~ Inflamatory Oratory CATEGORY:Special Ability TYPE:SpecialQuality.Righteous Zealot Class Feature SOURCEPAGE:p.85
#
###Besitary
Draconian Traits CATEGORY:Special Ability ABILITY:Special Ability|AUTOMATIC|Draconian ~ Disease Immunity ABILITY:Special Ability|AUTOMATIC|Draconian ~ Glide|!PRERACE:1,Draconian (Aurak) ABILITY:Special Ability|AUTOMATIC|Draconian ~ Inspired by Dragons ABILITY:Special Ability|AUTOMATIC|Draconian ~ Low Metabolism
Draconian ~ Disease Immunity CATEGORY:Special Ability TYPE:SpecialQuality
Draconian ~ Glide CATEGORY:Special Ability TYPE:SpecialQuality
Draconian ~ Inspired by Dragons CATEGORY:Special Ability TYPE:SpecialQuality
Draconian ~ Low Metabolism CATEGORY:Special Ability TYPE:SpecialQuality
###Block - Academic Priest
# ClassName KEY:Academic Priest ~ ClassName CATEGORY:Special Ability TYPE:Academic Priest BONUS:STAT|BASESPELLSTAT;Class=ClassName|AcademicPriest_ClassName DEFINE:AcademicPriest_ClassName|0 BONUS:VAR|AcademicPriest_ClassName|INTSCORE-WISSCORE BONUS:DC|CLASS.ClassName|-(AcademicPriest_ClassName/2)
Cleric KEY:Academic Priest ~ Cleric CATEGORY:Special Ability TYPE:Academic Priest BONUS:STAT|BASESPELLSTAT;Class=Cleric|AcademicPriest_Cleric DEFINE:AcademicPriest_Cleric|0 BONUS:VAR|AcademicPriest_Cleric|INTSCORE-WISSCORE BONUS:DC|CLASS.Cleric|-(AcademicPriest_Cleric/2)
Mystic KEY:Academic Priest ~ Mystic CATEGORY:Special Ability TYPE:Academic Priest BONUS:STAT|BASESPELLSTAT;Class=Mystic|AcademicPriest_Mystic DEFINE:AcademicPriest_Mystic|0 BONUS:VAR|AcademicPriest_Mystic|INTSCORE-WISSCORE BONUS:DC|CLASS.Mystic|-(AcademicPriest_Mystic/2)
| 1 | 0.591295 | 1 | 0.591295 | game-dev | MEDIA | 0.571586 | game-dev,ml-ai | 0.514532 | 1 | 0.514532 |
nasa/fpp | 4,644 | compiler/tools/fpp-to-cpp/test/struct/StringArraySerializableAc.ref.hpp | // ======================================================================
// \title StringArraySerializableAc.hpp
// \author Generated by fpp-to-cpp
// \brief hpp file for StringArray struct
// ======================================================================
#ifndef StringArraySerializableAc_HPP
#define StringArraySerializableAc_HPP
#include "Fw/FPrimeBasicTypes.hpp"
#include "Fw/Types/ExternalString.hpp"
#include "Fw/Types/Serializable.hpp"
#include "Fw/Types/String.hpp"
class StringArray :
public Fw::Serializable
{
public:
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
//! The type of s2
using Type_of_s2 = Fw::ExternalString[16];
public:
// ----------------------------------------------------------------------
// Constants
// ----------------------------------------------------------------------
enum {
//! The size of the serial representation
SERIALIZED_SIZE =
Fw::StringBase::STATIC_SERIALIZED_SIZE(80) +
Fw::StringBase::STATIC_SERIALIZED_SIZE(40) * 16
};
public:
// ----------------------------------------------------------------------
// Constructors
// ----------------------------------------------------------------------
//! Constructor (default value)
StringArray();
//! Member constructor
StringArray(
const Fw::StringBase& s1,
const Type_of_s2& s2
);
//! Copy constructor
StringArray(
const StringArray& obj //!< The source object
);
//! Member constructor (scalar values for arrays)
StringArray(
const Fw::StringBase& s1,
const Fw::StringBase& s2
);
public:
// ----------------------------------------------------------------------
// Operators
// ----------------------------------------------------------------------
//! Copy assignment operator
StringArray& operator=(
const StringArray& obj //!< The source object
);
//! Equality operator
bool operator==(
const StringArray& obj //!< The other object
) const;
//! Inequality operator
bool operator!=(
const StringArray& obj //!< The other object
) const;
#ifdef BUILD_UT
//! Ostream operator
friend std::ostream& operator<<(
std::ostream& os, //!< The ostream
const StringArray& obj //!< The object
);
#endif
public:
// ----------------------------------------------------------------------
// Member functions
// ----------------------------------------------------------------------
//! Serialization
Fw::SerializeStatus serializeTo(
Fw::SerializeBufferBase& buffer //!< The serial buffer
) const;
//! Deserialization
Fw::SerializeStatus deserializeFrom(
Fw::SerializeBufferBase& buffer //!< The serial buffer
);
//! Get the dynamic serialized size of the struct
FwSizeType serializedSize() const;
#if FW_SERIALIZABLE_TO_STRING
//! Convert struct to string
void toString(
Fw::StringBase& sb //!< The StringBase object to hold the result
) const;
#endif
// ----------------------------------------------------------------------
// Getter functions
// ----------------------------------------------------------------------
//! Get member s1
Fw::ExternalString& get_s1()
{
return this->m_s1;
}
//! Get member s1 (const)
const Fw::ExternalString& get_s1() const
{
return this->m_s1;
}
//! Get member s2
Type_of_s2& get_s2()
{
return this->m_s2;
}
//! Get member s2 (const)
const Type_of_s2& get_s2() const
{
return this->m_s2;
}
// ----------------------------------------------------------------------
// Setter functions
// ----------------------------------------------------------------------
//! Set all members
void set(
const Fw::StringBase& s1,
const Type_of_s2& s2
);
//! Set member s1
void set_s1(const Fw::StringBase& s1);
//! Set member s2
void set_s2(const Type_of_s2& s2);
protected:
// ----------------------------------------------------------------------
// Member variables
// ----------------------------------------------------------------------
char m___fprime_ac_s1_buffer[Fw::StringBase::BUFFER_SIZE(80)];
Fw::ExternalString m_s1;
char m___fprime_ac_s2_buffer[16][Fw::StringBase::BUFFER_SIZE(40)];
Fw::ExternalString m_s2[16];
};
#endif
| 1 | 0.922816 | 1 | 0.922816 | game-dev | MEDIA | 0.303457 | game-dev | 0.754204 | 1 | 0.754204 |
OneDeadKey/kalamine | 2,850 | tests/test_macos.py | from pathlib import Path
from lxml import etree
def check_keylayout(filename: str):
path = Path(__file__).parent.parent / f"dist/{filename}.keylayout"
tree = etree.parse(path, etree.XMLParser(recover=True))
dead_keys = []
# check all keymaps/layers: base, shift, caps, option, option+shift
for keymap_index in range(5):
keymap_query = f'//keyMap[@index="{keymap_index}"]'
keymap = tree.xpath(keymap_query)
assert len(keymap) == 1, f"{keymap_query} should be unique"
# check all key codes for this keymap / layer
# (the key codes below are not used, I don't know why)
excluded_keys = [
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
68,
73,
74,
90,
93,
94,
95,
]
for key_index in range(126):
if key_index in excluded_keys:
continue
# ensure the key is defined and unique
key_query = f'{keymap_query}/key[@code="{key_index}"]'
key = tree.xpath(key_query)
assert len(key) == 1, f"{key_query} should be unique"
# ensure the key has either a direct output or a valid action
action_id = key[0].get("action")
if action_id:
if action_id.startswith("dead_"):
dead_keys.append(action_id[5:])
action_query = f'//actions/action[@id="{action_id}"]'
action = tree.xpath(action_query)
assert len(action) == 1, f"{action_query} should be unique"
assert (
len(action_id) > 1
), f"{key_query} should have a multi-char action ID"
else:
assert (
len(key[0].get("output")) <= 1
), f"{key_query} should have a one-char output"
# check all dead keys
# TODO: ensure there are no unused actions or terminators
for dk in dead_keys:
# ensure all 'when' definitions are defined and unique
when_query = f'//actions/action[@id="dead_{dk}"]/when'
when = tree.xpath(when_query)
assert len(when) == 1, f"{when_query} should be unique"
assert when[0].get("state") == "none"
assert when[0].get("next") == dk
# ensure all terminators are defined and unique
terminator_query = f'//terminators/when[@state="{dk}"]'
terminator = tree.xpath(terminator_query)
assert len(terminator) == 1, f"{terminator_query} should be unique"
assert len(terminator[0].get("output")) == 1
def test_keylayouts():
check_keylayout("q-ansi")
check_keylayout("q-intl")
check_keylayout("q-prog")
| 1 | 0.961215 | 1 | 0.961215 | game-dev | MEDIA | 0.394691 | game-dev | 0.942762 | 1 | 0.942762 |
Minitour/The-Macintosh-Project | 1,541 | Macintosh.playground/Sources/Core/MenuAction.swift | import Foundation
public typealias ACTION = ()->Void
public struct MenuAction{
/// The title of the menu item.
var title: String
/// The action that will be triggered once the menu is selected.
var action: ACTION?
/// The sub menus the menu has.
var subMenus: [MenuAction]?
/// The type of the menu (action/seperator)
var type: MenuType = .action
/// Is the action menu enabled or disabled
var enabled: Bool
/// Closure that is triggered every time the menu actions is about to be displayed.
var runtimeClosure: ((Void)->Bool)?
/// Primary Initalizer
///
/// - Parameters:
/// - title: The title of the menu item.
/// - action: The action that will be triggered once the menu is selected.
/// - subMenus: The sub menus the menu has.
/// - type: The type of the menu (action/seperator)
/// - enabled: Is the action menu enabled or disabled
/// - runtimeClosure: Closure that is triggered every time the menu actions is about to be displayed.
init(title: String="",
action: ACTION?=nil,
subMenus: [MenuAction]?=nil,
type: MenuType = .action,
enabled: Bool = true,
runtimeClosure: ((Void)->Bool)?=nil) {
self.title = title
self.action = action
self.subMenus = subMenus
self.type = type
self.enabled = enabled
self.runtimeClosure = runtimeClosure
}
}
public enum MenuType{
case action
case seperator
}
| 1 | 0.869052 | 1 | 0.869052 | game-dev | MEDIA | 0.624259 | game-dev,mobile | 0.913649 | 1 | 0.913649 |
AuroraKy/CelesteCardCollection | 4,666 | lovely/bl_golden.toml | [manifest]
version = "1.0.0"
dump_lua = true
priority = 0
# do not
[[patches]]
[patches.pattern]
target = "functions/state_events.lua"
pattern = "G.FUNCS.draw_from_hand_to_discard()"
position = "after"
payload = '''
if not (G.GAME.ccc_golden_progress and G.GAME.ccc_golden_progress > 1) then
'''
match_indent = true
# end wrap
[[patches]]
[patches.pattern]
target = "functions/state_events.lua"
pattern = '''
end
return true
end
}))
end
function new_round()
'''
position = "before"
payload = '''
else
G.FUNCS.draw_from_discard_to_deck()
delay(0.8)
local function _reset()
G.GAME.chips = 0
G.GAME.current_round.discards_left = math.max(0, G.GAME.round_resets.discards + G.GAME.round_bonus.discards)
G.GAME.current_round.hands_left = (math.max(1, G.GAME.round_resets.hands + G.GAME.round_bonus.next_hands))
G.GAME.current_round.hands_played = 0
G.GAME.current_round.discards_used = 0
for k, v in pairs(G.GAME.hands) do
v.played_this_round = 0
end
G.GAME.ccc_golden_progress = G.GAME.ccc_golden_progress - 1
G.GAME.blind:set_text()
if (G.GAME.modifiers.ccc_bside and G.GAME.modifiers.ccc_bside >= 1) then
G.GAME.ccc_bonus_blind:set_text()
end
end
G.E_MANAGER:add_event(Event({
trigger = 'immediate',
func = function()
for i, v in ipairs({'blind', 'ccc_bonus_blind'}) do
if G.GAME[v].name == 'ccc_Golden Crown' then
SMODS.juice_up_blind(v)
end
end
G.E_MANAGER:add_event(Event({trigger = 'after', delay = 0.06*G.SETTINGS.GAMESPEED, blockable = false, blocking = false, func = function()
play_sound('tarot2', 0.76, 0.4);_reset();return true end}))
play_sound('tarot2', 1, 0.4)
return true
end
}))
delay(0.8)
-- literally just copypasted an entire set_blind chunk (i can't run the rest of it)
if (G.GAME.modifiers.ccc_bside and G.GAME.modifiers.ccc_bside >= 1) then
for i, v in ipairs({'blind', 'ccc_bonus_blind'}) do
local self = G.GAME[v]
local obj = self.config.blind
self.disabled = false
if self.name == 'The Eye' and not reset then
obj = G.P_BLINDS['bl_small'] -- nuke obj to avoid smods ownership
self.hands = {}
for _, v in ipairs(G.handlist) do
self.hands[v] = false
end
end
if not self.name == 'ccc_Golden Crown' and obj.set_blind and type(obj.set_blind) == 'function' then
obj:set_blind()
elseif self.name == 'The Mouth' and not reset then
self.only_hand = false
elseif self.name == 'The Fish' and not reset then
self.prepped = nil
elseif self.name == 'The Water' and not reset then
self.discards_sub = G.GAME.current_round.discards_left
ease_discard(-self.discards_sub)
elseif self.name == 'The Needle' and not reset then
self.hands_sub = G.GAME.round_resets.hands - 1
ease_hands_played(-self.hands_sub)
elseif self.name == 'The Manacle' and not reset then
G.hand:change_size(-1)
elseif self.name == 'Amber Acorn' and not reset and #G.jokers.cards > 0 then
G.jokers:unhighlight_all()
for k, v in ipairs(G.jokers.cards) do
if v.facing == 'front' then
v:flip()
end
end
if #G.jokers.cards > 1 then
G.E_MANAGER:add_event(Event({ trigger = 'after', delay = 0.2, func = function()
G.E_MANAGER:add_event(Event({ func = function() G.jokers:shuffle('aajk'); play_sound('cardSlide1', 0.85);return true end }))
delay(0.15)
G.E_MANAGER:add_event(Event({ func = function() G.jokers:shuffle('aajk'); play_sound('cardSlide1', 1.15);return true end }))
delay(0.15)
G.E_MANAGER:add_event(Event({ func = function() G.jokers:shuffle('aajk'); play_sound('cardSlide1', 1);return true end }))
delay(0.5)
return true end }))
end
end
end
for _, v in ipairs(G.playing_cards) do
G.GAME.blind:debuff_card(v)
end
for _, v in ipairs(G.jokers.cards) do
if not reset then G.GAME.blind:debuff_card(v, true) end
end
end
G.GAME.blind:alert_debuff(true)
if (G.GAME.modifiers.ccc_bside and G.GAME.modifiers.ccc_bside >= 1) then
G.GAME.ccc_bonus_blind:alert_debuff(true)
end
-- TARGET: setting_blind effects
delay(0.4)
G.E_MANAGER:add_event(Event({
trigger = 'immediate',
func = function()
G.STATE = G.STATES.DRAW_TO_HAND
G.deck:shuffle('nr'..G.GAME.round_resets.ante)
G.deck:hard_set_T()
G.STATE_COMPLETE = false
return true
end
}))
end
'''
match_indent = true
# end wrap
[[patches]]
[patches.pattern]
target = "functions/state_events.lua"
pattern = '''
if game_over then
'''
position = "before"
payload = '''
if (G.GAME.ccc_golden_progress and G.GAME.ccc_golden_progress > 1) then
game_won = false
G.GAME.won = false
end
'''
match_indent = true | 1 | 0.960551 | 1 | 0.960551 | game-dev | MEDIA | 0.966892 | game-dev | 0.915452 | 1 | 0.915452 |
flutter/samples | 3,544 | desktop_photo_search/fluent_ui/lib/src/unsplash/tags.g.dart | // Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'tags.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<Tags> _$tagsSerializer = new _$TagsSerializer();
class _$TagsSerializer implements StructuredSerializer<Tags> {
@override
final Iterable<Type> types = const [Tags, _$Tags];
@override
final String wireName = 'Tags';
@override
Iterable<Object?> serialize(
Serializers serializers,
Tags object, {
FullType specifiedType = FullType.unspecified,
}) {
final result = <Object?>[
'title',
serializers.serialize(
object.title,
specifiedType: const FullType(String),
),
];
return result;
}
@override
Tags deserialize(
Serializers serializers,
Iterable<Object?> serialized, {
FullType specifiedType = FullType.unspecified,
}) {
final result = new TagsBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current! as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
case 'title':
result.title =
serializers.deserialize(
value,
specifiedType: const FullType(String),
)!
as String;
break;
}
}
return result.build();
}
}
class _$Tags extends Tags {
@override
final String title;
factory _$Tags([void Function(TagsBuilder)? updates]) =>
(new TagsBuilder()..update(updates))._build();
_$Tags._({required this.title}) : super._() {
BuiltValueNullFieldError.checkNotNull(title, r'Tags', 'title');
}
@override
Tags rebuild(void Function(TagsBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
TagsBuilder toBuilder() => new TagsBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Tags && title == other.title;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, title.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(
r'Tags',
)..add('title', title)).toString();
}
}
class TagsBuilder implements Builder<Tags, TagsBuilder> {
_$Tags? _$v;
String? _title;
String? get title => _$this._title;
set title(String? title) => _$this._title = title;
TagsBuilder();
TagsBuilder get _$this {
final $v = _$v;
if ($v != null) {
_title = $v.title;
_$v = null;
}
return this;
}
@override
void replace(Tags other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$Tags;
}
@override
void update(void Function(TagsBuilder)? updates) {
if (updates != null) updates(this);
}
@override
Tags build() => _build();
_$Tags _build() {
final _$result =
_$v ??
new _$Tags._(
title: BuiltValueNullFieldError.checkNotNull(
title,
r'Tags',
'title',
),
);
replace(_$result);
return _$result;
}
}
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| 1 | 0.899206 | 1 | 0.899206 | game-dev | MEDIA | 0.558359 | game-dev | 0.9189 | 1 | 0.9189 |
quiverteam/Engine | 4,264 | src/vphysics/Physics_VehicleController.h | #ifndef PHYSICS_VEHICLECONTROLLER_H
#define PHYSICS_VEHICLECONTROLLER_H
#if defined(_MSC_VER) || (defined(__GNUC__) && __GNUC__ > 3)
#pragma once
#endif
#include <vphysics/vehicles.h>
#include "vehiclesV32.h"
class IPhysicsObject;
class CPhysicsObject;
class CPhysicsEnvironment;
struct btVehicleRaycaster;
class btRaycastVehicle;
class btWheeledVehicle;
// Toggle wheeled/raycast car (wheeled is not complete yet)
//#define USE_WHEELED_VEHICLE
// TODO: Implement this class and move it to the public interface.
// The game can implement this class to override wheel ray traces.
class IPhysicsVehicleWheelTrace {
public:
// Return the object if the ray hits, otherwise NULL
// Also, be sure to fill the result trace.
virtual IPhysicsObject * CastRay(int wheelIndex, const Vector &start, const Vector &end, trace_t &result) = 0;
};
class CPhysicsVehicleController : public IPhysicsVehicleController32 {
public:
CPhysicsVehicleController(CPhysicsEnvironment *pEnv, CPhysicsObject *pBody, const vehicleparams_t ¶ms, unsigned int nVehicleType, IPhysicsGameTrace *pGameTrace);
~CPhysicsVehicleController();
const vehicle_operatingparams_t & GetOperatingParams() { return m_vehicleState; };
const vehicleparams_t & GetVehicleParams() { return m_vehicleParams; }
vehicleparams_t & GetVehicleParamsForChange() { return m_vehicleParams; }
// force in kg*in/s
void SetWheelForce(int wheelIndex, float force);
void SetWheelBrake(int wheelIndex, float brakeVal);
// steerVal is in degrees!
void SetWheelSteering(int wheelIndex, float steerVal);
// Default vehicle handling...
void Update(float dt, vehicle_controlparams_t &controls);
float UpdateBooster(float dt);
int GetWheelCount();
IPhysicsObject * GetWheel(int index);
bool GetWheelContactPoint(int index, Vector *pContactPoint, int *pSurfaceProps);
void SetSpringLength(int wheelIndex, float length);
void SetWheelFriction(int wheelIndex, float friction);
void OnVehicleEnter() { m_bOccupied = true; }
void OnVehicleExit() { m_bOccupied = false; }
void SetEngineDisabled(bool bDisable) { m_bEngineDisabled = bDisable; }
bool IsEngineDisabled() { return m_bEngineDisabled; }
// Set the position of the vehicle controller and its wheels (wheels relative to vehicle pos).
// Use this instead of calling SetPosition on the chassis.
void SetPosition(const Vector *pos, const QAngle *ang);
// Debug
void GetCarSystemDebugData(vehicle_debugcarsystem_t &debugCarSystem);
void VehicleDataReload();
public:
// Unexposed functions
void InitVehicleParams(const vehicleparams_t ¶ms);
void InitBullVehicle();
void InitCarWheels();
void DestroyCarWheels();
CPhysicsObject * CreateWheel(int wheelIndex, vehicle_axleparams_t &axle);
CPhysicsObject * GetBody();
void UpdateSteering(vehicle_controlparams_t &controls, float dt);
void UpdateEngine(vehicle_controlparams_t &controls, float dt);
void UpdateWheels(vehicle_controlparams_t &controls, float dt);
void CalcEngineTransmission(vehicle_controlparams_t &controls, float dt);
void CalcEngine(vehicle_controlparams_t &controls, float dt);
void ShutdownBullVehicle();
// To be exposed functions
CPhysicsObject * AddWheel();
private:
vehicleparams_t m_vehicleParams;
vehicle_operatingparams_t m_vehicleState;
CPhysicsObject * m_pBody;
CPhysicsEnvironment * m_pEnv;
IPhysicsGameTrace * m_pGameTrace;
unsigned int m_iVehicleType;
bool m_bEngineDisabled;
bool m_bOccupied;
CPhysicsObject * m_pWheels[VEHICLE_MAX_WHEEL_COUNT];
int m_iWheelCount;
bool m_bSlipperyWheels;
#ifdef USE_WHEELED_VEHICLE
btWheeledVehicle * m_pVehicle;
#else
btRaycastVehicle * m_pVehicle;
btVehicleRaycaster * m_pRaycaster;
btRaycastVehicle::btVehicleTuning m_tuning;
#endif
};
IPhysicsVehicleController *CreateVehicleController(CPhysicsEnvironment *pEnv, CPhysicsObject *pBody, const vehicleparams_t ¶ms, unsigned int nVehicleType, IPhysicsGameTrace *pGameTrace);
#endif // PHYSICS_VEHICLECONTROLLER_H
| 1 | 0.698466 | 1 | 0.698466 | game-dev | MEDIA | 0.959722 | game-dev | 0.644079 | 1 | 0.644079 |
981011512/-- | 2,350 | cf-framework-parent/cf-internet-of-things/cf-car-park/forward-dh/src/main/java/com/cf/forward/dh/yangbang/BxCmdSendDynamicArea.java | package com.cf.forward.dh.yangbang;
import java.util.List;
public class BxCmdSendDynamicArea extends BxCmd {
private static final byte GROUP = (byte) 0xa3;
private static final byte CMD = 0x06;
//
// process mode
// 当该字节为 0 时,收到动态信息后不再进行清区域
// 和初始化区域的操作,当该字节为 1 时,收到动态
// 信息后需要进行清区域和初始化区域的操作。
private byte processMode = 0x00;
//
// reserved
private byte r2;
//
// 要删除的区域ID
private byte[] delAreaIds;
//
// 区域
private List<BxArea> areas;
//
public BxCmdSendDynamicArea(List<BxArea> areas) {
super(GROUP, CMD);
this.areas = areas;
}
@Override
public byte[] build() {
BxByteArray array = new BxByteArray();
//
// cmd group
array.add(getGroup());
array.add(getCmd());
//
// response or not
array.add(getReqResp());
//
// process mod
array.add(processMode);
//
// r2
array.add(r2);
//
// delete area ids
if(delAreaIds == null) {
array.add((byte)0x00);
}
else {
byte delIdNum = (byte) delAreaIds.length;
array.add(delIdNum);
array.add(delAreaIds);
}
//
// area data
if(areas != null) {
if(areas.size() == 0) {
array.add((byte)0x00);
}
else {
array.add((byte)areas.size());
for(BxArea area:areas) {
byte[] areaData = area.build();
short dataLen = (short) areaData.length;
array.add(dataLen);
array.add(areaData);
}
}
}
else {
array.add((byte)0x00);
}
return array.build();
}
public byte getProcessMode() {
return processMode;
}
public void setProcessMode(byte processMode) {
this.processMode = processMode;
}
public byte[] getDelAreaIds() {
return delAreaIds;
}
public void setDelAreaIds(byte[] delAreaIds) {
this.delAreaIds = delAreaIds;
}
public List<BxArea> getAreas() {
return areas;
}
public void setAreas(List<BxArea> areas) {
this.areas = areas;
}
}
| 1 | 0.742546 | 1 | 0.742546 | game-dev | MEDIA | 0.34031 | game-dev | 0.780778 | 1 | 0.780778 |
hushuangshaung/HSSFramework | 2,099 | Assets/ThirdParty/YIUIFramework/Plugins/I2Localization/Scripts/Targets/LocalizeTarget_UnityStandard_Child.cs | using UnityEditor;
using UnityEngine;
namespace I2.Loc
{
public class LocalizeTargetDesc_Child : LocalizeTargetDesc<LocalizeTarget_UnityStandard_Child>
{
public override bool CanLocalize(Localize cmp) { return cmp.transform.childCount > 1; }
}
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
public class LocalizeTarget_UnityStandard_Child : LocalizeTarget<GameObject>
{
static LocalizeTarget_UnityStandard_Child() { AutoRegister(); }
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] static void AutoRegister() { LocalizationManager.RegisterTarget(new LocalizeTargetDesc_Child { Name = "Child", Priority = 200 }); }
public override bool IsValid(Localize cmp) { return cmp.transform.childCount>1; }
public override eTermType GetPrimaryTermType(Localize cmp) { return eTermType.GameObject; }
public override eTermType GetSecondaryTermType(Localize cmp) { return eTermType.Text; }
public override bool CanUseSecondaryTerm() { return false; }
public override bool AllowMainTermToBeRTL() { return false; }
public override bool AllowSecondTermToBeRTL() { return false; }
public override void GetFinalTerms(Localize cmp, string Main, string Secondary, out string primaryTerm, out string secondaryTerm)
{
primaryTerm = cmp.name;
secondaryTerm = null;
}
public override void DoLocalize(Localize cmp, string mainTranslation, string secondaryTranslation)
{
if (string.IsNullOrEmpty(mainTranslation))
return;
Transform locTr = cmp.transform;
var objName = mainTranslation;
var idx = mainTranslation.LastIndexOfAny(LanguageSourceData.CategorySeparators);
if (idx >= 0)
objName = objName.Substring(idx + 1);
for (int i = 0; i < locTr.childCount; ++i)
{
var child = locTr.GetChild(i);
child.gameObject.SetActive(child.name == objName);
}
}
}
} | 1 | 0.830015 | 1 | 0.830015 | game-dev | MEDIA | 0.869226 | game-dev | 0.92367 | 1 | 0.92367 |
KgDW/NullPoint-Fabric | 3,011 | src/main/java/me/nullpoint/mod/modules/impl/movement/ElytraFlyPlus.java | package me.nullpoint.mod.modules.impl.movement;
import me.nullpoint.api.events.eventbus.EventHandler;
import me.nullpoint.api.events.impl.PacketEvent;
import me.nullpoint.api.events.impl.TravelEvent;
import me.nullpoint.mod.modules.Module;
import me.nullpoint.mod.modules.settings.impl.SliderSetting;
import net.minecraft.item.ElytraItem;
import net.minecraft.item.ItemStack;
import net.minecraft.network.packet.c2s.play.ClientCommandC2SPacket;
import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket;
import net.minecraft.util.math.Vec3d;
public class ElytraFlyPlus extends Module {
private final Vec3d vec3d = new Vec3d(0,0,0);
public static ElytraFlyPlus INSTANCE;
public boolean hasElytra = false;
public SliderSetting horizontalSpeed = add(new SliderSetting("HorizontalSpeed", 1.3, 0.1, 40.0));
public SliderSetting verticalSpeed = add(new SliderSetting("UpSpeed", 1.3, 0.1, 40.0));
public ElytraFlyPlus(){
super("ElytraFlyPlus", Category.Movement);
INSTANCE = this;
}
@Override
public void onUpdate() {
if (nullCheck()) return;
for (ItemStack is : mc.player.getArmorItems()) {
if (is.getItem() instanceof ElytraItem) {
hasElytra = true;
if (mc.options.forwardKey.isPressed()) {
vec3d.add(0, 0, horizontalSpeed.getValue());
vec3d.rotateY(-(float) Math.toRadians(mc.player.getYaw()));
} else if (mc.options.backKey.isPressed()) {
vec3d.add(0, 0, horizontalSpeed.getValue());
vec3d.rotateY((float) Math.toRadians(mc.player.getYaw()));
}
if (mc.options.jumpKey.isPressed()) {
vec3d.add(0, verticalSpeed.getValue(), 0);
} else if (!mc.options.jumpKey.isPressed()) {
vec3d.add(0, -verticalSpeed.getValue(), 0);
}
mc.player.setVelocity(vec3d);
mc.player.networkHandler.sendPacket(new ClientCommandC2SPacket(mc.player, ClientCommandC2SPacket.Mode.START_FALL_FLYING));
mc.player.networkHandler.sendPacket(new PlayerMoveC2SPacket.OnGroundOnly(true));
break;
} else {
hasElytra = false;
}
}
}
@Override
public void onDisable() {
mc.player.getAbilities().flying = false;
mc.player.getAbilities().allowFlying = false;
}
@EventHandler
public void onPacketSend(PacketEvent.Send event) {
if (event.getPacket() instanceof PlayerMoveC2SPacket) {
mc.player.networkHandler.sendPacket(new ClientCommandC2SPacket(mc.player, ClientCommandC2SPacket.Mode.START_FALL_FLYING));
}
}
@EventHandler
public void onMove(TravelEvent event) {
if(nullCheck()) return;
mc.player.getAbilities().flying = true;
mc.player.getAbilities().setFlySpeed(horizontalSpeed.getValueFloat() / 20);
}
}
| 1 | 0.86862 | 1 | 0.86862 | game-dev | MEDIA | 0.974356 | game-dev | 0.949303 | 1 | 0.949303 |
FWGS/hlsdk-portable | 8,345 | cl_dll/death.cpp | /***
*
* Copyright (c) 1996-2002, 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.
*
****/
//
// death notice
//
#include "hud.h"
#include "cl_util.h"
#include "parsemsg.h"
#include <string.h>
#include <stdio.h>
#if USE_VGUI
#include "vgui_TeamFortressViewport.h"
#endif
DECLARE_MESSAGE( m_DeathNotice, DeathMsg )
struct DeathNoticeItem {
char szKiller[MAX_PLAYER_NAME_LENGTH * 2];
char szVictim[MAX_PLAYER_NAME_LENGTH * 2];
int iId; // the index number of the associated sprite
int iSuicide;
int iTeamKill;
int iNonPlayerKill;
float flDisplayTime;
float *KillerColor;
float *VictimColor;
};
#define MAX_DEATHNOTICES 4
static int DEATHNOTICE_DISPLAY_TIME = 6;
#define DEATHNOTICE_TOP 32
DeathNoticeItem rgDeathNoticeList[MAX_DEATHNOTICES + 1];
float g_ColorBlue[3] = { 0.6, 0.8, 1.0 };
float g_ColorRed[3] = { 1.0, 0.25, 0.25 };
float g_ColorGreen[3] = { 0.6, 1.0, 0.6 };
float g_ColorYellow[3] = { 1.0, 0.7, 0.0 };
float g_ColorGrey[3] = { 0.8, 0.8, 0.8 };
float *GetClientColor( int clientIndex )
{
switch( g_PlayerExtraInfo[clientIndex].teamnumber )
{
case 1: return g_ColorBlue;
case 2: return g_ColorRed;
case 3: return g_ColorYellow;
case 4: return g_ColorGreen;
case 0: return g_ColorYellow;
default: return g_ColorGrey;
}
return NULL;
}
int CHudDeathNotice::Init( void )
{
gHUD.AddHudElem( this );
HOOK_MESSAGE( DeathMsg );
CVAR_CREATE( "hud_deathnotice_time", "6", FCVAR_ARCHIVE );
return 1;
}
void CHudDeathNotice::InitHUDData( void )
{
memset( rgDeathNoticeList, 0, sizeof(rgDeathNoticeList) );
}
int CHudDeathNotice::VidInit( void )
{
m_HUD_d_skull = gHUD.GetSpriteIndex( "d_skull" );
return 1;
}
int CHudDeathNotice::Draw( float flTime )
{
int x, y, r, g, b;
int gap = 20;
const wrect_t& sprite = gHUD.GetSpriteRect(m_HUD_d_skull);
gap = sprite.bottom - sprite.top;
SCREENINFO screenInfo;
screenInfo.iSize = sizeof(SCREENINFO);
gEngfuncs.pfnGetScreenInfo(&screenInfo);
gap = Q_max( gap, screenInfo.iCharHeight );
for( int i = 0; i < MAX_DEATHNOTICES; i++ )
{
if( rgDeathNoticeList[i].iId == 0 )
break; // we've gone through them all
if( rgDeathNoticeList[i].flDisplayTime < flTime )
{
// display time has expired
// remove the current item from the list
memmove( &rgDeathNoticeList[i], &rgDeathNoticeList[i + 1], sizeof(DeathNoticeItem) * ( MAX_DEATHNOTICES - i ) );
i--; // continue on the next item; stop the counter getting incremented
continue;
}
rgDeathNoticeList[i].flDisplayTime = Q_min( rgDeathNoticeList[i].flDisplayTime, gHUD.m_flTime + DEATHNOTICE_DISPLAY_TIME );
// Only draw if the viewport will let me
// vgui dropped out
#if USE_VGUI
if( gViewPort && gViewPort->AllowedToPrintText() )
#endif
{
// Draw the death notice
y = YRES( DEATHNOTICE_TOP ) + 2 + ( gap * i ); //!!!
int id = ( rgDeathNoticeList[i].iId == -1 ) ? m_HUD_d_skull : rgDeathNoticeList[i].iId;
x = ScreenWidth - ConsoleStringLen( rgDeathNoticeList[i].szVictim ) - ( gHUD.GetSpriteRect(id).right - gHUD.GetSpriteRect(id).left ) - 4;
if( !rgDeathNoticeList[i].iSuicide )
{
x -= ( 5 + ConsoleStringLen( rgDeathNoticeList[i].szKiller ) );
// Draw killers name
if( rgDeathNoticeList[i].KillerColor )
DrawSetTextColor( rgDeathNoticeList[i].KillerColor[0], rgDeathNoticeList[i].KillerColor[1], rgDeathNoticeList[i].KillerColor[2] );
x = 5 + DrawConsoleString( x, y + 4, rgDeathNoticeList[i].szKiller );
}
r = 255; g = 80; b = 0;
if( rgDeathNoticeList[i].iTeamKill )
{
r = 10; g = 240; b = 10; // display it in sickly green
}
// Draw death weapon
SPR_Set( gHUD.GetSprite(id), r, g, b );
SPR_DrawAdditive( 0, x, y, &gHUD.GetSpriteRect(id) );
x += ( gHUD.GetSpriteRect(id).right - gHUD.GetSpriteRect(id).left );
// Draw victims name (if it was a player that was killed)
if( rgDeathNoticeList[i].iNonPlayerKill == FALSE )
{
if( rgDeathNoticeList[i].VictimColor )
DrawSetTextColor( rgDeathNoticeList[i].VictimColor[0], rgDeathNoticeList[i].VictimColor[1], rgDeathNoticeList[i].VictimColor[2] );
x = DrawConsoleString( x, y + 4, rgDeathNoticeList[i].szVictim );
}
}
}
return 1;
}
// This message handler may be better off elsewhere
int CHudDeathNotice::MsgFunc_DeathMsg( const char *pszName, int iSize, void *pbuf )
{
int i;
m_iFlags |= HUD_ACTIVE;
BEGIN_READ( pbuf, iSize );
int killer = READ_BYTE();
int victim = READ_BYTE();
char killedwith[32];
strcpy( killedwith, "d_" );
strlcat( killedwith, READ_STRING(), sizeof( killedwith ));
#if USE_VGUI && !USE_NOVGUI_SCOREBOARD
if (gViewPort)
gViewPort->DeathMsg( killer, victim );
#else
gHUD.m_Scoreboard.DeathMsg( killer, victim );
#endif
gHUD.m_Spectator.DeathMessage( victim );
for( i = 0; i < MAX_DEATHNOTICES; i++ )
{
if( rgDeathNoticeList[i].iId == 0 )
break;
}
if( i == MAX_DEATHNOTICES )
{
// move the rest of the list forward to make room for this item
memmove( rgDeathNoticeList, rgDeathNoticeList + 1, sizeof(DeathNoticeItem) * MAX_DEATHNOTICES );
i = MAX_DEATHNOTICES - 1;
}
gHUD.GetAllPlayersInfo();
// Get the Killer's name
const char *killer_name = "";
killer_name = g_PlayerInfoList[killer].name;
if( !killer_name )
{
killer_name = "";
rgDeathNoticeList[i].szKiller[0] = 0;
}
else
{
rgDeathNoticeList[i].KillerColor = GetClientColor( killer );
strlcpy( rgDeathNoticeList[i].szKiller, killer_name, MAX_PLAYER_NAME_LENGTH );
}
// Get the Victim's name
const char *victim_name = "";
// If victim is -1, the killer killed a specific, non-player object (like a sentrygun)
if( ( (signed char)victim ) != -1 )
victim_name = g_PlayerInfoList[victim].name;
if( !victim_name )
{
victim_name = "";
rgDeathNoticeList[i].szVictim[0] = 0;
}
else
{
rgDeathNoticeList[i].VictimColor = GetClientColor( victim );
strlcpy( rgDeathNoticeList[i].szVictim, victim_name, MAX_PLAYER_NAME_LENGTH );
}
// Is it a non-player object kill?
if( ( (signed char)victim ) == -1 )
{
rgDeathNoticeList[i].iNonPlayerKill = TRUE;
// Store the object's name in the Victim slot (skip the d_ bit)
strcpy( rgDeathNoticeList[i].szVictim, killedwith + 2 );
}
else
{
if( killer == victim || killer == 0 )
rgDeathNoticeList[i].iSuicide = TRUE;
if( !strcmp( killedwith, "d_teammate" ) )
rgDeathNoticeList[i].iTeamKill = TRUE;
}
// Find the sprite in the list
int spr = gHUD.GetSpriteIndex( killedwith );
rgDeathNoticeList[i].iId = spr;
DEATHNOTICE_DISPLAY_TIME = CVAR_GET_FLOAT( "hud_deathnotice_time" );
rgDeathNoticeList[i].flDisplayTime = gHUD.m_flTime + DEATHNOTICE_DISPLAY_TIME;
if( rgDeathNoticeList[i].iNonPlayerKill )
{
ConsolePrint( rgDeathNoticeList[i].szKiller );
ConsolePrint( " killed a " );
ConsolePrint( rgDeathNoticeList[i].szVictim );
ConsolePrint( "\n" );
}
else
{
// record the death notice in the console
if( rgDeathNoticeList[i].iSuicide )
{
ConsolePrint( rgDeathNoticeList[i].szVictim );
if( !strcmp( killedwith, "d_world" ) )
{
ConsolePrint( " died" );
}
else
{
ConsolePrint( " killed self" );
}
}
else if( rgDeathNoticeList[i].iTeamKill )
{
ConsolePrint( rgDeathNoticeList[i].szKiller );
ConsolePrint( " killed his teammate " );
ConsolePrint( rgDeathNoticeList[i].szVictim );
}
else
{
ConsolePrint( rgDeathNoticeList[i].szKiller );
ConsolePrint( " killed " );
ConsolePrint( rgDeathNoticeList[i].szVictim );
}
if( *killedwith && (*killedwith > 13 ) && strcmp( killedwith, "d_world" ) && !rgDeathNoticeList[i].iTeamKill )
{
ConsolePrint( " with " );
// replace the code names with the 'real' names
if( !strcmp( killedwith + 2, "egon" ) )
strcpy( killedwith, "d_gluon gun" );
if( !strcmp( killedwith + 2, "gauss" ) )
strcpy( killedwith, "d_tau cannon" );
ConsolePrint( killedwith + 2 ); // skip over the "d_" part
}
ConsolePrint( "\n" );
}
return 1;
}
| 1 | 0.923905 | 1 | 0.923905 | game-dev | MEDIA | 0.899019 | game-dev | 0.925827 | 1 | 0.925827 |
chrismaltby/gb-studio | 1,030 | src/lib/events/eventActorSetAnimationSpeed.js | const l10n = require("../helpers/l10n").default;
const id = "EVENT_ACTOR_SET_ANIMATION_SPEED";
const groups = ["EVENT_GROUP_ACTOR"];
const subGroups = {
EVENT_GROUP_ACTOR: "EVENT_GROUP_PROPERTIES",
};
const autoLabel = (fetchArg) => {
return l10n("EVENT_ACTOR_SET_ANIMATION_SPEED_LABEL", {
actor: fetchArg("actorId"),
speed: fetchArg("speed"),
});
};
const fields = [
{
key: "actorId",
label: l10n("ACTOR"),
description: l10n("FIELD_ACTOR_UPDATE_DESC"),
type: "actor",
defaultValue: "$self$",
},
{
key: "speed",
label: l10n("FIELD_ANIMATION_SPEED"),
description: l10n("FIELD_ANIMATION_SPEED_DESC"),
type: "animSpeed",
defaultValue: 15,
},
];
const compile = (input, helpers) => {
const { actorSetActive, actorSetAnimationSpeed } = helpers;
actorSetActive(input.actorId);
actorSetAnimationSpeed(input.speed);
};
module.exports = {
id,
description: l10n("EVENT_ACTOR_SET_ANIMATION_SPEED_DESC"),
autoLabel,
groups,
subGroups,
fields,
compile,
};
| 1 | 0.714202 | 1 | 0.714202 | game-dev | MEDIA | 0.462459 | game-dev | 0.748232 | 1 | 0.748232 |
MafiaHub/Framework | 41,562 | vendors/slikenet/Source/include/slikenet/TeamManager.h | /*
* Original work: Copyright (c) 2014, Oculus VR, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* RakNet License.txt file in the licenses directory of this source tree. An additional grant
* of patent rights can be found in the RakNet Patents.txt file in the same directory.
*
*
* Modified work: Copyright (c) 2016-2017, SLikeSoft UG (haftungsbeschränkt)
*
* This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style
* license found in the license.txt file in the root directory of this source tree.
*/
// TODO: optimize the list of teams and team members to be O(1). Store in hashes, use linked lists to get ordered traversal
/// \file TeamManager.h
/// \brief Automates networking and list management for teams
/// \details TeamManager provides support for teams. A team is a list of team members.
/// Teams contain properties including the number of team members per team, whether or not tagged teams must have equal numbers of members, and if a team is locked or not to certain entry conditions
/// Team members contain properties including which teams they are on and which teams they want to join if a team is not immediately joinable
/// Advanced functionality includes the ability for a team member to be on multiple teams simultaneously, the ability to swap teams with other members, and the ability to resize the number of members supported per team
///
#include "NativeFeatureIncludes.h"
#if _RAKNET_SUPPORT_TeamManager==1
#ifndef __TEAM_MANAGER_H
#define __TEAM_MANAGER_H
#include "PluginInterface2.h"
#include "memoryoverride.h"
#include "NativeTypes.h"
#include "DS_List.h"
#include "types.h"
#include "DS_Hash.h"
#include "DS_OrderedList.h"
namespace SLNet
{
/// Forward declarations
class RakPeerInterface;
/// \defgroup TEAM_MANAGER_GROUP TeamManager
/// \brief Automates networking and list management for teams
/// \details When used with ReplicaManager3 and FullyConnectedMesh2, provides a complete solution to managing a distributed list of teams and team member objects with support for host migration.
/// \ingroup PLUGINS_GROUP
/// \ingroup TEAM_MANAGER_GROUP
/// \brief A subcategory of not being on a team. For example, 0 may mean no team for a player, while 1 may mean no team for a spectator. Defined by the user.
typedef unsigned char NoTeamId;
/// \ingroup TEAM_MANAGER_GROUP
/// Used for multiple worlds.
typedef uint8_t WorldId;
/// \ingroup TEAM_MANAGER_GROUP
/// Maximum number of members on one team. Use 65535 for unlimited.
typedef uint16_t TeamMemberLimit;
/// Allow members to join this team when they specify TeamSelection::JOIN_ANY_AVAILABLE_TEAM
#define ALLOW_JOIN_ANY_AVAILABLE_TEAM (1<<0)
/// Allow members to join this team when they specify TeamSelection::JOIN_SPECIFIC_TEAM
#define ALLOW_JOIN_SPECIFIC_TEAM (1<<1)
/// Allow the host to put members on this team when rebalancing with TM_World::SetBalanceTeams()
#define ALLOW_JOIN_REBALANCING (1<<2)
// Bitwise combination of ALLOW_JOIN_ANY_AVAILABLE_TEAM, ALLOW_JOIN_SPECIFIC_TEAM, ALLOW_JOIN_REBALANCING
typedef uint8_t JoinPermissions;
// Forward declarations
class TM_Team;
class TM_TeamMember;
class TM_World;
class TeamManager;
/// \ingroup TEAM_MANAGER_GROUP
enum JoinTeamType
{
/// Attempt to join the first available team.
JOIN_ANY_AVAILABLE_TEAM,
/// Attempt to join a specific team, previously added with TM_World::ReferenceTeam()
JOIN_SPECIFIC_TEAM,
/// No team. Always succeeds.
JOIN_NO_TEAM
};
/// \ingroup TEAM_MANAGER_GROUP
enum TMTopology
{
// Each system will send all messages to all participants
TM_PEER_TO_PEER,
// The host will relay incoming messages to all participants
TM_CLIENT_SERVER,
};
/// \brief Parameter to TM_World::ReferenceTeamMember()
/// \details Use TeamSelection::AnyAvailable(), TeamSelection::SpecificTeam(), or TeamSelection::NoTeam()
/// \ingroup TEAM_MANAGER_GROUP
struct TeamSelection
{
TeamSelection();
TeamSelection(JoinTeamType itt);
TeamSelection(JoinTeamType itt, TM_Team *param);
TeamSelection(JoinTeamType itt, NoTeamId param);
JoinTeamType joinTeamType;
union
{
TM_Team *specificTeamToJoin;
NoTeamId noTeamSubcategory;
} teamParameter;
/// \brief Join any team that has available slots and is tagged with ALLOW_JOIN_ANY_AVAILABLE_TEAM
/// \details ID_TEAM_BALANCER_TEAM_ASSIGNED, ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, or ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED will be returned to all systems.
static TeamSelection AnyAvailable(void);
/// \brief Join a specific team if it has available slots, and is tagged with JOIN_SPECIFIC_TEAMS
/// \details ID_TEAM_BALANCER_TEAM_ASSIGNED, ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, or ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED will be returned to all systems.
/// \param[in] specificTeamToJoin Which team to attempt to join.
static TeamSelection SpecificTeam(TM_Team *specificTeamToJoin);
/// \brief Do not join a team, or leave all current teams.
/// \details This always succeeds. ID_TEAM_BALANCER_TEAM_ASSIGNED will be returned to all systems.
/// \param[in] noTeamSubcategory Even when not on a team, you can internally identify a subcategory of not being on a team, such as AI or spectator.
static TeamSelection NoTeam(NoTeamId noTeamSubcategory);
};
/// \brief A member of one or more teams.
/// \details Contains data and operations on data to manage which team your game's team members are on.
/// Best used as a composite member of your "User" or "Player" class(es).
/// When using with ReplicaManager3, call TM_TeamMember::ReferenceTeamMember() in Replica3::DeserializeConstruction() and TM_TeamMember::DeserializeConstruction() in Replica3::PostDeserializeConstruction()
/// There is otherwise no need to manually serialize the class, as operations are networked internally.
/// \ingroup TEAM_MANAGER_GROUP
class RAK_DLL_EXPORT TM_TeamMember
{
public:
// GetInstance() and DestroyInstance(instance*)
STATIC_FACTORY_DECLARATIONS(TM_TeamMember)
TM_TeamMember();
virtual ~TM_TeamMember();
/// \brief Request to join any team, a specific team, or to leave all teams
/// \details Function will return false on invalid operations, such as joining a team you are already on.
/// Will also fail with TeamSelection::JOIN_ANY_AVAILABLE_TEAM if you are currently on a team.
/// On success, every system will get ID_TEAM_BALANCER_TEAM_ASSIGNED. Use TeamManager::DecomposeTeamAssigned() to get details of which team member the message refers to.
/// On failure, all systems will get ID_TEAM_BALANCER_REQUESTED_TEAM_FULL or ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED. Use TeamManager::DecomposeTeamFull() and TeamManager::DecomposeTeamLocked() to get details of which team member the message refers to.
/// \note Joining a specific team with this function may result in being on more than one team at once, even if you call the function while locally only on one team. If your game depends on only being on one team at a team, use RequestTeamSwitch() instead with the parameter teamToLeave set to 0
/// \param[in] TeamSelection::AnyAvailable(), TeamSelection::SpecificTeam(), or TeamSelection::NoTeam()
/// \return false On invalid or unnecessary operation. Otherwise returns true
bool RequestTeam(TeamSelection teamSelection);
/// \brief Similar to RequestTeam with TeamSelection::SpecificTeam(), but leave a team simultaneously when the desired team is joinable
/// \param[in] teamToJoin Which team to join
/// \param[in] teamToLeave If 0, means leave all current teams. Otherwise, leave the specified team.
/// \return false On invalid or unnecessary operation. Otherwise returns true
bool RequestTeamSwitch(TM_Team *teamToJoin, TM_Team *teamToLeave);
/// \brief Returns the first requested team in the list of requested teams, if you have a requested team at all.
/// \return TeamSelection::SpecificTeam(), TeamSelection::NoTeam(), or TeamSelection::AnyAvailable()
TeamSelection GetRequestedTeam(void) const;
/// \brief Returns pending calls to RequestTeam() when using TeamSelection::JOIN_SPECIFIC_TEAM
/// \param[out] All pending requested teams
void GetRequestedSpecificTeams(DataStructures::List<TM_Team*> &requestedTeams) const;
/// \brief Returns if the specified team is in the list of pending requested teams
/// \param[in] The team we are checking
/// \return Did we request to join this specific team?
bool HasRequestedTeam(TM_Team *team) const;
/// \brief Returns the index of \a team in the requested teams list
/// \param[in] The team we are checking
/// \return -1 if we did not requested to join this team. Otherwise the index.
unsigned int GetRequestedTeamIndex(TM_Team *team) const;
/// \return The number of teams that would be returned by a call to GetRequestedSpecificTeams()
unsigned int GetRequestedTeamCount(void) const;
/// \brief Cancels a request to join a specific team.
/// \details Useful if you got ID_TEAM_BALANCER_REQUESTED_TEAM_FULL or ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED and changed your mind about joining the team.
/// \note This is not guaranteed to work due to latency. To clarify, If the host switches your team at the same time you call CancelRequestTeam() you may still get ID_TEAM_BALANCER_TEAM_ASSIGNED for the team you tried to cancel.
/// \param[in] specificTeamToCancel Which team to no longer join. Use 0 for all.
/// \return false On invalid or unnecessary operation. Otherwise returns true
bool CancelTeamRequest(TM_Team *specificTeamToCancel);
/// \brief Leave a team
/// \details Leaves a team that you are on. Always succeeds provided you are on that team
/// Generates ID_TEAM_BALANCER_TEAM_ASSIGNED on all systems on success.
/// If you leave the last team you are on, \a noTeamSubcategory is set as well.
/// \param[in] team Which team to leave
/// \param[in] _noTeamSubcategory If the team member has been removed from all teams, which subcategory of NoTeamId to set them to
/// \return false On invalid or unnecessary operation. Otherwise returns true
bool LeaveTeam(TM_Team* team, NoTeamId _noTeamSubcategory);
/// \brief Leave all teams
/// \Details Leaves all teams you are on, and sets \a noTeamSubcategory
/// \note This is the same as and just calls RequestTeam(TeamSelection::NoTeam(noTeamSubcategory));
/// \return false On invalid or unnecessary operation. Otherwise returns true
bool LeaveAllTeams(NoTeamId inNoTeamSubcategory);
/// \return Get the first team we are on, or 0 if we are not on a team.
TM_Team* GetCurrentTeam(void) const;
/// \return How many teams we are on
unsigned int GetCurrentTeamCount(void) const;
/// \return Returns one of the teams in the current team list, up to GetCurrentTeamCount()
TM_Team* GetCurrentTeamByIndex(unsigned int index);
/// \param[out] Get all teams we are on, as a list
void GetCurrentTeams(DataStructures::List<TM_Team*> &_teams) const;
/// For each team member, when you get ID_TEAM_BALANCER_TEAM_ASSIGNED for that member, the team list is saved.
/// Use this function to get that list, for example to determine which teams we just left or joined
/// \param[out] _teams The previous list of teams we were on
void GetLastTeams(DataStructures::List<TM_Team*> &_teams) const;
/// \param[in] The team we are checking
/// \return Are we on this team?
bool IsOnTeam(TM_Team *team) const;
/// \return The teamMemberID parameter passed to TM_World::ReferenceTeamMember()
NetworkID GetNetworkID(void) const;
/// \return The TM_World instance that was used when calling TM_World::ReferenceTeamMember()
TM_World* GetTM_World(void) const;
/// \brief Serializes the current state of this object
/// \details To replicate a TM_TeamMember on another system, first instantiate the object using your own code, or a system such as ReplicaManager3.
/// Next, call SerializeConstruction() from whichever system owns the team member
/// Last, call DeserializeConstruction() on the newly created TM_TeamMember
/// \note You must instantiate and deserialize all TM_Team instances that the team member refers to before calling DesrializeConstruction(). ReplicaManager3::PostSerializeConstruction() and ReplicaManager3::PostDeserializeConstruction() will ensure this.
/// \param[out] constructionBitstream This object serialized to a BitStream
void SerializeConstruction(BitStream *constructionBitstream);
/// \brief Deserializes the current state of this object
/// \details See SerializeConstruction for more details()
/// \note DeserializeConstruction also calls ReferenceTeamMember on the passed \a teamManager instance, there is no need to do so yourself
/// \param[in] teamManager TeamManager instance
/// \param[in] constructionBitstream This object serialized to a BitStream
bool DeserializeConstruction(TeamManager *teamManager, BitStream *constructionBitstream);
/// \param[in] o Stores a void* for your own use. If using composition, this is useful to store a pointer to the containing object.
void SetOwner(void *o);
/// \return Whatever was passed to SetOwner()
void *GetOwner(void) const;
/// \return If not on a team, returns the current NoTeamId value
NoTeamId GetNoTeamId(void) const;
/// Return world->GetTeamMemberIndex(this)
unsigned int GetWorldIndex(void) const;
/// \internal
static unsigned long ToUint32( const NetworkID &g );
/// \internal
struct RequestedTeam
{
SLNet::Time whenRequested;
unsigned int requestIndex;
TM_Team *requested;
bool isTeamSwitch;
TM_Team *teamToLeave;
};
protected:
NetworkID networkId;
TM_World* world;
// Teams we are a member of. We can be on more than one team, but not on the same team more than once
DataStructures::List<TM_Team*> teams;
// If teams is empty, which subcategory of noTeam we are on
NoTeamId noTeamSubcategory;
// Teams we have requested to join. Mutually exclusive with teams we are already on. Cannot request the same team more than once.
DataStructures::List<RequestedTeam> teamsRequested;
// If teamsRequested is not empty, we want to join a specific team
// If teamsRequested is empty, then joinTeamType is either JOIN_NO_TEAM or JOIN_ANY_AVAILABLE_TEAM
JoinTeamType joinTeamType;
// Set by StoreLastTeams()
DataStructures::List<TM_Team*> lastTeams;
SLNet::Time whenJoinAnyRequested;
unsigned int joinAnyRequestIndex;
void *owner;
// Remove from all requested and current teams.
void UpdateListsToNoTeam(NoTeamId nti);
bool JoinAnyTeamCheck(void) const;
bool JoinSpecificTeamCheck(TM_Team *specificTeamToJoin, bool ignoreRequested) const;
bool SwitchSpecificTeamCheck(TM_Team *teamToJoin, TM_Team *teamToLeave, bool ignoreRequested) const;
bool LeaveTeamCheck(TM_Team *team) const;
void UpdateTeamsRequestedToAny(void);
void UpdateTeamsRequestedToNone(void);
void AddToRequestedTeams(TM_Team *teamToJoin);
void AddToRequestedTeams(TM_Team *teamToJoin, TM_Team *teamToLeave);
bool RemoveFromRequestedTeams(TM_Team *team);
void AddToTeamList(TM_Team *team);
void RemoveFromSpecificTeamInternal(TM_Team *team);
void RemoveFromAllTeamsInternal(void);
void StoreLastTeams(void);
friend class TM_World;
friend class TM_Team;
friend class TeamManager;
};
/// \brief A team, containing a list of TM_TeamMember instances
/// \details Contains lists of TM_TeamMember instances
/// Best used as a composite member of your "Team" or "PlayerList" class(es).
/// When using with ReplicaManager3, call TM_Team::ReferenceTeam() in Replica3::DeserializeConstruction() and TM_Team::DeserializeConstruction() in Replica3::PostDeserializeConstruction()
/// There is otherwise no need to manually serialize the class, as operations are networked internally.
/// \ingroup TEAM_MANAGER_GROUP
class RAK_DLL_EXPORT TM_Team
{
public:
// GetInstance() and DestroyInstance(instance*)
STATIC_FACTORY_DECLARATIONS(TM_Team)
TM_Team();
virtual ~TM_Team();
/// \brief Set the maximum number of members that can join this team.
/// Defaults to 65535
/// Setting the limit lower than the existing number of members kicks members out, and assigns noTeamSubcategory to them if they have no other team to go to
/// Setting the limit higher allows members to join in. If a member has a pending request to join this team, they join automatically and ID_TEAM_BALANCER_TEAM_ASSIGNED will be returned for those members.
/// \param[in] _teamMemberLimit The new limit
/// \param[in] noTeamSubcategory Which noTeamSubcategory to assign to members that now have no team.
/// \return false On invalid or unnecessary operation. Otherwise returns true
bool SetMemberLimit(TeamMemberLimit _teamMemberLimit, NoTeamId noTeamSubcategory);
/// \return If team balancing is on, the most members that can be on this team that would not either unbalance it or exceed the value passed to SetMemberLimit(). If team balancing is off, the same as GetMemberLimitSetting()
TeamMemberLimit GetMemberLimit(void) const;
/// \return What was passed to SetMemberLimit() or the default
TeamMemberLimit GetMemberLimitSetting(void) const;
/// \brief Who can join this team under what conditions, while the team is not full
/// To not allow new joins, pass 0
/// To allow all new joins under any circumstances, bitwise-OR all permission defines.
/// For an invite-only team, use ALLOW_JOIN_SPECIFIC_TEAM only and only allow the requester to call TM_TeamMember::RequestTeam() upon invitiation through your game code.
/// Defaults to allow all
/// \param[in] _joinPermissions Bitwise combination of ALLOW_JOIN_ANY_AVAILABLE_TEAM, ALLOW_JOIN_SPECIFIC_TEAM, ALLOW_JOIN_REBALANCING
/// \return false On invalid or unnecessary operation. Otherwise returns true
bool SetJoinPermissions(JoinPermissions _joinPermissions);
/// \return Whatever was passed to SetJoinPermissions(), or the default.
JoinPermissions GetJoinPermissions(void) const;
/// \brief Removes a member from a team he or she is on
/// \details Identical to teamMember->LeaveTeam(this, noTeamSubcategory); See TeamMember::LeaveTeam() for details.
/// \param[in] teamMember Which team member to remove
/// \param[in] noTeamSubcategory If the team member has been removed from all teams, which subcategory of NoTeamId to set them to
void LeaveTeam(TM_TeamMember* teamMember, NoTeamId noTeamSubcategory);
/// \return What was passed as the \a applyBalancing parameter TM_World::ReferenceTeam() when this team was added.
bool GetBalancingApplies(void) const;
/// \param[out] All team members of this team
void GetTeamMembers(DataStructures::List<TM_TeamMember*> &_teamMembers) const;
/// \return The number of team members on this team
unsigned int GetTeamMembersCount(void) const;
/// \return A team member on this team. Members are stored in the order they are added
/// \param[in] index A value between 0 and GetTeamMembersCount()
TM_TeamMember *GetTeamMemberByIndex(unsigned int index) const;
/// \return The teamID parameter passed to TM_World::ReferenceTeam()
NetworkID GetNetworkID(void) const;
/// \return The TM_World instance that was used when calling TM_World::ReferenceTeamMember()
TM_World* GetTM_World(void) const;
/// \brief Used by the host to serialize the initial state of this object to a new system
/// \details On the host, when sending existing objects to a new system, call SerializeConstruction() on each of those objects to serialize creation state.
/// Creating the actual Team and TeamMember objects should be handled by your game code, or a system such as ReplicaManager3
void SerializeConstruction(BitStream *constructionBitstream);
/// \brief Used by non-host systems to read the bitStream written by SerializeConstruction()
/// \details On non-host systems, after creating existing objects, call DeserializeConstruction() to read and setup that object
/// Creating the actual Team and TeamMember objects should be handled by your game code, or a system such as ReplicaManager3
bool DeserializeConstruction(TeamManager *teamManager, BitStream *constructionBitstream);
/// \param[in] o Stores a void* for your own use. If using composition, this is useful to store a pointer to the containing object.
void SetOwner(void *o);
/// \return Whatever was passed to SetOwner()
void *GetOwner(void) const;
/// Return world->GetTeamIndex(this)
unsigned int GetWorldIndex(void) const;
/// \internal
static unsigned long ToUint32( const NetworkID &g );
protected:
NetworkID ID;
TM_World* world;
// Which members are on this team. The same member cannot be on the same team more than once
DataStructures::List<TM_TeamMember*> teamMembers;
// Permissions on who can join this team
JoinPermissions joinPermissions;
// Whether or not to consider this team when balancing teams
bool balancingApplies;
TeamMemberLimit teamMemberLimit;
void *owner;
// Remove input from list teamMembers
void RemoveFromTeamMemberList(TM_TeamMember *teamMember);
// Find the member index that wants to join the indicated team, is only on one team, and wants to leave that team
unsigned int GetMemberWithRequestedSingleTeamSwitch(TM_Team *team);
friend class TM_World;
friend class TM_TeamMember;
friend class TeamManager;
};
/// \brief Stores a list of teams which may be enforcing a balanced number of members
/// \details Each TM_World instance is independent of other TM_World world instances. This enables you to host multiple games on a single computer.
/// Not currently supported to have the same TM_Team or TM_TeamMember in more than one world at a time, but easily added on request.
/// \ingroup TEAM_MANAGER_GROUP
class TM_World
{
public:
TM_World();
virtual ~TM_World();
/// \return Returns the plugin that created this TM_World instance
TeamManager *GetTeamManager(void) const;
/// \brief Add a new system to send team and team member updates to.
/// \param[in] rakNetGUID GUID of the system you are adding. See Packet::rakNetGUID or RakPeerInterface::GetGUIDFromSystemAddress()
void AddParticipant(RakNetGUID rakNetGUID);
/// \brief Remove a system that was previously added with AddParticipant()
/// \details Systems that disconnect are removed automatically
/// \param[in] rakNetGUID GUID of the system you are removing. See Packet::rakNetGUID or RakPeerInterface::GetGUIDFromSystemAddress()
void RemoveParticipant(RakNetGUID rakNetGUID);
/// \brief If true, all new connections are added to this world using AddParticipant()
/// \details Defaults to true
/// \param[in] autoAdd Setting to set
void SetAutoManageConnections(bool autoAdd);
/// Get the participants added with AddParticipant()
/// \param[out] participantList Participants added with AddParticipant();
void GetParticipantList(DataStructures::List<RakNetGUID> &participantList);
/// \brief Register a TM_Team object with this system.
/// \details Your game should contain instances of TM_Team, for example by using composition with your game's Team or PlayerList class
/// Tell TeamManager about these instances using ReferenceTeam().
/// \note The destrutor of TM_Team calls DereferenceTeam() automatically.
/// \param[in] team The instance you are registering
/// \param[in] networkId Identifies this instance. This value is independent of values used by NetworkIDManager. You can use the same value as the object that contains this instance.
/// \param[in] applyBalancing Whether or not to include this team for balancing when calling SetBalanceTeams().
void ReferenceTeam(TM_Team *team, NetworkID networkId, bool applyBalancing);
/// \brief Unregisters the associated TM_Team object with this system.
/// Call when a TM_Team instance is no longer needed
/// \param[in] team Which team instance to unregister
/// \param[in] noTeamSubcategory All players on this team are kicked off. If these players then have no team, they are set to this no team category.
void DereferenceTeam(TM_Team *team, NoTeamId noTeamSubcategory);
/// \return Number of teams uniquely added with ReferenceTeam()
unsigned int GetTeamCount(void) const;
/// \param[in] index A value between 0 and GetTeamCount()
/// \return Returns whatever was passed to \a team in the function ReferenceTeam() in the order it was called.
TM_Team *GetTeamByIndex(unsigned int index) const;
/// \param[in] teamId Value passed to ReferenceTeam()
/// \return Returns whatever was passed to \a team in the function ReferenceTeam() with this NetworkID.
TM_Team *GetTeamByNetworkID(NetworkID teamId);
/// \brief Inverse of GetTeamByIndex()
/// \param[in] team Which taem
/// \return The index of the specified team, or -1 if not found
unsigned int GetTeamIndex(const TM_Team *team) const;
/// \brief Register a TM_TeamMember object with this system.
/// \details Your game should contain instances of TM_TeamMember, for example by using composition with your game's User or Player classes
/// Tell TeamManager about these instances using ReferenceTeamMember().
/// \note The destrutor of TM_TeamMember calls DereferenceTeamMember() automatically.
/// \param[in] teamMember The instance you are registering
/// \param[in] networkId Identifies this instance. This value is independent of values used by NetworkIDManager. You can use the same value as the object that contains this instance
void ReferenceTeamMember(TM_TeamMember *teamMember, NetworkID networkId);
/// \brief Unregisters the associated TM_TeamMember object with this system.
/// Call when a TM_TeamMember instance is no longer needed
/// \note This is called by the destructor of TM_TeamMember automatically, so you do not normally need to call this function
void DereferenceTeamMember(TM_TeamMember *teamMember);
/// \return Number of team members uniquely added with ReferenceTeamMember()
unsigned int GetTeamMemberCount(void) const;
/// \param[in] index A value between 0 and GetTeamMemberCount()
/// \return Returns whatever was passed to \a team in the function ReferenceTeamMember() in the order it was called.
TM_TeamMember *GetTeamMemberByIndex(unsigned int index) const;
/// \param[in] index A value between 0 and GetTeamMemberCount()
/// \return Returns whatever was passed to \a teamMemberID in the function ReferenceTeamMember() in the order it was called.
NetworkID GetTeamMemberIDByIndex(unsigned int index) const;
/// \param[in] teamId Value passed to ReferenceTeamMember()
/// \return Returns Returns whatever was passed to \a team in the function ReferenceTeamMember() with this NetworkID
TM_TeamMember *GetTeamMemberByNetworkID(NetworkID teamMemberId);
/// \brief Inverse of GetTeamMemberByIndex()
/// \param[in] team Which team member
/// \return The index of the specified team member, or -1 if not found
unsigned int GetTeamMemberIndex(const TM_TeamMember *teamMember) const;
/// \brief Force or stop forcing teams to be balanced.
/// \details For each team added with ReferenceTeam() and \a applyBalancing set to true, players on unbalanced teams will be redistributed
/// While active, players can only join balanced teams if doing so would not cause that team to become unbalanced.
/// If a player on the desired team also wants to switch, then both players will switch simultaneously. Otherwise, ID_TEAM_BALANCER_REQUESTED_TEAM_FULL will be returned to the requester and switching will occur when possible.
/// If balanceTeams is true and later set to false, players waiting on ID_TEAM_BALANCER_REQUESTED_TEAM_FULL will be able to join the desired team immediately provided it is not full.
/// \param[in] balanceTeams Whether to activate or deactivate team balancing.
/// \param[in] noTeamSubcategory If a player is kicked off a team and is no longer on any team, his or her noTeamSubcategory is set to this value
bool SetBalanceTeams(bool balanceTeams, NoTeamId noTeamSubcategory);
/// \return \a balanceTeams parameter of SetBalanceTeams(), or the default
bool GetBalanceTeams(void) const;
/// \brief Set the host that will perform balancing calculations and send notifications
/// \details Operations that can cause conflicts due to latency, such as joining teams, are operated on by the host. The result is sent to all systems added with AddParticipant()
/// For a client/server game, call SetHost() with the server's RakNetGUID value on all systems (including the server itself). If you call TeamManager::SetTopology(TM_CLIENT_SERVER), the server will also relay messages between participants.
/// For a peer to peer game, call SetHost() on the same peer when host migration occurs. Use TeamManager::SetTopology(TM_PEER_TO_PEER) in this case.
/// \note If using FullyConnectedMesh2, SetHost() is called automatically when ID_FCM2_NEW_HOST is returned.
/// \param[in] _hostGuid The host, which is the system that will serialize and resolve team disputes and calculate team balancing.
void SetHost(RakNetGUID _hostGuid);
/// \return Returns the current host, or UNASSIGNED_RAKNET_GUID if unknown
RakNetGUID GetHost(void) const;
/// \return The \a worldId passed to TeamManagr::AddWorld()
WorldId GetWorldId(void) const;
/// \brief Clear all memory and reset everything.
/// \details It is up to the user to deallocate pointers passed to ReferenceTeamMember() or ReferenceTeam(), if so desired.
void Clear(void);
/// \internal
struct JoinRequestHelper
{
SLNet::Time whenRequestMade;
unsigned int teamMemberIndex;
unsigned int indexIntoTeamsRequested;
unsigned int requestIndex;
};
/// \internal
static int JoinRequestHelperComp(const TM_World::JoinRequestHelper &key, const TM_World::JoinRequestHelper &data);
protected:
virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason );
virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming);
// Teams with too many members have those members go to other teams.
void EnforceTeamBalance(NoTeamId noTeamSubcategory);
void KickExcessMembers(NoTeamId noTeamSubcategory);
void FillRequestedSlots(void);
unsigned int GetAvailableTeamIndexWithFewestMembers(TeamMemberLimit secondaryLimit, JoinPermissions joinPermissions);
void GetSortedJoinRequests(DataStructures::OrderedList<JoinRequestHelper, JoinRequestHelper, JoinRequestHelperComp> &joinRequests);
// Send a message to all participants
void BroadcastToParticipants(SLNet::BitStream *bsOut, RakNetGUID exclusionGuid);
void BroadcastToParticipants(unsigned char *data, const int length, RakNetGUID exclusionGuid);
// 1. If can join a team:
// A. teamMember->UpdateTeamsRequestedToNone();
// B. teamMember->AddToTeamList()
// C. Return new team
// 2. Else return 0
TM_Team* JoinAnyTeam(TM_TeamMember *teamMember, int *resultCode);
int JoinSpecificTeam(TM_TeamMember *teamMember, TM_Team *team, bool isTeamSwitch, TM_Team *teamToLeave, DataStructures::List<TM_Team*> &teamsWeAreLeaving);
TeamMemberLimit GetBalancedTeamLimit(void) const;
// For fast lookup. Shares pointers with list teams
DataStructures::Hash<NetworkID, TM_Team*, 256, TM_Team::ToUint32> teamsHash;
// For fast lookup. Shares pointers with list teamMembers
DataStructures::Hash<NetworkID, TM_TeamMember*, 256, TM_TeamMember::ToUint32> teamMembersHash;
TeamManager *teamManager;
DataStructures::List<RakNetGUID> participants;
DataStructures::List<TM_Team*> teams;
DataStructures::List<TM_TeamMember*> teamMembers;
bool balanceTeamsIsActive;
RakNetGUID hostGuid;
WorldId worldId;
bool autoAddParticipants;
int teamRequestIndex;
friend class TeamManager;
friend class TM_TeamMember;
friend class TM_Team;
};
/// \brief Automates networking and list management for teams
/// \details TeamManager provides support for teams. A team is a list of team members.
/// Teams contain properties including the number of team members per team, whether or not tagged teams must have equal numbers of members, and if a team is locked or not to certain entry conditions
/// Team members contain properties including which teams they are on and which teams they want to join if a team is not immediately joinable
/// Advanced functionality includes the ability for a team member to be on multiple teams simultaneously, the ability to swap teams with other members, and the ability to resize the number of members supported per team
/// The architecture is designed for easy integration with ReplicaManager3
///
/// Usage:<BR>
/// 1. Define your game classes to represent teams and team members. Your game classes should hold game-specific information such as team name and color.<BR>
/// 2. Have those game classes contain a corresponding TM_Team or TM_TeamMember instance. Operations on teams will be performed by those instances. Use SetOwner() to refer to the parent object when using composition.<BR>
/// 3. Call TeamManager::SetTopology() for client/server or peer to peer.<BR>
/// 4. Call AddWorld() to instantiate a TM_World object which will contain references to your TM_TeamMember and TM_Team instances.<BR>
/// 5. When you instantiate a TM_TeamMember or TM_Team object, call ReferenceTeam() and ReferenceTeamMember() for each corresponding object<BR>
/// 6. When sending world state to a new connection, for example in ReplicaManager3::SerializeConstruction(), call TM_SerializeConstruction() on the corresponding TM_TeamMember and TM_Team objects. TM_Team instances on the new connection must be created before TM_TeamMember instances.<BR>
/// 7. Call TM_DeserializeConstruction() on your new corresponding TM_TeamMember and TM_Team instances.<BR>
/// 8. Execute team operations. ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED, ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED, and ID_TEAM_BALANCER_TEAM_ASSIGNED are returned to all systems when the corresponding event occurs for a team member.<BR>
/// 9. As the peer to peer session host changes, call SetHost() (Not necessary if using FullyConnectedMesh2). If using client/server, you must set the host<BR>
/// \note This replaces TeamBalancer. You cannot use TeamBalancer and TeamManager at the same time.
/// \ingroup TEAM_MANAGER_GROUP
class RAK_DLL_EXPORT TeamManager : public PluginInterface2
{
public:
// GetInstance() and DestroyInstance(instance*)
STATIC_FACTORY_DECLARATIONS(TeamManager)
TeamManager();
virtual ~TeamManager();
/// \brief Allocate a world to hold a list of teams and players for that team.
/// Use the returned TM_World object for actual team functionality.
/// \note The world is tracked by TeamManager and deallocated by calling Clear()
/// \param[in] worldId Arbitrary user-defined id of the world to create. Each world instance must have a unique id.
TM_World* AddWorld(WorldId worldId);
/// \brief Deallocate a world created with AddWorld()
/// \param[in] worldId The world to deallocate
void RemoveWorld(WorldId worldId);
/// \return Returns the number of worlds created with AddWorld()
unsigned int GetWorldCount(void) const;
/// \param[in] index A value beteween 0 and GetWorldCount()-1 inclusive.
/// \return Returns a world created with AddWorld()
TM_World* GetWorldAtIndex(unsigned int index) const;
/// \param[in] worldId \a worldId value passed to AddWorld()
/// \return Returns a world created with AddWorld(), or 0 if no such \a worldId
TM_World* GetWorldWithId(WorldId worldId) const;
/// \brief When auto managing connections, call TM_World::AddParticipant() on all worlds for all new connections automatically
/// Defaults to true
/// \note You probably want this set to false if using multiple worlds
/// \param[in] autoAdd Automatically call TM_World::AddParticipant() all worlds each new connection. Defaults to true.
void SetAutoManageConnections(bool autoAdd);
/// \brief If \a _topology is set to TM_CLIENT_SERVER, the host will relay messages to participants.
/// \details If topology is set to TM_PEER_TO_PEER, the host assumes the original message source was connected to all other participants and does not relay messages.
/// \note If TM_PEER_TO_PEER, this plugin will listen for ID_FCM2_NEW_HOST and call SetHost() on all worlds automatically
/// \note Defaults to TM_PEER_TO_PEER
/// \param[in] _topology Topology to use
void SetTopology(TMTopology _topology);
/// \brief When you get ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, pass the packet to this function to read out parameters
/// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_REQUESTED_TEAM_FULL
/// \return true on success, false on read error
void DecomposeTeamFull(Packet *packet,
TM_World **world, TM_TeamMember **teamMember, TM_Team **team,
uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions);
/// \brief When you get ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED, pass the packet to this function to read out parameters
/// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED
/// \return true on success, false on read error
void DecomposeTeamLocked(Packet *packet,
TM_World **world, TM_TeamMember **teamMember, TM_Team **team,
uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions);
/// \brief Clear all memory and reset everything.
/// \details Deallocates TM_World instances. It is up to the user to deallocate pointers passed to ReferenceTeamMember() or ReferenceTeam(), if so desired.
void Clear(void);
/// \brief Reads out the world and teamMember from ID_TEAM_BALANCER_TEAM_ASSIGNED
/// \note You can get the current and prior team list from the teamMember itself
/// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_TEAM_ASSIGNED
/// \param[out] world Set to the world this \a teamMember is on. 0 on bad lookup.
/// \param[out] teamMember Set to the teamMember affected. 0 on bad lookup.
void DecodeTeamAssigned(Packet *packet, TM_World **world, TM_TeamMember **teamMember);
// \brief Reads out the world and teamMember from ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED
/// \note You can get the requested team list from the teamMember itself
/// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED
/// \param[out] world Set to the world this \a teamMember is on. 0 on bad lookup.
/// \param[out] teamMember Set to the teamMember affected. 0 on bad lookup.
/// \param[out] teamCancelled Set to the team that was cancelled. 0 for all teams.
void DecodeTeamCancelled(Packet *packet, TM_World **world, TM_TeamMember **teamMember, TM_Team **teamCancelled);
protected:
virtual void Update(void);
virtual PluginReceiveResult OnReceive(Packet *packet);
virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason );
virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming);
void Send( const SLNet::BitStream * bitStream, const AddressOrGUID systemIdentifier, bool broadcast );
void EncodeTeamFullOrLocked(SLNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team);
void DecomposeTeamFullOrLocked(SLNet::BitStream *bsIn, TM_World **world, TM_TeamMember **teamMember, TM_Team **team,
uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions);
void ProcessTeamAssigned(SLNet::BitStream *bsIn);
void EncodeTeamAssigned(SLNet::BitStream *bitStream, TM_TeamMember *teamMember);
void RemoveFromTeamsRequestedAndAddTeam(TM_TeamMember *teamMember, TM_Team *team, bool isTeamSwitch, TM_Team *teamToLeave);
void PushTeamAssigned(TM_TeamMember *teamMember);
void PushBitStream(SLNet::BitStream *bitStream);
void OnUpdateListsToNoTeam(Packet *packet, TM_World *world);
void OnUpdateTeamsRequestedToAny(Packet *packet, TM_World *world);
void OnJoinAnyTeam(Packet *packet, TM_World *world);
void OnJoinRequestedTeam(Packet *packet, TM_World *world);
void OnUpdateTeamsRequestedToNoneAndAddTeam(Packet *packet, TM_World *world);
void OnRemoveFromTeamsRequestedAndAddTeam(Packet *packet, TM_World *world);
void OnAddToRequestedTeams(Packet *packet, TM_World *world);
bool OnRemoveFromRequestedTeams(Packet *packet, TM_World *world);
void OnLeaveTeam(Packet *packet, TM_World *world);
void OnSetMemberLimit(Packet *packet, TM_World *world);
void OnSetJoinPermissions(Packet *packet, TM_World *world);
void OnSetBalanceTeams(Packet *packet, TM_World *world);
void OnSetBalanceTeamsInitial(Packet *packet, TM_World *world);
void EncodeTeamFull(SLNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team);
void EncodeTeamLocked(SLNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team);
/// \brief When you get ID_TEAM_BALANCER_TEAM_ASSIGNED, pass the packet to this function to read out parameters
/// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_TEAM_ASSIGNED
/// \return true on success, false on read error
void DecodeTeamAssigned(SLNet::BitStream *bsIn, TM_World **world, TM_TeamMember **teamMember, NoTeamId &noTeamSubcategory,
JoinTeamType &joinTeamType, DataStructures::List<TM_Team *> &newTeam,
DataStructures::List<TM_Team *> &teamsLeft, DataStructures::List<TM_Team *> &teamsJoined);
// O(1) lookup for a given world. If I need more worlds, change this to a hash or ordered list
TM_World *worldsArray[255];
// All allocated worlds for linear traversal
DataStructures::List<TM_World*> worldsList;
bool autoAddParticipants;
TMTopology topology;
friend class TM_TeamMember;
friend class TM_World;
friend class TM_Team;
};
} // namespace SLNet
#endif // __TEAM_MANAGER_H
#endif // _RAKNET_SUPPORT_*
| 1 | 0.964464 | 1 | 0.964464 | game-dev | MEDIA | 0.487686 | game-dev,testing-qa | 0.882452 | 1 | 0.882452 |
vittorioromeo/quakevr | 10,831 | QC_other/QC_keep/drake_hook.qc | //==========================================================================
//
// GRAPPLE (Based on Rogue's, heavily modified for Drake.)
//
//==========================================================================
// Rogue Grapple Implementation
// Jan'97 by ZOID <zoid@threewave.com>
// Under contract to id software for Rogue Entertainment
// PM: Added grapple support to Drake just in case others want to use it.
// I am not too fond of the grapple since it alters fundamental gameplay
// too much. It has its uses though.
//
// Note 9/11/10: Point is moot now since Tronyn used it in some of his maps.
// Moved custom fields to defs.qc.
// draw a line to the hook
void(entity h, entity player) GrappleTrail =
{Tent_Beam (13, h, h.origin, player.origin + '0 0 16');};
void(entity h) GrappleSever =
{
local entity src;
if (!h)
return; // The world is not a hook!
src = h.master;
if (src)
if (src.hook == h)
h.count = TRUE;
};
void() GrappleReset =
{
local entity src;
src = self.master;
if (src)
if (src.hook == self)
{
src.hook = world;
if (src.weapon == IT2_GRAPPLE)
{
local float reload;
// Add delay so player has a chance to release button
// and not shoot another hook immediately.
reload = time + 0.2; // Was 0.25.
if (src.attack_finished < reload)
src.attack_finished = reload;
if (src.flags & FL_CLIENT)
src.weaponframe = 0;
}
}
remove (self);
};
float() GrappleCutCheck =
{
local vector p1, p2;
p1 = self.origin;
p2 = self.master.origin + '0 0 16';
if (vlen (p2 - p1) > self.distance)
return TRUE; // Exceeded maximum distance.
traceline (p1, p2, TRUE, self);
if (trace_fraction < 1)
return TRUE; // Not in line-of-sight.
return FALSE;
};
void() GrappleTrack =
{
local vector spray;
if (self != self.master.hook)
{remove (self); return;} // PM: Not using this hook.
// drop the hook if owner is dead or has released the button
// Update 7/11/09: ...or has left the level.
if (!self.state || self.master.health <= 0 || !self.modelindex)
{GrappleReset(); return;}
// Player always drop the hook during a cutscene.
if (cutscene)
if (self.master.flags & FLx_CREATURE == FL_CLIENT)
{GrappleReset(); return;}
// PM: Must have a clear path between hook and source.
// Do this here instead of the grapple check because this is
// called only 10/sec while the other is called more often than that.
if (GrappleCutCheck ())
{GrappleReset(); return;}
if (self.state != 2)
{
local float dflags;
if (self.enemy.solid <= SOLID_TRIGGER)
{GrappleReset(); return;} // Release insubstantial targets.
if (self.enemy.teleport_time > time)
{GrappleReset(); return;}
// move the hook along with the player. It's invisible, but
// we need this to make the sound come from the right spot
self.velocity = '0 0 0';
// if (self.enemy.flags & FL_CLIENT)
// self.origin = self.enemy.origin;
// else
self.origin = Midpoint (self.enemy); //self.enemy.origin + self.enemy.mins + self.enemy.size * 0.5
setorigin (self, self.origin);
if (self.master.tome_finished)
dflags = DF_LEECH;
else
dflags = DF_NONE;
// Use Zerstorer's chainsaw grinding noise.
sound (self, CHAN_WEAPON, "weapons/sawguts.wav", 1, ATTN_NORM); //"pendulum/hit.wav"
T_Damage (self.enemy, self, self.master, self.dmg, DAMARMOR);
// PM: Removed 'makevectors (self.v_angle)'.
spray_x = 100 * crandom();
spray_y = 100 * crandom();
spray_z = 100 * crandom() + 50;
SpawnBlood (self.enemy,self.origin, spray, 20);
}
else
self.velocity = self.enemy.velocity;
self.nextthink = time + 0.1;
};
// Tries to anchor the grapple to whatever it touches
void() GrappleAnchor =
{
local string sfx;
if (pointcontents(self.origin) == CONTENT_SKY)
{GrappleReset(); return;}
//if (Reflected_Damage (self.dmg))
// return;
if (!self.dmg)
self.dmg = 10;
if (!self.cnt)
self.cnt = 1;
self.touch = SUB_Null; // Stack overflow prevention.
if (other.takedamage || (other.solid != SOLID_BSP))
{ // PM: Removed teammate immunity.
if (other.hittype == HIT_METAL)
sfx = "weapons/clang.wav";
else if (other.hittype == HIT_STONE)
sfx = "weapons/axhitwal.wav";
else if ((self.master.hook == self) && !self.count)
sfx = "shambler/smack.wav";
else // Not grabbing, so just thump.
sfx = "zombie/z_hit.wav";
}
else
{
sfx = "player/axhit2.wav";
self.velocity = '0 0 0';
self.avelocity = '0 0 0';
}
sound (self, CHAN_AUTO, sfx, 1, ATTN_NORM);
if (other.takedamage) {
spawn_touchblood (self,other,self.dmg);
T_Damage (other, self, self.master, self.dmg, DAMARMOR);
}
// Remove the hook if one of...
// 1) Button isn't held and grappler is current weapon.
// 2) Hook hits its master, possible with reflection.
// 3) Cable was severed.
// 4) Hook isn't connected with its master.
if ( (!self.master.button0 && self.weapon == IT2_GRAPPLE)
|| (other == self.master)
|| (self.count)
|| (self.master.hook != self) )
{
if (!other.takedamage)
{
local vector org;
org = self.origin - 8*normalize(self.velocity);
Tent_Point (TE_GUNSHOT, org);
}
GrappleReset();
return;
}
// Anchored.
if (other.solid == SOLID_BSP)
self.state = 2;
else
self.state = TRUE;
self.dmg = self.cnt;
self.enemy = other; // remember this guy!
self.think = GrappleTrack;
self.nextthink = 0.01;
self.solid = SOLID_NOT;
self.touch = SUB_Null;
};
void() Grapple_Think =
{
if (self.delay < time)
{GrappleReset (); return;}
if (GrappleCutCheck ())
{
GrappleSever (self);
self.think = GrappleReset;
self.nextthink = self.delay;
}
else
self.nextthink = time + 0.1;
};
void(entity attacker, vector start, vector dir) Grapple_Launch =
{
newmis = spawn();
newmis.movetype = MOVETYPE_FLYMISSILE;
newmis.solid = SOLID_BBOX;
newmis.master = newmis.owner = attacker;
newmis.classname= "hook";
newmis.count = FALSE; // Cable is uncut.
newmis.state = FALSE; // Hook is out flying.
newmis.movedir = dir;
newmis.speed = 800;
newmis.dmg = 10;
newmis.cnt = 2; // Grind damage. Was 1.
newmis.velocity = dir * newmis.speed;
newmis.avelocity= '0 0 -500'; // PM: Enabled spin.
newmis.angles = vectoangles(dir);
newmis.touch = GrappleAnchor;
newmis.think = Grapple_Think; //GrappleReset;
// grapple only lives for X seconds, this gives max range on it
newmis.delay = time + 1.5; // Was T+2.
newmis.nextthink= 0.01;
newmis.distance = 1500; // Maximum cable range.
newmis.frame = 1; // hook spread
setall (newmis, "progs/drake/hook.mdl", '0 0 0', '0 0 0', start);
if (attacker)
attacker.hook = newmis;
};
void() W_FireGrapple =
{
if (self.hook) // reject subsequent calls from player.qc
return;
self.punchangle_x = -2; // bump him
// chain out sound (loops)
sound (self, CHAN_WEAPON, "weapons/chain1.wav", 1, ATTN_NORM);
makevectors (self.v_angle);
Grapple_Launch (self, self.origin + v_forward * 16 + '0 0 16', v_forward);
};
//- - - - - - - - -
entity(entity attacker) Grapple_Pull_Who =
{
if (attacker.hook)
{
local entity targ;
targ = attacker.hook.enemy;
if (targ.mass == MASS_LIGHT)
return targ;
if (targ.mass == MASS_MEDIUM)
return world; // No one gets pulled.
}
return attacker;
};
float() Grapple_Pull_Me =
{
if (Grapple_Pull_Who (self) == self)
return TRUE;
return FALSE;
};
// Called each frame by CLIENT.QC if client has a hook.
void() GrappleService =
{
local vector /*delta,*/ vel;
local float sped, mx;
local entity targ; // Who gets pulled.
if (!self.hook)
return;
if (self.hook.count)
return; // Already severed.
if (!self.hook.state)
{ // Hook is flying and not attached to anything yet.
// just draw a line to the hook
if (vlen(self.hook.origin - self.origin) > HOOK_NEAR)
GrappleTrail (self.hook, self);
if (!self.button0 && self.weapon == IT2_GRAPPLE)
GrappleSever (self.hook);
return;
}
// From here on, we know the hook is attached to something.
// PM: We cannot check cutscene/intermission status here because
// This function isn't called during such as intermission.
// drop the hook if player lets go of button
if ((!self.button0 && self.weapon == IT2_GRAPPLE)
|| (!(InItems2(self, IT2_GRAPPLE))) // 6/10/11: Sever if weapon is stolen.
|| self.form_active // PM: Can't use grapple while morphed.
|| (self.teleport_time > time)) {
// release when we get 'ported
if (self.hook)
SUB_Think (self.hook, GrappleReset);
return;
}
// PM: Made to changes to pulling...
// 1) Smaller monsters are pulled toward the player.
// 2) Pulling speed was greatly reduced from 1000.
targ = Grapple_Pull_Who (self);
if (targ)
{
makevectors (self.angles);
// The jump button bumps the player up a little bit.
vel = self.hook.origin - ( self.origin + (v_up * 16 *
(!self.button2)) + (v_forward * 16));
if (targ == self)
mx = SPEED_HOOK;
else // Pulling target toward attacker.
{mx = 350; vel = vel * -1;}
sped = vlen (vel) * 10;
if (sped > mx) // Was 1000 -- way too fast!
sped = mx;
// DISABLED -- Combining velocity causes more trouble than it's worth.
// vel = normalize(vel) * 80 + targ.velocity;
// if (vlen(vel) > sped)
vel = normalize(vel) * sped;
targ.velocity = vel;
targ.flags = targ.flags - (targ.flags & FL_ONGROUND);
}
if (vlen(self.hook.origin - self.origin) > HOOK_NEAR)
GrappleTrail (self.hook, self);
};
//===========================/ END OF FILE /===========================//
| 1 | 0.986051 | 1 | 0.986051 | game-dev | MEDIA | 0.98461 | game-dev | 0.995834 | 1 | 0.995834 |
Railcraft/Railcraft | 5,422 | src/main/java/mods/railcraft/common/blocks/machine/manipulator/TileDispenserCart.java | /*------------------------------------------------------------------------------
Copyright (c) CovertJaguar, 2011-2019
http://railcraft.info
This code is the property of CovertJaguar
and may only be used with explicit written
permission unless otherwise specified on the
license page at http://railcraft.info/wiki/info:license.
-----------------------------------------------------------------------------*/
package mods.railcraft.common.blocks.machine.manipulator;
import mods.railcraft.api.items.IMinecartItem;
import mods.railcraft.common.carts.CartTools;
import mods.railcraft.common.core.RailcraftConfig;
import mods.railcraft.common.gui.EnumGui;
import mods.railcraft.common.gui.GuiHandler;
import mods.railcraft.common.plugins.forge.PowerPlugin;
import mods.railcraft.common.util.entity.EntitySearcher;
import mods.railcraft.common.util.inventory.InvTools;
import mods.railcraft.common.util.inventory.wrappers.InventoryCopy;
import mods.railcraft.common.util.misc.Game;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemMinecart;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.WorldServer;
public class TileDispenserCart extends TileManipulator {
protected boolean powered;
protected int timeSinceLastSpawn;
public TileDispenserCart() {
super(3);
}
@Override
public ManipulatorVariant getMachineType() {
return ManipulatorVariant.DISPENSER_CART;
}
@Override
public boolean openGui(EntityPlayer player) {
GuiHandler.openGui(EnumGui.CART_DISPENSER, player, world, getPos());
return true;
}
@Override
public void update() {
super.update();
if (timeSinceLastSpawn < Integer.MAX_VALUE)
timeSinceLastSpawn++;
}
public void onPulse() {
EntityMinecart cart = EntitySearcher.findMinecarts().around(getPos().offset(facing)).in(world).any();
if (cart == null) {
if (timeSinceLastSpawn > RailcraftConfig.getCartDispenserMinDelay() * 20)
for (int ii = 0; ii < getSizeInventory(); ii++) {
ItemStack cartStack = getStackInSlot(ii);
if (!InvTools.isEmpty(cartStack)) {
BlockPos pos = getPos().offset(facing);
boolean minecartItem = cartStack.getItem() instanceof IMinecartItem;
if (cartStack.getItem() instanceof ItemMinecart || minecartItem) {
boolean canPlace = true;
if (minecartItem)
canPlace = ((IMinecartItem) cartStack.getItem()).canBePlacedByNonPlayer(cartStack);
if (canPlace) {
ItemStack placedStack = cartStack.copy();
EntityMinecart placedCart = CartTools.placeCart(getOwner(), placedStack, (WorldServer) world, pos);
if (placedCart != null) {
decrStackSize(ii, 1);
timeSinceLastSpawn = 0;
break;
}
}
} else {
InvTools.spewItem(cartStack, world, pos.getX(), pos.getY(), pos.getZ());
setInventorySlotContents(ii, ItemStack.EMPTY);
}
}
}
} else if (!cart.isDead && !cart.getCartItem().isEmpty()) {
InventoryCopy testInv = new InventoryCopy(this);
ItemStack cartStack = cart.getCartItem();
if (cart.hasCustomName())
cartStack.setStackDisplayName(cart.getName());
ItemStack remainder = testInv.addStack(cartStack.copy());
if (remainder.isEmpty()) {
getInventory().addStack(cartStack);
if (cart.isBeingRidden())
CartTools.removePassengers(cart);
cart.setDead();
}
}
}
@Override
public void onNeighborBlockChange(IBlockState state, Block block, BlockPos neighborPos) {
super.onNeighborBlockChange(state, block, neighborPos);
if (Game.isClient(getWorld()))
return;
boolean newPower = PowerPlugin.isBlockBeingPowered(world, getPos());
if (!powered && newPower) {
powered = true;
onPulse();
} else
powered = newPower;
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound data) {
super.writeToNBT(data);
data.setBoolean("powered", powered);
data.setInteger("time", timeSinceLastSpawn);
return data;
}
@Override
public void readFromNBT(NBTTagCompound data) {
super.readFromNBT(data);
powered = data.getBoolean("powered");
timeSinceLastSpawn = data.getInteger("time");
}
public boolean getPowered() {
return powered;
}
public void setPowered(boolean power) {
powered = power;
}
@Override
public int getInventoryStackLimit() {
return 64;
}
}
| 1 | 0.907697 | 1 | 0.907697 | game-dev | MEDIA | 0.998129 | game-dev | 0.969038 | 1 | 0.969038 |
glKarin/com.n0n3m4.diii4a | 93,481 | Q3E/src/main/jni/doom3/neo/mod/doom3/perfected/Weapon.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 "sys/platform.h"
#include "framework/DeclEntityDef.h"
#include "framework/DeclSkin.h"
#include "gamesys/SysCvar.h"
#include "ai/AI.h"
#include "Player.h"
#include "Trigger.h"
#include "SmokeParticles.h"
#include "WorldSpawn.h"
#include "Weapon.h"
/***********************************************************************
idWeapon
***********************************************************************/
//
// event defs
//
const idEventDef EV_Weapon_Clear( "<clear>" );
const idEventDef EV_Weapon_GetOwner( "getOwner", NULL, 'e' );
const idEventDef EV_Weapon_Next( "nextWeapon" );
const idEventDef EV_Weapon_State( "weaponState", "sd" );
const idEventDef EV_Weapon_UseAmmo( "useAmmo", "d" );
const idEventDef EV_Weapon_AddToClip( "addToClip", "d" );
const idEventDef EV_Weapon_AmmoInClip( "ammoInClip", NULL, 'f' );
const idEventDef EV_Weapon_AmmoAvailable( "ammoAvailable", NULL, 'f' );
const idEventDef EV_Weapon_TotalAmmoCount( "totalAmmoCount", NULL, 'f' );
const idEventDef EV_Weapon_ClipSize( "clipSize", NULL, 'f' );
const idEventDef EV_Weapon_WeaponOutOfAmmo( "weaponOutOfAmmo" );
const idEventDef EV_Weapon_WeaponReady( "weaponReady" );
const idEventDef EV_Weapon_WeaponReloading( "weaponReloading" );
const idEventDef EV_Weapon_WeaponHolstered( "weaponHolstered" );
const idEventDef EV_Weapon_WeaponRising( "weaponRising" );
const idEventDef EV_Weapon_WeaponLowering( "weaponLowering" );
const idEventDef EV_Weapon_Flashlight( "flashlight", "d" );
const idEventDef EV_Weapon_LaunchProjectiles( "launchProjectiles", "dffff" );
const idEventDef EV_Weapon_CreateProjectile( "createProjectile", NULL, 'e' );
const idEventDef EV_Weapon_EjectBrass( "ejectBrass" );
const idEventDef EV_Weapon_Melee( "melee", NULL, 'd' );
const idEventDef EV_Weapon_GetWorldModel( "getWorldModel", NULL, 'e' );
const idEventDef EV_Weapon_AllowDrop( "allowDrop", "d" );
const idEventDef EV_Weapon_AutoReload( "autoReload", NULL, 'f' );
const idEventDef EV_Weapon_NetReload( "netReload" );
const idEventDef EV_Weapon_IsInvisible( "isInvisible", NULL, 'f' );
const idEventDef EV_Weapon_IsLowered( "isLowered", NULL, 'd' ); // doomtrinity
const idEventDef EV_Weapon_NetEndReload( "netEndReload" );
//
// class def
//
CLASS_DECLARATION( idAnimatedEntity, idWeapon )
EVENT( EV_Weapon_Clear, idWeapon::Event_Clear )
EVENT( EV_Weapon_GetOwner, idWeapon::Event_GetOwner )
EVENT( EV_Weapon_State, idWeapon::Event_WeaponState )
EVENT( EV_Weapon_WeaponReady, idWeapon::Event_WeaponReady )
EVENT( EV_Weapon_WeaponOutOfAmmo, idWeapon::Event_WeaponOutOfAmmo )
EVENT( EV_Weapon_WeaponReloading, idWeapon::Event_WeaponReloading )
EVENT( EV_Weapon_WeaponHolstered, idWeapon::Event_WeaponHolstered )
EVENT( EV_Weapon_WeaponRising, idWeapon::Event_WeaponRising )
EVENT( EV_Weapon_WeaponLowering, idWeapon::Event_WeaponLowering )
EVENT( EV_Weapon_UseAmmo, idWeapon::Event_UseAmmo )
EVENT( EV_Weapon_AddToClip, idWeapon::Event_AddToClip )
EVENT( EV_Weapon_AmmoInClip, idWeapon::Event_AmmoInClip )
EVENT( EV_Weapon_AmmoAvailable, idWeapon::Event_AmmoAvailable )
EVENT( EV_Weapon_TotalAmmoCount, idWeapon::Event_TotalAmmoCount )
EVENT( EV_Weapon_ClipSize, idWeapon::Event_ClipSize )
EVENT( AI_PlayAnim, idWeapon::Event_PlayAnim )
EVENT( AI_PlayCycle, idWeapon::Event_PlayCycle )
EVENT( AI_SetBlendFrames, idWeapon::Event_SetBlendFrames )
EVENT( AI_GetBlendFrames, idWeapon::Event_GetBlendFrames )
EVENT( AI_AnimDone, idWeapon::Event_AnimDone )
EVENT( EV_Weapon_Next, idWeapon::Event_Next )
EVENT( EV_SetSkin, idWeapon::Event_SetSkin )
EVENT( EV_Weapon_Flashlight, idWeapon::Event_Flashlight )
EVENT( EV_Light_GetLightParm, idWeapon::Event_GetLightParm )
EVENT( EV_Light_SetLightParm, idWeapon::Event_SetLightParm )
EVENT( EV_Light_SetLightParms, idWeapon::Event_SetLightParms )
EVENT( EV_Weapon_LaunchProjectiles, idWeapon::Event_LaunchProjectiles )
EVENT( EV_Weapon_CreateProjectile, idWeapon::Event_CreateProjectile )
EVENT( EV_Weapon_EjectBrass, idWeapon::Event_EjectBrass )
EVENT( EV_Weapon_Melee, idWeapon::Event_Melee )
EVENT( EV_Weapon_GetWorldModel, idWeapon::Event_GetWorldModel )
EVENT( EV_Weapon_AllowDrop, idWeapon::Event_AllowDrop )
EVENT( EV_Weapon_AutoReload, idWeapon::Event_AutoReload )
EVENT( EV_Weapon_NetReload, idWeapon::Event_NetReload )
EVENT( EV_Weapon_IsInvisible, idWeapon::Event_IsInvisible )
EVENT( EV_Weapon_IsLowered, idWeapon::Event_IsLowered ) // doomtrinity
EVENT( EV_Weapon_NetEndReload, idWeapon::Event_NetEndReload )
END_CLASS
/***********************************************************************
init
***********************************************************************/
/*
================
idWeapon::idWeapon()
================
*/
idWeapon::idWeapon() {
owner = NULL;
worldModel = NULL;
weaponDef = NULL;
thread = NULL;
memset( &guiLight, 0, sizeof( guiLight ) );
memset( &muzzleFlash, 0, sizeof( muzzleFlash ) );
memset( &worldMuzzleFlash, 0, sizeof( worldMuzzleFlash ) );
memset( &nozzleGlow, 0, sizeof( nozzleGlow ) );
muzzleFlashEnd = 0;
flashColor = vec3_origin;
muzzleFlashHandle = -1;
worldMuzzleFlashHandle = -1;
guiLightHandle = -1;
nozzleGlowHandle = -1;
modelDefHandle = -1;
berserk = 2;
brassDelay = 0;
allowDrop = true;
Clear();
fl.networkSync = true;
}
/*
================
idWeapon::~idWeapon()
================
*/
idWeapon::~idWeapon() {
Clear();
delete worldModel.GetEntity();
}
/*
================
idWeapon::Spawn
================
*/
void idWeapon::Spawn( void ) {
if ( !gameLocal.isClient ) {
// setup the world model
worldModel = static_cast< idAnimatedEntity * >( gameLocal.SpawnEntityType( idAnimatedEntity::Type, NULL ) );
worldModel.GetEntity()->fl.networkSync = true;
}
thread = new idThread();
thread->ManualDelete();
thread->ManualControl();
}
/*
================
idWeapon::SetOwner
Only called at player spawn time, not each weapon switch
================
*/
void idWeapon::SetOwner( idPlayer *_owner ) {
assert( !owner );
owner = _owner;
SetName( va( "%s_weapon", owner->name.c_str() ) );
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->SetName( va( "%s_weapon_worldmodel", owner->name.c_str() ) );
}
}
/*
================
idWeapon::ShouldConstructScriptObjectAtSpawn
Called during idEntity::Spawn to see if it should construct the script object or not.
Overridden by subclasses that need to spawn the script object themselves.
================
*/
bool idWeapon::ShouldConstructScriptObjectAtSpawn( void ) const {
return false;
}
/*
================
idWeapon::CacheWeapon
================
*/
void idWeapon::CacheWeapon( const char *weaponName ) {
const idDeclEntityDef *weaponDef;
const char *brassDefName;
const char *clipModelName;
idTraceModel trm;
const char *guiName;
weaponDef = gameLocal.FindEntityDef( weaponName, false );
if ( !weaponDef ) {
return;
}
// precache the brass collision model
brassDefName = weaponDef->dict.GetString( "def_ejectBrass" );
if ( brassDefName[0] ) {
const idDeclEntityDef *brassDef = gameLocal.FindEntityDef( brassDefName, false );
if ( brassDef ) {
brassDef->dict.GetString( "clipmodel", "", &clipModelName );
if ( !clipModelName[0] ) {
clipModelName = brassDef->dict.GetString( "model" ); // use the visual model
}
// load the trace model
collisionModelManager->TrmFromModel( clipModelName, trm );
}
}
guiName = weaponDef->dict.GetString( "gui" );
if ( guiName[0] ) {
uiManager->FindGui( guiName, true, false, true );
}
}
/*
================
idWeapon::Save
================
*/
void idWeapon::Save( idSaveGame *savefile ) const {
savefile->WriteInt( status );
savefile->WriteObject( thread );
savefile->WriteString( state );
savefile->WriteString( idealState );
savefile->WriteInt( animBlendFrames );
savefile->WriteInt( animDoneTime );
savefile->WriteBool( isLinked );
savefile->WriteObject( owner );
worldModel.Save( savefile );
savefile->WriteInt( hideTime );
savefile->WriteFloat( hideDistance );
savefile->WriteInt( hideStartTime );
savefile->WriteFloat( hideStart );
savefile->WriteFloat( hideEnd );
savefile->WriteFloat( hideOffset );
savefile->WriteBool( hide );
savefile->WriteBool( disabled );
savefile->WriteInt( berserk );
savefile->WriteVec3( playerViewOrigin );
savefile->WriteMat3( playerViewAxis );
savefile->WriteVec3( viewWeaponOrigin );
savefile->WriteMat3( viewWeaponAxis );
savefile->WriteVec3( muzzleOrigin );
savefile->WriteMat3( muzzleAxis );
savefile->WriteVec3( pushVelocity );
savefile->WriteString( weaponDef->GetName() );
savefile->WriteFloat( meleeDistance );
savefile->WriteString( meleeDefName );
savefile->WriteInt( brassDelay );
savefile->WriteString( icon );
savefile->WriteInt( guiLightHandle );
savefile->WriteRenderLight( guiLight );
savefile->WriteInt( muzzleFlashHandle );
savefile->WriteRenderLight( muzzleFlash );
savefile->WriteInt( worldMuzzleFlashHandle );
savefile->WriteRenderLight( worldMuzzleFlash );
savefile->WriteVec3( flashColor );
savefile->WriteInt( muzzleFlashEnd );
savefile->WriteInt( flashTime );
savefile->WriteBool( lightOn );
savefile->WriteBool( silent_fire );
savefile->WriteInt( kick_endtime );
savefile->WriteInt( muzzle_kick_time );
savefile->WriteInt( muzzle_kick_maxtime );
savefile->WriteAngles( muzzle_kick_angles );
savefile->WriteVec3( muzzle_kick_offset );
savefile->WriteInt( ammoType );
savefile->WriteInt( ammoRequired );
savefile->WriteInt( clipSize );
savefile->WriteInt( ammoClip );
savefile->WriteInt( lowAmmo );
savefile->WriteBool( powerAmmo );
// savegames <= 17
savefile->WriteInt( 0 );
savefile->WriteInt( zoomFov );
savefile->WriteJoint( barrelJointView );
savefile->WriteJoint( flashJointView );
savefile->WriteJoint( ejectJointView );
savefile->WriteJoint( guiLightJointView );
savefile->WriteJoint( ventLightJointView );
savefile->WriteJoint( headJointView ); // doomtrinity-headanim
savefile->WriteJoint( flashJointWorld );
savefile->WriteJoint( barrelJointWorld );
savefile->WriteJoint( ejectJointWorld );
savefile->WriteBool( hasBloodSplat );
savefile->WriteSoundShader( sndHum );
savefile->WriteParticle( weaponSmoke );
savefile->WriteInt( weaponSmokeStartTime );
savefile->WriteBool( continuousSmoke );
savefile->WriteParticle( strikeSmoke );
savefile->WriteInt( strikeSmokeStartTime );
savefile->WriteVec3( strikePos );
savefile->WriteMat3( strikeAxis );
savefile->WriteInt( nextStrikeFx );
savefile->WriteBool( nozzleFx );
savefile->WriteInt( nozzleFxFade );
savefile->WriteInt( lastAttack );
savefile->WriteInt( nozzleGlowHandle );
savefile->WriteRenderLight( nozzleGlow );
savefile->WriteVec3( nozzleGlowColor );
savefile->WriteMaterial( nozzleGlowShader );
savefile->WriteFloat( nozzleGlowRadius );
savefile->WriteInt( weaponAngleOffsetAverages );
savefile->WriteFloat( weaponAngleOffsetScale );
savefile->WriteFloat( weaponAngleOffsetMax );
savefile->WriteFloat( weaponOffsetTime );
savefile->WriteFloat( weaponOffsetScale );
savefile->WriteBool( allowDrop );
savefile->WriteObject( projectileEnt );
savefile->WriteFloat( wm_hide_distance ); // sikk - Weapon Management: Awareness
}
/*
================
idWeapon::Restore
================
*/
void idWeapon::Restore( idRestoreGame *savefile ) {
savefile->ReadInt( (int &)status );
savefile->ReadObject( reinterpret_cast<idClass *&>( thread ) );
savefile->ReadString( state );
savefile->ReadString( idealState );
savefile->ReadInt( animBlendFrames );
savefile->ReadInt( animDoneTime );
savefile->ReadBool( isLinked );
// Re-link script fields
WEAPON_ATTACK.LinkTo( scriptObject, "WEAPON_ATTACK" );
WEAPON_RELOAD.LinkTo( scriptObject, "WEAPON_RELOAD" );
WEAPON_NETRELOAD.LinkTo( scriptObject, "WEAPON_NETRELOAD" );
WEAPON_NETENDRELOAD.LinkTo( scriptObject, "WEAPON_NETENDRELOAD" );
WEAPON_NETFIRING.LinkTo( scriptObject, "WEAPON_NETFIRING" );
WEAPON_RAISEWEAPON.LinkTo( scriptObject, "WEAPON_RAISEWEAPON" );
WEAPON_LOWERWEAPON.LinkTo( scriptObject, "WEAPON_LOWERWEAPON" );
savefile->ReadObject( reinterpret_cast<idClass *&>( owner ) );
worldModel.Restore( savefile );
savefile->ReadInt( hideTime );
savefile->ReadFloat( hideDistance );
savefile->ReadInt( hideStartTime );
savefile->ReadFloat( hideStart );
savefile->ReadFloat( hideEnd );
savefile->ReadFloat( hideOffset );
savefile->ReadBool( hide );
savefile->ReadBool( disabled );
savefile->ReadInt( berserk );
savefile->ReadVec3( playerViewOrigin );
savefile->ReadMat3( playerViewAxis );
savefile->ReadVec3( viewWeaponOrigin );
savefile->ReadMat3( viewWeaponAxis );
savefile->ReadVec3( muzzleOrigin );
savefile->ReadMat3( muzzleAxis );
savefile->ReadVec3( pushVelocity );
idStr objectname;
savefile->ReadString( objectname );
weaponDef = gameLocal.FindEntityDef( objectname );
meleeDef = gameLocal.FindEntityDef( weaponDef->dict.GetString( "def_melee" ), false );
const idDeclEntityDef *projectileDef = gameLocal.FindEntityDef( weaponDef->dict.GetString( "def_projectile" ), false );
if ( projectileDef ) {
projectileDict = projectileDef->dict;
} else {
projectileDict.Clear();
}
const idDeclEntityDef *brassDef = gameLocal.FindEntityDef( weaponDef->dict.GetString( "def_ejectBrass" ), false );
if ( brassDef ) {
brassDict = brassDef->dict;
} else {
brassDict.Clear();
}
savefile->ReadFloat( meleeDistance );
savefile->ReadString( meleeDefName );
savefile->ReadInt( brassDelay );
savefile->ReadString( icon );
savefile->ReadInt( guiLightHandle );
savefile->ReadRenderLight( guiLight );
// DG: we need to get a fresh handle, otherwise this will be tied to a completely unrelated light!
if ( guiLightHandle != -1 ) {
guiLightHandle = gameRenderWorld->AddLightDef( &guiLight );
}
savefile->ReadInt( muzzleFlashHandle );
savefile->ReadRenderLight( muzzleFlash );
if ( muzzleFlashHandle != -1 ) { // DG: enforce getting fresh handle
muzzleFlashHandle = gameRenderWorld->AddLightDef( &muzzleFlash );
}
savefile->ReadInt( worldMuzzleFlashHandle );
savefile->ReadRenderLight( worldMuzzleFlash );
if ( worldMuzzleFlashHandle != -1 ) { // DG: enforce getting fresh handle
worldMuzzleFlashHandle = gameRenderWorld->AddLightDef( &worldMuzzleFlash );
}
savefile->ReadVec3( flashColor );
savefile->ReadInt( muzzleFlashEnd );
savefile->ReadInt( flashTime );
savefile->ReadBool( lightOn );
savefile->ReadBool( silent_fire );
savefile->ReadInt( kick_endtime );
savefile->ReadInt( muzzle_kick_time );
savefile->ReadInt( muzzle_kick_maxtime );
savefile->ReadAngles( muzzle_kick_angles );
savefile->ReadVec3( muzzle_kick_offset );
savefile->ReadInt( (int &)ammoType );
savefile->ReadInt( ammoRequired );
savefile->ReadInt( clipSize );
savefile->ReadInt( ammoClip );
savefile->ReadInt( lowAmmo );
savefile->ReadBool( powerAmmo );
// savegame versions <= 17
int foo;
savefile->ReadInt( foo );
savefile->ReadInt( zoomFov );
savefile->ReadJoint( barrelJointView );
savefile->ReadJoint( flashJointView );
savefile->ReadJoint( ejectJointView );
savefile->ReadJoint( guiLightJointView );
savefile->ReadJoint( ventLightJointView );
savefile->ReadJoint( headJointView ); // doomtrinity-headanim
savefile->ReadJoint( flashJointWorld );
savefile->ReadJoint( barrelJointWorld );
savefile->ReadJoint( ejectJointWorld );
savefile->ReadBool( hasBloodSplat );
savefile->ReadSoundShader( sndHum );
savefile->ReadParticle( weaponSmoke );
savefile->ReadInt( weaponSmokeStartTime );
savefile->ReadBool( continuousSmoke );
savefile->ReadParticle( strikeSmoke );
savefile->ReadInt( strikeSmokeStartTime );
savefile->ReadVec3( strikePos );
savefile->ReadMat3( strikeAxis );
savefile->ReadInt( nextStrikeFx );
savefile->ReadBool( nozzleFx );
savefile->ReadInt( nozzleFxFade );
savefile->ReadInt( lastAttack );
savefile->ReadInt( nozzleGlowHandle );
savefile->ReadRenderLight( nozzleGlow );
if ( nozzleGlowHandle != -1 ) { // DG: enforce getting fresh handle
nozzleGlowHandle = gameRenderWorld->AddLightDef( &nozzleGlow );
}
savefile->ReadVec3( nozzleGlowColor );
savefile->ReadMaterial( nozzleGlowShader );
savefile->ReadFloat( nozzleGlowRadius );
savefile->ReadInt( weaponAngleOffsetAverages );
savefile->ReadFloat( weaponAngleOffsetScale );
savefile->ReadFloat( weaponAngleOffsetMax );
savefile->ReadFloat( weaponOffsetTime );
savefile->ReadFloat( weaponOffsetScale );
savefile->ReadBool( allowDrop );
savefile->ReadObject( reinterpret_cast<idClass *&>( projectileEnt ) );
savefile->ReadFloat( wm_hide_distance ); // sikk - Weapon Management: Awareness
}
/***********************************************************************
Weapon definition management
***********************************************************************/
/*
================
idWeapon::Clear
================
*/
void idWeapon::Clear( void ) {
CancelEvents( &EV_Weapon_Clear );
DeconstructScriptObject();
scriptObject.Free();
WEAPON_ATTACK.Unlink();
WEAPON_RELOAD.Unlink();
WEAPON_NETRELOAD.Unlink();
WEAPON_NETENDRELOAD.Unlink();
WEAPON_NETFIRING.Unlink();
WEAPON_RAISEWEAPON.Unlink();
WEAPON_LOWERWEAPON.Unlink();
if ( muzzleFlashHandle != -1 ) {
gameRenderWorld->FreeLightDef( muzzleFlashHandle );
muzzleFlashHandle = -1;
}
if ( muzzleFlashHandle != -1 ) {
gameRenderWorld->FreeLightDef( muzzleFlashHandle );
muzzleFlashHandle = -1;
}
if ( worldMuzzleFlashHandle != -1 ) {
gameRenderWorld->FreeLightDef( worldMuzzleFlashHandle );
worldMuzzleFlashHandle = -1;
}
if ( guiLightHandle != -1 ) {
gameRenderWorld->FreeLightDef( guiLightHandle );
guiLightHandle = -1;
}
if ( nozzleGlowHandle != -1 ) {
gameRenderWorld->FreeLightDef( nozzleGlowHandle );
nozzleGlowHandle = -1;
}
memset( &renderEntity, 0, sizeof( renderEntity ) );
renderEntity.entityNum = entityNumber;
renderEntity.noShadow = true;
renderEntity.noSelfShadow = true;
renderEntity.customSkin = NULL;
// set default shader parms
renderEntity.shaderParms[ SHADERPARM_RED ] = 1.0f;
renderEntity.shaderParms[ SHADERPARM_GREEN ]= 1.0f;
renderEntity.shaderParms[ SHADERPARM_BLUE ] = 1.0f;
renderEntity.shaderParms[3] = 1.0f;
renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = 0.0f;
renderEntity.shaderParms[5] = 0.0f;
renderEntity.shaderParms[6] = 0.0f;
renderEntity.shaderParms[7] = 0.0f;
if ( refSound.referenceSound ) {
refSound.referenceSound->Free( true );
}
memset( &refSound, 0, sizeof( refSound_t ) );
// setting diversity to 0 results in no random sound. -1 indicates random.
refSound.diversity = -1.0f;
if ( owner ) {
// don't spatialize the weapon sounds
refSound.listenerId = owner->GetListenerId();
}
// clear out the sounds from our spawnargs since we'll copy them from the weapon def
const idKeyValue *kv = spawnArgs.MatchPrefix( "snd_" );
while( kv ) {
spawnArgs.Delete( kv->GetKey() );
kv = spawnArgs.MatchPrefix( "snd_" );
}
hideTime = 300;
hideDistance = -15.0f;
hideStartTime = gameLocal.time - hideTime;
hideStart = 0.0f;
hideEnd = 0.0f;
hideOffset = 0.0f;
hide = false;
disabled = false;
weaponSmoke = NULL;
weaponSmokeStartTime = 0;
continuousSmoke = false;
strikeSmoke = NULL;
strikeSmokeStartTime = 0;
strikePos.Zero();
strikeAxis = mat3_identity;
nextStrikeFx = 0;
icon = "";
playerViewAxis.Identity();
playerViewOrigin.Zero();
viewWeaponAxis.Identity();
viewWeaponOrigin.Zero();
muzzleAxis.Identity();
muzzleOrigin.Zero();
pushVelocity.Zero();
status = WP_HOLSTERED;
state = "";
idealState = "";
animBlendFrames = 0;
animDoneTime = 0;
projectileDict.Clear();
meleeDef = NULL;
meleeDefName = "";
meleeDistance = 0.0f;
brassDict.Clear();
flashTime = 250;
lightOn = false;
silent_fire = false;
ammoType = 0;
ammoRequired = 0;
ammoClip = 0;
clipSize = 0;
lowAmmo = 0;
powerAmmo = false;
kick_endtime = 0;
muzzle_kick_time = 0;
muzzle_kick_maxtime = 0;
muzzle_kick_angles.Zero();
muzzle_kick_offset.Zero();
zoomFov = 90;
barrelJointView = INVALID_JOINT;
flashJointView = INVALID_JOINT;
ejectJointView = INVALID_JOINT;
guiLightJointView = INVALID_JOINT;
ventLightJointView = INVALID_JOINT;
headJointView = INVALID_JOINT; // doomtrinity-headanim
barrelJointWorld = INVALID_JOINT;
flashJointWorld = INVALID_JOINT;
ejectJointWorld = INVALID_JOINT;
hasBloodSplat = false;
nozzleFx = false;
nozzleFxFade = 1500;
lastAttack = 0;
nozzleGlowHandle = -1;
nozzleGlowShader = NULL;
nozzleGlowRadius = 10;
nozzleGlowColor.Zero();
weaponAngleOffsetAverages = 0;
weaponAngleOffsetScale = 0.0f;
weaponAngleOffsetMax = 0.0f;
weaponOffsetTime = 0.0f;
weaponOffsetScale = 0.0f;
allowDrop = true;
animator.ClearAllAnims( gameLocal.time, 0 );
FreeModelDef();
sndHum = NULL;
isLinked = false;
projectileEnt = NULL;
isFiring = false;
wm_hide_distance = -15; // sikk - Weapon Management: Awareness
}
/*
================
idWeapon::InitWorldModel
================
*/
void idWeapon::InitWorldModel( const idDeclEntityDef *def ) {
idEntity *ent;
ent = worldModel.GetEntity();
assert( ent );
assert( def );
const char *model = def->dict.GetString( "model_world" );
const char *attach = def->dict.GetString( "joint_attach" );
ent->SetSkin( NULL );
if ( model[0] && attach[0] ) {
ent->Show();
ent->SetModel( model );
if ( ent->GetAnimator()->ModelDef() ) {
ent->SetSkin( ent->GetAnimator()->ModelDef()->GetDefaultSkin() );
}
ent->GetPhysics()->SetContents( 0 );
ent->GetPhysics()->SetClipModel( NULL, 1.0f );
ent->BindToJoint( owner, attach, true );
ent->GetPhysics()->SetOrigin( vec3_origin );
ent->GetPhysics()->SetAxis( mat3_identity );
// supress model in player views, but allow it in mirrors and remote views
renderEntity_t *worldModelRenderEntity = ent->GetRenderEntity();
if ( worldModelRenderEntity ) {
worldModelRenderEntity->suppressSurfaceInViewID = owner->entityNumber+1;
worldModelRenderEntity->suppressShadowInViewID = owner->entityNumber+1;
worldModelRenderEntity->suppressShadowInLightID = LIGHTID_VIEW_MUZZLE_FLASH + owner->entityNumber;
}
} else {
ent->SetModel( "" );
ent->Hide();
}
flashJointWorld = ent->GetAnimator()->GetJointHandle( "flash" );
barrelJointWorld = ent->GetAnimator()->GetJointHandle( "muzzle" );
ejectJointWorld = ent->GetAnimator()->GetJointHandle( "eject" );
}
/*
================
idWeapon::GetWeaponDef
================
*/
void idWeapon::GetWeaponDef( const char *objectname, int ammoinclip ) {
const char *shader;
const char *objectType;
const char *vmodel;
const char *guiName;
const char *projectileName;
const char *brassDefName;
const char *smokeName;
int ammoAvail;
Clear();
if ( !objectname || !objectname[ 0 ] ) {
return;
}
assert( owner );
weaponDef = gameLocal.FindEntityDef( objectname );
ammoType = GetAmmoNumForName( weaponDef->dict.GetString( "ammoType" ) );
ammoRequired = weaponDef->dict.GetInt( "ammoRequired" );
// sikk---> Ammo Management: Ammo Clip Size Type
if ( g_ammoClipSizeType.GetInteger() == 1 ) {
clipSize = weaponDef->dict.GetInt( "clipSize_doom" );
} else if ( g_ammoClipSizeType.GetInteger() == 2 ) {
clipSize = weaponDef->dict.GetInt( "clipSize_custom" );
} else {
clipSize = weaponDef->dict.GetInt( "clipSize" );
}
// <---sikk
lowAmmo = weaponDef->dict.GetInt( "lowAmmo" );
icon = weaponDef->dict.GetString( "icon" );
silent_fire = weaponDef->dict.GetBool( "silent_fire" );
powerAmmo = weaponDef->dict.GetBool( "powerAmmo" );
muzzle_kick_time = SEC2MS( weaponDef->dict.GetFloat( "muzzle_kick_time" ) );
muzzle_kick_maxtime = SEC2MS( weaponDef->dict.GetFloat( "muzzle_kick_maxtime" ) );
muzzle_kick_angles = weaponDef->dict.GetAngles( "muzzle_kick_angles" );
muzzle_kick_offset = weaponDef->dict.GetVector( "muzzle_kick_offset" );
hideTime = SEC2MS( weaponDef->dict.GetFloat( "hide_time", "0.3" ) );
hideDistance = weaponDef->dict.GetFloat( "hide_distance", "-15" );
wm_hide_distance = weaponDef->dict.GetFloat( "wm_hide_distance", "-15" ); // sikk - Weapon Management: Awareness
// muzzle smoke
smokeName = weaponDef->dict.GetString( "smoke_muzzle" );
if ( *smokeName != '\0' ) {
weaponSmoke = static_cast<const idDeclParticle *>( declManager->FindType( DECL_PARTICLE, smokeName ) );
} else {
weaponSmoke = NULL;
}
continuousSmoke = weaponDef->dict.GetBool( "continuousSmoke" );
weaponSmokeStartTime = ( continuousSmoke ) ? gameLocal.time : 0;
smokeName = weaponDef->dict.GetString( "smoke_strike" );
if ( *smokeName != '\0' ) {
strikeSmoke = static_cast<const idDeclParticle *>( declManager->FindType( DECL_PARTICLE, smokeName ) );
} else {
strikeSmoke = NULL;
}
strikeSmokeStartTime = 0;
strikePos.Zero();
strikeAxis = mat3_identity;
nextStrikeFx = 0;
// setup gui light
memset( &guiLight, 0, sizeof( guiLight ) );
const char *guiLightShader = weaponDef->dict.GetString( "mtr_guiLightShader" );
if ( *guiLightShader != '\0' ) {
guiLight.shader = declManager->FindMaterial( guiLightShader, false );
guiLight.lightRadius[0] = guiLight.lightRadius[1] = guiLight.lightRadius[2] = 3;
guiLight.pointLight = true;
}
// setup the view model
vmodel = weaponDef->dict.GetString( "model_view" );
SetModel( vmodel );
// setup the world model
InitWorldModel( weaponDef );
// copy the sounds from the weapon view model def into out spawnargs
const idKeyValue *kv = weaponDef->dict.MatchPrefix( "snd_" );
while( kv ) {
spawnArgs.Set( kv->GetKey(), kv->GetValue() );
kv = weaponDef->dict.MatchPrefix( "snd_", kv );
}
// find some joints in the model for locating effects
barrelJointView = animator.GetJointHandle( "barrel" );
flashJointView = animator.GetJointHandle( "flash" );
ejectJointView = animator.GetJointHandle( "eject" );
guiLightJointView = animator.GetJointHandle( "guiLight" );
ventLightJointView = animator.GetJointHandle( "ventLight" );
headJointView = animator.GetJointHandle( "head" ); // doomtrinity-headanim
// get the projectile
projectileDict.Clear();
projectileName = weaponDef->dict.GetString( "def_projectile" );
if ( projectileName[0] != '\0' ) {
const idDeclEntityDef *projectileDef = gameLocal.FindEntityDef( projectileName, false );
if ( !projectileDef ) {
gameLocal.Warning( "Unknown projectile '%s' in weapon '%s'", projectileName, objectname );
} else {
const char *spawnclass = projectileDef->dict.GetString( "spawnclass" );
idTypeInfo *cls = idClass::GetClass( spawnclass );
if ( !cls || !cls->IsType( idProjectile::Type ) ) {
gameLocal.Warning( "Invalid spawnclass '%s' on projectile '%s' (used by weapon '%s')", spawnclass, projectileName, objectname );
} else {
projectileDict = projectileDef->dict;
}
}
}
// set up muzzleflash render light
const idMaterial*flashShader;
idVec3 flashTarget;
idVec3 flashUp;
idVec3 flashRight;
float flashRadius;
bool flashPointLight;
weaponDef->dict.GetString( "mtr_flashShader", "", &shader );
flashShader = declManager->FindMaterial( shader, false );
flashPointLight = weaponDef->dict.GetBool( "flashPointLight", "1" );
weaponDef->dict.GetVector( "flashColor", "0 0 0", flashColor );
flashRadius = (float)weaponDef->dict.GetInt( "flashRadius" ); // if 0, no light will spawn
flashTime = SEC2MS( weaponDef->dict.GetFloat( "flashTime", "0.25" ) );
flashTarget = weaponDef->dict.GetVector( "flashTarget" );
flashUp = weaponDef->dict.GetVector( "flashUp" );
flashRight = weaponDef->dict.GetVector( "flashRight" );
memset( &muzzleFlash, 0, sizeof( muzzleFlash ) );
muzzleFlash.lightId = LIGHTID_VIEW_MUZZLE_FLASH + owner->entityNumber;
muzzleFlash.allowLightInViewID = owner->entityNumber+1;
// the weapon lights will only be in first person
guiLight.allowLightInViewID = owner->entityNumber+1;
nozzleGlow.allowLightInViewID = owner->entityNumber+1;
muzzleFlash.pointLight = flashPointLight;
muzzleFlash.shader = flashShader;
muzzleFlash.shaderParms[ SHADERPARM_RED ] = flashColor[0];
muzzleFlash.shaderParms[ SHADERPARM_GREEN ] = flashColor[1];
muzzleFlash.shaderParms[ SHADERPARM_BLUE ] = flashColor[2];
muzzleFlash.shaderParms[ SHADERPARM_TIMESCALE ] = 1.0f;
muzzleFlash.lightRadius[0] = flashRadius;
muzzleFlash.lightRadius[1] = flashRadius;
muzzleFlash.lightRadius[2] = flashRadius;
if ( !flashPointLight ) {
muzzleFlash.target = flashTarget;
muzzleFlash.up = flashUp;
muzzleFlash.right = flashRight;
muzzleFlash.end = flashTarget;
}
// the world muzzle flash is the same, just positioned differently
worldMuzzleFlash = muzzleFlash;
worldMuzzleFlash.suppressLightInViewID = owner->entityNumber+1;
worldMuzzleFlash.allowLightInViewID = 0;
worldMuzzleFlash.lightId = LIGHTID_WORLD_MUZZLE_FLASH + owner->entityNumber;
//-----------------------------------
nozzleFx = weaponDef->dict.GetBool("nozzleFx");
nozzleFxFade = weaponDef->dict.GetInt("nozzleFxFade", "1500");
nozzleGlowColor = weaponDef->dict.GetVector("nozzleGlowColor", "1 1 1");
nozzleGlowRadius = weaponDef->dict.GetFloat("nozzleGlowRadius", "10");
weaponDef->dict.GetString( "mtr_nozzleGlowShader", "", &shader );
nozzleGlowShader = declManager->FindMaterial( shader, false );
// get the melee damage def
meleeDistance = weaponDef->dict.GetFloat( "melee_distance" );
meleeDefName = weaponDef->dict.GetString( "def_melee" );
if ( meleeDefName.Length() ) {
meleeDef = gameLocal.FindEntityDef( meleeDefName, false );
if ( !meleeDef ) {
gameLocal.Error( "Unknown melee '%s'", meleeDefName.c_str() );
}
}
// get the brass def
brassDict.Clear();
brassDelay = weaponDef->dict.GetInt( "ejectBrassDelay", "0" );
brassDefName = weaponDef->dict.GetString( "def_ejectBrass" );
if ( brassDefName[0] ) {
const idDeclEntityDef *brassDef = gameLocal.FindEntityDef( brassDefName, false );
if ( !brassDef ) {
gameLocal.Warning( "Unknown brass '%s'", brassDefName );
} else {
brassDict = brassDef->dict;
}
}
if ( ( ammoType < 0 ) || ( ammoType >= AMMO_NUMTYPES ) ) {
gameLocal.Warning( "Unknown ammotype in object '%s'", objectname );
}
ammoClip = ammoinclip;
if ( ( ammoClip < 0 ) || ( ammoClip > clipSize ) ) {
// first time using this weapon so have it fully loaded to start
ammoClip = clipSize;
ammoAvail = owner->inventory.HasAmmo( ammoType, ammoRequired );
if ( ammoClip > ammoAvail ) {
ammoClip = ammoAvail;
}
//doomtrinity -> //From D3XP
//In D3XP we use ammo as soon as it is moved into the clip. This allows for weapons that share ammo
owner->inventory.UseAmmo(ammoType, ammoClip);
//<- doomtrinity
}
renderEntity.gui[ 0 ] = NULL;
guiName = weaponDef->dict.GetString( "gui" );
if ( guiName[0] ) {
renderEntity.gui[ 0 ] = uiManager->FindGui( guiName, true, false, true );
}
zoomFov = weaponDef->dict.GetInt( "zoomFov", "70" );
berserk = weaponDef->dict.GetInt( "berserk", "2" );
weaponAngleOffsetAverages = weaponDef->dict.GetInt( "weaponAngleOffsetAverages", "10" );
weaponAngleOffsetScale = weaponDef->dict.GetFloat( "weaponAngleOffsetScale", "0.25" );
weaponAngleOffsetMax = weaponDef->dict.GetFloat( "weaponAngleOffsetMax", "10" );
weaponOffsetTime = weaponDef->dict.GetFloat( "weaponOffsetTime", "400" );
weaponOffsetScale = weaponDef->dict.GetFloat( "weaponOffsetScale", "0.005" );
if ( !weaponDef->dict.GetString( "weapon_scriptobject", NULL, &objectType ) ) {
gameLocal.Error( "No 'weapon_scriptobject' set on '%s'.", objectname );
}
// setup script object
if ( !scriptObject.SetType( objectType ) ) {
gameLocal.Error( "Script object '%s' not found on weapon '%s'.", objectType, objectname );
}
WEAPON_ATTACK.LinkTo( scriptObject, "WEAPON_ATTACK" );
WEAPON_RELOAD.LinkTo( scriptObject, "WEAPON_RELOAD" );
WEAPON_NETRELOAD.LinkTo( scriptObject, "WEAPON_NETRELOAD" );
WEAPON_NETENDRELOAD.LinkTo( scriptObject, "WEAPON_NETENDRELOAD" );
WEAPON_NETFIRING.LinkTo( scriptObject, "WEAPON_NETFIRING" );
WEAPON_RAISEWEAPON.LinkTo( scriptObject, "WEAPON_RAISEWEAPON" );
WEAPON_LOWERWEAPON.LinkTo( scriptObject, "WEAPON_LOWERWEAPON" );
spawnArgs = weaponDef->dict;
shader = spawnArgs.GetString( "snd_hum" );
if ( shader && *shader ) {
sndHum = declManager->FindSound( shader );
StartSoundShader( sndHum, SND_CHANNEL_BODY, 0, false, NULL );
}
isLinked = true;
// call script object's constructor
ConstructScriptObject();
// make sure we have the correct skin
UpdateSkin();
}
/***********************************************************************
GUIs
***********************************************************************/
/*
================
idWeapon::Icon
================
*/
const char *idWeapon::Icon( void ) const {
return icon;
}
/*
================
idWeapon::UpdateGUI
================
*/
void idWeapon::UpdateGUI( void ) {
if ( !renderEntity.gui[ 0 ] ) {
return;
}
if ( status == WP_HOLSTERED ) {
return;
}
if ( owner->weaponGone ) {
// dropping weapons was implemented wierd, so we have to not update the gui when it happens or we'll get a negative ammo count
return;
}
if ( gameLocal.localClientNum != owner->entityNumber ) {
// if updating the hud for a followed client
if ( gameLocal.localClientNum >= 0 && gameLocal.entities[ gameLocal.localClientNum ] && gameLocal.entities[ gameLocal.localClientNum ]->IsType( idPlayer::Type ) ) {
idPlayer *p = static_cast< idPlayer * >( gameLocal.entities[ gameLocal.localClientNum ] );
if ( !p->spectating || p->spectator != owner->entityNumber ) {
return;
}
} else {
return;
}
}
int inclip = AmmoInClip();
int ammoamount = AmmoAvailable();
if ( ammoamount < 0 ) {
// show infinite ammo
renderEntity.gui[ 0 ]->SetStateString( "player_ammo", "" );
} else {
// show remaining ammo
// sikk---> Ammo Management: Ammo Clip Size Type
if ( g_ammoClipSizeType.GetInteger() == 1 ) {
renderEntity.gui[ 0 ]->SetStateString( "player_totalammo", ClipSize() ? va( "%i", ammoamount - inclip ) : va( "%i", ammoamount ) );
renderEntity.gui[ 0 ]->SetStateString( "player_ammo", ClipSize() ? va( "%i", inclip ) : "" );
renderEntity.gui[ 0 ]->SetStateString( "player_clips", ClipSize() ? va("%i", ammoamount / ClipSize()) : "" );
} else {
renderEntity.gui[ 0 ]->SetStateString( "player_totalammo", va( "%i", ammoamount ) );// doomtrinity (D3XP)
renderEntity.gui[ 0 ]->SetStateString( "player_ammo", ClipSize() ? va( "%i", inclip ) : "--" );
renderEntity.gui[ 0 ]->SetStateString( "player_clips", ClipSize() ? va("%i", ammoamount / ClipSize()) : "--" );
}
// <---sikk
renderEntity.gui[ 0 ]->SetStateString( "player_allammo", va( "%i/%i", inclip, ammoamount ) );// doomtrinity (D3XP)
}
renderEntity.gui[ 0 ]->SetStateBool( "player_ammo_empty", ( ammoamount == 0 ) );
renderEntity.gui[ 0 ]->SetStateBool( "player_clip_empty", ( inclip == 0 ) );
renderEntity.gui[ 0 ]->SetStateBool( "player_clip_low", ( inclip <= lowAmmo ) );
//doomtrinity -> //From D3XP
//Let the HUD know the total amount of ammo regardless of the ammo required value
renderEntity.gui[ 0 ]->SetStateString( "player_ammo_count", va("%i", AmmoCount()));
//<- doomtrinity
}
/***********************************************************************
Model and muzzleflash
***********************************************************************/
/*
================
idWeapon::UpdateFlashPosition
================
*/
void idWeapon::UpdateFlashPosition( void ) {
// the flash has an explicit joint for locating it
GetGlobalJointTransform( true, flashJointView, muzzleFlash.origin, muzzleFlash.axis );
// if the desired point is inside or very close to a wall, back it up until it is clear
idVec3 start = muzzleFlash.origin - playerViewAxis[0] * 16;
idVec3 end = muzzleFlash.origin + playerViewAxis[0] * 8;
trace_t tr;
gameLocal.clip.TracePoint( tr, start, end, MASK_SHOT_RENDERMODEL, owner );
// be at least 8 units away from a solid
muzzleFlash.origin = tr.endpos - playerViewAxis[0] * 8;
// put the world muzzle flash on the end of the joint, no matter what
GetGlobalJointTransform( false, flashJointWorld, worldMuzzleFlash.origin, worldMuzzleFlash.axis );
}
/*
================
idWeapon::MuzzleFlashLight
================
*/
void idWeapon::MuzzleFlashLight( void ) {
if ( !lightOn && ( !g_muzzleFlash.GetBool() || !muzzleFlash.lightRadius[0] ) ) {
return;
}
if ( flashJointView == INVALID_JOINT ) {
return;
}
UpdateFlashPosition();
// these will be different each fire
muzzleFlash.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.time );
muzzleFlash.shaderParms[ SHADERPARM_DIVERSITY ] = renderEntity.shaderParms[ SHADERPARM_DIVERSITY ];
worldMuzzleFlash.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.time );
worldMuzzleFlash.shaderParms[ SHADERPARM_DIVERSITY ] = renderEntity.shaderParms[ SHADERPARM_DIVERSITY ];
// the light will be removed at this time
muzzleFlashEnd = gameLocal.time + flashTime;
if ( muzzleFlashHandle != -1 ) {
gameRenderWorld->UpdateLightDef( muzzleFlashHandle, &muzzleFlash );
gameRenderWorld->UpdateLightDef( worldMuzzleFlashHandle, &worldMuzzleFlash );
} else {
muzzleFlashHandle = gameRenderWorld->AddLightDef( &muzzleFlash );
worldMuzzleFlashHandle = gameRenderWorld->AddLightDef( &worldMuzzleFlash );
}
}
/*
================
idWeapon::UpdateSkin
================
*/
bool idWeapon::UpdateSkin( void ) {
const function_t *func;
if ( !isLinked ) {
return false;
}
func = scriptObject.GetFunction( "UpdateSkin" );
if ( !func ) {
common->Warning( "Can't find function 'UpdateSkin' in object '%s'", scriptObject.GetTypeName() );
return false;
}
// use the frameCommandThread since it's safe to use outside of framecommands
gameLocal.frameCommandThread->CallFunction( this, func, true );
gameLocal.frameCommandThread->Execute();
return true;
}
/*
================
idWeapon::SetModel
================
*/
void idWeapon::SetModel( const char *modelname ) {
assert( modelname );
if ( modelDefHandle >= 0 ) {
gameRenderWorld->RemoveDecals( modelDefHandle );
}
renderEntity.hModel = animator.SetModel( modelname );
if ( renderEntity.hModel ) {
renderEntity.customSkin = animator.ModelDef()->GetDefaultSkin();
animator.GetJoints( &renderEntity.numJoints, &renderEntity.joints );
} else {
renderEntity.customSkin = NULL;
renderEntity.callback = NULL;
renderEntity.numJoints = 0;
renderEntity.joints = NULL;
}
// hide the model until an animation is played
Hide();
}
/*
================
idWeapon::GetGlobalJointTransform
This returns the offset and axis of a weapon bone in world space, suitable for attaching models or lights
================
*/
bool idWeapon::GetGlobalJointTransform( bool viewModel, const jointHandle_t jointHandle, idVec3 &offset, idMat3 &axis ) {
if ( viewModel ) {
// view model
if ( animator.GetJointTransform( jointHandle, gameLocal.time, offset, axis ) ) {
offset = offset * viewWeaponAxis + viewWeaponOrigin;
axis = axis * viewWeaponAxis;
return true;
}
} else {
// world model
if ( worldModel.GetEntity() && worldModel.GetEntity()->GetAnimator()->GetJointTransform( jointHandle, gameLocal.time, offset, axis ) ) {
offset = worldModel.GetEntity()->GetPhysics()->GetOrigin() + offset * worldModel.GetEntity()->GetPhysics()->GetAxis();
axis = axis * worldModel.GetEntity()->GetPhysics()->GetAxis();
return true;
}
}
offset = viewWeaponOrigin;
axis = viewWeaponAxis;
return false;
}
/*
================
idWeapon::GetHeadAngle // doomtrinity-headanim
returns the orientation of the joint in local space
================
*/
idAngles idWeapon::GetHeadAngle( void ) {// was idVec3
idVec3 offset;
idMat3 axis;
if ( !animator.GetJointTransform( headJointView, gameLocal.time, offset, axis ) ) {
gameLocal.Warning( "Joint # %d out of range on entity '%s'", headJointView, name.c_str() );
}
idAngles ang = axis.ToAngles();
return ang;
//idVec3 vec( ang[ 0 ], ang[ 1 ], ang[ 2 ] );
//return vec;
}
/*
================
idWeapon::SetPushVelocity
================
*/
void idWeapon::SetPushVelocity( const idVec3 &pushVelocity ) {
this->pushVelocity = pushVelocity;
}
/***********************************************************************
State control/player interface
***********************************************************************/
/*
================
idWeapon::Think
================
*/
void idWeapon::Think( void ) {
// do nothing because the present is called from the player through PresentWeapon
}
/*
================
idWeapon::Raise
================
*/
void idWeapon::Raise( void ) {
if ( isLinked ) {
WEAPON_RAISEWEAPON = true;
}
}
/*
================
idWeapon::PutAway
================
*/
void idWeapon::PutAway( void ) {
hasBloodSplat = false;
if ( isLinked ) {
WEAPON_LOWERWEAPON = true;
}
}
/*
================
idWeapon::Reload
NOTE: this is only for impulse-triggered reload, auto reload is scripted
================
*/
void idWeapon::Reload( void ) {
if ( isLinked ) {
WEAPON_RELOAD = true;
}
}
/*
================
idWeapon::LowerWeapon
================
*/
void idWeapon::LowerWeapon( void ) {
if ( !hide ) {
hideStart = 0.0f;
hideEnd = owner->bWAUseHideDist ? wm_hide_distance : hideDistance; // sikk - Weapon Management: Awareness
if ( gameLocal.time - hideStartTime < hideTime ) {
hideStartTime = gameLocal.time - ( hideTime - ( gameLocal.time - hideStartTime ) );
} else {
hideStartTime = gameLocal.time;
}
hide = true;
Event_IsLowered(); // doomtrinity
}
}
/*
================
idWeapon::RaiseWeapon
================
*/
void idWeapon::RaiseWeapon( void ) {
Show();
if ( hide ) {
hideStart = owner->bWAUseHideDist ? wm_hide_distance : hideDistance; // sikk - Weapon Management: Awareness
hideEnd = 0.0f;
if ( gameLocal.time - hideStartTime < hideTime ) {
hideStartTime = gameLocal.time - ( hideTime - ( gameLocal.time - hideStartTime ) );
} else {
hideStartTime = gameLocal.time;
}
hide = false;
Event_IsLowered(); // doomtrinity
}
}
/*
================
idWeapon::HideWeapon
================
*/
void idWeapon::HideWeapon( void ) {
Hide();
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Hide();
}
muzzleFlashEnd = 0;
}
/*
================
idWeapon::ShowWeapon
================
*/
void idWeapon::ShowWeapon( void ) {
Show();
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Show();
}
if ( lightOn ) {
MuzzleFlashLight();
}
}
/*
================
idWeapon::HideWorldModel
================
*/
void idWeapon::HideWorldModel( void ) {
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Hide();
}
}
/*
================
idWeapon::ShowWorldModel
================
*/
void idWeapon::ShowWorldModel( void ) {
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Show();
}
}
/*
================
idWeapon::OwnerDied
================
*/
void idWeapon::OwnerDied( void ) {
if ( isLinked ) {
SetState( "OwnerDied", 0 );
thread->Execute();
}
Hide();
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Hide();
}
// don't clear the weapon immediately since the owner might have killed himself by firing the weapon
// within the current stack frame
PostEventMS( &EV_Weapon_Clear, 0 );
}
/*
================
idWeapon::BeginAttack
================
*/
void idWeapon::BeginAttack( void ) {
if ( status != WP_OUTOFAMMO ) {
lastAttack = gameLocal.time;
}
if ( !isLinked ) {
return;
}
if ( !WEAPON_ATTACK ) {
if ( sndHum ) {
StopSound( SND_CHANNEL_BODY, false );
}
}
WEAPON_ATTACK = true;
}
/*
================
idWeapon::EndAttack
================
*/
void idWeapon::EndAttack( void ) {
if ( !WEAPON_ATTACK.IsLinked() ) {
return;
}
if ( WEAPON_ATTACK ) {
WEAPON_ATTACK = false;
if ( sndHum ) {
StartSoundShader( sndHum, SND_CHANNEL_BODY, 0, false, NULL );
}
}
}
/*
================
idWeapon::isReady
================
*/
bool idWeapon::IsReady( void ) const {
return !hide && !IsHidden() && ( ( status == WP_RELOAD ) || ( status == WP_READY ) || ( status == WP_OUTOFAMMO ) );
}
/*
================
idWeapon::IsReloading
================
*/
bool idWeapon::IsReloading( void ) const {
return ( status == WP_RELOAD );
}
/*
================
idWeapon::IsHolstered
================
*/
bool idWeapon::IsHolstered( void ) const {
return ( status == WP_HOLSTERED );
}
/*
================
idWeapon::ShowCrosshair
================
*/
bool idWeapon::ShowCrosshair( void ) const {
return !( state == idStr( WP_RISING ) || state == idStr( WP_LOWERING ) || state == idStr( WP_HOLSTERED ) );
}
/*
=====================
idWeapon::CanDrop
=====================
*/
bool idWeapon::CanDrop( void ) const {
if ( !weaponDef || !worldModel.GetEntity() ) {
return false;
}
const char *classname = weaponDef->dict.GetString( "def_dropItem" );
if ( !classname[ 0 ] ) {
return false;
}
return true;
}
/*
================
idWeapon::WeaponStolen
================
*/
void idWeapon::WeaponStolen( void ) {
assert( !gameLocal.isClient );
if ( projectileEnt ) {
if ( isLinked ) {
SetState( "WeaponStolen", 0 );
thread->Execute();
}
projectileEnt = NULL;
}
// set to holstered so we can switch weapons right away
status = WP_HOLSTERED;
HideWeapon();
}
/*
=====================
idWeapon::DropItem
=====================
*/
idEntity * idWeapon::DropItem( const idVec3 &velocity, int activateDelay, int removeDelay, bool died ) {
if ( !weaponDef || !worldModel.GetEntity() ) {
return NULL;
}
if ( !allowDrop ) {
return NULL;
}
const char *classname = weaponDef->dict.GetString( "def_dropItem" );
if ( !classname[0] ) {
return NULL;
}
StopSound( SND_CHANNEL_BODY, true );
StopSound( SND_CHANNEL_BODY3, true );
return idMoveableItem::DropItem( classname, worldModel.GetEntity()->GetPhysics()->GetOrigin(), worldModel.GetEntity()->GetPhysics()->GetAxis(), velocity, activateDelay, removeDelay );
}
/***********************************************************************
Script state management
***********************************************************************/
/*
=====================
idWeapon::SetState
=====================
*/
void idWeapon::SetState( const char *statename, int blendFrames ) {
const function_t *func;
if ( !isLinked ) {
return;
}
func = scriptObject.GetFunction( statename );
if ( !func ) {
assert( 0 );
gameLocal.Error( "Can't find function '%s' in object '%s'", statename, scriptObject.GetTypeName() );
}
thread->CallFunction( this, func, true );
state = statename;
animBlendFrames = blendFrames;
if ( g_debugWeapon.GetBool() ) {
gameLocal.Printf( "%d: weapon state : %s\n", gameLocal.time, statename );
}
idealState = "";
}
/***********************************************************************
Particles/Effects
***********************************************************************/
/*
================
idWeapon::UpdateNozzelFx
================
*/
void idWeapon::UpdateNozzleFx( void ) {
if ( !nozzleFx ) {
return;
}
//
// shader parms
//
int la = gameLocal.time - lastAttack + 1;
float s = 1.0f;
float l = 0.0f;
if ( la < nozzleFxFade ) {
s = ((float)la / nozzleFxFade);
l = 1.0f - s;
}
renderEntity.shaderParms[5] = s;
renderEntity.shaderParms[6] = l;
if ( ventLightJointView == INVALID_JOINT ) {
return;
}
//
// vent light
//
if ( nozzleGlowHandle == -1 ) {
memset(&nozzleGlow, 0, sizeof(nozzleGlow));
if ( owner ) {
nozzleGlow.allowLightInViewID = owner->entityNumber+1;
}
nozzleGlow.pointLight = true;
nozzleGlow.noShadows = true;
nozzleGlow.lightRadius.x = nozzleGlowRadius;
nozzleGlow.lightRadius.y = nozzleGlowRadius;
nozzleGlow.lightRadius.z = nozzleGlowRadius;
nozzleGlow.shader = nozzleGlowShader;
nozzleGlow.shaderParms[ SHADERPARM_TIMESCALE ] = 1.0f;
nozzleGlow.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.time );
GetGlobalJointTransform( true, ventLightJointView, nozzleGlow.origin, nozzleGlow.axis );
nozzleGlowHandle = gameRenderWorld->AddLightDef(&nozzleGlow);
}
GetGlobalJointTransform( true, ventLightJointView, nozzleGlow.origin, nozzleGlow.axis );
nozzleGlow.shaderParms[ SHADERPARM_RED ] = nozzleGlowColor.x * s;
nozzleGlow.shaderParms[ SHADERPARM_GREEN ] = nozzleGlowColor.y * s;
nozzleGlow.shaderParms[ SHADERPARM_BLUE ] = nozzleGlowColor.z * s;
gameRenderWorld->UpdateLightDef(nozzleGlowHandle, &nozzleGlow);
}
/*
================
idWeapon::BloodSplat
================
*/
bool idWeapon::BloodSplat( float size ) {
float s, c;
idMat3 localAxis, axistemp;
idVec3 localOrigin, normal;
if ( hasBloodSplat ) {
return true;
}
hasBloodSplat = true;
if ( modelDefHandle < 0 ) {
return false;
}
if ( !GetGlobalJointTransform( true, ejectJointView, localOrigin, localAxis ) ) {
return false;
}
localOrigin[0] += gameLocal.random.RandomFloat() * -10.0f;
localOrigin[1] += gameLocal.random.RandomFloat() * 1.0f;
localOrigin[2] += gameLocal.random.RandomFloat() * -2.0f;
normal = idVec3( gameLocal.random.CRandomFloat(), -gameLocal.random.RandomFloat(), -1 );
normal.Normalize();
idMath::SinCos16( gameLocal.random.RandomFloat() * idMath::TWO_PI, s, c );
localAxis[2] = -normal;
localAxis[2].NormalVectors( axistemp[0], axistemp[1] );
localAxis[0] = axistemp[ 0 ] * c + axistemp[ 1 ] * -s;
localAxis[1] = axistemp[ 0 ] * -s + axistemp[ 1 ] * -c;
localAxis[0] *= 1.0f / size;
localAxis[1] *= 1.0f / size;
idPlane localPlane[2];
localPlane[0] = localAxis[0];
localPlane[0][3] = -(localOrigin * localAxis[0]) + 0.5f;
localPlane[1] = localAxis[1];
localPlane[1][3] = -(localOrigin * localAxis[1]) + 0.5f;
const idMaterial *mtr = declManager->FindMaterial( "textures/decals/duffysplatgun" );
gameRenderWorld->ProjectOverlay( modelDefHandle, localPlane, mtr );
return true;
}
/*
================
idWeapon::HasHeadJoint // doomtrinity-headanim
================
*/
bool idWeapon::HasHeadJoint( void ) {
if ( headJointView != INVALID_JOINT ) {
return true;
}
return false;
}
/***********************************************************************
Visual presentation
***********************************************************************/
/*
================
idWeapon::MuzzleRise
The machinegun and chaingun will incrementally back up as they are being fired
================
*/
void idWeapon::MuzzleRise( idVec3 &origin, idMat3 &axis ) {
int time;
float amount;
idAngles ang;
idVec3 offset;
time = kick_endtime - gameLocal.time;
if ( time <= 0 ) {
return;
}
if ( muzzle_kick_maxtime <= 0 ) {
return;
}
if ( time > muzzle_kick_maxtime ) {
time = muzzle_kick_maxtime;
}
amount = ( float )time / ( float )muzzle_kick_maxtime;
ang = muzzle_kick_angles * amount;
offset = muzzle_kick_offset * amount;
origin = origin - axis * offset;
axis = ang.ToMat3() * axis;
}
/*
================
idWeapon::ConstructScriptObject
Called during idEntity::Spawn. Calls the constructor on the script object.
Can be overridden by subclasses when a thread doesn't need to be allocated.
================
*/
idThread *idWeapon::ConstructScriptObject( void ) {
const function_t *constructor;
thread->EndThread();
// call script object's constructor
constructor = scriptObject.GetConstructor();
if ( !constructor ) {
gameLocal.Error( "Missing constructor on '%s' for weapon", scriptObject.GetTypeName() );
}
// init the script object's data
scriptObject.ClearObject();
thread->CallFunction( this, constructor, true );
thread->Execute();
return thread;
}
/*
================
idWeapon::DeconstructScriptObject
Called during idEntity::~idEntity. Calls the destructor on the script object.
Can be overridden by subclasses when a thread doesn't need to be allocated.
Not called during idGameLocal::MapShutdown.
================
*/
void idWeapon::DeconstructScriptObject( void ) {
const function_t *destructor;
if ( !thread ) {
return;
}
// don't bother calling the script object's destructor on map shutdown
if ( gameLocal.GameState() == GAMESTATE_SHUTDOWN ) {
return;
}
thread->EndThread();
// call script object's destructor
destructor = scriptObject.GetDestructor();
if ( destructor ) {
// start a thread that will run immediately and end
thread->CallFunction( this, destructor, true );
thread->Execute();
thread->EndThread();
}
// clear out the object's memory
scriptObject.ClearObject();
}
/*
================
idWeapon::UpdateScript
================
*/
void idWeapon::UpdateScript( void ) {
int count;
if ( !isLinked ) {
return;
}
// only update the script on new frames
if ( !gameLocal.isNewFrame ) {
return;
}
if ( idealState.Length() ) {
SetState( idealState, animBlendFrames );
}
// update script state, which may call Event_LaunchProjectiles, among other things
count = 10;
while( ( thread->Execute() || idealState.Length() ) && count-- ) {
// happens for weapons with no clip (like grenades)
if ( idealState.Length() ) {
SetState( idealState, animBlendFrames );
}
}
WEAPON_RELOAD = false;
}
/*
================
idWeapon::AlertMonsters
================
*/
void idWeapon::AlertMonsters( void ) {
trace_t tr;
idEntity *ent;
idVec3 end = muzzleFlash.origin + muzzleFlash.axis * muzzleFlash.target;
gameLocal.clip.TracePoint( tr, muzzleFlash.origin, end, CONTENTS_OPAQUE | MASK_SHOT_RENDERMODEL | CONTENTS_FLASHLIGHT_TRIGGER, owner );
if ( g_debugWeapon.GetBool() ) {
gameRenderWorld->DebugLine( colorYellow, muzzleFlash.origin, end, 0 );
gameRenderWorld->DebugArrow( colorGreen, muzzleFlash.origin, tr.endpos, 2, 0 );
}
if ( tr.fraction < 1.0f ) {
ent = gameLocal.GetTraceEntity( tr );
if ( ent->IsType( idAI::Type ) ) {
static_cast<idAI *>( ent )->TouchedByFlashlight( owner );
} else if ( ent->IsType( idTrigger::Type ) ) {
ent->Signal( SIG_TOUCH );
ent->ProcessEvent( &EV_Touch, owner, &tr );
}
}
// jitter the trace to try to catch cases where a trace down the center doesn't hit the monster
end += muzzleFlash.axis * muzzleFlash.right * idMath::Sin16( MS2SEC( gameLocal.time ) * 31.34f );
end += muzzleFlash.axis * muzzleFlash.up * idMath::Sin16( MS2SEC( gameLocal.time ) * 12.17f );
gameLocal.clip.TracePoint( tr, muzzleFlash.origin, end, CONTENTS_OPAQUE | MASK_SHOT_RENDERMODEL | CONTENTS_FLASHLIGHT_TRIGGER, owner );
if ( g_debugWeapon.GetBool() ) {
gameRenderWorld->DebugLine( colorYellow, muzzleFlash.origin, end, 0 );
gameRenderWorld->DebugArrow( colorGreen, muzzleFlash.origin, tr.endpos, 2, 0 );
}
if ( tr.fraction < 1.0f ) {
ent = gameLocal.GetTraceEntity( tr );
if ( ent->IsType( idAI::Type ) ) {
static_cast<idAI *>( ent )->TouchedByFlashlight( owner );
} else if ( ent->IsType( idTrigger::Type ) ) {
ent->Signal( SIG_TOUCH );
ent->ProcessEvent( &EV_Touch, owner, &tr );
}
}
}
/*
================
idWeapon::PresentWeapon
================
*/
void idWeapon::PresentWeapon( bool showViewModel ) {
playerViewOrigin = owner->firstPersonViewOrigin;
playerViewAxis = owner->firstPersonViewAxis;
// calculate weapon position based on player movement bobbing
owner->CalculateViewWeaponPos( viewWeaponOrigin, viewWeaponAxis );
// hide offset is for dropping the gun when approaching a GUI or NPC
// This is simpler to manage than doing the weapon put-away animation
if ( gameLocal.time - hideStartTime < hideTime ) {
float frac = ( float )( gameLocal.time - hideStartTime ) / ( float )hideTime;
if ( hideStart < hideEnd ) {
frac = 1.0f - frac;
frac = 1.0f - frac * frac;
} else {
frac = frac * frac;
}
hideOffset = hideStart + ( hideEnd - hideStart ) * frac;
} else {
hideOffset = hideEnd;
if ( hide && disabled ) {
Hide();
}
}
viewWeaponOrigin += hideOffset * viewWeaponAxis[ 2 ];
// kick up based on repeat firing
MuzzleRise( viewWeaponOrigin, viewWeaponAxis );
// set the physics position and orientation
GetPhysics()->SetOrigin( viewWeaponOrigin );
GetPhysics()->SetAxis( viewWeaponAxis );
UpdateVisuals();
// update the weapon script
UpdateScript();
UpdateGUI();
// update animation
UpdateAnimation();
// only show the surface in player view
renderEntity.allowSurfaceInViewID = owner->entityNumber+1;
// crunch the depth range so it never pokes into walls this breaks the machine gun gui
renderEntity.weaponDepthHack = true;
// present the model
if ( showViewModel ) {
Present();
} else {
FreeModelDef();
}
if ( worldModel.GetEntity() && worldModel.GetEntity()->GetRenderEntity() ) {
// deal with the third-person visible world model
// don't show shadows of the world model in first person
if ( gameLocal.isMultiplayer || g_showPlayerShadow.GetBool() || pm_thirdPerson.GetBool() ) {
worldModel.GetEntity()->GetRenderEntity()->suppressShadowInViewID = 0;
} else {
worldModel.GetEntity()->GetRenderEntity()->suppressShadowInViewID = owner->entityNumber+1;
worldModel.GetEntity()->GetRenderEntity()->suppressShadowInLightID = LIGHTID_VIEW_MUZZLE_FLASH + owner->entityNumber;
}
}
if ( nozzleFx ) {
UpdateNozzleFx();
}
// muzzle smoke
if ( showViewModel && !disabled && weaponSmoke && ( weaponSmokeStartTime != 0 ) ) {
// use the barrel joint if available
if ( barrelJointView ) {
GetGlobalJointTransform( true, barrelJointView, muzzleOrigin, muzzleAxis );
} else {
// default to going straight out the view
muzzleOrigin = playerViewOrigin;
muzzleAxis = playerViewAxis;
}
// spit out a particle
if ( !gameLocal.smokeParticles->EmitSmoke( weaponSmoke, weaponSmokeStartTime, gameLocal.random.RandomFloat(), muzzleOrigin, muzzleAxis ) ) {
weaponSmokeStartTime = ( continuousSmoke ) ? gameLocal.time : 0;
}
}
if ( showViewModel && strikeSmoke && strikeSmokeStartTime != 0 ) {
// spit out a particle
if ( !gameLocal.smokeParticles->EmitSmoke( strikeSmoke, strikeSmokeStartTime, gameLocal.random.RandomFloat(), strikePos, strikeAxis ) ) {
strikeSmokeStartTime = 0;
}
}
// remove the muzzle flash light when it's done
if ( ( !lightOn && ( gameLocal.time >= muzzleFlashEnd ) ) || IsHidden() ) {
if ( muzzleFlashHandle != -1 ) {
gameRenderWorld->FreeLightDef( muzzleFlashHandle );
muzzleFlashHandle = -1;
}
if ( worldMuzzleFlashHandle != -1 ) {
gameRenderWorld->FreeLightDef( worldMuzzleFlashHandle );
worldMuzzleFlashHandle = -1;
}
}
// update the muzzle flash light, so it moves with the gun
if ( muzzleFlashHandle != -1 ) {
UpdateFlashPosition();
gameRenderWorld->UpdateLightDef( muzzleFlashHandle, &muzzleFlash );
gameRenderWorld->UpdateLightDef( worldMuzzleFlashHandle, &worldMuzzleFlash );
// wake up monsters with the flashlight
if ( !gameLocal.isMultiplayer && lightOn && !owner->fl.notarget ) {
AlertMonsters();
}
}
// update the gui light
if ( guiLight.lightRadius[0] && guiLightJointView != INVALID_JOINT ) {
GetGlobalJointTransform( true, guiLightJointView, guiLight.origin, guiLight.axis );
if ( ( guiLightHandle != -1 ) ) {
gameRenderWorld->UpdateLightDef( guiLightHandle, &guiLight );
} else {
guiLightHandle = gameRenderWorld->AddLightDef( &guiLight );
}
}
if ( status != WP_READY && sndHum ) {
StopSound( SND_CHANNEL_BODY, false );
}
UpdateSound();
}
/*
================
idWeapon::EnterCinematic
================
*/
void idWeapon::EnterCinematic( void ) {
StopSound( SND_CHANNEL_ANY, false );
if ( isLinked ) {
SetState( "EnterCinematic", 0 );
thread->Execute();
WEAPON_ATTACK = false;
WEAPON_RELOAD = false;
WEAPON_NETRELOAD = false;
WEAPON_NETENDRELOAD = false;
WEAPON_NETFIRING = false;
WEAPON_RAISEWEAPON = false;
WEAPON_LOWERWEAPON = false;
}
disabled = true;
LowerWeapon();
}
/*
================
idWeapon::ExitCinematic
================
*/
void idWeapon::ExitCinematic( void ) {
disabled = false;
if ( isLinked ) {
SetState( "ExitCinematic", 0 );
thread->Execute();
}
RaiseWeapon();
}
/*
================
idWeapon::NetCatchup
================
*/
void idWeapon::NetCatchup( void ) {
if ( isLinked ) {
SetState( "NetCatchup", 0 );
thread->Execute();
}
}
/*
================
idWeapon::GetZoomFov
================
*/
int idWeapon::GetZoomFov( void ) {
return zoomFov;
}
/*
================
idWeapon::GetWeaponAngleOffsets
================
*/
void idWeapon::GetWeaponAngleOffsets( int *average, float *scale, float *max ) {
*average = weaponAngleOffsetAverages;
*scale = weaponAngleOffsetScale;
*max = weaponAngleOffsetMax;
}
/*
================
idWeapon::GetWeaponTimeOffsets
================
*/
void idWeapon::GetWeaponTimeOffsets( float *time, float *scale ) {
*time = weaponOffsetTime;
*scale = weaponOffsetScale;
}
/***********************************************************************
Ammo
***********************************************************************/
/*
================
idWeapon::GetAmmoNumForName
================
*/
ammo_t idWeapon::GetAmmoNumForName( const char *ammoname ) {
int num;
const idDict *ammoDict;
assert( ammoname );
ammoDict = gameLocal.FindEntityDefDict( "ammo_types", false );
if ( !ammoDict ) {
gameLocal.Error( "Could not find entity definition for 'ammo_types'\n" );
}
if ( !ammoname[ 0 ] ) {
return 0;
}
if ( !ammoDict->GetInt( ammoname, "-1", num ) ) {
gameLocal.Error( "Unknown ammo type '%s'", ammoname );
}
if ( ( num < 0 ) || ( num >= AMMO_NUMTYPES ) ) {
gameLocal.Error( "Ammo type '%s' value out of range. Maximum ammo types is %d.\n", ammoname, AMMO_NUMTYPES );
}
return ( ammo_t )num;
}
/*
================
idWeapon::GetAmmoNameForNum
================
*/
const char *idWeapon::GetAmmoNameForNum( ammo_t ammonum ) {
int i;
int num;
const idDict *ammoDict;
const idKeyValue *kv;
char text[ 32 ];
ammoDict = gameLocal.FindEntityDefDict( "ammo_types", false );
if ( !ammoDict ) {
gameLocal.Error( "Could not find entity definition for 'ammo_types'\n" );
}
sprintf( text, "%d", ammonum );
num = ammoDict->GetNumKeyVals();
for( i = 0; i < num; i++ ) {
kv = ammoDict->GetKeyVal( i );
if ( kv->GetValue() == text ) {
return kv->GetKey();
}
}
return NULL;
}
/*
================
idWeapon::GetAmmoPickupNameForNum
================
*/
const char *idWeapon::GetAmmoPickupNameForNum( ammo_t ammonum ) {
int i;
int num;
const idDict *ammoDict;
const idKeyValue *kv;
ammoDict = gameLocal.FindEntityDefDict( "ammo_names", false );
if ( !ammoDict ) {
gameLocal.Error( "Could not find entity definition for 'ammo_names'\n" );
}
const char *name = GetAmmoNameForNum( ammonum );
if ( name && *name ) {
num = ammoDict->GetNumKeyVals();
for( i = 0; i < num; i++ ) {
kv = ammoDict->GetKeyVal( i );
if ( idStr::Icmp( kv->GetKey(), name) == 0 ) {
return kv->GetValue();
}
}
}
return "";
}
/*
================
idWeapon::AmmoAvailable
================
*/
int idWeapon::AmmoAvailable( void ) const {
if ( owner ) {
return owner->inventory.HasAmmo( ammoType, ammoRequired );
} else {
return 0;
}
}
/*
================
idWeapon::AmmoInClip
================
*/
int idWeapon::AmmoInClip( void ) const {
// sikk---> Ammo Management: Ammo Clip Size Type
if ( !clipSize ) {
return AmmoAvailable();
}
// <---sikk
return ammoClip;
}
/*
================
idWeapon::ResetAmmoClip
================
*/
void idWeapon::ResetAmmoClip( void ) {
ammoClip = -1;
}
/*
================
idWeapon::GetAmmoType
================
*/
ammo_t idWeapon::GetAmmoType( void ) const {
return ammoType;
}
/*
================
idWeapon::ClipSize
================
*/
int idWeapon::ClipSize( void ) const {
return clipSize;
}
/*
================
idWeapon::LowAmmo
================
*/
int idWeapon::LowAmmo() const {
return lowAmmo;
}
/*
================
idWeapon::AmmoRequired
================
*/
int idWeapon::AmmoRequired( void ) const {
return ammoRequired;
}
//doomtrinity -> //From D3XP
/*
================
idWeapon::AmmoCount
Returns the total number of rounds regardless of the required ammo
================
*/
int idWeapon::AmmoCount() const {
if ( owner ) {
return owner->inventory.HasAmmo( ammoType, 1 );
} else {
return 0;
}
}
//<- doomtrinity
/*
================
idWeapon::WriteToSnapshot
================
*/
void idWeapon::WriteToSnapshot( idBitMsgDelta &msg ) const {
msg.WriteBits( ammoClip, ASYNC_PLAYER_INV_CLIP_BITS );
msg.WriteBits( worldModel.GetSpawnId(), 32 );
msg.WriteBits( lightOn, 1 );
msg.WriteBits( isFiring ? 1 : 0, 1 );
}
/*
================
idWeapon::ReadFromSnapshot
================
*/
void idWeapon::ReadFromSnapshot( const idBitMsgDelta &msg ) {
ammoClip = msg.ReadBits( ASYNC_PLAYER_INV_CLIP_BITS );
worldModel.SetSpawnId( msg.ReadBits( 32 ) );
bool snapLight = msg.ReadBits( 1 ) != 0;
isFiring = msg.ReadBits( 1 ) != 0;
// WEAPON_NETFIRING is only turned on for other clients we're predicting. not for local client
if ( owner && gameLocal.localClientNum != owner->entityNumber && WEAPON_NETFIRING.IsLinked() ) {
// immediately go to the firing state so we don't skip fire animations
if ( !WEAPON_NETFIRING && isFiring ) {
idealState = "Fire";
}
// immediately switch back to idle
if ( WEAPON_NETFIRING && !isFiring ) {
idealState = "Idle";
}
WEAPON_NETFIRING = isFiring;
}
if ( snapLight != lightOn ) {
Reload();
}
}
/*
================
idWeapon::ClientReceiveEvent
================
*/
bool idWeapon::ClientReceiveEvent( int event, int time, const idBitMsg &msg ) {
switch( event ) {
case EVENT_RELOAD: {
if ( gameLocal.time - time < 1000 ) {
if ( WEAPON_NETRELOAD.IsLinked() ) {
WEAPON_NETRELOAD = true;
WEAPON_NETENDRELOAD = false;
}
}
return true;
}
case EVENT_ENDRELOAD: {
if ( WEAPON_NETENDRELOAD.IsLinked() ) {
WEAPON_NETENDRELOAD = true;
}
return true;
}
case EVENT_CHANGESKIN: {
int index = gameLocal.ClientRemapDecl( DECL_SKIN, msg.ReadInt() );
renderEntity.customSkin = ( index != -1 ) ? static_cast<const idDeclSkin *>( declManager->DeclByIndex( DECL_SKIN, index ) ) : NULL;
UpdateVisuals();
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->SetSkin( renderEntity.customSkin );
}
return true;
}
default:
break;
}
return idEntity::ClientReceiveEvent( event, time, msg );
}
/***********************************************************************
Script events
***********************************************************************/
/*
===============
idWeapon::Event_Clear
===============
*/
void idWeapon::Event_Clear( void ) {
Clear();
}
/*
===============
idWeapon::Event_GetOwner
===============
*/
void idWeapon::Event_GetOwner( void ) {
idThread::ReturnEntity( owner );
}
/*
===============
idWeapon::Event_WeaponState
===============
*/
void idWeapon::Event_WeaponState( const char *statename, int blendFrames ) {
const function_t *func;
// idStr inv_weapon; // doomtrinity-dual weapon test
// float result; // doomtrinity-dual weapon test
func = scriptObject.GetFunction( statename );
if ( !func ) {
assert( 0 );
gameLocal.Error( "Can't find function '%s' in object '%s'", statename, scriptObject.GetTypeName() );
}
idealState = statename;
if ( !idealState.Icmp( "Fire" ) ) {
isFiring = true;
} else {
isFiring = false;
}
// doomtrinity-dual weapon test->
// inv_weapon = spawnArgs.GetString( va("inv_weapon") );
// gameLocal.persistentLevelInfo.GetFloat( "player1_pistol_single", "0", result );
//
// if ( ( inv_weapon == "weapon_pistol" ) && ( !idealState.Icmp( "Raise" ) ) && !result ) {
// gameLocal.Printf( "raise pistol!\n" );
// }
// doomtrinity-dual weapon test-<
animBlendFrames = blendFrames;
thread->DoneProcessing();
}
/*
===============
idWeapon::Event_WeaponReady
===============
*/
void idWeapon::Event_WeaponReady( void ) {
status = WP_READY;
if ( isLinked ) {
WEAPON_RAISEWEAPON = false;
}
if ( sndHum ) {
StartSoundShader( sndHum, SND_CHANNEL_BODY, 0, false, NULL );
}
}
/*
===============
idWeapon::Event_WeaponOutOfAmmo
===============
*/
void idWeapon::Event_WeaponOutOfAmmo( void ) {
status = WP_OUTOFAMMO;
if ( isLinked ) {
WEAPON_RAISEWEAPON = false;
}
}
/*
===============
idWeapon::Event_WeaponReloading
===============
*/
void idWeapon::Event_WeaponReloading( void ) {
status = WP_RELOAD;
}
/*
===============
idWeapon::Event_WeaponHolstered
===============
*/
void idWeapon::Event_WeaponHolstered( void ) {
status = WP_HOLSTERED;
if ( isLinked ) {
WEAPON_LOWERWEAPON = false;
}
}
/*
===============
idWeapon::Event_WeaponRising
===============
*/
void idWeapon::Event_WeaponRising( void ) {
status = WP_RISING;
if ( isLinked ) {
WEAPON_LOWERWEAPON = false;
}
owner->WeaponRisingCallback();
}
/*
===============
idWeapon::Event_WeaponLowering
===============
*/
void idWeapon::Event_WeaponLowering( void ) {
status = WP_LOWERING;
if ( isLinked ) {
WEAPON_RAISEWEAPON = false;
}
owner->WeaponLoweringCallback();
}
/*
===============
idWeapon::Event_UseAmmo
===============
*/
void idWeapon::Event_UseAmmo( int amount ) {
if ( gameLocal.isClient ) {
return;
}
//owner->inventory.UseAmmo( ammoType, ( powerAmmo ) ? amount : ( amount * ammoRequired ) ); // Commented out, now this event works as it should. // doomtrinity
if ( clipSize && ammoRequired ) {
ammoClip -= powerAmmo ? amount : ( amount * ammoRequired );
if ( ammoClip < 0 ) {
ammoClip = 0;
}
}
}
/*
===============
idWeapon::Event_AddToClip
===============
*/
void idWeapon::Event_AddToClip( int amount ) {
int ammoAvail;
if ( gameLocal.isClient ) {
return;
}
//doomtrinity -> //From D3XP
int oldAmmo = ammoClip;
ammoAvail = owner->inventory.HasAmmo( ammoType, ammoRequired ) + AmmoInClip();
//<- doomtrinity
ammoClip += amount;
if ( ammoClip > clipSize ) {
ammoClip = clipSize;
}
//ammoAvail = owner->inventory.HasAmmo( ammoType, ammoRequired );// doomtrinity (D3XP)
if ( ammoClip > ammoAvail ) {
ammoClip = ammoAvail;
}
//doomtrinity -> //From D3XP
// for shared ammo we need to use the ammo when it is moved into the clip
int usedAmmo = ammoClip - oldAmmo;
owner->inventory.UseAmmo(ammoType, usedAmmo);
//<- doomtrinity
}
/*
===============
idWeapon::Event_AmmoInClip
===============
*/
void idWeapon::Event_AmmoInClip( void ) {
int ammo = AmmoInClip();
idThread::ReturnFloat( ammo );
}
/*
===============
idWeapon::Event_AmmoAvailable
===============
*/
void idWeapon::Event_AmmoAvailable( void ) {
int ammoAvail = owner->inventory.HasAmmo( ammoType, ammoRequired );
ammoAvail += AmmoInClip();// doomtrinity (D3XP)
idThread::ReturnFloat( ammoAvail );
}
/*
===============
idWeapon::Event_TotalAmmoCount
===============
*/
void idWeapon::Event_TotalAmmoCount( void ) {
int ammoAvail = owner->inventory.HasAmmo( ammoType, 1 );
idThread::ReturnFloat( ammoAvail );
}
/*
===============
idWeapon::Event_ClipSize
===============
*/
void idWeapon::Event_ClipSize( void ) {
idThread::ReturnFloat( clipSize );
}
/*
===============
idWeapon::Event_AutoReload
===============
*/
void idWeapon::Event_AutoReload( void ) {
assert( owner );
if ( gameLocal.isClient ) {
idThread::ReturnFloat( 0.0f );
return;
}
idThread::ReturnFloat( gameLocal.userInfo[ owner->entityNumber ].GetBool( "ui_autoReload" ) );
}
/*
===============
idWeapon::Event_NetReload
===============
*/
void idWeapon::Event_NetReload( void ) {
assert( owner );
if ( gameLocal.isServer ) {
ServerSendEvent( EVENT_RELOAD, NULL, false, -1 );
}
}
/*
===============
idWeapon::Event_NetEndReload
===============
*/
void idWeapon::Event_NetEndReload( void ) {
assert( owner );
if ( gameLocal.isServer ) {
ServerSendEvent( EVENT_ENDRELOAD, NULL, false, -1 );
}
}
/*
===============
idWeapon::Event_PlayAnim
===============
*/
void idWeapon::Event_PlayAnim( int channel, const char *animname ) {
int anim;
anim = animator.GetAnim( animname );
if ( !anim ) {
gameLocal.Warning( "missing '%s' animation on '%s' (%s)", animname, name.c_str(), GetEntityDefName() );
animator.Clear( channel, gameLocal.time, FRAME2MS( animBlendFrames ) );
animDoneTime = 0;
} else {
if ( !( owner && owner->GetInfluenceLevel() ) ) {
Show();
}
animator.PlayAnim( channel, anim, gameLocal.time, FRAME2MS( animBlendFrames ) );
animDoneTime = animator.CurrentAnim( channel )->GetEndTime();
if ( worldModel.GetEntity() ) {
anim = worldModel.GetEntity()->GetAnimator()->GetAnim( animname );
if ( anim ) {
worldModel.GetEntity()->GetAnimator()->PlayAnim( channel, anim, gameLocal.time, FRAME2MS( animBlendFrames ) );
}
}
}
animBlendFrames = 0;
idThread::ReturnInt( 0 );
}
/*
===============
idWeapon::Event_PlayCycle
===============
*/
void idWeapon::Event_PlayCycle( int channel, const char *animname ) {
int anim;
anim = animator.GetAnim( animname );
if ( !anim ) {
gameLocal.Warning( "missing '%s' animation on '%s' (%s)", animname, name.c_str(), GetEntityDefName() );
animator.Clear( channel, gameLocal.time, FRAME2MS( animBlendFrames ) );
animDoneTime = 0;
} else {
if ( !( owner && owner->GetInfluenceLevel() ) ) {
Show();
}
animator.CycleAnim( channel, anim, gameLocal.time, FRAME2MS( animBlendFrames ) );
animDoneTime = animator.CurrentAnim( channel )->GetEndTime();
if ( worldModel.GetEntity() ) {
anim = worldModel.GetEntity()->GetAnimator()->GetAnim( animname );
worldModel.GetEntity()->GetAnimator()->CycleAnim( channel, anim, gameLocal.time, FRAME2MS( animBlendFrames ) );
}
}
animBlendFrames = 0;
idThread::ReturnInt( 0 );
}
/*
===============
idWeapon::Event_AnimDone
===============
*/
void idWeapon::Event_AnimDone( int channel, int blendFrames ) {
if ( animDoneTime - FRAME2MS( blendFrames ) <= gameLocal.time ) {
idThread::ReturnInt( true );
} else {
idThread::ReturnInt( false );
}
}
/*
===============
idWeapon::Event_SetBlendFrames
===============
*/
void idWeapon::Event_SetBlendFrames( int channel, int blendFrames ) {
animBlendFrames = blendFrames;
}
/*
===============
idWeapon::Event_GetBlendFrames
===============
*/
void idWeapon::Event_GetBlendFrames( int channel ) {
idThread::ReturnInt( animBlendFrames );
}
/*
================
idWeapon::Event_Next
================
*/
void idWeapon::Event_Next( void ) {
// change to another weapon if possible
owner->NextBestWeapon();
}
/*
================
idWeapon::Event_SetSkin
================
*/
void idWeapon::Event_SetSkin( const char *skinname ) {
const idDeclSkin *skinDecl;
if ( !skinname || !skinname[ 0 ] ) {
skinDecl = NULL;
} else {
skinDecl = declManager->FindSkin( skinname );
}
renderEntity.customSkin = skinDecl;
UpdateVisuals();
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->SetSkin( skinDecl );
}
if ( gameLocal.isServer ) {
idBitMsg msg;
byte msgBuf[MAX_EVENT_PARAM_SIZE];
msg.Init( msgBuf, sizeof( msgBuf ) );
msg.WriteInt( ( skinDecl != NULL ) ? gameLocal.ServerRemapDecl( -1, DECL_SKIN, skinDecl->Index() ) : -1 );
ServerSendEvent( EVENT_CHANGESKIN, &msg, false, -1 );
}
}
/*
================
idWeapon::Event_Flashlight
================
*/
void idWeapon::Event_Flashlight( int enable ) {
if ( enable ) {
lightOn = true;
MuzzleFlashLight();
} else {
lightOn = false;
muzzleFlashEnd = 0;
}
}
/*
================
idWeapon::Event_GetLightParm
================
*/
void idWeapon::Event_GetLightParm( int parmnum ) {
if ( ( parmnum < 0 ) || ( parmnum >= MAX_ENTITY_SHADER_PARMS ) ) {
gameLocal.Error( "shader parm index (%d) out of range", parmnum );
}
idThread::ReturnFloat( muzzleFlash.shaderParms[ parmnum ] );
}
/*
================
idWeapon::Event_SetLightParm
================
*/
void idWeapon::Event_SetLightParm( int parmnum, float value ) {
if ( ( parmnum < 0 ) || ( parmnum >= MAX_ENTITY_SHADER_PARMS ) ) {
gameLocal.Error( "shader parm index (%d) out of range", parmnum );
}
muzzleFlash.shaderParms[ parmnum ] = value;
worldMuzzleFlash.shaderParms[ parmnum ] = value;
UpdateVisuals();
}
/*
================
idWeapon::Event_SetLightParms
================
*/
void idWeapon::Event_SetLightParms( float parm0, float parm1, float parm2, float parm3 ) {
muzzleFlash.shaderParms[ SHADERPARM_RED ] = parm0;
muzzleFlash.shaderParms[ SHADERPARM_GREEN ] = parm1;
muzzleFlash.shaderParms[ SHADERPARM_BLUE ] = parm2;
muzzleFlash.shaderParms[ SHADERPARM_ALPHA ] = parm3;
worldMuzzleFlash.shaderParms[ SHADERPARM_RED ] = parm0;
worldMuzzleFlash.shaderParms[ SHADERPARM_GREEN ] = parm1;
worldMuzzleFlash.shaderParms[ SHADERPARM_BLUE ] = parm2;
worldMuzzleFlash.shaderParms[ SHADERPARM_ALPHA ] = parm3;
UpdateVisuals();
}
/*
================
idWeapon::Event_CreateProjectile
================
*/
void idWeapon::Event_CreateProjectile( void ) {
if ( !gameLocal.isClient ) {
projectileEnt = NULL;
gameLocal.SpawnEntityDef( projectileDict, &projectileEnt, false );
if ( projectileEnt ) {
projectileEnt->SetOrigin( GetPhysics()->GetOrigin() );
projectileEnt->Bind( owner, false );
projectileEnt->Hide();
}
idThread::ReturnEntity( projectileEnt );
} else {
idThread::ReturnEntity( NULL );
}
}
/*
================
idWeapon::Event_LaunchProjectiles
================
*/
void idWeapon::Event_LaunchProjectiles( int num_projectiles, float spread, float fuseOffset, float launchPower, float dmgPower ) {
idProjectile *proj;
idEntity *ent;
int i;
idVec3 dir;
float ang;
float spin;
float distance;
trace_t tr;
idVec3 start;
idVec3 muzzle_pos;
idBounds ownerBounds, projBounds;
if ( IsHidden() ) {
return;
}
if ( !projectileDict.GetNumKeyVals() ) {
const char *classname = weaponDef->dict.GetString( "classname" );
gameLocal.Warning( "No projectile defined on '%s'", classname );
return;
}
// avoid all ammo considerations on an MP client
if ( !gameLocal.isClient ) {
//doomtrinity -> //From D3XP
int ammoAvail = owner->inventory.HasAmmo( ammoType, ammoRequired );
if ( ( clipSize != 0 ) && ( ammoClip <= 0 ) ) {
return;
}
/* // check if we're out of ammo or the clip is empty
int ammoAvail = owner->inventory.HasAmmo( ammoType, ammoRequired );
if ( !ammoAvail || ( ( clipSize != 0 ) && ( ammoClip <= 0 ) ) ) {
return;
}
*/
//<- doomtrinity
// if this is a power ammo weapon ( currently only the bfg ) then make sure
// we only fire as much power as available in each clip
if ( powerAmmo ) {
// power comes in as a float from zero to max
// if we use this on more than the bfg will need to define the max
// in the .def as opposed to just in the script so proper calcs
// can be done here.
dmgPower = ( int )dmgPower + 1;
if ( dmgPower > ammoClip ) {
dmgPower = ammoClip;
}
}
//doomtrinity -> //From D3XP
if(clipSize == 0) {
//Weapons with a clip size of 0 launch strait from inventory without moving to a clip
//In D3XP we used the ammo when the ammo was moved into the clip so we don't want to
//use it now.
owner->inventory.UseAmmo( ammoType, ( powerAmmo ) ? dmgPower : ammoRequired );
}
//<- doomtrinity
if ( clipSize && ammoRequired ) {
ammoClip -= powerAmmo ? dmgPower : ammoRequired;// doomtrinity (D3XP)
}
}
if ( !silent_fire ) {
// wake up nearby monsters
gameLocal.AlertAI( owner );
}
// set the shader parm to the time of last projectile firing,
// which the gun material shaders can reference for single shot barrel glows, etc
renderEntity.shaderParms[ SHADERPARM_DIVERSITY ] = gameLocal.random.CRandomFloat();
renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.realClientTime );
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->SetShaderParm( SHADERPARM_DIVERSITY, renderEntity.shaderParms[ SHADERPARM_DIVERSITY ] );
worldModel.GetEntity()->SetShaderParm( SHADERPARM_TIMEOFFSET, renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] );
}
// calculate the muzzle position
if ( barrelJointView != INVALID_JOINT && ( projectileDict.GetBool( "launchFromBarrel" ) || g_weaponProjectileOrigin.GetBool() ) ) { // sikk - Weapon Management: Projectile Origin
// there is an explicit joint for the muzzle
GetGlobalJointTransform( true, barrelJointView, muzzleOrigin, muzzleAxis );
} else {
// go straight out of the view
muzzleOrigin = playerViewOrigin;
muzzleAxis = playerViewAxis;
}
// add some to the kick time, incrementally moving repeat firing weapons back
if ( kick_endtime < gameLocal.realClientTime ) {
kick_endtime = gameLocal.realClientTime;
}
kick_endtime += muzzle_kick_time;
if ( kick_endtime > gameLocal.realClientTime + muzzle_kick_maxtime ) {
kick_endtime = gameLocal.realClientTime + muzzle_kick_maxtime;
}
// sikk---> Weapon Management: Handling/Awareness
if ( ( g_weaponHandlingType.GetInteger() == 1 || g_weaponHandlingType.GetInteger() == 3 ) && owner->GetCurrentWeapon() != 2 ) {
spread = ( spread + 2.0f ) * owner->fSpreadModifier;
owner->fSpreadModifier += 0.25f;
if ( owner->fSpreadModifier > 2.0f )
owner->fSpreadModifier = 2.0f;
}
if ( g_weaponAwareness.GetBool() && owner->bIsZoomed )
spread *= 0.5f;
// <---sikk
if ( gameLocal.isClient ) {
// predict instant hit projectiles
if ( projectileDict.GetBool( "net_instanthit" ) ) {
float spreadRad = DEG2RAD( spread );
muzzle_pos = muzzleOrigin + playerViewAxis[ 0 ] * 2.0f;
for( i = 0; i < num_projectiles; i++ ) {
ang = idMath::Sin( spreadRad * gameLocal.random.RandomFloat() );
spin = (float)DEG2RAD( 360.0f ) * gameLocal.random.RandomFloat();
dir = playerViewAxis[ 0 ] + playerViewAxis[ 2 ] * ( ang * idMath::Sin( spin ) ) - playerViewAxis[ 1 ] * ( ang * idMath::Cos( spin ) );
dir.Normalize();
gameLocal.clip.Translation( tr, muzzle_pos, muzzle_pos + dir * 4096.0f, NULL, mat3_identity, MASK_SHOT_RENDERMODEL, owner );
if ( tr.fraction < 1.0f ) {
idProjectile::ClientPredictionCollide( this, projectileDict, tr, vec3_origin, true );
}
}
}
} else {
ownerBounds = owner->GetPhysics()->GetAbsBounds();
owner->AddProjectilesFired( num_projectiles );
float spreadRad = DEG2RAD( spread );
for( i = 0; i < num_projectiles; i++ ) {
ang = idMath::Sin( spreadRad * gameLocal.random.RandomFloat() );
spin = (float)DEG2RAD( 360.0f ) * gameLocal.random.RandomFloat();
dir = playerViewAxis[ 0 ] + playerViewAxis[ 2 ] * ( ang * idMath::Sin( spin ) ) - playerViewAxis[ 1 ] * ( ang * idMath::Cos( spin ) );
dir.Normalize();
// sikk---> Weapon Management: Handling
if ( g_weaponHandlingType.GetInteger() > 1 && !( g_weaponAwareness.GetBool() && owner->bIsZoomed ) ) {
owner->SetViewAngles( owner->viewAngles + idAngles( -0.5f * owner->fSpreadModifier, 0.0f, 0.0f ) );
}
// <---sikk
if ( projectileEnt ) {
ent = projectileEnt;
ent->Show();
ent->Unbind();
projectileEnt = NULL;
} else {
gameLocal.SpawnEntityDef( projectileDict, &ent, false );
}
if ( !ent || !ent->IsType( idProjectile::Type ) ) {
const char *projectileName = weaponDef->dict.GetString( "def_projectile" );
gameLocal.Error( "'%s' is not an idProjectile", projectileName );
}
if ( projectileDict.GetBool( "net_instanthit" ) ) {
// don't synchronize this on top of the already predicted effect
ent->fl.networkSync = false;
}
proj = static_cast<idProjectile *>(ent);
proj->Create( owner, muzzleOrigin, dir );
projBounds = proj->GetPhysics()->GetBounds().Rotate( proj->GetPhysics()->GetAxis() );
// make sure the projectile starts inside the bounding box of the owner
if ( i == 0 ) {
muzzle_pos = muzzleOrigin + playerViewAxis[ 0 ] * 2.0f;
// DG: sometimes the assertion in idBounds::operator-(const idBounds&) triggers
// (would get bounding box with negative volume)
// => check that before doing ownerBounds - projBounds (equivalent to the check in the assertion)
idVec3 obDiff = ownerBounds[1] - ownerBounds[0];
idVec3 pbDiff = projBounds[1] - projBounds[0];
bool boundsSubLegal = obDiff.x > pbDiff.x && obDiff.y > pbDiff.y && obDiff.z > pbDiff.z;
if ( boundsSubLegal && ( ownerBounds - projBounds ).RayIntersection( muzzle_pos, playerViewAxis[0], distance ) ) {
start = muzzle_pos + distance * playerViewAxis[0];
} else {
start = ownerBounds.GetCenter();
}
gameLocal.clip.Translation( tr, start, muzzle_pos, proj->GetPhysics()->GetClipModel(), proj->GetPhysics()->GetClipModel()->GetAxis(), MASK_SHOT_RENDERMODEL, owner );
muzzle_pos = tr.endpos;
}
proj->Launch( muzzle_pos, dir, pushVelocity, fuseOffset, launchPower, dmgPower );
}
// toss the brass
//doomtrinity -> // From D3XP
if( brassDelay >= 0 ) {
PostEventMS( &EV_Weapon_EjectBrass, brassDelay );
}
//<- doomtrinity
}
// add the light for the muzzleflash
if ( !lightOn ) {
MuzzleFlashLight();
}
owner->WeaponFireFeedback( &weaponDef->dict );
// reset muzzle smoke
weaponSmokeStartTime = gameLocal.realClientTime;
}
/*
=====================
idWeapon::Event_Melee
=====================
*/
void idWeapon::Event_Melee( void ) {
idEntity *ent;
trace_t tr;
if ( !meleeDef ) {
gameLocal.Error( "No meleeDef on '%s'", weaponDef->dict.GetString( "classname" ) );
}
if ( !gameLocal.isClient ) {
idVec3 start = playerViewOrigin;
idVec3 end = start + playerViewAxis[0] * ( meleeDistance * owner->PowerUpModifier( MELEE_DISTANCE ) );
gameLocal.clip.TracePoint( tr, start, end, MASK_SHOT_RENDERMODEL, owner );
if ( tr.fraction < 1.0f ) {
ent = gameLocal.GetTraceEntity( tr );
} else {
ent = NULL;
}
if ( g_debugWeapon.GetBool() ) {
gameRenderWorld->DebugLine( colorYellow, start, end, 100 );
if ( ent ) {
gameRenderWorld->DebugBounds( colorRed, ent->GetPhysics()->GetBounds(), ent->GetPhysics()->GetOrigin(), 100 );
}
}
bool hit = false;
const char *hitSound = meleeDef->dict.GetString( "snd_miss" );
if ( ent ) {
float push = meleeDef->dict.GetFloat( "push" );
idVec3 impulse = -push * owner->PowerUpModifier( SPEED ) * tr.c.normal;
if ( gameLocal.world->spawnArgs.GetBool( "no_Weapons" ) && ( ent->IsType( idActor::Type ) || ent->IsType( idAFAttachment::Type) ) ) {
idThread::ReturnInt( 0 );
return;
}
ent->ApplyImpulse( this, tr.c.id, tr.c.point, impulse );
// weapon stealing - do this before damaging so weapons are not dropped twice
if ( gameLocal.isMultiplayer
&& weaponDef && weaponDef->dict.GetBool( "stealing" )
&& ent->IsType( idPlayer::Type )
&& !owner->PowerUpActive( BERSERK )
&& ( gameLocal.gameType != GAME_TDM || gameLocal.serverInfo.GetBool( "si_teamDamage" ) || ( owner->team != static_cast< idPlayer * >( ent )->team ) )
) {
owner->StealWeapon( static_cast< idPlayer * >( ent ) );
}
if ( ent->fl.takedamage ) {
idVec3 kickDir, globalKickDir;
meleeDef->dict.GetVector( "kickDir", "0 0 0", kickDir );
globalKickDir = muzzleAxis * kickDir;
ent->Damage( owner, owner, globalKickDir, meleeDefName, owner->PowerUpModifier( MELEE_DAMAGE ), tr.c.id );
hit = true;
// sikk---> Chainsaw View Sticking // commented out ( we want default chainsaw behaviour ),doomtrinity
/* if ( ent->IsType( idAI::Type ) && !idStr::Icmp( weaponDef->GetName(), "weapon_chainsaw" ) ) {
idVec3 playerOrigin;
idMat3 playerAxis;
idVec3 targetVec = ent->GetPhysics()->GetAbsBounds().GetCenter();
owner->GetViewPos( playerOrigin, playerAxis );
targetVec = ent->GetPhysics()->GetAbsBounds().GetCenter() - playerOrigin;
targetVec[2] *= 0.5f;
targetVec.Normalize();
idAngles delta = targetVec.ToAngles() - owner->cmdAngles - owner->GetDeltaViewAngles();
delta.Normalize180();
float fade = 1.0f - idMath::Fabs( playerAxis[ 0 ].z );
// move the view towards the monster
owner->SetDeltaViewAngles( owner->GetDeltaViewAngles() + delta * fade );
// push the player towards the monster
owner->ApplyImpulse( ent, 0, playerOrigin, playerAxis[ 0 ] * 20000.0f );
}
*/
// <---sikk
}
if ( weaponDef->dict.GetBool( "impact_damage_effect" ) ) {
if ( ent->spawnArgs.GetBool( "bleed" ) ) {
hitSound = meleeDef->dict.GetString( owner->PowerUpActive( BERSERK ) ? "snd_hit_berserk" : "snd_hit" );
ent->AddDamageEffect( tr, impulse, meleeDef->dict.GetString( "classname" ) );
} else {
int type = tr.c.material->GetSurfaceType();
if ( type == SURFTYPE_NONE ) {
type = GetDefaultSurfaceType();
}
const char *materialType = gameLocal.sufaceTypeNames[ type ];
// start impact sound based on material type
hitSound = meleeDef->dict.GetString( va( "snd_%s", materialType ) );
if ( *hitSound == '\0' ) {
hitSound = meleeDef->dict.GetString( "snd_metal" );
}
if ( gameLocal.time > nextStrikeFx ) {
const char *decal;
// project decal
decal = weaponDef->dict.GetString( "mtr_strike" );
if ( decal && *decal ) {
gameLocal.ProjectDecal( tr.c.point, -tr.c.normal, 8.0f, true, 6.0, decal );
}
nextStrikeFx = gameLocal.time + 200;
} else {
hitSound = "";
}
strikeSmokeStartTime = gameLocal.time;
strikePos = tr.c.point;
strikeAxis = -tr.endAxis;
}
}
}
if ( *hitSound != '\0' ) {
const idSoundShader *snd = declManager->FindSound( hitSound );
StartSoundShader( snd, SND_CHANNEL_BODY2, 0, true, NULL );
}
idThread::ReturnInt( hit );
owner->WeaponFireFeedback( &weaponDef->dict );
// sikk---> Blood Spray Screen Effect
if ( g_showBloodSpray.GetBool() ) {
if ( GetOwner()->GetCurrentWeapon() == 10 && ( gameLocal.random.RandomFloat() * 0.99999f ) < g_bloodSprayFrequency.GetFloat() && hit )
GetOwner()->playerView.AddBloodSpray( g_bloodSprayTime.GetFloat() );
}
// <---sikk
return;
}
idThread::ReturnInt( 0 );
owner->WeaponFireFeedback( &weaponDef->dict );
}
/*
=====================
idWeapon::Event_GetWorldModel
=====================
*/
void idWeapon::Event_GetWorldModel( void ) {
idThread::ReturnEntity( worldModel.GetEntity() );
}
/*
=====================
idWeapon::Event_AllowDrop
=====================
*/
void idWeapon::Event_AllowDrop( int allow ) {
if ( allow ) {
allowDrop = true;
} else {
allowDrop = false;
}
}
/*
================
idWeapon::Event_EjectBrass
Toss a shell model out from the breach if the bone is present
================
*/
void idWeapon::Event_EjectBrass( void ) {
if ( !g_showBrass.GetBool() || !owner->CanShowWeaponViewmodel() ) {
return;
}
if ( ejectJointView == INVALID_JOINT || !brassDict.GetNumKeyVals() ) {
return;
}
if ( gameLocal.isClient ) {
return;
}
idMat3 axis;
idVec3 origin, linear_velocity, angular_velocity;
idEntity *ent;
if ( !GetGlobalJointTransform( true, ejectJointView, origin, axis ) ) {
return;
}
gameLocal.SpawnEntityDef( brassDict, &ent, false );
if ( !ent || !ent->IsType( idDebris::Type ) ) {
gameLocal.Error( "'%s' is not an idDebris", weaponDef ? weaponDef->dict.GetString( "def_ejectBrass" ) : "def_ejectBrass" );
}
idDebris *debris = static_cast<idDebris *>(ent);
debris->Create( owner, origin, axis );
debris->Launch();
//doomtrinity -> // following code commented out. Linear velocity in brass def works properly now.
/*
linear_velocity = 40 * ( playerViewAxis[0] + playerViewAxis[1] + playerViewAxis[2] );
angular_velocity.Set( 10 * gameLocal.random.CRandomFloat(), 10 * gameLocal.random.CRandomFloat(), 10 * gameLocal.random.CRandomFloat() );
debris->GetPhysics()->SetLinearVelocity( linear_velocity );
debris->GetPhysics()->SetAngularVelocity( angular_velocity );
*/
//doomtrinity -<
}
/*
===============
idWeapon::Event_IsInvisible
===============
*/
void idWeapon::Event_IsInvisible( void ) {
if ( !owner ) {
idThread::ReturnFloat( 0 );
return;
}
idThread::ReturnFloat( owner->PowerUpActive( INVISIBILITY ) ? 1 : 0 );
}
//doomtrinity->
/*
===============
idWeapon::Event_IsLowered
===============
*/
void idWeapon::Event_IsLowered( void ) {
idThread::ReturnInt( hide );
}
//<-doomtrinity
/*
===============
idWeapon::ClientPredictionThink
===============
*/
void idWeapon::ClientPredictionThink( void ) {
UpdateAnimation();
}
| 1 | 0.928016 | 1 | 0.928016 | game-dev | MEDIA | 0.993505 | game-dev | 0.555877 | 1 | 0.555877 |
ImLegiitXD/Ambient | 2,819 | src/main/java/fr/ambient/module/impl/player/nofall/BlinkNofall.java | package fr.ambient.module.impl.player.nofall;
import fr.ambient.component.impl.packet.BlinkComponent;
import fr.ambient.event.annotations.SubscribeEvent;
import fr.ambient.event.impl.player.PreMotionEvent;
import fr.ambient.event.impl.render.Render2DEvent;
import fr.ambient.module.Module;
import fr.ambient.module.ModuleMode;
import fr.ambient.module.impl.player.NoFall;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import java.awt.*;
public class BlinkNofall extends ModuleMode {
private final NoFall noFall = (NoFall) this.getSuperModule();
public BlinkNofall(String modeName, Module module) {
super(modeName, module);
}
public boolean blinking = false;
private boolean wasBlinking = false;
private int ticks = 0;
public void onDisable() {
ticks = 0;
blinking = false;
wasBlinking = false;
mc.timer.timerSpeed = 1f;
BlinkComponent.onDisable();
}
@SubscribeEvent
private void onRender2D(Render2DEvent event) {
ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft());
if (blinking) {
switch (noFall.blinkindicator.getValue()) {
case "Legit":
mc.fontRendererObj.drawStringWithShadow("Blinking...", sr.getScaledWidth() / 1.9f, sr.getScaledHeight() / 1.9f, Color.WHITE.getRGB());
mc.fontRendererObj.drawStringWithShadow("Ticks : " + ticks, sr.getScaledWidth() / 1.9f, sr.getScaledHeight() / 1.9f + 12, Color.WHITE.getRGB());
break;
case "Raven":
mc.fontRendererObj.drawStringWithShadow("§fblinking : §a" + ticks, sr.getScaledWidth() / 1.9f, sr.getScaledHeight() / 1.9f, Color.WHITE.getRGB());
break;
case "Number":
mc.fontRendererObj.drawStringWithShadow("§a" + ticks, sr.getScaledWidth() / 1.9f, sr.getScaledHeight() / 1.9f, Color.WHITE.getRGB());
break;
case "None":
break;
}
}
}
@SubscribeEvent
private void onUpdate(PreMotionEvent event) {
if (mc.thePlayer.onGround) {
blinking = false;
ticks = 0;
} else {
boolean canFall = !(noFall.getDistanceToGround() < 2);
if (mc.thePlayer.airTicks < 2 && mc.thePlayer.motionY < 0 && canFall) {
blinking = true;
}
}
if (blinking && ticks < 115) {
event.setOnGround(true);
mc.thePlayer.fallDistance = 0;
BlinkComponent.onEnable();
} else if (wasBlinking && !blinking) {
BlinkComponent.onDisable();
}
wasBlinking = blinking;
ticks++;
}
}
| 1 | 0.916869 | 1 | 0.916869 | game-dev | MEDIA | 0.972592 | game-dev | 0.990365 | 1 | 0.990365 |
diphons/kernel_xiaomi_sm8250 | 2,037 | tools/perf/util/trigger.h | /* SPDX-License-Identifier: GPL-2.0 */
#ifndef __TRIGGER_H_
#define __TRIGGER_H_ 1
#include "util/debug.h"
#include "asm/bug.h"
/*
* Use trigger to model operations which need to be executed when
* an event (a signal, for example) is observed.
*
* States and transits:
*
*
* OFF--> ON --> READY --(hit)--> HIT
* ^ |
* | (ready)
* | |
* \_____________/
*
* is_hit and is_ready are two key functions to query the state of
* a trigger. is_hit means the event already happen; is_ready means the
* trigger is waiting for the event.
*/
struct trigger {
volatile enum {
TRIGGER_ERROR = -2,
TRIGGER_OFF = -1,
TRIGGER_ON = 0,
TRIGGER_READY = 1,
TRIGGER_HIT = 2,
} state;
const char *name;
};
#define TRIGGER_WARN_ONCE(t, exp) \
WARN_ONCE(t->state != exp, "trigger '%s' state transist error: %d in %s()\n", \
t->name, t->state, __func__)
static inline bool trigger_is_available(struct trigger *t)
{
return t->state >= 0;
}
static inline bool trigger_is_error(struct trigger *t)
{
return t->state <= TRIGGER_ERROR;
}
static inline void trigger_on(struct trigger *t)
{
TRIGGER_WARN_ONCE(t, TRIGGER_OFF);
t->state = TRIGGER_ON;
}
static inline void trigger_ready(struct trigger *t)
{
if (!trigger_is_available(t))
return;
t->state = TRIGGER_READY;
}
static inline void trigger_hit(struct trigger *t)
{
if (!trigger_is_available(t))
return;
TRIGGER_WARN_ONCE(t, TRIGGER_READY);
t->state = TRIGGER_HIT;
}
static inline void trigger_off(struct trigger *t)
{
if (!trigger_is_available(t))
return;
t->state = TRIGGER_OFF;
}
static inline void trigger_error(struct trigger *t)
{
t->state = TRIGGER_ERROR;
}
static inline bool trigger_is_ready(struct trigger *t)
{
return t->state == TRIGGER_READY;
}
static inline bool trigger_is_hit(struct trigger *t)
{
return t->state == TRIGGER_HIT;
}
#define DEFINE_TRIGGER(n) \
struct trigger n = {.state = TRIGGER_OFF, .name = #n}
#endif
| 1 | 0.948741 | 1 | 0.948741 | game-dev | MEDIA | 0.577035 | game-dev | 0.744958 | 1 | 0.744958 |
TaiyitistMC/Taiyitist | 3,401 | modules/taiyitist-server/src/main/java/org/bukkit/event/entity/EntityRemoveEvent.java | package org.bukkit.event.entity;
import org.bukkit.entity.Entity;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
/**
* Called when an {@link Entity} is removed.
* <p>
* This event should only be used for monitoring. The result
* of modifying the entity during or after this event is unspecified.
* This event is not called for a {@link org.bukkit.entity.Player}.
*/
@ApiStatus.Experimental
public class EntityRemoveEvent extends EntityEvent {
private static final HandlerList handlers = new HandlerList();
private final Cause cause;
public EntityRemoveEvent(@NotNull Entity what, @NotNull Cause cause) {
super(what);
this.cause = cause;
}
/**
* Gets the cause why the entity got removed.
*
* @return the cause why the entity got removed
*/
@NotNull
public Cause getCause() {
return cause;
}
@NotNull
@Override
public HandlerList getHandlers() {
return handlers;
}
@NotNull
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Represents various ways an entity gets removed.
*/
public enum Cause {
/**
* When an entity dies.
*/
DEATH,
/**
* When an entity does despawn. This includes mobs which are too far away,
* items or arrows which lay to long on the ground or area effect cloud.
*/
DESPAWN,
/**
* When an entity gets removed because it drops as an item.
* For example, trident or falling sand.
* <p>
* <b>Note:</b> Depending on other factors, such as gamerules, no item will actually drop,
* the cause, however, will still be drop.
*/
DROP,
/**
* When an entity gets removed because it enters a block.
* For example, bees or silverfish.
*/
ENTER_BLOCK,
/**
* When an entity gets removed because it exploded.
* For example, creepers, tnt or firework.
*/
EXPLODE,
/**
* When an entity gets removed because it hit something. This mainly applies to projectiles.
*/
HIT,
/**
* When an entity gets removed because it merges with another one.
* For example, items or xp.
*/
MERGE,
/**
* When an entity gets removed because it is too far below the world.
* This only applies to entities which get removed immediately,
* some entities get damage instead.
*/
OUT_OF_WORLD,
/**
* When an entity gets removed because it got pickup.
* For example, items, arrows, xp or parrots which get on a player shoulder.
*/
PICKUP,
/**
* When an entity gets removed with a player because the player quits the game.
* For example, a boat which gets removed with the player when he quits.
*/
PLAYER_QUIT,
/**
* When a plugin manually removes an entity.
*/
PLUGIN,
/**
* When an entity gets removed because it transforms into another one.
*/
TRANSFORMATION,
/**
* When the chunk an entity is in gets unloaded.
*/
UNLOAD,
}
}
| 1 | 0.912876 | 1 | 0.912876 | game-dev | MEDIA | 0.961609 | game-dev | 0.919421 | 1 | 0.919421 |
DevBobcorn/CornCraft | 4,302 | Assets/Scripts/Control/PlayerStates/ForceMoveState.cs | #nullable enable
using KinematicCharacterController;
using UnityEngine;
namespace CraftSharp.Control
{
public class ForceMoveState : IPlayerState
{
public readonly string Name;
public readonly ForceMoveOperation[] Operations;
private int currentOperationIndex = 0;
private ForceMoveOperation? currentOperation;
private float currentTime = 0F;
public ForceMoveState(string name, ForceMoveOperation[] op)
{
Name = name;
Operations = op;
}
public bool IgnoreCollision()
{
return true;
}
public void UpdateBeforeMotor(float interval, PlayerActions inputData, PlayerStatus info, KinematicCharacterMotor motor, PlayerController player)
{
if (currentOperation is null)
return;
currentTime = Mathf.Max(currentTime - interval, 0F);
if (currentTime <= 0F)
{
// Finish current operation
FinishOperation(info, motor, player);
currentOperationIndex++;
if (currentOperationIndex < Operations.Length)
{
// Start next operation in sequence
StartOperation(info, motor, player);
}
}
else
{
// Call operation update
var terminate = currentOperation.OperationUpdate?.Invoke(interval, currentTime, inputData, info, motor, player);
if (terminate ?? false)
{
// Finish current operation
FinishOperation(info, motor, player);
currentOperationIndex++;
currentTime = 0F;
if (currentOperationIndex < Operations.Length)
{
// Start next operation in sequence
StartOperation(info, motor, player);
}
}
}
}
public void UpdateMain(ref Vector3 currentVelocity, float interval, PlayerActions inputData, PlayerStatus info, KinematicCharacterMotor motor, PlayerController player)
{
if (currentOperation is not null)
{
// Distribute offset evenly into the movement
currentVelocity = currentOperation.Offset / currentOperation.Time;
}
else
{
currentVelocity = Vector3.zero;
}
}
private void StartOperation(PlayerStatus info, KinematicCharacterMotor motor, PlayerController player)
{
// Update current operation
currentOperation = Operations[currentOperationIndex];
if (currentOperation is not null)
{
// Invoke operation init if present
currentOperation.OperationInit?.Invoke(info, motor, player);
currentTime = currentOperation.Time;
}
else
{
currentTime = 0F;
}
}
private void FinishOperation(PlayerStatus info, KinematicCharacterMotor motor, PlayerController player)
{
currentOperation?.OperationExit?.Invoke(info, motor, player);
}
// This is not used, use PlayerController.StartForceMoveOperation() to enter this state
public bool ShouldEnter(PlayerActions inputData, PlayerStatus info) => false;
public bool ShouldExit(PlayerActions inputData, PlayerStatus info) =>
currentOperationIndex >= Operations.Length && currentTime <= 0F;
public void OnEnter(IPlayerState prevState, PlayerStatus info, KinematicCharacterMotor motor, PlayerController player)
{
if (Operations.Length > currentOperationIndex)
StartOperation(info, motor, player);
}
public void OnExit(IPlayerState nextState, PlayerStatus info, KinematicCharacterMotor motor, PlayerController player)
{
}
public override string ToString() => $"ForceMove [{Name}] {currentOperationIndex + 1}/{Operations.Length} ({currentTime:0.00}/{currentOperation?.Time:0.00})";
}
} | 1 | 0.968845 | 1 | 0.968845 | game-dev | MEDIA | 0.99025 | game-dev | 0.980839 | 1 | 0.980839 |
doughtmw/ArUcoDetectionHoloLens-Unity | 7,261 | ArUcoDetectionHoloLensUnity/Assets/MRTK/Core/Inspectors/Profiles/MixedRealitySpatialAwarenessMeshObserverProfileInspector.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using Microsoft.MixedReality.Toolkit.Utilities;
using UnityEditor;
using UnityEngine;
using Microsoft.MixedReality.Toolkit.SpatialAwareness;
using System.Linq;
namespace Microsoft.MixedReality.Toolkit.Editor.SpatialAwareness
{
[CustomEditor(typeof(MixedRealitySpatialAwarenessMeshObserverProfile))]
public class MixedRealitySpatialAwarenessMeshObserverProfileInspector : BaseMixedRealityToolkitConfigurationProfileInspector
{
// General settings
private SerializedProperty startupBehavior;
private SerializedProperty observationExtents;
private SerializedProperty observerVolumeType;
private SerializedProperty isStationaryObserver;
private SerializedProperty updateInterval;
// Physics settings
private SerializedProperty meshPhysicsLayer;
private SerializedProperty recalculateNormals;
private SerializedProperty physicsMaterial;
// Level of Detail settings
private SerializedProperty levelOfDetail;
private SerializedProperty trianglesPerCubicMeter;
// Display settings
private SerializedProperty displayOption;
private SerializedProperty visibleMaterial;
private SerializedProperty occlusionMaterial;
private readonly GUIContent displayOptionContent = new GUIContent("Display Option");
private readonly GUIContent lodContent = new GUIContent("Level of Detail");
private readonly GUIContent volumeTypeContent = new GUIContent("Observer Shape");
private readonly GUIContent physicsLayerContent = new GUIContent("Physics Layer");
private readonly GUIContent trianglesPerCubicMeterContent = new GUIContent("Triangles/Cubic Meter");
private const string ProfileTitle = "Spatial Mesh Observer Settings";
private const string ProfileDescription = "Configuration settings for how the real-world environment will be perceived and displayed.";
protected override void OnEnable()
{
base.OnEnable();
// General settings
startupBehavior = serializedObject.FindProperty("startupBehavior");
observationExtents = serializedObject.FindProperty("observationExtents");
observerVolumeType = serializedObject.FindProperty("observerVolumeType");
isStationaryObserver = serializedObject.FindProperty("isStationaryObserver");
updateInterval = serializedObject.FindProperty("updateInterval");
// Mesh settings
meshPhysicsLayer = serializedObject.FindProperty("meshPhysicsLayer");
physicsMaterial = serializedObject.FindProperty("physicsMaterial");
recalculateNormals = serializedObject.FindProperty("recalculateNormals");
levelOfDetail = serializedObject.FindProperty("levelOfDetail");
trianglesPerCubicMeter = serializedObject.FindProperty("trianglesPerCubicMeter");
displayOption = serializedObject.FindProperty("displayOption");
visibleMaterial = serializedObject.FindProperty("visibleMaterial");
occlusionMaterial = serializedObject.FindProperty("occlusionMaterial");
}
public override void OnInspectorGUI()
{
if (!RenderProfileHeader(ProfileTitle, ProfileDescription, target, true, BackProfileType.SpatialAwareness))
{
return;
}
using (new EditorGUI.DisabledGroupScope(IsProfileLock((BaseMixedRealityProfile)target)))
{
serializedObject.Update();
EditorGUILayout.LabelField("General Settings", EditorStyles.boldLabel);
{
EditorGUILayout.PropertyField(startupBehavior);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(updateInterval);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(isStationaryObserver);
EditorGUILayout.PropertyField(observerVolumeType, volumeTypeContent);
string message = string.Empty;
if (observerVolumeType.intValue == (int)VolumeType.AxisAlignedCube)
{
message = "Observed meshes will be aligned to the world coordinate space.";
}
else if (observerVolumeType.intValue == (int)VolumeType.UserAlignedCube)
{
message = "Observed meshes will be aligned to the user's coordinate space.";
}
else if (observerVolumeType.intValue == (int)VolumeType.Sphere)
{
message = "The X value of the Observation Extents will be used as the sphere radius.";
}
EditorGUILayout.HelpBox(message, MessageType.Info);
EditorGUILayout.PropertyField(observationExtents);
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Physics Settings", EditorStyles.boldLabel);
{
EditorGUILayout.PropertyField(meshPhysicsLayer, physicsLayerContent);
EditorGUILayout.PropertyField(recalculateNormals);
EditorGUILayout.PropertyField(physicsMaterial);
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Level of Detail Settings", EditorStyles.boldLabel);
{
EditorGUILayout.PropertyField(levelOfDetail, lodContent);
EditorGUILayout.PropertyField(trianglesPerCubicMeter, trianglesPerCubicMeterContent);
EditorGUILayout.HelpBox("The value of Triangles per Cubic Meter is ignored unless Level of Detail is set to Custom.", MessageType.Info);
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Display Settings", EditorStyles.boldLabel);
{
EditorGUILayout.PropertyField(displayOption, displayOptionContent);
EditorGUILayout.PropertyField(visibleMaterial);
EditorGUILayout.PropertyField(occlusionMaterial);
}
serializedObject.ApplyModifiedProperties();
}
}
protected override bool IsProfileInActiveInstance()
{
var profile = target as BaseMixedRealityProfile;
return MixedRealityToolkit.IsInitialized && profile != null &&
MixedRealityToolkit.Instance.HasActiveProfile &&
MixedRealityToolkit.Instance.ActiveProfile.SpatialAwarenessSystemProfile != null &&
MixedRealityToolkit.Instance.ActiveProfile.SpatialAwarenessSystemProfile.ObserverConfigurations != null &&
MixedRealityToolkit.Instance.ActiveProfile.SpatialAwarenessSystemProfile.ObserverConfigurations.Any(s => s.ObserverProfile == profile);
}
}
}
| 1 | 0.793916 | 1 | 0.793916 | game-dev | MEDIA | 0.944228 | game-dev | 0.764845 | 1 | 0.764845 |
Kleadworks/GDXP | 19,726 | servers/physics_2d/body_2d_sw.cpp | /*************************************************************************/
/* body_2d_sw.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "body_2d_sw.h"
#include "area_2d_sw.h"
#include "physics_2d_server_sw.h"
#include "space_2d_sw.h"
void Body2DSW::_update_inertia() {
if (!user_inertia && get_space() && !inertia_update_list.in_list())
get_space()->body_add_to_inertia_update_list(&inertia_update_list);
}
void Body2DSW::update_inertias() {
//update shapes and motions
switch (mode) {
case Physics2DServer::BODY_MODE_RIGID: {
if (user_inertia) break;
//update tensor for allshapes, not the best way but should be somehow OK. (inspired from bullet)
float total_area = 0;
for (int i = 0; i < get_shape_count(); i++) {
total_area += get_shape_aabb(i).get_area();
}
real_t _inertia = 0;
for (int i = 0; i < get_shape_count(); i++) {
const Shape2DSW *shape = get_shape(i);
float area = get_shape_aabb(i).get_area();
float mass = area * this->mass / total_area;
Matrix32 mtx = get_shape_transform(i);
Vector2 scale = mtx.get_scale();
_inertia += shape->get_moment_of_inertia(mass, scale) + mass * mtx.get_origin().length_squared();
//Rect2 ab = get_shape_aabb(i);
//_inertia+=mass*ab.size.dot(ab.size)/12.0f;
}
if (_inertia != 0)
_inv_inertia = 1.0 / _inertia;
else
_inv_inertia = 0.0; //wathever
if (mass)
_inv_mass = 1.0 / mass;
else
_inv_mass = 0;
} break;
case Physics2DServer::BODY_MODE_KINEMATIC:
case Physics2DServer::BODY_MODE_STATIC: {
_inv_inertia = 0;
_inv_mass = 0;
} break;
case Physics2DServer::BODY_MODE_CHARACTER: {
_inv_inertia = 0;
_inv_mass = 1.0 / mass;
} break;
}
//_update_inertia_tensor();
//_update_shapes();
}
void Body2DSW::set_active(bool p_active) {
if (active == p_active)
return;
active = p_active;
if (!p_active) {
if (get_space())
get_space()->body_remove_from_active_list(&active_list);
} else {
if (mode == Physics2DServer::BODY_MODE_STATIC)
return; //static bodies can't become active
if (get_space())
get_space()->body_add_to_active_list(&active_list);
//still_time=0;
}
/*
if (!space)
return;
for(int i=0;i<get_shape_count();i++) {
Shape &s=shapes[i];
if (s.bpid>0) {
get_space()->get_broadphase()->set_active(s.bpid,active);
}
}
*/
}
void Body2DSW::set_param(Physics2DServer::BodyParameter p_param, float p_value) {
switch (p_param) {
case Physics2DServer::BODY_PARAM_BOUNCE: {
bounce = p_value;
} break;
case Physics2DServer::BODY_PARAM_FRICTION: {
friction = p_value;
} break;
case Physics2DServer::BODY_PARAM_MASS: {
ERR_FAIL_COND(p_value <= 0);
mass = p_value;
_update_inertia();
} break;
case Physics2DServer::BODY_PARAM_INERTIA: {
if (p_value <= 0) {
user_inertia = false;
_update_inertia();
} else {
user_inertia = true;
_inv_inertia = 1.0 / p_value;
}
} break;
case Physics2DServer::BODY_PARAM_GRAVITY_SCALE: {
gravity_scale = p_value;
} break;
case Physics2DServer::BODY_PARAM_LINEAR_DAMP: {
linear_damp = p_value;
} break;
case Physics2DServer::BODY_PARAM_ANGULAR_DAMP: {
angular_damp = p_value;
} break;
default: {
}
}
}
float Body2DSW::get_param(Physics2DServer::BodyParameter p_param) const {
switch (p_param) {
case Physics2DServer::BODY_PARAM_BOUNCE: {
return bounce;
} break;
case Physics2DServer::BODY_PARAM_FRICTION: {
return friction;
} break;
case Physics2DServer::BODY_PARAM_MASS: {
return mass;
} break;
case Physics2DServer::BODY_PARAM_INERTIA: {
return _inv_inertia == 0 ? 0 : 1.0 / _inv_inertia;
} break;
case Physics2DServer::BODY_PARAM_GRAVITY_SCALE: {
return gravity_scale;
} break;
case Physics2DServer::BODY_PARAM_LINEAR_DAMP: {
return linear_damp;
} break;
case Physics2DServer::BODY_PARAM_ANGULAR_DAMP: {
return angular_damp;
} break;
default: {
}
}
return 0;
}
void Body2DSW::set_mode(Physics2DServer::BodyMode p_mode) {
Physics2DServer::BodyMode prev = mode;
mode = p_mode;
switch (p_mode) {
//CLEAR UP EVERYTHING IN CASE IT NOT WORKS!
case Physics2DServer::BODY_MODE_STATIC:
case Physics2DServer::BODY_MODE_KINEMATIC: {
_set_inv_transform(get_transform().affine_inverse());
_inv_mass = 0;
_set_static(p_mode == Physics2DServer::BODY_MODE_STATIC);
set_active(p_mode == Physics2DServer::BODY_MODE_KINEMATIC && contacts.size());
linear_velocity = Vector2();
angular_velocity = 0;
if (mode == Physics2DServer::BODY_MODE_KINEMATIC && prev != mode) {
first_time_kinematic = true;
}
} break;
case Physics2DServer::BODY_MODE_RIGID: {
_inv_mass = mass > 0 ? (1.0 / mass) : 0;
_set_static(false);
} break;
case Physics2DServer::BODY_MODE_CHARACTER: {
_inv_mass = mass > 0 ? (1.0 / mass) : 0;
_set_static(false);
} break;
}
_update_inertia();
//if (get_space())
// _update_queries();
}
Physics2DServer::BodyMode Body2DSW::get_mode() const {
return mode;
}
void Body2DSW::_shapes_changed() {
_update_inertia();
wakeup_neighbours();
}
void Body2DSW::_shape_index_removed(int p_index) {
for (Map<Constraint2DSW *, int>::Element *E = constraint_map.front(); E; E = E->next()) {
E->key()->shift_shape_indices(this, p_index);
}
}
void Body2DSW::set_state(Physics2DServer::BodyState p_state, const Variant &p_variant) {
switch (p_state) {
case Physics2DServer::BODY_STATE_TRANSFORM: {
if (mode == Physics2DServer::BODY_MODE_KINEMATIC) {
new_transform = p_variant;
//wakeup_neighbours();
set_active(true);
if (first_time_kinematic) {
_set_transform(p_variant);
_set_inv_transform(get_transform().affine_inverse());
first_time_kinematic = false;
}
} else if (mode == Physics2DServer::BODY_MODE_STATIC) {
_set_transform(p_variant);
_set_inv_transform(get_transform().affine_inverse());
wakeup_neighbours();
} else {
Matrix32 t = p_variant;
t.orthonormalize();
new_transform = get_transform(); //used as old to compute motion
if (t == new_transform)
break;
_set_transform(t);
_set_inv_transform(get_transform().inverse());
}
wakeup();
} break;
case Physics2DServer::BODY_STATE_LINEAR_VELOCITY: {
//if (mode==Physics2DServer::BODY_MODE_STATIC)
// break;
linear_velocity = p_variant;
wakeup();
} break;
case Physics2DServer::BODY_STATE_ANGULAR_VELOCITY: {
//if (mode!=Physics2DServer::BODY_MODE_RIGID)
// break;
angular_velocity = p_variant;
wakeup();
} break;
case Physics2DServer::BODY_STATE_SLEEPING: {
//?
if (mode == Physics2DServer::BODY_MODE_STATIC || mode == Physics2DServer::BODY_MODE_KINEMATIC)
break;
bool do_sleep = p_variant;
if (do_sleep) {
linear_velocity = Vector2();
//biased_linear_velocity=Vector3();
angular_velocity = 0;
//biased_angular_velocity=Vector3();
set_active(false);
} else {
if (mode != Physics2DServer::BODY_MODE_STATIC)
set_active(true);
}
} break;
case Physics2DServer::BODY_STATE_CAN_SLEEP: {
can_sleep = p_variant;
if (mode == Physics2DServer::BODY_MODE_RIGID && !active && !can_sleep)
set_active(true);
} break;
}
}
Variant Body2DSW::get_state(Physics2DServer::BodyState p_state) const {
switch (p_state) {
case Physics2DServer::BODY_STATE_TRANSFORM: {
return get_transform();
} break;
case Physics2DServer::BODY_STATE_LINEAR_VELOCITY: {
return linear_velocity;
} break;
case Physics2DServer::BODY_STATE_ANGULAR_VELOCITY: {
return angular_velocity;
} break;
case Physics2DServer::BODY_STATE_SLEEPING: {
return !is_active();
} break;
case Physics2DServer::BODY_STATE_CAN_SLEEP: {
return can_sleep;
} break;
}
return Variant();
}
void Body2DSW::set_space(Space2DSW *p_space) {
if (get_space()) {
wakeup_neighbours();
if (inertia_update_list.in_list())
get_space()->body_remove_from_inertia_update_list(&inertia_update_list);
if (active_list.in_list())
get_space()->body_remove_from_active_list(&active_list);
if (direct_state_query_list.in_list())
get_space()->body_remove_from_state_query_list(&direct_state_query_list);
}
_set_space(p_space);
if (get_space()) {
_update_inertia();
if (active)
get_space()->body_add_to_active_list(&active_list);
// _update_queries();
//if (is_active()) {
// active=false;
// set_active(true);
//}
}
first_integration = false;
}
void Body2DSW::_compute_area_gravity_and_dampenings(const Area2DSW *p_area) {
if (p_area->is_gravity_point()) {
if (p_area->get_gravity_distance_scale() > 0) {
Vector2 v = p_area->get_transform().xform(p_area->get_gravity_vector()) - get_transform().get_origin();
gravity += v.normalized() * (p_area->get_gravity() / Math::pow(v.length() * p_area->get_gravity_distance_scale() + 1, 2));
} else {
gravity += (p_area->get_transform().xform(p_area->get_gravity_vector()) - get_transform().get_origin()).normalized() * p_area->get_gravity();
}
} else {
gravity += p_area->get_gravity_vector() * p_area->get_gravity();
}
area_linear_damp += p_area->get_linear_damp();
area_angular_damp += p_area->get_angular_damp();
}
void Body2DSW::integrate_forces(real_t p_step) {
if (mode == Physics2DServer::BODY_MODE_STATIC)
return;
Area2DSW *def_area = get_space()->get_default_area();
// Area2DSW *damp_area = def_area;
ERR_FAIL_COND(!def_area);
int ac = areas.size();
bool stopped = false;
gravity = Vector2(0, 0);
area_angular_damp = 0;
area_linear_damp = 0;
if (ac) {
areas.sort();
const AreaCMP *aa = &areas[0];
// damp_area = aa[ac-1].area;
for (int i = ac - 1; i >= 0 && !stopped; i--) {
Physics2DServer::AreaSpaceOverrideMode mode = aa[i].area->get_space_override_mode();
switch (mode) {
case Physics2DServer::AREA_SPACE_OVERRIDE_COMBINE:
case Physics2DServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE: {
_compute_area_gravity_and_dampenings(aa[i].area);
stopped = mode == Physics2DServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE;
} break;
case Physics2DServer::AREA_SPACE_OVERRIDE_REPLACE:
case Physics2DServer::AREA_SPACE_OVERRIDE_REPLACE_COMBINE: {
gravity = Vector2(0, 0);
area_angular_damp = 0;
area_linear_damp = 0;
_compute_area_gravity_and_dampenings(aa[i].area);
stopped = mode == Physics2DServer::AREA_SPACE_OVERRIDE_REPLACE;
} break;
default: {
}
}
}
}
if (!stopped) {
_compute_area_gravity_and_dampenings(def_area);
}
gravity *= gravity_scale;
// If less than 0, override dampenings with that of the Body2D
if (angular_damp >= 0)
area_angular_damp = angular_damp;
//else
// area_angular_damp=damp_area->get_angular_damp();
if (linear_damp >= 0)
area_linear_damp = linear_damp;
//else
// area_linear_damp=damp_area->get_linear_damp();
Vector2 motion;
bool do_motion = false;
if (mode == Physics2DServer::BODY_MODE_KINEMATIC) {
//compute motion, angular and etc. velocities from prev transform
linear_velocity = (new_transform.elements[2] - get_transform().elements[2]) / p_step;
real_t rot = new_transform.affine_inverse().basis_xform(get_transform().elements[1]).angle();
angular_velocity = rot / p_step;
motion = new_transform.elements[2] - get_transform().elements[2];
do_motion = true;
//for(int i=0;i<get_shape_count();i++) {
// set_shape_kinematic_advance(i,Vector2());
// set_shape_kinematic_retreat(i,0);
//}
} else {
if (!omit_force_integration && !first_integration) {
//overriden by direct state query
Vector2 force = gravity * mass;
force += applied_force;
real_t torque = applied_torque;
real_t damp = 1.0 - p_step * area_linear_damp;
if (damp < 0) // reached zero in the given time
damp = 0;
real_t angular_damp = 1.0 - p_step * area_angular_damp;
if (angular_damp < 0) // reached zero in the given time
angular_damp = 0;
linear_velocity *= damp;
angular_velocity *= angular_damp;
linear_velocity += _inv_mass * force * p_step;
angular_velocity += _inv_inertia * torque * p_step;
}
if (continuous_cd_mode != Physics2DServer::CCD_MODE_DISABLED) {
motion = new_transform.get_origin() - get_transform().get_origin();
//linear_velocity*p_step;
do_motion = true;
}
}
//motion=linear_velocity*p_step;
first_integration = false;
biased_angular_velocity = 0;
biased_linear_velocity = Vector2();
if (do_motion) { //shapes temporarily extend for raycast
_update_shapes_with_motion(motion);
}
// damp_area=NULL; // clear the area, so it is set in the next frame
def_area = NULL; // clear the area, so it is set in the next frame
contact_count = 0;
}
void Body2DSW::integrate_velocities(real_t p_step) {
if (mode == Physics2DServer::BODY_MODE_STATIC)
return;
if (fi_callback)
get_space()->body_add_to_state_query_list(&direct_state_query_list);
if (mode == Physics2DServer::BODY_MODE_KINEMATIC) {
_set_transform(new_transform, false);
_set_inv_transform(new_transform.affine_inverse());
if (contacts.size() == 0 && linear_velocity == Vector2() && angular_velocity == 0)
set_active(false); //stopped moving, deactivate
return;
}
real_t total_angular_velocity = angular_velocity + biased_angular_velocity;
Vector2 total_linear_velocity = linear_velocity + biased_linear_velocity;
real_t angle = get_transform().get_rotation() - total_angular_velocity * p_step;
Vector2 pos = get_transform().get_origin() + total_linear_velocity * p_step;
_set_transform(Matrix32(angle, pos), continuous_cd_mode == Physics2DServer::CCD_MODE_DISABLED);
_set_inv_transform(get_transform().inverse());
if (continuous_cd_mode != Physics2DServer::CCD_MODE_DISABLED)
new_transform = get_transform();
//_update_inertia_tensor();
}
void Body2DSW::wakeup_neighbours() {
for (Map<Constraint2DSW *, int>::Element *E = constraint_map.front(); E; E = E->next()) {
const Constraint2DSW *c = E->key();
Body2DSW **n = c->get_body_ptr();
int bc = c->get_body_count();
for (int i = 0; i < bc; i++) {
if (i == E->get())
continue;
Body2DSW *b = n[i];
if (b->mode != Physics2DServer::BODY_MODE_RIGID)
continue;
if (!b->is_active())
b->set_active(true);
}
}
}
void Body2DSW::call_queries() {
if (fi_callback) {
Physics2DDirectBodyStateSW *dbs = Physics2DDirectBodyStateSW::singleton;
dbs->body = this;
Variant v = dbs;
const Variant *vp[2] = { &v, &fi_callback->callback_udata };
Object *obj = ObjectDB::get_instance(fi_callback->id);
if (!obj) {
set_force_integration_callback(0, StringName());
} else {
Variant::CallError ce;
if (fi_callback->callback_udata.get_type()) {
obj->call(fi_callback->method, vp, 2, ce);
} else {
obj->call(fi_callback->method, vp, 1, ce);
}
}
}
}
bool Body2DSW::sleep_test(real_t p_step) {
if (mode == Physics2DServer::BODY_MODE_STATIC || mode == Physics2DServer::BODY_MODE_KINEMATIC)
return true; //
else if (mode == Physics2DServer::BODY_MODE_CHARACTER)
return !active; // characters and kinematic bodies don't sleep unless asked to sleep
else if (!can_sleep)
return false;
if (Math::abs(angular_velocity) < get_space()->get_body_angular_velocity_sleep_treshold() && Math::abs(linear_velocity.length_squared()) < get_space()->get_body_linear_velocity_sleep_treshold() * get_space()->get_body_linear_velocity_sleep_treshold()) {
still_time += p_step;
return still_time > get_space()->get_body_time_to_sleep();
} else {
still_time = 0; //maybe this should be set to 0 on set_active?
return false;
}
}
void Body2DSW::set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata) {
if (fi_callback) {
memdelete(fi_callback);
fi_callback = NULL;
}
if (p_id != 0) {
fi_callback = memnew(ForceIntegrationCallback);
fi_callback->id = p_id;
fi_callback->method = p_method;
fi_callback->callback_udata = p_udata;
}
}
Body2DSW::Body2DSW() :
CollisionObject2DSW(TYPE_BODY),
active_list(this),
inertia_update_list(this),
direct_state_query_list(this) {
mode = Physics2DServer::BODY_MODE_RIGID;
active = true;
angular_velocity = 0;
biased_angular_velocity = 0;
mass = 1;
user_inertia = false;
_inv_inertia = 0;
_inv_mass = 1;
bounce = 0;
friction = 1;
omit_force_integration = false;
applied_torque = 0;
island_step = 0;
island_next = NULL;
island_list_next = NULL;
_set_static(false);
first_time_kinematic = false;
linear_damp = -1;
angular_damp = -1;
area_angular_damp = 0;
area_linear_damp = 0;
contact_count = 0;
gravity_scale = 1.0;
using_one_way_cache = false;
one_way_collision_max_depth = 0.1;
first_integration = false;
still_time = 0;
continuous_cd_mode = Physics2DServer::CCD_MODE_DISABLED;
can_sleep = false;
fi_callback = NULL;
}
Body2DSW::~Body2DSW() {
if (fi_callback)
memdelete(fi_callback);
}
Physics2DDirectBodyStateSW *Physics2DDirectBodyStateSW::singleton = NULL;
Physics2DDirectSpaceState *Physics2DDirectBodyStateSW::get_space_state() {
return body->get_space()->get_direct_state();
}
Variant Physics2DDirectBodyStateSW::get_contact_collider_shape_metadata(int p_contact_idx) const {
ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Variant());
if (!Physics2DServerSW::singletonsw->body_owner.owns(body->contacts[p_contact_idx].collider)) {
return Variant();
}
Body2DSW *other = Physics2DServerSW::singletonsw->body_owner.get(body->contacts[p_contact_idx].collider);
int sidx = body->contacts[p_contact_idx].collider_shape;
if (sidx < 0 || sidx >= other->get_shape_count()) {
return Variant();
}
return other->get_shape_metadata(sidx);
}
| 1 | 0.919769 | 1 | 0.919769 | game-dev | MEDIA | 0.953678 | game-dev | 0.904788 | 1 | 0.904788 |
magefree/mage | 1,867 | Mage.Sets/src/mage/cards/b/BroughtBack.java | package mage.cards.b;
import mage.abilities.effects.common.ReturnFromGraveyardToBattlefieldTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.filter.FilterCard;
import mage.filter.common.FilterPermanentCard;
import mage.filter.predicate.card.PutIntoGraveFromBattlefieldThisTurnPredicate;
import mage.target.common.TargetCardInYourGraveyard;
import mage.watchers.common.CardsPutIntoGraveyardWatcher;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class BroughtBack extends CardImpl {
private static final FilterCard filter = new FilterPermanentCard(
"permanent cards in your graveyard that were put there from the battlefield this turn"
);
static {
filter.add(PutIntoGraveFromBattlefieldThisTurnPredicate.instance);
}
public BroughtBack(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{W}{W}");
// Choose up to two target permanent cards in your graveyard that were put there from the battlefield this turn. Return them to the battlefield tapped.
this.getSpellAbility().addEffect(
new ReturnFromGraveyardToBattlefieldTargetEffect(true)
.setText("Choose up to two target permanent cards in your graveyard " +
"that were put there from the battlefield this turn. " +
"Return them to the battlefield tapped.")
);
this.getSpellAbility().addTarget(new TargetCardInYourGraveyard(0, 2, filter));
this.getSpellAbility().addWatcher(new CardsPutIntoGraveyardWatcher());
}
private BroughtBack(final BroughtBack card) {
super(card);
}
@Override
public BroughtBack copy() {
return new BroughtBack(this);
}
}
| 1 | 0.97207 | 1 | 0.97207 | game-dev | MEDIA | 0.698149 | game-dev | 0.958114 | 1 | 0.958114 |
OData/odata.net | 6,680 | src/Microsoft.OData.Edm/Cache.cs | //---------------------------------------------------------------------
// <copyright file="Cache.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
using System;
using System.Diagnostics;
namespace Microsoft.OData.Edm
{
/// <summary>
/// Provides a caching mechanism for semantic properties.
/// </summary>
/// <typeparam name="TContainer">Type of the element that contains the cached property</typeparam>
/// <typeparam name="TProperty">Type of the cached property</typeparam>
//// Using a Cache requires a function to compute the cached value at first access and a function
//// to create a result when the computation of the value involves a cyclic dependency. (The second
//// function can be omitted if a cycle is impossible.)
////
//// Cache provides concurrency safety.
internal class Cache<TContainer, TProperty>
{
private object value = CacheHelper.Unknown;
// In order to detect the boundaries of a cycle, we use two sentinel values. When we encounter the first sentinel, we know that a cycle exists and that we are a point on that cycle.
// When we reach an instance of the second sentinel, we know we have made a complete circuit of the cycle and that every node in the cycle has been marked with the second sentinel.
public TProperty GetValue(TContainer container, Func<TContainer, TProperty> compute, Func<TContainer, TProperty> onCycle)
{
// If a cycle is present, locking on the cache object can produce a deadlock (if one thread asks for one node in the cycle and another
// thread asks for another). If a cycle is possible, onCycle is required to be nonnull and the same--because there is one instance per
// property per TContainer type--for all participants in the cycle. Locking on onCycle therefore locks out all other computations of
// the property for all instances of TContainer, which by definition includes all participants in a cycle. If no cycle is possible,
// locking on the cache object allows computation of the property for other instances to occur in parallel and so is minimally selfish.
object lockOn = (object)onCycle ?? this;
object result = this.value;
if (result == CacheHelper.Unknown)
{
lock (lockOn)
{
// If another thread computed a value, use that. If the value is still unknown after acquiring the lock, compute the value.
if (this.value == CacheHelper.Unknown)
{
this.value = CacheHelper.CycleSentinel;
TProperty computedValue;
try
{
computedValue = compute(container);
}
catch
{
this.value = CacheHelper.Unknown;
throw;
}
// If this.value changed during computation, this cache was involved in a cycle and this.value was already set to the onCycle value
Debug.Assert(this.value != CacheHelper.SecondPassCycleSentinel, "Cycles should already have their cycle value set");
if (this.value == CacheHelper.CycleSentinel)
{
this.value = typeof(TProperty) == typeof(bool) ? CacheHelper.BoxedBool((bool)(object)computedValue) : computedValue;
}
}
result = this.value;
}
}
else if (result == CacheHelper.CycleSentinel)
{
lock (lockOn)
{
// If another thread computed a value, use that. If the value is still a sentinel after acquiring the lock,
// by definition this thread is the one computing the value. (Otherwise, the lock taken when the value was
// Unknown would still be in force.)
if (this.value == CacheHelper.CycleSentinel)
{
this.value = CacheHelper.SecondPassCycleSentinel;
try
{
compute(container);
}
catch
{
this.value = CacheHelper.CycleSentinel;
throw;
}
if (this.value == CacheHelper.SecondPassCycleSentinel)
{
this.value = onCycle(container);
}
}
else if (this.value == CacheHelper.Unknown)
{
// Another thread cleared the cache.
return this.GetValue(container, compute, onCycle);
}
result = this.value;
}
}
else if (result == CacheHelper.SecondPassCycleSentinel)
{
lock (lockOn)
{
// If another thread computed a value, use that. If the value is still a sentinel after acquiring the lock,
// by definition this thread is the one computing the value. (Otherwise, the lock taken when the value was
// Unknown would still be in force.)
if (this.value == CacheHelper.SecondPassCycleSentinel)
{
this.value = onCycle(container);
}
else if (this.value == CacheHelper.Unknown)
{
// Another thread cleared the cache.
return this.GetValue(container, compute, onCycle);
}
result = this.value;
}
}
return (TProperty)result;
}
public void Clear(Func<TContainer, TProperty> onCycle)
{
lock ((object)onCycle ?? this)
{
if (this.value != CacheHelper.CycleSentinel && this.value != CacheHelper.SecondPassCycleSentinel)
{
this.value = CacheHelper.Unknown;
}
}
}
}
} | 1 | 0.964464 | 1 | 0.964464 | game-dev | MEDIA | 0.118905 | game-dev | 0.962285 | 1 | 0.962285 |
mixxxdj/mixxx | 1,733 | src/widget/weffectname.cpp | #include "widget/weffectname.h"
#include "moc_weffectname.cpp"
#include "widget/effectwidgetutils.h"
WEffectName::WEffectName(QWidget* pParent, EffectsManager* pEffectsManager)
: WLabel(pParent),
m_pEffectsManager(pEffectsManager) {
effectUpdated();
}
void WEffectName::setup(const QDomNode& node, const SkinContext& context) {
WLabel::setup(node, context);
// EffectWidgetUtils propagates NULLs so this is all safe.
EffectChainPointer pChainSlot = EffectWidgetUtils::getEffectChainFromNode(
node, context, m_pEffectsManager);
EffectSlotPointer pEffectSlot = EffectWidgetUtils::getEffectSlotFromNode(
node, context, pChainSlot);
if (pEffectSlot) {
setEffectSlot(pEffectSlot);
} else {
SKIN_WARNING(node,
context,
QStringLiteral(
"EffectName node could not attach to effect slot."));
}
}
void WEffectName::setEffectSlot(EffectSlotPointer pEffectSlot) {
if (pEffectSlot) {
m_pEffectSlot = pEffectSlot;
connect(pEffectSlot.data(), &EffectSlot::effectChanged, this, &WEffectName::effectUpdated);
effectUpdated();
}
}
void WEffectName::effectUpdated() {
QString name;
QString description;
if (m_pEffectSlot && m_pEffectSlot->isLoaded()) {
EffectManifestPointer pManifest = m_pEffectSlot->getManifest();
name = pManifest->displayName();
//: %1 = effect name; %2 = effect description
description = tr("%1: %2").arg(pManifest->name(), pManifest->description());
} else {
name = kNoEffectString;
description = tr("No effect loaded.");
}
setText(name);
setBaseTooltip(description);
}
| 1 | 0.677805 | 1 | 0.677805 | game-dev | MEDIA | 0.545258 | game-dev,graphics-rendering | 0.654095 | 1 | 0.654095 |
giosuel/imperium-repo | 7,679 | Imperium/src/Interface/LayerSelector/LayerSelector.cs | #region
using Imperium.Core;
using Imperium.Core.Scripts;
using Imperium.Extensions;
using Imperium.Interface.Common;
using Imperium.Interface.MapUI;
using Imperium.Types;
using Imperium.Util;
using Librarium.Binding;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
#endregion
namespace Imperium.Interface.LayerSelector;
/// <summary>
/// This UI is a bit special as it is neither a child of another UI nor does it have a keybinding to open it at any
/// time.
/// Instead, this UI can only be opened by the <see cref="ImpFreecam" /> and the <see cref="MapUI" />.
/// </summary>
internal class LayerSelector : BaseUI
{
private int selectedLayer;
private GameObject layerTemplate;
private readonly LayerToggle[] layerToggles = new LayerToggle[31];
private ImpBinding<bool> isEnabledBinding = new(false);
private ImpBinding<int> layerMaskBinding = new(0);
private Transform fovSlider;
private Transform movementSpeedSlider;
private Transform controlBorder;
private const float toggleHeight = 12f;
internal ImpFreecam Freecam { get; set; }
protected override void InitUI()
{
// This needs to work standalone and as a widget (with and without scroll)
var layerList = transform.Find("Container/LayerList") ?? transform.Find("Content/Viewport/LayerList");
layerTemplate = layerList.Find("Template").gameObject;
layerTemplate.SetActive(false);
var listRect = layerList.GetComponent<RectTransform>();
listRect.sizeDelta = new Vector2(listRect.sizeDelta.x, layerToggles.Length * toggleHeight);
var positionY = 0f;
for (var i = 0; i < layerToggles.Length; i++)
{
var toggleObj = Instantiate(layerTemplate, layerList);
toggleObj.SetActive(true);
layerToggles[i] = toggleObj.AddComponent<LayerToggle>();
layerToggles[i].Init(LayerMask.LayerToName(i), i);
var currentIndex = i;
layerToggles[i].gameObject.AddComponent<ImpInteractable>().onEnter += _ =>
{
layerToggles[selectedLayer].SetSelected(false);
selectedLayer = currentIndex;
layerToggles[selectedLayer].SetSelected(true);
};
layerToggles[i].GetComponent<Button>().onClick.AddListener(OnLayerSelect);
layerToggles[i].GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -positionY);
positionY += toggleHeight;
}
layerToggles[0].SetSelected(true);
Imperium.InputBindings.FreecamMap.NextLayer.performed += OnLayerDown;
Imperium.InputBindings.FreecamMap.PreviousLayer.performed += OnLayerUp;
Imperium.InputBindings.FreecamMap.ToggleLayer.performed += OnLayerToggleLayer;
fovSlider = transform.Find("FovSlider");
movementSpeedSlider = transform.Find("MovementSpeedSlider");
controlBorder = transform.Find("Border");
if (fovSlider)
{
fovSlider.gameObject.SetActive(false);
ImpSlider.Bind(
"FovSlider",
transform,
Imperium.Settings.Freecam.FreecamFieldOfView,
minValue: 1,
maxValue: 180,
playClickSound: false,
theme: theme
);
}
if (movementSpeedSlider)
{
movementSpeedSlider.gameObject.SetActive(false);
ImpSlider.Bind(
"MovementSpeedSlider",
transform,
Imperium.Settings.Freecam.FreecamMovementSpeed,
minValue: 1,
maxValue: 100,
playClickSound: false,
theme: theme
);
}
if (controlBorder && Freecam)
{
Freecam.IsFreehandModeEnabled.OnUpdate += isEnabled => controlBorder.gameObject.SetActive(isEnabled);
controlBorder.gameObject.SetActive(false);
}
}
protected override void OnThemePrimaryUpdate(ImpTheme themeUpdate)
{
ImpThemeManager.Style(
themeUpdate,
container,
new StyleOverride("", Variant.BACKGROUND),
new StyleOverride("Border", Variant.DARKER),
new StyleOverride("TitleBox", Variant.DARKER)
);
ImpThemeManager.Style(
themeUpdate,
transform,
new StyleOverride("Border", Variant.DARKER),
new StyleOverride("FovSlider", Variant.BACKGROUND),
new StyleOverride("FovSlider/Border", Variant.DARKER),
new StyleOverride("MovementSpeedSlider", Variant.BACKGROUND),
new StyleOverride("MovementSpeedSlider/Border", Variant.DARKER)
);
ImpThemeManager.StyleText(
themeUpdate,
container,
new StyleOverride("TitleBox/Title", Variant.FOREGROUND)
);
ImpThemeManager.Style(
themeUpdate,
layerTemplate.transform,
new StyleOverride("Hover", Variant.FADED)
);
foreach (var toggle in layerToggles)
{
ImpThemeManager.Style(
themeUpdate,
toggle.transform,
new StyleOverride("Hover", Variant.FADED)
);
}
}
internal void Bind(ImpBinding<bool> enabledBinding, ImpBinding<int> maskMinding)
{
isEnabledBinding = enabledBinding;
layerMaskBinding = maskMinding;
foreach (var toggle in layerToggles) toggle.UpdateIsOn(layerMaskBinding.Value);
}
private void OnLayerDown(InputAction.CallbackContext callbackContext)
{
if (!IsOpen) return;
layerToggles[selectedLayer].SetSelected(false);
if (selectedLayer == layerToggles.Length - 1)
{
selectedLayer = 0;
}
else
{
selectedLayer++;
}
layerToggles[selectedLayer].SetSelected(true);
}
private void OnLayerUp(InputAction.CallbackContext callbackContext)
{
if (!IsOpen) return;
layerToggles[selectedLayer].SetSelected(false);
if (selectedLayer == 0)
{
selectedLayer = layerToggles.Length - 1;
}
else
{
selectedLayer--;
}
layerToggles[selectedLayer].SetSelected(true);
}
private void OnLayerToggleLayer(InputAction.CallbackContext callbackContext)
{
if (!IsOpen) return;
OnLayerSelect();
}
private void OnLayerSelect()
{
if (Imperium.Settings.Preferences.PlaySounds.Value) GameUtils.PlayClip(ImpAssets.ButtonClick);
var newMask = ImpUtils.ToggleLayerInMask(layerMaskBinding.Value, selectedLayer);
layerMaskBinding.Set(newMask);
layerToggles[selectedLayer].UpdateIsOn(newMask);
}
protected override void OnClose()
{
if (controlBorder) controlBorder.gameObject.SetActive(false);
if (fovSlider) fovSlider.gameObject.SetActive(false);
if (movementSpeedSlider) movementSpeedSlider.gameObject.SetActive(false);
}
protected override void OnOpen(bool wasOpen)
{
if (fovSlider) fovSlider.gameObject.SetActive(true);
if (movementSpeedSlider) movementSpeedSlider.gameObject.SetActive(true);
}
private void Update()
{
if (Imperium.Interface.IsOpen() || MenuManager.instance.IsOpen())
{
if (IsOpen) Close();
}
else if (isEnabledBinding is { Value: true } && Imperium.Freecam.IsFreecamEnabled.Value)
{
if (!IsOpen) Open();
}
}
} | 1 | 0.921203 | 1 | 0.921203 | game-dev | MEDIA | 0.878556 | game-dev | 0.992894 | 1 | 0.992894 |
keiyoushi/extensions-source | 11,837 | src/all/namicomi/src/eu/kanade/tachiyomi/extension/all/namicomi/NamiComiFilters.kt | package eu.kanade.tachiyomi.extension.all.namicomi
import eu.kanade.tachiyomi.extension.all.namicomi.dto.ContentRatingDto
import eu.kanade.tachiyomi.extension.all.namicomi.dto.StatusDto
import eu.kanade.tachiyomi.lib.i18n.Intl
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import okhttp3.HttpUrl
class NamiComiFilters {
internal fun getFilterList(intl: Intl): FilterList = FilterList(
HasAvailableChaptersFilter(intl),
ContentRatingList(intl, getContentRatings(intl)),
StatusList(intl, getStatus(intl)),
SortFilter(intl, getSortables(intl)),
TagsFilter(intl, getTagFilters(intl)),
TagList(intl["content"], getContents(intl)),
TagList(intl["format"], getFormats(intl)),
TagList(intl["genre"], getGenres(intl)),
TagList(intl["theme"], getThemes(intl)),
)
private interface UrlQueryFilter {
fun addQueryParameter(url: HttpUrl.Builder, extLang: String)
}
private class HasAvailableChaptersFilter(intl: Intl) :
Filter.CheckBox(intl["has_available_chapters"]),
UrlQueryFilter {
override fun addQueryParameter(url: HttpUrl.Builder, extLang: String) {
if (state) {
url.addQueryParameter("hasAvailableChapters", "true")
url.addQueryParameter("availableTranslatedLanguages[]", extLang)
}
}
}
private class ContentRating(name: String, val value: String) : Filter.CheckBox(name)
private class ContentRatingList(intl: Intl, contentRating: List<ContentRating>) :
Filter.Group<ContentRating>(intl["content_rating"], contentRating),
UrlQueryFilter {
override fun addQueryParameter(url: HttpUrl.Builder, extLang: String) {
state.filter(ContentRating::state)
.forEach { url.addQueryParameter("contentRatings[]", it.value) }
}
}
private fun getContentRatings(intl: Intl) = listOf(
ContentRating(intl["content_rating_safe"], ContentRatingDto.SAFE.value),
ContentRating(intl["content_rating_restricted"], ContentRatingDto.RESTRICTED.value),
ContentRating(intl["content_rating_mature"], ContentRatingDto.MATURE.value),
)
private class Status(name: String, val value: String) : Filter.CheckBox(name)
private class StatusList(intl: Intl, status: List<Status>) :
Filter.Group<Status>(intl["status"], status),
UrlQueryFilter {
override fun addQueryParameter(url: HttpUrl.Builder, extLang: String) {
state.filter(Status::state)
.forEach { url.addQueryParameter("publicationStatuses[]", it.value) }
}
}
private fun getStatus(intl: Intl) = listOf(
Status(intl["status_ongoing"], StatusDto.ONGOING.value),
Status(intl["status_completed"], StatusDto.COMPLETED.value),
Status(intl["status_hiatus"], StatusDto.HIATUS.value),
Status(intl["status_cancelled"], StatusDto.CANCELLED.value),
)
data class Sortable(val title: String, val value: String) {
override fun toString(): String = title
}
private fun getSortables(intl: Intl) = arrayOf(
Sortable(intl["sort_alphabetic"], "title"),
Sortable(intl["sort_number_of_chapters"], "chapterCount"),
Sortable(intl["sort_number_of_follows"], "followCount"),
Sortable(intl["sort_number_of_likes"], "reactions"),
Sortable(intl["sort_number_of_comments"], "commentCount"),
Sortable(intl["sort_content_created_at"], "publishedAt"),
Sortable(intl["sort_views"], "views"),
Sortable(intl["sort_year"], "year"),
Sortable(intl["sort_rating"], "rating"),
)
class SortFilter(intl: Intl, private val sortables: Array<Sortable>) :
Filter.Sort(
intl["sort"],
sortables.map(Sortable::title).toTypedArray(),
Selection(5, false),
),
UrlQueryFilter {
override fun addQueryParameter(url: HttpUrl.Builder, extLang: String) {
if (state != null) {
val query = sortables[state!!.index].value
val value = if (state!!.ascending) "asc" else "desc"
url.addQueryParameter("order[$query]", value)
}
}
}
internal class Tag(val id: String, name: String) : Filter.TriState(name)
private class TagList(collection: String, tags: List<Tag>) :
Filter.Group<Tag>(collection, tags),
UrlQueryFilter {
override fun addQueryParameter(url: HttpUrl.Builder, extLang: String) {
state.forEach { tag ->
if (tag.isIncluded()) {
url.addQueryParameter("includedTags[]", tag.id)
} else if (tag.isExcluded()) {
url.addQueryParameter("excludedTags[]", tag.id)
}
}
}
}
private fun getContents(intl: Intl): List<Tag> {
val tags = listOf(
Tag("drugs", intl["content_warnings_drugs"]),
Tag("gambling", intl["content_warnings_gambling"]),
Tag("gore", intl["content_warnings_gore"]),
Tag("mental-disorders", intl["content_warnings_mental_disorders"]),
Tag("physical-abuse", intl["content_warnings_physical_abuse"]),
Tag("racism", intl["content_warnings_racism"]),
Tag("self-harm", intl["content_warnings_self_harm"]),
Tag("sexual-abuse", intl["content_warnings_sexual_abuse"]),
Tag("verbal-abuse", intl["content_warnings_verbal_abuse"]),
)
return tags.sortIfTranslated(intl)
}
private fun getFormats(intl: Intl): List<Tag> {
val tags = listOf(
Tag("4-koma", intl["format_4_koma"]),
Tag("adaptation", intl["format_adaptation"]),
Tag("anthology", intl["format_anthology"]),
Tag("full-color", intl["format_full_color"]),
Tag("oneshot", intl["format_oneshot"]),
Tag("silent", intl["format_silent"]),
)
return tags.sortIfTranslated(intl)
}
private fun getGenres(intl: Intl): List<Tag> {
val tags = listOf(
Tag("action", intl["genre_action"]),
Tag("adventure", intl["genre_adventure"]),
Tag("boys-love", intl["genre_boys_love"]),
Tag("comedy", intl["genre_comedy"]),
Tag("crime", intl["genre_crime"]),
Tag("drama", intl["genre_drama"]),
Tag("fantasy", intl["genre_fantasy"]),
Tag("girls-love", intl["genre_girls_love"]),
Tag("historical", intl["genre_historical"]),
Tag("horror", intl["genre_horror"]),
Tag("isekai", intl["genre_isekai"]),
Tag("mecha", intl["genre_mecha"]),
Tag("medical", intl["genre_medical"]),
Tag("mystery", intl["genre_mystery"]),
Tag("philosophical", intl["genre_philosophical"]),
Tag("psychological", intl["genre_psychological"]),
Tag("romance", intl["genre_romance"]),
Tag("sci-fi", intl["genre_sci_fi"]),
Tag("slice-of-life", intl["genre_slice_of_life"]),
Tag("sports", intl["genre_sports"]),
Tag("superhero", intl["genre_superhero"]),
Tag("thriller", intl["genre_thriller"]),
Tag("tragedy", intl["genre_tragedy"]),
Tag("wuxia", intl["genre_wuxia"]),
)
return tags.sortIfTranslated(intl)
}
private fun getThemes(intl: Intl): List<Tag> {
val tags = listOf(
Tag("aliens", intl["theme_aliens"]),
Tag("animals", intl["theme_animals"]),
Tag("cooking", intl["theme_cooking"]),
Tag("crossdressing", intl["theme_crossdressing"]),
Tag("delinquents", intl["theme_delinquents"]),
Tag("demons", intl["theme_demons"]),
Tag("genderswap", intl["theme_genderswap"]),
Tag("ghosts", intl["theme_ghosts"]),
Tag("gyaru", intl["theme_gyaru"]),
Tag("harem", intl["theme_harem"]),
Tag("mafia", intl["theme_mafia"]),
Tag("magic", intl["theme_magic"]),
Tag("magical-girls", intl["theme_magical_girls"]),
Tag("martial-arts", intl["theme_martial_arts"]),
Tag("military", intl["theme_military"]),
Tag("monster-girls", intl["theme_monster_girls"]),
Tag("monsters", intl["theme_monsters"]),
Tag("music", intl["theme_music"]),
Tag("ninja", intl["theme_ninja"]),
Tag("office-workers", intl["theme_office_workers"]),
Tag("police", intl["theme_police"]),
Tag("post-apocalyptic", intl["theme_post_apocalyptic"]),
Tag("reincarnation", intl["theme_reincarnation"]),
Tag("reverse-harem", intl["theme_reverse_harem"]),
Tag("samurai", intl["theme_samurai"]),
Tag("school-life", intl["theme_school_life"]),
Tag("supernatural", intl["theme_supernatural"]),
Tag("survival", intl["theme_survival"]),
Tag("time-travel", intl["theme_time_travel"]),
Tag("traditional-games", intl["theme_traditional_games"]),
Tag("vampires", intl["theme_vampires"]),
Tag("video-games", intl["theme_video_games"]),
Tag("villainess", intl["theme_villainess"]),
Tag("virtual-reality", intl["theme_virtual_reality"]),
Tag("zombies", intl["theme_zombies"]),
)
return tags.sortIfTranslated(intl)
}
// Tags taken from: https://api.namicomi.com/title/tags
internal fun getTags(intl: Intl): List<Tag> {
return getContents(intl) + getFormats(intl) + getGenres(intl) + getThemes(intl)
}
private data class TagMode(val title: String, val value: String) {
override fun toString(): String = title
}
private fun getTagModes(intl: Intl) = arrayOf(
TagMode(intl["mode_and"], "and"),
TagMode(intl["mode_or"], "or"),
)
private class TagInclusionMode(intl: Intl, modes: Array<TagMode>) :
Filter.Select<TagMode>(intl["included_tags_mode"], modes, 0),
UrlQueryFilter {
override fun addQueryParameter(url: HttpUrl.Builder, extLang: String) {
url.addQueryParameter("includedTagsMode", values[state].value)
}
}
private class TagExclusionMode(intl: Intl, modes: Array<TagMode>) :
Filter.Select<TagMode>(intl["excluded_tags_mode"], modes, 1),
UrlQueryFilter {
override fun addQueryParameter(url: HttpUrl.Builder, extLang: String) {
url.addQueryParameter("excludedTagsMode", values[state].value)
}
}
private class TagsFilter(intl: Intl, innerFilters: FilterList) :
Filter.Group<Filter<*>>(intl["tags_mode"], innerFilters),
UrlQueryFilter {
override fun addQueryParameter(url: HttpUrl.Builder, extLang: String) {
state.filterIsInstance<UrlQueryFilter>()
.forEach { filter -> filter.addQueryParameter(url, extLang) }
}
}
private fun getTagFilters(intl: Intl): FilterList = FilterList(
TagInclusionMode(intl, getTagModes(intl)),
TagExclusionMode(intl, getTagModes(intl)),
)
internal fun addFiltersToUrl(url: HttpUrl.Builder, filters: FilterList, extLang: String): HttpUrl {
filters.filterIsInstance<UrlQueryFilter>()
.forEach { filter -> filter.addQueryParameter(url, extLang) }
return url.build()
}
private fun List<Tag>.sortIfTranslated(intl: Intl): List<Tag> = apply {
if (intl.chosenLanguage == NamiComiConstants.english) {
return this
}
return sortedWith(compareBy(intl.collator, Tag::name))
}
}
| 1 | 0.816357 | 1 | 0.816357 | game-dev | MEDIA | 0.719554 | game-dev | 0.576365 | 1 | 0.576365 |
MaximumADHD/Roblox-Client-Tracker | 5,858 | scripts/PlayerScripts/StarterPlayerScripts/PlayerModule.module/ControlModule/Keyboard.lua | --!nonstrict
--[[
Keyboard Character Control - This module handles controlling your avatar from a keyboard
2018 PlayerScripts Update - AllYourBlox
--]]
--[[ Roblox Services ]]--
local UserInputService = game:GetService("UserInputService")
local ContextActionService = game:GetService("ContextActionService")
local CommonUtils = script.Parent.Parent:WaitForChild("CommonUtils")
--[[ Constants ]]--
local ZERO_VECTOR3 = Vector3.new()
--[[ The Module ]]--
local BaseCharacterController = require(script.Parent:WaitForChild("BaseCharacterController"))
local Keyboard = setmetatable({}, BaseCharacterController)
Keyboard.__index = Keyboard
function Keyboard.new(CONTROL_ACTION_PRIORITY)
local self = setmetatable(BaseCharacterController.new() :: any, Keyboard)
self.CONTROL_ACTION_PRIORITY = CONTROL_ACTION_PRIORITY
self.forwardValue = 0
self.backwardValue = 0
self.leftValue = 0
self.rightValue = 0
self.jumpEnabled = true
return self
end
function Keyboard:Enable(enable: boolean)
if enable == self.enabled then
-- Module is already in the state being requested. True is returned here since the module will be in the state
-- expected by the code that follows the Enable() call. This makes more sense than returning false to indicate
-- no action was necessary. False indicates failure to be in requested/expected state.
return true
end
self.forwardValue = 0
self.backwardValue = 0
self.leftValue = 0
self.rightValue = 0
self.moveVector = ZERO_VECTOR3
self.jumpRequested = false
self:UpdateJump()
if enable then
self:BindContextActions()
self:ConnectFocusEventListeners()
else
self._connectionUtil:disconnectAll()
end
self.enabled = enable
return true
end
function Keyboard:UpdateMovement(inputState)
if inputState == Enum.UserInputState.Cancel then
self.moveVector = ZERO_VECTOR3
else
self.moveVector = Vector3.new(self.leftValue + self.rightValue, 0, self.forwardValue + self.backwardValue)
end
end
function Keyboard:UpdateJump()
self.isJumping = self.jumpRequested
end
function Keyboard:BindContextActions()
-- Note: In the previous version of this code, the movement values were not zeroed-out on UserInputState. Cancel, now they are,
-- which fixes them from getting stuck on.
-- We return ContextActionResult.Pass here for legacy reasons.
-- Many games rely on gameProcessedEvent being false on UserInputService.InputBegan for these control actions.
local handleMoveForward = function(actionName, inputState, inputObject)
self.forwardValue = (inputState == Enum.UserInputState.Begin) and -1 or 0
self:UpdateMovement(inputState)
return Enum.ContextActionResult.Pass
end
local handleMoveBackward = function(actionName, inputState, inputObject)
self.backwardValue = (inputState == Enum.UserInputState.Begin) and 1 or 0
self:UpdateMovement(inputState)
return Enum.ContextActionResult.Pass
end
local handleMoveLeft = function(actionName, inputState, inputObject)
self.leftValue = (inputState == Enum.UserInputState.Begin) and -1 or 0
self:UpdateMovement(inputState)
return Enum.ContextActionResult.Pass
end
local handleMoveRight = function(actionName, inputState, inputObject)
self.rightValue = (inputState == Enum.UserInputState.Begin) and 1 or 0
self:UpdateMovement(inputState)
return Enum.ContextActionResult.Pass
end
local handleJumpAction = function(actionName, inputState, inputObject)
self.jumpRequested = self.jumpEnabled and (inputState == Enum.UserInputState.Begin)
self:UpdateJump()
return Enum.ContextActionResult.Pass
end
-- TODO: Revert to KeyCode bindings so that in the future the abstraction layer from actual keys to
-- movement direction is done in Lua
ContextActionService:BindActionAtPriority("moveForwardAction", handleMoveForward, false,
self.CONTROL_ACTION_PRIORITY, Enum.PlayerActions.CharacterForward)
ContextActionService:BindActionAtPriority("moveBackwardAction", handleMoveBackward, false,
self.CONTROL_ACTION_PRIORITY, Enum.PlayerActions.CharacterBackward)
ContextActionService:BindActionAtPriority("moveLeftAction", handleMoveLeft, false,
self.CONTROL_ACTION_PRIORITY, Enum.PlayerActions.CharacterLeft)
ContextActionService:BindActionAtPriority("moveRightAction", handleMoveRight, false,
self.CONTROL_ACTION_PRIORITY, Enum.PlayerActions.CharacterRight)
ContextActionService:BindActionAtPriority("jumpAction", handleJumpAction, false,
self.CONTROL_ACTION_PRIORITY, Enum.PlayerActions.CharacterJump)
self._connectionUtil:trackBoundFunction("moveForwardAction", function() ContextActionService:UnbindAction("moveForwardAction") end)
self._connectionUtil:trackBoundFunction("moveBackwardAction", function() ContextActionService:UnbindAction("moveBackwardAction") end)
self._connectionUtil:trackBoundFunction("moveLeftAction", function() ContextActionService:UnbindAction("moveLeftAction") end)
self._connectionUtil:trackBoundFunction("moveRightAction", function() ContextActionService:UnbindAction("moveRightAction") end)
self._connectionUtil:trackBoundFunction("jumpAction", function() ContextActionService:UnbindAction("jumpAction") end)
end
function Keyboard:ConnectFocusEventListeners()
local function onFocusReleased()
self.moveVector = ZERO_VECTOR3
self.forwardValue = 0
self.backwardValue = 0
self.leftValue = 0
self.rightValue = 0
self.jumpRequested = false
self:UpdateJump()
end
local function onTextFocusGained(textboxFocused)
self.jumpRequested = false
self:UpdateJump()
end
self._connectionUtil:trackConnection("textBoxFocusReleased", UserInputService.TextBoxFocusReleased:Connect(onFocusReleased))
self._connectionUtil:trackConnection("textBoxFocused", UserInputService.TextBoxFocused:Connect(onTextFocusGained))
self._connectionUtil:trackConnection("windowFocusReleased", UserInputService.WindowFocused:Connect(onFocusReleased))
end
return Keyboard
| 1 | 0.934189 | 1 | 0.934189 | game-dev | MEDIA | 0.808323 | game-dev | 0.959692 | 1 | 0.959692 |
flutter/flutter | 3,308 | engine/src/flutter/third_party/accessibility/base/win/display.cc | // Copyright (c) 2011 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.
#include "base/win/display.h"
namespace base {
namespace win {
namespace {
template <typename T>
bool AssignProcAddress(HMODULE comBaseModule, const char* name, T*& outProc) {
outProc = reinterpret_cast<T*>(GetProcAddress(comBaseModule, name));
return *outProc != nullptr;
}
// Helper class for supporting display scale factor lookup across Windows
// versions, with fallbacks where these lookups are unavailable.
class ScaleHelperWin32 {
public:
ScaleHelperWin32();
~ScaleHelperWin32();
/// Returns the scale factor for the specified monitor. Sets |scale| to
/// SCALE_100_PERCENT if the API is not available.
HRESULT GetScaleFactorForMonitor(HMONITOR hmonitor,
DEVICE_SCALE_FACTOR* scale) const;
private:
using GetScaleFactorForMonitor_ =
HRESULT __stdcall(HMONITOR hmonitor, DEVICE_SCALE_FACTOR* scale);
GetScaleFactorForMonitor_* get_scale_factor_for_monitor_ = nullptr;
HMODULE shlib_module_ = nullptr;
bool scale_factor_for_monitor_supported_ = false;
};
ScaleHelperWin32::ScaleHelperWin32() {
if ((shlib_module_ = LoadLibraryA("Shcore.dll")) != nullptr) {
scale_factor_for_monitor_supported_ =
AssignProcAddress(shlib_module_, "GetScaleFactorForMonitor",
get_scale_factor_for_monitor_);
}
}
ScaleHelperWin32::~ScaleHelperWin32() {
if (shlib_module_ != nullptr) {
FreeLibrary(shlib_module_);
}
}
HRESULT ScaleHelperWin32::GetScaleFactorForMonitor(
HMONITOR hmonitor,
DEVICE_SCALE_FACTOR* scale) const {
if (hmonitor == nullptr || scale == nullptr) {
return E_INVALIDARG;
}
if (!scale_factor_for_monitor_supported_) {
*scale = SCALE_100_PERCENT;
return S_OK;
}
return get_scale_factor_for_monitor_(hmonitor, scale);
}
ScaleHelperWin32* GetHelper() {
static ScaleHelperWin32* helper = new ScaleHelperWin32();
return helper;
}
} // namespace
float GetScaleFactorForHWND(HWND hwnd) {
HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
DEVICE_SCALE_FACTOR scale = DEVICE_SCALE_FACTOR_INVALID;
if (SUCCEEDED(GetHelper()->GetScaleFactorForMonitor(monitor, &scale))) {
return ScaleFactorToFloat(scale);
}
return 1.0f;
}
float ScaleFactorToFloat(DEVICE_SCALE_FACTOR scale_factor) {
switch (scale_factor) {
case SCALE_100_PERCENT:
return 1.0f;
case SCALE_120_PERCENT:
return 1.2f;
case SCALE_125_PERCENT:
return 1.25f;
case SCALE_140_PERCENT:
return 1.4f;
case SCALE_150_PERCENT:
return 1.5f;
case SCALE_160_PERCENT:
return 1.6f;
case SCALE_175_PERCENT:
return 1.75f;
case SCALE_180_PERCENT:
return 1.8f;
case SCALE_200_PERCENT:
return 2.0f;
case SCALE_225_PERCENT:
return 2.25f;
case SCALE_250_PERCENT:
return 2.5f;
case SCALE_300_PERCENT:
return 3.0f;
case SCALE_350_PERCENT:
return 3.5f;
case SCALE_400_PERCENT:
return 4.0f;
case SCALE_450_PERCENT:
return 4.5f;
case SCALE_500_PERCENT:
return 5.0f;
default:
return 1.0f;
}
}
} // namespace win
} // namespace base
| 1 | 0.821287 | 1 | 0.821287 | game-dev | MEDIA | 0.195624 | game-dev | 0.63298 | 1 | 0.63298 |
nbelle1/strategy-game-agents | 3,380 | agents/fromScratchLLMStructured_player_v4/saved_agents/g4o_creator_20250515_123101/game_20250515_123316_fg/foo_player.py | import os
from catanatron import Player
from catanatron.game import Game
from catanatron.models.player import Color
from catanatron.models.actions import ActionType
class FooPlayer(Player):
def __init__(self, name=None):
super().__init__(Color.BLUE, name)
def decide(self, game, playable_actions):
# Should return one of the playable_actions.
# Args:
# game (Game): complete game state. read-only.
# Defined in in "catanatron/catanatron_core/catanatron/game.py"
# playable_actions (Iterable[Action]): options to choose from
# Return:
# action (Action): Chosen element of playable_actions
# ===== YOUR CODE HERE =====
# Helper function for evaluating trades
def evaluate_trade(current_resources, target_cost):
needed_resources = {r: target_cost.get(r, 0) - current_resources.get(r, 0)
for r in target_cost if target_cost.get(r, 0) > current_resources.get(r, 0)}
surplus_resources = [r for r, qty in current_resources.items() if qty > 3]
if needed_resources and surplus_resources:
return (surplus_resources[0], list(needed_resources.keys())[0]) # Trade surplus for needed
return None
# Settlement Expansion Strategy Implementation
print("Evaluating actions for Settlement Expansion Strategy")
for action in playable_actions:
if action.action_type == ActionType.BUILD_SETTLEMENT:
print(f"Chosen Action: {action}")
return action
# Road Building Strategy Implementation
print("Evaluating actions for Road Building Strategy")
for action in playable_actions:
if action.action_type == ActionType.BUILD_ROAD:
print(f"Chosen Action: {action}")
return action
# Resource Utilization Strategy Implementation
settlement_cost = {'Brick': 1, 'Wood': 1, 'Wheat': 1, 'Sheep': 1}
road_cost = {'Brick': 1, 'Wood': 1}
city_cost = {'Wheat': 2, 'Ore': 3}
if game.current_player.can_build('settlement'):
target_cost = settlement_cost
elif game.current_player.can_build('road'):
target_cost = road_cost
elif game.current_player.can_build('city'):
target_cost = city_cost
else:
target_cost = None
for action in playable_actions:
if action.action_type == ActionType.TRADE_RESOURCE and target_cost:
trade = evaluate_trade(game.current_player.resources, target_cost)
if trade:
print(f"Trading {trade[0]} for {trade[1]}")
return action
# Prevent Resource Stagnation
def prevent_stagnation(resources):
for resource, qty in resources.items():
if qty > 4: # Excess threshold
return resource
return None
stagnant_resource = prevent_stagnation(game.current_player.resources)
if stagnant_resource:
print(f"Using or trading surplus resource: {stagnant_resource}")
# Default to the first action as a fallback
print("Choosing First Action on Default")
return playable_actions[0]
# ===== END YOUR CODE ===== | 1 | 0.695349 | 1 | 0.695349 | game-dev | MEDIA | 0.832744 | game-dev | 0.816056 | 1 | 0.816056 |
unconed/NFSpace | 48,769 | Platform/OSX/Frameworks/OgreDebug.framework/Versions/A/Headers/OgreResourceGroupManager.h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
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 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#ifndef _ResourceGroupManager_H__
#define _ResourceGroupManager_H__
#include "OgrePrerequisites.h"
#include "OgreSingleton.h"
#include "OgreCommon.h"
#include "OgreDataStream.h"
#include "OgreResource.h"
#include "OgreArchive.h"
#include "OgreIteratorWrappers.h"
#include <ctime>
/// If X11/Xlib.h gets included before this header (for example it happens when
/// including wxWidgets and FLTK), Status is defined as an int which we don't
/// want as we have an enum named Status.
#ifdef Status
#undef Status
#endif
namespace Ogre {
/** This abstract class defines an interface which is called back during
resource group loading to indicate the progress of the load.
@remarks
Resource group loading is in 2 phases - creating resources from
declarations (which includes parsing scripts), and loading
resources. Note that you don't necessarily have to have both; it
is quite possible to just parse all the scripts for a group (see
ResourceGroupManager::initialiseResourceGroup, but not to
load the resource group.
The sequence of events is (* signifies a repeating item):
<ul>
<li>resourceGroupScriptingStarted</li>
<li>scriptParseStarted (*)</li>
<li>scriptParseEnded (*)</li>
<li>resourceGroupScriptingEnded</li>
<li>resourceGroupLoadStarted</li>
<li>resourceLoadStarted (*)</li>
<li>resourceLoadEnded (*)</li>
<li>worldGeometryStageStarted (*)</li>
<li>worldGeometryStageEnded (*)</li>
<li>resourceGroupLoadEnded</li>
<li>resourceGroupPrepareStarted</li>
<li>resourcePrepareStarted (*)</li>
<li>resourcePrepareEnded (*)</li>
<li>resourceGroupPrepareEnded</li>
</ul>
@note
If OGRE_THREAD_SUPPORT is 1, this class is thread-safe.
*/
class _OgreExport ResourceGroupListener
{
public:
virtual ~ResourceGroupListener() {}
/** This event is fired when a resource group begins parsing scripts.
@note
Remember that if you are loading resources through ResourceBackgroundQueue,
these callbacks will occur in the background thread, so you should
not perform any thread-unsafe actions in this callback if that's the
case (check the group name / script name).
@param groupName The name of the group
@param scriptCount The number of scripts which will be parsed
*/
virtual void resourceGroupScriptingStarted(const String& groupName, size_t scriptCount) = 0;
/** This event is fired when a script is about to be parsed.
@param scriptName Name of the to be parsed
@param skipThisScript A boolean passed by reference which is by default set to
false. If the event sets this to true, the script will be skipped and not
parsed. Note that in this case the scriptParseEnded event will not be raised
for this script.
*/
virtual void scriptParseStarted(const String& scriptName, bool& skipThisScript) = 0;
/** This event is fired when the script has been fully parsed.
*/
virtual void scriptParseEnded(const String& scriptName, bool skipped) = 0;
/** This event is fired when a resource group finished parsing scripts. */
virtual void resourceGroupScriptingEnded(const String& groupName) = 0;
/** This event is fired when a resource group begins preparing.
@param groupName The name of the group being prepared
@param resourceCount The number of resources which will be prepared, including
a number of stages required to prepare any linked world geometry
*/
virtual void resourceGroupPrepareStarted(const String& groupName, size_t resourceCount) {}
/** This event is fired when a declared resource is about to be prepared.
@param resource Weak reference to the resource prepared.
*/
virtual void resourcePrepareStarted(const ResourcePtr& resource) {}
/** This event is fired when the resource has been prepared.
*/
virtual void resourcePrepareEnded(void) {}
/** This event is fired when a stage of preparing linked world geometry
is about to start. The number of stages required will have been
included in the resourceCount passed in resourceGroupLoadStarted.
@param description Text description of what was just prepared
*/
virtual void worldGeometryPrepareStageStarted(const String& description) {}
/** This event is fired when a stage of preparing linked world geometry
has been completed. The number of stages required will have been
included in the resourceCount passed in resourceGroupLoadStarted.
@param description Text description of what was just prepared
*/
virtual void worldGeometryPrepareStageEnded(void) {}
/** This event is fired when a resource group finished preparing. */
virtual void resourceGroupPrepareEnded(const String& groupName) {}
/** This event is fired when a resource group begins loading.
@param groupName The name of the group being loaded
@param resourceCount The number of resources which will be loaded, including
a number of stages required to load any linked world geometry
*/
virtual void resourceGroupLoadStarted(const String& groupName, size_t resourceCount) = 0;
/** This event is fired when a declared resource is about to be loaded.
@param resource Weak reference to the resource loaded.
*/
virtual void resourceLoadStarted(const ResourcePtr& resource) = 0;
/** This event is fired when the resource has been loaded.
*/
virtual void resourceLoadEnded(void) = 0;
/** This event is fired when a stage of loading linked world geometry
is about to start. The number of stages required will have been
included in the resourceCount passed in resourceGroupLoadStarted.
@param description Text description of what was just loaded
*/
virtual void worldGeometryStageStarted(const String& description) = 0;
/** This event is fired when a stage of loading linked world geometry
has been completed. The number of stages required will have been
included in the resourceCount passed in resourceGroupLoadStarted.
@param description Text description of what was just loaded
*/
virtual void worldGeometryStageEnded(void) = 0;
/** This event is fired when a resource group finished loading. */
virtual void resourceGroupLoadEnded(const String& groupName) = 0;
};
/**
@remarks This class allows users to override resource loading behavior.
By overriding this class' methods, you can change how resources
are loaded and the behavior for resource name collisions.
*/
class ResourceLoadingListener
{
public:
virtual ~ResourceLoadingListener() {}
/** This event is called when a resource beings loading. */
virtual DataStreamPtr resourceLoading(const String &name, const String &group, Resource *resource) = 0;
/** This event is called when a resource stream has been opened, but not processed yet.
@remarks
You may alter the stream if you wish or alter the incoming pointer to point at
another stream if you wish.
*/
virtual void resourceStreamOpened(const String &name, const String &group, Resource *resource, DataStreamPtr& dataStream) = 0;
/** This event is called when a resource collides with another existing one in a resource manager
*/
virtual bool resourceCollision(Resource *resource, ResourceManager *resourceManager) = 0;
};
/** This singleton class manages the list of resource groups, and notifying
the various resource managers of their obligations to load / unload
resources in a group. It also provides facilities to monitor resource
loading per group (to do progress bars etc), provided the resources
that are required are pre-registered.
@par
Defining new resource groups, and declaring the resources you intend to
use in advance is optional, however it is a very useful feature. In addition,
if a ResourceManager supports the definition of resources through scripts,
then this is the class which drives the locating of the scripts and telling
the ResourceManager to parse them.
@par
There are several states that a resource can be in (the concept, not the
object instance in this case):
<ol>
<li><b>Undefined</b>. Nobody knows about this resource yet. It might be
in the filesystem, but Ogre is oblivious to it at the moment - there
is no Resource instance. This might be because it's never been declared
(either in a script, or using ResourceGroupManager::declareResource), or
it may have previously been a valid Resource instance but has been
removed, either individually through ResourceManager::remove or as a group
through ResourceGroupManager::clearResourceGroup.</li>
<li><b>Declared</b>. Ogre has some forewarning of this resource, either
through calling ResourceGroupManager::declareResource, or by declaring
the resource in a script file which is on one of the resource locations
which has been defined for a group. There is still no instance of Resource,
but Ogre will know to create this resource when
ResourceGroupManager::initialiseResourceGroup is called (which is automatic
if you declare the resource group before Root::initialise).</li>
<li><b>Unloaded</b>. There is now a Resource instance for this resource,
although it is not loaded. This means that code which looks for this
named resource will find it, but the Resource is not using a lot of memory
because it is in an unloaded state. A Resource can get into this state
by having just been created by ResourceGroupManager::initialiseResourceGroup
(either from a script, or from a call to declareResource), by
being created directly from code (ResourceManager::create), or it may
have previously been loaded and has been unloaded, either individually
through Resource::unload, or as a group through ResourceGroupManager::unloadResourceGroup.</li>
<li><b>Loaded</b>The Resource instance is fully loaded. This may have
happened implicitly because something used it, or it may have been
loaded as part of a group.</li>
</ol>
@see ResourceGroupManager::declareResource
@see ResourceGroupManager::initialiseResourceGroup
@see ResourceGroupManager::loadResourceGroup
@see ResourceGroupManager::unloadResourceGroup
@see ResourceGroupManager::clearResourceGroup
*/
class _OgreExport ResourceGroupManager : public Singleton<ResourceGroupManager>, public ResourceAlloc
{
public:
OGRE_AUTO_MUTEX // public to allow external locking
/// Default resource group name
static String DEFAULT_RESOURCE_GROUP_NAME;
/// Internal resource group name (should be used by OGRE internal only)
static String INTERNAL_RESOURCE_GROUP_NAME;
/// Bootstrap resource group name (min OGRE resources)
static String BOOTSTRAP_RESOURCE_GROUP_NAME;
/// Special resource group name which causes resource group to be automatically determined based on searching for the resource in all groups.
static String AUTODETECT_RESOURCE_GROUP_NAME;
/// The number of reference counts held per resource by the resource system
static size_t RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS;
/// Nested struct defining a resource declaration
struct ResourceDeclaration
{
String resourceName;
String resourceType;
ManualResourceLoader* loader;
NameValuePairList parameters;
};
/// List of resource declarations
typedef std::list<ResourceDeclaration> ResourceDeclarationList;
typedef std::map<String, ResourceManager*> ResourceManagerMap;
typedef MapIterator<ResourceManagerMap> ResourceManagerIterator;
protected:
/// Map of resource types (strings) to ResourceManagers, used to notify them to load / unload group contents
ResourceManagerMap mResourceManagerMap;
/// Map of loading order (Real) to ScriptLoader, used to order script parsing
typedef std::multimap<Real, ScriptLoader*> ScriptLoaderOrderMap;
ScriptLoaderOrderMap mScriptLoaderOrderMap;
typedef std::vector<ResourceGroupListener*> ResourceGroupListenerList;
ResourceGroupListenerList mResourceGroupListenerList;
ResourceLoadingListener *mLoadingListener;
/// Resource index entry, resourcename->location
typedef std::map<String, Archive*> ResourceLocationIndex;
/// Resource location entry
struct ResourceLocation
{
/// Pointer to the archive which is the destination
Archive* archive;
/// Whether this location was added recursively
bool recursive;
};
/// List of possible file locations
typedef std::list<ResourceLocation*> LocationList;
/// List of resources which can be loaded / unloaded
typedef std::list<ResourcePtr> LoadUnloadResourceList;
/// Resource group entry
struct ResourceGroup
{
enum Status
{
UNINITIALSED = 0,
INITIALISING = 1,
INITIALISED = 2,
LOADING = 3,
LOADED = 4
};
/// General mutex for dealing with group content
OGRE_AUTO_MUTEX
/// Status-specific mutex, separate from content-changing mutex
OGRE_MUTEX(statusMutex)
/// Group name
String name;
/// Group status
Status groupStatus;
/// List of possible locations to search
LocationList locationList;
/// Index of resource names to locations, built for speedy access (case sensitive archives)
ResourceLocationIndex resourceIndexCaseSensitive;
/// Index of resource names to locations, built for speedy access (case insensitive archives)
ResourceLocationIndex resourceIndexCaseInsensitive;
/// Pre-declared resources, ready to be created
ResourceDeclarationList resourceDeclarations;
/// Created resources which are ready to be loaded / unloaded
// Group by loading order of the type (defined by ResourceManager)
// (e.g. skeletons and materials before meshes)
typedef std::map<Real, LoadUnloadResourceList*> LoadResourceOrderMap;
LoadResourceOrderMap loadResourceOrderMap;
/// Linked world geometry, as passed to setWorldGeometry
String worldGeometry;
/// Scene manager to use with linked world geometry
SceneManager* worldGeometrySceneManager;
};
/// Map from resource group names to groups
typedef std::map<String, ResourceGroup*> ResourceGroupMap;
ResourceGroupMap mResourceGroupMap;
/// Group name for world resources
String mWorldGroupName;
/** Parses all the available scripts found in the resource locations
for the given group, for all ResourceManagers.
@remarks
Called as part of initialiseResourceGroup
*/
void parseResourceGroupScripts(ResourceGroup* grp);
/** Create all the pre-declared resources.
@remarks
Called as part of initialiseResourceGroup
*/
void createDeclaredResources(ResourceGroup* grp);
/** Adds a created resource to a group. */
void addCreatedResource(ResourcePtr& res, ResourceGroup& group);
/** Get resource group */
ResourceGroup* getResourceGroup(const String& name);
/** Drops contents of a group, leave group there, notify ResourceManagers. */
void dropGroupContents(ResourceGroup* grp);
/** Delete a group for shutdown - don't notify ResourceManagers. */
void deleteGroup(ResourceGroup* grp);
/// Internal find method for auto groups
ResourceGroup* findGroupContainingResourceImpl(const String& filename);
/// Internal event firing method
void fireResourceGroupScriptingStarted(const String& groupName, size_t scriptCount);
/// Internal event firing method
void fireScriptStarted(const String& scriptName, bool &skipScript);
/// Internal event firing method
void fireScriptEnded(const String& scriptName, bool skipped);
/// Internal event firing method
void fireResourceGroupScriptingEnded(const String& groupName);
/// Internal event firing method
void fireResourceGroupLoadStarted(const String& groupName, size_t resourceCount);
/// Internal event firing method
void fireResourceLoadStarted(const ResourcePtr& resource);
/// Internal event firing method
void fireResourceLoadEnded(void);
/// Internal event firing method
void fireResourceGroupLoadEnded(const String& groupName);
/// Internal event firing method
void fireResourceGroupPrepareStarted(const String& groupName, size_t resourceCount);
/// Internal event firing method
void fireResourcePrepareStarted(const ResourcePtr& resource);
/// Internal event firing method
void fireResourcePrepareEnded(void);
/// Internal event firing method
void fireResourceGroupPrepareEnded(const String& groupName);
/// Stored current group - optimisation for when bulk loading a group
ResourceGroup* mCurrentGroup;
public:
ResourceGroupManager();
virtual ~ResourceGroupManager();
/** Create a resource group.
@remarks
A resource group allows you to define a set of resources that can
be loaded / unloaded as a unit. For example, it might be all the
resources used for the level of a game. There is always one predefined
resource group called ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
which is typically used to hold all resources which do not need to
be unloaded until shutdown. There is another predefined resource
group called ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME too,
which should be used by OGRE internal only, the resources created
in this group aren't supposed to modify, unload or remove by user.
You can create additional ones so that you can control the life of
your resources in whichever way you wish.
There is one other predefined value,
ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME; using this
causes the group name to be derived at load time by searching for
the resource in the resource locations of each group in turn.
@par
Once you have defined a resource group, resources which will be loaded
as part of it are defined in one of 3 ways:
<ol>
<li>Manually through declareResource(); this is useful for scripted
declarations since it is entirely generalised, and does not
create Resource instances right away</li>
<li>Through the use of scripts; some ResourceManager subtypes have
script formats (e.g. .material, .overlay) which can be used
to declare resources</li>
<li>By calling ResourceManager::create to create a resource manually.
This resource will go on the list for it's group and will be loaded
and unloaded with that group</li>
</ol>
You must remember to call initialiseResourceGroup if you intend to use
the first 2 types.
@param name The name to give the resource group.
*/
void createResourceGroup(const String& name);
/** Initialises a resource group.
@remarks
After creating a resource group, adding some resource locations, and
perhaps pre-declaring some resources using declareResource(), but
before you need to use the resources in the group, you
should call this method to initialise the group. By calling this,
you are triggering the following processes:
<ol>
<li>Scripts for all resource types which support scripting are
parsed from the resource locations, and resources within them are
created (but not loaded yet).</li>
<li>Creates all the resources which have just pre-declared using
declareResource (again, these are not loaded yet)</li>
</ol>
So what this essentially does is create a bunch of unloaded Resource entries
in the respective ResourceManagers based on scripts, and resources
you've pre-declared. That means that code looking for these resources
will find them, but they won't be taking up much memory yet, until
they are either used, or they are loaded in bulk using loadResourceGroup.
Loading the resource group in bulk is entirely optional, but has the
advantage of coming with progress reporting as resources are loaded.
@par
Failure to call this method means that loadResourceGroup will do
nothing, and any resources you define in scripts will not be found.
Similarly, once you have called this method you won't be able to
pick up any new scripts or pre-declared resources, unless you
call clearResourceGroup, set up declared resources, and call this
method again.
@note
When you call Root::initialise, all resource groups that have already been
created are automatically initialised too. Therefore you do not need to
call this method for groups you define and set up before you call
Root::initialise. However, since one of the most useful features of
resource groups is to set them up after the main system initialisation
has occurred (e.g. a group per game level), you must remember to call this
method for the groups you create after this.
@param name The name of the resource group to initialise
*/
void initialiseResourceGroup(const String& name);
/** Initialise all resource groups which are yet to be initialised.
@see ResourceGroupManager::intialiseResourceGroup
*/
void initialiseAllResourceGroups(void);
/** Prepares a resource group.
@remarks
Prepares any created resources which are part of the named group.
Note that resources must have already been created by calling
ResourceManager::create, or declared using declareResource() or
in a script (such as .material and .overlay). The latter requires
that initialiseResourceGroup has been called.
When this method is called, this class will callback any ResourceGroupListeners
which have been registered to update them on progress.
@param name The name of the resource group to prepare.
@param prepareMainResources If true, prepares normal resources associated
with the group (you might want to set this to false if you wanted
to just prepare world geometry in bulk)
@param prepareWorldGeom If true, prepares any linked world geometry
@see ResourceGroupManager::linkWorldGeometryToResourceGroup
*/
void prepareResourceGroup(const String& name, bool prepareMainResources = true,
bool prepareWorldGeom = true);
/** Loads a resource group.
@remarks
Loads any created resources which are part of the named group.
Note that resources must have already been created by calling
ResourceManager::create, or declared using declareResource() or
in a script (such as .material and .overlay). The latter requires
that initialiseResourceGroup has been called.
When this method is called, this class will callback any ResourceGroupListeners
which have been registered to update them on progress.
@param name The name of the resource group to load.
@param loadMainResources If true, loads normal resources associated
with the group (you might want to set this to false if you wanted
to just load world geometry in bulk)
@param loadWorldGeom If true, loads any linked world geometry
@see ResourceGroupManager::linkWorldGeometryToResourceGroup
*/
void loadResourceGroup(const String& name, bool loadMainResources = true,
bool loadWorldGeom = true);
/** Unloads a resource group.
@remarks
This method unloads all the resources that have been declared as
being part of the named resource group. Note that these resources
will still exist in their respective ResourceManager classes, but
will be in an unloaded state. If you want to remove them entirely,
you should use clearResourceGroup or destroyResourceGroup.
@param name The name to of the resource group to unload.
@param reloadableOnly If set to true, only unload the resource that is
reloadable. Because some resources isn't reloadable, they will be
unloaded but can't load them later. Thus, you might not want to them
unloaded. Or, you might unload all of them, and then populate them
manually later.
@see Resource::isReloadable for resource is reloadable.
*/
void unloadResourceGroup(const String& name, bool reloadableOnly = true);
/** Unload all resources which are not referenced by any other object.
@remarks
This method behaves like unloadResourceGroup, except that it only
unloads resources in the group which are not in use, ie not referenced
by other objects. This allows you to free up some memory selectively
whilst still keeping the group around (and the resources present,
just not using much memory).
@param name The name of the group to check for unreferenced resources
@param reloadableOnly If true (the default), only unloads resources
which can be subsequently automatically reloaded
*/
void unloadUnreferencedResourcesInGroup(const String& name,
bool reloadableOnly = true);
/** Clears a resource group.
@remarks
This method unloads all resources in the group, but in addition it
removes all those resources from their ResourceManagers, and then
clears all the members from the list. That means after calling this
method, there are no resources declared as part of the named group
any more. Resource locations still persist though.
@param name The name to of the resource group to clear.
*/
void clearResourceGroup(const String& name);
/** Destroys a resource group, clearing it first, destroying the resources
which are part of it, and then removing it from
the list of resource groups.
@param name The name of the resource group to destroy.
*/
void destroyResourceGroup(const String& name);
/** Checks the status of a resource group.
@remarks
Looks at the state of a resource group.
If initialiseResourceGroup has been called for the resource
group return true, otherwise return false.
@param name The name to of the resource group to access.
*/
bool isResourceGroupInitialised(const String& name);
/** Checks the status of a resource group.
@remarks
Looks at the state of a resource group.
If loadResourceGroup has been called for the resource
group return true, otherwise return false.
@param name The name to of the resource group to access.
*/
bool isResourceGroupLoaded(const String& name);
/** Method to add a resource location to for a given resource group.
@remarks
Resource locations are places which are searched to load resource files.
When you choose to load a file, or to search for valid files to load,
the resource locations are used.
@param name The name of the resource location; probably a directory, zip file, URL etc.
@param locType The codename for the resource type, which must correspond to the
Archive factory which is providing the implementation.
@param resGroup The name of the resource group for which this location is
to apply. ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME is the
default group which always exists, and can
be used for resources which are unlikely to be unloaded until application
shutdown. Otherwise it must be the name of a group; if it
has not already been created with createResourceGroup then it is created
automatically.
@param recursive Whether subdirectories will be searched for files when using
a pattern match (such as *.material), and whether subdirectories will be
indexed. This can slow down initial loading of the archive and searches.
When opening a resource you still need to use the fully qualified name,
this allows duplicate names in alternate paths.
*/
void addResourceLocation(const String& name, const String& locType,
const String& resGroup = DEFAULT_RESOURCE_GROUP_NAME, bool recursive = false);
/** Removes a resource location from the search path. */
void removeResourceLocation(const String& name,
const String& resGroup = DEFAULT_RESOURCE_GROUP_NAME);
/** Declares a resource to be a part of a resource group, allowing you
to load and unload it as part of the group.
@remarks
By declaring resources before you attempt to use them, you can
more easily control the loading and unloading of those resources
by their group. Declaring them also allows them to be enumerated,
which means events can be raised to indicate the loading progress
(@see ResourceGroupListener). Note that another way of declaring
resources is to use a script specific to the resource type, if
available (e.g. .material).
@par
Declared resources are not created as Resource instances (and thus
are not available through their ResourceManager) until initialiseResourceGroup
is called, at which point all declared resources will become created
(but unloaded) Resource instances, along with any resources declared
in scripts in resource locations associated with the group.
@param name The resource name.
@param resourceType The type of the resource. Ogre comes preconfigured with
a number of resource types:
<ul>
<li>Font</li>
<li>GpuProgram</li>
<li>HighLevelGpuProgram</li>
<li>Material</li>
<li>Mesh</li>
<li>Skeleton</li>
<li>Texture</li>
</ul>
.. but more can be added by plugin ResourceManager classes.
@param groupName The name of the group to which it will belong.
@param loadParameters A list of name / value pairs which supply custom
parameters to the resource which will be required before it can
be loaded. These are specific to the resource type.
*/
void declareResource(const String& name, const String& resourceType,
const String& groupName = DEFAULT_RESOURCE_GROUP_NAME,
const NameValuePairList& loadParameters = NameValuePairList());
/** Declares a resource to be a part of a resource group, allowing you
to load and unload it as part of the group.
@remarks
By declaring resources before you attempt to use them, you can
more easily control the loading and unloading of those resources
by their group. Declaring them also allows them to be enumerated,
which means events can be raised to indicate the loading progress
(@see ResourceGroupListener). Note that another way of declaring
resources is to use a script specific to the resource type, if
available (e.g. .material).
@par
Declared resources are not created as Resource instances (and thus
are not available through their ResourceManager) until initialiseResourceGroup
is called, at which point all declared resources will become created
(but unloaded) Resource instances, along with any resources declared
in scripts in resource locations associated with the group.
@param name The resource name.
@param resourceType The type of the resource. Ogre comes preconfigured with
a number of resource types:
<ul>
<li>Font</li>
<li>GpuProgram</li>
<li>HighLevelGpuProgram</li>
<li>Material</li>
<li>Mesh</li>
<li>Skeleton</li>
<li>Texture</li>
</ul>
.. but more can be added by plugin ResourceManager classes.
@param groupName The name of the group to which it will belong.
@param loader Pointer to a ManualResourceLoader implementation which will
be called when the Resource wishes to load. If supplied, the resource
is manually loaded, otherwise it'll loading from file automatic.
@note We don't support declare manually loaded resource without loader
here, since it's meaningless.
@param loadParameters A list of name / value pairs which supply custom
parameters to the resource which will be required before it can
be loaded. These are specific to the resource type.
*/
void declareResource(const String& name, const String& resourceType,
const String& groupName, ManualResourceLoader* loader,
const NameValuePairList& loadParameters = NameValuePairList());
/** Undeclare a resource.
@remarks
Note that this will not cause it to be unloaded
if it is already loaded, nor will it destroy a resource which has
already been created if initialiseResourceGroup has been called already.
Only unloadResourceGroup / clearResourceGroup / destroyResourceGroup
will do that.
@param name The name of the resource.
@param groupName The name of the group this resource was declared in.
*/
void undeclareResource(const String& name, const String& groupName);
/** Open a single resource by name and return a DataStream
pointing at the source of the data.
@param resourceName The name of the resource to locate.
Even if resource locations are added recursively, you
must provide a fully qualified name to this method. You
can find out the matching fully qualified names by using the
find() method if you need to.
@param groupName The name of the resource group; this determines which
locations are searched.
@param searchGroupsIfNotFound If true, if the resource is not found in
the group specified, other groups will be searched. If you're
loading a real Resource using this option, you <strong>must</strong>
also provide the resourceBeingLoaded parameter to enable the
group membership to be changed
@param resourceBeingLoaded Optional pointer to the resource being
loaded, which you should supply if you want
@returns Shared pointer to data stream containing the data, will be
destroyed automatically when no longer referenced
*/
DataStreamPtr openResource(const String& resourceName,
const String& groupName = DEFAULT_RESOURCE_GROUP_NAME,
bool searchGroupsIfNotFound = true, Resource* resourceBeingLoaded = 0);
/** Open all resources matching a given pattern (which can contain
the character '*' as a wildcard), and return a collection of
DataStream objects on them.
@param pattern The pattern to look for. If resource locations have been
added recursively, subdirectories will be searched too so this
does not need to be fully qualified.
@param groupName The resource group; this determines which locations
are searched.
@returns Shared pointer to a data stream list , will be
destroyed automatically when no longer referenced
*/
DataStreamListPtr openResources(const String& pattern,
const String& groupName = DEFAULT_RESOURCE_GROUP_NAME);
/** List all file or directory names in a resource group.
@note
This method only returns filenames, you can also retrieve other
information using listFileInfo.
@param groupName The name of the group
@param dirs If true, directory names will be returned instead of file names
@returns A list of filenames matching the criteria, all are fully qualified
*/
StringVectorPtr listResourceNames(const String& groupName, bool dirs = false);
/** List all files in a resource group with accompanying information.
@param groupName The name of the group
@param dirs If true, directory names will be returned instead of file names
@returns A list of structures detailing quite a lot of information about
all the files in the archive.
*/
FileInfoListPtr listResourceFileInfo(const String& groupName, bool dirs = false);
/** Find all file or directory names matching a given pattern in a
resource group.
@note
This method only returns filenames, you can also retrieve other
information using findFileInfo.
@param groupName The name of the group
@param pattern The pattern to search for; wildcards (*) are allowed
@param dirs Set to true if you want the directories to be listed
instead of files
@returns A list of filenames matching the criteria, all are fully qualified
*/
StringVectorPtr findResourceNames(const String& groupName, const String& pattern,
bool dirs = false);
/** Find out if the named file exists in a group.
@param group The name of the resource group
@param filename Fully qualified name of the file to test for
*/
bool resourceExists(const String& group, const String& filename);
/** Find out if the named file exists in a group.
@param group Pointer to the resource group
@param filename Fully qualified name of the file to test for
*/
bool resourceExists(ResourceGroup* group, const String& filename);
/** Find the group in which a resource exists.
@param filename Fully qualified name of the file the resource should be
found as
@returns Name of the resource group the resource was found in. An
exception is thrown if the group could not be determined.
*/
const String& findGroupContainingResource(const String& filename);
/** Find all files or directories matching a given pattern in a group
and get some detailed information about them.
@param group The name of the resource group
@param pattern The pattern to search for; wildcards (*) are allowed
@param dirs Set to true if you want the directories to be listed
instead of files
@returns A list of file information structures for all files matching
the criteria.
*/
FileInfoListPtr findResourceFileInfo(const String& group, const String& pattern,
bool dirs = false);
/** Retrieve the modification time of a given file */
time_t resourceModifiedTime(const String& group, const String& filename);
/** Retrieve the modification time of a given file */
time_t resourceModifiedTime(ResourceGroup* group, const String& filename);
/** Adds a ResourceGroupListener which will be called back during
resource loading events.
*/
void addResourceGroupListener(ResourceGroupListener* l);
/** Removes a ResourceGroupListener */
void removeResourceGroupListener(ResourceGroupListener* l);
/** Sets the resource group that 'world' resources will use.
@remarks
This is the group which should be used by SceneManagers implementing
world geometry when looking for their resources. Defaults to the
DEFAULT_RESOURCE_GROUP_NAME but this can be altered.
*/
void setWorldResourceGroupName(const String& groupName) {mWorldGroupName = groupName;}
/// Gets the resource group that 'world' resources will use.
const String& getWorldResourceGroupName(void) const { return mWorldGroupName; }
/** Associates some world geometry with a resource group, causing it to
be loaded / unloaded with the resource group.
@remarks
You would use this method to essentially defer a call to
SceneManager::setWorldGeometry to the time when the resource group
is loaded. The advantage of this is that compatible scene managers
will include the estimate of the number of loading stages for that
world geometry when the resource group begins loading, allowing you
to include that in a loading progress report.
@param group The name of the resource group
@param worldGeometry The parameter which should be passed to setWorldGeometry
@param sceneManager The SceneManager which should be called
*/
void linkWorldGeometryToResourceGroup(const String& group,
const String& worldGeometry, SceneManager* sceneManager);
/** Clear any link to world geometry from a resource group.
@remarks
Basically undoes a previous call to linkWorldGeometryToResourceGroup.
*/
void unlinkWorldGeometryFromResourceGroup(const String& group);
/** Shutdown all ResourceManagers, performed as part of clean-up. */
void shutdownAll(void);
/** Internal method for registering a ResourceManager (which should be
a singleton). Creators of plugins can register new ResourceManagers
this way if they wish.
@remarks
ResourceManagers that wish to parse scripts must also call
_registerScriptLoader.
@param resourceType String identifying the resource type, must be unique.
@param rm Pointer to the ResourceManager instance.
*/
void _registerResourceManager(const String& resourceType, ResourceManager* rm);
/** Internal method for unregistering a ResourceManager.
@remarks
ResourceManagers that wish to parse scripts must also call
_unregisterScriptLoader.
@param resourceType String identifying the resource type.
*/
void _unregisterResourceManager(const String& resourceType);
/** Get an iterator over the registered resource managers.
*/
ResourceManagerIterator getResourceManagerIterator()
{ return ResourceManagerIterator(
mResourceManagerMap.begin(), mResourceManagerMap.end()); }
/** Internal method for registering a ScriptLoader.
@remarks ScriptLoaders parse scripts when resource groups are initialised.
@param su Pointer to the ScriptLoader instance.
*/
void _registerScriptLoader(ScriptLoader* su);
/** Internal method for unregistering a ScriptLoader.
@param su Pointer to the ScriptLoader instance.
*/
void _unregisterScriptLoader(ScriptLoader* su);
/** Internal method for getting a registered ResourceManager.
@param resourceType String identifying the resource type.
*/
ResourceManager* _getResourceManager(const String& resourceType);
/** Internal method called by ResourceManager when a resource is created.
@param res Weak reference to resource
*/
void _notifyResourceCreated(ResourcePtr& res);
/** Internal method called by ResourceManager when a resource is removed.
@param res Weak reference to resource
*/
void _notifyResourceRemoved(ResourcePtr& res);
/** Internal method to notify the group manager that a resource has
changed group (only applicable for autodetect group) */
void _notifyResourceGroupChanged(const String& oldGroup, Resource* res);
/** Internal method called by ResourceManager when all resources
for that manager are removed.
@param manager Pointer to the manager for which all resources are being removed
*/
void _notifyAllResourcesRemoved(ResourceManager* manager);
/** Notify this manager that one stage of world geometry loading has been
started.
@remarks
Custom SceneManagers which load custom world geometry should call this
method the number of times equal to the value they return from
SceneManager::estimateWorldGeometry while loading their geometry.
*/
void _notifyWorldGeometryPrepareStageStarted(const String& description);
/** Notify this manager that one stage of world geometry loading has been
completed.
@remarks
Custom SceneManagers which load custom world geometry should call this
method the number of times equal to the value they return from
SceneManager::estimateWorldGeometry while loading their geometry.
*/
void _notifyWorldGeometryPrepareStageEnded(void);
/** Notify this manager that one stage of world geometry loading has been
started.
@remarks
Custom SceneManagers which load custom world geometry should call this
method the number of times equal to the value they return from
SceneManager::estimateWorldGeometry while loading their geometry.
*/
void _notifyWorldGeometryStageStarted(const String& description);
/** Notify this manager that one stage of world geometry loading has been
completed.
@remarks
Custom SceneManagers which load custom world geometry should call this
method the number of times equal to the value they return from
SceneManager::estimateWorldGeometry while loading their geometry.
*/
void _notifyWorldGeometryStageEnded(void);
/** Get a list of the currently defined resource groups.
@note This method intentionally returns a copy rather than a reference in
order to avoid any contention issues in multithreaded applications.
@returns A copy of list of currently defined groups.
*/
StringVector getResourceGroups(void);
/** Get the list of resource declarations for the specified group name.
@note This method intentionally returns a copy rather than a reference in
order to avoid any contention issues in multithreaded applications.
@param groupName The name of the group
@returns A copy of list of currently defined resources.
*/
ResourceDeclarationList getResourceDeclarationList(const String& groupName);
/// Sets a new loading listener
void setLoadingListener(ResourceLoadingListener *listener);
/// Returns the current loading listener
ResourceLoadingListener *getLoadingListener();
/** Override standard Singleton retrieval.
@remarks
Why do we do this? Well, it's because the Singleton
implementation is in a .h file, which means it gets compiled
into anybody who includes it. This is needed for the
Singleton template to work, but we actually only want it
compiled into the implementation of the class based on the
Singleton, not all of them. If we don't change this, we get
link errors when trying to use the Singleton-based class from
an outside dll.
@par
This method just delegates to the template version anyway,
but the implementation stays in this single compilation unit,
preventing link errors.
*/
static ResourceGroupManager& getSingleton(void);
/** Override standard Singleton retrieval.
@remarks
Why do we do this? Well, it's because the Singleton
implementation is in a .h file, which means it gets compiled
into anybody who includes it. This is needed for the
Singleton template to work, but we actually only want it
compiled into the implementation of the class based on the
Singleton, not all of them. If we don't change this, we get
link errors when trying to use the Singleton-based class from
an outside dll.
@par
This method just delegates to the template version anyway,
but the implementation stays in this single compilation unit,
preventing link errors.
*/
static ResourceGroupManager* getSingletonPtr(void);
};
}
#endif
| 1 | 0.821531 | 1 | 0.821531 | game-dev | MEDIA | 0.520085 | game-dev | 0.791357 | 1 | 0.791357 |
llafuente/unity-platformer | 1,655 | Assets/UnityPlatformer/Scripts/Characters/Health/Damage.cs | using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Assertions;
namespace UnityPlatformer {
/// <summary>
/// Damage info
/// </summary>
public class Damage : MonoBehaviour {
/// <summary>
/// Damage amount
/// </summary>
[Comment("Damage amount")]
public int amount = 1;
/// <summary>
/// Damage type
/// </summary>
public DamageType type = DamageType.Default;
/// <summary>
/// who cause this damage
/// </summary>
public CharacterHealth causer;
/// <summary>
/// TODO direction will be calc, someday :)
/// </summary>
[HideInInspector]
public Vector3 direction;
/// <summary>
/// Can deal Damage to friends (same alignment)\n
/// NOTE: that require CharacterHealth.friendlyFire to be on.
/// </summary>
public bool friendlyFire = false;
/// <summary>
/// check missconfiguration
/// </summary>
public void Start() {
Assert.IsNotNull(causer, "(Damage) causer cannot be null at " + gameObject.GetFullName());
// REVIEW this may not be necessary...
HitBox hitbox = GetComponent<HitBox> ();
Assert.IsNotNull(hitbox, "(Damage) Missing MonoBehaviour HitBox at " + gameObject.GetFullName());
if (hitbox.type != HitBoxType.DealDamage) {
Assert.IsNotNull(null, "(Damage) Damage found but hitbox type is not DealDamage at " + gameObject.GetFullName());
}
}
#if UNITY_EDITOR
/// <summary>
/// Set layer to Configuration.ropesMask
/// </summary>
void Reset() {
if (causer == null) {
causer = GetComponentInParent<CharacterHealth>();
}
}
#endif
}
}
| 1 | 0.882783 | 1 | 0.882783 | game-dev | MEDIA | 0.931875 | game-dev | 0.876588 | 1 | 0.876588 |
SinlessDevil/EcsStickmanSurvivors | 3,768 | src/ecs_stickman_survivors/Assets/Code/Gameplay/Features/Armaments/Systems/HandleTargetsForBouncesSystem.cs | using System.Collections.Generic;
using System.Linq;
using Code.Gameplay.Common.Physics;
using Entitas;
using UnityEngine;
namespace Code.Gameplay.Features.Armaments.Systems
{
public class HandleTargetsForBouncesSystem : IExecuteSystem
{
private readonly IGroup<GameEntity> _armaments;
private readonly IGroup<GameEntity> _enemies;
private readonly IGroup<GameEntity> _heroes;
private readonly GameContext _game;
private readonly List<GameEntity> _bufferHero = new(1);
private readonly List<GameEntity> _bufferArmaments = new(16);
private readonly IPhysicsService _physicsService;
public HandleTargetsForBouncesSystem(GameContext game, IPhysicsService physicsService)
{
_game = game;
_physicsService = physicsService;
_armaments = game.GetGroup(GameMatcher
.AllOf(GameMatcher.Armament,
GameMatcher.Target,
GameMatcher.BounceRate,
GameMatcher.WorldPosition,
GameMatcher.Radius,
GameMatcher.LayerMask));
_enemies = game.GetGroup(GameMatcher
.AllOf(
GameMatcher.Enemy,
GameMatcher.WorldPosition));
_heroes = game.GetGroup(GameMatcher
.AllOf(
GameMatcher.Hero,
GameMatcher.WorldPosition));
}
public void Execute()
{
foreach (GameEntity hero in _heroes.GetEntities(_bufferHero))
foreach (GameEntity armament in _armaments.GetEntities(_bufferArmaments))
{
// if (armament.BounceRate <= 0)
// continue;
if (armament.hasTarget)
{
var targetId = TargetsInRadius(armament);
if (targetId == 0)
continue;
GameEntity currentTarget = _game.GetEntityWithId(targetId);
if (currentTarget is { hasWorldPosition: true })
{
GameEntity newTarget = FindFarthestTarget(currentTarget);
if (newTarget != null)
{
armament.ReplaceTarget(newTarget.Id)
.ReplaceBounceRate(armament.BounceRate - 1)
.ReplaceDirection((newTarget.WorldPosition - hero.WorldPosition).normalized);
}
}
}
}
}
private int TargetsInRadius(GameEntity entity)
{
var targets = _physicsService
.CircleCast(entity.WorldPosition, entity.Radius, entity.LayerMask)
.OrderBy(t => Vector3.Distance(entity.WorldPosition, t.WorldPosition))
.Select(t => t.Id)
.ToList();
return targets.FirstOrDefault();
}
private GameEntity FindFarthestTarget(GameEntity currentTarget)
{
float farthestDistanceSquared = 0;
GameEntity farthestTarget = null;
foreach (GameEntity enemy in _enemies)
{
if (enemy == currentTarget || enemy == null)
continue;
float distanceSquared = (enemy.WorldPosition - currentTarget.WorldPosition).sqrMagnitude;
if (distanceSquared > farthestDistanceSquared)
{
farthestDistanceSquared = distanceSquared;
farthestTarget = enemy;
}
}
return farthestTarget;
}
}
} | 1 | 0.925303 | 1 | 0.925303 | game-dev | MEDIA | 0.756863 | game-dev | 0.882485 | 1 | 0.882485 |
Angry-Pixel/The-Betweenlands | 3,924 | src/main/java/thebetweenlands/common/recipe/misc/RecipeGrapplingHookUpgrades.java | package thebetweenlands.common.recipe.misc;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.registries.IForgeRegistryEntry;
import thebetweenlands.common.item.misc.ItemMisc.EnumItemMisc;
import thebetweenlands.common.registries.ItemRegistry;
public class RecipeGrapplingHookUpgrades extends IForgeRegistryEntry.Impl<IRecipe> implements IRecipe {
@Override
public boolean matches(InventoryCrafting craftMatrix, World world) {
int size = craftMatrix.getSizeInventory();
if (size < 3) {
return false;
}
ItemStack hook = ItemStack.EMPTY;
int tongues = 0;
int teeth = 0;
for (int i = 0; i < size; i++) {
ItemStack stack = craftMatrix.getStackInSlot(i);
if(!stack.isEmpty()) {
if(stack.getItem() == ItemRegistry.GRAPPLING_HOOK) {
hook = stack;
} else if(stack.getItem() == ItemRegistry.SHAMBLER_TONGUE) {
tongues++;
} else if(EnumItemMisc.ANGLER_TOOTH.isItemOf(stack)) {
teeth++;
}
}
}
return !hook.isEmpty() && hook.getItemDamage() < hook.getMaxDamage() && tongues > 0 && teeth >= 2;
}
@Override
public ItemStack getCraftingResult(InventoryCrafting craftMatrix) {
ItemStack hook = ItemStack.EMPTY;
int tongues = 0;
int teeth = 0;
for (int i = 0; i < craftMatrix.getSizeInventory(); i++) {
ItemStack stack = craftMatrix.getStackInSlot(i);
if(!stack.isEmpty()) {
if(stack.getItem() == ItemRegistry.GRAPPLING_HOOK) {
hook = stack;
} else if(stack.getItem() == ItemRegistry.SHAMBLER_TONGUE) {
tongues++;
} else if(EnumItemMisc.ANGLER_TOOTH.isItemOf(stack)) {
teeth++;
}
}
}
int nodesPerUpgrade = 3;
int newDamage = Math.min(hook.getItemDamage() + Math.min(tongues, teeth / 2) * nodesPerUpgrade, hook.getMaxDamage());
hook = hook.copy();
hook.setItemDamage(newDamage);
return hook;
}
@Override
public boolean canFit(int width, int height) {
return width * height >= 3;
}
@Override
public boolean isDynamic() {
return true;
}
@Override
public ItemStack getRecipeOutput() {
return new ItemStack(ItemRegistry.GRAPPLING_HOOK);
}
@Override
public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) {
ItemStack hook = ItemStack.EMPTY;
int tongues = 0;
int teeth = 0;
for (int i = 0; i < inv.getSizeInventory(); i++) {
ItemStack stack = inv.getStackInSlot(i);
if(!stack.isEmpty()) {
if(stack.getItem() == ItemRegistry.GRAPPLING_HOOK) {
hook = stack;
} else if(stack.getItem() == ItemRegistry.SHAMBLER_TONGUE) {
tongues++;
} else if(EnumItemMisc.ANGLER_TOOTH.isItemOf(stack)) {
teeth++;
}
}
}
int nodesPerUpgrade = 3;
int newDamage = Math.min(hook.getItemDamage() + Math.min(tongues, teeth / 2) * nodesPerUpgrade, hook.getMaxDamage());
int upgrades = MathHelper.ceil((newDamage - hook.getItemDamage()) / (float)nodesPerUpgrade);
int tonguesToRemove = upgrades;
int teethToRemove = upgrades * 2;
NonNullList<ItemStack> remaining = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY);
for (int i = 0; i < remaining.size(); ++i) {
ItemStack stack = inv.getStackInSlot(i);
boolean consume = true;
if(stack.getItem() == ItemRegistry.SHAMBLER_TONGUE) {
if(tonguesToRemove > 0) {
tonguesToRemove--;
} else {
consume = false;
}
} else if(EnumItemMisc.ANGLER_TOOTH.isItemOf(stack)) {
if(teethToRemove > 0) {
teethToRemove--;
} else {
consume = false;
}
}
if(consume) {
remaining.set(i, ForgeHooks.getContainerItem(stack));
} else {
stack = stack.copy();
stack.setCount(1);
remaining.set(i, stack);
}
}
return remaining;
}
}
| 1 | 0.846409 | 1 | 0.846409 | game-dev | MEDIA | 0.993337 | game-dev | 0.968175 | 1 | 0.968175 |
paxo-phone/PaxOS-8 | 2,191 | src/lib/lua/ltable.h | /*
** $Id: ltable.h $
** Lua tables (hash)
** See Copyright Notice in lua.h
*/
#ifndef ltable_h
#define ltable_h
#include "lobject.h"
#define gnode(t,i) (&(t)->node[i])
#define gval(n) (&(n)->i_val)
#define gnext(n) ((n)->u.next)
/*
** Clear all bits of fast-access metamethods, which means that the table
** may have any of these metamethods. (First access that fails after the
** clearing will set the bit again.)
*/
#define invalidateTMcache(t) ((t)->flags &= ~maskflags)
/* true when 't' is using 'dummynode' as its hash part */
#define isdummy(t) ((t)->lastfree == NULL)
/* allocated size for hash nodes */
#define allocsizenode(t) (isdummy(t) ? 0 : sizenode(t))
/* returns the Node, given the value of a table entry */
#define nodefromval(v) cast(Node *, (v))
LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key);
LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key,
TValue *value);
LUAI_FUNC const TValue *luaH_getshortstr (Table *t, TString *key);
LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);
LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);
LUAI_FUNC void luaH_newkey (lua_State *L, Table *t, const TValue *key,
TValue *value);
LUAI_FUNC void luaH_set (lua_State *L, Table *t, const TValue *key,
TValue *value);
LUAI_FUNC void luaH_finishset (lua_State *L, Table *t, const TValue *key,
const TValue *slot, TValue *value);
LUAI_FUNC Table *luaH_new (lua_State *L);
LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize,
unsigned int nhsize);
LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize);
LUAI_FUNC void luaH_free (lua_State *L, Table *t);
LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key);
LUAI_FUNC lua_Unsigned luaH_getn (Table *t);
LUAI_FUNC unsigned int luaH_realasize (const Table *t);
#if defined(LUA_DEBUG)
LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key);
#endif
#endif
| 1 | 0.92577 | 1 | 0.92577 | game-dev | MEDIA | 0.356398 | game-dev | 0.631624 | 1 | 0.631624 |
awgil/ffxiv_bossmod | 15,280 | BossMod/Modules/Shadowbringers/Foray/DelubrumReginae/DRS8Queen/DRS8States.cs | namespace BossMod.Shadowbringers.Foray.DelubrumReginae.DRS8Queen;
class DRS8States : StateMachineBuilder
{
public DRS8States(BossModule module) : base(module)
{
SimplePhase(0, Phase1, "P1")
.Raw.Update = () => Module.PrimaryActor.IsDestroyed || Module.PrimaryActor.HPMP.CurHP <= 1 || (Module.PrimaryActor.CastInfo?.IsSpell(AID.GodsSaveTheQueen) ?? false);
DeathPhase(1, Phase2);
}
private void Phase1(uint id)
{
EmpyreanIniquity(id, 10.2f);
QueensWill(id + 0x10000, 13.7f);
CleansingSlash(id + 0x20000, 10.9f);
EmpyreanIniquity(id + 0x30000, 4.2f);
QueensEdict(id + 0x40000, 11.5f);
SimpleState(id + 0x50000, 12.5f, "Second phase");
}
private void Phase2(uint id)
{
GodsSaveTheQueen(id, 0);
MaelstromsBolt(id + 0x10000, 31.7f);
RelentlessPlay1(id + 0x20000, 7.3f);
CleansingSlash(id + 0x30000, 4.4f);
RelentlessPlay2(id + 0x40000, 8.2f);
EmpyreanIniquity(id + 0x50000, 5.1f);
QueensEdict(id + 0x60000, 11.5f);
CleansingSlash(id + 0x70000, 2.1f);
RelentlessPlay3(id + 0x80000, 10.2f);
MaelstromsBolt(id + 0x90000, 16.3f);
EmpyreanIniquity(id + 0xA0000, 6.2f);
RelentlessPlay4(id + 0xB0000, 8.2f);
RelentlessPlay5(id + 0xC0000, 0.1f);
// TODO: boss gains damage up at +6.6, then presumably would start some enrage cast...
SimpleState(id + 0xD0000, 15, "Enrage");
}
private void EmpyreanIniquity(uint id, float delay)
{
Cast(id, AID.EmpyreanIniquity, delay, 5, "Raidwide")
.SetHint(StateMachine.StateHint.Raidwide);
}
private void CleansingSlash(uint id, float delay)
{
Cast(id, AID.CleansingSlashFirst, delay, 5, "Tankbuster 1")
.SetHint(StateMachine.StateHint.Tankbuster);
ComponentCondition<CleansingSlashSecond>(id + 2, 3.1f, comp => comp.NumCasts > 0, "Tankbuster 2")
.ActivateOnEnter<CleansingSlashSecond>()
.DeactivateOnExit<CleansingSlashSecond>()
.SetHint(StateMachine.StateHint.Tankbuster);
}
private void QueensWill(uint id, float delay)
{
// right before cast start: ENVC 19.00200010, guards gain 2056 status with extra 0xE1 + PATE 1E43
Cast(id, AID.QueensWill, delay, 5)
.ActivateOnEnter<QueensWill>() // statuses appear ~0.7s after cast end
.OnEnter(() => Module.Arena.Bounds = new ArenaBoundsSquare(Module.Bounds.Radius)); // deathwall changes around cast start
Cast(id + 0x10, AID.NorthswainsGlow, 3.2f, 3)
.ActivateOnEnter<NorthswainsGlow>(); // aoe casts start ~0.8s after visual cast end
Cast(id + 0x20, AID.BeckAndCallToArmsWillKW, 3.1f, 5);
ComponentCondition<NorthswainsGlow>(id + 0x30, 2.6f, comp => comp.NumCasts > 0)
.DeactivateOnExit<NorthswainsGlow>();
CastStart(id + 0x40, AID.BeckAndCallToArmsWillSG, 0.5f);
ComponentCondition<QueensWill>(id + 0x41, 1.1f, comp => comp.NumCasts >= 2, "Easy chess 1");
CastEnd(id + 0x42, 3.9f);
ComponentCondition<QueensWill>(id + 0x43, 4.3f, comp => comp.NumCasts >= 4, "Easy chess 2")
.DeactivateOnExit<QueensWill>()
.OnExit(() => Module.Arena.Bounds = new ArenaBoundsCircle(Module.Bounds.Radius)); // deathwall changes ~4.7s after this
}
private void QueensEdict(uint id, float delay)
{
Cast(id, AID.QueensEdict, delay, 5)
.ActivateOnEnter<QueensEdict>() // safezone envcontrol, statuses on guards and players appear ~0.8s after cast end
.OnEnter(() => Module.Arena.Bounds = new ArenaBoundsSquare(Module.Bounds.Radius)); // deathwall changes around cast start
Targetable(id + 0x10, false, 3.1f, "Disappear");
Cast(id + 0x20, AID.BeckAndCallToArmsEdictKW, 0.1f, 16.3f);
CastStart(id + 0x30, AID.BeckAndCallToArmsEdictSG, 3.2f);
ComponentCondition<QueensEdict>(id + 0x31, 1.3f, comp => comp.NumCasts >= 2, "Super chess rows"); // 1st edict movement starts ~0.2s before this
CastEnd(id + 0x32, 7.4f);
ComponentCondition<QueensEdict>(id + 0x40, 2.4f, comp => comp.NumStuns > 0, "Super chess columns");
ComponentCondition<QueensEdict>(id + 0x41, 1.9f, comp => comp.NumCasts >= 4);
CastStart(id + 0x50, AID.GunnhildrsBlades, 2.8f);
ComponentCondition<QueensEdict>(id + 0x51, 1.3f, comp => comp.NumStuns == 0); // 2nd edict movement starts ~1.0s before this
ComponentCondition<QueensEdict>(id + 0x52, 9, comp => comp.NumStuns > 0, "Super chess safespot");
CastEnd(id + 0x53, 3.7f)
.DeactivateOnExit<QueensEdict>();
Targetable(id + 0x60, true, 3.1f, "Reappear")
.OnExit(() => Module.Arena.Bounds = new ArenaBoundsCircle(Module.Bounds.Radius)); // deathwall changes ~1.9s after this
}
private void GodsSaveTheQueen(uint id, float delay)
{
Cast(id, AID.GodsSaveTheQueen, delay, 5);
ComponentCondition<GodsSaveTheQueen>(id + 0x10, 2.1f, comp => comp.NumCasts > 0, "Raidwide")
.ActivateOnEnter<GodsSaveTheQueen>()
.DeactivateOnExit<GodsSaveTheQueen>()
.SetHint(StateMachine.StateHint.Raidwide);
}
private void MaelstromsBolt(uint id, float delay)
{
ComponentCondition<MaelstromsBolt>(id, delay, comp => comp.NumCasts > 0, "Reflect/raidwide")
.ActivateOnEnter<MaelstromsBolt>()
.DeactivateOnExit<MaelstromsBolt>();
}
private void RelentlessPlay1(uint id, float delay)
{
Cast(id, AID.RelentlessPlay, delay, 5);
// +3.0s: tethers/icons
ActorCast(id + 0x10, Module.Enemies(OID.QueensWarrior).FirstOrDefault, AID.ReversalOfForces, 3.1f, 4); // gunner casts automatic turret - starts 1s later, ends at the same time
// +1.0s: tethers are replaced with statuses
CastStart(id + 0x20, AID.NorthswainsGlow, 1.1f);
// +0.1s: turrets spawn
ActorCastStart(id + 0x21, Module.Enemies(OID.QueensGunner).FirstOrDefault, AID.Reading, 2.1f);
CastEnd(id + 0x22, 0.9f);
ActorCastEnd(id + 0x23, Module.Enemies(OID.QueensGunner).FirstOrDefault, 2.1f)
.ActivateOnEnter<NorthswainsGlow>(); // aoes start ~0.8s after visual cast end
// +1.0s: unseen statuses
ActorCastStart(id + 0x30, Module.Enemies(OID.QueensWarrior).FirstOrDefault, AID.WindsOfWeight, 3.0f);
ActorCastStart(id + 0x31, Module.Enemies(OID.QueensGunner).FirstOrDefault, AID.QueensShot, 0.2f)
.ActivateOnEnter<WindsOfWeight>();
ActorCastEnd(id + 0x32, Module.Enemies(OID.QueensWarrior).FirstOrDefault, 5.8f, false, "Wind/gravity")
.ActivateOnEnter<QueensShot>()
.DeactivateOnExit<WindsOfWeight>()
.DeactivateOnExit<NorthswainsGlow>();
ActorCastEnd(id + 0x33, Module.Enemies(OID.QueensGunner).FirstOrDefault, 1.2f, false, "Face gunner")
.DeactivateOnExit<QueensShot>();
// +0.5s: turrets start their casts
ComponentCondition<TurretsTourUnseen>(id + 0x40, 3.5f, comp => comp.NumCasts > 0, "Face turret")
.ActivateOnEnter<TurretsTourUnseen>()
.DeactivateOnExit<TurretsTourUnseen>();
}
private void RelentlessPlay2(uint id, float delay)
{
Cast(id, AID.RelentlessPlay, delay, 5);
ActorCast(id + 0x10, Module.Enemies(OID.QueensKnight).FirstOrDefault, AID.ShieldOmen, 3.2f, 3);
ActorCastStart(id + 0x20, Module.Enemies(OID.QueensSoldier).FirstOrDefault, AID.DoubleGambit, 4.5f);
Targetable(id + 0x21, false, 0.4f, "Disappear");
ActorCastStart(id + 0x22, Module.Enemies(OID.QueensKnight).FirstOrDefault, AID.OptimalOffensive, 1.4f);
CastStartMulti(id + 0x23, [AID.JudgmentBladeR, AID.JudgmentBladeL], 1.9f)
.ActivateOnEnter<OptimalOffensive>()
.ActivateOnEnter<OptimalOffensiveKnockback>()
.ActivateOnEnter<UnluckyLotAetherialSphere>();
ActorCastEnd(id + 0x24, Module.Enemies(OID.QueensSoldier).FirstOrDefault, 1.3f)
.ActivateOnEnter<JudgmentBlade>();
ActorCastStart(id + 0x25, Module.Enemies(OID.QueensSoldier).FirstOrDefault, AID.SecretsRevealed, 3.2f); // right before cast start, 2 unsafe avatars are tethered to caster
ActorCastEnd(id + 0x26, Module.Enemies(OID.QueensKnight).FirstOrDefault, 0.6f, false, "Charge + Knockback")
.DeactivateOnExit<OptimalOffensive>()
.DeactivateOnExit<OptimalOffensiveKnockback>();
CastEnd(id + 0x27, 1.9f);
ComponentCondition<JudgmentBlade>(id + 0x28, 0.3f, comp => comp.NumCasts > 0, "Cleave")
.DeactivateOnExit<JudgmentBlade>();
ComponentCondition<UnluckyLotAetherialSphere>(id + 0x29, 0.5f, comp => comp.NumCasts > 0, "Sphere explosion")
.DeactivateOnExit<UnluckyLotAetherialSphere>();
ActorCastEnd(id + 0x2A, Module.Enemies(OID.QueensSoldier).FirstOrDefault, 1.7f);
CastMulti(id + 0x30, [AID.JudgmentBladeR, AID.JudgmentBladeL], 2.2f, 7)
.ActivateOnEnter<JudgmentBlade>()
.ActivateOnEnter<PawnOff>(); // cast starts ~2.7s after judgment blade; we could show hints much earlier based on tethers
ComponentCondition<JudgmentBlade>(id + 0x32, 0.3f, comp => comp.NumCasts > 0, "Cleave")
.DeactivateOnExit<JudgmentBlade>();
ComponentCondition<PawnOff>(id + 0x33, 2.4f, comp => comp.NumCasts > 0, "Real/fake aoes")
.DeactivateOnExit<PawnOff>();
Targetable(id + 0x40, true, 2.0f, "Reappear");
}
private void RelentlessPlay3(uint id, float delay)
{
Cast(id, AID.RelentlessPlay, delay, 5);
ActorCastMulti(id + 0x10, Module.Enemies(OID.QueensKnight).FirstOrDefault, [AID.SwordOmen, AID.ShieldOmen], 3.1f, 3);
// note: gunner starts automatic turret visual together with optimal play
ActorCastMulti(id + 0x20, Module.Enemies(OID.QueensKnight).FirstOrDefault, [AID.OptimalPlaySword, AID.OptimalPlayShield], 6.5f, 5, false, "Cone + circle/donut")
.ActivateOnEnter<OptimalPlaySword>()
.ActivateOnEnter<OptimalPlayShield>()
.ActivateOnEnter<OptimalPlayCone>()
.DeactivateOnExit<OptimalPlaySword>()
.DeactivateOnExit<OptimalPlayShield>()
.DeactivateOnExit<OptimalPlayCone>();
ActorCast(id + 0x30, Module.Enemies(OID.QueensGunner).FirstOrDefault, AID.TurretsTour, 1, 5, false, "Turrets start")
.ActivateOnEnter<TurretsTour>();
ComponentCondition<TurretsTour>(id + 0x40, 1.7f, comp => comp.NumCasts >= 4, "Turrets resolve")
.DeactivateOnExit<TurretsTour>();
}
private void RelentlessPlay4(uint id, float delay)
{
Cast(id, AID.RelentlessPlay, delay, 5);
ActorCast(id + 0x10, Module.Enemies(OID.QueensWarrior).FirstOrDefault, AID.Bombslinger, 3.1f, 3);
// +0.9s: bombs spawn
ActorCastStart(id + 0x20, Module.Enemies(OID.QueensWarrior).FirstOrDefault, AID.ReversalOfForces, 3.2f); // icons/tethers appear ~0.1s before cast start
CastStart(id + 0x21, AID.HeavensWrath, 2.9f);
ActorCastEnd(id + 0x22, Module.Enemies(OID.QueensWarrior).FirstOrDefault, 1.1f);
CastEnd(id + 0x23, 1.9f);
ComponentCondition<HeavensWrathAOE>(id + 0x30, 0.8f, comp => comp.Casters.Count > 0)
.ActivateOnEnter<HeavensWrathAOE>();
ActorCastStartMulti(id + 0x31, Module.Enemies(OID.QueensSoldier).FirstOrDefault, [AID.FieryPortent, AID.IcyPortent], 2.2f)
.ActivateOnEnter<HeavensWrathKnockback>()
.ActivateOnEnter<AboveBoard>();
ComponentCondition<HeavensWrathAOE>(id + 0x32, 2.8f, comp => comp.NumCasts > 0, "Knockback")
.ActivateOnEnter<FieryIcyPortent>()
.DeactivateOnExit<HeavensWrathAOE>()
.DeactivateOnExit<HeavensWrathKnockback>();
ActorCastStart(id + 0x33, Module.Enemies(OID.QueensWarrior).FirstOrDefault, AID.AboveBoard, 0.5f);
Targetable(id + 0x34, false, 1.8f, "Boss disappears");
ActorCastEnd(id + 0x35, Module.Enemies(OID.QueensSoldier).FirstOrDefault, 0.9f, false, "Move/stay")
.DeactivateOnExit<FieryIcyPortent>();
ActorCastEnd(id + 0x36, Module.Enemies(OID.QueensWarrior).FirstOrDefault, 3.3f);
ComponentCondition<AboveBoard>(id + 0x40, 1.0f, comp => comp.CurState == AboveBoard.State.ThrowUpDone, "Throw up");
ComponentCondition<AboveBoard>(id + 0x41, 2.0f, comp => comp.CurState == AboveBoard.State.ShortExplosionsDone, "Bombs 1");
ComponentCondition<AboveBoard>(id + 0x42, 4.2f, comp => comp.CurState == AboveBoard.State.LongExplosionsDone, "Bombs 2")
.DeactivateOnExit<AboveBoard>();
Targetable(id + 0x50, true, 3.0f, "Boss reappears");
}
private void RelentlessPlay5(uint id, float delay)
{
Cast(id, AID.RelentlessPlay, delay, 5);
ActorCastStart(id + 0x10, Module.Enemies(OID.QueensWarrior).FirstOrDefault, AID.SoftEnrageW, 3.1f);
ActorCastStart(id + 0x11, Module.Enemies(OID.QueensSoldier).FirstOrDefault, AID.SoftEnrageS, 3);
ActorCastEnd(id + 0x12, Module.Enemies(OID.QueensWarrior).FirstOrDefault, 2, false, "Raidwide 1")
.SetHint(StateMachine.StateHint.Raidwide);
ActorCastEnd(id + 0x13, Module.Enemies(OID.QueensSoldier).FirstOrDefault, 3, false, "Raidwide 2")
.SetHint(StateMachine.StateHint.Raidwide);
ActorCastStart(id + 0x20, Module.Enemies(OID.QueensWarrior).FirstOrDefault, AID.SoftEnrageW, 0.1f);
ActorCastStart(id + 0x21, Module.Enemies(OID.QueensSoldier).FirstOrDefault, AID.SoftEnrageS, 3);
ActorCastEnd(id + 0x22, Module.Enemies(OID.QueensWarrior).FirstOrDefault, 2, false, "Raidwide 3")
.SetHint(StateMachine.StateHint.Raidwide);
CastStart(id + 0x23, AID.EmpyreanIniquity, 0.8f);
ActorCastEnd(id + 0x24, Module.Enemies(OID.QueensSoldier).FirstOrDefault, 2.2f, false, "Raidwide 4")
.SetHint(StateMachine.StateHint.Raidwide);
CastEnd(id + 0x25, 2.8f, "Raidwide 5")
.SetHint(StateMachine.StateHint.Raidwide);
ActorCastStart(id + 0x30, Module.Enemies(OID.QueensKnight).FirstOrDefault, AID.SoftEnrageK, 1.3f);
ActorCastStart(id + 0x31, Module.Enemies(OID.QueensWarrior).FirstOrDefault, AID.SoftEnrageW, 3);
ActorCastEnd(id + 0x32, Module.Enemies(OID.QueensKnight).FirstOrDefault, 2, false, "Raidwide 6")
.SetHint(StateMachine.StateHint.Raidwide);
ActorCastStart(id + 0x33, Module.Enemies(OID.QueensSoldier).FirstOrDefault, AID.SoftEnrageS, 1);
ActorCastEnd(id + 0x34, Module.Enemies(OID.QueensWarrior).FirstOrDefault, 2, false, "Raidwide 7")
.SetHint(StateMachine.StateHint.Raidwide);
ActorCastStart(id + 0x35, Module.Enemies(OID.QueensGunner).FirstOrDefault, AID.SoftEnrageG, 1);
ActorCastEnd(id + 0x36, Module.Enemies(OID.QueensSoldier).FirstOrDefault, 2, false, "Raidwide 8")
.SetHint(StateMachine.StateHint.Raidwide);
ActorCastEnd(id + 0x37, Module.Enemies(OID.QueensGunner).FirstOrDefault, 3, false, "Raidwide 9")
.SetHint(StateMachine.StateHint.Raidwide);
}
}
| 1 | 0.957353 | 1 | 0.957353 | game-dev | MEDIA | 0.876763 | game-dev | 0.651945 | 1 | 0.651945 |
Exortions/skyblock-2.0 | 5,528 | src/main/java/com/skyblock/skyblock/features/slayer/SlayerHandler.java | package com.skyblock.skyblock.features.slayer;
import com.skyblock.skyblock.Skyblock;
import com.skyblock.skyblock.SkyblockPlayer;
import com.skyblock.skyblock.features.scoreboard.HubScoreboard;
import com.skyblock.skyblock.features.scoreboard.SlayerScoreboard;
import com.skyblock.skyblock.features.slayer.gui.SlayerGUI;
import com.skyblock.skyblock.features.slayer.miniboss.SlayerMiniboss;
import com.skyblock.skyblock.utilities.Util;
import com.skyblock.skyblock.utilities.sound.SoundSequence;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicReference;
public class SlayerHandler {
@Getter
@AllArgsConstructor
public static class SlayerData {
private final SlayerQuest quest;
private final SlayerBoss boss;
}
private final HashMap<Player, SlayerData> slayers = new HashMap<>();
public void startQuest(Player player, SlayerType type, int level) {
SlayerData data = registerNewSlayer(player, type, level);
player.sendMessage(ChatColor.DARK_PURPLE + "" + ChatColor.BOLD + "SLAYER QUEST STARTED");
player.playSound(player.getLocation(), Sound.ENDERDRAGON_GROWL, 10, 2);
String entityName = "";
switch (type) {
case REVENANT:
entityName = "Zombies";
break;
case TARANTULA:
entityName = "Spiders";
break;
case SVEN:
entityName = "Wolves";
break;
}
SkyblockPlayer.getPlayer(player).addCoins(-1 * SlayerGUI.COINS.get(level - 1));
player.sendMessage(ChatColor.DARK_PURPLE + " ☠ " + ChatColor.GRAY + "Slay " + ChatColor.RED + Util.formatInt(data.quest.getNeededExp()) + " Combat XP " + ChatColor.GRAY + "worth of " + entityName + ".");
}
public void endQuest(Player player, boolean fail) {
SlayerData data = getSlayer(player);
if (data == null) return;
SlayerBoss boss = data.getBoss();
if (fail) {
player.sendMessage(" " + ChatColor.RED + ChatColor.BOLD + "SLAYER QUEST FAILED!");
player.sendMessage(" " + ChatColor.DARK_PURPLE + ChatColor.BOLD + "→ " + ChatColor.GRAY + "You died! What a noob!");
Skyblock.getPlugin(Skyblock.class).getEntityHandler().unregisterEntity(boss.getVanilla().getEntityId());
boss.getVanilla().remove();
}
unregisterSlayer(player);
}
public void addExp(Player player, double exp) {
SlayerData data = getSlayer(player);
SlayerQuest quest = data.quest;
quest.addExp((int) exp);
SkyblockPlayer skyblockPlayer = SkyblockPlayer.getPlayer(player);
AtomicReference<Location> spawnLoc = new AtomicReference<>(player.getLocation());
if (skyblockPlayer.getExtraData("lastKilledLoc") != null)
spawnLoc.set((Location) skyblockPlayer.getExtraData("lastKilledLoc"));
if (quest.getExp() >= quest.getNeededExp() && quest.getState().equals(SlayerQuest.QuestState.SUMMONING)) {
quest.setState(SlayerQuest.QuestState.FIGHTING);
SoundSequence.BOSS_SPAWN.play(player.getLocation());
BukkitRunnable particles = new BukkitRunnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
player.playEffect(spawnLoc.get(), Effect.SPELL, Effect.SPELL.getData());
player.playEffect(spawnLoc.get(), Effect.FLYING_GLYPH, Effect.FLYING_GLYPH.getData());
player.playEffect(spawnLoc.get(), Effect.WITCH_MAGIC, Effect.WITCH_MAGIC.getData());
}
}
};
particles.runTaskTimer(Skyblock.getPlugin(), 0, 5);
Util.delay(() -> {
particles.cancel();
player.playEffect(spawnLoc.get(), Effect.EXPLOSION_HUGE, Effect.EXPLOSION_HUGE.getData());
quest.getBoss().spawn(spawnLoc.get());
}, 28);
} else if (quest.getState().equals(SlayerQuest.QuestState.SUMMONING)) {
SlayerMiniboss miniboss = SlayerMiniboss.getMiniBoss(player, quest.getBoss().getLevel(), exp, quest.getType());
if (miniboss != null) miniboss.spawn(spawnLoc.get());
}
}
public SlayerData registerNewSlayer(Player player, SlayerType type, int level) {
SlayerBoss boss = type.getNewInstance(player, level);
if (boss == null) return null;
SlayerQuest quest = new SlayerQuest(player, boss);
SlayerData data = new SlayerData(quest, boss);
SkyblockPlayer skyblockPlayer = SkyblockPlayer.getPlayer(player);
skyblockPlayer.setExtraData("slayerData", data);
skyblockPlayer.setBoard(new SlayerScoreboard(player));
slayers.put(player, data);
return getSlayer(player);
}
public void unregisterSlayer(Player player) {
SkyblockPlayer skyblockPlayer = SkyblockPlayer.getPlayer(player);
skyblockPlayer.setBoard(new HubScoreboard(player));
slayers.remove(player);
}
public SlayerData getSlayer(Player player) {
if (!slayers.containsKey(player)) return new SlayerData(null, null);
return slayers.get(player);
}
}
| 1 | 0.771567 | 1 | 0.771567 | game-dev | MEDIA | 0.972318 | game-dev | 0.953958 | 1 | 0.953958 |
folgerwang/UnrealEngine | 17,340 | Engine/Source/ThirdParty/PhysX3/PhysX_3.4/Include/PxRigidDynamic.h | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_NX_RIGIDDYNAMIC
#define PX_PHYSICS_NX_RIGIDDYNAMIC
/** \addtogroup physics
@{
*/
#include "PxRigidBody.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Collection of flags providing a mechanism to lock motion along/around a specific axis.
@see PxRigidDynamic.setRigidDynamicLockFlag(), PxRigidBody.getRigidDynamicLockFlags()
*/
struct PxRigidDynamicLockFlag
{
enum Enum
{
eLOCK_LINEAR_X = (1 << 0),
eLOCK_LINEAR_Y = (1 << 1),
eLOCK_LINEAR_Z = (1 << 2),
eLOCK_ANGULAR_X = (1 << 3),
eLOCK_ANGULAR_Y = (1 << 4),
eLOCK_ANGULAR_Z = (1 << 5)
};
};
typedef PxFlags<PxRigidDynamicLockFlag::Enum, PxU16> PxRigidDynamicLockFlags;
PX_FLAGS_OPERATORS(PxRigidDynamicLockFlag::Enum, PxU16)
/**
\brief PxRigidDynamic represents a dynamic rigid simulation object in the physics SDK.
<h3>Creation</h3>
Instances of this class are created by calling #PxPhysics::createRigidDynamic() and deleted with #release().
<h3>Visualizations</h3>
\li #PxVisualizationParameter::eACTOR_AXES
\li #PxVisualizationParameter::eBODY_AXES
\li #PxVisualizationParameter::eBODY_MASS_AXES
\li #PxVisualizationParameter::eBODY_LIN_VELOCITY
\li #PxVisualizationParameter::eBODY_ANG_VELOCITY
\li #PxVisualizationParameter::eBODY_JOINT_GROUPS
@see PxRigidBody PxPhysics.createRigidDynamic() release()
*/
class PxRigidDynamic : public PxRigidBody
{
public:
// Runtime modifications
/************************************************************************************************/
/** @name Kinematic Actors
*/
/**
\brief Moves kinematically controlled dynamic actors through the game world.
You set a dynamic actor to be kinematic using the PxRigidBodyFlag::eKINEMATIC flag
with setRigidBodyFlag().
The move command will result in a velocity that will move the body into
the desired pose. After the move is carried out during a single time step,
the velocity is returned to zero. Thus, you must continuously call
this in every time step for kinematic actors so that they move along a path.
This function simply stores the move destination until the next simulation
step is processed, so consecutive calls will simply overwrite the stored target variable.
The motion is always fully carried out.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
<b>Sleeping:</b> This call wakes the actor if it is sleeping and will set the wake counter to #PxSceneDesc::wakeCounterResetValue.
\param[in] destination The desired pose for the kinematic actor, in the global frame. <b>Range:</b> rigid body transform.
@see getKinematicTarget() PxRigidBodyFlag setRigidBodyFlag()
*/
virtual void setKinematicTarget(const PxTransform& destination) = 0;
/**
\brief Get target pose of a kinematically controlled dynamic actor.
\param[out] target Transform to write the target pose to. Only valid if the method returns true.
\return True if the actor is a kinematically controlled dynamic and the target has been set, else False.
@see setKinematicTarget() PxRigidBodyFlag setRigidBodyFlag()
*/
virtual bool getKinematicTarget(PxTransform& target) const = 0;
/************************************************************************************************/
/** @name Damping
*/
/**
\brief Sets the linear damping coefficient.
Zero represents no damping. The damping coefficient must be nonnegative.
<b>Default:</b> 0.0
\param[in] linDamp Linear damping coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see getLinearDamping() setAngularDamping()
*/
virtual void setLinearDamping(PxReal linDamp) = 0;
/**
\brief Retrieves the linear damping coefficient.
\return The linear damping coefficient associated with this actor.
@see setLinearDamping() getAngularDamping()
*/
virtual PxReal getLinearDamping() const = 0;
/**
\brief Sets the angular damping coefficient.
Zero represents no damping.
The angular damping coefficient must be nonnegative.
<b>Default:</b> 0.05
\param[in] angDamp Angular damping coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see getAngularDamping() setLinearDamping()
*/
virtual void setAngularDamping(PxReal angDamp) = 0;
/**
\brief Retrieves the angular damping coefficient.
\return The angular damping coefficient associated with this actor.
@see setAngularDamping() getLinearDamping()
*/
virtual PxReal getAngularDamping() const = 0;
/************************************************************************************************/
/** @name Velocity
*/
/**
\brief Lets you set the maximum angular velocity permitted for this actor.
For various internal computations, very quickly rotating actors introduce error
into the simulation, which leads to undesired results.
With this function, you can set the maximum angular velocity permitted for this rigid body.
Higher angular velocities are clamped to this value.
Note: The angular velocity is clamped to the set value <i>before</i> the solver, which means that
the limit may still be momentarily exceeded.
<b>Default:</b> 7.0
\param[in] maxAngVel Max allowable angular velocity for actor. <b>Range:</b> [0, PX_MAX_F32)
@see getMaxAngularVelocity()
*/
virtual void setMaxAngularVelocity(PxReal maxAngVel) = 0;
/**
\brief Retrieves the maximum angular velocity permitted for this actor.
\return The maximum allowed angular velocity for this actor.
@see setMaxAngularVelocity
*/
virtual PxReal getMaxAngularVelocity() const = 0;
/************************************************************************************************/
/** @name Sleeping
*/
/**
\brief Returns true if this body is sleeping.
When an actor does not move for a period of time, it is no longer simulated in order to save time. This state
is called sleeping. However, because the object automatically wakes up when it is either touched by an awake object,
or one of its properties is changed by the user, the entire sleep mechanism should be transparent to the user.
In general, a dynamic rigid actor is guaranteed to be awake if at least one of the following holds:
\li The wake counter is positive (see #setWakeCounter()).
\li The linear or angular velocity is non-zero.
\li A non-zero force or torque has been applied.
If a dynamic rigid actor is sleeping, the following state is guaranteed:
\li The wake counter is zero.
\li The linear and angular velocity is zero.
\li There is no force update pending.
When an actor gets inserted into a scene, it will be considered asleep if all the points above hold, else it will be treated as awake.
If an actor is asleep after the call to PxScene::fetchResults() returns, it is guaranteed that the pose of the actor
was not changed. You can use this information to avoid updating the transforms of associated objects.
\note A kinematic actor is asleep unless a target pose has been set (in which case it will stay awake until the end of the next
simulation step where no target pose has been set anymore). The wake counter will get set to zero or to the reset value
#PxSceneDesc::wakeCounterResetValue in the case where a target pose has been set to be consistent with the definitions above.
\note It is invalid to use this method if the actor has not been added to a scene already.
\return True if the actor is sleeping.
@see isSleeping() wakeUp() putToSleep() getSleepThreshold()
*/
virtual bool isSleeping() const = 0;
/**
\brief Sets the mass-normalized kinetic energy threshold below which an actor may go to sleep.
Actors whose kinetic energy divided by their mass is below this threshold will be candidates for sleeping.
<b>Default:</b> 5e-5f * PxTolerancesScale::speed * PxTolerancesScale::speed
\param[in] threshold Energy below which an actor may go to sleep. <b>Range:</b> [0, PX_MAX_F32)
@see isSleeping() getSleepThreshold() wakeUp() putToSleep() PxTolerancesScale
*/
virtual void setSleepThreshold(PxReal threshold) = 0;
/**
\brief Returns the mass-normalized kinetic energy below which an actor may go to sleep.
\return The energy threshold for sleeping.
@see isSleeping() wakeUp() putToSleep() setSleepThreshold()
*/
virtual PxReal getSleepThreshold() const = 0;
/**
\brief Sets the mass-normalized kinetic energy threshold below which an actor may participate in stabilization.
Actors whose kinetic energy divided by their mass is above this threshold will not participate in stabilization.
This value has no effect if PxSceneFlag::eENABLE_STABILIZATION was not enabled on the PxSceneDesc.
<b>Default:</b> 1e-5f * PxTolerancesScale::speed * PxTolerancesScale::speed
\param[in] threshold Energy below which an actor may participate in stabilization. <b>Range:</b> [0,inf)
@see getStabilizationThreshold() PxSceneFlag::eENABLE_STABILIZATION
*/
virtual void setStabilizationThreshold(PxReal threshold) = 0;
/**
\brief Returns the mass-normalized kinetic energy below which an actor may participate in stabilization.
Actors whose kinetic energy divided by their mass is above this threshold will not participate in stabilization.
\return The energy threshold for participating in stabilization.
@see setStabilizationThreshold() PxSceneFlag::eENABLE_STABILIZATION
*/
virtual PxReal getStabilizationThreshold() const = 0;
/**
\brief Reads the PxRigidDynamic lock flags.
See the list of flags #PxRigidDynamicLockFlag
\return The values of the PxRigidDynamicLock flags.
@see PxRigidDynamicLockFlag setRigidDynamicLockFlag()
*/
virtual PxRigidDynamicLockFlags getRigidDynamicLockFlags() const = 0;
/**
\brief Raises or clears a particular rigid dynamic lock flag.
See the list of flags #PxRigidDynamicLockFlag
<b>Default:</b> no flags are set
\param[in] flag The PxRigidDynamicLockBody flag to raise(set) or clear. See #PxRigidBodyFlag.
\param[in] value The new boolean value for the flag.
@see PxRigidDynamicLockFlag getRigidDynamicLockFlags()
*/
virtual void setRigidDynamicLockFlag(PxRigidDynamicLockFlag::Enum flag, bool value) = 0;
virtual void setRigidDynamicLockFlags(PxRigidDynamicLockFlags flags) = 0;
/**
\brief Sets the wake counter for the actor.
The wake counter value determines the minimum amount of time until the body can be put to sleep. Please note
that a body will not be put to sleep if the energy is above the specified threshold (see #setSleepThreshold())
or if other awake bodies are touching it.
\note Passing in a positive value will wake the actor up automatically.
\note It is invalid to use this method for kinematic actors since the wake counter for kinematics is defined
based on whether a target pose has been set (see the comment in #isSleeping()).
\note It is invalid to use this method if PxActorFlag::eDISABLE_SIMULATION is set.
<b>Default:</b> 0.4 (which corresponds to 20 frames for a time step of 0.02)
\param[in] wakeCounterValue Wake counter value. <b>Range:</b> [0, PX_MAX_F32)
@see isSleeping() getWakeCounter()
*/
virtual void setWakeCounter(PxReal wakeCounterValue) = 0;
/**
\brief Returns the wake counter of the actor.
\return The wake counter of the actor.
@see isSleeping() setWakeCounter()
*/
virtual PxReal getWakeCounter() const = 0;
/**
\brief Wakes up the actor if it is sleeping.
The actor will get woken up and might cause other touching actors to wake up as well during the next simulation step.
\note This will set the wake counter of the actor to the value specified in #PxSceneDesc::wakeCounterResetValue.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\note It is invalid to use this method for kinematic actors since the sleep state for kinematics is defined
based on whether a target pose has been set (see the comment in #isSleeping()).
@see isSleeping() putToSleep()
*/
virtual void wakeUp() = 0;
/**
\brief Forces the actor to sleep.
The actor will stay asleep during the next simulation step if not touched by another non-sleeping actor.
\note Any applied force will be cleared and the velocity and the wake counter of the actor will be set to 0.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\note It is invalid to use this method for kinematic actors since the sleep state for kinematics is defined
based on whether a target pose has been set (see the comment in #isSleeping()).
@see isSleeping() wakeUp()
*/
virtual void putToSleep() = 0;
/************************************************************************************************/
/**
\brief Sets the solver iteration counts for the body.
The solver iteration count determines how accurately joints and contacts are resolved.
If you are having trouble with jointed bodies oscillating and behaving erratically, then
setting a higher position iteration count may improve their stability.
If intersecting bodies are being depenetrated too violently, increase the number of velocity
iterations. More velocity iterations will drive the relative exit velocity of the intersecting
objects closer to the correct value given the restitution.
<b>Default:</b> 4 position iterations, 1 velocity iteration
\param[in] minPositionIters Number of position iterations the solver should perform for this body. <b>Range:</b> [1,255]
\param[in] minVelocityIters Number of velocity iterations the solver should perform for this body. <b>Range:</b> [1,255]
@see getSolverIterationCounts()
*/
virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) = 0;
/**
\brief Retrieves the solver iteration counts.
@see setSolverIterationCounts()
*/
virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const = 0;
/**
\brief Retrieves the force threshold for contact reports.
The contact report threshold is a force threshold. If the force between
two actors exceeds this threshold for either of the two actors, a contact report
will be generated according to the contact report threshold flags provided by
the filter shader/callback.
See #PxPairFlag.
The threshold used for a collision between a dynamic actor and the static environment is
the threshold of the dynamic actor, and all contacts with static actors are summed to find
the total normal force.
<b>Default:</b> PX_MAX_F32
\return Force threshold for contact reports.
@see setContactReportThreshold PxPairFlag PxSimulationFilterShader PxSimulationFilterCallback
*/
virtual PxReal getContactReportThreshold() const = 0;
/**
\brief Sets the force threshold for contact reports.
See #getContactReportThreshold().
\param[in] threshold Force threshold for contact reports. <b>Range:</b> [0, PX_MAX_F32)
@see getContactReportThreshold PxPairFlag
*/
virtual void setContactReportThreshold(PxReal threshold) = 0;
virtual const char* getConcreteTypeName() const { return "PxRigidDynamic"; }
protected:
PX_INLINE PxRigidDynamic(PxType concreteType, PxBaseFlags baseFlags) : PxRigidBody(concreteType, baseFlags) {}
PX_INLINE PxRigidDynamic(PxBaseFlags baseFlags) : PxRigidBody(baseFlags) {}
virtual ~PxRigidDynamic() {}
virtual bool isKindOf(const char* name) const { return !::strcmp("PxRigidDynamic", name) || PxRigidBody::isKindOf(name); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 1 | 0.933646 | 1 | 0.933646 | game-dev | MEDIA | 0.853084 | game-dev | 0.83314 | 1 | 0.83314 |
MergHQ/CRYENGINE | 5,141 | Code/GameSDK/GameDll/MPPathFollowingManager.cpp | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
#include "StdAfx.h"
#include "MPPathFollowingManager.h"
#include "GameRules.h"
CMPPathFollowingManager::CMPPathFollowingManager()
{
m_Paths.reserve(4);
}
CMPPathFollowingManager::~CMPPathFollowingManager()
{
}
void CMPPathFollowingManager::RegisterClassFollower(uint16 classId, IMPPathFollower* pFollower)
{
#ifndef _RELEASE
PathFollowers::iterator iter = m_PathFollowers.find(classId);
CRY_ASSERT_MESSAGE(iter == m_PathFollowers.end(), "CMPPathFollowingManager::RegisterClassFollower - this class has already been registered!");
#endif
m_PathFollowers[classId] = pFollower;
}
void CMPPathFollowingManager::UnregisterClassFollower(uint16 classId)
{
PathFollowers::iterator iter = m_PathFollowers.find(classId);
if(iter != m_PathFollowers.end())
{
m_PathFollowers.erase(iter);
return;
}
CRY_ASSERT_MESSAGE(false, "CMPPathFollowingManager::UnregisterClassFollower - tried to unregister class but class not found");
}
void CMPPathFollowingManager::RequestAttachEntityToPath( const SPathFollowingAttachToPathParameters& params )
{
PathFollowers::const_iterator iter = m_PathFollowers.find(params.classId);
if(iter != m_PathFollowers.end())
{
CRY_ASSERT_MESSAGE(params.pathIndex < m_Paths.size(), "CMPPathFollowingManager::RequestAttachEntityToPath - path index out of range");
iter->second->OnAttachRequest(params, &m_Paths[params.pathIndex].path);
if(gEnv->bServer)
{
SPathFollowingAttachToPathParameters sendParams(params);
sendParams.forceSnap = true;
g_pGame->GetGameRules()->GetGameObject()->InvokeRMI(CGameRules::ClPathFollowingAttachToPath(), params, eRMI_ToRemoteClients);
}
}
}
void CMPPathFollowingManager::RequestUpdateSpeed(uint16 classId, EntityId attachEntityId, float newSpeed)
{
PathFollowers::const_iterator iter = m_PathFollowers.find(classId);
if(iter != m_PathFollowers.end())
{
iter->second->OnUpdateSpeedRequest(attachEntityId, newSpeed);
}
}
bool CMPPathFollowingManager::RegisterPath(EntityId pathEntityId)
{
IEntity* pPathEntity = gEnv->pEntitySystem->GetEntity(pathEntityId);
if(pPathEntity)
{
#ifndef _RELEASE
Paths::const_iterator iter = m_Paths.begin();
Paths::const_iterator end = m_Paths.end();
while(iter != end)
{
if(iter->pathId == pathEntityId)
{
CRY_ASSERT_MESSAGE(iter == m_Paths.end(), "CMPPathFollowingManager::RegisterPath - this path has already been registered!");
break;
}
++iter;
}
#endif
m_Paths.push_back( SPathEntry(pathEntityId) );
bool success = m_Paths.back().path.CreatePath(pPathEntity);
if(success)
{
//Editor support for changing path nodes
if(gEnv->IsEditor())
{
gEnv->pEntitySystem->AddEntityEventListener(pathEntityId, ENTITY_EVENT_RESET, this);
}
return true;
}
else
{
m_Paths.pop_back();
}
}
return false;
}
void CMPPathFollowingManager::UnregisterPath(EntityId pathEntityId)
{
Paths::iterator iter = m_Paths.begin();
Paths::iterator end = m_Paths.end();
while(iter != end)
{
if(iter->pathId == pathEntityId)
{
if(gEnv->IsEditor())
{
gEnv->pEntitySystem->RemoveEntityEventListener(pathEntityId, ENTITY_EVENT_RESET, this);
}
m_Paths.erase(iter);
return;
}
++iter;
}
}
void CMPPathFollowingManager::RegisterListener(EntityId listenToEntityId, IMPPathFollowingListener* pListener)
{
#ifndef _RELEASE
PathListeners::iterator iter = m_PathListeners.find(listenToEntityId);
CRY_ASSERT_MESSAGE(iter == m_PathListeners.end(), "CMPPathFollowingManager::RegisterListener - this listener has already been registered!");
#endif
m_PathListeners[listenToEntityId] = pListener;
}
void CMPPathFollowingManager::UnregisterListener(EntityId listenToEntityId)
{
PathListeners::iterator iter = m_PathListeners.find(listenToEntityId);
if(iter != m_PathListeners.end())
{
m_PathListeners.erase(iter);
return;
}
CRY_ASSERT_MESSAGE(false, "CMPPathFollowingManager::UnregisterListener - tried to unregister listener but listener not found");
}
const CWaypointPath* CMPPathFollowingManager::GetPath(EntityId pathEntityId, IMPPathFollower::MPPathIndex& outIndex) const
{
for(unsigned int i = 0; i < m_Paths.size(); ++i)
{
if(m_Paths[i].pathId == pathEntityId)
{
outIndex = i;
return &m_Paths[i].path;
}
}
return NULL;
}
void CMPPathFollowingManager::NotifyListenersOfPathCompletion(EntityId pathFollowingEntityId)
{
PathListeners::iterator iter = m_PathListeners.find(pathFollowingEntityId);
if(iter != m_PathListeners.end())
{
iter->second->OnPathCompleted(pathFollowingEntityId);
}
}
void CMPPathFollowingManager::OnEntityEvent( IEntity *pEntity,SEntityEvent &event )
{
if(event.event == ENTITY_EVENT_RESET && event.nParam[0] == 0) //Only on leaving the editor gamemode
{
UnregisterPath(pEntity->GetId());
}
}
#ifndef _RELEASE
void CMPPathFollowingManager::Update()
{
if(g_pGameCVars->g_mpPathFollowingRenderAllPaths)
{
Paths::const_iterator iter = m_Paths.begin();
Paths::const_iterator end = m_Paths.end();
while(iter != end)
{
iter->path.DebugDraw(true);
++iter;
}
}
}
#endif //_RELEASE
| 1 | 0.946453 | 1 | 0.946453 | game-dev | MEDIA | 0.742817 | game-dev | 0.972143 | 1 | 0.972143 |
Aeroluna/Heck | 6,709 | NoodleExtensions/HarmonyPatches/SmallFixes/SaberPlayerMovementFix.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using CustomJSONData.CustomBeatmap;
using HarmonyLib;
using Heck;
using NoodleExtensions.Managers;
using SiraUtil.Affinity;
using SiraUtil.Logging;
using UnityEngine;
namespace NoodleExtensions.HarmonyPatches.SmallFixes;
internal class SaberPlayerMovementFix : IAffinity, IDisposable
{
private static readonly FieldInfo _bottomPos = AccessTools.Field(
typeof(BladeMovementDataElement),
nameof(BladeMovementDataElement.bottomPos));
private static readonly FieldInfo _topPos = AccessTools.Field(
typeof(BladeMovementDataElement),
nameof(BladeMovementDataElement.topPos));
private static readonly Dictionary<IBladeMovementData, SaberMovementData> _worldMovementData = new();
private readonly bool _active;
private readonly CodeInstruction _computeWorld;
private readonly bool _local;
private readonly SiraLog _log;
private readonly Transform _origin;
private SaberPlayerMovementFix(
SiraLog log,
PlayerTransforms playerTransforms,
IReadonlyBeatmapData beatmapData,
NoodlePlayerTransformManager noodlePlayerTransformManager)
{
_log = log;
_origin = playerTransforms._originTransform;
_computeWorld = InstanceTranspilers.EmitInstanceDelegate<Func<Vector3, Vector3>>(ComputeWorld);
CustomBeatmapData customBeatmapData = (CustomBeatmapData)beatmapData;
_local = customBeatmapData.beatmapCustomData.Get<bool?>(NoodleController.TRAIL_LOCAL_SPACE) ?? false;
_active = noodlePlayerTransformManager.Active;
}
public void Dispose()
{
InstanceTranspilers.DisposeDelegate(_computeWorld);
}
[AffinityPostfix]
[AffinityPatch(typeof(SaberTrail), nameof(SaberTrail.OnDestroy))]
private void CleanupWorldMovement(IBladeMovementData ____movementData)
{
if (_local || !_active)
{
return;
}
_worldMovementData
.Where(n => n.Value == ____movementData)
.Select(n => n.Key)
.ToArray()
.Do(n => _worldMovementData.Remove(n));
}
private Vector3 ComputeWorld(Vector3 original)
{
return _origin.TransformPoint(original);
}
[AffinityTranspiler]
[AffinityPatch(typeof(SaberMovementData), nameof(SaberMovementData.ComputeAdditionalData))]
private IEnumerable<CodeInstruction> ComputeWorldTranspiler(IEnumerable<CodeInstruction> instructions)
{
if (_local || !_active)
{
return instructions;
}
return new CodeMatcher(instructions)
/*
* -- Vector3 topPos2 = this._data[num2].topPos;
* -- Vector3 bottomPos2 = this._data[num2].bottomPos;
* -- Vector3 topPos3 = this._data[num3].topPos;
* -- Vector3 bottomPos3 = this._data[num3].bottomPos;
* ++ Vector3 topPos2 = ComputeWorld(this._data[num2].topPos);
* ++ Vector3 bottomPos2 = ComputeWorld(this._data[num2].bottomPos);
* ++ Vector3 topPos3 = ComputeWorld(this._data[num3].topPos);
* ++ Vector3 bottomPos3 = ComputeWorld(this._data[num3].bottomPos);
*/
.MatchForward(
false,
new CodeMatch(
n => n.opcode == OpCodes.Ldfld &&
(ReferenceEquals(n.operand, _topPos) || ReferenceEquals(n.operand, _bottomPos))))
.Repeat(
n => n
.Advance(1)
.Insert(_computeWorld))
.InstructionEnumeration();
}
[AffinityPrefix]
[AffinityPatch(typeof(SaberSwingRatingCounter), nameof(SaberSwingRatingCounter.ProcessNewData))]
private void ConvertProcessorToLocal(ref BladeMovementDataElement newData, ref BladeMovementDataElement prevData)
{
if (_local || !_active)
{
return;
}
newData.topPos = _origin.TransformPoint(newData.topPos);
newData.bottomPos = _origin.TransformPoint(newData.bottomPos);
prevData.topPos = _origin.TransformPoint(prevData.topPos);
prevData.bottomPos = _origin.TransformPoint(prevData.bottomPos);
}
[AffinityPostfix]
[AffinityPatch(typeof(SaberMovementData), nameof(SaberMovementData.prevAddedData), AffinityMethodType.Getter)]
[AffinityPatch(typeof(SaberMovementData), nameof(SaberMovementData.lastAddedData), AffinityMethodType.Getter)]
private void ConvertToLocal(SaberMovementData __instance, ref BladeMovementDataElement __result)
{
if (_local || !_active)
{
return;
}
if (_worldMovementData.ContainsValue(__instance))
{
return;
}
__result.topPos = _origin.TransformPoint(__result.topPos);
__result.bottomPos = _origin.TransformPoint(__result.bottomPos);
}
// We store all positions as localpositions so that abrupt changes in world position do not affect this
// it gets converted back to world position to calculate cut
[AffinityPrefix]
[AffinityPatch(typeof(SaberMovementData), nameof(SaberMovementData.AddNewData))]
private void ConvertToWorld(SaberMovementData __instance, ref Vector3 topPos, ref Vector3 bottomPos, float time)
{
if (_local || !_active)
{
return;
}
if (_worldMovementData.ContainsValue(__instance))
{
return;
}
// fill world movement data with world position for saber
if (_worldMovementData.TryGetValue(__instance, out SaberMovementData world))
{
world.AddNewData(topPos, bottomPos, time);
}
topPos = _origin.InverseTransformPoint(topPos);
bottomPos = _origin.InverseTransformPoint(bottomPos);
}
[AffinityPrefix]
[AffinityPatch(typeof(SaberTrail), nameof(SaberTrail.Setup))]
private void CreateSaberMovementData(
ref IBladeMovementData movementData,
SaberTrail __instance,
TrailRenderer ____trailRenderer)
{
if (!_active)
{
return;
}
if (_local)
{
_log.Debug("Parented saber trail to local space");
____trailRenderer.transform.SetParent(_origin.parent, false);
return;
}
if (_worldMovementData.ContainsKey(movementData))
{
return;
}
// use world movement data for saber trail
SaberMovementData world = new();
_worldMovementData.Add(movementData, world);
movementData = world;
}
}
| 1 | 0.871396 | 1 | 0.871396 | game-dev | MEDIA | 0.690569 | game-dev | 0.793327 | 1 | 0.793327 |
NGLSG/Luma | 8,329 | Resources/RuntimeAsset/RuntimeGameObject.cpp | #include "RuntimeGameObject.h"
#include "RuntimeScene.h"
#include "../../Components/IDComponent.h"
#include "../../Components/RelationshipComponent.h"
#include <algorithm>
#include "Transform.h"
#include "../../Data/PrefabData.h"
#include <glm/glm.hpp>
#include "ActivityComponent.h"
#include "glm/detail/type_quat.hpp"
#include "glm/gtx/matrix_decompose.hpp"
#include "Components/ComponentRegistry.h"
#include "../Utils/Logger.h"
RuntimeGameObject::RuntimeGameObject(entt::entity handle, RuntimeScene* scene)
: m_entityHandle(handle), m_scene(scene)
{
}
std::string RuntimeGameObject::GetName()
{
return HasComponent<ECS::IDComponent>() ? GetComponent<ECS::IDComponent>().name : "";
}
void RuntimeGameObject::SetName(const std::string& name)
{
if (HasComponent<ECS::IDComponent>())
{
auto& idComp = GetComponent<ECS::IDComponent>();
idComp.name = name;
}
else
{
throw std::runtime_error("Cannot set name on GameObject without IDComponent.");
}
}
Guid RuntimeGameObject::GetGuid()
{
return HasComponent<ECS::IDComponent>() ? GetComponent<ECS::IDComponent>().guid : Guid();
}
bool RuntimeGameObject::operator==(const RuntimeGameObject& other) const
{
return m_entityHandle == other.m_entityHandle && m_scene == other.m_scene;
}
bool RuntimeGameObject::IsValid()
{
return m_scene != nullptr && m_scene->GetRegistry().valid(m_entityHandle);
}
Data::PrefabNode RuntimeGameObject::SerializeToPrefabData()
{
Data::PrefabNode node = m_scene->SerializeEntity(m_entityHandle, m_scene->GetRegistry());
return node;
}
bool RuntimeGameObject::IsDescendantOf(RuntimeGameObject dragged_object)
{
if (!IsValid() || !dragged_object.IsValid())
return false;
RuntimeGameObject current = *this;
while (current.IsValid())
{
if (current == dragged_object)
return true;
current = current.GetParent();
}
return false;
}
void RuntimeGameObject::SetChildren(std::vector<RuntimeGameObject>& children)
{
for (auto& child : children)
{
child.SetParent(*this);
}
}
void RuntimeGameObject::SetSiblingIndex(int newIndex)
{
if (!HasComponent<ECS::ParentComponent>()) return;
RuntimeGameObject parent = GetParent();
if (parent.IsValid() && parent.HasComponent<ECS::ChildrenComponent>())
{
auto& children = parent.GetComponent<ECS::ChildrenComponent>().children;
auto it = std::find(children.begin(), children.end(), m_entityHandle);
if (it == children.end()) return;
entt::entity selfHandle = *it;
children.erase(it);
if (newIndex < 0) newIndex = 0;
if (newIndex > children.size()) newIndex = children.size();
children.insert(children.begin() + newIndex, selfHandle);
}
}
int RuntimeGameObject::GetSiblingIndex()
{
if (!HasComponent<ECS::ParentComponent>())
{
return -1;
}
RuntimeGameObject parent = GetParent();
if (parent.IsValid() && parent.HasComponent<ECS::ChildrenComponent>())
{
const auto& children = parent.GetComponent<ECS::ChildrenComponent>().children;
auto it = std::find(children.begin(), children.end(), m_entityHandle);
if (it != children.end())
{
return static_cast<int>(std::distance(children.begin(), it));
}
}
return -1;
}
std::unordered_map<std::string, const ComponentRegistration*> RuntimeGameObject::GetAllComponents()
{
return m_scene->GetAllComponents(GetEntityHandle());
}
void RuntimeGameObject::SetParent(RuntimeGameObject parent)
{
if (!IsValid()) return;
if (parent == *this)
{
LogWarn("SetParent: attempt to set an object as its own parent. Ignored.");
return;
}
if (parent.IsValid() && parent.IsDescendantOf(*this))
{
LogWarn("SetParent: attempt to create cyclic hierarchy (new parent is a descendant). Ignored.");
return;
}
if (HasComponent<ECS::ParentComponent>())
{
RuntimeGameObject oldParent = GetParent();
if (oldParent.IsValid() && oldParent.HasComponent<ECS::ChildrenComponent>())
{
auto& children = oldParent.GetComponent<ECS::ChildrenComponent>().children;
std::erase(children, m_entityHandle);
}
}
m_scene->AddToRoot(*this);
if (parent.IsValid())
{
AddComponent<ECS::ParentComponent>().parent = parent;
if (!parent.HasComponent<ECS::ChildrenComponent>())
{
parent.AddComponent<ECS::ChildrenComponent>();
}
parent.GetComponent<ECS::ChildrenComponent>().children.push_back(m_entityHandle);
m_scene->RemoveFromRoot(*this);
}
else
{
RemoveComponent<ECS::ParentComponent>();
}
auto& childTransform = GetComponent<ECS::TransformComponent>();
auto& parentTransform = parent.GetComponent<ECS::TransformComponent>();
glm::mat4 parentWorldMatrix = glm::translate(glm::mat4(1.0f),
glm::vec3(parentTransform.position.x, parentTransform.position.y,
0.0f));
parentWorldMatrix = glm::rotate(parentWorldMatrix, parentTransform.rotation, glm::vec3(0.0f, 0.0f, 1.0f));
parentWorldMatrix = glm::scale(parentWorldMatrix,
glm::vec3(parentTransform.scale.x, parentTransform.scale.y, 1.0f));
glm::mat4 invParentWorldMatrix = glm::inverse(parentWorldMatrix);
glm::mat4 childWorldMatrix = glm::translate(glm::mat4(1.0f),
glm::vec3(childTransform.position.x, childTransform.position.y, 0.0f));
childWorldMatrix = glm::rotate(childWorldMatrix, childTransform.rotation, glm::vec3(0.0f, 0.0f, 1.0f));
childWorldMatrix = glm::scale(childWorldMatrix, glm::vec3(childTransform.scale.x, childTransform.scale.y, 1.0f));
glm::mat4 newLocalMatrix = invParentWorldMatrix * childWorldMatrix;
glm::vec3 scaleVec, translationVec, skew;
glm::vec4 perspective;
glm::quat rotationQuat;
glm::decompose(newLocalMatrix, scaleVec, rotationQuat, translationVec, skew, perspective);
childTransform.localPosition = {
childTransform.position.x - parentTransform.position.x,
childTransform.position.y - parentTransform.position.y
};
childTransform.localScale = {scaleVec.x, scaleVec.y};
childTransform.localRotation = glm::eulerAngles(rotationQuat).z;
}
void RuntimeGameObject::SetRoot()
{
if (!IsValid()) return;
if (HasComponent<ECS::ParentComponent>())
{
RuntimeGameObject parent = GetParent();
if (parent.IsValid() && parent.HasComponent<ECS::ChildrenComponent>())
{
auto& children = parent.GetComponent<ECS::ChildrenComponent>().children;
std::erase(children, m_entityHandle);
}
RemoveComponent<ECS::ParentComponent>();
}
m_scene->AddToRoot(*this);
}
RuntimeGameObject RuntimeGameObject::GetParent()
{
if (HasComponent<ECS::ParentComponent>())
{
entt::entity parentHandle = GetComponent<ECS::ParentComponent>().parent;
return {parentHandle, m_scene};
}
return {entt::null, m_scene};
}
std::vector<RuntimeGameObject> RuntimeGameObject::GetChildren()
{
if (HasComponent<ECS::ChildrenComponent>())
{
const auto& childrenComp = GetComponent<ECS::ChildrenComponent>();
std::vector<RuntimeGameObject> children;
children.reserve(childrenComp.children.size());
for (const auto& childHandle : childrenComp.children)
{
children.emplace_back(childHandle, m_scene);
}
return children;
}
return {};
}
bool RuntimeGameObject::IsActive()
{
return GetComponent<ECS::ActivityComponent>().isActive;
}
void RuntimeGameObject::SetActive(bool active)
{
auto e = InteractScriptEvent();
e.type = InteractScriptEvent::CommandType::ActivityChange;
e.entityId = static_cast<uint32_t>(m_entityHandle);
e.isActive = active;
EventBus::GetInstance().Publish(e);
if (HasComponent<ECS::ActivityComponent>())
{
GetComponent<ECS::ActivityComponent>().isActive = active;
}
else
{
AddComponent<ECS::ActivityComponent>(active);
}
}
| 1 | 0.867742 | 1 | 0.867742 | game-dev | MEDIA | 0.875097 | game-dev | 0.921354 | 1 | 0.921354 |
MegaMek/mekhq | 4,748 | MekHQ/src/mekhq/gui/menus/AssignForceToTacticalTransportMenu.java | /*
* Copyright (C) 2025 The MegaMek Team. All Rights Reserved.
*
* This file is part of MekHQ.
*
* MekHQ is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL),
* version 3 or (at your option) any later version,
* as published by the Free Software Foundation.
*
* MekHQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* A copy of the GPL should have been included with this project;
* if not, see <https://www.gnu.org/licenses/>.
*
* NOTICE: The MegaMek organization is a non-profit group of volunteers
* creating free software for the BattleTech community.
*
* MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks
* of The Topps Company, Inc. All Rights Reserved.
*
* Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of
* InMediaRes Productions, LLC.
*
* MechWarrior Copyright Microsoft Corporation. MekHQ was created under
* Microsoft's "Game Content Usage Rules"
* <https://www.xbox.com/en-US/developers/rules> and it is not endorsed by or
* affiliated with Microsoft.
*/
package mekhq.gui.menus;
import static mekhq.campaign.enums.CampaignTransportType.TACTICAL_TRANSPORT;
import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JOptionPane;
import mekhq.campaign.Campaign;
import mekhq.campaign.enums.CampaignTransportType;
import mekhq.campaign.unit.Unit;
import mekhq.campaign.unit.enums.TransporterType;
import mekhq.campaign.utilities.CampaignTransportUtilities;
import mekhq.utilities.MHQInternationalization;
/**
* Menu for assigning a force to a specific Tactical transport
*
* @see CampaignTransportType#TACTICAL_TRANSPORT
* @see mekhq.campaign.unit.TacticalTransportedUnitsSummary
* @see mekhq.campaign.unit.TransportAssignment
*/
public class AssignForceToTacticalTransportMenu extends AssignForceToTransportMenu {
/**
* Constructor for new tactical transport Menu
*
* @param campaign current campaign
* @param units selected units to try and assign
*
* @see CampaignTransportType#TACTICAL_TRANSPORT
*/
public AssignForceToTacticalTransportMenu(Campaign campaign, Set<Unit> units) {
super(TACTICAL_TRANSPORT, campaign, units);
}
/**
* Returns a Set of Transporters that the provided units could all be loaded into for Tactical Transport.
*
* @param units filter the Transporter list based on what these units could use
*
* @return most Transporter types except cargo and hitches
*/
@Override
protected Set<TransporterType> filterTransporterTypeMenus(final Set<Unit> units) {
Set<TransporterType> transporterTypes = new HashSet<>(campaign.getTransports(TACTICAL_TRANSPORT).keySet());
for (Unit unit : units) {
Set<TransporterType> unitTransporterTypes = CampaignTransportUtilities.mapEntityToTransporters(
TACTICAL_TRANSPORT,
unit.getEntity());
if (!unitTransporterTypes.isEmpty()) {
transporterTypes.retainAll(unitTransporterTypes);
} else {
return new HashSet<>();
}
}
if (transporterTypes.isEmpty()) {
return new HashSet<>();
}
return transporterTypes;
}
/**
* Assign a unit to a Tactical Transport.
*
* @param evt ActionEvent from the selection happening
* @param transporterType transporter type selected in an earlier menu
* @param transport transport (Unit) that will load these units
* @param units units being assigned to the transport
*/
@Override
protected void transportMenuAction(ActionEvent evt, TransporterType transporterType, Unit transport,
Set<Unit> units) {
for (Unit unit : units) {
if (!transport.getEntity().canLoad(unit.getEntity(), false)) {
JOptionPane.showMessageDialog(null, MHQInternationalization.getFormattedTextAt(
"mekhq.resources.AssignForceToTransport",
"AssignForceToTransportMenu.warningCouldNotLoadUnit.text",
unit.getName(),
transport.getName()), "Warning", JOptionPane.WARNING_MESSAGE);
return;
}
}
Set<Unit> oldTransports = transport.loadTacticalTransport(transporterType, units);
updateTransportsForTransportMenuAction(TACTICAL_TRANSPORT, transport, units, oldTransports);
}
}
| 1 | 0.768365 | 1 | 0.768365 | game-dev | MEDIA | 0.477722 | game-dev | 0.865922 | 1 | 0.865922 |
lostmyself8/Mekanism-Extras-neoforge | 6,171 | src/main/java/com/jerry/mekextras/common/tile/transmitter/ExtraTileEntityMechanicalPipe.java | package com.jerry.mekextras.common.tile.transmitter;
import com.jerry.mekextras.api.tier.AdvanceTier;
import com.jerry.mekextras.common.content.network.transmitter.ExtraMechanicalPipe;
import mekanism.api.NBTConstants;
import mekanism.api.fluid.IExtendedFluidTank;
import mekanism.api.providers.IBlockProvider;
import mekanism.common.block.states.BlockStateHelper;
import mekanism.common.block.states.TransmitterType;
import mekanism.common.capabilities.Capabilities;
import mekanism.common.capabilities.fluid.DynamicFluidHandler;
import mekanism.common.capabilities.resolver.manager.FluidHandlerManager;
import mekanism.common.content.network.FluidNetwork;
import mekanism.common.integration.computer.IComputerTile;
import mekanism.common.integration.computer.annotation.ComputerMethod;
import mekanism.common.lib.transmitter.ConnectionType;
import com.jerry.mekextras.common.registry.ExtraBlocks;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.level.block.state.BlockState;
import net.neoforged.neoforge.fluids.FluidStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
public class ExtraTileEntityMechanicalPipe extends ExtraTileEntityTransmitter implements IComputerTile {
private final FluidHandlerManager fluidHandlerManager;
public ExtraTileEntityMechanicalPipe(IBlockProvider blockProvider, BlockPos pos, BlockState state) {
super(blockProvider, pos, state);
addCapabilityResolver(fluidHandlerManager = new FluidHandlerManager(direction -> {
ExtraMechanicalPipe pipe = getTransmitter();
if (direction != null && (pipe.getConnectionTypeRaw(direction) == ConnectionType.NONE) || pipe.isRedstoneActivated()) {
return Collections.emptyList();
}
return pipe.getFluidTanks(direction);
}, new DynamicFluidHandler(this::getFluidTanks, getExtractPredicate(), getInsertPredicate(), null)));
}
@Override
protected ExtraMechanicalPipe createTransmitter(IBlockProvider blockProvider) {
return new ExtraMechanicalPipe(blockProvider, this);
}
@Override
public ExtraMechanicalPipe getTransmitter() {
return (ExtraMechanicalPipe) super.getTransmitter();
}
@Override
protected void onUpdateServer() {
getTransmitter().pullFromAcceptors();
super.onUpdateServer();
}
@Override
public TransmitterType getTransmitterType() {
return TransmitterType.MECHANICAL_PIPE;
}
@NotNull
@Override
protected BlockState upgradeResult(@NotNull BlockState current, @NotNull AdvanceTier tier) {
return BlockStateHelper.copyStateData(current, switch (tier) {
case ABSOLUTE -> ExtraBlocks.ABSOLUTE_MECHANICAL_PIPE;
case SUPREME -> ExtraBlocks.SUPREME_MECHANICAL_PIPE;
case COSMIC -> ExtraBlocks.COSMIC_MECHANICAL_PIPE;
case INFINITE -> ExtraBlocks.INFINITE_MECHANICAL_PIPE;
});
}
@NotNull
@Override
public CompoundTag getUpdateTag() {
//Note: We add the stored information to the initial update tag and not to the one we sync on side changes which uses getReducedUpdateTag
CompoundTag updateTag = super.getUpdateTag();
if (getTransmitter().hasTransmitterNetwork()) {
FluidNetwork network = getTransmitter().getTransmitterNetwork();
updateTag.put(NBTConstants.FLUID_STORED, network.lastFluid.writeToNBT(new CompoundTag()));
updateTag.putFloat(NBTConstants.SCALE, network.currentScale);
}
return updateTag;
}
private List<IExtendedFluidTank> getFluidTanks(@Nullable Direction side) {
return fluidHandlerManager.getContainers(side);
}
@Override
public void sideChanged(@NotNull Direction side, @NotNull ConnectionType old, @NotNull ConnectionType type) {
super.sideChanged(side, old, type);
if (type == ConnectionType.NONE) {
//We no longer have a capability, invalidate it, which will also notify the level
invalidateCapability(Capabilities.FLUID.block(), side);
} else if (old == ConnectionType.NONE) {
//Notify any listeners to our position that we now do have a capability
//Note: We don't invalidate our impls because we know they are already invalid, so we can short circuit setting them to null from null
invalidateCapabilities();
}
}
@Override
public void redstoneChanged(boolean powered) {
super.redstoneChanged(powered);
if (powered) {
//The transmitter now is powered by redstone and previously was not
//Note: While at first glance the below invalidation may seem over aggressive, it is not actually that aggressive as
// if a cap has not been initialized yet on a side then invalidating it will just NO-OP
invalidateCapabilityAll(Capabilities.FLUID.block());
} else {
//Notify any listeners to our position that we now do have a capability
//Note: We don't invalidate our impls because we know they are already invalid, so we can short circuit setting them to null from null
invalidateCapabilities();
}
}
//Methods relating to IComputerTile
@Override
public String getComputerName() {
return getTransmitter().getTier().getBaseTier().getLowerName() + "MechanicalPipe";
}
@ComputerMethod
FluidStack getBuffer() {
return getTransmitter().getBufferWithFallback();
}
@ComputerMethod
long getCapacity() {
ExtraMechanicalPipe pipe = getTransmitter();
return pipe.hasTransmitterNetwork() ? pipe.getTransmitterNetwork().getCapacity() : pipe.getCapacity();
}
@ComputerMethod
long getNeeded() {
return getCapacity() - getBuffer().getAmount();
}
@ComputerMethod
double getFilledPercentage() {
return getBuffer().getAmount() / (double) getCapacity();
}
//End methods IComputerTile
}
| 1 | 0.910959 | 1 | 0.910959 | game-dev | MEDIA | 0.765384 | game-dev | 0.96211 | 1 | 0.96211 |
cuberite/cuberite | 34,890 | src/Entities/Minecart.cpp |
// Minecart.cpp
// Implements the cMinecart class representing a minecart in the world
// Handles physics when a minecart is on any type of rail (overrides simulator in Entity.cpp)
// Indiana Jones!
#include "Globals.h"
#include "ChunkDef.h"
#include "Defines.h"
#include "Minecart.h"
#include "../BlockInfo.h"
#include "../ClientHandle.h"
#include "../Chunk.h"
#include "Player.h"
#include "../BoundingBox.h"
#include "../UI/MinecartWithChestWindow.h"
#define NO_SPEED 0.0
#define MAX_SPEED 8
#define MAX_SPEED_NEGATIVE -MAX_SPEED
#define DIR_NORTH_SOUTH 270
#define DIR_EAST_WEST 180
#define DIR_NORTH_WEST 315
#define DIR_NORTH_EAST 225
#define DIR_SOUTH_WEST 135
#define DIR_SOUTH_EAST 45
class cMinecartAttachCallback
{
public:
cMinecartAttachCallback(cMinecart & a_Minecart, cEntity * a_Attachee) :
m_Minecart(a_Minecart), m_Attachee(a_Attachee)
{
}
bool operator()(cEntity & a_Entity)
{
// Check if minecart is empty and if given entity is a mob:
if ((m_Attachee == nullptr) && a_Entity.IsMob())
{
// If so, attach to minecart and stop iterating:
a_Entity.AttachTo(m_Minecart);
return true;
}
return false;
}
protected:
cMinecart & m_Minecart;
cEntity * m_Attachee;
};
class cMinecartCollisionCallback
{
public:
cMinecartCollisionCallback(Vector3d a_Pos, double a_Height, double a_Width, UInt32 a_UniqueID, UInt32 a_AttacheeUniqueID) :
m_DoesIntersect(false),
m_CollidedEntityPos(0, 0, 0),
m_Pos(a_Pos),
m_Height(a_Height),
m_Width(a_Width),
m_UniqueID(a_UniqueID),
m_AttacheeUniqueID(a_AttacheeUniqueID)
{
}
bool operator () (cEntity & a_Entity)
{
if (
(
!a_Entity.IsPlayer() ||
static_cast<cPlayer &>(a_Entity).IsGameModeSpectator() // Spectators doesn't collide with anything
) &&
!a_Entity.IsMob() &&
!a_Entity.IsMinecart() &&
!a_Entity.IsBoat()
)
{
return false;
}
else if ((a_Entity.GetUniqueID() == m_UniqueID) || (a_Entity.GetUniqueID() == m_AttacheeUniqueID))
{
return false;
}
cBoundingBox bbEntity(a_Entity.GetPosition(), a_Entity.GetWidth() / 2, a_Entity.GetHeight());
cBoundingBox bbMinecart(Vector3d(m_Pos.x, floor(m_Pos.y), m_Pos.z), m_Width / 2, m_Height);
if (bbEntity.DoesIntersect(bbMinecart))
{
m_CollidedEntityPos = a_Entity.GetPosition();
m_DoesIntersect = true;
return true;
}
return false;
}
bool FoundIntersection(void) const
{
return m_DoesIntersect;
}
Vector3d GetCollidedEntityPosition(void) const
{
return m_CollidedEntityPos;
}
protected:
bool m_DoesIntersect;
Vector3d m_CollidedEntityPos;
Vector3d m_Pos;
double m_Height, m_Width;
UInt32 m_UniqueID;
UInt32 m_AttacheeUniqueID;
};
////////////////////////////////////////////////////////////////////////////////
// cMinecart:
cMinecart::cMinecart(ePayload a_Payload, Vector3d a_Pos):
Super(etMinecart, a_Pos, 0.98f, 0.7f),
m_Payload(a_Payload),
m_LastDamage(0),
m_DetectorRailPosition(0, 0, 0),
m_bIsOnDetectorRail(false)
{
SetMass(20.0f);
SetGravity(-16.0f);
SetAirDrag(0.05f);
SetMaxHealth(6);
SetHealth(6);
}
void cMinecart::SpawnOn(cClientHandle & a_ClientHandle)
{
a_ClientHandle.SendSpawnEntity(*this);
a_ClientHandle.SendEntityMetadata(*this);
}
void cMinecart::HandlePhysics(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
ASSERT(IsTicking());
int PosY = POSY_TOINT;
if ((PosY <= 0) || (PosY >= cChunkDef::Height))
{
// Outside the world, just process normal falling physics
Super::HandlePhysics(a_Dt, a_Chunk);
BroadcastMovementUpdate();
return;
}
// pos need floor, then call vec3i overload func
// if use default double -> int, will cast -1.xx -> -1(actually need to be -2)
auto relPos = cChunkDef::AbsoluteToRelative(GetPosition().Floor());
auto chunk = a_Chunk.GetRelNeighborChunkAdjustCoords(relPos);
if (chunk == nullptr)
{
// Inside an unloaded chunk, bail out all processing
return;
}
if (m_bIsOnDetectorRail && !Vector3i(POSX_TOINT, POSY_TOINT, POSZ_TOINT).Equals(m_DetectorRailPosition))
{
// Check if the rail is still there
if (m_World->GetBlock(m_DetectorRailPosition) == E_BLOCK_DETECTOR_RAIL)
{
m_World->SetBlock(m_DetectorRailPosition, E_BLOCK_DETECTOR_RAIL, m_World->GetBlockMeta(m_DetectorRailPosition) & 0x07);
}
m_bIsOnDetectorRail = false;
}
BLOCKTYPE InsideType;
NIBBLETYPE InsideMeta;
chunk->GetBlockTypeMeta(relPos, InsideType, InsideMeta);
if (!IsBlockRail(InsideType))
{
// When a descending minecart hits a flat rail, it goes through the ground; check for this
chunk->GetBlockTypeMeta(relPos.addedY(1), InsideType, InsideMeta);
if (IsBlockRail(InsideType))
{
// Push cart upwards
AddPosY(1);
}
else
{
// When a minecart gets to a descending rail, it should go down.
chunk->GetBlockTypeMeta(relPos.addedY(-1), InsideType, InsideMeta);
if (IsBlockRail(InsideType))
{
// Push cart downwards
AddPosY(-1);
}
}
}
if (IsBlockRail(InsideType))
{
if (InsideType == E_BLOCK_RAIL)
{
SnapToRail(InsideMeta);
}
else
{
SnapToRail(InsideMeta & 0x07);
}
switch (InsideType)
{
case E_BLOCK_RAIL: HandleRailPhysics(InsideMeta, a_Dt); break;
case E_BLOCK_ACTIVATOR_RAIL: HandleActivatorRailPhysics(InsideMeta, a_Dt); break;
case E_BLOCK_POWERED_RAIL: HandlePoweredRailPhysics(InsideMeta); break;
case E_BLOCK_DETECTOR_RAIL:
{
m_DetectorRailPosition = Vector3i(POSX_TOINT, POSY_TOINT, POSZ_TOINT);
m_bIsOnDetectorRail = true;
HandleDetectorRailPhysics(InsideMeta, a_Dt);
break;
}
default: VERIFY(!"Unhandled rail type despite checking if block was rail!"); break;
}
AddPosition(GetSpeed() * (static_cast<double>(a_Dt.count()) / 1000)); // Commit changes; as we use our own engine when on rails, this needs to be done, whereas it is normally in Entity.cpp
}
else
{
// Not on rail, default physics
SetPosY(floor(GetPosY()) + 0.35); // HandlePhysics overrides this if minecart can fall, else, it is to stop ground clipping minecart bottom when off-rail
Super::HandlePhysics(a_Dt, *chunk);
}
// Enforce speed limit:
m_Speed.Clamp(MAX_SPEED_NEGATIVE, MAX_SPEED);
// Broadcast positioning changes to client
BroadcastMovementUpdate();
}
void cMinecart::HandleRailPhysics(NIBBLETYPE a_RailMeta, std::chrono::milliseconds a_Dt)
{
/*
NOTE: Please bear in mind that taking away from negatives make them even more negative,
adding to negatives make them positive, etc.
*/
switch (a_RailMeta)
{
case E_META_RAIL_ZM_ZP: // NORTHSOUTH
{
SetYaw(DIR_NORTH_SOUTH);
SetPosY(floor(GetPosY()) + 0.55);
SetSpeedY(NO_SPEED); // Don't move vertically as on ground
SetSpeedX(NO_SPEED); // Correct diagonal movement from curved rails
// Execute both the entity and block collision checks
auto BlckCol = TestBlockCollision(a_RailMeta);
auto EntCol = TestEntityCollision(a_RailMeta);
if (EntCol || BlckCol)
{
return;
}
if (GetSpeedZ() != NO_SPEED) // Don't do anything if cart is stationary
{
if (GetSpeedZ() > 0)
{
// Going SOUTH, slow down
ApplyAcceleration({ 0.0, 0.0, 1.0 }, -0.1);
}
else
{
// Going NORTH, slow down
ApplyAcceleration({ 0.0, 0.0, -1.0 }, -0.1);
}
}
return;
}
case E_META_RAIL_XM_XP: // EASTWEST
{
SetYaw(DIR_EAST_WEST);
SetPosY(floor(GetPosY()) + 0.55);
SetSpeedY(NO_SPEED);
SetSpeedZ(NO_SPEED);
auto BlckCol = TestBlockCollision(a_RailMeta);
auto EntCol = TestEntityCollision(a_RailMeta);
if (EntCol || BlckCol)
{
return;
}
if (GetSpeedX() != NO_SPEED)
{
if (GetSpeedX() > 0)
{
ApplyAcceleration({ 1.0, 0.0, 0.0 }, -0.1);
}
else
{
ApplyAcceleration({ -1.0, 0.0, 0.0 }, -0.1);
}
}
return;
}
case E_META_RAIL_ASCEND_ZM: // ASCEND NORTH
{
SetYaw(DIR_NORTH_SOUTH);
SetSpeedX(NO_SPEED);
auto BlckCol = TestBlockCollision(a_RailMeta);
auto EntCol = TestEntityCollision(a_RailMeta);
if (EntCol || BlckCol)
{
return;
}
if (GetSpeedZ() >= 0)
{
// SpeedZ POSITIVE, going SOUTH
AddSpeedZ(0.5); // Speed up
SetSpeedY(-GetSpeedZ()); // Downward movement is negative (0 minus positive numbers is negative)
}
else
{
// SpeedZ NEGATIVE, going NORTH
AddSpeedZ(1); // Slow down
SetSpeedY(-GetSpeedZ()); // Upward movement is positive (0 minus negative number is positive number)
}
return;
}
case E_META_RAIL_ASCEND_ZP: // ASCEND SOUTH
{
SetYaw(DIR_NORTH_SOUTH);
SetSpeedX(NO_SPEED);
auto BlckCol = TestBlockCollision(a_RailMeta);
auto EntCol = TestEntityCollision(a_RailMeta);
if (EntCol || BlckCol)
{
return;
}
if (GetSpeedZ() > 0)
{
// SpeedZ POSITIVE, going SOUTH
AddSpeedZ(-1); // Slow down
SetSpeedY(GetSpeedZ()); // Upward movement positive
}
else
{
// SpeedZ NEGATIVE, going NORTH
AddSpeedZ(-0.5); // Speed up
SetSpeedY(GetSpeedZ()); // Downward movement negative
}
return;
}
case E_META_RAIL_ASCEND_XM: // ASCEND EAST
{
SetYaw(DIR_EAST_WEST);
SetSpeedZ(NO_SPEED);
auto BlckCol = TestBlockCollision(a_RailMeta);
auto EntCol = TestEntityCollision(a_RailMeta);
if (EntCol || BlckCol)
{
return;
}
if (GetSpeedX() >= NO_SPEED)
{
AddSpeedX(0.5);
SetSpeedY(-GetSpeedX());
}
else
{
AddSpeedX(1);
SetSpeedY(-GetSpeedX());
}
return;
}
case E_META_RAIL_ASCEND_XP: // ASCEND WEST
{
SetYaw(DIR_EAST_WEST);
SetSpeedZ(NO_SPEED);
auto BlckCol = TestBlockCollision(a_RailMeta);
auto EntCol = TestEntityCollision(a_RailMeta);
if (EntCol || BlckCol)
{
return;
}
if (GetSpeedX() > 0)
{
AddSpeedX(-1);
SetSpeedY(GetSpeedX());
}
else
{
AddSpeedX(-0.5);
SetSpeedY(GetSpeedX());
}
return;
}
case E_META_RAIL_CURVED_ZM_XM: // Ends pointing NORTH and WEST
{
SetYaw(DIR_NORTH_WEST); // Set correct rotation server side
SetPosY(floor(GetPosY()) + 0.55); // Levitate dat cart
SetSpeedY(NO_SPEED);
auto BlckCol = TestBlockCollision(a_RailMeta);
auto EntCol = TestEntityCollision(a_RailMeta);
if (EntCol || BlckCol)
{
return;
}
// SnapToRail handles turning
return;
}
case E_META_RAIL_CURVED_ZM_XP: // Curved NORTH EAST
{
SetYaw(DIR_NORTH_EAST);
SetPosY(floor(GetPosY()) + 0.55);
SetSpeedY(NO_SPEED);
auto BlckCol = TestBlockCollision(a_RailMeta);
auto EntCol = TestEntityCollision(a_RailMeta);
if (EntCol || BlckCol)
{
return;
}
return;
}
case E_META_RAIL_CURVED_ZP_XM: // Curved SOUTH WEST
{
SetYaw(DIR_SOUTH_WEST);
SetPosY(floor(GetPosY()) + 0.55);
SetSpeedY(NO_SPEED);
auto BlckCol = TestBlockCollision(a_RailMeta);
auto EntCol = TestEntityCollision(a_RailMeta);
if (EntCol || BlckCol)
{
return;
}
return;
}
case E_META_RAIL_CURVED_ZP_XP: // Curved SOUTH EAST
{
SetYaw(DIR_SOUTH_EAST);
SetPosY(floor(GetPosY()) + 0.55);
SetSpeedY(NO_SPEED);
auto BlckCol = TestBlockCollision(a_RailMeta);
auto EntCol = TestEntityCollision(a_RailMeta);
if (EntCol || BlckCol)
{
return;
}
return;
}
}
UNREACHABLE("Unsupported rail meta type");
}
void cMinecart::HandlePoweredRailPhysics(NIBBLETYPE a_RailMeta)
{
// If the rail is powered set to speed up else slow down.
const bool IsRailPowered = ((a_RailMeta & 0x8) == 0x8);
const double Acceleration = IsRailPowered ? 1.0 : -2.0;
// PoweredRail only has 5 status in low 3bit. so we need do a logical and to get correct powered rail meta data.
NIBBLETYPE PoweredRailMeta = a_RailMeta & 0x7;
switch (PoweredRailMeta)
{
case E_META_RAIL_ZM_ZP: // NORTHSOUTH
{
SetYaw(DIR_NORTH_SOUTH);
SetPosY(floor(GetPosY()) + 0.55);
SetSpeedY(0);
SetSpeedX(0);
bool BlckCol = TestBlockCollision(PoweredRailMeta), EntCol = TestEntityCollision(PoweredRailMeta);
if (EntCol || BlckCol)
{
return;
}
if (GetSpeedZ() != NO_SPEED)
{
if (GetSpeedZ() > NO_SPEED)
{
ApplyAcceleration({ 0.0, 0.0, 1.0 }, Acceleration);
}
else
{
ApplyAcceleration({ 0.0, 0.0, -1.0 }, Acceleration);
}
}
// If rail is powered check for nearby blocks that could kick-start the minecart
else if (IsRailPowered)
{
bool IsBlockZP = IsSolidBlockAtOffset(0, 0, 1);
bool IsBlockZM = IsSolidBlockAtOffset(0, 0, -1);
// Only kick-start the minecart if a block is on one side, but not both
if (IsBlockZM && !IsBlockZP)
{
ApplyAcceleration({ 0.0, 0.0, 1.0 }, Acceleration);
}
else if (!IsBlockZM && IsBlockZP)
{
ApplyAcceleration({ 0.0, 0.0, -1.0 }, Acceleration);
}
}
break;
}
case E_META_RAIL_XM_XP: // EASTWEST
{
SetYaw(DIR_EAST_WEST);
SetPosY(floor(GetPosY()) + 0.55);
SetSpeedY(NO_SPEED);
SetSpeedZ(NO_SPEED);
bool BlckCol = TestBlockCollision(PoweredRailMeta), EntCol = TestEntityCollision(PoweredRailMeta);
if (EntCol || BlckCol)
{
return;
}
if (GetSpeedX() != NO_SPEED)
{
if (GetSpeedX() > NO_SPEED)
{
ApplyAcceleration({ 1.0, 0.0, 0.0 }, Acceleration);
}
else
{
ApplyAcceleration({ -1.0, 0.0, 0.0 }, Acceleration);
}
}
// If rail is powered check for nearby blocks that could kick-start the minecart
else if (IsRailPowered)
{
bool IsBlockXP = IsSolidBlockAtOffset(1, 0, 0);
bool IsBlockXM = IsSolidBlockAtOffset(-1, 0, 0);
// Only kick-start the minecart if a block is on one side, but not both
if (IsBlockXM && !IsBlockXP)
{
ApplyAcceleration({ 1.0, 0.0, 0.0 }, Acceleration);
}
else if (!IsBlockXM && IsBlockXP)
{
ApplyAcceleration({ -1.0, 0.0, 0.0 }, Acceleration);
}
}
break;
}
case E_META_RAIL_ASCEND_XM: // ASCEND EAST
{
SetYaw(DIR_EAST_WEST);
SetSpeedZ(NO_SPEED);
if (GetSpeedX() >= NO_SPEED)
{
ApplyAcceleration({ 1.0, 0.0, 0.0 }, Acceleration);
SetSpeedY(-GetSpeedX());
}
else
{
ApplyAcceleration({ -1.0, 0.0, 0.0 }, Acceleration);
SetSpeedY(-GetSpeedX());
}
break;
}
case E_META_RAIL_ASCEND_XP: // ASCEND WEST
{
SetYaw(DIR_EAST_WEST);
SetSpeedZ(NO_SPEED);
if (GetSpeedX() > NO_SPEED)
{
ApplyAcceleration({ 1.0, 0.0, 0.0 }, Acceleration);
SetSpeedY(GetSpeedX());
}
else
{
ApplyAcceleration({ -1.0, 0.0, 0.0 }, Acceleration);
SetSpeedY(GetSpeedX());
}
break;
}
case E_META_RAIL_ASCEND_ZM: // ASCEND NORTH
{
SetYaw(DIR_NORTH_SOUTH);
SetSpeedX(NO_SPEED);
if (GetSpeedZ() >= NO_SPEED)
{
ApplyAcceleration({ 0.0, 0.0, 1.0 }, Acceleration);
SetSpeedY(-GetSpeedZ());
}
else
{
ApplyAcceleration({ 0.0, 0.0, -1.0 }, Acceleration);
SetSpeedY(-GetSpeedZ());
}
break;
}
case E_META_RAIL_ASCEND_ZP: // ASCEND SOUTH
{
SetYaw(DIR_NORTH_SOUTH);
SetSpeedX(NO_SPEED);
if (GetSpeedZ() > NO_SPEED)
{
ApplyAcceleration({ 0.0, 0.0, 1.0 }, Acceleration);
SetSpeedY(GetSpeedZ());
}
else
{
ApplyAcceleration({ 0.0, 0.0, -1.0 }, Acceleration);
SetSpeedY(GetSpeedZ());
}
break;
}
default: ASSERT(!"Unhandled powered rail metadata!"); break;
}
}
void cMinecart::HandleDetectorRailPhysics(NIBBLETYPE a_RailMeta, std::chrono::milliseconds a_Dt)
{
m_World->SetBlockMeta(m_DetectorRailPosition, a_RailMeta | 0x08);
// No special handling
HandleRailPhysics(a_RailMeta & 0x07, a_Dt);
}
void cMinecart::HandleActivatorRailPhysics(NIBBLETYPE a_RailMeta, std::chrono::milliseconds a_Dt)
{
HandleRailPhysics(a_RailMeta & 0x07, a_Dt);
// TODO - shake minecart, throw entities out
}
void cMinecart::SnapToRail(NIBBLETYPE a_RailMeta)
{
switch (a_RailMeta)
{
case E_META_RAIL_ASCEND_XM:
case E_META_RAIL_ASCEND_XP:
case E_META_RAIL_XM_XP:
{
SetSpeedZ(NO_SPEED);
SetPosZ(floor(GetPosZ()) + 0.5);
break;
}
case E_META_RAIL_ASCEND_ZM:
case E_META_RAIL_ASCEND_ZP:
case E_META_RAIL_ZM_ZP:
{
SetSpeedX(NO_SPEED);
SetPosX(floor(GetPosX()) + 0.5);
break;
}
// Curved rail physics: once minecart has reached more than half of the block in the direction that it is travelling in, jerk it in the direction of curvature
case E_META_RAIL_CURVED_ZM_XM:
{
if (GetPosZ() > floor(GetPosZ()) + 0.5)
{
if (GetSpeedZ() > NO_SPEED)
{
SetSpeedX(-GetSpeedZ() * 0.7);
}
SetSpeedZ(NO_SPEED);
SetPosZ(floor(GetPosZ()) + 0.5);
}
else if (GetPosX() > floor(GetPosX()) + 0.5)
{
if (GetSpeedX() > 0)
{
SetSpeedZ(-GetSpeedX() * 0.7);
}
SetSpeedX(NO_SPEED);
SetPosX(floor(GetPosX()) + 0.5);
}
SetSpeedY(NO_SPEED);
break;
}
case E_META_RAIL_CURVED_ZM_XP:
{
if (GetPosZ() > floor(GetPosZ()) + 0.5)
{
if (GetSpeedZ() > NO_SPEED)
{
SetSpeedX(GetSpeedZ() * 0.7);
}
SetSpeedZ(NO_SPEED);
SetPosZ(floor(GetPosZ()) + 0.5);
}
else if (GetPosX() < floor(GetPosX()) + 0.5)
{
if (GetSpeedX() < NO_SPEED)
{
SetSpeedZ(GetSpeedX() * 0.7);
}
SetSpeedX(NO_SPEED);
SetPosX(floor(GetPosX()) + 0.5);
}
SetSpeedY(NO_SPEED);
break;
}
case E_META_RAIL_CURVED_ZP_XM:
{
if (GetPosZ() < floor(GetPosZ()) + 0.5)
{
if (GetSpeedZ() < NO_SPEED)
{
SetSpeedX(GetSpeedZ() * 0.7);
}
SetSpeedZ(NO_SPEED);
SetPosZ(floor(GetPosZ()) + 0.5);
}
else if (GetPosX() > floor(GetPosX()) + 0.5)
{
if (GetSpeedX() > NO_SPEED)
{
SetSpeedZ(GetSpeedX() * 0.7);
}
SetSpeedX(NO_SPEED);
SetPosX(floor(GetPosX()) + 0.5);
}
SetSpeedY(NO_SPEED);
break;
}
case E_META_RAIL_CURVED_ZP_XP:
{
if (GetPosZ() < floor(GetPosZ()) + 0.5)
{
if (GetSpeedZ() < NO_SPEED)
{
SetSpeedX(-GetSpeedZ() * 0.7);
}
SetSpeedZ(NO_SPEED);
SetPosZ(floor(GetPosZ()) + 0.5);
}
else if (GetPosX() < floor(GetPosX()) + 0.5)
{
if (GetSpeedX() < NO_SPEED)
{
SetSpeedZ(-GetSpeedX() * 0.7);
}
SetSpeedX(NO_SPEED);
SetPosX(floor(GetPosX()) + 0.5);
}
SetSpeedY(0);
break;
}
default: break;
}
}
bool cMinecart::IsSolidBlockAtPosition(Vector3i a_Pos)
{
BLOCKTYPE Block = m_World->GetBlock(a_Pos);
return !IsBlockRail(Block) && cBlockInfo::IsSolid(Block);
}
bool cMinecart::IsSolidBlockAtOffset(int a_XOffset, int a_YOffset, int a_ZOffset)
{
return IsSolidBlockAtPosition({POSX_TOINT + a_XOffset, POSY_TOINT + a_YOffset, POSZ_TOINT + a_ZOffset});
}
bool cMinecart::IsBlockCollisionAtOffset(Vector3i a_Offset)
{
auto BlockPosition = GetPosition().Floor() + a_Offset;
if (!IsSolidBlockAtPosition(BlockPosition))
{
return false;
}
auto bbBlock = cBoundingBox(
static_cast<Vector3d>(BlockPosition),
static_cast<Vector3d>(BlockPosition + Vector3i(1, 1, 1))
);
return GetBoundingBox().DoesIntersect(bbBlock);
}
bool cMinecart::TestBlockCollision(NIBBLETYPE a_RailMeta)
{
auto SpeedX = GetSpeedX();
auto SpeedZ = GetSpeedZ();
// Don't do anything if minecarts aren't moving.
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wfloat-equal"
#endif
if ((SpeedX == 0) && (SpeedZ == 0))
{
return false;
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
auto StopTheCart = true;
auto StopOffset = Vector3d();
switch (a_RailMeta)
{
case E_META_RAIL_ZM_ZP:
{
if (SpeedZ > 0)
{
StopOffset = Vector3d(0, 0, 0.4);
StopTheCart = IsBlockCollisionAtOffset({0, 0, 1});
}
else // SpeedZ < 0
{
StopTheCart = IsBlockCollisionAtOffset({0, 0, -1});
StopOffset = Vector3d(0, 0, 0.65);
}
break;
}
case E_META_RAIL_XM_XP:
{
if (SpeedX > 0)
{
StopTheCart = IsBlockCollisionAtOffset({1, 0, 0});
StopOffset = Vector3d(0.4, 0, 0);
}
else // SpeedX < 0
{
StopTheCart = IsBlockCollisionAtOffset({-1, 0, 0});
StopOffset = Vector3d(0.65, 0, 0);
}
break;
}
// Ascending rails check for one block on the way up, two on the way down.
case E_META_RAIL_ASCEND_XM:
{
StopOffset = Vector3d(0.5, 0, 0);
if (SpeedX < 0)
{
StopTheCart = IsBlockCollisionAtOffset({-1, 1, 0});
}
else // SpeedX > 0
{
StopTheCart = IsBlockCollisionAtOffset({1, 0, 0}) || IsBlockCollisionAtOffset({1, 1, 0});
}
break;
}
case E_META_RAIL_ASCEND_XP:
{
StopOffset = Vector3d(0.5, 0, 0);
if (SpeedX > 0)
{
StopTheCart = IsBlockCollisionAtOffset({1, 1, 0});
}
else // SpeedX < 0
{
StopTheCart = IsBlockCollisionAtOffset({-1, 0, 0}) || IsBlockCollisionAtOffset({-1, 1, 0});
}
break;
}
case E_META_RAIL_ASCEND_ZM:
{
StopOffset = Vector3d(0, 0, 0.5);
if (SpeedZ < 0)
{
StopTheCart = IsBlockCollisionAtOffset({0, 1, -1});
}
else // SpeedZ > 0
{
StopTheCart = IsBlockCollisionAtOffset({0, 0, 1}) || IsBlockCollisionAtOffset({0, 1, 1});
}
break;
}
case E_META_RAIL_ASCEND_ZP:
{
StopOffset = Vector3d(0, 0, 0.5);
if (SpeedZ > 0)
{
StopTheCart = IsBlockCollisionAtOffset({0, 1, 1});
}
else // SpeedZ < 0
{
StopTheCart = IsBlockCollisionAtOffset({0, 0, -1}) || IsBlockCollisionAtOffset({0, 1, -1});
}
break;
}
// Curved rails allow movement across both the x and z axes. But when the cart is
// moving towards one of the rail endpoints, it will always have velocity towards
// the direction of that endpoint in the same axis.
case E_META_RAIL_CURVED_ZP_XP:
{
StopOffset = Vector3d(0.5, 0, 0.5);
if (SpeedZ > 0)
{
StopTheCart = IsBlockCollisionAtOffset({0, 0, 1});
break;
}
if (SpeedX > 0)
{
StopTheCart = IsBlockCollisionAtOffset({1, 0, 0});
break;
}
break;
}
case E_META_RAIL_CURVED_ZP_XM:
{
StopOffset = Vector3d(0.5, 0, 0.5);
if (SpeedZ > 0)
{
StopTheCart = IsBlockCollisionAtOffset({0, 0, 1});
break;
}
if (SpeedX < 0)
{
StopTheCart = IsBlockCollisionAtOffset({-1, 0, 0});
break;
}
break;
}
case E_META_RAIL_CURVED_ZM_XM:
{
StopOffset = Vector3d(0.5, 0, 0.5);
if (SpeedZ < 0)
{
StopTheCart = IsBlockCollisionAtOffset({0, 0, -1});
break;
}
if (SpeedX < 0)
{
StopTheCart = IsBlockCollisionAtOffset({-1, 0, 0});
break;
}
break;
}
case E_META_RAIL_CURVED_ZM_XP:
{
StopOffset = Vector3d(0.5, 0, 0.5);
if (SpeedZ < 0)
{
StopTheCart = IsBlockCollisionAtOffset({0, 0, -1});
break;
}
if (SpeedX > 0)
{
StopTheCart = IsBlockCollisionAtOffset({1, 0, 0});
break;
}
break;
}
}
if (StopTheCart)
{
SetSpeed(0, 0, 0);
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wfloat-equal"
#endif
if (StopOffset.x != 0)
{
SetPosX(POSX_TOINT + StopOffset.x);
}
if (StopOffset.z != 0)
{
SetPosZ(POSZ_TOINT + StopOffset.z);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
return true;
}
return false;
}
bool cMinecart::TestEntityCollision(NIBBLETYPE a_RailMeta)
{
cMinecartCollisionCallback MinecartCollisionCallback(
GetPosition(), GetHeight(), GetWidth(), GetUniqueID(),
((m_Attachee == nullptr) ? cEntity::INVALID_ID : m_Attachee->GetUniqueID())
);
int ChunkX, ChunkZ;
cChunkDef::BlockToChunk(POSX_TOINT, POSZ_TOINT, ChunkX, ChunkZ);
m_World->ForEachEntityInChunk(ChunkX, ChunkZ, MinecartCollisionCallback);
if (!MinecartCollisionCallback.FoundIntersection())
{
return false;
}
// Collision was true, create bounding box for minecart, call attach callback for all entities within that box
cMinecartAttachCallback MinecartAttachCallback(*this, m_Attachee);
Vector3d MinecartPosition = GetPosition();
cBoundingBox bbMinecart(Vector3d(MinecartPosition.x, floor(MinecartPosition.y), MinecartPosition.z), GetWidth() / 2, GetHeight());
m_World->ForEachEntityInBox(bbMinecart, MinecartAttachCallback);
switch (a_RailMeta)
{
case E_META_RAIL_ZM_ZP:
{
if (MinecartCollisionCallback.GetCollidedEntityPosition().z >= GetPosZ())
{
if (GetSpeedZ() > 0) // True if minecart is moving into the direction of the entity
{
SetSpeedZ(0); // Entity handles the pushing
}
}
else // if (MinecartCollisionCallback.GetCollidedEntityPosition().z < GetPosZ())
{
if (GetSpeedZ() < 0) // True if minecart is moving into the direction of the entity
{
SetSpeedZ(0); // Entity handles the pushing
}
}
return true;
}
case E_META_RAIL_XM_XP:
{
if (MinecartCollisionCallback.GetCollidedEntityPosition().x >= GetPosX())
{
if (GetSpeedX() > 0) // True if minecart is moving into the direction of the entity
{
SetSpeedX(0); // Entity handles the pushing
}
}
else // if (MinecartCollisionCallback.GetCollidedEntityPosition().x < GetPosX())
{
if (GetSpeedX() < 0) // True if minecart is moving into the direction of the entity
{
SetSpeedX(0); // Entity handles the pushing
}
}
return true;
}
case E_META_RAIL_CURVED_ZM_XM:
case E_META_RAIL_CURVED_ZP_XP:
{
Vector3d Distance = MinecartCollisionCallback.GetCollidedEntityPosition() - Vector3d(GetPosX(), 0, GetPosZ());
// Prevent division by small numbers
if (std::abs(Distance.z) < 0.001)
{
Distance.z = 0.001;
}
/* Check to which side the minecart is to be pushed.
Let's consider a z-x-coordinate system where the minecart is the center (0, 0).
The minecart moves along the line x = -z, the perpendicular line to this is x = z.
In order to decide to which side the minecart is to be pushed, it must be checked on what side of the perpendicular line the pushing entity is located. */
if (
((Distance.z > 0) && ((Distance.x / Distance.z) >= 1)) ||
((Distance.z < 0) && ((Distance.x / Distance.z) <= 1))
)
{
// Moving -X +Z
if ((-GetSpeedX() * 0.4 / sqrt(2.0)) < 0.01)
{
// ~ SpeedX >= 0 Immobile or not moving in the "right" direction. Give it a bump!
AddSpeedX(-4 / sqrt(2.0));
AddSpeedZ(4 / sqrt(2.0));
}
else
{
// ~ SpeedX < 0 Moving in the "right" direction. Only accelerate it a bit.
SetSpeedX(GetSpeedX() * 0.4 / sqrt(2.0));
SetSpeedZ(GetSpeedZ() * 0.4 / sqrt(2.0));
}
}
else if ((GetSpeedX() * 0.4 / sqrt(2.0)) < 0.01)
{
// Moving +X -Z
// ~ SpeedX <= 0 Immobile or not moving in the "right" direction
AddSpeedX(4 / sqrt(2.0));
AddSpeedZ(-4 / sqrt(2.0));
}
else
{
// ~ SpeedX > 0 Moving in the "right" direction
SetSpeedX(GetSpeedX() * 0.4 / sqrt(2.0));
SetSpeedZ(GetSpeedZ() * 0.4 / sqrt(2.0));
}
break;
}
case E_META_RAIL_CURVED_ZM_XP:
case E_META_RAIL_CURVED_ZP_XM:
{
Vector3d Distance = MinecartCollisionCallback.GetCollidedEntityPosition() - Vector3d(GetPosX(), 0, GetPosZ());
// Prevent division by small numbers
if (std::abs(Distance.z) < 0.001)
{
Distance.z = 0.001;
}
/* Check to which side the minecart is to be pushed.
Let's consider a z-x-coordinate system where the minecart is the center (0, 0).
The minecart moves along the line x = z, the perpendicular line to this is x = -z.
In order to decide to which side the minecart is to be pushed, it must be checked on what side of the perpendicular line the pushing entity is located. */
if (
((Distance.z > 0) && ((Distance.x / Distance.z) <= -1)) ||
((Distance.z < 0) && ((Distance.x / Distance.z) >= -1))
)
{
// Moving +X +Z
if ((GetSpeedX() * 0.4) < 0.01)
{
// ~ SpeedX <= 0 Immobile or not moving in the "right" direction
AddSpeedX(4 / sqrt(2.0));
AddSpeedZ(4 / sqrt(2.0));
}
else
{
// ~ SpeedX > 0 Moving in the "right" direction
SetSpeedX(GetSpeedX() * 0.4 / sqrt(2.0));
SetSpeedZ(GetSpeedZ() * 0.4 / sqrt(2.0));
}
}
else if ((-GetSpeedX() * 0.4) < 0.01)
{
// Moving -X -Z
// ~ SpeedX >= 0 Immobile or not moving in the "right" direction
AddSpeedX(-4 / sqrt(2.0));
AddSpeedZ(-4 / sqrt(2.0));
}
else
{
// ~ SpeedX < 0 Moving in the "right" direction
SetSpeedX(GetSpeedX() * 0.4 / sqrt(2.0));
SetSpeedZ(GetSpeedZ() * 0.4 / sqrt(2.0));
}
break;
}
default: break;
}
return false;
}
bool cMinecart::DoTakeDamage(TakeDamageInfo & TDI)
{
if ((TDI.Attacker != nullptr) && TDI.Attacker->IsPlayer() && static_cast<cPlayer *>(TDI.Attacker)->IsGameModeCreative())
{
TDI.FinalDamage = GetMaxHealth(); // Instant hit for creative
SetInvulnerableTicks(0);
return Super::DoTakeDamage(TDI); // No drops for creative
}
m_LastDamage = static_cast<int>(TDI.FinalDamage);
if (!Super::DoTakeDamage(TDI))
{
return false;
}
m_World->BroadcastEntityMetadata(*this);
return true;
}
void cMinecart::KilledBy(TakeDamageInfo & a_TDI)
{
Super::KilledBy(a_TDI);
Destroy();
}
void cMinecart::OnRemoveFromWorld(cWorld & a_World)
{
if (m_bIsOnDetectorRail)
{
m_World->SetBlock(m_DetectorRailPosition, E_BLOCK_DETECTOR_RAIL, m_World->GetBlockMeta(m_DetectorRailPosition) & 0x07);
}
Super::OnRemoveFromWorld(a_World);
}
void cMinecart::HandleSpeedFromAttachee(float a_Forward, float a_Sideways)
{
// limit normal minecart speed max lower than 4
// once speed is higher than 4, no more add speed.
if (GetSpeed().Length() > 4)
{
return;
}
Vector3d LookVector = m_Attachee->GetLookVector();
Vector3d ToAddSpeed = LookVector * (a_Forward * 0.4) ;
ToAddSpeed.y = 0;
AddSpeed(ToAddSpeed);
}
void cMinecart::ApplyAcceleration(Vector3d a_ForwardDirection, double a_Acceleration)
{
double CurSpeed = GetSpeed().Dot(a_ForwardDirection);
double NewSpeed = CurSpeed + a_Acceleration;
if (NewSpeed < 0.0)
{
// Prevent deceleration from turning the minecart around.
NewSpeed = 0.0;
}
auto Acceleration = a_ForwardDirection * (NewSpeed - CurSpeed);
AddSpeed(Acceleration);
}
////////////////////////////////////////////////////////////////////////////////
// cRideableMinecart:
cRideableMinecart::cRideableMinecart(Vector3d a_Pos, const cItem & a_Content, int a_ContentHeight):
Super(mpNone, a_Pos),
m_Content(a_Content),
m_ContentHeight(a_ContentHeight)
{
}
void cRideableMinecart::GetDrops(cItems & a_Drops, cEntity * a_Killer)
{
a_Drops.emplace_back(E_ITEM_MINECART);
}
void cRideableMinecart::OnRightClicked(cPlayer & a_Player)
{
Super::OnRightClicked(a_Player);
if (m_Attachee != nullptr)
{
if (m_Attachee->GetUniqueID() == a_Player.GetUniqueID())
{
// This player is already sitting in, they want out.
a_Player.Detach();
return;
}
if (m_Attachee->IsPlayer())
{
// Another player is already sitting in here, cannot attach
return;
}
// Detach whatever is sitting in this minecart now:
m_Attachee->Detach();
}
// Attach the player to this minecart:
a_Player.AttachTo(*this);
}
////////////////////////////////////////////////////////////////////////////////
// cMinecartWithChest:
cMinecartWithChest::cMinecartWithChest(Vector3d a_Pos):
Super(mpChest, a_Pos),
cEntityWindowOwner(this),
m_Contents(ContentsWidth, ContentsHeight)
{
m_Contents.AddListener(*this);
}
void cMinecartWithChest::GetDrops(cItems & a_Drops, cEntity * a_Killer)
{
m_Contents.CopyToItems(a_Drops);
a_Drops.emplace_back(E_ITEM_CHEST_MINECART);
}
void cMinecartWithChest::OnRemoveFromWorld(cWorld & a_World)
{
const auto Window = GetWindow();
if (Window != nullptr)
{
Window->OwnerDestroyed();
}
Super::OnRemoveFromWorld(a_World);
}
void cMinecartWithChest::OnRightClicked(cPlayer & a_Player)
{
// If the window is not created, open it anew:
cWindow * Window = GetWindow();
if (Window == nullptr)
{
OpenNewWindow();
Window = GetWindow();
}
// Open the window for the player:
if (Window != nullptr)
{
if (a_Player.GetWindow() != Window)
{
a_Player.OpenWindow(*Window);
}
}
}
void cMinecartWithChest::OpenNewWindow()
{
OpenWindow(new cMinecartWithChestWindow(this));
}
////////////////////////////////////////////////////////////////////////////////
// cMinecartWithFurnace:
cMinecartWithFurnace::cMinecartWithFurnace(Vector3d a_Pos):
Super(mpFurnace, a_Pos),
m_FueledTimeLeft(-1),
m_IsFueled(false)
{
}
void cMinecartWithFurnace::GetDrops(cItems & a_Drops, cEntity * a_Killer)
{
a_Drops.emplace_back(E_ITEM_FURNACE_MINECART);
}
void cMinecartWithFurnace::OnRightClicked(cPlayer & a_Player)
{
if (a_Player.GetEquippedItem().m_ItemType == E_ITEM_COAL)
{
if (!a_Player.IsGameModeCreative())
{
a_Player.GetInventory().RemoveOneEquippedItem();
}
if (!m_IsFueled) // We don't want to change the direction by right clicking it.
{
AddSpeed(a_Player.GetLookVector().x, 0, a_Player.GetLookVector().z);
}
m_IsFueled = true;
m_FueledTimeLeft = m_FueledTimeLeft + 600; // The minecart will be active 600 more ticks.
m_World->BroadcastEntityMetadata(*this);
}
}
void cMinecartWithFurnace::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
Super::Tick(a_Dt, a_Chunk);
if (!IsTicking())
{
// The base class tick destroyed us
return;
}
if (m_IsFueled)
{
m_FueledTimeLeft--;
if (m_FueledTimeLeft < 0)
{
m_IsFueled = false;
m_World->BroadcastEntityMetadata(*this);
return;
}
if (GetSpeed().Length() > 6)
{
return;
}
AddSpeed(GetSpeed() / 4);
}
}
////////////////////////////////////////////////////////////////////////////////
// cMinecartWithTNT:
cMinecartWithTNT::cMinecartWithTNT(Vector3d a_Pos):
Super(mpTNT, a_Pos)
{
}
void cMinecartWithTNT::HandleActivatorRailPhysics(NIBBLETYPE a_RailMeta, std::chrono::milliseconds a_Dt)
{
Super::HandleActivatorRailPhysics(a_RailMeta, a_Dt);
if ((a_RailMeta & 0x08) && !m_isTNTFused)
{
m_isTNTFused = true;
m_TNTFuseTicksLeft = 80;
m_World->BroadcastSoundEffect("entity.tnt.primed", GetPosition(), 1.0f, 1.0f);
m_World->BroadcastEntityAnimation(*this, EntityAnimation::MinecartTNTIgnites);
}
}
void cMinecartWithTNT::GetDrops(cItems & a_Drops, cEntity * a_Killer)
{
a_Drops.emplace_back(E_ITEM_MINECART_WITH_TNT);
}
void cMinecartWithTNT::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
Super::Tick(a_Dt, a_Chunk);
if (!IsTicking())
{
return;
}
if (m_isTNTFused)
{
if (m_TNTFuseTicksLeft > 0)
{
--m_TNTFuseTicksLeft;
}
else
{
Destroy();
m_World->DoExplosionAt(4.0, GetPosX(), GetPosY() + GetHeight() / 2, GetPosZ(), true, esTNTMinecart, this);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// cMinecartWithHopper:
cMinecartWithHopper::cMinecartWithHopper(Vector3d a_Pos):
Super(mpHopper, a_Pos)
{
}
// TODO: Make it suck up blocks and travel further than any other cart and physics and put and take blocks
// AND AVARYTHING!!
void cMinecartWithHopper::GetDrops(cItems & a_Drops, cEntity * a_Killer)
{
a_Drops.emplace_back(E_ITEM_MINECART_WITH_HOPPER);
}
| 1 | 0.914559 | 1 | 0.914559 | game-dev | MEDIA | 0.905222 | game-dev | 0.996783 | 1 | 0.996783 |
unmojang/FjordLauncher | 27,407 | launcher/minecraft/mod/tasks/LocalModParseTask.cpp | #include "LocalModParseTask.h"
#include <qdcss.h>
#include <quazip/quazip.h>
#include <quazip/quazipfile.h>
#include <toml++/toml.h>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QRegularExpression>
#include <QString>
#include "FileSystem.h"
#include "Json.h"
#include "minecraft/mod/ModDetails.h"
#include "settings/INIFile.h"
static QRegularExpression newlineRegex("\r\n|\n|\r");
namespace ModUtils {
// NEW format
// https://github.com/MinecraftForge/FML/wiki/FML-mod-information-file/c8d8f1929aff9979e322af79a59ce81f3e02db6a
// OLD format:
// https://github.com/MinecraftForge/FML/wiki/FML-mod-information-file/5bf6a2d05145ec79387acc0d45c958642fb049fc
ModDetails ReadMCModInfo(QByteArray contents)
{
auto getInfoFromArray = [&](QJsonArray arr) -> ModDetails {
if (!arr.at(0).isObject()) {
return {};
}
ModDetails details;
auto firstObj = arr.at(0).toObject();
details.mod_id = firstObj.value("modid").toString();
auto name = firstObj.value("name").toString();
// NOTE: ignore stupid example mods copies where the author didn't even bother to change the name
if (name != "Example Mod") {
details.name = name;
}
details.version = firstObj.value("version").toString();
auto homeurl = firstObj.value("url").toString().trimmed();
if (!homeurl.isEmpty()) {
// fix up url.
if (!homeurl.startsWith("http://") && !homeurl.startsWith("https://") && !homeurl.startsWith("ftp://")) {
homeurl.prepend("http://");
}
}
details.homeurl = homeurl;
details.description = firstObj.value("description").toString();
QJsonArray authors = firstObj.value("authorList").toArray();
if (authors.size() == 0) {
// FIXME: what is the format of this? is there any?
authors = firstObj.value("authors").toArray();
}
if (firstObj.contains("logoFile")) {
details.icon_file = firstObj.value("logoFile").toString();
}
for (auto author : authors) {
details.authors.append(author.toString());
}
return details;
};
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError);
// this is the very old format that had just the array
if (jsonDoc.isArray()) {
return getInfoFromArray(jsonDoc.array());
} else if (jsonDoc.isObject()) {
auto val = jsonDoc.object().value("modinfoversion");
if (val.isUndefined()) {
val = jsonDoc.object().value("modListVersion");
}
int version = Json::ensureInteger(val, -1);
// Some mods set the number with "", so it's a String instead
if (version < 0)
version = Json::ensureString(val, "").toInt();
if (version != 2) {
qWarning() << QString(R"(The value of 'modListVersion' is "%1" (expected "2")! The file may be corrupted.)").arg(version);
qWarning() << "The contents of 'mcmod.info' are as follows:";
qWarning() << contents;
}
auto arrVal = jsonDoc.object().value("modlist");
if (arrVal.isUndefined()) {
arrVal = jsonDoc.object().value("modList");
}
if (arrVal.isArray()) {
return getInfoFromArray(arrVal.toArray());
}
}
return {};
}
// https://github.com/MinecraftForge/Documentation/blob/5ab4ba6cf9abc0ac4c0abd96ad187461aefd72af/docs/gettingstarted/structuring.md
ModDetails ReadMCModTOML(QByteArray contents)
{
ModDetails details;
toml::table tomlData;
#if TOML_EXCEPTIONS
try {
tomlData = toml::parse(contents.toStdString());
} catch ([[maybe_unused]] const toml::parse_error& err) {
return {};
}
#else
toml::parse_result result = toml::parse(contents.toStdString());
if (!result) {
return {};
}
tomlData = result.table();
#endif
// array defined by [[mods]]
auto tomlModsArr = tomlData["mods"].as_array();
if (!tomlModsArr) {
qWarning() << "Corrupted mods.toml? Couldn't find [[mods]] array!";
return {};
}
// we only really care about the first element, since multiple mods in one file is not supported by us at the moment
auto tomlModsTable0 = tomlModsArr->get(0);
if (!tomlModsTable0) {
qWarning() << "Corrupted mods.toml? [[mods]] didn't have an element at index 0!";
return {};
}
auto modsTable = tomlModsTable0->as_table();
if (!modsTable) {
qWarning() << "Corrupted mods.toml? [[mods]] was not a table!";
return {};
}
// mandatory properties - always in [[mods]]
if (auto modIdDatum = (*modsTable)["modId"].as_string()) {
details.mod_id = QString::fromStdString(modIdDatum->get());
}
if (auto versionDatum = (*modsTable)["version"].as_string()) {
details.version = QString::fromStdString(versionDatum->get());
}
if (auto displayNameDatum = (*modsTable)["displayName"].as_string()) {
details.name = QString::fromStdString(displayNameDatum->get());
}
if (auto descriptionDatum = (*modsTable)["description"].as_string()) {
details.description = QString::fromStdString(descriptionDatum->get());
}
// optional properties - can be in the root table or [[mods]]
QString authors = "";
if (auto authorsDatum = tomlData["authors"].as_string()) {
authors = QString::fromStdString(authorsDatum->get());
} else if (auto authorsDatumMods = (*modsTable)["authors"].as_string()) {
authors = QString::fromStdString(authorsDatumMods->get());
}
if (!authors.isEmpty()) {
details.authors.append(authors);
}
QString homeurl = "";
if (auto homeurlDatum = tomlData["displayURL"].as_string()) {
homeurl = QString::fromStdString(homeurlDatum->get());
} else if (auto homeurlDatumMods = (*modsTable)["displayURL"].as_string()) {
homeurl = QString::fromStdString(homeurlDatumMods->get());
}
// fix up url.
if (!homeurl.isEmpty() && !homeurl.startsWith("http://") && !homeurl.startsWith("https://") && !homeurl.startsWith("ftp://")) {
homeurl.prepend("http://");
}
details.homeurl = homeurl;
QString issueTrackerURL = "";
if (auto issueTrackerURLDatum = tomlData["issueTrackerURL"].as_string()) {
issueTrackerURL = QString::fromStdString(issueTrackerURLDatum->get());
} else if (auto issueTrackerURLDatumMods = (*modsTable)["issueTrackerURL"].as_string()) {
issueTrackerURL = QString::fromStdString(issueTrackerURLDatumMods->get());
}
details.issue_tracker = issueTrackerURL;
QString license = "";
if (auto licenseDatum = tomlData["license"].as_string()) {
license = QString::fromStdString(licenseDatum->get());
} else if (auto licenseDatumMods = (*modsTable)["license"].as_string()) {
license = QString::fromStdString(licenseDatumMods->get());
}
if (!license.isEmpty())
details.licenses.append(ModLicense(license));
QString logoFile = "";
if (auto logoFileDatum = tomlData["logoFile"].as_string()) {
logoFile = QString::fromStdString(logoFileDatum->get());
} else if (auto logoFileDatumMods = (*modsTable)["logoFile"].as_string()) {
logoFile = QString::fromStdString(logoFileDatumMods->get());
}
details.icon_file = logoFile;
return details;
}
// https://fabricmc.net/wiki/documentation:fabric_mod_json
ModDetails ReadFabricModInfo(QByteArray contents)
{
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError);
auto object = jsonDoc.object();
auto schemaVersion = object.contains("schemaVersion") ? object.value("schemaVersion").toInt(0) : 0;
ModDetails details;
details.mod_id = object.value("id").toString();
details.version = object.value("version").toString();
details.name = object.contains("name") ? object.value("name").toString() : details.mod_id;
details.description = object.value("description").toString();
if (schemaVersion >= 1) {
QJsonArray authors = object.value("authors").toArray();
for (auto author : authors) {
if (author.isObject()) {
details.authors.append(author.toObject().value("name").toString());
} else {
details.authors.append(author.toString());
}
}
if (object.contains("contact")) {
QJsonObject contact = object.value("contact").toObject();
if (contact.contains("homepage")) {
details.homeurl = contact.value("homepage").toString();
}
if (contact.contains("issues")) {
details.issue_tracker = contact.value("issues").toString();
}
}
if (object.contains("license")) {
auto license = object.value("license");
if (license.isArray()) {
for (auto l : license.toArray()) {
if (l.isString()) {
details.licenses.append(ModLicense(l.toString()));
} else if (l.isObject()) {
auto obj = l.toObject();
details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(),
obj.value("url").toString(), obj.value("description").toString()));
}
}
} else if (license.isString()) {
details.licenses.append(ModLicense(license.toString()));
} else if (license.isObject()) {
auto obj = license.toObject();
details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(), obj.value("url").toString(),
obj.value("description").toString()));
}
}
if (object.contains("icon")) {
auto icon = object.value("icon");
if (icon.isObject()) {
auto obj = icon.toObject();
// take the largest icon
int largest = 0;
for (auto key : obj.keys()) {
auto size = key.split('x').first().toInt();
if (size > largest) {
largest = size;
}
}
if (largest > 0) {
auto key = QString::number(largest) + "x" + QString::number(largest);
details.icon_file = obj.value(key).toString();
} else { // parsing the sizes failed
// take the first
for (auto i : obj) {
details.icon_file = i.toString();
break;
}
}
} else if (icon.isString()) {
details.icon_file = icon.toString();
}
}
}
return details;
}
// https://github.com/QuiltMC/rfcs/blob/master/specification/0002-quilt.mod.json.md
ModDetails ReadQuiltModInfo(QByteArray contents)
{
ModDetails details;
try {
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError);
auto object = Json::requireObject(jsonDoc, "quilt.mod.json");
auto schemaVersion = Json::ensureInteger(object.value("schema_version"), 0, "Quilt schema_version");
// https://github.com/QuiltMC/rfcs/blob/be6ba280d785395fefa90a43db48e5bfc1d15eb4/specification/0002-quilt.mod.json.md
if (schemaVersion == 1) {
auto modInfo = Json::requireObject(object.value("quilt_loader"), "Quilt mod info");
details.mod_id = Json::requireString(modInfo.value("id"), "Mod ID");
details.version = Json::requireString(modInfo.value("version"), "Mod version");
auto modMetadata = Json::ensureObject(modInfo.value("metadata"));
details.name = Json::ensureString(modMetadata.value("name"), details.mod_id);
details.description = Json::ensureString(modMetadata.value("description"));
auto modContributors = Json::ensureObject(modMetadata.value("contributors"));
// We don't really care about the role of a contributor here
details.authors += modContributors.keys();
auto modContact = Json::ensureObject(modMetadata.value("contact"));
if (modContact.contains("homepage")) {
details.homeurl = Json::requireString(modContact.value("homepage"));
}
if (modContact.contains("issues")) {
details.issue_tracker = Json::requireString(modContact.value("issues"));
}
if (modMetadata.contains("license")) {
auto license = modMetadata.value("license");
if (license.isArray()) {
for (auto l : license.toArray()) {
if (l.isString()) {
details.licenses.append(ModLicense(l.toString()));
} else if (l.isObject()) {
auto obj = l.toObject();
details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(),
obj.value("url").toString(), obj.value("description").toString()));
}
}
} else if (license.isString()) {
details.licenses.append(ModLicense(license.toString()));
} else if (license.isObject()) {
auto obj = license.toObject();
details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(),
obj.value("url").toString(), obj.value("description").toString()));
}
}
if (modMetadata.contains("icon")) {
auto icon = modMetadata.value("icon");
if (icon.isObject()) {
auto obj = icon.toObject();
// take the largest icon
int largest = 0;
for (auto key : obj.keys()) {
auto size = key.split('x').first().toInt();
if (size > largest) {
largest = size;
}
}
if (largest > 0) {
auto key = QString::number(largest) + "x" + QString::number(largest);
details.icon_file = obj.value(key).toString();
} else { // parsing the sizes failed
// take the first
for (auto i : obj) {
details.icon_file = i.toString();
break;
}
}
} else if (icon.isString()) {
details.icon_file = icon.toString();
}
}
}
} catch (const Exception& e) {
qWarning() << "Unable to parse mod info:" << e.cause();
}
return details;
}
ModDetails ReadForgeInfo(QByteArray contents)
{
ModDetails details;
// Read the data
details.name = "Minecraft Forge";
details.mod_id = "Forge";
details.homeurl = "http://www.minecraftforge.net/forum/";
INIFile ini;
if (!ini.loadFile(contents))
return details;
QString major = ini.get("forge.major.number", "0").toString();
QString minor = ini.get("forge.minor.number", "0").toString();
QString revision = ini.get("forge.revision.number", "0").toString();
QString build = ini.get("forge.build.number", "0").toString();
details.version = major + "." + minor + "." + revision + "." + build;
return details;
}
ModDetails ReadLiteModInfo(QByteArray contents)
{
ModDetails details;
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(contents, &jsonError);
auto object = jsonDoc.object();
if (object.contains("name")) {
details.mod_id = details.name = object.value("name").toString();
}
if (object.contains("version")) {
details.version = object.value("version").toString("");
} else {
details.version = object.value("revision").toString("");
}
details.mcversion = object.value("mcversion").toString();
auto author = object.value("author").toString();
if (!author.isEmpty()) {
details.authors.append(author);
}
details.description = object.value("description").toString();
details.homeurl = object.value("url").toString();
return details;
}
// https://git.sleeping.town/unascribed/NilLoader/src/commit/d7fc87b255fc31019ff90f80d45894927fac6efc/src/main/java/nilloader/api/NilMetadata.java#L64
ModDetails ReadNilModInfo(QByteArray contents, QString fname)
{
ModDetails details;
QDCSS cssData = QDCSS(contents);
auto name = cssData.get("@nilmod.name");
auto desc = cssData.get("@nilmod.description");
auto authors = cssData.get("@nilmod.authors");
if (name->has_value()) {
details.name = name->value();
}
if (desc->has_value()) {
details.description = desc->value();
}
if (authors->has_value()) {
details.authors.append(authors->value());
}
details.version = cssData.get("@nilmod.version")->value_or("?");
details.mod_id = fname.remove(".nilmod.css");
return details;
}
bool process(Mod& mod, ProcessingLevel level)
{
switch (mod.type()) {
case ResourceType::FOLDER:
return processFolder(mod, level);
case ResourceType::ZIPFILE:
return processZIP(mod, level);
case ResourceType::LITEMOD:
return processLitemod(mod);
default:
qWarning() << "Invalid type for mod parse task!";
return false;
}
}
bool processZIP(Mod& mod, [[maybe_unused]] ProcessingLevel level)
{
ModDetails details;
QuaZip zip(mod.fileinfo().filePath());
if (!zip.open(QuaZip::mdUnzip))
return false;
QuaZipFile file(&zip);
if (zip.setCurrentFile("META-INF/mods.toml") || zip.setCurrentFile("META-INF/neoforge.mods.toml")) {
if (!file.open(QIODevice::ReadOnly)) {
zip.close();
return false;
}
details = ReadMCModTOML(file.readAll());
file.close();
// to replace ${file.jarVersion} with the actual version, as needed
if (details.version == "${file.jarVersion}") {
if (zip.setCurrentFile("META-INF/MANIFEST.MF")) {
if (!file.open(QIODevice::ReadOnly)) {
zip.close();
return false;
}
// quick and dirty line-by-line parser
auto manifestLines = QString(file.readAll()).split(newlineRegex);
QString manifestVersion = "";
for (auto& line : manifestLines) {
if (line.startsWith("Implementation-Version: ", Qt::CaseInsensitive)) {
manifestVersion = line.remove("Implementation-Version: ", Qt::CaseInsensitive);
break;
}
}
// some mods use ${projectversion} in their build.gradle, causing this mess to show up in MANIFEST.MF
// also keep with forge's behavior of setting the version to "NONE" if none is found
if (manifestVersion.contains("task ':jar' property 'archiveVersion'") || manifestVersion == "") {
manifestVersion = "NONE";
}
details.version = manifestVersion;
file.close();
}
}
zip.close();
mod.setDetails(details);
return true;
} else if (zip.setCurrentFile("mcmod.info")) {
if (!file.open(QIODevice::ReadOnly)) {
zip.close();
return false;
}
details = ReadMCModInfo(file.readAll());
file.close();
zip.close();
mod.setDetails(details);
return true;
} else if (zip.setCurrentFile("quilt.mod.json")) {
if (!file.open(QIODevice::ReadOnly)) {
zip.close();
return false;
}
details = ReadQuiltModInfo(file.readAll());
file.close();
zip.close();
mod.setDetails(details);
return true;
} else if (zip.setCurrentFile("fabric.mod.json")) {
if (!file.open(QIODevice::ReadOnly)) {
zip.close();
return false;
}
details = ReadFabricModInfo(file.readAll());
file.close();
zip.close();
mod.setDetails(details);
return true;
} else if (zip.setCurrentFile("forgeversion.properties")) {
if (!file.open(QIODevice::ReadOnly)) {
zip.close();
return false;
}
details = ReadForgeInfo(file.readAll());
file.close();
zip.close();
mod.setDetails(details);
return true;
} else if (zip.setCurrentFile("META-INF/nil/mappings.json")) {
// nilloader uses the filename of the metadata file for the modid, so we can't know the exact filename
// thankfully, there is a good file to use as a canary so we don't look for nil meta all the time
QString foundNilMeta;
for (auto& fname : zip.getFileNameList()) {
// nilmods can shade nilloader to be able to run as a standalone agent - which includes nilloader's own meta file
if (fname.endsWith(".nilmod.css") && fname != "nilloader.nilmod.css") {
foundNilMeta = fname;
break;
}
}
if (zip.setCurrentFile(foundNilMeta)) {
if (!file.open(QIODevice::ReadOnly)) {
zip.close();
return false;
}
details = ReadNilModInfo(file.readAll(), foundNilMeta);
file.close();
zip.close();
mod.setDetails(details);
return true;
}
}
zip.close();
return false; // no valid mod found in archive
}
bool processFolder(Mod& mod, [[maybe_unused]] ProcessingLevel level)
{
ModDetails details;
QFileInfo mcmod_info(FS::PathCombine(mod.fileinfo().filePath(), "mcmod.info"));
if (mcmod_info.exists() && mcmod_info.isFile()) {
QFile mcmod(mcmod_info.filePath());
if (!mcmod.open(QIODevice::ReadOnly))
return false;
auto data = mcmod.readAll();
if (data.isEmpty() || data.isNull())
return false;
details = ReadMCModInfo(data);
mod.setDetails(details);
return true;
}
return false; // no valid mcmod.info file found
}
bool processLitemod(Mod& mod, [[maybe_unused]] ProcessingLevel level)
{
ModDetails details;
QuaZip zip(mod.fileinfo().filePath());
if (!zip.open(QuaZip::mdUnzip))
return false;
QuaZipFile file(&zip);
if (zip.setCurrentFile("litemod.json")) {
if (!file.open(QIODevice::ReadOnly)) {
zip.close();
return false;
}
details = ReadLiteModInfo(file.readAll());
file.close();
mod.setDetails(details);
return true;
}
zip.close();
return false; // no valid litemod.json found in archive
}
/** Checks whether a file is valid as a mod or not. */
bool validate(QFileInfo file)
{
Mod mod{ file };
return ModUtils::process(mod, ProcessingLevel::BasicInfoOnly) && mod.valid();
}
bool processIconPNG(const Mod& mod, QByteArray&& raw_data, QPixmap* pixmap)
{
auto img = QImage::fromData(raw_data);
if (!img.isNull()) {
*pixmap = mod.setIcon(img);
} else {
qWarning() << "Failed to parse mod logo:" << mod.iconPath() << "from" << mod.name();
return false;
}
return true;
}
bool loadIconFile(const Mod& mod, QPixmap* pixmap)
{
if (mod.iconPath().isEmpty()) {
qWarning() << "No Iconfile set, be sure to parse the mod first";
return false;
}
auto png_invalid = [&mod](const QString& reason) {
qWarning() << "Mod at" << mod.fileinfo().filePath() << "does not have a valid icon:" << reason;
return false;
};
switch (mod.type()) {
case ResourceType::FOLDER: {
QFileInfo icon_info(FS::PathCombine(mod.fileinfo().filePath(), mod.iconPath()));
if (icon_info.exists() && icon_info.isFile()) {
QFile icon(icon_info.filePath());
if (!icon.open(QIODevice::ReadOnly)) {
return png_invalid("failed to open file " + icon_info.filePath());
}
auto data = icon.readAll();
bool icon_result = ModUtils::processIconPNG(mod, std::move(data), pixmap);
icon.close();
if (!icon_result) {
return png_invalid("invalid png image"); // icon invalid
}
return true;
}
return png_invalid("file '" + icon_info.filePath() + "' does not exists or is not a file");
}
case ResourceType::ZIPFILE: {
QuaZip zip(mod.fileinfo().filePath());
if (!zip.open(QuaZip::mdUnzip))
return png_invalid("failed to open '" + mod.fileinfo().filePath() + "' as a zip archive");
QuaZipFile file(&zip);
if (zip.setCurrentFile(mod.iconPath())) {
if (!file.open(QIODevice::ReadOnly)) {
qCritical() << "Failed to open file in zip.";
zip.close();
return png_invalid("Failed to open '" + mod.iconPath() + "' in zip archive");
}
auto data = file.readAll();
bool icon_result = ModUtils::processIconPNG(mod, std::move(data), pixmap);
file.close();
if (!icon_result) {
return png_invalid("invalid png image"); // icon png invalid
}
return true;
}
return png_invalid("Failed to set '" + mod.iconPath() +
"' as current file in zip archive"); // could not set icon as current file.
}
case ResourceType::LITEMOD: {
return png_invalid("litemods do not have icons"); // can lightmods even have icons?
}
default:
return png_invalid("Invalid type for mod, can not load icon.");
}
}
} // namespace ModUtils
LocalModParseTask::LocalModParseTask(int token, ResourceType type, const QFileInfo& modFile)
: Task(false), m_token(token), m_type(type), m_modFile(modFile), m_result(new Result())
{}
bool LocalModParseTask::abort()
{
m_aborted.store(true);
return true;
}
void LocalModParseTask::executeTask()
{
Mod mod{ m_modFile };
ModUtils::process(mod, ModUtils::ProcessingLevel::Full);
m_result->details = mod.details();
if (m_aborted)
emitAborted();
else
emitSucceeded();
}
| 1 | 0.867223 | 1 | 0.867223 | game-dev | MEDIA | 0.325658 | game-dev | 0.925152 | 1 | 0.925152 |
haqu/tiny-wings | 3,305 | tiny-wings/libs/Box2D/Collision/Shapes/b2EdgeShape.cpp | /*
* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Collision/Shapes/b2EdgeShape.h>
#include <new>
using namespace std;
void b2EdgeShape::Set(const b2Vec2& v1, const b2Vec2& v2)
{
m_vertex1 = v1;
m_vertex2 = v2;
m_hasVertex0 = false;
m_hasVertex3 = false;
}
b2Shape* b2EdgeShape::Clone(b2BlockAllocator* allocator) const
{
void* mem = allocator->Allocate(sizeof(b2EdgeShape));
b2EdgeShape* clone = new (mem) b2EdgeShape;
*clone = *this;
return clone;
}
int32 b2EdgeShape::GetChildCount() const
{
return 1;
}
bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const
{
B2_NOT_USED(xf);
B2_NOT_USED(p);
return false;
}
// p = p1 + t * d
// v = v1 + s * e
// p1 + t * d = v1 + s * e
// s * e - t * d = p1 - v1
bool b2EdgeShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
const b2Transform& xf, int32 childIndex) const
{
B2_NOT_USED(childIndex);
// Put the ray into the edge's frame of reference.
b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p);
b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p);
b2Vec2 d = p2 - p1;
b2Vec2 v1 = m_vertex1;
b2Vec2 v2 = m_vertex2;
b2Vec2 e = v2 - v1;
b2Vec2 normal(e.y, -e.x);
normal.Normalize();
// q = p1 + t * d
// dot(normal, q - v1) = 0
// dot(normal, p1 - v1) + t * dot(normal, d) = 0
float32 numerator = b2Dot(normal, v1 - p1);
float32 denominator = b2Dot(normal, d);
if (denominator == 0.0f)
{
return false;
}
float32 t = numerator / denominator;
if (t < 0.0f || 1.0f < t)
{
return false;
}
b2Vec2 q = p1 + t * d;
// q = v1 + s * r
// s = dot(q - v1, r) / dot(r, r)
b2Vec2 r = v2 - v1;
float32 rr = b2Dot(r, r);
if (rr == 0.0f)
{
return false;
}
float32 s = b2Dot(q - v1, r) / rr;
if (s < 0.0f || 1.0f < s)
{
return false;
}
output->fraction = t;
if (numerator > 0.0f)
{
output->normal = -normal;
}
else
{
output->normal = normal;
}
return true;
}
void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const
{
B2_NOT_USED(childIndex);
b2Vec2 v1 = b2Mul(xf, m_vertex1);
b2Vec2 v2 = b2Mul(xf, m_vertex2);
b2Vec2 lower = b2Min(v1, v2);
b2Vec2 upper = b2Max(v1, v2);
b2Vec2 r(m_radius, m_radius);
aabb->lowerBound = lower - r;
aabb->upperBound = upper + r;
}
void b2EdgeShape::ComputeMass(b2MassData* massData, float32 density) const
{
B2_NOT_USED(density);
massData->mass = 0.0f;
massData->center = 0.5f * (m_vertex1 + m_vertex2);
massData->I = 0.0f;
}
| 1 | 0.953594 | 1 | 0.953594 | game-dev | MEDIA | 0.951971 | game-dev | 0.97206 | 1 | 0.97206 |
pedroksl/AdvancedAE | 7,312 | src/main/java/net/pedroksl/advanced_ae/mixins/cpu/MixinCraftingCPUMenu.java | package net.pedroksl.advanced_ae.mixins.cpu;
import java.util.function.Consumer;
import com.google.common.collect.ImmutableList;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.MenuType;
import net.pedroksl.advanced_ae.common.cluster.AdvCraftingCPU;
import net.pedroksl.advanced_ae.common.entities.AdvCraftingBlockEntity;
import net.pedroksl.advanced_ae.common.logic.AdvCraftingCPULogic;
import appeng.api.config.CpuSelectionMode;
import appeng.api.networking.crafting.ICraftingCPU;
import appeng.api.stacks.AEKey;
import appeng.api.stacks.KeyCounter;
import appeng.core.network.clientbound.CraftingStatusPacket;
import appeng.me.cluster.implementations.CraftingCPUCluster;
import appeng.menu.AEBaseMenu;
import appeng.menu.me.common.IncrementalUpdateHelper;
import appeng.menu.me.crafting.CraftingCPUMenu;
import appeng.menu.me.crafting.CraftingStatus;
import appeng.menu.me.crafting.CraftingStatusEntry;
@Mixin(value = CraftingCPUMenu.class, remap = false)
public class MixinCraftingCPUMenu extends AEBaseMenu {
@Final
@Shadow
private IncrementalUpdateHelper incrementalUpdateHelper;
@Shadow
private boolean cachedSuspend;
@Shadow
private CraftingCPUCluster cpu;
@Unique
private AdvCraftingCPU advancedAE$advCpu = null;
@Final
@Shadow
private Consumer<AEKey> cpuChangeListener;
@Shadow
public CpuSelectionMode schedulingMode;
@Shadow
public boolean cantStoreItems;
@Shadow
protected void setCPU(ICraftingCPU c) {}
@Inject(
method = "<init>(Lnet/minecraft/world/inventory/MenuType;ILnet/minecraft/world/entity/player/Inventory;"
+ "Ljava/lang/Object;)V",
at = @At("TAIL"))
private void onInit(MenuType<?> menuType, int id, Inventory ip, Object te, CallbackInfo ci) {
if (te instanceof AdvCraftingBlockEntity advEntity) {
var cluster = advEntity.getCluster();
if (cluster == null) return;
var active = cluster.getActiveCPUs();
if (!active.isEmpty()) {
this.setCPU(active.getFirst());
} else {
this.setCPU(cluster.getRemainingCapacityCPU());
}
}
}
@Inject(method = "setCPU(Lappeng/api/networking/crafting/ICraftingCPU;)V", at = @At("HEAD"), cancellable = true)
private void onSetCPU(ICraftingCPU c, CallbackInfo ci) {
if (this.advancedAE$advCpu != null) {
this.advancedAE$advCpu.craftingLogic.removeListener(cpuChangeListener);
}
if (c instanceof AdvCraftingCPU advCPU) {
// Clear old cpu listener if it's still valid
if (this.cpu != null) {
this.cpu.craftingLogic.removeListener(cpuChangeListener);
}
// Clear helper inside the if statement because it will be cleared normally otherwise
incrementalUpdateHelper.reset();
cachedSuspend = false;
this.advancedAE$advCpu = advCPU;
// Initially send all items as a full-update to the client when the CPU changes
var allItems = new KeyCounter();
this.advancedAE$advCpu.craftingLogic.getAllItems(allItems);
for (var entry : allItems) {
incrementalUpdateHelper.addChange(entry.getKey());
}
this.advancedAE$advCpu.craftingLogic.addListener(cpuChangeListener);
ci.cancel();
} else {
this.advancedAE$advCpu = null;
}
}
@Inject(method = "cancelCrafting", at = @At("TAIL"))
public void onCancelCrafting(CallbackInfo ci) {
if (!isClientSide()) {
if (this.advancedAE$advCpu != null) {
this.advancedAE$advCpu.cancelJob();
}
}
}
@Inject(method = "toggleScheduling", at = @At("TAIL"))
public void onToggleScheduling(CallbackInfo ci) {
if (!isClientSide()) {
if (this.advancedAE$advCpu != null) {
var logic = this.advancedAE$advCpu.craftingLogic;
logic.setJobSuspended(!logic.isJobSuspended());
}
}
}
@Inject(method = "removed", at = @At("TAIL"))
public void onRemoved(Player player, CallbackInfo ci) {
if (this.advancedAE$advCpu != null) {
this.advancedAE$advCpu.craftingLogic.removeListener(cpuChangeListener);
}
}
@Inject(method = "broadcastChanges", at = @At(value = "HEAD"), remap = true)
public void onBroadcastChanges(CallbackInfo ci) {
if (isServerSide() && this.advancedAE$advCpu != null) {
this.schedulingMode = this.advancedAE$advCpu.getSelectionMode();
this.cantStoreItems = this.advancedAE$advCpu.craftingLogic.isCantStoreItems();
if (this.incrementalUpdateHelper.hasChanges()
|| this.cachedSuspend != this.advancedAE$advCpu.craftingLogic.isJobSuspended()) {
CraftingStatus status =
advancedAE$create(this.incrementalUpdateHelper, this.advancedAE$advCpu.craftingLogic);
this.incrementalUpdateHelper.commitChanges();
this.cachedSuspend = status.isSuspended();
sendPacketToClient(new CraftingStatusPacket(containerId, status));
}
}
}
@Unique
private static CraftingStatus advancedAE$create(IncrementalUpdateHelper changes, AdvCraftingCPULogic logic) {
boolean full = changes.isFullUpdate();
ImmutableList.Builder<CraftingStatusEntry> newEntries = ImmutableList.builder();
for (var what : changes) {
long storedCount = logic.getStored(what);
long activeCount = logic.getWaitingFor(what);
long pendingCount = logic.getPendingOutputs(what);
var sentStack = what;
if (!full && changes.getSerial(what) != null) {
// The item was already sent to the client, so we can skip the item stack
sentStack = null;
}
var entry = new CraftingStatusEntry(
changes.getOrAssignSerial(what), sentStack, storedCount, activeCount, pendingCount);
newEntries.add(entry);
if (entry.isDeleted()) {
changes.removeSerial(what);
}
}
long elapsedTime = logic.getElapsedTimeTracker().getElapsedTime();
long remainingItems = logic.getElapsedTimeTracker().getRemainingItemCount();
long startItems = logic.getElapsedTimeTracker().getStartItemCount();
boolean suspended = logic.isJobSuspended();
return new CraftingStatus(full, elapsedTime, remainingItems, startItems, newEntries.build(), suspended);
}
public MixinCraftingCPUMenu(MenuType<?> menuType, int id, Inventory playerInventory, Object host) {
super(menuType, id, playerInventory, host);
}
}
| 1 | 0.924581 | 1 | 0.924581 | game-dev | MEDIA | 0.936316 | game-dev | 0.977147 | 1 | 0.977147 |
lua9520/source-engine-2018-hl2_src | 4,024 | game/client/c_colorcorrection.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Color correction entity with simple radial falloff
//
// $NoKeywords: $
//===========================================================================//
#include "cbase.h"
#include "filesystem.h"
#include "cdll_client_int.h"
#include "colorcorrectionmgr.h"
#include "materialsystem/MaterialSystemUtil.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
static ConVar mat_colcorrection_disableentities( "mat_colcorrection_disableentities", "0", FCVAR_NONE, "Disable map color-correction entities" );
//------------------------------------------------------------------------------
// Purpose : Color correction entity with radial falloff
//------------------------------------------------------------------------------
class C_ColorCorrection : public C_BaseEntity
{
public:
DECLARE_CLASS( C_ColorCorrection, C_BaseEntity );
DECLARE_CLIENTCLASS();
C_ColorCorrection();
virtual ~C_ColorCorrection();
void OnDataChanged(DataUpdateType_t updateType);
bool ShouldDraw();
void ClientThink();
private:
Vector m_vecOrigin;
float m_minFalloff;
float m_maxFalloff;
float m_flCurWeight;
char m_netLookupFilename[MAX_PATH];
bool m_bEnabled;
ClientCCHandle_t m_CCHandle;
};
IMPLEMENT_CLIENTCLASS_DT(C_ColorCorrection, DT_ColorCorrection, CColorCorrection)
RecvPropVector( RECVINFO(m_vecOrigin) ),
RecvPropFloat( RECVINFO(m_minFalloff) ),
RecvPropFloat( RECVINFO(m_maxFalloff) ),
RecvPropFloat( RECVINFO(m_flCurWeight) ),
RecvPropString( RECVINFO(m_netLookupFilename) ),
RecvPropBool( RECVINFO(m_bEnabled) ),
END_RECV_TABLE()
//------------------------------------------------------------------------------
// Constructor, destructor
//------------------------------------------------------------------------------
C_ColorCorrection::C_ColorCorrection()
{
m_CCHandle = INVALID_CLIENT_CCHANDLE;
}
C_ColorCorrection::~C_ColorCorrection()
{
g_pColorCorrectionMgr->RemoveColorCorrection( m_CCHandle );
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
void C_ColorCorrection::OnDataChanged(DataUpdateType_t updateType)
{
BaseClass::OnDataChanged( updateType );
if ( updateType == DATA_UPDATE_CREATED )
{
if ( m_CCHandle == INVALID_CLIENT_CCHANDLE )
{
char filename[MAX_PATH];
Q_strncpy( filename, m_netLookupFilename, MAX_PATH );
m_CCHandle = g_pColorCorrectionMgr->AddColorCorrection( filename );
SetNextClientThink( ( m_CCHandle != INVALID_CLIENT_CCHANDLE ) ? CLIENT_THINK_ALWAYS : CLIENT_THINK_NEVER );
}
}
}
//------------------------------------------------------------------------------
// We don't draw...
//------------------------------------------------------------------------------
bool C_ColorCorrection::ShouldDraw()
{
return false;
}
void C_ColorCorrection::ClientThink()
{
if ( m_CCHandle == INVALID_CLIENT_CCHANDLE )
return;
if ( mat_colcorrection_disableentities.GetInt() )
{
// Allow the colorcorrectionui panel (or user) to turn off color-correction entities
g_pColorCorrectionMgr->SetColorCorrectionWeight( m_CCHandle, 0.0f );
return;
}
if( !m_bEnabled && m_flCurWeight == 0.0f )
{
g_pColorCorrectionMgr->SetColorCorrectionWeight( m_CCHandle, 0.0f );
return;
}
C_BaseEntity *pPlayer = C_BasePlayer::GetLocalPlayer();
if( !pPlayer )
return;
Vector playerOrigin = pPlayer->GetAbsOrigin();
float weight = 0;
if ( ( m_minFalloff != -1 ) && ( m_maxFalloff != -1 ) && m_minFalloff != m_maxFalloff )
{
float dist = (playerOrigin - m_vecOrigin).Length();
weight = (dist-m_minFalloff) / (m_maxFalloff-m_minFalloff);
if ( weight<0.0f ) weight = 0.0f;
if ( weight>1.0f ) weight = 1.0f;
}
g_pColorCorrectionMgr->SetColorCorrectionWeight( m_CCHandle, m_flCurWeight * ( 1.0 - weight ) );
BaseClass::ClientThink();
}
| 1 | 0.989729 | 1 | 0.989729 | game-dev | MEDIA | 0.727291 | game-dev | 0.977436 | 1 | 0.977436 |
folgerwang/UnrealEngine | 3,111 | Engine/Source/Runtime/Engine/Private/Camera/CameraModifier.cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "Camera/CameraModifier.h"
#include "Camera/PlayerCameraManager.h"
//////////////////////////////////////////////////////////////////////////
DEFINE_LOG_CATEGORY_STATIC(LogCamera, Log, All);
//////////////////////////////////////////////////////////////////////////
// UCameraModifier
UCameraModifier::UCameraModifier(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
Priority = 127;
}
bool UCameraModifier::ModifyCamera(float DeltaTime, FMinimalViewInfo& InOutPOV)
{
// Update the alpha
UpdateAlpha(DeltaTime);
// let BP do what it wants
BlueprintModifyCamera(DeltaTime, InOutPOV.Location, InOutPOV.Rotation, InOutPOV.FOV, InOutPOV.Location, InOutPOV.Rotation, InOutPOV.FOV);
if (CameraOwner)
{
// note: pushing these through the cached PP blend system in the camera to get
// proper layered blending, rather than letting subsequent mods stomp over each other in the
// InOutPOV struct.
float PPBlendWeight = 0.f;
FPostProcessSettings PPSettings;
BlueprintModifyPostProcess(DeltaTime, PPBlendWeight, PPSettings);
if (PPBlendWeight > 0.f)
{
CameraOwner->AddCachedPPBlend(PPSettings, PPBlendWeight);
}
}
// If pending disable and fully alpha'd out, truly disable this modifier
if (bPendingDisable && (Alpha <= 0.f))
{
DisableModifier(true);
}
// allow subsequent modifiers to update
return false;
}
float UCameraModifier::GetTargetAlpha()
{
return bPendingDisable ? 0.0f : 1.f;
}
void UCameraModifier::UpdateAlpha(float DeltaTime)
{
float const TargetAlpha = GetTargetAlpha();
float const BlendTime = (TargetAlpha == 0.f) ? AlphaOutTime : AlphaInTime;
// interpolate!
if (BlendTime <= 0.f)
{
// no blendtime means no blending, just go directly to target alpha
Alpha = TargetAlpha;
}
else if (Alpha > TargetAlpha)
{
// interpolate downward to target, while protecting against overshooting
Alpha = FMath::Max<float>(Alpha - DeltaTime / BlendTime, TargetAlpha);
}
else
{
// interpolate upward to target, while protecting against overshooting
Alpha = FMath::Min<float>(Alpha + DeltaTime / BlendTime, TargetAlpha);
}
}
bool UCameraModifier::IsDisabled() const
{
return bDisabled;
}
AActor* UCameraModifier::GetViewTarget() const
{
return CameraOwner ? CameraOwner->GetViewTarget() : nullptr;
}
void UCameraModifier::AddedToCamera( APlayerCameraManager* Camera )
{
CameraOwner = Camera;
}
UWorld* UCameraModifier::GetWorld() const
{
return CameraOwner ? CameraOwner->GetWorld() : nullptr;
}
void UCameraModifier::DisableModifier(bool bImmediate)
{
if (bImmediate)
{
bDisabled = true;
bPendingDisable = false;
}
else if (!bDisabled)
{
bPendingDisable = true;
}
}
void UCameraModifier::EnableModifier()
{
bDisabled = false;
bPendingDisable = false;
}
void UCameraModifier::ToggleModifier()
{
if( bDisabled )
{
EnableModifier();
}
else
{
DisableModifier();
}
}
bool UCameraModifier::ProcessViewRotation( AActor* ViewTarget, float DeltaTime, FRotator& OutViewRotation, FRotator& OutDeltaRot)
{
return false;
}
| 1 | 0.880052 | 1 | 0.880052 | game-dev | MEDIA | 0.657166 | game-dev | 0.948977 | 1 | 0.948977 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.