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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Dreamtowards/Ethertia | 27,152 | lib/_misc/bullet3/src/BulletCollision/CollisionShapes/btHeightfieldTerrainShape.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 "btHeightfieldTerrainShape.h"
#include "LinearMath/btTransformUtil.h"
btHeightfieldTerrainShape::btHeightfieldTerrainShape(
int heightStickWidth, int heightStickLength,
const float* heightfieldData, btScalar minHeight, btScalar maxHeight,
int upAxis, bool flipQuadEdges)
: m_userValue3(0), m_triangleInfoMap(0)
{
initialize(heightStickWidth, heightStickLength, heightfieldData,
/*heightScale=*/1, minHeight, maxHeight, upAxis, PHY_FLOAT,
flipQuadEdges);
}
btHeightfieldTerrainShape::btHeightfieldTerrainShape(
int heightStickWidth, int heightStickLength, const double* heightfieldData,
btScalar minHeight, btScalar maxHeight, int upAxis, bool flipQuadEdges)
: m_userValue3(0), m_triangleInfoMap(0)
{
initialize(heightStickWidth, heightStickLength, heightfieldData,
/*heightScale=*/1, minHeight, maxHeight, upAxis, PHY_DOUBLE,
flipQuadEdges);
}
btHeightfieldTerrainShape::btHeightfieldTerrainShape(
int heightStickWidth, int heightStickLength, const short* heightfieldData, btScalar heightScale,
btScalar minHeight, btScalar maxHeight, int upAxis, bool flipQuadEdges)
: m_userValue3(0), m_triangleInfoMap(0)
{
initialize(heightStickWidth, heightStickLength, heightfieldData,
heightScale, minHeight, maxHeight, upAxis, PHY_SHORT,
flipQuadEdges);
}
btHeightfieldTerrainShape::btHeightfieldTerrainShape(
int heightStickWidth, int heightStickLength, const unsigned char* heightfieldData, btScalar heightScale,
btScalar minHeight, btScalar maxHeight, int upAxis, bool flipQuadEdges)
: m_userValue3(0), m_triangleInfoMap(0)
{
initialize(heightStickWidth, heightStickLength, heightfieldData,
heightScale, minHeight, maxHeight, upAxis, PHY_UCHAR,
flipQuadEdges);
}
btHeightfieldTerrainShape::btHeightfieldTerrainShape(
int heightStickWidth, int heightStickLength, const void* heightfieldData,
btScalar heightScale, btScalar minHeight, btScalar maxHeight, int upAxis,
PHY_ScalarType hdt, bool flipQuadEdges)
:m_userValue3(0),
m_triangleInfoMap(0)
{
// legacy constructor: Assumes PHY_FLOAT means btScalar.
#ifdef BT_USE_DOUBLE_PRECISION
if (hdt == PHY_FLOAT) hdt = PHY_DOUBLE;
#endif
initialize(heightStickWidth, heightStickLength, heightfieldData,
heightScale, minHeight, maxHeight, upAxis, hdt,
flipQuadEdges);
}
btHeightfieldTerrainShape::btHeightfieldTerrainShape(int heightStickWidth, int heightStickLength, const void* heightfieldData, btScalar maxHeight, int upAxis, bool useFloatData, bool flipQuadEdges)
: m_userValue3(0),
m_triangleInfoMap(0)
{
// legacy constructor: support only btScalar or unsigned char data,
// and min height is zero.
PHY_ScalarType hdt = (useFloatData) ? PHY_FLOAT : PHY_UCHAR;
#ifdef BT_USE_DOUBLE_PRECISION
if (hdt == PHY_FLOAT) hdt = PHY_DOUBLE;
#endif
btScalar minHeight = 0.0f;
// previously, height = uchar * maxHeight / 65535.
// So to preserve legacy behavior, heightScale = maxHeight / 65535
btScalar heightScale = maxHeight / 65535;
initialize(heightStickWidth, heightStickLength, heightfieldData,
heightScale, minHeight, maxHeight, upAxis, hdt,
flipQuadEdges);
}
void btHeightfieldTerrainShape::initialize(
int heightStickWidth, int heightStickLength, const void* heightfieldData,
btScalar heightScale, btScalar minHeight, btScalar maxHeight, int upAxis,
PHY_ScalarType hdt, bool flipQuadEdges)
{
// validation
btAssert(heightStickWidth > 1); // && "bad width");
btAssert(heightStickLength > 1); // && "bad length");
btAssert(heightfieldData); // && "null heightfield data");
// btAssert(heightScale) -- do we care? Trust caller here
btAssert(minHeight <= maxHeight); // && "bad min/max height");
btAssert(upAxis >= 0 && upAxis < 3); // && "bad upAxis--should be in range [0,2]");
btAssert(hdt != PHY_UCHAR || hdt != PHY_FLOAT || hdt != PHY_DOUBLE || hdt != PHY_SHORT); // && "Bad height data type enum");
// initialize member variables
m_shapeType = TERRAIN_SHAPE_PROXYTYPE;
m_heightStickWidth = heightStickWidth;
m_heightStickLength = heightStickLength;
m_minHeight = minHeight;
m_maxHeight = maxHeight;
m_width = (btScalar)(heightStickWidth - 1);
m_length = (btScalar)(heightStickLength - 1);
m_heightScale = heightScale;
m_heightfieldDataUnknown = heightfieldData;
m_heightDataType = hdt;
m_flipQuadEdges = flipQuadEdges;
m_useDiamondSubdivision = false;
m_useZigzagSubdivision = false;
m_flipTriangleWinding = false;
m_upAxis = upAxis;
m_localScaling.setValue(btScalar(1.), btScalar(1.), btScalar(1.));
m_vboundsChunkSize = 0;
m_vboundsGridWidth = 0;
m_vboundsGridLength = 0;
// determine min/max axis-aligned bounding box (aabb) values
switch (m_upAxis)
{
case 0:
{
m_localAabbMin.setValue(m_minHeight, 0, 0);
m_localAabbMax.setValue(m_maxHeight, m_width, m_length);
break;
}
case 1:
{
m_localAabbMin.setValue(0, m_minHeight, 0);
m_localAabbMax.setValue(m_width, m_maxHeight, m_length);
break;
};
case 2:
{
m_localAabbMin.setValue(0, 0, m_minHeight);
m_localAabbMax.setValue(m_width, m_length, m_maxHeight);
break;
}
default:
{
//need to get valid m_upAxis
btAssert(0); // && "Bad m_upAxis");
}
}
// remember origin (defined as exact middle of aabb)
m_localOrigin = btScalar(0.5) * (m_localAabbMin + m_localAabbMax);
}
btHeightfieldTerrainShape::~btHeightfieldTerrainShape()
{
clearAccelerator();
}
void btHeightfieldTerrainShape::getAabb(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const
{
btVector3 halfExtents = (m_localAabbMax - m_localAabbMin) * m_localScaling * btScalar(0.5);
btVector3 localOrigin(0, 0, 0);
localOrigin[m_upAxis] = (m_minHeight + m_maxHeight) * btScalar(0.5);
localOrigin *= m_localScaling;
btMatrix3x3 abs_b = t.getBasis().absolute();
btVector3 center = t.getOrigin();
btVector3 extent = halfExtents.dot3(abs_b[0], abs_b[1], abs_b[2]);
extent += btVector3(getMargin(), getMargin(), getMargin());
aabbMin = center - extent;
aabbMax = center + extent;
}
/// This returns the "raw" (user's initial) height, not the actual height.
/// The actual height needs to be adjusted to be relative to the center
/// of the heightfield's AABB.
btScalar
btHeightfieldTerrainShape::getRawHeightFieldValue(int x, int y) const
{
btScalar val = 0.f;
switch (m_heightDataType)
{
case PHY_FLOAT:
{
val = m_heightfieldDataFloat[(y * m_heightStickWidth) + x];
break;
}
case PHY_DOUBLE:
{
val = m_heightfieldDataDouble[(y * m_heightStickWidth) + x];
break;
}
case PHY_UCHAR:
{
unsigned char heightFieldValue = m_heightfieldDataUnsignedChar[(y * m_heightStickWidth) + x];
val = heightFieldValue * m_heightScale;
break;
}
case PHY_SHORT:
{
short hfValue = m_heightfieldDataShort[(y * m_heightStickWidth) + x];
val = hfValue * m_heightScale;
break;
}
default:
{
btAssert(!"Bad m_heightDataType");
}
}
return val;
}
/// this returns the vertex in bullet-local coordinates
void btHeightfieldTerrainShape::getVertex(int x, int y, btVector3& vertex) const
{
btAssert(x >= 0);
btAssert(y >= 0);
btAssert(x < m_heightStickWidth);
btAssert(y < m_heightStickLength);
btScalar height = getRawHeightFieldValue(x, y);
switch (m_upAxis)
{
case 0:
{
vertex.setValue(
height - m_localOrigin.getX(),
(-m_width / btScalar(2.0)) + x,
(-m_length / btScalar(2.0)) + y);
break;
}
case 1:
{
vertex.setValue(
(-m_width / btScalar(2.0)) + x,
height - m_localOrigin.getY(),
(-m_length / btScalar(2.0)) + y);
break;
};
case 2:
{
vertex.setValue(
(-m_width / btScalar(2.0)) + x,
(-m_length / btScalar(2.0)) + y,
height - m_localOrigin.getZ());
break;
}
default:
{
//need to get valid m_upAxis
btAssert(0);
}
}
vertex *= m_localScaling;
}
static inline int
getQuantized(
btScalar x)
{
if (x < 0.0)
{
return (int)(x - 0.5);
}
return (int)(x + 0.5);
}
// Equivalent to std::minmax({a, b, c}).
// Performs at most 3 comparisons.
static btHeightfieldTerrainShape::Range minmaxRange(btScalar a, btScalar b, btScalar c)
{
if (a > b)
{
if (b > c)
return btHeightfieldTerrainShape::Range(c, a);
else if (a > c)
return btHeightfieldTerrainShape::Range(b, a);
else
return btHeightfieldTerrainShape::Range(b, c);
}
else
{
if (a > c)
return btHeightfieldTerrainShape::Range(c, b);
else if (b > c)
return btHeightfieldTerrainShape::Range(a, b);
else
return btHeightfieldTerrainShape::Range(a, c);
}
}
/// given input vector, return quantized version
/**
This routine is basically determining the gridpoint indices for a given
input vector, answering the question: "which gridpoint is closest to the
provided point?".
"with clamp" means that we restrict the point to be in the heightfield's
axis-aligned bounding box.
*/
void btHeightfieldTerrainShape::quantizeWithClamp(int* out, const btVector3& point, int /*isMax*/) const
{
btVector3 clampedPoint(point);
clampedPoint.setMax(m_localAabbMin);
clampedPoint.setMin(m_localAabbMax);
out[0] = getQuantized(clampedPoint.getX());
out[1] = getQuantized(clampedPoint.getY());
out[2] = getQuantized(clampedPoint.getZ());
}
/// process all triangles within the provided axis-aligned bounding box
/**
basic algorithm:
- convert input aabb to local coordinates (scale down and shift for local origin)
- convert input aabb to a range of heightfield grid points (quantize)
- iterate over all triangles in that subset of the grid
*/
void btHeightfieldTerrainShape::processAllTriangles(btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax) const
{
// scale down the input aabb's so they are in local (non-scaled) coordinates
btVector3 localAabbMin = aabbMin * btVector3(1.f / m_localScaling[0], 1.f / m_localScaling[1], 1.f / m_localScaling[2]);
btVector3 localAabbMax = aabbMax * btVector3(1.f / m_localScaling[0], 1.f / m_localScaling[1], 1.f / m_localScaling[2]);
// account for local origin
localAabbMin += m_localOrigin;
localAabbMax += m_localOrigin;
//quantize the aabbMin and aabbMax, and adjust the start/end ranges
int quantizedAabbMin[3];
int quantizedAabbMax[3];
quantizeWithClamp(quantizedAabbMin, localAabbMin, 0);
quantizeWithClamp(quantizedAabbMax, localAabbMax, 1);
// expand the min/max quantized values
// this is to catch the case where the input aabb falls between grid points!
for (int i = 0; i < 3; ++i)
{
quantizedAabbMin[i]--;
quantizedAabbMax[i]++;
}
int startX = 0;
int endX = m_heightStickWidth - 1;
int startJ = 0;
int endJ = m_heightStickLength - 1;
switch (m_upAxis)
{
case 0:
{
if (quantizedAabbMin[1] > startX)
startX = quantizedAabbMin[1];
if (quantizedAabbMax[1] < endX)
endX = quantizedAabbMax[1];
if (quantizedAabbMin[2] > startJ)
startJ = quantizedAabbMin[2];
if (quantizedAabbMax[2] < endJ)
endJ = quantizedAabbMax[2];
break;
}
case 1:
{
if (quantizedAabbMin[0] > startX)
startX = quantizedAabbMin[0];
if (quantizedAabbMax[0] < endX)
endX = quantizedAabbMax[0];
if (quantizedAabbMin[2] > startJ)
startJ = quantizedAabbMin[2];
if (quantizedAabbMax[2] < endJ)
endJ = quantizedAabbMax[2];
break;
};
case 2:
{
if (quantizedAabbMin[0] > startX)
startX = quantizedAabbMin[0];
if (quantizedAabbMax[0] < endX)
endX = quantizedAabbMax[0];
if (quantizedAabbMin[1] > startJ)
startJ = quantizedAabbMin[1];
if (quantizedAabbMax[1] < endJ)
endJ = quantizedAabbMax[1];
break;
}
default:
{
//need to get valid m_upAxis
btAssert(0);
}
}
// TODO If m_vboundsGrid is available, use it to determine if we really need to process this area
const Range aabbUpRange(aabbMin[m_upAxis], aabbMax[m_upAxis]);
for (int j = startJ; j < endJ; j++)
{
for (int x = startX; x < endX; x++)
{
btVector3 vertices[3];
int indices[3] = { 0, 1, 2 };
if (m_flipTriangleWinding)
{
indices[0] = 2;
indices[2] = 0;
}
if (m_flipQuadEdges || (m_useDiamondSubdivision && !((j + x) & 1)) || (m_useZigzagSubdivision && !(j & 1)))
{
getVertex(x, j, vertices[indices[0]]);
getVertex(x, j + 1, vertices[indices[1]]);
getVertex(x + 1, j + 1, vertices[indices[2]]);
// Skip triangle processing if the triangle is out-of-AABB.
Range upRange = minmaxRange(vertices[0][m_upAxis], vertices[1][m_upAxis], vertices[2][m_upAxis]);
if (upRange.overlaps(aabbUpRange))
callback->processTriangle(vertices, 2 * x, j);
// already set: getVertex(x, j, vertices[indices[0]])
// equivalent to: getVertex(x + 1, j + 1, vertices[indices[1]]);
vertices[indices[1]] = vertices[indices[2]];
getVertex(x + 1, j, vertices[indices[2]]);
upRange.min = btMin(upRange.min, vertices[indices[2]][m_upAxis]);
upRange.max = btMax(upRange.max, vertices[indices[2]][m_upAxis]);
if (upRange.overlaps(aabbUpRange))
callback->processTriangle(vertices, 2 * x + 1, j);
}
else
{
getVertex(x, j, vertices[indices[0]]);
getVertex(x, j + 1, vertices[indices[1]]);
getVertex(x + 1, j, vertices[indices[2]]);
// Skip triangle processing if the triangle is out-of-AABB.
Range upRange = minmaxRange(vertices[0][m_upAxis], vertices[1][m_upAxis], vertices[2][m_upAxis]);
if (upRange.overlaps(aabbUpRange))
callback->processTriangle(vertices, 2 * x, j);
// already set: getVertex(x, j + 1, vertices[indices[1]]);
// equivalent to: getVertex(x + 1, j, vertices[indices[0]]);
vertices[indices[0]] = vertices[indices[2]];
getVertex(x + 1, j + 1, vertices[indices[2]]);
upRange.min = btMin(upRange.min, vertices[indices[2]][m_upAxis]);
upRange.max = btMax(upRange.max, vertices[indices[2]][m_upAxis]);
if (upRange.overlaps(aabbUpRange))
callback->processTriangle(vertices, 2 * x + 1, j);
}
}
}
}
void btHeightfieldTerrainShape::calculateLocalInertia(btScalar, btVector3& inertia) const
{
//moving concave objects not supported
inertia.setValue(btScalar(0.), btScalar(0.), btScalar(0.));
}
void btHeightfieldTerrainShape::setLocalScaling(const btVector3& scaling)
{
m_localScaling = scaling;
}
const btVector3& btHeightfieldTerrainShape::getLocalScaling() const
{
return m_localScaling;
}
namespace
{
struct GridRaycastState
{
int x; // Next quad coords
int z;
int prev_x; // Previous quad coords
int prev_z;
btScalar param; // Exit param for previous quad
btScalar prevParam; // Enter param for previous quad
btScalar maxDistanceFlat;
btScalar maxDistance3d;
};
}
// TODO Does it really need to take 3D vectors?
/// Iterates through a virtual 2D grid of unit-sized square cells,
/// and executes an action on each cell intersecting the given segment, ordered from begin to end.
/// Initially inspired by http://www.cse.yorku.ca/~amana/research/grid.pdf
template <typename Action_T>
void gridRaycast(Action_T& quadAction, const btVector3& beginPos, const btVector3& endPos, int indices[3])
{
GridRaycastState rs;
rs.maxDistance3d = beginPos.distance(endPos);
if (rs.maxDistance3d < 0.0001)
{
// Consider the ray is too small to hit anything
return;
}
btScalar rayDirectionFlatX = endPos[indices[0]] - beginPos[indices[0]];
btScalar rayDirectionFlatZ = endPos[indices[2]] - beginPos[indices[2]];
rs.maxDistanceFlat = btSqrt(rayDirectionFlatX * rayDirectionFlatX + rayDirectionFlatZ * rayDirectionFlatZ);
if (rs.maxDistanceFlat < 0.0001)
{
// Consider the ray vertical
rayDirectionFlatX = 0;
rayDirectionFlatZ = 0;
}
else
{
rayDirectionFlatX /= rs.maxDistanceFlat;
rayDirectionFlatZ /= rs.maxDistanceFlat;
}
const int xiStep = rayDirectionFlatX > 0 ? 1 : rayDirectionFlatX < 0 ? -1 : 0;
const int ziStep = rayDirectionFlatZ > 0 ? 1 : rayDirectionFlatZ < 0 ? -1 : 0;
const float infinite = 9999999;
const btScalar paramDeltaX = xiStep != 0 ? 1.f / btFabs(rayDirectionFlatX) : infinite;
const btScalar paramDeltaZ = ziStep != 0 ? 1.f / btFabs(rayDirectionFlatZ) : infinite;
// pos = param * dir
btScalar paramCrossX; // At which value of `param` we will cross a x-axis lane?
btScalar paramCrossZ; // At which value of `param` we will cross a z-axis lane?
// paramCrossX and paramCrossZ are initialized as being the first cross
// X initialization
if (xiStep != 0)
{
if (xiStep == 1)
{
paramCrossX = (ceil(beginPos[indices[0]]) - beginPos[indices[0]]) * paramDeltaX;
}
else
{
paramCrossX = (beginPos[indices[0]] - floor(beginPos[indices[0]])) * paramDeltaX;
}
}
else
{
paramCrossX = infinite; // Will never cross on X
}
// Z initialization
if (ziStep != 0)
{
if (ziStep == 1)
{
paramCrossZ = (ceil(beginPos[indices[2]]) - beginPos[indices[2]]) * paramDeltaZ;
}
else
{
paramCrossZ = (beginPos[indices[2]] - floor(beginPos[indices[2]])) * paramDeltaZ;
}
}
else
{
paramCrossZ = infinite; // Will never cross on Z
}
rs.x = static_cast<int>(floor(beginPos[indices[0]]));
rs.z = static_cast<int>(floor(beginPos[indices[2]]));
// Workaround cases where the ray starts at an integer position
if (paramCrossX == 0.0)
{
paramCrossX += paramDeltaX;
// If going backwards, we should ignore the position we would get by the above flooring,
// because the ray is not heading in that direction
if (xiStep == -1)
{
rs.x -= 1;
}
}
if (paramCrossZ == 0.0)
{
paramCrossZ += paramDeltaZ;
if (ziStep == -1)
rs.z -= 1;
}
rs.prev_x = rs.x;
rs.prev_z = rs.z;
rs.param = 0;
while (true)
{
rs.prev_x = rs.x;
rs.prev_z = rs.z;
rs.prevParam = rs.param;
if (paramCrossX < paramCrossZ)
{
// X lane
rs.x += xiStep;
// Assign before advancing the param,
// to be in sync with the initialization step
rs.param = paramCrossX;
paramCrossX += paramDeltaX;
}
else
{
// Z lane
rs.z += ziStep;
rs.param = paramCrossZ;
paramCrossZ += paramDeltaZ;
}
if (rs.param > rs.maxDistanceFlat)
{
rs.param = rs.maxDistanceFlat;
quadAction(rs);
break;
}
else
{
quadAction(rs);
}
}
}
struct ProcessTrianglesAction
{
const btHeightfieldTerrainShape* shape;
bool flipQuadEdges;
bool useDiamondSubdivision;
int width;
int length;
btTriangleCallback* callback;
void exec(int x, int z) const
{
if (x < 0 || z < 0 || x >= width || z >= length)
{
return;
}
btVector3 vertices[3];
// TODO Since this is for raycasts, we could greatly benefit from an early exit on the first hit
// Check quad
if (flipQuadEdges || (useDiamondSubdivision && (((z + x) & 1) > 0)))
{
// First triangle
shape->getVertex(x, z, vertices[0]);
shape->getVertex(x + 1, z, vertices[1]);
shape->getVertex(x + 1, z + 1, vertices[2]);
callback->processTriangle(vertices, x, z);
// Second triangle
shape->getVertex(x, z, vertices[0]);
shape->getVertex(x + 1, z + 1, vertices[1]);
shape->getVertex(x, z + 1, vertices[2]);
callback->processTriangle(vertices, x, z);
}
else
{
// First triangle
shape->getVertex(x, z, vertices[0]);
shape->getVertex(x, z + 1, vertices[1]);
shape->getVertex(x + 1, z, vertices[2]);
callback->processTriangle(vertices, x, z);
// Second triangle
shape->getVertex(x + 1, z, vertices[0]);
shape->getVertex(x, z + 1, vertices[1]);
shape->getVertex(x + 1, z + 1, vertices[2]);
callback->processTriangle(vertices, x, z);
}
}
void operator()(const GridRaycastState& bs) const
{
exec(bs.prev_x, bs.prev_z);
}
};
struct ProcessVBoundsAction
{
const btAlignedObjectArray<btHeightfieldTerrainShape::Range>& vbounds;
int width;
int length;
int chunkSize;
btVector3 rayBegin;
btVector3 rayEnd;
btVector3 rayDir;
int* m_indices;
ProcessTrianglesAction processTriangles;
ProcessVBoundsAction(const btAlignedObjectArray<btHeightfieldTerrainShape::Range>& bnd, int* indices)
: vbounds(bnd),
m_indices(indices)
{
}
void operator()(const GridRaycastState& rs) const
{
int x = rs.prev_x;
int z = rs.prev_z;
if (x < 0 || z < 0 || x >= width || z >= length)
{
return;
}
const btHeightfieldTerrainShape::Range chunk = vbounds[x + z * width];
btVector3 enterPos;
btVector3 exitPos;
if (rs.maxDistanceFlat > 0.0001)
{
btScalar flatTo3d = chunkSize * rs.maxDistance3d / rs.maxDistanceFlat;
btScalar enterParam3d = rs.prevParam * flatTo3d;
btScalar exitParam3d = rs.param * flatTo3d;
enterPos = rayBegin + rayDir * enterParam3d;
exitPos = rayBegin + rayDir * exitParam3d;
// We did enter the flat projection of the AABB,
// but we have to check if we intersect it on the vertical axis
if (enterPos[1] > chunk.max && exitPos[m_indices[1]] > chunk.max)
{
return;
}
if (enterPos[1] < chunk.min && exitPos[m_indices[1]] < chunk.min)
{
return;
}
}
else
{
// Consider the ray vertical
// (though we shouldn't reach this often because there is an early check up-front)
enterPos = rayBegin;
exitPos = rayEnd;
}
gridRaycast(processTriangles, enterPos, exitPos, m_indices);
// Note: it could be possible to have more than one grid at different levels,
// to do this there would be a branch using a pointer to another ProcessVBoundsAction
}
};
// TODO How do I interrupt the ray when there is a hit? `callback` does not return any result
/// Performs a raycast using a hierarchical Bresenham algorithm.
/// Does not allocate any memory by itself.
void btHeightfieldTerrainShape::performRaycast(btTriangleCallback* callback, const btVector3& raySource, const btVector3& rayTarget) const
{
// Transform to cell-local
btVector3 beginPos = raySource / m_localScaling;
btVector3 endPos = rayTarget / m_localScaling;
beginPos += m_localOrigin;
endPos += m_localOrigin;
ProcessTrianglesAction processTriangles;
processTriangles.shape = this;
processTriangles.flipQuadEdges = m_flipQuadEdges;
processTriangles.useDiamondSubdivision = m_useDiamondSubdivision;
processTriangles.callback = callback;
processTriangles.width = m_heightStickWidth - 1;
processTriangles.length = m_heightStickLength - 1;
// TODO Transform vectors to account for m_upAxis
int indices[3] = { 0, 1, 2 };
if (m_upAxis == 2)
{
indices[1] = 2;
indices[2] = 1;
}
int iBeginX = static_cast<int>(floor(beginPos[indices[0]]));
int iBeginZ = static_cast<int>(floor(beginPos[indices[2]]));
int iEndX = static_cast<int>(floor(endPos[indices[0]]));
int iEndZ = static_cast<int>(floor(endPos[indices[2]]));
if (iBeginX == iEndX && iBeginZ == iEndZ)
{
// The ray will never cross quads within the plane,
// so directly process triangles within one quad
// (typically, vertical rays should end up here)
processTriangles.exec(iBeginX, iEndZ);
return;
}
if (m_vboundsGrid.size()==0)
{
// Process all quads intersecting the flat projection of the ray
gridRaycast(processTriangles, beginPos, endPos, &indices[0]);
}
else
{
btVector3 rayDiff = endPos - beginPos;
btScalar flatDistance2 = rayDiff[indices[0]] * rayDiff[indices[0]] + rayDiff[indices[2]] * rayDiff[indices[2]];
if (flatDistance2 < m_vboundsChunkSize * m_vboundsChunkSize)
{
// Don't use chunks, the ray is too short in the plane
gridRaycast(processTriangles, beginPos, endPos, &indices[0]);
return;
}
ProcessVBoundsAction processVBounds(m_vboundsGrid, &indices[0]);
processVBounds.width = m_vboundsGridWidth;
processVBounds.length = m_vboundsGridLength;
processVBounds.rayBegin = beginPos;
processVBounds.rayEnd = endPos;
processVBounds.rayDir = rayDiff.normalized();
processVBounds.processTriangles = processTriangles;
processVBounds.chunkSize = m_vboundsChunkSize;
// The ray is long, run raycast on a higher-level grid
gridRaycast(processVBounds, beginPos / m_vboundsChunkSize, endPos / m_vboundsChunkSize, indices);
}
}
/// Builds a grid data structure storing the min and max heights of the terrain in chunks.
/// if chunkSize is zero, that accelerator is removed.
/// If you modify the heights, you need to rebuild this accelerator.
void btHeightfieldTerrainShape::buildAccelerator(int chunkSize)
{
if (chunkSize <= 0)
{
clearAccelerator();
return;
}
m_vboundsChunkSize = chunkSize;
int nChunksX = m_heightStickWidth / chunkSize;
int nChunksZ = m_heightStickLength / chunkSize;
if (m_heightStickWidth % chunkSize > 0)
{
++nChunksX; // In case terrain size isn't dividable by chunk size
}
if (m_heightStickLength % chunkSize > 0)
{
++nChunksZ;
}
if (m_vboundsGridWidth != nChunksX || m_vboundsGridLength != nChunksZ)
{
clearAccelerator();
m_vboundsGridWidth = nChunksX;
m_vboundsGridLength = nChunksZ;
}
if (nChunksX == 0 || nChunksZ == 0)
{
return;
}
// This data structure is only reallocated if the required size changed
m_vboundsGrid.resize(nChunksX * nChunksZ);
// Compute min and max height for all chunks
for (int cz = 0; cz < nChunksZ; ++cz)
{
int z0 = cz * chunkSize;
for (int cx = 0; cx < nChunksX; ++cx)
{
int x0 = cx * chunkSize;
Range r;
r.min = getRawHeightFieldValue(x0, z0);
r.max = r.min;
// Compute min and max height for this chunk.
// We have to include one extra cell to account for neighbors.
// Here is why:
// Say we have a flat terrain, and a plateau that fits a chunk perfectly.
//
// Left Right
// 0---0---0---1---1---1
// | | | | | |
// 0---0---0---1---1---1
// | | | | | |
// 0---0---0---1---1---1
// x
//
// If the AABB for the Left chunk did not share vertices with the Right,
// then we would fail collision tests at x due to a gap.
//
for (int z = z0; z < z0 + chunkSize + 1; ++z)
{
if (z >= m_heightStickLength)
{
continue;
}
for (int x = x0; x < x0 + chunkSize + 1; ++x)
{
if (x >= m_heightStickWidth)
{
continue;
}
btScalar height = getRawHeightFieldValue(x, z);
if (height < r.min)
{
r.min = height;
}
else if (height > r.max)
{
r.max = height;
}
}
}
m_vboundsGrid[cx + cz * nChunksX] = r;
}
}
}
void btHeightfieldTerrainShape::clearAccelerator()
{
m_vboundsGrid.clear();
}
| 0 | 0.978903 | 1 | 0.978903 | game-dev | MEDIA | 0.925884 | game-dev | 0.993156 | 1 | 0.993156 |
spatialos/UnrealGDK | 27,746 | SpatialGDK/Source/SpatialGDK/Private/EngineClasses/SpatialPackageMapClient.cpp | // Copyright (c) Improbable Worlds Ltd, All Rights Reserved
#include "EngineClasses/SpatialPackageMapClient.h"
#include "EngineClasses/SpatialActorChannel.h"
#include "EngineClasses/SpatialNetDriver.h"
#include "EngineClasses/SpatialNetBitReader.h"
#include "Interop/Connection/SpatialWorkerConnection.h"
#include "Interop/SpatialReceiver.h"
#include "Interop/SpatialSender.h"
#include "Schema/UnrealObjectRef.h"
#include "SpatialConstants.h"
#include "Utils/SchemaOption.h"
#include "EngineUtils.h"
#include "Engine/Engine.h"
#include "GameFramework/Actor.h"
#include "Kismet/GameplayStatics.h"
#include "UObject/UObjectGlobals.h"
DEFINE_LOG_CATEGORY(LogSpatialPackageMap);
void USpatialPackageMapClient::Init(USpatialNetDriver* NetDriver, FTimerManager* TimerManager)
{
bIsServer = NetDriver->IsServer();
// Entity Pools should never exist on clients
if (bIsServer)
{
EntityPool = NewObject<UEntityPool>();
EntityPool->Init(NetDriver, TimerManager);
}
}
void GetSubobjects(UObject* ParentObject, TArray<UObject*>& InSubobjects)
{
InSubobjects.Empty();
ForEachObjectWithOuter(ParentObject, [&InSubobjects](UObject* Object)
{
// Objects can only be allocated NetGUIDs if this is true.
if (Object->IsSupportedForNetworking() && !Object->IsPendingKill() && !Object->IsEditorOnly())
{
// Walk up the outer chain and ensure that no object is PendingKill. This is required because although
// EInternalObjectFlags::PendingKill prevents objects that are PendingKill themselves from getting added
// to the list, it'll still add children of PendingKill objects. This then causes an assertion within
// FNetGUIDCache::RegisterNetGUID_Server where it again iterates up the object's owner chain, assigning
// ids and ensuring that no object is set to PendingKill in the process.
UObject* Outer = Object->GetOuter();
while (Outer != nullptr)
{
if (Outer->IsPendingKill())
{
return;
}
Outer = Outer->GetOuter();
}
InSubobjects.Add(Object);
}
}, true, RF_NoFlags, EInternalObjectFlags::PendingKill);
InSubobjects.StableSort([](UObject& A, UObject& B)
{
return A.GetName() < B.GetName();
});
}
Worker_EntityId USpatialPackageMapClient::AllocateEntityIdAndResolveActor(AActor* Actor)
{
check(Actor);
checkf(bIsServer, TEXT("Tried to allocate an Entity ID on the client, this shouldn't happen."));
if (!IsEntityPoolReady())
{
UE_LOG(LogSpatialPackageMap, Error, TEXT("EntityPool must be ready when resolving an Actor: %s"), *Actor->GetName());
return SpatialConstants::INVALID_ENTITY_ID;
}
Worker_EntityId EntityId = AllocateEntityId();
if (EntityId == SpatialConstants::INVALID_ENTITY_ID)
{
UE_LOG(LogSpatialPackageMap, Error, TEXT("Unable to retrieve an Entity ID for Actor: %s"), *Actor->GetName());
return EntityId;
}
// Register Actor with package map since we know what the entity id is.
if (!ResolveEntityActor(Actor, EntityId))
{
UE_LOG(LogSpatialPackageMap, Error, TEXT("Unable to resolve an Entity for Actor: %s"), *Actor->GetName());
return SpatialConstants::INVALID_ENTITY_ID;
}
return EntityId;
}
FNetworkGUID USpatialPackageMapClient::TryResolveObjectAsEntity(UObject* Value)
{
FNetworkGUID NetGUID;
if (!bIsServer)
{
return NetGUID;
}
AActor* Actor = Value->IsA<AActor>() ? Cast<AActor>(Value) : Value->GetTypedOuter<AActor>();
if (Actor == nullptr)
{
return NetGUID;
}
if (!Actor->GetIsReplicated())
{
return NetGUID;
}
// Resolve as an entity if it is an unregistered actor
if (Actor->Role == ROLE_Authority && GetEntityIdFromObject(Actor) == SpatialConstants::INVALID_ENTITY_ID)
{
Worker_EntityId EntityId = AllocateEntityIdAndResolveActor(Actor);
if (EntityId != SpatialConstants::INVALID_ENTITY_ID)
{
// Mark this entity ID as pending creation (checked in USpatialActorChannel::SetChannelActor).
PendingCreationEntityIds.Add(EntityId);
}
NetGUID = GetNetGUIDFromObject(Value);
}
return NetGUID;
}
bool USpatialPackageMapClient::IsEntityIdPendingCreation(Worker_EntityId EntityId) const
{
return PendingCreationEntityIds.Contains(EntityId);
}
void USpatialPackageMapClient::RemovePendingCreationEntityId(Worker_EntityId EntityId)
{
PendingCreationEntityIds.Remove(EntityId);
}
bool USpatialPackageMapClient::ResolveEntityActor(AActor* Actor, Worker_EntityId EntityId)
{
FSpatialNetGUIDCache* SpatialGuidCache = static_cast<FSpatialNetGUIDCache*>(GuidCache.Get());
FNetworkGUID NetGUID = SpatialGuidCache->GetNetGUIDFromEntityId(EntityId);
// check we haven't already assigned a NetGUID to this object
if (!NetGUID.IsValid())
{
NetGUID = SpatialGuidCache->AssignNewEntityActorNetGUID(Actor, EntityId);
}
if (GetEntityIdFromObject(Actor) != EntityId)
{
UE_LOG(LogSpatialPackageMap, Error, TEXT("ResolveEntityActor failed for Actor: %s with NetGUID: %s and passed entity ID: %lld"), *Actor->GetName(), *NetGUID.ToString(), EntityId);
return false;
}
return NetGUID.IsValid();
}
void USpatialPackageMapClient::ResolveSubobject(UObject* Object, const FUnrealObjectRef& ObjectRef)
{
FSpatialNetGUIDCache* SpatialGuidCache = static_cast<FSpatialNetGUIDCache*>(GuidCache.Get());
FNetworkGUID NetGUID = SpatialGuidCache->GetNetGUIDFromUnrealObjectRef(ObjectRef);
if (!NetGUID.IsValid())
{
SpatialGuidCache->AssignNewSubobjectNetGUID(Object, ObjectRef);
}
}
void USpatialPackageMapClient::RemoveEntityActor(Worker_EntityId EntityId)
{
FSpatialNetGUIDCache* SpatialGuidCache = static_cast<FSpatialNetGUIDCache*>(GuidCache.Get());
if (SpatialGuidCache->GetNetGUIDFromEntityId(EntityId).IsValid())
{
SpatialGuidCache->RemoveEntityNetGUID(EntityId);
}
}
void USpatialPackageMapClient::RemoveSubobject(const FUnrealObjectRef& ObjectRef)
{
FSpatialNetGUIDCache* SpatialGuidCache = static_cast<FSpatialNetGUIDCache*>(GuidCache.Get());
if (SpatialGuidCache->GetNetGUIDFromUnrealObjectRef(ObjectRef).IsValid())
{
SpatialGuidCache->RemoveSubobjectNetGUID(ObjectRef);
}
}
void USpatialPackageMapClient::UnregisterActorObjectRefOnly(const FUnrealObjectRef& ObjectRef)
{
FSpatialNetGUIDCache* SpatialGuidCache = static_cast<FSpatialNetGUIDCache*>(GuidCache.Get());
SpatialGuidCache->UnregisterActorObjectRefOnly(ObjectRef);
}
FNetworkGUID USpatialPackageMapClient::ResolveStablyNamedObject(UObject* Object)
{
FSpatialNetGUIDCache* SpatialGuidCache = static_cast<FSpatialNetGUIDCache*>(GuidCache.Get());
return SpatialGuidCache->AssignNewStablyNamedObjectNetGUID(Object);
}
FUnrealObjectRef USpatialPackageMapClient::GetUnrealObjectRefFromNetGUID(const FNetworkGUID & NetGUID) const
{
FSpatialNetGUIDCache* SpatialGuidCache = static_cast<FSpatialNetGUIDCache*>(GuidCache.Get());
return SpatialGuidCache->GetUnrealObjectRefFromNetGUID(NetGUID);
}
FNetworkGUID USpatialPackageMapClient::GetNetGUIDFromUnrealObjectRef(const FUnrealObjectRef & ObjectRef) const
{
FSpatialNetGUIDCache* SpatialGuidCache = static_cast<FSpatialNetGUIDCache*>(GuidCache.Get());
return SpatialGuidCache->GetNetGUIDFromUnrealObjectRef(ObjectRef);
}
FNetworkGUID USpatialPackageMapClient::GetNetGUIDFromEntityId(const Worker_EntityId& EntityId) const
{
FSpatialNetGUIDCache* SpatialGuidCache = static_cast<FSpatialNetGUIDCache*>(GuidCache.Get());
FUnrealObjectRef ObjectRef(EntityId, 0);
return GetNetGUIDFromUnrealObjectRef(ObjectRef);
}
TWeakObjectPtr<UObject> USpatialPackageMapClient::GetObjectFromUnrealObjectRef(const FUnrealObjectRef& ObjectRef)
{
FNetworkGUID NetGUID = GetNetGUIDFromUnrealObjectRef(ObjectRef);
if (NetGUID.IsValid() && !NetGUID.IsDefault())
{
return GetObjectFromNetGUID(NetGUID, true);
}
return nullptr;
}
TWeakObjectPtr<UObject> USpatialPackageMapClient::GetObjectFromEntityId(const Worker_EntityId& EntityId)
{
return GetObjectFromUnrealObjectRef(FUnrealObjectRef(EntityId, 0));
}
FUnrealObjectRef USpatialPackageMapClient::GetUnrealObjectRefFromObject(const UObject* Object)
{
if (Object == nullptr)
{
return FUnrealObjectRef::NULL_OBJECT_REF;
}
FNetworkGUID NetGUID = GetNetGUIDFromObject(Object);
return GetUnrealObjectRefFromNetGUID(NetGUID);
}
Worker_EntityId USpatialPackageMapClient::GetEntityIdFromObject(const UObject* Object)
{
if (Object == nullptr)
{
return SpatialConstants::INVALID_ENTITY_ID;
}
FNetworkGUID NetGUID = GetNetGUIDFromObject(Object);
return GetUnrealObjectRefFromNetGUID(NetGUID).Entity;
}
bool USpatialPackageMapClient::CanClientLoadObject(UObject* Object)
{
FNetworkGUID NetGUID = GetNetGUIDFromObject(Object);
return GuidCache->CanClientLoadObject(Object, NetGUID);
}
AActor* USpatialPackageMapClient::GetUniqueActorInstanceByClassRef(const FUnrealObjectRef& UniqueObjectClassRef)
{
if (UClass* UniqueObjectClass = Cast<UClass>(GetObjectFromUnrealObjectRef(UniqueObjectClassRef)))
{
return GetUniqueActorInstanceByClass(UniqueObjectClass);
}
else
{
FString FullPath;
SpatialGDK::GetFullPathFromUnrealObjectReference(UniqueObjectClassRef, FullPath);
UE_LOG(LogSpatialPackageMap, Warning, TEXT("Can't resolve unique object class: %s"), *FullPath);
return nullptr;
}
}
AActor* USpatialPackageMapClient::GetUniqueActorInstanceByClass(UClass* UniqueObjectClass) const
{
check(UniqueObjectClass != nullptr);
TArray<AActor*> FoundActors;
// USpatialPackageMapClient is an inner object of UNetConnection,
// which in turn contains a NetDriver and gets the UWorld it references.
UGameplayStatics::GetAllActorsOfClass(this, UniqueObjectClass, FoundActors);
// There should be only one Actor per class.
if (FoundActors.Num() == 1)
{
return FoundActors[0];
}
UE_LOG(LogSpatialPackageMap, Warning, TEXT("Found %d Actors for class: %s. There should only be one."), FoundActors.Num(), *UniqueObjectClass->GetName());
return nullptr;
}
Worker_EntityId USpatialPackageMapClient::AllocateEntityId()
{
return EntityPool->GetNextEntityId();
}
bool USpatialPackageMapClient::IsEntityPoolReady() const
{
return (EntityPool != nullptr) && (EntityPool->IsReady());
}
FEntityPoolReadyEvent& USpatialPackageMapClient::GetEntityPoolReadyDelegate()
{
check(bIsServer);
return EntityPool->GetEntityPoolReadyDelegate();
}
bool USpatialPackageMapClient::SerializeObject(FArchive& Ar, UClass* InClass, UObject*& Obj, FNetworkGUID *OutNetGUID)
{
// Super::SerializeObject is not called here on purpose
if (Ar.IsSaving())
{
Ar << Obj;
return true;
}
FSpatialNetBitReader& Reader = static_cast<FSpatialNetBitReader&>(Ar);
bool bUnresolved = false;
Obj = Reader.ReadObject(bUnresolved);
return !bUnresolved;
}
const FClassInfo* USpatialPackageMapClient::TryResolveNewDynamicSubobjectAndGetClassInfo(UObject* Object)
{
AActor* Actor = Object ? Object->GetTypedOuter<AActor>() : nullptr;
Worker_EntityId EntityId = GetEntityIdFromObject(Actor);
if (EntityId != SpatialConstants::INVALID_ENTITY_ID)
{
FUnrealObjectRef Ref = GetUnrealObjectRefFromObject(Object);
if (Ref.IsValid())
{
UE_LOG(LogSpatialPackageMap, Error, TEXT("Trying to resolve a dynamic subobject twice! Object %s, Actor %s, EntityId %d."), *GetNameSafe(Object), *GetNameSafe(Actor), EntityId);
return nullptr;
}
const FClassInfo* Info = Cast<USpatialNetDriver>(GuidCache->Driver)->ClassInfoManager->GetClassInfoForNewSubobject(Object, EntityId, this);
// If we don't get the info, an error is logged in the above function, that we have exceeded the maximum number of dynamic subobjects on the entity
if (Info != nullptr)
{
ResolveSubobject(Object, FUnrealObjectRef(EntityId, Info->SchemaComponents[SCHEMA_Data]));
}
return Info;
}
UE_LOG(LogSpatialPackageMap, Error, TEXT("While trying to resolve a new dynamic subobject %s, the parent actor %s was not resolved."), *GetNameSafe(Object), *GetNameSafe(Actor));
return nullptr;
}
FSpatialNetGUIDCache::FSpatialNetGUIDCache(USpatialNetDriver* InDriver)
: FNetGUIDCache(InDriver)
{
}
FNetworkGUID FSpatialNetGUIDCache::AssignNewEntityActorNetGUID(AActor* Actor, Worker_EntityId EntityId)
{
check(EntityId > 0);
USpatialNetDriver* SpatialNetDriver = Cast<USpatialNetDriver>(Driver);
USpatialReceiver* Receiver = SpatialNetDriver->Receiver;
FNetworkGUID NetGUID;
FUnrealObjectRef EntityObjectRef(EntityId, 0);
// Valid if Actor is stably named. Used for stably named subobject assignment further below
FUnrealObjectRef StablyNamedRef;
if (Actor->IsNameStableForNetworking())
{
// Startup Actors have two valid UnrealObjectRefs: the entity id and the path.
// AssignNewStablyNamedObjectNetGUID will register the path ref.
NetGUID = AssignNewStablyNamedObjectNetGUID(Actor);
// We register the entity id ref here.
UnrealObjectRefToNetGUID.Emplace(EntityObjectRef, NetGUID);
// Once we have an entity id, we should always be using it to refer to entities.
// Since the path ref may have been registered previously, we first try to remove it
// and then register the entity id ref.
StablyNamedRef = NetGUIDToUnrealObjectRef[NetGUID];
NetGUIDToUnrealObjectRef.Emplace(NetGUID, EntityObjectRef);
}
else
{
NetGUID = GetOrAssignNetGUID_SpatialGDK(Actor);
RegisterObjectRef(NetGUID, EntityObjectRef);
}
UE_LOG(LogSpatialPackageMap, Verbose, TEXT("Registered new object ref for actor: %s. NetGUID: %s, entity ID: %lld"),
*Actor->GetName(), *NetGUID.ToString(), EntityId);
const FClassInfo& Info = SpatialNetDriver->ClassInfoManager->GetOrCreateClassInfoByClass(Actor->GetClass());
const SubobjectToOffsetMap& SubobjectToOffset = SpatialGDK::CreateOffsetMapFromActor(Actor, Info);
for (auto& Pair : SubobjectToOffset)
{
UObject* Subobject = Pair.Key;
uint32 Offset = Pair.Value;
// AssignNewStablyNamedObjectNetGUID is not used due to using the wrong ObjectRef as the outer of the subobject.
// So it is ok to use RegisterObjectRef in both cases since no prior bookkeeping was done (unlike Actors)
FNetworkGUID SubobjectNetGUID = GetOrAssignNetGUID_SpatialGDK(Subobject);
FUnrealObjectRef EntityIdSubobjectRef(EntityId, Offset);
if (Subobject->IsNameStableForNetworking())
{
if (Subobject->GetFName().ToString().Equals(TEXT("PersistentLevel")) && !Subobject->IsA<ULevel>())
{
UE_LOG(LogSpatialPackageMap, Fatal, TEXT("Found object called PersistentLevel which isn't a Level! This is not allowed when using the GDK"));
}
// Using StablyNamedRef for the outer since referencing ObjectRef in the map
// will have the EntityId
FUnrealObjectRef StablyNamedSubobjectRef(0, 0, Subobject->GetFName().ToString(), StablyNamedRef);
// This is the only extra object ref that has to be registered for the subobject.
UnrealObjectRefToNetGUID.Emplace(StablyNamedSubobjectRef, SubobjectNetGUID);
// As the subobject may have be referred to previously in replication flow, it would
// have it's stable name registered as it's UnrealObjectRef inside NetGUIDToUnrealObjectRef.
// Update the map to point to the entity id version.
NetGUIDToUnrealObjectRef.Emplace(SubobjectNetGUID, EntityIdSubobjectRef);
}
RegisterObjectRef(SubobjectNetGUID, EntityIdSubobjectRef);
UE_LOG(LogSpatialPackageMap, Verbose, TEXT("Registered new object ref for subobject %s inside actor %s. NetGUID: %s, object ref: %s"),
*Subobject->GetName(), *Actor->GetName(), *SubobjectNetGUID.ToString(), *EntityIdSubobjectRef.ToString());
}
return NetGUID;
}
void FSpatialNetGUIDCache::AssignNewSubobjectNetGUID(UObject* Subobject, const FUnrealObjectRef& SubobjectRef)
{
FNetworkGUID SubobjectNetGUID = GetOrAssignNetGUID_SpatialGDK(Subobject);
RegisterObjectRef(SubobjectNetGUID, SubobjectRef);
}
// Recursively assign netguids to the outer chain of a UObject. Then associate them with their Spatial representation (FUnrealObjectRef)
// This is required in order to be able to refer to a non-replicated stably named UObject.
// Dynamically spawned actors and references to their subobjects do not go through this codepath.
FNetworkGUID FSpatialNetGUIDCache::AssignNewStablyNamedObjectNetGUID(UObject* Object)
{
FNetworkGUID NetGUID = GetOrAssignNetGUID_SpatialGDK(Object);
FUnrealObjectRef ExistingObjRef = GetUnrealObjectRefFromNetGUID(NetGUID);
if (ExistingObjRef != FUnrealObjectRef::UNRESOLVED_OBJECT_REF)
{
return NetGUID;
}
FNetworkGUID OuterGUID;
UObject* OuterObject = Object->GetOuter();
if (OuterObject)
{
OuterGUID = AssignNewStablyNamedObjectNetGUID(OuterObject);
}
if (Object->GetFName().ToString().Equals(TEXT("PersistentLevel")) && !Object->IsA<ULevel>())
{
UE_LOG(LogSpatialPackageMap, Fatal, TEXT("Found object called PersistentLevel which isn't a Level! This is not allowed when using the GDK"));
}
bool bNoLoadOnClient = false;
if (IsNetGUIDAuthority())
{
// If the server is replicating references to things inside levels, it needs to indicate
// that the client should not load these. Once the level is streamed in, the client will
// resolve the references.
bNoLoadOnClient = !CanClientLoadObject(Object, NetGUID);
}
FUnrealObjectRef StablyNamedObjRef(0, 0, Object->GetFName().ToString(), (OuterGUID.IsValid() && !OuterGUID.IsDefault()) ? GetUnrealObjectRefFromNetGUID(OuterGUID) : FUnrealObjectRef(), bNoLoadOnClient);
RegisterObjectRef(NetGUID, StablyNamedObjRef);
return NetGUID;
}
void FSpatialNetGUIDCache::RemoveEntityNetGUID(Worker_EntityId EntityId)
{
// Remove actor subobjects.
USpatialNetDriver* SpatialNetDriver = Cast<USpatialNetDriver>(Driver);
SpatialGDK::UnrealMetadata* UnrealMetadata = SpatialNetDriver->StaticComponentView->GetComponentData<SpatialGDK::UnrealMetadata>(EntityId);
// If UnrealMetadata is nullptr (can happen if the editor is closing down) just return.
if (UnrealMetadata == nullptr)
{
return;
}
// Due to UnrealMetadata::GetNativeEntityClass using LoadObject, if we are shutting down and garbage collecting,
// calling LoadObject will crash the editor. In this case, just return since everything will be cleaned up anyways.
if (IsInGameThread() && IsGarbageCollecting())
{
return;
}
SpatialGDK::TSchemaOption<FUnrealObjectRef>& StablyNamedRefOption = UnrealMetadata->StablyNamedRef;
if (UnrealMetadata->NativeClass.IsStale())
{
UE_LOG(LogSpatialPackageMap, Warning, TEXT("Attempting to remove stale object from package map - %s"), *UnrealMetadata->ClassPath);
}
else
{
const FClassInfo& Info = SpatialNetDriver->ClassInfoManager->GetOrCreateClassInfoByClass(UnrealMetadata->GetNativeEntityClass());
for (auto& SubobjectInfoPair : Info.SubobjectInfo)
{
FUnrealObjectRef SubobjectRef(EntityId, SubobjectInfoPair.Key);
if (FNetworkGUID* SubobjectNetGUID = UnrealObjectRefToNetGUID.Find(SubobjectRef))
{
NetGUIDToUnrealObjectRef.Remove(*SubobjectNetGUID);
UnrealObjectRefToNetGUID.Remove(SubobjectRef);
if (StablyNamedRefOption.IsSet())
{
UnrealObjectRefToNetGUID.Remove(FUnrealObjectRef(0, 0, SubobjectInfoPair.Value->SubobjectName.ToString(), StablyNamedRefOption.GetValue()));
}
}
}
}
// Remove dynamically attached subobjects
if (USpatialActorChannel* Channel = SpatialNetDriver->GetActorChannelByEntityId(EntityId))
{
for (UObject* DynamicSubobject : Channel->CreateSubObjects)
{
if (FNetworkGUID* SubobjectNetGUID = NetGUIDLookup.Find(DynamicSubobject))
{
if (FUnrealObjectRef* SubobjectRef = NetGUIDToUnrealObjectRef.Find(*SubobjectNetGUID))
{
UnrealObjectRefToNetGUID.Remove(*SubobjectRef);
NetGUIDToUnrealObjectRef.Remove(*SubobjectNetGUID);
}
}
}
}
// Remove actor.
FNetworkGUID EntityNetGUID = GetNetGUIDFromEntityId(EntityId);
// TODO: Figure out why NetGUIDToUnrealObjectRef might not have this GUID. UNR-989
if (FUnrealObjectRef* ActorRef = NetGUIDToUnrealObjectRef.Find(EntityNetGUID))
{
UnrealObjectRefToNetGUID.Remove(*ActorRef);
}
NetGUIDToUnrealObjectRef.Remove(EntityNetGUID);
if (StablyNamedRefOption.IsSet())
{
UnrealObjectRefToNetGUID.Remove(StablyNamedRefOption.GetValue());
}
}
void FSpatialNetGUIDCache::RemoveSubobjectNetGUID(const FUnrealObjectRef& SubobjectRef)
{
if (!UnrealObjectRefToNetGUID.Contains(SubobjectRef))
{
return;
}
USpatialNetDriver* SpatialNetDriver = Cast<USpatialNetDriver>(Driver);
SpatialGDK::UnrealMetadata* UnrealMetadata = SpatialNetDriver->StaticComponentView->GetComponentData<SpatialGDK::UnrealMetadata>(SubobjectRef.Entity);
// If UnrealMetadata is nullptr (can happen if the editor is closing down) just return.
if (UnrealMetadata == nullptr)
{
return;
}
// Due to UnrealMetadata::GetNativeEntityClass using LoadObject, if we are shutting down and garbage collecting,
// calling LoadObject will crash the editor. In this case, just return since everything will be cleaned up anyways.
if (IsInGameThread() && IsGarbageCollecting())
{
return;
}
if (UnrealMetadata->NativeClass.IsStale())
{
UE_LOG(LogSpatialPackageMap, Warning, TEXT("Attempting to remove stale subobject from package map - %s"), *UnrealMetadata->ClassPath);
}
else
{
const FClassInfo& Info = SpatialNetDriver->ClassInfoManager->GetOrCreateClassInfoByClass(UnrealMetadata->GetNativeEntityClass());
// Part of the CDO
if (const TSharedRef<const FClassInfo>* SubobjectInfoPtr = Info.SubobjectInfo.Find(SubobjectRef.Offset))
{
SpatialGDK::TSchemaOption<FUnrealObjectRef>& StablyNamedRefOption = UnrealMetadata->StablyNamedRef;
if (StablyNamedRefOption.IsSet())
{
UnrealObjectRefToNetGUID.Remove(FUnrealObjectRef(0, 0, SubobjectInfoPtr->Get().SubobjectName.ToString(), StablyNamedRefOption.GetValue()));
}
}
}
FNetworkGUID SubobjectNetGUID = UnrealObjectRefToNetGUID[SubobjectRef];
NetGUIDToUnrealObjectRef.Remove(SubobjectNetGUID);
UnrealObjectRefToNetGUID.Remove(SubobjectRef);
}
FNetworkGUID FSpatialNetGUIDCache::GetNetGUIDFromUnrealObjectRef(const FUnrealObjectRef& ObjectRef)
{
return GetNetGUIDFromUnrealObjectRefInternal(ObjectRef);
}
FNetworkGUID FSpatialNetGUIDCache::GetNetGUIDFromUnrealObjectRefInternal(const FUnrealObjectRef& ObjectRef)
{
FNetworkGUID* CachedGUID = UnrealObjectRefToNetGUID.Find(ObjectRef);
FNetworkGUID NetGUID = CachedGUID ? *CachedGUID : FNetworkGUID{};
if (!NetGUID.IsValid() && ObjectRef.Path.IsSet())
{
FNetworkGUID OuterGUID;
// Recursively resolve the outers for this object in order to ensure that the package can be loaded
if (ObjectRef.Outer.IsSet())
{
OuterGUID = GetNetGUIDFromUnrealObjectRef(ObjectRef.Outer.GetValue());
}
// Once all outer packages have been resolved, assign a new NetGUID for this object
NetGUID = RegisterNetGUIDFromPathForStaticObject(ObjectRef.Path.GetValue(), OuterGUID, ObjectRef.bNoLoadOnClient);
RegisterObjectRef(NetGUID, ObjectRef);
}
return NetGUID;
}
void FSpatialNetGUIDCache::NetworkRemapObjectRefPaths(FUnrealObjectRef& ObjectRef, bool bReading) const
{
// If we have paths, network-sanitize all of them (e.g. removing PIE prefix).
if (!ObjectRef.Path.IsSet())
{
return;
}
FUnrealObjectRef* Iterator = &ObjectRef;
while (true)
{
if (Iterator->Path.IsSet())
{
FString TempPath(*Iterator->Path);
GEngine->NetworkRemapPath(Driver, TempPath, bReading);
Iterator->Path = TempPath;
}
if (!Iterator->Outer.IsSet())
{
break;
}
Iterator = &Iterator->Outer.GetValue();
}
}
void FSpatialNetGUIDCache::UnregisterActorObjectRefOnly(const FUnrealObjectRef& ObjectRef)
{
FNetworkGUID& NetGUID = UnrealObjectRefToNetGUID.FindChecked(ObjectRef);
// Remove ObjectRef first so the reference above isn't destroyed
NetGUIDToUnrealObjectRef.Remove(NetGUID);
UnrealObjectRefToNetGUID.Remove(ObjectRef);
}
FUnrealObjectRef FSpatialNetGUIDCache::GetUnrealObjectRefFromNetGUID(const FNetworkGUID& NetGUID) const
{
const FUnrealObjectRef* ObjRef = NetGUIDToUnrealObjectRef.Find(NetGUID);
return ObjRef ? (FUnrealObjectRef)*ObjRef : FUnrealObjectRef::UNRESOLVED_OBJECT_REF;
}
FNetworkGUID FSpatialNetGUIDCache::GetNetGUIDFromEntityId(Worker_EntityId EntityId) const
{
FUnrealObjectRef ObjRef(EntityId, 0);
const FNetworkGUID* NetGUID = UnrealObjectRefToNetGUID.Find(ObjRef);
return (NetGUID == nullptr) ? FNetworkGUID(0) : *NetGUID;
}
FNetworkGUID FSpatialNetGUIDCache::RegisterNetGUIDFromPathForStaticObject(const FString& PathName, const FNetworkGUID& OuterGUID, bool bNoLoadOnClient)
{
// Put the PIE prefix back (if applicable) so that the correct object can be found.
FString TempPath = PathName;
GEngine->NetworkRemapPath(Driver, TempPath, true);
// This function should only be called for stably named object references, not dynamic ones.
FNetGuidCacheObject CacheObject;
CacheObject.PathName = FName(*TempPath);
CacheObject.OuterGUID = OuterGUID;
CacheObject.bNoLoad = bNoLoadOnClient; // server decides whether the client should load objects (e.g. don't load levels)
CacheObject.bIgnoreWhenMissing = bNoLoadOnClient;
FNetworkGUID NetGUID = GenerateNewNetGUID(1);
RegisterNetGUID_Internal(NetGUID, CacheObject);
return NetGUID;
}
FNetworkGUID FSpatialNetGUIDCache::GenerateNewNetGUID(const int32 IsStatic)
{
// Here we have to borrow from FNetGuidCache::AssignNewNetGUID_Server to avoid a source change.
#define COMPOSE_NET_GUID(Index, IsStatic) (((Index) << 1) | (IsStatic) )
#define ALLOC_NEW_NET_GUID(IsStatic) (COMPOSE_NET_GUID(++UniqueNetIDs[IsStatic], IsStatic))
// Generate new NetGUID and assign it
FNetworkGUID NetGUID = FNetworkGUID(ALLOC_NEW_NET_GUID(IsStatic));
return NetGUID;
}
FNetworkGUID FSpatialNetGUIDCache::GetOrAssignNetGUID_SpatialGDK(UObject* Object)
{
FNetworkGUID NetGUID = GetOrAssignNetGUID(Object);
// One major difference between how Unreal does NetGUIDs vs us is, we don't attempt to make them consistent across workers and client.
// The function above might have returned without assigning new GUID, because we are the client.
// Let's directly call the client function in that case.
if (Object != nullptr && NetGUID == FNetworkGUID::GetDefault() && !IsNetGUIDAuthority())
{
NetGUID = GenerateNewNetGUID(IsDynamicObject(Object) ? 0 : 1);
FNetGuidCacheObject CacheObject;
CacheObject.Object = MakeWeakObjectPtr(const_cast<UObject*>(Object));
CacheObject.PathName = Object->GetFName();
CacheObject.OuterGUID = GetOrAssignNetGUID_SpatialGDK(Object->GetOuter());
CacheObject.bIgnoreWhenMissing = true;
RegisterNetGUID_Internal(NetGUID, CacheObject);
UE_LOG(LogSpatialPackageMap, Verbose, TEXT("%s: NetGUID for object %s was not found in the cache. Generated new NetGUID %s."),
*Cast<USpatialNetDriver>(Driver)->Connection->GetWorkerId(),
*Object->GetPathName(),
*NetGUID.ToString());
}
check((NetGUID.IsValid() && !NetGUID.IsDefault()) || Object == nullptr);
return NetGUID;
}
void FSpatialNetGUIDCache::RegisterObjectRef(FNetworkGUID NetGUID, const FUnrealObjectRef& ObjectRef)
{
// Registered ObjectRefs should never have PIE.
FUnrealObjectRef RemappedObjectRef = ObjectRef;
NetworkRemapObjectRefPaths(RemappedObjectRef, false /*bIsReading*/);
checkfSlow(!NetGUIDToUnrealObjectRef.Contains(NetGUID) || (NetGUIDToUnrealObjectRef.Contains(NetGUID) && NetGUIDToUnrealObjectRef.FindChecked(NetGUID) == RemappedObjectRef),
TEXT("NetGUID to UnrealObjectRef mismatch - NetGUID: %s ObjRef in map: %s ObjRef expected: %s"), *NetGUID.ToString(),
*NetGUIDToUnrealObjectRef.FindChecked(NetGUID).ToString(), *RemappedObjectRef.ToString());
checkfSlow(!UnrealObjectRefToNetGUID.Contains(RemappedObjectRef) || (UnrealObjectRefToNetGUID.Contains(RemappedObjectRef) && UnrealObjectRefToNetGUID.FindChecked(RemappedObjectRef) == NetGUID),
TEXT("UnrealObjectRef to NetGUID mismatch - UnrealObjectRef: %s NetGUID in map: %s NetGUID expected: %s"), *NetGUID.ToString(),
*UnrealObjectRefToNetGUID.FindChecked(RemappedObjectRef).ToString(), *RemappedObjectRef.ToString());
NetGUIDToUnrealObjectRef.Emplace(NetGUID, RemappedObjectRef);
UnrealObjectRefToNetGUID.Emplace(RemappedObjectRef, NetGUID);
}
| 0 | 0.650837 | 1 | 0.650837 | game-dev | MEDIA | 0.204588 | game-dev | 0.642171 | 1 | 0.642171 |
jabuwu/shanty-quest | 6,637 | src/game/overworld/attacks/kraken.rs | use crate::common::prelude::*;
use crate::game::prelude::*;
use audio_plus::prelude::*;
use bevy::prelude::*;
pub struct KrakenPlugin;
impl Plugin for KrakenPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, (kraken_fire, tentacle_update, tentacle_animate));
}
}
#[derive(Component, Default)]
pub struct Kraken {
pub shoot: bool,
pub hurt_flags: u32,
pub level: KrakenLevel,
}
#[derive(Default)]
pub struct KrakenLevel(pub u32);
impl KrakenLevel {
fn stats(&self) -> KrakenStats {
if self.0 == 6 {
// boss stats
KrakenStats {
damage: 1.5,
close_tentacles: 1,
far_tentacles: 5,
far_tentacle_distance_min: 150.,
far_tentacle_distance_max: 1650.,
knockback_intensity: 6.,
}
} else {
KrakenStats {
damage: 1.5,
close_tentacles: 0,
far_tentacles: 2 * self.0,
far_tentacle_distance_min: 150.,
far_tentacle_distance_max: 500.,
knockback_intensity: 5.,
}
}
}
}
#[derive(Copy, Clone, Debug)]
struct KrakenStats {
damage: f32,
close_tentacles: u32,
far_tentacles: u32,
far_tentacle_distance_min: f32,
far_tentacle_distance_max: f32,
knockback_intensity: f32,
}
#[derive(Component)]
struct Tentacle {
pub submerge_time: f32,
pub submerge_time_max: f32,
pub spawned_hurtbox: bool,
pub parent: Entity,
pub hurt_flags: u32,
pub time_to_live: f32,
pub stats: KrakenStats,
}
fn kraken_fire(
mut query: Query<(Entity, &mut Kraken, &GlobalTransform)>,
mut commands: Commands,
asset_library: Res<AssetLibrary>,
) {
for (boat_entity, mut kraken, global_transform) in query.iter_mut() {
if kraken.shoot {
let stats = kraken.level.stats();
commands.spawn((
Transform2Bundle {
transform2: Transform2::from_translation(
global_transform.translation().truncate(),
),
..Default::default()
},
AudioPlusSource::new(
asset_library
.sound_effects
.sfx_overworld_attack_kraken
.clone(),
)
.as_playing(),
TimeToLive { seconds: 3. },
));
for i in 0..(stats.close_tentacles + stats.far_tentacles) {
let close_tentacle = i < stats.close_tentacles;
let (distance_min, distance_max) = if close_tentacle {
(100., 100.)
} else {
(
stats.far_tentacle_distance_min,
stats.far_tentacle_distance_max,
)
};
let forward = Vec2::from_angle(rand::random::<f32>() * std::f32::consts::TAU);
let position = global_transform.translation().truncate()
+ forward
* (distance_min + rand::random::<f32>() * (distance_max - distance_min));
let (scale, _, _) = global_transform.to_scale_rotation_translation();
let submerge_time = if close_tentacle { 0. } else { 1.0 };
commands.spawn((
SpriteSheetBundle {
texture_atlas: asset_library.sprite_tentacle_atlas.clone(),
..Default::default()
},
Transform2::from_translation(position)
.with_depth((DepthLayer::Entity, 0.0))
.with_scale(scale.truncate()),
YDepth { offset: 20. },
Tentacle {
submerge_time,
submerge_time_max: submerge_time,
spawned_hurtbox: false,
parent: boat_entity,
hurt_flags: kraken.hurt_flags,
time_to_live: if close_tentacle { 1.5 } else { 3.0 },
stats,
},
));
}
}
kraken.shoot = false;
}
}
fn tentacle_update(
mut query: Query<(Entity, &mut Tentacle, &GlobalTransform)>,
time: Res<Time>,
mut commands: Commands,
asset_library: Res<AssetLibrary>,
) {
for (entity, mut tentacle, global_transform) in query.iter_mut() {
tentacle.submerge_time -= time.delta_seconds();
tentacle.time_to_live -= time.delta_seconds();
if tentacle.time_to_live < 0. && tentacle.spawned_hurtbox {
commands.entity(entity).despawn();
}
if tentacle.submerge_time <= 0. && !tentacle.spawned_hurtbox {
if rand::random() {
commands.spawn((
TransformBundle::default(),
Transform2::from_translation(global_transform.translation().truncate()),
AudioPlusSource::new(
asset_library
.sound_effects
.sfx_overworld_attack_tentacle
.clone(),
)
.as_playing(),
TimeToLive { seconds: 4. },
));
}
commands.entity(entity).insert(Hurtbox {
shape: CollisionShape::Rect {
size: Vec2::new(32., 48.),
},
for_entity: Some(tentacle.parent),
auto_despawn: false,
flags: tentacle.hurt_flags,
knockback_type: HurtboxKnockbackType::Difference(
tentacle.stats.knockback_intensity,
),
damage: tentacle.stats.damage,
});
tentacle.spawned_hurtbox = true;
}
}
}
fn tentacle_animate(mut query: Query<(&mut TextureAtlasSprite, &Tentacle)>, time: Res<Time>) {
for (mut sprite, tentacle) in query.iter_mut() {
if tentacle.submerge_time > 0. {
if tentacle.submerge_time > tentacle.submerge_time_max * 0.25 {
sprite.index = 0;
} else {
sprite.index = 1;
}
} else {
let time = (time.elapsed_seconds() * 3.) % 1.;
if time > 0.5 {
sprite.index = 3;
} else {
sprite.index = 2;
}
}
}
}
| 0 | 0.76879 | 1 | 0.76879 | game-dev | MEDIA | 0.98671 | game-dev | 0.945282 | 1 | 0.945282 |
Kaedrin/nwn2cc | 1,393 | Source/KaedPRCPack_v1.42.1_Override_Dialogtlk/Scripts/cmi_s0_hawkeye.nss | //::///////////////////////////////////////////////
//:: Hawkeye
//:: cmi_s0_hawkeye
//:: Purpose:
//:: Created By: Kaedrin (Matt)
//:: Created On: January 23, 2010
//:://////////////////////////////////////////////
#include "cmi_ginc_spells"
#include "x2_inc_spellhook"
#include "x0_i0_spells"
void main()
{
if (!X2PreSpellCastCode())
{
// If code within the PreSpellCastHook (i.e. UMD) reports FALSE, do not run this spell
return;
}
object oTarget = GetSpellTargetObject();
object oWeapon = GetItemInSlot(INVENTORY_SLOT_RIGHTHAND, oTarget);
if (GetIsObjectValid(oWeapon) && GetWeaponRanged(oWeapon))
{
int nSpellId = GetSpellId();
int nCasterLvl = GetPalRngCasterLevel();
float fDuration = TurnsToSeconds( nCasterLvl ) * 10;
fDuration = ApplyMetamagicDurationMods(fDuration);
effect eSkill = EffectSkillIncrease(SKILL_SPOT, 5);
effect eAB = EffectAttackIncrease(1);
effect eVis = EffectVisualEffect(VFX_DUR_SPELL_PREMONITION);
effect eLink = EffectLinkEffects(eSkill, eAB);
eLink = EffectLinkEffects(eLink, eVis);
RemoveEffectsFromSpell(oTarget, nSpellId);
SignalEvent(oTarget, EventSpellCastAt(OBJECT_SELF, nSpellId, FALSE));
ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eLink, oTarget, fDuration);
}
else
SendMessageToPC(OBJECT_SELF, "You must use a ranged weapon for this spell to work");
} | 0 | 0.745172 | 1 | 0.745172 | game-dev | MEDIA | 0.985297 | game-dev | 0.952893 | 1 | 0.952893 |
KaboomB52/KewlSpigot | 3,160 | kewlspigot-api/src/main/java/org/bukkit/event/Event.java | package org.bukkit.event;
import org.bukkit.plugin.PluginManager;
/**
* Represents an event.
*
* All events require a static method named getHandlerList() which returns the same {@link HandlerList} as {@link #getHandlers()}.
*
* @see PluginManager#callEvent(Event)
* @see PluginManager#registerEvents(Listener,Plugin)
*/
public abstract class Event {
private String name;
private final boolean async;
/**
* The default constructor is defined for cleaner code. This constructor
* assumes the event is synchronous.
*/
public Event() {
this(false);
}
/**
* This constructor is used to explicitly declare an event as synchronous
* or asynchronous.
*
* @param isAsync true indicates the event will fire asynchronously, false
* by default from default constructor
*/
public Event(boolean isAsync) {
this.async = isAsync;
}
/**
* Convenience method for providing a user-friendly identifier. By
* default, it is the event's class's {@linkplain Class#getSimpleName()
* simple name}.
*
* @return name of this event
*/
public String getEventName() {
if (name == null) {
name = getClass().getSimpleName();
}
return name;
}
public abstract HandlerList getHandlers();
/**
* Any custom event that should not by synchronized with other events must
* use the specific constructor. These are the caveats of using an
* asynchronous event:
* <ul>
* <li>The event is never fired from inside code triggered by a
* synchronous event. Attempting to do so results in an {@link
* java.lang.IllegalStateException}.
* <li>However, asynchronous event handlers may fire synchronous or
* asynchronous events
* <li>The event may be fired multiple times simultaneously and in any
* order.
* <li>Any newly registered or unregistered handler is ignored after an
* event starts execution.
* <li>The handlers for this event may block for any length of time.
* <li>Some implementations may selectively declare a specific event use
* as asynchronous. This behavior should be clearly defined.
* <li>Asynchronous calls are not calculated in the plugin timing system.
* </ul>
*
* @return false by default, true if the event fires asynchronously
*/
public final boolean isAsynchronous() {
return async;
}
public enum Result {
/**
* Deny the event. Depending on the event, the action indicated by the
* event will either not take place or will be reverted. Some actions
* may not be denied.
*/
DENY,
/**
* Neither deny nor allow the event. The server will proceed with its
* normal handling.
*/
DEFAULT,
/**
* Allow / Force the event. The action indicated by the event will
* take place if possible, even if the server would not normally allow
* the action. Some actions may not be allowed.
*/
ALLOW;
}
}
| 0 | 0.852301 | 1 | 0.852301 | game-dev | MEDIA | 0.230694 | game-dev | 0.880721 | 1 | 0.880721 |
rutgerkok/BlockLocker | 1,405 | src/main/java/nl/rutgerkok/blocklocker/impl/group/mcMMOGroupSystem.java | package nl.rutgerkok.blocklocker.impl.group;
import java.util.Objects;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.api.PartyAPI;
import nl.rutgerkok.blocklocker.group.GroupSystem;
/**
* Group system hooking into the mcMMO plugin.
*
*/
public final class mcMMOGroupSystem extends GroupSystem {
/**
* Tests if the mcMMO plugin is installed.
*
* @return True if the mcMMO plugin is installed, false otherwise.
*/
public static boolean isAvailable() {
try {
JavaPlugin.getProvidingPlugin(mcMMO.class);
return true;
} catch (NoClassDefFoundError e) {
return false;
}
}
@Override
public boolean isGroupLeader(Player player, String groupName) {
if (!isInGroup(player, groupName)) {
return false;
}
String leader = PartyAPI.getPartyLeader(groupName);
return Objects.equals(player.getName(), leader) ? true : false;
}
@Override
public boolean isInGroup(Player player, String groupName) {
if (!PartyAPI.inParty(player)) {
// Player is not in a party
return false;
}
String partyName = PartyAPI.getPartyName(player);
// Ignore case, mcMMO is not case sensitive
return partyName.equalsIgnoreCase(groupName);
}
@Override
public boolean keepOnReload() {
// BlockLocker will re-add the group system
return false;
}
} | 0 | 0.824817 | 1 | 0.824817 | game-dev | MEDIA | 0.825951 | game-dev | 0.81664 | 1 | 0.81664 |
jjbali/Extended-Experienced-PD | 3,371 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/custom/visuals/effects/BeamCustom.java | package com.shatteredpixel.shatteredpixeldungeon.custom.visuals.effects;
import com.shatteredpixel.shatteredpixeldungeon.effects.Effects;
import com.watabou.glwrap.Blending;
import com.watabou.noosa.Game;
import com.watabou.noosa.Image;
import com.watabou.utils.Callback;
import com.watabou.utils.PointF;
public class BeamCustom extends Image {
private static final double A = 180 / Math.PI;
private float duration;
private float timeLeft;
private Callback callback;
private float chargeTime = 0f;
private float keepTime = 0f;
private float fadeTime = 0.5f;
public BeamCustom(PointF s, PointF e, Effects.Type asset, Callback callback){
super( Effects.get( asset ) );
origin.set( 0, height / 2 );
x = s.x - origin.x;
y = s.y - origin.y;
float dx = e.x - s.x;
float dy = e.y - s.y;
angle = (float)(Math.atan2( dy, dx ) * A);
scale.x = (float)Math.sqrt( dx * dx + dy * dy ) / width;
//Sample.INSTANCE.play( Assets.Sounds.RAY );
timeLeft = this.duration = 0.5f;
this.callback = callback;
}
public BeamCustom(PointF s, PointF e, Effects.Type asset) {
this(s, e, asset, null);
}
public BeamCustom setDiameter(float diameterModifier){
scale.y *= diameterModifier;
return this;
}
public BeamCustom setColor(int color){
hardlight(color);
return this;
}
public BeamCustom setTime(float rise, float flat, float down){
chargeTime = rise;
keepTime = flat;
fadeTime = down;
timeLeft = rise + flat + down;
updateImage();
return this;
}
//avoid using both setLifespan and setTime.
//Old interface, should abandon
public BeamCustom setLifespan(float life){
timeLeft = this.duration = life;
fadeTime = life;
chargeTime = keepTime = 0f;
return this;
}
/*
public static class DeathRay extends Beam{
public DeathRay(PointF s, PointF e){
super(s, e, Effects.Type.DEATH_RAY, 0.5f);
}
}
public static class LightRay extends Beam{
public LightRay(PointF s, PointF e){
super(s, e, Effects.Type.LIGHT_RAY, 1f);
}
}
public static class HealthRay extends Beam {
public HealthRay(PointF s, PointF e){
super(s, e, Effects.Type.HEALTH_RAY, 0.75f);
}
}
*/
@Override
public void update() {
super.update();
updateImage();
if ((timeLeft -= Game.elapsed) <= 0) {
if(callback != null){
callback.call();
}
killAndErase();
}
}
protected void updateImage(){
if(timeLeft > keepTime + fadeTime){
float p = ( keepTime + fadeTime + chargeTime - timeLeft) / Math.max(chargeTime, Game.elapsed);
alpha( p );
scale.set( scale.x, p );
}else if(timeLeft > fadeTime){
alpha(1f);
scale.set( scale.x, 1f );
}else{
float p = ( fadeTime - timeLeft) / Math.max(fadeTime, Game.elapsed);
alpha( 1f-p );
scale.set( scale.x, 1f-p );
}
}
@Override
public void draw() {
Blending.setLightMode();
super.draw();
Blending.setNormalMode();
}
}
| 0 | 0.986662 | 1 | 0.986662 | game-dev | MEDIA | 0.903729 | game-dev,graphics-rendering | 0.971906 | 1 | 0.971906 |
daltonbr/Undercooked | 2,564 | Assets/Scripts/UI/OrdersPanelUI.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Undercooked.Managers;
using Undercooked.Model;
using UnityEngine;
using UnityEngine.Assertions;
namespace Undercooked.UI
{
public class OrdersPanelUI : MonoBehaviour
{
[SerializeField] private OrderUI orderUIPrefab;
private readonly List<OrderUI> _ordersUI = new List<OrderUI>();
private readonly Queue<OrderUI> _orderUIPool = new Queue<OrderUI>();
private void Awake()
{
#if UNITY_EDITOR
Assert.IsNotNull(orderUIPrefab);
#endif
}
private OrderUI GetOrderUIFromPool()
{
return _orderUIPool.Count > 0 ? _orderUIPool.Dequeue() : Instantiate(orderUIPrefab, transform);
}
private void OnEnable()
{
OrderManager.OnOrderSpawned += HandleOrderSpawned;
}
private void OnDisable()
{
OrderManager.OnOrderSpawned -= HandleOrderSpawned;
}
private void HandleOrderSpawned(Order order)
{
var rightmostX = GetRightmostXFromLastElement();
var orderUI = GetOrderUIFromPool();
orderUI.Setup(order);
_ordersUI.Add(orderUI);
orderUI.SlideInSpawn(rightmostX);
}
private float GetRightmostXFromLastElement()
{
if (_ordersUI.Count == 0) return 0;
float rightmostX = 0f;
List<OrderUI> orderUisNotDeliveredOrderedByLeftToRight = _ordersUI
.Where(x => x.Order.IsDelivered == false)
.OrderBy(y => y.CurrentAnchorX).ToList();
if (orderUisNotDeliveredOrderedByLeftToRight.Count == 0) return 0;
var last = orderUisNotDeliveredOrderedByLeftToRight.Last();
rightmostX = last.CurrentAnchorX + last.SizeDeltaX;
return rightmostX;
}
public void RegroupPanelsLeft()
{
float leftmostX = 0f;
for (var i = 0; i < _ordersUI.Count; i++)
{
var orderUI = _ordersUI[i];
if (orderUI.Order.IsDelivered)
{
_orderUIPool.Enqueue(orderUI);
_ordersUI.RemoveAt(i);
i--;
}
else
{
orderUI.SlideLeft(leftmostX);
leftmostX += orderUI.SizeDeltaX;
}
}
}
}
}
| 0 | 0.69595 | 1 | 0.69595 | game-dev | MEDIA | 0.409034 | game-dev,web-backend | 0.926243 | 1 | 0.926243 |
ggnkua/Atari_ST_Sources | 5,476 | C/Sokoban/SOK.C | #include <stdio.h>
#include <curses.h>
#include <string.h>
#include "sokoban.h"
short level, packets, savepack, moves, pushes, rows, cols;
short scorelevel, scoremoves, scorepushes;
char map[MAXROW+1][MAXCOL+1];
POS ppos;
char *username, *prgname;
short optshowscore = 0, optmakescore = 0, optrestore = 0, optlevel = 0;
short scoring = 1, superuser = 0;
short userlevel;
extern int state_num;
#if ATARIST
extern char *getenv();
char *getlogin()
{
static char username[40];
char *c;
if ((c = getenv("USER")) != NULL) return c;
printf("What is your name? ");
gets(username);
return username;
}
#else
char *getlogin();
#endif
main( argc, argv)
short argc;
char *argv[];
{
short ret, ret2;
char *strrchr();
scorelevel = 0;
moves = pushes = packets = savepack = 0;
#if ATARIST
if( (prgname = strrchr( argv[0], '\\')) == NULL)
#else
if( (prgname = strrchr( argv[0], '/')) == NULL)
#endif
prgname = argv[0];
else prgname++;
if( (username = getlogin("SOKNAM")) == NULL)
ret = E_NOUSER;
else {
#if ATARIST
superuser = TRUE;
#else
superuser = (strcmp( username, SUPERUSER) == 0);
#endif
state_num = 0;
if( (ret = checkcmdline( argc, argv)) == 0) {
if( optshowscore)
ret = outputscore();
else if( optmakescore) {
if( superuser) {
if( (ret = getpassword()) == 0)
ret = makenewscore();
}
else ret = E_NOSUPER;
}
else if( optrestore) {
ret = restoregame();
}
else if( (ret = getuserlevel( &userlevel)) == 0) {
if( optlevel > 0) {
if( superuser) {
level = optlevel;
scoring = 0;
}
else if( userlevel < optlevel)
ret = E_LEVELTOOHIGH;
else level = optlevel;
}
else level = userlevel;
}
}
}
if( ret == 0)
ret = gameloop();
errmess( ret);
if( scorelevel && scoring) {
ret2 = score();
errmess( ret2);
}
exit( ret);
}
checkcmdline( argc, argv)
short argc;
char *argv[];
{
short ret = 0;
if( argc > 1)
if( (argc == 2) && (argv[1][0] == '-')) {
if( (argv[1][1] == 's') && (argv[1][2] == '\0'))
optshowscore = 1;
else if( (argv[1][1] == 'c') && (argv[1][2] == '\0'))
optmakescore = 1;
else if( (argv[1][1] == 'r') && (argv[1][2] == '\0'))
optrestore = 1;
else if( (level = optlevel = atoi( &(argv[1][1]))) == 0)
ret = E_USAGE;
}
else ret = E_USAGE;
return( ret);
}
gameloop() {
short ret = 0;
initscr(); crmode(); noecho();
if( ! optrestore) ret = readscreen();
while( ret == 0) {
if( (ret = play()) == 0) {
level++;
moves = pushes = packets = savepack = 0;
ret = readscreen();
state_num = 0;
}
}
move( 0, 0); clrtobot(); refresh();
nocrmode(); echo(); erase(); endwin();
return( ret);
}
getpassword() {
#if ATARIST
char c;
printf("Do you really want to make a new score file? ");
c = getchar();
if (c == 'y' || c == 'Y') return 0;
return E_ILLPASSWORD;
#else
short c, i;
char *p, *getpass();
p = getpass( "Password: ");
return( (strcmp( p, PASSWORD) == 0) ? 0 : E_ILLPASSWORD);
#endif
}
char *message[] = {
"illegal error number",
"cannot open screen file",
"more than one player position in screen file",
"illegal char in screen file",
"no player position in screenfile",
"too many rows in screen file",
"too many columns in screenfile",
"quit the game",
"cannot open the help file",
"cannot get your username",
"cannot open savefile",
"error writing to savefile",
"cannot stat savefile",
"error reading savefile",
"cannot restore, your savefile has been altered",
"game saved",
"too much users in score table",
"cannot open score file",
"error reading scorefile",
"error writing scorefile",
"illegal command line syntax",
"illegal password",
"level number too big in command line",
"only superuser is allowed to make a new score table",
"cannot find file to restore"
};
errmess( ret)
short ret;
{
if( ret != E_ENDGAME) {
fprintf( stderr, "%s: ", prgname);
switch( ret) {
case E_FOPENSCREEN: case E_PLAYPOS1: case E_ILLCHAR:
case E_PLAYPOS2: case E_TOMUCHROWS: case E_TOMUCHCOLS:
case E_ENDGAME: case E_FOPENHELP: case E_NOUSER:
case E_FOPENSAVE: case E_WRITESAVE: case E_STATSAVE:
case E_READSAVE: case E_ALTERSAVE: case E_SAVED:
case E_TOMUCHSE: case E_FOPENSCORE: case E_READSCORE:
case E_WRITESCORE: case E_USAGE: case E_ILLPASSWORD:
case E_LEVELTOOHIGH: case E_NOSUPER: case E_NOSAVEFILE:
fprintf( stderr, "%s\n", message[ret]);
break;
default: fprintf( stderr, "%s\n", message[0]);
break;
}
if( ret == E_USAGE) usage();
}
}
usage() {
fprintf( stderr, "Usage: %s [-{s|c|r|<nn>}]\n\n", prgname);
fprintf( stderr, " -c: create new score table (superuser only)\n");
fprintf( stderr, " -r: restore saved game\n");
fprintf( stderr, " -s: show score table\n");
fprintf( stderr, " -<nn>: play this level (<nn> must be greater 0)\n");
}
| 0 | 0.755056 | 1 | 0.755056 | game-dev | MEDIA | 0.545154 | game-dev | 0.952592 | 1 | 0.952592 |
overwolf/events-sample-apps | 3,383 | apex-events-sample-app/main.js | // this a subset of the features that Apex Legends events provides - however,
// when writing an app that consumes events - it is best if you request
// only those features that you want to handle.
//
// NOTE: in the future we'll have a wildcard option to allow retrieving all
// features
var g_interestedInFeatures = [
'death',
'kill',
'match_state',
'me',
'revive',
'team',
'roster',
'kill_feed',
'rank',
'match_summary',
'location',
'match_info',
'victory',
'damage',
'inventory',
'localization'
];
var onErrorListener,onInfoUpdates2Listener, onNewEventsListener;
function registerEvents() {
onErrorListener = function(info) {
console.log("Error: " + JSON.stringify(info));
}
onInfoUpdates2Listener = function(info) {
console.log("Info UPDATE: " + JSON.stringify(info));
}
onNewEventsListener = function(info) {
console.log("EVENT FIRED: " + JSON.stringify(info));
}
// general events errors
overwolf.games.events.onError.addListener(onErrorListener);
// "static" data changed (total kills, username, steam-id)
// This will also be triggered the first time we register
// for events and will contain all the current information
overwolf.games.events.onInfoUpdates2.addListener(onInfoUpdates2Listener);
// an event triggerd
overwolf.games.events.onNewEvents.addListener(onNewEventsListener);
}
function unregisterEvents() {
overwolf.games.events.onError.removeListener(onErrorListener);
overwolf.games.events.onInfoUpdates2.removeListener(onInfoUpdates2Listener);
overwolf.games.events.onNewEvents.removeListener(onNewEventsListener);
}
function gameLaunched(gameInfoResult) {
if (!gameInfoResult) {
return false;
}
if (!gameInfoResult.gameInfo) {
return false;
}
if (!gameInfoResult.runningChanged && !gameInfoResult.gameChanged) {
return false;
}
if (!gameInfoResult.gameInfo.isRunning) {
return false;
}
// NOTE: we divide by 10 to get the game class id without it's sequence number
if (Math.floor(gameInfoResult.gameInfo.id/10) != 21566) {
return false;
}
console.log("Apex Legends Launched");
return true;
}
function gameRunning(gameInfo) {
if (!gameInfo) {
return false;
}
if (!gameInfo.isRunning) {
return false;
}
// NOTE: we divide by 10 to get the game class id without it's sequence number
if (Math.floor(gameInfo.id/10) != 21566) {
return false;
}
console.log("Apex Legends running");
return true;
}
function setFeatures() {
overwolf.games.events.setRequiredFeatures(g_interestedInFeatures, function(info) {
if (info.status == "error")
{
//console.log("Could not set required features: " + info.reason);
//console.log("Trying in 2 seconds");
window.setTimeout(setFeatures, 2000);
return;
}
console.log("Set required features:");
console.log(JSON.stringify(info));
});
}
// Start here
overwolf.games.onGameInfoUpdated.addListener(function (res) {
if (gameLaunched(res)) {
registerEvents();
unregisterEvents();
setTimeout(setFeatures, 1000);
}
console.log("onGameInfoUpdated: " + JSON.stringify(res));
});
overwolf.games.getRunningGameInfo(function (res) {
if (gameRunning(res)) {
registerEvents();
setTimeout(setFeatures, 1000);
}
console.log("getRunningGameInfo: " + JSON.stringify(res));
});
| 0 | 0.665636 | 1 | 0.665636 | game-dev | MEDIA | 0.362102 | game-dev | 0.748301 | 1 | 0.748301 |
LambdAurora/LambDynamicLights | 6,664 | api/src/main/java/dev/lambdaurora/lambdynlights/api/predicate/LightSourceLocationPredicate.java | /*
* Copyright © 2024 LambdAurora <email@lambdaurora.dev>
*
* This file is part of LambDynamicLights.
*
* Licensed under the Lambda License. For more information,
* see the LICENSE file.
*/
package dev.lambdaurora.lambdynlights.api.predicate;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.advancements.critereon.MinMaxBounds;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.RegistryCodecs;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.CampfireBlock;
import java.util.Optional;
/**
* Represents a predicate to match a location with.
* <p>
* This is inspired from the {@linkplain net.minecraft.advancements.critereon.LocationPredicate location predicate}
* found in advancements but with fewer features since this one needs to work on the client.
*
* @param position the position predicate to match if present
* @param biomes the biomes to match if present
* @param dimension the dimension to match if present
* @param smokey {@code true} to match if the given position is smokey, or {@code false} otherwise
* @param light the light predicate to match if present
* @param canSeeSky {@code true} to match if the given position can see the sky, or {@code false} otherwise
* @author LambdAurora
* @version 4.0.0
* @since 4.0.0
*/
public record LightSourceLocationPredicate(
Optional<PositionPredicate> position,
Optional<HolderSet<Biome>> biomes,
Optional<ResourceKey<Level>> dimension,
Optional<Boolean> smokey,
Optional<LightSourceLightPredicate> light,
Optional<Boolean> canSeeSky
) {
public static final Codec<LightSourceLocationPredicate> CODEC = RecordCodecBuilder.create(
instance -> instance.group(
PositionPredicate.CODEC.optionalFieldOf("position").forGetter(LightSourceLocationPredicate::position),
RegistryCodecs.homogeneousList(Registries.BIOME).optionalFieldOf("biomes").forGetter(LightSourceLocationPredicate::biomes),
ResourceKey.codec(Registries.DIMENSION).optionalFieldOf("dimension").forGetter(LightSourceLocationPredicate::dimension),
Codec.BOOL.optionalFieldOf("smokey").forGetter(LightSourceLocationPredicate::smokey),
LightSourceLightPredicate.CODEC.optionalFieldOf("light").forGetter(LightSourceLocationPredicate::light),
Codec.BOOL.optionalFieldOf("can_see_sky").forGetter(LightSourceLocationPredicate::canSeeSky)
)
.apply(instance, LightSourceLocationPredicate::new)
);
public boolean matches(Level level, double x, double y, double z) {
if (this.position.isPresent() && !this.position.get().matches(x, y, z)) {
return false;
} else if (this.dimension.isPresent() && this.dimension.get() != level.dimension()) {
return false;
} else {
BlockPos pos = BlockPos.ofFloored(x, y, z);
boolean loaded = level.isLoaded(pos);
if (this.biomes.isEmpty() || loaded && this.biomes.get().contains(level.getBiome(pos))) {
if (this.smokey.isEmpty() || loaded && this.smokey.get() == CampfireBlock.isSmokeyPos(level, pos)) {
if (this.light.isPresent() && !this.light.get().matches(level, pos)) {
return false;
} else {
return this.canSeeSky.isEmpty() || this.canSeeSky.get() == level.canSeeSky(pos);
}
} else {
return false;
}
} else {
return false;
}
}
}
public static class Builder {
private MinMaxBounds.Doubles x = MinMaxBounds.Doubles.ANY;
private MinMaxBounds.Doubles y = MinMaxBounds.Doubles.ANY;
private MinMaxBounds.Doubles z = MinMaxBounds.Doubles.ANY;
private Optional<HolderSet<Biome>> biomes = Optional.empty();
private Optional<ResourceKey<Level>> dimension = Optional.empty();
private Optional<Boolean> smokey = Optional.empty();
private Optional<LightSourceLightPredicate> light = Optional.empty();
private Optional<Boolean> canSeeSky = Optional.empty();
public static Builder location() {
return new Builder();
}
public static Builder inBiome(Holder<Biome> holder) {
return location().biomes(HolderSet.direct(holder));
}
public static Builder inDimension(ResourceKey<Level> resourceKey) {
return location().dimension(resourceKey);
}
public static Builder atYLocation(MinMaxBounds.Doubles doubles) {
return location().y(doubles);
}
public Builder x(MinMaxBounds.Doubles doubles) {
this.x = doubles;
return this;
}
public Builder y(MinMaxBounds.Doubles doubles) {
this.y = doubles;
return this;
}
public Builder z(MinMaxBounds.Doubles doubles) {
this.z = doubles;
return this;
}
public Builder biomes(HolderSet<Biome> holderSet) {
this.biomes = Optional.of(holderSet);
return this;
}
public Builder dimension(ResourceKey<Level> resourceKey) {
this.dimension = Optional.of(resourceKey);
return this;
}
public Builder light(LightSourceLightPredicate predicate) {
this.light = Optional.of(predicate);
return this;
}
public Builder smokey(boolean smokey) {
this.smokey = Optional.of(smokey);
return this;
}
public Builder canSeeSky(boolean canSeeSky) {
this.canSeeSky = Optional.of(canSeeSky);
return this;
}
public LightSourceLocationPredicate build() {
Optional<PositionPredicate> position = PositionPredicate.of(this.x, this.y, this.z);
return new LightSourceLocationPredicate(position, this.biomes, this.dimension, this.smokey, this.light, this.canSeeSky);
}
}
public record PositionPredicate(MinMaxBounds.Doubles x, MinMaxBounds.Doubles y, MinMaxBounds.Doubles z) {
public static final Codec<PositionPredicate> CODEC = RecordCodecBuilder.create(
instance -> instance.group(
MinMaxBounds.Doubles.CODEC.optionalFieldOf("x", MinMaxBounds.Doubles.ANY).forGetter(PositionPredicate::x),
MinMaxBounds.Doubles.CODEC.optionalFieldOf("y", MinMaxBounds.Doubles.ANY).forGetter(PositionPredicate::y),
MinMaxBounds.Doubles.CODEC.optionalFieldOf("z", MinMaxBounds.Doubles.ANY).forGetter(PositionPredicate::z)
)
.apply(instance, PositionPredicate::new)
);
public static Optional<PositionPredicate> of(
MinMaxBounds.Doubles x,
MinMaxBounds.Doubles y,
MinMaxBounds.Doubles z
) {
return x.isAny() && y.isAny() && z.isAny()
? Optional.empty()
: Optional.of(new PositionPredicate(x, y, z));
}
public boolean matches(double x, double y, double z) {
return this.x.matches(x) && this.y.matches(y) && this.z.matches(z);
}
}
}
| 0 | 0.804864 | 1 | 0.804864 | game-dev | MEDIA | 0.332945 | game-dev | 0.765154 | 1 | 0.765154 |
fhoedemakers/PicoSystem_InfoNes | 4,443 | infones/mapper/InfoNES_Mapper_243.cpp | /*===================================================================*/
/* */
/* Mapper 243 (Pirates) */
/* */
/*===================================================================*/
BYTE Map243_Regs[4];
/*-------------------------------------------------------------------*/
/* Initialize Mapper 243 */
/*-------------------------------------------------------------------*/
void Map243_Init()
{
/* Initialize Mapper */
MapperInit = Map243_Init;
/* Write to Mapper */
MapperWrite = Map0_Write;
/* Write to SRAM */
MapperSram = Map0_Sram;
/* Write to APU */
MapperApu = Map243_Apu;
/* Read from APU */
MapperReadApu = Map0_ReadApu;
/* Callback at VSync */
MapperVSync = Map0_VSync;
/* Callback at HSync */
MapperHSync = Map0_HSync;
/* Callback at PPU */
MapperPPU = Map0_PPU;
/* Callback at Rendering Screen ( 1:BG, 0:Sprite ) */
MapperRenderScreen = Map0_RenderScreen;
/* Set SRAM Banks */
SRAMBANK = SRAM;
/* Set ROM Banks */
ROMBANK0 = ROMPAGE( 0 );
ROMBANK1 = ROMPAGE( 1 );
ROMBANK2 = ROMPAGE( 2 );
ROMBANK3 = ROMPAGE( 3 );
/* Set PPU Banks */
if ( NesHeader.byVRomSize > 0 )
{
for ( int nPage = 0; nPage < 8; ++nPage )
{
PPUBANK[ nPage ] = VROMPAGE( nPage );
}
InfoNES_SetupChr();
}
/* Initialize state registers */
Map243_Regs[0] = Map243_Regs[1] = Map243_Regs[2] = Map243_Regs[3] = 0;
/* Set up wiring of the interrupt pin */
K6502_Set_Int_Wiring( 1, 1 );
}
/*-------------------------------------------------------------------*/
/* Mapper 243 Write to Apu Function */
/*-------------------------------------------------------------------*/
void Map243_Apu( WORD wAddr, BYTE byData )
{
if ( wAddr == 0x4100 )
{
Map243_Regs[0] = byData;
}
else if ( wAddr == 0x4101 )
{
switch ( Map243_Regs[0] & 0x07 )
{
case 0x02:
Map243_Regs[1] = byData & 0x01;
break;
case 0x00:
case 0x04:
case 0x07:
Map243_Regs[2] = ( byData & 0x01 ) << 1;
break;
/* Set ROM Banks */
case 0x05:
ROMBANK0 = ROMPAGE( ( byData * 4 + 0 ) % ( NesHeader.byRomSize << 1 ) );
ROMBANK1 = ROMPAGE( ( byData * 4 + 1 ) % ( NesHeader.byRomSize << 1 ) );
ROMBANK2 = ROMPAGE( ( byData * 4 + 2 ) % ( NesHeader.byRomSize << 1 ) );
ROMBANK3 = ROMPAGE( ( byData * 4 + 3 ) % ( NesHeader.byRomSize << 1 ) );
break;
case 0x06:
Map243_Regs[3] = ( byData & 0x03 ) << 2;
break;
}
/* Set PPU Banks */
if ( ( NesHeader.byVRomSize << 3 ) <= 64 )
{
BYTE chr_bank = ( Map243_Regs[2] + Map243_Regs[3] ) >> 1;
PPUBANK[ 0 ] = VROMPAGE( ( chr_bank * 8 + 0 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 1 ] = VROMPAGE( ( chr_bank * 8 + 1 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 2 ] = VROMPAGE( ( chr_bank * 8 + 2 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 3 ] = VROMPAGE( ( chr_bank * 8 + 3 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 4 ] = VROMPAGE( ( chr_bank * 8 + 4 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 5 ] = VROMPAGE( ( chr_bank * 8 + 5 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 6 ] = VROMPAGE( ( chr_bank * 8 + 6 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 7 ] = VROMPAGE( ( chr_bank * 8 + 7 ) % ( NesHeader.byVRomSize << 3 ) );
InfoNES_SetupChr();
}
else
{
BYTE chr_bank = Map243_Regs[1] + Map243_Regs[2] + Map243_Regs[3];
PPUBANK[ 0 ] = VROMPAGE( ( chr_bank * 8 + 0 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 1 ] = VROMPAGE( ( chr_bank * 8 + 1 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 2 ] = VROMPAGE( ( chr_bank * 8 + 2 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 3 ] = VROMPAGE( ( chr_bank * 8 + 3 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 4 ] = VROMPAGE( ( chr_bank * 8 + 4 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 5 ] = VROMPAGE( ( chr_bank * 8 + 5 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 6 ] = VROMPAGE( ( chr_bank * 8 + 6 ) % ( NesHeader.byVRomSize << 3 ) );
PPUBANK[ 7 ] = VROMPAGE( ( chr_bank * 8 + 7 ) % ( NesHeader.byVRomSize << 3 ) );
InfoNES_SetupChr();
}
}
}
| 0 | 0.908911 | 1 | 0.908911 | game-dev | MEDIA | 0.396689 | game-dev,embedded-firmware | 0.969607 | 1 | 0.969607 |
ratrecommends/dice-heroes | 1,822 | main/src/com/vlaaad/dice/game/requirements/DieRequirement.java | /*
* Dice heroes is a turn based rpg-strategy game where characters are dice.
* Copyright (C) 2016 Vladislav Protsenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vlaaad.dice.game.requirements;
import com.vlaaad.dice.game.user.Die;
/**
* Created 06.10.13 by vlaaad
*/
public abstract class DieRequirement {
public static final DieRequirement ANY = new DieRequirement() {
@Override protected void doInit(Object setup) { }
@Override public boolean isSatisfied(Die die) { return true; }
@Override public boolean canBeSatisfied(Die die) { return true; }
@Override public String toString() { return "any"; }
@Override public String describe(Die die) { return ""; }
};
private Object config;
public final DieRequirement init(Object setup) {
config = setup;
doInit(setup);
return this;
}
public final Object getConfig() {
return config;
}
protected abstract void doInit(Object setup);
public abstract boolean isSatisfied(Die die);
public abstract boolean canBeSatisfied(Die die);
@Override public abstract String toString();
public abstract String describe(Die die);
}
| 0 | 0.648348 | 1 | 0.648348 | game-dev | MEDIA | 0.923047 | game-dev | 0.710901 | 1 | 0.710901 |
SuperNewRoles/SuperNewRoles | 24,352 | SuperNewRoles/CustomOptions/GhostOptionMenu.cs | using System.Collections.Generic;
using HarmonyLib;
using SuperNewRoles.Modules;
using SuperNewRoles.Roles;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using System.Linq;
using System;
using SuperNewRoles.CustomOptions.Data;
namespace SuperNewRoles.CustomOptions;
public static class GhostOptionMenu
{
private const string GHOST_OPTION_MENU_ASSET_NAME = "RoleOptionMenu";
public const string GHOST_ROLE_DETAIL_BUTTON_ASSET_NAME = "RoleDetailButton";
public static void ShowGhostOptionMenu()
{
if (GhostOptionMenuObjectData.Instance?.MenuObject == null)
InitializeGhostOptionMenu();
GhostOptionMenuObjectData.Instance.MenuObject?.SetActive(true);
UpdateMenuTitle();
UpdateGhostRoleButtons();
HideRightSettings();
}
public static void HideGhostOptionMenu()
{
GhostOptionMenuObjectData.Instance?.MenuObject.SetActive(false);
}
private static void InitializeGhostOptionMenu()
{
var gameSettingMenu = GameObject.FindObjectOfType<GameSettingMenu>();
var menuObject = GameObject.Instantiate(AssetManager.GetAsset<GameObject>(GHOST_OPTION_MENU_ASSET_NAME));
menuObject.transform.SetParent(gameSettingMenu.transform);
menuObject.transform.localScale = Vector3.one * 0.2f;
menuObject.transform.localPosition = new(0, 0, -1f);
var data = new GhostOptionMenuObjectData(menuObject);
(data.Scroller, data.InnerScroll) = CreateScrollbar(menuObject.transform);
data.InnerScroll.transform.localPosition = new Vector3(data.InnerScroll.transform.localPosition.x, 0f, 0.2f);
// 右側設定エリアのキャッシュ
data.SettingsScroller = menuObject.transform.Find("SettingsScroller")?.GetComponent<Scroller>();
data.SettingsInner = menuObject.transform.Find("SettingsScroller/InnerContent");
}
private static (Scroller, GameObject) CreateScrollbar(Transform parent)
{
var gameSettingMenu = GameObject.FindObjectOfType<GameSettingMenu>();
if (gameSettingMenu == null) return (null, null);
var gameSettingsTab = gameSettingMenu.GameSettingsTab;
if (gameSettingsTab == null) return (null, null);
var tabCopy = GameObject.Instantiate(gameSettingsTab.gameObject, parent, false);
tabCopy.transform.localScale = Vector3.one * 5.3f;
tabCopy.transform.localPosition = new Vector3(-30.7f, 12f, 0f);
tabCopy.gameObject.SetActive(true);
var Gradient = tabCopy.transform.Find("Gradient");
if (Gradient != null)
{
Gradient.transform.localPosition = new(5.77f, -3.98f, -20f);
Gradient.transform.localScale = new(0.774f, 0.6f, 7.2125f);
}
var closeButton = tabCopy.transform.Find("CloseButton");
if (closeButton != null)
GameObject.Destroy(closeButton.gameObject);
var scrollInner = tabCopy.transform.Find("Scroller/SliderInner");
if (scrollInner != null)
{
var wasActive = scrollInner.gameObject.activeSelf;
scrollInner.gameObject.SetActive(false);
for (int i = scrollInner.childCount - 1; i >= 0; i--)
{
var child = scrollInner.GetChild(i);
child.SetParent(null);
GameObject.Destroy(child.gameObject);
}
scrollInner.gameObject.SetActive(wasActive);
}
var scroller = tabCopy.GetComponentInChildren<Scroller>();
var innerscroll = tabCopy.transform.Find("Scroller/SliderInner").gameObject;
return (scroller, innerscroll);
}
private static void UpdateMenuTitle()
{
var data = GhostOptionMenuObjectData.Instance;
if (data?.TitleText != null)
data.TitleText.text = $"{ModTranslation.GetString($"RoleOptionMenuType.Ghost")}";
}
private static void UpdateGhostRoleButtons()
{
var data = GhostOptionMenuObjectData.Instance;
for (int i = data.InnerScroll.transform.childCount - 1; i >= 0; i--)
{
GameObject.Destroy(data.InnerScroll.transform.GetChild(i).gameObject);
}
data.GhostRoleButtonDictionary.Clear();
var ghostRoleOptions = RoleOptionManager.GhostRoleOptions;
int index = 0;
foreach (var ghostRoleOption in ghostRoleOptions)
{
var roleBase = CustomRoleManager.AllGhostRoles.FirstOrDefault(r => r.Role == ghostRoleOption.RoleId);
if (roleBase == null) continue;
if (roleBase.HiddenOption) continue;
string roleName = ModTranslation.GetString($"{roleBase.Role}");
var obj = GameObject.Instantiate(AssetManager.GetAsset<GameObject>(GHOST_ROLE_DETAIL_BUTTON_ASSET_NAME));
obj.transform.SetParent(data.InnerScroll.transform);
obj.transform.localScale = Vector3.one * 0.31f;
int col = index % 4;
int row = index / 4;
float posX = -1.27f + col * 1.63f;
float posY = 0.85f - row * 0.38f;
obj.transform.localPosition = new Vector3(posX, posY, -0.21f);
obj.transform.Find("Text").GetComponent<TextMeshPro>().text = $"<b><color=#{ColorUtility.ToHtmlStringRGB(ghostRoleOption.RoleColor)}>{roleName}</color></b>";
var passiveButton = obj.AddComponent<PassiveButton>();
passiveButton.Colliders = new Collider2D[1];
passiveButton.Colliders[0] = obj.GetComponent<BoxCollider2D>();
passiveButton.OnClick = new();
GameObject SelectedObject = null;
var spriteRenderer = obj.GetComponent<SpriteRenderer>();
UpdateRoleDetailButtonColor(spriteRenderer, ghostRoleOption);
passiveButton.OnClick.AddListener((UnityAction)(() =>
{
ClickedGhostRole(spriteRenderer, ghostRoleOption);
}));
// 右クリック検知用のコンポーネントを追加し、イベントを登録
var rightClickDetector = obj.AddComponent<RightClickDetector>();
rightClickDetector.OnRightClick.AddListener((UnityAction)(() =>
{
// 対象が有効のとき
if (ghostRoleOption.NumberOfCrews >= 1)
{
ghostRoleOption.NumberOfCrews = 0;
ghostRoleOption.Percentage = 0;
}
else
{
// デフォルト値を設定(必要に応じて調整してください)
ghostRoleOption.NumberOfCrews = 1;
ghostRoleOption.Percentage = 100;
}
UpdateRoleDetailButtonColor(spriteRenderer, ghostRoleOption);
// 変更を同期
RoleOptionManager.RpcSyncGhostRoleOptionDelay(ghostRoleOption.RoleId, ghostRoleOption.NumberOfCrews, ghostRoleOption.Percentage);
// 右側の設定も更新
if (data.CurrentGhostRoleId == ghostRoleOption.RoleId)
{
ShowRightSettings(spriteRenderer, ghostRoleOption); // 右側の設定UIを再描画
}
}));
passiveButton.OnMouseOut = new();
passiveButton.OnMouseOut.AddListener((UnityAction)(() =>
{
if (SelectedObject == null)
SelectedObject = obj.transform.FindChild("Selected").gameObject;
SelectedObject.SetActive(false);
}));
passiveButton.OnMouseOver = new();
passiveButton.OnMouseOver.AddListener((UnityAction)(() =>
{
if (SelectedObject == null)
SelectedObject = obj.transform.FindChild("Selected").gameObject;
SelectedObject.SetActive(true);
}));
data.GhostRoleButtonDictionary[ghostRoleOption.RoleId] = obj;
index++;
}
data.Scroller.ContentYBounds.max = index < 25 ? 0f : (0.38f * ((index - 24) / 4 + 1)) - 0.5f;
data.Scroller.UpdateScrollBars();
}
private static void UpdateRoleDetailButtonColor(SpriteRenderer spriteRenderer, RoleOptionManager.GhostRoleOption ghostRoleOption)
{
if (ghostRoleOption == null) throw new Exception("ghostRoleOption is null");
if (spriteRenderer == null) throw new Exception("spriteRenderer is null");
if (ghostRoleOption.NumberOfCrews > 0 && ghostRoleOption.Percentage > 0)
spriteRenderer.color = Color.white;
else
spriteRenderer.color = new Color(1, 1f, 1f, 0.6f);
}
private static void ClickedGhostRole(SpriteRenderer spriteRenderer, RoleOptionManager.GhostRoleOption ghostRoleOption)
{
var data = GhostOptionMenuObjectData.Instance;
data.CurrentGhostRoleId = ghostRoleOption.RoleId;
ShowRightSettings(spriteRenderer, ghostRoleOption);
}
private static void ShowRightSettings(SpriteRenderer spriteRenderer, RoleOptionManager.GhostRoleOption ghostRoleOption)
{
var data = GhostOptionMenuObjectData.Instance;
// 既存の設定UIを破棄
if (data.CurrentSettingsParent != null)
GameObject.Destroy(data.CurrentSettingsParent);
data.CurrentOptionDisplays.Clear();
float lastY = 4f;
// 親オブジェクト生成
data.CurrentSettingsParent = new GameObject("Parent");
data.CurrentSettingsParent.transform.SetParent(data.SettingsInner);
data.CurrentSettingsParent.transform.localScale = Vector3.one;
data.CurrentSettingsParent.transform.localPosition = Vector3.zero;
data.CurrentSettingsParent.layer = 5;
// 人数・確率セレクタ
CreateNumberOfCrewsSelectAndPerSelect(spriteRenderer, data.CurrentSettingsParent.transform, ghostRoleOption, ref lastY);
int index = 2;
// カスタムオプション
foreach (var option in ghostRoleOption.Options)
{
if (option.IsBooleanOption)
CreateCheckBox(data.CurrentSettingsParent.transform, option, ref lastY);
else
CreateSelect(data.CurrentSettingsParent.transform, option, ref lastY);
index++;
}
foreach (var option in ghostRoleOption.Options)
{
if (option.ParentOption == null)
UpdateOptionsActive(data.CurrentSettingsParent.transform, option);
}
// スクロール位置リセット
if (data.SettingsInner != null && data.SettingsScroller != null)
{
data.SettingsInner.localPosition = new Vector3(data.SettingsInner.localPosition.x, 0f, data.SettingsInner.localPosition.z);
data.SettingsScroller.UpdateScrollBars();
}
// スクロールバー範囲調整
if (data.SettingsScroller != null)
{
data.SettingsScroller.ContentYBounds.max = index < 4 ? 0.1f : index == 4 ? 2.1f : (index - 4) * 4.5f + 2f;
data.SettingsScroller.UpdateScrollBars();
}
}
private static void HideRightSettings()
{
var data = GhostOptionMenuObjectData.Instance;
if (data.CurrentSettingsParent != null)
GameObject.Destroy(data.CurrentSettingsParent);
data.CurrentOptionDisplays.Clear();
}
// --- 以下、UI生成ヘルパー ---
private static GameObject CreateCheckBox(Transform parent, CustomOption option, ref float lastY)
{
var data = GhostOptionMenuObjectData.Instance;
GameObject optionInstance = CreateOptionElement(parent, ModTranslation.GetString(option.Name), ref lastY, "Option_Check");
var passiveButton = optionInstance.AddComponent<PassiveButton>();
var checkMark = optionInstance.transform.Find("CheckMark");
SetupCheckBoxButton(passiveButton, checkMark, option);
passiveButton.Colliders = new[] { optionInstance.GetComponent<BoxCollider2D>() };
var checkMarkTMP = checkMark.gameObject.AddComponent<TextMeshPro>();
data.CurrentOptionDisplays.Add((checkMarkTMP, option));
return optionInstance;
}
private static void SetupCheckBoxButton(PassiveButton passiveButton, Transform checkMark, CustomOption option)
{
checkMark.gameObject.SetActive((bool)option.Value);
var spriteRenderer = passiveButton.GetComponent<SpriteRenderer>();
ConfigurePassiveButton(passiveButton, () =>
{
bool newValue = !checkMark.gameObject.activeSelf;
checkMark.gameObject.SetActive(newValue);
option.UpdateSelection(newValue ? (byte)1 : (byte)0);
UpdateDisplayAfterOptionChange(passiveButton.transform.parent, option);
if (AmongUsClient.Instance.AmHost)
CustomOptionManager.RpcSyncOption(option.Id, newValue ? (byte)1 : (byte)0);
}, spriteRenderer);
}
private static GameObject CreateSelect(Transform parent, CustomOption option, ref float lastY)
{
var data = GhostOptionMenuObjectData.Instance;
GameObject optionInstance = CreateOptionElement(parent, ModTranslation.GetString(option.Name), ref lastY, "Option_Select");
var selectedText = optionInstance.transform.Find("SelectedText").GetComponent<TextMeshPro>();
selectedText.text = UIHelper.FormatOptionValue(option.Selections[option.Selection], option);
SetupSelectButtons(optionInstance, selectedText, option);
data.CurrentOptionDisplays.Add((selectedText, option));
return optionInstance;
}
private static void SetupSelectButtons(GameObject optionInstance, TextMeshPro selectedText, CustomOption option)
{
SetupMinusButton(optionInstance, selectedText, option);
SetupPlusButton(optionInstance, selectedText, option);
}
private static void SetupMinusButton(GameObject optionInstance, TextMeshPro selectedText, CustomOption option)
{
var minusButton = optionInstance.transform.Find("Button_Minus").gameObject;
var passiveButton = minusButton.AddComponent<PassiveButton>();
var spriteRenderer = passiveButton.GetComponent<SpriteRenderer>();
ConfigurePassiveButton(passiveButton, () =>
{
byte newSelection = option.Selection > 0 ? (byte)(option.Selection - 1) : (byte)(option.Selections.Length - 1);
option.UpdateSelection(newSelection);
selectedText.text = UIHelper.FormatOptionValue(option.Selections[option.Selection], option);
UpdateDisplayAfterOptionChange(selectedText.transform.parent.parent, option);
if (AmongUsClient.Instance.AmHost)
CustomOptionManager.RpcSyncOption(option.Id, newSelection);
}, spriteRenderer);
}
private static void SetupPlusButton(GameObject optionInstance, TextMeshPro selectedText, CustomOption option)
{
var plusButton = optionInstance.transform.Find("Button_Plus").gameObject;
var passiveButton = plusButton.AddComponent<PassiveButton>();
var spriteRenderer = passiveButton.GetComponent<SpriteRenderer>();
ConfigurePassiveButton(passiveButton, () =>
{
byte newSelection = 0;
if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
{
newSelection = (byte)(option.Selections.Length - 1);
}
else
{
int additional = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) ? RoleOptionSettings.ShiftSelection : 1;
newSelection = option.Selection + additional < option.Selections.Length ? (byte)(option.Selection + additional) : (byte)0;
}
option.UpdateSelection(newSelection);
selectedText.text = UIHelper.FormatOptionValue(option.Selections[option.Selection], option);
UpdateDisplayAfterOptionChange(selectedText.transform.parent.parent, option);
if (AmongUsClient.Instance.AmHost)
CustomOptionManager.RpcSyncOption(option.Id, newSelection);
}, spriteRenderer);
}
private static void UpdateDisplayAfterOptionChange(Transform parentTransform, CustomOption changedOption)
{
// 子オプションを持つ場合のみ表示状態を更新
if ((changedOption.ChildrenOption != null && changedOption.ChildrenOption.Count > 0) || changedOption.ParentOption != null)
{
Transform topParent = FindTopParent(parentTransform);
UpdateOptionsActive(topParent, changedOption);
RecalculateOptionsPosition(topParent, GhostOptionMenuObjectData.Instance.SettingsScroller);
}
}
private static Transform FindTopParent(Transform transform)
{
Transform current = transform;
while (current.parent != null && current.parent.name != "InnerContent" && current.parent.name != "SettingsScroller")
{
current = current.parent;
}
return current;
}
private static void UpdateOptionsActive(Transform parentTransform, CustomOption changedOption)
{
for (int i = 0; i < parentTransform.childCount; i++)
{
var child = parentTransform.GetChild(i);
var textComp = child.Find("Text")?.GetComponent<TextMeshPro>();
if (textComp != null && ModTranslation.GetString(changedOption.Name) == textComp.text)
{
child.gameObject.SetActive(changedOption.ShouldDisplay());
}
}
if (changedOption.ChildrenOption != null)
{
foreach (var childOption in changedOption.ChildrenOption)
{
UpdateOptionsActive(parentTransform, childOption);
}
}
}
private static void RecalculateOptionsPosition(Transform parentTransform, Scroller scroller)
{
float lastY = 4f;
int activeCount = 0;
for (int i = 0; i < parentTransform.childCount; i++)
{
Transform child = parentTransform.GetChild(i);
if (!child.gameObject.activeSelf)
continue;
child.localPosition = new Vector3(-0.22f, lastY, -5f);
lastY -= 4.5f;
activeCount++;
}
if (scroller != null)
{
scroller.ContentYBounds.max = activeCount <= 4 ? 0.1f : (activeCount - 4) * 4.5f + 2f;
scroller.UpdateScrollBars();
}
}
private static GameObject CreateOptionElement(Transform parent, string optionName, ref float lastY, string prefabName)
{
var optionPrefab = AssetManager.GetAsset<GameObject>(prefabName);
var optionInstance = UnityEngine.Object.Instantiate(optionPrefab, parent);
optionInstance.transform.localPosition = new Vector3(-0.22f, lastY, -5f);
lastY -= 4.5f;
optionInstance.transform.localScale = Vector3.one * 2f;
optionInstance.transform.Find("Text").GetComponent<TextMeshPro>().text = optionName;
return optionInstance;
}
private static GameObject CreateNumberOfCrewsSelectAndPerSelect(SpriteRenderer spriteRenderer, Transform parent, RoleOptionManager.GhostRoleOption ghostRoleOption, ref float lastY)
{
var data = GhostOptionMenuObjectData.Instance;
GameObject optionInstance = CreateOptionElement(parent, ModTranslation.GetString("NumberOfCrews"), ref lastY, "Option_Select");
var selectedText = optionInstance.transform.Find("SelectedText").GetComponent<TextMeshPro>();
selectedText.text = ModTranslation.GetString("NumberOfCrewsSelected", ghostRoleOption.NumberOfCrews);
var minusButton = optionInstance.transform.Find("Button_Minus").gameObject;
var minusPassiveButton = minusButton.AddComponent<PassiveButton>();
var minusSpriteRenderer = minusPassiveButton.GetComponent<SpriteRenderer>();
ConfigurePassiveButton(minusPassiveButton, () =>
{
byte playerCount = 15;
ghostRoleOption.NumberOfCrews--;
if (ghostRoleOption.NumberOfCrews < 0)
ghostRoleOption.NumberOfCrews = playerCount;
if (ghostRoleOption.NumberOfCrews > playerCount)
ghostRoleOption.NumberOfCrews = playerCount;
selectedText.text = ModTranslation.GetString("NumberOfCrewsSelected", ghostRoleOption.NumberOfCrews);
UpdateRoleDetailButtonColor(spriteRenderer, ghostRoleOption);
RoleOptionManager.RpcSyncGhostRoleOptionDelay(ghostRoleOption.RoleId, ghostRoleOption.NumberOfCrews, ghostRoleOption.Percentage);
}, minusSpriteRenderer);
var plusButton = optionInstance.transform.Find("Button_Plus").gameObject;
var plusPassiveButton = plusButton.AddComponent<PassiveButton>();
var plusSpriteRenderer = plusPassiveButton.GetComponent<SpriteRenderer>();
ConfigurePassiveButton(plusPassiveButton, () =>
{
byte playerCount = 15;
byte oldValue = ghostRoleOption.NumberOfCrews;
ghostRoleOption.NumberOfCrews++;
if (ghostRoleOption.NumberOfCrews > playerCount)
ghostRoleOption.NumberOfCrews = 0;
if (oldValue == 0 && ghostRoleOption.NumberOfCrews > 0 && ghostRoleOption.Percentage == 0)
{
ghostRoleOption.Percentage = 100;
}
selectedText.text = ModTranslation.GetString("NumberOfCrewsSelected", ghostRoleOption.NumberOfCrews);
UpdateRoleDetailButtonColor(spriteRenderer, ghostRoleOption);
RoleOptionManager.RpcSyncGhostRoleOptionDelay(ghostRoleOption.RoleId, ghostRoleOption.NumberOfCrews, ghostRoleOption.Percentage);
}, plusSpriteRenderer);
// 確率設定
var perOption = CreateAssignPerSelect(parent, ghostRoleOption, ref lastY);
var percentageText = perOption.transform.Find("SelectedText").GetComponent<TextMeshPro>();
data.CurrentRoleNumbersOfCrewsText = selectedText;
data.CurrentRolePercentageText = percentageText;
return optionInstance;
}
private static GameObject CreateAssignPerSelect(Transform parent, RoleOptionManager.GhostRoleOption ghostRoleOption, ref float lastY)
{
GameObject optionInstance = CreateOptionElement(parent, ModTranslation.GetString("AssignPer"), ref lastY, "Option_Select");
var selectedText = optionInstance.transform.Find("SelectedText").GetComponent<TextMeshPro>();
selectedText.text = ghostRoleOption.Percentage + "%";
var minusButton = optionInstance.transform.Find("Button_Minus").gameObject;
var minusPassiveButton = minusButton.AddComponent<PassiveButton>();
var minusSpriteRenderer = minusPassiveButton.GetComponent<SpriteRenderer>();
ConfigurePassiveButton(minusPassiveButton, () =>
{
ghostRoleOption.Percentage -= 10;
if (ghostRoleOption.Percentage < 0)
ghostRoleOption.Percentage = 100;
if (ghostRoleOption.Percentage > 100)
ghostRoleOption.Percentage = 100;
selectedText.text = ghostRoleOption.Percentage + "%";
RoleOptionManager.RpcSyncGhostRoleOptionDelay(ghostRoleOption.RoleId, ghostRoleOption.NumberOfCrews, ghostRoleOption.Percentage);
}, minusSpriteRenderer);
var plusButton = optionInstance.transform.Find("Button_Plus").gameObject;
var plusPassiveButton = plusButton.AddComponent<PassiveButton>();
var plusSpriteRenderer = plusPassiveButton.GetComponent<SpriteRenderer>();
ConfigurePassiveButton(plusPassiveButton, () =>
{
ghostRoleOption.Percentage += 10;
if (ghostRoleOption.Percentage > 100)
ghostRoleOption.Percentage = 0;
selectedText.text = ghostRoleOption.Percentage + "%";
RoleOptionManager.RpcSyncGhostRoleOptionDelay(ghostRoleOption.RoleId, ghostRoleOption.NumberOfCrews, ghostRoleOption.Percentage);
}, plusSpriteRenderer);
return optionInstance;
}
private static void ConfigurePassiveButton(PassiveButton button, Action onClick, SpriteRenderer spriteRenderer = null)
{
button.OnClick = new();
button.OnClick.AddListener(onClick);
button.OnMouseOver = new();
button.OnMouseOver.AddListener((UnityAction)(() =>
{
if (spriteRenderer != null)
spriteRenderer.color = new Color32(45, 235, 198, 255);
}));
button.OnMouseOut = new();
button.OnMouseOut.AddListener((UnityAction)(() =>
{
if (spriteRenderer != null)
spriteRenderer.color = Color.white;
}));
}
} | 0 | 0.872501 | 1 | 0.872501 | game-dev | MEDIA | 0.959573 | game-dev | 0.926909 | 1 | 0.926909 |
PrismLauncher/PrismLauncher | 12,478 | launcher/minecraft/auth/AccountData.cpp | // SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "AccountData.h"
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUuid>
namespace {
void tokenToJSONV3(QJsonObject& parent, const Token& t, const char* tokenName)
{
if (!t.persistent) {
return;
}
QJsonObject out;
if (t.issueInstant.isValid()) {
out["iat"] = QJsonValue(t.issueInstant.toMSecsSinceEpoch() / 1000);
}
if (t.notAfter.isValid()) {
out["exp"] = QJsonValue(t.notAfter.toMSecsSinceEpoch() / 1000);
}
bool save = false;
if (!t.token.isEmpty()) {
out["token"] = QJsonValue(t.token);
save = true;
}
if (!t.refresh_token.isEmpty()) {
out["refresh_token"] = QJsonValue(t.refresh_token);
save = true;
}
if (t.extra.size()) {
out["extra"] = QJsonObject::fromVariantMap(t.extra);
save = true;
}
if (save) {
parent[tokenName] = out;
}
}
Token tokenFromJSONV3(const QJsonObject& parent, const char* tokenName)
{
Token out;
auto tokenObject = parent.value(tokenName).toObject();
if (tokenObject.isEmpty()) {
return out;
}
auto issueInstant = tokenObject.value("iat");
if (issueInstant.isDouble()) {
out.issueInstant = QDateTime::fromMSecsSinceEpoch(((int64_t)issueInstant.toDouble()) * 1000);
}
auto notAfter = tokenObject.value("exp");
if (notAfter.isDouble()) {
out.notAfter = QDateTime::fromMSecsSinceEpoch(((int64_t)notAfter.toDouble()) * 1000);
}
auto token = tokenObject.value("token");
if (token.isString()) {
out.token = token.toString();
out.validity = Validity::Assumed;
}
auto refresh_token = tokenObject.value("refresh_token");
if (refresh_token.isString()) {
out.refresh_token = refresh_token.toString();
}
auto extra = tokenObject.value("extra");
if (extra.isObject()) {
out.extra = extra.toObject().toVariantMap();
}
return out;
}
void profileToJSONV3(QJsonObject& parent, MinecraftProfile p, const char* tokenName)
{
if (p.id.isEmpty()) {
return;
}
QJsonObject out;
out["id"] = QJsonValue(p.id);
out["name"] = QJsonValue(p.name);
if (!p.currentCape.isEmpty()) {
out["cape"] = p.currentCape;
}
{
QJsonObject skinObj;
skinObj["id"] = p.skin.id;
skinObj["url"] = p.skin.url;
skinObj["variant"] = p.skin.variant;
if (p.skin.data.size()) {
skinObj["data"] = QString::fromLatin1(p.skin.data.toBase64());
}
out["skin"] = skinObj;
}
QJsonArray capesArray;
for (auto& cape : p.capes) {
QJsonObject capeObj;
capeObj["id"] = cape.id;
capeObj["url"] = cape.url;
capeObj["alias"] = cape.alias;
if (cape.data.size()) {
capeObj["data"] = QString::fromLatin1(cape.data.toBase64());
}
capesArray.push_back(capeObj);
}
out["capes"] = capesArray;
parent[tokenName] = out;
}
MinecraftProfile profileFromJSONV3(const QJsonObject& parent, const char* tokenName)
{
MinecraftProfile out;
auto tokenObject = parent.value(tokenName).toObject();
if (tokenObject.isEmpty()) {
return out;
}
{
auto idV = tokenObject.value("id");
auto nameV = tokenObject.value("name");
if (!idV.isString() || !nameV.isString()) {
qWarning() << "mandatory profile attributes are missing or of unexpected type";
return MinecraftProfile();
}
out.name = nameV.toString();
out.id = idV.toString();
}
{
auto skinV = tokenObject.value("skin");
if (!skinV.isObject()) {
qWarning() << "skin is missing";
return MinecraftProfile();
}
auto skinObj = skinV.toObject();
auto idV = skinObj.value("id");
auto urlV = skinObj.value("url");
auto variantV = skinObj.value("variant");
if (!idV.isString() || !urlV.isString() || !variantV.isString()) {
qWarning() << "mandatory skin attributes are missing or of unexpected type";
return MinecraftProfile();
}
out.skin.id = idV.toString();
out.skin.url = urlV.toString();
out.skin.url.replace("http://textures.minecraft.net", "https://textures.minecraft.net");
out.skin.variant = variantV.toString();
// data for skin is optional
auto dataV = skinObj.value("data");
if (dataV.isString()) {
// TODO: validate base64
out.skin.data = QByteArray::fromBase64(dataV.toString().toLatin1());
} else if (!dataV.isUndefined()) {
qWarning() << "skin data is something unexpected";
return MinecraftProfile();
}
}
{
auto capesV = tokenObject.value("capes");
if (!capesV.isArray()) {
qWarning() << "capes is not an array!";
return MinecraftProfile();
}
auto capesArray = capesV.toArray();
for (auto capeV : capesArray) {
if (!capeV.isObject()) {
qWarning() << "cape is not an object!";
return MinecraftProfile();
}
auto capeObj = capeV.toObject();
auto idV = capeObj.value("id");
auto urlV = capeObj.value("url");
auto aliasV = capeObj.value("alias");
if (!idV.isString() || !urlV.isString() || !aliasV.isString()) {
qWarning() << "mandatory skin attributes are missing or of unexpected type";
return MinecraftProfile();
}
Cape cape;
cape.id = idV.toString();
cape.url = urlV.toString();
cape.url.replace("http://textures.minecraft.net", "https://textures.minecraft.net");
cape.alias = aliasV.toString();
// data for cape is optional.
auto dataV = capeObj.value("data");
if (dataV.isString()) {
// TODO: validate base64
cape.data = QByteArray::fromBase64(dataV.toString().toLatin1());
} else if (!dataV.isUndefined()) {
qWarning() << "cape data is something unexpected";
return MinecraftProfile();
}
out.capes[cape.id] = cape;
}
}
// current cape
{
auto capeV = tokenObject.value("cape");
if (capeV.isString()) {
auto currentCape = capeV.toString();
if (out.capes.contains(currentCape)) {
out.currentCape = currentCape;
}
}
}
out.validity = Validity::Assumed;
return out;
}
void entitlementToJSONV3(QJsonObject& parent, MinecraftEntitlement p)
{
if (p.validity == Validity::None) {
return;
}
QJsonObject out;
out["ownsMinecraft"] = QJsonValue(p.ownsMinecraft);
out["canPlayMinecraft"] = QJsonValue(p.canPlayMinecraft);
parent["entitlement"] = out;
}
bool entitlementFromJSONV3(const QJsonObject& parent, MinecraftEntitlement& out)
{
auto entitlementObject = parent.value("entitlement").toObject();
if (entitlementObject.isEmpty()) {
return false;
}
{
auto ownsMinecraftV = entitlementObject.value("ownsMinecraft");
auto canPlayMinecraftV = entitlementObject.value("canPlayMinecraft");
if (!ownsMinecraftV.isBool() || !canPlayMinecraftV.isBool()) {
qWarning() << "mandatory attributes are missing or of unexpected type";
return false;
}
out.canPlayMinecraft = canPlayMinecraftV.toBool(false);
out.ownsMinecraft = ownsMinecraftV.toBool(false);
out.validity = Validity::Assumed;
}
return true;
}
} // namespace
bool AccountData::resumeStateFromV3(QJsonObject data)
{
auto typeV = data.value("type");
if (!typeV.isString()) {
qWarning() << "Failed to parse account data: type is missing.";
return false;
}
auto typeS = typeV.toString();
if (typeS == "MSA") {
type = AccountType::MSA;
} else if (typeS == "Offline") {
type = AccountType::Offline;
} else {
qWarning() << "Failed to parse account data: type is not recognized.";
return false;
}
if (type == AccountType::MSA) {
auto clientIDV = data.value("msa-client-id");
if (clientIDV.isString()) {
msaClientID = clientIDV.toString();
} // leave msaClientID empty if it doesn't exist or isn't a string
msaToken = tokenFromJSONV3(data, "msa");
userToken = tokenFromJSONV3(data, "utoken");
xboxApiToken = tokenFromJSONV3(data, "xrp-main");
mojangservicesToken = tokenFromJSONV3(data, "xrp-mc");
}
yggdrasilToken = tokenFromJSONV3(data, "ygg");
// versions before 7.2 used "offline" as the offline token
if (yggdrasilToken.token == "offline")
yggdrasilToken.token = "0";
minecraftProfile = profileFromJSONV3(data, "profile");
if (!entitlementFromJSONV3(data, minecraftEntitlement)) {
if (minecraftProfile.validity != Validity::None) {
minecraftEntitlement.canPlayMinecraft = true;
minecraftEntitlement.ownsMinecraft = true;
minecraftEntitlement.validity = Validity::Assumed;
}
}
validity_ = minecraftProfile.validity;
return true;
}
QJsonObject AccountData::saveState() const
{
QJsonObject output;
if (type == AccountType::MSA) {
output["type"] = "MSA";
output["msa-client-id"] = msaClientID;
tokenToJSONV3(output, msaToken, "msa");
tokenToJSONV3(output, userToken, "utoken");
tokenToJSONV3(output, xboxApiToken, "xrp-main");
tokenToJSONV3(output, mojangservicesToken, "xrp-mc");
} else if (type == AccountType::Offline) {
output["type"] = "Offline";
}
tokenToJSONV3(output, yggdrasilToken, "ygg");
profileToJSONV3(output, minecraftProfile, "profile");
entitlementToJSONV3(output, minecraftEntitlement);
return output;
}
QString AccountData::accessToken() const
{
return yggdrasilToken.token;
}
QString AccountData::profileId() const
{
return minecraftProfile.id;
}
QString AccountData::profileName() const
{
if (minecraftProfile.name.size() == 0) {
return QObject::tr("No profile (%1)").arg(accountDisplayString());
} else {
return minecraftProfile.name;
}
}
QString AccountData::accountDisplayString() const
{
switch (type) {
case AccountType::Offline: {
return QObject::tr("<Offline>");
}
case AccountType::MSA: {
if (xboxApiToken.extra.contains("gtg")) {
return xboxApiToken.extra["gtg"].toString();
}
return "Xbox profile missing";
}
default: {
return "Invalid Account";
}
}
}
QString AccountData::lastError() const
{
return errorString;
}
| 0 | 0.723975 | 1 | 0.723975 | game-dev | MEDIA | 0.425675 | game-dev,graphics-rendering | 0.951542 | 1 | 0.951542 |
tgstation/TerraGov-Marine-Corps | 15,348 | code/datums/elements/strippable.dm | /// An element for atoms that, when dragged and dropped onto a mob, opens a strip panel.
/datum/element/strippable
element_flags = ELEMENT_BESPOKE | ELEMENT_DETACH_ON_HOST_DESTROY
argument_hash_start_idx = 2
/// An assoc list of keys to /datum/strippable_item
var/list/items
/// An optional list of lists of strippable_item_layout to order the slots in.
/// Nested lists are used to indicate sections which will be spaced out in the interface.
var/list/layout
/// An existing strip menus
var/list/strip_menus
/datum/element/strippable/Attach(datum/target, list/_items, list/_layout)
. = ..()
if(!isatom(target))
return ELEMENT_INCOMPATIBLE
RegisterSignal(target, COMSIG_MOUSEDROP_ONTO, PROC_REF(mouse_drop_onto))
items = _items
layout = _layout
/datum/element/strippable/Detach(datum/source, force)
. = ..()
UnregisterSignal(source, COMSIG_MOUSEDROP_ONTO)
if(!isnull(strip_menus))
qdel(strip_menus[source])
strip_menus -= source
/datum/element/strippable/proc/mouse_drop_onto(datum/source, atom/over, mob/user)
SIGNAL_HANDLER
if(user == source)
return
if(over != user)
return
if(isxeno(user))
return //bad
var/datum/strip_menu/strip_menu = LAZYACCESS(strip_menus, source)
if(isnull(strip_menu))
strip_menu = new(source, src)
LAZYSET(strip_menus, source, strip_menu)
INVOKE_ASYNC(strip_menu, TYPE_PROC_REF(/datum, ui_interact), user)
/datum/strippable_item_layout
/// The STRIPPABLE_ITEM_* key
var/key
/// Is the slot dependent on the last non-indented slot?
var/indented
/datum/strippable_item_layout/New(_key, _indented)
key = _key
indented = _indented
/// A representation of an item that can be stripped down
/datum/strippable_item
/// The STRIPPABLE_ITEM_* key
var/key
/datum/strippable_item/proc/is_incorporeal(mob/user)
if(isliving(user))
var/mob/living/L = user
if(CHECK_BITFIELD(L.status_flags, INCORPOREAL)) // Mobs that can walk through walls cannot grasp items to strip
to_chat(user, "<span class='warning'>You can't interact with the physical plane while you are incorporeal!</span>")
return FALSE
return TRUE
else
return FALSE // Mobs that are not living cannot strip
/// Gets the item from the given source.
/datum/strippable_item/proc/get_item(atom/source)
/// Tries to equip the item onto the given source.
/// Returns TRUE/FALSE depending on if it is allowed.
/// This should be used for checking if an item CAN be equipped.
/// It should not perform the equipping itself.
/datum/strippable_item/proc/try_equip(atom/source, obj/item/equipping, mob/user)
if(!is_incorporeal(user))
return FALSE
if(!equipping)
return
if(HAS_TRAIT(equipping, TRAIT_NODROP))
to_chat(user, "<span class='warning'>You can't put [equipping] on [source], it's stuck to your hand!</span>")
return FALSE
//This is important due to the fact otherwise it will be equipped without a proper existing icon, because it's forced on through the strip menu
//if(ismonkey(source)) //Todo delete this if monkeys arent strippable
// equipping.compile_monkey_icon()
return TRUE
/// Start the equipping process. This is the proc you should yield in.
/// Returns TRUE/FALSE depending on if it is allowed.
/datum/strippable_item/proc/start_equip(atom/source, obj/item/equipping, mob/user)
if(isclothing(source))
source.visible_message(
"<span class='notice'>[user] tries to put [equipping] on [source].</span>",
"<span class='notice'>[user] tries to put [equipping] on you.</span>",
ignored_mob = user
)
to_chat(user, "<span class='notice'>You try to put [equipping] on [source]...</span>")
var/log = "[key_name(source)] is having [equipping] put on them by [key_name(user)]"
source.log_message(log, LOG_ATTACK, color="red")
user.log_message(log, LOG_ATTACK, color="red", log_globally=FALSE)
return TRUE
/// The proc that places the item on the source. This should not yield.
/datum/strippable_item/proc/finish_equip(atom/source, obj/item/equipping, mob/user)
SHOULD_NOT_SLEEP(TRUE)
/// Tries to unequip the item from the given source.
/// Returns TRUE/FALSE depending on if it is allowed.
/// This should be used for checking if it CAN be unequipped.
/// It should not perform the unequipping itself.
/datum/strippable_item/proc/try_unequip(atom/source, mob/user)
SHOULD_NOT_SLEEP(TRUE)
if(!is_incorporeal(user))
return FALSE
var/obj/item/item = get_item(source)
if(isnull(item))
return FALSE
if(ismob(source))
var/mob/mob_source = source
if(!item.canStrip(user, mob_source))
return FALSE
return TRUE
/// Start the unequipping process. This is the proc you should yield in.
/// Returns TRUE/FALSE depending on if it is allowed.
/datum/strippable_item/proc/start_unequip(atom/source, mob/user)
var/obj/item/item = get_item(source)
if(isnull(item))
return FALSE
source.visible_message(
"<span class='warning'>[user] tries to remove [source]'s [item.name].</span>",
"<span class='userdanger'>[user] tries to remove your [item.name].</span>",
ignored_mob = user,
)
to_chat(user, "<span class='danger'>You try to remove [source]'s [item.name]...</span>")
source.log_message("[key_name(source)] is being stripped of [item.name] by [key_name(user)]", LOG_ATTACK, color="red")
user.log_message("[key_name(source)] is being stripped of [item.name] by [key_name(user)]", LOG_ATTACK, color="red", log_globally=FALSE)
item.add_fingerprint(user, "stripping")
return TRUE
/// The proc that unequips the item from the source. This should not yield.
/datum/strippable_item/proc/finish_unequip(atom/source, mob/user)
/// Returns a STRIPPABLE_OBSCURING_* define to report on whether or not this is obscured.
/datum/strippable_item/proc/get_obscuring(atom/source)
SHOULD_NOT_SLEEP(TRUE)
return STRIPPABLE_OBSCURING_NONE
/// Returns the ID of this item's strippable action.
/// Return `null` if there is no alternate action.
/// Any return value of this must be in StripMenu.
/datum/strippable_item/proc/get_alternate_action(atom/source, mob/user)
return null
/// Performs an alternative action on this strippable_item.
/// `has_alternate_action` needs to be TRUE.
/datum/strippable_item/proc/alternate_action(atom/source, mob/user)
/// Returns whether or not this item should show.
/datum/strippable_item/proc/should_show(atom/source, mob/user)
return TRUE
/// Returns TRUE if the item is present for the mob, but not available.
/// This is used, for example, for pockets when a jumpsuit is not worn.
/datum/strippable_item/proc/is_unavailable(atom/source)
/// A preset for equipping items onto mob slots
/datum/strippable_item/mob_item_slot
/// The ITEM_SLOT_* to equip to.
var/item_slot
/datum/strippable_item/mob_item_slot/get_item(atom/source)
if(!ismob(source))
return null
var/mob/mob_source = source
return mob_source.get_item_by_slot_bit(item_slot)
/datum/strippable_item/mob_item_slot/try_equip(atom/source, obj/item/equipping, mob/user)
. = ..()
if(!.)
return
if(!ismob(source))
return FALSE
if(!equipping.mob_can_equip(source, item_slot, warning = TRUE, override_nodrop = FALSE, bitslot = TRUE))
to_chat(user, "<span class='warning'>\The [equipping] doesn't fit in that place!</span>")
return FALSE
return TRUE
/datum/strippable_item/mob_item_slot/start_equip(atom/source, obj/item/equipping, mob/user)
. = ..()
if(!.)
return
if(!ismob(source))
return FALSE
if(!do_after(user, get_equip_delay(equipping), NONE, source, BUSY_ICON_FRIENDLY))
return FALSE
if(!equipping.mob_can_equip(source, item_slot,warning = TRUE,override_nodrop = FALSE, bitslot = TRUE))
return FALSE
if(!user.temporarilyRemoveItemFromInventory(equipping))
return FALSE
return TRUE
/datum/strippable_item/mob_item_slot/finish_equip(atom/source, obj/item/equipping, mob/user)
if(!ismob(source))
return FALSE
var/mob/mob_source = source
mob_source.equip_to_slot(equipping, item_slot, TRUE)
/datum/strippable_item/mob_item_slot/get_obscuring(atom/source)
if(iscarbon(source))
var/mob/living/carbon/carbon_source = source
return(carbon_source.check_obscured_slots() & item_slot) \
? STRIPPABLE_OBSCURING_COMPLETELY \
: STRIPPABLE_OBSCURING_NONE
return FALSE
/datum/strippable_item/mob_item_slot/start_unequip(atom/source, mob/user)
. = ..()
if(!.)
return
return start_unequip_mob(get_item(source), source, user)
/datum/strippable_item/mob_item_slot/finish_unequip(atom/source, mob/user)
var/obj/item/item = get_item(source)
if(isnull(item))
return FALSE
if(!ismob(source))
return FALSE
return finish_unequip_mob(item, source, user)
/// Returns the delay of equipping this item to a mob
/datum/strippable_item/mob_item_slot/proc/get_equip_delay(obj/item/equipping)
return equipping.equip_delay_other
/// A utility function for `/datum/strippable_item`s to start unequipping an item from a mob.
/datum/strippable_item/proc/start_unequip_mob(obj/item/item, mob/source, mob/user, strip_delay)
if(!do_after(user, strip_delay || item.strip_delay, NONE, source, BUSY_ICON_FRIENDLY))
return FALSE
return TRUE
/// A utility function for `/datum/strippable_item`s to finish unequipping an item from a mob.
/datum/strippable_item/proc/finish_unequip_mob(obj/item/item, mob/source, mob/user)
if(item.special_stripped_behavior(user, source))
return FALSE
if(!source.dropItemToGround(item))
return FALSE
source.log_message("[key_name(source)] has been stripped of [item] by [key_name(user)]", LOG_ATTACK, color="red")
user.log_message("[key_name(source)] has been stripped of [item] by [key_name(user)]", LOG_ATTACK, color="red", log_globally=FALSE)
/// A representation of the stripping UI
/datum/strip_menu
/// The owner who has the element /datum/element/strippable
var/atom/movable/owner
/// The strippable element itself
var/datum/element/strippable/strippable
/// A lazy list of user mobs to a list of strip menu keys that they're interacting with
var/list/interactions
/datum/strip_menu/New(atom/movable/_owner, datum/element/strippable/_strippable)
. = ..()
owner = _owner
strippable = _strippable
/datum/strip_menu/Destroy()
owner = null
strippable = null
return ..()
/datum/strip_menu/ui_interact(mob/user, datum/tgui/ui)
ui = SStgui.try_update_ui(user, src, ui)
if(!ui)
ui = new(user, src, "StripMenu")
ui.open()
ui.set_autoupdate(TRUE) // Item changes from outside stripping
/datum/strip_menu/ui_data(mob/user)
var/list/data = list()
var/list/items = list()
for(var/strippable_key in strippable.items)
var/datum/strippable_item/item_data = strippable.items[strippable_key]
if(!item_data.should_show(owner, user))
continue
var/list/result
if(strippable_key in LAZYACCESS(interactions, user))
LAZYSET(result, "interacting", TRUE)
var/obscuring = item_data.get_obscuring(owner)
if(obscuring != STRIPPABLE_OBSCURING_NONE)
LAZYSET(result, "obscured", obscuring)
items[strippable_key] = result
continue
if(item_data.is_unavailable(owner))
LAZYSET(result, "unavailable", TRUE)
items[strippable_key] = result
continue
var/obj/item/item = item_data.get_item(owner)
if(isnull(item))
items[strippable_key] = result
continue
LAZYINITLIST(result)
/* We don't use item icons in our strip menu, keeping this here in case we want it in the future
result["icon"] = icon2base64(icon(item.icon, item.icon_state, frame=1))
*/
result["name"] = item.name
result["alternate"] = item_data.get_alternate_action(owner, user)
items[strippable_key] = result
data["items"] = items
// While most `\the`s are implicit, this one is not.
// In this case, `\The` would otherwise be used.
// This doesn't match with what it's used for, which is to say "Stripping the alien drone",
// as opposed to "Stripping The alien drone".
// Human names will still show without "the", as they are proper nouns.
data["name"] = "\the [owner]"
return data
/datum/strip_menu/ui_static_data(mob/user)
. = list()
if(!isnull(strippable.layout))
var/layout = list()
for(var/section in strippable.layout)
var/section_result = list()
for(var/datum/strippable_item_layout/slot as() in section)
section_result += list(list(
"id" = slot.key,
"indented" = slot.indented,
))
layout += list(section_result)
.["layout"] = layout
/datum/strip_menu/ui_act(action, list/params, datum/tgui/ui, datum/ui_state/state)
. = ..()
if(.)
return
. = TRUE
var/mob/user = usr
switch(action)
if("use")
var/key = params["key"]
var/datum/strippable_item/strippable_item = strippable.items[key]
if(isnull(strippable_item))
return
if(!strippable_item.should_show(owner, user))
return
if(strippable_item.get_obscuring(owner) == STRIPPABLE_OBSCURING_COMPLETELY)
return
var/item = strippable_item.get_item(owner)
if(isnull(item))
var/obj/item/held_item = user.get_active_held_item()
if(isnull(held_item))
return
if(strippable_item.try_equip(owner, held_item, user))
LAZYORASSOCLIST(interactions, user, key)
SStgui.update_uis(src)
// Yielding call
var/should_finish = strippable_item.start_equip(owner, held_item, user)
LAZYREMOVEASSOC(interactions, user, key)
. = TRUE
if(!should_finish)
return
if(QDELETED(src) || QDELETED(owner))
return
// They equipped an item in the meantime
if(!isnull(strippable_item.get_item(owner)))
return
if(!user.Adjacent(owner))
return
strippable_item.finish_equip(owner, held_item, user)
else if(strippable_item.try_unequip(owner, user))
LAZYORASSOCLIST(interactions, user, key)
SStgui.update_uis(src)
var/should_unequip = strippable_item.start_unequip(owner, user)
LAZYREMOVEASSOC(interactions, user, key)
. = TRUE
// Yielding call
if(!should_unequip)
return
if(QDELETED(src) || QDELETED(owner))
return
// They changed the item in the meantime
if(strippable_item.get_item(owner) != item)
return
if(!user.Adjacent(owner))
return
strippable_item.finish_unequip(owner, user)
if("alt")
var/key = params["key"]
var/datum/strippable_item/strippable_item = strippable.items[key]
if(isnull(strippable_item))
return
if(!strippable_item.should_show(owner, user))
return
if(strippable_item.get_obscuring(owner) == STRIPPABLE_OBSCURING_COMPLETELY)
return
var/item = strippable_item.get_item(owner)
if(isnull(item))
return
if(isnull(strippable_item.get_alternate_action(owner, user)))
return
LAZYORASSOCLIST(interactions, user, key)
// Potentially yielding
strippable_item.alternate_action(owner, user)
LAZYREMOVEASSOC(interactions, user, key)
/datum/strip_menu/ui_host(mob/user)
return owner
/datum/strip_menu/ui_state(mob/user)
return GLOB.always_state
/datum/strip_menu/ui_status(mob/user, datum/ui_state/state)
return min(
ui_status_only_living(user, owner),
ui_status_user_is_adjacent(user, owner),
max(
ui_status_user_is_conscious_and_lying_down(user),
ui_status_user_is_abled(user, owner),
),
)
/// Creates an assoc list of keys to /datum/strippable_item
/proc/create_strippable_list(types)
var/list/strippable_items = list()
for(var/strippable_type in types)
var/datum/strippable_item/strippable_item = new strippable_type
strippable_items[strippable_item.key] = strippable_item
return strippable_items
| 0 | 0.858047 | 1 | 0.858047 | game-dev | MEDIA | 0.923238 | game-dev | 0.932245 | 1 | 0.932245 |
CrazyVince/Hacking | 2,012 | Library/PackageCache/com.unity.timeline@1.6.4/Editor/Activation/ActivationTrackEditor.cs | using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.Timeline;
using UnityEngine.Playables;
namespace UnityEditor.Timeline
{
[UsedImplicitly]
[CustomTimelineEditor(typeof(ActivationTrack))]
class ActivationTrackEditor : TrackEditor
{
static readonly string ClipText = L10n.Tr("Active");
static readonly string k_ErrorParentString = L10n.Tr("The bound GameObject is a parent of the PlayableDirector.");
static readonly string k_ErrorString = L10n.Tr("The bound GameObject contains the PlayableDirector.");
public override TrackDrawOptions GetTrackOptions(TrackAsset track, Object binding)
{
var options = base.GetTrackOptions(track, binding);
options.errorText = GetErrorText(track, binding);
return options;
}
string GetErrorText(TrackAsset track, Object binding)
{
var gameObject = binding as GameObject;
var currentDirector = TimelineEditor.inspectedDirector;
if (gameObject != null && currentDirector != null)
{
var director = gameObject.GetComponent<PlayableDirector>();
if (currentDirector == director)
{
return k_ErrorString;
}
if (currentDirector.gameObject.transform.IsChildOf(gameObject.transform))
{
return k_ErrorParentString;
}
}
return base.GetErrorText(track, binding, TrackBindingErrors.PrefabBound);
}
public override void OnCreate(TrackAsset track, TrackAsset copiedFrom)
{
// Add a default clip to the newly created track
if (copiedFrom == null)
{
var clip = track.CreateClip(0);
clip.displayName = ClipText;
clip.duration = System.Math.Max(clip.duration, track.timelineAsset.duration * 0.5f);
}
}
}
}
| 0 | 0.953898 | 1 | 0.953898 | game-dev | MEDIA | 0.971504 | game-dev | 0.95845 | 1 | 0.95845 |
amethyst/rustrogueliketutorial | 3,843 | chapter-75-darkplaza/src/systems/ai/adjacent_ai_system.rs | use specs::prelude::*;
use crate::{MyTurn, Faction, Position, Map, raws::Reaction, WantsToMelee, TileSize};
pub struct AdjacentAI {}
impl<'a> System<'a> for AdjacentAI {
#[allow(clippy::type_complexity)]
type SystemData = (
WriteStorage<'a, MyTurn>,
ReadStorage<'a, Faction>,
ReadStorage<'a, Position>,
ReadExpect<'a, Map>,
WriteStorage<'a, WantsToMelee>,
Entities<'a>,
ReadExpect<'a, Entity>,
ReadStorage<'a, TileSize>
);
fn run(&mut self, data : Self::SystemData) {
let (mut turns, factions, positions, map, mut want_melee, entities, player, sizes) = data;
let mut turn_done : Vec<Entity> = Vec::new();
for (entity, _turn, my_faction, pos) in (&entities, &turns, &factions, &positions).join() {
if entity != *player {
let mut reactions : Vec<(Entity, Reaction)> = Vec::new();
let idx = map.xy_idx(pos.x, pos.y);
let w = map.width;
let h = map.height;
if let Some(size) = sizes.get(entity) {
use crate::rect::Rect;
let mob_rect = Rect::new(pos.x, pos.y, size.x, size.y).get_all_tiles();
let parent_rect = Rect::new(pos.x -1, pos.y -1, size.x+2, size.y + 2);
parent_rect.get_all_tiles().iter().filter(|t| !mob_rect.contains(t)).for_each(|t| {
if t.0 > 0 && t.0 < w-1 && t.1 > 0 && t.1 < h-1 {
let target_idx = map.xy_idx(t.0, t.1);
evaluate(target_idx, &map, &factions, &my_faction.name, &mut reactions);
}
});
} else {
// Add possible reactions to adjacents for each direction
if pos.x > 0 { evaluate(idx-1, &map, &factions, &my_faction.name, &mut reactions); }
if pos.x < w-1 { evaluate(idx+1, &map, &factions, &my_faction.name, &mut reactions); }
if pos.y > 0 { evaluate(idx-w as usize, &map, &factions, &my_faction.name, &mut reactions); }
if pos.y < h-1 { evaluate(idx+w as usize, &map, &factions, &my_faction.name, &mut reactions); }
if pos.y > 0 && pos.x > 0 { evaluate((idx-w as usize)-1, &map, &factions, &my_faction.name, &mut reactions); }
if pos.y > 0 && pos.x < w-1 { evaluate((idx-w as usize)+1, &map, &factions, &my_faction.name, &mut reactions); }
if pos.y < h-1 && pos.x > 0 { evaluate((idx+w as usize)-1, &map, &factions, &my_faction.name, &mut reactions); }
if pos.y < h-1 && pos.x < w-1 { evaluate((idx+w as usize)+1, &map, &factions, &my_faction.name, &mut reactions); }
}
let mut done = false;
for reaction in reactions.iter() {
if let Reaction::Attack = reaction.1 {
want_melee.insert(entity, WantsToMelee{ target: reaction.0 }).expect("Error inserting melee");
done = true;
}
}
if done { turn_done.push(entity); }
}
}
// Remove turn marker for those that are done
for done in turn_done.iter() {
turns.remove(*done);
}
}
}
fn evaluate(idx : usize, map : &Map, factions : &ReadStorage<Faction>, my_faction : &str, reactions : &mut Vec<(Entity, Reaction)>) {
crate::spatial::for_each_tile_content(idx, |other_entity| {
if let Some(faction) = factions.get(other_entity) {
reactions.push((
other_entity,
crate::raws::faction_reaction(my_faction, &faction.name, &crate::raws::RAWS.lock().unwrap())
));
}
});
}
| 0 | 0.864976 | 1 | 0.864976 | game-dev | MEDIA | 0.936187 | game-dev | 0.841892 | 1 | 0.841892 |
Misaka-Mikoto-Tech/UnityScriptHotReload | 6,752 | Assets/HotReload/Editor/EditorCompilationWrapper.cs | /*
* Author: Misaka Mikoto
* email: easy66@live.com
* github: https://github.com/Misaka-Mikoto-Tech/UnityScriptHotReload
*/
#if UNITY_2021_2_OR_NEWER
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using System.Linq;
namespace ScriptHotReload
{
public enum CompileStatus
{
Idle,
Compiling,
CompilationStarted,
CompilationFailed,
CompilationComplete
}
[Flags]
public enum EditorScriptCompilationOptions
{
BuildingEmpty = 0,
BuildingDevelopmentBuild = 1 << 0,
BuildingForEditor = 1 << 1,
BuildingEditorOnlyAssembly = 1 << 2,
BuildingForIl2Cpp = 1 << 3,
BuildingWithAsserts = 1 << 4,
BuildingIncludingTestAssemblies = 1 << 5,
BuildingPredefinedAssembliesAllowUnsafeCode = 1 << 6,
BuildingForHeadlessPlayer = 1 << 7,
BuildingUseDeterministicCompilation = 1 << 9,
BuildingWithRoslynAnalysis = 1 << 10,
BuildingWithoutScriptUpdater = 1 << 11
}
/// <summary>
/// 封装反射调用的 UnityEditor.Scripting.ScriptCompilation 及相关命名空间内的类型和函数
/// </summary>
public static class EditorCompilationWrapper
{
public static Type tEditorCompilationInterface { get; private set; }
public static Type tEditorCompilation { get; private set; }
public static Type tScriptAssemblySettings { get; private set; }
public static Type tBeeDriver { get; private set; }
public static MethodInfo miTickCompilationPipeline { get; private set; }
public static MethodInfo miBeeDriver_Tick { get; private set; }
public static MethodInfo miCreateScriptAssemblySettings { get; private set; }
public static MethodInfo miScriptSettings_SetOutputDirectory { get; private set; }
public static MethodInfo miCompileScriptsWithSettings { get; private set; }
public static MethodInfo miRequestScriptCompilation { get; private set; }
public static MethodInfo miDirtyAllScripts { get; private set; }
public static object EditorCompilation_Instance { get; private set; }
static EditorCompilationWrapper()
{
tEditorCompilationInterface = typeof(UnityEditor.AssetDatabase).Assembly.GetType("UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface");
tEditorCompilation = typeof(UnityEditor.AssetDatabase).Assembly.GetType("UnityEditor.Scripting.ScriptCompilation.EditorCompilation");
tScriptAssemblySettings = typeof(UnityEditor.AssetDatabase).Assembly.GetType("UnityEditor.Scripting.ScriptCompilation.ScriptAssemblySettings");
tBeeDriver = (from ass in AppDomain.CurrentDomain.GetAssemblies() where ass.FullName.StartsWith("Bee.BeeDriver") select ass).FirstOrDefault().GetType("Bee.BeeDriver.BeeDriver");
miBeeDriver_Tick = tBeeDriver.GetMethod("Tick", BindingFlags.Public | BindingFlags.Instance);
miTickCompilationPipeline = tEditorCompilationInterface.GetMethod("TickCompilationPipeline", BindingFlags.Static | BindingFlags.Public);
foreach (var mi in tEditorCompilation.GetMethods())
{
if (mi.Name == "CreateScriptAssemblySettings" && mi.GetParameters().Length == 4)
miCreateScriptAssemblySettings = mi;
else if (mi.Name == "CompileScriptsWithSettings")
miCompileScriptsWithSettings = mi;
}
miScriptSettings_SetOutputDirectory = tScriptAssemblySettings.GetProperty("OutputDirectory", BindingFlags.Public | BindingFlags.Instance).GetSetMethod();
miRequestScriptCompilation = tEditorCompilation.GetMethod("RequestScriptCompilation", BindingFlags.Public | BindingFlags.Instance);
miDirtyAllScripts = tEditorCompilationInterface.GetMethod("DirtyAllScripts", BindingFlags.Public | BindingFlags.Static);
EditorCompilation_Instance = tEditorCompilationInterface.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public).GetGetMethod().Invoke(null, null);
}
public static CompileStatus TickCompilationPipeline(EditorScriptCompilationOptions options, BuildTargetGroup platfromGroup, BuildTarget platform, int subtarget, string[] extraScriptingDefines, bool allowBlocking)
{
#if UNITY_2022_2_OR_NEWER
CompileStatus ret = (CompileStatus)miTickCompilationPipeline.Invoke(null, new object[]
{
(int)options, platfromGroup, platform, subtarget, extraScriptingDefines, allowBlocking
});
#else
CompileStatus ret = (CompileStatus)miTickCompilationPipeline.Invoke(null, new object[]
{
(int)options, platfromGroup, platform, subtarget, extraScriptingDefines
});
#endif
return ret;
}
public static object CreateScriptAssemblySettings(BuildTargetGroup platfromGroup, BuildTarget platform, EditorScriptCompilationOptions options, string[] extraScriptingDefines, string outputDir)
{
object ret = miCreateScriptAssemblySettings.Invoke(EditorCompilation_Instance, new object[] { platfromGroup, platform, (int)options, extraScriptingDefines });
SetScriptAssemblyOutputDir(ret, outputDir);
return ret;
}
public static void SetScriptAssemblyOutputDir(object scriptAssemblySettings, string buildDir)
{
miScriptSettings_SetOutputDirectory.Invoke(scriptAssemblySettings, new object[] { buildDir });
}
public static CompileStatus CompileScriptsWithSettings(object scriptAssemblySettings)
{
CompileStatus ret = (CompileStatus)miCompileScriptsWithSettings.Invoke(EditorCompilation_Instance, new object[] { scriptAssemblySettings });
return ret;
}
public static void RequestScriptCompilation(string reason)
{
//miRequestScriptCompilation.Invoke(EditorCompilation_Instance, new object[] { reason, UnityEditor.Compilation.RequestScriptCompilationOptions.CleanBuildCache });
miRequestScriptCompilation.Invoke(EditorCompilation_Instance, new object[] { reason, UnityEditor.Compilation.RequestScriptCompilationOptions.None });
}
public static void DirtyAllScripts()
{
// DirtyAllScripts has been removed since 2021.1
miDirtyAllScripts?.Invoke(null, new object[] { });
}
}
}
#endif | 0 | 0.674894 | 1 | 0.674894 | game-dev | MEDIA | 0.613026 | game-dev | 0.619425 | 1 | 0.619425 |
eveningglow/multi-object-tracker | 3,727 | dlib-19.3/dlib/general_hash/hash.h | // Copyright (C) 2011 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_HAsH_Hh_
#define DLIB_HAsH_Hh_
#include "hash_abstract.h"
#include <vector>
#include <string>
#include <map>
#include "murmur_hash3.h"
#include "../algs.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
inline uint32 hash (
const std::string& item,
uint32 seed = 0
)
{
if (item.size() == 0)
return 0;
else
return murmur_hash3(&item[0], sizeof(item[0])*item.size(), seed);
}
// ----------------------------------------------------------------------------------------
inline uint32 hash (
const std::wstring& item,
uint32 seed = 0
)
{
if (item.size() == 0)
return 0;
else
return murmur_hash3(&item[0], sizeof(item[0])*item.size(), seed);
}
// ----------------------------------------------------------------------------------------
template <typename T, typename alloc>
uint32 hash (
const std::vector<T,alloc>& item,
uint32 seed = 0
)
{
DLIB_ASSERT_HAS_STANDARD_LAYOUT(T);
if (item.size() == 0)
return 0;
else
return murmur_hash3(&item[0], sizeof(T)*item.size(), seed);
}
// ----------------------------------------------------------------------------------------
template <typename T, typename U, typename alloc>
uint32 hash (
const std::vector<std::pair<T,U>,alloc>& item,
uint32 seed = 0
)
{
DLIB_ASSERT_HAS_STANDARD_LAYOUT(T);
DLIB_ASSERT_HAS_STANDARD_LAYOUT(U);
if (item.size() == 0)
return 0;
else
return murmur_hash3(&item[0], sizeof(item[0])*item.size(), seed);
}
// ----------------------------------------------------------------------------------------
template <typename T, typename U, typename comp, typename alloc>
uint32 hash (
const std::map<T,U,comp,alloc>& item,
uint32 seed = 0
)
{
return hash(std::vector<std::pair<T,U> >(item.begin(), item.end()), seed);
}
// ----------------------------------------------------------------------------------------
inline uint32 hash (
uint32 val,
uint32 seed = 0
)
{
return murmur_hash3_2(val,seed);
}
// ----------------------------------------------------------------------------------------
inline uint32 hash (
uint64 val,
uint32 seed = 0
)
{
return static_cast<uint32>(murmur_hash3_128bit_3(val,seed,0).first);
}
// ----------------------------------------------------------------------------------------
inline uint32 hash (
const std::pair<uint64,uint64>& item,
uint32 seed = 0
)
{
return static_cast<uint32>(murmur_hash3_128bit_3(item.first,item.second,seed).first);
}
// ----------------------------------------------------------------------------------------
inline uint32 hash (
const std::pair<uint32,uint32>& item,
uint32 seed = 0
)
{
return murmur_hash3_3(item.first,item.second,seed);
}
// ----------------------------------------------------------------------------------------
template <typename T, typename U>
uint32 hash (
const std::pair<T,U>& item,
uint32 seed = 0
)
{
return hash(item.first, seed) ^ hash(item.second, seed+1);
}
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_HAsH_Hh_
| 0 | 0.82631 | 1 | 0.82631 | game-dev | MEDIA | 0.169285 | game-dev | 0.775043 | 1 | 0.775043 |
bozimmerman/CoffeeMud | 41,858 | com/planet_ink/coffee_mud/Libraries/ColumbiaUniv.java | package com.planet_ink.coffee_mud.Libraries;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.core.interfaces.CostDef.CostType;
import com.planet_ink.coffee_mud.Libraries.interfaces.ExpertiseLibrary.ExpertiseDefinition;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.CMSecurity.SecFlag;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.Session.InputCallback;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
import java.util.Map.Entry;
/*
Copyright 2006-2025 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class ColumbiaUniv extends StdLibrary implements ExpertiseLibrary
{
@Override
public String ID()
{
return "ColumbiaUniv";
}
protected STreeMap<String, ExpertiseDefinition> completeEduMap = new STreeMap<String, ExpertiseDefinition>();
protected SHashtable<String, List<String>> baseEduSetLists = new SHashtable<String, List<String>>();
@SuppressWarnings("unchecked")
protected Map<String, String>[] completeUsageMap = new Hashtable[XType.values().length];
@SuppressWarnings("unchecked")
protected Map<String, String[]>[] completeUsageMaps = new Hashtable[XType.values().length];
protected Map<String, String> helpMap = new TreeMap<String, String>();
protected ExpertiseLibrary.ExpertiseDefinition addDefinition(final String ID, final String name, final String baseName, final String listMask, final String finalMask, final String[] costs, final String[] data)
{
ExpertiseLibrary.ExpertiseDefinition def=getDefinition(ID);
if(def!=null)
return def;
if(CMSecurity.isExpertiseDisabled(ID.toUpperCase()))
return null;
if(CMSecurity.isExpertiseDisabled("*"))
return null;
for(int i=1;i<ID.length();i++)
{
if(CMSecurity.isExpertiseDisabled(ID.substring(0,i).toUpperCase()+"*"))
return null;
}
def=createNewExpertiseDefinition(ID.toUpperCase(), name, baseName);
def.addListMask(listMask);
def.addFinalMask(finalMask);
def.setStageNames((data==null)?new String[0]:data);
final int practices=CMath.s_int(costs[0]);
final int trains=CMath.s_int(costs[1]);
final int qpCost=CMath.s_int(costs[2]);
final int expCost=CMath.s_int(costs[3]);
//int timeCost=CMath.s_int(costs[0]);
if(practices>0)
def.addCost(CostType.PRACTICE, Double.valueOf(practices));
if(trains>0)
def.addCost(CostType.TRAIN, Double.valueOf(trains));
if(qpCost>0)
def.addCost(CostType.QP, Double.valueOf(qpCost));
if(expCost>0)
def.addCost(CostType.XP, Double.valueOf(expCost));
//if(timeCost>0) def.addCost(CostType.PRACTICE, Double.valueOf(practices));
completeEduMap.put(def.ID(),def);
baseEduSetLists.clear();
return def;
}
@Override
public boolean addModifyDefinition(final String codedLine, final boolean andSave)
{
int x=codedLine.indexOf('=');
if(x<0)
return false;
String ID=codedLine.substring(0,x).toUpperCase().trim();
ID=CMStrings.replaceAll(CMStrings.replaceAll(ID,"@X2",""),"@X1","").toUpperCase();
final String resp = this.confirmExpertiseLine(codedLine, ID, false);
if((resp!=null)&&(resp.toLowerCase().startsWith("error")))
return false;
if(andSave)
{
String baseID=null;
if(completeEduMap.containsKey(ID.trim().toUpperCase()))
{
final ExpertiseDefinition def=completeEduMap.get(ID.trim().toUpperCase());
baseID=def.getBaseName();
}
else
{
for(final String defID : completeEduMap.keySet())
{
final ExpertiseDefinition def = completeEduMap.get(defID);
if(def.getBaseName().equalsIgnoreCase(ID))
baseID = def.getBaseName();
}
}
if(baseID != null)
{
final String expertiseFilename="skills/expertises.txt";
String fileName=Resources.getRawFileResourceName(expertiseFilename, false);
final List<String> lines = getExpertiseLines();
final StringBuilder buf = new StringBuilder("");
boolean readyToSave=false;
for(final String l : lines)
{
if(l.trim().startsWith("#"))
{
if(l.trim().startsWith("#FILE:"))
{
if(readyToSave)
break;
fileName = l.trim().substring(6).trim();
buf.setLength(0);
continue;
}
}
else
{
x=l.indexOf('=');
if(x>0)
{
String baseId=l.substring(0,x).trim().toUpperCase();
baseId=CMStrings.replaceAll(CMStrings.replaceAll(baseId,"@X2",""),"@X1","").toUpperCase();
if(baseId.equalsIgnoreCase(baseID))
{
buf.append(codedLine).append("\n\r");
readyToSave=true;
continue;
}
}
}
buf.append(l).append("\n\r");
}
if(readyToSave && (buf.length()>0))
new CMFile(fileName,null).saveText(buf);
}
else
{
final CMFile F=new CMFile(Resources.makeFileResourceName("skills/expertises.txt"),null,CMFile.FLAG_LOGERRORS);
F.saveText("\n"+codedLine,true);
}
Resources.removeResource(Resources.makeFileResourceName("skills/expertises.txt"));
CMLib.expertises().recompileExpertises();
}
return true;
}
@Override
public String findExpertiseID(String ID, final boolean exact)
{
if(ID==null)
return null;
ID=ID.toUpperCase();
if(helpMap.containsKey(ID))
return ID;
if(exact)
return null;
for(final String key : helpMap.keySet())
{
if(key.startsWith(ID))
return key;
}
for(final String key : helpMap.keySet())
{
if(CMLib.english().containsString(key, ID))
return key;
}
return null;
}
@Override
public String getExpertiseHelp(final String ID)
{
if(ID==null)
return null;
return helpMap.get(ID.toUpperCase());
}
@Override
public boolean delDefinition(final String ID, final boolean andSave)
{
final List<String> delThese = new LinkedList<String>();
String baseID=null;
if(completeEduMap.containsKey(ID.trim().toUpperCase()))
{
final ExpertiseDefinition def=completeEduMap.get(ID.trim().toUpperCase());
delThese.add(ID.trim().toUpperCase());
baseID=def.getBaseName();
}
else
{
for(final String defID : completeEduMap.keySet())
{
final ExpertiseDefinition def = completeEduMap.get(defID);
if(def.getBaseName().equalsIgnoreCase(ID))
{
baseID = def.getBaseName();
delThese.add(defID);
}
}
}
for(final String id : delThese)
completeEduMap.remove(id);
baseEduSetLists.clear();
if(andSave && (baseID != null))
{
final String expertiseFilename="skills/expertises.txt";
String fileName=Resources.getRawFileResourceName(expertiseFilename, false);
final List<String> lines = getExpertiseLines();
final StringBuilder buf = new StringBuilder("");
boolean readyToSave=false;
boolean delNextHelp=false;
for(final String l : lines)
{
if(l.trim().startsWith("#"))
{
if(l.trim().startsWith("#FILE:"))
{
if(readyToSave)
break;
fileName = l.trim().substring(6).trim();
buf.setLength(0);
}
}
else
if(delNextHelp && l.trim().startsWith("HELP_=<EXPERTISE>"))
{
delNextHelp=false;
continue;
}
else
{
delNextHelp=false;
final int x=l.indexOf('=');
if(x>0)
{
String baseId=l.substring(0,x).trim().toUpperCase();
baseId=CMStrings.replaceAll(CMStrings.replaceAll(baseId,"@X2",""),"@X1","").toUpperCase();
if(baseId.equalsIgnoreCase(baseID))
{
delNextHelp=true;
readyToSave=true;
continue;
}
}
}
buf.append(l).append("\n\r");
}
if(readyToSave && (buf.length()>0))
new CMFile(fileName,null).saveText(buf);
Resources.removeResource(fileName);
recompileExpertises();
}
return delThese.size()>0;
}
@Override
public Enumeration<ExpertiseDefinition> definitions()
{
return new IteratorEnumeration<ExpertiseDefinition>(completeEduMap.values().iterator());
}
@Override
public ExpertiseDefinition getDefinition(final String ID)
{
if(ID!=null)
return completeEduMap.get(ID.trim().toUpperCase());
return null;
}
@Override
public ExpertiseDefinition findDefinition(final String ID, final boolean exactOnly)
{
ExpertiseDefinition D=getDefinition(ID);
if(D!=null)
return D;
for(final Iterator<ExpertiseDefinition> e=completeEduMap.values().iterator();e.hasNext();)
{
D=e.next();
if(D.name().equalsIgnoreCase(ID))
return D;
}
if(exactOnly)
return null;
for(final Iterator<ExpertiseDefinition> e=completeEduMap.values().iterator();e.hasNext();)
{
D=e.next();
if(D.ID().startsWith(ID))
return D;
}
for(final Iterator<ExpertiseDefinition> e=completeEduMap.values().iterator();e.hasNext();)
{
D=e.next();
if(CMLib.english().containsString(D.name(),ID))
return D;
}
return null;
}
@Override
public List<ExpertiseDefinition> myQualifiedExpertises(final MOB mob)
{
ExpertiseDefinition D=null;
final List<ExpertiseDefinition> V=new Vector<ExpertiseDefinition>();
for(final Iterator<ExpertiseDefinition> e=completeEduMap.values().iterator();e.hasNext();)
{
D=e.next();
if(((D.compiledFinalMask()==null)||(CMLib.masking().maskCheck(D.compiledFinalMask(),mob,true)))
&&((D.compiledListMask()==null)||(CMLib.masking().maskCheck(D.compiledListMask(),mob,true))))
V.add(D);
}
final PlayerStats pStats = mob.playerStats();
if(pStats != null)
{
for(final ExpertiseDefinition def : pStats.getExtraQualifiedExpertises().values())
{
if(((def.compiledFinalMask()==null)||(CMLib.masking().maskCheck(def.compiledFinalMask(),mob,true)))
&&((def.compiledListMask()==null)||(CMLib.masking().maskCheck(def.compiledListMask(),mob,true))))
{
D = completeEduMap.get(def.ID());
if(D!=null)
V.remove(D);
V.add(def);
}
}
}
return V;
}
@Override
public List<ExpertiseDefinition> myListableExpertises(final MOB mob)
{
ExpertiseDefinition D=null;
final List<ExpertiseDefinition> V=new Vector<ExpertiseDefinition>();
for(final Iterator<ExpertiseDefinition> e=completeEduMap.values().iterator();e.hasNext();)
{
D=e.next();
if((D.compiledListMask()==null)||(CMLib.masking().maskCheck(D.compiledListMask(),mob,true)))
{
V.add(D);
}
}
final PlayerStats pStats = mob.playerStats();
if(pStats != null)
{
for(final ExpertiseDefinition def : pStats.getExtraQualifiedExpertises().values())
{
if((def.compiledListMask()==null)||(CMLib.masking().maskCheck(def.compiledListMask(),mob,true)))
{
D = completeEduMap.get(def.ID());
if(D!=null)
V.remove(D);
V.add(def);
}
}
}
return V;
}
@Override
public int getExpertiseLevelCached(final MOB mob, final String abilityID, final ExpertiseLibrary.XType code)
{
if((mob==null)
||(code==null)
||(abilityID==null)
||(abilityID.length()==0))
return 0;
int expertiseLvl=0;
final int[][] usageCache=mob.getAbilityUsageCache(abilityID);
if(usageCache[Ability.CACHEINDEX_EXPERTISE]!=null)
expertiseLvl=usageCache[Ability.CACHEINDEX_EXPERTISE][code.ordinal()];
else
{
final int[] xFlagCache=new int[ExpertiseLibrary.XType.values().length];
final CharClass charClass = mob.baseCharStats().getCurrentClass();
if(charClass == null)
return 0;
for(final ExpertiseLibrary.XType flag : ExpertiseLibrary.XType.values())
{
xFlagCache[flag.ordinal()]=getExpertiseLevelCalced(mob,abilityID,flag)
+charClass.addedExpertise(mob, flag, abilityID);
}
usageCache[Ability.CACHEINDEX_EXPERTISE]=xFlagCache;
expertiseLvl = xFlagCache[code.ordinal()];
}
return expertiseLvl;
}
private int getStageNumber(final ExpertiseDefinition D)
{
if(D.ID().startsWith(D.getBaseName()))
{
final String remID=D.ID().substring(D.getBaseName().length());
if(CMath.isInteger(remID))
return CMath.s_int(remID);
if(CMath.isRomanNumeral(remID))
return CMath.convertFromRoman(remID);
}
return 0;
}
@Override
public int getHighestListableStageBySkill(final MOB mob, final String ableID, final ExpertiseLibrary.XType flag)
{
final String expertiseID = completeUsageMap[flag.ordinal()].get(ableID);
if(expertiseID == null)
return 0;
ExpertiseDefinition D=null;
int max=0;
for(final Iterator<ExpertiseDefinition> e=completeEduMap.values().iterator();e.hasNext();)
{
D=e.next();
if(expertiseID.equals(D.getBaseName()))
{
if((D.compiledListMask()==null)||(CMLib.masking().maskCheck(D.compiledListMask(),mob,true)))
{
final int stage=getStageNumber(D);
if(stage > max)
max=stage;
}
}
}
final PlayerStats pStats = mob.playerStats();
if(pStats != null)
{
for(final ExpertiseDefinition def : pStats.getExtraQualifiedExpertises().values())
{
if(expertiseID.equals(def.getBaseName()))
{
if((def.compiledListMask()==null)||(CMLib.masking().maskCheck(def.compiledListMask(),mob,true)))
{
final int stage=getStageNumber(def);
if(stage > max)
max=stage;
}
}
}
}
return max;
}
@Override
public int numExpertises()
{
return completeEduMap.size();
}
private String expertMath(String s,final int l)
{
int x=s.indexOf('{');
while(x>=0)
{
final int y=s.indexOf('}',x);
if(y<0)
break;
s=s.substring(0,x)+CMath.parseIntExpression(s.substring(x+1,y))+s.substring(y+1);
x=s.indexOf('{');
}
return s;
}
@Override
public List<String> getStageCodes(String baseExpertiseCode)
{
String key=null;
if(baseExpertiseCode==null)
return new ReadOnlyVector<String>(1);
baseExpertiseCode=baseExpertiseCode.toUpperCase();
List<String> set=baseEduSetLists.get(baseExpertiseCode);
if(set == null)
{
synchronized(CMClass.getSync(("ListedEduBuild:"+baseExpertiseCode)))
{
set=baseEduSetLists.get(baseExpertiseCode);
if(set==null)
{
final List<String> codes=new LinkedList<String>();
for(final Iterator<String> e=completeEduMap.keySet().iterator();e.hasNext();)
{
key=e.next();
if(key.startsWith(baseExpertiseCode)
&&(CMath.isInteger(key.substring(baseExpertiseCode.length()))||CMath.isRomanNumeral(key.substring(baseExpertiseCode.length()))))
codes.add(key);
}
set=new ReadOnlyVector<String>(codes);
baseEduSetLists.put(baseExpertiseCode, set);
}
}
}
return set;
}
@Override
public int numStages(final String baseExpertiseCode)
{
return getStageCodes(baseExpertiseCode).size();
}
protected String getGuessedBaseExpertiseName(final String expertiseCode)
{
int lastBadChar=expertiseCode.length()-1;
while( (lastBadChar>=0)
&&(CMath.isInteger(expertiseCode.substring(lastBadChar))||CMath.isRomanNumeral(expertiseCode.substring(lastBadChar))))
lastBadChar--;
if(lastBadChar<expertiseCode.length()-1)
return expertiseCode.substring(0,lastBadChar+1);
return expertiseCode;
}
@Override
public List<String> getPeerStageCodes(final String expertiseCode)
{
return getStageCodes(getGuessedBaseExpertiseName(expertiseCode));
}
@Override
public String getApplicableExpertise(final String abilityID, final XType code)
{
return completeUsageMap[code.ordinal()].get(abilityID);
}
@Override
public String[] getApplicableExpertises(final String abilityID, final XType code)
{
if(code == null)
{
final Set<String> all=new TreeSet<String>();
for(final XType f : XType.values())
{
final String[] set=completeUsageMaps[f.ordinal()].get(abilityID);
if(set != null)
all.addAll(Arrays.asList(set));
}
return all.toArray(new String[0]);
}
return completeUsageMaps[code.ordinal()].get(abilityID);
}
@Override
public ExpertiseDefinition getConfirmedDefinition(final MOB mob, final String ID)
{
if(mob == null)
return getDefinition(ID);
if(ID!=null)
{
final ExpertiseDefinition def=getDefinition(ID);
if(def != null)
{
final Pair<String,Integer> e=mob.fetchExpertise(ID);
if((e!=null)
&&(e.getValue()!=null))
{
final int level = getConfirmedExpertiseLevel(mob, def.getBaseName(), e);
if(level == e.second.intValue())
return def;
if(level == 0)
return null;
return getDefinition(def.getBaseName()+level);
}
}
return completeEduMap.get(ID.trim().toUpperCase());
}
return null;
}
protected int getConfirmedExpertiseLevel(final MOB mob, final String baseID, final Pair<String,Integer> e)
{
if((!mob.isMonster())
&&(!CMSecurity.isAllowedEverywhere(mob, SecFlag.ALLSKILLS)))
{
final ExpertiseDefinition def=getDefinition(baseID+e.getValue().toString());
if((def == null)
||(!CMLib.masking().maskCheck(def.compiledListMask(), mob, true))
||(!CMLib.masking().maskCheck(def.compiledFinalMask(), mob, true)))
{
final List<String> defList = getStageCodes(baseID);
for(int i = defList.size()-e.getValue().intValue();i<defList.size();i++)
{
final ExpertiseDefinition def2=getDefinition(defList.get(i));
if((def2 != null)
&&(CMLib.masking().maskCheck(def2.compiledListMask(), mob, true))
&&(CMLib.masking().maskCheck(def2.compiledFinalMask(), mob, true)))
return this.getStageNumber(def2);
}
return 0;
}
}
return e.getValue().intValue();
}
@Override
public int getExpertiseLevelCalced(final MOB mob, final String abilityID, final XType code)
{
final String[] applicableExpIDs = getApplicableExpertises(abilityID, code);
if((applicableExpIDs==null)||(applicableExpIDs.length<1))
return 0;
final Pair<String,Integer> e=mob.fetchExpertise(applicableExpIDs[0]);
if((e!=null)
&&(e.getValue()!=null))
return e.getValue().intValue();
//return getConfirmedExpertiseLevel(mob, applicableExpIDs[0], e);
if(applicableExpIDs.length<2)
return 0;
for(final String expID : applicableExpIDs)
{
final Pair<String,Integer> e2=mob.fetchExpertise(expID);
if((e2!=null)
&&(e2.getValue()!=null))
return e2.getValue().intValue();
//return getConfirmedExpertiseLevel(mob, applicableExpIDs[0], e2);
}
return 0;
}
@Override
public String confirmExpertiseLine(String row, String ID, final boolean addIfPossible)
{
int levels=0;
final HashSet<String> flags=new HashSet<String>();
String s=null;
String skillMask=null;
final String[] costs=new String[5];
final String[] data=new String[0];
String WKID=null;
String name,WKname=null;
String listMask,WKlistMask=null;
String finalMask,WKfinalMask=null;
List<String> skillsToRegister=null;
ExpertiseLibrary.ExpertiseDefinition def=null;
boolean didOne=false;
if(row.trim().startsWith("#")||row.trim().startsWith(";")||(row.trim().length()==0))
return null;
int x=row.indexOf('=');
if(x<0)
return "Error: Invalid line! Not comment, whitespace, and does not contain an = sign!";
if(row.trim().toUpperCase().startsWith("DATA_"))
{
final String lastID=ID;
ID=row.substring(0,x).toUpperCase();
row=row.substring(x+1);
ID=ID.substring(5).toUpperCase();
if(ID.length()==0)
ID=lastID;
if((lastID==null)||(lastID.length()==0))
return "Error: No last expertise found for data: "+lastID+"="+row;
else
if(this.getDefinition(ID)!=null)
{
def=getDefinition(ID);
WKID=def.name().toUpperCase().replace(' ','_');
if(addIfPossible)
{
def.setStageNames(CMParms.parseCommas(row,true).toArray(new String[0]));
}
}
else
{
final List<String> stages=getStageCodes(ID);
if(addIfPossible)
{
for(int s1=0;s1<stages.size();s1++)
{
def=getDefinition(stages.get(s1));
if(def==null)
continue;
def.setStageNames(CMParms.parseCommas(row,true).toArray(new String[0]));
}
}
}
return null;
}
if(row.trim().toUpperCase().startsWith("HELP_"))
{
final String lastID=ID;
ID=row.substring(0,x).toUpperCase();
row=row.substring(x+1);
ID=ID.substring(5).toUpperCase();
if(ID.length()==0)
ID=lastID;
if((lastID==null)||(lastID.length()==0))
return "Error: No last expertise found for help: "+lastID+"="+row;
else
if(getDefinition(ID)!=null)
{
def=getDefinition(ID);
WKID=def.name().toUpperCase().replace(' ','_');
if(addIfPossible)
helpMap.put(WKID,row);
}
else
{
final List<String> stages=getStageCodes(ID);
if((stages==null)||(stages.size()==0))
return "Error: Expertise not yet defined: "+ID+"="+row;
def=getDefinition(stages.get(0));
if(def!=null)
{
WKID=def.name().toUpperCase().replace(' ','_');
x=WKID.lastIndexOf('_');
if((x>=0)&&(CMath.isInteger(WKID.substring(x+1))||CMath.isRomanNumeral(WKID.substring(x+1))))
{
WKID=WKID.substring(0,x);
if(addIfPossible)
if(!helpMap.containsKey(WKID))
helpMap.put(WKID,row+"\n\r(See help on "+def.name()+").");
}
}
if(addIfPossible)
{
for(int s1=0;s1<stages.size();s1++)
{
def=getDefinition(stages.get(s1));
if(def==null)
continue;
WKID=def.name().toUpperCase().replace(' ','_');
if(!helpMap.containsKey(WKID))
helpMap.put(WKID,row);
}
}
}
return null;
}
ID=row.substring(0,x).toUpperCase();
row=row.substring(x+1);
final List<String> parts=CMParms.parseCommas(row,false);
if(parts.size()!=11)
return "Error: Expertise row malformed (Requires 11 entries/10 commas): "+ID+"="+row;
name=parts.get(0);
if(name.length()==0)
return "Error: Expertise name ("+name+") malformed: "+ID+"="+row;
if(!CMath.isInteger(parts.get(1)))
return "Error: Expertise num ("+(parts.get(1))+") malformed: "+ID+"="+row;
levels=CMath.s_int(parts.get(1));
flags.clear();
flags.addAll(CMParms.parseAny(parts.get(2).toUpperCase(),'|',true));
skillMask=parts.get(3);
if(skillMask.length()==0)
return "Error: Expertise skill mask ("+skillMask+") malformed: "+ID+"="+row;
skillsToRegister=CMLib.masking().getAbilityEduReqs(skillMask);
if(skillsToRegister.size()==0)
{
skillsToRegister=CMLib.masking().getAbilityEduReqs(skillMask);
return "Error: Expertise no skills ("+skillMask+") found: "+ID+"="+row;
}
listMask=skillMask+" "+(parts.get(4));
finalMask=((parts.get(5)));
for(int i=6;i<11;i++)
costs[i-6]=parts.get(i);
didOne=false;
for(int u=0;u<completeUsageMap.length;u++)
{
didOne=didOne||flags.contains(ExpertiseLibrary.XType.values()[u].name());
}
if(!didOne)
return "Error: No flags ("+parts.get(2).toUpperCase()+") were set: "+ID+"="+row;
if(addIfPossible)
{
final Set<XType> fflags = new HashSet<XType>();
for(final String f : flags)
{
final XType fl = (XType)CMath.s_valueOf(XType.class, f.toUpperCase().trim());
if(fl != null)
fflags.add(fl);
}
final String baseName=CMStrings.replaceAll(CMStrings.replaceAll(ID,"@X2",""),"@X1","").toUpperCase();
for(int l=1;l<=levels;l++)
{
WKID=CMStrings.replaceAll(ID,"@X1",""+l);
WKID=CMStrings.replaceAll(WKID,"@X2",""+CMath.convertToRoman(l));
WKname=CMStrings.replaceAll(name,"@x1",""+l);
WKname=CMStrings.replaceAll(WKname,"@x2",""+CMath.convertToRoman(l));
WKlistMask=CMStrings.replaceAll(listMask,"@x1",""+l);
WKlistMask=CMStrings.replaceAll(WKlistMask,"@x2",""+CMath.convertToRoman(l));
WKfinalMask=CMStrings.replaceAll(finalMask,"@x1",""+l);
WKfinalMask=CMStrings.replaceAll(WKfinalMask,"@x2",""+CMath.convertToRoman(l));
if((l>1)&&(listMask.toUpperCase().indexOf("-EXPERT")<0))
{
s=CMStrings.replaceAll(ID,"@X1",""+(l-1));
s=CMStrings.replaceAll(s,"@X2",""+CMath.convertToRoman(l-1));
WKlistMask="-EXPERTISE \"+"+s+"\" "+WKlistMask;
}
WKlistMask=expertMath(WKlistMask,l);
WKfinalMask=expertMath(WKfinalMask,l);
def=addDefinition(WKID,WKname,baseName,WKlistMask,WKfinalMask,costs,data);
if(def!=null)
{
def.addRawMasks(listMask, finalMask);
def.getFlagTypes().addAll(fflags);
def.compiledFinalMask();
def.compiledListMask();
}
}
}
ID=CMStrings.replaceAll(ID,"@X1","");
ID=CMStrings.replaceAll(ID,"@X2","");
for(int u=0;u<completeUsageMap.length;u++)
{
if(flags.contains(ExpertiseLibrary.XType.values()[u].name()))
{
for(int k=0;k<skillsToRegister.size();k++)
{
final String skid = skillsToRegister.get(k);
completeUsageMap[u].put(skid, ID);
if(!completeUsageMaps[u].containsKey(skid))
completeUsageMaps[u].put(skid, new String[]{ID});
else
{
final String[] oldSet=completeUsageMaps[u].get(skid);
final String[] newSet=Arrays.copyOf(oldSet, oldSet.length+1);
newSet[newSet.length-1]=ID;
completeUsageMaps[u].put(skid, newSet);
}
}
}
}
return addIfPossible?ID:null;
}
@Override
public String getExpertiseInstructions()
{
final StringBuilder inst = new StringBuilder("");
final String expertiseFilename="skills/expertises.txt";
final List<String> V=Resources.getFileLineVector(Resources.getFileResource(expertiseFilename,true));
for(int v=0;v<V.size();v++)
{
if(V.get(v).startsWith("#"))
inst.append(V.get(v).substring(1)+"\n\r");
else
if(V.get(v).length()>0)
break;
}
return inst.toString();
}
protected List<String> getExpertiseLines()
{
final String expertiseFilename="skills/expertises.txt";
final List<String> V=Resources.getFileLineVector(Resources.getFileResource(expertiseFilename,true));
Resources.removeResource(Resources.makeFileResourceName("skills/expertises.txt"));
for(int i=2;i<99;i++)
{
final String fileName=Resources.getRawFileResourceName(expertiseFilename, false)+"."+i;
final StringBuffer buf = Resources.getFileResource(expertiseFilename+"."+i,false);
Resources.removeResource(fileName);
if(buf.length()==0)
break;
V.add("#FILE:"+fileName);
V.addAll(Resources.getFileLineVector(buf));
}
return V;
}
@Override
public void recompileExpertises()
{
for(int u=0;u<completeUsageMap.length;u++)
completeUsageMap[u]=new Hashtable<String,String>();
for(int u=0;u<completeUsageMaps.length;u++)
completeUsageMaps[u]=new Hashtable<String,String[]>();
helpMap.clear();
final List<String> V = getExpertiseLines();
String ID=null,WKID=null;
for(int v=0;v<V.size();v++)
{
final String row=V.get(v);
WKID=this.confirmExpertiseLine(row,ID,true);
if(WKID==null)
continue;
if(WKID.startsWith("Error: "))
Log.errOut("ColumbiaUniv",WKID);
else
ID=WKID;
}
}
@Override
public Iterator<String> filterUniqueExpertiseIDList(final Iterator<String> i)
{
final Set<String> ids=new HashSet<String>();
for(;i.hasNext();)
{
final String id=i.next();
final ExpertiseDefinition def=getDefinition(id);
if((def != null)
&&(!(def.ID().equals(def.getBaseName()+"1")||def.ID().equals(def.getBaseName()+"I")||(def.ID().equals(def.getBaseName())))))
{
continue;
}
ids.add(id);
}
return ids.iterator();
}
protected Object parseLearnID(final String msg)
{
if(msg==null)
return null;
int learnStart=msg.indexOf("^<LEARN");
if(learnStart>=0)
{
int end=-1;
learnStart=msg.indexOf("\"",learnStart+1);
if(learnStart>=0)
end=msg.indexOf("\"",learnStart+1);
if(end>learnStart)
{
final String ID=msg.substring(learnStart+1,end);
final Ability A=CMClass.getAbility(ID);
if(A!=null)
return A;
final ExpertiseDefinition X = this.findDefinition(ID, true);
if(X!=null)
return X;
return CMClass.getObjectOrPrototype(ID);
}
}
return null;
}
@Override
public boolean canBeTaught(final MOB teacher, final MOB student, final Environmental item, final String msg)
{
if(teacher.isAttributeSet(MOB.Attrib.NOTEACH))
{
teacher.tell(L("You are refusing to teach right now."));
return false;
}
if((student.isAttributeSet(MOB.Attrib.NOTEACH))
&&((!student.isMonster())||(!student.willFollowOrdersOf(teacher))))
{
if(teacher.isMonster())
CMLib.commands().postSay(teacher,student,L("You are refusing training at this time."),true,false);
else
teacher.tell(L("@x1 is refusing training at this time.",student.name()));
return false;
}
Object learnThis=item;
if(learnThis==null)
learnThis=parseLearnID(msg);
String teachWhat="";
if(learnThis instanceof Ability)
{
final Ability theA=(Ability)learnThis;
teachWhat=theA.name();
if(!theA.canBeTaughtBy(teacher,student))
return false;
if(!theA.canBeLearnedBy(teacher,student))
return false;
final Ability studA=student.fetchAbility(theA.ID());
if((studA!=null)&&(studA.isSavable()))
{
if(teacher.isMonster())
CMLib.commands().postSay(teacher,student,L("You already know '@x1'.",teachWhat),true,false);
else
teacher.tell(L("@x1 already knows how to do that.",student.name()));
return false;
}
}
else
if(learnThis instanceof ExpertiseDefinition)
{
final ExpertiseDefinition theExpertise=(ExpertiseDefinition)learnThis;
teachWhat=theExpertise.name();
if(student.fetchExpertise(theExpertise.ID())!=null)
{
if(teacher.isMonster())
CMLib.commands().postSay(teacher,student,L("You already know @x1",theExpertise.name()),true,false);
else
teacher.tell(L("@x1 already knows @x2",student.name(),theExpertise.name()));
return false;
}
if(!myQualifiedExpertises(student).contains(theExpertise))
{
if(teacher.isMonster())
{
CMLib.commands().postSay(teacher,student,
L("I'm sorry, you do not yet fully qualify for the expertise '@x1'.\n\rRequirements: @x2",
theExpertise.name(),CMLib.masking().maskDesc(theExpertise.allRequirements())),true,false);
}
else
{
teacher.tell(L("@x1 does not yet fully qualify for the expertise '@x2'.\n\rRequirements: @x3",
student.name(),theExpertise.name(),CMLib.masking().maskDesc(theExpertise.allRequirements())));
}
return false;
}
if(!theExpertise.meetsCostRequirements(student))
{
if(teacher.isMonster())
{
CMLib.commands().postSay(teacher,student,L("I'm sorry, but to learn the expertise '@x1' requires: @x2",
theExpertise.name(),theExpertise.costDescription()),true,false);
}
else
teacher.tell(L("Training for that expertise requires @x1.",theExpertise.costDescription()));
return false;
}
teachWhat=theExpertise.name();
}
return true;
}
@Override
public void handleBeingTaught(final MOB teacher, final MOB student, final Environmental item, final String msg, final int add)
{
Object learnThis=item;
if(learnThis==null)
learnThis=parseLearnID(msg);
if(learnThis instanceof Ability)
{
final Ability theA=(Ability)learnThis;
teacher.charStats().setStat(CharStats.STAT_WISDOM, teacher.charStats().getStat(CharStats.STAT_WISDOM)+5);
teacher.charStats().setStat(CharStats.STAT_INTELLIGENCE, teacher.charStats().getStat(CharStats.STAT_INTELLIGENCE)+5);
final Set<String> oldSkillSet = new HashSet<String>();
for(final Enumeration<Ability> a=student.abilities();a.hasMoreElements();)
oldSkillSet.add(a.nextElement().ID());
theA.teach(teacher,student);
teacher.recoverCharStats();
final Ability studentA=student.fetchAbility(theA.ID());
if((studentA==null) && (!oldSkillSet.contains(theA.ID())))
student.tell(L("You failed to understand @x1.",theA.name()));
else
if((!teacher.isMonster()) && (!student.isMonster()))
CMLib.leveler().postExperience(teacher, "COMMAND:Teach", null, null, 100, false);
if((studentA!=null)
&& (!oldSkillSet.contains(theA.ID()))
&& (add!=0))
{
int newProficiency=studentA.proficiency() + add;
if(newProficiency > 75)
newProficiency = 75;
if(newProficiency < 0)
newProficiency = 0;
studentA.setProficiency(newProficiency);
final Ability studentEffA = student.fetchEffect(theA.ID());
if(studentEffA != null)
studentEffA.setProficiency(newProficiency);
}
}
else
if(learnThis instanceof ExpertiseDefinition)
{
final ExpertiseDefinition theExpertise=(ExpertiseDefinition)learnThis;
theExpertise.spendCostRequirements(student);
student.addExpertise(theExpertise.ID());
if((!teacher.isMonster()) && (!student.isMonster()))
CMLib.leveler().postExperience(teacher, "COMMAND:Teach", null, null, 100, false);
}
}
@Override
public boolean confirmAndTeach(final MOB teacherM, final MOB studentM, final CMObject teachableO, final Runnable callBack)
{
if((teacherM==null)||(studentM==null))
{
if(callBack != null)
callBack.run();
return false;
}
final Session sess=studentM.session();
final Room R=studentM.location();
if((sess==null)
||(R==null)
||((!teacherM.isPlayer())&&(!teacherM.getGroupLeader().isPlayer())))
{
final boolean success=postTeach(teacherM,studentM,teachableO);
if(callBack != null)
callBack.run();
return success;
}
final String name;
if(teachableO instanceof Ability)
name=((Ability)teachableO).Name();
else
if(teachableO instanceof ExpertiseLibrary.ExpertiseDefinition)
name=((ExpertiseLibrary.ExpertiseDefinition)teachableO).name();
else
name=L("Something");
final Environmental tool=(teachableO instanceof Environmental)?(Environmental)teachableO:null;
final String teachWhat=teachableO.name();
final String ID=teachableO.ID();
final CMMsg msg=CMClass.getMsg(teacherM,studentM,tool,CMMsg.MSG_TEACH,null,teachWhat,ID);
if((!R.show(teacherM, studentM, CMMsg.MSG_SPEAK, L("<S-NAME> offer(s) to teach <T-NAME>.")))
||(!R.okMessage(teacherM, msg)))
{
if(callBack != null)
callBack.run();
return false;
}
sess.prompt(new InputCallback(InputCallback.Type.CONFIRM,"N",10000)
{
final MOB teacher = teacherM;
final MOB student = studentM;
final Session session = sess;
final CMObject teachable=teachableO;
final String teachWhat= name;
final Runnable postCallback=callBack;
@Override
public void showPrompt()
{
sess.promptPrint(L("\n\r@x1 wants to teach you @x2. Is this Ok (y/N)?",teacher.Name(),teachWhat));
}
@Override
public void timedOut()
{
teacher.tell(L("@x1 does not answer you.",student.charStats().HeShe()));
if(postCallback != null)
postCallback.run();
}
@Override
public void callBack()
{
try
{
if(this.input.equals("Y"))
{
if(studentM.location()!=teacherM.location())
{
studentM.tell(L("@x1 vanished.",teacherM.name()));
teacherM.tell(L("@x1 vanished.",studentM.name()));
}
else
postTeach(teacher,student,teachable);
}
else
{
if(!session.isStopped())
session.println("\n\r");
teacher.tell(L("@x1 does not want you to.",student.charStats().HeShe()));
}
}
finally
{
if(postCallback != null)
postCallback.run();
}
}
});
return true;
}
@Override
public boolean postTeach(final MOB teacher, final MOB student, final CMObject teachObj)
{
CMMsg msg=CMClass.getMsg(teacher,student,null,CMMsg.MSG_SPEAK,null);
if(!teacher.location().okMessage(teacher,msg))
return false;
final Environmental tool=(teachObj instanceof Environmental)?(Environmental)teachObj:null;
final String teachWhat=teachObj.name();
final String ID=teachObj.ID();
msg=CMClass.getMsg(teacher,student,tool,CMMsg.MSG_TEACH,L("<S-NAME> teach(es) <T-NAMESELF> '@x1'. ^<LEARN NAME=\"@x2\" /^>",teachWhat,ID));
if(!teacher.location().okMessage(teacher,msg))
return false;
teacher.location().send(teacher,msg);
return true;
}
protected ExpertiseDefinition createNewExpertiseDefinition(final String ID, final String name, final String baseName)
{
final ExpertiseDefinition definition = new ExpertiseDefinition()
{
private String ID = "";
private String name = "";
private String baseName = "";
private String[] data = new String[0];
private String uncompiledListMask = "";
private String uncompiledFinalMask = "";
private String rawListMask = "";
private String rawFinalMask = "";
private int minLevel = Integer.MIN_VALUE + 1;
private MaskingLibrary.CompiledZMask compiledListMask = null;
private final ExpertiseDefinition parent = null;
private MaskingLibrary.CompiledZMask compiledFinalMask = null;
private final List<CostManager> costs = new LinkedList<CostManager>();
private final Set<XType> xTypes = new HashSet<XType>();
@Override
public String getBaseName()
{
return baseName;
}
@Override
public void setBaseName(final String baseName)
{
this.baseName = baseName;
}
@Override
public void setName(final String name)
{
this.name = name;
}
@Override
public void setID(final String ID)
{
this.ID = ID;
}
@Override
public void setStageNames(final String[] data)
{
this.data = data;
}
@Override
public ExpertiseDefinition getParent()
{
return parent;
}
@Override
public String name()
{
return name;
}
@Override
public int getMinimumLevel()
{
if(minLevel==Integer.MIN_VALUE+1)
minLevel=CMLib.masking().minMaskLevel(allRequirements(),0);
return minLevel;
}
@Override
public String[] getStageNames()
{
return data;
}
@Override
public MaskingLibrary.CompiledZMask compiledListMask()
{
if((this.compiledListMask==null)&&(uncompiledListMask.length()>0))
{
compiledListMask=CMLib.masking().getPreCompiledMask(uncompiledListMask);
CMLib.ableMapper().addPreRequisites(ID,new Vector<String>(),uncompiledListMask.trim());
}
return this.compiledListMask;
}
@Override
public MaskingLibrary.CompiledZMask compiledFinalMask()
{
if((this.compiledFinalMask==null)&&(uncompiledFinalMask.length()>0))
{
this.compiledFinalMask=CMLib.masking().getPreCompiledMask(uncompiledFinalMask);
CMLib.ableMapper().addPreRequisites(ID,new Vector<String>(),uncompiledFinalMask.trim());
}
return this.compiledFinalMask;
}
@Override
public String allRequirements()
{
String req=uncompiledListMask;
if(req==null)
req="";
else
req=req.trim();
if((uncompiledFinalMask!=null)&&(uncompiledFinalMask.length()>0))
req=req+" "+uncompiledFinalMask;
return req.trim();
}
@Override
public String listRequirements()
{
return uncompiledListMask;
}
@Override
public String finalRequirements()
{
return uncompiledFinalMask;
}
@Override
public void addListMask(final String mask)
{
if((mask==null)||(mask.length()==0))
return;
if(uncompiledListMask==null)
uncompiledListMask=mask;
else
uncompiledListMask+=mask;
compiledListMask=null;
}
@Override
public void addFinalMask(final String mask)
{
if((mask==null)||(mask.length()==0))
return;
if(uncompiledFinalMask==null)
uncompiledFinalMask=mask;
else
uncompiledFinalMask+=mask;
compiledFinalMask=CMLib.masking().getPreCompiledMask(uncompiledFinalMask);
CMLib.ableMapper().addPreRequisites(ID,new Vector<String>(),uncompiledFinalMask.trim());
}
@Override
public void addRawMasks(final String listMask, final String finalMask)
{
this.rawListMask = listMask;
this.rawFinalMask = finalMask;
}
@Override
public String rawListMask()
{
return this.rawListMask;
}
@Override
public String rawFinalMask()
{
return this.rawFinalMask;
}
@Override
public void addCost(final CostType type, final Double value)
{
costs.add(CMLib.utensils().createCostManager(type,value));
}
@Override
public String costDescription()
{
final StringBuffer costStr=new StringBuffer("");
for(final CostManager cost : costs)
costStr.append(cost.requirements(null)).append(", ");
if(costStr.length()==0)
return "";
return costStr.substring(0,costStr.length()-2);
}
@Override
public boolean meetsCostRequirements(final MOB mob)
{
for(final CostManager cost : costs)
{
if(!cost.doesMeetCostRequirements(mob))
return false;
}
return true;
}
@Override
public void spendCostRequirements(final MOB mob)
{
for(final CostManager cost : costs)
cost.doSpend(mob);
}
@Override
public int compareTo(final CMObject o)
{
return (o == this) ? 0 : 1;
}
@Override
public String ID()
{
return ID;
}
@Override
public CMObject newInstance()
{
return this;
}
@Override
public CMObject copyOf()
{
return this;
}
@Override
public void initializeClass()
{
}
@Override
public Set<XType> getFlagTypes()
{
return xTypes;
}
};
definition.setID(ID.toUpperCase());
definition.setName(name);
definition.setBaseName(baseName);
return definition;
}
}
| 0 | 0.947309 | 1 | 0.947309 | game-dev | MEDIA | 0.46949 | game-dev | 0.952368 | 1 | 0.952368 |
gurrhack/NetHack-Android | 3,085 | include/region.h | /* NetHack 3.6 region.h $NHDT-Date: 1432512779 2015/05/25 00:12:59 $ $NHDT-Branch: master $:$NHDT-Revision: 1.13 $ */
/* Copyright (c) 1996 by Jean-Christophe Collet */
/* NetHack may be freely redistributed. See license for details. */
#ifndef REGION_H
#define REGION_H
/* generic callback function */
typedef boolean FDECL((*callback_proc), (genericptr_t, genericptr_t));
/*
* player_flags
*/
#define REG_HERO_INSIDE 0x01
#define REG_NOT_HEROS 0x02
#define hero_inside(r) ((r)->player_flags & REG_HERO_INSIDE)
#define heros_fault(r) (!((r)->player_flags & REG_NOT_HEROS))
#define set_hero_inside(r) ((r)->player_flags |= REG_HERO_INSIDE)
#define clear_hero_inside(r) ((r)->player_flags &= ~REG_HERO_INSIDE)
#define set_heros_fault(r) ((r)->player_flags &= ~REG_NOT_HEROS)
#define clear_heros_fault(r) ((r)->player_flags |= REG_NOT_HEROS)
/*
* Note: if you change the size/type of any of the fields below,
* or add any/remove any fields, you must update the
* bwrite() calls in save_regions(), and the
* mread() calls in rest_regions() in src/region.c
* to reflect the changes.
*/
typedef struct {
NhRect bounding_box; /* Bounding box of the region */
NhRect *rects; /* Rectangles composing the region */
short nrects; /* Number of rectangles */
boolean attach_2_u; /* Region attached to player ? */
unsigned int attach_2_m; /* Region attached to monster ? */
/*struct obj *attach_2_o;*/ /* Region attached to object ? UNUSED YET */
const char *enter_msg; /* Message when entering */
const char *leave_msg; /* Message when leaving */
long ttl; /* Time to live. -1 is forever */
short expire_f; /* Function to call when region's ttl expire */
short can_enter_f; /* Function to call to check whether the player
can, or can not, enter the region */
short enter_f; /* Function to call when the player enters*/
short can_leave_f; /* Function to call to check whether the player
can, or can not, leave the region */
short leave_f; /* Function to call when the player leaves */
short inside_f; /* Function to call every turn if player's
inside */
unsigned int player_flags; /* (see above) */
unsigned int *monsters; /* Monsters currently inside this region */
short n_monst; /* Number of monsters inside this region */
short max_monst; /* Maximum number of monsters that can be
listed without having to grow the array */
#define MONST_INC 5
/* Should probably do the same thing about objects */
boolean visible; /* Is the region visible ? */
int glyph; /* Which glyph to use if visible */
anything arg; /* Optional user argument (Ex: strength of
force field, damage of a fire zone, ...*/
} NhRegion;
#endif /* REGION_H */
| 0 | 0.986481 | 1 | 0.986481 | game-dev | MEDIA | 0.928031 | game-dev | 0.971993 | 1 | 0.971993 |
panda3d/panda3d | 4,495 | panda/src/putil/gamepadButton.cxx | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file gamepadButton.cxx
* @author rdb
* @date 2015-08-21
*/
#include "gamepadButton.h"
#include "buttonRegistry.h"
#define DEFINE_GAMEPAD_BUTTON_HANDLE(KeyName) \
static ButtonHandle _##KeyName; \
ButtonHandle GamepadButton::KeyName() { return _##KeyName; }
DEFINE_GAMEPAD_BUTTON_HANDLE(lstick)
DEFINE_GAMEPAD_BUTTON_HANDLE(rstick)
DEFINE_GAMEPAD_BUTTON_HANDLE(lshoulder)
DEFINE_GAMEPAD_BUTTON_HANDLE(rshoulder)
DEFINE_GAMEPAD_BUTTON_HANDLE(ltrigger)
DEFINE_GAMEPAD_BUTTON_HANDLE(rtrigger)
DEFINE_GAMEPAD_BUTTON_HANDLE(lgrip)
DEFINE_GAMEPAD_BUTTON_HANDLE(rgrip)
DEFINE_GAMEPAD_BUTTON_HANDLE(dpad_left)
DEFINE_GAMEPAD_BUTTON_HANDLE(dpad_right)
DEFINE_GAMEPAD_BUTTON_HANDLE(dpad_up)
DEFINE_GAMEPAD_BUTTON_HANDLE(dpad_down)
DEFINE_GAMEPAD_BUTTON_HANDLE(back)
DEFINE_GAMEPAD_BUTTON_HANDLE(guide)
DEFINE_GAMEPAD_BUTTON_HANDLE(start)
DEFINE_GAMEPAD_BUTTON_HANDLE(next)
DEFINE_GAMEPAD_BUTTON_HANDLE(previous)
DEFINE_GAMEPAD_BUTTON_HANDLE(face_a)
DEFINE_GAMEPAD_BUTTON_HANDLE(face_b)
DEFINE_GAMEPAD_BUTTON_HANDLE(face_c)
DEFINE_GAMEPAD_BUTTON_HANDLE(face_x)
DEFINE_GAMEPAD_BUTTON_HANDLE(face_y)
DEFINE_GAMEPAD_BUTTON_HANDLE(face_z)
DEFINE_GAMEPAD_BUTTON_HANDLE(face_1)
DEFINE_GAMEPAD_BUTTON_HANDLE(face_2)
DEFINE_GAMEPAD_BUTTON_HANDLE(trigger)
DEFINE_GAMEPAD_BUTTON_HANDLE(hat_up)
DEFINE_GAMEPAD_BUTTON_HANDLE(hat_down)
DEFINE_GAMEPAD_BUTTON_HANDLE(hat_left)
DEFINE_GAMEPAD_BUTTON_HANDLE(hat_right)
/**
* Returns the ButtonHandle associated with the particular numbered joystick
* button (zero-based), if there is one, or ButtonHandle::none() if there is
* not.
*/
ButtonHandle GamepadButton::
joystick(int button_number) {
if (button_number >= 0) {
// "button1" does not exist, it is called "trigger" instead
static pvector<ButtonHandle> buttons(1, _trigger);
while ((size_t)button_number >= buttons.size()) {
char numstr[20];
sprintf(numstr, "joystick%d", (int)buttons.size() + 1);
ButtonHandle handle;
ButtonRegistry::ptr()->register_button(handle, numstr);
buttons.push_back(handle);
}
return buttons[button_number];
}
return ButtonHandle::none();
}
/**
* This is intended to be called only once, by the static initialization
* performed in config_util.cxx.
*/
void GamepadButton::
init_gamepad_buttons() {
ButtonRegistry::ptr()->register_button(_lstick, "lstick");
ButtonRegistry::ptr()->register_button(_rstick, "rstick");
ButtonRegistry::ptr()->register_button(_lshoulder, "lshoulder");
ButtonRegistry::ptr()->register_button(_rshoulder, "rshoulder");
ButtonRegistry::ptr()->register_button(_ltrigger, "ltrigger");
ButtonRegistry::ptr()->register_button(_rtrigger, "rtrigger");
ButtonRegistry::ptr()->register_button(_lgrip, "lgrip");
ButtonRegistry::ptr()->register_button(_rgrip, "rgrip");
ButtonRegistry::ptr()->register_button(_dpad_left, "dpad_left");
ButtonRegistry::ptr()->register_button(_dpad_right, "dpad_right");
ButtonRegistry::ptr()->register_button(_dpad_up, "dpad_up");
ButtonRegistry::ptr()->register_button(_dpad_down, "dpad_down");
ButtonRegistry::ptr()->register_button(_back, "back");
ButtonRegistry::ptr()->register_button(_guide, "guide");
ButtonRegistry::ptr()->register_button(_start, "start");
ButtonRegistry::ptr()->register_button(_next, "next");
ButtonRegistry::ptr()->register_button(_previous, "previous");
ButtonRegistry::ptr()->register_button(_face_a, "face_a");
ButtonRegistry::ptr()->register_button(_face_b, "face_b");
ButtonRegistry::ptr()->register_button(_face_c, "face_c");
ButtonRegistry::ptr()->register_button(_face_x, "face_x");
ButtonRegistry::ptr()->register_button(_face_y, "face_y");
ButtonRegistry::ptr()->register_button(_face_z, "face_z");
ButtonRegistry::ptr()->register_button(_face_1, "face_1");
ButtonRegistry::ptr()->register_button(_face_2, "face_2");
ButtonRegistry::ptr()->register_button(_trigger, "trigger");
ButtonRegistry::ptr()->register_button(_hat_up, "hat_up");
ButtonRegistry::ptr()->register_button(_hat_down, "hat_down");
ButtonRegistry::ptr()->register_button(_hat_left, "hat_left");
ButtonRegistry::ptr()->register_button(_hat_right, "hat_right");
}
| 0 | 0.967791 | 1 | 0.967791 | game-dev | MEDIA | 0.645696 | game-dev,desktop-app | 0.514417 | 1 | 0.514417 |
crownengine/crown | 82,755 | 3rdparty/bullet3/src/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans https://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.
*/
//#define COMPUTE_IMPULSE_DENOM 1
#ifdef BT_DEBUG
# define BT_ADDITIONAL_DEBUG
#endif
//It is not necessary (redundant) to refresh contact manifolds, this refresh has been moved to the collision algorithms.
#include "btSequentialImpulseConstraintSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
#include "LinearMath/btIDebugDraw.h"
#include "LinearMath/btCpuFeatureUtility.h"
//#include "btJacobianEntry.h"
#include "LinearMath/btMinMax.h"
#include "BulletDynamics/ConstraintSolver/btTypedConstraint.h"
#include <new>
#include "LinearMath/btStackAlloc.h"
#include "LinearMath/btQuickprof.h"
//#include "btSolverBody.h"
//#include "btSolverConstraint.h"
#include "LinearMath/btAlignedObjectArray.h"
#include <string.h> //for memset
int gNumSplitImpulseRecoveries = 0;
#include "BulletDynamics/Dynamics/btRigidBody.h"
//#define VERBOSE_RESIDUAL_PRINTF 1
///This is the scalar reference implementation of solving a single constraint row, the innerloop of the Projected Gauss Seidel/Sequential Impulse constraint solver
///Below are optional SSE2 and SSE4/FMA3 versions. We assume most hardware has SSE2. For SSE4/FMA3 we perform a CPU feature check.
static btScalar gResolveSingleConstraintRowGeneric_scalar_reference(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
{
btScalar deltaImpulse = c.m_rhs - btScalar(c.m_appliedImpulse) * c.m_cfm;
const btScalar deltaVel1Dotn = c.m_contactNormal1.dot(bodyA.internalGetDeltaLinearVelocity()) + c.m_relpos1CrossNormal.dot(bodyA.internalGetDeltaAngularVelocity());
const btScalar deltaVel2Dotn = c.m_contactNormal2.dot(bodyB.internalGetDeltaLinearVelocity()) + c.m_relpos2CrossNormal.dot(bodyB.internalGetDeltaAngularVelocity());
// const btScalar delta_rel_vel = deltaVel1Dotn-deltaVel2Dotn;
deltaImpulse -= deltaVel1Dotn * c.m_jacDiagABInv;
deltaImpulse -= deltaVel2Dotn * c.m_jacDiagABInv;
const btScalar sum = btScalar(c.m_appliedImpulse) + deltaImpulse;
if (sum < c.m_lowerLimit)
{
deltaImpulse = c.m_lowerLimit - c.m_appliedImpulse;
c.m_appliedImpulse = c.m_lowerLimit;
}
else if (sum > c.m_upperLimit)
{
deltaImpulse = c.m_upperLimit - c.m_appliedImpulse;
c.m_appliedImpulse = c.m_upperLimit;
}
else
{
c.m_appliedImpulse = sum;
}
bodyA.internalApplyImpulse(c.m_contactNormal1 * bodyA.internalGetInvMass(), c.m_angularComponentA, deltaImpulse);
bodyB.internalApplyImpulse(c.m_contactNormal2 * bodyB.internalGetInvMass(), c.m_angularComponentB, deltaImpulse);
return deltaImpulse * (1. / c.m_jacDiagABInv);
}
static btScalar gResolveSingleConstraintRowLowerLimit_scalar_reference(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
{
btScalar deltaImpulse = c.m_rhs - btScalar(c.m_appliedImpulse) * c.m_cfm;
const btScalar deltaVel1Dotn = c.m_contactNormal1.dot(bodyA.internalGetDeltaLinearVelocity()) + c.m_relpos1CrossNormal.dot(bodyA.internalGetDeltaAngularVelocity());
const btScalar deltaVel2Dotn = c.m_contactNormal2.dot(bodyB.internalGetDeltaLinearVelocity()) + c.m_relpos2CrossNormal.dot(bodyB.internalGetDeltaAngularVelocity());
deltaImpulse -= deltaVel1Dotn * c.m_jacDiagABInv;
deltaImpulse -= deltaVel2Dotn * c.m_jacDiagABInv;
const btScalar sum = btScalar(c.m_appliedImpulse) + deltaImpulse;
if (sum < c.m_lowerLimit)
{
deltaImpulse = c.m_lowerLimit - c.m_appliedImpulse;
c.m_appliedImpulse = c.m_lowerLimit;
}
else
{
c.m_appliedImpulse = sum;
}
bodyA.internalApplyImpulse(c.m_contactNormal1 * bodyA.internalGetInvMass(), c.m_angularComponentA, deltaImpulse);
bodyB.internalApplyImpulse(c.m_contactNormal2 * bodyB.internalGetInvMass(), c.m_angularComponentB, deltaImpulse);
return deltaImpulse * (1. / c.m_jacDiagABInv);
}
#ifdef USE_SIMD
#include <emmintrin.h>
#define btVecSplat(x, e) _mm_shuffle_ps(x, x, _MM_SHUFFLE(e, e, e, e))
static inline __m128 btSimdDot3(__m128 vec0, __m128 vec1)
{
__m128 result = _mm_mul_ps(vec0, vec1);
return _mm_add_ps(btVecSplat(result, 0), _mm_add_ps(btVecSplat(result, 1), btVecSplat(result, 2)));
}
#if defined(BT_ALLOW_SSE4)
#include <intrin.h>
#define USE_FMA 1
#define USE_FMA3_INSTEAD_FMA4 1
#define USE_SSE4_DOT 1
#define SSE4_DP(a, b) _mm_dp_ps(a, b, 0x7f)
#define SSE4_DP_FP(a, b) _mm_cvtss_f32(_mm_dp_ps(a, b, 0x7f))
#if USE_SSE4_DOT
#define DOT_PRODUCT(a, b) SSE4_DP(a, b)
#else
#define DOT_PRODUCT(a, b) btSimdDot3(a, b)
#endif
#if USE_FMA
#if USE_FMA3_INSTEAD_FMA4
// a*b + c
#define FMADD(a, b, c) _mm_fmadd_ps(a, b, c)
// -(a*b) + c
#define FMNADD(a, b, c) _mm_fnmadd_ps(a, b, c)
#else // USE_FMA3
// a*b + c
#define FMADD(a, b, c) _mm_macc_ps(a, b, c)
// -(a*b) + c
#define FMNADD(a, b, c) _mm_nmacc_ps(a, b, c)
#endif
#else // USE_FMA
// c + a*b
#define FMADD(a, b, c) _mm_add_ps(c, _mm_mul_ps(a, b))
// c - a*b
#define FMNADD(a, b, c) _mm_sub_ps(c, _mm_mul_ps(a, b))
#endif
#endif
// Project Gauss Seidel or the equivalent Sequential Impulse
static btScalar gResolveSingleConstraintRowGeneric_sse2(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
{
__m128 cpAppliedImp = _mm_set1_ps(c.m_appliedImpulse);
__m128 lowerLimit1 = _mm_set1_ps(c.m_lowerLimit);
__m128 upperLimit1 = _mm_set1_ps(c.m_upperLimit);
btSimdScalar deltaImpulse = _mm_sub_ps(_mm_set1_ps(c.m_rhs), _mm_mul_ps(_mm_set1_ps(c.m_appliedImpulse), _mm_set1_ps(c.m_cfm)));
__m128 deltaVel1Dotn = _mm_add_ps(btSimdDot3(c.m_contactNormal1.mVec128, bodyA.internalGetDeltaLinearVelocity().mVec128), btSimdDot3(c.m_relpos1CrossNormal.mVec128, bodyA.internalGetDeltaAngularVelocity().mVec128));
__m128 deltaVel2Dotn = _mm_add_ps(btSimdDot3(c.m_contactNormal2.mVec128, bodyB.internalGetDeltaLinearVelocity().mVec128), btSimdDot3(c.m_relpos2CrossNormal.mVec128, bodyB.internalGetDeltaAngularVelocity().mVec128));
deltaImpulse = _mm_sub_ps(deltaImpulse, _mm_mul_ps(deltaVel1Dotn, _mm_set1_ps(c.m_jacDiagABInv)));
deltaImpulse = _mm_sub_ps(deltaImpulse, _mm_mul_ps(deltaVel2Dotn, _mm_set1_ps(c.m_jacDiagABInv)));
btSimdScalar sum = _mm_add_ps(cpAppliedImp, deltaImpulse);
btSimdScalar resultLowerLess, resultUpperLess;
resultLowerLess = _mm_cmplt_ps(sum, lowerLimit1);
resultUpperLess = _mm_cmplt_ps(sum, upperLimit1);
__m128 lowMinApplied = _mm_sub_ps(lowerLimit1, cpAppliedImp);
deltaImpulse = _mm_or_ps(_mm_and_ps(resultLowerLess, lowMinApplied), _mm_andnot_ps(resultLowerLess, deltaImpulse));
c.m_appliedImpulse = _mm_or_ps(_mm_and_ps(resultLowerLess, lowerLimit1), _mm_andnot_ps(resultLowerLess, sum));
__m128 upperMinApplied = _mm_sub_ps(upperLimit1, cpAppliedImp);
deltaImpulse = _mm_or_ps(_mm_and_ps(resultUpperLess, deltaImpulse), _mm_andnot_ps(resultUpperLess, upperMinApplied));
c.m_appliedImpulse = _mm_or_ps(_mm_and_ps(resultUpperLess, c.m_appliedImpulse), _mm_andnot_ps(resultUpperLess, upperLimit1));
__m128 linearComponentA = _mm_mul_ps(c.m_contactNormal1.mVec128, bodyA.internalGetInvMass().mVec128);
__m128 linearComponentB = _mm_mul_ps((c.m_contactNormal2).mVec128, bodyB.internalGetInvMass().mVec128);
__m128 impulseMagnitude = deltaImpulse;
bodyA.internalGetDeltaLinearVelocity().mVec128 = _mm_add_ps(bodyA.internalGetDeltaLinearVelocity().mVec128, _mm_mul_ps(linearComponentA, impulseMagnitude));
bodyA.internalGetDeltaAngularVelocity().mVec128 = _mm_add_ps(bodyA.internalGetDeltaAngularVelocity().mVec128, _mm_mul_ps(c.m_angularComponentA.mVec128, impulseMagnitude));
bodyB.internalGetDeltaLinearVelocity().mVec128 = _mm_add_ps(bodyB.internalGetDeltaLinearVelocity().mVec128, _mm_mul_ps(linearComponentB, impulseMagnitude));
bodyB.internalGetDeltaAngularVelocity().mVec128 = _mm_add_ps(bodyB.internalGetDeltaAngularVelocity().mVec128, _mm_mul_ps(c.m_angularComponentB.mVec128, impulseMagnitude));
return deltaImpulse.x / c.m_jacDiagABInv;
}
// Enhanced version of gResolveSingleConstraintRowGeneric_sse2 with SSE4.1 and FMA3
static btScalar gResolveSingleConstraintRowGeneric_sse4_1_fma3(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
{
#if defined(BT_ALLOW_SSE4)
__m128 tmp = _mm_set_ps1(c.m_jacDiagABInv);
__m128 deltaImpulse = _mm_set_ps1(c.m_rhs - btScalar(c.m_appliedImpulse) * c.m_cfm);
const __m128 lowerLimit = _mm_set_ps1(c.m_lowerLimit);
const __m128 upperLimit = _mm_set_ps1(c.m_upperLimit);
const __m128 deltaVel1Dotn = _mm_add_ps(DOT_PRODUCT(c.m_contactNormal1.mVec128, bodyA.internalGetDeltaLinearVelocity().mVec128), DOT_PRODUCT(c.m_relpos1CrossNormal.mVec128, bodyA.internalGetDeltaAngularVelocity().mVec128));
const __m128 deltaVel2Dotn = _mm_add_ps(DOT_PRODUCT(c.m_contactNormal2.mVec128, bodyB.internalGetDeltaLinearVelocity().mVec128), DOT_PRODUCT(c.m_relpos2CrossNormal.mVec128, bodyB.internalGetDeltaAngularVelocity().mVec128));
deltaImpulse = FMNADD(deltaVel1Dotn, tmp, deltaImpulse);
deltaImpulse = FMNADD(deltaVel2Dotn, tmp, deltaImpulse);
tmp = _mm_add_ps(c.m_appliedImpulse, deltaImpulse); // sum
const __m128 maskLower = _mm_cmpgt_ps(tmp, lowerLimit);
const __m128 maskUpper = _mm_cmpgt_ps(upperLimit, tmp);
deltaImpulse = _mm_blendv_ps(_mm_sub_ps(lowerLimit, c.m_appliedImpulse), _mm_blendv_ps(_mm_sub_ps(upperLimit, c.m_appliedImpulse), deltaImpulse, maskUpper), maskLower);
c.m_appliedImpulse = _mm_blendv_ps(lowerLimit, _mm_blendv_ps(upperLimit, tmp, maskUpper), maskLower);
bodyA.internalGetDeltaLinearVelocity().mVec128 = FMADD(_mm_mul_ps(c.m_contactNormal1.mVec128, bodyA.internalGetInvMass().mVec128), deltaImpulse, bodyA.internalGetDeltaLinearVelocity().mVec128);
bodyA.internalGetDeltaAngularVelocity().mVec128 = FMADD(c.m_angularComponentA.mVec128, deltaImpulse, bodyA.internalGetDeltaAngularVelocity().mVec128);
bodyB.internalGetDeltaLinearVelocity().mVec128 = FMADD(_mm_mul_ps(c.m_contactNormal2.mVec128, bodyB.internalGetInvMass().mVec128), deltaImpulse, bodyB.internalGetDeltaLinearVelocity().mVec128);
bodyB.internalGetDeltaAngularVelocity().mVec128 = FMADD(c.m_angularComponentB.mVec128, deltaImpulse, bodyB.internalGetDeltaAngularVelocity().mVec128);
btSimdScalar deltaImp = deltaImpulse;
return deltaImp.x * (1. / c.m_jacDiagABInv);
#else
return gResolveSingleConstraintRowGeneric_sse2(bodyA, bodyB, c);
#endif
}
static btScalar gResolveSingleConstraintRowLowerLimit_sse2(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
{
__m128 cpAppliedImp = _mm_set1_ps(c.m_appliedImpulse);
__m128 lowerLimit1 = _mm_set1_ps(c.m_lowerLimit);
__m128 upperLimit1 = _mm_set1_ps(c.m_upperLimit);
btSimdScalar deltaImpulse = _mm_sub_ps(_mm_set1_ps(c.m_rhs), _mm_mul_ps(_mm_set1_ps(c.m_appliedImpulse), _mm_set1_ps(c.m_cfm)));
__m128 deltaVel1Dotn = _mm_add_ps(btSimdDot3(c.m_contactNormal1.mVec128, bodyA.internalGetDeltaLinearVelocity().mVec128), btSimdDot3(c.m_relpos1CrossNormal.mVec128, bodyA.internalGetDeltaAngularVelocity().mVec128));
__m128 deltaVel2Dotn = _mm_add_ps(btSimdDot3(c.m_contactNormal2.mVec128, bodyB.internalGetDeltaLinearVelocity().mVec128), btSimdDot3(c.m_relpos2CrossNormal.mVec128, bodyB.internalGetDeltaAngularVelocity().mVec128));
deltaImpulse = _mm_sub_ps(deltaImpulse, _mm_mul_ps(deltaVel1Dotn, _mm_set1_ps(c.m_jacDiagABInv)));
deltaImpulse = _mm_sub_ps(deltaImpulse, _mm_mul_ps(deltaVel2Dotn, _mm_set1_ps(c.m_jacDiagABInv)));
btSimdScalar sum = _mm_add_ps(cpAppliedImp, deltaImpulse);
btSimdScalar resultLowerLess, resultUpperLess;
resultLowerLess = _mm_cmplt_ps(sum, lowerLimit1);
resultUpperLess = _mm_cmplt_ps(sum, upperLimit1);
__m128 lowMinApplied = _mm_sub_ps(lowerLimit1, cpAppliedImp);
deltaImpulse = _mm_or_ps(_mm_and_ps(resultLowerLess, lowMinApplied), _mm_andnot_ps(resultLowerLess, deltaImpulse));
c.m_appliedImpulse = _mm_or_ps(_mm_and_ps(resultLowerLess, lowerLimit1), _mm_andnot_ps(resultLowerLess, sum));
__m128 linearComponentA = _mm_mul_ps(c.m_contactNormal1.mVec128, bodyA.internalGetInvMass().mVec128);
__m128 linearComponentB = _mm_mul_ps(c.m_contactNormal2.mVec128, bodyB.internalGetInvMass().mVec128);
__m128 impulseMagnitude = deltaImpulse;
bodyA.internalGetDeltaLinearVelocity().mVec128 = _mm_add_ps(bodyA.internalGetDeltaLinearVelocity().mVec128, _mm_mul_ps(linearComponentA, impulseMagnitude));
bodyA.internalGetDeltaAngularVelocity().mVec128 = _mm_add_ps(bodyA.internalGetDeltaAngularVelocity().mVec128, _mm_mul_ps(c.m_angularComponentA.mVec128, impulseMagnitude));
bodyB.internalGetDeltaLinearVelocity().mVec128 = _mm_add_ps(bodyB.internalGetDeltaLinearVelocity().mVec128, _mm_mul_ps(linearComponentB, impulseMagnitude));
bodyB.internalGetDeltaAngularVelocity().mVec128 = _mm_add_ps(bodyB.internalGetDeltaAngularVelocity().mVec128, _mm_mul_ps(c.m_angularComponentB.mVec128, impulseMagnitude));
return deltaImpulse.x / c.m_jacDiagABInv;
}
// Enhanced version of gResolveSingleConstraintRowGeneric_sse2 with SSE4.1 and FMA3
static btScalar gResolveSingleConstraintRowLowerLimit_sse4_1_fma3(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
{
#ifdef BT_ALLOW_SSE4
__m128 tmp = _mm_set_ps1(c.m_jacDiagABInv);
__m128 deltaImpulse = _mm_set_ps1(c.m_rhs - btScalar(c.m_appliedImpulse) * c.m_cfm);
const __m128 lowerLimit = _mm_set_ps1(c.m_lowerLimit);
const __m128 deltaVel1Dotn = _mm_add_ps(DOT_PRODUCT(c.m_contactNormal1.mVec128, bodyA.internalGetDeltaLinearVelocity().mVec128), DOT_PRODUCT(c.m_relpos1CrossNormal.mVec128, bodyA.internalGetDeltaAngularVelocity().mVec128));
const __m128 deltaVel2Dotn = _mm_add_ps(DOT_PRODUCT(c.m_contactNormal2.mVec128, bodyB.internalGetDeltaLinearVelocity().mVec128), DOT_PRODUCT(c.m_relpos2CrossNormal.mVec128, bodyB.internalGetDeltaAngularVelocity().mVec128));
deltaImpulse = FMNADD(deltaVel1Dotn, tmp, deltaImpulse);
deltaImpulse = FMNADD(deltaVel2Dotn, tmp, deltaImpulse);
tmp = _mm_add_ps(c.m_appliedImpulse, deltaImpulse);
const __m128 mask = _mm_cmpgt_ps(tmp, lowerLimit);
deltaImpulse = _mm_blendv_ps(_mm_sub_ps(lowerLimit, c.m_appliedImpulse), deltaImpulse, mask);
c.m_appliedImpulse = _mm_blendv_ps(lowerLimit, tmp, mask);
bodyA.internalGetDeltaLinearVelocity().mVec128 = FMADD(_mm_mul_ps(c.m_contactNormal1.mVec128, bodyA.internalGetInvMass().mVec128), deltaImpulse, bodyA.internalGetDeltaLinearVelocity().mVec128);
bodyA.internalGetDeltaAngularVelocity().mVec128 = FMADD(c.m_angularComponentA.mVec128, deltaImpulse, bodyA.internalGetDeltaAngularVelocity().mVec128);
bodyB.internalGetDeltaLinearVelocity().mVec128 = FMADD(_mm_mul_ps(c.m_contactNormal2.mVec128, bodyB.internalGetInvMass().mVec128), deltaImpulse, bodyB.internalGetDeltaLinearVelocity().mVec128);
bodyB.internalGetDeltaAngularVelocity().mVec128 = FMADD(c.m_angularComponentB.mVec128, deltaImpulse, bodyB.internalGetDeltaAngularVelocity().mVec128);
btSimdScalar deltaImp = deltaImpulse;
return deltaImp.x * (1. / c.m_jacDiagABInv);
#else
return gResolveSingleConstraintRowLowerLimit_sse2(bodyA, bodyB, c);
#endif //BT_ALLOW_SSE4
}
#endif //USE_SIMD
btScalar btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGenericSIMD(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
{
return m_resolveSingleConstraintRowGeneric(bodyA, bodyB, c);
}
// Project Gauss Seidel or the equivalent Sequential Impulse
btScalar btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGeneric(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
{
return m_resolveSingleConstraintRowGeneric(bodyA, bodyB, c);
}
btScalar btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimitSIMD(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
{
return m_resolveSingleConstraintRowLowerLimit(bodyA, bodyB, c);
}
btScalar btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimit(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
{
return m_resolveSingleConstraintRowLowerLimit(bodyA, bodyB, c);
}
static btScalar gResolveSplitPenetrationImpulse_scalar_reference(
btSolverBody& bodyA,
btSolverBody& bodyB,
const btSolverConstraint& c)
{
btScalar deltaImpulse = 0.f;
if (c.m_rhsPenetration)
{
gNumSplitImpulseRecoveries++;
deltaImpulse = c.m_rhsPenetration - btScalar(c.m_appliedPushImpulse) * c.m_cfm;
const btScalar deltaVel1Dotn = c.m_contactNormal1.dot(bodyA.internalGetPushVelocity()) + c.m_relpos1CrossNormal.dot(bodyA.internalGetTurnVelocity());
const btScalar deltaVel2Dotn = c.m_contactNormal2.dot(bodyB.internalGetPushVelocity()) + c.m_relpos2CrossNormal.dot(bodyB.internalGetTurnVelocity());
deltaImpulse -= deltaVel1Dotn * c.m_jacDiagABInv;
deltaImpulse -= deltaVel2Dotn * c.m_jacDiagABInv;
const btScalar sum = btScalar(c.m_appliedPushImpulse) + deltaImpulse;
if (sum < c.m_lowerLimit)
{
deltaImpulse = c.m_lowerLimit - c.m_appliedPushImpulse;
c.m_appliedPushImpulse = c.m_lowerLimit;
}
else
{
c.m_appliedPushImpulse = sum;
}
bodyA.internalApplyPushImpulse(c.m_contactNormal1 * bodyA.internalGetInvMass(), c.m_angularComponentA, deltaImpulse);
bodyB.internalApplyPushImpulse(c.m_contactNormal2 * bodyB.internalGetInvMass(), c.m_angularComponentB, deltaImpulse);
}
return deltaImpulse * (1. / c.m_jacDiagABInv);
}
static btScalar gResolveSplitPenetrationImpulse_sse2(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
{
#ifdef USE_SIMD
if (!c.m_rhsPenetration)
return 0.f;
gNumSplitImpulseRecoveries++;
__m128 cpAppliedImp = _mm_set1_ps(c.m_appliedPushImpulse);
__m128 lowerLimit1 = _mm_set1_ps(c.m_lowerLimit);
__m128 upperLimit1 = _mm_set1_ps(c.m_upperLimit);
__m128 deltaImpulse = _mm_sub_ps(_mm_set1_ps(c.m_rhsPenetration), _mm_mul_ps(_mm_set1_ps(c.m_appliedPushImpulse), _mm_set1_ps(c.m_cfm)));
__m128 deltaVel1Dotn = _mm_add_ps(btSimdDot3(c.m_contactNormal1.mVec128, bodyA.internalGetPushVelocity().mVec128), btSimdDot3(c.m_relpos1CrossNormal.mVec128, bodyA.internalGetTurnVelocity().mVec128));
__m128 deltaVel2Dotn = _mm_add_ps(btSimdDot3(c.m_contactNormal2.mVec128, bodyB.internalGetPushVelocity().mVec128), btSimdDot3(c.m_relpos2CrossNormal.mVec128, bodyB.internalGetTurnVelocity().mVec128));
deltaImpulse = _mm_sub_ps(deltaImpulse, _mm_mul_ps(deltaVel1Dotn, _mm_set1_ps(c.m_jacDiagABInv)));
deltaImpulse = _mm_sub_ps(deltaImpulse, _mm_mul_ps(deltaVel2Dotn, _mm_set1_ps(c.m_jacDiagABInv)));
btSimdScalar sum = _mm_add_ps(cpAppliedImp, deltaImpulse);
btSimdScalar resultLowerLess, resultUpperLess;
resultLowerLess = _mm_cmplt_ps(sum, lowerLimit1);
resultUpperLess = _mm_cmplt_ps(sum, upperLimit1);
__m128 lowMinApplied = _mm_sub_ps(lowerLimit1, cpAppliedImp);
deltaImpulse = _mm_or_ps(_mm_and_ps(resultLowerLess, lowMinApplied), _mm_andnot_ps(resultLowerLess, deltaImpulse));
c.m_appliedPushImpulse = _mm_or_ps(_mm_and_ps(resultLowerLess, lowerLimit1), _mm_andnot_ps(resultLowerLess, sum));
__m128 linearComponentA = _mm_mul_ps(c.m_contactNormal1.mVec128, bodyA.internalGetInvMass().mVec128);
__m128 linearComponentB = _mm_mul_ps(c.m_contactNormal2.mVec128, bodyB.internalGetInvMass().mVec128);
__m128 impulseMagnitude = deltaImpulse;
bodyA.internalGetPushVelocity().mVec128 = _mm_add_ps(bodyA.internalGetPushVelocity().mVec128, _mm_mul_ps(linearComponentA, impulseMagnitude));
bodyA.internalGetTurnVelocity().mVec128 = _mm_add_ps(bodyA.internalGetTurnVelocity().mVec128, _mm_mul_ps(c.m_angularComponentA.mVec128, impulseMagnitude));
bodyB.internalGetPushVelocity().mVec128 = _mm_add_ps(bodyB.internalGetPushVelocity().mVec128, _mm_mul_ps(linearComponentB, impulseMagnitude));
bodyB.internalGetTurnVelocity().mVec128 = _mm_add_ps(bodyB.internalGetTurnVelocity().mVec128, _mm_mul_ps(c.m_angularComponentB.mVec128, impulseMagnitude));
btSimdScalar deltaImp = deltaImpulse;
return deltaImp.x * (1. / c.m_jacDiagABInv);
#else
return gResolveSplitPenetrationImpulse_scalar_reference(bodyA, bodyB, c);
#endif
}
btSequentialImpulseConstraintSolver::btSequentialImpulseConstraintSolver()
{
m_btSeed2 = 0;
m_cachedSolverMode = 0;
setupSolverFunctions(false);
}
void btSequentialImpulseConstraintSolver::setupSolverFunctions(bool useSimd)
{
m_resolveSingleConstraintRowGeneric = gResolveSingleConstraintRowGeneric_scalar_reference;
m_resolveSingleConstraintRowLowerLimit = gResolveSingleConstraintRowLowerLimit_scalar_reference;
m_resolveSplitPenetrationImpulse = gResolveSplitPenetrationImpulse_scalar_reference;
if (useSimd)
{
#ifdef USE_SIMD
m_resolveSingleConstraintRowGeneric = gResolveSingleConstraintRowGeneric_sse2;
m_resolveSingleConstraintRowLowerLimit = gResolveSingleConstraintRowLowerLimit_sse2;
m_resolveSplitPenetrationImpulse = gResolveSplitPenetrationImpulse_sse2;
#ifdef BT_ALLOW_SSE4
int cpuFeatures = btCpuFeatureUtility::getCpuFeatures();
if ((cpuFeatures & btCpuFeatureUtility::CPU_FEATURE_FMA3) && (cpuFeatures & btCpuFeatureUtility::CPU_FEATURE_SSE4_1))
{
m_resolveSingleConstraintRowGeneric = gResolveSingleConstraintRowGeneric_sse4_1_fma3;
m_resolveSingleConstraintRowLowerLimit = gResolveSingleConstraintRowLowerLimit_sse4_1_fma3;
}
#endif //BT_ALLOW_SSE4
#endif //USE_SIMD
}
}
btSequentialImpulseConstraintSolver::~btSequentialImpulseConstraintSolver()
{
}
btSingleConstraintRowSolver btSequentialImpulseConstraintSolver::getScalarConstraintRowSolverGeneric()
{
return gResolveSingleConstraintRowGeneric_scalar_reference;
}
btSingleConstraintRowSolver btSequentialImpulseConstraintSolver::getScalarConstraintRowSolverLowerLimit()
{
return gResolveSingleConstraintRowLowerLimit_scalar_reference;
}
#ifdef USE_SIMD
btSingleConstraintRowSolver btSequentialImpulseConstraintSolver::getSSE2ConstraintRowSolverGeneric()
{
return gResolveSingleConstraintRowGeneric_sse2;
}
btSingleConstraintRowSolver btSequentialImpulseConstraintSolver::getSSE2ConstraintRowSolverLowerLimit()
{
return gResolveSingleConstraintRowLowerLimit_sse2;
}
#ifdef BT_ALLOW_SSE4
btSingleConstraintRowSolver btSequentialImpulseConstraintSolver::getSSE4_1ConstraintRowSolverGeneric()
{
return gResolveSingleConstraintRowGeneric_sse4_1_fma3;
}
btSingleConstraintRowSolver btSequentialImpulseConstraintSolver::getSSE4_1ConstraintRowSolverLowerLimit()
{
return gResolveSingleConstraintRowLowerLimit_sse4_1_fma3;
}
#endif //BT_ALLOW_SSE4
#endif //USE_SIMD
unsigned long btSequentialImpulseConstraintSolver::btRand2()
{
m_btSeed2 = (1664525L * m_btSeed2 + 1013904223L) & 0xffffffff;
return m_btSeed2;
}
//See ODE: adam's all-int straightforward(?) dRandInt (0..n-1)
int btSequentialImpulseConstraintSolver::btRandInt2(int n)
{
// seems good; xor-fold and modulus
const unsigned long un = static_cast<unsigned long>(n);
unsigned long r = btRand2();
// note: probably more aggressive than it needs to be -- might be
// able to get away without one or two of the innermost branches.
if (un <= 0x00010000UL)
{
r ^= (r >> 16);
if (un <= 0x00000100UL)
{
r ^= (r >> 8);
if (un <= 0x00000010UL)
{
r ^= (r >> 4);
if (un <= 0x00000004UL)
{
r ^= (r >> 2);
if (un <= 0x00000002UL)
{
r ^= (r >> 1);
}
}
}
}
}
return (int)(r % un);
}
void btSequentialImpulseConstraintSolver::initSolverBody(btSolverBody* solverBody, btCollisionObject* collisionObject, btScalar timeStep)
{
btRigidBody* rb = collisionObject ? btRigidBody::upcast(collisionObject) : 0;
solverBody->internalGetDeltaLinearVelocity().setValue(0.f, 0.f, 0.f);
solverBody->internalGetDeltaAngularVelocity().setValue(0.f, 0.f, 0.f);
solverBody->internalGetPushVelocity().setValue(0.f, 0.f, 0.f);
solverBody->internalGetTurnVelocity().setValue(0.f, 0.f, 0.f);
if (rb)
{
solverBody->m_worldTransform = rb->m_worldTransform;
solverBody->internalSetInvMass(btVector3(rb->m_inverseMass, rb->m_inverseMass, rb->m_inverseMass) * rb->m_linearFactor);
solverBody->m_originalBody = rb;
solverBody->m_angularFactor = rb->m_angularFactor;
solverBody->m_linearFactor = rb->m_linearFactor;
solverBody->m_linearVelocity = rb->m_linearVelocity;
solverBody->m_angularVelocity = rb->m_angularVelocity;
solverBody->m_externalForceImpulse = rb->m_totalForce * rb->m_inverseMass * timeStep;
solverBody->m_externalTorqueImpulse = rb->m_totalTorque * rb->m_invInertiaTensorWorld * timeStep;
}
else
{
solverBody->m_worldTransform.setIdentity();
solverBody->internalSetInvMass(btVector3(0, 0, 0));
solverBody->m_originalBody = 0;
solverBody->m_angularFactor.setValue(1, 1, 1);
solverBody->m_linearFactor.setValue(1, 1, 1);
solverBody->m_linearVelocity.setValue(0, 0, 0);
solverBody->m_angularVelocity.setValue(0, 0, 0);
solverBody->m_externalForceImpulse.setValue(0, 0, 0);
solverBody->m_externalTorqueImpulse.setValue(0, 0, 0);
}
}
btScalar btSequentialImpulseConstraintSolver::restitutionCurve(btScalar rel_vel, btScalar restitution, btScalar velocityThreshold)
{
//printf("rel_vel =%f\n", rel_vel);
if (btFabs(rel_vel) < velocityThreshold)
return 0.;
btScalar rest = restitution * -rel_vel;
return rest;
}
void btSequentialImpulseConstraintSolver::applyAnisotropicFriction(btCollisionObject* colObj, btVector3& frictionDirection, int frictionMode)
{
if (colObj && colObj->hasAnisotropicFriction(frictionMode))
{
// transform to local coordinates
btVector3 loc_lateral = frictionDirection * colObj->m_worldTransform.m_basis;
const btVector3& friction_scaling = colObj->m_anisotropicFriction;
//apply anisotropic friction
loc_lateral *= friction_scaling;
// ... and transform it back to global coordinates
frictionDirection = colObj->m_worldTransform.m_basis * loc_lateral;
}
}
void btSequentialImpulseConstraintSolver::setupFrictionConstraint(btSolverConstraint& solverConstraint, const btVector3& normalAxis, int solverBodyIdA, int solverBodyIdB, btManifoldPoint& cp, const btVector3& rel_pos1, const btVector3& rel_pos2, btCollisionObject* colObj0, btCollisionObject* colObj1, btScalar relaxation, const btContactSolverInfo& infoGlobal, btScalar desiredVelocity, btScalar cfmSlip)
{
btSolverBody& solverBodyA = m_tmpSolverBodyPool[solverBodyIdA];
btSolverBody& solverBodyB = m_tmpSolverBodyPool[solverBodyIdB];
btRigidBody* body0 = m_tmpSolverBodyPool[solverBodyIdA].m_originalBody;
btRigidBody* bodyA = m_tmpSolverBodyPool[solverBodyIdB].m_originalBody;
solverConstraint.m_solverBodyIdA = solverBodyIdA;
solverConstraint.m_solverBodyIdB = solverBodyIdB;
solverConstraint.m_friction = cp.m_combinedFriction;
solverConstraint.m_originalContactPoint = 0;
solverConstraint.m_appliedImpulse = 0.f;
solverConstraint.m_appliedPushImpulse = 0.f;
if (body0)
{
solverConstraint.m_contactNormal1 = normalAxis;
btVector3 ftorqueAxis1 = rel_pos1.cross(solverConstraint.m_contactNormal1);
solverConstraint.m_relpos1CrossNormal = ftorqueAxis1;
solverConstraint.m_angularComponentA = body0->m_invInertiaTensorWorld * ftorqueAxis1 * body0->m_angularFactor;
}
else
{
solverConstraint.m_contactNormal1.setZero();
solverConstraint.m_relpos1CrossNormal.setZero();
solverConstraint.m_angularComponentA.setZero();
}
if (bodyA)
{
solverConstraint.m_contactNormal2 = -normalAxis;
btVector3 ftorqueAxis1 = rel_pos2.cross(solverConstraint.m_contactNormal2);
solverConstraint.m_relpos2CrossNormal = ftorqueAxis1;
solverConstraint.m_angularComponentB = bodyA->m_invInertiaTensorWorld * ftorqueAxis1 * bodyA->m_angularFactor;
}
else
{
solverConstraint.m_contactNormal2.setZero();
solverConstraint.m_relpos2CrossNormal.setZero();
solverConstraint.m_angularComponentB.setZero();
}
{
btVector3 vec;
btScalar denom0 = 0.f;
btScalar denom1 = 0.f;
if (body0)
{
vec = (solverConstraint.m_angularComponentA).cross(rel_pos1);
denom0 = body0->m_inverseMass + normalAxis.dot(vec);
}
if (bodyA)
{
vec = (-solverConstraint.m_angularComponentB).cross(rel_pos2);
denom1 = bodyA->m_inverseMass + normalAxis.dot(vec);
}
btScalar denom = relaxation / (denom0 + denom1);
solverConstraint.m_jacDiagABInv = denom;
}
{
btScalar rel_vel;
btScalar vel1Dotn = solverConstraint.m_contactNormal1.dot(body0 ? solverBodyA.m_linearVelocity + solverBodyA.m_externalForceImpulse : btVector3(0, 0, 0)) + solverConstraint.m_relpos1CrossNormal.dot(body0 ? solverBodyA.m_angularVelocity : btVector3(0, 0, 0));
btScalar vel2Dotn = solverConstraint.m_contactNormal2.dot(bodyA ? solverBodyB.m_linearVelocity + solverBodyB.m_externalForceImpulse : btVector3(0, 0, 0)) + solverConstraint.m_relpos2CrossNormal.dot(bodyA ? solverBodyB.m_angularVelocity : btVector3(0, 0, 0));
rel_vel = vel1Dotn + vel2Dotn;
// btScalar positionalError = 0.f;
btScalar velocityError = desiredVelocity - rel_vel;
btScalar velocityImpulse = velocityError * solverConstraint.m_jacDiagABInv;
btScalar penetrationImpulse = btScalar(0);
if (cp.m_contactPointFlags & BT_CONTACT_FLAG_FRICTION_ANCHOR)
{
btScalar distance = (cp.getPositionWorldOnA() - cp.getPositionWorldOnB()).dot(normalAxis);
btScalar positionalError = -distance * infoGlobal.m_frictionERP / infoGlobal.m_timeStep;
penetrationImpulse = positionalError * solverConstraint.m_jacDiagABInv;
}
solverConstraint.m_rhs = penetrationImpulse + velocityImpulse;
solverConstraint.m_rhsPenetration = 0.f;
solverConstraint.m_cfm = cfmSlip;
solverConstraint.m_lowerLimit = -solverConstraint.m_friction;
solverConstraint.m_upperLimit = solverConstraint.m_friction;
}
}
btSolverConstraint& btSequentialImpulseConstraintSolver::addFrictionConstraint(const btVector3& normalAxis, int solverBodyIdA, int solverBodyIdB, int frictionIndex, btManifoldPoint& cp, const btVector3& rel_pos1, const btVector3& rel_pos2, btCollisionObject* colObj0, btCollisionObject* colObj1, btScalar relaxation, const btContactSolverInfo& infoGlobal, btScalar desiredVelocity, btScalar cfmSlip)
{
btSolverConstraint& solverConstraint = m_tmpSolverContactFrictionConstraintPool.expandNonInitializing();
solverConstraint.m_frictionIndex = frictionIndex;
setupFrictionConstraint(solverConstraint, normalAxis, solverBodyIdA, solverBodyIdB, cp, rel_pos1, rel_pos2,
colObj0, colObj1, relaxation, infoGlobal, desiredVelocity, cfmSlip);
return solverConstraint;
}
void btSequentialImpulseConstraintSolver::setupTorsionalFrictionConstraint(btSolverConstraint& solverConstraint, const btVector3& normalAxis1, int solverBodyIdA, int solverBodyIdB,
btManifoldPoint& cp, btScalar combinedTorsionalFriction, const btVector3& rel_pos1, const btVector3& rel_pos2,
btCollisionObject* colObj0, btCollisionObject* colObj1, btScalar relaxation,
btScalar desiredVelocity, btScalar cfmSlip)
{
btVector3 normalAxis(0, 0, 0);
solverConstraint.m_contactNormal1 = normalAxis;
solverConstraint.m_contactNormal2 = -normalAxis;
btSolverBody& solverBodyA = m_tmpSolverBodyPool[solverBodyIdA];
btSolverBody& solverBodyB = m_tmpSolverBodyPool[solverBodyIdB];
btRigidBody* body0 = m_tmpSolverBodyPool[solverBodyIdA].m_originalBody;
btRigidBody* bodyA = m_tmpSolverBodyPool[solverBodyIdB].m_originalBody;
solverConstraint.m_solverBodyIdA = solverBodyIdA;
solverConstraint.m_solverBodyIdB = solverBodyIdB;
solverConstraint.m_friction = combinedTorsionalFriction;
solverConstraint.m_originalContactPoint = 0;
solverConstraint.m_appliedImpulse = 0.f;
solverConstraint.m_appliedPushImpulse = 0.f;
{
btVector3 ftorqueAxis1 = -normalAxis1;
solverConstraint.m_relpos1CrossNormal = ftorqueAxis1;
solverConstraint.m_angularComponentA = body0 ? body0->m_invInertiaTensorWorld * ftorqueAxis1 * body0->m_angularFactor : btVector3(0, 0, 0);
}
{
btVector3 ftorqueAxis1 = normalAxis1;
solverConstraint.m_relpos2CrossNormal = ftorqueAxis1;
solverConstraint.m_angularComponentB = bodyA ? bodyA->m_invInertiaTensorWorld * ftorqueAxis1 * bodyA->m_angularFactor : btVector3(0, 0, 0);
}
{
btVector3 iMJaA = body0 ? body0->m_invInertiaTensorWorld * solverConstraint.m_relpos1CrossNormal : btVector3(0, 0, 0);
btVector3 iMJaB = bodyA ? bodyA->m_invInertiaTensorWorld * solverConstraint.m_relpos2CrossNormal : btVector3(0, 0, 0);
btScalar sum = 0;
sum += iMJaA.dot(solverConstraint.m_relpos1CrossNormal);
sum += iMJaB.dot(solverConstraint.m_relpos2CrossNormal);
solverConstraint.m_jacDiagABInv = btScalar(1.) / sum;
}
{
btScalar rel_vel;
btScalar vel1Dotn = solverConstraint.m_contactNormal1.dot(body0 ? solverBodyA.m_linearVelocity + solverBodyA.m_externalForceImpulse : btVector3(0, 0, 0)) + solverConstraint.m_relpos1CrossNormal.dot(body0 ? solverBodyA.m_angularVelocity : btVector3(0, 0, 0));
btScalar vel2Dotn = solverConstraint.m_contactNormal2.dot(bodyA ? solverBodyB.m_linearVelocity + solverBodyB.m_externalForceImpulse : btVector3(0, 0, 0)) + solverConstraint.m_relpos2CrossNormal.dot(bodyA ? solverBodyB.m_angularVelocity : btVector3(0, 0, 0));
rel_vel = vel1Dotn + vel2Dotn;
// btScalar positionalError = 0.f;
btSimdScalar velocityError = desiredVelocity - rel_vel;
btSimdScalar velocityImpulse = velocityError * btSimdScalar(solverConstraint.m_jacDiagABInv);
solverConstraint.m_rhs = velocityImpulse;
solverConstraint.m_cfm = cfmSlip;
solverConstraint.m_lowerLimit = -solverConstraint.m_friction;
solverConstraint.m_upperLimit = solverConstraint.m_friction;
}
}
btSolverConstraint& btSequentialImpulseConstraintSolver::addTorsionalFrictionConstraint(const btVector3& normalAxis, int solverBodyIdA, int solverBodyIdB, int frictionIndex, btManifoldPoint& cp, btScalar combinedTorsionalFriction, const btVector3& rel_pos1, const btVector3& rel_pos2, btCollisionObject* colObj0, btCollisionObject* colObj1, btScalar relaxation, btScalar desiredVelocity, btScalar cfmSlip)
{
btSolverConstraint& solverConstraint = m_tmpSolverContactRollingFrictionConstraintPool.expandNonInitializing();
solverConstraint.m_frictionIndex = frictionIndex;
setupTorsionalFrictionConstraint(solverConstraint, normalAxis, solverBodyIdA, solverBodyIdB, cp, combinedTorsionalFriction, rel_pos1, rel_pos2,
colObj0, colObj1, relaxation, desiredVelocity, cfmSlip);
return solverConstraint;
}
int btSequentialImpulseConstraintSolver::getOrInitSolverBody(btCollisionObject& body, btScalar timeStep)
{
#if BT_THREADSAFE
int solverBodyId = -1;
const bool isRigidBodyType = btRigidBody::upcast(&body) != NULL;
const bool isStaticOrKinematic = body.isStaticOrKinematicObject();
const bool isKinematic = body.isKinematicObject();
if (isRigidBodyType && !isStaticOrKinematic)
{
// dynamic body
// Dynamic bodies can only be in one island, so it's safe to write to the companionId
solverBodyId = body.m_companionId;
if (solverBodyId < 0)
{
solverBodyId = m_tmpSolverBodyPool.size();
btSolverBody& solverBody = m_tmpSolverBodyPool.expand();
initSolverBody(&solverBody, &body, timeStep);
body.m_companionId = (solverBodyId);
}
}
else if (isRigidBodyType && isKinematic)
{
//
// NOTE: must test for kinematic before static because some kinematic objects also
// identify as "static"
//
// Kinematic bodies can be in multiple islands at once, so it is a
// race condition to write to them, so we use an alternate method
// to record the solverBodyId
int uniqueId = body.m_worldArrayIndex;
const int INVALID_SOLVER_BODY_ID = -1;
if (uniqueId >= m_kinematicBodyUniqueIdToSolverBodyTable.size())
{
m_kinematicBodyUniqueIdToSolverBodyTable.resize(uniqueId + 1, INVALID_SOLVER_BODY_ID);
}
solverBodyId = m_kinematicBodyUniqueIdToSolverBodyTable[uniqueId];
// if no table entry yet,
if (solverBodyId == INVALID_SOLVER_BODY_ID)
{
// create a table entry for this body
solverBodyId = m_tmpSolverBodyPool.size();
btSolverBody& solverBody = m_tmpSolverBodyPool.expand();
initSolverBody(&solverBody, &body, timeStep);
m_kinematicBodyUniqueIdToSolverBodyTable[uniqueId] = solverBodyId;
}
}
else
{
bool isMultiBodyType = (body.m_internalType & btCollisionObject::CO_FEATHERSTONE_LINK);
// Incorrectly set collision object flags can degrade performance in various ways.
if (!isMultiBodyType)
{
btAssert(body.isStaticOrKinematicObject());
}
//it could be a multibody link collider
// all fixed bodies (inf mass) get mapped to a single solver id
if (m_fixedBodyId < 0)
{
m_fixedBodyId = m_tmpSolverBodyPool.size();
btSolverBody& fixedBody = m_tmpSolverBodyPool.expand();
initSolverBody(&fixedBody, 0, timeStep);
}
solverBodyId = m_fixedBodyId;
}
btAssert(solverBodyId >= 0 && solverBodyId < m_tmpSolverBodyPool.size());
return solverBodyId;
#else // BT_THREADSAFE
int solverBodyIdA = -1;
if (body.m_companionId >= 0)
{
//body has already been converted
solverBodyIdA = body.m_companionId;
btAssert(solverBodyIdA < m_tmpSolverBodyPool.size());
}
else
{
btRigidBody* rb = btRigidBody::upcast(&body);
//convert both active and kinematic objects (for their velocity)
if (rb && (rb->m_inverseMass || rb->isKinematicObject()))
{
solverBodyIdA = m_tmpSolverBodyPool.size();
btSolverBody& solverBody = m_tmpSolverBodyPool.expand();
initSolverBody(&solverBody, &body, timeStep);
body.m_companionId = (solverBodyIdA);
}
else
{
if (m_fixedBodyId < 0)
{
m_fixedBodyId = m_tmpSolverBodyPool.size();
btSolverBody& fixedBody = m_tmpSolverBodyPool.expand();
initSolverBody(&fixedBody, 0, timeStep);
}
return m_fixedBodyId;
// return 0;//assume first one is a fixed solver body
}
}
return solverBodyIdA;
#endif // BT_THREADSAFE
}
#include <stdio.h>
void btSequentialImpulseConstraintSolver::setupContactConstraint(btSolverConstraint& solverConstraint,
int solverBodyIdA, int solverBodyIdB,
btManifoldPoint& cp, const btContactSolverInfo& infoGlobal,
btScalar& relaxation,
const btVector3& rel_pos1, const btVector3& rel_pos2)
{
// const btVector3& pos1 = cp.getPositionWorldOnA();
// const btVector3& pos2 = cp.getPositionWorldOnB();
btSolverBody* bodyA = &m_tmpSolverBodyPool[solverBodyIdA];
btSolverBody* bodyB = &m_tmpSolverBodyPool[solverBodyIdB];
btRigidBody* rb0 = bodyA->m_originalBody;
btRigidBody* rb1 = bodyB->m_originalBody;
// btVector3 rel_pos1 = pos1 - colObj0->m_worldTransform.m_origin;
// btVector3 rel_pos2 = pos2 - colObj1->m_worldTransform.m_origin;
//rel_pos1 = pos1 - bodyA->m_worldTransform.m_origin;
//rel_pos2 = pos2 - bodyB->m_worldTransform.m_origin;
relaxation = infoGlobal.m_sor;
btScalar invTimeStep = btScalar(1) / infoGlobal.m_timeStep;
//cfm = 1 / ( dt * kp + kd )
//erp = dt * kp / ( dt * kp + kd )
btScalar cfm = infoGlobal.m_globalCfm;
btScalar erp = infoGlobal.m_erp2;
if ((cp.m_contactPointFlags & BT_CONTACT_FLAG_HAS_CONTACT_CFM) || (cp.m_contactPointFlags & BT_CONTACT_FLAG_HAS_CONTACT_ERP))
{
if (cp.m_contactPointFlags & BT_CONTACT_FLAG_HAS_CONTACT_CFM)
cfm = cp.m_contactCFM;
if (cp.m_contactPointFlags & BT_CONTACT_FLAG_HAS_CONTACT_ERP)
erp = cp.m_contactERP;
}
else
{
if (cp.m_contactPointFlags & BT_CONTACT_FLAG_CONTACT_STIFFNESS_DAMPING)
{
btScalar denom = (infoGlobal.m_timeStep * cp.m_combinedContactStiffness1 + cp.m_combinedContactDamping1);
if (denom < SIMD_EPSILON)
{
denom = SIMD_EPSILON;
}
cfm = btScalar(1) / denom;
erp = (infoGlobal.m_timeStep * cp.m_combinedContactStiffness1) / denom;
}
}
cfm *= invTimeStep;
btVector3 torqueAxis0 = rel_pos1.cross(cp.m_normalWorldOnB);
solverConstraint.m_angularComponentA = rb0 ? rb0->m_invInertiaTensorWorld * torqueAxis0 * rb0->m_angularFactor : btVector3(0, 0, 0);
btVector3 torqueAxis1 = rel_pos2.cross(cp.m_normalWorldOnB);
solverConstraint.m_angularComponentB = rb1 ? rb1->m_invInertiaTensorWorld * -torqueAxis1 * rb1->m_angularFactor : btVector3(0, 0, 0);
{
#ifdef COMPUTE_IMPULSE_DENOM
btScalar denom0 = rb0->computeImpulseDenominator(pos1, cp.m_normalWorldOnB);
btScalar denom1 = rb1->computeImpulseDenominator(pos2, cp.m_normalWorldOnB);
#else
btVector3 vec;
btScalar denom0 = 0.f;
btScalar denom1 = 0.f;
if (rb0)
{
vec = (solverConstraint.m_angularComponentA).cross(rel_pos1);
denom0 = rb0->m_inverseMass + cp.m_normalWorldOnB.dot(vec);
}
if (rb1)
{
vec = (-solverConstraint.m_angularComponentB).cross(rel_pos2);
denom1 = rb1->m_inverseMass + cp.m_normalWorldOnB.dot(vec);
}
#endif //COMPUTE_IMPULSE_DENOM
btScalar denom = relaxation / (denom0 + denom1 + cfm);
solverConstraint.m_jacDiagABInv = denom;
}
if (rb0)
{
solverConstraint.m_contactNormal1 = cp.m_normalWorldOnB;
solverConstraint.m_relpos1CrossNormal = torqueAxis0;
}
else
{
solverConstraint.m_contactNormal1.setZero();
solverConstraint.m_relpos1CrossNormal.setZero();
}
if (rb1)
{
solverConstraint.m_contactNormal2 = -cp.m_normalWorldOnB;
solverConstraint.m_relpos2CrossNormal = -torqueAxis1;
}
else
{
solverConstraint.m_contactNormal2.setZero();
solverConstraint.m_relpos2CrossNormal.setZero();
}
btScalar restitution = 0.f;
btScalar penetration = cp.getDistance() + infoGlobal.m_linearSlop;
{
btVector3 vel1, vel2;
vel1 = rb0 ? rb0->getVelocityInLocalPoint(rel_pos1) : btVector3(0, 0, 0);
vel2 = rb1 ? rb1->getVelocityInLocalPoint(rel_pos2) : btVector3(0, 0, 0);
// btVector3 vel2 = rb1 ? rb1->getVelocityInLocalPoint(rel_pos2) : btVector3(0,0,0);
btVector3 vel = vel1 - vel2;
btScalar rel_vel = cp.m_normalWorldOnB.dot(vel);
solverConstraint.m_friction = cp.m_combinedFriction;
restitution = restitutionCurve(rel_vel, cp.m_combinedRestitution, infoGlobal.m_restitutionVelocityThreshold);
if (restitution <= btScalar(0.))
{
restitution = 0.f;
};
}
///warm starting (or zero if disabled)
if (infoGlobal.m_solverMode & SOLVER_USE_WARMSTARTING)
{
solverConstraint.m_appliedImpulse = cp.m_appliedImpulse * infoGlobal.m_warmstartingFactor;
if (rb0)
bodyA->internalApplyImpulse(solverConstraint.m_contactNormal1 * bodyA->internalGetInvMass(), solverConstraint.m_angularComponentA, solverConstraint.m_appliedImpulse);
if (rb1)
bodyB->internalApplyImpulse(-solverConstraint.m_contactNormal2 * bodyB->internalGetInvMass(), -solverConstraint.m_angularComponentB, -(btScalar)solverConstraint.m_appliedImpulse);
}
else
{
solverConstraint.m_appliedImpulse = 0.f;
}
solverConstraint.m_appliedPushImpulse = 0.f;
{
btVector3 externalForceImpulseA = bodyA->m_originalBody ? bodyA->m_externalForceImpulse : btVector3(0, 0, 0);
btVector3 externalTorqueImpulseA = bodyA->m_originalBody ? bodyA->m_externalTorqueImpulse : btVector3(0, 0, 0);
btVector3 externalForceImpulseB = bodyB->m_originalBody ? bodyB->m_externalForceImpulse : btVector3(0, 0, 0);
btVector3 externalTorqueImpulseB = bodyB->m_originalBody ? bodyB->m_externalTorqueImpulse : btVector3(0, 0, 0);
btScalar vel1Dotn = solverConstraint.m_contactNormal1.dot(bodyA->m_linearVelocity + externalForceImpulseA) + solverConstraint.m_relpos1CrossNormal.dot(bodyA->m_angularVelocity + externalTorqueImpulseA);
btScalar vel2Dotn = solverConstraint.m_contactNormal2.dot(bodyB->m_linearVelocity + externalForceImpulseB) + solverConstraint.m_relpos2CrossNormal.dot(bodyB->m_angularVelocity + externalTorqueImpulseB);
btScalar rel_vel = vel1Dotn + vel2Dotn;
btScalar positionalError = 0.f;
btScalar velocityError = restitution - rel_vel; // * damping;
if (penetration > 0)
{
positionalError = 0;
velocityError -= penetration * invTimeStep;
}
else
{
positionalError = -penetration * erp * invTimeStep;
}
btScalar penetrationImpulse = positionalError * solverConstraint.m_jacDiagABInv;
btScalar velocityImpulse = velocityError * solverConstraint.m_jacDiagABInv;
if (!infoGlobal.m_splitImpulse || (penetration > infoGlobal.m_splitImpulsePenetrationThreshold))
{
//combine position and velocity into rhs
solverConstraint.m_rhs = penetrationImpulse + velocityImpulse; //-solverConstraint.m_contactNormal1.dot(bodyA->m_externalForce*bodyA->m_invMass-bodyB->m_externalForce/bodyB->m_invMass)*solverConstraint.m_jacDiagABInv;
solverConstraint.m_rhsPenetration = 0.f;
}
else
{
//split position and velocity into rhs and m_rhsPenetration
solverConstraint.m_rhs = velocityImpulse;
solverConstraint.m_rhsPenetration = penetrationImpulse;
}
solverConstraint.m_cfm = cfm * solverConstraint.m_jacDiagABInv;
solverConstraint.m_lowerLimit = 0;
solverConstraint.m_upperLimit = 1e10f;
}
}
void btSequentialImpulseConstraintSolver::setFrictionConstraintImpulse(btSolverConstraint& solverConstraint,
int solverBodyIdA, int solverBodyIdB,
btManifoldPoint& cp, const btContactSolverInfo& infoGlobal)
{
{
btSolverConstraint& frictionConstraint1 = m_tmpSolverContactFrictionConstraintPool[solverConstraint.m_frictionIndex];
frictionConstraint1.m_appliedImpulse = 0.f;
}
if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
{
btSolverConstraint& frictionConstraint2 = m_tmpSolverContactFrictionConstraintPool[solverConstraint.m_frictionIndex + 1];
frictionConstraint2.m_appliedImpulse = 0.f;
}
}
void btSequentialImpulseConstraintSolver::convertContact(btPersistentManifold* manifold, const btContactSolverInfo& infoGlobal)
{
btCollisionObject *colObj0 = 0, *colObj1 = 0;
colObj0 = (btCollisionObject*)manifold->getBody0();
colObj1 = (btCollisionObject*)manifold->getBody1();
int solverBodyIdA = getOrInitSolverBody(*colObj0, infoGlobal.m_timeStep);
int solverBodyIdB = getOrInitSolverBody(*colObj1, infoGlobal.m_timeStep);
// btRigidBody* bodyA = btRigidBody::upcast(colObj0);
// btRigidBody* bodyB = btRigidBody::upcast(colObj1);
btSolverBody* solverBodyA = &m_tmpSolverBodyPool[solverBodyIdA];
btSolverBody* solverBodyB = &m_tmpSolverBodyPool[solverBodyIdB];
///avoid collision response between two static objects
if (!solverBodyA || (solverBodyA->m_invMass.fuzzyZero() && (!solverBodyB || solverBodyB->m_invMass.fuzzyZero())))
return;
int rollingFriction = 1;
for (int j = 0; j < manifold->getNumContacts(); j++)
{
btManifoldPoint& cp = manifold->getContactPoint(j);
if (cp.getDistance() <= manifold->getContactProcessingThreshold())
{
btVector3 rel_pos1;
btVector3 rel_pos2;
btScalar relaxation;
int frictionIndex = m_tmpSolverContactConstraintPool.size();
btSolverConstraint& solverConstraint = m_tmpSolverContactConstraintPool.expandNonInitializing();
solverConstraint.m_solverBodyIdA = solverBodyIdA;
solverConstraint.m_solverBodyIdB = solverBodyIdB;
solverConstraint.m_originalContactPoint = &cp;
const btVector3& pos1 = cp.getPositionWorldOnA();
const btVector3& pos2 = cp.getPositionWorldOnB();
rel_pos1 = pos1 - colObj0->m_worldTransform.m_origin;
rel_pos2 = pos2 - colObj1->m_worldTransform.m_origin;
btVector3 vel1;
btVector3 vel2;
solverBodyA->getVelocityInLocalPointNoDelta(rel_pos1, vel1);
solverBodyB->getVelocityInLocalPointNoDelta(rel_pos2, vel2);
btVector3 vel = vel1 - vel2;
btScalar rel_vel = cp.m_normalWorldOnB.dot(vel);
setupContactConstraint(solverConstraint, solverBodyIdA, solverBodyIdB, cp, infoGlobal, relaxation, rel_pos1, rel_pos2);
/////setup the friction constraints
solverConstraint.m_frictionIndex = m_tmpSolverContactFrictionConstraintPool.size();
if ((cp.m_combinedRollingFriction > 0.f) && (rollingFriction > 0))
{
{
addTorsionalFrictionConstraint(cp.m_normalWorldOnB, solverBodyIdA, solverBodyIdB, frictionIndex, cp, cp.m_combinedSpinningFriction, rel_pos1, rel_pos2, colObj0, colObj1, relaxation);
btVector3 axis0, axis1;
btPlaneSpace1(cp.m_normalWorldOnB, axis0, axis1);
axis0.normalize();
axis1.normalize();
applyAnisotropicFriction(colObj0, axis0, btCollisionObject::CF_ANISOTROPIC_ROLLING_FRICTION);
applyAnisotropicFriction(colObj1, axis0, btCollisionObject::CF_ANISOTROPIC_ROLLING_FRICTION);
applyAnisotropicFriction(colObj0, axis1, btCollisionObject::CF_ANISOTROPIC_ROLLING_FRICTION);
applyAnisotropicFriction(colObj1, axis1, btCollisionObject::CF_ANISOTROPIC_ROLLING_FRICTION);
if (axis0.length() > 0.001)
addTorsionalFrictionConstraint(axis0, solverBodyIdA, solverBodyIdB, frictionIndex, cp,
cp.m_combinedRollingFriction, rel_pos1, rel_pos2, colObj0, colObj1, relaxation);
if (axis1.length() > 0.001)
addTorsionalFrictionConstraint(axis1, solverBodyIdA, solverBodyIdB, frictionIndex, cp,
cp.m_combinedRollingFriction, rel_pos1, rel_pos2, colObj0, colObj1, relaxation);
}
}
///Bullet has several options to set the friction directions
///By default, each contact has only a single friction direction that is recomputed automatically very frame
///based on the relative linear velocity.
///If the relative velocity it zero, it will automatically compute a friction direction.
///You can also enable two friction directions, using the SOLVER_USE_2_FRICTION_DIRECTIONS.
///In that case, the second friction direction will be orthogonal to both contact normal and first friction direction.
///
///If you choose SOLVER_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION, then the friction will be independent from the relative projected velocity.
///
///The user can manually override the friction directions for certain contacts using a contact callback,
///and use contactPoint.m_contactPointFlags |= BT_CONTACT_FLAG_LATERAL_FRICTION_INITIALIZED
///In that case, you can set the target relative motion in each friction direction (cp.m_contactMotion1 and cp.m_contactMotion2)
///this will give a conveyor belt effect
///
if (!(infoGlobal.m_solverMode & SOLVER_ENABLE_FRICTION_DIRECTION_CACHING) || !(cp.m_contactPointFlags & BT_CONTACT_FLAG_LATERAL_FRICTION_INITIALIZED))
{
cp.m_lateralFrictionDir1 = vel - cp.m_normalWorldOnB * rel_vel;
btScalar lat_rel_vel = cp.m_lateralFrictionDir1.length2();
if (!(infoGlobal.m_solverMode & SOLVER_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION) && lat_rel_vel > SIMD_EPSILON)
{
cp.m_lateralFrictionDir1 *= 1.f / btSqrt(lat_rel_vel);
applyAnisotropicFriction(colObj0, cp.m_lateralFrictionDir1, btCollisionObject::CF_ANISOTROPIC_FRICTION);
applyAnisotropicFriction(colObj1, cp.m_lateralFrictionDir1, btCollisionObject::CF_ANISOTROPIC_FRICTION);
addFrictionConstraint(cp.m_lateralFrictionDir1, solverBodyIdA, solverBodyIdB, frictionIndex, cp, rel_pos1, rel_pos2, colObj0, colObj1, relaxation, infoGlobal);
if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
{
cp.m_lateralFrictionDir2 = cp.m_lateralFrictionDir1.cross(cp.m_normalWorldOnB);
cp.m_lateralFrictionDir2.normalize(); //??
applyAnisotropicFriction(colObj0, cp.m_lateralFrictionDir2, btCollisionObject::CF_ANISOTROPIC_FRICTION);
applyAnisotropicFriction(colObj1, cp.m_lateralFrictionDir2, btCollisionObject::CF_ANISOTROPIC_FRICTION);
addFrictionConstraint(cp.m_lateralFrictionDir2, solverBodyIdA, solverBodyIdB, frictionIndex, cp, rel_pos1, rel_pos2, colObj0, colObj1, relaxation, infoGlobal);
}
}
else
{
btPlaneSpace1(cp.m_normalWorldOnB, cp.m_lateralFrictionDir1, cp.m_lateralFrictionDir2);
applyAnisotropicFriction(colObj0, cp.m_lateralFrictionDir1, btCollisionObject::CF_ANISOTROPIC_FRICTION);
applyAnisotropicFriction(colObj1, cp.m_lateralFrictionDir1, btCollisionObject::CF_ANISOTROPIC_FRICTION);
addFrictionConstraint(cp.m_lateralFrictionDir1, solverBodyIdA, solverBodyIdB, frictionIndex, cp, rel_pos1, rel_pos2, colObj0, colObj1, relaxation, infoGlobal);
if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
{
applyAnisotropicFriction(colObj0, cp.m_lateralFrictionDir2, btCollisionObject::CF_ANISOTROPIC_FRICTION);
applyAnisotropicFriction(colObj1, cp.m_lateralFrictionDir2, btCollisionObject::CF_ANISOTROPIC_FRICTION);
addFrictionConstraint(cp.m_lateralFrictionDir2, solverBodyIdA, solverBodyIdB, frictionIndex, cp, rel_pos1, rel_pos2, colObj0, colObj1, relaxation, infoGlobal);
}
if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS) && (infoGlobal.m_solverMode & SOLVER_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION))
{
cp.m_contactPointFlags |= BT_CONTACT_FLAG_LATERAL_FRICTION_INITIALIZED;
}
}
}
else
{
addFrictionConstraint(cp.m_lateralFrictionDir1, solverBodyIdA, solverBodyIdB, frictionIndex, cp, rel_pos1, rel_pos2, colObj0, colObj1, relaxation, infoGlobal, cp.m_contactMotion1, cp.m_frictionCFM);
if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
addFrictionConstraint(cp.m_lateralFrictionDir2, solverBodyIdA, solverBodyIdB, frictionIndex, cp, rel_pos1, rel_pos2, colObj0, colObj1, relaxation, infoGlobal, cp.m_contactMotion2, cp.m_frictionCFM);
}
setFrictionConstraintImpulse(solverConstraint, solverBodyIdA, solverBodyIdB, cp, infoGlobal);
}
}
}
void btSequentialImpulseConstraintSolver::convertContacts(btPersistentManifold** manifoldPtr, int numManifolds, const btContactSolverInfo& infoGlobal)
{
int i;
btPersistentManifold* manifold = 0;
// btCollisionObject* colObj0=0,*colObj1=0;
for (i = 0; i < numManifolds; i++)
{
manifold = manifoldPtr[i];
convertContact(manifold, infoGlobal);
}
}
void btSequentialImpulseConstraintSolver::convertJoint(btSolverConstraint* currentConstraintRow,
btTypedConstraint* constraint,
const btTypedConstraint::btConstraintInfo1& info1,
int solverBodyIdA,
int solverBodyIdB,
const btContactSolverInfo& infoGlobal)
{
const btRigidBody& rbA = constraint->getRigidBodyA();
const btRigidBody& rbB = constraint->getRigidBodyB();
const btSolverBody* bodyAPtr = &m_tmpSolverBodyPool[solverBodyIdA];
const btSolverBody* bodyBPtr = &m_tmpSolverBodyPool[solverBodyIdB];
int overrideNumSolverIterations = constraint->getOverrideNumSolverIterations() > 0 ? constraint->getOverrideNumSolverIterations() : infoGlobal.m_numIterations;
if (overrideNumSolverIterations > m_maxOverrideNumSolverIterations)
m_maxOverrideNumSolverIterations = overrideNumSolverIterations;
for (int j = 0; j < info1.m_numConstraintRows; j++)
{
memset(¤tConstraintRow[j], 0, sizeof(btSolverConstraint));
currentConstraintRow[j].m_lowerLimit = -SIMD_INFINITY;
currentConstraintRow[j].m_upperLimit = SIMD_INFINITY;
currentConstraintRow[j].m_appliedImpulse = 0.f;
currentConstraintRow[j].m_appliedPushImpulse = 0.f;
currentConstraintRow[j].m_solverBodyIdA = solverBodyIdA;
currentConstraintRow[j].m_solverBodyIdB = solverBodyIdB;
currentConstraintRow[j].m_overrideNumSolverIterations = overrideNumSolverIterations;
}
// these vectors are already cleared in initSolverBody, no need to redundantly clear again
btAssert(bodyAPtr->getDeltaLinearVelocity().isZero());
btAssert(bodyAPtr->getDeltaAngularVelocity().isZero());
btAssert(bodyAPtr->getPushVelocity().isZero());
btAssert(bodyAPtr->getTurnVelocity().isZero());
btAssert(bodyBPtr->getDeltaLinearVelocity().isZero());
btAssert(bodyBPtr->getDeltaAngularVelocity().isZero());
btAssert(bodyBPtr->getPushVelocity().isZero());
btAssert(bodyBPtr->getTurnVelocity().isZero());
//bodyAPtr->internalGetDeltaLinearVelocity().setValue(0.f,0.f,0.f);
//bodyAPtr->internalGetDeltaAngularVelocity().setValue(0.f,0.f,0.f);
//bodyAPtr->internalGetPushVelocity().setValue(0.f,0.f,0.f);
//bodyAPtr->internalGetTurnVelocity().setValue(0.f,0.f,0.f);
//bodyBPtr->internalGetDeltaLinearVelocity().setValue(0.f,0.f,0.f);
//bodyBPtr->internalGetDeltaAngularVelocity().setValue(0.f,0.f,0.f);
//bodyBPtr->internalGetPushVelocity().setValue(0.f,0.f,0.f);
//bodyBPtr->internalGetTurnVelocity().setValue(0.f,0.f,0.f);
btTypedConstraint::btConstraintInfo2 info2;
info2.fps = 1.f / infoGlobal.m_timeStep;
info2.erp = infoGlobal.m_erp;
info2.m_J1linearAxis = currentConstraintRow->m_contactNormal1;
info2.m_J1angularAxis = currentConstraintRow->m_relpos1CrossNormal;
info2.m_J2linearAxis = currentConstraintRow->m_contactNormal2;
info2.m_J2angularAxis = currentConstraintRow->m_relpos2CrossNormal;
info2.rowskip = sizeof(btSolverConstraint) / sizeof(btScalar); //check this
///the size of btSolverConstraint needs be a multiple of btScalar
btAssert(info2.rowskip * sizeof(btScalar) == sizeof(btSolverConstraint));
info2.m_constraintError = ¤tConstraintRow->m_rhs;
currentConstraintRow->m_cfm = infoGlobal.m_globalCfm;
info2.m_damping = infoGlobal.m_damping;
info2.cfm = ¤tConstraintRow->m_cfm;
info2.m_lowerLimit = ¤tConstraintRow->m_lowerLimit;
info2.m_upperLimit = ¤tConstraintRow->m_upperLimit;
info2.m_numIterations = infoGlobal.m_numIterations;
constraint->getInfo2(&info2);
///finalize the constraint setup
for (int j = 0; j < info1.m_numConstraintRows; j++)
{
btSolverConstraint& solverConstraint = currentConstraintRow[j];
if (solverConstraint.m_upperLimit >= constraint->getBreakingImpulseThreshold())
{
solverConstraint.m_upperLimit = constraint->getBreakingImpulseThreshold();
}
if (solverConstraint.m_lowerLimit <= -constraint->getBreakingImpulseThreshold())
{
solverConstraint.m_lowerLimit = -constraint->getBreakingImpulseThreshold();
}
solverConstraint.m_originalContactPoint = constraint;
{
const btVector3& ftorqueAxis1 = solverConstraint.m_relpos1CrossNormal;
solverConstraint.m_angularComponentA = constraint->getRigidBodyA().m_invInertiaTensorWorld * ftorqueAxis1 * constraint->getRigidBodyA().m_angularFactor;
}
{
const btVector3& ftorqueAxis2 = solverConstraint.m_relpos2CrossNormal;
solverConstraint.m_angularComponentB = constraint->getRigidBodyB().m_invInertiaTensorWorld * ftorqueAxis2 * constraint->getRigidBodyB().m_angularFactor;
}
{
btVector3 iMJlA = solverConstraint.m_contactNormal1 * rbA.m_inverseMass;
btVector3 iMJaA = rbA.m_invInertiaTensorWorld * solverConstraint.m_relpos1CrossNormal;
btVector3 iMJlB = solverConstraint.m_contactNormal2 * rbB.m_inverseMass; //sign of normal?
btVector3 iMJaB = rbB.m_invInertiaTensorWorld * solverConstraint.m_relpos2CrossNormal;
btScalar sum = iMJlA.dot(solverConstraint.m_contactNormal1);
sum += iMJaA.dot(solverConstraint.m_relpos1CrossNormal);
sum += iMJlB.dot(solverConstraint.m_contactNormal2);
sum += iMJaB.dot(solverConstraint.m_relpos2CrossNormal);
btScalar fsum = btFabs(sum);
btAssert(fsum > SIMD_EPSILON);
btScalar sorRelaxation = 1.f; //todo: get from globalInfo?
solverConstraint.m_jacDiagABInv = fsum > SIMD_EPSILON ? sorRelaxation / sum : 0.f;
}
{
btScalar rel_vel;
btVector3 externalForceImpulseA = bodyAPtr->m_originalBody ? bodyAPtr->m_externalForceImpulse : btVector3(0, 0, 0);
btVector3 externalTorqueImpulseA = bodyAPtr->m_originalBody ? bodyAPtr->m_externalTorqueImpulse : btVector3(0, 0, 0);
btVector3 externalForceImpulseB = bodyBPtr->m_originalBody ? bodyBPtr->m_externalForceImpulse : btVector3(0, 0, 0);
btVector3 externalTorqueImpulseB = bodyBPtr->m_originalBody ? bodyBPtr->m_externalTorqueImpulse : btVector3(0, 0, 0);
btScalar vel1Dotn = solverConstraint.m_contactNormal1.dot(rbA.m_linearVelocity + externalForceImpulseA) + solverConstraint.m_relpos1CrossNormal.dot(rbA.m_angularVelocity + externalTorqueImpulseA);
btScalar vel2Dotn = solverConstraint.m_contactNormal2.dot(rbB.m_linearVelocity + externalForceImpulseB) + solverConstraint.m_relpos2CrossNormal.dot(rbB.m_angularVelocity + externalTorqueImpulseB);
rel_vel = vel1Dotn + vel2Dotn;
btScalar restitution = 0.f;
btScalar positionalError = solverConstraint.m_rhs; //already filled in by getConstraintInfo2
btScalar velocityError = restitution - rel_vel * info2.m_damping;
btScalar penetrationImpulse = positionalError * solverConstraint.m_jacDiagABInv;
btScalar velocityImpulse = velocityError * solverConstraint.m_jacDiagABInv;
solverConstraint.m_rhs = penetrationImpulse + velocityImpulse;
solverConstraint.m_appliedImpulse = 0.f;
}
}
}
void btSequentialImpulseConstraintSolver::convertJoints(btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal)
{
BT_PROFILE("convertJoints");
for (int j = 0; j < numConstraints; j++)
{
btTypedConstraint* constraint = constraints[j];
constraint->buildJacobian();
constraint->internalSetAppliedImpulse(0.0f);
}
int totalNumRows = 0;
m_tmpConstraintSizesPool.resizeNoInitialize(numConstraints);
//calculate the total number of contraint rows
for (int i = 0; i < numConstraints; i++)
{
btTypedConstraint::btConstraintInfo1& info1 = m_tmpConstraintSizesPool[i];
btJointFeedback* fb = constraints[i]->getJointFeedback();
if (fb)
{
fb->m_appliedForceBodyA.setZero();
fb->m_appliedTorqueBodyA.setZero();
fb->m_appliedForceBodyB.setZero();
fb->m_appliedTorqueBodyB.setZero();
}
if (constraints[i]->isEnabled())
{
constraints[i]->getInfo1(&info1);
}
else
{
info1.m_numConstraintRows = 0;
info1.nub = 0;
}
totalNumRows += info1.m_numConstraintRows;
}
m_tmpSolverNonContactConstraintPool.resizeNoInitialize(totalNumRows);
///setup the btSolverConstraints
int currentRow = 0;
for (int i = 0; i < numConstraints; i++)
{
const btTypedConstraint::btConstraintInfo1& info1 = m_tmpConstraintSizesPool[i];
if (info1.m_numConstraintRows)
{
btAssert(currentRow < totalNumRows);
btSolverConstraint* currentConstraintRow = &m_tmpSolverNonContactConstraintPool[currentRow];
btTypedConstraint* constraint = constraints[i];
btRigidBody& rbA = constraint->getRigidBodyA();
btRigidBody& rbB = constraint->getRigidBodyB();
int solverBodyIdA = getOrInitSolverBody(rbA, infoGlobal.m_timeStep);
int solverBodyIdB = getOrInitSolverBody(rbB, infoGlobal.m_timeStep);
convertJoint(currentConstraintRow, constraint, info1, solverBodyIdA, solverBodyIdB, infoGlobal);
}
currentRow += info1.m_numConstraintRows;
}
}
void btSequentialImpulseConstraintSolver::convertBodies(btCollisionObject** bodies, int numBodies, const btContactSolverInfo& infoGlobal)
{
BT_PROFILE("convertBodies");
for (int i = 0; i < numBodies; i++)
{
bodies[i]->m_companionId = (-1);
}
#if BT_THREADSAFE
m_kinematicBodyUniqueIdToSolverBodyTable.resize(0);
#endif // BT_THREADSAFE
m_tmpSolverBodyPool.reserve(numBodies + 1);
m_tmpSolverBodyPool.resize(0);
//btSolverBody& fixedBody = m_tmpSolverBodyPool.expand();
//initSolverBody(&fixedBody,0);
for (int i = 0; i < numBodies; i++)
{
int bodyId = getOrInitSolverBody(*bodies[i], infoGlobal.m_timeStep);
btRigidBody* body = btRigidBody::upcast(bodies[i]);
if (body && body->m_inverseMass)
{
btSolverBody& solverBody = m_tmpSolverBodyPool[bodyId];
btVector3 gyroForce(0, 0, 0);
if (body->m_rigidbodyFlags & BT_ENABLE_GYROSCOPIC_FORCE_EXPLICIT)
{
gyroForce = body->computeGyroscopicForceExplicit(infoGlobal.m_maxGyroscopicForce);
solverBody.m_externalTorqueImpulse -= gyroForce * body->m_invInertiaTensorWorld * infoGlobal.m_timeStep;
}
if (body->m_rigidbodyFlags & BT_ENABLE_GYROSCOPIC_FORCE_IMPLICIT_WORLD)
{
gyroForce = body->computeGyroscopicImpulseImplicit_World(infoGlobal.m_timeStep);
solverBody.m_externalTorqueImpulse += gyroForce;
}
if (body->m_rigidbodyFlags & BT_ENABLE_GYROSCOPIC_FORCE_IMPLICIT_BODY)
{
gyroForce = body->computeGyroscopicImpulseImplicit_Body(infoGlobal.m_timeStep);
solverBody.m_externalTorqueImpulse += gyroForce;
}
}
}
}
btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySetup(btCollisionObject** bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer)
{
m_fixedBodyId = -1;
BT_PROFILE("solveGroupCacheFriendlySetup");
(void)debugDrawer;
// if solver mode has changed,
if (infoGlobal.m_solverMode != m_cachedSolverMode)
{
// update solver functions to use SIMD or non-SIMD
bool useSimd = !!(infoGlobal.m_solverMode & SOLVER_SIMD);
setupSolverFunctions(useSimd);
m_cachedSolverMode = infoGlobal.m_solverMode;
}
m_maxOverrideNumSolverIterations = 0;
#ifdef BT_ADDITIONAL_DEBUG
//make sure that dynamic bodies exist for all (enabled) constraints
for (int i = 0; i < numConstraints; i++)
{
btTypedConstraint* constraint = constraints[i];
if (constraint->isEnabled())
{
if (!constraint->getRigidBodyA().isStaticOrKinematicObject())
{
bool found = false;
for (int b = 0; b < numBodies; b++)
{
if (&constraint->getRigidBodyA() == bodies[b])
{
found = true;
break;
}
}
btAssert(found);
}
if (!constraint->getRigidBodyB().isStaticOrKinematicObject())
{
bool found = false;
for (int b = 0; b < numBodies; b++)
{
if (&constraint->getRigidBodyB() == bodies[b])
{
found = true;
break;
}
}
btAssert(found);
}
}
}
//make sure that dynamic bodies exist for all contact manifolds
for (int i = 0; i < numManifolds; i++)
{
if (!manifoldPtr[i]->getBody0()->isStaticOrKinematicObject())
{
bool found = false;
for (int b = 0; b < numBodies; b++)
{
if (manifoldPtr[i]->getBody0() == bodies[b])
{
found = true;
break;
}
}
btAssert(found);
}
if (!manifoldPtr[i]->getBody1()->isStaticOrKinematicObject())
{
bool found = false;
for (int b = 0; b < numBodies; b++)
{
if (manifoldPtr[i]->getBody1() == bodies[b])
{
found = true;
break;
}
}
btAssert(found);
}
}
#endif //BT_ADDITIONAL_DEBUG
//convert all bodies
convertBodies(bodies, numBodies, infoGlobal);
convertJoints(constraints, numConstraints, infoGlobal);
convertContacts(manifoldPtr, numManifolds, infoGlobal);
// btContactSolverInfo info = infoGlobal;
int numNonContactPool = m_tmpSolverNonContactConstraintPool.size();
int numConstraintPool = m_tmpSolverContactConstraintPool.size();
int numFrictionPool = m_tmpSolverContactFrictionConstraintPool.size();
///@todo: use stack allocator for such temporarily memory, same for solver bodies/constraints
m_orderNonContactConstraintPool.resizeNoInitialize(numNonContactPool);
if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
m_orderTmpConstraintPool.resizeNoInitialize(numConstraintPool * 2);
else
m_orderTmpConstraintPool.resizeNoInitialize(numConstraintPool);
m_orderFrictionConstraintPool.resizeNoInitialize(numFrictionPool);
{
int i;
for (i = 0; i < numNonContactPool; i++)
{
m_orderNonContactConstraintPool[i] = i;
}
for (i = 0; i < numConstraintPool; i++)
{
m_orderTmpConstraintPool[i] = i;
}
for (i = 0; i < numFrictionPool; i++)
{
m_orderFrictionConstraintPool[i] = i;
}
}
return 0.f;
}
btScalar btSequentialImpulseConstraintSolver::solveSingleIteration(int iteration, btCollisionObject** /*bodies */, int /*numBodies*/, btPersistentManifold** /*manifoldPtr*/, int /*numManifolds*/, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* /*debugDrawer*/)
{
BT_PROFILE("solveSingleIteration");
btScalar leastSquaresResidual = 0.f;
int numNonContactPool = m_tmpSolverNonContactConstraintPool.size();
int numConstraintPool = m_tmpSolverContactConstraintPool.size();
int numFrictionPool = m_tmpSolverContactFrictionConstraintPool.size();
if (infoGlobal.m_solverMode & SOLVER_RANDMIZE_ORDER)
{
if (1) // uncomment this for a bit less random ((iteration & 7) == 0)
{
for (int j = 0; j < numNonContactPool; ++j)
{
int tmp = m_orderNonContactConstraintPool[j];
int swapi = btRandInt2(j + 1);
m_orderNonContactConstraintPool[j] = m_orderNonContactConstraintPool[swapi];
m_orderNonContactConstraintPool[swapi] = tmp;
}
//contact/friction constraints are not solved more than
if (iteration < infoGlobal.m_numIterations)
{
for (int j = 0; j < numConstraintPool; ++j)
{
int tmp = m_orderTmpConstraintPool[j];
int swapi = btRandInt2(j + 1);
m_orderTmpConstraintPool[j] = m_orderTmpConstraintPool[swapi];
m_orderTmpConstraintPool[swapi] = tmp;
}
for (int j = 0; j < numFrictionPool; ++j)
{
int tmp = m_orderFrictionConstraintPool[j];
int swapi = btRandInt2(j + 1);
m_orderFrictionConstraintPool[j] = m_orderFrictionConstraintPool[swapi];
m_orderFrictionConstraintPool[swapi] = tmp;
}
}
}
}
///solve all joint constraints
for (int j = 0; j < m_tmpSolverNonContactConstraintPool.size(); j++)
{
btSolverConstraint& constraint = m_tmpSolverNonContactConstraintPool[m_orderNonContactConstraintPool[j]];
if (iteration < constraint.m_overrideNumSolverIterations)
{
btScalar residual = resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[constraint.m_solverBodyIdA], m_tmpSolverBodyPool[constraint.m_solverBodyIdB], constraint);
leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
}
}
if (iteration < infoGlobal.m_numIterations)
{
for (int j = 0; j < numConstraints; j++)
{
if (constraints[j]->isEnabled())
{
int bodyAid = getOrInitSolverBody(constraints[j]->getRigidBodyA(), infoGlobal.m_timeStep);
int bodyBid = getOrInitSolverBody(constraints[j]->getRigidBodyB(), infoGlobal.m_timeStep);
btSolverBody& bodyA = m_tmpSolverBodyPool[bodyAid];
btSolverBody& bodyB = m_tmpSolverBodyPool[bodyBid];
constraints[j]->solveConstraintObsolete(bodyA, bodyB, infoGlobal.m_timeStep);
}
}
///solve all contact constraints
if (infoGlobal.m_solverMode & SOLVER_INTERLEAVE_CONTACT_AND_FRICTION_CONSTRAINTS)
{
int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
int multiplier = (infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS) ? 2 : 1;
for (int c = 0; c < numPoolConstraints; c++)
{
btScalar totalImpulse = 0;
{
const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[c]];
btScalar residual = resolveSingleConstraintRowLowerLimit(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB], solveManifold);
leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
totalImpulse = solveManifold.m_appliedImpulse;
}
bool applyFriction = true;
if (applyFriction)
{
{
btSolverConstraint& solveManifold = m_tmpSolverContactFrictionConstraintPool[m_orderFrictionConstraintPool[c * multiplier]];
if (totalImpulse > btScalar(0))
{
solveManifold.m_lowerLimit = -(solveManifold.m_friction * totalImpulse);
solveManifold.m_upperLimit = solveManifold.m_friction * totalImpulse;
btScalar residual = resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB], solveManifold);
leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
}
}
if (infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS)
{
btSolverConstraint& solveManifold = m_tmpSolverContactFrictionConstraintPool[m_orderFrictionConstraintPool[c * multiplier + 1]];
if (totalImpulse > btScalar(0))
{
solveManifold.m_lowerLimit = -(solveManifold.m_friction * totalImpulse);
solveManifold.m_upperLimit = solveManifold.m_friction * totalImpulse;
btScalar residual = resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB], solveManifold);
leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
}
}
}
}
}
else //SOLVER_INTERLEAVE_CONTACT_AND_FRICTION_CONSTRAINTS
{
//solve the friction constraints after all contact constraints, don't interleave them
int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
int j;
for (j = 0; j < numPoolConstraints; j++)
{
const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[j]];
btScalar residual = resolveSingleConstraintRowLowerLimit(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB], solveManifold);
leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
}
///solve all friction constraints
int numFrictionPoolConstraints = m_tmpSolverContactFrictionConstraintPool.size();
for (j = 0; j < numFrictionPoolConstraints; j++)
{
btSolverConstraint& solveManifold = m_tmpSolverContactFrictionConstraintPool[m_orderFrictionConstraintPool[j]];
btScalar totalImpulse = m_tmpSolverContactConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
if (totalImpulse > btScalar(0))
{
solveManifold.m_lowerLimit = -(solveManifold.m_friction * totalImpulse);
solveManifold.m_upperLimit = solveManifold.m_friction * totalImpulse;
btScalar residual = resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB], solveManifold);
leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
}
}
}
int numRollingFrictionPoolConstraints = m_tmpSolverContactRollingFrictionConstraintPool.size();
for (int j = 0; j < numRollingFrictionPoolConstraints; j++)
{
btSolverConstraint& rollingFrictionConstraint = m_tmpSolverContactRollingFrictionConstraintPool[j];
btScalar totalImpulse = m_tmpSolverContactConstraintPool[rollingFrictionConstraint.m_frictionIndex].m_appliedImpulse;
if (totalImpulse > btScalar(0))
{
btScalar rollingFrictionMagnitude = rollingFrictionConstraint.m_friction * totalImpulse;
if (rollingFrictionMagnitude > rollingFrictionConstraint.m_friction)
rollingFrictionMagnitude = rollingFrictionConstraint.m_friction;
rollingFrictionConstraint.m_lowerLimit = -rollingFrictionMagnitude;
rollingFrictionConstraint.m_upperLimit = rollingFrictionMagnitude;
btScalar residual = resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[rollingFrictionConstraint.m_solverBodyIdA], m_tmpSolverBodyPool[rollingFrictionConstraint.m_solverBodyIdB], rollingFrictionConstraint);
leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
}
}
}
return leastSquaresResidual;
}
void btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySplitImpulseIterations(btCollisionObject** bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer)
{
BT_PROFILE("solveGroupCacheFriendlySplitImpulseIterations");
int iteration;
if (infoGlobal.m_splitImpulse)
{
{
for (iteration = 0; iteration < infoGlobal.m_numIterations; iteration++)
{
btScalar leastSquaresResidual = 0.f;
{
int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
int j;
for (j = 0; j < numPoolConstraints; j++)
{
const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[j]];
btScalar residual = resolveSplitPenetrationImpulse(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB], solveManifold);
leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
}
}
if (leastSquaresResidual <= infoGlobal.m_leastSquaresResidualThreshold || iteration >= (infoGlobal.m_numIterations - 1))
{
#ifdef VERBOSE_RESIDUAL_PRINTF
printf("residual = %f at iteration #%d\n", leastSquaresResidual, iteration);
#endif
break;
}
}
}
}
}
btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlyIterations(btCollisionObject** bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer)
{
BT_PROFILE("solveGroupCacheFriendlyIterations");
{
///this is a special step to resolve penetrations (just for contacts)
solveGroupCacheFriendlySplitImpulseIterations(bodies, numBodies, manifoldPtr, numManifolds, constraints, numConstraints, infoGlobal, debugDrawer);
int maxIterations = m_maxOverrideNumSolverIterations > infoGlobal.m_numIterations ? m_maxOverrideNumSolverIterations : infoGlobal.m_numIterations;
for (int iteration = 0; iteration < maxIterations; iteration++)
//for ( int iteration = maxIterations-1 ; iteration >= 0;iteration--)
{
m_leastSquaresResidual = solveSingleIteration(iteration, bodies, numBodies, manifoldPtr, numManifolds, constraints, numConstraints, infoGlobal, debugDrawer);
if (m_leastSquaresResidual <= infoGlobal.m_leastSquaresResidualThreshold || (iteration >= (maxIterations - 1)))
{
#ifdef VERBOSE_RESIDUAL_PRINTF
printf("residual = %f at iteration #%d\n", m_leastSquaresResidual, iteration);
#endif
m_analyticsData.m_numSolverCalls++;
m_analyticsData.m_numIterationsUsed = iteration+1;
m_analyticsData.m_islandId = -2;
if (numBodies>0)
m_analyticsData.m_islandId = bodies[0]->m_companionId;
m_analyticsData.m_numBodies = numBodies;
m_analyticsData.m_numContactManifolds = numManifolds;
m_analyticsData.m_remainingLeastSquaresResidual = m_leastSquaresResidual;
break;
}
}
}
return 0.f;
}
void btSequentialImpulseConstraintSolver::writeBackContacts(int iBegin, int iEnd, const btContactSolverInfo& infoGlobal)
{
for (int j = iBegin; j < iEnd; j++)
{
const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[j];
btManifoldPoint* pt = (btManifoldPoint*)solveManifold.m_originalContactPoint;
btAssert(pt);
pt->m_appliedImpulse = solveManifold.m_appliedImpulse;
// float f = m_tmpSolverContactFrictionConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
// printf("pt->m_appliedImpulseLateral1 = %f\n", f);
pt->m_appliedImpulseLateral1 = m_tmpSolverContactFrictionConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
//printf("pt->m_appliedImpulseLateral1 = %f\n", pt->m_appliedImpulseLateral1);
if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
{
pt->m_appliedImpulseLateral2 = m_tmpSolverContactFrictionConstraintPool[solveManifold.m_frictionIndex + 1].m_appliedImpulse;
}
//do a callback here?
}
}
void btSequentialImpulseConstraintSolver::writeBackJoints(int iBegin, int iEnd, const btContactSolverInfo& infoGlobal)
{
for (int j = iBegin; j < iEnd; j++)
{
const btSolverConstraint& solverConstr = m_tmpSolverNonContactConstraintPool[j];
btTypedConstraint* constr = (btTypedConstraint*)solverConstr.m_originalContactPoint;
btJointFeedback* fb = constr->getJointFeedback();
if (fb)
{
fb->m_appliedForceBodyA += solverConstr.m_contactNormal1 * solverConstr.m_appliedImpulse * constr->getRigidBodyA().m_linearFactor / infoGlobal.m_timeStep;
fb->m_appliedForceBodyB += solverConstr.m_contactNormal2 * solverConstr.m_appliedImpulse * constr->getRigidBodyB().m_linearFactor / infoGlobal.m_timeStep;
fb->m_appliedTorqueBodyA += solverConstr.m_relpos1CrossNormal * constr->getRigidBodyA().m_angularFactor * solverConstr.m_appliedImpulse / infoGlobal.m_timeStep;
fb->m_appliedTorqueBodyB += solverConstr.m_relpos2CrossNormal * constr->getRigidBodyB().m_angularFactor * solverConstr.m_appliedImpulse / infoGlobal.m_timeStep; /*RGM ???? */
}
constr->internalSetAppliedImpulse(solverConstr.m_appliedImpulse);
if (btFabs(solverConstr.m_appliedImpulse) >= constr->getBreakingImpulseThreshold())
{
constr->setEnabled(false);
}
}
}
void btSequentialImpulseConstraintSolver::writeBackBodies(int iBegin, int iEnd, const btContactSolverInfo& infoGlobal)
{
for (int i = iBegin; i < iEnd; i++)
{
btRigidBody* body = m_tmpSolverBodyPool[i].m_originalBody;
if (body)
{
if (infoGlobal.m_splitImpulse)
m_tmpSolverBodyPool[i].writebackVelocityAndTransform(infoGlobal.m_timeStep, infoGlobal.m_splitImpulseTurnErp);
else
m_tmpSolverBodyPool[i].writebackVelocity();
m_tmpSolverBodyPool[i].m_originalBody->setLinearVelocity(
m_tmpSolverBodyPool[i].m_linearVelocity +
m_tmpSolverBodyPool[i].m_externalForceImpulse);
m_tmpSolverBodyPool[i].m_originalBody->setAngularVelocity(
m_tmpSolverBodyPool[i].m_angularVelocity +
m_tmpSolverBodyPool[i].m_externalTorqueImpulse);
if (infoGlobal.m_splitImpulse)
m_tmpSolverBodyPool[i].m_originalBody->setWorldTransform(m_tmpSolverBodyPool[i].m_worldTransform);
m_tmpSolverBodyPool[i].m_originalBody->m_companionId = (-1);
}
}
}
btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlyFinish(btCollisionObject** bodies, int numBodies, const btContactSolverInfo& infoGlobal)
{
BT_PROFILE("solveGroupCacheFriendlyFinish");
if (infoGlobal.m_solverMode & SOLVER_USE_WARMSTARTING)
{
writeBackContacts(0, m_tmpSolverContactConstraintPool.size(), infoGlobal);
}
writeBackJoints(0, m_tmpSolverNonContactConstraintPool.size(), infoGlobal);
writeBackBodies(0, m_tmpSolverBodyPool.size(), infoGlobal);
m_tmpSolverContactConstraintPool.resizeNoInitialize(0);
m_tmpSolverNonContactConstraintPool.resizeNoInitialize(0);
m_tmpSolverContactFrictionConstraintPool.resizeNoInitialize(0);
m_tmpSolverContactRollingFrictionConstraintPool.resizeNoInitialize(0);
m_tmpSolverBodyPool.resizeNoInitialize(0);
return 0.f;
}
/// btSequentialImpulseConstraintSolver Sequentially applies impulses
btScalar btSequentialImpulseConstraintSolver::solveGroup(btCollisionObject** bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer, btDispatcher* /*dispatcher*/)
{
BT_PROFILE("solveGroup");
//you need to provide at least some bodies
solveGroupCacheFriendlySetup(bodies, numBodies, manifoldPtr, numManifolds, constraints, numConstraints, infoGlobal, debugDrawer);
solveGroupCacheFriendlyIterations(bodies, numBodies, manifoldPtr, numManifolds, constraints, numConstraints, infoGlobal, debugDrawer);
solveGroupCacheFriendlyFinish(bodies, numBodies, infoGlobal);
return 0.f;
}
void btSequentialImpulseConstraintSolver::reset()
{
m_btSeed2 = 0;
}
| 0 | 0.909167 | 1 | 0.909167 | game-dev | MEDIA | 0.53611 | game-dev | 0.711369 | 1 | 0.711369 |
BG-Software-LLC/WildChests | 10,094 | src/main/java/com/bgsoftware/wildchests/handlers/SettingsHandler.java | package com.bgsoftware.wildchests.handlers;
import com.bgsoftware.common.config.CommentedConfiguration;
import com.bgsoftware.wildchests.WildChestsPlugin;
import com.bgsoftware.wildchests.api.objects.ChestType;
import com.bgsoftware.wildchests.api.objects.DepositMethod;
import com.bgsoftware.wildchests.api.objects.data.ChestData;
import com.bgsoftware.wildchests.api.objects.data.InventoryData;
import com.bgsoftware.wildchests.hooks.PricesProvider_Default;
import com.bgsoftware.wildchests.hooks.StackerProviderType;
import com.bgsoftware.wildchests.key.KeySet;
import com.bgsoftware.wildchests.objects.data.WChestData;
import com.bgsoftware.wildchests.objects.data.WInventoryData;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@SuppressWarnings("WeakerAccess")
public final class SettingsHandler {
public final long notifyInterval;
public final boolean detailedNotifier;
public final boolean confirmGUI;
public final String sellCommand;
public final boolean sellFormat;
public final String pricesProvider;
public final StackerProviderType stackerProvider;
public final int explodeDropChance;
public final boolean invalidWorldDelete;
public final boolean wildStackerHook;
public final int maximumPickupDelay;
public final int maxStacksOnDrop;
public SettingsHandler(WildChestsPlugin plugin) {
WildChestsPlugin.log("Loading configuration started...");
long startTime = System.currentTimeMillis();
int chestsAmount = 0;
File file = new File(plugin.getDataFolder(), "config.yml");
if (!file.exists())
plugin.saveResource("config.yml", false);
CommentedConfiguration cfg = CommentedConfiguration.loadConfiguration(file);
try {
cfg.syncWithConfig(file, plugin.getResource("config.yml"), "chests");
} catch (IOException error) {
error.printStackTrace();
}
notifyInterval = cfg.getLong("notifier-interval", 12000);
detailedNotifier = cfg.getBoolean("detailed-notifier", true);
confirmGUI = cfg.getBoolean("confirm-gui", false);
sellCommand = cfg.getString("sell-command", "");
sellFormat = cfg.getBoolean("sell-format", false);
explodeDropChance = cfg.getInt("explode-drop-chance", 100);
pricesProvider = cfg.getString("prices-provider");
stackerProvider = StackerProviderType.fromName(cfg.getString("stacker-provider")).orElse(StackerProviderType.AUTO);
invalidWorldDelete = cfg.getBoolean("database.invalid-world-delete", false);
wildStackerHook = cfg.getBoolean("hooks.wildstacker", true);
maximumPickupDelay = cfg.getInt("maximum-pickup-delay", 32767);
maxStacksOnDrop = cfg.getInt("max-stacks-on-drop", -1);
Map<String, Double> prices = new HashMap<>();
if (cfg.contains("prices-list")) {
for (String line : cfg.getStringList("prices-list")) {
String[] split = line.split(":");
try {
if (split.length == 2) {
prices.put(split[0], Double.valueOf(split[1]));
} else if (split.length == 3) {
prices.put(split[0] + ":" + split[1], Double.valueOf(split[2]));
}
} catch (IllegalArgumentException ignored) {
}
}
}
PricesProvider_Default.prices = prices;
Map<String, ChestData> chestsData = new HashMap<>();
for (String name : cfg.getConfigurationSection("chests").getKeys(false)) {
if (!cfg.isConfigurationSection("chests." + name)) {
WildChestsPlugin.log("Not a valid section: chests." + name + " - skipping...");
continue;
}
ConfigurationSection chestSection = cfg.getConfigurationSection("chests." + name);
ChestData chestData;
try {
chestData = loadChestFromSection(plugin, name, chestSection);
} catch (Throwable error) {
WildChestsPlugin.log("An unexpected error occurred while loading chest " + name + ":");
error.printStackTrace();
continue;
}
if (chestData == null)
continue;
chestsData.put(name.toLowerCase(), chestData);
chestsAmount++;
}
plugin.getChestsManager().loadChestsData(chestsData);
WildChestsPlugin.log(" - Found " + chestsAmount + " chests in config.yml.");
WildChestsPlugin.log("Loading configuration done (Took " + (System.currentTimeMillis() - startTime) + "ms)");
}
public static void reload() {
WildChestsPlugin plugin = WildChestsPlugin.getPlugin();
plugin.setSettings(new SettingsHandler(plugin));
}
@Nullable
private static ChestData loadChestFromSection(WildChestsPlugin plugin, String chestName, ConfigurationSection section) {
ChestType chestType;
if (!section.contains("chest-mode")) {
WildChestsPlugin.log("Couldn't find chest-mode for " + chestName + " - skipping...");
return null;
}
try {
chestType = ChestType.valueOf(section.getString("chest-mode"));
} catch (IllegalArgumentException ex) {
WildChestsPlugin.log("Found an invalid chest-type for " + chestName + " - skipping...");
return null;
}
if (!section.contains("item.name") && !section.contains("item.lore")) {
WildChestsPlugin.log("Found an invalid item for " + chestName + " - skipping...");
return null;
}
ItemStack itemStack = new ItemStack(Material.CHEST);
ItemMeta itemMeta = itemStack.getItemMeta();
if (section.contains("item.name")) {
itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', section.getString("item.name")));
}
if (section.contains("item.lore")) {
List<String> lore = new LinkedList<>();
for (String line : section.getStringList("item.lore"))
lore.add(ChatColor.translateAlternateColorCodes('&', line));
itemMeta.setLore(lore);
}
itemStack.setItemMeta(itemMeta);
ChestData chestData = new WChestData(chestName, plugin.getNMSAdapter().setChestType(itemStack, chestType), chestType);
if (section.contains("size")) {
int rows = section.getInt("size");
if (rows < 1 || rows > 6) {
WildChestsPlugin.log("Found an invalid rows amount for " + chestName + " - setting default size to 3 rows");
rows = 3;
}
chestData.setDefaultSize(rows * 9);
}
if (section.contains("title")) {
chestData.setDefaultTitle(ChatColor.translateAlternateColorCodes('&', section.getString("title")));
}
if (section.getBoolean("sell-mode", false)) {
chestData.setSellMode(true);
}
if (section.contains("deposit-method")) {
String depositMethod = section.getString("deposit-method").toUpperCase(Locale.ENGLISH);
try {
chestData.setDepositMethod(DepositMethod.valueOf(depositMethod));
} catch (IllegalArgumentException error) {
WildChestsPlugin.log("Found an invalid deposit-method for " + chestName + " - skipping...");
}
}
if (section.contains("crafter-chest")) {
chestData.setAutoCrafter(section.getStringList("crafter-chest"));
}
if (section.contains("hopper-filter")) {
chestData.setHopperFilter(section.getBoolean("hopper-filter"));
}
if (section.contains("pages")) {
Map<Integer, InventoryData> pages = new HashMap<>();
for (String index : section.getConfigurationSection("pages").getKeys(false)) {
if (!index.equals("default")) {
String title = section.getString("pages." + index + ".title");
double price = section.getDouble("pages." + index + ".price", 0);
pages.put(Integer.valueOf(index), new WInventoryData(title, price));
} else {
chestData.setDefaultPagesAmount(section.getInt("pages.default"));
}
}
chestData.setPagesData(pages);
}
if (section.contains("multiplier")) {
chestData.setMultiplier(section.getDouble("multiplier"));
}
if (section.contains("auto-collect")) {
chestData.setAutoCollect(section.getBoolean("auto-collect"));
}
if (section.contains("auto-suction")) {
chestData.setAutoSuctionRange(section.getInt("auto-suction.range", 1));
chestData.setAutoSuctionChunk(section.getBoolean("auto-suction.chunk", false));
}
if (section.contains("blacklist")) {
chestData.setBlacklisted(new KeySet(section.getStringList("blacklist")));
}
if (section.contains("whitelist")) {
chestData.setWhitelisted(new KeySet(section.getStringList("whitelist")));
}
if (section.contains("max-amount") && chestType == ChestType.STORAGE_UNIT) {
chestData.setStorageUnitMaxAmount(section.isInt("max-amount") ?
BigInteger.valueOf(section.getInt("max-amount")) :
new BigInteger(section.getString("max-amount")));
}
if (section.contains("particles")) {
chestData.setParticles(section.getStringList("particles"));
}
return chestData;
}
}
| 0 | 0.974165 | 1 | 0.974165 | game-dev | MEDIA | 0.920242 | game-dev | 0.993711 | 1 | 0.993711 |
Azure/autorest.powershell | 1,949 | powershell/resources/runtime/csharp/json/Nodes/Collections/XList.cs | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace Carbon.Json
{
public sealed class XList<T> : JsonArray, IEnumerable<JsonNode>
{
private readonly IList<T> values;
private readonly JsonType elementType;
private readonly TypeCode elementCode;
public XList(IList<T> values)
{
this.values = values ?? throw new ArgumentNullException(nameof(values));
this.elementCode = System.Type.GetTypeCode(typeof(T));
this.elementType = XHelper.GetElementType(this.elementCode);
}
public override JsonNode this[int index] =>
XHelper.Create(elementType, elementCode, values[index]);
public override JsonType? ElementType => elementType;
public override int Count => values.Count;
public bool IsReadOnly => values.IsReadOnly;
#region IList
public void Add(T value)
{
values.Add(value);
}
public bool Contains(T value) => values.Contains(value);
#endregion
#region IEnumerable Members
IEnumerator<JsonNode> IEnumerable<JsonNode>.GetEnumerator()
{
foreach (var value in values)
{
yield return XHelper.Create(elementType, elementCode, value);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
foreach (var value in values)
{
yield return XHelper.Create(elementType, elementCode, value);
}
}
#endregion
}
} | 0 | 0.835949 | 1 | 0.835949 | game-dev | MEDIA | 0.25374 | game-dev | 0.90431 | 1 | 0.90431 |
C3RV1/UndertaleNDS | 3,268 | tools/cutscenes/r11/c10.py | import typing
if typing.TYPE_CHECKING:
from tools.CutsceneTypes import *
else:
from CutsceneTypes import *
def cutscene(c: Cutscene):
c.player_control(False)
c.set_animation(Target(TargetType.PLAYER), "rightIdle")
c.set_collider_enabled(2, False)
c.play_sfx("snd_phone.wav", 0)
c.dialogue_centered(10, "", 0, 0, "", "",
Target(TargetType.NULL), "", "",
type_sound="SND_TXT1.wav")
c.wait(WaitTypes.DIALOGUE)
c.cmp_flag(FlagOffsets.CINNAMON_BUTTERSCOTCH, "==", 1)
chosen_cinnamon_before = c.jump_if()
c.cmp_flag(FlagOffsets.CINNAMON_BUTTERSCOTCH, "==", 2)
chosen_butterscotch_before = c.jump_if()
# == FIRST TIME ==
c.dialogue_centered(20, "speaker/toriel", (256 - 50) // 2, (192 - 39) // 4 - 5,
"talkIdle", "talkTalk",
Target(TargetType.NULL),
"", "", type_sound="snd_txttor.wav")
c.wait(WaitTypes.DIALOGUE)
c.cmp_flag(FlagOffsets.DIALOGUE_OPTION, "==", 0) # cinnamon is 0
after_intro = c.jump()
# == CHOSEN CINNAMON BEFORE ==
c.bind(chosen_cinnamon_before)
c.dialogue_centered(21, "speaker/toriel", (256 - 50) // 2, (192 - 39) // 4 - 5,
"talkIdle", "talkTalk",
Target(TargetType.NULL),
"", "", type_sound="snd_txttor.wav")
c.wait(WaitTypes.DIALOGUE)
c.cmp_flag(FlagOffsets.DIALOGUE_OPTION, "==", 0) # cinnamon is yes
guessed_correctly = c.jump_if()
guessed_incorrectly = c.jump_if_not()
# == CHOSEN BUTTERSCOTCH BEFORE ==
c.bind(chosen_butterscotch_before)
c.dialogue_centered(22, "speaker/toriel", (256 - 50) // 2, (192 - 39) // 4 - 5,
"talkIdle", "talkTalk",
Target(TargetType.NULL),
"", "", type_sound="snd_txttor.wav")
c.wait(WaitTypes.DIALOGUE)
c.cmp_flag(FlagOffsets.DIALOGUE_OPTION, "==", 1) # cinnamon is no
guessed_incorrectly2 = c.jump_if()
# == GUESSED CORRECTLY ==
c.bind(guessed_correctly)
c.dialogue_centered(23, "speaker/toriel", (256 - 50) // 2, (192 - 39) // 4 - 5,
"talkIdle", "talkTalk",
Target(TargetType.NULL),
"", "", type_sound="snd_txttor.wav")
c.wait(WaitTypes.DIALOGUE)
after_intro2 = c.jump()
# == GUESSED INCORRECTLY ==
c.bind(guessed_incorrectly)
c.bind(guessed_incorrectly2)
c.dialogue_centered(24, "speaker/toriel", (256 - 50) // 2, (192 - 39) // 4 - 5,
"talkIdle", "talkTalk",
Target(TargetType.NULL),
"", "", type_sound="snd_txttor.wav")
c.wait(WaitTypes.DIALOGUE)
# == END ==
c.bind(after_intro)
c.bind(after_intro2)
butterscotch_jump = c.jump_if_not()
c.set_flag(FlagOffsets.CINNAMON_BUTTERSCOTCH, 1)
end_jump = c.jump()
c.bind(butterscotch_jump)
c.set_flag(FlagOffsets.CINNAMON_BUTTERSCOTCH, 2)
c.bind(end_jump)
c.dialogue_centered(30, "", 0, 0, "", "",
Target(TargetType.NULL), "", "",
type_sound="SND_TXT1.wav")
c.wait(WaitTypes.DIALOGUE)
c.set_flag(FlagOffsets.PROGRESS, 9)
| 0 | 0.797867 | 1 | 0.797867 | game-dev | MEDIA | 0.428863 | game-dev,cli-devtools | 0.791598 | 1 | 0.791598 |
OpenEnroth/OpenEnroth | 1,366 | src/Bin/OpenEnroth/OpenEnrothOptions.h | #pragma once
#include <string>
#include <vector>
#include "Application/Startup/GameStarterOptions.h"
class GameConfig;
class Platform;
struct OpenEnrothOptions : public GameStarterOptions {
enum class Subcommand {
SUBCOMMAND_GAME,
SUBCOMMAND_PLAY,
SUBCOMMAND_RETRACE
};
using enum Subcommand;
enum class Migration {
MIGRATION_NONE,
MIGRATION_DROP_REDUNDANT_KEY_EVENTS,
MIGRATION_COLLAPSE_KEY_EVENTS,
MIGRATION_DROP_PAINT_AFTER_ACTIVATE,
};
using enum Migration;
struct RetraceOptions {
std::vector<std::string> traces;
Migration migration = MIGRATION_NONE;
bool checkCanonical = false;
};
struct PlayOptions {
std::vector<std::string> traces;
float speed = 1.0f;
};
Subcommand subcommand = SUBCOMMAND_GAME;
bool helpPrinted = false; // True means that help message was already printed.
RetraceOptions retrace;
PlayOptions play;
/**
* Parses OpenEnroth command line options.
*
* @param argc argc as passed to main.
* @param argv argv as passed to main.
* @throw std::exception On errors.
*/
static OpenEnrothOptions parse(int argc, char **argv);
};
MM_DECLARE_SERIALIZATION_FUNCTIONS(OpenEnrothOptions::Migration)
| 0 | 0.951451 | 1 | 0.951451 | game-dev | MEDIA | 0.77025 | game-dev | 0.795425 | 1 | 0.795425 |
kem0x/raider3.5 | 3,212 | Raider/SDK/FN_CollectionBookWidget_functions.cpp | // Fortnite (3.1) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function CollectionBookWidget.CollectionBookWidget_C.Construct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
void UCollectionBookWidget_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function CollectionBookWidget.CollectionBookWidget_C.Construct");
UCollectionBookWidget_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CollectionBookWidget.CollectionBookWidget_C.SlotItemComplete
// (BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortAccountItem* ItemSlotted (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
// struct FName SlotId (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UCollectionBookWidget_C::SlotItemComplete(class UFortAccountItem* ItemSlotted, const struct FName& SlotId)
{
static auto fn = UObject::FindObject<UFunction>("Function CollectionBookWidget.CollectionBookWidget_C.SlotItemComplete");
UCollectionBookWidget_C_SlotItemComplete_Params params;
params.ItemSlotted = ItemSlotted;
params.SlotId = SlotId;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CollectionBookWidget.CollectionBookWidget_C.Destruct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
void UCollectionBookWidget_C::Destruct()
{
static auto fn = UObject::FindObject<UFunction>("Function CollectionBookWidget.CollectionBookWidget_C.Destruct");
UCollectionBookWidget_C_Destruct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CollectionBookWidget.CollectionBookWidget_C.OnActivated
// (Event, Protected, BlueprintEvent)
void UCollectionBookWidget_C::OnActivated()
{
static auto fn = UObject::FindObject<UFunction>("Function CollectionBookWidget.CollectionBookWidget_C.OnActivated");
UCollectionBookWidget_C_OnActivated_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CollectionBookWidget.CollectionBookWidget_C.ExecuteUbergraph_CollectionBookWidget
// ()
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void UCollectionBookWidget_C::ExecuteUbergraph_CollectionBookWidget(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function CollectionBookWidget.CollectionBookWidget_C.ExecuteUbergraph_CollectionBookWidget");
UCollectionBookWidget_C_ExecuteUbergraph_CollectionBookWidget_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 0 | 0.590618 | 1 | 0.590618 | game-dev | MEDIA | 0.856573 | game-dev | 0.581185 | 1 | 0.581185 |
SiMaLaoShi/AssetStudio_Tuanjie | 15,274 | AssetStudio/BundleFile.cs | using K4os.Compression.LZ4;
using System;
using System.IO;
using System.Linq;
namespace AssetStudio
{
[Flags]
public enum ArchiveFlags
{
CompressionTypeMask = 0x3f,
BlocksAndDirectoryInfoCombined = 0x40,
BlocksInfoAtTheEnd = 0x80,
OldWebPluginCompatibility = 0x100,
BlockInfoNeedPaddingAtStart = 0x200
}
[Flags]
public enum StorageBlockFlags
{
CompressionTypeMask = 0x3f,
Streamed = 0x40
}
public enum CompressionType
{
None,
Lzma,
Lz4,
Lz4HC,
Lzham
}
public class BundleFile
{
public class Header
{
public string signature;
public uint version;
public string unityVersion;
public string unityRevision;
public long size;
public uint compressedBlocksInfoSize;
public uint uncompressedBlocksInfoSize;
public ArchiveFlags flags;
}
public class StorageBlock
{
public uint compressedSize;
public uint uncompressedSize;
public StorageBlockFlags flags;
}
public class Node
{
public long offset;
public long size;
public uint flags;
public string path;
}
public Header m_Header;
private StorageBlock[] m_BlocksInfo;
private Node[] m_DirectoryInfo;
public StreamFile[] fileList;
public BundleFile(FileReader reader)
{
m_Header = new Header();
m_Header.signature = reader.ReadStringToNull();
m_Header.version = reader.ReadUInt32();
m_Header.unityVersion = reader.ReadStringToNull();
m_Header.unityRevision = reader.ReadStringToNull();
switch (m_Header.signature)
{
case "UnityArchive":
break; //TODO
case "UnityWeb":
case "UnityRaw":
if (m_Header.version == 6)
{
goto case "UnityFS";
}
ReadHeaderAndBlocksInfo(reader);
using (var blocksStream = CreateBlocksStream(reader.FullPath))
{
ReadBlocksAndDirectory(reader, blocksStream);
ReadFiles(blocksStream, reader.FullPath);
}
break;
case "UnityFS":
ReadHeader(reader);
ReadBlocksInfoAndDirectory(reader);
using (var blocksStream = CreateBlocksStream(reader.FullPath))
{
ReadBlocks(reader, blocksStream);
ReadFiles(blocksStream, reader.FullPath);
}
break;
}
}
private void ReadHeaderAndBlocksInfo(EndianBinaryReader reader)
{
if (m_Header.version >= 4)
{
var hash = reader.ReadBytes(16);
var crc = reader.ReadUInt32();
}
var minimumStreamedBytes = reader.ReadUInt32();
m_Header.size = reader.ReadUInt32();
var numberOfLevelsToDownloadBeforeStreaming = reader.ReadUInt32();
var levelCount = reader.ReadInt32();
m_BlocksInfo = new StorageBlock[1];
for (int i = 0; i < levelCount; i++)
{
var storageBlock = new StorageBlock()
{
compressedSize = reader.ReadUInt32(),
uncompressedSize = reader.ReadUInt32(),
};
if (i == levelCount - 1)
{
m_BlocksInfo[0] = storageBlock;
}
}
if (m_Header.version >= 2)
{
var completeFileSize = reader.ReadUInt32();
}
if (m_Header.version >= 3)
{
var fileInfoHeaderSize = reader.ReadUInt32();
}
reader.Position = m_Header.size;
}
private Stream CreateBlocksStream(string path)
{
Stream blocksStream;
var uncompressedSizeSum = m_BlocksInfo.Sum(x => x.uncompressedSize);
if (uncompressedSizeSum >= int.MaxValue)
{
/*var memoryMappedFile = MemoryMappedFile.CreateNew(null, uncompressedSizeSum);
assetsDataStream = memoryMappedFile.CreateViewStream();*/
blocksStream = new FileStream(path + ".temp", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.DeleteOnClose);
}
else
{
blocksStream = new MemoryStream((int)uncompressedSizeSum);
}
return blocksStream;
}
private void ReadBlocksAndDirectory(EndianBinaryReader reader, Stream blocksStream)
{
var isCompressed = m_Header.signature == "UnityWeb";
foreach (var blockInfo in m_BlocksInfo)
{
var uncompressedBytes = reader.ReadBytes((int)blockInfo.compressedSize);
if (isCompressed)
{
using (var memoryStream = new MemoryStream(uncompressedBytes))
{
using (var decompressStream = SevenZipHelper.StreamDecompress(memoryStream))
{
uncompressedBytes = decompressStream.ToArray();
}
}
}
blocksStream.Write(uncompressedBytes, 0, uncompressedBytes.Length);
}
blocksStream.Position = 0;
var blocksReader = new EndianBinaryReader(blocksStream);
var nodesCount = blocksReader.ReadInt32();
m_DirectoryInfo = new Node[nodesCount];
for (int i = 0; i < nodesCount; i++)
{
m_DirectoryInfo[i] = new Node
{
path = blocksReader.ReadStringToNull(),
offset = blocksReader.ReadUInt32(),
size = blocksReader.ReadUInt32()
};
}
}
public void ReadFiles(Stream blocksStream, string path)
{
fileList = new StreamFile[m_DirectoryInfo.Length];
for (int i = 0; i < m_DirectoryInfo.Length; i++)
{
var node = m_DirectoryInfo[i];
var file = new StreamFile();
fileList[i] = file;
file.path = node.path;
file.fileName = Path.GetFileName(node.path);
if (node.size >= int.MaxValue)
{
/*var memoryMappedFile = MemoryMappedFile.CreateNew(null, entryinfo_size);
file.stream = memoryMappedFile.CreateViewStream();*/
var extractPath = path + "_unpacked" + Path.DirectorySeparatorChar;
Directory.CreateDirectory(extractPath);
file.stream = new FileStream(extractPath + file.fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
}
else
{
file.stream = new MemoryStream((int)node.size);
}
blocksStream.Position = node.offset;
blocksStream.CopyTo(file.stream, node.size);
file.stream.Position = 0;
}
}
private void ReadHeader(EndianBinaryReader reader)
{
m_Header.size = reader.ReadInt64();
m_Header.compressedBlocksInfoSize = reader.ReadUInt32();
m_Header.uncompressedBlocksInfoSize = reader.ReadUInt32();
m_Header.flags = (ArchiveFlags)reader.ReadUInt32();
if (m_Header.signature != "UnityFS")
{
reader.ReadByte();
}
}
private void ReadBlocksInfoAndDirectory(EndianBinaryReader reader)
{
byte[] blocksInfoBytes;
if (m_Header.version >= 7)
{
reader.AlignStream(16);
}
if ((m_Header.flags & ArchiveFlags.BlocksInfoAtTheEnd) != 0)
{
var position = reader.Position;
reader.Position = reader.BaseStream.Length - m_Header.compressedBlocksInfoSize;
blocksInfoBytes = reader.ReadBytes((int)m_Header.compressedBlocksInfoSize);
reader.Position = position;
}
else //0x40 BlocksAndDirectoryInfoCombined
{
blocksInfoBytes = reader.ReadBytes((int)m_Header.compressedBlocksInfoSize);
}
MemoryStream blocksInfoUncompresseddStream;
var uncompressedSize = m_Header.uncompressedBlocksInfoSize;
var compressionType = (CompressionType)(m_Header.flags & ArchiveFlags.CompressionTypeMask);
switch (compressionType)
{
case CompressionType.None:
{
Console.WriteLine("CompressionType in ReadBlocksInfoAndDirectory: " + "None");
blocksInfoUncompresseddStream = new MemoryStream(blocksInfoBytes);
break;
}
case CompressionType.Lzma:
{
Console.WriteLine("CompressionType in ReadBlocksInfoAndDirectory: " + "LZMA");
blocksInfoUncompresseddStream = new MemoryStream((int)(uncompressedSize));
using (var blocksInfoCompressedStream = new MemoryStream(blocksInfoBytes))
{
SevenZipHelper.StreamDecompress(blocksInfoCompressedStream, blocksInfoUncompresseddStream, m_Header.compressedBlocksInfoSize, m_Header.uncompressedBlocksInfoSize);
}
blocksInfoUncompresseddStream.Position = 0;
break;
}
case CompressionType.Lz4:
case CompressionType.Lz4HC:
{
Console.WriteLine("CompressionType in ReadBlocksInfoAndDirectory: " + (compressionType == CompressionType.Lz4 ? "LZ4" : "LZ4HC"));
var uncompressedBytes = new byte[uncompressedSize];
var numWrite = LZ4Codec.Decode(blocksInfoBytes, uncompressedBytes);
if (numWrite != uncompressedSize)
{
throw new IOException($"Lz4 decompression error, write {numWrite} bytes but expected {uncompressedSize} bytes");
}
blocksInfoUncompresseddStream = new MemoryStream(uncompressedBytes);
break;
}
default:
throw new IOException($"Unsupported compression type {compressionType}");
}
using (var blocksInfoReader = new EndianBinaryReader(blocksInfoUncompresseddStream))
{
var uncompressedDataHash = blocksInfoReader.ReadBytes(16);
var blocksInfoCount = blocksInfoReader.ReadInt32();
m_BlocksInfo = new StorageBlock[blocksInfoCount];
for (int i = 0; i < blocksInfoCount; i++)
{
m_BlocksInfo[i] = new StorageBlock
{
uncompressedSize = blocksInfoReader.ReadUInt32(),
compressedSize = blocksInfoReader.ReadUInt32(),
flags = (StorageBlockFlags)blocksInfoReader.ReadUInt16()
};
}
var nodesCount = blocksInfoReader.ReadInt32();
m_DirectoryInfo = new Node[nodesCount];
for (int i = 0; i < nodesCount; i++)
{
m_DirectoryInfo[i] = new Node
{
offset = blocksInfoReader.ReadInt64(),
size = blocksInfoReader.ReadInt64(),
flags = blocksInfoReader.ReadUInt32(),
path = blocksInfoReader.ReadStringToNull(),
};
}
}
if ((m_Header.flags & ArchiveFlags.BlockInfoNeedPaddingAtStart) != 0)
{
reader.AlignStream(16);
}
}
private void ReadBlocks(EndianBinaryReader reader, Stream blocksStream)
{
foreach (var blockInfo in m_BlocksInfo)
{
var compressionType = (CompressionType)(blockInfo.flags & StorageBlockFlags.CompressionTypeMask);
switch (compressionType)
{
case CompressionType.None:
{
Console.WriteLine("CompressionType in ReadBlocks: " + "None");
reader.BaseStream.CopyTo(blocksStream, blockInfo.compressedSize);
break;
}
case CompressionType.Lzma:
{
Console.WriteLine("CompressionType in ReadBlocks: " + "LZMA");
SevenZipHelper.StreamDecompress(reader.BaseStream, blocksStream, blockInfo.compressedSize, blockInfo.uncompressedSize);
break;
}
case CompressionType.Lz4:
case CompressionType.Lz4HC:
{
Console.WriteLine("CompressionType in ReadBlocks: " + (compressionType == CompressionType.Lz4 ? "LZ4" : "LZ4HC"));
var compressedSize = (int)blockInfo.compressedSize;
var compressedBytes = BigArrayPool<byte>.Shared.Rent(compressedSize);
reader.Read(compressedBytes, 0, compressedSize);
var uncompressedSize = (int)blockInfo.uncompressedSize;
var uncompressedBytes = BigArrayPool<byte>.Shared.Rent(uncompressedSize);
var numWrite = LZ4Codec.Decode(compressedBytes, 0, compressedSize, uncompressedBytes, 0, uncompressedSize);
if (numWrite != uncompressedSize)
{
throw new IOException($"Lz4 decompression error, write {numWrite} bytes but expected {uncompressedSize} bytes");
}
blocksStream.Write(uncompressedBytes, 0, uncompressedSize);
BigArrayPool<byte>.Shared.Return(compressedBytes);
BigArrayPool<byte>.Shared.Return(uncompressedBytes);
break;
}
default:
throw new IOException($"Unsupported compression type {compressionType}");
}
}
blocksStream.Position = 0;
}
}
}
| 0 | 0.94517 | 1 | 0.94517 | game-dev | MEDIA | 0.338506 | game-dev | 0.993594 | 1 | 0.993594 |
Alex-Rachel/TEngine | 1,566 | UnityProject/Assets/TEngine/Runtime/Module/Settings/Settings.cs | using UnityEngine;
namespace TEngine
{
public class Settings : MonoBehaviour
{
private static Settings _instance;
public static Settings Instance
{
get
{
if (_instance == null)
{
_instance = Utility.Unity.FindObjectOfType<Settings>();
if (_instance != null)
{
return _instance;
}
}
return _instance;
}
}
[SerializeField]
private AudioSetting audioSetting;
[SerializeField]
private ProcedureSetting procedureSetting;
[SerializeField]
private UpdateSetting updateSetting;
public static AudioSetting AudioSetting => Instance.audioSetting;
public static ProcedureSetting ProcedureSetting => Instance.procedureSetting;
public static UpdateSetting UpdateSetting
{
get
{
#if UNITY_EDITOR
if (Instance == null)
{
string[] guids = UnityEditor.AssetDatabase.FindAssets("t:UpdateSetting");
if (guids.Length >= 1)
{
string path = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[0]);
return UnityEditor.AssetDatabase.LoadAssetAtPath<UpdateSetting>(path);
}
}
#endif
return Instance.updateSetting;
}
}
}
} | 0 | 0.665209 | 1 | 0.665209 | game-dev | MEDIA | 0.905648 | game-dev | 0.64794 | 1 | 0.64794 |
Grimrukh/SoulsAI | 2,926 | ai_scripts/m13_00_00_00/291001_battle.lua | REGISTER_GOAL(GOAL_BigSk_Bow291001_Battle, "BigSk_Bow291001Battle")
local Att3000_Dist_min = 0
local Att3000_Dist_max = 0
local Att3006_Dist_min = 0
local Att3006_Dist_max = 2.5
REGISTER_GOAL_NO_UPDATE(GOAL_BigSk_Bow291001_Battle, 1)
Att3000_Dist_min = Att3006_Dist_max
function BigSk_Bow291001Battle_Activate(ai, goal)
local actPerArr = {}
local actFuncArr = {}
local defFuncParamTbl = {}
Common_Clear_Param(actPerArr, actFuncArr, defFuncParamTbl)
local targetDist = ai:GetDist(TARGET_ENE_0)
if 12 <= targetDist then
actPerArr[1] = 100
actPerArr[2] = 0
actPerArr[3] = 0
actPerArr[4] = 0
elseif 3 <= targetDist then
actPerArr[1] = 0
actPerArr[2] = 100
actPerArr[3] = 0
actPerArr[4] = 0
else
actPerArr[1] = 0
actPerArr[2] = 0
actPerArr[3] = 70
actPerArr[4] = 30
end
actFuncArr[1] = REGIST_FUNC(ai, goal, BigSk_Bow291001_Act01)
actFuncArr[2] = REGIST_FUNC(ai, goal, BigSk_Bow291001_Act02)
local local0 = {Att3006_Dist_max, 0, 3006, DIST_Middle}
defFuncParamTbl[3] = local0
actFuncArr[4] = REGIST_FUNC(ai, goal, BigSk_Bow291001_Act04)
local0 = {0, 100, 0, 0, 0, 0, 0}
local atkAfterFunc = REGIST_FUNC(ai, goal, HumanCommon_ActAfter_AdjustSpace_IncludeSidestep, local0)
Common_Battle_Activate(ai, goal, actPerArr, actFuncArr, atkAfterFunc, defFuncParamTbl)
return
end
function BigSk_Bow291001_Act01(ai, goal, paramTbl)
local targetDist = ai:GetDist(TARGET_ENE_0)
local fate = ai:GetRandam_Int(1, 100)
goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3000, TARGET_ENE_0, DIST_None, 0)
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
function BigSk_Bow291001_Act02(ai, goal, paramTbl)
local targetDist = ai:GetDist(TARGET_ENE_0)
goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3000, TARGET_ENE_0, DIST_None, 0)
goal:AddSubGoal(GOAL_COMMON_LeaveTarget, 2, TARGET_ENE_0, 20, TARGET_ENE_0, true, -1)
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
function BigSk_Bow291001_Act04(ai, goal, paramTbl)
local targetDist = ai:GetDist(TARGET_ENE_0)
goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3000, TARGET_ENE_0, DIST_None, 0)
goal:AddSubGoal(GOAL_COMMON_LeaveTarget, 5, TARGET_ENE_0, 10, TARGET_SELF, false, -1)
GetWellSpace_Odds = 0
return GetWellSpace_Odds
end
function BigSk_Bow291001Battle_Update(ai, goal)
return GOAL_RESULT_Continue
end
function BigSk_Bow291001Battle_Terminate(ai, goal)
return
end
function BigSk_Bow291001Battle_Interupt(ai, goal)
local distDamagedStep = 3
local oddsDamagedStep = 25
local bkStepPer = 40
local leftStepPer = 30
local rightStepPer = 30
local safetyDist = 4
if Damaged_Step(ai, goal, distDamagedStep, oddsDamagedStep, bkStepPer, leftStepPer, rightStepPer, safetyDist) then
return true
else
return false
end
end
return
| 0 | 0.837483 | 1 | 0.837483 | game-dev | MEDIA | 0.96127 | game-dev | 0.871442 | 1 | 0.871442 |
Loyalists/gflh2 | 1,271 | mods/gfl/aitype/enemy_favela_lmg.gsc | // H2 GSC SOURCE
// Decompiled by https://github.com/xensik/gsc-tool
main()
{
self.animtree = "";
self.additionalassets = "common_rambo_anims.csv";
self.team = "axis";
self.type = "human";
self.subclass = "militia";
self.accuracy = 0.12;
self.health = 150;
self.grenadeweapon = "fraggrenade";
self.grenadeammo = 0;
self.secondaryweapon = "";
self.sidearm = "glock";
if ( isai( self ) )
{
self setengagementmindist( 512.0, 400.0 );
self setengagementmaxdist( 1024.0, 1250.0 );
}
switch ( codescripts\character::get_random_weapon( 4 ) )
{
case 0:
self.weapon = "rpd_acog";
break;
case 1:
self.weapon = "rpd";
break;
case 2:
self.weapon = "rpd_reflex";
break;
case 3:
self.weapon = "iw5_asaw_sp";
break;
}
character\gfl\randomizer_favela_lmg::main();
}
spawner()
{
self setspawnerteam( "axis" );
}
precache()
{
character\gfl\randomizer_favela_lmg::precache();
precacheitem( "rpd_acog" );
precacheitem( "rpd" );
precacheitem( "rpd_reflex" );
precacheitem( "glock" );
precacheitem( "fraggrenade" );
maps\_rambo::main();
}
| 0 | 0.918189 | 1 | 0.918189 | game-dev | MEDIA | 0.98322 | game-dev | 0.814473 | 1 | 0.814473 |
Floating-Trees-Inc/Kaleidoscope | 9,007 | thirdparty/jolt/Jolt/Physics/Constraints/SliderConstraint.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Constraints/TwoBodyConstraint.h>
#include <Jolt/Physics/Constraints/MotorSettings.h>
#include <Jolt/Physics/Constraints/ConstraintPart/DualAxisConstraintPart.h>
#include <Jolt/Physics/Constraints/ConstraintPart/RotationEulerConstraintPart.h>
#include <Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.h>
JPH_NAMESPACE_BEGIN
/// Slider constraint settings, used to create a slider constraint
class JPH_EXPORT SliderConstraintSettings final : public TwoBodyConstraintSettings
{
JPH_DECLARE_SERIALIZABLE_VIRTUAL(JPH_EXPORT, SliderConstraintSettings)
public:
// See: ConstraintSettings::SaveBinaryState
virtual void SaveBinaryState(StreamOut &inStream) const override;
/// Create an instance of this constraint.
/// Note that the rotation constraint will be solved from body 1. This means that if body 1 and body 2 have different masses / inertias (kinematic body = infinite mass / inertia), body 1 should be the heaviest body.
virtual TwoBodyConstraint * Create(Body &inBody1, Body &inBody2) const override;
/// Simple way of setting the slider and normal axis in world space (assumes the bodies are already oriented correctly when the constraint is created)
void SetSliderAxis(Vec3Arg inSliderAxis);
/// This determines in which space the constraint is setup, all properties below should be in the specified space
EConstraintSpace mSpace = EConstraintSpace::WorldSpace;
/// When mSpace is WorldSpace mPoint1 and mPoint2 can be automatically calculated based on the positions of the bodies when the constraint is created (the current relative position/orientation is chosen as the '0' position). Set this to false if you want to supply the attachment points yourself.
bool mAutoDetectPoint = false;
/// Body 1 constraint reference frame (space determined by mSpace).
/// Slider axis is the axis along which movement is possible (direction), normal axis is a perpendicular vector to define the frame.
RVec3 mPoint1 = RVec3::sZero();
Vec3 mSliderAxis1 = Vec3::sAxisX();
Vec3 mNormalAxis1 = Vec3::sAxisY();
/// Body 2 constraint reference frame (space determined by mSpace)
RVec3 mPoint2 = RVec3::sZero();
Vec3 mSliderAxis2 = Vec3::sAxisX();
Vec3 mNormalAxis2 = Vec3::sAxisY();
/// When the bodies move so that mPoint1 coincides with mPoint2 the slider position is defined to be 0, movement will be limited between [mLimitsMin, mLimitsMax] where mLimitsMin e [-inf, 0] and mLimitsMax e [0, inf]
float mLimitsMin = -FLT_MAX;
float mLimitsMax = FLT_MAX;
/// When enabled, this makes the limits soft. When the constraint exceeds the limits, a spring force will pull it back.
SpringSettings mLimitsSpringSettings;
/// Maximum amount of friction force to apply (N) when not driven by a motor.
float mMaxFrictionForce = 0.0f;
/// In case the constraint is powered, this determines the motor settings around the sliding axis
MotorSettings mMotorSettings;
protected:
// See: ConstraintSettings::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
};
/// A slider constraint allows movement in only 1 axis (and no rotation). Also known as a prismatic constraint.
class JPH_EXPORT SliderConstraint final : public TwoBodyConstraint
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Construct slider constraint
SliderConstraint(Body &inBody1, Body &inBody2, const SliderConstraintSettings &inSettings);
// Generic interface of a constraint
virtual EConstraintSubType GetSubType() const override { return EConstraintSubType::Slider; }
virtual void NotifyShapeChanged(const BodyID &inBodyID, Vec3Arg inDeltaCOM) override;
virtual void SetupVelocityConstraint(float inDeltaTime) override;
virtual void ResetWarmStart() override;
virtual void WarmStartVelocityConstraint(float inWarmStartImpulseRatio) override;
virtual bool SolveVelocityConstraint(float inDeltaTime) override;
virtual bool SolvePositionConstraint(float inDeltaTime, float inBaumgarte) override;
#ifdef JPH_DEBUG_RENDERER
virtual void DrawConstraint(DebugRenderer *inRenderer) const override;
virtual void DrawConstraintLimits(DebugRenderer *inRenderer) const override;
#endif // JPH_DEBUG_RENDERER
virtual void SaveState(StateRecorder &inStream) const override;
virtual void RestoreState(StateRecorder &inStream) override;
virtual Ref<ConstraintSettings> GetConstraintSettings() const override;
// See: TwoBodyConstraint
virtual Mat44 GetConstraintToBody1Matrix() const override;
virtual Mat44 GetConstraintToBody2Matrix() const override;
/// Get the current distance from the rest position
float GetCurrentPosition() const;
/// Friction control
void SetMaxFrictionForce(float inFrictionForce) { mMaxFrictionForce = inFrictionForce; }
float GetMaxFrictionForce() const { return mMaxFrictionForce; }
/// Motor settings
MotorSettings & GetMotorSettings() { return mMotorSettings; }
const MotorSettings & GetMotorSettings() const { return mMotorSettings; }
// Motor controls
void SetMotorState(EMotorState inState) { JPH_ASSERT(inState == EMotorState::Off || mMotorSettings.IsValid()); mMotorState = inState; }
EMotorState GetMotorState() const { return mMotorState; }
void SetTargetVelocity(float inVelocity) { mTargetVelocity = inVelocity; }
float GetTargetVelocity() const { return mTargetVelocity; }
void SetTargetPosition(float inPosition) { mTargetPosition = mHasLimits? Clamp(inPosition, mLimitsMin, mLimitsMax) : inPosition; }
float GetTargetPosition() const { return mTargetPosition; }
/// Update the limits of the slider constraint (see SliderConstraintSettings)
void SetLimits(float inLimitsMin, float inLimitsMax);
float GetLimitsMin() const { return mLimitsMin; }
float GetLimitsMax() const { return mLimitsMax; }
bool HasLimits() const { return mHasLimits; }
/// Update the limits spring settings
const SpringSettings & GetLimitsSpringSettings() const { return mLimitsSpringSettings; }
SpringSettings & GetLimitsSpringSettings() { return mLimitsSpringSettings; }
void SetLimitsSpringSettings(const SpringSettings &inLimitsSpringSettings) { mLimitsSpringSettings = inLimitsSpringSettings; }
///@name Get Lagrange multiplier from last physics update (the linear/angular impulse applied to satisfy the constraint)
inline Vector<2> GetTotalLambdaPosition() const { return mPositionConstraintPart.GetTotalLambda(); }
inline float GetTotalLambdaPositionLimits() const { return mPositionLimitsConstraintPart.GetTotalLambda(); }
inline Vec3 GetTotalLambdaRotation() const { return mRotationConstraintPart.GetTotalLambda(); }
inline float GetTotalLambdaMotor() const { return mMotorConstraintPart.GetTotalLambda(); }
private:
// Internal helper function to calculate the values below
void CalculateR1R2U(Mat44Arg inRotation1, Mat44Arg inRotation2);
void CalculateSlidingAxisAndPosition(Mat44Arg inRotation1);
void CalculatePositionConstraintProperties(Mat44Arg inRotation1, Mat44Arg inRotation2);
void CalculatePositionLimitsConstraintProperties(float inDeltaTime);
void CalculateMotorConstraintProperties(float inDeltaTime);
// CONFIGURATION PROPERTIES FOLLOW
// Local space constraint positions
Vec3 mLocalSpacePosition1;
Vec3 mLocalSpacePosition2;
// Local space sliding direction
Vec3 mLocalSpaceSliderAxis1;
// Local space normals to the sliding direction (in body 1 space)
Vec3 mLocalSpaceNormal1;
Vec3 mLocalSpaceNormal2;
// Inverse of initial rotation from body 1 to body 2 in body 1 space
Quat mInvInitialOrientation;
// Slider limits
bool mHasLimits;
float mLimitsMin;
float mLimitsMax;
// Soft constraint limits
SpringSettings mLimitsSpringSettings;
// Friction
float mMaxFrictionForce;
// Motor controls
MotorSettings mMotorSettings;
EMotorState mMotorState = EMotorState::Off;
float mTargetVelocity = 0.0f;
float mTargetPosition = 0.0f;
// RUN TIME PROPERTIES FOLLOW
// Positions where the point constraint acts on (middle point between center of masses)
Vec3 mR1;
Vec3 mR2;
// X2 + R2 - X1 - R1
Vec3 mU;
// World space sliding direction
Vec3 mWorldSpaceSliderAxis;
// Normals to the slider axis
Vec3 mN1;
Vec3 mN2;
// Distance along the slide axis
float mD = 0.0f;
// The constraint parts
DualAxisConstraintPart mPositionConstraintPart;
RotationEulerConstraintPart mRotationConstraintPart;
AxisConstraintPart mPositionLimitsConstraintPart;
AxisConstraintPart mMotorConstraintPart;
};
JPH_NAMESPACE_END
| 0 | 0.953302 | 1 | 0.953302 | game-dev | MEDIA | 0.887138 | game-dev | 0.921083 | 1 | 0.921083 |
Dark-Basic-Software-Limited/GameGuruRepo | 6,137 | GameGuru Core/SDK/BULLET/bullet-2.81-rev2613/src/BulletCollision/Gimpact/gim_array.h | #ifndef GIM_ARRAY_H_INCLUDED
#define GIM_ARRAY_H_INCLUDED
/*! \file gim_array.h
\author Francisco Leon Najera
*/
/*
-----------------------------------------------------------------------------
This source file is part of GIMPACT Library.
For the latest info, see http://gimpact.sourceforge.net/
Copyright (c) 2006 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com
This library is free software; you can redistribute it and/or
modify it under the terms of EITHER:
(1) The GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at
your option) any later version. The text of the GNU Lesser
General Public License is included with this library in the
file GIMPACT-LICENSE-LGPL.TXT.
(2) The BSD-style license that is included with this library in
the file GIMPACT-LICENSE-BSD.TXT.
(3) The zlib/libpng license that is included with this library in
the file GIMPACT-LICENSE-ZLIB.TXT.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files
GIMPACT-LICENSE-LGPL.TXT, GIMPACT-LICENSE-ZLIB.TXT and GIMPACT-LICENSE-BSD.TXT for more details.
-----------------------------------------------------------------------------
*/
#include "gim_memory.h"
#define GIM_ARRAY_GROW_INCREMENT 2
#define GIM_ARRAY_GROW_FACTOR 2
//! Very simple array container with fast access and simd memory
template<typename T>
class gim_array
{
public:
//! properties
//!@{
T *m_data;
GUINT m_size;
GUINT m_allocated_size;
//!@}
//! protected operations
//!@{
inline void destroyData()
{
m_allocated_size = 0;
if(m_data==NULL) return;
gim_free(m_data);
m_data = NULL;
}
inline bool resizeData(GUINT newsize)
{
if(newsize==0)
{
destroyData();
return true;
}
if(m_size>0)
{
m_data = (T*)gim_realloc(m_data,m_size*sizeof(T),newsize*sizeof(T));
}
else
{
m_data = (T*)gim_alloc(newsize*sizeof(T));
}
m_allocated_size = newsize;
return true;
}
inline bool growingCheck()
{
if(m_allocated_size<=m_size)
{
GUINT requestsize = m_size;
m_size = m_allocated_size;
if(resizeData((requestsize+GIM_ARRAY_GROW_INCREMENT)*GIM_ARRAY_GROW_FACTOR)==false) return false;
}
return true;
}
//!@}
//! public operations
//!@{
inline bool reserve(GUINT size)
{
if(m_allocated_size>=size) return false;
return resizeData(size);
}
inline void clear_range(GUINT start_range)
{
while(m_size>start_range)
{
m_data[--m_size].~T();
}
}
inline void clear()
{
if(m_size==0)return;
clear_range(0);
}
inline void clear_memory()
{
clear();
destroyData();
}
gim_array()
{
m_data = 0;
m_size = 0;
m_allocated_size = 0;
}
gim_array(GUINT reservesize)
{
m_data = 0;
m_size = 0;
m_allocated_size = 0;
reserve(reservesize);
}
~gim_array()
{
clear_memory();
}
inline GUINT size() const
{
return m_size;
}
inline GUINT max_size() const
{
return m_allocated_size;
}
inline T & operator[](size_t i)
{
return m_data[i];
}
inline const T & operator[](size_t i) const
{
return m_data[i];
}
inline T * pointer(){ return m_data;}
inline const T * pointer() const
{ return m_data;}
inline T * get_pointer_at(GUINT i)
{
return m_data + i;
}
inline const T * get_pointer_at(GUINT i) const
{
return m_data + i;
}
inline T & at(GUINT i)
{
return m_data[i];
}
inline const T & at(GUINT i) const
{
return m_data[i];
}
inline T & front()
{
return *m_data;
}
inline const T & front() const
{
return *m_data;
}
inline T & back()
{
return m_data[m_size-1];
}
inline const T & back() const
{
return m_data[m_size-1];
}
inline void swap(GUINT i, GUINT j)
{
gim_swap_elements(m_data,i,j);
}
inline void push_back(const T & obj)
{
this->growingCheck();
m_data[m_size] = obj;
m_size++;
}
//!Simply increase the m_size, doesn't call the new element constructor
inline void push_back_mem()
{
this->growingCheck();
m_size++;
}
inline void push_back_memcpy(const T & obj)
{
this->growingCheck();
irr_simd_memcpy(&m_data[m_size],&obj,sizeof(T));
m_size++;
}
inline void pop_back()
{
m_size--;
m_data[m_size].~T();
}
//!Simply decrease the m_size, doesn't call the deleted element destructor
inline void pop_back_mem()
{
m_size--;
}
//! fast erase
inline void erase(GUINT index)
{
if(index<m_size-1)
{
swap(index,m_size-1);
}
pop_back();
}
inline void erase_sorted_mem(GUINT index)
{
m_size--;
for(GUINT i = index;i<m_size;i++)
{
gim_simd_memcpy(m_data+i,m_data+i+1,sizeof(T));
}
}
inline void erase_sorted(GUINT index)
{
m_data[index].~T();
erase_sorted_mem(index);
}
inline void insert_mem(GUINT index)
{
this->growingCheck();
for(GUINT i = m_size;i>index;i--)
{
gim_simd_memcpy(m_data+i,m_data+i-1,sizeof(T));
}
m_size++;
}
inline void insert(const T & obj,GUINT index)
{
insert_mem(index);
m_data[index] = obj;
}
inline void resize(GUINT size, bool call_constructor = true, const T& fillData=T())
{
if(size>m_size)
{
reserve(size);
if(call_constructor)
{
while(m_size<size)
{
m_data[m_size] = fillData;
m_size++;
}
}
else
{
m_size = size;
}
}
else if(size<m_size)
{
if(call_constructor) clear_range(size);
m_size = size;
}
}
inline void refit()
{
resizeData(m_size);
}
};
#endif // GIM_CONTAINERS_H_INCLUDED
| 0 | 0.9287 | 1 | 0.9287 | game-dev | MEDIA | 0.132526 | game-dev | 0.986411 | 1 | 0.986411 |
SpongePowered/Sponge | 4,678 | src/main/java/org/spongepowered/common/item/util/SpongeItemStackComparatorFactory.java | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.
*/
package org.spongepowered.common.item.util;
import org.spongepowered.api.data.Key;
import org.spongepowered.api.data.value.Value;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.item.inventory.ItemStackComparators;
import org.spongepowered.api.registry.RegistryTypes;
import java.util.Comparator;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class SpongeItemStackComparatorFactory implements ItemStackComparators.Factory {
private Comparator<ItemStack> comparator;
public SpongeItemStackComparatorFactory() {
}
public SpongeItemStackComparatorFactory(Comparator<ItemStack> comparator) {
this.comparator = comparator;
}
@Override
public ItemStackComparators.Factory byType() {
final Comparator<ItemStack> comparator = Comparator.comparing(i -> i.type().key(RegistryTypes.ITEM_TYPE));
return new SpongeItemStackComparatorFactory(this.comparator == null ? comparator : this.comparator.thenComparing(comparator));
}
@Override
public ItemStackComparators.Factory byData() {
final Comparator<ItemStack> comparator = new ItemDataComparator();
return new SpongeItemStackComparatorFactory(this.comparator == null ? comparator : this.comparator.thenComparing(comparator));
}
@Override
public ItemStackComparators.Factory byDurability() {
final Comparator<ItemStack> comparator = new ItemDataComparator();
return new SpongeItemStackComparatorFactory(this.comparator == null ? comparator : this.comparator.thenComparing(comparator));
}
@Override
public ItemStackComparators.Factory bySize() {
final Comparator<ItemStack> comparator = Comparator.comparing(ItemStack::quantity);
return new SpongeItemStackComparatorFactory(this.comparator == null ? comparator : this.comparator.thenComparing(this.comparator));
}
@Override
public Supplier<Comparator<ItemStack>> asSupplier() {
final Comparator<ItemStack> comparator = this.build();
return () -> comparator;
}
@Override
public Comparator<ItemStack> build() {
return this.comparator;
}
private static final class ItemDataComparator implements Comparator<ItemStack> {
private final Key<? extends Value<?>>[] ignored;
ItemDataComparator(Key<? extends Value<?>>... ignored) {
this.ignored = ignored;
}
@Override
public int compare(ItemStack o1, ItemStack o2) {
final Map<? extends Key<? extends Value<?>>, ?> map = o2.getValues().stream().collect(Collectors.toMap(Value::key, Value::get));
for (Value.Immutable<?> value : o1.getValues()) {
if (map.containsKey(value.key()) && map.get(value.key()).equals(value.get())) {
map.remove(value.key());
} else if (!this.isIgnored(map, value)) {
return -1;
}
}
return map.size();
}
private boolean isIgnored(Map<? extends Key<? extends Value<?>>, ?> map, Value.Immutable<?> toCheck) {
for (Key<? extends Value<?>> ignore : this.ignored) {
if (toCheck.key().equals(ignore)) {
map.remove(ignore);
return true;
}
}
return false;
}
}
}
| 0 | 0.800133 | 1 | 0.800133 | game-dev | MEDIA | 0.763926 | game-dev | 0.930214 | 1 | 0.930214 |
SyndiShanX/Synergy-IW-GSC-Menu | 33,712 | IW7-GSC/scripts/mp/bots/gametype_assault.gsc | /************************************************
* Decompiled by Bog
* Edited by SyndiShanX
* Script: scripts\mp\bots\gametype_assault.gsc
************************************************/
main() {
setup_callbacks();
bot_sd_start();
}
setup_callbacks() {
level.bot_funcs["crate_can_use"] = ::crate_can_use;
level.bot_funcs["gametype_think"] = ::bot_sd_think;
level.bot_funcs["should_start_cautious_approach"] = ::should_start_cautious_approach_sd;
level.bot_funcs["know_enemies_on_start"] = undefined;
level.bot_funcs["notify_enemy_bots_bomb_used"] = ::notify_enemy_team_bomb_used;
}
bot_sd_start() {
setup_bot_sd();
}
crate_can_use(param_00) {
if(isagent(self) && !isdefined(param_00.boxtype)) {
return 0;
}
if(isdefined(param_00.cratetype) && !scripts\mp\bots\_bots_killstreaks::bot_is_killstreak_supported(param_00.cratetype)) {
return 0;
}
if(!scripts\mp\utility::isteamparticipant(self)) {
return 1;
}
if(!isdefined(self.role)) {
return 0;
}
switch (self.role) {
case "investigate_someone_using_bomb":
case "bomb_defuser":
case "atk_bomber":
return 0;
}
return 1;
}
setup_bot_sd() {
level.bots_disable_team_switching = 1;
level.initial_pickup_wait_time = 3000;
scripts\mp\bots\_bots_strategy::bot_setup_bombzone_bottargets();
scripts\mp\bots\_bots_util::bot_waittill_bots_enabled(1);
level.bot_sd_override_zone_targets = [];
level.bot_sd_override_zone_targets["axis"] = [];
level.bot_sd_override_zone_targets["allies"] = [];
level.bot_default_sd_role_behavior["atk_bomber"] = ::atk_bomber_update;
level.bot_default_sd_role_behavior["clear_target_zone"] = ::clear_target_zone_update;
level.bot_default_sd_role_behavior["defend_planted_bomb"] = ::defend_planted_bomb_update;
level.bot_default_sd_role_behavior["bomb_defuser"] = ::bomb_defuser_update;
level.bot_default_sd_role_behavior["investigate_someone_using_bomb"] = ::investigate_someone_using_bomb_update;
level.bot_default_sd_role_behavior["camp_bomb"] = ::camp_bomb_update;
level.bot_default_sd_role_behavior["defender"] = ::defender_update;
level.bot_default_sd_role_behavior["backstabber"] = ::backstabber_update;
level.bot_default_sd_role_behavior["random_killer"] = ::random_killer_update;
var_00 = 0;
botzonesetteam(level.curbombzone, game["defenders"]);
}
bot_sd_think() {
self notify("bot_sd_think");
self endon("bot_sd_think");
self endon("death");
self endon("disconnect");
level endon("game_ended");
while (!isdefined(level.bot_gametype_precaching_done)) {
wait(0.05);
}
self botsetflag("separation", 0);
self botsetflag("grenade_objectives", 1);
self botsetflag("use_obj_path_style", 1);
var_00 = game["attackers"];
var_01 = 1;
if(isdefined(level.sdbomb) && isdefined(level.sdbomb.carrier) && level.sdbomb.carrier == self && isdefined(self.role) && self.role == "atk_bomber") {
var_01 = 0;
}
if(var_01) {
self.role = undefined;
}
self.suspend_sd_role = undefined;
self.has_started_thinking = 0;
self.atk_bomber_no_path_to_bomb_count = 0;
self.scripted_path_style = undefined;
self.defender_set_script_pathstyle = undefined;
self.defuser_bad_path_counter = 0;
if(!isdefined(level.initial_bomb_location) && !level.multibomb) {
level.initial_bomb_location = level.sdbomb.curorigin;
level.initial_bomb_location_nearest_node = getclosestnodeinsight(level.sdbomb.curorigin);
}
if(self.team == var_00 && !isdefined(level.can_pickup_bomb_time)) {
var_02 = 0;
if(!level.multibomb) {
var_03 = get_living_players_on_team(var_00);
foreach(var_05 in var_03) {
if(!isai(var_05)) {
var_02 = 1;
}
}
}
if(var_02) {
var_07 = 6000;
level.can_pickup_bomb_time = gettime() + var_07;
badplace_cylinder("bomb", var_07 / 1000, level.sdbomb.curorigin, 75, 300, var_00);
}
}
for (;;) {
wait(randomintrange(1, 3) * 0.05);
if(self.health <= 0) {
continue;
}
self.has_started_thinking = 1;
if(!isdefined(self.role)) {
initialize_sd_role();
}
if(isdefined(self.suspend_sd_role)) {
continue;
}
if(self.team == var_00) {
if(!level.multibomb && isdefined(level.can_pickup_bomb_time) && gettime() < level.can_pickup_bomb_time && !isdefined(level.sdbomb.carrier)) {
if(!scripts\mp\bots\_bots_util::bot_is_defending_point(level.sdbomb.curorigin)) {
var_08 = getclosestnodeinsight(level.sdbomb.curorigin);
if(isdefined(var_08)) {
var_09["nearest_node_to_center"] = var_08;
scripts\mp\bots\_bots_strategy::bot_protect_point(level.sdbomb.curorigin, 900, var_09);
} else {
level.can_pickup_bomb_time = gettime();
}
}
} else {
self[[level.bot_default_sd_role_behavior[self.role]]]();
}
continue;
}
if(level.bombplanted) {
if(distancesquared(self.origin, level.sdbombmodel.origin) > squared(level.protect_radius * 2)) {
if(!isdefined(self.defender_set_script_pathstyle)) {
self.defender_set_script_pathstyle = 1;
self getpathactionvalue("scripted");
}
} else if(isdefined(self.defender_set_script_pathstyle) && !isdefined(self.scripted_path_style)) {
self.defender_set_script_pathstyle = undefined;
self getpathactionvalue(undefined);
}
}
if(level.bombplanted && isdefined(level.bomb_defuser) && self.role != "bomb_defuser") {
if(!scripts\mp\bots\_bots_util::bot_is_defending_point(level.sdbombmodel.origin)) {
self botclearscriptgoal();
scripts\mp\bots\_bots_strategy::bot_protect_point(level.sdbombmodel.origin, level.protect_radius);
}
continue;
}
self[[level.bot_default_sd_role_behavior[self.role]]]();
}
}
atk_bomber_update() {
self endon("new_role");
if(scripts\mp\bots\_bots_util::bot_is_defending()) {
scripts\mp\bots\_bots_strategy::bot_defend_stop();
}
if(isdefined(level.sdbomb) && isdefined(level.sdbomb.carrier) && isalive(level.sdbomb.carrier) && level.sdbomb.carrier != self) {
wait(0.7);
}
if(!self.isbombcarrier && !level.multibomb) {
if(isdefined(level.sdbomb)) {
if(!isdefined(self.last_bomb_location)) {
self.last_bomb_location = level.sdbomb.curorigin;
}
if(distancesquared(self.last_bomb_location, level.sdbomb.curorigin) > 4) {
self botclearscriptgoal();
self.last_bomb_location = level.sdbomb.curorigin;
}
}
if(self.atk_bomber_no_path_to_bomb_count >= 2) {
var_01 = getnodesinradiussorted(level.sdbomb.curorigin, 512, 0);
var_02 = undefined;
foreach(var_04 in var_01) {
if(!var_04 getweaponbarsize()) {
var_02 = var_04;
break;
}
}
if(isdefined(var_02)) {
self botsetscriptgoal(var_02.origin, 20, "critical");
scripts\mp\bots\_bots_util::bot_waittill_goal_or_fail();
if(isdefined(level.sdbomb) && !isdefined(level.sdbomb.carrier)) {
level.sdbomb scripts\mp\gameobjects::setpickedup(self);
}
} else {}
return;
}
if(!self bothasscriptgoal()) {
var_06 = 15;
var_07 = 32;
var_08 = scripts\mp\bots\_bots_util::bot_queued_process("BotGetClosestNavigablePoint", ::scripts\mp\bots\_bots_util::func_bot_get_closest_navigable_point, level.sdbomb.curorigin, var_06 + var_07, self);
if(isdefined(var_08)) {
var_09 = self botsetscriptgoal(level.sdbomb.curorigin, 0, "critical");
if(var_09) {
childthread bomber_monitor_no_path();
return;
}
return;
}
var_01 = getnodesinradiussorted(level.sdbomb.curorigin, 512, 0);
if(var_08.size > 0) {
self botsetscriptgoal(var_08[0].origin, 0, "critical");
scripts\mp\bots\_bots_util::bot_waittill_goal_or_fail();
}
if(isdefined(level.sdbomb) && !isdefined(level.sdbomb.carrier)) {
var_07 = scripts\mp\bots\_bots_util::bot_queued_process("BotGetClosestNavigablePoint", ::scripts\mp\bots\_bots_util::func_bot_get_closest_navigable_point, level.sdbomb.curorigin, var_05 + var_06, self);
if(!isdefined(var_07)) {
level.sdbomb scripts\mp\gameobjects::setpickedup(self);
return;
}
return;
}
return;
}
return;
}
if(isdefined(self.dont_plant_until_time) && gettime() < self.dont_plant_until_time) {
return;
}
if(!isdefined(level.bomb_zone_assaulting)) {
level.bomb_zone_assaulting = level.curbombzone;
}
var_0A = level.bomb_zone_assaulting;
self.bombzonegoal = var_0A;
if(!isdefined(level.initial_bomb_pickup_time) || gettime() - level.initial_bomb_pickup_time < level.initial_pickup_wait_time) {
level.initial_bomb_pickup_time = gettime() + level.initial_pickup_wait_time;
self botclearscriptgoal();
self botsetscriptgoal(self.origin, 0, "tactical");
wait(level.initial_pickup_wait_time / 1000);
}
self botclearscriptgoal();
if(level.attack_behavior == "rush") {
self getpathactionvalue("scripted");
var_0B = self getparent(var_0A.bottargets, "node_exposed");
var_0C = self botgetdifficultysetting("strategyLevel") * 0.45;
var_0D = self botgetdifficultysetting("strategyLevel") + 1 * 0.15;
foreach(var_0E in var_0A.bottargets) {
if(!scripts\engine\utility::array_contains(var_0A, var_0E)) {
var_0A[var_0A.size] = var_0E;
}
}
if(randomfloat(1) < var_0B) {
var_10 = var_0A[0];
} else if(randomfloat(1) < var_0D) {
var_10 = var_0B[1];
} else {
var_10 = scripts\engine\utility::random(var_0B);
}
self botsetscriptgoal(var_10.origin, 0, "critical");
}
var_11 = scripts\mp\bots\_bots_util::bot_waittill_goal_or_fail();
if(var_11 == "goal") {
var_12 = get_round_end_time() - gettime();
var_13 = var_12 - level.planttime * 2 * 1000;
var_14 = gettime() + var_13;
if(var_13 > 0) {
scripts\mp\bots\_bots_util::bot_waittill_out_of_combat_or_time(var_13);
}
var_15 = gettime() >= var_14;
var_16 = sd_press_use(level.planttime + 2, "bomb_planted", var_15);
self botclearscriptgoal();
if(var_16) {
scripts\mp\bots\_bots_strategy::bot_enable_tactical_goals();
bot_set_role("defend_planted_bomb");
return;
}
if(var_13 > 5000) {
self.dont_plant_until_time = gettime() + 5000;
return;
}
return;
}
}
get_round_end_time() {
if(level.bombplanted) {
return level.defuseendtime;
}
return gettime() + scripts\mp\gamelogic::gettimeremaining();
}
bomber_monitor_no_path() {
self notify("bomber_monitor_no_path");
self endon("death");
self endon("disconnect");
self endon("goal");
self endon("bomber_monitor_no_path");
level.sdbomb endon("pickup_object");
for (;;) {
self waittill("no_path");
self.atk_bomber_no_path_to_bomb_count++;
}
}
clear_target_zone_update() {
self endon("new_role");
if(isdefined(level.atk_bomber)) {
if(level.attack_behavior == "rush") {
if(!isdefined(self.set_initial_rush_goal)) {
if(!level.multibomb) {
var_00["nearest_node_to_center"] = level.initial_bomb_location_nearest_node;
scripts\mp\bots\_bots_strategy::bot_protect_point(level.initial_bomb_location, 900, var_00);
wait(randomfloatrange(0, 4));
scripts\mp\bots\_bots_strategy::bot_defend_stop();
}
self.set_initial_rush_goal = 1;
}
if(self botgetdifficultysetting("strategyLevel") > 0) {
set_force_sprint();
}
if(isai(level.atk_bomber) && isdefined(level.atk_bomber.bombzonegoal)) {
var_01 = level.atk_bomber.bombzonegoal;
} else if(isdefined(level.bomb_zone_assaulting)) {
var_01 = level.bomb_zone_assaulting;
} else {
var_01 = find_closest_bombzone_to_player(level.atk_bomber);
}
if(!scripts\mp\bots\_bots_util::bot_is_defending_point(var_01.curorigin)) {
var_01["min_goal_time"] = 2;
var_01["max_goal_time"] = 4;
var_01["override_origin_node"] = scripts\engine\utility::random(var_01.bottargets);
scripts\mp\bots\_bots_strategy::bot_protect_point(var_01.curorigin, level.protect_radius, var_01);
return;
}
}
}
}
defend_planted_bomb_update() {
self endon("new_role");
if(level.bombplanted) {
if(level.attack_behavior == "rush") {
disable_force_sprint();
}
if(!scripts\mp\bots\_bots_util::bot_is_defending_point(level.sdbombmodel.origin)) {
scripts\mp\bots\_bots_strategy::bot_protect_point(level.sdbombmodel.origin, level.protect_radius);
}
}
}
bomb_defuser_update() {
self endon("new_role");
if(level.bombdefused) {
return;
}
var_00 = find_ticking_bomb();
if(!isdefined(var_00)) {
return;
}
var_01 = scripts\engine\utility::get_array_of_closest(level.sdbombmodel.origin, var_00.bottargets);
var_02 = (level.sdbombmodel.origin[0], level.sdbombmodel.origin[1], var_01[0].origin[2]);
var_03 = cautious_approach_till_close(var_02, undefined);
if(!var_03) {
return;
}
var_04 = scripts\mp\bots\_bots_util::bot_waittill_goal_or_fail();
if(var_04 == "bad_path") {
self.defuser_bad_path_counter++;
if(self.defuser_bad_path_counter >= 4) {
for (;;) {
var_05 = getnodesinradiussorted(var_02, 50, 0);
var_06 = self.defuser_bad_path_counter - 4;
if(var_05.size <= var_06) {
break;
}
self botsetscriptgoal(var_05[var_06].origin, 20, "critical");
var_04 = scripts\mp\bots\_bots_util::bot_waittill_goal_or_fail();
if(var_04 == "bad_path") {
self.defuser_bad_path_counter++;
continue;
}
break;
}
}
}
if(var_04 == "goal") {
var_07 = get_round_end_time() - gettime();
var_08 = var_07 - level.defusetime * 2 * 1000;
var_09 = gettime() + var_08;
if(var_08 > 0) {
scripts\mp\bots\_bots_util::bot_waittill_out_of_combat_or_time(var_08);
}
var_0A = gettime() >= var_09;
sd_press_use(level.defusetime + 2, "bomb_defused", var_0A);
self botclearscriptgoal();
scripts\mp\bots\_bots_strategy::bot_enable_tactical_goals();
}
}
investigate_someone_using_bomb_update() {
self endon("new_role");
if(scripts\mp\bots\_bots_util::bot_is_defending()) {
scripts\mp\bots\_bots_strategy::bot_defend_stop();
}
var_00 = find_closest_bombzone_to_player(self);
self botsetscriptgoalnode(scripts\engine\utility::random(var_00.bottargets), "guard");
var_01 = scripts\mp\bots\_bots_util::bot_waittill_goal_or_fail();
if(var_01 == "goal") {
wait(4);
bot_set_role(self.prev_role);
}
}
camp_bomb_update() {
self endon("new_role");
if(isdefined(level.sdbomb.carrier)) {
if(self.prev_role == "defender") {
self.defend_zone = find_closest_bombzone_to_player(self);
}
bot_set_role(self.prev_role);
return;
}
if(!scripts\mp\bots\_bots_util::bot_is_defending_point(level.sdbomb.curorigin)) {
var_00["nearest_node_to_center"] = level.sdbomb.nearest_node_for_camping;
scripts\mp\bots\_bots_strategy::bot_protect_point(level.sdbomb.curorigin, level.protect_radius, var_00);
}
}
defender_update() {
self endon("new_role");
if(!scripts\mp\bots\_bots_util::bot_is_defending_point(self.defend_zone.curorigin)) {
var_00["score_flags"] = "strict_los";
var_00["override_origin_node"] = scripts\engine\utility::random(self.defend_zone.bottargets);
scripts\mp\bots\_bots_strategy::bot_protect_point(self.defend_zone.curorigin, level.protect_radius, var_00);
}
}
backstabber_update() {
self endon("new_role");
if(scripts\mp\bots\_bots_util::bot_is_defending()) {
scripts\mp\bots\_bots_strategy::bot_defend_stop();
}
if(!isdefined(self.backstabber_stage)) {
self.backstabber_stage = "1_move_to_midpoint";
}
if(self.backstabber_stage == "1_move_to_midpoint") {
var_00 = level.bombzones[0].curorigin;
var_01 = level.bombzones[1].curorigin;
var_02 = (var_00[0] + var_01[0] * 0.5, var_00[1] + var_01[1] * 0.5, var_00[2] + var_01[2] * 0.5);
var_03 = getnodesinradiussorted(var_02, 512, 0);
if(var_03.size == 0) {
bot_set_role("random_killer");
return;
}
var_04 = undefined;
var_05 = int(var_03.size * var_03.size + 1 * 0.5);
var_06 = randomint(var_05);
for (var_07 = 0; var_07 < var_03.size; var_07++) {
var_08 = var_03.size - var_07;
if(var_06 < var_08) {
var_04 = var_03[var_07];
break;
}
var_06 = var_06 - var_08;
}
self getpathactionvalue("scripted");
var_09 = self botsetscriptgoalnode(var_04, "guard");
if(var_09) {
var_0A = scripts\mp\bots\_bots_util::bot_waittill_goal_or_fail();
if(var_0A == "goal") {
wait(randomfloatrange(1, 4));
self.backstabber_stage = "2_move_to_enemy_spawn";
}
}
}
if(self.backstabber_stage == "2_move_to_enemy_spawn") {
var_0B = scripts\mp\spawnlogic::getspawnpointarray("mp_sd_spawn_attacker");
var_0C = scripts\engine\utility::random(var_0B);
self getpathactionvalue("scripted");
var_09 = self botsetscriptgoal(var_0C.origin, 250, "guard");
if(var_09) {
var_0A = scripts\mp\bots\_bots_util::bot_waittill_goal_or_fail();
if(var_0A == "goal") {
self.backstabber_stage = "3_move_to_bombzone";
}
}
}
if(self.backstabber_stage == "3_move_to_bombzone") {
if(!isdefined(self.bombzone_num_picked)) {
self.bombzone_num_picked = randomint(level.bombzones.size);
}
self getpathactionvalue(undefined);
var_09 = self botsetscriptgoal(scripts\engine\utility::random(level.bombzones[self.bombzone_num_picked].bottargets).origin, 160, "objective");
if(var_09) {
var_0A = scripts\mp\bots\_bots_util::bot_waittill_goal_or_fail();
if(var_0A == "goal") {
self botclearscriptgoal();
self.backstabber_stage = "2_move_to_enemy_spawn";
self.bombzone_num_picked = 1 - self.bombzone_num_picked;
return;
}
}
}
}
random_killer_update() {
self endon("new_role");
if(scripts\mp\bots\_bots_util::bot_is_defending()) {
scripts\mp\bots\_bots_strategy::bot_defend_stop();
}
self[[self.personality_update_function]]();
}
set_force_sprint() {
if(!isdefined(self.always_sprint)) {
self botsetflag("force_sprint", 1);
self.always_sprint = 1;
}
}
disable_force_sprint() {
if(isdefined(self.always_sprint)) {
self botsetflag("force_sprint", 0);
self.always_sprint = undefined;
}
}
set_scripted_pathing_style() {
if(!isdefined(self.scripted_path_style)) {
self getpathactionvalue("scripted");
self.scripted_path_style = 1;
}
}
cautious_approach_till_close(param_00, param_01) {
var_02 = level.capture_radius;
var_03["entrance_points_index"] = param_01;
scripts\mp\bots\_bots_strategy::bot_capture_point(param_00, var_02, var_03);
wait(0.05);
while (distancesquared(self.origin, param_00) > var_02 * var_02 && scripts\mp\bots\_bots_util::bot_is_defending()) {
if(get_round_end_time() - gettime() < 20000) {
set_scripted_pathing_style();
set_force_sprint();
break;
}
wait(0.05);
}
if(scripts\mp\bots\_bots_util::bot_is_defending()) {
scripts\mp\bots\_bots_strategy::bot_defend_stop();
}
return self botsetscriptgoal(param_00, 20, "critical");
}
sd_press_use(param_00, param_01, param_02) {
var_03 = 0;
if(self botgetdifficultysetting("strategyLevel") == 1) {
var_03 = 40;
} else if(self botgetdifficultysetting("strategyLevel") >= 2) {
var_03 = 80;
}
if(randomint(100) < var_03) {
self botsetstance("prone");
wait(0.2);
}
if(self botgetdifficultysetting("strategyLevel") > 0 && !param_02) {
thread notify_on_whizby();
thread notify_on_damage();
}
self botpressbutton("use", param_00);
var_04 = scripts\mp\bots\_bots_util::bot_usebutton_wait(param_00, param_01, "use_interrupted");
self botsetstance("none");
self getothermode("use");
var_05 = var_04 == param_01;
return var_05;
}
notify_enemy_team_bomb_used(param_00) {
var_01 = get_living_players_on_team(scripts\engine\utility::get_enemy_team(self.team), 1);
foreach(var_03 in var_01) {
var_04 = 0;
if(param_00 == "plant") {
var_04 = 300 + var_03 botgetdifficultysetting("strategyLevel") * 100;
} else if(param_00 == "defuse") {
var_04 = 500 + var_03 botgetdifficultysetting("strategyLevel") * 500;
}
if(distancesquared(var_03.origin, self.origin) < squared(var_04)) {
var_03 bot_set_role("investigate_someone_using_bomb");
}
}
}
notify_on_whizby() {
var_00 = find_closest_bombzone_to_player(self);
self waittill("bulletwhizby", var_01);
if(!isdefined(var_01.team) || var_01.team != self.team) {
var_02 = var_00.usetime - var_00.curprogress;
if(var_02 > 1000) {
self notify("use_interrupted");
}
}
}
notify_on_damage() {
self waittill("damage", var_00, var_01);
if(!isdefined(var_01.team) || var_01.team != self.team) {
self notify("use_interrupted");
}
}
should_start_cautious_approach_sd(param_00) {
var_01 = 2000;
var_02 = var_01 * var_01;
if(param_00) {
if(get_round_end_time() - gettime() < 15000) {
return 0;
}
var_03 = 0;
var_04 = scripts\engine\utility::get_enemy_team(self.team);
foreach(var_06 in level.players) {
if(!isdefined(var_06.team)) {
continue;
}
if(isalive(var_06) && var_06.team == var_04) {
var_03 = 1;
}
}
return var_03;
}
return distancesquared(self.origin, self.bot_defending_center) <= var_07 && self botpursuingscriptgoal();
}
find_closest_bombzone_to_player(param_00) {
var_01 = undefined;
var_02 = 999999999;
foreach(var_04 in level.bombzones) {
var_05 = distancesquared(var_04.curorigin, param_00.origin);
if(var_05 < var_02) {
var_01 = var_04;
var_02 = var_05;
}
}
return var_01;
}
get_players_defending_zone(param_00) {
var_01 = [];
var_02 = get_living_players_on_team(game["defenders"]);
foreach(var_04 in var_02) {
if(isai(var_04) && isdefined(var_04.role) && var_04.role == "defender") {
if(isdefined(var_04.defend_zone) && var_04.defend_zone == param_00) {
var_01 = scripts\engine\utility::array_add(var_01, var_04);
}
continue;
}
if(distancesquared(var_04.origin, param_00.curorigin) < level.protect_radius * level.protect_radius) {
var_01 = scripts\engine\utility::array_add(var_01, var_04);
}
}
return var_01;
}
find_ticking_bomb() {
if(isdefined(level.tickingobject)) {
foreach(var_01 in level.bombzones) {
if(distancesquared(level.tickingobject.origin, var_01.curorigin) < 90000) {
return var_01;
}
}
}
return undefined;
}
get_specific_zone(param_00) {
param_00 = "_" + tolower(param_00);
for (var_01 = 0; var_01 < level.bombzones.size; var_01++) {
if(level.bombzones[var_01].label == param_00) {
return level.bombzones[var_01];
}
}
}
bomber_wait_for_death() {
self endon("stopped_being_bomb_carrier");
self endon("new_role");
scripts\engine\utility::waittill_any_3("death", "disconnect");
level.atk_bomber = undefined;
level.last_atk_bomber_death_time = gettime();
if(isdefined(self)) {
self.role = undefined;
}
var_00 = get_living_players_on_team(game["attackers"], 1);
force_all_players_to_role(var_00, undefined);
}
bomber_wait_for_bomb_reset() {
self endon("death");
self endon("disconnect");
self endon("stopped_being_bomb_carrier");
level.sdbomb endon("pickup_object");
level.sdbomb waittill("reset");
if(scripts\mp\utility::isaiteamparticipant(self)) {
self botclearscriptgoal();
}
bot_set_role("atk_bomber");
}
set_new_bomber() {
level.atk_bomber = self;
bot_set_role("atk_bomber");
thread bomber_wait_for_death();
if(!level.multibomb) {
thread bomber_wait_for_bomb_reset();
}
if(isai(self)) {
scripts\mp\bots\_bots_strategy::bot_disable_tactical_goals();
if(level.attack_behavior == "rush" && self botgetdifficultysetting("strategyLevel") > 0) {
set_force_sprint();
}
}
}
initialize_sd_role() {
if(self.team == game["attackers"]) {
if(level.bombplanted) {
bot_set_role("defend_planted_bomb");
return;
}
if(!isdefined(level.atk_bomber)) {
set_new_bomber();
return;
}
if(level.attack_behavior == "rush") {
bot_set_role("clear_target_zone");
return;
}
return;
}
var_00 = get_players_by_role("backstabber");
var_01 = get_players_by_role("defender");
var_02 = level.bot_personality_type[self.personality];
var_03 = self botgetdifficultysetting("strategyLevel");
if(var_02 == "active") {
if(!isdefined(self.role) && level.allow_backstabbers && var_03 > 0) {
if(var_00.size == 0) {
bot_set_role("backstabber");
} else {
var_04 = 1;
foreach(var_06 in var_00) {
var_07 = level.bot_personality_type[var_06.personality];
if(var_07 == "active") {
var_04 = 0;
break;
}
}
if(var_04) {
bot_set_role("backstabber");
var_00[0] bot_set_role(undefined);
}
}
}
if(!isdefined(self.role)) {
if(var_01.size < 4) {
bot_set_role("defender");
}
}
if(!isdefined(self.role)) {
var_09 = randomint(4);
if(var_09 == 3 && level.allow_random_killers && var_03 > 0) {
bot_set_role("random_killer");
} else if(var_09 == 2 && level.allow_backstabbers && var_03 > 0) {
bot_set_role("backstabber");
} else {
bot_set_role("defender");
}
}
} else if(var_02 == "stationary") {
if(!isdefined(self.role)) {
if(var_01.size < 4) {
bot_set_role("defender");
} else {
foreach(var_0B in var_01) {
var_0C = level.bot_personality_type[var_0B.personality];
if(var_0C == "active") {
bot_set_role("defender");
var_0B bot_set_role(undefined);
break;
}
}
}
}
if(!isdefined(self.role) && level.allow_backstabbers && var_03 > 0) {
if(var_00.size == 0) {
bot_set_role("backstabber");
}
}
if(!isdefined(self.role)) {
bot_set_role("defender");
}
}
if(self.role == "defender") {
var_0E = level.bombzones;
if(has_override_zone_targets(self.team)) {
var_0E = get_override_zone_targets(self.team);
}
if(var_0E.size == 1) {
self.defend_zone = var_0E[0];
return;
}
var_0F = get_players_defending_zone(var_0E[0]);
var_10 = get_players_defending_zone(var_0E[1]);
if(var_0F.size < var_10.size) {
self.defend_zone = var_0E[0];
return;
}
if(var_10.size < var_0F.size) {
self.defend_zone = var_0E[1];
return;
}
self.defend_zone = scripts\engine\utility::random(var_0E);
return;
}
}
bot_set_role(param_00) {
if(isai(self)) {
scripts\mp\bots\_bots_strategy::bot_defend_stop();
self getpathactionvalue(undefined);
}
self.prev_role = self.role;
self.role = param_00;
self notify("new_role");
}
bot_set_role_delayed(param_00, param_01) {
self endon("death");
self endon("disconnect");
self endon("new_role");
wait(param_01);
bot_set_role(param_00);
}
force_all_players_to_role(param_00, param_01, param_02) {
foreach(var_04 in param_00) {
if(isdefined(param_02)) {
var_04 thread bot_set_role_delayed(param_01, randomfloatrange(0, param_02));
continue;
}
var_04 thread bot_set_role(param_01);
}
}
get_override_zone_targets(param_00) {
return level.bot_sd_override_zone_targets[param_00];
}
has_override_zone_targets(param_00) {
var_01 = get_override_zone_targets(param_00);
return var_01.size > 0;
}
get_players_by_role(param_00) {
var_01 = [];
foreach(var_03 in level.participants) {
if(isalive(var_03) && scripts\mp\utility::isteamparticipant(var_03) && isdefined(var_03.role) && var_03.role == param_00) {
var_01[var_01.size] = var_03;
}
}
return var_01;
}
get_living_players_on_team(param_00, param_01) {
var_02 = [];
foreach(var_04 in level.participants) {
if(!isdefined(var_04.team)) {
continue;
}
if(scripts\mp\utility::isreallyalive(var_04) && scripts\mp\utility::isteamparticipant(var_04) && var_04.team == param_00) {
if(!isdefined(param_01) || param_01 && isai(var_04) && isdefined(var_04.role)) {
var_02[var_02.size] = var_04;
}
}
}
return var_02;
}
bot_sd_ai_director_update() {
level notify("bot_sd_ai_director_update");
level endon("bot_sd_ai_director_update");
level endon("game_ended");
level.allow_backstabbers = randomint(3) <= 1;
level.allow_random_killers = randomint(3) <= 1;
level.attack_behavior = "rush";
level.protect_radius = 725;
level.capture_radius = 140;
for (;;) {
if(isdefined(level.sdbomb) && isdefined(level.sdbomb.carrier) && !isai(level.sdbomb.carrier)) {
level.bomb_zone_assaulting = find_closest_bombzone_to_player(level.sdbomb.carrier);
}
var_00 = 0;
if(!level.bombplanted) {
var_01 = get_living_players_on_team(game["attackers"]);
foreach(var_03 in var_01) {
if(var_03.isbombcarrier) {
level.can_pickup_bomb_time = gettime();
if(!isdefined(level.atk_bomber) || var_03 != level.atk_bomber) {
if(isdefined(level.atk_bomber) && isalive(level.atk_bomber)) {
level.atk_bomber bot_set_role(undefined);
level.atk_bomber notify("stopped_being_bomb_carrier");
}
var_00 = 1;
var_03 set_new_bomber();
}
}
}
if(!level.multibomb && !isdefined(level.sdbomb.carrier)) {
var_05 = getclosestnodeinsight(level.sdbomb.curorigin);
if(isdefined(var_05)) {
level.sdbomb.nearest_node_for_camping = var_05;
var_06 = 0;
var_07 = get_living_players_on_team(game["defenders"], 1);
foreach(var_09 in var_07) {
var_0A = var_09 getnearestnode();
var_0B = var_09 botgetdifficultysetting("strategyLevel");
if(var_0B > 0 && var_09.role != "camp_bomb" && isdefined(var_0A) && nodesvisible(var_05, var_0A, 1)) {
var_0C = var_09 botgetfovdot();
if(scripts\engine\utility::within_fov(var_09.origin, var_09.angles, level.sdbomb.curorigin, var_0C)) {
if(var_0B >= 2 || distancesquared(var_09.origin, level.sdbomb.curorigin) < squared(700)) {
var_06 = 1;
break;
}
}
}
}
if(var_06) {
foreach(var_09 in var_07) {
if(var_09.role != "camp_bomb" && var_09 botgetdifficultysetting("strategyLevel") > 0) {
var_09 bot_set_role("camp_bomb");
}
}
}
}
}
var_10 = level.bombzones;
if(has_override_zone_targets(game["defenders"])) {
var_10 = get_override_zone_targets(game["defenders"]);
}
for (var_11 = 0; var_11 < var_10.size; var_11++) {
for (var_12 = 0; var_12 < var_10.size; var_12++) {
var_13 = get_players_defending_zone(var_10[var_11]);
var_14 = get_players_defending_zone(var_10[var_12]);
if(var_13.size > var_14.size + 1) {
var_15 = [];
foreach(var_03 in var_13) {
if(isai(var_03)) {
var_15 = scripts\engine\utility::array_add(var_15, var_03);
}
}
if(var_15.size > 0) {
var_18 = scripts\engine\utility::random(var_15);
var_18 scripts\mp\bots\_bots_strategy::bot_defend_stop();
var_18.defend_zone = var_10[var_12];
}
}
}
}
} else {
if(isdefined(level.atk_bomber)) {
level.atk_bomber = undefined;
}
if(!isdefined(level.bomb_defuser) || !isalive(level.bomb_defuser)) {
var_19 = [];
var_1A = get_players_by_role("defender");
var_1B = get_players_by_role("backstabber");
var_1C = get_players_by_role("random_killer");
if(var_1A.size > 0) {
var_19 = var_1A;
} else if(var_1B.size > 0) {
var_19 = var_1B;
} else if(var_1C.size > 0) {
var_19 = var_1C;
}
if(var_19.size > 0) {
var_1D = scripts\engine\utility::get_array_of_closest(level.sdbombmodel.origin, var_19);
level.bomb_defuser = var_1D[0];
level.bomb_defuser bot_set_role("bomb_defuser");
level.bomb_defuser scripts\mp\bots\_bots_strategy::bot_disable_tactical_goals();
level.bomb_defuser thread defuser_wait_for_death();
}
}
if(!isdefined(level.sd_bomb_just_planted)) {
level.sd_bomb_just_planted = 1;
var_1E = get_living_players_on_team(game["attackers"]);
foreach(var_03 in var_1E) {
if(isdefined(var_03.role)) {
if(var_03.role == "atk_bomber") {
var_03 thread bot_set_role(undefined);
continue;
}
if(var_03.role != "defend_planted_bomb") {
var_03 thread bot_set_role_delayed("defend_planted_bomb", randomfloatrange(0, 3));
}
}
}
}
}
wait(0.5);
}
}
defuser_wait_for_death() {
scripts\engine\utility::waittill_any_3("death", "disconnect");
level.bomb_defuser = undefined;
} | 0 | 0.9181 | 1 | 0.9181 | game-dev | MEDIA | 0.942437 | game-dev | 0.922423 | 1 | 0.922423 |
Bubb13/EEex | 6,272 | EEex/copy/EEex_Object_Patch.lua |
(function()
EEex_DisableCodeProtection()
--[[
+----------------------------------------------------------------------------------------------+
| Prevent certain OBJECT.IDS entries from interpreting their string parameter as a script name |
+----------------------------------------------------------------------------------------------+
| 117 EEex_Target() |
| 118 EEex_LuaDecode() |
+----------------------------------------------------------------------------------------------+
| [Lua] EEex_Object_Hook_ForceIgnoreActorScriptName(aiType: CAIObjectType) -> boolean |
| return: |
| -> false - Don't alter engine behavior |
| -> true - Even though the script object was defined with a string parameter, |
| this string should not be treated as a script name |
+----------------------------------------------------------------------------------------------+
--]]
EEex_HookConditionalJumpOnFailWithLabels(EEex_Label("Hook-CAIObjectType::Decode()-TargetNameOverride"), 0, {
{"hook_integrity_watchdog_ignore_registers", {
EEex_HookIntegrityWatchdogRegister.RAX, EEex_HookIntegrityWatchdogRegister.RCX, EEex_HookIntegrityWatchdogRegister.RDX,
EEex_HookIntegrityWatchdogRegister.R8, EEex_HookIntegrityWatchdogRegister.R9, EEex_HookIntegrityWatchdogRegister.R10,
EEex_HookIntegrityWatchdogRegister.R11
}}},
EEex_FlattenTable({
{[[
#MAKE_SHADOW_SPACE(40)
]]},
EEex_GenLuaCall("EEex_Object_Hook_ForceIgnoreActorScriptName", {
["args"] = {
function(rspOffset) return {"mov qword ptr ss:[rsp+#$(1)], r13 #ENDL", {rspOffset}}, "CAIObjectType" end,
},
["returnType"] = EEex_LuaCallReturnType.Boolean,
}),
{[[
jmp no_error
call_error:
xor rax, rax
no_error:
test rax, rax
#DESTROY_SHADOW_SPACE
jnz #L(jmp_success)
]]},
})
)
--[[
+------------------------------------------------------------------------------------------------------------------------------+
| Implement new OBJECT.IDS entries |
+------------------------------------------------------------------------------------------------------------------------------+
| 117 EEex_Target() |
| 118 EEex_LuaDecode() |
+------------------------------------------------------------------------------------------------------------------------------+
| [Lua] EEex_Object_Hook_OnEvaluatingUnknown(decodingAIType: CAIObjectType, caller CGameAIBase|EEex_GameObject_CastUT, |
| nSpecialCaseI: number, curAIType: CAIObjectType) -> number |
| return: |
| -> EEex_Object_Hook_OnEvaluatingUnknown_ReturnType.HANDLED_CONTINUE - Continue evaluating outer objects |
| |
| -> EEex_Object_Hook_OnEvaluatingUnknown_ReturnType.HANDLED_DONE - Halt OBJECT.IDS processing and use curAIType |
| |
| -> EEex_Object_Hook_OnEvaluatingUnknown_ReturnType.UNHANDLED - Engine falls back to "Myself" and continues |
| evaluating outer objects |
+------------------------------------------------------------------------------------------------------------------------------+
--]]
EEex_HookConditionalJumpOnSuccessWithLabels(EEex_Label("Hook-CAIObjectType::Decode()-DefaultJmp"), 0, {
{"hook_integrity_watchdog_ignore_registers", {
EEex_HookIntegrityWatchdogRegister.RAX, EEex_HookIntegrityWatchdogRegister.RCX, EEex_HookIntegrityWatchdogRegister.R8,
EEex_HookIntegrityWatchdogRegister.R9, EEex_HookIntegrityWatchdogRegister.R10, EEex_HookIntegrityWatchdogRegister.R11
}}},
EEex_FlattenTable({
{[[
#MAKE_SHADOW_SPACE(72)
mov qword ptr ss:[rsp+#SHADOW_SPACE_BOTTOM(-8)], rdx
]]},
EEex_GenLuaCall("EEex_Object_Hook_OnEvaluatingUnknown", {
["args"] = {
function(rspOffset) return {"mov qword ptr ss:[rsp+#$(1)], r13 #ENDL", {rspOffset}}, "CAIObjectType" end,
function(rspOffset) return {"mov qword ptr ss:[rsp+#$(1)], r12 #ENDL", {rspOffset}}, "CGameAIBase", "EEex_GameObject_CastUT" end,
function(rspOffset) return {"mov qword ptr ss:[rsp+#$(1)], r15 #ENDL", {rspOffset}} end,
function(rspOffset) return {[[
lea rax, qword ptr ss:[rbp-11h]
mov qword ptr ss:[rsp+#$(1)], rax
]], {rspOffset}}, "CAIObjectType" end,
},
["returnType"] = EEex_LuaCallReturnType.Number,
}),
{[[
jmp no_error
call_error:
mov rax, #$(1) ]], {EEex_Object_Hook_OnEvaluatingUnknown_ReturnType.UNHANDLED}, [[ #ENDL
no_error:
mov rdx, qword ptr ss:[rsp+#SHADOW_SPACE_BOTTOM(-8)]
#DESTROY_SHADOW_SPACE
cmp rax, #$(1) ]], {EEex_Object_Hook_OnEvaluatingUnknown_ReturnType.HANDLED_CONTINUE}, [[ #ENDL
je normal_return
cmp rax, #$(1) ]], {EEex_Object_Hook_OnEvaluatingUnknown_ReturnType.HANDLED_DONE}, [[ #ENDL
jne #L(jmp_success)
#MANUAL_HOOK_EXIT(0)
jmp #L(Hook-CAIObjectType::Decode()-ReturnBranch)
normal_return:
#MANUAL_HOOK_EXIT(0)
jmp #L(Hook-CAIObjectType::Decode()-NormalBranch)
]]},
})
)
EEex_HookIntegrityWatchdog_IgnoreStackSizes(EEex_Label("Hook-CAIObjectType::Decode()-DefaultJmp"), {{0x68, CAIObjectType.sizeof}})
EEex_EnableCodeProtection()
end)()
| 0 | 0.879775 | 1 | 0.879775 | game-dev | MEDIA | 0.816092 | game-dev | 0.861509 | 1 | 0.861509 |
OpenVSP/OpenVSP | 54,113 | src/geom_core/HumanGeom.cpp | //
// This file is released under the terms of the NASA Open Source Agreement (NOSA)
// version 1.3 as detailed in the LICENSE file which accompanies this software.
//
//
//////////////////////////////////////////////////////////////////////
#include <unordered_set>
#include "HumanGeom.h"
#include "ParmMgr.h"
#include "Vehicle.h"
#include "PntNodeMerge.h"
#include "UnitConversion.h"
#include "MaleGeomData.h"
#include "FemaleGeomData.h"
unordered_set < int > HumanGeom::m_VertCopySet;
Pinocchio::Mesh HumanGeom::m_MasterMesh;
Pinocchio::Attachment *HumanGeom::m_MasterAttach = nullptr;
Vsp1DCurve HumanGeom::m_MaleStatureECDF;
Vsp1DCurve HumanGeom::m_FemaleStatureECDF;
Vsp1DCurve HumanGeom::m_MaleBMIECDF;
Vsp1DCurve HumanGeom::m_FemaleBMIECDF;
//==== Constructor ====//
HumanGeom::HumanGeom( Vehicle* vehicle_ptr ) : Geom( vehicle_ptr )
{
m_Name = "HumanGeom";
m_Type.m_Name = "Human";
m_Type.m_Type = HUMAN_GEOM_TYPE;
m_TessU.Deactivate();
m_TessW.Deactivate();
m_Origin.Deactivate();
m_LenUnit.Init( "LenUnit", "Anthropometric", this, vsp::LEN_FT, vsp::LEN_MM, vsp::LEN_YD );
m_LenUnit.SetDescript( "Length unit" );
m_MassUnit.Init( "MassUnit", "Anthropometric", this, vsp::MASS_UNIT_LBM, vsp::MASS_UNIT_G, vsp::MASS_LBFSEC2IN );
m_MassUnit.SetDescript( "Mass unit" );
m_GenderFlag.Init( "GenderFlag", "Anthropometric", this, vsp::MALE, vsp::MALE, vsp::FEMALE );
m_GenderFlag.SetDescript( "Gender" );
m_Stature.Init( "Stature", "Anthropometric", this, 1755.0*Get_mm2UX(), 1500.0*Get_mm2UX(), 2000.0*Get_mm2UX() );
m_Stature.SetDescript( "Height of person" );
m_Stature_pct.Init( "Stature_pct", "Anthropometric", this, .5, 0.05, 0.95 );
m_Stature_pct.SetDescript( "Percentile height" );
m_BMI.Init( "BMI", "Anthropometric", this, 20.0, 16.0, 55.0 );
m_BMI.SetDescript( "Body mass index of person" );
m_BMI_pct.Init( "BMI_pct", "Anthropometric", this, .5, 0.05, 0.95 );
m_BMI_pct.SetDescript( "Percentile BMI" );
m_Mass.Init("Mass", "Anthropometric", this, 1, 0, 1e6 );
m_Mass.SetDescript( "Mass of person" );
m_Volume.Init( "Volume", "Anthropometric", this, 0, 0, 1e12 );
m_Volume.SetDescript( "Volume of person" );
m_AutoDensity.Init( "AutoDensity", "Anthropometric", this, true, false, true );
m_AutoDensity.SetDescript( "Flag to calculate density based on mass and volume" );
m_Age.Init( "Age", "Anthropometric", this, 30.0, 18, 80 );
m_Age.SetDescript( "Age of person" );
m_SitFrac.Init( "SitFrac", "Anthropometric", this, 0.51, 0.4, 0.6 );
m_SitFrac.SetDescript( "Sitting height divided by stature" );
m_ShowSkelFlag.Init( "ShowSkelFlag", "Anthropometric", this, 0, 0, 1 );
m_ShowSkelFlag.SetDescript( "Flag to show or hide the skeleton." );
m_RLSymFlag.Init( "RLSym", "Pose", this, 1, 0, 1 );
m_RLSymFlag.SetDescript( "Set left/right pose parameters equal." );
m_WristRt.Init( "WristRt", "Pose", this, 0.0, -90.0, 90.0 );
m_WristRt.SetDescript( "Right wrist angle" );
m_ForearmRt.Init( "ForearmRt", "Pose", this, 0.0, -90.0, 90.0 );
m_ForearmRt.SetDescript( "Right forearm angle" );
m_ElbowRt.Init( "ElbowRt", "Pose", this, 15.0, 0, 150.0 );
m_ElbowRt.SetDescript( "Right elbow angle" );
m_ShoulderABADRt.Init( "ShoulderABADRt", "Pose", this, 0, -40, 170.0 );
m_ShoulderABADRt.SetDescript( "Right shoulder AB/AD angle" );
m_ShoulderFERt.Init( "ShoulderFERt", "Pose", this, 0, -30, 180.0 );
m_ShoulderFERt.SetDescript( "Right shoulder FE angle" );
m_ShoulderIERt.Init( "ShoulderIERt", "Pose", this, 0.0, -30, 100.0 );
m_ShoulderIERt.SetDescript( "Right shoulder IE angle" );
m_HipABADRt.Init( "HipABADRt", "Pose", this, 0.5, -45, 45.0 );
m_HipABADRt.SetDescript( "Right hip AB/AD angle" );
m_HipFERt.Init( "HipFERt", "Pose", this, 2.5, -15.0, 130.0 );
m_HipFERt.SetDescript( "Right hip FE angle" );
m_KneeRt.Init( "KneeRt", "Pose", this, 0.0, 0.0, 140.0 );
m_KneeRt.SetDescript( "Right knee angle" );
m_AnkleRt.Init( "AnkleRt", "Pose", this, 0.0, -15, 15.0 );
m_AnkleRt.SetDescript( "Right ankle angle" );
m_WristLt.Init( "WristLt", "Pose", this, 0.0, -90.0, 90.0 );
m_WristLt.SetDescript( "Left wrist angle" );
m_ForearmLt.Init( "ForearmLt", "Pose", this, 0.0, -90.0, 90.0 );
m_ForearmLt.SetDescript( "Left forearm angle" );
m_ElbowLt.Init( "ElbowLt", "Pose", this, 15.0, 0, 150.0 );
m_ElbowLt.SetDescript( "Left elbow angle" );
m_ShoulderABADLt.Init( "ShoulderABADLt", "Pose", this, 15.0, -40, 170.0 );
m_ShoulderABADLt.SetDescript( "Left shoulder AB/AD angle" );
m_ShoulderFELt.Init( "ShoulderFELt", "Pose", this, 1.0, -30, 180.0 );
m_ShoulderFELt.SetDescript( "Left shoulder FE angle" );
m_ShoulderIELt.Init( "ShoulderIELt", "Pose", this, 0.0, -30, 100.0 );
m_ShoulderIELt.SetDescript( "Left shoulder IE angle" );
m_HipABADLt.Init( "HipABADLt", "Pose", this, 0.5, -45, 45.0 );
m_HipABADLt.SetDescript( "Left hip AB/AD angle" );
m_HipFELt.Init( "HipFELt", "Pose", this, 2.5, -15.0, 130.0 );
m_HipFELt.SetDescript( "Left hip FE angle" );
m_KneeLt.Init( "KneeLt", "Pose", this, 0.0, 0.0, 140.0 );
m_KneeLt.SetDescript( "Left knee angle" );
m_AnkleLt.Init( "AnkleLt", "Pose", this, 0.0, -15, 15.0 );
m_AnkleLt.SetDescript( "Left ankle angle" );
m_Back.Init( "Back", "Pose", this, 0.0, -15, 45.0 );
m_Back.SetDescript( "Back angle" );
m_Waist.Init( "Waist", "Pose", this, 0.0, -15, 45.0 );
m_Waist.SetDescript( "Waist angle" );
m_Nod.Init( "Nod", "Pose", this, 0.0, -40, 50.0 );
m_Nod.SetDescript( "Nod angle" );
m_RotateHead.Init( "RotateHead", "Pose", this, 0.0, -80, 80.0 );
m_RotateHead.SetDescript( "Turn head angle" );
m_PresetPose.Init( "PresetPose", "Pose", this, HumanGeom::STANDING, HumanGeom::STANDING, HumanGeom::SITTING );
m_PresetPose.SetDescript( "Pose to set when triggered from GUI" );
// Setup static member variables to be used by all HumanGeom
if ( !m_MasterAttach )
{
SetupMesh( m_MasterMesh );
Pinocchio::DataSkeleton skeleton;
REAL_T androg_skel_verts[NUM_SKEL_VERT][3];
ComputeAvePts( m_male_skel_verts, m_female_skel_verts, NUM_SKEL_VERT, androg_skel_verts );
SetupSkel( androg_skel_verts, skeleton );
m_MasterAttach = SetupAttach( m_MasterMesh, skeleton );
// 20 & over. From NHANES
vector < double > cprob = {.05, .10, .15, .25, .50, .75, .85, .90, .95};
vector < double > msta = {1634, 1662, 1680, 1706, 1756, 1808, 1837, 1854, 1881};
vector < double > fsta = {1498, 1527, 1543, 1568, 1619, 1664, 1690, 1707, 1735};
vector < double > mbmi = {20.7, 22.2, 23.0, 24.6, 27.7, 31.6, 34.0, 36.1, 39.8};
vector < double > fbmi = {19.6, 21.0, 22.0, 23.6, 27.7, 33.2, 36.5, 39.3, 43.3};
m_MaleStatureECDF.InterpolatePCHIP( msta, cprob, false );
m_FemaleStatureECDF.InterpolatePCHIP( fsta, cprob, false );
m_MaleBMIECDF.InterpolatePCHIP( mbmi, cprob, false );
m_FemaleBMIECDF.InterpolatePCHIP( fbmi, cprob, false );
// DebugDump();
}
m_MainSurfVec.clear();
}
//==== Destructor ====//
HumanGeom::~HumanGeom()
{
}
void HumanGeom::DebugDump()
{
m_MasterMesh.writeObj("debug.obj");
//output attachment
std::ofstream astrm("attachment.out");
for(int i = 0; i < (int)m_MasterMesh.vertices.size(); ++i)
{
Vector<double, -1> v = m_MasterAttach->getWeights(i);
for(int j = 0; j < v.size(); ++j)
{
double d = floor(0.5 + v[j] * 10000.) / 10000.;
astrm << d << " ";
}
astrm << std::endl;
}
}
void HumanGeom::ComputeScore( const REAL_T C[200][6], const vector < double > &X, vector < double > &score )
{
const int m = 6;
const int n = 200;
for ( int i = 0; i < n; i++ )
{
score[i] = 0.0;
for ( int j = 0; j < m; j++ )
{
score[i] += C[i][j] * X[j];
}
}
}
// Y = Ybar + P * ( m_coeffs * X );
void HumanGeom::ComputeResultsMesh( const REAL_T P[][200], const vector < double > &score, const REAL_T Ybar[][3], vector < vec3d > &Y )
{
const int n = 200;
int npt = NUM_MESH_VERT;
for ( int i = 0; i < npt; i++ )
{
Y[i].set_arr( Ybar[i] );
double yadd[3];
for ( int k = 0; k < 3; k++ )
{
yadd[k] = 0;
int l = i * 3 + k;
for ( int j = 0; j < n; j++ )
{
yadd[k] += P[l][j] * score[j];
}
}
Y[i] += yadd;
Y[i+NUM_MESH_VERT].set_refy( Y[i] );
}
}
// Y = Ybar + P * ( m_coeffs * X );
void HumanGeom::ComputeResultsSkel( const REAL_T P[][200], const vector < double > &score, const REAL_T Ybar[][3], vector < vec3d > &Y )
{
const int n = 200;
int npt = Y.size();
for ( int i = 0; i < npt; i++ )
{
Y[i].set_arr( Ybar[i] );
double yadd[3];
for ( int k = 0; k < 3; k++ )
{
yadd[k] = 0;
int l = i * 3 + k;
for ( int j = 0; j < n; j++ )
{
yadd[k] += P[l][j] * score[j];
}
}
Y[i] += yadd;
}
}
void Mat2Trans( const Matrix4d &M, Pinocchio::Transform<> &T )
{
double qw, qx, qy, qz, tx, ty, tz;
M.toQuat( qw, qx, qy, qz, tx, ty, tz );
T = Pinocchio::Transform<>( Pinocchio::Quaternion<>( qw, qx, qy, qz ), 1.0, Vector3( tx, ty, tz ) );
}
void HumanGeom::CopyVertsToSkel( const vector < vec3d > & sv )
{
m_SkelVerts.resize( NUM_SKEL );
for ( int i = 0; i < m_SkelVerts.size(); i++ )
{
int ind = m_skel_indx[i];
if ( ind < 0 )
{
m_SkelVerts[i].set_refy( sv[-ind] );
}
else
{
m_SkelVerts[i] = sv[ind];
}
}
}
vec3d HumanGeom::GetDesignEye() const
{
return m_ModelMatrix.xform( m_PoseSkelVerts[ DES_EYE ] );
}
Matrix4d HumanGeom::GetDesignEyeMatrix( bool axisaligned ) const
{
vec3d eyept = GetDesignEye();
Matrix4d mat;
if ( axisaligned )
{
mat.translatev( eyept );
}
else
{
vec3d xdir, ydir, zdir;
m_TVision.getBasis( xdir, ydir, zdir );
Matrix4d modelinv = m_ModelMatrix;
modelinv.affineInverse();
eyept.Transform( modelinv );
mat.translatev( eyept );
mat.setBasis( xdir, ydir, zdir );
mat.postMult( m_ModelMatrix );
}
return mat;
}
double HumanGeom::Get_mm2UX()
{
double sf = 1.0;
switch ( m_LenUnit() )
{
case vsp::LEN_MM:
sf = 1.0;
break;
case vsp::LEN_CM:
sf = 0.1;
break;
case vsp::LEN_M:
sf = 0.001;
break;
case vsp::LEN_IN:
sf = 1.0/25.4;
break;
case vsp::LEN_FT:
sf = 1.0/(25.4*12.0);
break;
case vsp::LEN_YD:
sf = 1.0/(25.4*12.0*3.0);
break;
}
return sf;
}
void HumanGeom::ValidateParms( )
{
if ( m_RLSymFlag() )
{
m_WristLt = m_WristRt();
m_ForearmLt = m_ForearmRt();
m_ElbowLt = m_ElbowRt();
m_ShoulderABADLt = m_ShoulderABADRt();
m_ShoulderFELt = m_ShoulderFERt();
m_ShoulderIELt = m_ShoulderIERt();
m_HipABADLt = m_HipABADRt();
m_HipFELt = m_HipFERt();
m_KneeLt = m_KneeRt();
m_AnkleLt = m_AnkleRt();
}
if ( UpdatedParm( m_LenUnit.GetID() ) )
{
m_Stature.SetLowerLimit( 0.0 );
m_Stature.SetUpperLimit( 1e5 );
double sf = Get_mm2UX();
if ( m_GenderFlag() == vsp::MALE )
{
m_Stature = m_MaleStatureECDF.CompPnt( m_Stature_pct() ) * sf;
m_Stature.SetLowerLimit( 1634 * sf );
m_Stature.SetUpperLimit( 1881 * sf );
}
else
{
m_Stature = m_FemaleStatureECDF.CompPnt( m_Stature_pct() ) * sf;
m_Stature.SetLowerLimit( 1498 * sf );
m_Stature.SetUpperLimit( 1735 * sf );
}
}
if( UpdatedParm( m_Stature.GetID() ) )
{
double p;
if ( m_GenderFlag() == vsp::MALE )
{
m_MaleStatureECDF.FindNearest( p, m_Stature() / Get_mm2UX() );
}
else
{
m_FemaleStatureECDF.FindNearest( p, m_Stature() / Get_mm2UX() );
}
m_Stature_pct = p;
}
else
{
if ( m_GenderFlag() == vsp::MALE )
{
m_Stature = m_MaleStatureECDF.CompPnt( m_Stature_pct() ) * Get_mm2UX();
}
else
{
m_Stature = m_FemaleStatureECDF.CompPnt( m_Stature_pct() ) * Get_mm2UX();
}
}
if( UpdatedParm( m_Mass.GetID() ) )
{
double sta_m = 0.001 * m_Stature() / Get_mm2UX();
m_BMI = ConvertMass( m_Mass(), m_MassUnit(), vsp::MASS_UNIT_KG ) / ( sta_m * sta_m );
double p;
if ( m_GenderFlag() == vsp::MALE )
{
m_MaleBMIECDF.FindNearest( p, m_BMI() );
}
else
{
m_FemaleBMIECDF.FindNearest( p, m_BMI() );
}
m_BMI_pct = p;
}
else if( UpdatedParm( m_BMI.GetID() ) )
{
double sta_m = 0.001 * m_Stature() / Get_mm2UX();
m_Mass = ConvertMass( m_BMI() * sta_m * sta_m, vsp::MASS_UNIT_KG, m_MassUnit() );
double p;
if ( m_GenderFlag() == vsp::MALE )
{
m_MaleBMIECDF.FindNearest( p, m_BMI() );
}
else
{
m_FemaleBMIECDF.FindNearest( p, m_BMI() );
}
m_BMI_pct = p;
}
else
{
if ( m_GenderFlag() == vsp::MALE )
{
m_BMI = m_MaleBMIECDF.CompPnt( m_BMI_pct() );
}
else
{
m_BMI = m_FemaleBMIECDF.CompPnt( m_BMI_pct() );
}
double sta_m = 0.001 * m_Stature() / Get_mm2UX();
m_Mass = ConvertMass( m_BMI() * sta_m * sta_m, vsp::MASS_UNIT_KG, m_MassUnit() );
}
}
void HumanGeom::SetPreset()
{
int p = m_PresetPose();
switch( p )
{
case STANDING:
m_RLSymFlag = true;
m_Back = 0;
m_Waist = 0;
m_Nod = 0;
m_RotateHead = 0;
m_WristRt = 0;
m_ForearmRt = 0;
m_ElbowRt = 15;
m_ShoulderABADRt = 0;
m_ShoulderFERt = 0;
m_ShoulderIERt = 0;
m_HipABADRt = 0.5;
m_HipFERt = 2.5;
m_KneeRt = 0.0;
m_AnkleRt = 0.0;
break;
case SITTING:
m_RLSymFlag = true;
m_Back = 0;
m_Waist = 0;
m_Nod = 0;
m_RotateHead = 0;
m_WristRt = 0;
m_ForearmRt = 0;
m_ElbowRt = 80;
m_ShoulderABADRt = 0;
m_ShoulderFERt = 0;
m_ShoulderIERt = 45;
m_HipABADRt = 0.5;
m_HipFERt = 80;
m_KneeRt = 80;
m_AnkleRt = 0.0;
break;
}
}
void HumanGeom::UpdateSurf()
{
ValidateParms();
// Compute score vector used in anthropometric calculations
double stamm = m_Stature() / Get_mm2UX();
vector < double > vars(6);
vars[0] = stamm;
vars[1] = m_BMI();
vars[2] = m_SitFrac();
vars[3] = m_Age();
vars[4] = m_BMI() * m_Age();
vars[5] = 1.0;
vector < double > score( 200, 0.0 );
if ( m_GenderFlag() == vsp::MALE )
{
ComputeScore( m_male_coeffs, vars, score );
}
else
{
ComputeScore( m_female_coeffs, vars, score );
}
// Compute anthropometric skeleton.
vector < vec3d > sv( NUM_SKEL_VERT );
if ( m_GenderFlag() == vsp::MALE )
{
ComputeResultsSkel( m_male_skel_pcs, score, m_male_skel_verts, sv );
}
else
{
ComputeResultsSkel( m_female_skel_pcs, score, m_female_skel_verts, sv );
}
CopyVertsToSkel( sv );
// Compute pose transformations.
Matrix4d t_rtwrist, t_rtforearm, t_rtbicep, t_rtfoot, t_rtshin, t_rtthigh, t_back, t_waist, t_head;
Matrix4d t_ltwrist, t_ltforearm, t_ltbicep, t_ltfoot, t_ltshin, t_ltthigh;
ComputeShoulderTrans( RSHOULDER, RELBOW, m_ShoulderABADRt(), m_ShoulderFERt(), t_rtbicep );
ComputeElbowTrans( RSHOULDER, RELBOW, RWRIST, m_ElbowRt() * M_PI / 180.0, m_ShoulderIERt() * M_PI / 180.0, t_rtforearm );
t_rtforearm.postMult( t_rtbicep );
ComputeForearmTrans( RELBOW, RWRIST, RWRISTAX, RFINGER, m_ForearmRt() * M_PI / 180.0, m_WristRt() * M_PI / 180.0, t_rtwrist);
t_rtwrist.postMult( t_rtforearm );
ComputeShoulderTrans( LSHOULDER, LELBOW, -m_ShoulderABADLt(), m_ShoulderFELt(), t_ltbicep );
ComputeElbowTrans( LSHOULDER, LELBOW, LWRIST, m_ElbowLt() * M_PI / 180.0, -m_ShoulderIELt() * M_PI / 180.0, t_ltforearm );
t_ltforearm.postMult( t_ltbicep );
ComputeForearmTrans( LELBOW, LWRIST, LWRISTAX, LFINGER, -m_ForearmLt() * M_PI / 180.0, -m_WristLt() * M_PI / 180.0, t_ltwrist);
t_ltwrist.postMult( t_ltforearm );
ComputeHeadTrans( ORIGIN, HEAD, m_Nod() * M_PI / 180.0, m_RotateHead() * M_PI / 180.0, t_head );
ComputeBackTrans( ORIGIN, BACK, WAIST, m_Back() * M_PI / 180.0, t_back );
ComputeWaistTrans( BACK, WAIST, RHIP, m_Waist() * M_PI / 180.0, t_waist );
t_waist.postMult( t_back );
ComputeHipTrans( WAIST, RHIP, RKNEE, m_HipABADRt(), m_HipFERt(), t_rtthigh );
t_rtthigh.postMult( t_waist );
ComputeKneeTrans( RHIP, RKNEE, RANKLE, m_KneeRt() * M_PI / 180.0, t_rtshin );
t_rtshin.postMult( t_rtthigh );
ComputeAnkleTrans( RKNEE, RANKLE, RTOE, m_AnkleRt() * M_PI / 180.0, t_rtfoot );
t_rtfoot.postMult( t_rtshin );
ComputeHipTrans( WAIST, LHIP, LKNEE, -m_HipABADLt(), m_HipFELt(), t_ltthigh );
t_ltthigh.postMult( t_waist );
ComputeKneeTrans( LHIP, LKNEE, LANKLE, m_KneeLt() * M_PI / 180.0, t_ltshin );
t_ltshin.postMult( t_ltthigh );
ComputeAnkleTrans( LKNEE, LANKLE, LTOE, m_AnkleLt() * M_PI / 180.0, t_ltfoot );
t_ltfoot.postMult( t_ltshin );
// Pose skeleton.
m_PoseSkelVerts = m_SkelVerts;
m_PoseSkelVerts[WAIST] = t_back.xform( m_PoseSkelVerts[WAIST] );
m_PoseSkelVerts[RHIP] = t_waist.xform( m_PoseSkelVerts[RHIP] );
m_PoseSkelVerts[LHIP] = t_waist.xform( m_PoseSkelVerts[LHIP] );
m_PoseSkelVerts[HEAD] = t_head.xform( m_PoseSkelVerts[HEAD] );
m_PoseSkelVerts[REYE] = t_head.xform( m_PoseSkelVerts[REYE] );
m_PoseSkelVerts[LEYE] = t_head.xform( m_PoseSkelVerts[LEYE] );
m_PoseSkelVerts[DES_EYE] = t_head.xform( m_PoseSkelVerts[DES_EYE] );
m_PoseSkelVerts[RELBOW] = t_rtbicep.xform( m_PoseSkelVerts[RELBOW] );
m_PoseSkelVerts[RWRIST] = t_rtforearm.xform( m_PoseSkelVerts[RWRIST] );
m_PoseSkelVerts[RWRISTAX] = t_rtforearm.xform( m_PoseSkelVerts[RWRISTAX] );
m_PoseSkelVerts[RFINGER] = t_rtwrist.xform( m_PoseSkelVerts[RFINGER] );
m_PoseSkelVerts[LELBOW] = t_ltbicep.xform( m_PoseSkelVerts[LELBOW] );
m_PoseSkelVerts[LWRIST] = t_ltforearm.xform( m_PoseSkelVerts[LWRIST] );
m_PoseSkelVerts[LWRISTAX] = t_ltforearm.xform( m_PoseSkelVerts[LWRISTAX] );
m_PoseSkelVerts[LFINGER] = t_ltwrist.xform( m_PoseSkelVerts[LFINGER] );
m_PoseSkelVerts[RKNEE] = t_rtthigh.xform( m_PoseSkelVerts[RKNEE] );
m_PoseSkelVerts[RANKLE] = t_rtshin.xform( m_PoseSkelVerts[RANKLE] );
m_PoseSkelVerts[RTOE] = t_rtfoot.xform( m_PoseSkelVerts[RTOE] );
m_PoseSkelVerts[LKNEE] = t_ltthigh.xform( m_PoseSkelVerts[LKNEE] );
m_PoseSkelVerts[LANKLE] = t_ltshin.xform( m_PoseSkelVerts[LANKLE] );
m_PoseSkelVerts[LTOE] = t_ltfoot.xform( m_PoseSkelVerts[LTOE] );
// Transfer transformations to Pinocchio vector form.
unsigned int nbones = m_SkelVerts.size();
std::vector< Pinocchio::Transform<> > trs( nbones );
Mat2Trans( t_head, trs[NECK] );
Mat2Trans( t_head, trs[SKULL] );
Mat2Trans( t_head, trs[LORBITAL] );
Mat2Trans( t_head, trs[RORBITAL] );
Mat2Trans( t_waist, trs[LOWSPINE] );
Mat2Trans( t_waist, trs[LPELVIS] );
Mat2Trans( t_waist, trs[RPELVIS] );
Mat2Trans( t_rtwrist, trs[RHAND] );
Mat2Trans( t_rtforearm, trs[RWRISTBASE] );
Mat2Trans( t_rtforearm, trs[RFOREARM] );
Mat2Trans( t_rtbicep, trs[RBICEP] );
Mat2Trans( t_ltwrist, trs[LHAND] );
Mat2Trans( t_ltforearm, trs[LWRISTBASE] );
Mat2Trans( t_ltforearm, trs[LFOREARM] );
Mat2Trans( t_ltbicep, trs[LBICEP] );
Mat2Trans( t_rtfoot, trs[RFOOT] );
Mat2Trans( t_rtshin, trs[RSHIN] );
Mat2Trans( t_rtthigh, trs[RTHIGH] );
Mat2Trans( t_ltfoot, trs[LFOOT] );
Mat2Trans( t_ltshin, trs[LSHIN] );
Mat2Trans( t_ltthigh, trs[LTHIGH] );
// Build up vision transformation matrix.
Matrix4d tcenter1;
tcenter1.translatev( -m_SkelVerts[WAIST] );
Matrix4d tfinal1 = t_waist;
tfinal1.affineInverse();
tcenter1.matMult( tfinal1 );
m_TVision = t_head;
m_TVision.postMult( tcenter1 );
// Process main geometry
m_MainVerts.clear();
m_MainVerts.resize( NUM_MESH_VERT * 2 );
// Anthropometric calculation of base mesh
if ( m_GenderFlag() == vsp::MALE )
{
ComputeResultsMesh( m_male_half_pcs, score, m_male_half_verts, m_MainVerts );
}
else
{
ComputeResultsMesh( m_female_half_pcs, score, m_female_half_verts, m_MainVerts );
}
Pinocchio::Mesh m_LocalMesh = m_MasterMesh;
CopyVertsToMesh( m_MainVerts, m_LocalMesh );
// Deform for pose
Pinocchio::Mesh newmesh = m_MasterAttach->deform( m_LocalMesh, trs );
CopyMeshToVerts( newmesh, m_MainVerts );
// Get scale for units.
double sf = Get_mm2UX();
// Calculate volume of posed figure
m_Volume = CalculateVolume() * sf * sf * sf;
if ( m_AutoDensity() )
{
m_Density = m_Mass() / m_Volume();
}
// Final positioning & scale -- hold waist fixed & origin
Matrix4d tcenter;
tcenter.translatev( -m_SkelVerts[WAIST] );
Matrix4d sc;
sc.scale( sf );
tcenter.postMult( sc );
tcenter.xformvec( m_SkelVerts );
Matrix4d tfinal = t_waist;
tfinal.affineInverse();
tcenter.matMult( tfinal );
tcenter.xformvec( m_MainVerts );
tcenter.xformvec( m_PoseSkelVerts );
/*
for ( int i = 0; i < nbones; i++ )
{
Pinocchio::Quaternion<> q = trs[i].getRot();
printf( "%d ", i );
for ( int j = 0; j < 4; j++ )
{
printf( "q_%d %f ", j, q[j] );
}
Vector3 v = trs[i].getTrans();
for ( int j = 0; j < 3; j++ )
{
printf( "t_%d %f ", j, v[j] );
}
printf( "s %f\n", trs[i].getScale() );
}
*/
}
double HumanGeom::CalculateVolume()
{
int num_tris = NUM_MESH_TRI;
double vol = 0;
for ( int t = 0 ; t < ( int ) num_tris ; t++ )
{
vec3d p0 = m_MainVerts[m_half_tris[t][0]];
vec3d p1 = m_MainVerts[m_half_tris[t][1]];
vec3d p2 = m_MainVerts[m_half_tris[t][2]];
vol += tetra_volume( p0, p1, p2 );
}
for ( int t = 0 ; t < ( int ) num_tris ; t++ )
{
vec3d p0 = m_MainVerts[m_half_tris[t][0] + NUM_MESH_VERT];
vec3d p1 = m_MainVerts[m_half_tris[t][2] + NUM_MESH_VERT];
vec3d p2 = m_MainVerts[m_half_tris[t][1] + NUM_MESH_VERT];
vol += tetra_volume( p0, p1, p2 );
}
return vol;
}
void HumanGeom::UpdateBBox()
{
BndBox new_box;
for ( int j = 0 ; j < ( int )m_Verts.size() ; j++ )
{
for ( int i = 0; i < ( int )m_Verts[j].size(); i++ )
{
new_box.Update( m_Verts[j][i] );
}
}
if ( new_box != m_BBox )
{
m_BbXLen = new_box.GetMax( 0 ) - new_box.GetMin( 0 );
m_BbYLen = new_box.GetMax( 1 ) - new_box.GetMin( 1 );
m_BbZLen = new_box.GetMax( 2 ) - new_box.GetMin( 2 );
m_BbXMin = new_box.GetMin( 0 );
m_BbYMin = new_box.GetMin( 1 );
m_BbZMin = new_box.GetMin( 2 );
m_BBox = new_box;
m_ScaleIndependentBBox = m_BBox;
}
}
// This is substantially similar to Geom::UpdateSymmAttach() and could probably be combined in a meaningful way.
void HumanGeom::UpdateSymmAttach()
{
unsigned int num_surf = GetNumTotalMeshs();
m_Verts.clear();
m_FlipNormal.clear();
m_MainSurfIndxVec.clear();
m_SurfSymmMap.clear();
m_SurfCopyIndx.clear();
m_Verts.resize( num_surf );
m_FlipNormal.resize( num_surf, false );
m_MainSurfIndxVec.resize( num_surf, -1 );
m_SurfSymmMap.resize( num_surf );
m_SurfCopyIndx.resize( num_surf );
int num_main = GetNumMainMeshs(); // Currently hard-coded to 1. Some of below is over-complex for this case.
for ( int i = 0 ; i < ( int )num_main ; i++ )
{
m_Verts[i] = m_MainVerts;
m_FlipNormal[i] = false; // Assume main mesh is properly oriented.
m_MainSurfIndxVec[i] = i;
m_SurfSymmMap[ m_MainSurfIndxVec[i] ].push_back( i );
m_SurfCopyIndx[i] = 0;
}
m_TransMatVec.resize( num_surf, Matrix4d() );
// Compute Relative Translation Matrix
Matrix4d symmOriginMat;
Matrix4d relTrans;
if ( m_SymAncestOriginFlag() )
{
symmOriginMat = GetAncestorAttachMatrix( m_SymAncestor() - 1 );
}
else
{
symmOriginMat = GetAncestorModelMatrix( m_SymAncestor() - 1 );
}
relTrans = symmOriginMat;
relTrans.affineInverse();
relTrans.matMult( m_ModelMatrix.data() );
for ( int i = 0 ; i < ( int )m_TransMatVec.size() ; i++ )
{
m_TransMatVec[i].initMat( relTrans.data() );
}
// Copy main surfs
int symFlag = GetSymFlag();
if ( symFlag != 0 )
{
int numShifts = -1;
Matrix4d Ref; // Reflection Matrix
Matrix4d Ref_Orig; // Original Reflection Matrix
Matrix4d Rel; // Relative Transformation matrix with Reflection applied ( this is for the main surfaces )
double angle = ( 360 ) / ( double )m_SymRotN();
int currentIndex = num_main;
bool radial = false;
for ( int i = 0 ; i < GetNumSymFlags() ; i ++ ) // Loop through each of the set sym flags
{
// Find next set sym flag
while ( true )
{
numShifts++;
if ( ( ( symFlag >> numShifts ) & ( 1 << 0 ) ) || numShifts > vsp::SYM_NUM_TYPES )
{
break;
}
}
// Create Reflection Matrix
if ( ( 1 << numShifts ) == vsp::SYM_XY )
{
Ref.loadXYRef();
}
else if ( ( 1 << numShifts ) == vsp::SYM_XZ )
{
Ref.loadXZRef();
}
else if ( ( 1 << numShifts ) == vsp::SYM_YZ )
{
Ref.loadYZRef();
}
else if ( ( 1 << numShifts ) == vsp::SYM_ROT_X )
{
Ref.loadIdentity();
Ref.rotateX( angle );
Ref_Orig = Ref;
radial = true;
}
else if ( ( 1 << numShifts ) == vsp::SYM_ROT_Y )
{
Ref.loadIdentity();
Ref.rotateY( angle );
Ref_Orig = Ref;
radial = true;
}
else if ( ( 1 << numShifts ) == vsp::SYM_ROT_Z )
{
Ref.loadIdentity();
Ref.rotateZ( angle );
Ref_Orig = Ref;
radial = true;
}
// number of additional surfaces for a single reflection ( for rotational reflections it is m_SymRotN-1 times this number
int numAddSurfs = currentIndex;
int addIndex = 0;
for ( int j = currentIndex ; j < currentIndex + numAddSurfs ; j++ )
{
if ( radial ) // rotational reflection
{
for ( int k = 0 ; k < m_SymRotN() - 1 ; k++ )
{
m_Verts[j + k * numAddSurfs] = m_Verts[j - currentIndex];
m_MainSurfIndxVec[j + k * numAddSurfs] = m_MainSurfIndxVec[j - currentIndex];
m_SurfCopyIndx[j + k * numAddSurfs] = m_SurfSymmMap[ m_MainSurfIndxVec[j + k * numAddSurfs] ].size();
m_SurfSymmMap[ m_MainSurfIndxVec[j + k * numAddSurfs] ].push_back( j + k * numAddSurfs );
m_TransMatVec[j + k * numAddSurfs].initMat( m_TransMatVec[j - currentIndex].data() );
m_TransMatVec[j + k * numAddSurfs].postMult( Ref.data() ); // Apply Reflection
// Increment rotation by the angle
Ref.postMult( Ref_Orig.data() );
addIndex++;
}
// Reset reflection matrices to the beginning angle
Ref = Ref_Orig;
}
else
{
m_Verts[j] = m_Verts[j - currentIndex];
m_FlipNormal[j] = !m_FlipNormal[j - currentIndex];
m_MainSurfIndxVec[j] = m_MainSurfIndxVec[j - currentIndex];
m_SurfCopyIndx[j] = m_SurfSymmMap[ m_MainSurfIndxVec[j] ].size();
m_SurfSymmMap[ m_MainSurfIndxVec[ j ] ].push_back( j );
m_TransMatVec[j].initMat( m_TransMatVec[j - currentIndex].data() );
m_TransMatVec[j].postMult( Ref.data() ); // Apply Reflection
addIndex++;
}
}
currentIndex += addIndex;
radial = false;
}
}
Matrix4d retrun_relTrans = relTrans;
retrun_relTrans.affineInverse();
m_FeaTransMatVec.clear();
m_FeaTransMatVec.resize( num_surf );
//==== Save Transformation Matrix and Apply Transformations ====//
for ( int i = 0 ; i < num_surf ; i++ )
{
m_TransMatVec[i].postMult( symmOriginMat.data() );
m_TransMatVec[i].xformvec( m_Verts[i] ); // Apply total transformation to meshes
m_FeaTransMatVec[i] = m_TransMatVec[i];
m_FeaTransMatVec[i].matMult( retrun_relTrans.data() ); // m_FeaTransMatVec does not include the relTrans matrix
}
}
void HumanGeom::UpdateDrawObj()
{
// Add in SubSurfaces to TMeshVec if m_DrawSubSurfs is true
int num_meshes = m_Verts.size();
// Mesh Should Be Flat Before Calling this Method
int add_ind = 0;
m_WireShadeDrawObj_vec.resize( 1, DrawObj() );
unsigned int pi = 0;
unsigned int ido = 0;
unsigned int isize = 0;
for ( int m = 0 ; m < ( int )num_meshes ; m++ )
{
int num_tris = NUM_MESH_TRI;
isize = isize + num_tris * 3 * 2;
m_WireShadeDrawObj_vec[ido].m_PntVec.resize( isize );
m_WireShadeDrawObj_vec[ido].m_NormVec.resize( isize );
for ( int t = 0 ; t < ( int ) num_tris ; t++ )
{
int i2 = 1;
int i3 = 2;
if( m_FlipNormal[m] )
{
i2 = 2;
i3 = 1;
}
vec3d p0 = m_Verts[m][m_half_tris[t][0]];
vec3d p1 = m_Verts[m][m_half_tris[t][i2]];
vec3d p2 = m_Verts[m][m_half_tris[t][i3]];
vec3d v0 (0, 0, 0);
if ( dist (p0, v0) == 0 )
{
printf("Found zero vert %d\n", m_half_tris[t][0] );
}
if ( dist (p1, v0) == 0 )
{
printf("Found zero vert %d\n", m_half_tris[t][i2] );
}
if ( dist (p2, v0) == 0 )
{
printf("Found zero vert %d\n", m_half_tris[t][i3] );
}
//==== Compute Normal ====//
vec3d p10 = p1 - p0;
vec3d p20 = p2 - p0;
vec3d norm = cross( p10, p20 );
norm.normalize();
m_WireShadeDrawObj_vec[ido].m_PntVec[pi] = p0 ;
m_WireShadeDrawObj_vec[ido].m_PntVec[pi + 1] = p1 ;
m_WireShadeDrawObj_vec[ido].m_PntVec[pi + 2] = p2 ;
m_WireShadeDrawObj_vec[ido].m_NormVec[pi] = norm;
m_WireShadeDrawObj_vec[ido].m_NormVec[pi + 1] = norm;
m_WireShadeDrawObj_vec[ido].m_NormVec[pi + 2] = norm;
pi += 3;
}
for ( int t = 0 ; t < ( int ) num_tris ; t++ )
{
int i2 = 2;
int i3 = 1;
if( m_FlipNormal[m] )
{
i2 = 1;
i3 = 2;
}
vec3d p0 = m_Verts[m][m_half_tris[t][0]+NUM_MESH_VERT];
vec3d p1 = m_Verts[m][m_half_tris[t][i2]+NUM_MESH_VERT];
vec3d p2 = m_Verts[m][m_half_tris[t][i3]+NUM_MESH_VERT];
vec3d v0 (0, 0, 0);
if ( dist (p0, v0) == 0 )
{
printf("Found zero vert %d\n", m_half_tris[t][0] );
}
if ( dist (p1, v0) == 0 )
{
printf("Found zero vert %d\n", m_half_tris[t][i2] );
}
if ( dist (p2, v0) == 0 )
{
printf("Found zero vert %d\n", m_half_tris[t][i3] );
}
//==== Compute Normal ====//
vec3d p10 = p1 - p0;
vec3d p20 = p2 - p0;
vec3d norm = cross( p10, p20 );
norm.normalize();
m_WireShadeDrawObj_vec[ido].m_PntVec[pi] = p0 ;
m_WireShadeDrawObj_vec[ido].m_PntVec[pi + 1] = p1 ;
m_WireShadeDrawObj_vec[ido].m_PntVec[pi + 2] = p2 ;
m_WireShadeDrawObj_vec[ido].m_NormVec[pi] = norm;
m_WireShadeDrawObj_vec[ido].m_NormVec[pi + 1] = norm;
m_WireShadeDrawObj_vec[ido].m_NormVec[pi + 2] = norm;
pi += 3;
}
}
//==== Bounding Box ====//
m_HighlightDrawObj.m_PntVec = m_BBox.GetBBoxDrawLines();
m_HighlightDrawObj.m_GeomChanged = true;
// Flag the DrawObjects as changed
for ( int i = 0 ; i < ( int )m_WireShadeDrawObj_vec.size(); i++ )
{
m_WireShadeDrawObj_vec[i].m_GeomChanged = true;
}
m_FeatureDrawObj_vec.clear();
m_FeatureDrawObj_vec.resize(2);
m_FeatureDrawObj_vec[0].m_GeomChanged = true;
m_FeatureDrawObj_vec[0].m_LineWidth = 3.0;
m_FeatureDrawObj_vec[0].m_LineColor = vec3d( 0.0, 0.0, 0.0 );
m_FeatureDrawObj_vec[1].m_GeomChanged = true;
m_FeatureDrawObj_vec[1].m_LineWidth = 3.0;
m_FeatureDrawObj_vec[1].m_LineColor = vec3d( 0.0, 0.0, 1.0 );
if( m_GuiDraw.GetDispFeatureFlag() )
{
m_FeatureDrawObj_vec[0].m_PntVec.resize( ( NUM_SKEL - 1 ) * 2 );
m_FeatureDrawObj_vec[1].m_PntVec.resize( ( NUM_SKEL - 1 ) * 2 );
const int prevarr[] = {-1, 0, 1, 0, 2, 4, 5, 6, 2, 8, 9, 10, 0, 12, 13, 14, 0, 16, 17, 18, 22, 22, 3, 18, 14};
for ( int i = 1; i < NUM_SKEL; i++ )
{
int iprev = prevarr[i];
m_FeatureDrawObj_vec[0].m_PntVec[ (i - 1) * 2 ] = m_SkelVerts[iprev];
m_FeatureDrawObj_vec[0].m_PntVec[ (i - 1) * 2 + 1 ] = m_SkelVerts[i];
m_FeatureDrawObj_vec[1].m_PntVec[ (i - 1) * 2 ] = m_PoseSkelVerts[iprev];
m_FeatureDrawObj_vec[1].m_PntVec[ (i - 1) * 2 + 1 ] = m_PoseSkelVerts[i];
}
}
//=== Axis ===//
m_AxisDrawObj_vec.clear();
m_AxisDrawObj_vec.resize( 3 );
for ( int i = 0; i < 3; i++ )
{
MakeDashedLine( m_AttachOrigin, m_AttachAxis[i], 4, m_AxisDrawObj_vec[i].m_PntVec );
vec3d c;
c.v[i] = 1.0;
m_AxisDrawObj_vec[i].m_LineColor = c;
m_AxisDrawObj_vec[i].m_GeomChanged = true;
}
}
void HumanGeom::LoadDrawObjs( vector< DrawObj* > & draw_obj_vec )
{
char str[256];
for ( int i = 0 ; i < ( int )m_WireShadeDrawObj_vec.size() ; i++ )
{
// Symmetry drawObjs have same m_ID. Make them unique by adding index
// at the end of m_ID.
snprintf( str, sizeof( str ), "_%d", i );
m_WireShadeDrawObj_vec[i].m_GeomID = m_ID + str;
m_WireShadeDrawObj_vec[i].m_Visible = GetSetFlag( vsp::SET_SHOWN );
// Set Render Destination to Main VSP Window.
m_WireShadeDrawObj_vec[i].m_Screen = DrawObj::VSP_MAIN_SCREEN;
Material * material = m_GuiDraw.getMaterial();
for ( int j = 0; j < 4; j++ )
m_WireShadeDrawObj_vec[i].m_MaterialInfo.Ambient[j] = (float)material->m_Ambi[j];
for ( int j = 0; j < 4; j++ )
m_WireShadeDrawObj_vec[i].m_MaterialInfo.Diffuse[j] = (float)material->m_Diff[j];
for ( int j = 0; j < 4; j++ )
m_WireShadeDrawObj_vec[i].m_MaterialInfo.Specular[j] = (float)material->m_Spec[j];
for ( int j = 0; j < 4; j++ )
m_WireShadeDrawObj_vec[i].m_MaterialInfo.Emission[j] = (float)material->m_Emis[j];
m_WireShadeDrawObj_vec[i].m_MaterialInfo.Shininess = (float)material->m_Shininess;
vec3d lineColor = vec3d( m_GuiDraw.GetWireColor().x() / 255.0,
m_GuiDraw.GetWireColor().y() / 255.0,
m_GuiDraw.GetWireColor().z() / 255.0 );
m_WireShadeDrawObj_vec[i].m_LineWidth = 1.0;
m_WireShadeDrawObj_vec[i].m_LineColor = lineColor;
switch ( m_GuiDraw.GetDrawType() )
{
case vsp::DRAW_TYPE::GEOM_DRAW_WIRE:
m_WireShadeDrawObj_vec[i].m_Type = DrawObj::VSP_WIRE_TRIS;
break;
case vsp::DRAW_TYPE::GEOM_DRAW_HIDDEN:
m_WireShadeDrawObj_vec[i].m_Type = DrawObj::VSP_WIRE_HIDDEN_TRIS;
break;
case vsp::DRAW_TYPE::GEOM_DRAW_SHADE:
m_WireShadeDrawObj_vec[i].m_Type = DrawObj::VSP_SHADED_TRIS;
break;
case vsp::DRAW_TYPE::GEOM_DRAW_NONE:
m_WireShadeDrawObj_vec[i].m_Type = DrawObj::VSP_SHADED_TRIS;
m_WireShadeDrawObj_vec[i].m_Visible = false;
break;
case vsp::DRAW_TYPE::GEOM_DRAW_TEXTURE:
m_WireShadeDrawObj_vec[i].m_Type = DrawObj::VSP_SHADED_TRIS;
break;
}
draw_obj_vec.push_back( &m_WireShadeDrawObj_vec[i] );
}
// Load Feature Lines
for ( int i = 0; i < m_FeatureDrawObj_vec.size(); i++ )
{
m_FeatureDrawObj_vec[i].m_Screen = DrawObj::VSP_MAIN_SCREEN;
snprintf( str, sizeof( str ), "_%d", i );
m_FeatureDrawObj_vec[i].m_GeomID = m_ID + "Feature_" + str;
m_FeatureDrawObj_vec[i].m_Visible = m_GuiDraw.GetDispFeatureFlag() && GetSetFlag( vsp::SET_SHOWN ) && m_ShowSkelFlag();
m_FeatureDrawObj_vec[i].m_Type = DrawObj::VSP_LINES;
draw_obj_vec.push_back( &m_FeatureDrawObj_vec[i] );
}
// Load BoundingBox and Axes
m_HighlightDrawObj.m_Screen = DrawObj::VSP_MAIN_SCREEN;
m_HighlightDrawObj.m_GeomID = BBOXHEADER + m_ID;
m_HighlightDrawObj.m_Visible = m_Vehicle->IsGeomActive( m_ID );
m_HighlightDrawObj.m_LineWidth = 2.0;
m_HighlightDrawObj.m_LineColor = vec3d( 1.0, 0., 0.0 );
m_HighlightDrawObj.m_Type = DrawObj::VSP_LINES;
draw_obj_vec.push_back( &m_HighlightDrawObj );
for ( int i = 0; i < m_AxisDrawObj_vec.size(); i++ )
{
m_AxisDrawObj_vec[i].m_Screen = DrawObj::VSP_MAIN_SCREEN;
snprintf( str, sizeof( str ), "_%d", i );
m_AxisDrawObj_vec[i].m_GeomID = m_ID + "Axis_" + str;
m_AxisDrawObj_vec[i].m_Visible = m_Vehicle->IsGeomActive( m_ID );
m_AxisDrawObj_vec[i].m_LineWidth = 2.0;
m_AxisDrawObj_vec[i].m_Type = DrawObj::VSP_LINES;
draw_obj_vec.push_back( &m_AxisDrawObj_vec[i] );
}
}
//==== Count Number of Sym Surfaces ====//
int HumanGeom::GetNumTotalMeshs() const
{
return GetNumSymmCopies() * GetNumMainMeshs();
}
void HumanGeom::Scale()
{
double currentScale = m_Scale() / m_LastScale();
m_LastScale = m_Scale();
}
void HumanGeom::ApplyScale()
{
}
void HumanGeom::CreateDegenGeom( vector<DegenGeom> &dgs, bool preview, const int & n_ref )
{
unsigned int num_meshes = GetNumTotalMeshs();
dgs.resize( num_meshes );
for ( int i = 0; i < num_meshes; i++ )
{
DegenGeom °enGeom = dgs[i];
degenGeom.setType( DegenGeom::MESH_TYPE );
degenGeom.setParentGeom( this );
degenGeom.setSurfNum( i );
degenGeom.setFlipNormal( m_FlipNormal[i] );
degenGeom.setMainSurfInd( m_MainSurfIndxVec[i] );
degenGeom.setSymCopyInd( m_SurfCopyIndx[i] );
vector < double > tmatvec( 16 );
for ( int j = 0; j < 16; j++ )
{
tmatvec[ j ] = m_TransMatVec[i].data()[ j ];
}
degenGeom.setTransMat( tmatvec );
degenGeom.setNumXSecs( 0 );
degenGeom.setNumPnts( 0 );
degenGeom.setName( GetName() );
}
}
vector<TMesh*> HumanGeom::CreateTMeshVec( bool skipnegflipnormal, const int & n_ref ) const
{
vector<TMesh*> retTMeshVec;
for ( int j = 0; j < m_Verts.size(); j++ )
{
int num_tris;
num_tris = NUM_MESH_TRI;
TMesh* tMesh = new TMesh();
tMesh->LoadGeomAttributes( this );
tMesh->m_SurfNum = j;
for ( int i = 0 ; i < num_tris ; i++ )
{
int i2 = 1;
int i3 = 2;
if ( m_FlipNormal[j] )
{
i2 = 2;
i3 = 1;
}
vec3d p0 = vec3d( m_Verts[j][m_half_tris[i][0]] );
vec3d p1 = vec3d( m_Verts[j][m_half_tris[i][i2]] );
vec3d p2 = vec3d( m_Verts[j][m_half_tris[i][i3]] );
//==== Compute Normal ====//
vec3d p10 = p1 - p0;
vec3d p20 = p2 - p0;
vec3d norm = cross( p10, p20 );
norm.normalize();
//==== Add Valid Facet ====//
tMesh->AddTri( p0, p1, p2, norm, -1 );
}
for ( int i = 0 ; i < num_tris ; i++ )
{
int i2 = 2;
int i3 = 1;
if ( m_FlipNormal[j] )
{
i2 = 1;
i3 = 2;
}
vec3d p0 = vec3d( m_Verts[j][m_half_tris[i][0] + NUM_MESH_VERT] );
vec3d p1 = vec3d( m_Verts[j][m_half_tris[i][i2] + NUM_MESH_VERT] );
vec3d p2 = vec3d( m_Verts[j][m_half_tris[i][i3] + NUM_MESH_VERT] );
//==== Compute Normal ====//
vec3d p10 = p1 - p0;
vec3d p20 = p2 - p0;
vec3d norm = cross( p10, p20 );
norm.normalize();
//==== Add Valid Facet ====//
tMesh->AddTri( p0, p1, p2, norm, -1 );
}
retTMeshVec.push_back( tMesh );
}
return retTMeshVec;
}
void HumanGeom::SetupMesh( Pinocchio::Mesh &m )
{
m.algo = Pinocchio::Mesh::DQS;
// m.algo = Pinocchio::Mesh::LBS;
m.blendWeight = 0.5;
m.vertices.clear();
m.vertices.resize( NUM_MESH_VERT * 2 );
m_VertCopySet.clear();
// Seed initial verts as positive copies
for ( int i = 0; i < NUM_MESH_VERT; i++ )
{
m.vertices[ i ].origVertID = i;
}
// Seed initial verts as negative copies -- except on center line, then reference positive one.
for ( int i = 0; i < NUM_MESH_VERT; i++ )
{
double y = m_male_half_verts[i][1];
if ( y == -y )
{
m_VertCopySet.emplace_hint( m_VertCopySet.end(), i );
}
m.vertices[ i + NUM_MESH_VERT ].origVertID = i + NUM_MESH_VERT;
}
REAL_T androg_half_verts[NUM_MESH_VERT][3];
ComputeAvePts( m_male_half_verts, m_female_half_verts, NUM_MESH_VERT, androg_half_verts );
CopyVertsToMesh( androg_half_verts, m );
m.edges.reserve( 3 * 2 * NUM_MESH_TRI );
// Setup first half of tris as edges.
for ( int i = 0; i < NUM_MESH_TRI; i++ )
{
int first = m.edges.size();
m.edges.resize( m.edges.size() + 3 );
for( int j = 0; j < 3; ++j )
{
m.edges[ first + j ].vertex = m_half_tris[i][j];
}
}
// Setup second half of tris as edges.
for ( int i = 0; i < NUM_MESH_TRI; i++ )
{
int first = m.edges.size();
m.edges.resize( m.edges.size() + 3 );
for( int j = 0; j < 3; ++j )
{
int k = 2 - j; // Reverse direction
int ivert = m_half_tris[i][k] + NUM_MESH_VERT;
if ( m_VertCopySet.count( m_half_tris[i][k] ) ) // This vert is a duplicate.
{
ivert = m_half_tris[i][k];
}
m.edges[ first + j ].vertex = ivert;
}
}
m.fixDupFaces(); // Also eliminates un-used verts. Causes re-numbering of m.vertices
m.computeTopology();
m.computeVertexNormals();
m.normalizeBoundingBox();
}
template < typename vertmat >
void HumanGeom::SetupSkel( const vertmat & vm, Pinocchio::DataSkeleton &skeleton )
{
// m_SkelVerts
// const int HumanGeom::m_skel_indx[NUM_SKEL] = {0, 1, 2, 3, -4, -5, -6, -7, 4, 5, 6, 7, -8, -9, -10, -11, 8, 9, 10, 11, 12, -12, 13, 14, -14};
const int prevarr[] = {-1, 0, 1, 0, 2, 4, 5, 6, 2, 8, 9, 10, 0, 12, 13, 14, 0, 16, 17, 18, 22, 22, 3, 18, 14};
std::vector < int > previd( NUM_SKEL );
std::vector < Vector3 > skel_pts( NUM_SKEL );
for ( int i = 0; i < NUM_SKEL; i++ )
{
int ivert = m_skel_indx[i];
double yref = 1.0;
if ( ivert < 0 )
{
ivert = -ivert;
yref = -1.0;
}
skel_pts[i] = Vector3( vm[ivert][0], yref * vm[ivert][1], vm[ivert][2] );
previd[i] = prevarr[i];
}
// Set up skeleton.
skeleton.init( skel_pts, previd );
// Symmetry
skeleton.makeSymmetric( LHIP, RHIP );
skeleton.makeSymmetric( LKNEE, RKNEE );
skeleton.makeSymmetric( LANKLE, RANKLE );
skeleton.makeSymmetric( LTOE, RTOE );
skeleton.makeSymmetric( LSHOULDER, RSHOULDER );
skeleton.makeSymmetric( LELBOW, RELBOW );
skeleton.makeSymmetric( LWRIST, RWRIST );
skeleton.makeSymmetric( LWRISTAX, RWRISTAX );
skeleton.makeSymmetric( LFINGER, RFINGER );
skeleton.makeSymmetric( LEYE, REYE );
skeleton.initCompressed();
skeleton.setFoot( LTOE );
skeleton.setFoot( RTOE );
skeleton.setFat( WAIST );
skeleton.setFat( ORIGIN );
skeleton.setFat( DES_EYE );
skeleton.setFat( LEYE );
skeleton.setFat( REYE );
}
Pinocchio::Attachment* HumanGeom::SetupAttach( const Pinocchio::Mesh &m, const Pinocchio::Skeleton &skeleton )
{
//skip the fitting step--assume the skeleton is already correct for the mesh
Pinocchio::TreeType *distanceField = constructDistanceField( m );
Pinocchio::VisTester<Pinocchio::TreeType> *tester = new Pinocchio::VisTester<Pinocchio::TreeType>( distanceField );
std::vector<Vector3> embedding;
embedding = skeleton.fGraph().verts;
for ( int i = 0; i < (int) embedding.size(); ++i )
{
embedding[i] = m.toAdd + embedding[i] * m.scale;
}
Pinocchio::Attachment *a = new Pinocchio::Attachment( m, skeleton, embedding, tester );
delete tester;
delete distanceField;
return a;
}
template < typename vertmat >
void HumanGeom::CopyVertsToMesh( const vertmat & vm, Pinocchio::Mesh &m )
{
int nvert = m.vertices.size();
for ( int i = 0; i < nvert; i++ )
{
int oVID = m.vertices[i].origVertID;
// Use reflected point
double refy = 1.0;
if ( oVID >= NUM_MESH_VERT ) // Don't check first half -- no point.
{
oVID = oVID - NUM_MESH_VERT;
if ( m_VertCopySet.count( oVID ) == 0 ) // Vert is a mirror.
{
refy = -1.0;
}
}
m.vertices[i].pos = Vector3( vm[oVID][0], refy * vm[oVID][1], vm[oVID][2] );
}
}
template < typename vertmat >
void HumanGeom::CopyMeshToVerts( const Pinocchio::Mesh &m, vertmat & vm )
{
int nvert = m.vertices.size();
for ( int i = 0; i < nvert; i++ )
{
int oVID = m.vertices[i].origVertID;
// Copy point
for ( int j = 0; j < 3; j++ )
{
vm[oVID][j] = m.vertices[i].pos[j];
}
if ( oVID < NUM_MESH_VERT ) // Don't check second half -- no point.
{
if ( m_VertCopySet.count( oVID ) ) // Vert is used as a copy, copy there too.
{
int idupper = oVID + NUM_MESH_VERT;
for ( int j = 0; j < 3; j++ )
{
vm[idupper][j] = m.vertices[i].pos[j];
}
}
}
}
}
template < typename vertmat >
void HumanGeom::ComputeAvePts( const vertmat &A, const vertmat &B, int n, vertmat &C )
{
for ( int i = 0; i < n; i++ )
{
for ( int j = 0; j < 3; j++ )
{
C[i][j] = ( A[i][j] + B[i][j] ) * 0.5;
}
}
}
void HumanGeom::ComputeHeadTrans( const int &iorigin, const int &ihead, const double &ang, const double &ang2, Matrix4d &T )
{
const vec3d &porigin = m_SkelVerts[ iorigin ];
const vec3d &phead = m_SkelVerts[ ihead ];
vec3d axis = vec3d( 0, 1, 0 );
vec3d vneck = phead - porigin;
vneck.normalize();
T.translatev( porigin );
T.rotate( ang, axis );
T.rotate( ang2, vneck );
T.translatev( -porigin );
}
void HumanGeom::ComputeShoulderTrans( const int &ishoulder, const int &ielbow, const double &ang1, const double &ang2, Matrix4d &T )
{
const vec3d &pshoulder = m_SkelVerts[ ishoulder ];
const vec3d &pelbow = m_SkelVerts[ ielbow ];
vec3d vbicep = pelbow - pshoulder;
vec3d vfwd = vec3d( -1, 0, 0 );
vec3d out = cross( vbicep, vfwd );
out.normalize();
vbicep.normalize();
vfwd = cross( out, vbicep );
vfwd.normalize();
Matrix4d Tstart;
Tstart.setBasis( vfwd, out, vbicep );
vec3d angles = Tstart.getAngles();
T.translatev( pshoulder );
T.rotateX( ang1 ); // - angles.x() + 180 );
T.rotateY( ang2 - angles.y() );
T.translatev( -pshoulder );
}
void HumanGeom::ComputeElbowTrans( const int &ishoulder, const int &ielbow, const int &ihand, const double &ang, const double &ang2, Matrix4d &T )
{
const vec3d &pshoulder = m_SkelVerts[ ishoulder ];
const vec3d &pelbow = m_SkelVerts[ ielbow ];
const vec3d &phand = m_SkelVerts[ ihand ];
vec3d vforearm = phand - pelbow;
vec3d vbicep = pelbow - pshoulder;
double angle0 = angle( vforearm, vbicep );
vec3d axis = cross( vforearm, vbicep );
vbicep.normalize();
T.translatev( pelbow );
T.rotate( ang2, vbicep );
T.rotate( ang - angle0, axis );
T.translatev( -pelbow );
}
void HumanGeom::ComputeForearmTrans( const int &ielbow, const int &iwrist, const int &iwristax, const int &ifinger, const double &ang, const double &ang2, Matrix4d &T )
{
const vec3d &pelbow = m_SkelVerts[ ielbow ];
const vec3d &pwrist = m_SkelVerts[ iwrist ];
const vec3d &pwristax = m_SkelVerts[ iwristax ];
const vec3d &pfinger = m_SkelVerts[ ifinger ];
vec3d vforearm = pwrist - pelbow;
vec3d vwrist = pwristax - pwrist;
vforearm.normalize();
vwrist.normalize();
vec3d vhand = pfinger - pwrist;
T.translatev( pwrist );
T.rotate( ang, vforearm );
T.rotate( ang2, vwrist );
T.translatev( -pwrist );
}
void HumanGeom::ComputeHipTrans( const int &iwaist, const int &ihip, const int &iknee, const double &ang1, const double &ang2, Matrix4d &T )
{
const vec3d &pwaist = m_SkelVerts[ iwaist ];
const vec3d &phip = m_SkelVerts[ ihip ];
const vec3d &pknee = m_SkelVerts[ iknee ];
vec3d vthigh = pknee - phip;
vec3d vfwd = vec3d( -1, 0, 0 );
vec3d out = cross( vthigh, vfwd );
out.normalize();
vthigh.normalize();
vfwd = cross( out, vthigh );
vfwd.normalize();
Matrix4d Tstart;
Tstart.setBasis( vfwd, out, vthigh );
vec3d angles = Tstart.getAngles();
T.translatev( phip );
T.rotateX( ang1 - angles.x() + 180 );
T.rotateY( ang2 - angles.y() );
T.translatev( -phip );
}
void HumanGeom::ComputeKneeTrans( const int &ihip, const int &iknee, const int &iankle, const double &ang, Matrix4d &T )
{
const vec3d &phip = m_SkelVerts[ ihip ];
const vec3d &pknee = m_SkelVerts[ iknee ];
const vec3d &pankle = m_SkelVerts[ iankle ];
// vec3d vthigh = pknee - phip;
// vec3d vshin = pankle - pknee;
// double angle0 = angle( vshin, vthigh );
vec3d axis = vec3d( 0, 1, 0 ); // cross( vshin, vthigh );
T.translatev( pknee );
T.rotate( ang , axis );
T.translatev( -pknee );
}
void HumanGeom::ComputeAnkleTrans( const int &iknee, const int &iankle, const int &itoe, const double &ang, Matrix4d &T )
{
const vec3d &pknee = m_SkelVerts[ iknee ];
const vec3d &pankle = m_SkelVerts[ iankle ];
const vec3d &ptoe = m_SkelVerts[ itoe ];
vec3d vfoot = ptoe - pankle;
vec3d vshin = pankle - pknee;
// double angle0 = angle( vfoot, vshin );
vec3d axis = cross( vfoot, vshin );
T.translatev( pankle );
T.rotate( ang, axis );
T.translatev( -pankle );
}
void HumanGeom::ComputeBackTrans( const int &iorigin, const int &iback, const int &iwaist, const double &ang, Matrix4d &T )
{
const vec3d &porigin = m_SkelVerts[ iorigin ];
const vec3d &pback = m_SkelVerts[ iback ];
const vec3d &pwaist = m_SkelVerts[ iwaist ];
vec3d vupper = pback - porigin;
vec3d vlower = pwaist - pback;
double angle0 = angle( vlower, vupper );
vec3d axis = vec3d( 0, 1, 0 ); // cross( vshin, vthigh );
T.translatev( pback );
T.rotate( -ang, axis );
T.translatev( -pback );
}
void HumanGeom::ComputeWaistTrans( const int &iback, const int &iwaist, const int &ihip, const double &ang, Matrix4d &T )
{
const vec3d &pback = m_SkelVerts[ iback ];
const vec3d &pwaist = m_SkelVerts[ iwaist ];
vec3d phip = m_SkelVerts[ ihip ];
phip.set_y( 0.0 );
vec3d vupper = pwaist - pback;
vec3d vlower = phip - pwaist;
double angle0 = angle( vlower, vupper );
vec3d axis = vec3d( 0, 1, 0 ); // cross( vshin, vthigh );
T.translatev( pwaist );
T.rotate( -ang , axis );
T.translatev( -pwaist );
}
| 0 | 0.938879 | 1 | 0.938879 | game-dev | MEDIA | 0.697407 | game-dev | 0.937249 | 1 | 0.937249 |
Ji-Rath/MassAIExample | 1,560 | Plugins/MassPersistence/Source/MassPersistence/Private/RandomizePositionProcessor.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "RandomizePositionProcessor.h"
#include "MassCommonFragments.h"
#include "MassExecutionContext.h"
#include "MassSignalSubsystem.h"
#include "MassPersistentDataSubsystem.h"
URandomizePositionProcessor::URandomizePositionProcessor()
: EntityQuery(*this)
{
}
void URandomizePositionProcessor::ConfigureQueries(const TSharedRef<FMassEntityManager>& EntityManager)
{
EntityQuery.AddRequirement<FTransformFragment>(EMassFragmentAccess::ReadWrite);
}
void URandomizePositionProcessor::SignalEntities(FMassEntityManager& EntityManager, FMassExecutionContext& Context,
FMassSignalNameLookup& EntitySignals)
{
EntityQuery.ForEachEntityChunk(Context, [this](FMassExecutionContext& Context)
{
const auto TransformFragments = Context.GetMutableFragmentView<FTransformFragment>();
const int32 NumEntities = Context.GetNumEntities();
for (int EntityIdx = 0; EntityIdx < NumEntities; EntityIdx++)
{
auto& TransformFragment = TransformFragments[EntityIdx];
TransformFragment.GetMutableTransform().SetLocation(FVector(FMath::RandRange(-2000, 2000), FMath::RandRange(-2000, 2000), 0.f));
}
});
}
void URandomizePositionProcessor::InitializeInternal(UObject& Owner, const TSharedRef<FMassEntityManager>& EntityManager)
{
UMassSignalSubsystem* SignalSubsystem = UWorld::GetSubsystem<UMassSignalSubsystem>(Owner.GetWorld());
SubscribeToSignal(*SignalSubsystem, PersistentData::Signals::RandomizePositions);
Super::InitializeInternal(Owner, EntityManager);
}
| 0 | 0.826647 | 1 | 0.826647 | game-dev | MEDIA | 0.924436 | game-dev | 0.900991 | 1 | 0.900991 |
ryzom/ryzomcore | 6,533 | ryzom/server/src/gpm_service/patat_grid.h | // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef NL_PATAT_GRID_H
#define NL_PATAT_GRID_H
// Nel Misc
#include "nel/misc/types_nl.h"
#include "nel/misc/stream.h"
// Nel Ligo
#include "nel/ligo/primitive.h"
//
#include "move_grid.h"
// stl
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <string>
// resolution in meters
#define PatatGridResolution 1.0f
#define mmPatatGridResolution 1000
/**
* <Class description>
* \author Benjamin Legros
* \author Nevrax France
* \date 2002
*/
class CPatatGrid
{
public:
/// \name public Typedefs
//@{
/// The grid entry index
typedef uint16 TEntryIndex;
//@}
protected:
/// \name typedefs
//@{
/// The container of prim zone
typedef std::vector<NLLIGO::CPrimZone> TZoneVector;
/// The entry type
class CEntry
{
public:
CEntry() : EntryIndex(0), HashCode(0), NumSamples(0) {}
/// The entry index for this entry
TEntryIndex EntryIndex;
/// The entry hash code
uint32 HashCode;
/// The number of point in grid that point to this entry
uint32 NumSamples;
/// The zones for this
std::vector<uint32> Zones;
/// serial
void serial(NLMISC::IStream &f)
{
sint version = f.serialVersion(0);
f.serial(EntryIndex, HashCode, NumSamples);
f.serialCont(Zones);
}
};
/// The entry table type
typedef std::vector<CEntry> TEntryTable;
/// The entry map type to find entry quickly
typedef std::multimap<uint32, TEntryIndex> TEntryMap;
/// The map of zone name (to zone id)
typedef std::map<std::string, sint32> TZoneMap;
/// The move grid, used as grid
typedef CMoveGrid<TEntryIndex, 1024, mmPatatGridResolution> TGrid;
//@}
/// \name Attributes
//@{
/// Patats
TZoneVector _PrimZones;
/// Patat map
TZoneMap _ZoneMap;
/// The move grid
TGrid _SelectGrid;
/// The entry table
TEntryTable _EntryTable;
/// The flag table
std::vector<bool> _FlagTable;
/// The fast entry map
TEntryMap _EntryMap;
/// The free table entries
std::deque<TEntryIndex> _FreeEntries;
//@}
/// \name Class filtering
//@{
std::set<std::string> _PrimZoneFilters;
//@}
public:
/// Constructor
CPatatGrid();
/// Destructor
~CPatatGrid();
/// Init grid;
void init();
/// Use a prim file
void usePrim(const std::string &primFile, std::vector<uint32> &inFile);
/// Check if patat exists
bool exist(const std::string &name) const { return (_ZoneMap.find(name) != _ZoneMap.end()); }
/// Get entry index
sint32 getEntryIndex(const NLMISC::CVector &v)
{
_SelectGrid.select(v);
TGrid::CIterator it = _SelectGrid.begin();
sint32 index = (it != _SelectGrid.end()) ? (*it) : 0;
_SelectGrid.clearSelection();
return index;
}
/// Set entry index
void setEntryIndex(const NLMISC::CVector &v, sint32 entry)
{
_SelectGrid.select(v);
TGrid::CIterator it = _SelectGrid.begin();
if (it != _SelectGrid.end())
{
(*it) = (TEntryIndex)entry;
}
else
{
TEntryIndex idx = (TEntryIndex)entry;
_SelectGrid.insert(idx, v);
}
_SelectGrid.clearSelection();
}
/// Get zone id from its name
sint32 getZoneId(const std::string &name) const
{
TZoneMap::const_iterator it = _ZoneMap.find(name);
if (it == _ZoneMap.end())
{
nlwarning("Can't find Prim zone %s", name.c_str());
return 0;
}
return (*it).second;
}
/// Get zone name from its id
const std::string &getZoneName(uint32 id) const
{
std::string *ret;
if (_PrimZones[id].getPropertyByName("name", ret))
return *ret;
else
{
static std::string noName;
return noName;
}
}
/// Get zone differences between 2 entry
bool diff(TEntryIndex previous, TEntryIndex next, std::vector<uint32> &in, std::vector<uint32> &out);
/// Serial
void serial(NLMISC::IStream &f)
{
sint version = f.serialVersion(1);
f.serialCont(_PrimZones);
f.serialCont(_ZoneMap);
f.serial(_SelectGrid);
f.serialCont(_EntryTable);
f.serialCont(_FlagTable);
f.serialCont(_EntryMap);
f.serialCont(_FreeEntries);
if (version >= 1)
f.serialCont(_PrimZoneFilters);
}
/// Display
void displayInfo(NLMISC::CLog *log = NLMISC::InfoLog)
{
log->displayNL("Display PatatGrid PrimZones: %d zones", _PrimZones.size());
uint i, j;
for (i=0; i<_PrimZones.size(); ++i)
{
std::string name;
_PrimZones[i].getPropertyByName("name", name);
log->displayNL(" + %d: Name:%s Points:%d", i, name.c_str(), _PrimZones[i].VPoints.size());
}
log->displayNL("Display PatatGrid entries: %d entries", _EntryTable.size());
for (i=0; i<_EntryTable.size(); ++i)
{
log->displayNL(" + %d: EntryIndex:%d HashCode:%d NumSamples:%d", i, _EntryTable[i].EntryIndex, _EntryTable[i].HashCode, _EntryTable[i].NumSamples);
for (j=0; j<_EntryTable[i].Zones.size(); ++j)
log->displayNL(" + Zone %d", _EntryTable[i].Zones[j]);
}
log->displayNL("Display quick EntryMap: %d in map", _EntryMap.size());
TEntryMap::iterator ite;
for (ite=_EntryMap.begin(); ite!=_EntryMap.end(); ++ite)
log->displayNL(" + %d->%d", (*ite).first, (*ite).second);
log->displayNL("Display free Entries: %d free entries", _FreeEntries.size());
for (i=0; i<_FreeEntries.size(); ++i)
log->displayNL(" + %d", _FreeEntries[i]);
log->displayNL("End of PatatGrid info");
}
/// Add CPrimZone class filter
void addPrimZoneFilter(const std::string &filter)
{
_PrimZoneFilters.insert(filter);
}
/// Remove CPrimZone class filter
void removePrimZoneFilter(const std::string &filter)
{
_PrimZoneFilters.erase(filter);
}
/// Reset CPrimZone class filter
void resetPrimZoneFilter()
{
_PrimZoneFilters.clear();
}
protected:
/// read recursive primitive
void readPrimitive(NLLIGO::IPrimitive *primitive, std::vector<uint32> &inFile);
};
#endif // NL_PATAT_GRID_H
/* End of patat_grid.h */
| 0 | 0.934597 | 1 | 0.934597 | game-dev | MEDIA | 0.642868 | game-dev | 0.720849 | 1 | 0.720849 |
Egodystonic/TinyFFR | 1,757 | ThirdParty/filament/third_party/dawn/third_party/dxc/tools/clang/test/SemaCXX/overloaded-operator-decl.cpp | // RUN: %clang_cc1 -fsyntax-only -verify %s
struct X {
X();
X(int);
};
X operator+(X, X);
X operator-(X, X) { X x; return x; }
struct Y {
Y operator-() const;
void operator()(int x = 17) const;
int operator[](int);
static int operator+(Y, Y); // expected-error{{overloaded 'operator+' cannot be a static member function}}
};
void f(X x) {
x = operator+(x, x);
}
X operator+(int, float); // expected-error{{overloaded 'operator+' must have at least one parameter of class or enumeration type}}
X operator*(X, X = 5); // expected-error{{parameter of overloaded 'operator*' cannot have a default argument}}
X operator/(X, X, ...); // expected-error{{overloaded 'operator/' cannot be variadic}}
X operator%(Y); // expected-error{{overloaded 'operator%' must be a binary operator (has 1 parameter)}}
void operator()(Y&, int, int); // expected-error{{overloaded 'operator()' must be a non-static member function}}
typedef int INT;
typedef float FLOAT;
Y& operator++(Y&);
Y operator++(Y&, INT);
X operator++(X&, FLOAT); // expected-error{{parameter of overloaded post-increment operator must have type 'int' (not 'FLOAT' (aka 'float'))}}
int operator+; // expected-error{{'operator+' cannot be the name of a variable or data member}}
namespace PR6238 {
static struct {
void operator()();
} plus;
}
struct PR10839 {
operator int; // expected-error{{'operator int' cannot be the name of a variable or data member}}
int operator+; // expected-error{{'operator+' cannot be the name of a variable or data member}}
};
namespace PR14120 {
struct A {
static void operator()(int& i) { ++i; } // expected-error{{overloaded 'operator()' cannot be a static member function}}
};
void f() {
int i = 0;
A()(i);
}
}
| 0 | 0.744183 | 1 | 0.744183 | game-dev | MEDIA | 0.330087 | game-dev | 0.503342 | 1 | 0.503342 |
jedis/jediacademy | 71,174 | code/game/g_mover.cpp | // leave this line at the top for all g_xxxx.cpp files...
#include "g_headers.h"
#include "g_functions.h"
#include "objectives.h"
#include "../Icarus/IcarusInterface.h"
int BMS_START = 0;
int BMS_MID = 1;
int BMS_END = 2;
extern void G_SetEnemy( gentity_t *self, gentity_t *enemy );
void CalcTeamDoorCenter ( gentity_t *ent, vec3_t center );
void InitMover( gentity_t *ent ) ;
/*
===============================================================================
PUSHMOVE
===============================================================================
*/
void MatchTeam( gentity_t *teamLeader, int moverState, int time );
extern qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2);
typedef struct {
gentity_t *ent;
vec3_t origin;
vec3_t angles;
float deltayaw;
} pushed_t;
pushed_t pushed[MAX_GENTITIES], *pushed_p;
/*
-------------------------
G_SetLoopSound
-------------------------
*/
void G_PlayDoorLoopSound( gentity_t *ent )
{
if ( VALIDSTRING( ent->soundSet ) == false )
return;
sfxHandle_t sfx = CAS_GetBModelSound( ent->soundSet, BMS_MID );
if ( sfx == -1 )
{
ent->s.loopSound = 0;
return;
}
ent->s.loopSound = sfx;
}
/*
-------------------------
G_PlayDoorSound
-------------------------
*/
void G_PlayDoorSound( gentity_t *ent, int type )
{
if ( VALIDSTRING( ent->soundSet ) == false )
return;
sfxHandle_t sfx = CAS_GetBModelSound( ent->soundSet, type );
if ( sfx == -1 )
return;
vec3_t doorcenter;
CalcTeamDoorCenter( ent, doorcenter );
if ( ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER )
{
AddSoundEvent( ent->activator, doorcenter, 128, AEL_MINOR, qfalse, qtrue );
}
G_AddEvent( ent, EV_BMODEL_SOUND, sfx );
}
/*
============
G_TestEntityPosition
============
*/
gentity_t *G_TestEntityPosition( gentity_t *ent ) {
trace_t tr;
int mask;
if ( (ent->client && ent->health <= 0) || !ent->clipmask )
{//corpse or something with no clipmask
mask = MASK_SOLID;
}
else
{
mask = ent->clipmask;
}
if ( ent->client )
{
gi.trace( &tr, ent->client->ps.origin, ent->mins, ent->maxs, ent->client->ps.origin, ent->s.number, mask );
}
else
{
if ( ent->s.eFlags & EF_MISSILE_STICK )//Arggh, this is dumb...but when it used the bbox, it was pretty much always in solid when it is riding something..which is wrong..so I changed it to basically be a point contents check
{
gi.trace( &tr, ent->s.pos.trBase, vec3_origin, vec3_origin, ent->s.pos.trBase, ent->s.number, mask );
}
else
{
gi.trace( &tr, ent->s.pos.trBase, ent->mins, ent->maxs, ent->s.pos.trBase, ent->s.number, mask );
}
}
if (tr.startsolid)
return &g_entities[ tr.entityNum ];
return NULL;
}
/*
==================
G_TryPushingEntity
Returns qfalse if the move is blocked
==================
*/
extern qboolean G_OkayToRemoveCorpse( gentity_t *self );
qboolean G_TryPushingEntity( gentity_t *check, gentity_t *pusher, vec3_t move, vec3_t amove ) {
vec3_t forward, right, up;
vec3_t org, org2, move2;
gentity_t *block;
/*
// EF_MOVER_STOP will just stop when contacting another entity
// instead of pushing it, but entities can still ride on top of it
if ( ( pusher->s.eFlags & EF_MOVER_STOP ) &&
check->s.groundEntityNum != pusher->s.number ) {
return qfalse;
}
*/
// save off the old position
if (pushed_p > &pushed[MAX_GENTITIES]) {
G_Error( "pushed_p > &pushed[MAX_GENTITIES]" );
}
pushed_p->ent = check;
VectorCopy (check->s.pos.trBase, pushed_p->origin);
VectorCopy (check->s.apos.trBase, pushed_p->angles);
if ( check->client ) {
pushed_p->deltayaw = check->client->ps.delta_angles[YAW];
VectorCopy (check->client->ps.origin, pushed_p->origin);
}
pushed_p++;
// we need this for pushing things later
VectorSubtract (vec3_origin, amove, org);
AngleVectors (org, forward, right, up);
// try moving the contacted entity
VectorAdd (check->s.pos.trBase, move, check->s.pos.trBase);
if (check->client) {
// make sure the client's view rotates when on a rotating mover
check->client->ps.delta_angles[YAW] += ANGLE2SHORT(amove[YAW]);
}
// figure movement due to the pusher's amove
VectorSubtract (check->s.pos.trBase, pusher->currentOrigin, org);
org2[0] = DotProduct (org, forward);
org2[1] = -DotProduct (org, right);
org2[2] = DotProduct (org, up);
VectorSubtract (org2, org, move2);
VectorAdd (check->s.pos.trBase, move2, check->s.pos.trBase);
if ( check->client ) {
VectorAdd (check->client->ps.origin, move, check->client->ps.origin);
VectorAdd (check->client->ps.origin, move2, check->client->ps.origin);
}
// may have pushed them off an edge
if ( check->s.groundEntityNum != pusher->s.number ) {
check->s.groundEntityNum = ENTITYNUM_NONE;
}
/*
if ( check->client && check->health <= 0 && check->contents == CONTENTS_CORPSE )
{//sigh... allow pushing corpses into walls... problem is, they'll be stuck in there... maybe just remove them?
return qtrue;
}
*/
block = G_TestEntityPosition( check );
if (!block) {
// pushed ok
if ( check->client ) {
VectorCopy( check->client->ps.origin, check->currentOrigin );
} else {
VectorCopy( check->s.pos.trBase, check->currentOrigin );
}
gi.linkentity (check);
return qtrue;
}
// if it is ok to leave in the old position, do it
// this is only relevent for riding entities, not pushed
// Sliding trapdoors can cause this.
VectorCopy( (pushed_p-1)->origin, check->s.pos.trBase);
if ( check->client ) {
VectorCopy( (pushed_p-1)->origin, check->client->ps.origin);
}
VectorCopy( (pushed_p-1)->angles, check->s.apos.trBase );
block = G_TestEntityPosition (check);
if ( !block ) {
check->s.groundEntityNum = ENTITYNUM_NONE;
pushed_p--;
return qtrue;
}
// blocked
if ( pusher->damage )
{//Do damage
if ( (pusher->spawnflags&MOVER_CRUSHER)//a crusher
&& check->s.clientNum >= MAX_CLIENTS//not the player
&& check->client //NPC
&& check->health <= 0 //dead
&& G_OkayToRemoveCorpse( check ) )//okay to remove him
{//crusher stuck on a non->player corpse that does not have a key and is not running a script
G_FreeEntity( check );
}
else
{
G_Damage(check, pusher, pusher->activator, move, check->currentOrigin, pusher->damage, 0, MOD_CRUSH );
}
}
return qfalse;
}
/*
============
G_MoverPush
Objects need to be moved back on a failed push,
otherwise riders would continue to slide.
If qfalse is returned, *obstacle will be the blocking entity
============
*/
qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t **obstacle ) {
qboolean notMoving;
int i, e;
int listedEntities;
vec3_t mins, maxs;
vec3_t pusherMins, pusherMaxs, totalMins, totalMaxs;
pushed_t *p;
gentity_t *entityList[MAX_GENTITIES];
gentity_t *check;
*obstacle = NULL;
if ( !pusher->bmodel )
{//misc_model_breakable
VectorAdd( pusher->currentOrigin, pusher->mins, pusherMins );
VectorAdd( pusher->currentOrigin, pusher->maxs, pusherMaxs );
}
// mins/maxs are the bounds at the destination
// totalMins / totalMaxs are the bounds for the entire move
if ( pusher->currentAngles[0] || pusher->currentAngles[1] || pusher->currentAngles[2]
|| amove[0] || amove[1] || amove[2] )
{
float radius;
radius = RadiusFromBounds( pusher->mins, pusher->maxs );
for ( i = 0 ; i < 3 ; i++ )
{
mins[i] = pusher->currentOrigin[i] + move[i] - radius;
maxs[i] = pusher->currentOrigin[i] + move[i] + radius;
totalMins[i] = mins[i] - move[i];
totalMaxs[i] = maxs[i] - move[i];
}
}
else
{
for (i=0 ; i<3 ; i++)
{
mins[i] = pusher->absmin[i] + move[i];
maxs[i] = pusher->absmax[i] + move[i];
}
VectorCopy( pusher->absmin, totalMins );
VectorCopy( pusher->absmax, totalMaxs );
for (i=0 ; i<3 ; i++)
{
if ( move[i] > 0 )
{
totalMaxs[i] += move[i];
}
else
{
totalMins[i] += move[i];
}
}
}
// unlink the pusher so we don't get it in the entityList
gi.unlinkentity( pusher );
listedEntities = gi.EntitiesInBox( totalMins, totalMaxs, entityList, MAX_GENTITIES );
// move the pusher to it's final position
VectorAdd( pusher->currentOrigin, move, pusher->currentOrigin );
VectorAdd( pusher->currentAngles, amove, pusher->currentAngles );
gi.linkentity( pusher );
notMoving = (VectorCompare( vec3_origin, move )&&VectorCompare( vec3_origin, amove ));
// see if any solid entities are inside the final position
for ( e = 0 ; e < listedEntities ; e++ ) {
check = entityList[ e ];
if (( check->s.eFlags & EF_MISSILE_STICK ) && (notMoving || check->s.groundEntityNum < 0 || check->s.groundEntityNum >= ENTITYNUM_NONE ))
{
// special case hack for sticky things, destroy it if we aren't attached to the thing that is moving, but the moving thing is pushing us
G_Damage( check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH );
continue;
}
// only push items and players
if ( check->s.eType != ET_ITEM )
{
//FIXME: however it allows items to be pushed through stuff, do same for corpses?
if ( check->s.eType != ET_PLAYER )
{
if ( !( check->s.eFlags & EF_MISSILE_STICK ))
{
// cannot be pushed by this mover
continue;
}
}
/*
else if ( check->health <= 0 )
{//For now, don't push on dead players
continue;
}
*/
else if ( !pusher->bmodel )
{
vec3_t checkMins, checkMaxs;
VectorAdd( check->currentOrigin, check->mins, checkMins );
VectorAdd( check->currentOrigin, check->maxs, checkMaxs );
if ( G_BoundsOverlap( checkMins, checkMaxs, pusherMins, pusherMaxs ) )
{//They're inside me already, no push - FIXME: we're testing a moves spot, aren't we, so we could have just moved inside them?
continue;
}
}
}
if ( check->maxs[0] - check->mins[0] <= 0 &&
check->maxs[1] - check->mins[1] <= 0 &&
check->maxs[2] - check->mins[2] <= 0 )
{//no size, don't push
continue;
}
// if the entity is standing on the pusher, it will definitely be moved
if ( check->s.groundEntityNum != pusher->s.number ) {
// see if the ent needs to be tested
if ( check->absmin[0] >= maxs[0]
|| check->absmin[1] >= maxs[1]
|| check->absmin[2] >= maxs[2]
|| check->absmax[0] <= mins[0]
|| check->absmax[1] <= mins[1]
|| check->absmax[2] <= mins[2] ) {
continue;
}
// see if the ent's bbox is inside the pusher's final position
// this does allow a fast moving object to pass through a thin entity...
if ( G_TestEntityPosition( check ) != pusher )
{
continue;
}
}
if ( ((pusher->spawnflags&2)&&!Q_stricmp("func_breakable",pusher->classname))
||((pusher->spawnflags&16)&&!Q_stricmp("func_static",pusher->classname)) )
{//ugh, avoid stricmp with a unique flag
//Damage on impact
if ( pusher->damage )
{//Do damage
G_Damage( check, pusher, pusher->activator, move, check->currentOrigin, pusher->damage, 0, MOD_CRUSH );
if ( pusher->health >= 0 && pusher->takedamage && !(pusher->spawnflags&1) )
{//do some damage to me, too
G_Damage( pusher, check, pusher->activator, move, pusher->s.pos.trBase, floor(pusher->damage/4.0f), 0, MOD_CRUSH );
}
}
}
// really need a flag like MOVER_TOUCH that calls the ent's touch function here, instead of this stricmp crap
else if ( (pusher->spawnflags&2) && !Q_stricmp( "func_rotating", pusher->classname ) )
{
GEntity_TouchFunc( pusher, check, NULL );
continue; // don't want it blocking so skip past it
}
vec3_t oldOrg;
VectorCopy( check->s.pos.trBase, oldOrg );
// the entity needs to be pushed
if ( G_TryPushingEntity( check, pusher, move, amove ) )
{
// the mover wasn't blocked
if ( check->s.eFlags & EF_MISSILE_STICK )
{
if ( !VectorCompare( oldOrg, check->s.pos.trBase ))
{
// and the rider was actually pushed, so interpolate position change to smooth out the ride
check->s.pos.trType = TR_INTERPOLATE;
continue;
}
//else..the mover wasn't blocked & we are riding the mover & but the rider did not move even though the mover itself did...so
// drop through and let it blow up the rider up
}
else
{
continue;
}
}
// the move was blocked even after pushing this rider
if ( check->s.eFlags & EF_MISSILE_STICK )
{
// so nuke 'em so they don't block us anymore
G_Damage( check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH );
continue;
}
// save off the obstacle so we can call the block function (crush, etc)
*obstacle = check;
// move back any entities we already moved
// go backwards, so if the same entity was pushed
// twice, it goes back to the original position
for ( p=pushed_p-1 ; p>=pushed ; p-- ) {
VectorCopy (p->origin, p->ent->s.pos.trBase);
VectorCopy (p->angles, p->ent->s.apos.trBase);
if ( p->ent->client ) {
p->ent->client->ps.delta_angles[YAW] = p->deltayaw;
VectorCopy (p->origin, p->ent->client->ps.origin);
}
gi.linkentity (p->ent);
}
return qfalse;
}
return qtrue;
}
/*
=================
G_MoverTeam
=================
*/
void G_MoverTeam( gentity_t *ent ) {
vec3_t move, amove;
gentity_t *part, *obstacle;
vec3_t origin, angles;
obstacle = NULL;
// make sure all team slaves can move before commiting
// any moves or calling any think functions
// if the move is blocked, all moved objects will be backed out
pushed_p = pushed;
for (part = ent ; part ; part=part->teamchain)
{
// get current position
part->s.eFlags &= ~EF_BLOCKED_MOVER;
EvaluateTrajectory( &part->s.pos, level.time, origin );
EvaluateTrajectory( &part->s.apos, level.time, angles );
VectorSubtract( origin, part->currentOrigin, move );
VectorSubtract( angles, part->currentAngles, amove );
if ( !G_MoverPush( part, move, amove, &obstacle ) )
{
break; // move was blocked
}
}
if (part)
{
// if the pusher has a "blocked" function, call it
// go back to the previous position
for ( part = ent ; part ; part = part->teamchain )
{
//Push up time so it doesn't wiggle when blocked
part->s.pos.trTime += level.time - level.previousTime;
part->s.apos.trTime += level.time - level.previousTime;
EvaluateTrajectory( &part->s.pos, level.time, part->currentOrigin );
EvaluateTrajectory( &part->s.apos, level.time, part->currentAngles );
gi.linkentity( part );
part->s.eFlags |= EF_BLOCKED_MOVER;
}
if ( ent->e_BlockedFunc != blockedF_NULL )
{// this check no longer necessary, done internally below, but it's here for reference
GEntity_BlockedFunc( ent, obstacle );
}
return;
}
// the move succeeded
for ( part = ent ; part ; part = part->teamchain )
{
// call the reached function if time is at or past end point
if ( part->s.pos.trType == TR_LINEAR_STOP ||
part->s.pos.trType == TR_NONLINEAR_STOP )
{
if ( level.time >= part->s.pos.trTime + part->s.pos.trDuration )
{
GEntity_ReachedFunc( part );
}
}
}
}
/*
================
G_RunMover
================
*/
//void rebolt_turret( gentity_t *base );
void G_RunMover( gentity_t *ent ) {
// if not a team captain, don't do anything, because
// the captain will handle everything
if ( ent->flags & FL_TEAMSLAVE ) {
return;
}
// if stationary at one of the positions, don't move anything
if ( ent->s.pos.trType != TR_STATIONARY || ent->s.apos.trType != TR_STATIONARY ) {
G_MoverTeam( ent );
}
/* if ( ent->classname && Q_stricmp("misc_turret", ent->classname ) == 0 )
{
rebolt_turret( ent );
}
*/
// check think function
G_RunThink( ent );
}
/*
============================================================================
GENERAL MOVERS
Doors, plats, and buttons are all binary (two position) movers
Pos1 is "at rest", pos2 is "activated"
============================================================================
*/
/*
CalcTeamDoorCenter
Finds all the doors of a team and returns their center position
*/
void CalcTeamDoorCenter ( gentity_t *ent, vec3_t center )
{
vec3_t slavecenter;
gentity_t *slave;
//Start with our center
VectorAdd(ent->mins, ent->maxs, center);
VectorScale(center, 0.5, center);
for ( slave = ent->teamchain ; slave ; slave = slave->teamchain )
{
//Find slave's center
VectorAdd(slave->mins, slave->maxs, slavecenter);
VectorScale(slavecenter, 0.5, slavecenter);
//Add that to our own, find middle
VectorAdd(center, slavecenter, center);
VectorScale(center, 0.5, center);
}
}
/*
===============
SetMoverState
===============
*/
void SetMoverState( gentity_t *ent, moverState_t moverState, int time ) {
vec3_t delta;
float f;
ent->moverState = moverState;
ent->s.pos.trTime = time;
if ( ent->s.pos.trDuration <= 0 )
{//Don't allow divide by zero!
ent->s.pos.trDuration = 1;
}
switch( moverState ) {
case MOVER_POS1:
VectorCopy( ent->pos1, ent->s.pos.trBase );
ent->s.pos.trType = TR_STATIONARY;
break;
case MOVER_POS2:
VectorCopy( ent->pos2, ent->s.pos.trBase );
ent->s.pos.trType = TR_STATIONARY;
break;
case MOVER_1TO2:
VectorCopy( ent->pos1, ent->s.pos.trBase );
VectorSubtract( ent->pos2, ent->pos1, delta );
f = 1000.0 / ent->s.pos.trDuration;
VectorScale( delta, f, ent->s.pos.trDelta );
if ( ent->alt_fire )
{
ent->s.pos.trType = TR_LINEAR_STOP;
}
else
{
ent->s.pos.trType = TR_NONLINEAR_STOP;
}
ent->s.eFlags &= ~EF_BLOCKED_MOVER;
break;
case MOVER_2TO1:
VectorCopy( ent->pos2, ent->s.pos.trBase );
VectorSubtract( ent->pos1, ent->pos2, delta );
f = 1000.0 / ent->s.pos.trDuration;
VectorScale( delta, f, ent->s.pos.trDelta );
if ( ent->alt_fire )
{
ent->s.pos.trType = TR_LINEAR_STOP;
}
else
{
ent->s.pos.trType = TR_NONLINEAR_STOP;
}
ent->s.eFlags &= ~EF_BLOCKED_MOVER;
break;
}
EvaluateTrajectory( &ent->s.pos, level.time, ent->currentOrigin );
gi.linkentity( ent );
}
/*
================
MatchTeam
All entities in a mover team will move from pos1 to pos2
in the same amount of time
================
*/
void MatchTeam( gentity_t *teamLeader, int moverState, int time ) {
gentity_t *slave;
for ( slave = teamLeader ; slave ; slave = slave->teamchain ) {
SetMoverState( slave, (moverState_t) moverState, time );
}
}
/*
================
ReturnToPos1
================
*/
void ReturnToPos1( gentity_t *ent ) {
ent->e_ThinkFunc = thinkF_NULL;
ent->nextthink = 0;
ent->s.time = level.time;
MatchTeam( ent, MOVER_2TO1, level.time );
// starting sound
G_PlayDoorLoopSound( ent );
G_PlayDoorSound( ent, BMS_START ); //??
}
/*
================
Reached_BinaryMover
================
*/
void Reached_BinaryMover( gentity_t *ent )
{
// stop the looping sound
ent->s.loopSound = 0;
if ( ent->moverState == MOVER_1TO2 )
{//reached open
// reached pos2
SetMoverState( ent, MOVER_POS2, level.time );
vec3_t doorcenter;
CalcTeamDoorCenter( ent, doorcenter );
if ( ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER )
{
AddSightEvent( ent->activator, doorcenter, 256, AEL_MINOR, 1 );
}
// play sound
G_PlayDoorSound( ent, BMS_END );
if ( ent->wait < 0 )
{//Done for good
ent->e_ThinkFunc = thinkF_NULL;
ent->nextthink = -1;
ent->e_UseFunc = useF_NULL;
}
else
{
// return to pos1 after a delay
ent->e_ThinkFunc = thinkF_ReturnToPos1;
if(ent->spawnflags & 8)
{//Toggle, keep think, wait for next use?
ent->nextthink = -1;
}
else
{
ent->nextthink = level.time + ent->wait;
}
}
// fire targets
if ( !ent->activator )
{
ent->activator = ent;
}
G_UseTargets2( ent, ent->activator, ent->opentarget );
}
else if ( ent->moverState == MOVER_2TO1 )
{//closed
// reached pos1
SetMoverState( ent, MOVER_POS1, level.time );
vec3_t doorcenter;
CalcTeamDoorCenter( ent, doorcenter );
if ( ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER )
{
AddSightEvent( ent->activator, doorcenter, 256, AEL_MINOR, 1 );
}
// play sound
G_PlayDoorSound( ent, BMS_END );
// close areaportals
if ( ent->teammaster == ent || !ent->teammaster )
{
gi.AdjustAreaPortalState( ent, qfalse );
}
G_UseTargets2( ent, ent->activator, ent->closetarget );
}
else
{
G_Error( "Reached_BinaryMover: bad moverState" );
}
}
/*
================
Use_BinaryMover_Go
================
*/
void Use_BinaryMover_Go( gentity_t *ent )
{
int total;
int partial;
// gentity_t *other = ent->enemy;
gentity_t *activator = ent->activator;
ent->activator = activator;
if ( ent->moverState == MOVER_POS1 )
{
// start moving 50 msec later, becase if this was player
// triggered, level.time hasn't been advanced yet
MatchTeam( ent, MOVER_1TO2, level.time + 50 );
vec3_t doorcenter;
CalcTeamDoorCenter( ent, doorcenter );
if ( ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER )
{
AddSightEvent( ent->activator, doorcenter, 256, AEL_MINOR, 1 );
}
// starting sound
G_PlayDoorLoopSound( ent );
G_PlayDoorSound( ent, BMS_START );
ent->s.time = level.time;
// open areaportal
if ( ent->teammaster == ent || !ent->teammaster ) {
gi.AdjustAreaPortalState( ent, qtrue );
}
G_UseTargets( ent, ent->activator );
return;
}
// if all the way up, just delay before coming down
if ( ent->moverState == MOVER_POS2 ) {
//have to do this because the delay sets our think to Use_BinaryMover_Go
ent->e_ThinkFunc = thinkF_ReturnToPos1;
if ( ent->spawnflags & 8 )
{//TOGGLE doors don't use wait!
ent->nextthink = level.time + FRAMETIME;
}
else
{
ent->nextthink = level.time + ent->wait;
}
G_UseTargets2( ent, ent->activator, ent->target2 );
return;
}
// only partway down before reversing
if ( ent->moverState == MOVER_2TO1 )
{
total = ent->s.pos.trDuration-50;
if ( ent->s.pos.trType == TR_NONLINEAR_STOP )
{
vec3_t curDelta;
VectorSubtract( ent->currentOrigin, ent->pos1, curDelta );
float fPartial = VectorLength( curDelta )/VectorLength( ent->s.pos.trDelta );
VectorScale( ent->s.pos.trDelta, fPartial, curDelta );
fPartial /= ent->s.pos.trDuration;
fPartial /= 0.001f;
fPartial = acos( fPartial );
fPartial = RAD2DEG( fPartial );
fPartial = (90.0f - fPartial)/90.0f*ent->s.pos.trDuration;
partial = total - floor( fPartial );
}
else
{
partial = level.time - ent->s.pos.trTime;//ent->s.time;
}
if ( partial > total ) {
partial = total;
}
ent->s.pos.trTime = level.time - ( total - partial );//ent->s.time;
MatchTeam( ent, MOVER_1TO2, ent->s.pos.trTime );
G_PlayDoorSound( ent, BMS_START );
return;
}
// only partway up before reversing
if ( ent->moverState == MOVER_1TO2 )
{
total = ent->s.pos.trDuration-50;
if ( ent->s.pos.trType == TR_NONLINEAR_STOP )
{
vec3_t curDelta;
VectorSubtract( ent->currentOrigin, ent->pos2, curDelta );
float fPartial = VectorLength( curDelta )/VectorLength( ent->s.pos.trDelta );
VectorScale( ent->s.pos.trDelta, fPartial, curDelta );
fPartial /= ent->s.pos.trDuration;
fPartial /= 0.001f;
fPartial = acos( fPartial );
fPartial = RAD2DEG( fPartial );
fPartial = (90.0f - fPartial)/90.0f*ent->s.pos.trDuration;
partial = total - floor( fPartial );
}
else
{
partial = level.time - ent->s.pos.trTime;//ent->s.time;
}
if ( partial > total ) {
partial = total;
}
ent->s.pos.trTime = level.time - ( total - partial );//ent->s.time;
MatchTeam( ent, MOVER_2TO1, ent->s.pos.trTime );
G_PlayDoorSound( ent, BMS_START );
return;
}
}
void UnLockDoors(gentity_t *const ent)
{
//noise?
//go through and unlock the door and all the slaves
gentity_t *slave = ent;
do
{ // want to allow locked toggle doors, so keep the targetname
if( !(slave->spawnflags & MOVER_TOGGLE) )
{
slave->targetname = NULL;//not usable ever again
}
slave->spawnflags &= ~MOVER_LOCKED;
slave->s.frame = 1;//second stage of anim
slave = slave->teamchain;
} while ( slave );
}
void LockDoors(gentity_t *const ent)
{
//noise?
//go through and lock the door and all the slaves
gentity_t *slave = ent;
do
{
slave->spawnflags |= MOVER_LOCKED;
slave->s.frame = 0;//first stage of anim
slave = slave->teamchain;
} while ( slave );
}
/*
================
Use_BinaryMover
================
*/
void Use_BinaryMover( gentity_t *ent, gentity_t *other, gentity_t *activator )
{
int key;
char *text;
if ( ent->e_UseFunc == useF_NULL )
{//I cannot be used anymore, must be a door with a wait of -1 that's opened.
return;
}
// only the master should be used
if ( ent->flags & FL_TEAMSLAVE )
{
Use_BinaryMover( ent->teammaster, other, activator );
return;
}
if ( ent->svFlags & SVF_INACTIVE )
{
return;
}
if ( ent->spawnflags & MOVER_LOCKED )
{//a locked door, unlock it
UnLockDoors(ent);
return;
}
if ( ent->spawnflags & MOVER_GOODIE )
{
if ( ent->fly_sound_debounce_time > level.time )
{
return;
}
else
{
key = INV_GoodieKeyCheck( activator );
if (key)
{//activator has a goodie key, remove it
activator->client->ps.inventory[key]--;
G_Sound( activator, G_SoundIndex( "sound/movers/goodie_pass.wav" ) );
// once the goodie mover has been used, it no longer requires a goodie key
ent->spawnflags &= ~MOVER_GOODIE;
}
else
{ //don't have a goodie key
G_Sound( activator, G_SoundIndex( "sound/movers/goodie_fail.wav" ) );
ent->fly_sound_debounce_time = level.time + 5000;
text = "cp @SP_INGAME_NEED_KEY_TO_OPEN";
//FIXME: temp message, only on certain difficulties?, graphic instead of text?
gi.SendServerCommand( NULL, text );
return;
}
}
}
G_ActivateBehavior(ent,BSET_USE);
G_SetEnemy( ent, other );
ent->activator = activator;
if(ent->delay)
{
ent->e_ThinkFunc = thinkF_Use_BinaryMover_Go;
ent->nextthink = level.time + ent->delay;
}
else
{
Use_BinaryMover_Go(ent);
}
}
/*
================
InitMover
"pos1", "pos2", and "speed" should be set before calling,
so the movement delta can be calculated
================
*/
void InitMoverTrData( gentity_t *ent )
{
vec3_t move;
float distance;
ent->s.pos.trType = TR_STATIONARY;
VectorCopy( ent->pos1, ent->s.pos.trBase );
// calculate time to reach second position from speed
VectorSubtract( ent->pos2, ent->pos1, move );
distance = VectorLength( move );
if ( ! ent->speed )
{
ent->speed = 100;
}
VectorScale( move, ent->speed, ent->s.pos.trDelta );
ent->s.pos.trDuration = distance * 1000 / ent->speed;
if ( ent->s.pos.trDuration <= 0 )
{
ent->s.pos.trDuration = 1;
}
}
void InitMover( gentity_t *ent )
{
float light;
vec3_t color;
qboolean lightSet, colorSet;
// if the "model2" key is set, use a seperate model
// for drawing, but clip against the brushes
if ( ent->model2 )
{
if ( strstr( ent->model2, ".glm" ))
{
ent->s.modelindex2 = G_ModelIndex( ent->model2 );
ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, ent->model2, ent->s.modelindex2 );
if ( ent->playerModel >= 0 )
{
ent->rootBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "model_root", qtrue );
}
ent->s.radius = 120;
}
else
{
ent->s.modelindex2 = G_ModelIndex( ent->model2 );
}
}
// if the "color" or "light" keys are set, setup constantLight
lightSet = G_SpawnFloat( "light", "100", &light );
colorSet = G_SpawnVector( "color", "1 1 1", color );
if ( lightSet || colorSet ) {
int r, g, b, i;
r = color[0] * 255;
if ( r > 255 ) {
r = 255;
}
g = color[1] * 255;
if ( g > 255 ) {
g = 255;
}
b = color[2] * 255;
if ( b > 255 ) {
b = 255;
}
i = light / 4;
if ( i > 255 ) {
i = 255;
}
ent->s.constantLight = r | ( g << 8 ) | ( b << 16 ) | ( i << 24 );
}
ent->e_UseFunc = useF_Use_BinaryMover;
ent->e_ReachedFunc = reachedF_Reached_BinaryMover;
ent->moverState = MOVER_POS1;
ent->svFlags = SVF_USE_CURRENT_ORIGIN;
if ( ent->spawnflags & MOVER_INACTIVE )
{// Make it inactive
ent->svFlags |= SVF_INACTIVE;
}
if(ent->spawnflags & MOVER_PLAYER_USE)
{//Can be used by the player's BUTTON_USE
ent->svFlags |= SVF_PLAYER_USABLE;
}
ent->s.eType = ET_MOVER;
VectorCopy( ent->pos1, ent->currentOrigin );
gi.linkentity( ent );
InitMoverTrData( ent );
}
/*
===============================================================================
DOOR
A use can be triggered either by a touch function, by being shot, or by being
targeted by another entity.
===============================================================================
*/
/*
================
Blocked_Door
================
*/
void Blocked_Door( gentity_t *ent, gentity_t *other ) {
// remove anything other than a client -- no longer the case
// don't remove security keys or goodie keys
if ( (other->s.eType == ET_ITEM) && (other->item->giTag >= INV_GOODIE_KEY && other->item->giTag <= INV_SECURITY_KEY) )
{
// should we be doing anything special if a key blocks it... move it somehow..?
}
// if your not a client, or your a dead client remove yourself...
else if ( other->s.number && (!other->client || (other->client && other->health <= 0 && other->contents == CONTENTS_CORPSE && !other->message)) )
{
if ( !IIcarusInterface::GetIcarus()->IsRunning( other->m_iIcarusID ) /*!other->taskManager || !other->taskManager->IsRunning()*/ )
{
// if an item or weapon can we do a little explosion..?
G_FreeEntity( other );
return;
}
}
if ( ent->damage )
{
if ( (ent->spawnflags&MOVER_CRUSHER)//a crusher
&& other->s.clientNum >= MAX_CLIENTS//not the player
&& other->client //NPC
&& other->health <= 0 //dead
&& G_OkayToRemoveCorpse( other ) )//okay to remove him
{//crusher stuck on a non->player corpse that does not have a key and is not running a script
G_FreeEntity( other );
}
else
{
G_Damage( other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH );
}
}
if ( ent->spawnflags & MOVER_CRUSHER ) {
return; // crushers don't reverse
}
// reverse direction
Use_BinaryMover( ent, ent, other );
}
/*
================
Touch_DoorTrigger
================
*/
void Touch_DoorTrigger( gentity_t *ent, gentity_t *other, trace_t *trace )
{
if ( ent->svFlags & SVF_INACTIVE )
{
return;
}
if ( ent->owner->spawnflags & MOVER_LOCKED )
{//don't even try to use the door if it's locked
return;
}
if ( ent->owner->moverState != MOVER_1TO2 )
{//Door is not already opening
//if ( ent->owner->moverState == MOVER_POS1 || ent->owner->moverState == MOVER_2TO1 )
//{//only check these if closed or closing
//If door is closed, opening or open, check this
Use_BinaryMover( ent->owner, ent, other );
}
/*
//Old style
if ( ent->owner->moverState != MOVER_1TO2 ) {
Use_BinaryMover( ent->owner, ent, other );
}
*/
}
/*
======================
Think_SpawnNewDoorTrigger
All of the parts of a door have been spawned, so create
a trigger that encloses all of them
======================
*/
void Think_SpawnNewDoorTrigger( gentity_t *ent )
{
gentity_t *other;
vec3_t mins, maxs;
int i, best;
// set all of the slaves as shootable
if ( ent->takedamage )
{
for ( other = ent ; other ; other = other->teamchain )
{
other->takedamage = qtrue;
}
}
// find the bounds of everything on the team
VectorCopy (ent->absmin, mins);
VectorCopy (ent->absmax, maxs);
for (other = ent->teamchain ; other ; other=other->teamchain) {
AddPointToBounds (other->absmin, mins, maxs);
AddPointToBounds (other->absmax, mins, maxs);
}
// find the thinnest axis, which will be the one we expand
best = 0;
for ( i = 1 ; i < 3 ; i++ ) {
if ( maxs[i] - mins[i] < maxs[best] - mins[best] ) {
best = i;
}
}
maxs[best] += 120;
mins[best] -= 120;
// create a trigger with this size
other = G_Spawn ();
VectorCopy (mins, other->mins);
VectorCopy (maxs, other->maxs);
other->owner = ent;
other->contents = CONTENTS_TRIGGER;
other->e_TouchFunc = touchF_Touch_DoorTrigger;
gi.linkentity (other);
other->classname = "trigger_door";
MatchTeam( ent, ent->moverState, level.time );
}
void Think_MatchTeam( gentity_t *ent )
{
MatchTeam( ent, ent->moverState, level.time );
}
qboolean G_EntIsDoor( int entityNum )
{
if ( entityNum < 0 || entityNum >= ENTITYNUM_WORLD )
{
return qfalse;
}
gentity_t *ent = &g_entities[entityNum];
if ( ent && !Q_stricmp( "func_door", ent->classname ) )
{//blocked by a door
return qtrue;
}
return qfalse;
}
gentity_t *G_FindDoorTrigger( gentity_t *ent )
{
gentity_t *owner = NULL;
gentity_t *door = ent;
if ( door->flags & FL_TEAMSLAVE )
{//not the master door, get the master door
while ( door->teammaster && (door->flags&FL_TEAMSLAVE))
{
door = door->teammaster;
}
}
if ( door->targetname )
{//find out what is targeting it
//FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay?
while ( (owner = G_Find( owner, FOFS( target ), door->targetname )) != NULL )
{
if ( owner && (owner->contents&CONTENTS_TRIGGER) )
{
return owner;
}
}
owner = NULL;
while ( (owner = G_Find( owner, FOFS( target2 ), door->targetname )) != NULL )
{
if ( owner && (owner->contents&CONTENTS_TRIGGER) )
{
return owner;
}
}
}
owner = NULL;
while ( (owner = G_Find( owner, FOFS( classname ), "trigger_door" )) != NULL )
{
if ( owner->owner == door )
{
return owner;
}
}
return NULL;
}
qboolean G_TriggerActive( gentity_t *self );
qboolean G_EntIsUnlockedDoor( int entityNum )
{
if ( entityNum < 0 || entityNum >= ENTITYNUM_WORLD )
{
return qfalse;
}
if ( G_EntIsDoor( entityNum ) )
{
gentity_t *ent = &g_entities[entityNum];
gentity_t *owner = NULL;
if ( ent->flags & FL_TEAMSLAVE )
{//not the master door, get the master door
while ( ent->teammaster && (ent->flags&FL_TEAMSLAVE))
{
ent = ent->teammaster;
}
}
if ( ent->targetname )
{//find out what is targetting it
owner = NULL;
//FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay?
while ( (owner = G_Find( owner, FOFS( target ), ent->targetname )) != NULL )
{
if ( !Q_stricmp( "trigger_multiple", owner->classname )
|| !Q_stricmp( "trigger_once", owner->classname ) )//FIXME: other triggers okay too?
{
if ( G_TriggerActive( owner ) )
{
return qtrue;
}
}
}
owner = NULL;
while ( (owner = G_Find( owner, FOFS( target2 ), ent->targetname )) != NULL )
{
if ( !Q_stricmp( "trigger_multiple", owner->classname ) )//FIXME: other triggers okay too?
{
if ( G_TriggerActive( owner ) )
{
return qtrue;
}
}
}
return qfalse;
}
else
{//check the door's auto-created trigger instead
owner = G_FindDoorTrigger( ent );
if ( owner && (owner->svFlags&SVF_INACTIVE) )
{//owning auto-created trigger is inactive
return qfalse;
}
}
if ( !(ent->svFlags & SVF_INACTIVE) && //assumes that the reactivate trigger isn't right next to the door!
!ent->health &&
!(ent->spawnflags & MOVER_PLAYER_USE) &&
!(ent->spawnflags & MOVER_FORCE_ACTIVATE) &&
!(ent->spawnflags & MOVER_LOCKED))
//FIXME: what about MOVER_GOODIE?
{
return qtrue;
}
}
return qfalse;
}
/*QUAKED func_door (0 .5 .8) ? START_OPEN FORCE_ACTIVATE CRUSHER TOGGLE LOCKED GOODIE PLAYER_USE INACTIVE
START_OPEN the door to moves to its destination when spawned, and operate in reverse. It is used to temporarily or permanently close off an area when triggered (not useful for touch or takedamage doors).
FORCE_ACTIVATE Can only be activated by a force push or pull
CRUSHER ?
TOGGLE wait in both the start and end states for a trigger event - does NOT work on Trek doors.
LOCKED Starts locked, with the shader animmap at the first frame and inactive. Once used, the animmap changes to the second frame and the door operates normally. Note that you cannot use the door again after this.
GOODIE Door will not work unless activator has a "goodie key" in his inventory
PLAYER_USE Player can use it with the use button
INACTIVE must be used by a target_activate before it can be used
"target" Door fires this when it starts moving from it's closed position to its open position.
"opentarget" Door fires this after reaching its "open" position
"target2" Door fires this when it starts moving from it's open position to its closed position.
"closetarget" Door fires this after reaching its "closed" position
"model2" .md3 model to also draw
"modelAngles" md3 model's angles <pitch yaw roll> (in addition to any rotation on the part of the brush entity itself)
"angle" determines the opening direction
"targetname" if set, no touch field will be spawned and a remote button or trigger field activates the door.
"speed" movement speed (100 default)
"wait" wait before returning (3 default, -1 = never return)
"delay" when used, how many seconds to wait before moving - default is none
"lip" lip remaining at end of move (8 default)
"dmg" damage to inflict when blocked (2 default, set to negative for no damage)
"color" constantLight color
"light" constantLight radius
"health" if set, the door must be shot open
"sounds" - sound door makes when opening/closing
"linear" set to 1 and it will move linearly rather than with acceleration (default is 0)
0 - no sound (default)
*/
void SP_func_door (gentity_t *ent)
{
vec3_t abs_movedir;
float distance;
vec3_t size;
float lip;
ent->e_BlockedFunc = blockedF_Blocked_Door;
if ( ent->spawnflags & MOVER_GOODIE )
{
G_SoundIndex( "sound/movers/goodie_fail.wav" );
G_SoundIndex( "sound/movers/goodie_pass.wav" );
}
// default speed of 400
if (!ent->speed)
ent->speed = 400;
// default wait of 2 seconds
if (!ent->wait)
ent->wait = 2;
ent->wait *= 1000;
ent->delay *= 1000;
// default lip of 8 units
G_SpawnFloat( "lip", "8", &lip );
// default damage of 2 points
G_SpawnInt( "dmg", "2", &ent->damage );
if ( ent->damage < 0 )
{
ent->damage = 0;
}
// first position at start
VectorCopy( ent->s.origin, ent->pos1 );
// calculate second position
gi.SetBrushModel( ent, ent->model );
G_SetMovedir( ent->s.angles, ent->movedir );
abs_movedir[0] = fabs( ent->movedir[0] );
abs_movedir[1] = fabs( ent->movedir[1] );
abs_movedir[2] = fabs( ent->movedir[2] );
VectorSubtract( ent->maxs, ent->mins, size );
distance = DotProduct( abs_movedir, size ) - lip;
VectorMA( ent->pos1, distance, ent->movedir, ent->pos2 );
// if "start_open", reverse position 1 and 2
if ( ent->spawnflags & 1 )
{
vec3_t temp;
VectorCopy( ent->pos2, temp );
VectorCopy( ent->s.origin, ent->pos2 );
VectorCopy( temp, ent->pos1 );
}
if ( ent->spawnflags & MOVER_LOCKED )
{//a locked door, set up as locked until used directly
ent->s.eFlags |= EF_SHADER_ANIM;//use frame-controlled shader anim
ent->s.frame = 0;//first stage of anim
}
InitMover( ent );
ent->nextthink = level.time + FRAMETIME;
if ( !(ent->flags&FL_TEAMSLAVE) )
{
int health;
G_SpawnInt( "health", "0", &health );
if ( health )
{
ent->takedamage = qtrue;
}
if ( !(ent->spawnflags&MOVER_LOCKED) && (ent->targetname || health || ent->spawnflags & MOVER_PLAYER_USE || ent->spawnflags & MOVER_FORCE_ACTIVATE) )
{
// non touch/shoot doors
ent->e_ThinkFunc = thinkF_Think_MatchTeam;
}
else
{//locked doors still spawn a trigger
ent->e_ThinkFunc = thinkF_Think_SpawnNewDoorTrigger;
}
}
}
/*
===============================================================================
PLAT
===============================================================================
*/
/*
==============
Touch_Plat
Don't allow decent if a living player is on it
===============
*/
void Touch_Plat( gentity_t *ent, gentity_t *other, trace_t *trace ) {
if ( !other->client || other->client->ps.stats[STAT_HEALTH] <= 0 ) {
return;
}
// delay return-to-pos1 by one second
if ( ent->moverState == MOVER_POS2 ) {
ent->nextthink = level.time + 1000;
}
}
/*
==============
Touch_PlatCenterTrigger
If the plat is at the bottom position, start it going up
===============
*/
void Touch_PlatCenterTrigger(gentity_t *ent, gentity_t *other, trace_t *trace ) {
if ( !other->client ) {
return;
}
if ( ent->owner->moverState == MOVER_POS1 ) {
Use_BinaryMover( ent->owner, ent, other );
}
}
/*
================
SpawnPlatTrigger
Spawn a trigger in the middle of the plat's low position
Elevator cars require that the trigger extend through the entire low position,
not just sit on top of it.
================
*/
void SpawnPlatTrigger( gentity_t *ent ) {
gentity_t *trigger;
vec3_t tmin, tmax;
// the middle trigger will be a thin trigger just
// above the starting position
trigger = G_Spawn();
trigger->e_TouchFunc = touchF_Touch_PlatCenterTrigger;
trigger->contents = CONTENTS_TRIGGER;
trigger->owner = ent;
tmin[0] = ent->pos1[0] + ent->mins[0] + 33;
tmin[1] = ent->pos1[1] + ent->mins[1] + 33;
tmin[2] = ent->pos1[2] + ent->mins[2];
tmax[0] = ent->pos1[0] + ent->maxs[0] - 33;
tmax[1] = ent->pos1[1] + ent->maxs[1] - 33;
tmax[2] = ent->pos1[2] + ent->maxs[2] + 8;
if ( tmax[0] <= tmin[0] ) {
tmin[0] = ent->pos1[0] + (ent->mins[0] + ent->maxs[0]) *0.5;
tmax[0] = tmin[0] + 1;
}
if ( tmax[1] <= tmin[1] ) {
tmin[1] = ent->pos1[1] + (ent->mins[1] + ent->maxs[1]) *0.5;
tmax[1] = tmin[1] + 1;
}
VectorCopy (tmin, trigger->mins);
VectorCopy (tmax, trigger->maxs);
gi.linkentity (trigger);
}
/*QUAKED func_plat (0 .5 .8) ? x x x x x x PLAYER_USE INACTIVE
PLAYER_USE Player can use it with the use button
INACTIVE must be used by a target_activate before it can be used
Plats are always drawn in the extended position so they will light correctly.
"lip" default 8, protrusion above rest position
"height" total height of movement, defaults to model height
"speed" overrides default 200.
"dmg" overrides default 2
"model2" .md3 model to also draw
"modelAngles" md3 model's angles <pitch yaw roll> (in addition to any rotation on the part of the brush entity itself)
"color" constantLight color
"light" constantLight radius
*/
void SP_func_plat (gentity_t *ent) {
float lip, height;
// ent->sound1to2 = ent->sound2to1 = G_SoundIndex("sound/movers/plats/pt1_strt.wav");
// ent->soundPos1 = ent->soundPos2 = G_SoundIndex("sound/movers/plats/pt1_end.wav");
VectorClear (ent->s.angles);
G_SpawnFloat( "speed", "200", &ent->speed );
G_SpawnInt( "dmg", "2", &ent->damage );
G_SpawnFloat( "wait", "1", &ent->wait );
G_SpawnFloat( "lip", "8", &lip );
ent->wait = 1000;
// create second position
gi.SetBrushModel( ent, ent->model );
if ( !G_SpawnFloat( "height", "0", &height ) ) {
height = (ent->maxs[2] - ent->mins[2]) - lip;
}
// pos1 is the rest (bottom) position, pos2 is the top
VectorCopy( ent->s.origin, ent->pos2 );
VectorCopy( ent->pos2, ent->pos1 );
ent->pos1[2] -= height;
InitMover( ent );
// touch function keeps the plat from returning while
// a live player is standing on it
ent->e_TouchFunc = touchF_Touch_Plat;
ent->e_BlockedFunc = blockedF_Blocked_Door;
ent->owner = ent; // so it can be treated as a door
// spawn the trigger if one hasn't been custom made
if ( !ent->targetname ) {
SpawnPlatTrigger(ent);
}
}
/*
===============================================================================
BUTTON
===============================================================================
*/
/*
==============
Touch_Button
===============
*/
void Touch_Button(gentity_t *ent, gentity_t *other, trace_t *trace ) {
if ( !other->client ) {
return;
}
if ( ent->moverState == MOVER_POS1 ) {
Use_BinaryMover( ent, other, other );
}
}
/*QUAKED func_button (0 .5 .8) ? x x x x x x PLAYER_USE INACTIVE
PLAYER_USE Player can use it with the use button
INACTIVE must be used by a target_activate before it can be used
When a button is touched, it moves some distance in the direction of it's angle, triggers all of it's targets, waits some time, then returns to it's original position where it can be triggered again.
"model2" .md3 model to also draw
"modelAngles" md3 model's angles <pitch yaw roll> (in addition to any rotation on the part of the brush entity itself)
"angle" determines the opening direction
"target" all entities with a matching targetname will be used
"speed" override the default 40 speed
"wait" override the default 1 second wait (-1 = never return)
"lip" override the default 4 pixel lip remaining at end of move
"health" if set, the button must be killed instead of touched
"color" constantLight color
"light" constantLight radius
*/
void SP_func_button( gentity_t *ent ) {
vec3_t abs_movedir;
float distance;
vec3_t size;
float lip;
// ent->sound1to2 = G_SoundIndex("sound/movers/switches/butn2.wav");
if ( !ent->speed ) {
ent->speed = 40;
}
if ( !ent->wait ) {
ent->wait = 1;
}
ent->wait *= 1000;
// first position
VectorCopy( ent->s.origin, ent->pos1 );
// calculate second position
gi.SetBrushModel( ent, ent->model );
G_SpawnFloat( "lip", "4", &lip );
G_SetMovedir( ent->s.angles, ent->movedir );
abs_movedir[0] = fabs(ent->movedir[0]);
abs_movedir[1] = fabs(ent->movedir[1]);
abs_movedir[2] = fabs(ent->movedir[2]);
VectorSubtract( ent->maxs, ent->mins, size );
distance = abs_movedir[0] * size[0] + abs_movedir[1] * size[1] + abs_movedir[2] * size[2] - lip;
VectorMA (ent->pos1, distance, ent->movedir, ent->pos2);
if (ent->health) {
// shootable button
ent->takedamage = qtrue;
} else {
// touchable button
ent->e_TouchFunc = touchF_Touch_Button;
}
InitMover( ent );
}
/*
===============================================================================
TRAIN
===============================================================================
*/
#define TRAIN_START_ON 1
#define TRAIN_TOGGLE 2
#define TRAIN_BLOCK_STOPS 4
/*
===============
Think_BeginMoving
The wait time at a corner has completed, so start moving again
===============
*/
void Think_BeginMoving( gentity_t *ent ) {
if ( ent->spawnflags & 2048 )
{
// this tie fighter hack is done for doom_detention, where the shooting gallery takes place. let them draw again when they start moving
ent->s.eFlags &= ~EF_NODRAW;
}
ent->s.pos.trTime = level.time;
if ( ent->alt_fire )
{
ent->s.pos.trType = TR_LINEAR_STOP;
}
else
{
ent->s.pos.trType = TR_NONLINEAR_STOP;
}
}
/*
===============
Reached_Train
===============
*/
void Reached_Train( gentity_t *ent ) {
gentity_t *next;
float speed;
vec3_t move;
float length;
// copy the apropriate values
next = ent->nextTrain;
if ( !next || !next->nextTrain ) {
//FIXME: can we go backwards- say if we are toggle-able?
return; // just stop
}
// fire all other targets
G_UseTargets( next, ent );
// set the new trajectory
ent->nextTrain = next->nextTrain;
VectorCopy( next->s.origin, ent->pos1 );
VectorCopy( next->nextTrain->s.origin, ent->pos2 );
// if the path_corner has a speed, use that
if ( next->speed ) {
speed = next->speed;
} else {
// otherwise use the train's speed
speed = ent->speed;
}
if ( speed < 1 ) {
speed = 1;
}
// calculate duration
VectorSubtract( ent->pos2, ent->pos1, move );
length = VectorLength( move );
ent->s.pos.trDuration = length * 1000 / speed;
// looping sound
/*
if ( VALIDSTRING( next->soundSet ) )
{
ent->s.loopSound = CAS_GetBModelSound( next->soundSet, BMS_MID );//ent->soundLoop;
}
*/
G_PlayDoorLoopSound( ent );
// start it going
SetMoverState( ent, MOVER_1TO2, level.time );
if (( next->spawnflags & 1 ))
{
vec3_t angs;
vectoangles( move, angs );
AnglesSubtract( angs, ent->currentAngles, angs );
for ( int i = 0; i < 3; i++ )
{
AngleNormalize360( angs[i] );
}
VectorCopy( ent->currentAngles, ent->s.apos.trBase );
VectorScale( angs, 0.5f, ent->s.apos.trDelta );
ent->s.apos.trTime = level.time;
ent->s.apos.trDuration = 2000;
if ( ent->alt_fire )
{
ent->s.apos.trType = TR_LINEAR_STOP;
}
else
{
ent->s.apos.trType = TR_NONLINEAR_STOP;
}
}
else
{
if (( next->spawnflags & 4 ))
{//yaw
vec3_t angs;
vectoangles( move, angs );
AnglesSubtract( angs, ent->currentAngles, angs );
for ( int i = 0; i < 3; i++ )
{
AngleNormalize360( angs[i] );
}
VectorCopy( ent->currentAngles, ent->s.apos.trBase );
ent->s.apos.trDelta[YAW] = angs[YAW] * 0.5f;
if (( next->spawnflags & 8 ))
{//roll, too
ent->s.apos.trDelta[ROLL] = angs[YAW] * -0.1f;
}
ent->s.apos.trTime = level.time;
ent->s.apos.trDuration = 2000;
if ( ent->alt_fire )
{
ent->s.apos.trType = TR_LINEAR_STOP;
}
else
{
ent->s.apos.trType = TR_NONLINEAR_STOP;
}
}
}
// This is for the tie fighter shooting gallery on doom detention, you could see them waiting under the bay, but the architecture couldn't easily be changed..
if (( next->spawnflags & 2 ))
{
ent->s.eFlags |= EF_NODRAW; // make us invisible until we start moving again
}
// if there is a "wait" value on the target, don't start moving yet
if ( next->wait )
{
ent->nextthink = level.time + next->wait * 1000;
ent->e_ThinkFunc = thinkF_Think_BeginMoving;
ent->s.pos.trType = TR_STATIONARY;
}
else if (!( next->spawnflags & 2 ))
{
// we aren't waiting to start, so let us draw right away
ent->s.eFlags &= ~EF_NODRAW;
}
}
void TrainUse( gentity_t *ent, gentity_t *other, gentity_t *activator )
{
Reached_Train( ent );
}
/*
===============
Think_SetupTrainTargets
Link all the corners together
===============
*/
void Think_SetupTrainTargets( gentity_t *ent ) {
gentity_t *path, *next, *start;
ent->nextTrain = G_Find( NULL, FOFS(targetname), ent->target );
if ( !ent->nextTrain ) {
gi.Printf( "func_train at %s with an unfound target\n", vtos(ent->absmin) );
//Free me?`
return;
}
//FIXME: this can go into an infinite loop if last path_corner doesn't link to first
//path_corner, like so:
// t1---->t2---->t3
// ^ |
// \_____|
start = NULL;
next = NULL;
int iterations = 2000; //max attempts to find our path start
for ( path = ent->nextTrain ; path != start ; path = next ) {
if (!iterations--)
{
G_Error( "Think_SetupTrainTargets: last path_corner doesn't link back to first on func_train(%s)", vtos(ent->absmin) );
}
if (!start)
{
start = path;
}
if ( !path->target ) {
// gi.Printf( "Train corner at %s without a target\n", vtos(path->s.origin) );
//end of path
break;
}
// find a path_corner among the targets
// there may also be other targets that get fired when the corner
// is reached
next = NULL;
do {
next = G_Find( next, FOFS(targetname), path->target );
if ( !next ) {
// gi.Printf( "Train corner at %s without a target path_corner\n", vtos(path->s.origin) );
//end of path
break;
}
} while ( strcmp( next->classname, "path_corner" ) );
if ( next )
{
path->nextTrain = next;
}
else
{
break;
}
}
if ( !ent->targetname || (ent->spawnflags&1) /*start on*/)
{
// start the train moving from the first corner
Reached_Train( ent );
}
else
{
G_SetOrigin( ent, ent->s.origin );
}
}
/*QUAKED path_corner (.5 .3 0) (-8 -8 -8) (8 8 8) TURN_TRAIN INVISIBLE YAW_TRAIN ROLL_TRAIN
TURN_TRAIN func_train moving on this path will turn to face the next path_corner within 2 seconds
INVISIBLE - train will become invisible ( but still solid ) when it reaches this path_corner.
It will become visible again at the next path_corner that does not have this option checked
Train path corners.
Target: next path corner and other targets to fire
"speed" speed to move to the next corner
"wait" seconds to wait before behining move to next corner
*/
void SP_path_corner( gentity_t *self ) {
if ( !self->targetname ) {
gi.Printf ("path_corner with no targetname at %s\n", vtos(self->s.origin));
G_FreeEntity( self );
return;
}
// path corners don't need to be linked in
VectorCopy(self->s.origin, self->currentOrigin);
}
void func_train_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc )
{
if ( self->target3 )
{
G_UseTargets2( self, self, self->target3 );
}
//HACKHACKHACKHACK
G_PlayEffect( "explosions/fighter_explosion2", self->currentOrigin );
G_FreeEntity( self );
//HACKHACKHACKHACK
}
/*QUAKED func_train (0 .5 .8) ? START_ON TOGGLE BLOCK_STOPS x x LOOP PLAYER_USE INACTIVE TIE
LOOP - if it's a ghoul2 model, it will just loop the animation
PLAYER_USE Player can use it with the use button
INACTIVE must be used by a target_activate before it can be used
TIE flying Tie-fighter hack, should be made more flexible so other things can use this if needed
A train is a mover that moves between path_corner target points.
Trains MUST HAVE AN ORIGIN BRUSH.
The train spawns at the first target it is pointing at.
"model2" .md3 model to also draw
"modelAngles" md3 model's angles <pitch yaw roll> (in addition to any rotation on the part of the brush entity itself)
"speed" default 100
"dmg" default 2
"health" default 0
"noise" looping sound to play when the train is in motion
"targetname" will not start until used
"target" next path corner
"target3" what to use when it breaks
"color" constantLight color
"light" constantLight radius
"linear" set to 1 and it will move linearly rather than with acceleration (default is 0)
"startframe" default 0...ghoul2 animation start frame
"endframe" default 0...ghoul2 animation end frame
*/
void SP_func_train (gentity_t *self) {
VectorClear (self->s.angles);
if (self->spawnflags & TRAIN_BLOCK_STOPS) {
self->damage = 0;
} else {
if (!self->damage) {
self->damage = 2;
}
}
if ( !self->speed ) {
self->speed = 100;
}
if ( !self->target ) {
gi.Printf ("func_train without a target at %s\n", vtos(self->absmin));
G_FreeEntity( self );
return;
}
char *noise;
G_SpawnInt( "startframe", "0", &self->startFrame );
G_SpawnInt( "endframe", "0", &self->endFrame );
if ( G_SpawnString( "noise", "", &noise ) )
{
if ( VALIDSTRING( noise ) )
{
self->s.loopSound = cgi_S_RegisterSound( noise );//G_SoundIndex( noise );
}
}
gi.SetBrushModel( self, self->model );
InitMover( self );
if ( self->spawnflags & 2048 ) // TIE HACK
{
//HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK
self->s.modelindex2 = G_ModelIndex( "models/map_objects/ships/tie_fighter.md3" );
G_EffectIndex( "explosions/fighter_explosion2" );
self->contents = CONTENTS_SHOTCLIP;
self->takedamage = qtrue;
VectorSet( self->maxs, 112, 112, 112 );
VectorSet( self->mins, -112, -112, -112 );
self->e_DieFunc = dieF_func_train_die;
gi.linkentity( self );
//HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK
}
if ( self->targetname )
{
self->e_UseFunc = useF_TrainUse;
}
self->e_ReachedFunc = reachedF_Reached_Train;
// start trains on the second frame, to make sure their targets have had
// a chance to spawn
self->nextthink = level.time + START_TIME_LINK_ENTS;
self->e_ThinkFunc = thinkF_Think_SetupTrainTargets;
if ( self->playerModel >= 0 && self->spawnflags & 32 ) // loop...dunno, could support it on other things, but for now I need it for the glider...so...kill the flag
{
self->spawnflags &= ~32; // once only
gi.G2API_SetBoneAnim( &self->ghoul2[self->playerModel], "model_root", self->startFrame, self->endFrame, BONE_ANIM_OVERRIDE_LOOP, 1.0f + crandom() * 0.1f, 0 );
self->endFrame = 0; // don't allow it to do anything with the animation function in G_main
}
}
/*
===============================================================================
STATIC
===============================================================================
*/
/*QUAKED func_static (0 .5 .8) ? F_PUSH F_PULL SWITCH_SHADER CRUSHER IMPACT SOLITARY PLAYER_USE INACTIVE BROADCAST
F_PUSH Will be used when you Force-Push it
F_PULL Will be used when you Force-Pull it
SWITCH_SHADER Toggle the shader anim frame between 1 and 2 when used
CRUSHER Make it do damage when it's blocked
IMPACT Make it do damage when it hits any entity
SOLITARY Can only be pushed when directly under crosshair, when pushed you shall push nothing else BUT me.
PLAYER_USE Player can use it with the use button
INACTIVE must be used by a target_activate before it can be used
BROADCAST don't ever use this, it's evil
A bmodel that just sits there, doing nothing. Can be used for conditional walls and models.
"model2" .md3 model to also draw
"modelAngles" md3 model's angles <pitch yaw roll> (in addition to any rotation on the part of the brush entity itself)
"color" constantLight color
"light" constantLight radius
"dmg" how much damage to do when it crushes (use with CRUSHER spawnflag default is 2)
"linear" set to 1 and it will move linearly rather than with acceleration (default is 0)
"NPC_targetname" if set up to be push/pullable, only this NPC can push/pull it (for the player, use "player")
*/
void SP_func_static( gentity_t *ent )
{
gi.SetBrushModel( ent, ent->model );
VectorCopy( ent->s.origin, ent->pos1 );
VectorCopy( ent->s.origin, ent->pos2 );
InitMover( ent );
G_SetOrigin( ent, ent->s.origin );
G_SetAngles( ent, ent->s.angles );
ent->e_UseFunc = useF_func_static_use;
ent->e_ReachedFunc = reachedF_NULL;
if( ent->spawnflags & 2048 )
{ // yes this is very very evil, but for now (pre-alpha) it's a solution
ent->svFlags |= SVF_BROADCAST; // I need to rotate something that is huge and it's touching too many area portals...
}
if ( ent->spawnflags & 4/*SWITCH_SHADER*/ )
{
ent->s.eFlags |= EF_SHADER_ANIM;//use frame-controlled shader anim
ent->s.frame = 0;//first stage of anim
ent->spawnflags &= ~4;//this is the CRUSHER spawnflag! remove it!
}
if ( ent->spawnflags & 8 )
{//!!! 8 is NOT the crusher spawnflag, 4 is!!!
ent->spawnflags &= ~8;
ent->spawnflags |= MOVER_CRUSHER;
if ( !ent->damage )
{
ent->damage = 2;
}
}
gi.linkentity( ent );
if (level.mBSPInstanceDepth)
{ // this means that this guy will never be updated, moved, changed, etc.
ent->s.eFlags = EF_PERMANENT;
}
}
void func_static_use ( gentity_t *self, gentity_t *other, gentity_t *activator )
{
G_ActivateBehavior( self, BSET_USE );
if ( self->spawnflags & 4/*SWITCH_SHADER*/ )
{
self->s.frame = self->s.frame ? 0 : 1;//toggle frame
}
G_UseTargets( self, activator );
}
/*
===============================================================================
ROTATING
===============================================================================
*/
void func_rotating_touch( gentity_t *self, gentity_t *other, trace_t *trace )
{
// vec3_t spot;
// gentity_t *tent;
if( !other->client ) // don't want to disintegrate items or weapons, etc...
{
return;
}
// yeah, this is a bit hacky...
if( self->s.apos.trType != TR_STATIONARY && !(other->flags & FL_DISINTEGRATED) ) // only damage if it's moving
{
// VectorCopy( self->currentOrigin, spot );
// tent = G_TempEntity( spot, EV_DISINTEGRATION );
// tent->s.eventParm = PW_DISRUPTION;
// tent->owner = self;
// let G_Damage call the fx instead, beside, this way you can disintegrate a corpse this way
G_Sound( other, G_SoundIndex( "sound/effects/energy_crackle.wav" ) );
G_Damage( other, self, self, NULL, NULL, 10000, DAMAGE_NO_KNOCKBACK, MOD_SNIPER );
}
}
void func_rotating_use( gentity_t *self, gentity_t *other, gentity_t *activator )
{
if( self->s.apos.trType == TR_LINEAR )
{
self->s.apos.trType = TR_STATIONARY;
// stop the sound if it stops moving
self->s.loopSound = 0;
// play stop sound too?
if ( VALIDSTRING( self->soundSet ) == true )
{
G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_END ));
}
}
else
{
if ( VALIDSTRING( self->soundSet ) == true )
{
G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_START ));
self->s.loopSound = CAS_GetBModelSound( self->soundSet, BMS_MID );
if ( self->s.loopSound < 0 )
{
self->s.loopSound = 0;
}
}
self->s.apos.trType = TR_LINEAR;
}
}
/*QUAKED func_rotating (0 .5 .8) ? START_ON TOUCH_KILL X_AXIS Y_AXIS x x PLAYER_USE INACTIVE
PLAYER_USE Player can use it with the use button
TOUCH_KILL Inflicts massive damage upon touching it, disitegrates bodies
INACTIVE must be used by a target_activate before it can be used
You need to have an origin brush as part of this entity. The center of that brush will be
the point around which it is rotated. It will rotate around the Z axis by default. You can
check either the X_AXIS or Y_AXIS box to change that.
"model2" .md3 model to also draw
"modelAngles" md3 model's angles <pitch yaw roll> (in addition to any rotation on the part of the brush entity itself)
"speed" determines how fast it moves; default value is 100.
"dmg" damage to inflict when blocked (2 default)
"color" constantLight color
"light" constantLight radius
*/
void SP_func_rotating (gentity_t *ent) {
if ( !ent->speed ) {
ent->speed = 100;
}
ent->s.apos.trType = TR_STATIONARY;
if( ent->spawnflags & 1 ) // start on
{
ent->s.apos.trType = TR_LINEAR;
}
// set the axis of rotation
if ( ent->spawnflags & 4 ) {
ent->s.apos.trDelta[2] = ent->speed;
} else if ( ent->spawnflags & 8 ) {
ent->s.apos.trDelta[0] = ent->speed;
} else {
ent->s.apos.trDelta[1] = ent->speed;
}
if (!ent->damage) {
ent->damage = 2;
}
gi.SetBrushModel( ent, ent->model );
InitMover( ent );
if ( ent->targetname )
{
ent->e_UseFunc = useF_func_rotating_use;
}
VectorCopy( ent->s.origin, ent->s.pos.trBase );
VectorCopy( ent->s.pos.trBase, ent->currentOrigin );
VectorCopy( ent->s.apos.trBase, ent->currentAngles );
if( ent->spawnflags & 2 )
{
ent->e_TouchFunc = touchF_func_rotating_touch;
G_SoundIndex( "sound/effects/energy_crackle.wav" );
}
gi.linkentity( ent );
}
/*
===============================================================================
BOBBING
===============================================================================
*/
void func_bobbing_use( gentity_t *self, gentity_t *other, gentity_t *activator )
{
// Toggle our move state
if ( self->s.pos.trType == TR_SINE )
{
self->s.pos.trType = TR_INTERPOLATE;
// Save off roughly where we were
VectorCopy( self->currentOrigin, self->s.pos.trBase );
// Store the current phase value so we know how to start up where we left off.
self->radius = ( level.time - self->s.pos.trTime ) / (float)self->s.pos.trDuration;
}
else
{
self->s.pos.trType = TR_SINE;
// Set the time based on the saved phase value
self->s.pos.trTime = level.time - self->s.pos.trDuration * self->radius;
// Always make sure we are starting with a fresh base
VectorCopy( self->s.origin, self->s.pos.trBase );
}
}
/*QUAKED func_bobbing (0 .5 .8) ? X_AXIS Y_AXIS START_OFF x x x PLAYER_USE INACTIVE
PLAYER_USE Player can use it with the use button
INACTIVE must be used by a target_activate before it can be used
Normally bobs on the Z axis
"model2" .md3 model to also draw
"modelAngles" md3 model's angles <pitch yaw roll> (in addition to any rotation on the part of the brush entity itself)
"height" amplitude of bob (32 default)
"speed" seconds to complete a bob cycle (4 default)
"phase" the 0.0 to 1.0 offset in the cycle to start at
"dmg" damage to inflict when blocked (2 default)
"color" constantLight color
"light" constantLight radius
"targetname" turns on/off when used
*/
void SP_func_bobbing (gentity_t *ent) {
float height;
float phase;
G_SpawnFloat( "speed", "4", &ent->speed );
G_SpawnFloat( "height", "32", &height );
G_SpawnInt( "dmg", "2", &ent->damage );
G_SpawnFloat( "phase", "0", &phase );
gi.SetBrushModel( ent, ent->model );
InitMover( ent );
VectorCopy( ent->s.origin, ent->s.pos.trBase );
VectorCopy( ent->s.origin, ent->currentOrigin );
// set the axis of bobbing
if ( ent->spawnflags & 1 ) {
ent->s.pos.trDelta[0] = height;
} else if ( ent->spawnflags & 2 ) {
ent->s.pos.trDelta[1] = height;
} else {
ent->s.pos.trDelta[2] = height;
}
ent->s.pos.trDuration = ent->speed * 1000;
ent->s.pos.trTime = ent->s.pos.trDuration * phase;
if ( ent->spawnflags & 4 ) // start_off
{
ent->s.pos.trType = TR_INTERPOLATE;
// Now use the phase to calculate where it should be at the start.
ent->radius = phase;
phase = (float)sin( phase * M_PI * 2 );
VectorMA( ent->s.pos.trBase, phase, ent->s.pos.trDelta, ent->s.pos.trBase );
if ( ent->targetname )
{
ent->e_UseFunc = useF_func_bobbing_use;
}
}
else
{
ent->s.pos.trType = TR_SINE;
}
}
/*
===============================================================================
PENDULUM
===============================================================================
*/
/*QUAKED func_pendulum (0 .5 .8) ? x x x x x x PLAYER_USE INACTIVE
PLAYER_USE Player can use it with the use button
INACTIVE must be used by a target_activate before it can be used
You need to have an origin brush as part of this entity.
Pendulums always swing north / south on unrotated models. Add an angles field to the model to allow rotation in other directions.
Pendulum frequency is a physical constant based on the length of the beam and gravity.
"model2" .md3 model to also draw
"modelAngles" md3 model's angles <pitch yaw roll> (in addition to any rotation on the part of the brush entity itself)
"speed" the number of degrees each way the pendulum swings, (30 default)
"phase" the 0.0 to 1.0 offset in the cycle to start at
"dmg" damage to inflict when blocked (2 default)
"color" constantLight color
"light" constantLight radius
*/
void SP_func_pendulum(gentity_t *ent) {
float freq;
float length;
float phase;
float speed;
G_SpawnFloat( "speed", "30", &speed );
G_SpawnInt( "dmg", "2", &ent->damage );
G_SpawnFloat( "phase", "0", &phase );
gi.SetBrushModel( ent, ent->model );
// find pendulum length
length = fabs( ent->mins[2] );
if ( length < 8 ) {
length = 8;
}
freq = 1 / ( M_PI * 2 ) * sqrt( g_gravity->value / ( 3 * length ) );
ent->s.pos.trDuration = ( 1000 / freq );
InitMover( ent );
VectorCopy( ent->s.origin, ent->s.pos.trBase );
VectorCopy( ent->s.origin, ent->currentOrigin );
VectorCopy( ent->s.angles, ent->s.apos.trBase );
ent->s.apos.trDuration = 1000 / freq;
ent->s.apos.trTime = ent->s.apos.trDuration * phase;
ent->s.apos.trType = TR_SINE;
ent->s.apos.trDelta[2] = speed;
}
/*
===============================================================================
WALL
===============================================================================
*/
//static -slc
void use_wall( gentity_t *ent, gentity_t *other, gentity_t *activator )
{
G_ActivateBehavior(ent,BSET_USE);
// Not there so make it there
//if (!(ent->contents & CONTENTS_SOLID))
if (!ent->count) // off
{
ent->svFlags &= ~SVF_NOCLIENT;
ent->s.eFlags &= ~EF_NODRAW;
ent->count = 1;
//NOTE: reset the brush model because we need to get *all* the contents back
//ent->contents |= CONTENTS_SOLID;
gi.SetBrushModel( ent, ent->model );
if ( !(ent->spawnflags&1) )
{//START_OFF doesn't effect area portals
gi.AdjustAreaPortalState( ent, qfalse );
}
}
// Make it go away
else
{
//NOTE: MUST do this BEFORE clearing contents, or you may not open the area portal!!!
if ( !(ent->spawnflags&1) )
{//START_OFF doesn't effect area portals
gi.AdjustAreaPortalState( ent, qtrue );
}
ent->contents = 0;
ent->svFlags |= SVF_NOCLIENT;
ent->s.eFlags |= EF_NODRAW;
ent->count = 0; // off
}
}
#define FUNC_WALL_OFF 1
#define FUNC_WALL_ANIM 2
/*QUAKED func_wall (0 .5 .8) ? START_OFF AUTOANIMATE x x x x PLAYER_USE INACTIVE
PLAYER_USE Player can use it with the use button
INACTIVE must be used by a target_activate before it can be used
A bmodel that just sits there, doing nothing. Can be used for conditional walls and models.
"model2" .md3 model to also draw
"modelAngles" md3 model's angles <pitch yaw roll> (in addition to any rotation on the part of the brush entity itself)
"color" constantLight color
"light" constantLight radius
START_OFF - the wall will not be there
AUTOANIMATE - if a model is used it will animate
*/
void SP_func_wall( gentity_t *ent )
{
gi.SetBrushModel( ent, ent->model );
VectorCopy( ent->s.origin, ent->pos1 );
VectorCopy( ent->s.origin, ent->pos2 );
InitMover( ent );
VectorCopy( ent->s.origin, ent->s.pos.trBase );
VectorCopy( ent->s.origin, ent->currentOrigin );
// count is used as an on/off switch (start it on)
ent->count = 1;
// it must be START_OFF
if (ent->spawnflags & FUNC_WALL_OFF)
{
ent->spawnContents = ent->contents;
ent->contents = 0;
ent->svFlags |= SVF_NOCLIENT;
ent->s.eFlags |= EF_NODRAW;
// turn it off
ent->count = 0;
}
if (!(ent->spawnflags & FUNC_WALL_ANIM))
{
ent->s.eFlags |= EF_ANIM_ALLFAST;
}
ent->e_UseFunc = useF_use_wall;
gi.linkentity (ent);
}
void security_panel_use( gentity_t *self, gentity_t *other, gentity_t *activator )
{
if ( !activator )
{
return;
}
if ( INV_SecurityKeyCheck( activator, self->message ) )
{//congrats!
gi.SendServerCommand( NULL, "cp @SP_INGAME_SECURITY_KEY_UNLOCKEDDOOR" );
//use targets
G_UseTargets( self, activator );
//take key
INV_SecurityKeyTake( activator, self->message );
if ( activator->ghoul2.size() )
{
gi.G2API_SetSurfaceOnOff( &activator->ghoul2[activator->playerModel], "l_arm_key", 0x00000002 );
}
//FIXME: maybe set frame on me to have key sticking out?
//self->s.frame = 1;
//play sound
G_Sound( self, self->soundPos2 );
//unusable
self->e_UseFunc = useF_NULL;
}
else
{//failure sound/display
if ( activator->message )
{//have a key, just the wrong one
gi.SendServerCommand( NULL, "cp @SP_INGAME_INCORRECT_KEY" );
}
else
{//don't have a key at all
gi.SendServerCommand( NULL, "cp @SP_INGAME_NEED_SECURITY_KEY" );
}
G_UseTargets2( self, activator, self->target2 );
//FIXME: change display? Maybe shader animmap change?
//play sound
G_Sound( self, self->soundPos1 );
}
}
/*QUAKED misc_security_panel (0 .5 .8) (-8 -8 -8) (8 8 8) x x x x x x x INACTIVE
model="models/map_objects/kejim/sec_panel.md3"
A model that just sits there and opens when a player uses it and has right key
INACTIVE - Start off, has to be activated to be usable
"message" name of the key player must have
"target" thing to use when successfully opened
"target2" thing to use when player uses the panel without the key
*/
void SP_misc_security_panel ( gentity_t *self )
{
self->s.modelindex = G_ModelIndex( "models/map_objects/kejim/sec_panel.md3" );
self->soundPos1 = G_SoundIndex( "sound/movers/sec_panel_fail.mp3" );
self->soundPos2 = G_SoundIndex( "sound/movers/sec_panel_pass.mp3" );
G_SetOrigin( self, self->s.origin );
G_SetAngles( self, self->s.angles );
VectorSet( self->mins, -8, -8, -8 );
VectorSet( self->maxs, 8, 8, 8 );
self->contents = CONTENTS_SOLID;
gi.linkentity( self );
//NOTE: self->message is the key
self->svFlags |= SVF_PLAYER_USABLE;
if(self->spawnflags & 128)
{
self->svFlags |= SVF_INACTIVE;
}
self->e_UseFunc = useF_security_panel_use;
} | 0 | 0.973954 | 1 | 0.973954 | game-dev | MEDIA | 0.956349 | game-dev | 0.99972 | 1 | 0.99972 |
jeffsponaugle/roscoe | 1,539 | src/Roscoe/Emulator/Shared/libsdl/libsdlsrc/src/main/psp/SDL_psp_main.c | /*
SDL_psp_main.c, placed in the public domain by Sam Lantinga 3/13/14
*/
#include "SDL_config.h"
#ifdef __PSP__
#include "SDL_main.h"
#include <pspkernel.h>
#include <pspthreadman.h>
#ifdef main
#undef main
#endif
/* If application's main() is redefined as SDL_main, and libSDLmain is
linked, then this file will create the standard exit callback,
define the PSP_MODULE_INFO macro, and exit back to the browser when
the program is finished.
You can still override other parameters in your own code if you
desire, such as PSP_HEAP_SIZE_KB, PSP_MAIN_THREAD_ATTR,
PSP_MAIN_THREAD_STACK_SIZE, etc.
*/
PSP_MODULE_INFO("SDL App", 0, 1, 0);
PSP_MAIN_THREAD_ATTR(THREAD_ATTR_VFPU | THREAD_ATTR_USER);
int sdl_psp_exit_callback(int arg1, int arg2, void *common)
{
sceKernelExitGame();
return 0;
}
int sdl_psp_callback_thread(SceSize args, void *argp)
{
int cbid;
cbid = sceKernelCreateCallback("Exit Callback",
sdl_psp_exit_callback, NULL);
sceKernelRegisterExitCallback(cbid);
sceKernelSleepThreadCB();
return 0;
}
int sdl_psp_setup_callbacks(void)
{
int thid;
thid = sceKernelCreateThread("update_thread",
sdl_psp_callback_thread, 0x11, 0xFA0, 0, 0);
if(thid >= 0)
sceKernelStartThread(thid, 0, 0);
return thid;
}
int main(int argc, char *argv[])
{
sdl_psp_setup_callbacks();
SDL_SetMainReady();
(void)SDL_main(argc, argv);
return 0;
}
#endif /* __PSP__ */
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.888836 | 1 | 0.888836 | game-dev | MEDIA | 0.631454 | game-dev | 0.671832 | 1 | 0.671832 |
BlesseNtumble/GalaxySpace | 3,834 | src/main/java/galaxyspace/core/client/jei/nasaworkbench/body/BodyRecipeCategory.java | package galaxyspace.core.client.jei.nasaworkbench.body;
import javax.annotation.Nonnull;
import galaxyspace.GalaxySpace;
import galaxyspace.core.client.jei.GSRecipeCategories;
import mezz.jei.api.IGuiHelper;
import mezz.jei.api.gui.IDrawable;
import mezz.jei.api.gui.IGuiItemStackGroup;
import mezz.jei.api.gui.IRecipeLayout;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.IRecipeCategory;
import mezz.jei.api.recipe.IRecipeWrapper;
import micdoodle8.mods.galacticraft.core.util.GCCoreUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
public class BodyRecipeCategory implements IRecipeCategory
{
private static final ResourceLocation rocketGuiTexture = new ResourceLocation(GalaxySpace.ASSET_PREFIX, "textures/gui/schematics/schematic_clear.png");
@Nonnull
private final IDrawable background;
@Nonnull
private final IDrawable result;
@Nonnull
private final String localizedName;
public BodyRecipeCategory(IGuiHelper guiHelper)
{
this.background = guiHelper.createDrawable(rocketGuiTexture, 3, 4, 187, 151);
this.localizedName = GCCoreUtil.translate("tile.rocket_workbench.name");
this.result = guiHelper.createDrawable(rocketGuiTexture, 192, 21, 34, 34);
}
@Nonnull
@Override
public String getUid()
{
return GSRecipeCategories.BODY;
}
@Nonnull
@Override
public String getTitle()
{
return this.localizedName;
}
@Nonnull
@Override
public IDrawable getBackground()
{
return this.background;
}
@Override
public void drawExtras(Minecraft minecraft)
{
this.result.draw(minecraft, 135, 110);
}
@Override
public void setRecipe(IRecipeLayout recipeLayout, IRecipeWrapper recipeWrapper, IIngredients ingredients)
{
IGuiItemStackGroup itemstacks = recipeLayout.getItemStacks();
int xOffset = 5;
int yOffset = 10;
itemstacks.init(0, true, 13 + xOffset, 25 + yOffset);
itemstacks.init(1, true, 13 + xOffset, 25+16 + yOffset);
itemstacks.init(2, true, 13 + xOffset, 25+16*2 + yOffset);
itemstacks.init(3, true, 13 + xOffset, 25+16*3 + yOffset);
itemstacks.init(4, true, 13 + xOffset, 25+16*4 + yOffset);
itemstacks.init(5, true, 13 + xOffset, 25+16*5 + yOffset);
itemstacks.init(6, true, 29 + xOffset, 25 + yOffset);
itemstacks.init(7, true, 29 + xOffset, 25+16 + yOffset);
itemstacks.init(8, true, 29 + xOffset, 25+16*2 + yOffset);
itemstacks.init(9, true, 29 + xOffset, 25+16*3 + yOffset);
itemstacks.init(10, true, 29 + xOffset, 25+16*4 + yOffset);
itemstacks.init(11, true, 29 + xOffset, 25+16*5 + yOffset);
itemstacks.init(12, true, 45 + xOffset, 25 + yOffset);
itemstacks.init(13, true, 45 + xOffset, 25+16 + yOffset);
itemstacks.init(14, true, 45 + xOffset, 25+16*2 + yOffset);
itemstacks.init(15, true, 45 + xOffset, 25+16*3 + yOffset);
itemstacks.init(16, true, 45 + xOffset, 25+16*4 + yOffset);
itemstacks.init(17, true, 45 + xOffset, 25+16*5 + yOffset);
itemstacks.init(18, true, 61 + xOffset, 25 + yOffset);
itemstacks.init(19, true, 61 + xOffset, 25+16 + yOffset);
itemstacks.init(20, true, 61 + xOffset, 25+16*2 + yOffset);
itemstacks.init(21, true, 61 + xOffset, 25+16*3 + yOffset);
itemstacks.init(22, true, 61 + xOffset, 25+16*4 + yOffset);
itemstacks.init(23, true, 61 + xOffset, 25+16*5 + yOffset);
itemstacks.init(24, false, 143, 118);
itemstacks.set(ingredients);
}
@Override
public String getModName()
{
return GalaxySpace.NAME;
}
}
| 0 | 0.682447 | 1 | 0.682447 | game-dev | MEDIA | 0.955129 | game-dev | 0.611695 | 1 | 0.611695 |
P3pp3rF1y/AncientWarfare2 | 1,827 | src/main/java/net/shadowmage/ancientwarfare/automation/block/BlockChunkLoaderSimple.java | package net.shadowmage.ancientwarfare.automation.block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.shadowmage.ancientwarfare.automation.tile.TileChunkLoaderSimple;
import net.shadowmage.ancientwarfare.core.util.WorldTools;
public class BlockChunkLoaderSimple extends BlockBaseAutomation {
public BlockChunkLoaderSimple(String regName) {
super(Material.ROCK, regName);
setHardness(2.f);
}
@Override
public boolean hasTileEntity(IBlockState state) {
return true;
}
@Override
public TileEntity createTileEntity(World world, IBlockState state) {
return new TileChunkLoaderSimple();
}
@Override
public void breakBlock(World world, BlockPos pos, IBlockState state) {
WorldTools.getTile(world, pos, TileChunkLoaderSimple.class).ifPresent(TileChunkLoaderSimple::releaseTicket);
super.breakBlock(world, pos, state);
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
return WorldTools.clickInteractableTileWithHand(world, pos, player, hand);
}
@Override
public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) {
super.onBlockPlacedBy(world, pos, state, placer, stack);
if (!world.isRemote) {
WorldTools.getTile(world, pos, TileChunkLoaderSimple.class).ifPresent(TileChunkLoaderSimple::setupInitialTicket);
}
}
}
| 0 | 0.702789 | 1 | 0.702789 | game-dev | MEDIA | 0.999761 | game-dev | 0.907622 | 1 | 0.907622 |
ForOne-Club/ImproveGame | 9,891 | Content/Items/Globes/Core/GlobeRevealer.cs | using ImproveGame.Packets.Notifications;
using ImproveGame.Packets.WorldFeatures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria.Chat;
using Terraria.DataStructures;
namespace ImproveGame.Content.Items.Globes.Core;
public static class GlobeRevealer
{
public static void NoDataNotification(Globe dummyItem)
{
AddNotification(Language.GetText("Mods.ImproveGame.Items.GlobeBase.NotFound")
.WithFormatArgs(dummyItem.GetLocalizedValue("BiomeName")).Value, Globe.hintTextColor);
}
public static void NotFoundNotification(Globe dummyItem)
{
AddNotification(dummyItem.GetLocalizedValue("NotFound"), Globe.hintTextColor);
}
public static void AlreadyRevealedNotification(Globe dummyItem)
{
if (dummyItem is OnceForAllGlobe)
AddNotification(Language.GetText("Mods.ImproveGame.Items.GlobeBase.AlreadyRevealed")
.WithFormatArgs(dummyItem.GetLocalizedValue("BiomeName")).Value, Globe.hintTextColor);
else
AddNotification(dummyItem.GetLocalizedValue("AlreadyRevealed"), Globe.hintTextColor);
}
public static void RevealNotification(Globe dummyItem, string name)
=> AddNotification(Language.GetText("Mods.ImproveGame.Items.GlobeBase.Reveal")
.WithFormatArgs(dummyItem.GetLocalizedValue("BiomeName"), name).Value, Globe.foundColor);
public static void RevealBroadcast(Globe dummyItem, string name) =>
// 由于服务器和客户端使用的语言可能不一样,所以用FromKey并专门设了个翻译文本
ChatHelper.BroadcastChatMessage(NetworkText.FromKey("Mods.ImproveGame.Items.GlobeBase.Reveal", dummyItem.GetLocalizedValue("BiomeName"), name), Globe.foundColor);
//这两个都是实时查找,一次解锁一个型
public static bool RevealPlantera(Projectile projectile, Globe dummyItem, bool onlyJudging)
{
if (Main.netMode is NetmodeID.MultiplayerClient) //此时由服务器进行查找
return true;
var player = Main.player[projectile.owner];
var playerPosition = player.position.ToTileCoordinates().ToVector2();
Point16 position = Point16.Zero;
float currentDistance = float.MaxValue;
for (int i = 10; i < Main.maxTilesX - 10; i++)
{
for (int j = 10; j < Main.maxTilesY - 10; j++)
{
var tile = Framing.GetTileSafely(i, j);
if (!tile.HasTile || tile.TileType is not TileID.PlanteraBulb ||
tile.TileFrameX is not 18 || tile.TileFrameY is not 18)
continue;
var tilePosition = new Vector2(i, j);
if (StructureDatas.PlanteraPositions.Contains(tilePosition.ToPoint16()))
continue;
var newDistance = tilePosition.Distance(playerPosition);
if (newDistance < currentDistance)
{
currentDistance = newDistance;
position = tilePosition.ToPoint16();
}
}
}
if (onlyJudging)
return position != Point16.Zero;
if (position == Point16.Zero)
{
SyncNotificationKey.Send("Items.PlanteraGlobe.NotFound", Globe.hintTextColor, player.whoAmI);
return false;
}
var module = NetModuleLoader.Get<RevealPlanteraPacket>();
module._position = position;
module.Send(runLocally: true);
if (Main.netMode == NetmodeID.SinglePlayer)
RevealNotification(dummyItem, player.name);
else
RevealBroadcast(dummyItem, player.name);
return true;
}
public static bool RevealEnchantedSword(Projectile projectile, Globe dummyItem, bool onlyJudging)
{
if (Main.netMode is NetmodeID.MultiplayerClient) //此时由服务器进行查找
return true;
var player = Main.player[projectile.owner];
var playerPosition = player.position.ToTileCoordinates().ToVector2();
Point16 position = Point16.Zero;
float currentDistance = float.MaxValue;
for (int i = 10; i < Main.maxTilesX - 10; i++)
{
for (int j = 10; j < Main.maxTilesY - 10; j++)
{
var tile = Framing.GetTileSafely(i, j);
if (!tile.HasTile || tile.TileType is not TileID.LargePiles2 ||
tile.TileFrameX is not 918 || tile.TileFrameY is not 0)
continue;
var tilePosition = new Vector2(i, j);
if (StructureDatas.EnchantedSwordPositions.Contains(tilePosition.ToPoint16()))
continue;
var newDistance = tilePosition.Distance(playerPosition);
if (newDistance < currentDistance)
{
currentDistance = newDistance;
position = tilePosition.ToPoint16();
}
}
}
if (onlyJudging)
return position != Point16.Zero;
if (position == Point16.Zero)
{
SyncNotificationKey.Send("Items.EnchantedSwordGlobe.NotFound", Globe.hintTextColor, player.whoAmI);
return false;
}
var module = NetModuleLoader.Get<RevealEnchantedSwordPacket>();
module._position = position;
module.Send(runLocally: true);
if (Main.netMode == NetmodeID.SinglePlayer)
RevealNotification(dummyItem, player.name);
else
RevealBroadcast(dummyItem, player.name);
return true;
}
//这两个都是生成时查找,一次解锁一个
public static bool RevealMarble(Projectile projectile, Globe dummyItem, bool onlyJudging)
{
if (StructureDatas.AllMarbleCavePositions.Count <= StructureDatas.MarbleCavePositions.Count)//没有判定0的必要,因为如果是0一定满足这个
{
if (!onlyJudging && projectile.owner == Main.myPlayer)
{
if (!StructureDatas.QotEanbledInWorldGeneration)
NoDataNotification(dummyItem);
else
NotFoundNotification(dummyItem);
}
return false;
}
if (onlyJudging)
return true;
StructureDatas.MarbleCavePositions.Add(StructureDatas.AllMarbleCavePositions
.Except(StructureDatas.MarbleCavePositions)
.MinBy(position => projectile.Center.Distance(position.ToVector2() * 16)));
var playerName = Main.player[projectile.owner].name;
if (projectile.owner == Main.myPlayer)
RevealNotification(dummyItem, playerName);
if (Main.netMode == NetmodeID.Server)
RevealBroadcast(dummyItem, playerName);
return true;
}
public static bool RevealGranite(Projectile projectile, Globe dummyItem, bool onlyJudging)
{
if (StructureDatas.AllGraniteCavePositions.Count <= StructureDatas.GraniteCavePositions.Count)//没有判定0的必要,因为如果是0一定满足这个
{
if (!onlyJudging && projectile.owner == Main.myPlayer)
{
if (!StructureDatas.QotEanbledInWorldGeneration)
NoDataNotification(dummyItem);
else
NotFoundNotification(dummyItem);
}
return false;
}
if (onlyJudging)
return true;
StructureDatas.GraniteCavePositions.Add(StructureDatas.AllGraniteCavePositions
.Except(StructureDatas.GraniteCavePositions)
.MinBy(position => projectile.Center.Distance(position.ToVector2() * 16)));
var playerName = Main.player[projectile.owner].name;
if (projectile.owner == Main.myPlayer)
RevealNotification(dummyItem, playerName);
if (Main.netMode == NetmodeID.Server)
RevealBroadcast(dummyItem, playerName);
return true;
}
//这里都是生成时查找,一次解锁完毕,有对于生成时数据未记录的额外查找处理
public static bool RevealOnceForAll(Projectile projectile, Globe dummyItem, bool onlyJudging)
{
var onceForAll = projectile.ModProjectile as IOnceForAllGlobeProj;
bool extraChecked = false;
//这一遍是看看世界数据有没有记录
if ((!StructureDatas.QotEanbledInWorldGeneration || onceForAll.NotFoundCheck()) && Main.netMode != NetmodeID.MultiplayerClient)
{
//没有就当场另作检测
onceForAll.ExtraCheckWhenNotRecorded();
extraChecked = true;
}
//你要再没我也没办法了
if (onceForAll.NotFoundCheck())
{
if (!onlyJudging && projectile.owner == Main.myPlayer)
{
if (StructureDatas.QotEanbledInWorldGeneration)
NotFoundNotification(dummyItem);
else
NoDataNotification(dummyItem);
}
return false;
}
if (StructureDatas.StructuresUnlocked[(byte)onceForAll.StructureType])
{
if (!onlyJudging && projectile.owner == Main.myPlayer)
AlreadyRevealedNotification(dummyItem);
return false;
}
if (onlyJudging)
return true;
StructureDatas.StructuresUnlocked[(byte)onceForAll.StructureType] = true;
string name = Main.player[projectile.owner].name;
//多人下只有自己看见弹窗
if (projectile.owner == Main.myPlayer)
RevealNotification(dummyItem, name);
//由服务器发送聊天信息
if (Main.netMode == NetmodeID.Server)
RevealBroadcast(dummyItem, name);
if (extraChecked) //只有额外检测了才有发包的意义
{
var packet = NetModuleLoader.Get<RevealOnceForAllPacket>();
packet._type = onceForAll.StructureType;
packet._position = onceForAll.Positions;
packet._positionAnother = onceForAll.PositionsAnother;
packet.Send(runLocally: true);
}
else
StructureDatas.StructuresUnlocked[(byte)onceForAll.StructureType] = true;
return true;
}
}
| 0 | 0.854364 | 1 | 0.854364 | game-dev | MEDIA | 0.841769 | game-dev | 0.81869 | 1 | 0.81869 |
EvolutionRTS/Evolution-RTS | 1,755 | Scripts/ehbotthud_lus.lua | base, turret, barrel1, firepoint1, firepoint2, dirt, backpack, exhaust1, exhaust2 = piece('base', 'turret', 'barrel1', 'firepoint1', 'firepoint2', 'dirt', 'backpack', 'exhaust1', 'exhaust2')
local SIG_AIM = {}
-- state variables
isMoving = "isMoving"
terrainType = "terrainType"
function script.Create()
StartThread(common.SmokeUnit, {base, turret, barrel1})
StartThread(doYouEvenLift)
end
common = include("headers/common_includes_lus.lua")
function script.StartMoving()
isMoving = true
StartThread(thrust)
end
function script.StopMoving()
isMoving = false
end
function doYouEvenLift()
common.HbotLift()
end
function thrust()
common.DirtTrail()
end
local function RestoreAfterDelay()
Sleep(2000)
Turn(base, y_axis, 0, 5)
Turn(barrel1, x_axis, 0, 5)
end
function script.AimFromWeapon(weaponID)
--Spring.Echo("AimFromWeapon: FireWeapon")
return turret
end
local firepoints = {firepoint1, firepoint2}
local currentFirepoint = 1
function script.QueryWeapon(weaponID)
return firepoints[currentFirepoint]
end
function script.FireWeapon(weaponID)
currentFirepoint = 3 - currentFirepoint
EmitSfx (firepoints[currentFirepoint], 1024)
end
function script.AimWeapon(weaponID, heading, pitch)
Signal(SIG_AIM)
SetSignalMask(SIG_AIM)
Turn(base, y_axis, heading, 100)
Turn(barrel1, x_axis, -pitch, 100)
WaitForTurn(base, y_axis)
WaitForTurn(barrel1, x_axis)
StartThread(RestoreAfterDelay)
--Spring.Echo("AimWeapon: FireWeapon")
return true
end
function script.Killed()
Explode(barrel1, SFX.EXPLODE_ON_HIT)
Explode(turret, SFX.EXPLODE_ON_HIT)
Explode(base, SFX.EXPLODE_ON_HIT)
Explode(backpack, SFX.EXPLODE_ON_HIT)
return 1 -- spawn ARMSTUMP_DEAD corpse / This is the equivalent of corpsetype = 1; in bos
end | 0 | 0.916464 | 1 | 0.916464 | game-dev | MEDIA | 0.986113 | game-dev | 0.5293 | 1 | 0.5293 |
ProjectIgnis/CardScripts | 2,536 | official/c90050480.lua | --E HERO コズモ・ネオス
--Elemental HERO Cosmo Neos
--Scripted by AlphaKretin
local s,id=GetID()
function s.initial_effect(c)
--fusion material
c:EnableReviveLimit()
Fusion.AddProcMixN(c,false,false,CARD_NEOS,1,s.ffilter,3)
Fusion.AddContactProc(c,s.contactfil,s.contactop,s.splimit)
--no activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(s.nacon)
e1:SetTarget(s.natg)
e1:SetOperation(s.naop)
c:RegisterEffect(e1)
--neos return
aux.EnableNeosReturn(c,CATEGORY_DESTROY,s.desinfo,s.desop)
end
s.listed_names={CARD_NEOS}
s.material_setcode={SET_HERO,SET_ELEMENTAL_HERO,SET_NEOS,SET_NEO_SPACIAN}
function s.ffilter(c,fc,sumtype,tp,sub,mg,sg)
return c:IsSetCard(SET_NEO_SPACIAN,fc,sumtype,tp) and c:GetAttribute(fc,sumtype,tp)~=0 and (not sg or not sg:IsExists(s.fusfilter,1,c,c:GetAttribute(fc,sumtype,tp),fc,sumtype,tp))
end
function s.fusfilter(c,attr,fc,sumtype,tp)
return c:IsSetCard(SET_NEO_SPACIAN,fc,sumtype,tp) and c:IsAttribute(attr,fc,sumtype,tp) and not c:IsHasEffect(511002961)
end
function s.contactfil(tp)
return Duel.GetMatchingGroup(Card.IsAbleToDeckOrExtraAsCost,tp,LOCATION_ONFIELD,0,nil)
end
function s.contactop(g,tp)
Duel.ConfirmCards(1-tp,g)
Duel.SendtoDeck(g,nil,SEQ_DECKSHUFFLE,REASON_COST|REASON_MATERIAL)
end
function s.splimit(e,se,sp,st)
return not e:GetHandler():IsLocation(LOCATION_EXTRA)
end
function s.nacon(e)
return e:GetHandler():GetSummonLocation()&LOCATION_EXTRA==LOCATION_EXTRA
end
function s.natg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetChainLimit(s.chainlm)
end
function s.chainlm(e,rp,tp)
return tp==rp
end
function s.naop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CLIENT_HINT)
e1:SetDescription(aux.Stringid(id,1))
e1:SetTargetRange(0,1)
e1:SetValue(s.aclimit)
e1:SetReset(RESET_PHASE|PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function s.aclimit(e,re,tp)
return re:GetHandler():IsOnField() or re:IsHasType(EFFECT_TYPE_ACTIVATE)
end
function s.desinfo(e,tp,eg,ep,ev,re,r,rp)
local dg=Duel.GetFieldGroup(tp,0,LOCATION_ONFIELD)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,dg,#dg,0,0)
end
function s.desop(e,tp,eg,ep,ev,re,r,rp)
local dg=Duel.GetFieldGroup(tp,0,LOCATION_ONFIELD)
if #dg>0 then
Duel.Destroy(dg,REASON_EFFECT)
end
end | 0 | 0.938059 | 1 | 0.938059 | game-dev | MEDIA | 0.943195 | game-dev | 0.974765 | 1 | 0.974765 |
BigheadSMZ/Zelda-LA-DX-HD-Updated | 10,702 | ladxhd_game_source_code/InGame/GameObjects/Things/ObjRaft.cs | using Microsoft.Xna.Framework;
using ProjectZ.Base;
using ProjectZ.InGame.GameObjects.Base;
using ProjectZ.InGame.GameObjects.Base.CObjects;
using ProjectZ.InGame.GameObjects.Base.Components;
using ProjectZ.InGame.GameObjects.Base.Components.AI;
using ProjectZ.InGame.Map;
using ProjectZ.InGame.SaveLoad;
using ProjectZ.InGame.Things;
using System;
namespace ProjectZ.InGame.GameObjects.Things
{
public class ObjRaft : GameObject
{
public readonly BodyComponent Body;
private readonly Animator _animator;
private readonly AiComponent _aiComponent;
//private readonly CRectangle _collisionRectangle;
private Vector2 _startPosition;
private Vector2 _targetPosition;
private float _jumpMoveTime;
private float _jumpTime;
private float _jumpCounter;
private bool _isActive;
private bool _wasColliding;
private bool _wasMoved;
public ObjRaft() : base("raft") { }
public ObjRaft(Map.Map map, int posX, int posY, string strActivationKey) : base(map)
{
if (!string.IsNullOrEmpty(strActivationKey))
{
var activationValue = Game1.GameManager.SaveManager.GetString(strActivationKey);
if (activationValue != null && activationValue == "1")
_isActive = true;
}
var offsetY = -5;
EntityPosition = new CPosition(posX + 8, posY + 16 + offsetY + (_isActive ? 16 : 0), 0);
EntitySize = new Rectangle(-8, -16 - offsetY, 16, 16);
//_collisionRectangle = new CRectangle(EntityPosition, new Rectangle(-4, -offsetY - 6, 8, 4));
Body = new BodyComponent(EntityPosition, -4, -offsetY - 14, 8, 10, 8)
{
IsActive = false,
IgnoreHeight = true,
IgnoreHoles = true,
IsSlider = true,
Gravity = -0.2f,
MoveCollision = OnMoveCollision,
CollisionTypes = Values.CollisionTypes.Normal | Values.CollisionTypes.RaftExit,
};
_aiComponent = new AiComponent();
_aiComponent.States.Add("idle", new AiState(UpdateIdle));
_aiComponent.States.Add("moving", new AiState(UpdateMoving));
_aiComponent.ChangeState("idle");
_animator = AnimatorSaveLoad.LoadAnimator("Objects/raft");
_animator.Play(_isActive ? "water" : "idle");
var _sprite = new CSprite(EntityPosition);
var animationComponent = new AnimationComponent(_animator, _sprite, new Vector2(-8, -offsetY - 15));
AddComponent(AiComponent.Index, _aiComponent);
AddComponent(BodyComponent.Index, Body);
AddComponent(BaseAnimationComponent.Index, animationComponent);
AddComponent(DrawComponent.Index, new DrawCSpriteComponent(_sprite, Values.LayerBottom));
AddComponent(CollisionComponent.Index,
new BoxCollisionComponent(new CBox(EntityPosition, -8, -16 - offsetY, -8, 16, 16, 8), Values.CollisionTypes.Normal));
if (!_isActive)
AddComponent(CollisionComponent.Index, new BoxCollisionComponent(
new CBox(EntityPosition, -8, -offsetY - 1, 16, 1, 8), Values.CollisionTypes.Normal | Values.CollisionTypes.ThrowWeaponIgnore));
}
public override void Init()
{
if (_isActive)
ToggleWater();
}
// toggle the water field state
private void ToggleWater()
{
var fieldX = (int)EntityPosition.X / 16;
var fieldY = (int)EntityPosition.Y / 16;
var oldState = Map.GetFieldState(fieldX, fieldY);
Map.SetFieldState(fieldX, fieldY, oldState ^ MapStates.FieldStates.DeepWater);
}
private void OnMoveCollision(Values.BodyCollision collision)
{
// align with the raft exit
var offset = Vector2.Zero;
if ((collision & Values.BodyCollision.Left) != 0)
offset.X -= 1;
if ((collision & Values.BodyCollision.Right) != 0)
offset.X += 1;
if ((collision & Values.BodyCollision.Top) != 0)
offset.Y -= 1;
if ((collision & Values.BodyCollision.Bottom) != 0)
offset.Y += 1;
var box = Body.BodyBox.Box;
box.X += offset.X;
box.Y += offset.Y;
var outBox = Box.Empty;
Map.Objects.Collision(box, box, Values.CollisionTypes.RaftExit, 0, 0, ref outBox);
if (outBox != Box.Empty)
{
var exitCenter = outBox.Center;
var direction = exitCenter - EntityPosition.Position;
var alignSpeed = 0.5f * Game1.TimeMultiplier;
var maxAlignDist = 6;
// align horizontally or vertically
if ((collision & Values.BodyCollision.Vertical) != 0)
{
Body.AdditionalMovementVT = Vector2.Zero;
Body.LastAdditionalMovementVT = Vector2.Zero;
if (alignSpeed < Math.Abs(direction.X) && Math.Abs(direction.X) < maxAlignDist)
Body.SlideOffset.X = Math.Sign(direction.X) * alignSpeed;
else if (Math.Abs(direction.X) < maxAlignDist)
{
EntityPosition.Set(new Vector2(exitCenter.X, EntityPosition.Y));
ExitRaft();
}
}
else if ((collision & Values.BodyCollision.Horizontal) != 0)
{
Body.AdditionalMovementVT = Vector2.Zero;
Body.LastAdditionalMovementVT = Vector2.Zero;
if (alignSpeed < Math.Abs(direction.Y) && Math.Abs(direction.Y) < maxAlignDist)
Body.SlideOffset.Y = Math.Sign(direction.Y) * alignSpeed;
else if (Math.Abs(direction.Y) < maxAlignDist)
{
EntityPosition.Set(new Vector2(EntityPosition.X, exitCenter.Y));
ExitRaft();
}
}
}
}
public void TargetVelocity(Vector2 direction)
{
var targetDir = direction - Body.VelocityTarget;
if (targetDir.Length() > 0.1f * Game1.TimeMultiplier)
{
targetDir.Normalize();
Body.VelocityTarget += targetDir * 0.1f * Game1.TimeMultiplier;
}
else
{
Body.VelocityTarget = direction;
}
_wasMoved = true;
}
public void Jump(Vector2 targetPosition, int time)
{
targetPosition.Y -= 7;
_startPosition = EntityPosition.Position;
_targetPosition = targetPosition;
var percentage = (targetPosition.Y - _startPosition.Y) / 80;
_jumpMoveTime = 150;// * percentage;
_jumpTime = 1000 * percentage;
_jumpCounter = 0;
Body.IsActive = false;
Body.VelocityTarget = Vector2.Zero;
MapManager.ObjLink._body.IsGrounded = false;
MapManager.ObjLink._body.IsActive = false;
}
private void UpdateIdle()
{
var distance = MapManager.ObjLink.EntityPosition.Position - new Vector2(EntityPosition.X, EntityPosition.Y + 1);
// Use a zone large enough players can't clip off the raft or jump over it.
var isColliding = Math.Abs(distance.X) <= 4 && Math.Abs(distance.Y) <= 2;
if (_isActive && isColliding && !_wasColliding)
EnterRaft();
_wasColliding = isColliding;
}
private void UpdateMoving()
{
if (!_wasMoved)
TargetVelocity(Vector2.Zero);
_wasMoved = false;
// jump
if (_jumpTime > 0)
{
var lastJumpCounter = _jumpCounter;
_jumpCounter += Game1.DeltaTime;
// finished jumping?
if (MapManager.ObjLink._body.IsGrounded || _jumpCounter > _jumpTime)
{
_jumpTime = 0;
EntityPosition.Set(_targetPosition);
Map.CameraTarget = null;
}
else
{
var percentage = MathHelper.Clamp(_jumpCounter / _jumpMoveTime, 0, 1);
if (_jumpCounter <= _jumpMoveTime)
{
var percentageHeight = _jumpCounter / _jumpMoveTime;
var posZ = MathF.Sin(percentageHeight * MathF.PI * 0.5f);
EntityPosition.Z = posZ * 12 + percentage * (_targetPosition.Y - _startPosition.Y);
MapManager.ObjLink.EntityPosition.Z = posZ * 16 + percentage * (_targetPosition.Y - _startPosition.Y);
}
else if (lastJumpCounter <= _jumpMoveTime)
{
MapManager.ObjLink._body.IsActive = true;
Body.IsActive = true;
}
Map.CameraTarget = new Vector2(MapManager.ObjLink.EntityPosition.X, MapManager.ObjLink.EntityPosition.Y - MapManager.ObjLink.EntityPosition.Z);
var newPosition = Vector2.Lerp(_startPosition, _targetPosition, percentage);
EntityPosition.Set(newPosition);
}
}
}
private void EnterRaft()
{
ToggleWater();
Body.IsActive = true;
Body.VelocityTarget = Vector2.Zero;
_aiComponent.ChangeState("moving");
EntityPosition.AddPositionListener(typeof(ObjRaft), OnPositionChange);
((DrawComponent)Components[DrawComponent.Index]).Layer = Values.LayerPlayer;
MapManager.ObjLink.StartRaftRiding(this);
}
private void ExitRaft()
{
ToggleWater();
Body.IsActive = false;
Body.VelocityTarget = Vector2.Zero;
_aiComponent.ChangeState("idle");
EntityPosition.RemovePositionListener(typeof(ObjRaft));
((DrawComponent)Components[DrawComponent.Index]).Layer = Values.LayerBottom;
MapManager.ObjLink.ExitRaft();
}
private void OnPositionChange(CPosition newPosition)
{
MapManager.ObjLink.SetPosition(new Vector2(newPosition.X, newPosition.Y + 1));
}
}
} | 0 | 0.910276 | 1 | 0.910276 | game-dev | MEDIA | 0.983238 | game-dev | 0.991108 | 1 | 0.991108 |
focus-creative-games/luban_examples | 1,662 | Projects/CfgValidator/Gen/ai/Selector.cs |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Luban;
using System.Text.Json;
namespace cfg.ai
{
public sealed partial class Selector : ai.ComposeNode
{
public Selector(JsonElement _buf) : base(_buf)
{
{ var __json0 = _buf.GetProperty("children"); Children = new System.Collections.Generic.List<ai.FlowNode>(__json0.GetArrayLength()); foreach(JsonElement __e0 in __json0.EnumerateArray()) { ai.FlowNode __v0; __v0 = ai.FlowNode.DeserializeFlowNode(__e0); Children.Add(__v0); } }
}
public static Selector DeserializeSelector(JsonElement _buf)
{
return new ai.Selector(_buf);
}
public readonly System.Collections.Generic.List<ai.FlowNode> Children;
public const int __ID__ = -1946981627;
public override int GetTypeId() => __ID__;
public override void ResolveRef(Tables tables)
{
base.ResolveRef(tables);
foreach (var _e in Children) { _e?.ResolveRef(tables); }
}
public override string ToString()
{
return "{ "
+ "id:" + Id + ","
+ "nodeName:" + NodeName + ","
+ "decorators:" + Luban.StringUtil.CollectionToString(Decorators) + ","
+ "services:" + Luban.StringUtil.CollectionToString(Services) + ","
+ "children:" + Luban.StringUtil.CollectionToString(Children) + ","
+ "}";
}
}
}
| 0 | 0.860452 | 1 | 0.860452 | game-dev | MEDIA | 0.756994 | game-dev | 0.865597 | 1 | 0.865597 |
maxuser0/minescript | 1,670 | common/src/main/java/net/minescript/common/mixin/KeyMappingMixin.java | // SPDX-FileCopyrightText: © 2022-2025 Greg Christiana <maxuser@minescript.net>
// SPDX-License-Identifier: GPL-3.0-only
package net.minescript.common.mixin;
import com.mojang.blaze3d.platform.InputConstants;
import net.minecraft.client.KeyMapping;
import net.minescript.common.Minescript;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(KeyMapping.class)
public abstract class KeyMappingMixin {
@Shadow
public abstract String getName();
// TODO(maxuser): Clicking the button in the Key Binds screen to reset all bindings does not
// trigger setKey(...) below, but it seems it should since KeyBindsScreen.init() calls
// `keyMapping.setKey(keyMapping.getDefaultKey())` for all key mappings. The workaround is to
// restart Minecraft after clicking the "reset all" button so that Minescript has up-to-date key
// bindings.
@Inject(
at = @At("TAIL"),
method =
"<init>(Ljava/lang/String;Lcom/mojang/blaze3d/platform/InputConstants$Type;ILnet/minecraft/client/KeyMapping$Category;)V")
public void init(
String name,
InputConstants.Type type,
int keyCode,
KeyMapping.Category category,
CallbackInfo ci) {
Minescript.setKeyBind(name, type.getOrCreate(keyCode));
}
@Inject(at = @At("HEAD"), method = "setKey(Lcom/mojang/blaze3d/platform/InputConstants$Key;)V")
public void setKey(InputConstants.Key key, CallbackInfo ci) {
Minescript.setKeyBind(this.getName(), key);
}
}
| 0 | 0.874722 | 1 | 0.874722 | game-dev | MEDIA | 0.900669 | game-dev | 0.931192 | 1 | 0.931192 |
kool-engine/kool | 4,168 | kool-editor-model/src/commonMain/kotlin/de/fabmax/kool/editor/components/BehaviorComponent.kt | package de.fabmax.kool.editor.components
import de.fabmax.kool.editor.api.*
import de.fabmax.kool.editor.data.*
import de.fabmax.kool.modules.ui2.mutableStateOf
import de.fabmax.kool.pipeline.RenderPass
import de.fabmax.kool.util.logE
class BehaviorComponent(
gameEntity: GameEntity,
componentInfo: ComponentInfo<BehaviorComponentData>
) : GameEntityDataComponent<BehaviorComponentData>(gameEntity, componentInfo) {
override val componentType: String = "${this::class.simpleName}<${data.behaviorClassName}>"
val behaviorInstance = mutableStateOf<KoolBehavior?>(null)
private val EntityId.gameEntity: GameEntity? get() {
return this@BehaviorComponent.gameEntity.scene.sceneEntities[this]
}
init {
componentOrder = COMPONENT_ORDER_LATE
}
override suspend fun applyComponent() {
checkDependencies()
var allOk = true
try {
val behavior = BehaviorLoader.newInstance(data.behaviorClassName)
behaviorInstance.set(behavior)
// set script member properties from componentData, remove them in case they don't exist anymore (e.g.
// because script has changed)
val removeProps = mutableListOf<String>()
data.propertyValues.forEach { (name, value) ->
val setValue = when {
value.gameEntityRef != null -> {
val entity = value.gameEntityRef.gameEntity
if (!entity.isNullOrPrepared) {
allOk = false
}
entity
}
value.componentRef != null -> {
val entity = value.componentRef.entityId.gameEntity
if (!entity.isNullOrPrepared) {
allOk = false
}
entity?.getComponent(value.componentRef)
}
value.behaviorRef != null -> {
val entity = value.behaviorRef.entityId.gameEntity
if (!entity.isNullOrPrepared) {
allOk = false
}
entity?.getBehavior(value.behaviorRef)
}
else -> value.get()
}
if (!setProperty(name, setValue)) {
removeProps += name
}
}
if (removeProps.isNotEmpty()) {
setPersistent(data.copy(propertyValues = data.propertyValues - removeProps))
}
} catch (e: Exception) {
logE { "Failed to initialize BehaviorComponent in entity ${gameEntity.id}('${gameEntity.name}'): $e" }
e.printStackTrace()
}
if (allOk) {
lifecycle = EntityLifecycle.PREPARED
behaviorInstance.value?.init(this)
}
}
private val GameEntity?.isNullOrPrepared: Boolean get() = this == null || isPreparedOrRunning
override fun onStart() {
super.onStart()
behaviorInstance.value?.onStart()
}
override fun onUpdate(ev: RenderPass.UpdateEvent) {
val instance = behaviorInstance.value ?: return
if (AppState.appMode == AppMode.PLAY || instance.isUpdateInEditMode) {
instance.onUpdate(ev)
}
}
override fun onPhysicsUpdate(timeStep: Float) {
behaviorInstance.value?.onPhysicsUpdate(timeStep)
}
override fun destroyComponent() {
super.destroyComponent()
behaviorInstance.value?.onDestroy()
}
fun setProperty(name: String, value: Any?): Boolean {
return try {
behaviorInstance.value?.let { BehaviorLoader.setProperty(it, name, value) }
true
} catch (e: Exception) {
logE { "${data.behaviorClassName}: Failed setting property $name to value $value: $e" }
e.printStackTrace()
false
}
}
fun getProperty(name: String): Any? {
return behaviorInstance.value?.let { BehaviorLoader.getProperty(it, name) }
}
} | 0 | 0.881698 | 1 | 0.881698 | game-dev | MEDIA | 0.977828 | game-dev | 0.901067 | 1 | 0.901067 |
lfzawacki/musical-artifacts | 1,393 | app/views/artifacts/_artifact_list.html.haml | - if artifacts.empty?
.artifact-item.empty-search
%p
= t('.none')
= t('.return_html', path: artifacts_path())
- artifacts.in_groups_of(per_row, false).each do |group|
%div{class: "#{'row' if per_row > 1}"}
- group.each do |artifact|
- if per_row.present? && per_row > 0
- col_class = "col-sm-#{12 / per_row}"
.artifact-item{class: "#{cycle('dark', 'light')}-item #{col_class}"}
- # If the artifact is new to the user, put a little ribbon on it
= render 'artifacts/new_artifact_ribbon', artifact: artifact
= render "artifacts/side_buttons", artifact: artifact
.artifact-name-wrapper
%h2.artifact-name
= link_to artifact.name, artifact
%span
= render "artifacts/created_by", artifact: artifact
.artifact-description
-if artifact.description.present?
= strip_tags(artifact.description_html).truncate(480)
- else
.no-description= t('artifacts.show.no_description')
%p.more-info
= link_to t('.more_info'), artifact_path(artifact)
.artifact-tags
= render 'artifacts/artifact_tags', artifact: artifact
.artifact-license
= render 'artifacts/license', artifact: artifact, small: true
= render partial: 'artifacts/buttons', locals: { artifact: artifact }
| 0 | 0.659497 | 1 | 0.659497 | game-dev | MEDIA | 0.333411 | game-dev | 0.63664 | 1 | 0.63664 |
Keepsie/HS-Stride-Packer | 12,000 | HS-Stride-Package-Manager/HS.Stride.PackageManager.Core/Core/ResourcePathValidator.cs | // HS Stride Packer (c) 2025 Happenstance Games LLC - Apache License 2.0
using System.Text.RegularExpressions;
namespace HS.Stride.Packer.Core
{
public class ResourcePathValidator
{
public ValidationResult ValidateProject(string projectPath)
{
var result = new ValidationResult();
if (string.IsNullOrEmpty(projectPath) || !Directory.Exists(projectPath))
return result;
var allAssets = Directory.GetFiles(projectPath, "*.sd*", SearchOption.AllDirectories);
foreach (var assetFile in allAssets)
{
var resourceRefs = ScanForResourceReferences(assetFile);
foreach (var resourceRef in resourceRefs)
{
ValidateResourcePath(assetFile, resourceRef, projectPath, result);
}
}
return result;
}
public ValidationResult ValidateAndCollectDependencies(string projectPath, List<string> selectedAssetFolders)
{
var result = new ValidationResult();
if (string.IsNullOrEmpty(projectPath) || !Directory.Exists(projectPath))
return result;
// Only scan the selected asset folders, not the entire project
foreach (var assetFolderPath in selectedAssetFolders)
{
var fullAssetPath = Path.Combine(projectPath, assetFolderPath);
if (!Directory.Exists(fullAssetPath))
continue;
// Find all Stride asset files in this folder
var assetFiles = Directory.GetFiles(fullAssetPath, "*.sd*", SearchOption.AllDirectories)
.ToList();
foreach (var assetFile in assetFiles)
{
var resourceRefs = ScanForResourceReferencesEnhanced(assetFile);
foreach (var resourceRef in resourceRefs)
{
ValidateAndCollectResourcePath(assetFile, resourceRef, projectPath, result);
}
}
}
return result;
}
//Private
private List<ResourceReference> ScanForResourceReferences(string filePath)
{
if (!File.Exists(filePath))
return new List<ResourceReference>();
var content = File.ReadAllText(filePath);
var references = new List<ResourceReference>();
// Fixed regex pattern to find !file references - capture until end of line or next !
var fileRefRegex = new Regex(@"!file\s+(.+?)(?:\r?\n|!|$)");
var matches = fileRefRegex.Matches(content);
foreach (Match match in matches)
{
var resourcePath = match.Groups[1].Value.Trim();
references.Add(new ResourceReference
{
AssetFile = filePath,
ResourcePath = resourcePath,
LineNumber = GetLineNumber(content, match.Index),
Type = ResourceReferenceType.FileReference
});
}
return references;
}
private void ValidateResourcePath(string assetFile, ResourceReference resourceRef,
string projectPath, ValidationResult result)
{
var assetDir = Path.GetDirectoryName(assetFile);
if (assetDir == null) return;
var fullResourcePath = Path.GetFullPath(Path.Combine(assetDir, resourceRef.ResourcePath));
var projectFullPath = Path.GetFullPath(projectPath);
if (!fullResourcePath.StartsWith(projectFullPath, StringComparison.OrdinalIgnoreCase))
{
result.ExternalResources.Add(new ExternalResourceIssue
{
AssetFile = assetFile,
ResourcePath = resourceRef.ResourcePath
});
}
else if (!File.Exists(fullResourcePath))
{
result.MissingResources.Add(new MissingResourceIssue
{
AssetFile = assetFile,
ResourcePath = resourceRef.ResourcePath
});
}
}
private List<ResourceReference> ScanForResourceReferencesEnhanced(string filePath)
{
if (!File.Exists(filePath))
return new List<ResourceReference>();
var content = File.ReadAllText(filePath);
var references = new List<ResourceReference>();
// Pattern 1: !file "any/path/to/resource.ext"
var filePattern = @"!file\s+""([^""]+)""";
var fileMatches = Regex.Matches(content, filePattern);
foreach (Match match in fileMatches)
{
var resourcePath = match.Groups[1].Value;
references.Add(new ResourceReference
{
AssetFile = filePath,
ResourcePath = resourcePath,
LineNumber = GetLineNumber(content, match.Index),
Type = ResourceReferenceType.FileReference
});
}
// Pattern 2: Source: any/path/resource.ext
var sourcePattern = @"Source:\s*([^\r\n]+)";
var sourceMatches = Regex.Matches(content, sourcePattern);
foreach (Match match in sourceMatches)
{
var sourcePath = match.Groups[1].Value.Trim();
references.Add(new ResourceReference
{
AssetFile = filePath,
ResourcePath = sourcePath,
LineNumber = GetLineNumber(content, match.Index),
Type = ResourceReferenceType.SourceReference
});
}
// Pattern 3: Any path containing common resource extensions
var resourceExtensions = new[] { ".png", ".jpg", ".jpeg", ".tga", ".dds", ".fbx", ".obj", ".dae", ".wav", ".ogg", ".mp3" };
foreach (var ext in resourceExtensions)
{
var pattern = $@"""([^""]*{Regex.Escape(ext)})""";
var matches = Regex.Matches(content, pattern, RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
var resourcePath = match.Groups[1].Value;
references.Add(new ResourceReference
{
AssetFile = filePath,
ResourcePath = resourcePath,
LineNumber = GetLineNumber(content, match.Index),
Type = ResourceReferenceType.EmbeddedReference
});
}
}
return references;
}
private void ValidateAndCollectResourcePath(string assetFile, ResourceReference resourceRef, string projectPath, ValidationResult result)
{
// Try to find the actual resource file
var actualResourcePath = FindActualResourceFile(resourceRef.ResourcePath, assetFile, projectPath);
if (!string.IsNullOrEmpty(actualResourcePath))
{
// Find existing dependency for this actual file path
var existingDep = result.ResourceDependencies
.FirstOrDefault(d => d.ActualPath.Equals(actualResourcePath, StringComparison.OrdinalIgnoreCase));
if (existingDep != null)
{
// Add this reference to existing dependency (avoid duplicate resources)
existingDep.References.Add(resourceRef);
}
else
{
// Create new dependency with first reference
var dependency = new ResourceDependency
{
FileName = Path.GetFileName(actualResourcePath),
ActualPath = actualResourcePath,
References = new List<ResourceReference> { resourceRef },
// Legacy properties for backward compatibility
OriginalPath = resourceRef.ResourcePath,
ReferencedInAsset = assetFile,
AssetFilePath = assetFile,
OriginalPathInAsset = resourceRef.ResourcePath
};
result.ResourceDependencies.Add(dependency);
}
// Also do validation
var assetDir = Path.GetDirectoryName(assetFile);
if (assetDir != null)
{
var fullResourcePath = Path.GetFullPath(actualResourcePath);
var projectFullPath = Path.GetFullPath(projectPath);
if (!fullResourcePath.StartsWith(projectFullPath, StringComparison.OrdinalIgnoreCase))
{
result.ExternalResources.Add(new ExternalResourceIssue
{
AssetFile = assetFile,
ResourcePath = resourceRef.ResourcePath
});
}
}
}
else
{
// Resource not found - add to missing resources
result.MissingResources.Add(new MissingResourceIssue
{
AssetFile = assetFile,
ResourcePath = resourceRef.ResourcePath
});
}
}
private string FindActualResourceFile(string resourcePath, string assetFilePath, string projectPath)
{
// Try different ways to resolve the resource path
// 1. Try relative to the asset file
var assetDir = Path.GetDirectoryName(assetFilePath) ?? "";
var relativeToAsset = Path.Combine(assetDir, resourcePath);
if (File.Exists(relativeToAsset))
return Path.GetFullPath(relativeToAsset);
// 2. Try relative to project root
var relativeToProject = Path.Combine(projectPath, resourcePath);
if (File.Exists(relativeToProject))
return Path.GetFullPath(relativeToProject);
// 3. Try as absolute path
if (Path.IsPathRooted(resourcePath) && File.Exists(resourcePath))
return Path.GetFullPath(resourcePath);
// 4. Search in common resource locations
var fileName = Path.GetFileName(resourcePath);
var searchPaths = new[]
{
Path.Combine(projectPath, "Resources"),
Path.Combine(projectPath, "Assets", "Resources"),
Path.Combine(projectPath, "Assets"),
projectPath
};
foreach (var searchPath in searchPaths)
{
if (Directory.Exists(searchPath))
{
var foundFile = Directory.GetFiles(searchPath, fileName, SearchOption.AllDirectories)
.FirstOrDefault();
if (foundFile != null)
return foundFile;
}
}
return string.Empty;
}
private static int GetLineNumber(string content, int position)
{
if (position < 0 || position >= content.Length)
return 1;
return content.Take(position).Count(c => c == '\n') + 1;
}
}
}
| 0 | 0.908094 | 1 | 0.908094 | game-dev | MEDIA | 0.52498 | game-dev | 0.932445 | 1 | 0.932445 |
Robosturm/Commander_Wars | 4,228 | resources/scripts/units/ZCOUNIT_COMMANDO.js | var Constructor = function()
{
this.getUnitDamageID = function(unit)
{
return "MECH";
};
this.init = function(unit)
{
unit.setAmmo1(3);
unit.setMaxAmmo1(3);
unit.setWeapon1ID("WEAPON_BAZOOKA");
unit.setAmmo2(10);
unit.setMaxAmmo2(10);
unit.setWeapon2ID("WEAPON_RECON_MG");
unit.setFuel(100);
unit.setMaxFuel(100);
unit.setBaseMovementPoints(4);
unit.setMinRange(1);
unit.setMaxRange(1);
unit.setVision(3);
};
this.getBaseCost = function()
{
return 5000;
};
this.loadSprites = function(unit)
{
unit.loadSpriteV2("commando+mask", GameEnums.Recoloring_Matrix);
};
this.getMovementType = function()
{
return "MOVE_MECH";
};
this.actionList = ["ACTION_FIRE", "ACTION_MISSILE", "ACTION_CAPTURE", "ACTION_JOIN", "ACTION_LOAD", "ACTION_WAIT", "ACTION_CO_UNIT_0", "ACTION_CO_UNIT_1"];
this.doWalkingAnimation = function(action, map)
{
var unit = action.getTargetUnit();
var animation = GameAnimationFactory.createWalkingAnimation(map, unit, action);
animation.loadSpriteV2("commando+walk+mask", GameEnums.Recoloring_Matrix, 2);
animation.setSound("moveboots.wav", -2);
return animation;
};
this.getName = function()
{
return qsTr("Commando");
};
this.canMoveAndFire = function()
{
return true;
};
this.getDescription = function()
{
return qsTr("<r>High attack power. Can </r><div c='#00ff00'>capture </div><r> bases. </r><div c='#00ff00'>Vision +3 </div><r> when on mountains and gets cloaked in addition.</r> Moving out of a mountain removes any cloaks from the Commando unit.");
};
this.getUnitType = function()
{
return GameEnums.UnitType_Infantry;
};
this.startOfTurn = function(unit, map)
{
ZCOUNIT_COMMANDO.cloak(unit, map);
};
this.cloak = function(unit, map)
{
var terrain = unit.getTerrain();
if (terrain !== null)
{
var terrainId = terrain.getID();
if (terrainId === "MOUNTAIN" ||
terrainId === "SNOW_MOUNTAIN" ||
terrainId === "DESERT_ROCK" ||
terrainId === "WASTE_MOUNTAIN")
{
var cloaked = unit.getCloaked();
unit.setCloaked(1);
var cloakedNow = unit.getCloaked();
if (cloaked !== cloakedNow)
{
var animationCount = GameAnimationFactory.getAnimationCount();
var queueAnimation = null;
if (animationCount > 0)
{
queueAnimation = GameAnimationFactory.getAnimation(animationCount - 1);
}
var animation = GameAnimationFactory.createAnimation(map, unit.getX(), unit.getY());
animation.addSprite("stealth", -map.getImageSize() / 2, -map.getImageSize() / 2, 0, 2);
animation.setSound("stealth.wav", 1);
if (queueAnimation !== null)
{
queueAnimation.queueAnimation(animation);
}
}
}
else
{
var cloaked = unit.getCloaked();
unit.removeCloaked();
var cloakedNow = unit.getCloaked();
if (cloaked !== cloakedNow)
{
var animation = GameAnimationFactory.createAnimation(map, unit.getX(), unit.getY());
animation.addSprite("stealth", -map.getImageSize() / 2, -map.getImageSize() / 2, 0, 2);
animation.setSound("unstealth.wav", 1);
}
}
}
};
this.postAction = function(unit, action, map)
{
ZCOUNIT_COMMANDO.cloak(unit, map);
};
this.getCOSpecificUnit = function(building)
{
return true;
};
this.getEditorPlacementSound = function()
{
return "moveboots.wav";
};
}
Constructor.prototype = UNIT;
var ZCOUNIT_COMMANDO = new Constructor();
| 0 | 0.871392 | 1 | 0.871392 | game-dev | MEDIA | 0.989545 | game-dev | 0.902589 | 1 | 0.902589 |
exmex/KingdomRushFrontiers | 2,380 | cocos2d/cocos/2d/CCTMXObjectGroup.cpp | /****************************************************************************
Copyright (c) 2010 Neophit
Copyright (c) 2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
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 "2d/CCTMXObjectGroup.h"
#include "base/ccMacros.h"
NS_CC_BEGIN
//implementation TMXObjectGroup
TMXObjectGroup::TMXObjectGroup()
: _groupName("")
{
}
TMXObjectGroup::~TMXObjectGroup()
{
CCLOGINFO("deallocing TMXObjectGroup: %p", this);
}
ValueMap TMXObjectGroup::getObject(const std::string& objectName) const
{
if (!_objects.empty())
{
for (const auto& v : _objects)
{
const ValueMap& dict = v.asValueMap();
if (dict.find("name") != dict.end())
{
if (dict.at("name").asString() == objectName)
return dict;
}
}
}
// object not found
return ValueMap();
}
Value TMXObjectGroup::getProperty(const std::string& propertyName) const
{
if (_properties.find(propertyName) != _properties.end())
return _properties.at(propertyName);
return Value();
}
NS_CC_END
| 0 | 0.746346 | 1 | 0.746346 | game-dev | MEDIA | 0.541659 | game-dev | 0.783373 | 1 | 0.783373 |
InfernumTeam/InfernumMode | 27,750 | Content/BehaviorOverrides/BossAIs/KingSlime/KingSlimeBehaviorOverride.cs | using System;
using System.Collections.Generic;
using CalamityMod.Buffs.StatDebuffs;
using CalamityMod.Events;
using CalamityMod.NPCs.NormalNPCs;
using CalamityMod.Particles;
using InfernumMode.Assets.Sounds;
using InfernumMode.Common.Graphics.Particles;
using InfernumMode.Common.Worldgen;
using InfernumMode.Content.Projectiles.Pets;
using InfernumMode.Core.GlobalInstances.Systems;
using InfernumMode.Core.OverridingSystem;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.Audio;
using Terraria.GameContent;
using Terraria.ID;
using Terraria.ModLoader;
using Terraria.WorldBuilding;
namespace InfernumMode.Content.BehaviorOverrides.BossAIs.KingSlime
{
public class KingSlimeBehaviorOverride : NPCBehaviorOverride
{
public override int NPCOverrideType => NPCID.KingSlime;
#region Enumerations
public enum KingSlimeAttackType
{
SmallJump,
LargeJump,
SlamJump,
Teleport,
}
#endregion
#region AI
public static int ShurikenDamage => 65;
public static int JewelBeamDamage => 70;
public static readonly KingSlimeAttackType[] AttackPattern =
[
KingSlimeAttackType.SmallJump,
KingSlimeAttackType.SmallJump,
KingSlimeAttackType.LargeJump,
KingSlimeAttackType.Teleport,
KingSlimeAttackType.LargeJump,
];
public const float Phase2LifeRatio = 0.75f;
public const float Phase3LifeRatio = 0.3f;
public const float DespawnDistance = 4700f;
public const float MaxScale = 2.3f;
public const float MinScale = 1.1f;
public static Vector2 HitboxScaleFactor => new(128f, 88f);
public override float[] PhaseLifeRatioThresholds =>
[
Phase2LifeRatio,
Phase3LifeRatio
];
public override bool PreAI(NPC npc)
{
// Select a new target if an old one was lost.
npc.TargetClosestIfTargetIsInvalid();
Player target = Main.player[npc.target];
npc.direction = (target.Center.X > npc.Center.X).ToDirectionInt();
npc.damage = npc.defDamage - 15;
npc.dontTakeDamage = false;
npc.noTileCollide = false;
ref float attackTimer = ref npc.ai[2];
ref float hasSummonedNinjaFlag = ref npc.localAI[0];
ref float jewelSummonTimer = ref npc.localAI[1];
ref float teleportDirection = ref npc.Infernum().ExtraAI[5];
ref float deathTimer = ref npc.Infernum().ExtraAI[6];
ref float stuckTimer = ref npc.Infernum().ExtraAI[7];
float lifeRatio = npc.life / (float)npc.lifeMax;
// Constantly give the target Weak Pertrification in boss rush.
if (Main.netMode != NetmodeID.Server && BossRushEvent.BossRushActive)
{
if (!target.dead && target.active)
target.AddBuff(ModContent.BuffType<WeakPetrification>(), 15);
}
// Despawn if the target is gone or too far away.
if (!Main.player[npc.target].active || Main.player[npc.target].dead || !npc.WithinRange(Main.player[npc.target].Center, DespawnDistance))
{
npc.TargetClosest();
if (!Main.player[npc.target].active || Main.player[npc.target].dead)
{
DoBehavior_Despawn(npc);
return false;
}
}
else
npc.timeLeft = 3600;
float oldScale = npc.scale;
float idealScale = Lerp(MaxScale, MinScale, 1f - lifeRatio);
npc.scale = idealScale;
if (npc.localAI[2] == 0f)
{
npc.timeLeft = 3600;
npc.localAI[2] = 1f;
}
// Disable natural despawning.
npc.Infernum().DisableNaturalDespawning = true;
if (npc.life < npc.lifeMax * Phase3LifeRatio && hasSummonedNinjaFlag == 0f)
{
HatGirl.SayThingWhileOwnerIsAlive(target, "Mods.InfernumMode.PetDialog.KingSlimeNinjaTip");
if (Main.netMode != NetmodeID.MultiplayerClient)
{
NPC.NewNPC(npc.GetSource_FromAI(), (int)npc.Center.X, (int)npc.Center.Y, ModContent.NPCType<Ninja>());
hasSummonedNinjaFlag = 1f;
npc.netUpdate = true;
}
}
// Summon the jewel for the first time when King Slime enters the first phase. This waits until King Slime isn't teleporting to happen.
if (npc.life < npc.lifeMax * Phase2LifeRatio && jewelSummonTimer == 0f && npc.scale >= 0.8f)
{
Vector2 jewelSpawnPosition = target.Center - Vector2.UnitY * 350f;
SoundEngine.PlaySound(SoundID.Item67, target.Center);
Dust.QuickDustLine(npc.Top + Vector2.UnitY * 60f, jewelSpawnPosition, 150f, Color.Red);
HatGirl.SayThingWhileOwnerIsAlive(target, "Mods.InfernumMode.PetDialog.KingSlimeJewelTip");
if (Main.netMode != NetmodeID.MultiplayerClient)
NPC.NewNPC(npc.GetSource_FromAI(), (int)jewelSpawnPosition.X, (int)jewelSpawnPosition.Y, ModContent.NPCType<KingSlimeJewelRuby>());
jewelSummonTimer = 1f;
npc.netUpdate = true;
}
// Resummon the jewel if it's gone and enough time has passed.
if (!NPC.AnyNPCs(ModContent.NPCType<KingSlimeJewelRuby>()) && jewelSummonTimer >= 1f)
{
jewelSummonTimer++;
if (jewelSummonTimer >= 2100f)
{
jewelSummonTimer = 0f;
npc.netUpdate = true;
}
}
// Enforce slightly stronger gravity.
if (npc.velocity.Y > 0f)
{
npc.velocity.Y += Lerp(0.05f, 0.25f, 1f - lifeRatio);
if (BossRushEvent.BossRushActive && npc.velocity.Y > 4f)
npc.position.Y += 4f;
}
if (deathTimer > 0)
{
DoBehavior_DeathAnimation(npc, target, ref deathTimer);
deathTimer++;
return false;
}
if (npc.position.WithinRange(npc.oldPosition, 2f))
{
stuckTimer++;
if (stuckTimer >= 300f)
{
npc.ai[1] = (int)KingSlimeAttackType.Teleport;
stuckTimer = 0f;
npc.netUpdate = true;
}
}
else
stuckTimer = 0f;
switch ((KingSlimeAttackType)(int)npc.ai[1])
{
case KingSlimeAttackType.SmallJump:
case KingSlimeAttackType.LargeJump:
DoBehavior_Jump(npc, ref target, npc.ai[1] == (int)KingSlimeAttackType.LargeJump);
break;
case KingSlimeAttackType.Teleport:
DoBehavior_Teleport(npc, target, idealScale, ref attackTimer, ref teleportDirection);
break;
}
// Update the hitbox based on the current scale if it changed.
if (oldScale != npc.scale)
{
npc.position = npc.Center;
npc.Size = HitboxScaleFactor * npc.scale;
npc.Center = npc.position;
}
if (npc.Opacity > 0.7f)
npc.Opacity = 0.7f;
// Don't get stuck.
for (int i = 0; i < 2; i++)
{
if (Collision.SolidCollision(npc.BottomLeft - Vector2.UnitY * 8f, npc.width, 4) && !npc.noTileCollide)
{
npc.position.Y -= 8f;
npc.frame.Y = 0;
npc.velocity.Y = 0f;
}
}
npc.gfxOffY = (int)(npc.scale * -14f);
attackTimer++;
return false;
}
public static void DoBehavior_DeathAnimation(NPC npc, Player target, ref float deathTimer)
{
int deathAnimationLength = 230;
// Constantly get the ninja.
NPC ninjaNPC = null;
for (int i = 0; i < Main.npc.Length; i++)
{
if (Main.npc[i].type == ModContent.NPCType<Ninja>())
{
ninjaNPC = Main.npc[i];
break;
}
}
if (deathTimer == 1)
{
DespawnAllSlimeEnemies();
// Despawn the jewel
for (int i = 0; i < Main.npc.Length; i++)
{
if (Main.npc[i].type == ModContent.NPCType<KingSlimeJewelRuby>())
{
Main.npc[i].active = false;
break;
}
}
// If the ninja doesnt exist, spawn it!
if (ninjaNPC is null)
{
NPC.NewNPC(npc.GetSource_FromAI(), (int)npc.Center.X, (int)npc.Center.Y, ModContent.NPCType<Ninja>());
npc.netUpdate = true;
return;
}
// Set the ninjas synced death timer, allowing them to sync with us when needed.
ninjaNPC.Infernum().ExtraAI[7] = 1;
}
// Don't do or take damage.
npc.damage = 0;
npc.dontTakeDamage = true;
// Make the camera focus on King Slime.
if (Main.LocalPlayer.WithinRange(npc.Center, 3700f))
{
Main.LocalPlayer.Infernum_Camera().ScreenFocusPosition = npc.Center;
Main.LocalPlayer.Infernum_Camera().ScreenFocusInterpolant = Utils.GetLerpValue(0f, 15f, deathTimer, true);
Main.LocalPlayer.Infernum_Camera().ScreenFocusInterpolant *= Utils.GetLerpValue(210f, 202f, deathTimer, true);
}
// Perform a large jump.
DoBehavior_Jump(npc, ref target, true, true);
// Stay above ground.
if (Collision.SolidCollision(npc.TopLeft, npc.width, npc.height, true))
{
npc.velocity.Y = 0f;
npc.position.Y -= 12f;
}
// Check if the ninja has initialized their local timer, which happens after they create the projectile, plus the length which is ~30.
if (deathTimer > 70)
{
if (deathTimer == 71)
SoundEngine.PlaySound(InfernumSoundRegistry.KingSlimeDeathAnimation, npc.position);
float interpolant = (deathTimer - 70) / (deathAnimationLength - 70);
Main.LocalPlayer.Infernum_Camera().CurrentScreenShakePower = Lerp(0, 13, interpolant);
for (int i = 0; i < Lerp(2, 4, interpolant); i++)
{
Dust slime = Dust.NewDustPerfect(npc.Center + Main.rand.NextVector2Circular(100f, 70f), 4);
slime.color = new Color(78, 136, 255, 80);
slime.noGravity = true;
slime.velocity = Main.rand.NextVector2Unit() * Main.rand.NextFloat(6f, 20.5f);
slime.scale = 1.6f;
}
Vector2 position = npc.Center + Main.rand.NextVector2Circular(100f, 70f);
Vector2 velocity = position.DirectionFrom(npc.Center);
Particle slimeParticle = new EoCBloodParticle(position, velocity * Main.rand.NextFloat(4f, 12.5f), 60, Main.rand.NextFloat(0.75f, 1.1f), Main.rand.NextBool() ? Color.Blue : Color.CadetBlue, 3);
GeneralParticleHandler.SpawnParticle(slimeParticle);
}
if (deathTimer >= deathAnimationLength || BossRushEvent.BossRushActive)
{
// Die
HatGirl.SayThingWhileOwnerIsAlive(target, "Mods.InfernumMode.PetDialog.KingSlimeDefeatTip");
KillKingSlime(npc, target);
}
}
public static void KillKingSlime(NPC npc, Player target)
{
for (int i = 0; i < 50; i++)
{
Dust slime = Dust.NewDustPerfect(npc.Center + Main.rand.NextVector2Circular(100f, 70f), 4);
slime.color = new Color(78, 136, 255, 80);
slime.noGravity = true;
slime.velocity = Main.rand.NextVector2Unit() * Main.rand.NextFloat(11f, 25.5f);
slime.scale = 3.6f;
Vector2 position = npc.Center + Main.rand.NextVector2Circular(100f, 70f);
Vector2 velocity = position.DirectionFrom(npc.Center);
Particle slimeParticle = new EoCBloodParticle(position, velocity * Main.rand.NextFloat(6f, 16.5f), 60, Main.rand.NextFloat(0.75f, 1.1f), Main.rand.NextBool() ? Color.Blue : Color.CadetBlue, 3);
GeneralParticleHandler.SpawnParticle(slimeParticle);
}
// Spawn slimes that just fall to the ground.
for (int i = 0; i < Main.rand.Next(4, 8); i++)
{
Vector2 position = npc.Center + Main.rand.NextVector2Circular(100f, 70f);
NPC.NewNPC(npc.GetSource_FromAI(), (int)position.X, (int)position.Y, Main.rand.NextBool() ? NPCID.BlueSlime : NPCID.SlimeSpiked);
}
// Spawn slimes that shoot away from him.
for (int i = 0; i < Main.rand.Next(4, 7); i++)
{
Vector2 position = npc.Center + Main.rand.NextVector2Circular(100f, 70f);
NPC slime = NPC.NewNPCDirect(npc.GetSource_FromAI(), (int)position.X, (int)position.Y, Main.rand.NextBool() ? NPCID.BlueSlime : NPCID.SlimeSpiked);
Vector2 velocity = Vector2.One.RotateRandom(TwoPi) * Main.rand.NextFloat(6.5f, 12.5f);
if (velocity.AngleBetween(npc.SafeDirectionTo(target.Center)) > 0.5f)
{
slime.velocity = velocity;
}
else
{
velocity = velocity.RotatedBy(Main.rand.NextFloat(PiOver2, Pi));
slime.velocity = velocity;
}
}
Utilities.CreateShockwave(npc.Center, 1, 4, 40, false);
npc.NPCLoot();
npc.active = false;
}
public static void DoBehavior_Despawn(NPC npc)
{
// Rapidly cease any horizontal movement, to prevent weird sliding behaviors
npc.velocity.X *= 0.8f;
if (Math.Abs(npc.velocity.X) < 0.1f)
npc.velocity.X = 0f;
// Disable damage.
npc.dontTakeDamage = true;
npc.damage = 0;
// Release slime dust to accompany the despawn behavior.
for (int i = 0; i < 30; i++)
{
Dust slime = Dust.NewDustDirect(npc.position + Vector2.UnitX * -20f, npc.width + 40, npc.height, DustID.TintableDust, npc.velocity.X, npc.velocity.Y, 150, new Color(78, 136, 255, 80), 2f);
slime.noGravity = true;
slime.velocity *= 0.5f;
}
// Shrink over time.
npc.scale *= 0.97f;
if (npc.timeLeft > 30)
npc.timeLeft = 30;
// Update the hitbox based on the current scale.
npc.position = npc.Center;
npc.Size = HitboxScaleFactor * npc.scale;
npc.Center = npc.position;
// Despawn if sufficiently small. This is bypassed if the target is sufficiently far away, in which case the despawn happens immediately.
if (npc.scale < 0.7f || !npc.WithinRange(Main.player[npc.target].Center, DespawnDistance))
{
npc.active = false;
npc.netUpdate = true;
}
}
public static void DoBehavior_Jump(NPC npc, ref Player target, bool bigJump, bool performingDeathAnimation = false)
{
int jumpCount = 3;
int jumpDelay = 25;
float jumpSpeedX = 8.5f;
float jumpSpeedY = Utils.Remap(Distance(npc.Center.Y, target.Center.Y), 40f, 480f, 8.25f, 15f);
if (bigJump || performingDeathAnimation)
{
jumpCount = 1;
jumpDelay += 10;
jumpSpeedX += 1.75f;
jumpSpeedY = Utils.Remap(Distance(npc.Center.Y, target.Center.Y), 40f, 500f, 10f, 20.5f);
}
if (performingDeathAnimation)
jumpCount = 0;
// Jump higher if there's an obstacle ahead.
if (!Collision.CanHit(npc.Center, 1, 1, npc.Center + Vector2.UnitX * (target.Center.X > npc.Center.X).ToDirectionInt() * 250f, 1, 1))
jumpSpeedY *= 1.75f;
ref float jumpTimer = ref npc.Infernum().ExtraAI[0];
ref float jumpCounter = ref npc.Infernum().ExtraAI[1];
ref float tileIgnoreCountdown = ref npc.Infernum().ExtraAI[2];
// Increment the jump timer if King Slime is atop solid blocks.
if (tileIgnoreCountdown >= 1f)
{
tileIgnoreCountdown--;
npc.noTileCollide = true;
}
else if (Utilities.ActualSolidCollisionTop(npc.BottomLeft - Vector2.UnitY * 32f, npc.width, 64) && npc.Bottom.Y >= target.Bottom.Y - 320f)
{
npc.velocity.X *= 0.9f;
jumpTimer++;
}
if (jumpTimer >= jumpDelay)
{
jumpCounter++;
if (jumpCounter >= jumpCount + 1f)
{
SelectNextAttack(npc);
if (performingDeathAnimation)
{
NPC ninjaNPC = null;
for (int i = 0; i < Main.npc.Length; i++)
{
if (Main.npc[i].type == ModContent.NPCType<Ninja>())
{
ninjaNPC = Main.npc[i];
break;
}
}
if (ninjaNPC is not null)
{
ninjaNPC.Infernum().ExtraAI[8] = npc.Center.X;
ninjaNPC.Infernum().ExtraAI[9] = npc.Center.Y;
ninjaNPC.netUpdate = true;
}
}
}
else
{
SoundEngine.PlaySound(SoundID.Item167, npc.Bottom);
jumpTimer = 0f;
tileIgnoreCountdown = 10f;
npc.velocity = new((target.Center.X > npc.Center.X).ToDirectionInt() * jumpSpeedX, -jumpSpeedY);
npc.noTileCollide = true;
npc.netUpdate = true;
}
}
}
public static void DoBehavior_Teleport(NPC npc, Player target, float idealScale, ref float attackTimer, ref float teleportDirection)
{
int digTime = 60;
int reappearTime = 30;
ref float digXPosition = ref npc.Infernum().ExtraAI[0];
ref float digYPosition = ref npc.Infernum().ExtraAI[1];
if (attackTimer < digTime)
{
// Rapidly cease any horizontal movement, to prevent weird sliding behaviors
npc.velocity.X *= 0.8f;
if (Math.Abs(npc.velocity.X) < 0.1f)
npc.velocity.X = 0f;
npc.scale = Lerp(idealScale, 0.2f, Clamp(Pow(attackTimer / digTime, 3f), 0f, 1f));
npc.Opacity = Utils.GetLerpValue(0.7f, 1f, npc.scale, true) * 0.7f;
npc.dontTakeDamage = true;
npc.damage = 0;
// Release slime dust to accompany the teleport
for (int i = 0; i < 30; i++)
{
Dust slime = Dust.NewDustDirect(npc.position + Vector2.UnitX * -20f, npc.width + 40, npc.height, DustID.TintableDust, npc.velocity.X, npc.velocity.Y, 150, new Color(78, 136, 255, 80), 2f);
slime.noGravity = true;
slime.velocity *= 0.5f;
}
}
// Perform the teleport.
if (attackTimer == digTime)
{
// Initialize the teleport direction as on the right if it has not been defined yet.
if (teleportDirection == 0f)
teleportDirection = 1f;
digXPosition = target.Center.X + 600f * teleportDirection;
digYPosition = target.Top.Y - 100f;
if (digYPosition < 100f)
digYPosition = 100f;
if (Main.netMode != NetmodeID.Server)
Gore.NewGore(npc.GetSource_FromAI(), npc.Center + new Vector2(-40f, npc.height * -0.5f), npc.velocity, 734, 1f);
WorldUtils.Find(new Vector2(digXPosition, digYPosition).ToTileCoordinates(), Searches.Chain(new Searches.Down(200),
[
new CustomTileConditions.IsSolidOrSolidTop(),
new CustomTileConditions.ActiveAndNotActuated(),
]), out Point newBottom);
// Decide the teleport position and prepare the teleport direction for next time by making it go to the other side.
if (Main.netMode != NetmodeID.MultiplayerClient)
{
npc.Bottom = newBottom.ToWorldCoordinates();
npc.velocity.Y = -2f;
teleportDirection *= -1f;
npc.netUpdate = true;
}
npc.scale = 0.2f;
npc.Opacity = 0.7f;
}
if (attackTimer > digTime && attackTimer <= digTime + reappearTime)
{
npc.scale = Lerp(0.2f, idealScale, Utils.GetLerpValue(digTime, digTime + reappearTime, attackTimer, true));
npc.position.Y -= 2f;
npc.velocity.Y = 0f;
npc.Opacity = 0.7f;
npc.dontTakeDamage = true;
npc.damage = 0;
// Release slime dust to accompany the teleport
for (int i = 0; i < 30; i++)
{
Dust slime = Dust.NewDustDirect(npc.position + Vector2.UnitX * -20f, npc.width + 40, npc.height, DustID.TintableDust, npc.velocity.X, npc.velocity.Y, 150, new Color(78, 136, 255, 80), 2f);
slime.noGravity = true;
slime.velocity *= 0.5f;
}
}
if (attackTimer > digTime + reappearTime + 25)
SelectNextAttack(npc);
}
public static void SelectNextAttack(NPC npc)
{
npc.ai[3]++;
KingSlimeAttackType[] patternToUse = AttackPattern;
KingSlimeAttackType nextAttackType = patternToUse[(int)(npc.ai[3] % patternToUse.Length)];
// Go to the next AI state.
npc.ai[1] = (int)nextAttackType;
// Reset the attack timer.
npc.ai[2] = 0f;
// And reset the misc ai slots.
for (int i = 0; i < 5; i++)
npc.Infernum().ExtraAI[i] = 0f;
if (npc.velocity.Y < 0f)
npc.velocity.Y = 0f;
npc.netUpdate = true;
}
public static void DespawnAllSlimeEnemies()
{
for (int i = 0; i < Main.maxNPCs; i++)
{
NPC npc = Main.npc[i];
if (npc.type is NPCID.BlueSlime or NPCID.SlimeSpiked)
{
npc.active = false;
}
}
// Also clear any projectiles.
Utilities.DeleteAllProjectiles(true,
[
ModContent.ProjectileType<JewelBeam>(),
ModContent.ProjectileType<Shuriken>()
]);
}
#endregion AI
#region Draw Code
public override bool PreDraw(NPC npc, SpriteBatch spriteBatch, Color lightColor)
{
Texture2D kingSlimeTexture = TextureAssets.Npc[npc.type].Value;
Vector2 kingSlimeDrawPosition = npc.Center - Main.screenPosition + Vector2.UnitY * npc.gfxOffY;
if (npc.ai[1] == (int)KingSlimeAttackType.Teleport)
npc.frame.Y = 0;
// Draw the ninja, if it's still stuck.
if (npc.life > npc.lifeMax * Phase3LifeRatio)
{
Vector2 drawOffset = Vector2.Zero;
float ninjaRotation = npc.velocity.X * 0.05f;
drawOffset.Y -= npc.velocity.Y;
drawOffset.X -= npc.velocity.X * 2f;
if (npc.frame.Y == 120)
drawOffset.Y += 2f;
if (npc.frame.Y == 360)
drawOffset.Y -= 2f;
if (npc.frame.Y == 480)
drawOffset.Y -= 6f;
Texture2D ninjaTexture = TextureAssets.Ninja.Value;
Vector2 ninjaDrawPosition = npc.Center - Main.screenPosition + drawOffset;
Main.spriteBatch.Draw(ninjaTexture, ninjaDrawPosition, null, lightColor, ninjaRotation, ninjaTexture.Size() * 0.5f, 1f, SpriteEffects.None, 0f);
}
Main.spriteBatch.Draw(kingSlimeTexture, kingSlimeDrawPosition, npc.frame, npc.GetAlpha(lightColor), npc.rotation, npc.frame.Size() * 0.5f, npc.scale, SpriteEffects.None, 0f);
float verticalCrownOffset = 0f;
switch (npc.frame.Y / (TextureAssets.Npc[npc.type].Value.Height / Main.npcFrameCount[npc.type]))
{
case 0:
verticalCrownOffset = 2f;
break;
case 1:
verticalCrownOffset = -6f;
break;
case 2:
verticalCrownOffset = 2f;
break;
case 3:
verticalCrownOffset = 10f;
break;
case 4:
verticalCrownOffset = 2f;
break;
case 5:
verticalCrownOffset = 0f;
break;
}
Texture2D crownTexture = TextureAssets.Extra[39].Value;
Vector2 crownDrawPosition = npc.Center - Main.screenPosition + Vector2.UnitY * (npc.gfxOffY - (56f - verticalCrownOffset) * npc.scale);
Main.spriteBatch.Draw(crownTexture, crownDrawPosition, null, lightColor, 0f, crownTexture.Size() * 0.5f, 1f, SpriteEffects.None, 0f);
return false;
}
#endregion Drawcode
#region Death Effects
public override bool CheckDead(NPC npc)
{
npc.Infernum().ExtraAI[6] = 1;
npc.life = 1;
npc.dontTakeDamage = true;
npc.active = true;
npc.netUpdate = true;
return false;
}
#endregion Death Effects
#region Tips
public override IEnumerable<Func<NPC, string>> GetTips()
{
yield return n => "Mods.InfernumMode.PetDialog.KingSlimeTip1";
yield return n => "Mods.InfernumMode.PetDialog.KingSlimeTip2";
yield return n =>
{
if (TipsManager.ShouldUseJokeText)
return "Mods.InfernumMode.PetDialog.KingSlimeJokeTip1";
return string.Empty;
};
}
#endregion
}
}
| 0 | 0.893219 | 1 | 0.893219 | game-dev | MEDIA | 0.994436 | game-dev | 0.968771 | 1 | 0.968771 |
aatxe/Orpheus | 1,691 | src/server/maps/MapMonitor.java | /*
OrpheusMS: MapleStory Private Server based on OdinMS
Copyright (C) 2012 Aaron Weiss <aaron@deviant-core.net>
Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package server.maps;
import java.util.concurrent.ScheduledFuture;
import server.MaplePortal;
import server.TimerManager;
public class MapMonitor {
private ScheduledFuture<?> monitorSchedule;
private MapleMap map;
private MaplePortal portal;
public MapMonitor(final MapleMap map, String portal) {
this.map = map;
this.portal = map.getPortal(portal);
this.monitorSchedule = TimerManager.getInstance().register(new Runnable() {
@Override
public void run() {
if (map.getCharacters().size() < 1) {
cancelAction();
}
}
}, 5000);
}
private void cancelAction() {
monitorSchedule.cancel(false);
map.killAllMonsters();
map.clearDrops();
if (portal != null) {
portal.setPortalStatus(MaplePortal.OPEN);
}
map.resetReactors();
}
}
| 0 | 0.742095 | 1 | 0.742095 | game-dev | MEDIA | 0.33569 | game-dev | 0.517553 | 1 | 0.517553 |
SitronX/UnityFingerCamera | 3,845 | Assets/FingerCamera/ExampleScene/Scripts/TouchControl.cs | using System;
using System.Collections.Generic;
using UnityEngine;
public class TouchControl : MonoBehaviour
{
[SerializeField] Camera _camera;
[SerializeField] FingerCameraBehaviour _fingerCamera;
PlaceablePosition _initialPos;
PlaceablePosition _lastHoverPosition;
int _fingerCameraMode = 0;
Dictionary<Collider,PlaceablePosition> _placeablePositions=new Dictionary<Collider,PlaceablePosition>();
List<Tuple<Vector3, Quaternion>> _mainCameraPositions = new List<Tuple<Vector3, Quaternion>>()
{
new Tuple<Vector3, Quaternion>(new Vector3(-0.5f, 10, -4), Quaternion.Euler(new Vector3(60, 0, 0))),
new Tuple<Vector3, Quaternion>(new Vector3(-6, 9, 2f), Quaternion.Euler(new Vector3(60, 90, 0)))
};
private void Start()
{
foreach (PlaceablePosition i in FindObjectsOfType<PlaceablePosition>())
_placeablePositions.Add(i.GetComponent<Collider>(), i);
}
public void ChangeMainCameraPos(int posIndex)
{
var pos = _mainCameraPositions[posIndex];
_camera.transform.position = pos.Item1;
_camera.transform.rotation = pos.Item2;
if (_fingerCamera.IsFingerCameraOn)
StartFingerCamera(); //Refresh if it is already on
}
public void SetFingerCameraMode(int mode)
{
_fingerCameraMode = mode;
if (_fingerCamera.IsFingerCameraOn)
StartFingerCamera(); //Refresh if it is already on
}
private void Update()
{
InputHelper.GetTouch(InputHelper.TouchNumber.First, out Vector3 lastPos, out Vector2 lastTouchDelta, out int inputCount);
if (inputCount>0)
{
Ray ray = _camera.ScreenPointToRay(lastPos);
if (_initialPos==null)
{
if (Physics.Raycast(ray, out RaycastHit info, 300, 1 << 9))
{
if(_placeablePositions[info.collider].Figure != null)
{
_initialPos = _placeablePositions[info.collider];
StartFingerCamera();
}
}
}
else
{
if (Physics.Raycast(ray, out RaycastHit info, 300, 1 << 9|1<<0))
{
_initialPos.Figure.position = info.point + (Vector3.up * 0.2f);
if (_placeablePositions.ContainsKey(info.collider))
{
foreach (PlaceablePosition item in _placeablePositions.Values)
item.ClearHighlight();
_lastHoverPosition = _placeablePositions[info.collider];
_lastHoverPosition.SetHighlightColor(_lastHoverPosition.Figure == null ? Color.green : Color.red);
}
}
}
}
else if(_initialPos != null)
{
_lastHoverPosition.ClearHighlight();
if (_lastHoverPosition.Figure == null)
{
_lastHoverPosition.Figure = _initialPos.Figure;
_lastHoverPosition.PlaceFigureIntoPosition(_initialPos.Figure);
_initialPos.Figure = null;
}
else
_initialPos.PlaceFigureIntoPosition(_initialPos.Figure);
_initialPos = null;
_fingerCamera.StopFingerCamera();
}
}
void StartFingerCamera()
{
if(_fingerCameraMode == 0)
_fingerCamera.StartFingerCamera(_initialPos.Figure, Vector3.down, Vector3.forward);
else if(_fingerCameraMode == 1)
_fingerCamera.StartFingerCamera(_initialPos.Figure, Vector3.down, Vector3.right);
else
_fingerCamera.StartFingerCamera(_initialPos.Figure, _camera.transform.forward,Vector3.up);
}
}
| 0 | 0.877381 | 1 | 0.877381 | game-dev | MEDIA | 0.878794 | game-dev | 0.993795 | 1 | 0.993795 |
feifeid47/Unity-Async-UIFrame | 1,925 | Editor/Scripts/UIFrameSetting.cs | using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Feif.UIFramework.Editor
{
[CreateAssetMenu(fileName = "UIFrameSetting", menuName = "UIFrame/UIFrameSetting", order = 0)]
public class UIFrameSetting : ScriptableObject
{
public TextAsset UIBaseTemplate;
public TextAsset UIComponentTemplate;
public TextAsset UIPanelTemplate;
public TextAsset UIWindowTemplate;
public bool AutoReference = true;
public static UIFrameSetting Instance
{
get
{
var guid = AssetDatabase.FindAssets("t:UIFrameSetting").FirstOrDefault();
if (guid == null)
{
var asset = CreateInstance<UIFrameSetting>();
AssetDatabase.CreateAsset(asset, "Assets/UIFrameSetting.asset");
AssetDatabase.Refresh();
guid = AssetDatabase.FindAssets("t:UIFrameSetting").FirstOrDefault();
}
var path = AssetDatabase.GUIDToAssetPath(guid);
var setting = AssetDatabase.LoadAssetAtPath<UIFrameSetting>(path);
return setting;
}
}
private void Reset()
{
var ms = MonoScript.FromScriptableObject(this);
var path = AssetDatabase.GetAssetPath(ms);
var resPath = Path.GetDirectoryName(path).Replace("Scripts", "Resources");
var fields = GetType().GetFields();
foreach (var field in fields)
{
if (field.Name.EndsWith("Template"))
{
var file = Path.Combine(resPath, $"{field.Name}.txt");
var res = AssetDatabase.LoadAssetAtPath<TextAsset>(file);
field.SetValue(this, res);
}
}
EditorUtility.SetDirty(this);
}
}
} | 0 | 0.794984 | 1 | 0.794984 | game-dev | MEDIA | 0.887104 | game-dev | 0.872521 | 1 | 0.872521 |
janfokke/MonoSync | 1,784 | samples/Tweening/TweenGame.cs | using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MonoGame.Extended;
using MonoGame.Extended.Input;
using MonoGame.Extended.Screens;
using MonoGame.Extended.Tweening;
namespace MonoSync.Sample.Tweening
{
public class TweenGame : GameScreen
{
private readonly Map _map;
private SpriteBatch _spriteBatch;
public TweenGame(Game game, Map map) : base(game)
{
_map = map;
}
public event EventHandler<Vector2> Click;
public override void Update(GameTime gameTime)
{
MouseStateExtended mouseState = MouseExtended.GetState();
float elapsedSeconds = gameTime.GetElapsedSeconds();
foreach (Player player in _map.Players)
{
player.Position = Vector2.Lerp(player.Position, player.TargetPosition, 0.05f);
}
if (mouseState.WasButtonJustDown(MouseButton.Left))
{
Click?.Invoke(this, mouseState.Position.ToVector2());
}
}
public override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
base.LoadContent();
}
public override void UnloadContent()
{
_spriteBatch.Dispose();
base.UnloadContent();
}
public override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
_spriteBatch.Begin(samplerState: SamplerState.PointClamp);
foreach (Player player in _map.Players)
{
_spriteBatch.FillRectangle(player.Position.X, player.Position.Y, 50, 50, player.Color);
}
_spriteBatch.End();
}
}
} | 0 | 0.734791 | 1 | 0.734791 | game-dev | MEDIA | 0.578787 | game-dev,graphics-rendering | 0.832957 | 1 | 0.832957 |
newhoryzon/farmers-delight-fabric | 3,809 | src/main/java/com/nhoryzon/mc/farmersdelight/item/KnifeItem.java | package com.nhoryzon.mc.farmersdelight.item;
import com.nhoryzon.mc.farmersdelight.registry.EnchantmentsRegistry;
import com.nhoryzon.mc.farmersdelight.registry.TagsRegistry;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.CarvedPumpkinBlock;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.Enchantments;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.ItemEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.item.Items;
import net.minecraft.item.MiningToolItem;
import net.minecraft.item.ToolMaterial;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.ActionResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
import java.util.Set;
public class KnifeItem extends MiningToolItem {
public static final Set<Enchantment> ALLOWED_ENCHANTMENTS = Set.of(Enchantments.SHARPNESS, Enchantments.SMITE,
Enchantments.BANE_OF_ARTHROPODS, Enchantments.KNOCKBACK, Enchantments.FIRE_ASPECT, Enchantments.LOOTING,
Enchantments.MENDING, EnchantmentsRegistry.BACKSTABBING.get());
public KnifeItem(ToolMaterial material) {
super(.5f, -1.8f, material, TagsRegistry.MINABLE_KNIFE, new ModItemSettings());
}
public KnifeItem(ToolMaterial material, Item.Settings settings) {
super(.5f, -1.8f, material, TagsRegistry.MINABLE_KNIFE, settings);
}
@Override
public boolean canMine(BlockState state, World world, BlockPos pos, PlayerEntity miner) {
return !miner.isCreative();
}
@Override
public boolean postHit(ItemStack stack, LivingEntity target, LivingEntity attacker) {
stack.damage(1, attacker, user -> user.sendEquipmentBreakStatus(EquipmentSlot.MAINHAND));
return true;
}
@Override
public ActionResult useOnBlock(ItemUsageContext context) {
World world = context.getWorld();
ItemStack tool = context.getStack();
BlockPos pos = context.getBlockPos();
BlockState state = world.getBlockState(pos);
Direction facing = context.getSide();
if (state.getBlock() == Blocks.PUMPKIN && tool.isIn(TagsRegistry.KNIVES)) {
PlayerEntity player = context.getPlayer();
if (player != null && !world.isClient()) {
Direction direction = facing.getAxis() == Direction.Axis.Y ? player.getHorizontalFacing().getOpposite() : facing;
world.playSound(null, pos, SoundEvents.BLOCK_PUMPKIN_CARVE, SoundCategory.BLOCKS, 1.f, 1.f);
world.setBlockState(pos, Blocks.CARVED_PUMPKIN.getDefaultState().with(CarvedPumpkinBlock.FACING, direction), 11);
ItemEntity itemEntity = new ItemEntity(world,
pos.getX() + .5d + direction.getOffsetX() * .65d,
pos.getY() + .1d, pos.getZ() + .5d + direction.getOffsetZ() * .65d,
new ItemStack(Items.PUMPKIN_SEEDS, 4));
itemEntity.setVelocity(
.05d * direction.getOffsetX() + world.getRandom().nextDouble() * .02d,
.05d,
.05d * direction.getOffsetZ() + world.getRandom().nextDouble() * 0.02D);
world.spawnEntity(itemEntity);
tool.damage(1, player, playerIn -> playerIn.sendToolBreakStatus(context.getHand()));
}
return ActionResult.success(world.isClient());
} else {
return ActionResult.PASS;
}
}
} | 0 | 0.814918 | 1 | 0.814918 | game-dev | MEDIA | 0.999721 | game-dev | 0.77407 | 1 | 0.77407 |
MineralStudios/Mineral-Bot | 3,400 | bot-base-client/src/main/mc-client/net/minecraft/inventory/SlotFurnace.java | package net.minecraft.inventory;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.stats.AchievementList;
import net.minecraft.util.MathHelper;
public class SlotFurnace extends Slot {
/** The player that is using the GUI where this slot resides. */
private EntityPlayer thePlayer;
private int field_75228_b;
public SlotFurnace(EntityPlayer p_i1813_1_, IInventory p_i1813_2_, int p_i1813_3_, int p_i1813_4_, int p_i1813_5_) {
super(p_i1813_2_, p_i1813_3_, p_i1813_4_, p_i1813_5_);
this.thePlayer = p_i1813_1_;
}
/**
* Check if the stack is a valid item for this slot. Always true beside for the
* armor slots.
*/
public boolean isItemValid(ItemStack p_75214_1_) {
return false;
}
/**
* Decrease the size of the stack in slot (first int arg) by the amount of the
* second int arg. Returns the new
* stack.
*/
public ItemStack decrStackSize(int p_75209_1_) {
if (this.getHasStack()) {
this.field_75228_b += Math.min(p_75209_1_, this.getStack().stackSize);
}
return super.decrStackSize(p_75209_1_);
}
public void onPickupFromSlot(EntityPlayer p_82870_1_, ItemStack p_82870_2_) {
this.onCrafting(p_82870_2_);
super.onPickupFromSlot(p_82870_1_, p_82870_2_);
}
/**
* the itemStack passed in is the output - ie, iron ingots, and pickaxes, not
* ore and wood. Typically increases an
* internal count then calls onCrafting(item).
*/
protected void onCrafting(ItemStack p_75210_1_, int p_75210_2_) {
this.field_75228_b += p_75210_2_;
this.onCrafting(p_75210_1_);
}
/**
* the itemStack passed in is the output - ie, iron ingots, and pickaxes, not
* ore and wood.
*/
protected void onCrafting(ItemStack p_75208_1_) {
p_75208_1_.onCrafting(this.thePlayer.worldObj, this.thePlayer, this.field_75228_b);
if (!this.thePlayer.worldObj.isClient) {
int var2 = this.field_75228_b;
float var3 = FurnaceRecipes.smelting().func_151398_b(p_75208_1_);
int var4;
if (var3 == 0.0F) {
var2 = 0;
} else if (var3 < 1.0F) {
var4 = MathHelper.floor_float((float) var2 * var3);
if (var4 < MathHelper.ceiling_float_int((float) var2 * var3)
&& (float) Math.random() < (float) var2 * var3 - (float) var4) {
++var4;
}
var2 = var4;
}
while (var2 > 0) {
var4 = EntityXPOrb.getXPSplit(var2);
var2 -= var4;
this.thePlayer.worldObj.spawnEntityInWorld(new EntityXPOrb(this.thePlayer.worldObj, this.thePlayer.posX,
this.thePlayer.posY + 0.5D, this.thePlayer.posZ + 0.5D, var4));
}
}
this.field_75228_b = 0;
if (p_75208_1_.getItem() == Items.iron_ingot) {
this.thePlayer.addStat(AchievementList.acquireIron, 1);
}
if (p_75208_1_.getItem() == Items.cooked_fished) {
this.thePlayer.addStat(AchievementList.cookFish, 1);
}
}
}
| 0 | 0.58784 | 1 | 0.58784 | game-dev | MEDIA | 0.993564 | game-dev | 0.71124 | 1 | 0.71124 |
Cooler2/ApusGameEngine | 2,301 | extra/sdl2/sdltimer.inc | //from "sdl_timer.h"
{**
* Get the number of milliseconds since the SDL library initialization.
*
* This value wraps if the program runs for more than ~49 days.
*}
function SDL_GetTicks: UInt32 cdecl; external SDL_LibName {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GetTicks' {$ENDIF} {$ENDIF};
{**
* Get the current value of the high resolution counter
*}
function SDL_GetPerformanceCounter: UInt64 cdecl; external SDL_LibName {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GetPerformanceCounter' {$ENDIF} {$ENDIF};
{**
* Get the count per second of the high resolution counter
*}
function SDL_GetPerformanceFrequency: UInt64 cdecl; external SDL_LibName {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GetPerformanceFrequency' {$ENDIF} {$ENDIF};
{**
* Wait a specified number of milliseconds before returning.
*}
procedure SDL_Delay(ms: UInt32) cdecl; external SDL_LibName {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_Delay' {$ENDIF} {$ENDIF};
{**
* Function prototype for the timer callback function.
*
* The callback function is passed the current timer interval and returns
* the next timer interval. If the returned value is the same as the one
* passed in, the periodic alarm continues, otherwise a new alarm is
* scheduled. If the callback returns 0, the periodic alarm is cancelled.
*}
type
TSDL_TimerCallback = function(interval: UInt32; param: Pointer): UInt32; cdecl;
{**
* Definition of the timer ID type.
*}
TSDL_TimerID = SInt32;
{**
* Add a new timer to the pool of timers already running.
*
* A timer ID, or NULL when an error occurs.
*}
function SDL_AddTimer(interval: UInt32; callback: TSDL_TimerCallback; param: Pointer): TSDL_TimerID cdecl; external SDL_LibName {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_AddTimer' {$ENDIF} {$ENDIF};
{**
* Remove a timer knowing its ID.
*
* A boolean value indicating success or failure.
*
* It is not safe to remove a timer multiple times.
*}
function SDL_RemoveTimer(id: TSDL_TimerID): Boolean cdecl; external SDL_LibName {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_RemoveTimer' {$ENDIF} {$ENDIF};
{**
* Compare SDL ticks values, and return true if A has passed B.
*}
function SDL_TICKS_PASSED(Const A, B:UInt32):Boolean;
| 0 | 0.723253 | 1 | 0.723253 | game-dev | MEDIA | 0.784366 | game-dev | 0.78184 | 1 | 0.78184 |
silvematt/TomentRaycaster | 7,557 | src/Engine/G_MainMenu.c | #include "G_MainMenu.h"
#include "G_Game.h"
#include "R_Rendering.h"
#include "T_TextRendering.h"
#include "D_AssetsManager.h"
//-------------------------------------
// BUTTONS CALLBACKS
//-------------------------------------
static void CALLBACK_MAINMENU_NewGame(void);
static void CALLBACK_MAINMENU_Options(void);
static void CALLBACK_MAINMENU_Quit(void);
static void CALLBACK_ReturnToMainMenu(void);
static void CALLBACK_OPTIONSMENU_ChangeGraphics(void);
static void CALLBACK_OPTIONSMENU_ChangeShowFPS(void);
static void CALLBACK_MAINMENU_About(void);
static void CALLBACK_Continue(void);
// ----------------------------
// Define Menus
// ----------------------------
menuelement_t MainMenuElements[] =
{
{"Continue", {220, 150, 400, 40}, CALLBACK_Continue},
{"New Game", {220, 200, 400, 40}, CALLBACK_MAINMENU_NewGame},
{"Load Game", {220, 250, 400, 40}, NULL},
{"Options", {220, 300, 400, 40}, CALLBACK_MAINMENU_Options},
{"About", {220, 350, 400, 40}, CALLBACK_MAINMENU_About},
{"Quit", {220, 400, 400, 40}, CALLBACK_MAINMENU_Quit}
};
menu_t MainMenu = {MENU_START, MainMenuElements, 6, &MainMenuElements[1]};
menuelement_t DeathMenuElements[] =
{
{"Restart Game", {220, 200, 400, 40}, CALLBACK_MAINMENU_NewGame},
{"Return", {220, 250, 200, 40}, CALLBACK_ReturnToMainMenu},
};
menu_t DeathMenu = {MENU_DEATH, DeathMenuElements, 2, &DeathMenuElements[0]};
menuelement_t OptionsMenuElements[] =
{
{"Graphics:", {220, 200, 400, 40}, CALLBACK_OPTIONSMENU_ChangeGraphics},
{"Fps:", {220, 250, 400, 40}, CALLBACK_OPTIONSMENU_ChangeShowFPS},
{"Return", {220, 300, 200, 40}, CALLBACK_ReturnToMainMenu},
};
menu_t OptionsMenu = {MENU_OPTIONS, OptionsMenuElements, 3, &OptionsMenuElements[0]};
menuelement_t EndGameMenuElements[] =
{
{"Return", {220, 350, 400, 40}, CALLBACK_ReturnToMainMenu},
};
menu_t EndGameMenu = {MENU_END_GAME, EndGameMenuElements, 1, &EndGameMenuElements[0]};
menuelement_t AboutMenuElements[] =
{
{"Return", {220, 350, 400, 40}, CALLBACK_ReturnToMainMenu},
};
menu_t AboutMenu = {MENU_ABOUT, AboutMenuElements, 1, &AboutMenuElements[0]};
menu_t* currentMenu;
void G_InitMainMenu()
{
G_SetMenu(&MainMenu);
}
//-------------------------------------
// Renders what's gonna be behind the current menu
//-------------------------------------
void G_RenderCurrentMenuBackground(void)
{
switch(currentMenu->ID)
{
case MENU_START:
{
SDL_Rect titleRect = {110, 10, tomentdatapack.uiAssets[M_ASSET_TITLE]->texture->w, tomentdatapack.uiAssets[M_ASSET_TITLE]->texture->h};
R_BlitIntoScreenScaled(NULL, tomentdatapack.uiAssets[M_ASSET_TITLE]->texture, &titleRect);
break;
}
case MENU_OPTIONS:
{
T_DisplayTextScaled(FONT_BLKCRY, "Settings", 180, 80, 2.0f);
// Display graphics current setting:
switch(r_CurrentGraphicsSetting)
{
case GRAPHICS_LOW:
T_DisplayTextScaled(FONT_BLKCRY, "Low", 350, 205, 1.0f);
break;
case GRAPHICS_MEDIUM:
T_DisplayTextScaled(FONT_BLKCRY, "Medium", 350, 205, 1.0f);
break;
case GRAPHICS_HIGH:
T_DisplayTextScaled(FONT_BLKCRY, "High", 350, 205, 1.0f);
break;
}
// Display graphics current setting:
switch(showFPS)
{
case true:
T_DisplayTextScaled(FONT_BLKCRY, "true", 300, 255, 1.0f);
break;
case false:
T_DisplayTextScaled(FONT_BLKCRY, "false", 300, 255, 1.0f);
break;
}
break;
}
case MENU_DEATH:
{
T_DisplayTextScaled(FONT_BLKCRY, "You died!", 180, 80, 2.0f);
break;
}
case MENU_END_GAME:
{
T_DisplayTextScaled(FONT_BLKCRY, "You won!", 180, 80, 2.0f);
T_DisplayTextScaled(FONT_BLKCRY, "You slayed the Lord of all Skeletons\nand you earnt your freedom.", 140, 200, 1.0f);
break;
}
case MENU_ABOUT:
{
T_DisplayTextScaled(FONT_BLKCRY, "About", 210, 80, 2.0f);
T_DisplayTextScaled(FONT_BLKCRY, "Programmer: Mattia Silvestro ( silvematt)\nVersion: 1.2", 80, 200, 1.0f);
break;
}
}
}
//-------------------------------------
// Render menu routine
//-------------------------------------
void G_RenderCurrentMenu(void)
{
// Display text
for(int i = 0; i < currentMenu->elementsLength; i++)
{
T_DisplayTextScaled(FONT_BLKCRY, currentMenu->elements[i].text, currentMenu->elements[i].box.x, currentMenu->elements[i].box.y, 1.25f);
}
// Display cursor
SDL_Rect cursorRect = {currentMenu->selectedElement->box.x - CURSOR_X_OFFSET, currentMenu->selectedElement->box.y, tomentdatapack.uiAssets[M_ASSET_SELECT_CURSOR]->texture->w, tomentdatapack.uiAssets[M_ASSET_SELECT_CURSOR]->texture->h};
R_BlitIntoScreen(NULL, tomentdatapack.uiAssets[M_ASSET_SELECT_CURSOR]->texture, &cursorRect);
}
void G_InMenuInputHandling(SDL_Event* e)
{
// Offset mouse pos
static int x = 0;
static int y = 0;
//Get the mouse offsets
x = e->button.x;
y = e->button.y;
for(int i = 0; i < currentMenu->elementsLength; i++)
{
bool isOn = (( x > currentMenu->elements[i].box.x) && ( x < currentMenu->elements[i].box.x + currentMenu->elements[i].box.w ) &&
( y > currentMenu->elements[i].box.y) && ( y < currentMenu->elements[i].box.y + currentMenu->elements[i].box.h ));
if(e->type == SDL_MOUSEMOTION)
{
// Select hovering element
if (isOn)
currentMenu->selectedElement = ¤tMenu->elements[i];
}
else if(e->type == SDL_MOUSEBUTTONUP && e->button.button == SDL_BUTTON_LEFT)
{
if (isOn && currentMenu->selectedElement->OnClick != NULL)
{
currentMenu->selectedElement->OnClick();
return;
}
}
}
}
void G_SetMenu(menu_t* newMenu)
{
currentMenu = newMenu;
currentMenu->elementsLength = newMenu->elementsLength;
}
//-------------------------------------
// BUTTONS CALLBACKS
//-------------------------------------
static void CALLBACK_MAINMENU_NewGame(void)
{
// Initialize the player
player.hasBeenInitialized = false;
G_InitGame();
A_ChangeState(GSTATE_GAME);
}
static void CALLBACK_MAINMENU_Options(void)
{
G_SetMenu(&OptionsMenu);
A_ChangeState(GSTATE_MENU);
}
static void CALLBACK_MAINMENU_Quit(void)
{
application.quit = true;
}
static void CALLBACK_ReturnToMainMenu(void)
{
G_SetMenu(&MainMenu);
A_ChangeState(GSTATE_MENU);
}
static void CALLBACK_OPTIONSMENU_ChangeGraphics(void)
{
if(r_CurrentGraphicsSetting+1 < 3)
r_CurrentGraphicsSetting++;
else
r_CurrentGraphicsSetting = 0;
R_SetRenderingGraphics(r_CurrentGraphicsSetting);
R_ClearRendering();
}
static void CALLBACK_OPTIONSMENU_ChangeShowFPS(void)
{
showFPS = !showFPS;
}
static void CALLBACK_Continue(void)
{
if(player.hasBeenInitialized)
A_ChangeState(GSTATE_GAME);
}
static void CALLBACK_MAINMENU_About(void)
{
G_SetMenu(&AboutMenu);
A_ChangeState(GSTATE_MENU);
} | 0 | 0.79332 | 1 | 0.79332 | game-dev | MEDIA | 0.90816 | game-dev | 0.830164 | 1 | 0.830164 |
CapsAdmin/goluwa | 4,061 | core/lua/libraries/event.lua | local event = _G.event or {}
event.active = event.active or {}
event.destroy_tag = {}
e.EVENT_DESTROY = event.destroy_tag
local function sort_events()
for key, tbl in pairs(event.active) do
local new = {}
for _, v in pairs(tbl) do
list.insert(new, v)
end
list.sort(new, function(a, b)
return a.priority > b.priority
end)
event.active[key] = new
end
end
function event.AddListener(event_type, id, callback, config)
if type(event_type) == "table" then config = event_type end
if not callback and type(id) == "function" then
callback = id
id = nil
end
config = config or {}
config.event_type = config.event_type or event_type
config.id = config.id or id
config.callback = config.callback or callback
config.priority = config.priority or 0
-- useful for initialize events
if config.id == nil then
config.id = {}
config.remove_after_one_call = true
end
config.print_str = config.event_type .. "->" .. tostring(config.id)
event.RemoveListener(config.event_type, config.id)
event.active[config.event_type] = event.active[config.event_type] or {}
list.insert(event.active[config.event_type], config)
sort_events()
if event_type ~= "EventAdded" then event.Call("EventAdded", config) end
end
event.fix_indices = {}
function event.RemoveListener(event_type, id)
if type(event_type) == "table" then
id = id or event_type.id
event_type = event_type or event_type.event_type
end
if id ~= nil and event.active[event_type] then
if event_type ~= "EventRemoved" then
event.Call("EventRemoved", event.active[event_type])
end
for index, val in pairs(event.active[event_type]) do
if id == val.id then
event.active[event_type][index] = nil
event.fix_indices[event_type] = true
break
end
end
else
--logn(("Tried to remove non existing event '%s:%s'"):format(event, tostring(unique)))
end
end
function event.Call(event_type, a_, b_, c_, d_, e_)
local status, a, b, c, d, e
if event.active[event_type] then
for index = 1, #event.active[event_type] do
local data = event.active[event_type][index]
if not data then break end
if data.self_arg then
if data.self_arg:IsValid() then
if data.self_arg_with_callback then
status, a, b, c, d, e = xpcall(data.callback, data.on_error or system.OnError, a_, b_, c_, d_, e_)
else
status, a, b, c, d, e = xpcall(data.callback, data.on_error or system.OnError, data.self_arg, a_, b_, c_, d_, e_)
end
else
event.RemoveListener(event_type, data.id)
event.active[event_type][index] = nil
sort_events()
llog("[%q][%q] removed because self is invalid", event_type, data.unique)
return
end
else
status, a, b, c, d, e = xpcall(data.callback, data.on_error or system.OnError, a_, b_, c_, d_, e_)
end
if a == event.destroy_tag or data.remove_after_one_call then
event.RemoveListener(event_type, data.id)
else
if status == false then
if type(data.on_error) == "function" then
data.on_error(a, event_type, data.id)
else
event.RemoveListener(event_type, data.id)
llog("[%q][%q] removed", event_type, data.id)
end
end
if a ~= nil then return a, b, c, d, e end
end
end
end
if event.fix_indices[event_type] then
list.fix_indices(event.active[event_type])
event.fix_indices[event_type] = nil
sort_events()
end
end
do -- helpers
function event.CreateRealm(config)
if type(config) == "string" then config = {id = config} end
return setmetatable(
{},
{
__index = function(_, key, val)
for i, data in ipairs(event.active[key]) do
if data.id == config.id then return config.callback end
end
end,
__newindex = function(_, key, val)
if type(val) == "function" then
config = table.copy(config)
config.event_type = key
config.callback = val
event.AddListener(config)
elseif val == nil then
config = table.copy(config)
config.event_type = key
event.RemoveListener(config)
end
end,
}
)
end
end
return event | 0 | 0.875384 | 1 | 0.875384 | game-dev | MEDIA | 0.744358 | game-dev | 0.927179 | 1 | 0.927179 |
AzureeDev/payday-2-luajit | 3,593 | pd2-lua/core/lib/managers/cutscene/keys/coresubtitlecutscenekey.lua | require("core/lib/managers/cutscene/keys/CoreCutsceneKeyBase")
CoreSubtitleCutsceneKey = CoreSubtitleCutsceneKey or class(CoreCutsceneKeyBase)
CoreSubtitleCutsceneKey.ELEMENT_NAME = "subtitle"
CoreSubtitleCutsceneKey.NAME = "Subtitle"
CoreSubtitleCutsceneKey:register_serialized_attribute("category", "")
CoreSubtitleCutsceneKey:register_serialized_attribute("string_id", "")
CoreSubtitleCutsceneKey:register_serialized_attribute("duration", 3, tonumber)
CoreSubtitleCutsceneKey:register_control("divider")
CoreSubtitleCutsceneKey:register_control("localized_text")
CoreSubtitleCutsceneKey:attribute_affects("category", "string_id")
CoreSubtitleCutsceneKey:attribute_affects("string_id", "localized_text")
CoreSubtitleCutsceneKey.control_for_category = CoreCutsceneKeyBase.standard_combo_box_control
CoreSubtitleCutsceneKey.control_for_string_id = CoreCutsceneKeyBase.standard_combo_box_control
CoreSubtitleCutsceneKey.control_for_divider = CoreCutsceneKeyBase.standard_divider_control
function CoreSubtitleCutsceneKey:__tostring()
return "Display subtitle \"" .. self:string_id() .. "\"."
end
function CoreSubtitleCutsceneKey:can_evaluate_with_player(player)
return true
end
function CoreSubtitleCutsceneKey:unload(player)
managers.subtitle:clear_subtitle()
end
function CoreSubtitleCutsceneKey:play(player, undo, fast_forward)
if undo then
managers.subtitle:clear_subtitle()
elseif not fast_forward then
managers.subtitle:show_subtitle(self:string_id(), self:duration())
end
end
function CoreSubtitleCutsceneKey:is_valid_category(value)
return value and value ~= ""
end
function CoreSubtitleCutsceneKey:is_valid_string_id(value)
return value and value ~= ""
end
function CoreSubtitleCutsceneKey:is_valid_duration(value)
return value and value > 0
end
function CoreSubtitleCutsceneKey:control_for_localized_text(parent_frame)
local control = EWS:TextCtrl(parent_frame, "", "", "NO_BORDER,TE_RICH,TE_MULTILINE,TE_READONLY")
control:set_min_size(control:get_min_size():with_y(160))
control:set_background_colour(parent_frame:background_colour():unpack())
return control
end
function CoreSubtitleCutsceneKey:refresh_control_for_category(control)
control:freeze()
control:clear()
local categories = managers.localization:xml_names()
if table.empty(categories) then
control:set_enabled(false)
else
control:set_enabled(true)
local value = self:category()
for _, category in ipairs(categories) do
control:append(category)
if category == value then
control:set_value(value)
end
end
end
control:thaw()
end
function CoreSubtitleCutsceneKey:refresh_control_for_string_id(control)
control:freeze()
control:clear()
local string_ids = self:category() ~= "" and managers.localization:string_map(self:category()) or {}
if table.empty(string_ids) then
control:set_enabled(false)
else
control:set_enabled(true)
local value = self:string_id()
for _, string_id in ipairs(string_ids) do
control:append(string_id)
if string_id == value then
control:set_value(value)
end
end
end
control:thaw()
end
function CoreSubtitleCutsceneKey:refresh_control_for_localized_text(control)
if self:is_valid_category(self:category()) and self:is_valid_string_id(self:string_id()) then
control:set_value(managers.localization:text(self:string_id()))
else
control:set_value("<No String Id>")
end
end
function CoreSubtitleCutsceneKey:validate_control_for_attribute(attribute_name)
if attribute_name ~= "localized_text" then
return self.super.validate_control_for_attribute(self, attribute_name)
end
return true
end
| 0 | 0.893009 | 1 | 0.893009 | game-dev | MEDIA | 0.414198 | game-dev,desktop-app | 0.663774 | 1 | 0.663774 |
Me-Maped/Gameframework-at-FairyGUI | 1,353 | Luban/Tools/Luban/Templates/cpp-sharedptr-bin/schema_cpp.sbn | #include "{{__schema_header_file}}"
{{namespace_with_grace_begin __top_module}}
{{~for bean in __beans~}}
bool {{make_cpp_name bean.full_name}}::deserialize(::luban::ByteBuf& _buf)
{
{{~if bean.parent_def_type~}}
if (!{{make_cpp_name bean.parent_def_type.full_name}}::deserialize(_buf))
{
return false;
}
{{~end~}}
{{~ for field in bean.export_fields ~}}
{{deserialize '_buf' (format_field_name __code_style field.name) field.ctype}}
{{~end~}}
return true;
}
bool {{make_cpp_name bean.full_name}}::deserialize{{bean.name}}(::luban::ByteBuf& _buf, ::luban::SharedPtr<{{make_cpp_name bean.full_name}}>& _out)
{
{{~if bean.is_abstract_type~}}
int32_t id;
if (!_buf.readInt(id)) return false;
switch (id)
{
{{~for child in bean.hierarchy_not_abstract_children~}}
case {{make_type_cpp_name child}}::__ID__: { _out.reset(LUBAN_NEW({{make_type_cpp_name child}})); if (_out->deserialize(_buf)) { return true; } else { _out.reset(); return false;} }
{{~end~}}
default: { _out = nullptr; return false;}
}
{{~else~}}
_out.reset(LUBAN_NEW({{make_type_cpp_name bean}}));
if (_out->deserialize(_buf))
{
return true;
}
else
{
_out.reset();
return false;
}
{{~end~}}
}
{{~end~}}
{{namespace_with_grace_end __top_module}}
| 0 | 0.922283 | 1 | 0.922283 | game-dev | MEDIA | 0.137029 | game-dev | 0.724497 | 1 | 0.724497 |
NeuralHarbour/LLM-Based-3D-Avatar-Assistant | 7,462 | Client Side/Assets/UniGLTF/Editor/UniGLTF/Validation/HumanoidValidator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UniGLTF.M17N;
using UnityEngine;
namespace UniGLTF
{
public static class HumanoidValidator
{
public enum ValidationMessages
{
[LangMsg(Languages.ja, "回転・拡大縮小もしくはWeightの無いBlendShapeが含まれています。正規化が必用です。Setting の PoseFreeze を有効にしてください")]
[LangMsg(Languages.en, " Normalization is required. There are nodes (child GameObject) where rotation and scaling or blendshape without bone weight are not default. Please enable PoseFreeze")]
ROTATION_OR_SCALEING_INCLUDED_IN_NODE,
[LangMsg(Languages.ja, "正規化済みです。Setting の PoseFreeze は不要です")]
[LangMsg(Languages.en, "Normalization has been done. PoseFreeze is not required")]
IS_POSE_FREEZE_DONE,
[LangMsg(Languages.ja, "ExportRootに Animator がありません")]
[LangMsg(Languages.en, "No Animator in ExportRoot")]
NO_ANIMATOR,
[LangMsg(Languages.ja, "ExportRootに Animator と Humanoid がありません")]
[LangMsg(Languages.en, "No Animator and Humanoid in ExportRoot")]
NO_HUMANOID,
[LangMsg(Languages.ja, "Z+ 向きにしてください")]
[LangMsg(Languages.en, "The model needs to face the positive Z-axis")]
FACE_Z_POSITIVE_DIRECTION,
[LangMsg(Languages.ja, "T-Pose にしてください")]
[LangMsg(Languages.en, "Set T-Pose")]
NOT_TPOSE,
[LangMsg(Languages.ja, "ExportRootの Animator に Avatar がありません")]
[LangMsg(Languages.en, "No Avatar in ExportRoot's Animator")]
NO_AVATAR_IN_ANIMATOR,
[LangMsg(Languages.ja, "ExportRootの Animator.Avatar が不正です")]
[LangMsg(Languages.en, "Animator.avatar in ExportRoot is not valid")]
AVATAR_IS_NOT_VALID,
[LangMsg(Languages.ja, "ExportRootの Animator.Avatar がヒューマノイドではありません。FBX importer の Rig で設定してください")]
[LangMsg(Languages.en, "Animator.avatar is not humanoid. Please change model's AnimationType to humanoid")]
AVATAR_IS_NOT_HUMANOID,
[LangMsg(Languages.ja, "Jaw(顎)ボーンが含まれています。意図していない場合は設定解除をおすすめします。FBX importer の rig 設定から変更できます")]
[LangMsg(Languages.en, "Jaw bone is included. It may not what you intended. Please check the humanoid avatar setting screen")]
JAW_BONE_IS_INCLUDED,
}
public static bool HasRotationOrScale(GameObject root)
{
foreach (var t in root.GetComponentsInChildren<Transform>())
{
if (t.localRotation != Quaternion.identity)
{
return true;
}
if (t.localScale != Vector3.one)
{
return true;
}
}
return false;
}
static Vector3 GetForward(Transform l, Transform r)
{
if (l == null || r == null)
{
return Vector3.zero;
}
var lr = (r.position - l.position).normalized;
return Vector3.Cross(lr, Vector3.up);
}
public static IReadOnlyList<UniGLTF.MeshExportInfo> MeshInformations;
public static bool EnableFreeze;
public static IEnumerable<Validation> Validate_Normalize(GameObject ExportRoot)
{
if (!ExportRoot)
{
yield break;
}
if (MeshInformations != null)
{
if (HasRotationOrScale(ExportRoot) || MeshInformations.Any(x => x.ExportBlendShapeCount > 0 && !x.HasSkinning))
{
// 正規化必用
if (EnableFreeze)
{
// する
yield return Validation.Info("PoseFreeze checked. OK");
}
else
{
// しない
yield return Validation.Warning(ValidationMessages.ROTATION_OR_SCALEING_INCLUDED_IN_NODE.Msg());
}
}
else
{
// 不要
if (EnableFreeze)
{
// する
yield return Validation.Warning(ValidationMessages.IS_POSE_FREEZE_DONE.Msg());
}
else
{
// しない
yield return Validation.Info("Root OK");
}
}
}
}
public static IEnumerable<Validation> Validate_TPose(GameObject ExportRoot)
{
if (!ExportRoot)
{
yield break;
}
//
// animator
//
Func<HumanBodyBones, Transform> getBoneTransform = null;
if (ExportRoot.TryGetComponent<UniHumanoid.Humanoid>(out var humanoid))
{
getBoneTransform = humanoid.GetBoneTransform;
}
else if (ExportRoot.TryGetComponent<Animator>(out var animator))
{
getBoneTransform = animator.GetBoneTransform;
// avatar
var avatar = animator.avatar;
if (avatar == null)
{
yield return Validation.Critical(ValidationMessages.NO_AVATAR_IN_ANIMATOR.Msg());
yield break;
}
if (!avatar.isValid)
{
yield return Validation.Critical(ValidationMessages.AVATAR_IS_NOT_VALID.Msg());
yield break;
}
if (!avatar.isHuman)
{
yield return Validation.Critical(ValidationMessages.AVATAR_IS_NOT_HUMANOID.Msg());
yield break;
}
}
else
{
yield return Validation.Critical(ValidationMessages.NO_HUMANOID.Msg());
yield break;
}
// direction
{
var l = getBoneTransform(HumanBodyBones.LeftUpperLeg);
var r = getBoneTransform(HumanBodyBones.RightUpperLeg);
var f = GetForward(l, r);
if (Vector3.Dot(f, Vector3.forward) < 0.8f)
{
yield return Validation.Critical(ValidationMessages.FACE_Z_POSITIVE_DIRECTION.Msg());
yield break;
}
}
{
var lu = getBoneTransform(HumanBodyBones.LeftUpperArm);
var ll = getBoneTransform(HumanBodyBones.LeftLowerArm);
var ru = getBoneTransform(HumanBodyBones.RightUpperArm);
var rl = getBoneTransform(HumanBodyBones.RightLowerArm);
if (Vector3.Dot((ll.position - lu.position).normalized, Vector3.left) < 0.8f
|| Vector3.Dot((rl.position - ru.position).normalized, Vector3.right) < 0.8f)
{
yield return Validation.Error(ValidationMessages.NOT_TPOSE.Msg());
}
}
var jaw = getBoneTransform(HumanBodyBones.Jaw);
if (jaw != null)
{
yield return Validation.Warning(ValidationMessages.JAW_BONE_IS_INCLUDED.Msg(), ValidationContext.Create(jaw));
}
}
}
}
| 0 | 0.841542 | 1 | 0.841542 | game-dev | MEDIA | 0.934349 | game-dev | 0.814506 | 1 | 0.814506 |
MailRuChamps/raic-2019 | 1,062 | clients/dlang/source/model/jump_state.d | import model;
import stream;
import std.conv;
import std.typecons : Nullable;
struct JumpState {
bool canJump;
double speed;
double maxTime;
bool canCancel;
this(bool canJump, double speed, double maxTime, bool canCancel) {
this.canJump = canJump;
this.speed = speed;
this.maxTime = maxTime;
this.canCancel = canCancel;
}
static JumpState readFrom(Stream reader) {
auto result = JumpState();
result.canJump = reader.readBool();
result.speed = reader.readDouble();
result.maxTime = reader.readDouble();
result.canCancel = reader.readBool();
return result;
}
void writeTo(Stream writer) const {
writer.write(canJump);
writer.write(speed);
writer.write(maxTime);
writer.write(canCancel);
}
string toString() const {
return "JumpState" ~ "(" ~
to!string(canJump) ~
to!string(speed) ~
to!string(maxTime) ~
to!string(canCancel) ~
")";
}
}
| 0 | 0.644467 | 1 | 0.644467 | game-dev | MEDIA | 0.352379 | game-dev | 0.858753 | 1 | 0.858753 |
OpenRA/OpenRA | 13,813 | mods/ra/maps/top-o-the-world/top-o-the-world.lua | --[[
Copyright (c) The OpenRA Developers and Contributors
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
--All timers have been reduced by 40% because time was flying 40% faster than reality in the original game.
--That's why instead of having an hour to complete the mission you only have 36 minutes.
--Unit Groups Setup
USSRDie01 = { USSRGrenadier01, USSRGrenadier02, USSRGrenadier03, USSRFlame01, USSRFlame03 }
USSRDie02 = { USSRGrenadier04, USSRGrenadier05, USSRFlame02, USSRFlame04 }
USSRDie03 = { USSRHTank01, USSRHTank02 }
USSRDie04 = { USSRDog01, USSRDog03 }
USSRDie05 = { USSRDog02, USSRDog04 }
USSRDie06 = { USSRV202, USSRV203 }
AlliedSquad01 = { AlliedSquad01RocketInf01, AlliedSquad01RocketInf02, AlliedSquad01RocketInf03, AlliedSquad01RocketInf04, AlliedSquad01RocketInf05 }
AlliedSquad02 = { AlliedSquad02RifleInf01, AlliedSquad02RifleInf02, AlliedSquad02RifleInf03, AlliedSquad02RifleInf04, AlliedSquad02RifleInf05, AlliedSquad02RifleInf06, AlliedSquad02RifleInf07, AlliedSquad02RifleInf08, AlliedSquad02RifleInf09 }
AlliedSquad03 = { AlliedSquad03LTank01, AlliedSquad03RocketInf01, AlliedSquad03RocketInf02, AlliedSquad03RocketInf03 }
AlliedSquad04 = { AlliedSquad04MGG01, AlliedSquad04MTank01, AlliedSquad04MTank02, AlliedSquad04MTank03, AlliedSquad04MTank04, AlliedSquad04MTank05, AlliedSquad04Arty01, AlliedSquad04Arty02, AlliedSquad04Arty03 }
AlliedTanksReinforcement = { "2tnk", "2tnk" }
if Difficulty == "easy" then
AlliedHuntingParty = { "1tnk" }
elseif Difficulty == "normal" then
AlliedHuntingParty = { "1tnk", "1tnk" }
elseif Difficulty == "hard" then
AlliedHuntingParty = { "1tnk", "1tnk", "1tnk" }
end
--Building Group Setup
AlliedAAGuns = { AAGun01, AAGun02, AAGun03, AAGun04, AAGun05, AAGun06 }
--Area Triggers Setup
WaystationTrigger = { CPos.New(61, 37), CPos.New(62, 37), CPos.New(63, 37), CPos.New(64, 37), CPos.New(65, 37), CPos.New(66, 37), CPos.New(67, 37), CPos.New(68, 37), CPos.New(69, 37), CPos.New(70, 37), CPos.New(71, 37), CPos.New(72, 37), CPos.New(73, 37), CPos.New(74, 37), CPos.New(75, 37), CPos.New(61, 38), CPos.New(62, 38), CPos.New(63, 38), CPos.New(64, 38), CPos.New(65, 38), CPos.New(66, 38), CPos.New(67, 38), CPos.New(68, 38), CPos.New(69, 38), CPos.New(70, 38), CPos.New(71, 38), CPos.New(72, 38), CPos.New(73, 38), CPos.New(74, 38), CPos.New(75, 38), CPos.New(61, 39), CPos.New(62, 39), CPos.New(63, 39), CPos.New(64, 39), CPos.New(65, 39), CPos.New(66, 39), CPos.New(67, 39), CPos.New(68, 39), CPos.New(69, 39), CPos.New(70, 39), CPos.New(71, 39), CPos.New(72, 39), CPos.New(73, 39), CPos.New(74, 39), CPos.New(75, 39) }
Inf01Trigger = { CPos.New(81, 90), CPos.New(81, 91), CPos.New(81, 92), CPos.New(81, 93), CPos.New(81, 94), CPos.New(81, 95), CPos.New(82, 90), CPos.New(82, 91), CPos.New(82, 92), CPos.New(82, 93), CPos.New(82, 94), CPos.New(82, 95) }
Inf02Trigger = { CPos.New(85, 90), CPos.New(85, 91), CPos.New(85, 92), CPos.New(85, 93), CPos.New(85, 94), CPos.New(85, 95), CPos.New(86, 90), CPos.New(86, 91), CPos.New(86, 92), CPos.New(86, 93), CPos.New(86, 94), CPos.New(86, 95) }
RevealBridgeTrigger = { CPos.New(74, 52), CPos.New(75, 52), CPos.New(76, 52), CPos.New(77, 52), CPos.New(78, 52), CPos.New(79, 52), CPos.New(80, 52), CPos.New(81, 52), CPos.New(82, 52), CPos.New(83, 52), CPos.New(84, 52), CPos.New(85, 52), CPos.New(86, 52), CPos.New(87, 52), CPos.New(88, 52), CPos.New(76, 53), CPos.New(77, 53), CPos.New(78, 53), CPos.New(79, 53), CPos.New(80, 53), CPos.New(81, 53), CPos.New(82, 53), CPos.New(83, 53), CPos.New(84, 53), CPos.New(85, 53), CPos.New(86, 53), CPos.New(87, 53) }
--Mission Variables Setup
DateTime.TimeLimit = DateTime.Minutes(36)
BridgeIsIntact = true
--Mission Functions Setup
HuntObjectiveTruck = function(a)
if a.HasProperty("Hunt") then
if a.Owner == Greece or a.Owner == GoodGuy then
Trigger.OnIdle(a, function(a)
if a.IsInWorld and not ObjectiveTruck01.IsDead then
a.AttackMove(ObjectiveTruck01.Location, 2)
elseif a.IsInWorld then
a.Hunt()
end
end)
end
end
end
HuntEnemyUnits = function(a)
if a.HasProperty("Hunt") then
Trigger.OnIdle(a, function(a)
if a.IsInWorld then
a.Hunt()
end
end)
end
end
AlliedGroundPatrols = function(a)
if a.HasProperty("Hunt") then
if a.IsInWorld then
a.Patrol({ AlliedHuntingPartyWP02.Location, AlliedHuntingPartyWP03.Location, AlliedHuntingPartyWP04.Location, AlliedHuntingPartyWP05.Location, AlliedHuntingPartyWP06.Location, AlliedHuntingPartyWP07.Location }, false, 50)
end
end
end
SpawnAlliedHuntingParty = function()
Trigger.AfterDelay(DateTime.Minutes(3), function()
if BridgeIsIntact then
local tanks = Reinforcements.Reinforce(Greece, AlliedHuntingParty, { AlliedHuntingPartySpawn.Location, AlliedHuntingPartyWP01.Location,AlliedHuntingPartyWP03.Location, AlliedHuntingPartyWP05.Location }, 0)
Utils.Do(tanks, function(units)
HuntObjectiveTruck(units)
end)
SpawnAlliedHuntingParty()
end
end)
end
WorldLoaded = function()
--Players Setup
USSR = Player.GetPlayer("USSR")
Greece = Player.GetPlayer("Greece")
GoodGuy = Player.GetPlayer("GoodGuy")
BadGuy = Player.GetPlayer("BadGuy")
Neutral = Player.GetPlayer("Neutral")
Creeps = Player.GetPlayer("Creeps")
Camera.Position = DefaultCameraPosition.CenterPosition
--Objectives Setup
InitObjectives(USSR)
BringSupplyTruck = AddPrimaryObjective(USSR, "supply-truck-waystation")
ProtectWaystation = AddPrimaryObjective(USSR, "waystation-must-not-be-destroyed")
DestroyAAGuns = AddSecondaryObjective(USSR, "destroy-aa-guns-enable-air-support")
PreventAlliedIncursions = AddSecondaryObjective(USSR, "find-destroy-bridge-stop-allied-reinforcements")
Trigger.OnKilled(USSRTechCenter01, function()
USSR.MarkFailedObjective(ProtectWaystation)
end)
Trigger.OnKilled(ObjectiveTruck01, function()
USSR.MarkFailedObjective(BringSupplyTruck)
end)
Trigger.OnEnteredFootprint(WaystationTrigger, function(unit, id)
if unit == ObjectiveTruck01 then
Trigger.RemoveFootprintTrigger(id)
USSR.MarkCompletedObjective(BringSupplyTruck)
USSR.MarkCompletedObjective(ProtectWaystation)
end
end)
Trigger.OnAllKilled(AlliedAAGuns, function()
USSR.MarkCompletedObjective(DestroyAAGuns)
Media.PlaySpeechNotification(USSR, "ObjectiveMet")
Trigger.AfterDelay(DateTime.Seconds(2), function()
Actor.Create("powerproxy.spyplane", true, { Owner = USSR })
Actor.Create("powerproxy.parabombs", true, { Owner = USSR })
Media.DisplayMessage(UserInterface.GetFluentMessage("air-support-t-minus-3"))
end)
end)
--Triggers Setup
SpawnAlliedHuntingParty()
Trigger.AfterDelay(0, function()
local playerrevealcam = Actor.Create("camera", true, { Owner = USSR, Location = PlayerStartLocation.Location })
Trigger.AfterDelay(1, function()
if playerrevealcam.IsInWorld then playerrevealcam.Destroy() end
end)
end)
Trigger.OnEnteredFootprint(Inf01Trigger, function(unit, id)
if unit.Owner == USSR then
if not AlliedGNRLHouse.IsDead then
Reinforcements.Reinforce(Greece, { "gnrl" }, { AlliedGNRLSpawn.Location, AlliedGNRLDestination.Location }, 0, function(unit)
HuntEnemyUnits(unit)
end)
end
Utils.Do(AlliedSquad01, HuntEnemyUnits)
local alliedgnrlcamera = Actor.Create("scamera", true, { Owner = USSR, Location = AlliedGNRLSpawn.Location })
Trigger.AfterDelay(DateTime.Seconds(6), function()
if alliedgnrlcamera.IsInWorld then alliedgnrlcamera.Destroy() end
end)
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(Inf02Trigger, function(unit, id)
if unit.Owner == USSR then
Utils.Do(AlliedSquad02, HuntEnemyUnits)
Trigger.RemoveFootprintTrigger(id)
end
end)
Utils.Do(AlliedSquad03, function(actor)
Trigger.OnDamaged(actor, function(unit, attacker)
if attacker.Owner == USSR then
Utils.Do(AlliedSquad03, HuntEnemyUnits)
end
end)
end)
Trigger.OnEnteredFootprint(RevealBridgeTrigger, function(unit, id)
if unit.Owner == USSR then
local bridgecamera01 = Actor.Create("camera", true, { Owner = USSR, Location = AlliedHuntingPartySpawn.Location })
local bridgecamera02 = Actor.Create("camera", true, { Owner = USSR, Location = AlliedHuntingPartyWP01.Location })
Trigger.AfterDelay(DateTime.Seconds(6), function()
if bridgecamera01.IsInWorld then bridgecamera01.Destroy() end
if bridgecamera02.IsInWorld then bridgecamera02.Destroy() end
end)
if Difficulty == "normal" then
Reinforcements.Reinforce(GoodGuy, { "dd" }, { AlliedDestroyer01Spawn.Location, AlliedDestroyer01WP01.Location, AlliedDestroyer01WP02.Location }, 0, function(unit)
unit.Stance = "Defend"
end)
end
if Difficulty == "hard" then
Reinforcements.Reinforce(GoodGuy, { "dd" }, { AlliedDestroyer01Spawn.Location, AlliedDestroyer01WP01.Location, AlliedDestroyer01WP02.Location }, 0, function(unit)
unit.Stance = "Defend"
end)
Reinforcements.Reinforce(GoodGuy, { "dd" }, { AlliedDestroyer02Spawn.Location, AlliedDestroyer02WP01.Location, AlliedDestroyer02WP02.Location }, 0, function(unit)
unit.Stance = "Defend"
end)
end
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.AfterDelay(DateTime.Minutes(9), function()
local powerproxy01 = Actor.Create("powerproxy.paratroopers", true, { Owner = Greece })
local aircraft01 = powerproxy01.TargetParatroopers(AlliedParadropLZ01.CenterPosition, Angle.SouthWest)
Utils.Do(aircraft01, function(a)
Trigger.OnPassengerExited(a, function(t, p)
HuntObjectiveTruck(p)
end)
end)
local powerproxy02 = Actor.Create("powerproxy.paratroopers", true, { Owner = GoodGuy })
local aircraft02 = powerproxy02.TargetParatroopers(AlliedParadropLZ02.CenterPosition, Angle.SouthWest)
Utils.Do(aircraft02, function(a)
Trigger.OnPassengerExited(a, function(t, p)
HuntObjectiveTruck(p)
end)
end)
end)
Trigger.AfterDelay(0, function()
BridgeEnd = Map.ActorsInBox(AlliedHuntingPartySpawn.CenterPosition, AlliedHuntingPartyWP01.CenterPosition, function(self) return self.Type == "br2" end)[1]
Trigger.OnKilled(BridgeEnd, function()
BridgeIsIntact = false
if not BridgeBarrel01.IsDead then BridgeBarrel01.Kill() end
if not BridgeBarrel03.IsDead then BridgeBarrel03.Kill() end
USSR.MarkCompletedObjective(PreventAlliedIncursions)
Media.PlaySpeechNotification(USSR, "ObjectiveMet")
Trigger.AfterDelay(DateTime.Seconds(2), function()
Media.DisplayMessage(UserInterface.GetFluentMessage("allied-ground-reinforcements-stopped"))
end)
end)
end)
Trigger.OnAnyKilled({ BridgeBarrel01, BridgeBarrel03 }, function()
if not BridgeEnd.IsDead then
BridgeEnd.Kill()
end
end)
Trigger.OnAnyKilled(AlliedSquad04, function()
if BridgeIsIntact then
local tanks = Reinforcements.Reinforce(Greece, AlliedTanksReinforcement, { AlliedHuntingPartySpawn.Location, AlliedHuntingPartyWP01.Location }, 0, function(units)
AlliedGroundPatrols(units)
end)
Trigger.OnAllKilled(tanks, function()
if BridgeIsIntact then
Reinforcements.Reinforce(Greece, AlliedTanksReinforcement, { AlliedHuntingPartySpawn.Location, AlliedHuntingPartyWP01.Location }, 0, function(units)
AlliedGroundPatrols(units)
end)
end
end)
end
end)
Trigger.OnAllKilled(AlliedSquad04, function()
if BridgeIsIntact then
local tanks = Reinforcements.Reinforce(Greece, AlliedTanksReinforcement, { AlliedHuntingPartySpawn.Location, AlliedHuntingPartyWP01.Location }, 0, function(units)
AlliedGroundPatrols(units)
end)
Trigger.OnAllKilled(tanks, function()
if BridgeIsIntact then
Reinforcements.Reinforce(Greece, AlliedTanksReinforcement, { AlliedHuntingPartySpawn.Location, AlliedHuntingPartyWP01.Location }, 0, function(units)
AlliedGroundPatrols(units)
end)
end
end)
end
end)
--Units Death Setup
Trigger.AfterDelay(DateTime.Seconds(660), function()
Utils.Do(USSRDie01, function(actor)
if not actor.IsDead then actor.Kill("DefaultDeath") end
end)
end)
Trigger.AfterDelay(DateTime.Seconds(744), function()
Utils.Do(USSRDie02, function(actor)
if not actor.IsDead then actor.Kill("DefaultDeath") end
end)
end)
Trigger.AfterDelay(DateTime.Seconds(1122), function()
if not USSRHTank03.IsDead then USSRHTank03.Kill("DefaultDeath") end
end)
Trigger.AfterDelay(DateTime.Seconds(1230), function()
Utils.Do(USSRDie03, function(actor)
if not actor.IsDead then actor.Kill("DefaultDeath") end
end)
end)
Trigger.AfterDelay(DateTime.Seconds(1338), function()
Utils.Do(USSRDie04, function(actor)
if not actor.IsDead then actor.Kill("DefaultDeath") end
end)
end)
Trigger.AfterDelay(DateTime.Seconds(1416), function()
Utils.Do(USSRDie05, function(actor)
if not actor.IsDead then actor.Kill("DefaultDeath") end
end)
end)
Trigger.AfterDelay(DateTime.Seconds(1668), function()
if not USSRV201.IsDead then USSRV201.Kill("DefaultDeath") end
end)
Trigger.AfterDelay(DateTime.Seconds(1746), function()
Utils.Do(USSRDie06, function(actor)
if not actor.IsDead then actor.Kill("DefaultDeath") end
end)
end)
Trigger.AfterDelay(DateTime.Seconds(2034), function()
if not USSRMTank02.IsDead then USSRMTank02.Kill("DefaultDeath") end
end)
Trigger.AfterDelay(DateTime.Seconds(2142), function()
if not USSRMTank01.IsDead then USSRMTank01.Kill("DefaultDeath") end
end)
Trigger.OnTimerExpired(function()
if not ObjectiveTruck01.IsDead then
ObjectiveTruck01.Kill("DefaultDeath")
-- Set the limit to one so that the timer displays 0 and never ends
-- (which would display the game time instead of 0)
DateTime.TimeLimit = 1
end
end)
end
| 0 | 0.884892 | 1 | 0.884892 | game-dev | MEDIA | 0.947639 | game-dev | 0.722241 | 1 | 0.722241 |
526077247/ETPro | 7,245 | Unity/Codes/Model/Module/CoroutineLock/CoroutineLockComponent.cs | using System;
using System.Collections.Generic;
namespace ET
{
[FriendClass(typeof (CoroutineLockComponent))]
public static class CoroutineLockComponentSystem
{
[ObjectSystem]
public class CoroutineLockComponentAwakeSystem: AwakeSystem<CoroutineLockComponent>
{
public override void Awake(CoroutineLockComponent self)
{
CoroutineLockComponent.Instance = self;
self.list = new List<CoroutineLockQueueType>(CoroutineLockType.Max);
for (int i = 0; i < CoroutineLockType.Max; ++i)
{
CoroutineLockQueueType coroutineLockQueueType = self.AddChildWithId<CoroutineLockQueueType>(++self.idGenerator);
self.list.Add(coroutineLockQueueType);
}
}
}
[ObjectSystem]
public class CoroutineLockComponentDestroySystem: DestroySystem<CoroutineLockComponent>
{
public override void Destroy(CoroutineLockComponent self)
{
self.list.Clear();
self.nextFrameRun.Clear();
self.timers.Clear();
self.timeOutIds.Clear();
self.timerOutTimer.Clear();
self.idGenerator = 0;
self.minTime = 0;
}
}
[FriendClass(typeof (CoroutineLock))]
public class CoroutineLockComponentUpdateSystem: UpdateSystem<CoroutineLockComponent>
{
public override void Update(CoroutineLockComponent self)
{
// 检测超时的CoroutineLock
TimeoutCheck(self);
// 循环过程中会有对象继续加入队列
while (self.nextFrameRun.Count > 0)
{
(int coroutineLockType, long key, int count) = self.nextFrameRun.Dequeue();
self.Notify(coroutineLockType, key, count);
}
}
private void TimeoutCheck(CoroutineLockComponent self)
{
// 超时的锁
if (self.timers.Count == 0)
{
return;
}
self.timeNow = TimeHelper.ClientFrameTime();
if (self.timeNow < self.minTime)
{
return;
}
foreach (var item in self.timers)
{
if (item.Key > self.timeNow)
{
self.minTime = item.Key;
break;
}
self.timeOutIds.Enqueue(item.Key);
}
self.timerOutTimer.Clear();
while (self.timeOutIds.Count > 0)
{
long time = self.timeOutIds.Dequeue();
var list = self.timers[time];
for (int i = 0; i < list.Count; ++i)
{
CoroutineLockTimer coroutineLockTimer = list[i];
self.timerOutTimer.Enqueue(coroutineLockTimer);
}
self.timers.Remove(time);
}
while (self.timerOutTimer.Count > 0)
{
CoroutineLockTimer coroutineLockTimer = self.timerOutTimer.Dequeue();
if (coroutineLockTimer.CoroutineLockInstanceId != coroutineLockTimer.CoroutineLock.InstanceId)
{
continue;
}
CoroutineLock coroutineLock = coroutineLockTimer.CoroutineLock;
// 超时直接调用下一个锁
self.RunNextCoroutine(coroutineLock.coroutineLockType, coroutineLock.key, coroutineLock.level + 1);
coroutineLock.coroutineLockType = CoroutineLockType.None; // 上面调用了下一个, dispose不再调用
}
}
}
public static void RunNextCoroutine(this CoroutineLockComponent self, int coroutineLockType, long key, int level)
{
// 一个协程队列一帧处理超过100个,说明比较多了,打个warning,检查一下是否够正常
if (level == 100)
{
Log.Warning($"too much coroutine level: {coroutineLockType} {key}");
}
self.nextFrameRun.Enqueue((coroutineLockType, key, level));
}
private static void AddTimer(this CoroutineLockComponent self, long tillTime, CoroutineLock coroutineLock)
{
self.timers.Add(tillTime, new CoroutineLockTimer(coroutineLock));
if (tillTime < self.minTime)
{
self.minTime = tillTime;
}
}
public static async ETTask<CoroutineLock> Wait(this CoroutineLockComponent self, int coroutineLockType, long key, int time = 60000)
{
CoroutineLockQueueType coroutineLockQueueType = self.list[coroutineLockType];
if (!coroutineLockQueueType.TryGetValue(key, out CoroutineLockQueue queue))
{
coroutineLockQueueType.Add(key, self.AddChildWithId<CoroutineLockQueue>(++self.idGenerator, true));
return self.CreateCoroutineLock(coroutineLockType, key, time, 1);
}
ETTask<CoroutineLock> tcs = ETTask<CoroutineLock>.Create(true);
queue.Add(tcs, time);
return await tcs;
}
private static CoroutineLock CreateCoroutineLock(this CoroutineLockComponent self, int coroutineLockType, long key, int time, int level)
{
CoroutineLock coroutineLock = self.AddChildWithId<CoroutineLock, int, long, int>(++self.idGenerator, coroutineLockType, key, level, true);
if (time > 0)
{
self.AddTimer(TimeHelper.ClientFrameTime() + time, coroutineLock);
}
return coroutineLock;
}
public static void Notify(this CoroutineLockComponent self, int coroutineLockType, long key, int level)
{
CoroutineLockQueueType coroutineLockQueueType = self.list[coroutineLockType];
if (!coroutineLockQueueType.TryGetValue(key, out CoroutineLockQueue queue))
{
return;
}
if (queue.Count == 0)
{
coroutineLockQueueType.Remove(key);
return;
}
CoroutineLockInfo coroutineLockInfo = queue.Dequeue();
coroutineLockInfo.Tcs.SetResult(self.CreateCoroutineLock(coroutineLockType, key, coroutineLockInfo.Time, level));
}
}
[ComponentOf(typeof(Scene))]
public class CoroutineLockComponent: Entity, IAwake, IUpdate, IDestroy
{
public static CoroutineLockComponent Instance;
public List<CoroutineLockQueueType> list;
public Queue<(int, long, int)> nextFrameRun = new Queue<(int, long, int)>();
public MultiMap<long, CoroutineLockTimer> timers = new MultiMap<long, CoroutineLockTimer>();
public Queue<long> timeOutIds = new Queue<long>();
public Queue<CoroutineLockTimer> timerOutTimer = new Queue<CoroutineLockTimer>();
public long idGenerator;
public long minTime;
public long timeNow;
}
} | 0 | 0.76529 | 1 | 0.76529 | game-dev | MEDIA | 0.246161 | game-dev | 0.947341 | 1 | 0.947341 |
headlesshq/mc-runtime-test | 6,141 | 1_20_1/build.gradle | import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
id 'com.github.johnrengelman.shadow' version '7.1.2'
id 'java'
id 'maven-publish'
id 'xyz.wagyourtail.unimined' version '1.3.10-SNAPSHOT'
}
group 'me.earth'
version "$minecraft_version-${project(':api').project_version}"
base {
archivesName = 'mc-runtime-test'
}
sourceSets {
fabric
lexforge
}
repositories {
mavenCentral()
maven {
url = "https://maven.neoforged.net/releases"
}
maven {
url = "https://maven.fabricmc.net/"
}
maven {
url = "https://files.minecraftforge.net/maven"
}
maven {
name = "sponge"
url = "https://repo.spongepowered.org/maven"
}
maven {
url = "https://maven.wagyourtail.xyz/releases"
}
maven {
name = '3arthMaven'
url = 'https://3arthqu4ke.github.io/maven'
}
}
unimined.minecraft {
version project.minecraft_version
mappings {
mojmap()
// intermediary()
// yarn(1)
devFallbackNamespace "mojmap"
/*stub.withMappings("intermediary", ["yarn"]) {
c("net/minecraft/class_1927", []) {
m("method_55109", "()Lnet/minecraft/class_243;", ["getPos"])
}
}*/
}
defaultRemapJar = false
}
unimined.minecraft(sourceSets.fabric) {
combineWith(sourceSets.main)
fabric {
loader project.fabric_version
}
defaultRemapJar = true
}
unimined.minecraft(sourceSets.lexforge) {
combineWith(sourceSets.main)
minecraftForge {
loader project.lexforge_version
mixinConfig 'mc_runtime_test.mixins.json'
}
minecraftRemapper.config {
ignoreConflicts(true)
}
defaultRemapJar = true
}
configurations {
mainImplementation
lwjglAgent.extendsFrom runtimeOnly
jarLibs
implementation.extendsFrom jarLibs
}
for (String platform_capitalized : ['Fabric', 'Lexforge']) {
def platform = platform_capitalized.toLowerCase()
def remapJarTask = tasks.named("remap${platform_capitalized}Jar", AbstractArchiveTask).get()
def shadowTask = tasks.register("${platform}ShadowJar", ShadowJar) {
dependsOn(remapJarTask)
it.group = 'build'
it.archiveClassifier = "${platform}-release"
from remapJarTask.outputs
it.configurations += [ project.configurations.jarLibs ]
exclude "**/module-info.class"
}
tasks.named('build') { finalizedBy(shadowTask) }
}
dependencies {
compileOnly 'org.spongepowered:mixin:0.8.5-SNAPSHOT'
compileOnly 'me.earth.headlessmc:headlessmc:1.8.1'
lwjglAgent 'me.earth.headlessmc:headlessmc-lwjgl:1.8.1'
// yes, I actually want this at runtime to use assertions!
jarLibs 'org.junit.jupiter:junit-jupiter-api:5.10.1'
jarLibs project(':api')
}
afterEvaluate {
fabricRunClient {
standardInput = System.in
if (rootProject.property('hmc.lwjgl').toBoolean()) {
jvmArgs += ["-javaagent:${configurations.lwjglAgent.files.iterator().next()}"]
systemProperties['joml.nounsafe'] = 'true'
systemProperties['fabric.systemLibraries'] = "${configurations.lwjglAgent.files.iterator().next()}"
}
}
}
jar {
enabled = false
}
processFabricResources {
inputs.property "version", project.version
filesMatching("fabric.mod.json") {
expand "version": project.version
}
}
processLexforgeResources {
inputs.property "version", project.version
filesMatching("META-INF/mods.toml") {
expand "version": project.version
}
}
// Forge Runs seem to have problems running from the build/classes folder
// So instead we just run from the built jar
afterEvaluate {
lexforgeRunClient {
dependsOn(lexforgeJar)
classpath = classpath.filter {
!it.toString().contains('mc-runtime-test/build/classes/java/'.replace('/', File.separator))
&& !it.toString().contains('mc-runtime-test/build/resources/'.replace('/', File.separator))
}
classpath += files("${projectDir}/build/libs/mc-runtime-test-${version}-lexforge-dev.jar".replace('/', File.separator))
}
}
tasks.withType(org.gradle.jvm.tasks.Jar).configureEach {
from("LICENSE") {
duplicatesStrategy = DuplicatesStrategy.INCLUDE
rename { "${it}_${project.archivesBaseName}" }
}
manifest {
attributes(
'Implementation-Title': 'MC-Runtime-Test',
'MixinConfigs': "mc_runtime_test.mixins.json",
'Implementation-Version': project.version,
)
}
}
afterEvaluate {
publishing {
publications {
"${name.toLowerCase()}"(MavenPublication) {
((MavenPublication) it).groupId "${group}"
((MavenPublication) it).artifactId "${archivesBaseName.toLowerCase()}"
((MavenPublication) it).version "${version}"
from components.java
for (String platform: ['Fabric', 'Lexforge']) {
String platform_lower = platform.toLowerCase()
artifact tasks.named("${platform_lower}Jar").get()
artifact tasks.named("remap${platform}Jar").get()
artifact tasks.named("${platform_lower}ShadowJar").get()
}
}
}
repositories {
if (System.getenv('DEPLOY_TO_GITHUB_PACKAGES_URL') == null) {
maven {
name = 'BuildDirMaven'
// this project is in 1_20/1_20_1, so use parent twice
url = rootProject.projectDir.toPath().parent.resolve('build').resolve('maven')
}
} else {
maven {
name = 'GithubPagesMaven'
url = System.getenv('DEPLOY_TO_GITHUB_PACKAGES_URL')
credentials {
username = System.getenv('GITHUB_USER')
password = System.getenv('GITHUB_TOKEN')
}
}
}
}
}
}
| 0 | 0.971486 | 1 | 0.971486 | game-dev | MEDIA | 0.513355 | game-dev | 0.766073 | 1 | 0.766073 |
rorywalsh/cabbage_v1_old | 2,512 | JuceLibraryCode/modules/juce_box2d/box2d/Collision/Shapes/b2CircleShape.h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_CIRCLE_SHAPE_H
#define B2_CIRCLE_SHAPE_H
#include "b2Shape.h"
/// A circle shape.
class b2CircleShape : public b2Shape
{
public:
b2CircleShape();
/// Implement b2Shape.
b2Shape* Clone(b2BlockAllocator* allocator) const;
/// @see b2Shape::GetChildCount
int32 GetChildCount() const;
/// Implement b2Shape.
bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
/// Implement b2Shape.
bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
const b2Transform& transform, int32 childIndex) const;
/// @see b2Shape::ComputeAABB
void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const;
/// @see b2Shape::ComputeMass
void ComputeMass(b2MassData* massData, float32 density) const;
/// Get the supporting vertex index in the given direction.
int32 GetSupport(const b2Vec2& d) const;
/// Get the supporting vertex in the given direction.
const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
/// Get the vertex count.
int32 GetVertexCount() const { return 1; }
/// Get a vertex by index. Used by b2Distance.
const b2Vec2& GetVertex(int32 index) const;
/// Position
b2Vec2 m_p;
};
inline b2CircleShape::b2CircleShape()
{
m_type = e_circle;
m_radius = 0.0f;
m_p.SetZero();
}
inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const
{
B2_NOT_USED(d);
return 0;
}
inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const
{
B2_NOT_USED(d);
return m_p;
}
inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const
{
B2_NOT_USED(index);
b2Assert(index == 0);
return m_p;
}
#endif
| 0 | 0.967849 | 1 | 0.967849 | game-dev | MEDIA | 0.767962 | game-dev | 0.938468 | 1 | 0.938468 |
kgsws/kg3d_x16 | 2,594 | PC/x16_editor/engine/engine.c | #include "inc.h"
#include "defs.h"
#include "engine.h"
#include "x16r.h"
sector_link_t **engine_link_ptr;
//
// API
void engine_reset_box(float *box)
{
box[BOX_XMIN] = +INFINITY;
box[BOX_XMAX] = -INFINITY;
box[BOX_YMIN] = +INFINITY;
box[BOX_YMAX] = -INFINITY;
}
void engine_add_to_box(float *box, float x, float y)
{
if(x < box[BOX_XMIN])
box[BOX_XMIN] = x;
if(x > box[BOX_XMAX])
box[BOX_XMAX] = x;
if(y < box[BOX_YMIN])
box[BOX_YMIN] = y;
if(y > box[BOX_YMAX])
box[BOX_YMAX] = y;
}
void engine_update_sector(kge_sector_t *sec)
{
uint32_t flags = PSF_IS_CONVEX;
kge_vertex_t *vtx = NULL;
// reset bounding box
engine_reset_box(sec->stuff.box);
// go trough lines
for(uint32_t i = 0; i < sec->line_count; i++)
{
kge_line_t *line = sec->line + i;
engine_add_to_box(sec->stuff.box, line->vertex[0]->x, line->vertex[0]->y);
engine_add_to_box(sec->stuff.box, line->vertex[1]->x, line->vertex[1]->y);
if(vtx && line->vertex[0] != vtx)
flags = 0;
if(flags & PSF_IS_CONVEX)
{
kge_line_t *ll;
if(i + 1 == sec->line_count)
ll = sec->line;
else
ll = line + 1;
if(kge_line_point_side(line, ll->vertex[1]->x, ll->vertex[1]->y) < 0)
flags = 0;
}
vtx = line->vertex[1];
}
// center location
sec->stuff.center.x = sec->stuff.box[BOX_XMIN] + (sec->stuff.box[BOX_XMAX] - sec->stuff.box[BOX_XMIN]) * 0.5f;
sec->stuff.center.y = sec->stuff.box[BOX_YMIN] + (sec->stuff.box[BOX_YMAX] - sec->stuff.box[BOX_YMIN]) * 0.5f;
// flags
sec->stuff.flags = flags;
}
void engine_update_line(kge_line_t *line)
{
line->stuff.dist.x = line->vertex[1]->x - line->vertex[0]->x;
line->stuff.dist.y = line->vertex[1]->y - line->vertex[0]->y;
line->stuff.center.x = line->vertex[0]->x + line->stuff.dist.x * 0.5f;
line->stuff.center.y = line->vertex[0]->y + line->stuff.dist.y * 0.5f;
line->stuff.length = sqrtf(line->stuff.dist.x * line->stuff.dist.x + line->stuff.dist.y * line->stuff.dist.y);
line->stuff.normal.x = -line->stuff.dist.y / line->stuff.length;
line->stuff.normal.y = line->stuff.dist.x / line->stuff.length;
line->stuff.x16angle = x16r_line_angle(line);
}
void engine_add_sector_link(kge_thing_t *th, kge_sector_t *sector)
{
sector_link_t **link = §or->thinglist;
sector_link_t *add = malloc(sizeof(sector_link_t));
if(!add)
return;
add->thing = th;
add->next_thing = *link;
if(*link)
(*link)->prev_thing = &add->next_thing;
add->prev_thing = link;
*link = add;
add->prev_sector = engine_link_ptr;
add->next_sector = NULL;
*engine_link_ptr = add;
engine_link_ptr = &add->next_sector;
}
| 0 | 0.868154 | 1 | 0.868154 | game-dev | MEDIA | 0.311984 | game-dev | 0.816682 | 1 | 0.816682 |
kingston-csj/gforgame | 7,240 | client/cocos/assets/scripts/game/hero/view/HeroDetailView.ts | import { _decorator, Button, Color, Label, Node, Sprite } from 'cc';
import { ConfigContext } from '../../../data/config/container/ConfigContext';
import { BaseUiView } from '../../../frame/mvc/BaseUiView';
import { HeroVo } from '../../../net/protocol/items/HeroVo';
import AssetResourceFactory from '../../../ui/AssetResourceFactory';
import R from '../../../ui/R';
import { UiUtil } from '../../../utils/UiUtil';
import { TipsPaneController } from '../../common/TipsPaneController';
import GameConstants from '../../constants/GameConstants';
import { PurseModel } from '../../main/PurseModel';
import { HeroBoxModel } from '../HeroBoxModel';
import { HeroDetailController } from '../controller/HeroDetailController';
const { ccclass, property } = _decorator;
@ccclass('HeroDetailView')
export class HeroDetailView extends BaseUiView {
@property(Node)
public touchArea: Node;
@property(Label)
public heroName: Label;
@property(Node)
public heroIcon: Node;
@property(Label)
public skill1Name: Label;
@property(Label)
public skill2Name: Label;
@property(Label)
public skill3Name: Label;
@property(Label)
public skill4Name: Label;
@property(Node)
public skill1Btn: Node;
@property(Node)
public skill2Btn: Node;
@property(Node)
public skill3Btn: Node;
@property(Node)
public skill4Btn: Node;
private skillNameGroup: Label[];
private skillBtnGroup: Node[];
@property(Node)
public fightArea: Node;
@property(Node)
public attrGroup: Node;
@property(Label)
public attr1Label: Label;
@property(Label)
public attr2Label: Label;
@property(Label)
public attr3Label: Label;
@property(Label)
public attr4Label: Label;
@property(Label)
public skillDesc: Label;
@property(Node)
public skillDescPanel: Node;
@property(Node)
public upLevelBtn: Node;
@property(Node)
public upLevelGroup: Node;
@property(Node)
public upStageGroup: Node;
@property(Node)
public upStageBtn: Node;
@property(Label)
public upLevelInfo: Label;
@property(Label)
public goldNum: Label;
@property(Label)
public upstageItemNum: Label;
@property(Label)
public fightNum: Label;
@property(Label)
public levelNum: Label;
@property(Label)
public description: Label;
@property(Node)
camp: Node;
private hero: HeroVo;
protected start(): void {
this.touchArea.on(Button.EventType.CLICK, () => {
HeroDetailController.closeUi();
});
this.skillNameGroup = [this.skill1Name, this.skill2Name, this.skill3Name, this.skill4Name];
this.skillBtnGroup = [this.skill1Btn, this.skill2Btn, this.skill3Btn, this.skill4Btn];
PurseModel.getInstance().onChange('gold', (value) => {
this.goldNum.string = value.toString();
this.updateLevelOrStageBtn();
});
}
public updateCurrentHeroData() {
if (!this.hero) {
return;
}
this.fillData(this.hero);
}
public fillData(hero: HeroVo) {
this.hero = hero;
let heroData = ConfigContext.configHeroContainer.getRecord(hero.id);
this.heroName.string = heroData.name;
let heroSpriteAtlas = AssetResourceFactory.instance.getSpriteAtlas(R.Sprites.Hero);
// 设置UITransform的contentSize为原始图片尺寸
UiUtil.fillSpriteContent(this.heroIcon, heroSpriteAtlas.getSpriteFrame(heroData.icon));
let campSpriteAtlas = AssetResourceFactory.instance.getSpriteAtlas(R.Sprites.Camp);
UiUtil.fillSpriteContent(this.camp, campSpriteAtlas.getSpriteFrame('camp_' + heroData.camp));
let skills = heroData.skills.split(';');
// 技能组
this.skillNameGroup.forEach((label, index) => {
let skillData = ConfigContext.configSkillContainer.getSkill(Number(skills[index]));
label.string = skillData.name;
});
this.skillBtnGroup.forEach((btn, index) => {
// 先移除已存在的事件监听器
btn.off(Button.EventType.CLICK);
// 再添加新的事件监听器
btn.on(Button.EventType.CLICK, () => {
this.skillDescPanel.active = true;
let skills = heroData.skills.split(';');
let skillData = ConfigContext.configSkillContainer.getSkill(Number(skills[index]));
this.skillDesc.string = skillData.tips;
});
let skillData = ConfigContext.configSkillContainer.getSkill(Number(skills[index]));
if (hero.stage < skillData.stage) {
// 设置按钮为灰色
btn.getComponent(Sprite).color = Color.GRAY;
}
});
// 主公不显示战斗力和属性面板
if (heroData.quality === 0) {
this.fightArea.active = false;
this.attrGroup.active = false;
this.description.string = heroData.tips;
this.description.node.active = true;
} else {
this.description.node.active = false;
this.fightArea.active = true;
this.attrGroup.active = true;
this.attr1Label.string = hero.attrBox.getHp().toString();
this.attr2Label.string = hero.attrBox.getAttack().toString();
this.attr3Label.string = hero.attrBox.getDefense().toString();
this.attr4Label.string = hero.attrBox.getSpeed().toString();
}
this.fightNum.string = hero.fight.toString();
this.levelNum.string = hero.level.toString();
this.upLevelBtn.off(Button.EventType.CLICK);
this.upLevelBtn.on(Button.EventType.CLICK, () => {
let canUpLevel = HeroBoxModel.getInstance().calcUpLevel(this.hero);
if (canUpLevel <= 0) {
TipsPaneController.showI18nContent(GameConstants.I18N.ITEM_NOT_ENOUGH);
return;
}
HeroBoxModel.getInstance()
.requestUpLevel(this.hero.id, this.hero.level + canUpLevel)
.then((code) => {
if (code === 0) {
// 数据模型会触发界面更新
this.levelNum.string = (this.hero.level + canUpLevel).toString();
this.updateLevelOrStageBtn();
} else {
TipsPaneController.showI18nContent(code);
}
});
});
this.goldNum.string = PurseModel.getInstance().gold.toString();
this.upStageBtn.off(Button.EventType.CLICK);
this.upStageBtn.on(Button.EventType.CLICK, () => {
HeroBoxModel.getInstance()
.requestUpStage(this.hero.id)
.then((code) => {
if (code === 0) {
this.updateLevelOrStageBtn();
} else {
TipsPaneController.showI18nContent(code);
}
});
});
this.updateLevelOrStageBtn();
}
private updateLevelOrStageBtn() {
this.upLevelGroup.active = false;
this.upStageGroup.active = false;
let heroStageData = ConfigContext.configHeroStageContainer.getRecordByStage(this.hero.stage);
let nextStageData = ConfigContext.configHeroStageContainer.getRecordByStage(
this.hero.stage + 1
);
if (this.hero.level == heroStageData.max_level && nextStageData) {
this.upStageGroup.active = true;
} else {
if (this.hero.level < ConfigContext.configHeroLevelContainer.getMaxLevel()) {
this.upLevelGroup.active = true;
let times = HeroBoxModel.getInstance().calcUpLevel(this.hero);
if (times > 1) {
this.upLevelInfo.string = `升${times}级`;
} else {
this.upLevelInfo.string = `升级`;
}
this.levelNum.string = this.hero.level.toString();
}
}
}
public onHide(): void {
this.skillDescPanel.active = false;
}
}
| 0 | 0.892398 | 1 | 0.892398 | game-dev | MEDIA | 0.72911 | game-dev | 0.952733 | 1 | 0.952733 |
fabiensanglard/gebbdoom | 2,759 | tools/wadExplorer/WadArchive.cpp | //
// Created by fabien sanglard on 2017-11-23.
//
#include "WadArchive.h"
#include <sys/mman.h>
#include <sys/stat.h>
#include <cassert>
#include <fcntl.h>
#include <zconf.h>
#include <iostream>
struct WadHeader {
char magic[4];
int32_t numLumps;
int32_t offsetToLumps;
};
WadArchive::WadArchive(uint8_t *data, size_t size) : mData(data), mSize(size) {
}
void WadArchive::parse() {
WadHeader *header = reinterpret_cast<WadHeader *>(mData);
mMagic = std::string(header->magic, 4);
uint8_t *rover = static_cast<uint8_t *>(mData) + header->offsetToLumps;
for (int i = 0; i < header->numLumps; i++) {
mLumps.push_back(Lump(rover, mData));
rover += 16;
}
}
void WadArchive::categories() {
for (Lump lump : mLumps) {
Category cat = categorizeLump(lump);
categoriesSize[cat] += lump.size();
}
for(size_t i = 0 ; i < Category::NUM_CATEGORIES ; i++) {
std::cout << i << ":" << categoriesSize[i] << "(" << categoriesSize[i]/(float)mSize * 100 << "%)" << std::endl;
}
}
WadArchive::Category WadArchive::categorizeLump(Lump &lump) {
// We are withing a map.
if (catMode == MAP) {
if (!strcmp(lump.name().c_str(), "BLOCKMAP")) { // Last lump in a map.
catMode = OTHERS;
}
return MAP;
}
std::cout << lump.name() << std::endl;
if (lump.name().size() >= 2 && lump.name()[0] == 'E' && lump.name()[2] == 'M') {
catMode = MAP;
return MAP;
}
else if(lump.name().size() >= 3 && !strncmp(lump.name().c_str(), "MAP", 3)) {
catMode = MAP;
return MAP;
}
if (!strncmp(lump.name().c_str(), "DS", 2)) { // PCM Sound
return Category::SOUND;
}
if (!strncmp(lump.name().c_str(), "DP", 2)) { // PC Speaker
return Category::SOUND;
}
if (!strncmp(lump.name().c_str(), "D_", 2)) {
return Category::MUSIC;
}
if (!strcmp(lump.name().c_str(), "PLAYPAL")) {
return Category::OTHERS;
}
if (!strcmp(lump.name().c_str(), "COLORMAP")) {
return Category::OTHERS;
}
if (!strcmp(lump.name().c_str(), "ENDOOM")) {
return Category::OTHERS;
}
if (!strcmp(lump.name().c_str(), "TEXTURE1")) {
return Category::OTHERS;
}
if (!strcmp(lump.name().c_str(), "TEXTURE2")) {
return Category::OTHERS;
}
if (!strcmp(lump.name().c_str(), "PNAMES")) {
return Category::OTHERS;
}
if (!strcmp(lump.name().c_str(), "GENMIDI")) {
return Category::MUSIC;
}
if (!strcmp(lump.name().c_str(), "DMXGUS")) {
return Category::MUSIC;
}
if (!strncmp(lump.name().c_str(), "DEMO", 4)) {
return Category::OTHERS;
}
return GFX;
}
| 0 | 0.946108 | 1 | 0.946108 | game-dev | MEDIA | 0.187931 | game-dev | 0.980818 | 1 | 0.980818 |
cmss13-devs/cmss13 | 4,094 | code/datums/effects/bleeding.dm | #define BICAOD_BLOOD_REDUCTION 0.67 //15 OD ticks to heal 1 blood loss
#define CRYO_BLOOD_REDUCTION 0.67
#define THWEI_BLOOD_REDUCTION 0.75
#define BLOOD_ADD_PENALTY 1.5
/datum/effects/bleeding
effect_name = "bleeding"
duration = null
flags = NO_PROCESS_ON_DEATH | DEL_ON_UNDEFIBBABLE
var/blood_loss = 0 //How much blood to lose every tick
var/obj/limb/limb = null
var/blood_duration_multiplier = 2.5
var/blood_loss_divider = 80
/datum/effects/bleeding/New(atom/A, obj/limb/L = null, damage = 0)
..()
duration = damage * blood_duration_multiplier
blood_loss = damage / blood_loss_divider
if(L && istype(L))
limb = L
/datum/effects/bleeding/Destroy()
if(limb)
SEND_SIGNAL(limb, COMSIG_LIMB_STOP_BLEEDING, TRUE, FALSE)
limb.bleeding_effects_list -= src
limb = null
return ..()
/datum/effects/bleeding/validate_atom(atom/A)
if(isobj(A))
return FALSE
. = ..()
/datum/effects/bleeding/process_mob()
. = ..()
if(!.)
return FALSE
if(blood_loss <= 0)
qdel(src)
return FALSE
if(!limb)
qdel(src)
return FALSE
var/mob/living/carbon/human/affected_mob = affected_atom
if(affected_mob.status_flags & NO_PERMANENT_DAMAGE)
return FALSE
return TRUE
/datum/effects/bleeding/proc/add_on(damage)
if(damage)
duration += damage * (blood_duration_multiplier / BLOOD_ADD_PENALTY)
blood_loss += damage / (blood_loss_divider * BLOOD_ADD_PENALTY) //Make the first hit count, adding on bleeding has a penalty
/datum/effects/bleeding/external
var/buffer_blood_loss = 0
/datum/effects/bleeding/external/process_mob()
. = ..()
if(!.)
return FALSE
buffer_blood_loss += blood_loss
var/mob/living/carbon/affected_mob = affected_atom
if(duration % 3 == 0) //Do it every third tick
if(affected_mob.reagents) // Annoying QC check
if(affected_mob.reagents.get_reagent_amount("thwei"))
blood_loss -= THWEI_BLOOD_REDUCTION
if(affected_mob.bodytemperature <= BODYTEMP_CRYO_LIQUID_THRESHOLD && (affected_mob.reagents.get_reagent_amount("cryoxadone") || affected_mob.reagents.get_reagent_amount("clonexadone")) )
var/obj/structure/machinery/cryo_cell/cryo = affected_mob.loc
if(istype(cryo) && cryo.on && cryo.operable())
blood_loss -= CRYO_BLOOD_REDUCTION
var/mob/living/carbon/human/affected_human = affected_mob
if(istype(affected_human))
//CHEM_EFFECT_NO_BLEEDING effect cures bleeding via blood_loss reduction.
if(affected_human.chem_effect_flags & CHEM_EFFECT_NO_BLEEDING)
buffer_blood_loss = 0
blood_loss -= CRYO_BLOOD_REDUCTION
return FALSE
if(SEND_SIGNAL(affected_human, COMSIG_BLEEDING_PROCESS, FALSE) & COMPONENT_BLEEDING_CANCEL)
return FALSE
affected_mob.drip(buffer_blood_loss)
buffer_blood_loss = 0
return TRUE
/datum/effects/bleeding/internal
effect_name = "internal bleeding"
flags = INF_DURATION | NO_PROCESS_ON_DEATH | DEL_ON_UNDEFIBBABLE
/datum/effects/bleeding/internal/process_mob()
. = ..()
if(!.)
return FALSE
var/mob/living/carbon/affected_mob = affected_atom
if(affected_mob.in_stasis == STASIS_IN_BAG)
return FALSE
if(affected_mob.reagents) // Annoying QC check
if(affected_mob.reagents.get_reagent_amount("thwei"))
blood_loss -= THWEI_BLOOD_REDUCTION
if(affected_mob.bodytemperature <= BODYTEMP_CRYO_LIQUID_THRESHOLD && (affected_mob.reagents.get_reagent_amount("cryoxadone") || affected_mob.reagents.get_reagent_amount("clonexadone")))
blood_loss -= CRYO_BLOOD_REDUCTION
var/mob/living/carbon/human/affected_human = affected_mob
if(istype(affected_human))
//CHEM_EFFECT_NO_BLEEDING effect cure bleeding via blood_loss reduction. Preferably this would be modified by the property level
if(affected_human.chem_effect_flags & CHEM_EFFECT_NO_BLEEDING)
blood_loss -= CRYO_BLOOD_REDUCTION
return FALSE
if(SEND_SIGNAL(affected_human, COMSIG_BLEEDING_PROCESS, TRUE) & COMPONENT_BLEEDING_CANCEL)
return FALSE
blood_loss = max(blood_loss, 0) // Bleeding shouldn't give extra blood even if its only 1 tick
affected_mob.blood_volume = max(affected_mob.blood_volume - blood_loss, 0)
return TRUE
#undef BLOOD_ADD_PENALTY
| 0 | 0.587841 | 1 | 0.587841 | game-dev | MEDIA | 0.971208 | game-dev | 0.723957 | 1 | 0.723957 |
Sigma-Skidder-Team/SigmaRemap | 4,432 | src/main/java/com/mentalfrostbyte/jello/module/impl/combat/antikb/AACAntiKB.java | package com.mentalfrostbyte.jello.module.impl.combat.antikb;
import com.mentalfrostbyte.jello.event.EventTarget;
import com.mentalfrostbyte.jello.event.impl.EventMove;
import com.mentalfrostbyte.jello.event.impl.ReceivePacketEvent;
import com.mentalfrostbyte.jello.module.Module;
import com.mentalfrostbyte.jello.module.ModuleCategory;
import com.mentalfrostbyte.jello.module.settings.impl.NumberSetting;
import com.mentalfrostbyte.jello.util.MultiUtilities;
import com.mentalfrostbyte.jello.util.player.MovementUtil;
import mapped.RotationHelper;
import net.minecraft.network.IPacket;
import net.minecraft.network.play.server.SEntityVelocityPacket;
import net.minecraft.network.play.server.SExplosionPacket;
public class AACAntiKB extends Module {
public static int field23907;
public float field23908;
public float field23909;
public AACAntiKB() {
super(ModuleCategory.COMBAT, "AAC", "Places block underneath");
this.registerSetting(new NumberSetting<Float>("Strengh", "Boost strengh", 0.7F, Float.class, 0.0F, 1.0F, 0.01F));
field23907 = 20;
}
@Override
public void onDisable() {
field23907 = 20;
}
@EventTarget
private void method16788(EventMove var1) {
if (this.isEnabled() && mc.player != null) {
if (this.method16790()) {
if (field23907 == 0 && !mc.player.onGround && mc.player.hurtTime > 0 && mc.player.fallDistance < 2.0F) {
mc.player.addVelocity(0.0, -1.0, 0.0);
MultiUtilities.setPlayerYMotion(mc.player.getMotion().getY());
mc.player.onGround = true;
field23907 = 20;
}
} else {
if (field23907 < 7) {
field23907++;
if (field23907 > 1) {
float var4 = MovementUtil.lenientStrafe()[1];
float var5 = MovementUtil.lenientStrafe()[2];
float var6 = MovementUtil.lenientStrafe()[0];
double var7 = Math.cos(Math.toRadians(var6));
double var9 = Math.sin(Math.toRadians(var6));
double var11 = (double) ((float) (7 - field23907) * this.getNumberValueBySettingName("Strengh")) * 0.04 * (double) this.field23909 * 0.2;
double var13 = ((double) var4 * var7 + (double) var5 * var9) * var11;
double var15 = ((double) var4 * var9 - (double) var5 * var7) * var11;
float var17 = (float) (Math.atan2(var13, var15) * 180.0 / Math.PI) - 90.0F;
float var18 = RotationHelper.angleDiff(this.field23908, var17);
if (var18 > 100.0F && MultiUtilities.isMoving()) {
var1.setX(var1.getX() + var13);
var1.setZ(var1.getZ() + var15);
} else {
var1.setX(var1.getX() * 0.8);
var1.setZ(var1.getZ() * 0.8);
}
MultiUtilities.setPlayerXMotion(var1.getX());
MultiUtilities.setPlayerZMotion(var1.getZ());
}
}
}
}
}
@EventTarget
private void method16789(ReceivePacketEvent var1) {
if (this.isEnabled() && mc.player != null) {
IPacket var4 = var1.getPacket();
if (var4 instanceof SEntityVelocityPacket) {
if (this.method16790()) {
field23907 = 0;
return;
}
SEntityVelocityPacket var5 = (SEntityVelocityPacket) var4;
if (var5.getEntityID() == mc.player.getEntityId() && (var5.motionX != 0 || var5.motionZ != 0)) {
this.field23909 = (float) (Math.sqrt(var5.motionX * var5.motionX + var5.motionZ * var5.motionZ) / 1000.0);
this.field23908 = (float) (Math.atan2(var5.motionX / 1000, var5.motionZ / 1000) * 180.0 / Math.PI) - 90.0F;
field23907 = 0;
}
}
if (var1.getPacket() instanceof SExplosionPacket) {
SExplosionPacket var6 = (SExplosionPacket) var4;
}
}
}
public boolean method16790() {
return this.getNumberValueBySettingName("Strengh") == 0.0F;
}
}
| 0 | 0.873782 | 1 | 0.873782 | game-dev | MEDIA | 0.973469 | game-dev | 0.866788 | 1 | 0.866788 |
QYhB05/FinalTECH-Changed | 1,527 | src/main/java/io/taraxacum/finaltech/core/item/usable/machine/MachineChargeCardL1.java | package io.taraxacum.finaltech.core.item.usable.machine;
import io.github.thebusybiscuit.slimefun4.api.items.ItemGroup;
import io.github.thebusybiscuit.slimefun4.api.items.SlimefunItemStack;
import io.github.thebusybiscuit.slimefun4.api.recipes.RecipeType;
import io.taraxacum.finaltech.FinalTechChanged;
import io.taraxacum.finaltech.FinalTechChanged;
import io.taraxacum.finaltech.core.interfaces.RecipeItem;
import io.taraxacum.finaltech.util.ConfigUtil;
import io.taraxacum.finaltech.util.RecipeUtil;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import javax.annotation.Nonnull;
public class MachineChargeCardL1 extends AbstractMachineChargeCard implements RecipeItem {
private final double energy = ConfigUtil.getOrDefaultItemSetting(16.04, this, "energy");
public MachineChargeCardL1(ItemGroup itemGroup, SlimefunItemStack item, RecipeType recipeType, ItemStack[] recipe) {
super(itemGroup, item, recipeType, recipe);
}
@Override
protected double energy() {
return energy;
}
@Override
protected boolean consume() {
return true;
}
@Override
protected boolean conditionMatch(@Nonnull Player player) {
return true;
}
@Override
public void registerDefaultRecipes() {
RecipeUtil.registerDescriptiveRecipe(FinalTechChanged.getLanguageManager(), this,
String.valueOf((int) (Math.floor(energy))),
String.format("%.2f", (energy - Math.floor(energy)) * 100));
}
}
| 0 | 0.83473 | 1 | 0.83473 | game-dev | MEDIA | 0.990928 | game-dev | 0.864436 | 1 | 0.864436 |
davidbuzatto/RayMario | 2,235 | old-visual-studio-2022/game/src/QuestionStarBlock.cpp | /**
* @file QuestionStarBlock.cpp
* @author Prof. Dr. David Buzatto
* @brief QuestionStarBlock class implementation.
*
* @copyright Copyright (c) 2024
*/
#include "Block.h"
#include "GameWorld.h"
#include "QuestionStarBlock.h"
#include "raylib.h"
#include "ResourceManager.h"
#include "Star.h"
#include <iostream>
#include <string>
QuestionStarBlock::QuestionStarBlock( Vector2 pos, Vector2 dim, Color color ) :
QuestionStarBlock( pos, dim, color, 0.1, 4 ) {}
QuestionStarBlock::QuestionStarBlock( Vector2 pos, Vector2 dim, Color color, float frameTime, int maxFrames ) :
Block( pos, dim, color, frameTime, maxFrames ),
item( nullptr ),
itemVelY( -80 ),
itemMinY( 0 ),
map( nullptr ) {}
QuestionStarBlock::~QuestionStarBlock() = default;
void QuestionStarBlock::update() {
const float delta = GetFrameTime();
if ( !hit ) {
frameAcum += delta;
if ( frameAcum >= frameTime ) {
frameAcum = 0;
currentFrame++;
currentFrame %= maxFrames;
}
}
if ( item != nullptr ) {
item->setY( item->getY() + itemVelY * delta );
if ( item->getY() <= itemMinY ) {
item->setY( itemMinY );
item->setState( SPRITE_STATE_ACTIVE );
map->getItems().push_back( item );
item = nullptr;
}
}
}
void QuestionStarBlock::draw() {
if ( item != nullptr ) {
item->draw();
}
if ( hit ) {
DrawTexture( ResourceManager::getTextures()["blockEyesClosed"], pos.x, pos.y, WHITE );
} else {
DrawTexture( ResourceManager::getTextures()[std::string( TextFormat( "blockQuestion%d", currentFrame ) )], pos.x, pos.y, WHITE );
}
if ( GameWorld::debug && color.a != 0 ) {
DrawRectangle( pos.x, pos.y, dim.x, dim.y, Fade( color, 0.5 ) );
}
}
void QuestionStarBlock::doHit( Mario& mario, Map* map ) {
if ( !hit ) {
PlaySound( ResourceManager::getSounds()["powerUpAppears"] );
hit = true;
item = new Star( Vector2( pos.x, pos.y ), Vector2( 32, 32 ), Vector2( 300, 0 ), YELLOW );
item->setFacingDirection( mario.getFacingDirection() );
itemMinY = pos.y - 32;
this->map = map;
}
} | 0 | 0.923111 | 1 | 0.923111 | game-dev | MEDIA | 0.779584 | game-dev | 0.85067 | 1 | 0.85067 |
CircumSpector/DS4Windows | 2,497 | DS4Windows/DS4Forms/ViewModels/AxialStickControlViewModel.cs | using System;
using DS4Windows;
using DS4Windows.Shared.Common.Types;
namespace DS4WinWPF.DS4Forms.ViewModels
{
public class AxialStickControlViewModel
{
private StickDeadZoneInfo stickInfo;
public double DeadZoneX
{
get => Math.Round(stickInfo.XAxisDeadInfo.DeadZone / 127d, 2);
set
{
double temp = Math.Round(stickInfo.XAxisDeadInfo.DeadZone / 127d, 2);
if (temp == value) return;
stickInfo.XAxisDeadInfo.DeadZone = (int)Math.Round(value * 127d);
DeadZoneXChanged?.Invoke(this, EventArgs.Empty);
}
}
public event EventHandler DeadZoneXChanged;
public double DeadZoneY
{
get => Math.Round(stickInfo.YAxisDeadInfo.DeadZone / 127d, 2);
set
{
double temp = Math.Round(stickInfo.YAxisDeadInfo.DeadZone / 127d, 2);
if (temp == value) return;
stickInfo.YAxisDeadInfo.DeadZone = (int)Math.Round(value * 127d);
DeadZoneYChanged?.Invoke(this, EventArgs.Empty);
}
}
public event EventHandler DeadZoneYChanged;
public double MaxZoneX
{
get => stickInfo.XAxisDeadInfo.MaxZone / 100.0;
set => stickInfo.XAxisDeadInfo.MaxZone = (int)(value * 100.0);
}
public double MaxZoneY
{
get => stickInfo.YAxisDeadInfo.MaxZone / 100.0;
set => stickInfo.YAxisDeadInfo.MaxZone = (int)(value * 100.0);
}
public double AntiDeadZoneX
{
get => stickInfo.XAxisDeadInfo.AntiDeadZone / 100.0;
set => stickInfo.XAxisDeadInfo.AntiDeadZone = (int)(value * 100.0);
}
public double AntiDeadZoneY
{
get => stickInfo.YAxisDeadInfo.AntiDeadZone / 100.0;
set => stickInfo.YAxisDeadInfo.AntiDeadZone = (int)(value * 100.0);
}
public double MaxOutputX
{
get => stickInfo.XAxisDeadInfo.MaxOutput / 100.0;
set => stickInfo.XAxisDeadInfo.MaxOutput = value * 100.0;
}
public double MaxOutputY
{
get => stickInfo.YAxisDeadInfo.MaxOutput / 100.0;
set => stickInfo.YAxisDeadInfo.MaxOutput = value * 100.0;
}
public AxialStickControlViewModel(StickDeadZoneInfo deadInfo)
{
this.stickInfo = deadInfo;
}
}
}
| 0 | 0.561288 | 1 | 0.561288 | game-dev | MEDIA | 0.671179 | game-dev | 0.722532 | 1 | 0.722532 |
TrashboxBobylev/Summoning-Pixel-Dungeon | 4,775 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/quest/CleanWater.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2022 Evan Debenham
*
* Summoning Pixel Dungeon
* Copyright (C) 2019-2022 TrashboxBobylev
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.items.quest;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Conducts;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.blobs.Fire;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.*;
import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero;
import com.shatteredpixel.shatteredpixeldungeon.effects.Speck;
import com.shatteredpixel.shatteredpixeldungeon.effects.Splash;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.Potion;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.PotionOfHealing;
import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.watabou.noosa.audio.Sample;
import java.util.ArrayList;
public class CleanWater extends Item {
private static final String AC_DRINK = "DRINK";
{
image = ItemSpriteSheet.CLEAN_WATER;
bones = true;
stackable = true;
}
@Override
public ArrayList<String> actions(Hero hero ) {
ArrayList<String> actions = super.actions( hero );
actions.add( AC_DRINK );
return actions;
}
@Override
public boolean isIdentified() {
return !Dungeon.isChallenged(Conducts.Conduct.UNKNOWN);
}
@Override
public void execute( final Hero hero, String action ) {
super.execute( hero, action );
if (action.equals( AC_DRINK )) {
drink( hero );
}
}
protected void drink( Hero hero ) {
detach( hero.belongings.backpack );
hero.spend( 1f );
hero.busy();
apply( hero );
Sample.INSTANCE.play( Assets.Sounds.DRINK );
hero.sprite.operate( hero.pos );
}
public void apply( Hero hero ) {
if (Dungeon.mode == Dungeon.GameMode.HELL){
hero.HP = Math.min(hero.HT, hero.HP + hero.HT / 2);
}
else {
hero.HP = hero.HT;
}
hero.sprite.emitter().start( Speck.factory( Speck.HEALING ), 0.4f, 4 );
cure( hero );
GLog.positive( Messages.get(PotionOfHealing.class, "heal") );
}
public static void cure( Char ch ) {
Buff.detach( ch, Poison.class );
Buff.detach( ch, Cripple.class );
Buff.detach( ch, Weakness.class );
Buff.detach( ch, Bleeding.class );
}
@Override
protected void onThrow( int cell ) {
if (Dungeon.level.map[cell] == Terrain.WELL || Dungeon.level.pit[cell]) {
super.onThrow( cell );
} else {
Dungeon.level.pressCell(cell);
shatter( cell );
}
}
public void shatter( int cell ) {
if (Dungeon.level.heroFOV[cell]) {
GLog.i( Messages.get(Potion.class, "shatter") );
Sample.INSTANCE.play( Assets.Sounds.SHATTER );
splash( cell );
}
}
protected void splash( int cell ) {
Fire fire = (Fire)Dungeon.level.blobs.get( Fire.class );
if (fire != null)
fire.clear( cell );
final int color = 0xFFFFFF;
Char ch = Actor.findChar(cell);
if (ch != null) {
Buff.detach(ch, Burning.class);
Buff.detach(ch, Ooze.class);
Splash.at( ch.sprite.center(), color, 5 );
} else {
Splash.at( cell, color, 5 );
}
}
@Override
public boolean isUpgradable() {
return false;
}
@Override
public int value() {
int i = 100 * quantity;
return i;
}
}
| 0 | 0.819243 | 1 | 0.819243 | game-dev | MEDIA | 0.955064 | game-dev | 0.624697 | 1 | 0.624697 |
OpenXRay/xray-15 | 9,141 | cs/sdk/3d_sdk/3dsmax/ver-6.0/samples/objects/ParticleFlow/Actions/PFOperatorSimpleSpeed.cpp | /**********************************************************************
*<
FILE: PFOperatorSimpleSpeed.cpp
DESCRIPTION: SimpleSpeed Operator implementation
Operator to effect speed unto particles
CREATED BY: David C. Thompson
HISTORY: created 01-15-02
modified 07-23-02 [o.bayborodin]
*> Copyright (c) 2002, All Rights Reserved.
**********************************************************************/
#include "resource.h"
#include "PFActions_SysUtil.h"
#include "PFActions_GlobalFunctions.h"
#include "PFActions_GlobalVariables.h"
#include "PFOperatorSimpleSpeed.h"
#include "PFOperatorSimpleSpeed_ParamBlock.h"
#include "PFClassIDs.h"
#include "IPFSystem.h"
#include "IParticleObjectExt.h"
#include "IParticleChannels.h"
#include "IChannelContainer.h"
#include "IPViewManager.h"
#include "PFMessages.h"
namespace PFActions {
PFOperatorSimpleSpeed::PFOperatorSimpleSpeed()
{
GetClassDesc()->MakeAutoParamBlocks(this);
}
FPInterfaceDesc* PFOperatorSimpleSpeed::GetDescByID(Interface_ID id)
{
if (id == PFACTION_INTERFACE) return &simpleSpeed_action_FPInterfaceDesc;
if (id == PFOPERATOR_INTERFACE) return &simpleSpeed_operator_FPInterfaceDesc;
if (id == PVIEWITEM_INTERFACE) return &simpleSpeed_PViewItem_FPInterfaceDesc;
return NULL;
}
void PFOperatorSimpleSpeed::GetClassName(TSTR& s)
{
s = GetString(IDS_OPERATOR_SIMPLESPEED_CLASS_NAME);
}
Class_ID PFOperatorSimpleSpeed::ClassID()
{
return PFOperatorSimpleSpeed_Class_ID;
}
void PFOperatorSimpleSpeed::BeginEditParams(IObjParam *ip,ULONG flags,Animatable *prev)
{
GetClassDesc()->BeginEditParams(ip, this, flags, prev);
}
void PFOperatorSimpleSpeed::EndEditParams(IObjParam *ip, ULONG flags,Animatable *next)
{
GetClassDesc()->EndEditParams(ip, this, flags, next );
}
RefResult PFOperatorSimpleSpeed::NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget,
PartID& partID, RefMessage message)
{
switch(message) {
case REFMSG_CHANGE:
if ( hTarget == pblock() ) {
int lastUpdateID = pblock()->LastNotifyParamID();
if (lastUpdateID == kSimpleSpeed_direction)
NotifyDependents(FOREVER, 0, kPFMSG_DynamicNameChange, NOTIFY_ALL, TRUE);
UpdatePViewUI(lastUpdateID);
}
break;
case kSimpleSpeed_RefMsg_NewRand:
theHold.Begin();
NewRand();
theHold.Accept(GetString(IDS_NEWRANDOMSEED));
return REF_STOP;
}
return REF_SUCCEED;
}
RefTargetHandle PFOperatorSimpleSpeed::Clone(RemapDir &remap)
{
PFOperatorSimpleSpeed* newOp = new PFOperatorSimpleSpeed();
newOp->ReplaceReference(0, remap.CloneRef(pblock()));
BaseClone(this, newOp, remap);
return newOp;
}
TCHAR* PFOperatorSimpleSpeed::GetObjectName()
{
return GetString(IDS_OPERATOR_SIMPLESPEED_OBJECT_NAME);
}
const ParticleChannelMask& PFOperatorSimpleSpeed::ChannelsUsed(const Interval& time) const
{
// read & write channels
static ParticleChannelMask mask(PCU_New|PCU_Time|PCU_Position|PCU_Amount, PCU_Speed);
return mask;
}
//+--------------------------------------------------------------------------+
//| From IPViewItem |
//+--------------------------------------------------------------------------+
HBITMAP PFOperatorSimpleSpeed::GetActivePViewIcon()
{
if (activeIcon() == NULL)
_activeIcon() = (HBITMAP)LoadImage(hInstance, MAKEINTRESOURCE(IDB_SIMPLESPEED_ACTIVEICON),IMAGE_BITMAP,
kActionImageWidth, kActionImageHeight, LR_SHARED);
return activeIcon();
}
//+--------------------------------------------------------------------------+
//| From IPViewItem |
//+--------------------------------------------------------------------------+
HBITMAP PFOperatorSimpleSpeed::GetInactivePViewIcon()
{
if (inactiveIcon() == NULL)
_inactiveIcon() = (HBITMAP)LoadImage(hInstance, MAKEINTRESOURCE(IDB_SIMPLESPEED_INACTIVEICON),IMAGE_BITMAP,
kActionImageWidth, kActionImageHeight, LR_SHARED);
return inactiveIcon();
}
//+--------------------------------------------------------------------------+
//| From IPViewItem |
//+--------------------------------------------------------------------------+
bool PFOperatorSimpleSpeed::HasDynamicName(TSTR& nameSuffix)
{
int type = pblock()->GetInt(kSimpleSpeed_direction, 0);
int ids;
switch(type) {
case kSS_Along_Icon_Arrow: ids = IDS_ALONG_ICON_ARROW; break;
case kSS_Icon_Center_Out: ids = IDS_ICON_CENTER_0UT; break;
case kSS_Icon_Arrow_Out: ids = IDS_ICON_ARROW_OUT; break;
case kSS_Rand_3D: ids = IDS_RAND_3D; break;
case kSS_Rand_Horiz: ids = IDS_RAND_HORIZ; break;
case kSS_Inherit_Prev: ids = IDS_INHERIT_PREV; break;
}
nameSuffix = GetString(ids);
return true;
}
bool PFOperatorSimpleSpeed::Proceed(IObject* pCont,
PreciseTimeValue timeStart,
PreciseTimeValue& timeEnd,
Object* pSystem,
INode* pNode,
INode* actionNode,
IPFIntegrator* integrator)
{
// acquire all necessary channels, create additional if needed
IParticleChannelNewR* chNew = GetParticleChannelNewRInterface(pCont);
if(chNew == NULL) return false;
IParticleChannelPTVR* chTime = GetParticleChannelTimeRInterface(pCont);
if(chTime == NULL) return false;
IParticleChannelAmountR* chAmount = GetParticleChannelAmountRInterface(pCont);
if(chAmount == NULL) return false;
// the position channel may not be present. For some option configurations it is okay
IParticleChannelPoint3R* chPos = GetParticleChannelPositionRInterface(pCont);
int iDir = _pblock()->GetInt(kSimpleSpeed_direction, timeStart);
if ((chPos == NULL) && ((iDir == kSS_Icon_Center_Out) || (iDir == kSS_Icon_Arrow_Out)))
return false;
IChannelContainer* chCont;
chCont = GetChannelContainerInterface(pCont);
if (chCont == NULL) return false;
// the channel of interest
bool initSpeed = false;
IParticleChannelPoint3W* chSpeed = (IParticleChannelPoint3W*)chCont->EnsureInterface(PARTICLECHANNELSPEEDW_INTERFACE,
ParticleChannelPoint3_Class_ID,
true, PARTICLECHANNELSPEEDR_INTERFACE,
PARTICLECHANNELSPEEDW_INTERFACE, true,
actionNode, (Object*)NULL, &initSpeed);
IParticleChannelPoint3R* chSpeedR = GetParticleChannelSpeedRInterface(pCont);
if ((chSpeed == NULL) || (chSpeedR == NULL)) return false;
// there are no new particles
if (chNew->IsAllOld()) return true;
float fUPFScale = 1.0f/TIME_TICKSPERSEC; // conversion units per seconds to units per tick
Point3 pt3SpeedVec;
RandGenerator* prg = randLinker().GetRandGenerator(pCont);
int iQuant = chAmount->Count();
bool wasIgnoringEmitterTMChange = IsIgnoringEmitterTMChange();
if (!wasIgnoringEmitterTMChange) SetIgnoreEmitterTMChange();
for(int i = 0; i < iQuant; i++) {
if(chNew->IsNew(i)) { // apply only to new particles
TimeValue tv = chTime->GetValue(i).TimeValue();
Matrix3 nodeTM = pNode->GetObjectTM(tv);
float fSpeedParam = fUPFScale * GetPFFloat(pblock(), kSimpleSpeed_speed, tv);
// change speed in user selected direction
switch(iDir) {
case kSS_Along_Icon_Arrow: {
// icon arrow appears to be in the negative z direction
pt3SpeedVec = -Normalize(nodeTM.GetRow(2));
}
break;
case kSS_Icon_Center_Out: {
Point3 pt3IconCenter = nodeTM.GetTrans();
Point3 pt3PartPos = chPos->GetValue(i);
pt3SpeedVec = Normalize(pt3PartPos - pt3IconCenter);
}
break;
case kSS_Icon_Arrow_Out: {
Point3 pt3PartPos = chPos->GetValue(i);
Point3 pt3ArrowVec = nodeTM.GetRow(2);
Point3 pt3Tmp = CrossProd(pt3PartPos - nodeTM.GetTrans(), pt3ArrowVec);
pt3SpeedVec = Normalize(CrossProd(pt3ArrowVec, pt3Tmp));
}
break;
case kSS_Rand_3D: {
pt3SpeedVec = RandSphereSurface(prg);
}
break;
case kSS_Rand_Horiz: {
float fAng = TWOPI * prg->Rand01();
// establish x, y coordinates of random angle, z component zero
float x = cos(fAng); float y = sin(fAng); float z = 0.0f;
pt3SpeedVec = Point3(x, y, z);
}
break;
case kSS_Inherit_Prev: {
if (initSpeed)
pt3SpeedVec = Point3::Origin;
else
pt3SpeedVec = Normalize(chSpeedR->GetValue(i));
}
break;
}
// account for reverse check box
int iRev = _pblock()->GetInt(kSimpleSpeed_reverse, 0);
float fDirMult = iRev > 0 ? -1.f : 1.f;
// calculate variation
float fVar = fUPFScale * GetPFFloat(pblock(), kSimpleSpeed_variation, tv);
if(fVar > 0.f)
fSpeedParam = fSpeedParam + fVar * prg->Rand11();
pt3SpeedVec = fDirMult * fSpeedParam * pt3SpeedVec;
// calculate divergence
float fDiv = GetPFFloat(pblock(), kSimpleSpeed_divergence, tv);
pt3SpeedVec = DivergeVectorRandom(pt3SpeedVec, prg, fDiv);
chSpeed->SetValue(i, pt3SpeedVec);
}
}
if (!wasIgnoringEmitterTMChange) ClearIgnoreEmitterTMChange();
return true;
}
ClassDesc* PFOperatorSimpleSpeed::GetClassDesc() const
{
return GetPFOperatorSimpleSpeedDesc();
}
int PFOperatorSimpleSpeed::GetRand()
{
return pblock()->GetInt(kSimpleSpeed_seed);
}
void PFOperatorSimpleSpeed::SetRand(int seed)
{
_pblock()->SetValue(kSimpleSpeed_seed, 0, seed);
}
} // end of namespace PFActions | 0 | 0.95424 | 1 | 0.95424 | game-dev | MEDIA | 0.462235 | game-dev | 0.986244 | 1 | 0.986244 |
mCRL2org/mCRL2 | 5,003 | libraries/pg/source/ComponentSolver.cpp | // Copyright (c) 2009-2013 University of Twente
// Copyright (c) 2009-2013 Michael Weber <michaelw@cs.utwente.nl>
// Copyright (c) 2009-2013 Maks Verver <maksverver@geocities.com>
// Copyright (c) 2009-2013 Eindhoven University of Technology
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "mcrl2/pg/ComponentSolver.h"
#include "mcrl2/pg/attractor.h"
ComponentSolver::ComponentSolver(
const ParityGame &game, ParityGameSolverFactory &pgsf,
int max_depth, const verti *vmap, verti vmap_size )
: ParityGameSolver(game), pgsf_(pgsf), max_depth_(max_depth),
vmap_(vmap), vmap_size_(vmap_size)
{
pgsf_.ref();
}
ComponentSolver::~ComponentSolver()
{
pgsf_.deref();
}
ParityGame::Strategy ComponentSolver::solve()
{
verti V = game_.graph().V();
strategy_.assign(V, NO_VERTEX);
DenseSet<verti> W0(0, V);
DenseSet<verti> W1(0, V);
winning_[0] = &W0;
winning_[1] = &W1;
if (decompose_graph(game_.graph(), *this) != 0)
{
strategy_.clear();
}
winning_[0] = nullptr;
winning_[1] = nullptr;
ParityGame::Strategy result;
result.swap(strategy_);
return result;
}
int ComponentSolver::operator()(const verti *vertices, std::size_t num_vertices)
{
if (aborted())
{
return -1;
}
assert(num_vertices > 0);
// Filter out solved vertices:
std::vector<verti> unsolved;
unsolved.reserve(num_vertices);
for (std::size_t n = 0; n < num_vertices; ++n)
{
verti v = vertices[n];
if (!winning_[0]->count(v) && !winning_[1]->count(v))
{
unsolved.push_back(vertices[n]);
}
}
mCRL2log(mcrl2::log::verbose) << "SCC of size " << num_vertices << " with "
<< unsolved.size() << " unsolved vertices..." << std::endl;
if (unsolved.empty())
{
return 0;
}
// Construct a subgame for unsolved vertices in this component:
ParityGame subgame;
subgame.make_subgame(game_, unsolved.begin(), unsolved.end(), true);
ParityGame::Strategy substrat;
if (max_depth_ > 0 && unsolved.size() < num_vertices)
{
mCRL2log(mcrl2::log::verbose) << "Recursing on subgame of size "
<< unsolved.size() << "..." << std::endl;
ComponentSolver(subgame, pgsf_, max_depth_ - 1).solve().swap(substrat);
}
else
{
// Compress vertex priorities
{
std::size_t old_d = subgame.d();
subgame.compress_priorities();
std::size_t new_d = subgame.d();
if (old_d != new_d)
{
mCRL2log(mcrl2::log::verbose) << "Priority compression removed "
<< old_d - new_d << " of "
<< old_d << " priorities" << std::endl;
}
}
// Solve the subgame
mCRL2log(mcrl2::log::verbose) << "Solving subgame of size "
<< unsolved.size() << "..." << std::endl;
std::vector<verti> submap; // declared here so it survives subsolver
std::unique_ptr<ParityGameSolver> subsolver;
if (vmap_size_ > 0)
{
submap = unsolved;
merge_vertex_maps(submap.begin(), submap.end(), vmap_, vmap_size_);
subsolver.reset(
pgsf_.create(subgame, &submap[0], submap.size()) );
}
else
{
subsolver.reset(
pgsf_.create(subgame, &unsolved[0], unsolved.size()) );
}
subsolver->solve().swap(substrat);
}
if (substrat.empty())
{
return -1; // solving failed
}
mCRL2log(mcrl2::log::verbose) << "Merging strategies..." << std::endl;
merge_strategies(strategy_, substrat, unsolved);
mCRL2log(mcrl2::log::verbose) << "Building attractor sets for winning regions..." << std::endl;
// Extract winning sets from subgame:
std::deque<verti> todo[2];
for (std::size_t n = 0; n < unsolved.size(); ++n)
{
ParityGame::Player pl = subgame.winner(substrat, n);
verti v = unsolved[n];
winning_[pl]->insert(v);
todo[pl].push_back(v);
}
// Extend winning sets to attractor sets:
for (int player = 0; player < 2; ++player)
{
make_attractor_set( game_, (ParityGame::Player)player,
*winning_[player], todo[player], strategy_ );
}
mCRL2log(mcrl2::log::verbose) << "Leaving." << std::endl;
return 0;
}
ParityGameSolver *ComponentSolverFactory::create( const ParityGame &game,
const verti *vertex_map, verti vertex_map_size )
{
return new ComponentSolver( game, pgsf_, max_depth_,
vertex_map, vertex_map_size );
}
| 0 | 0.873963 | 1 | 0.873963 | game-dev | MEDIA | 0.272112 | game-dev | 0.963621 | 1 | 0.963621 |
anathema/anathema_legacy | 1,677 | Character_Equipment/src/main/java/net/sf/anathema/hero/equipment/model/natural/DefaultNaturalSoak.java | package net.sf.anathema.hero.equipment.model.natural;
import net.sf.anathema.character.equipment.character.model.stats.AbstractCombatStats;
import net.sf.anathema.hero.equipment.sheet.content.stats.weapon.IArmourStats;
import net.sf.anathema.hero.traits.model.ValuedTraitType;
import net.sf.anathema.character.framework.type.CharacterType;
import net.sf.anathema.hero.health.HealthType;
import net.sf.anathema.lib.util.Identifier;
import net.sf.anathema.lib.util.SimpleIdentifier;
public class DefaultNaturalSoak extends AbstractCombatStats implements IArmourStats, NaturalSoak {
private final ValuedTraitType stamina;
private final CharacterType characterType;
public DefaultNaturalSoak(ValuedTraitType stamina, CharacterType characterType) {
this.stamina = stamina;
this.characterType = characterType;
}
@Override
public Integer getFatigue() {
return null;
}
@Override
public Integer getHardness(HealthType type) {
return null;
}
@Override
public Integer getMobilityPenalty() {
return null;
}
@Override
public Integer getSoak(HealthType type) {
if (type == HealthType.Aggravated) {
return null;
}
if (!characterType.isEssenceUser() && type == HealthType.Lethal) {
return 0;
}
return getExaltedSoak(type);
}
private Integer getExaltedSoak(HealthType type) {
if (type == HealthType.Lethal) {
return (stamina.getCurrentValue() / 2);
}
else {
return stamina.getCurrentValue();
}
}
@Override
public Identifier getName() {
return new SimpleIdentifier("NaturalSoak");
}
@Override
public String getId() {
return getName().getId();
}
} | 0 | 0.590465 | 1 | 0.590465 | game-dev | MEDIA | 0.846147 | game-dev | 0.934928 | 1 | 0.934928 |
lordofduct/spacepuppy-unity-framework-4.0 | 5,478 | Framework/com.spacepuppy.ui/Runtime/src/UI/SPUIButton.cs | using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using com.spacepuppy;
using com.spacepuppy.Utils;
using com.spacepuppy.Events;
namespace com.spacepuppy.UI
{
[RequireComponent(typeof(RectTransform))]
public class SPUIButton : Selectable, IUIComponent, IPointerClickHandler, ISubmitHandler, IObservableTrigger
{
[System.Flags]
public enum ButtonMask
{
Left = 1 << PointerEventData.InputButton.Left,
Right = 1 << PointerEventData.InputButton.Right,
Middle = 1 << PointerEventData.InputButton.Middle,
}
#region Fields
[SerializeField]
private SPEvent _onClick = new SPEvent("OnClick");
[SerializeField]
[TimeUnitsSelector("Seconds")]
private float _clickDuration = float.PositiveInfinity;
[SerializeField, EnumFlags]
private ButtonMask _acceptedButtons = ButtonMask.Left;
[System.NonSerialized]
private double _lastDownTime;
#endregion
#region CONSTRUCTOR
public SPUIButton()
{
#if UNITY_EDITOR
com.spacepuppy.Dynamic.DynamicUtil.SetValue(this, "m_Transition", Transition.None);
#endif
}
#endregion
#region Properties
public float ClickDuration
{
get => _clickDuration;
set => _clickDuration = value;
}
public SPEvent OnClick => _onClick;
/// <summary>
/// Reflects which mouse button effected the click. This is only set if during a click event.
/// OnSubmit signaling a click does not set this.
/// </summary>
public PointerEventData.InputButton? CurrentClickButton { get; private set; }
#endregion
#region Methods
private void SignalOnClick()
{
if (!this.IsActive() || !IsInteractable()) return;
_onClick.ActivateTrigger(this, null);
}
public override void OnPointerDown(PointerEventData eventData)
{
var ebtn = eventData.button;
if (((1 << (int)ebtn) & (int)_acceptedButtons) == 0) return;
try
{
eventData.button = PointerEventData.InputButton.Left; //Selectable only responds to leftclick, this fakes that
base.OnPointerDown(eventData);
_lastDownTime = Time.unscaledTimeAsDouble;
}
finally
{
eventData.button = ebtn; //reset the button so any other IPointerXXX message receivers get the correct info
}
}
public override void OnPointerUp(PointerEventData eventData)
{
var ebtn = eventData.button;
if (((1 << (int)ebtn) & (int)_acceptedButtons) == 0) return;
try
{
eventData.button = PointerEventData.InputButton.Left; //Selectable only responds to leftclick, this fakes that
base.OnPointerUp(eventData);
}
finally
{
eventData.button = ebtn; //reset the button so any other IPointerXXX message receivers get the correct info
}
}
public virtual void OnPointerClick(PointerEventData eventData)
{
var ebtn = eventData.button;
if (((1 << (int)ebtn) & (int)_acceptedButtons) == 0) return;
//if (eventData.button != PointerEventData.InputButton.Left) return;
try
{
this.CurrentClickButton = ebtn;
double delta = Time.unscaledTimeAsDouble - _lastDownTime;
if (delta >= 0f && delta <= _clickDuration)
{
SignalOnClick();
}
}
finally
{
this.CurrentClickButton = null;
}
}
public virtual void OnSubmit(BaseEventData eventData)
{
SignalOnClick();
if (!this.IsActive() || !IsInteractable()) return;
DoStateTransition(SelectionState.Pressed, false);
this.StartCoroutine(this.OnSubmit_DelayedFadeOut(colors.fadeDuration));
}
private System.Collections.IEnumerable OnSubmit_DelayedFadeOut(float duration)
{
float t = 0f;
while (t < duration)
{
yield return null;
t += SPTime.Real.Delta;
}
DoStateTransition(currentSelectionState, false);
}
#endregion
#region IUIComponent Interface
public new RectTransform transform => base.transform as RectTransform;
RectTransform IUIComponent.transform => base.transform as RectTransform;
Component IComponent.component => this;
[System.NonSerialized]
private Canvas _canvas;
Canvas IUIComponent.canvas
{
get
{
if (!_canvas) _canvas = IUIComponentExtensions.FindCanvas(this.gameObject);
return _canvas;
}
}
#endregion
#region IObservableTrigger Interface
BaseSPEvent[] IObservableTrigger.GetEvents()
{
return this.GetEvents();
}
protected virtual BaseSPEvent[] GetEvents()
{
return new BaseSPEvent[] { _onClick };
}
#endregion
}
}
| 0 | 0.96267 | 1 | 0.96267 | game-dev | MEDIA | 0.668158 | game-dev | 0.935755 | 1 | 0.935755 |
ghostinthecamera/IGCS-GITC | 1,911 | Cameras/Dark Souls 3/InjectableGenericCameraSystem/BinaryPathStructs.h | #pragma once
#include "PathManager.h"
namespace IGCS::BinaryPathStructs
{
// Binary format version - increment when structure changes
constexpr uint8_t BINARY_PATH_FORMAT_VERSION = 1;
// Binary structures must be packed to ensure consistent memory layout
#pragma pack(push, 1)
// Header for the entire data packet
struct BinaryPathHeader {
uint8_t formatVersion; // Format version for compatibility checking
uint8_t pathCount; // Number of paths in the packet
};
// Header for each path
struct BinaryPathData {
uint16_t nameLength; // Length of the path name string (keep uint16_t for longer names)
uint8_t nodeCount; // Number of nodes in this path
// Followed by nameLength bytes for the path name (char array)
// Followed by nodeCount BinaryNodeData structures
};
// Data for a single camera node
struct BinaryNodeData {
uint8_t index; // Node index
float position[3]; // x, y, z
float rotation[4]; // x, y, z, w (quaternion)
float fov; // Field of view
};
#pragma pack(pop)
// Helper function to calculate the size of a path in bytes
inline size_t calculatePathSize(const std::string& pathName, size_t nodeCount) {
return sizeof(BinaryPathData) + pathName.length() + (nodeCount * sizeof(BinaryNodeData));
}
// Helper function to calculate the total size of all paths in bytes
inline size_t calculateTotalSize(const CameraPathManager& manager) {
size_t totalSize = sizeof(BinaryPathHeader);
for (const auto& pair : manager.getPaths()) {
const std::string& pathName = pair.first;
const CameraPath& path = pair.second;
totalSize += calculatePathSize(pathName, path.GetNodeCount());
}
return totalSize;
}
}
| 0 | 0.969972 | 1 | 0.969972 | game-dev | MEDIA | 0.327279 | game-dev | 0.948232 | 1 | 0.948232 |
apstygo/sfiii-decomp | 1,911 | src/anniversary/sf33rd/Source/Game/EFFA5.c | #include "sf33rd/Source/Game/EFFA5.h"
#include "common.h"
#include "sf33rd/Source/Game/BCD.h"
#include "sf33rd/Source/Game/EFFECT.h"
#include "sf33rd/Source/Game/debug/Debug.h"
#include "sf33rd/Source/Game/workuser.h"
s32 Check_Sleep_A5(WORK_Other* ewk);
void effect_A5_move(WORK_Other* ewk) {
if (Present_Mode == 4 || Present_Mode == 5) {
return;
}
if (Debug_w[24]) {
return;
}
if (Break_Into) {
return;
}
switch (ewk->wu.routine_no[0]) {
case 0:
if (Time_Stop == 0) {
ewk->wu.routine_no[0]++;
}
break;
case 1:
if (!Check_Sleep_A5(ewk)) {
break;
}
if (--Unit_Of_Timer) {
break;
}
Unit_Of_Timer = 50;
bcdext = 0;
if ((Select_Timer = sbcd(1, Select_Timer)) == 0) {
ewk->wu.routine_no[0]++;
ewk->wu.dir_timer = 30;
}
break;
case 2:
if (!Check_Sleep_A5(ewk)) {
break;
}
if (Select_Timer) {
ewk->wu.routine_no[0] = 1;
Unit_Of_Timer = 50;
} else if (--ewk->wu.dir_timer == 0) {
Time_Over = 1;
ewk->wu.routine_no[0]++;
}
break;
case 3:
if (!Check_Sleep_A5(ewk)) {
break;
}
Time_Over = 1;
if (Select_Timer) {
ewk->wu.routine_no[0] = 1;
Unit_Of_Timer = 50;
}
break;
default:
push_effect_work(&ewk->wu);
break;
}
}
s32 Check_Sleep_A5(WORK_Other* ewk) {
if (Time_Stop == 2) {
ewk->wu.routine_no[0] = 0;
}
return 1;
}
s32 effect_A5_init() {
WORK_Other* ewk;
s16 ix;
if ((ix = pull_effect_work(4)) == -1) {
return -1;
}
ewk = (WORK_Other*)frw[ix];
ewk->wu.be_flag = 1;
ewk->wu.id = 105;
return 0;
}
| 0 | 0.826218 | 1 | 0.826218 | game-dev | MEDIA | 0.572688 | game-dev | 0.957905 | 1 | 0.957905 |
AgriCraft/AgriCraft | 7,288 | src/main/java/com/infinityraider/agricraft/content/world/LootModifierGrassDrops.java | package com.infinityraider.agricraft.content.world;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.api.v1.AgriApi;
import com.infinityraider.agricraft.api.v1.plant.IAgriPlant;
import com.infinityraider.infinitylib.loot.IInfLootModifierSerializer;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraftforge.common.loot.GlobalLootModifierSerializer;
import net.minecraftforge.common.loot.LootModifier;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class LootModifierGrassDrops extends LootModifier {
private static final Serializer SERIALIZER = new Serializer();
public static Serializer getSerializer() {
return SERIALIZER;
}
private final boolean reset;
private final double chance;
private final Entry[] entries;
private final int totalWeight;
protected LootModifierGrassDrops(LootItemCondition[] conditions, boolean reset, double chance, Entry[] entries) {
super(conditions);
this.reset = reset;
this.chance = chance;
this.entries = entries;
this.totalWeight = Arrays.stream(entries).mapToInt(Entry::getWeight).sum();
}
protected boolean reset() {
return this.reset;
}
protected double getChance() {
return this.chance;
}
protected boolean roll(Random random) {
return random.nextDouble() < this.getChance();
}
@Nonnull
@Override
protected List<ItemStack> doApply(List<ItemStack> generatedLoot, LootContext context) {
if(AgriCraft.instance.getConfig().allowGrassDropResets() && this.reset()) {
generatedLoot.clear();
}
if(generatedLoot.size() <= 0 && this.roll(context.getRandom()) && this.entries.length > 0) {
Entry entry = this.selectRandomEntry(context.getRandom());
if(entry != null) {
ItemStack stack = entry.generateSeed(context.getRandom());
if(!stack.isEmpty()) {
generatedLoot.add(stack);
}
}
}
return generatedLoot;
}
@Nullable
protected Entry selectRandomEntry(Random random) {
int selector = random.nextInt(this.totalWeight);
for (Entry entry : this.entries) {
if (entry.getWeight() >= selector) {
if (entry.getPlant() != null) {
return entry;
}
}
selector -= entry.weight;
}
return null;
}
public static class Entry {
private final String plantId;
private final int statsMin;
private final int statsMax;
private final int weight;
private IAgriPlant plant;
public Entry(String plantId, int min, int max, int weight) {
this.plantId = plantId;
this.statsMin = min;
this.statsMax = max;
this.weight = weight;
}
public String getPlantId() {
return this.plantId;
}
@Nullable
public IAgriPlant getPlant() {
if(this.plant == null) {
this.plant = AgriApi.getPlantRegistry().get(this.getPlantId()).orElse(null);
}
return this.plant;
}
public int getStatsMin() {
return this.statsMin;
}
public int getStatsMax() {
return this.statsMax;
}
public int generateStat(Random random) {
return random.nextInt(this.getStatsMax() - this.getStatsMin() + 1) + this.getStatsMin();
}
public int getWeight() {
return this.weight;
}
public ItemStack generateSeed(Random random) {
IAgriPlant plant = this.getPlant();
if(plant == null) {
return ItemStack.EMPTY;
}
return AgriApi.getAgriGenomeBuilder(plant)
.randomStats(stat -> this.generateStat(random))
.build()
.toSeedStack();
}
}
public static final class Serializer extends GlobalLootModifierSerializer<LootModifierGrassDrops> implements IInfLootModifierSerializer {
@Nonnull
@Override
public String getInternalName() {
return "grass_seed_drops";
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public LootModifierGrassDrops read(ResourceLocation location, JsonObject object, LootItemCondition[] conditions) {
return new LootModifierGrassDrops(
conditions,
object.get("reset").getAsBoolean(),
object.get("chance").getAsDouble(),
this.readEntries(object.get("seeds").getAsJsonArray())
);
}
protected Entry[] readEntries(JsonArray array) {
Entry[] entries = new Entry[array.size()];
for(int i = 0; i < entries.length; i++) {
entries[i] = this.readEntry(array.get(i).getAsJsonObject());
}
return entries;
}
protected Entry readEntry(JsonObject object) {
String plant = object.get("plant").getAsString();
JsonArray statsArray = object.get("stats").getAsJsonArray();
if(statsArray.size() != 2) {
throw new JsonSyntaxException("The \"stats\" field in an agricraft:grass_drops seed entry must contain 2 numbers");
}
int min = statsArray.get(0).getAsInt();
int max = statsArray.get(1).getAsInt();
if(min > max) {
throw new JsonSyntaxException("The first value in the \"stats\" field in an agricraft:grass_drops seed entry must not be larger than the second");
}
int weight = object.get("weight").getAsInt();
return new Entry(plant, min, max, weight);
}
@Override
public JsonObject write(LootModifierGrassDrops instance) {
JsonObject json = super.makeConditions(instance.conditions);
json.addProperty("reset", instance.reset());
json.addProperty("chance", instance.getChance());
JsonArray entries = new JsonArray();
Arrays.stream(instance.entries).map(this::writeEntry).forEach(entries::add);
json.add("seeds", entries);
return json;
}
protected JsonObject writeEntry(Entry entry) {
JsonObject json = new JsonObject();
json.addProperty("plant", entry.getPlantId());
JsonArray statsArray = new JsonArray();
statsArray.add(entry.getStatsMin());
statsArray.add(entry.getStatsMax());
json.add("stats", statsArray);
json.addProperty("weight", entry.getWeight());
return json;
}
}
}
| 0 | 0.946437 | 1 | 0.946437 | game-dev | MEDIA | 0.994256 | game-dev | 0.974422 | 1 | 0.974422 |
EphemeralSpace/ephemeral-space | 1,581 | Content.Client/Strip/StrippableSystem.cs | using Content.Client.Inventory;
using Content.Shared.Cuffs.Components;
using Content.Shared.Ensnaring.Components;
using Content.Shared.Hands;
using Content.Shared.Inventory.Events;
using Content.Shared.Strip;
using Content.Shared.Strip.Components;
namespace Content.Client.Strip;
/// <summary>
/// This is the client-side stripping system, which just triggers UI updates on events.
/// </summary>
public sealed class StrippableSystem : SharedStrippableSystem
{
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<StrippableComponent, CuffedStateChangeEvent>(OnCuffStateChange);
SubscribeLocalEvent<StrippableComponent, DidEquipEvent>(UpdateUi);
SubscribeLocalEvent<StrippableComponent, DidUnequipEvent>(UpdateUi);
SubscribeLocalEvent<StrippableComponent, DidEquipHandEvent>(UpdateUi);
SubscribeLocalEvent<StrippableComponent, DidUnequipHandEvent>(UpdateUi);
SubscribeLocalEvent<StrippableComponent, EnsnaredChangedEvent>(UpdateUi);
}
private void OnCuffStateChange(EntityUid uid, StrippableComponent component, ref CuffedStateChangeEvent args)
{
UpdateUi(uid, component);
}
public void UpdateUi(EntityUid uid, StrippableComponent? component = null, EntityEventArgs? args = null)
{
if (!TryComp(uid, out UserInterfaceComponent? uiComp))
return;
foreach (var ui in uiComp.ClientOpenInterfaces.Values)
{
if (ui is StrippableBoundUserInterface stripUi)
stripUi.DirtyMenu();
}
}
}
| 0 | 0.796836 | 1 | 0.796836 | game-dev | MEDIA | 0.962392 | game-dev | 0.778283 | 1 | 0.778283 |
FoxMCTeam/TenacityRecode-master | 2,444 | src/java/net/optifine/util/SmoothFloat.java | package net.optifine.util;
public class SmoothFloat
{
private float valueLast;
private float timeFadeUpSec;
private float timeFadeDownSec;
private long timeLastMs;
public SmoothFloat(float valueLast, float timeFadeSec)
{
this(valueLast, timeFadeSec, timeFadeSec);
}
public SmoothFloat(float valueLast, float timeFadeUpSec, float timeFadeDownSec)
{
this.valueLast = valueLast;
this.timeFadeUpSec = timeFadeUpSec;
this.timeFadeDownSec = timeFadeDownSec;
this.timeLastMs = System.currentTimeMillis();
}
public float getValueLast()
{
return this.valueLast;
}
public float getTimeFadeUpSec()
{
return this.timeFadeUpSec;
}
public float getTimeFadeDownSec()
{
return this.timeFadeDownSec;
}
public long getTimeLastMs()
{
return this.timeLastMs;
}
public float getSmoothValue(float value, float timeFadeUpSec, float timeFadeDownSec)
{
this.timeFadeUpSec = timeFadeUpSec;
this.timeFadeDownSec = timeFadeDownSec;
return this.getSmoothValue(value);
}
public float getSmoothValue(float value)
{
long i = System.currentTimeMillis();
float f = this.valueLast;
long j = this.timeLastMs;
float f1 = (float)(i - j) / 1000.0F;
float f2 = value >= f ? this.timeFadeUpSec : this.timeFadeDownSec;
float f3 = getSmoothValue(f, value, f1, f2);
this.valueLast = f3;
this.timeLastMs = i;
return f3;
}
public static float getSmoothValue(float valPrev, float value, float timeDeltaSec, float timeFadeSec)
{
if (timeDeltaSec <= 0.0F)
{
return valPrev;
}
else
{
float f = value - valPrev;
float f1;
if (timeFadeSec > 0.0F && timeDeltaSec < timeFadeSec && Math.abs(f) > 1.0E-6F)
{
float f2 = timeFadeSec / timeDeltaSec;
float f3 = 4.61F;
float f4 = 0.13F;
float f5 = 10.0F;
float f6 = f3 - 1.0F / (f4 + f2 / f5);
float f7 = timeDeltaSec / timeFadeSec * f6;
f7 = NumUtils.limit(f7, 0.0F, 1.0F);
f1 = valPrev + f * f7;
}
else
{
f1 = value;
}
return f1;
}
}
}
| 0 | 0.820116 | 1 | 0.820116 | game-dev | MEDIA | 0.49742 | game-dev | 0.744311 | 1 | 0.744311 |
OpenMPDK/KVCeph | 6,974 | src/rgw/rgw_rest_pubsub_common.h | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#pragma once
#include <string>
#include <optional>
#include "rgw_op.h"
#include "rgw_pubsub.h"
// create a topic
class RGWPSCreateTopicOp : public RGWDefaultResponseOp {
protected:
std::optional<RGWUserPubSub> ups;
std::string topic_name;
rgw_pubsub_sub_dest dest;
std::string topic_arn;
virtual int get_params() = 0;
public:
int verify_permission() override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute() override;
const char* name() const override { return "pubsub_topic_create"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_TOPIC_CREATE; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
// list all topics
class RGWPSListTopicsOp : public RGWOp {
protected:
std::optional<RGWUserPubSub> ups;
rgw_pubsub_user_topics result;
public:
int verify_permission() override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute() override;
const char* name() const override { return "pubsub_topics_list"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_TOPICS_LIST; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
// get topic information
class RGWPSGetTopicOp : public RGWOp {
protected:
std::string topic_name;
std::optional<RGWUserPubSub> ups;
rgw_pubsub_topic_subs result;
virtual int get_params() = 0;
public:
int verify_permission() override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute() override;
const char* name() const override { return "pubsub_topic_get"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_TOPIC_GET; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
// delete a topic
class RGWPSDeleteTopicOp : public RGWDefaultResponseOp {
protected:
string topic_name;
std::optional<RGWUserPubSub> ups;
virtual int get_params() = 0;
public:
int verify_permission() override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute() override;
const char* name() const override { return "pubsub_topic_delete"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_TOPIC_DELETE; }
uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
};
// create a subscription
class RGWPSCreateSubOp : public RGWDefaultResponseOp {
protected:
std::string sub_name;
std::string topic_name;
std::optional<RGWUserPubSub> ups;
rgw_pubsub_sub_dest dest;
virtual int get_params() = 0;
public:
int verify_permission() override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute() override;
const char* name() const override { return "pubsub_subscription_create"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_SUB_CREATE; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
// get subscription information (including push-endpoint if exist)
class RGWPSGetSubOp : public RGWOp {
protected:
std::string sub_name;
std::optional<RGWUserPubSub> ups;
rgw_pubsub_sub_config result;
virtual int get_params() = 0;
public:
int verify_permission() override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute() override;
const char* name() const override { return "pubsub_subscription_get"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_SUB_GET; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
// delete subscription
class RGWPSDeleteSubOp : public RGWDefaultResponseOp {
protected:
std::string sub_name;
std::string topic_name;
std::optional<RGWUserPubSub> ups;
virtual int get_params() = 0;
public:
int verify_permission() override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute() override;
const char* name() const override { return "pubsub_subscription_delete"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_SUB_DELETE; }
uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
};
// acking of an event
class RGWPSAckSubEventOp : public RGWDefaultResponseOp {
protected:
std::string sub_name;
std::string event_id;
std::optional<RGWUserPubSub> ups;
virtual int get_params() = 0;
public:
RGWPSAckSubEventOp() {}
int verify_permission() override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute() override;
const char* name() const override { return "pubsub_subscription_ack"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_SUB_ACK; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
// fetching events from a subscription
// dpending on whether the subscription was created via s3 compliant API or not
// the matching events will be returned
class RGWPSPullSubEventsOp : public RGWOp {
protected:
int max_entries{0};
std::string sub_name;
std::string marker;
std::optional<RGWUserPubSub> ups;
RGWUserPubSub::SubRef sub;
virtual int get_params() = 0;
public:
RGWPSPullSubEventsOp() {}
int verify_permission() override {
return 0;
}
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
void execute() override;
const char* name() const override { return "pubsub_subscription_pull"; }
RGWOpType get_type() override { return RGW_OP_PUBSUB_SUB_PULL; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
// notification creation
class RGWPSCreateNotifOp : public RGWDefaultResponseOp {
protected:
std::optional<RGWUserPubSub> ups;
string bucket_name;
RGWBucketInfo bucket_info;
virtual int get_params() = 0;
public:
int verify_permission() override;
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
RGWOpType get_type() override { return RGW_OP_PUBSUB_NOTIF_CREATE; }
uint32_t op_mask() override { return RGW_OP_TYPE_WRITE; }
};
// delete a notification
class RGWPSDeleteNotifOp : public RGWDefaultResponseOp {
protected:
std::optional<RGWUserPubSub> ups;
std::string bucket_name;
RGWBucketInfo bucket_info;
virtual int get_params() = 0;
public:
int verify_permission() override;
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
RGWOpType get_type() override { return RGW_OP_PUBSUB_NOTIF_DELETE; }
uint32_t op_mask() override { return RGW_OP_TYPE_DELETE; }
};
// get topics/notifications on a bucket
class RGWPSListNotifsOp : public RGWOp {
protected:
std::string bucket_name;
RGWBucketInfo bucket_info;
std::optional<RGWUserPubSub> ups;
virtual int get_params() = 0;
public:
int verify_permission() override;
void pre_exec() override {
rgw_bucket_object_pre_exec(s);
}
RGWOpType get_type() override { return RGW_OP_PUBSUB_NOTIF_LIST; }
uint32_t op_mask() override { return RGW_OP_TYPE_READ; }
};
| 0 | 0.722929 | 1 | 0.722929 | game-dev | MEDIA | 0.260902 | game-dev | 0.535527 | 1 | 0.535527 |
Camotoy/BedrockSkinUtility | 1,808 | src/main/java/net/camotoy/bedrockskinutility/client/MixinConfigPlugin.java | package net.camotoy.bedrockskinutility.client;
import net.fabricmc.loader.api.FabricLoader;
import org.objectweb.asm.tree.ClassNode;
import org.slf4j.LoggerFactory;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import java.util.List;
import java.util.Set;
public class MixinConfigPlugin implements IMixinConfigPlugin {
@Override
public void onLoad(String mixinPackage) {
}
@Override
public String getRefMapperConfig() {
return null;
}
@Override
public boolean shouldApplyMixin(String targetClassName, String mixinClassName) {
if (mixinClassName.equals("net.camotoy.bedrockskinutility.client.mixin.CapeFeatureRendererMixin")) {
boolean capes = FabricLoader.getInstance().getModContainer("capes").isPresent()
|| FabricLoader.getInstance().getModContainer("cosmetica").isPresent();
if (capes) {
// these mods have Mixins that just set all capes to transparent, so we don't need this Mixin
LoggerFactory.getLogger(MixinConfigPlugin.class).info("Disabling transparent cape mixin in BedrockSkinUtility as another cape-related mod is also installed.");
return false;
}
}
return true;
}
@Override
public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) {
}
@Override
public List<String> getMixins() {
return null;
}
@Override
public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
}
@Override
public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
}
}
| 0 | 0.843395 | 1 | 0.843395 | game-dev | MEDIA | 0.884424 | game-dev | 0.883127 | 1 | 0.883127 |
AXiX-official/CrossCoreLuascripts | 3,468 | ios/Others/DungeonActivityView3.lua | local openInfo = nil
local lastBGM = nil
local isLoading = false
function Awake()
eventMgr = ViewEvent.New()
eventMgr:AddListener(EventType.Mission_List, function ()
SetRed(MissionMgr:CheckDungeonActivityRed(data.id))
end)
eventMgr:AddListener(EventType.Bag_Update, function()
CSAPI.SetText(txtNum, BagMgr:GetCount(10201) .. "")
end)
-- eventMgr:AddListener(EventType.View_Lua_Closed,OnViewClosed)
eventMgr:AddListener(EventType.Scene_Load_Complete, OnLoadComplete)
end
function OnViewClosed(viewKey)
if viewKey == "Plot" then
CSAPI.PlayBGM("Sys_Hesitant_Cage", 1)
end
end
function OnLoadComplete()
if isLoading then
FuncUtil:Call(function ()
if gameObject then
lastBGM = CSAPI.PlayBGM("Sys_Hesitant_Cage", 1)
end
end,nil,200)
end
end
function OnInit()
UIUtil:AddTop2("DungeonActivity3", gameObject, OnClickReturn);
end
function Update()
if openInfo and not openInfo:IsOpen() then
openInfo = nil
LanguageMgr:ShowTips(24001)
UIUtil:ToHome()
end
end
function OnOpen()
if openSetting and openSetting.isDungeonOver then --战斗完返回
isLoading = true
else
lastBGM = CSAPI.PlayBGM("Sys_Hesitant_Cage", 1)
end
if data then
SetEffectScale()
SetTime()
SetNum()
SetRed(MissionMgr:CheckDungeonActivityRed(data.id))
-- SetPlot()
end
end
function SetEffectScale()
local canvasSize = CSAPI.GetMainCanvasSize()
local scale1 = canvasSize[0] / 1920
local scale2 = canvasSize[1] / 1080
local scale = scale1 > scale2 and scale1 or scale2
CSAPI.SetScale(effect_bg,scale,scale,scale)
end
function SetTime()
local sectionData = DungeonMgr:GetSectionData(data.id)
if sectionData then
openInfo = DungeonMgr:GetActiveOpenInfo(sectionData:GetActiveOpenID())
if openInfo:IsDungeonOpen() then
local strs = openInfo:GetTimeStrs()
local str = LanguageMgr:GetByID(22021) .. strs[1] .. " " .. strs[2] .. "-" .. strs[3] .. " " .. strs[4]
CSAPI.SetText(txtTime, str)
else
local str = openInfo:GetCloseTimeStr()
CSAPI.SetText(txtTime,str)
end
end
end
function SetNum()
CSAPI.SetText(txtNum, BagMgr:GetCount(10201) .. "")
end
function SetRed(b)
UIUtil:SetRedPoint(redParent,b,0,0)
end
function SetPlot()
local sectionData = DungeonMgr:GetSectionData(data.id)
if sectionData:GetStoryID() and (not PlotMgr:IsPlayed(sectionData:GetStoryID())) then
PlotMgr:TryPlay(sectionData:GetStoryID(), function()
PlotMgr:Save()
end, this, true);
end
end
function OnClickMission()
CSAPI.OpenView("MissionActivity", {
type = eTaskType.Story,
group = data.id,
title = LanguageMgr:GetByID(6021)
})
end
function OnClickShop()
CSAPI.OpenView("ShopView",openInfo:GetShopID())
end
function OnClickDungeon()
if not openInfo:IsDungeonOpen() then
LanguageMgr:ShowTips(24003)
return
end
if data then
CSAPI.OpenView("DungeonRole", {
id = data.id
})
end
end
function OnClickReturn()
view:Close()
end
function OnDestroy()
-- EventMgr.Dispatch(EventType.Replay_BGM);
if not FightClient:IsFightting() then --不在战斗中关闭界面时重播bgm
CSAPI.ReplayBGM(lastBGM)
end
eventMgr:ClearListener()
end
| 0 | 0.814502 | 1 | 0.814502 | game-dev | MEDIA | 0.81452 | game-dev | 0.888173 | 1 | 0.888173 |
holycake/mhsj | 793 | d/xueshan/wuchang-nw.c | //standroom.c used by weiqi...others may hate this format:D
//wuchang-nw.c
inherit ROOM;
void create ()
{
set ("short", "西北武场");
set ("long", @LONG
这是冰宫前的一块平地,供大雪山弟子练功之用。冰面极平,光
鉴照人。不过走在上面得小心点,雪山弟子也正是借此锻炼下盘
的稳固功夫。东面的一栋房子顶上一股炊烟冉冉升起,想必是厨
房了。
LONG);
//set("item_desc", ([" *** " : " *** \n", ]));
//for look something.
set("exits",
([ //sizeof() == 4
"south" : __DIR__"wuchang-w",
//"north" : __DIR__"icegate",
//"west" : __DIR__"restroom",
"east" : __DIR__"wuchang-n",
//"up" : __DIR__"***",
//"down" : __DIR__"***",
]));
set("objects",
([ //sizeof() == 1
"/d/obj/misc/ice" : 2,
//__DIR__"npc/yingwu-guai" : 1,
]));
set("outdoors", "xueshan");
setup();
}
//void init()
//{
//add_action("do_jump", "jump");
//}
//int do_jump(string arg)
//{
//}
| 0 | 0.644293 | 1 | 0.644293 | game-dev | MEDIA | 0.877875 | game-dev | 0.661924 | 1 | 0.661924 |
Laidout/laidout | 8,874 | src/dataobjects/objectcontainer.cc | //
//
// Laidout, for laying out
// Please consult http://www.laidout.org about where to send any
// correspondence about this software.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
// For more details, consult the COPYING file in the top directory.
//
// Copyright (C) 2004-2007,2010-2013 by Tom Lechner
//
#include "objectcontainer.h"
#include <cstdlib>
#include <iostream>
using namespace std;
#define DBG
namespace Laidout {
//------------------------------ ObjectContainer ----------------------------------
/*! \class ObjectContainer
* \brief Abstract base class to simplify project wide object tree searching.
*
* Used by Group, LaidoutViewport, Spread, and others to be a generic object
* container. Access methods should be considered very temporary. They are not quite
* equivalent to member access in scripting. Containment is queried entirely by index numbers,
* not named extensions, and how those numbers are sometimes assigned depending on state at the moment,
* not on a standardized naming system as in scripting.
*
* No actual data list is defined here, only access methods.
* Three functions are built in: getanObject(), contains(), and nextObject(). Derived
* classes must define their own n() and object_e().
*
* \todo *** do something with parent...
*/
/*! \fn int ObjectContainer::n()
* \brief Return the number of objects that can be returned.
*/
/*! \fn Laxkit::anObject *ObjectContainer::object_e(int i)
* \brief Return pointer to object with index i.
*/
/*! \fn const char *ObjectContainer::object_e(int i)
* \brief Return the name of fild with index i.
*/
/*! \var unsigned int ObjectContainer::obj_flags
* \brief Any permanent flags. Returned by default in object_flags().
*/
ObjectContainer::ObjectContainer()
{
//parent=NULL;
obj_flags=0;
id=NULL;
}
ObjectContainer::~ObjectContainer()
{
if (id) delete[] id;
}
//! Find the next object from place, modifying place to refer to it.
/*! Also make d point to it if found. This function does not check against any first
* object. That is a higher level searching function.
*
* offset means that *this corresponds to place.e(offset-1). In other words,
* place.e(offset) is an index referring to a child of *this.
*
* Incrementing\n
* If an object has kids, then step to the first child.
* If an object has no kids, then step to its next sibling.
* If there are no more siblings, then step to next sibling of the parent, or its parent's sibling, etc.
*
* Return Next_Success on successful stepping. Place points to that next step.\n
* Return Next_Error for error.\n
*
* \todo *** should implement 1. search only at offset's level,
* 2. select only leaves (nodes with no children),
* 3. (other search criteria? maybe pass in check function?)
*/
int ObjectContainer::nextObject(FieldPlace &place,
int offset,
unsigned int flags,
Laxkit::anObject **d)//d=NULL
{
DBG place.out("ObjectContainer::nextObject start: ");
anObject *anobj=NULL;
ObjectContainer *oc=NULL;
int i,nn;
FieldPlace orig = place;
anobj = getanObject(place,offset); //retrieve the object pointed to by place
oc = dynamic_cast<ObjectContainer *>(anobj);
if (flags&Next_Increment) {
if (oc && !(flags & Next_PlaceLevelOnly)) { //find number of kids to consider
if ((flags & Next_SkipLockedKids) && (oc->object_flags() & OBJ_IgnoreKids)) nn=0;
else nn=oc->n();
} else nn=0;
if (oc && nn) {
//object has kids, return the first kid
place.push(0);
if (d) *d=oc->object_e(0);
DBG place.out("ObjectContainer::nextObject returning A: ");
return Next_Success;
}
//else object does not have kids. switch to next sibling
while (1) {
if (place.n()==offset) {
if (d) *d=anobj;
DBG place.out("ObjectContainer::nextObject returning B: ");
return Next_Success;
}
i=place.pop(); //old child index
anobj=getanObject(place,offset); //retrieve the object pointed to by place
oc=dynamic_cast<ObjectContainer *>(anobj);
if (oc) { //find number of kids to consider
if ((flags&Next_SkipLockedKids) && (oc->object_flags()&OBJ_IgnoreKids)) nn=0;
else nn=oc->n();
} else nn=0;
i++;
if (i<nn) {
//we are able to switch to next sibling
place.push(i);
anobj=getanObject(place,offset); //retrieve the object pointed to by place
if (d) *d=anobj;
DBG place.out("ObjectContainer::nextObject returning C: ");
return Next_Success;
}
//no more kids of original object's parent, so try siblings of parent
}
} else if (flags&Next_Decrement) {
if (place.n()>offset) {
i=place.pop();
if (i==0) {
anobj=getanObject(place,offset); //retrieve the object pointed to by place
if (d) *d=anobj;
DBG place.out("ObjectContainer::nextObject returning D: ");
return Next_Success;
}
//switch to rightmost leaf of earlier sibling
place.push(i-1);
anobj=getanObject(place,offset); //retrieve the object pointed to by place
oc=dynamic_cast<ObjectContainer *>(anobj);
//if (oc && !(flags & Next_PlaceLevelOnly)) { //find number of kids to consider
if (oc) { //find number of kids to consider
if ((flags&Next_SkipLockedKids) && (oc->object_flags()&OBJ_IgnoreKids)) nn=0;
else nn=oc->n();
} else nn=0;
//select the bottom most, forward most child
while (oc && nn) {
place.push(nn-1);
anobj=getanObject(place,offset); //retrieve the object pointed to by place
oc=dynamic_cast<ObjectContainer *>(anobj);
if (oc) { //find number of kids to consider
if ((flags&Next_SkipLockedKids) && (oc->object_flags()&OBJ_IgnoreKids)) nn=0;
else nn=oc->n();
} else nn=0;
}
if (d) *d=anobj;
DBG place.out("ObjectContainer::nextObject returning E: ");
return Next_Success;
}
if (oc && place.n()==offset) {
//If at root, switch to right most leaf
if (oc) { //find number of kids to consider
if ((flags&Next_SkipLockedKids) && (oc->object_flags()&OBJ_IgnoreKids)) nn=0;
else nn=oc->n();
} else nn=0;
while (oc && nn) {
place.push(nn-1);
anobj=getanObject(place,offset); //retrieve the object pointed to by place
oc=dynamic_cast<ObjectContainer *>(anobj);
if (oc) { //find number of kids to consider
if ((flags&Next_SkipLockedKids) && (oc->object_flags()&OBJ_IgnoreKids)) nn=0;
else nn=oc->n();
} else nn=0;
}
if (d) *d=anobj;
DBG place.out("ObjectContainer::nextObject returning F: ");
return Next_Success;
}
}
if (d) *d=this;
DBG place.out("ObjectContainer::nextObject end G: ");
return Next_Success;
}
//! Retrieve the object at position place.
/*! If offset>0, then check position in place starting at index offset. That is, pretend
* that *this is at offset-1, so place[offset] is a subobject of *this.
*
* If nn>0, then only go down nn number of subobjects from offset. Otherwise, use
* up the rest of place.
*
* If there is no object at that position, then return NULL;
*
* Note that if place.n()==0, then NULL is returned, not <tt>this</tt>.
*/
Laxkit::anObject *ObjectContainer::getanObject(FieldPlace &place, int offset,int nn)//nn=-1
{
// if (place.n()<=offset) return NULL;
// if (place.e(offset)>=n() || place.e(offset)<0) return NULL;
// if (nn<=0) nn=place.n()-offset;
// if (nn==1) { // place refers to this container
// return object_e(place.e(offset));
// }
// // must be a subelement
// ObjectContainer *g=dynamic_cast<ObjectContainer *>(object_e(place.e(offset)));
// if (!g) return NULL;
// return g->getanObject(place,offset+1);
//------------non-recursive:
if (place.n()<offset) return NULL;
if (place.n()==offset) return this;
int i=offset;
ObjectContainer *g=this;
if (nn<=0) nn=place.n()-offset;
while (nn) {
if (place.e(i)>=g->n() || place.e(i)<0) return NULL;
if (nn==1) { // place refers to g
return g->object_e(place.e(i));
}
// must be a subelement
g=dynamic_cast<ObjectContainer *>(g->object_e(place.e(i)));
if (!g) return NULL;
i++;
nn--;
}
return NULL;
}
//! Return whether d is in here somewhere.
/*! Returns place.n if the object is found, which is how deep down the
* object is. Otherwise return 0.
*
* The position gets pushed onto place starting at place.n.
*/
int ObjectContainer::contains(Laxkit::anObject *d,FieldPlace &place)
{
int c;
int m=place.n();
for (c=0; c<n(); c++) {
if (d==object_e(c)) {
place.push(c,m);
return place.n();
}
}
ObjectContainer *g;
for (c=0; c<n(); c++) {
g=dynamic_cast<ObjectContainer *>(object_e(c));
if (g && g->contains(d,place)) {
place.push(c,m);
return place.n();
}
}
return 0;
}
} //namespace Laidout
| 0 | 0.911672 | 1 | 0.911672 | game-dev | MEDIA | 0.257087 | game-dev | 0.922862 | 1 | 0.922862 |
nexusnode/crafting-dead | 8,905 | crafting-dead-core/src/main/java/com/craftingdead/core/world/item/gun/Gun.java | /*
* Crafting Dead
* Copyright (C) 2022 NexusNode LTD
*
* This Non-Commercial Software License Agreement (the "Agreement") is made between
* you (the "Licensee") and NEXUSNODE (BRAD HUNTER). (the "Licensor").
* By installing or otherwise using Crafting Dead (the "Software"), you agree to be
* bound by the terms and conditions of this Agreement as may be revised from time
* to time at Licensor's sole discretion.
*
* If you do not agree to the terms and conditions of this Agreement do not download,
* copy, reproduce or otherwise use any of the source code available online at any time.
*
* https://github.com/nexusnode/crafting-dead/blob/1.18.x/LICENSE.txt
*
* https://craftingdead.net/terms.php
*/
package com.craftingdead.core.world.item.gun;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.craftingdead.core.network.Synched;
import com.craftingdead.core.world.entity.extension.LivingExtension;
import com.craftingdead.core.world.entity.extension.PlayerExtension;
import com.craftingdead.core.world.inventory.GunCraftSlotType;
import com.craftingdead.core.world.item.combatslot.CombatSlotProvider;
import com.craftingdead.core.world.item.equipment.Equipment;
import com.craftingdead.core.world.item.gun.ammoprovider.AmmoProvider;
import com.craftingdead.core.world.item.gun.attachment.Attachment;
import com.craftingdead.core.world.item.gun.attachment.Attachment.MultiplierType;
import com.craftingdead.core.world.item.gun.skin.Skin;
import com.mojang.serialization.Codec;
import net.minecraft.core.Holder;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.util.StringRepresentable;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
public interface Gun extends Equipment, CombatSlotProvider, Synched {
Capability<Gun> CAPABILITY = CapabilityManager.get(new CapabilityToken<>() {});
@Override
default boolean isValidForSlot(Slot slot) {
return slot == Slot.GUN;
}
/**
* Ticked when held by the passed in {@link LivingExtension}.
*
* @param living - the entity holding the gun
*/
void tick(LivingExtension<?, ?> living);
/**
* Reset any actions currently being performed (e.g. secondary action or trigger).
*
* @param living - the entity holding the gun
*/
void reset(LivingExtension<?, ?> living);
/**
* Set the trigger pressed state.
*
* @param living - the entity holding the gun
* @param triggerPressed - whether the trigger is pressed
* @param sendUpdate - send an update to the opposing logical side (client/server)
*/
void setTriggerPressed(LivingExtension<?, ?> living, boolean triggerPressed, boolean sendUpdate);
/**
* Whether the trigger is currently pressed.
*
* @return <code>true</code> if pressed, <code>false</code> otherwise.
*/
boolean isTriggerPressed();
/**
* Handles pending hit messages sent by the client.
*
* @param player - the player who sent the message
* @param hitLiving - the entity hit
* @param pendingHit - hit data
*/
void validatePendingHit(PlayerExtension<ServerPlayer> player,
LivingExtension<?, ?> hitLiving, PendingHit pendingHit);
/**
* Get current accuracy percentage of the gun.
*
* @param living - the entity holding the gun
* @return the accuracy percentage
*/
float getAccuracy(LivingExtension<?, ?> living);
/**
* Get current attachments on the gun.
*
* @return the attachments
*/
Map<GunCraftSlotType, Attachment> getAttachments();
/**
* Get the combined attachment multiplier of the specified {@link MultiplierType}.
*
* @param multiplierType - the type of multiplier
* @return the combined multiplier
*/
default float getAttachmentMultiplier(Attachment.MultiplierType multiplierType) {
return this.getAttachments().values().stream()
.map(attachment -> attachment.getMultiplier(multiplierType))
.reduce(1.0F, (x, y) -> x * y);
}
/**
* Set the attachments on the gun.
*
* @param attachments - the attachments to set
*/
void setAttachments(Map<GunCraftSlotType, Attachment> attachments);
/**
* If the gun has an iron sight (no over-barrel attachments).
*
* @return <code>true</code> if the gun has an iron sight, <code>false</code> otherwise
*/
default boolean hasIronSight() {
return !this.getAttachments().containsKey(GunCraftSlotType.OVERBARREL_ATTACHMENT);
}
/**
* Get the {@link ItemStack} used to paint the gun with.
*
* @return the {@link ItemStack}
*/
ItemStack getPaintStack();
/**
* Paint the gun with the specified {@link ItemStack}.
*
* @param paintStack - the paint {@link ItemStack}
*/
void setPaintStack(ItemStack paintStack);
@Nullable
Skin getSkin();
void setSkin(@Nullable Holder<Skin> skin);
/**
* Get an optional skin to be used for this gun.
*
* @return the optional skin name
*/
default Optional<ResourceLocation> getSkinName() {
return this.getPaintStack().isEmpty()
? Optional.empty()
: Optional.of(this.getPaintStack().getItem().getRegistryName());
}
/**
* Check if the specified {@link ItemStack} is an acceptable paint or attachment for this gun.
*
* @param itemStack - the {@link ItemStack} to check
* @return <code>true</code> if accepted, <code>false</code> otherwise
*/
boolean isAcceptedAttachment(ItemStack itemStack);
/**
* Get the currently selected {@link FireMode}.
*
* @return the {@link FireMode}
*/
FireMode getFireMode();
/**
* Set the current {@link FireMode}.
*
* @param living - the entity holding the gun
* @param fireMode - the selected {@link FireMode}
* @param sendUpdate - send an update to the opposing logical side (client/server)
*/
void setFireMode(LivingExtension<?, ?> living, FireMode fireMode, boolean sendUpdate);
/**
* Toggle the next {@link FireMode}.
*
* @param living - the entity holding the gun
* @param sendUpdate - send an update to the opposing logical side (client/server)
*/
void toggleFireMode(LivingExtension<?, ?> living, boolean sendUpdate);
/**
* If the secondary action of this gun is being performed (e.g. aiming).
*
* @return <code>true</code> if being performed, otherwise <code>false</code>
*/
boolean isPerformingSecondaryAction();
/**
* Set the secondary action performing state.
*
* @param living - the entity holding the gun
* @param performingAction - whether to perform the action or not
* @param sendUpdate - send an update to the opposing logical side (client/server)
*/
void setPerformingSecondaryAction(LivingExtension<?, ?> living, boolean performingAction,
boolean sendUpdate);
/**
* Get the type of trigger for the secondary action.
*
* @return the {@link SecondaryActionTrigger}
*/
SecondaryActionTrigger getSecondaryActionTrigger();
/**
* Get the sound to be played when reloading this gun.
*
* @return an optional {@link SoundEvent}
*/
Optional<SoundEvent> getReloadSound();
/**
* Get the reload duration in ticks of this gun.
*
* @return the duration in ticks
*/
int getReloadDurationTicks();
/**
* Get the {@link GunClient} associated with this gun. Will be null on dedicated server. <br>
* <b>Always check <u>logical</u> side before accessing.
*
* @return
*/
GunClient getClient();
AmmoProvider getAmmoProvider();
void setAmmoProvider(AmmoProvider ammoProvider);
Set<? extends Item> getAcceptedMagazines();
ItemStack getDefaultMagazineStack();
ItemStack getItemStack();
enum SecondaryActionTrigger implements StringRepresentable {
HOLD("hold"), TOGGLE("toggle");
private static final Map<String, SecondaryActionTrigger> BY_NAME = Arrays.stream(values())
.collect(Collectors.toMap(SecondaryActionTrigger::getSerializedName, Function.identity()));
public static final Codec<SecondaryActionTrigger> CODEC =
StringRepresentable.fromEnum(SecondaryActionTrigger::values,
SecondaryActionTrigger::byName);
private final String name;
SecondaryActionTrigger(String name) {
this.name = name;
}
@Override
public @NotNull String getSerializedName() {
return name;
}
public static SecondaryActionTrigger byName(String name) {
return BY_NAME.get(name);
}
}
}
| 0 | 0.837282 | 1 | 0.837282 | game-dev | MEDIA | 0.922073 | game-dev | 0.801158 | 1 | 0.801158 |
Job-Bouwhuis/WinterRose.WinterForge | 1,164 | UsageDocs/WinterRose.WinterForge/CustomValueCompiler.md | # CustomValueCompiler
the compiled variant of [CustomValueProvider](CustomValueProvider_Examples.md)
This system is not foolproof yet i believe, i think the hashes for the types change from PC to PC, but on one pc i believe they are identical
across app runs. further testing will be done and a later version will have a potential fix if this ends up begin a problem
#### Other docs
- [CSharp Usage](CSharp_Usage.md)
- [Syntax Features](Syntax_Features.md)
- [Built-in Functions](WinterForge_Built-in_Functions.md)
- [Custom Value Providers](CustomValueProvider_Examples.md)
- [Anonymous Type Syntax](Anonymous_Type_Syntax.md)
- [Access Restrictions](Access_Restrictions.md)
- [Flow Hooks](FlowHooks.md)
an example of a Vector2 compiler.
```cs
public sealed class Vector2Compiler : CustomValueCompiler<Vector2>
{
public override void Compile(BinaryWriter writer, Vector2 value)
{
writer.Write(value.X);
writer.Write(value.Y);
}
public override Vector2 Decompile(BinaryReader reader)
{
float x = reader.ReadSingle();
float y = reader.ReadSingle();
return new Vector2(x, y);
}
}
``` | 0 | 0.93249 | 1 | 0.93249 | game-dev | MEDIA | 0.200823 | game-dev | 0.76757 | 1 | 0.76757 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.