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
bloomberg/bde
11,940
groups/bsl/bslstl/bslstl_setcomparator.h
// bslstl_setcomparator.h -*-C++-*- #ifndef INCLUDED_BSLSTL_SETCOMPARATOR #define INCLUDED_BSLSTL_SETCOMPARATOR #include <bsls_ident.h> BSLS_IDENT("$Id: $") //@PURPOSE: Provide a comparator for `TreeNode` objects and a lookup key. // //@CLASSES: // bslstl::SetComparator: comparator for `TreeNode` objects and key objects // //@SEE_ALSO: bslstl_set, bslstl_treenode, bslalg_rbtreeutil // //@DESCRIPTION: This component provides a functor adapter, `SetComparator`, // that adapts a parameterized `COMPARATOR` comparing objects of a // parameterized `KEY` type into a functor comparing a object of `KEY` type // with a object of `bslstl::TreeNode` type holding a object of `KEY` type. // Note that this functor was designed to be supplied to functions in // `bslalg::RbTreeUtil` primarily for the purpose of implementing a `set` // container. // ///Usage ///----- // This section illustrates intended use of this component. // ///Example 1: Create a Simple Tree of `TreeNode` Objects ///- - - - - - - - - - - - - - - - - - - - - - - - - - - // Suppose that we want to create a tree of `TreeNode` objects arranged // according to a functor that we supply. // // First, we create an array of `bslstl::TreeNode` objects, each holding a pair // of integers: // ``` // typedef bsl::allocator<TreeNode<int> > Alloc; // // bslma::TestAllocator oa; // Alloc allocator(&oa); // // enum { NUM_NODES = 5 }; // // TreeNode<int>* nodes[NUM_NODES]; // // for (int i = 0; i < NUM_NODES; ++i) { // nodes[i] = allocator.allocate(1); // nodes[i]->value() = i; // } // ``` // Then, we define a `SetComparator` object, `comparator`, for comparing // `bslstl::TreeNode<int>` objects with integers. // ``` // SetComparator<int, std::less<int> > comparator; // ``` // Now, we can use the functions in `bslalg::RbTreeUtil` to arrange our tree: // ``` // bslalg::RbTreeAnchor tree; // // for (int i = 0; i < NUM_NODES; ++i) { // int comparisonResult; // bslalg::RbTreeNode *insertLocation = // bslalg::RbTreeUtil::findUniqueInsertLocation( // &comparisonResult, // &tree, // comparator, // nodes[i]->value()); // // assert(0 != comparisonResult); // // bslalg::RbTreeUtil::insertAt(&tree, // insertLocation, // comparisonResult < 0, // nodes[i]); // } // // assert(5 == tree.numNodes()); // ``` // Then, we use `bslalg::RbTreeUtil::next()` to navigate the elements of the // tree, printing their values: // ``` // const bslalg::RbTreeNode *nodeIterator = tree.firstNode(); // // while (nodeIterator != tree.sentinel()) { // printf("Node value: %d\n", // static_cast<const TreeNode<int> *>(nodeIterator)->value()); // nodeIterator = bslalg::RbTreeUtil::next(nodeIterator); // } // ``` // Next, we destroy and deallocate each of the `bslstl::TreeNode` objects: // ``` // for (int i = 0; i < NUM_NODES; ++i) { // allocator.deallocate(nodes[i], 1); // } // ``` // Finally, we observe the console output: // ``` // Node value: 0 // Node value: 1 // Node value: 2 // Node value: 3 // Node value: 4 // ``` #include <bslscm_version.h> #include <bslstl_pair.h> #include <bslstl_treenode.h> #include <bslalg_functoradapter.h> #include <bslalg_swaputil.h> #include <bslmf_movableref.h> #include <bsls_platform.h> #include <bsls_util.h> namespace BloombergLP { namespace bslstl { // =================== // class SetComparator // =================== // This class overloads the function-call operator to compare a referenced // `bslalg::RbTreeNode` object with a object of the parameterized `KEY` // type, assuming the reference to `bslalg::RbTreeNode` is a base of a // `bslstl::TreeNode` holding an integer, using a functor of the // parameterized `COMPARATOR` type. template <class KEY, class COMPARATOR> #ifdef BSLS_PLATFORM_CMP_MSVC // Visual studio compiler fails to resolve the conversion operator in // `bslalg::FunctorAdapter_FunctionPointer` when using private inheritance. // Below is a workaround until a more suitable way the resolve this issue can // be found. class SetComparator : public bslalg::FunctorAdapter<COMPARATOR>::Type { #else class SetComparator : private bslalg::FunctorAdapter<COMPARATOR>::Type { #endif private: // This class does not support assignment. SetComparator& operator=(const SetComparator&); // Declared but not // defined public: // TYPES /// This alias represents the type of node holding a `KEY` object. typedef TreeNode<KEY> NodeType; // CREATORS /// Create a `SetComparator` object that will use a default constructed /// `COMPARATOR`. SetComparator(); /// Create a `SetComparator` object holding a copy of the specified /// `keyComparator`. explicit SetComparator(const COMPARATOR& keyComparator); /// Create a `SapComparator` object with the `COMPARATOR` object of the /// specified `original` object. //! SetComparator(const SetComparator&) = default; /// Destroy this object. //! ~SapComparator() = default; // MANIPULATORS /// Return `true` if the specified `lhs` is less than (ordered before, /// according to the comparator held by this object) `value()` of the /// specified `rhs` after being cast to `NodeType`, and `false` /// otherwise. The behavior is undefined unless `rhs` can be safely /// cast to `NodeType`. template <class LOOKUP_KEY> bool operator()(const LOOKUP_KEY& lhs, const bslalg::RbTreeNode& rhs); /// Return `true` if `value()` of the specified `lhs` after /// being cast to `NodeType` is less than (ordered before, according to /// the comparator held by this object) the specified `rhs`, and `false` /// otherwise. The behavior is undefined unless `rhs` can be safely /// cast to `NodeType`. template <class LOOKUP_KEY> bool operator()(const bslalg::RbTreeNode& lhs, const LOOKUP_KEY& rhs); /// Efficiently exchange the value of this object with the value of the /// specified `other` object. This method provides the no-throw /// exception-safety guarantee. void swap(SetComparator& other); // ACCESSORS /// Return `true` if the specified `lhs` is less than (ordered before, /// according to the comparator held by this object) `value()` of the /// specified `rhs` after being cast to `NodeType`, and `false` /// otherwise. The behavior is undefined unless `rhs` can be safely /// cast to `NodeType`. template <class LOOKUP_KEY> bool operator()(const LOOKUP_KEY& lhs, const bslalg::RbTreeNode& rhs) const; /// Return `true` if `value()` of the specified `lhs` after /// being cast to `NodeType` is less than (ordered before, according to /// the comparator held by this object) the specified `rhs`, and `false` /// otherwise. The behavior is undefined unless `rhs` can be safely /// cast to `NodeType`. template <class LOOKUP_KEY> bool operator()(const bslalg::RbTreeNode& lhs, const LOOKUP_KEY& rhs) const; /// Return a reference providing modifiable access to the function /// pointer or functor to which this comparator delegates comparison /// operations. COMPARATOR& keyComparator(); /// Return a reference providing non-modifiable access to the function /// pointer or functor to which this comparator delegates comparison /// operations. const COMPARATOR& keyComparator() const; }; // FREE FUNCTIONS /// Efficiently exchange the values of the specified `a` and `b` objects. /// This function provides the no-throw exception-safety guarantee. template <class KEY, class COMPARATOR> void swap(SetComparator<KEY, COMPARATOR>& a, SetComparator<KEY, COMPARATOR>& b); // ============================================================================ // TEMPLATE AND INLINE FUNCTION DEFINITIONS // ============================================================================ // ------------------- // class SetComparator // ------------------- // CREATORS template <class KEY, class COMPARATOR> inline SetComparator<KEY, COMPARATOR>::SetComparator() : bslalg::FunctorAdapter<COMPARATOR>::Type() { } template <class KEY, class COMPARATOR> inline SetComparator<KEY, COMPARATOR>:: SetComparator(const COMPARATOR& valueComparator) : bslalg::FunctorAdapter<COMPARATOR>::Type(valueComparator) { } // MANIPULATORS template <class KEY, class COMPARATOR> template <class LOOKUP_KEY> inline bool SetComparator<KEY, COMPARATOR>::operator()( const LOOKUP_KEY& lhs, const bslalg::RbTreeNode& rhs) { return keyComparator()(lhs, static_cast<const NodeType&>(rhs).value()); } template <class KEY, class COMPARATOR> template <class LOOKUP_KEY> inline bool SetComparator<KEY, COMPARATOR>::operator()( const bslalg::RbTreeNode& lhs, const LOOKUP_KEY& rhs) { return keyComparator()(static_cast<const NodeType&>(lhs).value(), rhs); } template <class KEY, class COMPARATOR> inline void SetComparator<KEY, COMPARATOR>::swap( SetComparator<KEY, COMPARATOR>& other) { bslalg::SwapUtil::swap( static_cast<typename bslalg::FunctorAdapter<COMPARATOR>::Type*>(this), static_cast<typename bslalg::FunctorAdapter<COMPARATOR>::Type*>( BSLS_UTIL_ADDRESSOF(other))); } // ACCESSORS template <class KEY, class COMPARATOR> template <class LOOKUP_KEY> inline bool SetComparator<KEY, COMPARATOR>::operator()( const LOOKUP_KEY& lhs, const bslalg::RbTreeNode& rhs) const { return keyComparator()(lhs, static_cast<const NodeType&>(rhs).value()); } template <class KEY, class COMPARATOR> template <class LOOKUP_KEY> inline bool SetComparator<KEY, COMPARATOR>::operator()( const bslalg::RbTreeNode& lhs, const LOOKUP_KEY& rhs) const { return keyComparator()(static_cast<const NodeType&>(lhs).value(), rhs); } template <class KEY, class COMPARATOR> inline COMPARATOR& SetComparator<KEY, COMPARATOR>::keyComparator() { return *this; } template <class KEY, class COMPARATOR> inline const COMPARATOR& SetComparator<KEY, COMPARATOR>::keyComparator() const { return *this; } // FREE FUNCTIONS template <class KEY, class COMPARATOR> inline void swap(SetComparator<KEY, COMPARATOR>& a, SetComparator<KEY, COMPARATOR>& b) { a.swap(b); } } // close package namespace } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
412
0.967594
1
0.967594
game-dev
MEDIA
0.270873
game-dev
0.863594
1
0.863594
SwitchGDX/switch-gdx
8,769
switch-gdx/res/switchgdx/bullet/bullet/LinearMath/btTransform.h
/* Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_TRANSFORM_H #define BT_TRANSFORM_H #include "btMatrix3x3.h" #ifdef BT_USE_DOUBLE_PRECISION #define btTransformData btTransformDoubleData #else #define btTransformData btTransformFloatData #endif /**@brief The btTransform class supports rigid transforms with only translation and rotation and no scaling/shear. *It can be used in combination with btVector3, btQuaternion and btMatrix3x3 linear algebra classes. */ ATTRIBUTE_ALIGNED16(class) btTransform { ///Storage for the rotation btMatrix3x3 m_basis; ///Storage for the translation btVector3 m_origin; public: /**@brief No initialization constructor */ btTransform() {} /**@brief Constructor from btQuaternion (optional btVector3 ) * @param q Rotation from quaternion * @param c Translation from Vector (default 0,0,0) */ explicit SIMD_FORCE_INLINE btTransform(const btQuaternion& q, const btVector3& c = btVector3(btScalar(0), btScalar(0), btScalar(0))) : m_basis(q), m_origin(c) {} /**@brief Constructor from btMatrix3x3 (optional btVector3) * @param b Rotation from Matrix * @param c Translation from Vector default (0,0,0)*/ explicit SIMD_FORCE_INLINE btTransform(const btMatrix3x3& b, const btVector3& c = btVector3(btScalar(0), btScalar(0), btScalar(0))) : m_basis(b), m_origin(c) {} /**@brief Copy constructor */ SIMD_FORCE_INLINE btTransform (const btTransform& other) : m_basis(other.m_basis), m_origin(other.m_origin) { } /**@brief Assignment Operator */ SIMD_FORCE_INLINE btTransform& operator=(const btTransform& other) { m_basis = other.m_basis; m_origin = other.m_origin; return *this; } /**@brief Set the current transform as the value of the product of two transforms * @param t1 Transform 1 * @param t2 Transform 2 * This = Transform1 * Transform2 */ SIMD_FORCE_INLINE void mult(const btTransform& t1, const btTransform& t2) { m_basis = t1.m_basis * t2.m_basis; m_origin = t1(t2.m_origin); } /* void multInverseLeft(const btTransform& t1, const btTransform& t2) { btVector3 v = t2.m_origin - t1.m_origin; m_basis = btMultTransposeLeft(t1.m_basis, t2.m_basis); m_origin = v * t1.m_basis; } */ /**@brief Return the transform of the vector */ SIMD_FORCE_INLINE btVector3 operator()(const btVector3& x) const { return x.dot3(m_basis[0], m_basis[1], m_basis[2]) + m_origin; } /**@brief Return the transform of the vector */ SIMD_FORCE_INLINE btVector3 operator*(const btVector3& x) const { return (*this)(x); } /**@brief Return the transform of the btQuaternion */ SIMD_FORCE_INLINE btQuaternion operator*(const btQuaternion& q) const { return getRotation() * q; } /**@brief Return the basis matrix for the rotation */ SIMD_FORCE_INLINE btMatrix3x3& getBasis() { return m_basis; } /**@brief Return the basis matrix for the rotation */ SIMD_FORCE_INLINE const btMatrix3x3& getBasis() const { return m_basis; } /**@brief Return the origin vector translation */ SIMD_FORCE_INLINE btVector3& getOrigin() { return m_origin; } /**@brief Return the origin vector translation */ SIMD_FORCE_INLINE const btVector3& getOrigin() const { return m_origin; } /**@brief Return a quaternion representing the rotation */ btQuaternion getRotation() const { btQuaternion q; m_basis.getRotation(q); return q; } /**@brief Set from an array * @param m A pointer to a 16 element array (12 rotation(row major padded on the right by 1), and 3 translation */ void setFromOpenGLMatrix(const btScalar *m) { m_basis.setFromOpenGLSubMatrix(m); m_origin.setValue(m[12],m[13],m[14]); } /**@brief Fill an array representation * @param m A pointer to a 16 element array (12 rotation(row major padded on the right by 1), and 3 translation */ void getOpenGLMatrix(btScalar *m) const { m_basis.getOpenGLSubMatrix(m); m[12] = m_origin.x(); m[13] = m_origin.y(); m[14] = m_origin.z(); m[15] = btScalar(1.0); } /**@brief Set the translational element * @param origin The vector to set the translation to */ SIMD_FORCE_INLINE void setOrigin(const btVector3& origin) { m_origin = origin; } SIMD_FORCE_INLINE btVector3 invXform(const btVector3& inVec) const; /**@brief Set the rotational element by btMatrix3x3 */ SIMD_FORCE_INLINE void setBasis(const btMatrix3x3& basis) { m_basis = basis; } /**@brief Set the rotational element by btQuaternion */ SIMD_FORCE_INLINE void setRotation(const btQuaternion& q) { m_basis.setRotation(q); } /**@brief Set this transformation to the identity */ void setIdentity() { m_basis.setIdentity(); m_origin.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)); } /**@brief Multiply this Transform by another(this = this * another) * @param t The other transform */ btTransform& operator*=(const btTransform& t) { m_origin += m_basis * t.m_origin; m_basis *= t.m_basis; return *this; } /**@brief Return the inverse of this transform */ btTransform inverse() const { btMatrix3x3 inv = m_basis.transpose(); return btTransform(inv, inv * -m_origin); } /**@brief Return the inverse of this transform times the other transform * @param t The other transform * return this.inverse() * the other */ btTransform inverseTimes(const btTransform& t) const; /**@brief Return the product of this transform and the other */ btTransform operator*(const btTransform& t) const; /**@brief Return an identity transform */ static const btTransform& getIdentity() { static const btTransform identityTransform(btMatrix3x3::getIdentity()); return identityTransform; } void serialize(struct btTransformData& dataOut) const; void serializeFloat(struct btTransformFloatData& dataOut) const; void deSerialize(const struct btTransformData& dataIn); void deSerializeDouble(const struct btTransformDoubleData& dataIn); void deSerializeFloat(const struct btTransformFloatData& dataIn); }; SIMD_FORCE_INLINE btVector3 btTransform::invXform(const btVector3& inVec) const { btVector3 v = inVec - m_origin; return (m_basis.transpose() * v); } SIMD_FORCE_INLINE btTransform btTransform::inverseTimes(const btTransform& t) const { btVector3 v = t.getOrigin() - m_origin; return btTransform(m_basis.transposeTimes(t.m_basis), v * m_basis); } SIMD_FORCE_INLINE btTransform btTransform::operator*(const btTransform& t) const { return btTransform(m_basis * t.m_basis, (*this)(t.m_origin)); } /**@brief Test if two transforms have all elements equal */ SIMD_FORCE_INLINE bool operator==(const btTransform& t1, const btTransform& t2) { return ( t1.getBasis() == t2.getBasis() && t1.getOrigin() == t2.getOrigin() ); } ///for serialization struct btTransformFloatData { btMatrix3x3FloatData m_basis; btVector3FloatData m_origin; }; struct btTransformDoubleData { btMatrix3x3DoubleData m_basis; btVector3DoubleData m_origin; }; SIMD_FORCE_INLINE void btTransform::serialize(btTransformData& dataOut) const { m_basis.serialize(dataOut.m_basis); m_origin.serialize(dataOut.m_origin); } SIMD_FORCE_INLINE void btTransform::serializeFloat(btTransformFloatData& dataOut) const { m_basis.serializeFloat(dataOut.m_basis); m_origin.serializeFloat(dataOut.m_origin); } SIMD_FORCE_INLINE void btTransform::deSerialize(const btTransformData& dataIn) { m_basis.deSerialize(dataIn.m_basis); m_origin.deSerialize(dataIn.m_origin); } SIMD_FORCE_INLINE void btTransform::deSerializeFloat(const btTransformFloatData& dataIn) { m_basis.deSerializeFloat(dataIn.m_basis); m_origin.deSerializeFloat(dataIn.m_origin); } SIMD_FORCE_INLINE void btTransform::deSerializeDouble(const btTransformDoubleData& dataIn) { m_basis.deSerializeDouble(dataIn.m_basis); m_origin.deSerializeDouble(dataIn.m_origin); } #endif //BT_TRANSFORM_H
412
0.971469
1
0.971469
game-dev
MEDIA
0.969238
game-dev
0.893668
1
0.893668
KaboomB52/KewlSpigot
10,176
kewlspigot-api/src/main/java/org/bukkit/block/Block.java
package org.bukkit.block; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.Metadatable; import java.util.Collection; /** * Represents a block. This is a live object, and only one Block may exist for * any given location in a world. The state of the block may change * concurrently to your own handling of it; use block.getState() to get a * snapshot state of a block which will not be modified. */ public interface Block extends Metadatable { /** * Gets the metadata for this block * * @return block specific metadata * @deprecated Magic value */ @Deprecated byte getData(); /** * Gets the block at the given offsets * * @param modX X-coordinate offset * @param modY Y-coordinate offset * @param modZ Z-coordinate offset * @return Block at the given offsets */ Block getRelative(int modX, int modY, int modZ); /** * Gets the block at the given face * <p> * This method is equal to getRelative(face, 1) * * @param face Face of this block to return * @return Block at the given face * @see #getRelative(BlockFace, int) */ Block getRelative(BlockFace face); /** * Gets the block at the given distance of the given face * <p> * For example, the following method places water at 100,102,100; two * blocks above 100,100,100. * * <pre> * Block block = world.getBlockAt(100, 100, 100); * Block shower = block.getRelative(BlockFace.UP, 2); * shower.setType(Material.WATER); * </pre> * * @param face Face of this block to return * @param distance Distance to get the block at * @return Block at the given face */ Block getRelative(BlockFace face, int distance); /** * Gets the type of this block * * @return block type */ Material getType(); /** * Gets the type-id of this block * * @return block type-id * @deprecated Magic value */ @Deprecated int getTypeId(); /** * Gets the light level between 0-15 * * @return light level */ byte getLightLevel(); /** * Get the amount of light at this block from the sky. * <p> * Any light given from other sources (such as blocks like torches) will * be ignored. * * @return Sky light level */ byte getLightFromSky(); /** * Get the amount of light at this block from nearby blocks. * <p> * Any light given from other sources (such as the sun) will be ignored. * * @return Block light level */ byte getLightFromBlocks(); /** * Gets the world which contains this Block * * @return World containing this block */ World getWorld(); /** * Gets the x-coordinate of this block * * @return x-coordinate */ int getX(); /** * Gets the y-coordinate of this block * * @return y-coordinate */ int getY(); /** * Gets the z-coordinate of this block * * @return z-coordinate */ int getZ(); /** * Gets the Location of the block * * @return Location of block */ Location getLocation(); /** * Stores the location of the block in the provided Location object. * <p> * If the provided Location is null this method does nothing and returns * null. * * @param loc the location to copy into * @return The Location object provided or null */ Location getLocation(Location loc); /** * Gets the chunk which contains this block * * @return Containing Chunk */ Chunk getChunk(); /** * Sets the metadata for this block * * @param data New block specific metadata * @deprecated Magic value */ @Deprecated void setData(byte data); /** * Sets the metadata for this block * * @param data New block specific metadata * @param applyPhysics False to cancel physics from the changed block. * @deprecated Magic value */ @Deprecated void setData(byte data, boolean applyPhysics); /** * Sets the type of this block * * @param type Material to change this block to */ void setType(Material type); /** * Sets the type of this block * * @param type Material to change this block to * @param applyPhysics False to cancel physics on the changed block. */ void setType(Material type, boolean applyPhysics); /** * Sets the type-id of this block * * @param type Type-Id to change this block to * @return whether the block was changed * @deprecated Magic value */ @Deprecated boolean setTypeId(int type); /** * Sets the type-id of this block * * @param type Type-Id to change this block to * @param applyPhysics False to cancel physics on the changed block. * @return whether the block was changed * @deprecated Magic value */ @Deprecated boolean setTypeId(int type, boolean applyPhysics); /** * Sets the type-id of this block * * @param type Type-Id to change this block to * @param data The data value to change this block to * @param applyPhysics False to cancel physics on the changed block * @return whether the block was changed * @deprecated Magic value */ @Deprecated boolean setTypeIdAndData(int type, byte data, boolean applyPhysics); /** * Gets the face relation of this block compared to the given block. * <p> * For example: * <pre>{@code * Block current = world.getBlockAt(100, 100, 100); * Block target = world.getBlockAt(100, 101, 100); * * current.getFace(target) == BlockFace.Up; * }</pre> * <br> * If the given block is not connected to this block, null may be returned * * @param block Block to compare against this block * @return BlockFace of this block which has the requested block, or null */ BlockFace getFace(Block block); /** * Captures the current state of this block. You may then cast that state * into any accepted type, such as Furnace or Sign. * <p> * The returned object will never be updated, and you are not guaranteed * that (for example) a sign is still a sign after you capture its state. * * @return BlockState with the current state of this block. */ BlockState getState(); /** * Returns the biome that this block resides in * * @return Biome type containing this block */ Biome getBiome(); /** * Sets the biome that this block resides in * * @param bio new Biome type for this block */ void setBiome(Biome bio); /** * Returns true if the block is being powered by Redstone. * * @return True if the block is powered. */ boolean isBlockPowered(); /** * Returns true if the block is being indirectly powered by Redstone. * * @return True if the block is indirectly powered. */ boolean isBlockIndirectlyPowered(); /** * Returns true if the block face is being powered by Redstone. * * @param face The block face * @return True if the block face is powered. */ boolean isBlockFacePowered(BlockFace face); /** * Returns true if the block face is being indirectly powered by Redstone. * * @param face The block face * @return True if the block face is indirectly powered. */ boolean isBlockFaceIndirectlyPowered(BlockFace face); /** * Returns the redstone power being provided to this block face * * @param face the face of the block to query or BlockFace.SELF for the * block itself * @return The power level. */ int getBlockPower(BlockFace face); /** * Returns the redstone power being provided to this block * * @return The power level. */ int getBlockPower(); /** * Checks if this block is empty. * <p> * A block is considered empty when {@link #getType()} returns {@link * Material#AIR}. * * @return true if this block is empty */ boolean isEmpty(); /** * Checks if this block is liquid. * <p> * A block is considered liquid when {@link #getType()} returns {@link * Material#WATER}, {@link Material#STATIONARY_WATER}, {@link * Material#LAVA} or {@link Material#STATIONARY_LAVA}. * * @return true if this block is liquid */ boolean isLiquid(); /** * Gets the temperature of the biome of this block * * @return Temperature of this block */ double getTemperature(); /** * Gets the humidity of the biome of this block * * @return Humidity of this block */ double getHumidity(); /** * Returns the reaction of the block when moved by a piston * * @return reaction */ PistonMoveReaction getPistonMoveReaction(); /** * Breaks the block and spawns items as if a player had digged it * * @return true if the block was destroyed */ boolean breakNaturally(); /** * Breaks the block and spawns items as if a player had digged it with a * specific tool * * @param tool The tool or item in hand used for digging * @return true if the block was destroyed */ boolean breakNaturally(ItemStack tool); /** * Returns a list of items which would drop by destroying this block * * @return a list of dropped items for this type of block */ Collection<ItemStack> getDrops(); /** * Returns a list of items which would drop by destroying this block with * a specific tool * * @param tool The tool or item in hand used for digging * @return a list of dropped items for this type of block */ Collection<ItemStack> getDrops(ItemStack tool); }
412
0.897922
1
0.897922
game-dev
MEDIA
0.592824
game-dev
0.588628
1
0.588628
ohjeongwook/binkit
8,833
src/engine/DiffAlgorithms.h
#pragma once #include <unordered_map> #include "Binary.h" #include "BasicBlocks.h" #include "FunctionMatching.h" #include <iostream> #include <boost/format.hpp> #include <boost/log/trivial.hpp> using namespace std; class AddressPair { public: va_t SourceAddress; va_t TargetAddress; AddressPair(va_t sourceAddress = 0, va_t targetAddress = 0) { SourceAddress = sourceAddress; TargetAddress = targetAddress; } }; class BasicBlockMatchCombination { private: vector<BasicBlockMatch> m_basicBlockMatchList; float m_matchRateTotal = 0; public: BasicBlockMatchCombination() { m_matchRateTotal = 0; } BasicBlockMatchCombination(BasicBlockMatchCombination* p_basicBlockMatchCombination) { for (BasicBlockMatch basicBlockMatch : p_basicBlockMatchCombination->GetBasicBlockMatchList()) { m_basicBlockMatchList.push_back(basicBlockMatch); m_matchRateTotal += basicBlockMatch.MatchRate; } } void Add(va_t source, BasicBlockMatch& basicBlockMatch) { BasicBlockMatch newBasicBlockMatch; memcpy(&newBasicBlockMatch, &basicBlockMatch, sizeof(BasicBlockMatch)); BOOST_LOG_TRIVIAL(debug) << boost::format("%x - %x") % source % newBasicBlockMatch.Target; m_basicBlockMatchList.push_back(newBasicBlockMatch); m_matchRateTotal += newBasicBlockMatch.MatchRate; } size_t Count() { return m_basicBlockMatchList.size(); } BasicBlockMatch Get(int index) { return m_basicBlockMatchList.at(index); } vector<BasicBlockMatch> GetBasicBlockMatchList() { return m_basicBlockMatchList; } vector<AddressPair> GetAddressPairs() { vector<AddressPair> addressPairs; for (auto& val : m_basicBlockMatchList) { addressPairs.push_back(AddressPair(val.Source, val.Target)); } return addressPairs; } bool FindSource(va_t address) { BOOST_LOG_TRIVIAL(debug) << boost::format("%x") % address; for (BasicBlockMatch basicBlockMatch : m_basicBlockMatchList) { if (basicBlockMatch.Source == address) { BOOST_LOG_TRIVIAL(debug) << boost::format("return true"); return true; } } BOOST_LOG_TRIVIAL(debug) << boost::format("return false"); return false; } bool FindTarget(va_t address) { BOOST_LOG_TRIVIAL(debug) << boost::format("%x") % address; for (BasicBlockMatch basicBlockMatch : m_basicBlockMatchList) { if (basicBlockMatch.Target == address) { BOOST_LOG_TRIVIAL(debug) << boost::format("return true"); return true; } } BOOST_LOG_TRIVIAL(debug) << boost::format("return false"); return false; } void Print() { printf("* BasicBlockMatchCombination:\n"); for (BasicBlockMatch basicBlockMatch : m_basicBlockMatchList) { printf("%x - %x matchRate: %d \n", basicBlockMatch.Source, basicBlockMatch.Target, basicBlockMatch.MatchRate); } printf("averageMatchRate : %f\n", GetMatchRate()); } float GetMatchRate() { if (m_basicBlockMatchList.size() > 0) { return m_matchRateTotal / m_basicBlockMatchList.size(); } return 0; } }; class BasicBlockMatchCombinations { private: unordered_map<va_t, unordered_set<va_t>> m_processedAddresses; vector<BasicBlockMatchCombination *>* m_pcombinations; public: BasicBlockMatchCombinations() { m_pcombinations = new vector<BasicBlockMatchCombination*>; } bool IsNew(va_t source, va_t target) { BOOST_LOG_TRIVIAL(debug) << boost::format("%x %x") % source % target; unordered_map<va_t, unordered_set<va_t>>::iterator it = m_processedAddresses.find(source); if (it == m_processedAddresses.end()) { unordered_set<va_t> addressMap; addressMap.insert(target); m_processedAddresses.insert({ source, addressMap }); } else { if (it->second.find(target) != it->second.end()) { return false; } it->second.insert(target); } return true; } BasicBlockMatchCombination* Add(va_t source, BasicBlockMatch &basicBlockMatch) { BOOST_LOG_TRIVIAL(debug) << boost::format("%x %x") % source % basicBlockMatch.Target; BasicBlockMatchCombination* p_addressPairCombination = new BasicBlockMatchCombination(); p_addressPairCombination->Add(source, basicBlockMatch); m_pcombinations->push_back(p_addressPairCombination); return p_addressPairCombination; } void AddCombinations(va_t source, vector<BasicBlockMatch> &basicBlockMatchList) { BOOST_LOG_TRIVIAL(debug) << boost::format("basicBlockMatchList.size(): %d") %basicBlockMatchList.size(); if (m_pcombinations->size() == 0) { for (BasicBlockMatch basicBlockMatch : basicBlockMatchList) { BOOST_LOG_TRIVIAL(debug) << boost::format("+ %x - %x") % source % basicBlockMatch.Target; Add(source, basicBlockMatch); } } else { vector<BasicBlockMatchCombination*>* p_newCombinations = new vector<BasicBlockMatchCombination*>; for (BasicBlockMatchCombination* p_basicBlockMatchCombination : *m_pcombinations) { for (BasicBlockMatch basicBlockMatch : basicBlockMatchList) { BOOST_LOG_TRIVIAL(debug) << boost::format("+ %x - %x") % source % basicBlockMatch.Target; BasicBlockMatchCombination* p_duplicatedBasicBlockMatchCombination = new BasicBlockMatchCombination(p_basicBlockMatchCombination); p_duplicatedBasicBlockMatchCombination->Add(source, basicBlockMatch); p_newCombinations->push_back(p_duplicatedBasicBlockMatchCombination); } } delete m_pcombinations; m_pcombinations = p_newCombinations; } BOOST_LOG_TRIVIAL(debug) << boost::format("size(): %d") % m_pcombinations->size(); } void Print() { for (BasicBlockMatchCombination* p_combination : *m_pcombinations) { p_combination->Print(); } } vector<BasicBlockMatchCombination*> GetTopMatches() { vector<BasicBlockMatchCombination*> basicBlockMatchCombinations; float maxMatchRate = 0; BasicBlockMatchCombination* p_selectedBasicBlockMatchCombination = NULL; for (BasicBlockMatchCombination* p_combination : *m_pcombinations) { float matchRate = p_combination->GetMatchRate(); if (maxMatchRate < matchRate) { maxMatchRate = matchRate; } } for (BasicBlockMatchCombination* p_basicBlockMatchCombination : *m_pcombinations) { float matchRate = p_basicBlockMatchCombination->GetMatchRate(); if (maxMatchRate == matchRate) { basicBlockMatchCombinations.push_back(p_basicBlockMatchCombination); } } return basicBlockMatchCombinations; } vector<BasicBlockMatchCombination*>* GetCombinations() { return m_pcombinations; } }; class DiffAlgorithms { private: int m_debugLevel; unordered_map<va_t, unordered_map<va_t, int>> m_matchRateCache; BasicBlocks *m_psrcBasicBlocks; BasicBlocks* m_ptargetBasicBlocks; InstructionHashMap *m_psrcInstructionHash; InstructionHashMap* m_ptargetInstructionHash; BasicBlockMatchCombinations* GenerateBasicBlockMatchCombinations(vector<BasicBlockMatch> basicBlockMatchList); public: DiffAlgorithms(); DiffAlgorithms(Binary* p_sourceBinary, Binary* p_targetBinary); int GetInstructionHashMatchRate(vector<unsigned char> instructionHash1, vector<unsigned char> instructionHash2); vector<BasicBlockMatch> DoInstructionHashMatch(); vector<BasicBlockMatch> DoBlocksInstructionHashMatch(unordered_set<va_t>& sourceBlockAddresses, unordered_set<va_t>& targetBlockAddresses); int GetMatchRate(va_t source, va_t target); vector<BasicBlockMatchCombination*> GetBasicBlockMatchCombinations(vector<BasicBlockMatch> basicBlockMatchList); vector<BasicBlockMatch> DoControlFlowMatch(va_t sourceAddress, va_t targetAddress, int matchType); vector<BasicBlockMatchCombination*> DoControlFlowMatches(vector<AddressPair> addressPairs, int matchType); string GetMatchTypeStr(int Type); };
412
0.682661
1
0.682661
game-dev
MEDIA
0.26505
game-dev
0.54834
1
0.54834
Sunnnix/Sunnixs_RPG_Engine
2,370
engine/src/de/sunnix/srpge/engine/ecs/event/ChangeVariableEvent.java
package de.sunnix.srpge.engine.ecs.event; import de.sunnix.sdso.DataSaveObject; import de.sunnix.srpge.engine.ecs.GameObject; import de.sunnix.srpge.engine.ecs.World; import de.sunnix.srpge.engine.evaluation.Variables; public class ChangeVariableEvent extends Event{ protected enum Array { INT, FLOAT, BOOL } protected enum Operation { SET, INC, DEC } protected Array array = Array.INT; protected int index; protected Number value = 0; protected Operation operation = Operation.SET; /** * Constructs a new event with the specified ID. */ public ChangeVariableEvent() { super("change_var"); } @Override public void load(DataSaveObject dso) { array = Array.values()[dso.getByte("array", (byte) Array.INT.ordinal())]; index = dso.getInt("index", 0); value = dso.getDouble("value", 0); operation = Operation.values()[dso.getByte("op", (byte) Operation.SET.ordinal())]; } @Override public void prepare(World world, GameObject parent) {} @Override public void run(World world) { switch (array){ case INT -> { switch (operation){ case SET -> Variables.setIntVar(index, value.intValue()); case INC -> Variables.setIntVar(index, Variables.getInt(index) + value.intValue()); case DEC -> Variables.setIntVar(index, Variables.getInt(index) - value.intValue()); } } case FLOAT -> { switch (operation){ case SET -> Variables.setFloatVar(index, value.floatValue()); case INC -> Variables.setFloatVar(index, Variables.getFloat(index) + value.floatValue()); case DEC -> Variables.setFloatVar(index, Variables.getFloat(index) - value.floatValue()); } } case BOOL -> { if(operation == Operation.SET) Variables.setBoolVar(index, value.intValue() != 0); else Variables.setBoolVar(index, !Variables.getBool(index)); } } } @Override public boolean isFinished(World world) { return true; } @Override public boolean isInstant(World world) { return true; } }
412
0.858286
1
0.858286
game-dev
MEDIA
0.769385
game-dev
0.920587
1
0.920587
frengor/UltimateAdvancementAPI
1,231
NMS/1_19_R2/src/main/java/com/fren_gor/ultimateAdvancementAPI/nms/v1_19_R2/MinecraftKeyWrapper_v1_19_R2.java
package com.fren_gor.ultimateAdvancementAPI.nms.v1_19_R2; import com.fren_gor.ultimateAdvancementAPI.nms.wrappers.MinecraftKeyWrapper; import net.minecraft.ResourceLocationException; import net.minecraft.resources.ResourceLocation; import org.jetbrains.annotations.NotNull; public class MinecraftKeyWrapper_v1_19_R2 extends MinecraftKeyWrapper { private final ResourceLocation key; public MinecraftKeyWrapper_v1_19_R2(@NotNull Object key) { this.key = (ResourceLocation) key; } public MinecraftKeyWrapper_v1_19_R2(@NotNull String namespace, @NotNull String key) { try { this.key = new ResourceLocation(namespace, key); } catch (ResourceLocationException e) { throw new IllegalArgumentException(e.getMessage()); } } @Override @NotNull public String getNamespace() { return key.getNamespace(); } @Override @NotNull public String getKey() { return key.getPath(); } @Override public int compareTo(@NotNull MinecraftKeyWrapper obj) { return key.compareTo((ResourceLocation) obj.toNMS()); } @Override @NotNull public ResourceLocation toNMS() { return key; } }
412
0.552219
1
0.552219
game-dev
MEDIA
0.878559
game-dev
0.542073
1
0.542073
antonkarliner/timer-coffee
2,066
lib/utils/version_vector.dart
import 'dart:convert'; import 'dart:math'; import 'package:uuid/uuid.dart'; class VersionVector { final String deviceId; final int version; static const String _legacyDeviceId = 'legacy'; static const int _legacyVersion = 0; VersionVector(this.deviceId, this.version); factory VersionVector.fromJson(Map<String, dynamic> json) { return VersionVector(json['deviceId'], json['version']); } factory VersionVector.legacy() { return VersionVector(_legacyDeviceId, _legacyVersion); } factory VersionVector.initial(String deviceId) { return VersionVector(deviceId, 1); } Map<String, dynamic> toJson() => { 'deviceId': deviceId, 'version': version, }; bool get isLegacy => deviceId == _legacyDeviceId && version == _legacyVersion; VersionVector increment() { if (isLegacy) { // Generate a new UUID for the device ID when upgrading from legacy String newDeviceId = Uuid().v4(); return VersionVector(newDeviceId, 1); } return VersionVector(deviceId, version + 1); } static VersionVector merge(VersionVector a, VersionVector b) { if (a.deviceId != b.deviceId) { throw ArgumentError( 'Cannot merge version vectors from different devices'); } return VersionVector(a.deviceId, max(a.version, b.version)); } @override String toString() { return json.encode(toJson()); } static VersionVector fromString(String str) { return VersionVector.fromJson(json.decode(str)); } @override bool operator ==(Object other) => identical(this, other) || other is VersionVector && runtimeType == other.runtimeType && deviceId == other.deviceId && version == other.version; @override int get hashCode => deviceId.hashCode ^ version.hashCode; bool isNewerThan(VersionVector other) { if (version != other.version) { return version > other.version; } // If versions are equal, compare the deviceIds lexicographically return deviceId.compareTo(other.deviceId) > 0; } }
412
0.720671
1
0.720671
game-dev
MEDIA
0.463222
game-dev
0.891073
1
0.891073
synhershko/Spatial4n
10,386
Spatial4n.Core/Shapes/Impl/BufferedLine.cs
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ using Spatial4n.Core.Context; using Spatial4n.Core.Distance; using System; using System.Diagnostics; namespace Spatial4n.Core.Shapes.Impl { /// <summary> /// INTERNAL: A line between two points with a buffer distance extending in every direction. By /// contrast, an un-buffered line covers no area and as such is extremely unlikely to intersect with /// a point. <see cref="BufferedLine"/> isn't yet aware of geodesics (e.g. the dateline); it operates in Euclidean /// space. /// </summary> public class BufferedLine : IShape { private readonly IPoint pA, pB; private readonly double buf; private readonly IRectangle bbox; /// <summary>the primary line; passes through pA &amp; pB</summary> private readonly InfBufLine linePrimary; /// <summary>perpendicular to the primary line, centered between pA &amp; pB</summary> private readonly InfBufLine linePerp; /// <summary> /// Creates a buffered line from pA to pB. The buffer extends on both sides of /// the line, making the width 2x the buffer. The buffer extends out from /// pA &amp; pB, making the line in effect 2x the buffer longer than pA to pB. /// </summary> /// <param name="pA">start point</param> /// <param name="pB">end point</param> /// <param name="buf">the buffer distance in degrees</param> /// <param name="ctx"></param> /// <exception cref="ArgumentNullException"><paramref name="pA"/>, <paramref name="pB"/>, or <paramref name="ctx"/> is <c>null</c>.</exception> public BufferedLine(IPoint pA, IPoint pB, double buf, SpatialContext ctx) { if (pA is null) throw new ArgumentNullException(nameof(pA)); // spatial4n specific - use ArgumentNullException instead of NullReferenceException if (pB is null) throw new ArgumentNullException(nameof(pB)); // spatial4n specific - use ArgumentNullException instead of NullReferenceException if (ctx is null) throw new ArgumentNullException(nameof(ctx)); // spatial4n specific - use ArgumentNullException instead of NullReferenceException Debug.Assert(buf >= 0);//TODO support buf=0 via another class ? // If true, buf should bump-out from the pA & pB, in effect // extending the line a little. bool bufExtend = true;//TODO support false and make this a // parameter this.pA = pA; this.pB = pB; this.buf = buf; double deltaY = pB.Y - pA.Y; double deltaX = pB.X - pA.X; Point center = new Point(pA.X + deltaX / 2, pA.Y + deltaY / 2, null); double perpExtent = bufExtend ? buf : 0; if (deltaX == 0 && deltaY == 0) { linePrimary = new InfBufLine(0, center, buf); linePerp = new InfBufLine(double.PositiveInfinity, center, buf); } else { linePrimary = new InfBufLine(deltaY / deltaX, center, buf); double length = Math.Sqrt(deltaX * deltaX + deltaY * deltaY); linePerp = new InfBufLine(-deltaX / deltaY, center, length / 2 + perpExtent); } double minY, maxY; double minX, maxX; if (deltaX == 0) { // vertical if (pA.Y <= pB.Y) { minY = pA.Y; maxY = pB.Y; } else { minY = pB.Y; maxY = pA.Y; } minX = pA.X - buf; maxX = pA.X + buf; minY = minY - perpExtent; maxY = maxY + perpExtent; } else { if (!bufExtend) { throw new NotSupportedException("TODO"); //solve for B & A (C=buf), one is buf-x, other is buf-y. } //Given a right triangle of A, B, C sides, C (hypotenuse) == // buf, and A + B == the bounding box offset from pA & pB in x & y. double bboxBuf = buf * (1 + Math.Abs(linePrimary.Slope)) * linePrimary.DistDenomInv; Debug.Assert(bboxBuf >= buf && bboxBuf <= buf * 1.5); if (pA.X <= pB.X) { minX = pA.X - bboxBuf; maxX = pB.X + bboxBuf; } else { minX = pB.X - bboxBuf; maxX = pA.X + bboxBuf; } if (pA.Y <= pB.Y) { minY = pA.Y - bboxBuf; maxY = pB.Y + bboxBuf; } else { minY = pB.Y - bboxBuf; maxY = pA.Y + bboxBuf; } } IRectangle bounds = ctx.WorldBounds; bbox = ctx.MakeRectangle( Math.Max(bounds.MinX, minX), Math.Min(bounds.MaxX, maxX), Math.Max(bounds.MinY, minY), Math.Min(bounds.MaxY, maxY)); } public virtual bool IsEmpty => pA.IsEmpty; public virtual IShape GetBuffered(double distance, SpatialContext ctx) { return new BufferedLine(pA, pB, buf + distance, ctx); } /// <summary> /// Calls <see cref="DistanceUtils.CalcLonDegreesAtLat(double, double)"/> given pA or pB's latitude; /// whichever is farthest. It's useful to expand a buffer of a line segment when used in /// a geospatial context to cover the desired area. /// </summary> public static double ExpandBufForLongitudeSkew(IPoint pA, IPoint pB, double buf) { double absA = Math.Abs(pA.Y); double absB = Math.Abs(pB.Y); double maxLat = Math.Max(absA, absB); double newBuf = DistanceUtils.CalcLonDegreesAtLat(maxLat, buf); // if (newBuf + maxLat >= 90) { // //TODO substitute spherical cap ? // } Debug.Assert(newBuf >= buf); return newBuf; } public virtual SpatialRelation Relate(IShape other) { if (other is IPoint) return Contains((IPoint)other) ? SpatialRelation.Contains : SpatialRelation.Disjoint; if (other is IRectangle) return Relate((IRectangle)other); throw new NotSupportedException(); } public virtual SpatialRelation Relate(IRectangle r) { //Check BBox for disjoint & within. SpatialRelation bboxR = bbox.Relate(r); if (bboxR == SpatialRelation.Disjoint || bboxR == SpatialRelation.Within) return bboxR; //Either CONTAINS, INTERSECTS, or DISJOINT IPoint scratch = new Point(0, 0, null); IPoint prC = r.Center; SpatialRelation result = linePrimary.Relate(r, prC, scratch); if (result == SpatialRelation.Disjoint) return SpatialRelation.Disjoint; SpatialRelation resultOpp = linePerp.Relate(r, prC, scratch); if (resultOpp == SpatialRelation.Disjoint) return SpatialRelation.Disjoint; if (result == resultOpp)//either CONTAINS or INTERSECTS return result; return SpatialRelation.Intersects; } public virtual bool Contains(IPoint p) { //TODO check bbox 1st? return linePrimary.Contains(p) && linePerp.Contains(p); } public virtual IRectangle BoundingBox => bbox; public virtual bool HasArea => buf > 0; public virtual double GetArea(SpatialContext? ctx) { return linePrimary.Buf * linePerp.Buf * 4; } public virtual IPoint Center => BoundingBox.Center; public virtual IPoint A => pA; public virtual IPoint B => pB; public virtual double Buf => buf; /// <summary> /// INTERNAL /// </summary> public virtual InfBufLine LinePrimary => linePrimary; /// <summary> /// INTERNAL /// </summary> public virtual InfBufLine LinePerp => linePerp; public override string ToString() { return "BufferedLine(" + pA + ", " + pB + " b=" + buf + ")"; } public override bool Equals(object o) { if (this == o) return true; if (o == null || GetType() != o.GetType()) return false; BufferedLine that = (BufferedLine)o; if (that.buf.CompareTo(buf) != 0) return false; if (!pA.Equals(that.pA)) return false; if (!pB.Equals(that.pB)) return false; return true; } public override int GetHashCode() { int result; long temp; result = pA.GetHashCode(); result = 31 * result + pB.GetHashCode(); temp = buf != +0.0d ? BitConverter.DoubleToInt64Bits(buf) : 0L; result = 31 * result + (int)(temp ^ (long)((ulong)temp >> 32)); return result; } } }
412
0.769392
1
0.769392
game-dev
MEDIA
0.291395
game-dev
0.954075
1
0.954075
daleao/sdv
1,230
Arsenal/Framework/Patchers/Infinity/ForgeMenuSpendRightItemPatcher.cs
namespace DaLion.Arsenal.Framework.Patchers.Infinity; #region using directives using System.Reflection; using DaLion.Arsenal.Framework.Integrations; using DaLion.Shared.Harmony; using HarmonyLib; using StardewValley.Menus; #endregion using directives [UsedImplicitly] internal sealed class ForgeMenuSpendRightItemPatcher : HarmonyPatcher { /// <summary>Initializes a new instance of the <see cref="ForgeMenuSpendRightItemPatcher"/> class.</summary> internal ForgeMenuSpendRightItemPatcher() { this.Target = this.RequireMethod<ForgeMenu>(nameof(ForgeMenu.SpendRightItem)); } #region harmony patches /// <summary>Prevent spending Hero Soul.</summary> [HarmonyPrefix] private static bool ForgeMenuSpendRightItemPrefix(ForgeMenu __instance) { try { return !JsonAssetsIntegration.HeroSoulIndex.HasValue || __instance.rightIngredientSpot.item?.ParentSheetIndex != JsonAssetsIntegration.HeroSoulIndex.Value; } catch (Exception ex) { Log.E($"Failed in {MethodBase.GetCurrentMethod()?.Name}:\n{ex}"); return true; // default to original logic } } #endregion harmony patches }
412
0.803473
1
0.803473
game-dev
MEDIA
0.893574
game-dev
0.751238
1
0.751238
FireEmblemUniverse/fireemblem8u
2,450
src/events/ch3-eventinfo.h
#pragma once #include "global.h" #include "event.h" #include "eventinfo.h" #include "eventcall.h" #include "EAstdlib.h" #include "bmtrap.h" #include "chapterdata.h" #include "constants/event-flags.h" #include "constants/characters.h" #include "constants/items.h" CONST_DATA EventListScr EventListScr_Ch3_Turn[] = { TURN(EVFLAG_TMP(7), EventScr_Ch3_Turn1Npc, 1, 1, FACTION_GREEN) TURN(EVFLAG_TMP(8), EventScr_Ch3_Turn2Player, 2, 2, FACTION_BLUE) END_MAIN }; CONST_DATA EventListScr EventListScr_Ch3_Character[] = { CHAR(EVFLAG_TMP(9), EventScr_Ch3_Talk_NeimiColm, CHARACTER_NEIMI, CHARACTER_COLM) END_MAIN }; CONST_DATA EventListScr EventListScr_Ch3_Location[] = { Chest(ITEM_LANCE_IRON, 6, 3) Chest(ITEM_AXE_HANDAXE, 8, 3) Chest(ITEM_SWORD_IRON, 10, 3) Chest(ITEM_LANCE_JAVELIN, 6, 12) Seize(14, 1) Door_(6, 10) Door_(10, 5) Door_(2, 3) END_MAIN }; CONST_DATA EventListScr EventListScr_Ch3_Misc[] = { CauseGameOverIfLordDies END_MAIN }; CONST_DATA EventListScr EventListScr_Ch3_SelectUnit[] = { END_MAIN }; CONST_DATA EventListScr EventListScr_Ch3_SelectDestination[] = { END_MAIN }; CONST_DATA EventListScr EventListScr_Ch3_UnitMove[] = { END_MAIN }; CONST_DATA EventListScr * EventListScr_Ch3_Tutorials[] = { NULL }; CONST_DATA struct ChapterEventGroup Ch3Events = { .turnBasedEvents = EventListScr_Ch3_Turn, .characterBasedEvents = EventListScr_Ch3_Character, .locationBasedEvents = EventListScr_Ch3_Location, .miscBasedEvents = EventListScr_Ch3_Misc, .specialEventsWhenUnitSelected = EventListScr_Ch3_SelectUnit, .specialEventsWhenDestSelected = EventListScr_Ch3_SelectDestination, .specialEventsAfterUnitMoved = EventListScr_Ch3_UnitMove, .tutorialEvents = EventListScr_Ch3_Tutorials, .traps = TrapData_Event_Ch3, .extraTrapsInHard = TrapData_Event_Ch3Hard, .playerUnitsInNormal = UnitDef_Event_Ch3Ally, .playerUnitsInHard = UnitDef_Event_Ch3Ally, .playerUnitsChoice1InEncounter = NULL, .playerUnitsChoice2InEncounter = NULL, .playerUnitsChoice3InEncounter = NULL, .enemyUnitsChoice1InEncounter = NULL, .enemyUnitsChoice2InEncounter = NULL, .enemyUnitsChoice3InEncounter = NULL, .beginningSceneEvents = EventScr_Ch3_BeginningScene, .endingSceneEvents = EventScr_Ch3_EndingScene, };
412
0.872691
1
0.872691
game-dev
MEDIA
0.959226
game-dev
0.933472
1
0.933472
monicanagent/cypherpoker
48,880
Libraries/Starling/src/starling/core/Starling.as
// ================================================================================================= // // Starling Framework // Copyright Gamua GmbH. All Rights Reserved. // // This program is free software. You can redistribute and/or modify it // in accordance with the terms of the accompanying license agreement. // // ================================================================================================= package starling.core { import flash.display.Shape; import flash.display.Sprite; import flash.display.Stage3D; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.display3D.Context3D; import flash.display3D.Context3DProfile; import flash.errors.IllegalOperationError; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TouchEvent; import flash.geom.Rectangle; import flash.system.Capabilities; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import flash.text.TextFormatAlign; import flash.ui.Mouse; import flash.ui.Multitouch; import flash.ui.MultitouchInputMode; import flash.utils.getTimer; import flash.utils.setTimeout; import starling.animation.Juggler; import starling.display.DisplayObject; import starling.display.Stage; import starling.events.EventDispatcher; import starling.events.ResizeEvent; import starling.events.TouchPhase; import starling.events.TouchProcessor; import starling.rendering.Painter; import starling.utils.Align; import starling.utils.RectangleUtil; import starling.utils.SystemUtil; /** Dispatched when a new render context is created. The 'data' property references the context. */ [Event(name="context3DCreate", type="starling.events.Event")] /** Dispatched when the root class has been created. The 'data' property references that object. */ [Event(name="rootCreated", type="starling.events.Event")] /** Dispatched when a fatal error is encountered. The 'data' property contains an error string. */ [Event(name="fatalError", type="starling.events.Event")] /** Dispatched when the display list is about to be rendered. This event provides the last * opportunity to make changes before the display list is rendered. */ [Event(name="render", type="starling.events.Event")] /** The Starling class represents the core of the Starling framework. * * <p>The Starling framework makes it possible to create 2D applications and games that make * use of the Stage3D architecture introduced in Flash Player 11. It implements a display tree * system that is very similar to that of conventional Flash, while leveraging modern GPUs * to speed up rendering.</p> * * <p>The Starling class represents the link between the conventional Flash display tree and * the Starling display tree. To create a Starling-powered application, you have to create * an instance of the Starling class:</p> * * <pre>var starling:Starling = new Starling(Game, stage);</pre> * * <p>The first parameter has to be a Starling display object class, e.g. a subclass of * <code>starling.display.Sprite</code>. In the sample above, the class "Game" is the * application root. An instance of "Game" will be created as soon as Starling is initialized. * The second parameter is the conventional (Flash) stage object. Per default, Starling will * display its contents directly below the stage.</p> * * <p>It is recommended to store the Starling instance as a member variable, to make sure * that the Garbage Collector does not destroy it. After creating the Starling object, you * have to start it up like this:</p> * * <pre>starling.start();</pre> * * <p>It will now render the contents of the "Game" class in the frame rate that is set up for * the application (as defined in the Flash stage).</p> * * <strong>Context3D Profiles</strong> * * <p>Stage3D supports different rendering profiles, and Starling works with all of them. The * last parameter of the Starling constructor allows you to choose which profile you want. * The following profiles are available:</p> * * <ul> * <li>BASELINE_CONSTRAINED: provides the broadest hardware reach. If you develop for the * browser, this is the profile you should test with.</li> * <li>BASELINE: recommend for any mobile application, as it allows Starling to use a more * memory efficient texture type (RectangleTextures). It also supports more complex * AGAL code.</li> * <li>BASELINE_EXTENDED: adds support for textures up to 4096x4096 pixels. This is * especially useful on mobile devices with very high resolutions.</li> * <li>STANDARD_CONSTRAINED, STANDARD, STANDARD_EXTENDED: each provide more AGAL features, * among other things. Most Starling games will not gain much from them.</li> * </ul> * * <p>The recommendation is to deploy your app with the profile "auto" (which makes Starling * pick the best available of those), but to test it in all available profiles.</p> * * <strong>Accessing the Starling object</strong> * * <p>From within your application, you can access the current Starling object anytime * through the static method <code>Starling.current</code>. It will return the active Starling * instance (most applications will only have one Starling object, anyway).</p> * * <strong>Viewport</strong> * * <p>The area the Starling content is rendered into is, per default, the complete size of the * stage. You can, however, use the "viewPort" property to change it. This can be useful * when you want to render only into a part of the screen, or if the player size changes. For * the latter, you can listen to the RESIZE-event dispatched by the Starling * stage.</p> * * <strong>Native overlay</strong> * * <p>Sometimes you will want to display native Flash content on top of Starling. That's what the * <code>nativeOverlay</code> property is for. It returns a Flash Sprite lying directly * on top of the Starling content. You can add conventional Flash objects to that overlay.</p> * * <p>Beware, though, that conventional Flash content on top of 3D content can lead to * performance penalties on some (mobile) platforms. For that reason, always remove all child * objects from the overlay when you don't need them any longer.</p> * * <strong>Multitouch</strong> * * <p>Starling supports multitouch input on devices that provide it. During development, * where most of us are working with a conventional mouse and keyboard, Starling can simulate * multitouch events with the help of the "Shift" and "Ctrl" (Mac: "Cmd") keys. Activate * this feature by enabling the <code>simulateMultitouch</code> property.</p> * * <strong>Skipping Unchanged Frames</strong> * * <p>It happens surprisingly often in an app or game that a scene stays completely static for * several frames. So why redraw the stage at all in those situations? That's exactly the * point of the <code>skipUnchangedFrames</code>-property. If enabled, static scenes are * recognized as such and the back buffer is simply left as it is. On a mobile device, the * impact of this feature can't be overestimated! There's simply no better way to enhance * battery life. Make it a habit to always activate it; look at the documentation of the * corresponding property for details.</p> * * <strong>Handling a lost render context</strong> * * <p>On some operating systems and under certain conditions (e.g. returning from system * sleep), Starling's stage3D render context may be lost. Starling will try to recover * from a lost context automatically; to be able to do this, it will cache textures in * RAM. This will take up quite a bit of extra memory, though, which might be problematic * especially on mobile platforms. To avoid the higher memory footprint, it's recommended * to load your textures with Starling's "AssetManager"; it is smart enough to recreate a * texture directly from its origin.</p> * * <p>In case you want to react to a context loss manually, Starling dispatches an event with * the type "Event.CONTEXT3D_CREATE" when the context is restored, and textures will execute * their <code>root.onRestore</code> callback, to which you can attach your own logic. * Refer to the "Texture" class for more information.</p> * * <strong>Sharing a 3D Context</strong> * * <p>Per default, Starling handles the Stage3D context itself. If you want to combine * Starling with another Stage3D engine, however, this may not be what you want. In this case, * you can make use of the <code>shareContext</code> property:</p> * * <ol> * <li>Manually create and configure a context3D object that both frameworks can work with * (ideally through <code>RenderUtil.requestContext3D</code> and * <code>context.configureBackBuffer</code>).</li> * <li>Initialize Starling with the stage3D instance that contains that configured context. * This will automatically enable <code>shareContext</code>.</li> * <li>Call <code>start()</code> on your Starling instance (as usual). This will make * Starling queue input events (keyboard/mouse/touch).</li> * <li>Create a game loop (e.g. using the native <code>ENTER_FRAME</code> event) and let it * call Starling's <code>nextFrame</code> as well as the equivalent method of the other * Stage3D engine. Surround those calls with <code>context.clear()</code> and * <code>context.present()</code>.</li> * </ol> * * <p>The Starling wiki contains a <a href="http://goo.gl/BsXzw">tutorial</a> with more * information about this topic.</p> * * @see starling.utils.AssetManager * @see starling.textures.Texture * */ public class Starling extends EventDispatcher { /** The version of the Starling framework. */ public static const VERSION:String = "2.1"; // members private var _stage:Stage; // starling.display.stage! private var _rootClass:Class; private var _root:DisplayObject; private var _juggler:Juggler; private var _painter:Painter; private var _touchProcessor:TouchProcessor; private var _antiAliasing:int; private var _frameTimestamp:Number; private var _frameID:uint; private var _leftMouseDown:Boolean; private var _statsDisplay:StatsDisplay; private var _started:Boolean; private var _rendering:Boolean; private var _supportHighResolutions:Boolean; private var _skipUnchangedFrames:Boolean; private var _showStats:Boolean; private var _viewPort:Rectangle; private var _previousViewPort:Rectangle; private var _clippedViewPort:Rectangle; private var _nativeStage:flash.display.Stage; private var _nativeStageEmpty:Boolean; private var _nativeOverlay:Sprite; private static var sCurrent:Starling; private static var sAll:Vector.<Starling> = new <Starling>[]; // construction /** Creates a new Starling instance. * @param rootClass A subclass of 'starling.display.DisplayObject'. It will be created * as soon as initialization is finished and will become the first child * of the Starling stage. Pass <code>null</code> if you don't want to * create a root object right away. (You can use the * <code>rootClass</code> property later to make that happen.) * @param stage The Flash (2D) stage. * @param viewPort A rectangle describing the area into which the content will be * rendered. Default: stage size * @param stage3D The Stage3D object into which the content will be rendered. If it * already contains a context, <code>sharedContext</code> will be set * to <code>true</code>. Default: the first available Stage3D. * @param renderMode The Context3D render mode that should be requested. * Use this parameter if you want to force "software" rendering. * @param profile The Context3D profile that should be requested. * * <ul> * <li>If you pass a profile String, this profile is enforced.</li> * <li>Pass an Array of profiles to make Starling pick the first * one that works (starting with the first array element).</li> * <li>Pass the String "auto" to make Starling pick the best available * profile automatically.</li> * </ul> */ public function Starling(rootClass:Class, stage:flash.display.Stage, viewPort:Rectangle=null, stage3D:Stage3D=null, renderMode:String="auto", profile:Object="auto") { if (stage == null) throw new ArgumentError("Stage must not be null"); if (viewPort == null) viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); if (stage3D == null) stage3D = stage.stage3Ds[0]; // TODO it might make sense to exchange the 'renderMode' and 'profile' parameters. SystemUtil.initialize(); sAll.push(this); makeCurrent(); _rootClass = rootClass; _viewPort = viewPort; _previousViewPort = new Rectangle(); _stage = new Stage(viewPort.width, viewPort.height, stage.color); _nativeOverlay = new Sprite(); _nativeStage = stage; _nativeStage.addChild(_nativeOverlay); _touchProcessor = new TouchProcessor(_stage); _juggler = new Juggler(); _antiAliasing = 0; _supportHighResolutions = false; _painter = new Painter(stage3D); _frameTimestamp = getTimer() / 1000.0; _frameID = 1; // all other modes are problematic in Starling, so we force those here stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; // register touch/mouse event handlers for each (var touchEventType:String in touchEventTypes) stage.addEventListener(touchEventType, onTouch, false, 0, true); // register other event handlers stage.addEventListener(Event.ENTER_FRAME, onEnterFrame, false, 0, true); stage.addEventListener(KeyboardEvent.KEY_DOWN, onKey, false, 0, true); stage.addEventListener(KeyboardEvent.KEY_UP, onKey, false, 0, true); stage.addEventListener(Event.RESIZE, onResize, false, 0, true); stage.addEventListener(Event.MOUSE_LEAVE, onMouseLeave, false, 0, true); stage3D.addEventListener(Event.CONTEXT3D_CREATE, onContextCreated, false, 10, true); stage3D.addEventListener(ErrorEvent.ERROR, onStage3DError, false, 10, true); if (_painter.shareContext) { setTimeout(initialize, 1); // we don't call it right away, because Starling should // behave the same way with or without a shared context } else { if (!SystemUtil.supportsDepthAndStencil) trace("[Starling] Mask support requires 'depthAndStencil' to be enabled" + " in the application descriptor."); _painter.requestContext3D(renderMode, profile); } } /** Disposes all children of the stage and the render context; removes all registered * event listeners. */ public function dispose():void { stop(true); _nativeStage.removeEventListener(Event.ENTER_FRAME, onEnterFrame, false); _nativeStage.removeEventListener(KeyboardEvent.KEY_DOWN, onKey, false); _nativeStage.removeEventListener(KeyboardEvent.KEY_UP, onKey, false); _nativeStage.removeEventListener(Event.RESIZE, onResize, false); _nativeStage.removeEventListener(Event.MOUSE_LEAVE, onMouseLeave, false); _nativeStage.removeChild(_nativeOverlay); stage3D.removeEventListener(Event.CONTEXT3D_CREATE, onContextCreated, false); stage3D.removeEventListener(Event.CONTEXT3D_CREATE, onContextRestored, false); stage3D.removeEventListener(ErrorEvent.ERROR, onStage3DError, false); for each (var touchEventType:String in touchEventTypes) _nativeStage.removeEventListener(touchEventType, onTouch, false); _touchProcessor.dispose(); _painter.dispose(); _stage.dispose(); var index:int = sAll.indexOf(this); if (index != -1) sAll.removeAt(index); if (sCurrent == this) sCurrent = null; } // functions private function initialize():void { makeCurrent(); updateViewPort(true); // ideal time: after viewPort setup, before root creation dispatchEventWith(Event.CONTEXT3D_CREATE, false, context); initializeRoot(); _frameTimestamp = getTimer() / 1000.0; } private function initializeRoot():void { if (_root == null && _rootClass != null) { _root = new _rootClass() as DisplayObject; if (_root == null) throw new Error("Invalid root class: " + _rootClass); _stage.addChildAt(_root, 0); dispatchEventWith(starling.events.Event.ROOT_CREATED, false, _root); } } /** Calls <code>advanceTime()</code> (with the time that has passed since the last frame) * and <code>render()</code>. */ public function nextFrame():void { var now:Number = getTimer() / 1000.0; var passedTime:Number = now - _frameTimestamp; _frameTimestamp = now; // to avoid overloading time-based animations, the maximum delta is truncated. if (passedTime > 1.0) passedTime = 1.0; // after about 25 days, 'getTimer()' will roll over. A rare event, but still ... if (passedTime < 0.0) passedTime = 1.0 / _nativeStage.frameRate; advanceTime(passedTime); render(); } /** Dispatches ENTER_FRAME events on the display list, advances the Juggler * and processes touches. */ public function advanceTime(passedTime:Number):void { if (!contextValid) return; makeCurrent(); _touchProcessor.advanceTime(passedTime); _stage.advanceTime(passedTime); _juggler.advanceTime(passedTime); } /** Renders the complete display list. Before rendering, the context is cleared; afterwards, * it is presented (to avoid this, enable <code>shareContext</code>). * * <p>This method also dispatches an <code>Event.RENDER</code>-event on the Starling * instance. That's the last opportunity to make changes before the display list is * rendered.</p> */ public function render():void { if (!contextValid) return; makeCurrent(); updateViewPort(); var doRedraw:Boolean = _stage.requiresRedraw || mustAlwaysRender; if (doRedraw) { dispatchEventWith(starling.events.Event.RENDER); var shareContext:Boolean = _painter.shareContext; var scaleX:Number = _viewPort.width / _stage.stageWidth; var scaleY:Number = _viewPort.height / _stage.stageHeight; _painter.nextFrame(); _painter.pixelSize = 1.0 / contentScaleFactor; _painter.state.setProjectionMatrix( _viewPort.x < 0 ? -_viewPort.x / scaleX : 0.0, _viewPort.y < 0 ? -_viewPort.y / scaleY : 0.0, _clippedViewPort.width / scaleX, _clippedViewPort.height / scaleY, _stage.stageWidth, _stage.stageHeight, _stage.cameraPosition); if (!shareContext) _painter.clear(_stage.color, 0.0); _stage.render(_painter); _painter.finishFrame(); _painter.frameID = ++_frameID; if (!shareContext) _painter.present(); } if (_statsDisplay) { _statsDisplay.drawCount = _painter.drawCount; if (!doRedraw) _statsDisplay.markFrameAsSkipped(); } } private function updateViewPort(forceUpdate:Boolean=false):void { // the last set viewport is stored in a variable; that way, people can modify the // viewPort directly (without a copy) and we still know if it has changed. if (forceUpdate || !RectangleUtil.compare(_viewPort, _previousViewPort)) { _previousViewPort.setTo(_viewPort.x, _viewPort.y, _viewPort.width, _viewPort.height); // Constrained mode requires that the viewport is within the native stage bounds; // thus, we use a clipped viewport when configuring the back buffer. (In baseline // mode, that's not necessary, but it does not hurt either.) _clippedViewPort = _viewPort.intersection( new Rectangle(0, 0, _nativeStage.stageWidth, _nativeStage.stageHeight)); var contentScaleFactor:Number = _supportHighResolutions ? _nativeStage.contentsScaleFactor : 1.0; _painter.configureBackBuffer(_clippedViewPort, contentScaleFactor, _antiAliasing, true); } } private function updateNativeOverlay():void { _nativeOverlay.x = _viewPort.x; _nativeOverlay.y = _viewPort.y; _nativeOverlay.scaleX = _viewPort.width / _stage.stageWidth; _nativeOverlay.scaleY = _viewPort.height / _stage.stageHeight; } /** Stops Starling right away and displays an error message on the native overlay. * This method will also cause Starling to dispatch a FATAL_ERROR event. */ public function stopWithFatalError(message:String):void { var background:Shape = new Shape(); background.graphics.beginFill(0x0, 0.8); background.graphics.drawRect(0, 0, _stage.stageWidth, _stage.stageHeight); background.graphics.endFill(); var textField:TextField = new TextField(); var textFormat:TextFormat = new TextFormat("Verdana", 14, 0xFFFFFF); textFormat.align = TextFormatAlign.CENTER; textField.defaultTextFormat = textFormat; textField.wordWrap = true; textField.width = _stage.stageWidth * 0.75; textField.autoSize = TextFieldAutoSize.CENTER; textField.text = message; textField.x = (_stage.stageWidth - textField.width) / 2; textField.y = (_stage.stageHeight - textField.height) / 2; textField.background = true; textField.backgroundColor = 0x550000; updateNativeOverlay(); nativeOverlay.addChild(background); nativeOverlay.addChild(textField); stop(true); trace("[Starling]", message); dispatchEventWith(starling.events.Event.FATAL_ERROR, false, message); } /** Make this Starling instance the <code>current</code> one. */ public function makeCurrent():void { sCurrent = this; } /** As soon as Starling is started, it will queue input events (keyboard/mouse/touch); * furthermore, the method <code>nextFrame</code> will be called once per Flash Player * frame. (Except when <code>shareContext</code> is enabled: in that case, you have to * call that method manually.) */ public function start():void { _started = _rendering = true; _frameTimestamp = getTimer() / 1000.0; // mainly for Android: force redraw when app moves into foreground setTimeout(setRequiresRedraw, 100); } /** Stops all logic and input processing, effectively freezing the app in its current state. * Per default, rendering will continue: that's because the classic display list * is only updated when stage3D is. (If Starling stopped rendering, conventional Flash * contents would freeze, as well.) * * <p>However, if you don't need classic Flash contents, you can stop rendering, too. * On some mobile systems (e.g. iOS), you are even required to do so if you have * activated background code execution.</p> */ public function stop(suspendRendering:Boolean=false):void { _started = false; _rendering = !suspendRendering; } /** Makes sure that the next frame is actually rendered. * * <p>When <code>skipUnchangedFrames</code> is enabled, some situations require that you * manually force a redraw, e.g. when a RenderTexture is changed. This method is the * easiest way to do so; it's just a shortcut to <code>stage.setRequiresRedraw()</code>. * </p> */ public function setRequiresRedraw():void { _stage.setRequiresRedraw(); } // event handlers private function onStage3DError(event:ErrorEvent):void { if (event.errorID == 3702) { var mode:String = Capabilities.playerType == "Desktop" ? "renderMode" : "wmode"; stopWithFatalError("Context3D not available! Possible reasons: wrong " + mode + " or missing device support."); } else stopWithFatalError("Stage3D error: " + event.text); } private function onContextCreated(event:Event):void { stage3D.removeEventListener(Event.CONTEXT3D_CREATE, onContextCreated); stage3D.addEventListener(Event.CONTEXT3D_CREATE, onContextRestored, false, 10, true); trace("[Starling] Context ready. Display Driver:", context.driverInfo); initialize(); } private function onContextRestored(event:Event):void { trace("[Starling] Context restored."); updateViewPort(true); dispatchEventWith(Event.CONTEXT3D_CREATE, false, context); } private function onEnterFrame(event:Event):void { // On mobile, the native display list is only updated on stage3D draw calls. // Thus, we render even when Starling is paused. if (!shareContext) { if (_started) nextFrame(); else if (_rendering) render(); } updateNativeOverlay(); } private function onKey(event:KeyboardEvent):void { if (!_started) return; var keyEvent:starling.events.KeyboardEvent = new starling.events.KeyboardEvent( event.type, event.charCode, event.keyCode, event.keyLocation, event.ctrlKey, event.altKey, event.shiftKey); makeCurrent(); _stage.dispatchEvent(keyEvent); if (keyEvent.isDefaultPrevented()) event.preventDefault(); } private function onResize(event:Event):void { var stageWidth:int = event.target.stageWidth; var stageHeight:int = event.target.stageHeight; if (contextValid) dispatchResizeEvent(); else addEventListener(Event.CONTEXT3D_CREATE, dispatchResizeEvent); function dispatchResizeEvent():void { // on Android, the context is not valid while we're resizing. To avoid problems // with user code, we delay the event dispatching until it becomes valid again. makeCurrent(); removeEventListener(Event.CONTEXT3D_CREATE, dispatchResizeEvent); _stage.dispatchEvent(new ResizeEvent(Event.RESIZE, stageWidth, stageHeight)); } } private function onMouseLeave(event:Event):void { _touchProcessor.enqueueMouseLeftStage(); } private function onTouch(event:Event):void { if (!_started) return; var globalX:Number; var globalY:Number; var touchID:int; var phase:String; var pressure:Number = 1.0; var width:Number = 1.0; var height:Number = 1.0; // figure out general touch properties if (event is MouseEvent) { var mouseEvent:MouseEvent = event as MouseEvent; globalX = mouseEvent.stageX; globalY = mouseEvent.stageY; touchID = 0; // MouseEvent.buttonDown returns true for both left and right button (AIR supports // the right mouse button). We only want to react on the left button for now, // so we have to save the state for the left button manually. if (event.type == MouseEvent.MOUSE_DOWN) _leftMouseDown = true; else if (event.type == MouseEvent.MOUSE_UP) _leftMouseDown = false; } else { var touchEvent:TouchEvent = event as TouchEvent; // On a system that supports both mouse and touch input, the primary touch point // is dispatched as mouse event as well. Since we don't want to listen to that // event twice, we ignore the primary touch in that case. if (Mouse.supportsCursor && touchEvent.isPrimaryTouchPoint) return; else { globalX = touchEvent.stageX; globalY = touchEvent.stageY; touchID = touchEvent.touchPointID; pressure = touchEvent.pressure; width = touchEvent.sizeX; height = touchEvent.sizeY; } } // figure out touch phase switch (event.type) { case TouchEvent.TOUCH_BEGIN: phase = TouchPhase.BEGAN; break; case TouchEvent.TOUCH_MOVE: phase = TouchPhase.MOVED; break; case TouchEvent.TOUCH_END: phase = TouchPhase.ENDED; break; case MouseEvent.MOUSE_DOWN: phase = TouchPhase.BEGAN; break; case MouseEvent.MOUSE_UP: phase = TouchPhase.ENDED; break; case MouseEvent.MOUSE_MOVE: phase = (_leftMouseDown ? TouchPhase.MOVED : TouchPhase.HOVER); break; } // move position into viewport bounds globalX = _stage.stageWidth * (globalX - _viewPort.x) / _viewPort.width; globalY = _stage.stageHeight * (globalY - _viewPort.y) / _viewPort.height; // enqueue touch in touch processor _touchProcessor.enqueue(touchID, phase, globalX, globalY, pressure, width, height); // allow objects that depend on mouse-over state to be updated immediately if (event.type == MouseEvent.MOUSE_UP && Mouse.supportsCursor) _touchProcessor.enqueue(touchID, TouchPhase.HOVER, globalX, globalY); } private function get touchEventTypes():Array { var types:Array = []; if (multitouchEnabled) types.push(TouchEvent.TOUCH_BEGIN, TouchEvent.TOUCH_MOVE, TouchEvent.TOUCH_END); if (!multitouchEnabled || Mouse.supportsCursor) types.push(MouseEvent.MOUSE_DOWN, MouseEvent.MOUSE_MOVE, MouseEvent.MOUSE_UP); return types; } private function get mustAlwaysRender():Boolean { // On mobile, and in some browsers with the "baselineConstrained" profile, the // standard display list is only rendered after calling "context.present()". // In such a case, we cannot omit frames if there is any content on the stage. if (!_skipUnchangedFrames || _painter.shareContext) return true; else if (SystemUtil.isDesktop && profile != Context3DProfile.BASELINE_CONSTRAINED) return false; else { // Rendering can be skipped when both this and previous frame are empty. var nativeStageEmpty:Boolean = isNativeDisplayObjectEmpty(_nativeStage); var mustAlwaysRender:Boolean = !nativeStageEmpty || !_nativeStageEmpty; _nativeStageEmpty = nativeStageEmpty; return mustAlwaysRender; } } // properties /** Indicates if this Starling instance is started. */ public function get isStarted():Boolean { return _started; } /** The default juggler of this instance. Will be advanced once per frame. */ public function get juggler():Juggler { return _juggler; } /** The painter, which is used for all rendering. The same instance is passed to all * <code>render</code>methods each frame. */ public function get painter():Painter { return _painter; } /** The render context of this instance. */ public function get context():Context3D { return _painter.context; } /** Indicates if multitouch simulation with "Shift" and "Ctrl"/"Cmd"-keys is enabled. * @default false */ public function get simulateMultitouch():Boolean { return _touchProcessor.simulateMultitouch; } public function set simulateMultitouch(value:Boolean):void { _touchProcessor.simulateMultitouch = value; } /** Indicates if Stage3D render methods will report errors. It's recommended to activate * this when writing custom rendering code (shaders, etc.), since you'll get more detailed * error messages. However, it has a very negative impact on performance, and it prevents * ATF textures from being restored on a context loss. Never activate for release builds! * * @default false */ public function get enableErrorChecking():Boolean { return _painter.enableErrorChecking; } public function set enableErrorChecking(value:Boolean):void { _painter.enableErrorChecking = value; } /** The anti-aliasing level. 0 - none, 16 - maximum. @default 0 */ public function get antiAliasing():int { return _antiAliasing; } public function set antiAliasing(value:int):void { if (_antiAliasing != value) { _antiAliasing = value; if (contextValid) updateViewPort(true); } } /** The viewport into which Starling contents will be rendered. */ public function get viewPort():Rectangle { return _viewPort; } public function set viewPort(value:Rectangle):void { _viewPort = value.clone(); } /** The ratio between viewPort width and stage width. Useful for choosing a different * set of textures depending on the display resolution. */ public function get contentScaleFactor():Number { return (_viewPort.width * _painter.backBufferScaleFactor) / _stage.stageWidth; } /** A Flash Sprite placed directly on top of the Starling content. Use it to display native * Flash components. */ public function get nativeOverlay():Sprite { return _nativeOverlay; } /** Indicates if a small statistics box (with FPS, memory usage and draw count) is * displayed. * * <p>When the box turns dark green, more than 50% of the frames since the box' last * update could skip rendering altogether. This will only happen if the property * <code>skipUnchangedFrames</code> is enabled.</p> * * <p>Beware that the memory usage should be taken with a grain of salt. The value is * determined via <code>System.totalMemory</code> and does not take texture memory * into account. It is recommended to use Adobe Scout for reliable and comprehensive * memory analysis.</p> */ public function get showStats():Boolean { return _showStats; } public function set showStats(value:Boolean):void { _showStats = value; if (value) { if (_statsDisplay) _stage.addChild(_statsDisplay); else showStatsAt(); } else if (_statsDisplay) { _statsDisplay.removeFromParent(); } } /** Displays the statistics box at a certain position. */ public function showStatsAt(horizontalAlign:String="left", verticalAlign:String="top", scale:Number=1):void { _showStats = true; if (context == null) { // Starling is not yet ready - we postpone this until it's initialized. addEventListener(starling.events.Event.ROOT_CREATED, onRootCreated); } else { var stageWidth:int = _stage.stageWidth; var stageHeight:int = _stage.stageHeight; if (_statsDisplay == null) { _statsDisplay = new StatsDisplay(); _statsDisplay.touchable = false; } _stage.addChild(_statsDisplay); _statsDisplay.scaleX = _statsDisplay.scaleY = scale; if (horizontalAlign == Align.LEFT) _statsDisplay.x = 0; else if (horizontalAlign == Align.RIGHT) _statsDisplay.x = stageWidth - _statsDisplay.width; else if (horizontalAlign == Align.CENTER) _statsDisplay.x = (stageWidth - _statsDisplay.width) / 2; else throw new ArgumentError("Invalid horizontal alignment: " + horizontalAlign); if (verticalAlign == Align.TOP) _statsDisplay.y = 0; else if (verticalAlign == Align.BOTTOM) _statsDisplay.y = stageHeight - _statsDisplay.height; else if (verticalAlign == Align.CENTER) _statsDisplay.y = (stageHeight - _statsDisplay.height) / 2; else throw new ArgumentError("Invalid vertical alignment: " + verticalAlign); } function onRootCreated():void { if (_showStats) showStatsAt(horizontalAlign, verticalAlign, scale); removeEventListener(starling.events.Event.ROOT_CREATED, onRootCreated); } } /** The Starling stage object, which is the root of the display tree that is rendered. */ public function get stage():Stage { return _stage; } /** The Flash Stage3D object Starling renders into. */ public function get stage3D():Stage3D { return _painter.stage3D; } /** The Flash (2D) stage object Starling renders beneath. */ public function get nativeStage():flash.display.Stage { return _nativeStage; } /** The instance of the root class provided in the constructor. Available as soon as * the event 'ROOT_CREATED' has been dispatched. */ public function get root():DisplayObject { return _root; } /** The class that will be instantiated by Starling as the 'root' display object. * Must be a subclass of 'starling.display.DisplayObject'. * * <p>If you passed <code>null</code> as first parameter to the Starling constructor, * you can use this property to set the root class at a later time. As soon as the class * is instantiated, Starling will dispatch a <code>ROOT_CREATED</code> event.</p> * * <p>Beware: you cannot change the root class once the root object has been * instantiated.</p> */ public function get rootClass():Class { return _rootClass; } public function set rootClass(value:Class):void { if (_rootClass != null && _root != null) throw new Error("Root class may not change after root has been instantiated"); else if (_rootClass == null) { _rootClass = value; if (context) initializeRoot(); } } /** Indicates if another Starling instance (or another Stage3D framework altogether) * uses the same render context. If enabled, Starling will not execute any destructive * context operations (e.g. not call 'configureBackBuffer', 'clear', 'present', etc. * This has to be done manually, then. @default false */ public function get shareContext() : Boolean { return _painter.shareContext; } public function set shareContext(value : Boolean) : void { _painter.shareContext = value; } /** The Context3D profile of the current render context, or <code>null</code> * if the context has not been created yet. */ public function get profile():String { return _painter.profile; } /** Indicates that if the device supports HiDPI screens Starling will attempt to allocate * a larger back buffer than indicated via the viewPort size. Note that this is used * on Desktop only; mobile AIR apps still use the "requestedDisplayResolution" parameter * the application descriptor XML. @default false */ public function get supportHighResolutions():Boolean { return _supportHighResolutions; } public function set supportHighResolutions(value:Boolean):void { if (_supportHighResolutions != value) { _supportHighResolutions = value; if (contextValid) updateViewPort(true); } } /** When enabled, Starling will skip rendering the stage if it hasn't changed since the * last frame. This is great for apps that remain static from time to time, since it will * greatly reduce power consumption. You should activate this whenever possible! * * <p>The reason why it's disabled by default is just that it causes problems with Render- * and VideoTextures. When you use those, you either have to disable this property * temporarily, or call <code>setRequiresRedraw()</code> (ideally on the stage) whenever * those textures are changing. Otherwise, the changes won't show up.</p> * * @default false */ public function get skipUnchangedFrames():Boolean { return _skipUnchangedFrames; } public function set skipUnchangedFrames(value:Boolean):void { _skipUnchangedFrames = value; _nativeStageEmpty = false; // required by 'mustAlwaysRender' } /** The TouchProcessor is passed all mouse and touch input and is responsible for * dispatching TouchEvents to the Starling display tree. If you want to handle these * types of input manually, pass your own custom subclass to this property. */ public function get touchProcessor():TouchProcessor { return _touchProcessor; } public function set touchProcessor(value:TouchProcessor):void { if (value == null) throw new ArgumentError("TouchProcessor must not be null"); else if (value != _touchProcessor) { _touchProcessor.dispose(); _touchProcessor = value; } } /** The number of frames that have been rendered since this instance was created. */ public function get frameID():uint { return _frameID; } /** Indicates if the Context3D object is currently valid (i.e. it hasn't been lost or * disposed). */ public function get contextValid():Boolean { return _painter.contextValid; } // static properties /** The currently active Starling instance. */ public static function get current():Starling { return sCurrent; } /** All Starling instances. <p>CAUTION: not a copy, but the actual object! Do not modify!</p> */ public static function get all():Vector.<Starling> { return sAll; } /** The render context of the currently active Starling instance. */ public static function get context():Context3D { return sCurrent ? sCurrent.context : null; } /** The default juggler of the currently active Starling instance. */ public static function get juggler():Juggler { return sCurrent ? sCurrent._juggler : null; } /** The painter used for all rendering of the currently active Starling instance. */ public static function get painter():Painter { return sCurrent ? sCurrent._painter : null; } /** The contentScaleFactor of the currently active Starling instance. */ public static function get contentScaleFactor():Number { return sCurrent ? sCurrent.contentScaleFactor : 1.0; } /** Indicates if multitouch input should be supported. */ public static function get multitouchEnabled():Boolean { return Multitouch.inputMode == MultitouchInputMode.TOUCH_POINT; } public static function set multitouchEnabled(value:Boolean):void { if (sCurrent) throw new IllegalOperationError( "'multitouchEnabled' must be set before Starling instance is created"); else Multitouch.inputMode = value ? MultitouchInputMode.TOUCH_POINT : MultitouchInputMode.NONE; } /** The number of frames that have been rendered since the current instance was created. */ public static function get frameID():uint { return sCurrent ? sCurrent._frameID : 0; } } } import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; // put here to avoid naming conflicts function isNativeDisplayObjectEmpty(object:DisplayObject):Boolean { if (object == null) return true; else if (object is DisplayObjectContainer) { var container:DisplayObjectContainer = object as DisplayObjectContainer; var numChildren:int = container.numChildren; for (var i:int=0; i<numChildren; ++i) { if (!isNativeDisplayObjectEmpty(container.getChildAt(i))) return false; } return true; } else return !object.visible; }
412
0.923693
1
0.923693
game-dev
MEDIA
0.863648
game-dev
0.654968
1
0.654968
spartanoah/acrimony-client
69,728
net/minecraft/entity/Entity.java
/* * Decompiled with CFR 0.153-SNAPSHOT (d6f6758-dirty). */ package net.minecraft.entity; import Acrimony.Acrimony; import Acrimony.event.impl.PostStepEvent; import Acrimony.event.impl.PreStepEvent; import Acrimony.event.impl.RaytraceEvent; import Acrimony.module.impl.ghost.Safewalk; import Acrimony.util.ModuleUtil; import com.viaversion.viaversion.api.protocol.version.ProtocolVersion; import java.util.List; import java.util.Random; import java.util.UUID; import java.util.concurrent.Callable; import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFenceGate; import net.minecraft.block.BlockLiquid; import net.minecraft.block.BlockWall; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.pattern.BlockPattern; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.command.CommandResultStats; import net.minecraft.command.ICommandSender; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.EnchantmentProtection; import net.minecraft.entity.DataWatcher; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.event.HoverEvent; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagDouble; import net.minecraft.nbt.NBTTagFloat; import net.minecraft.nbt.NBTTagList; import net.minecraft.server.MinecraftServer; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentText; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.IChatComponent; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.ReportedException; import net.minecraft.util.StatCollector; import net.minecraft.util.Vec3; import net.minecraft.world.Explosion; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.vialoadingbase.ViaLoadingBase; public abstract class Entity implements ICommandSender { private static final AxisAlignedBB ZERO_AABB = new AxisAlignedBB(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); private static int nextEntityID; private int entityId = nextEntityID++; public double renderDistanceWeight = 1.0; public boolean preventEntitySpawning; public Entity riddenByEntity; public Entity ridingEntity; public boolean forceSpawn; public World worldObj; public double prevPosX; public double prevPosY; public double prevPosZ; public double posX; public double posY; public double posZ; public double motionX; public double motionY; public double motionZ; public float rotationYaw; public float rotationPitch; public float prevRotationYaw; public float prevRotationPitch; private AxisAlignedBB boundingBox = ZERO_AABB; public boolean onGround; public boolean isCollidedHorizontally; public boolean isCollidedVertically; public boolean isCollided; public boolean velocityChanged; protected boolean isInWeb; private boolean isOutsideBorder; public boolean isDead; public float width = 0.6f; public float height = 1.8f; public float prevDistanceWalkedModified; public float distanceWalkedModified; public float distanceWalkedOnStepModified; public float fallDistance; private int nextStepDistance = 1; public double lastTickPosX; public double lastTickPosY; public double lastTickPosZ; public float stepHeight; public boolean noClip; public float entityCollisionReduction; protected Random rand = new Random(); public int ticksExisted; public int ticksSinceExplosionVelo; public int fireResistance = 1; private int fire; protected boolean inWater; public int hurtResistantTime; protected boolean firstUpdate = true; protected boolean isImmuneToFire; protected DataWatcher dataWatcher; private double entityRiderPitchDelta; private double entityRiderYawDelta; public boolean addedToChunk; public int chunkCoordX; public int chunkCoordY; public int chunkCoordZ; public int serverPosX; public int serverPosY; public int serverPosZ; public boolean ignoreFrustumCheck; public boolean isAirBorne; public int timeUntilPortal; protected boolean inPortal; protected int portalCounter; public int dimension; protected BlockPos field_181016_an; protected Vec3 field_181017_ao; protected EnumFacing field_181018_ap; private boolean invulnerable; protected UUID entityUniqueID = MathHelper.getRandomUuid(this.rand); private final CommandResultStats cmdResultStats = new CommandResultStats(); public int getEntityId() { return this.entityId; } public void setEntityId(int id) { this.entityId = id; } public void onKillCommand() { this.setDead(); } public Entity(World worldIn) { this.worldObj = worldIn; this.setPosition(0.0, 0.0, 0.0); if (worldIn != null) { this.dimension = worldIn.provider.getDimensionId(); } this.dataWatcher = new DataWatcher(this); this.dataWatcher.addObject(0, (byte)0); this.dataWatcher.addObject(1, (short)300); this.dataWatcher.addObject(3, (byte)0); this.dataWatcher.addObject(2, ""); this.dataWatcher.addObject(4, (byte)0); this.entityInit(); } protected abstract void entityInit(); public DataWatcher getDataWatcher() { return this.dataWatcher; } public boolean equals(Object p_equals_1_) { return p_equals_1_ instanceof Entity ? ((Entity)p_equals_1_).entityId == this.entityId : false; } public int hashCode() { return this.entityId; } protected void preparePlayerToSpawn() { if (this.worldObj != null) { while (this.posY > 0.0 && this.posY < 256.0) { this.setPosition(this.posX, this.posY, this.posZ); if (this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty()) break; this.posY += 1.0; } this.motionZ = 0.0; this.motionY = 0.0; this.motionX = 0.0; this.rotationPitch = 0.0f; } } public void setDead() { this.isDead = true; } protected void setSize(float width, float height) { if (width != this.width || height != this.height) { float f = this.width; this.width = width; this.height = height; this.setEntityBoundingBox(new AxisAlignedBB(this.getEntityBoundingBox().minX, this.getEntityBoundingBox().minY, this.getEntityBoundingBox().minZ, this.getEntityBoundingBox().minX + (double)this.width, this.getEntityBoundingBox().minY + (double)this.height, this.getEntityBoundingBox().minZ + (double)this.width)); if (this.width > f && !this.firstUpdate && !this.worldObj.isRemote) { this.moveEntity(f - this.width, 0.0, f - this.width); } } } protected void setRotation(float yaw, float pitch) { this.rotationYaw = yaw % 360.0f; this.rotationPitch = pitch % 360.0f; } public void setPosition(double x, double y, double z) { this.posX = x; this.posY = y; this.posZ = z; float f = this.width / 2.0f; float f1 = this.height; this.setEntityBoundingBox(new AxisAlignedBB(x - (double)f, y, z - (double)f, x + (double)f, y + (double)f1, z + (double)f)); } public void setAngles(float yaw, float pitch) { float f = this.rotationPitch; float f1 = this.rotationYaw; this.rotationYaw = (float)((double)this.rotationYaw + (double)yaw * 0.15); this.rotationPitch = (float)((double)this.rotationPitch - (double)pitch * 0.15); this.rotationPitch = MathHelper.clamp_float(this.rotationPitch, -90.0f, 90.0f); this.prevRotationPitch += this.rotationPitch - f; this.prevRotationYaw += this.rotationYaw - f1; } public void onUpdate() { this.onEntityUpdate(); } public void onEntityUpdate() { this.worldObj.theProfiler.startSection("entityBaseTick"); if (this.ridingEntity != null && this.ridingEntity.isDead) { this.ridingEntity = null; } this.prevDistanceWalkedModified = this.distanceWalkedModified; this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; this.prevRotationPitch = this.rotationPitch; this.prevRotationYaw = this.rotationYaw; if (!this.worldObj.isRemote && this.worldObj instanceof WorldServer) { this.worldObj.theProfiler.startSection("portal"); MinecraftServer minecraftserver = ((WorldServer)this.worldObj).getMinecraftServer(); int i = this.getMaxInPortalTime(); if (this.inPortal) { if (minecraftserver.getAllowNether()) { if (this.ridingEntity == null && this.portalCounter++ >= i) { this.portalCounter = i; this.timeUntilPortal = this.getPortalCooldown(); int j = this.worldObj.provider.getDimensionId() == -1 ? 0 : -1; this.travelToDimension(j); } this.inPortal = false; } } else { if (this.portalCounter > 0) { this.portalCounter -= 4; } if (this.portalCounter < 0) { this.portalCounter = 0; } } if (this.timeUntilPortal > 0) { --this.timeUntilPortal; } this.worldObj.theProfiler.endSection(); } this.spawnRunningParticles(); this.handleWaterMovement(); if (this.worldObj.isRemote) { this.fire = 0; } else if (this.fire > 0) { if (this.isImmuneToFire) { this.fire -= 4; if (this.fire < 0) { this.fire = 0; } } else { if (this.fire % 20 == 0) { this.attackEntityFrom(DamageSource.onFire, 1.0f); } --this.fire; } } if (this.isInLava()) { this.setOnFireFromLava(); this.fallDistance *= 0.5f; } if (this.posY < -64.0) { this.kill(); } if (!this.worldObj.isRemote) { this.setFlag(0, this.fire > 0); } this.firstUpdate = false; this.worldObj.theProfiler.endSection(); } public int getMaxInPortalTime() { return 0; } protected void setOnFireFromLava() { if (!this.isImmuneToFire) { this.attackEntityFrom(DamageSource.lava, 4.0f); this.setFire(15); } } public void setFire(int seconds) { int i = seconds * 20; if (this.fire < (i = EnchantmentProtection.getFireTimeForEntity(this, i))) { this.fire = i; } } public void extinguish() { this.fire = 0; } protected void kill() { this.setDead(); } public boolean isOffsetPositionInLiquid(double x, double y, double z) { AxisAlignedBB axisalignedbb = this.getEntityBoundingBox().offset(x, y, z); return this.isLiquidPresentInAABB(axisalignedbb); } private boolean isLiquidPresentInAABB(AxisAlignedBB bb) { return this.worldObj.getCollidingBoundingBoxes(this, bb).isEmpty() && !this.worldObj.isAnyLiquid(bb); } public void moveEntity(double x, double y, double z) { if (this.noClip) { this.setEntityBoundingBox(this.getEntityBoundingBox().offset(x, y, z)); this.resetPositionToBB(); } else { Block block; Safewalk safewalkModule; boolean flag; this.worldObj.theProfiler.startSection("move"); double d0 = this.posX; double d1 = this.posY; double d2 = this.posZ; if (this.isInWeb) { this.isInWeb = false; x *= 0.25; y *= (double)0.05f; z *= 0.25; this.motionX = 0.0; this.motionY = 0.0; this.motionZ = 0.0; } double d3 = x; double d4 = y; double d5 = z; boolean bl = flag = this.onGround && this.isSneaking() && this instanceof EntityPlayer; if (this == Minecraft.getMinecraft().thePlayer && (safewalkModule = Acrimony.instance.getModuleManager().getModule(Safewalk.class)).isEnabled()) { flag = safewalkModule.offGround.isEnabled() ? true : this.onGround; } if (flag) { double d6 = 0.05; while (x != 0.0 && this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox().offset(x, -1.0, 0.0)).isEmpty()) { x = x < d6 && x >= -d6 ? 0.0 : (x > 0.0 ? (x -= d6) : (x += d6)); d3 = x; } while (z != 0.0 && this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox().offset(0.0, -1.0, z)).isEmpty()) { z = z < d6 && z >= -d6 ? 0.0 : (z > 0.0 ? (z -= d6) : (z += d6)); d5 = z; } while (x != 0.0 && z != 0.0 && this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox().offset(x, -1.0, z)).isEmpty()) { x = x < d6 && x >= -d6 ? 0.0 : (x > 0.0 ? (x -= d6) : (x += d6)); d3 = x; z = z < d6 && z >= -d6 ? 0.0 : (z > 0.0 ? (z -= d6) : (z += d6)); d5 = z; } } List<AxisAlignedBB> list1 = this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox().addCoord(x, y, z)); AxisAlignedBB axisalignedbb = this.getEntityBoundingBox(); for (AxisAlignedBB axisAlignedBB : list1) { y = axisAlignedBB.calculateYOffset(this.getEntityBoundingBox(), y); } this.setEntityBoundingBox(this.getEntityBoundingBox().offset(0.0, y, 0.0)); boolean flag1 = this.onGround || d4 != y && d4 < 0.0; for (AxisAlignedBB axisalignedbb2 : list1) { x = axisalignedbb2.calculateXOffset(this.getEntityBoundingBox(), x); } this.setEntityBoundingBox(this.getEntityBoundingBox().offset(x, 0.0, 0.0)); for (AxisAlignedBB axisalignedbb13 : list1) { z = axisalignedbb13.calculateZOffset(this.getEntityBoundingBox(), z); } this.setEntityBoundingBox(this.getEntityBoundingBox().offset(0.0, 0.0, z)); if (this.stepHeight > 0.0f && flag1 && (d3 != x || d5 != z)) { boolean isPlayer; double d = x; double d7 = y; double d8 = z; AxisAlignedBB axisalignedbb3 = this.getEntityBoundingBox(); this.setEntityBoundingBox(axisalignedbb); boolean bl2 = isPlayer = this == Minecraft.getMinecraft().thePlayer; if (isPlayer) { PreStepEvent event = new PreStepEvent(this.stepHeight); Acrimony.instance.getEventManager().post(event); y = event.getHeight(); } else { y = this.stepHeight; } List<AxisAlignedBB> list = this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox().addCoord(d3, y, d5)); AxisAlignedBB axisalignedbb4 = this.getEntityBoundingBox(); AxisAlignedBB axisalignedbb5 = axisalignedbb4.addCoord(d3, 0.0, d5); double d9 = y; for (AxisAlignedBB axisalignedbb6 : list) { d9 = axisalignedbb6.calculateYOffset(axisalignedbb5, d9); } axisalignedbb4 = axisalignedbb4.offset(0.0, d9, 0.0); double d15 = d3; for (AxisAlignedBB axisalignedbb7 : list) { d15 = axisalignedbb7.calculateXOffset(axisalignedbb4, d15); } axisalignedbb4 = axisalignedbb4.offset(d15, 0.0, 0.0); double d16 = d5; for (AxisAlignedBB axisalignedbb8 : list) { d16 = axisalignedbb8.calculateZOffset(axisalignedbb4, d16); } axisalignedbb4 = axisalignedbb4.offset(0.0, 0.0, d16); AxisAlignedBB axisalignedbb14 = this.getEntityBoundingBox(); double d17 = y; for (AxisAlignedBB axisalignedbb9 : list) { d17 = axisalignedbb9.calculateYOffset(axisalignedbb14, d17); } axisalignedbb14 = axisalignedbb14.offset(0.0, d17, 0.0); double d18 = d3; for (AxisAlignedBB axisalignedbb10 : list) { d18 = axisalignedbb10.calculateXOffset(axisalignedbb14, d18); } axisalignedbb14 = axisalignedbb14.offset(d18, 0.0, 0.0); double d19 = d5; for (AxisAlignedBB axisalignedbb11 : list) { d19 = axisalignedbb11.calculateZOffset(axisalignedbb14, d19); } axisalignedbb14 = axisalignedbb14.offset(0.0, 0.0, d19); double d20 = d15 * d15 + d16 * d16; double d10 = d18 * d18 + d19 * d19; if (d20 > d10) { x = d15; z = d16; y = -d9; this.setEntityBoundingBox(axisalignedbb4); } else { x = d18; z = d19; y = -d17; this.setEntityBoundingBox(axisalignedbb14); } for (AxisAlignedBB axisalignedbb12 : list) { y = axisalignedbb12.calculateYOffset(this.getEntityBoundingBox(), y); } this.setEntityBoundingBox(this.getEntityBoundingBox().offset(0.0, y, 0.0)); if (d * d + d8 * d8 >= x * x + z * z) { x = d; y = d7; z = d8; this.setEntityBoundingBox(axisalignedbb3); } if (isPlayer) { Acrimony.instance.getEventManager().post(new PostStepEvent((float)(this.getEntityBoundingBox().minY - this.posY))); } } this.worldObj.theProfiler.endSection(); this.worldObj.theProfiler.startSection("rest"); this.resetPositionToBB(); this.isCollidedHorizontally = d3 != x || d5 != z; this.isCollidedVertically = d4 != y; this.onGround = this.isCollidedVertically && d4 < 0.0; this.isCollided = this.isCollidedHorizontally || this.isCollidedVertically; int n = MathHelper.floor_double(this.posX); int j = MathHelper.floor_double(this.posY - (double)0.2f); int k = MathHelper.floor_double(this.posZ); BlockPos blockpos = new BlockPos(n, j, k); Block block1 = this.worldObj.getBlockState(blockpos).getBlock(); if (block1.getMaterial() == Material.air && ((block = this.worldObj.getBlockState(blockpos.down()).getBlock()) instanceof BlockFence || block instanceof BlockWall || block instanceof BlockFenceGate)) { block1 = block; blockpos = blockpos.down(); } this.updateFallState(y, this.onGround, block1, blockpos); if (d3 != x) { this.motionX = 0.0; } if (d5 != z) { this.motionZ = 0.0; } if (d4 != y) { block1.onLanded(this.worldObj, this); } if (this.canTriggerWalking() && !flag && this.ridingEntity == null) { double d12 = this.posX - d0; double d13 = this.posY - d1; double d14 = this.posZ - d2; if (block1 != Blocks.ladder) { d13 = 0.0; } if (block1 != null && this.onGround) { block1.onEntityCollidedWithBlock(this.worldObj, blockpos, this); } this.distanceWalkedModified = (float)((double)this.distanceWalkedModified + (double)MathHelper.sqrt_double(d12 * d12 + d14 * d14) * 0.6); this.distanceWalkedOnStepModified = (float)((double)this.distanceWalkedOnStepModified + (double)MathHelper.sqrt_double(d12 * d12 + d13 * d13 + d14 * d14) * 0.6); if (this.distanceWalkedOnStepModified > (float)this.nextStepDistance && block1.getMaterial() != Material.air) { this.nextStepDistance = (int)this.distanceWalkedOnStepModified + 1; if (this.isInWater()) { float f = MathHelper.sqrt_double(this.motionX * this.motionX * (double)0.2f + this.motionY * this.motionY + this.motionZ * this.motionZ * (double)0.2f) * 0.35f; if (f > 1.0f) { f = 1.0f; } this.playSound(this.getSwimSound(), f, 1.0f + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.4f); } this.playStepSound(blockpos, block1); } } try { this.doBlockCollisions(); } catch (Throwable throwable) { CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Checking entity block collision"); CrashReportCategory crashreportcategory = crashreport.makeCategory("Entity being checked for collision"); this.addEntityCrashInfo(crashreportcategory); throw new ReportedException(crashreport); } boolean flag2 = this.isWet(); if (this.worldObj.isFlammableWithin(this.getEntityBoundingBox().contract(0.001, 0.001, 0.001))) { this.dealFireDamage(1); if (!flag2) { ++this.fire; if (this.fire == 0) { this.setFire(8); } } } else if (this.fire <= 0) { this.fire = -this.fireResistance; } if (flag2 && this.fire > 0) { this.playSound("random.fizz", 0.7f, 1.6f + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.4f); this.fire = -this.fireResistance; } this.worldObj.theProfiler.endSection(); } } private void resetPositionToBB() { this.posX = (this.getEntityBoundingBox().minX + this.getEntityBoundingBox().maxX) / 2.0; this.posY = this.getEntityBoundingBox().minY; this.posZ = (this.getEntityBoundingBox().minZ + this.getEntityBoundingBox().maxZ) / 2.0; } protected String getSwimSound() { return "game.neutral.swim"; } protected void doBlockCollisions() { BlockPos blockpos = new BlockPos(this.getEntityBoundingBox().minX + 0.001, this.getEntityBoundingBox().minY + 0.001, this.getEntityBoundingBox().minZ + 0.001); BlockPos blockpos1 = new BlockPos(this.getEntityBoundingBox().maxX - 0.001, this.getEntityBoundingBox().maxY - 0.001, this.getEntityBoundingBox().maxZ - 0.001); if (this.worldObj.isAreaLoaded(blockpos, blockpos1)) { for (int i = blockpos.getX(); i <= blockpos1.getX(); ++i) { for (int j = blockpos.getY(); j <= blockpos1.getY(); ++j) { for (int k = blockpos.getZ(); k <= blockpos1.getZ(); ++k) { BlockPos blockpos2 = new BlockPos(i, j, k); IBlockState iblockstate = this.worldObj.getBlockState(blockpos2); try { iblockstate.getBlock().onEntityCollidedWithBlock(this.worldObj, blockpos2, iblockstate, this); continue; } catch (Throwable throwable) { CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Colliding entity with block"); CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being collided with"); CrashReportCategory.addBlockInfo(crashreportcategory, blockpos2, iblockstate); throw new ReportedException(crashreport); } } } } } } protected void playStepSound(BlockPos pos, Block blockIn) { Block.SoundType block$soundtype = blockIn.stepSound; if (this.worldObj.getBlockState(pos.up()).getBlock() == Blocks.snow_layer) { block$soundtype = Blocks.snow_layer.stepSound; this.playSound(block$soundtype.getStepSound(), block$soundtype.getVolume() * 0.15f, block$soundtype.getFrequency()); } else if (!blockIn.getMaterial().isLiquid()) { this.playSound(block$soundtype.getStepSound(), block$soundtype.getVolume() * 0.15f, block$soundtype.getFrequency()); } } public void playSound(String name, float volume, float pitch) { if (!this.isSilent()) { this.worldObj.playSoundAtEntity(this, name, volume, pitch); } } public boolean isSilent() { return this.dataWatcher.getWatchableObjectByte(4) == 1; } public void setSilent(boolean isSilent) { this.dataWatcher.updateObject(4, (byte)(isSilent ? (char)'\u0001' : '\u0000')); } protected boolean canTriggerWalking() { return true; } protected void updateFallState(double y, boolean onGroundIn, Block blockIn, BlockPos pos) { if (onGroundIn) { if (this.fallDistance > 0.0f) { if (blockIn != null) { blockIn.onFallenUpon(this.worldObj, pos, this, this.fallDistance); } else { this.fall(this.fallDistance, 1.0f); } this.fallDistance = 0.0f; } } else if (y < 0.0) { this.fallDistance = (float)((double)this.fallDistance - y); } } public AxisAlignedBB getCollisionBoundingBox() { return null; } protected void dealFireDamage(int amount) { if (!this.isImmuneToFire) { this.attackEntityFrom(DamageSource.inFire, amount); } } public final boolean isImmuneToFire() { return this.isImmuneToFire; } public void fall(float distance, float damageMultiplier) { if (this.riddenByEntity != null) { this.riddenByEntity.fall(distance, damageMultiplier); } } public boolean isWet() { return this.inWater || this.worldObj.canLightningStrike(new BlockPos(this.posX, this.posY, this.posZ)) || this.worldObj.canLightningStrike(new BlockPos(this.posX, this.posY + (double)this.height, this.posZ)); } public boolean isInWater() { return this.inWater; } public boolean handleWaterMovement() { if (this.worldObj.handleMaterialAcceleration(this.getEntityBoundingBox().expand(0.0, -0.4f, 0.0).contract(0.001, 0.001, 0.001), Material.water, this)) { if (!this.inWater && !this.firstUpdate) { this.resetHeight(); } this.fallDistance = 0.0f; this.inWater = true; this.fire = 0; } else { this.inWater = false; } return this.inWater; } protected void resetHeight() { float f = MathHelper.sqrt_double(this.motionX * this.motionX * (double)0.2f + this.motionY * this.motionY + this.motionZ * this.motionZ * (double)0.2f) * 0.2f; if (f > 1.0f) { f = 1.0f; } this.playSound(this.getSplashSound(), f, 1.0f + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.4f); float f1 = MathHelper.floor_double(this.getEntityBoundingBox().minY); int i = 0; while ((float)i < 1.0f + this.width * 20.0f) { float f2 = (this.rand.nextFloat() * 2.0f - 1.0f) * this.width; float f3 = (this.rand.nextFloat() * 2.0f - 1.0f) * this.width; this.worldObj.spawnParticle(EnumParticleTypes.WATER_BUBBLE, this.posX + (double)f2, (double)(f1 + 1.0f), this.posZ + (double)f3, this.motionX, this.motionY - (double)(this.rand.nextFloat() * 0.2f), this.motionZ, new int[0]); ++i; } int j = 0; while ((float)j < 1.0f + this.width * 20.0f) { float f4 = (this.rand.nextFloat() * 2.0f - 1.0f) * this.width; float f5 = (this.rand.nextFloat() * 2.0f - 1.0f) * this.width; this.worldObj.spawnParticle(EnumParticleTypes.WATER_SPLASH, this.posX + (double)f4, (double)(f1 + 1.0f), this.posZ + (double)f5, this.motionX, this.motionY, this.motionZ, new int[0]); ++j; } } public void spawnRunningParticles() { if (this.isSprinting() && !this.isInWater()) { this.createRunningParticles(); } } protected void createRunningParticles() { int k; int j; int i = MathHelper.floor_double(this.posX); BlockPos blockpos = new BlockPos(i, j = MathHelper.floor_double(this.posY - (double)0.2f), k = MathHelper.floor_double(this.posZ)); IBlockState iblockstate = this.worldObj.getBlockState(blockpos); Block block = iblockstate.getBlock(); if (block.getRenderType() != -1) { this.worldObj.spawnParticle(EnumParticleTypes.BLOCK_CRACK, this.posX + ((double)this.rand.nextFloat() - 0.5) * (double)this.width, this.getEntityBoundingBox().minY + 0.1, this.posZ + ((double)this.rand.nextFloat() - 0.5) * (double)this.width, -this.motionX * 4.0, 1.5, -this.motionZ * 4.0, Block.getStateId(iblockstate)); } } protected String getSplashSound() { return "game.neutral.swim.splash"; } public boolean isInsideOfMaterial(Material materialIn) { double d0 = this.posY + (double)this.getEyeHeight(); BlockPos blockpos = new BlockPos(this.posX, d0, this.posZ); IBlockState iblockstate = this.worldObj.getBlockState(blockpos); Block block = iblockstate.getBlock(); if (block.getMaterial() == materialIn) { float f = BlockLiquid.getLiquidHeightPercent(iblockstate.getBlock().getMetaFromState(iblockstate)) - 0.11111111f; float f1 = (float)(blockpos.getY() + 1) - f; boolean flag = d0 < (double)f1; return !flag && this instanceof EntityPlayer ? false : flag; } return false; } public boolean isInLava() { return this.worldObj.isMaterialInBB(this.getEntityBoundingBox().expand(-0.1f, -0.4f, -0.1f), Material.lava); } public void moveFlying(float strafe, float forward, float friction, float yaw) { float f = strafe * strafe + forward * forward; if (f >= 1.0E-4f) { if ((f = MathHelper.sqrt_float(f)) < 1.0f) { f = 1.0f; } f = friction / f; float f1 = MathHelper.sin(yaw * (float)Math.PI / 180.0f); float f2 = MathHelper.cos(yaw * (float)Math.PI / 180.0f); this.motionX += (double)((strafe *= f) * f2 - (forward *= f) * f1); this.motionZ += (double)(forward * f2 + strafe * f1); } } public int getBrightnessForRender(float partialTicks) { BlockPos blockpos = new BlockPos(this.posX, this.posY + (double)this.getEyeHeight(), this.posZ); return this.worldObj.isBlockLoaded(blockpos) ? this.worldObj.getCombinedLight(blockpos, 0) : 0; } public float getBrightness(float partialTicks) { BlockPos blockpos = new BlockPos(this.posX, this.posY + (double)this.getEyeHeight(), this.posZ); return this.worldObj.isBlockLoaded(blockpos) ? this.worldObj.getLightBrightness(blockpos) : 0.0f; } public void setWorld(World worldIn) { this.worldObj = worldIn; } public void setPositionAndRotation(double x, double y, double z, float yaw, float pitch) { this.prevPosX = this.posX = x; this.prevPosY = this.posY = y; this.prevPosZ = this.posZ = z; this.prevRotationYaw = this.rotationYaw = yaw; this.prevRotationPitch = this.rotationPitch = pitch; double d0 = this.prevRotationYaw - yaw; if (d0 < -180.0) { this.prevRotationYaw += 360.0f; } if (d0 >= 180.0) { this.prevRotationYaw -= 360.0f; } this.setPosition(this.posX, this.posY, this.posZ); this.setRotation(yaw, pitch); } public void moveToBlockPosAndAngles(BlockPos pos, float rotationYawIn, float rotationPitchIn) { this.setLocationAndAngles((double)pos.getX() + 0.5, pos.getY(), (double)pos.getZ() + 0.5, rotationYawIn, rotationPitchIn); } public void setLocationAndAngles(double x, double y, double z, float yaw, float pitch) { this.prevPosX = this.posX = x; this.lastTickPosX = this.posX; this.prevPosY = this.posY = y; this.lastTickPosY = this.posY; this.prevPosZ = this.posZ = z; this.lastTickPosZ = this.posZ; this.rotationYaw = yaw; this.rotationPitch = pitch; this.setPosition(this.posX, this.posY, this.posZ); } public float getDistanceToEntity(Entity entityIn) { float f = (float)(this.posX - entityIn.posX); float f1 = (float)(this.posY - entityIn.posY); float f2 = (float)(this.posZ - entityIn.posZ); return MathHelper.sqrt_float(f * f + f1 * f1 + f2 * f2); } public double getDistanceSq(double x, double y, double z) { double d0 = this.posX - x; double d1 = this.posY - y; double d2 = this.posZ - z; return d0 * d0 + d1 * d1 + d2 * d2; } public double getDistanceSq(BlockPos pos) { return pos.distanceSq(this.posX, this.posY, this.posZ); } public double getDistanceSqToCenter(BlockPos pos) { return pos.distanceSqToCenter(this.posX, this.posY, this.posZ); } public double getDistance(double x, double y, double z) { double d0 = this.posX - x; double d1 = this.posY - y; double d2 = this.posZ - z; return MathHelper.sqrt_double(d0 * d0 + d1 * d1 + d2 * d2); } public double getDistanceSqToEntity(Entity entityIn) { double d0 = this.posX - entityIn.posX; double d1 = this.posY - entityIn.posY; double d2 = this.posZ - entityIn.posZ; return d0 * d0 + d1 * d1 + d2 * d2; } public void onCollideWithPlayer(EntityPlayer entityIn) { } public void applyEntityCollision(Entity entityIn) { double d1; double d0; double d2; if (entityIn.riddenByEntity != this && entityIn.ridingEntity != this && !entityIn.noClip && !this.noClip && (d2 = MathHelper.abs_max(d0 = entityIn.posX - this.posX, d1 = entityIn.posZ - this.posZ)) >= (double)0.01f) { d2 = MathHelper.sqrt_double(d2); d0 /= d2; d1 /= d2; double d3 = 1.0 / d2; if (d3 > 1.0) { d3 = 1.0; } d0 *= d3; d1 *= d3; d0 *= (double)0.05f; d1 *= (double)0.05f; d0 *= (double)(1.0f - this.entityCollisionReduction); d1 *= (double)(1.0f - this.entityCollisionReduction); if (this.riddenByEntity == null) { this.addVelocity(-d0, 0.0, -d1); } if (entityIn.riddenByEntity == null) { entityIn.addVelocity(d0, 0.0, d1); } } } public void addVelocity(double x, double y, double z) { this.motionX += x; this.motionY += y; this.motionZ += z; this.isAirBorne = true; } protected void setBeenAttacked() { this.velocityChanged = true; } public boolean attackEntityFrom(DamageSource source, float amount) { if (this.isEntityInvulnerable(source)) { return false; } this.setBeenAttacked(); return false; } public Vec3 getLook(float partialTicks) { RaytraceEvent raytraceEvent = new RaytraceEvent(this.rotationYaw, this.rotationPitch, this.prevRotationYaw, this.prevRotationPitch, partialTicks); if (this == Minecraft.getMinecraft().thePlayer) { Acrimony.instance.getEventManager().post(raytraceEvent); } if (ModuleUtil.getDelayRemover().isEnabled() && ModuleUtil.getDelayRemover().mouseDelayMode.is("None") && this instanceof EntityPlayerSP) { return this.getVectorForRotation(raytraceEvent.getPitch(), raytraceEvent.getYaw()); } if (partialTicks == 1.0f) { return this.getVectorForRotation(raytraceEvent.getPitch(), raytraceEvent.getYaw()); } float f = raytraceEvent.getPrevPitch() + (raytraceEvent.getPitch() - raytraceEvent.getPrevPitch()) * partialTicks; float f1 = raytraceEvent.getPrevYaw() + (raytraceEvent.getYaw() - raytraceEvent.getPrevYaw()) * partialTicks; return this.getVectorForRotation(f, f1); } public final Vec3 getVectorForRotation(float pitch, float yaw) { float f = MathHelper.cos(-yaw * ((float)Math.PI / 180) - (float)Math.PI); float f1 = MathHelper.sin(-yaw * ((float)Math.PI / 180) - (float)Math.PI); float f2 = -MathHelper.cos(-pitch * ((float)Math.PI / 180)); float f3 = MathHelper.sin(-pitch * ((float)Math.PI / 180)); return new Vec3(f1 * f2, f3, f * f2); } public Vec3 getPositionEyes(float partialTicks) { if (partialTicks == 1.0f) { return new Vec3(this.posX, this.posY + (double)this.getEyeHeight(), this.posZ); } double d0 = this.prevPosX + (this.posX - this.prevPosX) * (double)partialTicks; double d1 = this.prevPosY + (this.posY - this.prevPosY) * (double)partialTicks + (double)this.getEyeHeight(); double d2 = this.prevPosZ + (this.posZ - this.prevPosZ) * (double)partialTicks; return new Vec3(d0, d1, d2); } public MovingObjectPosition rayTrace(double blockReachDistance, float partialTicks) { Vec3 vec3 = this.getPositionEyes(partialTicks); Vec3 vec31 = this.getLook(partialTicks); Vec3 vec32 = vec3.addVector(vec31.xCoord * blockReachDistance, vec31.yCoord * blockReachDistance, vec31.zCoord * blockReachDistance); return this.worldObj.rayTraceBlocks(vec3, vec32, false, false, true); } public boolean canBeCollidedWith() { return false; } public boolean canBePushed() { return false; } public void addToPlayerScore(Entity entityIn, int amount) { } public boolean isInRangeToRender3d(double x, double y, double z) { double d0 = this.posX - x; double d1 = this.posY - y; double d2 = this.posZ - z; double d3 = d0 * d0 + d1 * d1 + d2 * d2; return this.isInRangeToRenderDist(d3); } public boolean isInRangeToRenderDist(double distance) { double d0 = this.getEntityBoundingBox().getAverageEdgeLength(); if (Double.isNaN(d0)) { d0 = 1.0; } return distance < (d0 = d0 * 64.0 * this.renderDistanceWeight) * d0; } public boolean writeMountToNBT(NBTTagCompound tagCompund) { String s = this.getEntityString(); if (!this.isDead && s != null) { tagCompund.setString("id", s); this.writeToNBT(tagCompund); return true; } return false; } public boolean writeToNBTOptional(NBTTagCompound tagCompund) { String s = this.getEntityString(); if (!this.isDead && s != null && this.riddenByEntity == null) { tagCompund.setString("id", s); this.writeToNBT(tagCompund); return true; } return false; } public void writeToNBT(NBTTagCompound tagCompund) { try { NBTTagCompound nbttagcompound; tagCompund.setTag("Pos", this.newDoubleNBTList(this.posX, this.posY, this.posZ)); tagCompund.setTag("Motion", this.newDoubleNBTList(this.motionX, this.motionY, this.motionZ)); tagCompund.setTag("Rotation", this.newFloatNBTList(this.rotationYaw, this.rotationPitch)); tagCompund.setFloat("FallDistance", this.fallDistance); tagCompund.setShort("Fire", (short)this.fire); tagCompund.setShort("Air", (short)this.getAir()); tagCompund.setBoolean("OnGround", this.onGround); tagCompund.setInteger("Dimension", this.dimension); tagCompund.setBoolean("Invulnerable", this.invulnerable); tagCompund.setInteger("PortalCooldown", this.timeUntilPortal); tagCompund.setLong("UUIDMost", this.getUniqueID().getMostSignificantBits()); tagCompund.setLong("UUIDLeast", this.getUniqueID().getLeastSignificantBits()); if (this.getCustomNameTag() != null && this.getCustomNameTag().length() > 0) { tagCompund.setString("CustomName", this.getCustomNameTag()); tagCompund.setBoolean("CustomNameVisible", this.getAlwaysRenderNameTag()); } this.cmdResultStats.writeStatsToNBT(tagCompund); if (this.isSilent()) { tagCompund.setBoolean("Silent", this.isSilent()); } this.writeEntityToNBT(tagCompund); if (this.ridingEntity != null && this.ridingEntity.writeMountToNBT(nbttagcompound = new NBTTagCompound())) { tagCompund.setTag("Riding", nbttagcompound); } } catch (Throwable throwable) { CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Saving entity NBT"); CrashReportCategory crashreportcategory = crashreport.makeCategory("Entity being saved"); this.addEntityCrashInfo(crashreportcategory); throw new ReportedException(crashreport); } } public void readFromNBT(NBTTagCompound tagCompund) { try { NBTTagList nbttaglist = tagCompund.getTagList("Pos", 6); NBTTagList nbttaglist1 = tagCompund.getTagList("Motion", 6); NBTTagList nbttaglist2 = tagCompund.getTagList("Rotation", 5); this.motionX = nbttaglist1.getDoubleAt(0); this.motionY = nbttaglist1.getDoubleAt(1); this.motionZ = nbttaglist1.getDoubleAt(2); if (Math.abs(this.motionX) > 10.0) { this.motionX = 0.0; } if (Math.abs(this.motionY) > 10.0) { this.motionY = 0.0; } if (Math.abs(this.motionZ) > 10.0) { this.motionZ = 0.0; } this.lastTickPosX = this.posX = nbttaglist.getDoubleAt(0); this.prevPosX = this.posX; this.lastTickPosY = this.posY = nbttaglist.getDoubleAt(1); this.prevPosY = this.posY; this.lastTickPosZ = this.posZ = nbttaglist.getDoubleAt(2); this.prevPosZ = this.posZ; this.prevRotationYaw = this.rotationYaw = nbttaglist2.getFloatAt(0); this.prevRotationPitch = this.rotationPitch = nbttaglist2.getFloatAt(1); this.setRotationYawHead(this.rotationYaw); this.func_181013_g(this.rotationYaw); this.fallDistance = tagCompund.getFloat("FallDistance"); this.fire = tagCompund.getShort("Fire"); this.setAir(tagCompund.getShort("Air")); this.onGround = tagCompund.getBoolean("OnGround"); this.dimension = tagCompund.getInteger("Dimension"); this.invulnerable = tagCompund.getBoolean("Invulnerable"); this.timeUntilPortal = tagCompund.getInteger("PortalCooldown"); if (tagCompund.hasKey("UUIDMost", 4) && tagCompund.hasKey("UUIDLeast", 4)) { this.entityUniqueID = new UUID(tagCompund.getLong("UUIDMost"), tagCompund.getLong("UUIDLeast")); } else if (tagCompund.hasKey("UUID", 8)) { this.entityUniqueID = UUID.fromString(tagCompund.getString("UUID")); } this.setPosition(this.posX, this.posY, this.posZ); this.setRotation(this.rotationYaw, this.rotationPitch); if (tagCompund.hasKey("CustomName", 8) && tagCompund.getString("CustomName").length() > 0) { this.setCustomNameTag(tagCompund.getString("CustomName")); } this.setAlwaysRenderNameTag(tagCompund.getBoolean("CustomNameVisible")); this.cmdResultStats.readStatsFromNBT(tagCompund); this.setSilent(tagCompund.getBoolean("Silent")); this.readEntityFromNBT(tagCompund); if (this.shouldSetPosAfterLoading()) { this.setPosition(this.posX, this.posY, this.posZ); } } catch (Throwable throwable) { CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Loading entity NBT"); CrashReportCategory crashreportcategory = crashreport.makeCategory("Entity being loaded"); this.addEntityCrashInfo(crashreportcategory); throw new ReportedException(crashreport); } } protected boolean shouldSetPosAfterLoading() { return true; } protected final String getEntityString() { return EntityList.getEntityString(this); } protected abstract void readEntityFromNBT(NBTTagCompound var1); protected abstract void writeEntityToNBT(NBTTagCompound var1); public void onChunkLoad() { } protected NBTTagList newDoubleNBTList(double ... numbers) { NBTTagList nbttaglist = new NBTTagList(); for (double d0 : numbers) { nbttaglist.appendTag(new NBTTagDouble(d0)); } return nbttaglist; } protected NBTTagList newFloatNBTList(float ... numbers) { NBTTagList nbttaglist = new NBTTagList(); for (float f : numbers) { nbttaglist.appendTag(new NBTTagFloat(f)); } return nbttaglist; } public EntityItem dropItem(Item itemIn, int size) { return this.dropItemWithOffset(itemIn, size, 0.0f); } public EntityItem dropItemWithOffset(Item itemIn, int size, float offsetY) { return this.entityDropItem(new ItemStack(itemIn, size, 0), offsetY); } public EntityItem entityDropItem(ItemStack itemStackIn, float offsetY) { if (itemStackIn.stackSize != 0 && itemStackIn.getItem() != null) { EntityItem entityitem = new EntityItem(this.worldObj, this.posX, this.posY + (double)offsetY, this.posZ, itemStackIn); entityitem.setDefaultPickupDelay(); this.worldObj.spawnEntityInWorld(entityitem); return entityitem; } return null; } public boolean isEntityAlive() { return !this.isDead; } public boolean isEntityInsideOpaqueBlock() { if (this.noClip) { return false; } BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); for (int i = 0; i < 8; ++i) { int j = MathHelper.floor_double(this.posY + (double)(((float)((i >> 0) % 2) - 0.5f) * 0.1f) + (double)this.getEyeHeight()); int k = MathHelper.floor_double(this.posX + (double)(((float)((i >> 1) % 2) - 0.5f) * this.width * 0.8f)); int l = MathHelper.floor_double(this.posZ + (double)(((float)((i >> 2) % 2) - 0.5f) * this.width * 0.8f)); if (blockpos$mutableblockpos.getX() == k && blockpos$mutableblockpos.getY() == j && blockpos$mutableblockpos.getZ() == l) continue; blockpos$mutableblockpos.func_181079_c(k, j, l); if (!this.worldObj.getBlockState(blockpos$mutableblockpos).getBlock().isVisuallyOpaque()) continue; return true; } return false; } public boolean interactFirst(EntityPlayer playerIn) { return false; } public AxisAlignedBB getCollisionBox(Entity entityIn) { return null; } public void updateRidden() { if (this.ridingEntity.isDead) { this.ridingEntity = null; } else { this.motionX = 0.0; this.motionY = 0.0; this.motionZ = 0.0; this.onUpdate(); if (this.ridingEntity != null) { this.ridingEntity.updateRiderPosition(); this.entityRiderYawDelta += (double)(this.ridingEntity.rotationYaw - this.ridingEntity.prevRotationYaw); this.entityRiderPitchDelta += (double)(this.ridingEntity.rotationPitch - this.ridingEntity.prevRotationPitch); while (this.entityRiderYawDelta >= 180.0) { this.entityRiderYawDelta -= 360.0; } while (this.entityRiderYawDelta < -180.0) { this.entityRiderYawDelta += 360.0; } while (this.entityRiderPitchDelta >= 180.0) { this.entityRiderPitchDelta -= 360.0; } while (this.entityRiderPitchDelta < -180.0) { this.entityRiderPitchDelta += 360.0; } double d0 = this.entityRiderYawDelta * 0.5; double d1 = this.entityRiderPitchDelta * 0.5; float f = 10.0f; if (d0 > (double)f) { d0 = f; } if (d0 < (double)(-f)) { d0 = -f; } if (d1 > (double)f) { d1 = f; } if (d1 < (double)(-f)) { d1 = -f; } this.entityRiderYawDelta -= d0; this.entityRiderPitchDelta -= d1; } } } public void updateRiderPosition() { if (this.riddenByEntity != null) { this.riddenByEntity.setPosition(this.posX, this.posY + this.getMountedYOffset() + this.riddenByEntity.getYOffset(), this.posZ); } } public double getYOffset() { return 0.0; } public double getMountedYOffset() { return (double)this.height * 0.75; } public void mountEntity(Entity entityIn) { this.entityRiderPitchDelta = 0.0; this.entityRiderYawDelta = 0.0; if (entityIn == null) { if (this.ridingEntity != null) { this.setLocationAndAngles(this.ridingEntity.posX, this.ridingEntity.getEntityBoundingBox().minY + (double)this.ridingEntity.height, this.ridingEntity.posZ, this.rotationYaw, this.rotationPitch); this.ridingEntity.riddenByEntity = null; } this.ridingEntity = null; } else { if (this.ridingEntity != null) { this.ridingEntity.riddenByEntity = null; } if (entityIn != null) { Entity entity = entityIn.ridingEntity; while (entity != null) { if (entity == this) { return; } entity = entity.ridingEntity; } } this.ridingEntity = entityIn; entityIn.riddenByEntity = this; } } public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) { this.setPosition(x, y, z); this.setRotation(yaw, pitch); List<AxisAlignedBB> list = this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox().contract(0.03125, 0.0, 0.03125)); if (!list.isEmpty()) { double d0 = 0.0; for (AxisAlignedBB axisalignedbb : list) { if (!(axisalignedbb.maxY > d0)) continue; d0 = axisalignedbb.maxY; } this.setPosition(x, y += d0 - this.getEntityBoundingBox().minY, z); } } public float getCollisionBorderSize() { if (ViaLoadingBase.getInstance().getTargetVersion().isNewerThan(ProtocolVersion.v1_8)) { return 0.0f; } return 0.1f; } public Vec3 getLookVec() { return null; } public void func_181015_d(BlockPos p_181015_1_) { if (this.timeUntilPortal > 0) { this.timeUntilPortal = this.getPortalCooldown(); } else { if (!this.worldObj.isRemote && !p_181015_1_.equals(this.field_181016_an)) { this.field_181016_an = p_181015_1_; BlockPattern.PatternHelper blockpattern$patternhelper = Blocks.portal.func_181089_f(this.worldObj, p_181015_1_); double d0 = blockpattern$patternhelper.getFinger().getAxis() == EnumFacing.Axis.X ? (double)blockpattern$patternhelper.func_181117_a().getZ() : (double)blockpattern$patternhelper.func_181117_a().getX(); double d1 = blockpattern$patternhelper.getFinger().getAxis() == EnumFacing.Axis.X ? this.posZ : this.posX; d1 = Math.abs(MathHelper.func_181160_c(d1 - (double)(blockpattern$patternhelper.getFinger().rotateY().getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE ? (char)'\u0001' : '\u0000'), d0, d0 - (double)blockpattern$patternhelper.func_181118_d())); double d2 = MathHelper.func_181160_c(this.posY - 1.0, blockpattern$patternhelper.func_181117_a().getY(), blockpattern$patternhelper.func_181117_a().getY() - blockpattern$patternhelper.func_181119_e()); this.field_181017_ao = new Vec3(d1, d2, 0.0); this.field_181018_ap = blockpattern$patternhelper.getFinger(); } this.inPortal = true; } } public int getPortalCooldown() { return 300; } public void setVelocity(double x, double y, double z) { this.motionX = x; this.motionY = y; this.motionZ = z; } public void handleHealthUpdate(byte id) { } public void performHurtAnimation() { } public ItemStack[] getInventory() { return null; } public void setCurrentItemOrArmor(int slotIn, ItemStack stack) { } public boolean isBurning() { boolean flag = this.worldObj != null && this.worldObj.isRemote; return !this.isImmuneToFire && (this.fire > 0 || flag && this.getFlag(0)); } public boolean isRiding() { return this.ridingEntity != null; } public boolean isSneaking() { return this.getFlag(1); } public void setSneaking(boolean sneaking) { this.setFlag(1, sneaking); } public boolean isSprinting() { return this.getFlag(3); } public void setSprinting(boolean sprinting) { this.setFlag(3, sprinting); } public boolean isInvisible() { return this.getFlag(5); } public boolean isInvisibleToPlayer(EntityPlayer player) { return player.isSpectator() ? false : this.isInvisible(); } public void setInvisible(boolean invisible) { this.setFlag(5, invisible); } public boolean isEating() { return this.getFlag(4); } public void setEating(boolean eating) { this.setFlag(4, eating); } protected boolean getFlag(int flag) { return (this.dataWatcher.getWatchableObjectByte(0) & 1 << flag) != 0; } protected void setFlag(int flag, boolean set) { byte b0 = this.dataWatcher.getWatchableObjectByte(0); if (set) { this.dataWatcher.updateObject(0, (byte)(b0 | 1 << flag)); } else { this.dataWatcher.updateObject(0, (byte)(b0 & ~(1 << flag))); } } public int getAir() { return this.dataWatcher.getWatchableObjectShort(1); } public void setAir(int air) { this.dataWatcher.updateObject(1, (short)air); } public void onStruckByLightning(EntityLightningBolt lightningBolt) { this.attackEntityFrom(DamageSource.lightningBolt, 5.0f); ++this.fire; if (this.fire == 0) { this.setFire(8); } } public void onKillEntity(EntityLivingBase entityLivingIn) { } protected boolean pushOutOfBlocks(double x, double y, double z) { BlockPos blockpos = new BlockPos(x, y, z); double d0 = x - (double)blockpos.getX(); double d1 = y - (double)blockpos.getY(); double d2 = z - (double)blockpos.getZ(); List<AxisAlignedBB> list = this.worldObj.func_147461_a(this.getEntityBoundingBox()); if (list.isEmpty() && !this.worldObj.isBlockFullCube(blockpos)) { return false; } int i = 3; double d3 = 9999.0; if (!this.worldObj.isBlockFullCube(blockpos.west()) && d0 < d3) { d3 = d0; i = 0; } if (!this.worldObj.isBlockFullCube(blockpos.east()) && 1.0 - d0 < d3) { d3 = 1.0 - d0; i = 1; } if (!this.worldObj.isBlockFullCube(blockpos.up()) && 1.0 - d1 < d3) { d3 = 1.0 - d1; i = 3; } if (!this.worldObj.isBlockFullCube(blockpos.north()) && d2 < d3) { d3 = d2; i = 4; } if (!this.worldObj.isBlockFullCube(blockpos.south()) && 1.0 - d2 < d3) { d3 = 1.0 - d2; i = 5; } float f = this.rand.nextFloat() * 0.2f + 0.1f; if (i == 0) { this.motionX = -f; } if (i == 1) { this.motionX = f; } if (i == 3) { this.motionY = f; } if (i == 4) { this.motionZ = -f; } if (i == 5) { this.motionZ = f; } return true; } public void setInWeb() { this.isInWeb = true; this.fallDistance = 0.0f; } @Override public String getCommandSenderName() { if (this.hasCustomName()) { return this.getCustomNameTag(); } String s = EntityList.getEntityString(this); if (s == null) { s = "generic"; } return StatCollector.translateToLocal("entity." + s + ".name"); } public Entity[] getParts() { return null; } public boolean isEntityEqual(Entity entityIn) { return this == entityIn; } public float getRotationYawHead() { return 0.0f; } public void setRotationYawHead(float rotation) { } public void func_181013_g(float p_181013_1_) { } public boolean canAttackWithItem() { return true; } public boolean hitByEntity(Entity entityIn) { return false; } public String toString() { return String.format("%s['%s'/%d, l='%s', x=%.2f, y=%.2f, z=%.2f]", this.getClass().getSimpleName(), this.getCommandSenderName(), this.entityId, this.worldObj == null ? "~NULL~" : this.worldObj.getWorldInfo().getWorldName(), this.posX, this.posY, this.posZ); } public boolean isEntityInvulnerable(DamageSource source) { return this.invulnerable && source != DamageSource.outOfWorld && !source.isCreativePlayer(); } public void copyLocationAndAnglesFrom(Entity entityIn) { this.setLocationAndAngles(entityIn.posX, entityIn.posY, entityIn.posZ, entityIn.rotationYaw, entityIn.rotationPitch); } public void copyDataFromOld(Entity entityIn) { NBTTagCompound nbttagcompound = new NBTTagCompound(); entityIn.writeToNBT(nbttagcompound); this.readFromNBT(nbttagcompound); this.timeUntilPortal = entityIn.timeUntilPortal; this.field_181016_an = entityIn.field_181016_an; this.field_181017_ao = entityIn.field_181017_ao; this.field_181018_ap = entityIn.field_181018_ap; } public void travelToDimension(int dimensionId) { if (!this.worldObj.isRemote && !this.isDead) { this.worldObj.theProfiler.startSection("changeDimension"); MinecraftServer minecraftserver = MinecraftServer.getServer(); int i = this.dimension; WorldServer worldserver = minecraftserver.worldServerForDimension(i); WorldServer worldserver1 = minecraftserver.worldServerForDimension(dimensionId); this.dimension = dimensionId; if (i == 1 && dimensionId == 1) { worldserver1 = minecraftserver.worldServerForDimension(0); this.dimension = 0; } this.worldObj.removeEntity(this); this.isDead = false; this.worldObj.theProfiler.startSection("reposition"); minecraftserver.getConfigurationManager().transferEntityToWorld(this, i, worldserver, worldserver1); this.worldObj.theProfiler.endStartSection("reloading"); Entity entity = EntityList.createEntityByName(EntityList.getEntityString(this), worldserver1); if (entity != null) { entity.copyDataFromOld(this); if (i == 1 && dimensionId == 1) { BlockPos blockpos = this.worldObj.getTopSolidOrLiquidBlock(worldserver1.getSpawnPoint()); entity.moveToBlockPosAndAngles(blockpos, entity.rotationYaw, entity.rotationPitch); } worldserver1.spawnEntityInWorld(entity); } this.isDead = true; this.worldObj.theProfiler.endSection(); worldserver.resetUpdateEntityTick(); worldserver1.resetUpdateEntityTick(); this.worldObj.theProfiler.endSection(); } } public float getExplosionResistance(Explosion explosionIn, World worldIn, BlockPos pos, IBlockState blockStateIn) { return blockStateIn.getBlock().getExplosionResistance(this); } public boolean verifyExplosion(Explosion explosionIn, World worldIn, BlockPos pos, IBlockState blockStateIn, float p_174816_5_) { return true; } public int getMaxFallHeight() { return 3; } public Vec3 func_181014_aG() { return this.field_181017_ao; } public EnumFacing func_181012_aH() { return this.field_181018_ap; } public boolean doesEntityNotTriggerPressurePlate() { return false; } public void addEntityCrashInfo(CrashReportCategory category) { category.addCrashSectionCallable("Entity Type", new Callable<String>(){ @Override public String call() throws Exception { return EntityList.getEntityString(Entity.this) + " (" + Entity.this.getClass().getCanonicalName() + ")"; } }); category.addCrashSection("Entity ID", this.entityId); category.addCrashSectionCallable("Entity Name", new Callable<String>(){ @Override public String call() throws Exception { return Entity.this.getCommandSenderName(); } }); category.addCrashSection("Entity's Exact location", String.format("%.2f, %.2f, %.2f", this.posX, this.posY, this.posZ)); category.addCrashSection("Entity's Block location", CrashReportCategory.getCoordinateInfo(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.posY), MathHelper.floor_double(this.posZ))); category.addCrashSection("Entity's Momentum", String.format("%.2f, %.2f, %.2f", this.motionX, this.motionY, this.motionZ)); category.addCrashSectionCallable("Entity's Rider", new Callable<String>(){ @Override public String call() throws Exception { return Entity.this.riddenByEntity.toString(); } }); category.addCrashSectionCallable("Entity's Vehicle", new Callable<String>(){ @Override public String call() throws Exception { return Entity.this.ridingEntity.toString(); } }); } public boolean canRenderOnFire() { return this.isBurning(); } public UUID getUniqueID() { return this.entityUniqueID; } public boolean isPushedByWater() { return true; } @Override public IChatComponent getDisplayName() { ChatComponentText chatcomponenttext = new ChatComponentText(this.getCommandSenderName()); chatcomponenttext.getChatStyle().setChatHoverEvent(this.getHoverEvent()); chatcomponenttext.getChatStyle().setInsertion(this.getUniqueID().toString()); return chatcomponenttext; } public void setCustomNameTag(String name) { this.dataWatcher.updateObject(2, name); } public String getCustomNameTag() { return this.dataWatcher.getWatchableObjectString(2); } public boolean hasCustomName() { return this.dataWatcher.getWatchableObjectString(2).length() > 0; } public void setAlwaysRenderNameTag(boolean alwaysRenderNameTag) { this.dataWatcher.updateObject(3, (byte)(alwaysRenderNameTag ? (char)'\u0001' : '\u0000')); } public boolean getAlwaysRenderNameTag() { return this.dataWatcher.getWatchableObjectByte(3) == 1; } public void setPositionAndUpdate(double x, double y, double z) { this.setLocationAndAngles(x, y, z, this.rotationYaw, this.rotationPitch); } public boolean getAlwaysRenderNameTagForRender() { return this.getAlwaysRenderNameTag(); } public void onDataWatcherUpdate(int dataID) { } public EnumFacing getHorizontalFacing() { return EnumFacing.getHorizontal(MathHelper.floor_double((double)(this.rotationYaw * 4.0f / 360.0f) + 0.5) & 3); } protected HoverEvent getHoverEvent() { NBTTagCompound nbttagcompound = new NBTTagCompound(); String s = EntityList.getEntityString(this); nbttagcompound.setString("id", this.getUniqueID().toString()); if (s != null) { nbttagcompound.setString("type", s); } nbttagcompound.setString("name", this.getCommandSenderName()); return new HoverEvent(HoverEvent.Action.SHOW_ENTITY, new ChatComponentText(nbttagcompound.toString())); } public boolean isSpectatedByPlayer(EntityPlayerMP player) { return true; } public AxisAlignedBB getEntityBoundingBox() { return this.boundingBox; } public void setEntityBoundingBox(AxisAlignedBB bb) { this.boundingBox = bb; } public float getEyeHeight() { return this.height * 0.85f; } public boolean isOutsideBorder() { return this.isOutsideBorder; } public void setOutsideBorder(boolean outsideBorder) { this.isOutsideBorder = outsideBorder; } public boolean replaceItemInInventory(int inventorySlot, ItemStack itemStackIn) { return false; } @Override public void addChatMessage(IChatComponent component) { } @Override public boolean canCommandSenderUseCommand(int permLevel, String commandName) { return true; } @Override public BlockPos getPosition() { return new BlockPos(this.posX, this.posY + 0.5, this.posZ); } @Override public Vec3 getPositionVector() { return new Vec3(this.posX, this.posY, this.posZ); } @Override public World getEntityWorld() { return this.worldObj; } @Override public Entity getCommandSenderEntity() { return this; } @Override public boolean sendCommandFeedback() { return false; } @Override public void setCommandStat(CommandResultStats.Type type, int amount) { this.cmdResultStats.func_179672_a(this, type, amount); } public CommandResultStats getCommandStats() { return this.cmdResultStats; } public void func_174817_o(Entity entityIn) { this.cmdResultStats.func_179671_a(entityIn.getCommandStats()); } public NBTTagCompound getNBTTagCompound() { return null; } public void clientUpdateEntityNBT(NBTTagCompound compound) { } public boolean interactAt(EntityPlayer player, Vec3 targetVec3) { return false; } public boolean isImmuneToExplosions() { return false; } protected void applyEnchantments(EntityLivingBase entityLivingBaseIn, Entity entityIn) { if (entityIn instanceof EntityLivingBase) { EnchantmentHelper.applyThornEnchantments((EntityLivingBase)entityIn, entityLivingBaseIn); } EnchantmentHelper.applyArthropodEnchantments(entityLivingBaseIn, entityIn); } }
412
0.915813
1
0.915813
game-dev
MEDIA
0.985891
game-dev
0.950352
1
0.950352
krystalgamer/spidey-decomp
15,211
rhino.cpp
#include "rhino.h" #include "validate.h" #include "utils.h" #include "panel.h" #include "ps2pad.h" #include "spidey.h" #include "ps2lowsfx.h" #include "ps2redbook.h" #include "camera.h" #include "ai.h" #include "my_assert.h" EXPORT i32 gRhinoStrangeInitData[2] = { 0x201, 0 }; EXPORT SLight M3d_RhinoLight = { { { -2430, -2228, -2430 }, { 2509, -2896, 1447 }, { -648, -3711, -1607 } }, 0, { { 4800, 1560, 3072 }, { 4080, 2400, 2880 }, { 3600, 3840, 3072 } }, 0, { 1800, 1800, 1440 } }; // @FIXME #define LEN_RHINO_DATA 0x17 EXPORT SRhinoData gRhinoData[LEN_RHINO_DATA]; #define LEN_RHINO_DAZED_DATA 0x5 EXPORT i16 gRhinoDazedData[LEN_RHINO_DAZED_DATA]; EXPORT u32 gRhinoSound; extern i32 DifficultyLevel; u8 gActuatorRelated; extern CBody* EnvironmentalObjectList; extern CPlayer* MechList; extern i32 gAttackRelated; extern CBaddy *BaddyList; extern CCamera *CameraList; // @Ok // @Matching void Rhino_RelocatableModuleInit(reloc_mod *pMod) { pMod->mClearFunc = Rhino_RelocatableModuleClear; pMod->field_C[0] = Rhino_CreateRhino; } // @MEDIUMTODO void CRhino::AI(void) { printf("CRhino::AI(void)"); } // @MEDIUMTODO void CRhino::AttackPlayer(void) { printf("CRhino::AttackPlayer(void)"); } // @MEDIUMTODO void CRhino::ChargePlayer(void) { printf("CRhino::ChargePlayer(void)"); } // @MEDIUMTODO void CRhino::ChasePlayer(i32) { printf("CRhino::ChasePlayer(i32)"); } // @NotOk // @Validate INLINE i32 CRhino::CheckIfPlayerHit(void) { i32 v4; if (this->field_288 & 0x10) { this->field_288 &= 0xFFFFFFEF; v4 = 1; } else { v4 = 0; } if (v4) { SHitInfo v9; v9.field_0 = 14; v9.field_4 = 11; v9.field_C = MechList->mPos - this->mPos; this->field_344 = gAttackRelated; v9.field_8 = 15; if (MechList->Hit(&v9)) { return 1; } } return 0; } // @MEDIUMTODO void CRhino::DieRhino(void) { printf("CRhino::DieRhino(void)"); } // @MEDIUMTODO void CRhino::DoDazedEffect(void) { printf("CRhino::DoDazedEffect(void)"); } // @MEDIUMTODO void CRhino::DoMGSShadow(void) { printf("CRhino::DoMGSShadow(void)"); } // @Ok // would love to remove the goto void CRhino::FollowWaypoints(void) { i32 v6; SMoveToInfo v8; v8.field_0.vx = 0; v8.field_0.vy = 0; v8.field_0.vz = 0; this->RunAppropriateAnim(); switch (this->dumbAssPad) { case 0: this->Neutralize(); this->field_310 = 0; if (this->field_1F0) { this->field_2A8 &= ~0x10000000; v8.field_0 = this->field_1A8[this->field_1F0]; v8.field_C = 40; v8.field_10 = 40; v8.field_14 = 500; new CAIProc_MoveTo(this, &v8, 1); this->dumbAssPad++; } else { this->field_31C.bothFlags = 2; this->dumbAssPad = 0; } break; case 1: if (this->field_288 & 1) { this->field_288 &= ~1; v6 = 1; } else { v6 = 0; } if (v6) { if (this->field_1F0) { this->field_1F0--; // @FIXME this makes it match but i don't like it goto force_match; } else if (this->GetNextWaypoint()) { force_match: if ((this->field_2F0 & 2) == 0) { this->dumbAssPad = 0; } } else { this->field_31C.bothFlags = 2; this->dumbAssPad = 0; } } break; default: print_if_false(0, "Unknown substate!"); break; } } // @Ok void CRhino::GetLaunched(void) { switch (this->dumbAssPad) { case 0: this->dumbAssPad = 1; this->PlaySingleAnim(15, 0, -1); new CAIProc_LookAt(this, MechList, 0, 2, 80, 0); this->field_230 = Utils_GetValueFromDifficultyLevel(40, 30, 21, 21); case 1: this->DoPhysics(1); this->RunTimer(&this->field_230); if (!this->field_1F8) { this->dumbAssPad++; this->mVel.vx = 0; this->mVel.vy = 0; this->mVel.vz = 0; } break; case 2: this->RunTimer(&this->field_230); if (!this->field_230) { if (this->DetermineFightState(1)) { if (this->DistanceToPlayer(0) > 500) { if (this->field_31C.bothFlags == 5 || this->field_31C.bothFlags == 4) { this->field_31C.bothFlags = 8; this->dumbAssPad = 0; } } else if (this->field_31C.bothFlags == 8) { this->field_31C.bothFlags = 5; this->dumbAssPad = 0; } } else { this->PlaySingleAnim(0, 0, -1); this->field_31C.bothFlags = 22; this->dumbAssPad = 0; } } break; default: print_if_false(0, "Unknown substate"); break; } } // @MEDIUMTODO void CRhino::GetShocked(void) { printf("CRhino::GetShocked(void)"); } // @MEDIUMTODO void CRhino::GetTrapped(void) { printf("CRhino::GetTrapped(void)"); } // @MEDIUMTODO void CRhino::GonnaHitWall(i32) { printf("CRhino::GonnaHitWall(i32)"); } // @MEDIUMTODO void CRhino::LineOfSightCheck(CVector const *,i32) { printf("CRhino::LineOfSightCheck(CVector const *,i32)"); } // @MEDIUMTODO void CRhino::PlaySounds(void) { printf("CRhino::PlaySounds(void)"); } // @Ok // @AlmostMatching: slightly diff code gen void CRhino::PlayXAPlease( i32 a2, i32 a3, i32 a4) { i32 v5 = Rnd(a3 + a4); i32 v6 = this->field_3DC; if (v5 < a3) { if (a3 > 1) { if ( ((v6 >> a2) & (1 << v5)) != 0 && ++v5 >= a3 ) { v5 = 0; } for (i32 i = 0; i < a3; i++) { v6 &= ~(1 << (i + a2)); } v6 |= 1 << (v5 + a2); } i32 v8 = a2 + v5; if ( gRhinoData[v8].field_4 ) { if (Redbook_XAPlayPos( gRhinoData[v8].field_0, gRhinoData[v8].field_2, &this->mPos, gRhinoData[v8].field_6) ) { this->AttachXA(gRhinoData[v8].field_0, gRhinoData[v8].field_2); this->field_3DC = v6; } } else if (MechList->CanITalkRightNow() && Redbook_XAPlayPos( gRhinoData[v8].field_0, gRhinoData[v8].field_2, &MechList->mPos, gRhinoData[v8].field_6) ) { MechList->AttachXA(gRhinoData[v8].field_0, gRhinoData[v8].field_2); this->field_3DC = v6; } } } // @MEDIUMTODO void CRhino::SetUpStuckHorn(SLineInfo *,i32) { printf("CRhino::SetUpStuckHorn(SLineInfo *,i32)"); } // @MEDIUMTODO void CRhino::SlideFromHit(i32,i32,CVector *) { printf("CRhino::SlideFromHit(i32,i32,CVector *)"); } // @MEDIUMTODO void CRhino::StompGround(void) { printf("CRhino::StompGround(void)"); } // @MEDIUMTODO void CRhino::StuckInWall(void) { printf("CRhino::StuckInWall(void)"); } // @Ok CRhinoNasalSteam::~CRhinoNasalSteam(void) { } // @Ok // @Matching void Rhino_RelocatableModuleClear(void) { CItem *pSearch = BaddyList; while (pSearch) { CItem *pNext = pSearch->mNextItem; if (pSearch->mType == 307) delete pSearch; pSearch = pNext; } } // @MEDIUMTODO i32 CRhino::DetermineFightState(i32) { printf("i32 CRhino::DetermineFightState(i32)"); return 0x28072024; } // @Ok void CRhino::TakeHit(void) { switch (this->dumbAssPad) { case 0: this->field_310 = 0; new CAIProc_LookAt(this, MechList, 0, 0, 80, 200); this->PlaySingleAnim(0xFu, 0, -1); this->field_230 = Utils_GetValueFromDifficultyLevel(40, 30, 21, 21); this->dumbAssPad++; break; case 1: this->RunTimer(&this->field_230); if (!this->field_230) { if (this->DetermineFightState(1)) { if (this->DistanceToPlayer(0) > 500) { if (this->field_31C.bothFlags == 5 || this->field_31C.bothFlags == 4) { this->field_31C.bothFlags = 8; this->dumbAssPad = 0; } } else if (this->field_31C.bothFlags == 8) { this->field_31C.bothFlags = 5; this->dumbAssPad = 0; } } else { this->PlaySingleAnim(0, 0, -1); this->field_31C.bothFlags = 22; this->dumbAssPad = 0; } } break; default: print_if_false(0, "Unknown substate!"); break; } } // @Ok void CRhino::HitWall(void) { switch (this->dumbAssPad) { case 0: this->ShakePad(); CameraList->Shake(this->mPos, CAMERASHAKE_BIG); this->Neutralize(); this->mCBodyFlags &= ~0x10; this->PlaySingleAnim(17, 0, -1); this->dumbAssPad++; break; case 1: if (this->mAnimFinished) { if ( this->mHealth <= 0 ) { this->field_31C.bothFlags = 21; this->dumbAssPad = 0; } else { this->PlaySingleAnim(0x12u, 0, -1); } } break; case 2: if ( this->mAnimFinished ) { if ( this->mAnim == 18 ) { this->mAngles.vy = (this->mAngles.vy - 2048) & 0xFFF; this->PlaySingleAnim(0x15u, 0, -1); } else { this->mCBodyFlags |= 0x10u; this->PlaySingleAnim(0, 0, -1); this->field_31C.bothFlags = 2; this->dumbAssPad = 0; } } break; default: print_if_false(0, "Unknown substate!"); break; } } // @NotOk // figure out types of fields that call destructors CRhino::~CRhino(void) { this->DeleteFrom(reinterpret_cast<CBody**>(&BaddyList)); Panel_DestroyHealthBar(); if (this->field_3E0) delete reinterpret_cast<CItem*>(this->field_3E0); for (i32 i = 0; i < 5; i++) { if (this->field_3E4[i]) delete reinterpret_cast<CItem*>(this->field_3E4[i]); this->field_3E4[i] = 0; if (this->field_3F8[i]) delete reinterpret_cast<CItem*>(this->field_3F8[i]); this->field_3F8[i] = 0; if (this->field_40C[i]) delete reinterpret_cast<CItem*>(this->field_40C[i]); this->field_40C[i] = 0; } gBossRelated = 0; } // @Ok void CRhino::Laugh(void) { switch (this->dumbAssPad) { case 0: this->field_230 = 100; this->PlaySingleAnim(20, 0, -1); SFX_PlayPos(((gAttackRelated & 1) == 0 ? 1 : 0) | 0x8046, &this->mPos, 0); this->dumbAssPad++; break; case 1: this->RunTimer(&this->field_230); if (this->mAnimFinished) { if (!this->field_230) { this->field_31C.bothFlags = 2; this->dumbAssPad = 0; } else { this->PlaySingleAnim(0, 0, -1); } } break; default: print_if_false(0, "Unknown substate."); break; } } // @Ok void CRhino::RhinoInit(void) { switch (this->dumbAssPad) { case 0: this->field_358 = gAttackRelated - 155; i32 GroundHeight; GroundHeight = Utils_GetGroundHeight(&this->mPos, 300, 300, 0); if ( GroundHeight != -1 ) { this->mPos.vy = GroundHeight - (this->field_21E << 12); this->field_29C = this->mPos.vy; this->field_2A0 = GroundHeight; this->dumbAssPad++; this->PlaySingleAnim(0, 0, -1); } break; case 1: this->field_31C.bothFlags = 8; this->dumbAssPad = 0; break; default: print_if_false(0, "Unknown sub-state!"); break; } } // @NotOk // understand if that's really PlayerIsVisible call void CRhino::FuckUpSomeBarrels(void) { i32 barrels = 0; for ( CBody* cur = EnvironmentalObjectList; cur && barrels < 2; cur = reinterpret_cast<CBody*>(cur->mNextItem)) { if (cur->mType == 401) { if (Utils_CrapDist(this->mPos, cur->mPos) < 0x2BC && cur != MechList->mHeldObject) { reinterpret_cast<CBaddy*>(cur)->PlayerIsVisible(); barrels++; } } } } // @Ok void CRhino::StandStill(void) { switch (this->dumbAssPad) { case 0: this->Neutralize(); this->dumbAssPad++; case 1: if (this->mAnim) this->PlaySingleAnim(0, 0, -1); break; default: print_if_false(0, "Unknown substate."); break; } } // @Ok INLINE void CRhino::ShakePad(void) { if ( gActuatorRelated ) { if ( Pad_GetActuatorTime(0, 0) <= 2u ) Pad_ActuatorOn(0, 6u, 0, 1u); if ( Pad_GetActuatorTime(0, 1u) <= 2u ) Pad_ActuatorOn(0, 0xAu, 1, 0xC8u); } } // @NotOk // validate when get shocked i32 CRhino::GetShockDamage(void) { switch ( DifficultyLevel ) { case 0: case 1: return 175; case 2: return 125; case 3: return 75; default: print_if_false(0, "Unknown difficulty level!"); return 0; } } // @NotOk // validate when playsounds is done u32 CRhino::GetNextFootstepSFX(void) { u32 res; for (res = (Rnd(3) + 76) | 0x8000; res == gRhinoSound; res = (Rnd(3) + 76) | 0x8000) ; return res; } // @Ok INLINE void CRhino::PlaySingleAnim(u32 a2, i32 a3, i32 a4) { this->field_388 = 0; this->RunAnim(a2, a3, a4); } // @NotOk // globals CRhino::CRhino(i16* a2, i32 a3) { i16 *v5 = this->SquirtAngles(reinterpret_cast<i16*>(this->SquirtPos(a2))); this->InitItem("rhino"); this->mFlags |= 0x480; // @FIXME this->mpLight = &M3d_RhinoLight; this->AttachTo(reinterpret_cast<CBody**>(&BaddyList)); this->field_21E = 100; this->field_1F4 = a3; this->mNode = a3; this->mRMinor = 175; this->field_230 = 0; this->field_216 = 32; this->mPushVal = 64; this->field_31C.bothFlags = 0; this->field_2A8 |= 1; this->field_2A8 |= 0x200; this->field_2A8 |= 0x2000000; this->mType = 307; this->mHealth = Utils_GetValueFromDifficultyLevel(1400, 1400, 1400, 1400); this->field_294.Int = gRhinoStrangeInitData[0]; this->field_298.Int = gRhinoStrangeInitData[1]; this->field_344 = gAttackRelated - 240; for (i32 i = 0; i < LEN_RHINO_DAZED_DATA; i++) { gRhinoDazedData[i] = Rnd(4096); } for (i32 j = 0; j < LEN_RHINO_DATA; j++) { if (gRhinoData[j].field_8 != j) DoAssert(0, "Fire Matt, he fucked up the rhino XA. Actually, kick him in the nuts first."); } this->ParseScript(reinterpret_cast<u16*>(v5)); Panel_CreateHealthBar(this, 307); } // @NotOk // globals CRhino::CRhino(void) { this->InitItem("rhino"); this->mFlags |= 0x480; // @FIXME this->mpLight = &M3d_RhinoLight; this->mType = 307; } // @Ok void Rhino_CreateRhino(const u32 *stack, u32 *result) { i16* v2 = reinterpret_cast<i16*>(*stack); i32 v3 = static_cast<i32>(stack[1]); if (v2) { *result = reinterpret_cast<u32>(new CRhino(v2, v3)); } else { *result = reinterpret_cast<u32>(new CRhino()); } } // @Ok CRhinoNasalSteam::CRhinoNasalSteam(CVector* a2, CVector* a3) { this->mPos = *a2; this->mVel = *a3; this->SetAnim(1); this->SetSemiTransparent(); this->SetTransparency(64); this->SetAnimSpeed(128); this->SetScale(128); this->mAngle = Rnd(4096); } // @Ok // minor decomp diff void CRhinoNasalSteam::Move(void) { i16 mAnimSpeed = this->mAnimSpeed; if (mAnimSpeed) { u16 v3 = (this->mFrame << 8) | this->mFrameFrac; u16 v4 = mAnimSpeed + v3; this->mFrameFrac = v4; v4 >>= 8; this->mFrame = v4; if ( (char)v4 >= (i32)this->mNumFrames) { this->mAnimSpeed = 0; this->mFrame = this->mNumFrames - 1; } i32 index = this->mFrame; this->mpPSXFrame = &this->mpPSXAnim[index]; } this->mPos += this->mVel; bool v7 = ++this->mAge <= 30; this->mVel.vy -= 1024; if (!v7 ) { this->Die(); } else { this->SetTransparency(64 - 2 * (this->mAge & 0xFF)); this->SetScale(Rnd(4) + 4 * (this->mAge + 32)); } } void validate_CRhino(void){ VALIDATE_SIZE(CRhino, 0x424); VALIDATE(CRhino, field_344, 0x344); VALIDATE(CRhino, field_358, 0x358); VALIDATE(CRhino, field_388, 0x388); VALIDATE(CRhino, field_3DC, 0x3DC); VALIDATE(CRhino, field_3E0, 0x3E0); VALIDATE(CRhino, field_3E4, 0x3E4); VALIDATE(CRhino, field_3F8, 0x3F8); VALIDATE(CRhino, field_40C, 0x40C); } void validate_CRhinoNasalSteam(void) { VALIDATE_SIZE(CRhinoNasalSteam, 0x68); } void validate_SRhinoData(void) { VALIDATE_SIZE(SRhinoData, 0xC); VALIDATE(SRhinoData, field_0, 0x0); VALIDATE(SRhinoData, field_2, 0x2); VALIDATE(SRhinoData, field_4, 0x4); VALIDATE(SRhinoData, field_6, 0x6); VALIDATE(SRhinoData, field_8, 0x8); }
412
0.920617
1
0.920617
game-dev
MEDIA
0.814814
game-dev
0.735589
1
0.735589
maksimKorzh/chess_programming
9,323
didactic_engines/Wuttang/position.cpp
#include <iostream> #include "position.h" #include "hashKey.h" void Position::resetBoard() { for (int i = 0; i < sq_no; ++i) { pieces[i] = OFFBOARD; } for (int sq = 0; sq < 64; ++sq) { pieces[sq120(sq)] = EMPTY; } for (int i = white; i < both; ++i) { bigPce[i] = 0; majPce[i] = 0; minPce[i] = 0; material[i] = 0; kingSq[i] = NO_SQ; } for (int i = white; i <= both; ++i) { pawns[i] = 0ull; } for (int i = wP; i <= bK; ++i) { pceNum[i] = 0; } side = both; enPass_sq = NO_SQ; fifty_move = 0; ply = hisPly = 0; castleRights = NO_CASTLING; posKey = 0ULL; } void Position::updateListMaterial() { int piece, color; for (int sq = 0; sq < sq_no; ++sq) { piece = pieces[sq]; if (piece != OFFBOARD && piece != EMPTY) { color = pceCol[piece]; if (pceBig[piece]) { ++bigPce[color]; if (pceMaj[piece]) ++majPce[color]; else ++minPce[color]; } material[color] += pceVal[piece]; pList[piece][pceNum[piece]] = sq; ++pceNum[piece]; if (piece == wK) { kingSq[white] = sq; } else if (piece == bK) { kingSq[black] = sq; } else if (piece == wP) { SETBIT(pawns[white], sq64(sq)); SETBIT(pawns[both], sq64(sq)); } else if (piece == bP) { SETBIT(pawns[black], sq64(sq)); SETBIT(pawns[both], sq64(sq)); } } } } void Position::parseFEN(const std::string fenStr) { const char *fen = &(fenStr[0]); assert(fen != nullptr); int rank = rank_8, file = file_A, cnt = 1, piece = EMPTY; resetBoard(); while (rank >= rank_1) { cnt = 1; switch(*fen) { case 'r' : piece = bR; break; case 'n' : piece = bN; break; case 'b' : piece = bB; break; case 'q' : piece = bQ; break; case 'k' : piece = bK; break; case 'p' : piece = bP; break; case 'R' : piece = wR; break; case 'N' : piece = wN; break; case 'B' : piece = wB; break; case 'Q' : piece = wQ; break; case 'K' : piece = wK; break; case 'P' : piece = wP; break; case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : piece = EMPTY; cnt = *fen - '0'; break; case ' ' : case '/' : rank--; file = file_A; ++fen; continue; default : std::cout << "FEN error\n"; return; } while (cnt > 0) { if (piece != EMPTY) pieces[fr2sq(file, rank)] = piece; ++file; --cnt; } ++fen; } assert(*fen == 'w' || *fen == 'b'); side = (*fen == 'w' ? white : black); fen += 2; for (int i = 0; i < 4; ++i) { if (*fen == ' ') { break; } switch (*fen) { case 'K' : castleRights |= WKCA; break; case 'Q' : castleRights |= WQCA; break; case 'k' : castleRights |= BKCA; break; case 'q' : castleRights |= BQCA; break; default : break; } ++fen; } ++fen; assert (castleRights >= 0 && castleRights < 16); if (*fen != '-') { file = fen[0] - 'a'; rank = fen[1] - '1'; assert(file >= file_A && file <= file_H); assert(rank >= rank_1 && rank <= rank_8); enPass_sq = fr2sq(file, rank); } posKey = generatePosKey(*this); updateListMaterial(); } void Position::display() const { int sq; std::cout << "\n\n"; for (int rank = rank_8; rank >= rank_1; --rank) { std::cout << ' ' << rank+1 << " "; for (int file = file_A; file <= file_H; ++file) { sq = fr2sq(file, rank); std::cout << pceChar[pieces[sq]] << " "; } std::cout << "\n\n"; } std::cout << " a b c d e f g h\n\n"; std::cout << "Side : " << sideChar[side] << '\n' << "EnPassSq : " << enPass_sq << '\n' << "CastleRights : " << (castleRights & WKCA ? 'K' : '-') << (castleRights & WQCA ? 'Q' : '-') << (castleRights & BKCA ? 'k' : '-') << (castleRights & BQCA ? 'q' : '-') << '\n' << "PosKey : " << std::hex << posKey << '\n' << std::dec; } bool Position::checkBoard() const { int t_pceNum[13] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int t_bigPce[2] = {0, 0}; int t_majPce[2] = {0, 0}; int t_minPce[2] = {0, 0}; int t_material[2] = {0, 0}; BitBoard t_pawns[3] = {0ull, 0ull, 0ull}; t_pawns[white] = pawns[white]; t_pawns[black] = pawns[black]; t_pawns[both] = pawns[both]; //Check piece list for (int piece = wP; piece <= bK; ++piece) { for (int num = 0; num < pceNum[piece]; ++num) { assert(pieces[pList[piece][num]] == piece); } } //Check piece count and other parameters int piece, color; for (int sq64 = 0; sq64 < 64; ++sq64) { piece = pieces[sq120(sq64)]; color = pceCol[piece]; ++t_pceNum[piece]; if (pceBig[piece]) { ++t_bigPce[color]; if (pceMaj[piece]) { ++t_majPce[color]; } else { ++t_minPce[color]; } } t_material[color] += pceVal[piece]; } for (piece = wP; piece <= bK; ++piece) { assert(t_pceNum[piece] == pceNum[piece]); } //Check BitBoard count int cnt = countBits(t_pawns[white]); assert(cnt == pceNum[wP]); cnt = countBits(t_pawns[black]); assert(cnt == pceNum[bP]); cnt = countBits(t_pawns[both]); assert(cnt == (pceNum[wP]+pceNum[bP])); //Check BitBoards square int sq_64; while (t_pawns[white]) { sq_64 = popBit(t_pawns[white]); assert(pieces[sq120(sq_64)] == wP); } while (t_pawns[black]) { sq_64 = popBit(t_pawns[black]); assert(pieces[sq120(sq_64)] == bP); } while (t_pawns[both]) { sq_64 = popBit(t_pawns[both]); assert(pieces[sq120(sq_64)] == wP || pieces[sq120(sq_64)] == bP); } assert(t_material[white] == material[white] && t_material[black] == material[black]); assert(t_majPce[white] == majPce[white] && t_majPce[black] == majPce[black]); assert(t_minPce[white] == minPce[white] && t_minPce[black] == minPce[black]); assert(t_bigPce[white] == bigPce[white] && t_bigPce[black] == bigPce[black]); assert(side == white || side == black); assert(generatePosKey(*this) == posKey); assert(enPass_sq == NO_SQ || (rankSq(enPass_sq) == rank_6 && side == white) || (rankSq(enPass_sq) == rank_3 && side == black)); assert(pieces[kingSq[white]] == wK); assert(pieces[kingSq[black]] == bK); return true; } bool Position::isSqAttacked(const int sq, const int side) const { assert(SqOnBoard(sq)); assert(SideValid(side)); assert(checkBoard()); //pawns if (side == white) { if (pieces[sq-11] == wP || pieces[sq-9] == wP) return true; } else { if (pieces[sq+11] == bP || pieces[sq+9] == bP) return true; } //knights int piece; for (int i = 0; i < 8; ++i) { piece = pieces[sq+KnDir[i]]; if (piece != OFFBOARD && IsKn(piece) && pceCol[piece] == side) { return true; } } //rooks, queens int dir, t_sq; for (int i = 0; i < 4; ++i) { dir = RkDir[i]; t_sq = sq+dir; piece = pieces[t_sq]; while (piece != OFFBOARD) { if (piece != EMPTY) { if (IsRQ(piece) && pceCol[piece] == side) { return true; } break; } t_sq += dir; piece = pieces[t_sq]; } } //bishops, queens for (int i = 0; i < 4; ++i) { dir = BiDir[i]; t_sq = sq + dir; piece = pieces[t_sq]; while (piece != OFFBOARD) { if (piece != EMPTY) { if (IsBQ(piece) && pceCol[piece] == side) { return true; } break; } t_sq += dir; piece = pieces[t_sq]; } } //kings for (int i = 0; i < 8; ++i) { piece = pieces[sq+KiDir[i]]; if (piece != OFFBOARD && IsKi(piece) && pceCol[piece] == side) { return true; } } return false; }
412
0.976962
1
0.976962
game-dev
MEDIA
0.862898
game-dev
0.989752
1
0.989752
gomint/gomint
2,173
gomint-server/src/main/java/io/gomint/server/crafting/SmeltingRecipe.java
/* * Copyright (c) 2020, GoMint, BlackyPaw and geNAZt * * This code is licensed under the BSD license found in the * LICENSE file in the root directory of this source tree. */ package io.gomint.server.crafting; import io.gomint.inventory.item.ItemStack; import io.gomint.jraknet.PacketBuffer; import io.gomint.server.inventory.Inventory; import io.gomint.server.network.packet.Packet; import java.util.Collection; import java.util.Collections; import java.util.UUID; /** * Resembles a smelting recipe which may be used in conjunction with furnaces. * * @author BlackyPaw * @version 1.0 */ public class SmeltingRecipe extends Recipe { private final String block; private final ItemStack<?> input; private final ItemStack<?> outcome; /** * Create new smelting recipe * * @param input for this recipe * @param outcome of this recipe * @param uuid of the recipe */ public SmeltingRecipe(String block, ItemStack<?> input, ItemStack<?> outcome, UUID uuid, int priority) { super(uuid, priority); this.block = block; this.input = input; this.outcome = outcome; } @Override public ItemStack<?>[] ingredients() { return new ItemStack[]{this.input}; } @Override public Collection<ItemStack<?>> createResult() { return Collections.singletonList(((io.gomint.server.inventory.item.ItemStack<?>) this.outcome).clone()); } @Override public void serialize(PacketBuffer buffer) { io.gomint.server.inventory.item.ItemStack<?> implInput = (io.gomint.server.inventory.item.ItemStack<?>) this.input; // The type of this recipe is defined after the input metadata buffer.writeSignedVarInt(implInput.data() == 0 ? 2 : 3); // We need to custom write items buffer.writeSignedVarInt(implInput.runtimeID()); if (implInput.data() != 0) buffer.writeSignedVarInt(implInput.data()); Packet.writeItemStack(this.outcome, buffer); buffer.writeString(this.block); } @Override public int[] isCraftable(Inventory<?> inputInventory) { return new int[0]; } }
412
0.709258
1
0.709258
game-dev
MEDIA
0.840101
game-dev
0.804833
1
0.804833
Kein/Altar
1,086
Source/Altar/Public/VLevelStreaming.h
#pragma once #include "CoreMinimal.h" #include "UObject/NoExportTypes.h" #include "Engine/LevelStreamingDynamic.h" #include "VLevelStreaming.generated.h" class AActor; UCLASS(Blueprintable, EditInlineNew) class ALTAR_API UVLevelStreaming : public ULevelStreamingDynamic { GENERATED_BODY() public: UPROPERTY(EditAnywhere, meta=(AllowPrivateAccess=true)) TMap<uint32, AActor*> PawnActors; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FBox LevelBounds; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float ZKillDistUnderLevel; private: UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TArray<AActor*> ContainedActors; public: UVLevelStreaming(); UFUNCTION(BlueprintCallable) void OnInteriorLevelUnloaded(); UFUNCTION(BlueprintCallable) void OnInteriorLevelShown(); UFUNCTION(BlueprintCallable) void OnInteriorLevelLoaded(); UFUNCTION(BlueprintCallable) void OnInteriorLevelHidden(); };
412
0.855584
1
0.855584
game-dev
MEDIA
0.658271
game-dev
0.591224
1
0.591224
blendogames/thirtyflightsofloving
37,417
awaken2/g_utils.c
// g_utils.c -- misc utility functions for game module #include "g_local.h" void G_ProjectSource(vec3_t point, vec3_t distance, vec3_t forward, vec3_t right, vec3_t result) { result[0] = point[0] + forward[0] * distance[0] + right[0] * distance[1]; result[1] = point[1] + forward[1] * distance[0] + right[1] * distance[1]; result[2] = point[2] + forward[2] * distance[0] + right[2] * distance[1] + distance[2]; } /* ============= G_Find Searches all active entities for the next one that holds the matching string at fieldofs (use the FOFS() macro) in the structure. Searches beginning at the edict after from, or the beginning if NULL. NULL will be returned if the end of the list is reached. ============= */ edict_t *G_Find(edict_t *from, size_t fieldofs, char *match) // Knightmare- changed fieldofs from int { char *s; if (!from) from = g_edicts; else from++; for ( ; from < &g_edicts[globals.num_edicts]; from++) { if (!from->inuse) continue; s = *(char **) ((byte *)from + fieldofs); if (!s) continue; if (!Q_stricmp(s, match)) return from; } return NULL; } //CW++ /* ================= FindClientRadius Returns active client entities whose bounding boxes are within a spherical volume centred around the specified point. ================= */ edict_t *FindClientRadius(edict_t *from, vec3_t origin, float radius) { vec3_t ent_vec; int i; if (!from) from = g_edicts; else ++from; for ( ; from < &g_edicts[game.maxclients]; ++from) { if (!from->client) continue; if (!from->inuse) continue; if (from->solid == SOLID_NOT) continue; for (i = 0; i < 3; ++i) ent_vec[i] = origin[i] - (from->s.origin[i] + (from->mins[i] + from->maxs[i])*0.5); if (VectorLength(ent_vec) > radius) continue; return from; } return NULL; } /* ================= FindPointRadius Returns solid and non-solid entities whose origins are within a spherical volume centred around the specified point. ================= */ edict_t *FindPointRadius(edict_t *from, vec3_t org, float rad) { vec3_t eorg; int i; if (!from) from = g_edicts; else from++; for ( ; from < &g_edicts[globals.num_edicts]; ++from) { if (!from->inuse) continue; for (i = 0; i < 3; ++i) eorg[i] = org[i] - from->s.origin[i]; if (VectorLength(eorg) > rad) continue; return from; } return NULL; } //CW-- /* ================= FindRadius Returns solid entities whose bounding boxes are within a spherical volume centred around the specified point. ================= */ edict_t *FindRadius(edict_t *from, vec3_t org, float rad) { vec3_t eorg; int i; if (!from) from = g_edicts; else from++; for ( ; from < &g_edicts[globals.num_edicts]; from++) { if (!from->inuse) continue; if (from->solid == SOLID_NOT) continue; for (i = 0; i < 3; ++i) eorg[i] = org[i] - (from->s.origin[i] + (from->mins[i] + from->maxs[i])*0.5); if (VectorLength(eorg) > rad) continue; return from; } return NULL; } /* ============= G_PickTarget Searches all active entities for the next one that holds the matching string at fieldofs (use the FOFS() macro) in the structure. Searches beginning at the edict after from, or the beginning if NULL NULL will be returned if the end of the list is reached. ============= */ #define MAXCHOICES 8 edict_t *G_PickTarget(char *targetname) { edict_t *ent = NULL; edict_t *choice[MAXCHOICES]; int num_choices = 0; if (!targetname) { gi.dprintf("G_PickTarget called with NULL targetname\n"); return NULL; } while (1) { ent = G_Find(ent, FOFS(targetname), targetname); if (!ent) break; choice[num_choices++] = ent; if (num_choices == MAXCHOICES) break; } if (!num_choices) { gi.dprintf("G_PickTarget: target %s not found\n", targetname); return NULL; } return choice[rand() % num_choices]; } void Think_Delay(edict_t *ent) { G_UseTargets(ent, ent->activator); G_FreeEdict(ent); } /* ============================== G_UseTargets the global "activator" should be set to the entity that initiated the firing. If self.delay is set, a DelayedUse entity will be created that will actually do the SUB_UseTargets after that many seconds have passed. Centerprints any self.message to the activator. Search for (string)targetname in all entities that match (string)self.target and call their .use function ============================== */ void G_UseTargets(edict_t *ent, edict_t *activator) { edict_t *t; //CW++ edict_t *cl_ent; int i; //CW-- // Check for a delay. if (ent->delay) { // create a temp object to fire at a later time t = G_Spawn(); t->classname = "DelayedUse"; t->nextthink = level.time + ent->delay; t->think = Think_Delay; t->activator = activator; if (!activator) gi.dprintf("Think_Delay with no activator\n"); t->message = ent->message; t->target = ent->target; t->killtarget = ent->killtarget; //CW++ t->svflags |= SVF_NOCLIENT; //CW-- return; } // Print the message. if ((ent->message) && !(activator->svflags & SVF_MONSTER)) { //CW++ // For a trigger_waypoint, the message is displayed to all players. if (ent->classname && !Q_stricmp(ent->classname, "trigger_waypoint")) { for (i = 1; i <= game.maxclients; ++i) { cl_ent = &g_edicts[i]; if (!cl_ent->client) continue; if (!cl_ent->inuse) continue; gi_centerprintf(cl_ent, "%s", ent->message); } if (ent->noise_index) gi.positioned_sound(world->s.origin, world, CHAN_AUTO, ent->noise_index, 1, ATTN_NONE, 0); else gi.positioned_sound(world->s.origin, world, CHAN_AUTO, gi.soundindex("misc/talk1.wav"), 1, ATTN_NONE, 0); } else { //CW-- gi_centerprintf(activator, "%s", ent->message); if (ent->noise_index) gi.sound(activator, CHAN_AUTO, ent->noise_index, 1, ATTN_NORM, 0); else gi.sound(activator, CHAN_AUTO, gi.soundindex("misc/talk1.wav"), 1, ATTN_NORM, 0); } } // Kill killtargets. if (ent->killtarget) { t = NULL; while ((t = G_Find(t, FOFS(targetname), ent->killtarget))) { G_FreeEdict(t); if (!ent->inuse) { gi.dprintf("entity was removed while using killtargets\n"); return; } } } // Fire targets. if (ent->target) { t = NULL; while ((t = G_Find(t, FOFS(targetname), ent->target))) { // doors fire area portals in a specific way if (!Q_stricmp(t->classname, "func_areaportal") && (!Q_stricmp(ent->classname, "func_door") || !Q_stricmp(ent->classname, "func_door_rotating"))) continue; if (t == ent) gi.dprintf("WARNING: Entity used itself.\n"); else { if (t->use) t->use(t, ent, activator); } if (!ent->inuse) { gi.dprintf("entity was removed while using targets\n"); return; } } } } /* ============= TempVector This is just a convenience function for making temporary vectors for function calls ============= */ float *tv(float x, float y, float z) { static int index; static vec3_t vecs[8]; float *v; // use an array so that multiple tempvectors won't collide for a while v = vecs[index]; index = (index + 1)&7; v[0] = x; v[1] = y; v[2] = z; return v; } /* ============= VectorToString This is just a convenience function for printing vectors. ============= */ char *vtos(vec3_t v) { static int index; static char str[8][32]; char *s; // use an array so that multiple vtos won't collide s = str[index]; index = (index + 1)&7; Com_sprintf(s, 32, "(%i %i %i)", (int)v[0], (int)v[1], (int)v[2]); return s; } //CW++ /* ============= VectorToString - floating point Prints out vector components to 3dp. ============= */ char *vtosf(vec3_t v) { static int index; static char str[8][64]; char *s; // use an array so that multiple vtos won't collide s = str[index]; index = (index + 1)&7; Com_sprintf(s, 64, "(%.3f %.3f %.3f)", v[0], v[1], v[2]); return s; } //CW-- vec3_t VEC_UP = {0.0F, -1.0F, 0.0F}; vec3_t MOVEDIR_UP = {0.0F, 0.0F, 1.0F}; vec3_t VEC_DOWN = {0.0F, -2.0F, 0.0F}; vec3_t MOVEDIR_DOWN = {0.0F, 0.0F, -1.0F}; void G_SetMovedir(vec3_t angles, vec3_t movedir) { if (VectorCompare(angles, VEC_UP)) VectorCopy(MOVEDIR_UP, movedir); else if(VectorCompare (angles, VEC_DOWN)) VectorCopy(MOVEDIR_DOWN, movedir); else AngleVectors(angles, movedir, NULL, NULL); VectorClear(angles); } float vectoyaw(vec3_t vec) { float yaw; if (/* vec[YAW] == 0 && */ vec[PITCH] == 0.0) { yaw = 0.0; if (vec[YAW] > 0.0) yaw = 90.0; else if (vec[YAW] < 0.0) yaw = -90.0; } else { yaw = (int)(RAD2DEG(atan2(vec[YAW], vec[PITCH]))); //CW if (yaw < 0.0) yaw += 360.0; } return yaw; } void vectoangles(vec3_t value1, vec3_t angles) { float forward; float yaw; float pitch; if ((value1[1] == 0.0) && (value1[0] == 0.0)) { yaw = 0.0F; if (value1[2] > 0.0) pitch = 90.0; else pitch = 270.0; } else { if (value1[0]) yaw = (int)(RAD2DEG(atan2(value1[1], value1[0]))); //CW else if (value1[1] > 0.0) yaw = 90.0; else yaw = -90.0; if (yaw < 0) yaw += 360.0; forward = sqrt(value1[0]*value1[0] + value1[1]*value1[1]); pitch = (int)(RAD2DEG(atan2(value1[2], forward))); //CW if (pitch < 0.0) pitch += 360.0; } angles[PITCH] = -pitch; angles[YAW] = yaw; angles[ROLL] = 0.0; } // Knightmare added void vectoangles2 (vec3_t value1, vec3_t angles) { float forward; float yaw, pitch; if (value1[1] == 0 && value1[0] == 0) { yaw = 0; if (value1[2] > 0) pitch = 90; else pitch = 270; } else { if (value1[0]) yaw = (atan2(value1[1], value1[0]) * 180 / M_PI); else if (value1[1] > 0) yaw = 90; else yaw = 270; if (yaw < 0) yaw += 360; forward = sqrt (value1[0]*value1[0] + value1[1]*value1[1]); pitch = (atan2(value1[2], forward) * 180 / M_PI); if (pitch < 0) pitch += 360; } angles[PITCH] = -pitch; angles[YAW] = yaw; angles[ROLL] = 0; } // end Knightmare char *G_CopyString(char *in) { size_t outSize; char *out; // out = gi.TagMalloc((int)strlen(in)+1, TAG_LEVEL); outSize = strlen(in) + 1; out = gi.TagMalloc(outSize, TAG_LEVEL); // strcpy(out, in); Com_strcpy(out, outSize, in); return out; } void G_InitEdict(edict_t *e) { e->inuse = true; e->classname = "noclass"; e->gravity = 1.0; e->s.number = e - g_edicts; } /* ================= G_Spawn Either finds a free edict, or allocates a new one. Try to avoid reusing an entity that was recently freed, because it can cause the client to think the entity morphed into something else instead of being removed and recreated, which can cause interpolated angles and bad trails. ================= */ edict_t *G_Spawn(void) { edict_t *e; int i; e = &g_edicts[(int)maxclients->value + 1]; for (i = (int)maxclients->value + 1; i < globals.num_edicts; i++, e++) { // the first couple seconds of server time can involve a lot of // freeing and allocating, so relax the replacement policy if (!e->inuse && ((level.time - e->freetime > 0.5) || (e->freetime < 2.0))) { G_InitEdict(e); return e; } } if (i == game.maxentities) gi.error("ED_Alloc: no free edicts"); globals.num_edicts++; G_InitEdict(e); return e; } /* ================= G_FreeEdict Marks the edict as free ================= */ void G_FreeEdict(edict_t *ed) { gi.unlinkentity(ed); // unlink from world if ((ed - g_edicts) <= ((int)maxclients->value + BODY_QUEUE_SIZE)) { gi.dprintf("BUG: tried to free special edict (%d)\n\n", (ed - g_edicts)); //CW++ if (ed->classname) gi.dprintf("ed->classname = %s\n", ed->classname); gi.dprintf("ed->movetype = %d\n", ed->movetype); gi.dprintf("ed->solid = %d\n", ed->solid); if (ed->model) gi.dprintf("ed->model = %s\n", ed->model); if (ed->client) gi.dprintf("ed->client->name = %s\n", ed->client->pers.netname); gi.dprintf("ed->burning = %s\n", (ed->burning)?"TRUE":"FALSE"); gi.dprintf("ed->disintegrated = %s\n", (ed->disintegrated)?"TRUE":"FALSE"); if (ed->owner && ed->owner->client) gi.dprintf("owner->name = %s\n", ed->owner->client->pers.netname); if (ed->owner && ed->owner->classname) gi.dprintf("owner->classname = %s\n", ed->owner->classname); if (ed->enemy) { if (ed->enemy->client) gi.dprintf("enemy->name = %s\n", ed->enemy->client->pers.netname); if (ed->enemy->classname) gi.dprintf("enemy->classname = %s\n", ed->enemy->classname); gi.dprintf("enemy->burning = %s\n", (ed->enemy->burning)?"TRUE":"FALSE"); gi.dprintf("enemy->disintegrated = %s\n", (ed->enemy->disintegrated)?"TRUE":"FALSE"); } if (ed->oldenemy) { if (ed->oldenemy->client) gi.dprintf("oldenemy->name = %s\n", ed->oldenemy->client->pers.netname); if (ed->oldenemy->classname) gi.dprintf("oldenemy->classname = %s\n", ed->oldenemy->classname); gi.dprintf("oldenemy->burning = %s\n", (ed->oldenemy->burning)?"TRUE":"FALSE"); gi.dprintf("oldenemy->disintegrated = %s\n", (ed->oldenemy->disintegrated)?"TRUE":"FALSE"); } gi.dprintf("----------------------------\n\n"); //CW-- return; } memset(ed, 0, sizeof(*ed)); ed->classname = "freed"; ed->freetime = level.time; ed->inuse = false; } //CW++ void trigger_push_touch(edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf); //CW-- /* ============ G_TouchTriggers ============ */ void G_TouchTriggers(edict_t *ent) { static edict_t *touch[MAX_EDICTS]; // Knightmare- made static due to stack size edict_t *hit; int num; int i; // dead things don't activate triggers! if ((ent->client || (ent->svflags & SVF_MONSTER)) && (ent->health <= 0)) return; num = gi.BoxEdicts(ent->absmin, ent->absmax, touch, MAX_EDICTS, AREA_TRIGGERS); // be careful - it is possible to have an entity in this list removed before we get to it (killtriggered) for (i = 0; i < num; ++i) { hit = touch[i]; if (!hit->inuse) continue; if (!hit->touch) continue; //DH++ if (ent->client && ent->client->spycam) continue; //DH-- //CW++ if (ent->isabot && (hit->touch == trigger_push_touch)) ent->client->movestate |= STS_TRIGPUSH; //CW-- hit->touch(hit, ent, NULL, NULL); } } /* ============ G_TouchSolids Call after linking a new trigger in during gameplay to force all entities it covers to immediately touch it ============ */ void G_TouchSolids(edict_t *ent) { static edict_t *touch[MAX_EDICTS]; // Knightmare- made static due to stack size edict_t *hit; int num; int i; num = gi.BoxEdicts(ent->absmin, ent->absmax, touch, MAX_EDICTS, AREA_SOLID); // be careful, it is possible to have an entity in this list removed before we get to it (killtriggered) for (i = 0; i < num; ++i) { hit = touch[i]; if (!hit->inuse) continue; if (ent->touch) ent->touch(hit, ent, NULL, NULL); if (!ent->inuse) break; } } /* ================= KillBox Kills all entities that would touch the proposed new positioning of ent. Ent should be unlinked before calling this! ================= */ qboolean KillBox(edict_t *ent) { trace_t tr; //CW++ trace_t tr_check; edict_t *kill_ent; //CW-- while (1) { tr = gi.trace(ent->s.origin, ent->mins, ent->maxs, ent->s.origin, NULL, MASK_PLAYERSOLID); //CW++ // If we're inside a solid, do a point check on our origin to see if // we're also inside another player (this fixes the "buried teleporters" bug). if (tr.startsolid) { tr_check = gi.trace(ent->s.origin, vec3_origin, vec3_origin, ent->s.origin, NULL, MASK_PLAYERSOLID); if (!tr_check.ent) break; else kill_ent = tr_check.ent; } else { if (!tr.ent) break; else kill_ent = tr.ent; } //CW-- // nail it T_Damage(kill_ent, ent, ent, vec3_origin, ent->s.origin, vec3_origin, 100000, 0, DAMAGE_NO_PROTECTION, MOD_TELEFRAG); //CW // if we didn't kill it, fail if (kill_ent->solid) //CW return false; } return true; // all clear } // Knightmare added void GameDirRelativePath (const char *filename, char *output, size_t outputSize) { #ifdef KMQUAKE2_ENGINE_MOD Com_sprintf(output, outputSize, "%s/%s", gi.GameDir(), filename); #else // KMQUAKE2_ENGINE_MOD cvar_t *basedir, *gamedir; basedir = gi.cvar("basedir", "", 0); gamedir = gi.cvar("gamedir", "", 0); if (strlen(gamedir->string)) Com_sprintf(output, outputSize, "%s/%s/%s", basedir->string, gamedir->string, filename); else Com_sprintf(output, outputSize, "%s/baseq2/%s", basedir->string, filename); #endif // KMQUAKE2_ENGINE_MOD } void SavegameDirRelativePath (const char *filename, char *output, size_t outputSize) { #ifdef KMQUAKE2_ENGINE_MOD Com_sprintf(output, outputSize, "%s/%s", gi.SaveGameDir(), filename); #else // KMQUAKE2_ENGINE_MOD cvar_t *basedir, *gamedir; basedir = gi.cvar("basedir", "", 0); gamedir = gi.cvar("gamedir", "", 0); if (strlen(gamedir->string)) Com_sprintf(output, outputSize, "%s/%s/%s", basedir->string, gamedir->string, filename); else Com_sprintf(output, outputSize, "%s/baseq2/%s", basedir->string, filename); #endif // KMQUAKE2_ENGINE_MOD } void CreatePath (const char *path) { #ifdef KMQUAKE2_ENGINE_MOD gi.CreatePath (path); #else // KMQUAKE2_ENGINE_MOD char tmpBuf[MAX_OSPATH]; char *ofs; if (strstr(path, "..") || strstr(path, "::") || strstr(path, "\\\\") || strstr(path, "//")) { gi.dprintf("WARNING: refusing to create relative path '%s'\n", path); return; } Com_strcpy (tmpBuf, sizeof(tmpBuf), path); for (ofs = tmpBuf+1 ; *ofs ; ofs++) { if (*ofs == '/' || *ofs == '\\') { // create the directory *ofs = 0; _mkdir (tmpBuf); *ofs = '/'; } } #endif // KMQUAKE2_ENGINE_MOD } // end Knightmare /* ============= visible returns 1 if the entity is visible to self, even if not infront() ============= */ qboolean visible(edict_t *self, edict_t *other) //CW { vec3_t spot1; vec3_t spot2; trace_t trace; VectorCopy(self->s.origin, spot1); spot1[2] += self->viewheight; VectorCopy(other->s.origin, spot2); spot2[2] += other->viewheight; trace = gi.trace(spot1, vec3_origin, vec3_origin, spot2, self, MASK_OPAQUE); if (trace.fraction == 1.0) return true; return false; } /* ============= infront returns 1 if the entity is in front (in sight) of self ============= */ qboolean infront(edict_t *self, edict_t *other) //CW { vec3_t vec; vec3_t forward; float dot; AngleVectors(self->s.angles, forward, NULL, NULL); VectorSubtract(other->s.origin, self->s.origin, vec); VectorNormalize(vec); dot = DotProduct(vec, forward); if (dot > 0.3) return true; return false; } //CW++ /* ============ VecRange Returns the magnitude of the vector between two points. ============ */ float VecRange(vec3_t start, vec3_t end) { vec3_t vec; VectorSubtract(end, start, vec); return VectorLength(vec); } /* ============ TList_DelNode Deletes a node from a player's linked list of C4/Trap entities ============ */ void TList_DelNode(edict_t *ent) { edict_t *index; edict_t *prev; // Sanity checks. if (!ent->owner) { gi.dprintf("BUG: Entity with no owner passed to TList_DelNode().\nPlease contact musashi@planetquake.com\n"); return; } if (!ent->owner->next_node) { gi.dprintf("BUG: TList_DelNode() called for an empty list.\nPlease contact musashi@planetquake.com\n"); return; } if ((ent->owner->next_node->die != C4_DieFromDamage) && (ent->owner->next_node->die != Trap_DieFromDamage)) { gi.dprintf("BUG: Invalid pointer passed to TList_DelNode().\nPlease contact musashi@planetquake.com\n"); return; } // Find the node. index = ent->owner->next_node; prev = ent->owner->next_node; while (ent != index) { if (!index) return; prev = index; index = index->next_node; } // Remove the node from the list, and reroute the linking. if (index == ent->owner->next_node) //first in chain ent->owner->next_node = ent->owner->next_node->next_node; else if (!index->next_node) //last in chain prev->next_node = NULL; else { prev->next_node = index->next_node; index->next_node->prev_node = prev; } --ent->owner->client->resp.nodes_active; } /* ============ TList_AddNode Adds a node to a player's linked list of C4/Trap entities ============ */ void TList_AddNode(edict_t *ent) { edict_t *index; // Sanity checks. if (!ent->owner) { gi.dprintf("BUG: Entity with no owner passed to TList_AddNode().\nPlease contact musashi@planetquake.com\n"); return; } if (ent->owner->next_node && (ent->owner->next_node->die != C4_DieFromDamage) && (ent->owner->next_node->die != Trap_DieFromDamage)) { gi.dprintf("BUG: Invalid pointer passed to TList_AddNode().\nPlease contact musashi@planetquake.com\n"); return; } // If the player currently has their maximum number of C4/Traps active, pop the oldest (first) one. if (ent->owner->client->resp.nodes_active >= (int)sv_traps_max_active->value) { if (ent->owner->next_node->die == C4_DieFromDamage) C4_Die(ent->owner->next_node); else Trap_Die(ent->owner->next_node); } // Add the new node to the end of the list. if (ent->owner->next_node) { index = ent->owner->next_node; while (index->next_node) index = index->next_node; index->next_node = ent; } else ent->owner->next_node = ent; ++ent->owner->client->resp.nodes_active; } /* ================= PrintFFAScores Sort the player scores for DM/FFA games, and print them to the server console. ================= */ void PrintFFAScores(void) { edict_t *cl_ent; gclient_t *cl; int sorted[MAX_CLIENTS]; int sortedscores[MAX_CLIENTS]; int score; int total; int i; int j; int k; gi.dprintf("-------------------------\n"); gi.dprintf("Player Scores:\n\n"); // Sort the clients according to score. total = 0; for (i = 0; i < game.maxclients; i++) { cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse) continue; if (cl_ent->client->spectator) continue; score = game.clients[i].resp.score; for (j = 0; j < total; j++) { if (score > sortedscores[j]) break; } for (k = total; k > j; k--) { sorted[k] = sorted[k-1]; sortedscores[k] = sortedscores[k-1]; } sorted[j] = i; sortedscores[j] = score; total++; } // Write the sorted list to the server console. for (i = 0; i < total; i++) { cl = &game.clients[sorted[i]]; gi.dprintf(" %-16.16s : %3d\n", cl->pers.netname, cl->resp.score); } // Write the spectator list to the server console. gi.dprintf("-------------------------\n"); gi.dprintf("Spectators:\n\n"); for (i = 0; i < game.maxclients; i++) { cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse) continue; if (cl_ent->client->spectator) gi.dprintf(" %-16.16s\n", cl_ent->client->pers.netname); } gi.dprintf("-------------------------\n"); } /* ================= PrintTeamScores Sort the player scores by team, and print them to the server console. ================= */ void PrintTeamScores(void) { edict_t *cl_ent; gclient_t *cl; int sorted[2][MAX_CLIENTS]; int sortedscores[2][MAX_CLIENTS]; int score; int total[2]; int totalscore[2]; int team; int i; int j; int k; gi.dprintf("-------------------------\n"); // Sort the clients according to team and score. total[0] = total[1] = 0; totalscore[0] = totalscore[1] = 0; for (i = 0; i < game.maxclients; i++) { cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse) continue; if (cl_ent->client->spectator) continue; if (game.clients[i].resp.ctf_team == CTF_TEAM1) team = 0; else if (game.clients[i].resp.ctf_team == CTF_TEAM2) team = 1; else continue; score = game.clients[i].resp.score; for (j = 0; j < total[team]; j++) { if (score > sortedscores[team][j]) break; } for (k = total[team]; k > j; k--) { sorted[team][k] = sorted[team][k-1]; sortedscores[team][k] = sortedscores[team][k-1]; } sorted[team][j] = i; sortedscores[team][j] = score; totalscore[team] += score; total[team]++; } // Write the sorted lists to the server console... // Team 1's scores. gi.dprintf("Red Team Scores : %4d\n\n", totalscore[0]); for (i = 0; i < total[0]; i++) { cl = &game.clients[sorted[0][i]]; gi.dprintf(" %-16.16s : %4d\n", cl->pers.netname, cl->resp.score); } // Team 2's scores. gi.dprintf("-------------------------\n"); gi.dprintf("Blue Team Scores : %4d\n\n", totalscore[1]); for (i = 0; i < total[1]; i++) { cl = &game.clients[sorted[1][i]]; gi.dprintf(" %-16.16s : %4d\n", cl->pers.netname, cl->resp.score); } // Write the spectator list to the server console. gi.dprintf("-------------------------\n"); gi.dprintf("Spectators:\n\n"); for (i = 0; i < game.maxclients; i++) { cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse) continue; if (cl_ent->client->spectator) gi.dprintf(" %-16.16s\n", cl_ent->client->pers.netname); } gi.dprintf("-------------------------\n"); } /* ============ dm "Debug Message" - displays a single line of text in the server console (used for development/debugging purposes). ============ */ void dm(char *msg) { gi.dprintf("%s", msg); } /* =============================== File opening functions =============================== */ FILE* OpenMaplistFile(qboolean report) { FILE *iostream; cvar_t *game; char filename[MAX_OSPATH]; if (strlen(sv_map_file->string) == 0) return NULL; game = gi.cvar("game", "", 0); if (!*game->string) Com_sprintf(filename, sizeof(filename), "%s/%s", GAMEVERSION, sv_map_file->string); else Com_sprintf(filename, sizeof(filename), "%s/%s", game->string, sv_map_file->string); iostream = fopen(filename, "r"); if (report) { if (iostream != NULL) gi.dprintf("\n>> Map list \"%s\" opened\n", filename); else gi.dprintf("\n** Failed to open \"%s\"\n", filename); } return iostream; } FILE* OpenConfiglistFile(qboolean report) { FILE *iostream; cvar_t *game; char filename[MAX_OSPATH]; if (strlen(sv_config_file->string) == 0) return NULL; game = gi.cvar("game", "", 0); if (!*game->string) Com_sprintf(filename, sizeof(filename), "%s/%s", GAMEVERSION, sv_config_file->string); else Com_sprintf(filename, sizeof(filename), "%s/%s", game->string, sv_config_file->string); iostream = fopen(filename, "r"); if (report) { if (iostream != NULL) gi.dprintf("\n>> Config list \"%s\" opened\n", filename); else gi.dprintf("\n** Failed to open \"%s\"\n", filename); } return iostream; } FILE* OpenAGMDropFile(qboolean report, qboolean readonly) { FILE *iostream; cvar_t *game; char filename[MAX_OSPATH]; if (strlen(sv_agm_drop_file->string) == 0) return NULL; game = gi.cvar("game", "", 0); if (!*game->string) Com_sprintf(filename, sizeof(filename), "%s/%s", GAMEVERSION, sv_agm_drop_file->string); else Com_sprintf(filename, sizeof(filename), "%s/%s", game->string, sv_agm_drop_file->string); if (readonly) iostream = fopen(filename, "r"); else iostream = fopen(filename, "a+"); if (report) { if (iostream != NULL) gi.dprintf("\n>> AGM drop file \"%s\" opened\n", filename); else gi.dprintf("\n** Failed to open \"%s\"\n", filename); } return iostream; } FILE* OpenDiscLauncherDropFile(qboolean report, qboolean readonly) { FILE *iostream; cvar_t *game; char filename[MAX_OSPATH]; if (strlen(sv_disc_drop_file->string) == 0) return NULL; game = gi.cvar("game", "", 0); if (!*game->string) Com_sprintf(filename, sizeof(filename), "%s/%s", GAMEVERSION, sv_disc_drop_file->string); else Com_sprintf(filename, sizeof(filename), "%s/%s", game->string, sv_disc_drop_file->string); if (readonly) iostream = fopen(filename, "r"); else iostream = fopen(filename, "a+"); if (report) { if (iostream != NULL) gi.dprintf("\n>> Disc Launcher drop file \"%s\" opened\n", filename); else gi.dprintf("\n** Failed to open \"%s\"\n", filename); } return iostream; } FILE* OpenBotConfigFile(qboolean report, qboolean readonly) { FILE *iostream; cvar_t *game; char filename[MAX_OSPATH]; if (strlen(sv_bots_config_file->string) == 0) return NULL; game = gi.cvar("game", "", 0); if (!*game->string) Com_sprintf(filename, sizeof(filename), "%s/%s", GAMEVERSION, sv_bots_config_file->string); else Com_sprintf(filename, sizeof(filename), "%s/%s", game->string, sv_bots_config_file->string); if (readonly) iostream = fopen(filename, "r"); else iostream = fopen(filename, "a+"); if (report) { if (iostream != NULL) gi.dprintf("\n>> Bot config file \"%s\" opened\n", filename); else gi.dprintf("\n** Failed to open \"%s\"\n", filename); } return iostream; } //CW-- //DH++ //CW: These functions were written by David Hyde for the Lazarus mod. edict_t *LookingAt(edict_t *ent, int filter, vec3_t endpos, float *range) { edict_t *who; static edict_t *trigger[MAX_EDICTS]; // Knightmare- made static due to stack size edict_t *ignore; trace_t tr; vec_t r; vec3_t end; vec3_t forward; vec3_t start; vec3_t dir; vec3_t entp; vec3_t mins; vec3_t maxs; int i; int num; if (!ent->client) { if (endpos) VectorClear(endpos); if (range) *range = 0; return NULL; } VectorClear(end); if (ent->client->spycam) { AngleVectors(ent->client->ps.viewangles, forward, NULL, NULL); VectorCopy(ent->s.origin, start); ignore = ent->client->spycam; } else { AngleVectors(ent->client->v_angle, forward, NULL, NULL); VectorCopy(ent->s.origin, start); start[2] += ent->viewheight; ignore = ent; } VectorMA(start, WORLD_SIZE, forward, end); // was 8192.0 // First check for looking directly at a pickup item VectorSet(mins, -4096.0, -4096.0, -4096.0); VectorSet(maxs, 4096.0, 4096.0, 4096.0); num = gi.BoxEdicts(mins, maxs, trigger, MAX_EDICTS, AREA_TRIGGERS); for (i = 0; i < num; ++i) { who = trigger[i]; if (!who->inuse) continue; if (!who->item) continue; if (!visible(ent,who)) continue; if (!infront(ent,who)) continue; VectorSubtract(who->s.origin,start,dir); r = VectorLength(dir); VectorMA(start, r, forward, entp); if (entp[0] < who->s.origin[0] - 17.0) continue; if (entp[1] < who->s.origin[1] - 17.0) continue; if (entp[2] < who->s.origin[2] - 17.0) continue; if (entp[0] > who->s.origin[0] + 17.0) continue; if (entp[1] > who->s.origin[1] + 17.0) continue; if (entp[2] > who->s.origin[2] + 17.0) continue; if (endpos) VectorCopy(who->s.origin,endpos); if (range) *range = r; return who; } tr = gi.trace(start, NULL, NULL, end, ignore, MASK_SHOT); if (tr.fraction == 1.0) { // too far away gi.sound(ent, CHAN_AUTO, gi.soundindex("misc/talk1.wav"), 1, ATTN_NORM, 0); return NULL; } if (!tr.ent) { // no hit gi.sound(ent, CHAN_AUTO, gi.soundindex("misc/talk1.wav"), 1, ATTN_NORM, 0); return NULL; } if (!tr.ent->classname) { // should never happen gi.sound(ent, CHAN_AUTO, gi.soundindex("misc/talk1.wav"), 1, ATTN_NORM, 0); return NULL; } if ((strstr(tr.ent->classname, "func_") != NULL) && (filter & LOOKAT_NOBRUSHMODELS)) { // don't hit on brush models gi.sound(ent, CHAN_AUTO, gi.soundindex("misc/talk1.wav"), 1, ATTN_NORM, 0); return NULL; } if ((Q_stricmp(tr.ent->classname, "worldspawn") == 0) && (filter & LOOKAT_NOWORLD)) { // world brush gi.sound(ent, CHAN_AUTO, gi.soundindex("misc/talk1.wav"), 1, ATTN_NORM, 0); return NULL; } if (endpos) { endpos[0] = tr.endpos[0]; endpos[1] = tr.endpos[1]; endpos[2] = tr.endpos[2]; } if (range) { VectorSubtract(tr.endpos,start,start); *range = VectorLength(start); } return tr.ent; } void AnglesNormalize(vec3_t vec) { while(vec[0] > 180.0) vec[0] -= 360.0; while(vec[0] < -180.0) vec[0] += 360.0; while(vec[1] > 360.0) vec[1] -= 360.0; while(vec[1] < 0.0) vec[1] += 360.0; } float SnapToEights(float x) { x *= 8.0; if (x > 0.0) x += 0.5; else x -= 0.5; return 0.125 * (int)x; } /* =============================== Checks that the specified file is inside a PAK. =============================== */ qboolean InPak(char *basedir, char *gamedir, char *filename) { char pakfile[MAX_OSPATH]; FILE *f; pak_header_t pakheader; pak_item_t pakitem; qboolean found = false; int k; int kk; int num; int numitems; // Search paks in the game folder. for (k = 9; (k >= 0) && !found; k--) { // strcpy(pakfile, basedir); Com_strcpy(pakfile, sizeof(pakfile), basedir); if (strlen(gamedir)) { Com_strcat(pakfile, sizeof(pakfile), "/"); Com_strcat(pakfile, sizeof(pakfile), gamedir); } Com_strcat(pakfile, sizeof(pakfile), va("/pak%d.pak", k)); if (NULL != (f = fopen(pakfile, "rb"))) { num = (int)fread(&pakheader, 1, sizeof(pak_header_t), f); if (num >= sizeof(pak_header_t)) { if ((pakheader.id[0] == 'P') && (pakheader.id[1] == 'A') && (pakheader.id[2] == 'C') && (pakheader.id[3] == 'K')) { numitems = pakheader.dsize / sizeof(pak_item_t); fseek(f, pakheader.dstart, SEEK_SET); for (kk = 0; (kk < numitems) && !found; kk++) { fread(&pakitem, 1, sizeof(pak_item_t), f); if (!Q_stricmp(pakitem.name, filename)) found = true; } } } fclose(f); } } return found; } //DH-- //CW++ /* =============================== Checks that the specified file exists. NB: This function assumes that the file specified as 'checkname' has no extension. This is based on code written by David Hyde for the Lazarus mod. =============================== */ qboolean FileExists(char *checkname, filetype_t ftype) { FILE *fstream; cvar_t *basedir; cvar_t *gamedir; char filename[MAX_OSPATH]; char path[MAX_OSPATH]; basedir = gi.cvar("basedir", "", 0); gamedir = gi.cvar("gamedir", "", 0); switch (ftype) { case FILE_MAP: Com_sprintf(path, sizeof(path), "maps/%s.bsp", checkname); break; case FILE_MODEL: Com_sprintf(path, sizeof(path), "models/%s.md2", checkname); break; case FILE_SOUND: Com_sprintf(path, sizeof(path), "sound/%s.wav", checkname); break; case FILE_TEXTURE: Com_sprintf(path, sizeof(path), "textures/%s.wal", checkname); break; default: Com_sprintf(path, sizeof(path), "%s", checkname); break; } if (strlen(gamedir->string)) { // Search in the game directory for external file. Com_sprintf(filename, sizeof(filename), "%s/%s/%s", basedir->string, gamedir->string, path); if ((fstream = fopen(filename, "r")) != NULL) { fclose(fstream); return true; } // Search paks in the game directory. if (InPak(basedir->string, gamedir->string, path)) return true; } // Search in the 'baseq2' directory for external file. Com_sprintf(filename, sizeof(filename), "%s/baseq2/%s", basedir->string, path); if ((fstream = fopen(filename, "r")) != NULL) { fclose(fstream); return true; } // Search paks in the 'baseq2' directory. if (InPak(basedir->string, "baseq2", path)) return true; return false; } //CW-- //Maj++ void gi_cprintf(edict_t *ent, int printlevel, char *fmt, ...) { va_list argptr; char bigbuffer[0x10000]; int len; if (!ent || !ent->inuse || !ent->client) return; // bots don't get messages if (ent->isabot) return; va_start(argptr, fmt); // len = vsprintf(bigbuffer, fmt, argptr); len = Q_vsnprintf(bigbuffer, sizeof(bigbuffer), fmt, argptr); //CW++ //r1 // Check for overflow. if (len > sizeof(bigbuffer)) { gi.dprintf("String too long for gi_bprintf().\n"); return; } //CW-- va_end(argptr); gi.cprintf(ent, printlevel, "%s", bigbuffer); //r1: format string exploit fix } void gi_centerprintf(edict_t *ent, char *fmt, ...) { va_list argptr; char bigbuffer[0x10000]; int len; if (!ent || !ent->inuse || !ent->client) return; // bots don't get messages if (ent->isabot) return; va_start(argptr, fmt); // len = vsprintf(bigbuffer, fmt, argptr); len = Q_vsnprintf(bigbuffer, sizeof(bigbuffer), fmt, argptr); //CW++ //r1 // Check for overflow. if (len > sizeof(bigbuffer)) { gi.dprintf("String too long for gi_bprintf().\n"); return; } //CW-- va_end(argptr); gi.centerprintf(ent, "%s", bigbuffer); //r1: format string exploit fix } void gi_bprintf(int printlevel, char *fmt, ...) { edict_t *ent; va_list argptr; char bigbuffer[0x10000]; int len; int i; va_start(argptr, fmt); // len = vsprintf(bigbuffer, fmt, argptr); len = Q_vsnprintf(bigbuffer, sizeof(bigbuffer), fmt, argptr); //CW++ //r1 // Check for overflow. if (len > sizeof(bigbuffer)) { gi.dprintf("String too long for gi_bprintf().\n"); return; } //CW-- va_end(argptr); if (dedicated->value) gi.cprintf(NULL, printlevel, "%s", bigbuffer); //r1: format string exploit fix for (i = 0; i < game.maxclients; i++) { ent = g_edicts + 1 + i; gi_cprintf(ent, printlevel, "%s", bigbuffer); //r1: format string exploit fix } } //Maj-- //r1++ #define MASK_VOLUME 1 #define MASK_ATTENUATION 2 #define MASK_POSITION 4 #define MASK_ENTITY_CHANNEL 8 #define MASK_TIMEOFS 16 void unicastSound (edict_t *player, int soundIndex, float volume) { int mask = MASK_ENTITY_CHANNEL; // Knightmare- don't send this to bots- causes fatal server error if (!player || player->isabot) return; if (volume != 1.0) mask |= MASK_VOLUME; gi.WriteByte(svc_sound); gi.WriteByte((byte)mask); gi.WriteByte((byte)soundIndex); if (mask & MASK_VOLUME) gi.WriteByte((byte)(volume * 255)); gi.WriteShort(((player - g_edicts - 1) << 3) + CHAN_NO_PHS_ADD); gi.unicast(player, true); } //r1--
412
0.827367
1
0.827367
game-dev
MEDIA
0.92177
game-dev
0.976173
1
0.976173
RHESSys/RHESSys
3,262
rhessys/cycle/surface_hourly.c
/*--------------------------------------------------------------*/ /* */ /* surface_hourly */ /* */ /* NAME */ /* surface_hourly */ /* */ /* */ /* SYNOPSIS */ /* void surface_hourly */ /* */ /* OPTIONS */ /* */ /* DESCRIPTION */ /* */ /* */ /* */ /* PROGRAMMER NOTES */ /* */ /* */ /* */ /* calculate the interception only, leave all evaporation in surface_daily_F.c */ /* */ /*--------------------------------------------------------------*/ #include <stdio.h> #include "rhessys.h" #include "phys_constants.h" void surface_hourly( struct world_object *world, struct basin_object *basin, struct hillslope_object *hillslope, struct zone_object *zone, struct patch_object *patch, struct command_line_object *command_line, struct tec_entry *event, struct date current_date) { /*--------------------------------------------------------------*/ /* Local function declaration */ /*--------------------------------------------------------------*/ double compute_hourly_litter_rain_stored( int, struct patch_object *); /*--------------------------------------------------------------*/ /* Local variable definition. */ /*--------------------------------------------------------------*/ struct litter_object *litter; double surface_NO3; double litter_NO3; /*--------------------------------------------------------------*/ /* Initialize litter variables. */ /*--------------------------------------------------------------*/ litter = &(patch[0].litter); surface_NO3 = 0; litter_NO3 = 0; /*--------------------------------------------------------------*/ /* LITTER STORE INTERCEPTION: */ /*--------------------------------------------------------------*/ if ( (patch[0].detention_store > (max(litter[0].rain_capacity - litter[0].rain_stored, 0.0))) && (patch[0].soil_defaults[0][0].detention_store_size >= 0.0)) { /* assume if det store over litter then litter is saturated */ patch[0].detention_store -= (litter[0].rain_capacity - litter[0].rain_stored); litter[0].rain_stored = litter[0].rain_capacity; surface_NO3 = patch[0].surface_NO3; litter_NO3 = litter[0].NO3_stored; litter[0].NO3_stored = litter[0].rain_stored / (litter[0].rain_stored + patch[0].detention_store) * (litter_NO3 + surface_NO3); patch[0].surface_NO3 = patch[0].detention_store / (litter[0].rain_stored + patch[0].detention_store) * (litter_NO3 + surface_NO3); } if ( patch[0].detention_store <= (litter[0].rain_capacity - litter[0].rain_stored) ) { /*--------------------------------------------------------------*/ /* Update rain storage ( this also updates the patch level */ /* detention store and potential_evaporation */ /*--------------------------------------------------------------*/ litter[0].rain_stored = compute_hourly_litter_rain_stored( command_line[0].verbose_flag, patch); litter[0].NO3_stored += patch[0].surface_NO3; patch[0].surface_NO3 = 0; } return; }/*end surface_hourly.c*/
412
0.941569
1
0.941569
game-dev
MEDIA
0.443523
game-dev
0.624546
1
0.624546
rehlds/Metamod-R
9,379
metamod/include/dlls/schedule.h
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * This source code contains proprietary and confidential information of * Valve LLC and its suppliers. Access to this code is restricted to * persons who have executed a written SDK license with Valve. Any access, * use or distribution of this code by or to any unlicensed person is illegal. * ****/ //========================================================= // Scheduling //========================================================= #ifndef SCHEDULE_H #define SCHEDULE_H #define TASKSTATUS_NEW 0 // Just started #define TASKSTATUS_RUNNING 1 // Running task & movement #define TASKSTATUS_RUNNING_MOVEMENT 2 // Just running movement #define TASKSTATUS_RUNNING_TASK 3 // Just running task #define TASKSTATUS_COMPLETE 4 // Completed, get next task //========================================================= // These are the schedule types //========================================================= typedef enum { SCHED_NONE = 0, SCHED_IDLE_STAND, SCHED_IDLE_WALK, SCHED_WAKE_ANGRY, SCHED_WAKE_CALLED, SCHED_ALERT_FACE, SCHED_ALERT_SMALL_FLINCH, SCHED_ALERT_BIG_FLINCH, SCHED_ALERT_STAND, SCHED_INVESTIGATE_SOUND, SCHED_COMBAT_FACE, SCHED_COMBAT_STAND, SCHED_CHASE_ENEMY, SCHED_CHASE_ENEMY_FAILED, SCHED_VICTORY_DANCE, SCHED_TARGET_FACE, SCHED_TARGET_CHASE, SCHED_SMALL_FLINCH, SCHED_TAKE_COVER_FROM_ENEMY, SCHED_TAKE_COVER_FROM_BEST_SOUND, SCHED_TAKE_COVER_FROM_ORIGIN, SCHED_COWER, // usually a last resort! SCHED_MELEE_ATTACK1, SCHED_MELEE_ATTACK2, SCHED_RANGE_ATTACK1, SCHED_RANGE_ATTACK2, SCHED_SPECIAL_ATTACK1, SCHED_SPECIAL_ATTACK2, SCHED_STANDOFF, SCHED_ARM_WEAPON, SCHED_RELOAD, SCHED_GUARD, SCHED_AMBUSH, SCHED_DIE, SCHED_WAIT_TRIGGER, SCHED_FOLLOW, SCHED_SLEEP, SCHED_WAKE, SCHED_BARNACLE_VICTIM_GRAB, SCHED_BARNACLE_VICTIM_CHOMP, SCHED_AISCRIPT, SCHED_FAIL, LAST_COMMON_SCHEDULE // Leave this at the bottom } SCHEDULE_TYPE; //========================================================= // These are the shared tasks //========================================================= typedef enum { TASK_INVALID = 0, TASK_WAIT, TASK_WAIT_FACE_ENEMY, TASK_WAIT_PVS, TASK_SUGGEST_STATE, TASK_WALK_TO_TARGET, TASK_RUN_TO_TARGET, TASK_MOVE_TO_TARGET_RANGE, TASK_GET_PATH_TO_ENEMY, TASK_GET_PATH_TO_ENEMY_LKP, TASK_GET_PATH_TO_ENEMY_CORPSE, TASK_GET_PATH_TO_LEADER, TASK_GET_PATH_TO_SPOT, TASK_GET_PATH_TO_TARGET, TASK_GET_PATH_TO_HINTNODE, TASK_GET_PATH_TO_LASTPOSITION, TASK_GET_PATH_TO_BESTSOUND, TASK_GET_PATH_TO_BESTSCENT, TASK_RUN_PATH, TASK_WALK_PATH, TASK_STRAFE_PATH, TASK_CLEAR_MOVE_WAIT, TASK_STORE_LASTPOSITION, TASK_CLEAR_LASTPOSITION, TASK_PLAY_ACTIVE_IDLE, TASK_FIND_HINTNODE, TASK_CLEAR_HINTNODE, TASK_SMALL_FLINCH, TASK_FACE_IDEAL, TASK_FACE_ROUTE, TASK_FACE_ENEMY, TASK_FACE_HINTNODE, TASK_FACE_TARGET, TASK_FACE_LASTPOSITION, TASK_RANGE_ATTACK1, TASK_RANGE_ATTACK2, TASK_MELEE_ATTACK1, TASK_MELEE_ATTACK2, TASK_RELOAD, TASK_RANGE_ATTACK1_NOTURN, TASK_RANGE_ATTACK2_NOTURN, TASK_MELEE_ATTACK1_NOTURN, TASK_MELEE_ATTACK2_NOTURN, TASK_RELOAD_NOTURN, TASK_SPECIAL_ATTACK1, TASK_SPECIAL_ATTACK2, TASK_CROUCH, TASK_STAND, TASK_GUARD, TASK_STEP_LEFT, TASK_STEP_RIGHT, TASK_STEP_FORWARD, TASK_STEP_BACK, TASK_DODGE_LEFT, TASK_DODGE_RIGHT, TASK_SOUND_ANGRY, TASK_SOUND_DEATH, TASK_SET_ACTIVITY, TASK_SET_SCHEDULE, TASK_SET_FAIL_SCHEDULE, TASK_CLEAR_FAIL_SCHEDULE, TASK_PLAY_SEQUENCE, TASK_PLAY_SEQUENCE_FACE_ENEMY, TASK_PLAY_SEQUENCE_FACE_TARGET, TASK_SOUND_IDLE, TASK_SOUND_WAKE, TASK_SOUND_PAIN, TASK_SOUND_DIE, TASK_FIND_COVER_FROM_BEST_SOUND,// tries lateral cover first, then node cover TASK_FIND_COVER_FROM_ENEMY,// tries lateral cover first, then node cover TASK_FIND_LATERAL_COVER_FROM_ENEMY, TASK_FIND_NODE_COVER_FROM_ENEMY, TASK_FIND_NEAR_NODE_COVER_FROM_ENEMY,// data for this one is the MAXIMUM acceptable distance to the cover. TASK_FIND_FAR_NODE_COVER_FROM_ENEMY,// data for this one is there MINIMUM aceptable distance to the cover. TASK_FIND_COVER_FROM_ORIGIN, TASK_EAT, TASK_DIE, TASK_WAIT_FOR_SCRIPT, TASK_PLAY_SCRIPT, TASK_ENABLE_SCRIPT, TASK_PLANT_ON_SCRIPT, TASK_FACE_SCRIPT, TASK_WAIT_RANDOM, TASK_WAIT_INDEFINITE, TASK_STOP_MOVING, TASK_TURN_LEFT, TASK_TURN_RIGHT, TASK_REMEMBER, TASK_FORGET, TASK_WAIT_FOR_MOVEMENT, // wait until MovementIsComplete() LAST_COMMON_TASK, // LEAVE THIS AT THE BOTTOM!! (sjb) } SHARED_TASKS; // These go in the flData member of the TASK_WALK_TO_TARGET, TASK_RUN_TO_TARGET enum { TARGET_MOVE_NORMAL = 0, TARGET_MOVE_SCRIPTED = 1, }; // A goal should be used for a task that requires several schedules to complete. // The goal index should indicate which schedule (ordinally) the monster is running. // That way, when tasks fail, the AI can make decisions based on the context of the // current goal and sequence rather than just the current schedule. enum { GOAL_ATTACK_ENEMY, GOAL_MOVE, GOAL_TAKE_COVER, GOAL_MOVE_TARGET, GOAL_EAT, }; // an array of tasks is a task list // an array of schedules is a schedule list struct Task_t { int iTask; float flData; }; struct Schedule_t { Task_t *pTasklist; int cTasks; int iInterruptMask;// a bit mask of conditions that can interrupt this schedule // a more specific mask that indicates which TYPES of sounds will interrupt the schedule in the // event that the schedule is broken by COND_HEAR_SOUND int iSoundMask; const char *pName; }; // an array of waypoints makes up the monster's route. // !!!LATER- this declaration doesn't belong in this file. struct WayPoint_t { Vector vecLocation; int iType; }; // these MoveFlag values are assigned to a WayPoint's TYPE in order to demonstrate the // type of movement the monster should use to get there. #define bits_MF_TO_TARGETENT ( 1 << 0 ) // local move to targetent. #define bits_MF_TO_ENEMY ( 1 << 1 ) // local move to enemy #define bits_MF_TO_COVER ( 1 << 2 ) // local move to a hiding place #define bits_MF_TO_DETOUR ( 1 << 3 ) // local move to detour point. #define bits_MF_TO_PATHCORNER ( 1 << 4 ) // local move to a path corner #define bits_MF_TO_NODE ( 1 << 5 ) // local move to a node #define bits_MF_TO_LOCATION ( 1 << 6 ) // local move to an arbitrary point #define bits_MF_IS_GOAL ( 1 << 7 ) // this waypoint is the goal of the whole move. #define bits_MF_DONT_SIMPLIFY ( 1 << 8 ) // Don't let the route code simplify this waypoint // If you define any flags that aren't _TO_ flags, add them here so we can mask // them off when doing compares. #define bits_MF_NOT_TO_MASK (bits_MF_IS_GOAL | bits_MF_DONT_SIMPLIFY) #define MOVEGOAL_NONE (0) #define MOVEGOAL_TARGETENT (bits_MF_TO_TARGETENT) #define MOVEGOAL_ENEMY (bits_MF_TO_ENEMY) #define MOVEGOAL_PATHCORNER (bits_MF_TO_PATHCORNER) #define MOVEGOAL_LOCATION (bits_MF_TO_LOCATION) #define MOVEGOAL_NODE (bits_MF_TO_NODE) // these bits represent conditions that may befall the monster, of which some are allowed // to interrupt certain schedules. #define bits_COND_NO_AMMO_LOADED ( 1 << 0 ) // weapon needs to be reloaded! #define bits_COND_SEE_HATE ( 1 << 1 ) // see something that you hate #define bits_COND_SEE_FEAR ( 1 << 2 ) // see something that you are afraid of #define bits_COND_SEE_DISLIKE ( 1 << 3 ) // see something that you dislike #define bits_COND_SEE_ENEMY ( 1 << 4 ) // target entity is in full view. #define bits_COND_ENEMY_OCCLUDED ( 1 << 5 ) // target entity occluded by the world #define bits_COND_SMELL_FOOD ( 1 << 6 ) #define bits_COND_ENEMY_TOOFAR ( 1 << 7 ) #define bits_COND_LIGHT_DAMAGE ( 1 << 8 ) // hurt a little #define bits_COND_HEAVY_DAMAGE ( 1 << 9 ) // hurt a lot #define bits_COND_CAN_RANGE_ATTACK1 ( 1 << 10) #define bits_COND_CAN_MELEE_ATTACK1 ( 1 << 11) #define bits_COND_CAN_RANGE_ATTACK2 ( 1 << 12) #define bits_COND_CAN_MELEE_ATTACK2 ( 1 << 13) // #define bits_COND_CAN_RANGE_ATTACK3 ( 1 << 14) #define bits_COND_PROVOKED ( 1 << 15) #define bits_COND_NEW_ENEMY ( 1 << 16) #define bits_COND_HEAR_SOUND ( 1 << 17) // there is an interesting sound #define bits_COND_SMELL ( 1 << 18) // there is an interesting scent #define bits_COND_ENEMY_FACING_ME ( 1 << 19) // enemy is facing me #define bits_COND_ENEMY_DEAD ( 1 << 20) // enemy was killed. If you get this in combat, try to find another enemy. If you get it in alert, victory dance. #define bits_COND_SEE_CLIENT ( 1 << 21) // see a client #define bits_COND_SEE_NEMESIS ( 1 << 22) // see my nemesis #define bits_COND_SPECIAL1 ( 1 << 28) // Defined by individual monster #define bits_COND_SPECIAL2 ( 1 << 29) // Defined by individual monster #define bits_COND_TASK_FAILED ( 1 << 30) #define bits_COND_SCHEDULE_DONE ( 1 << 31) #define bits_COND_ALL_SPECIAL (bits_COND_SPECIAL1 | bits_COND_SPECIAL2) #define bits_COND_CAN_ATTACK (bits_COND_CAN_RANGE_ATTACK1 | bits_COND_CAN_MELEE_ATTACK1 | bits_COND_CAN_RANGE_ATTACK2 | bits_COND_CAN_MELEE_ATTACK2) #endif // SCHEDULE_H
412
0.987691
1
0.987691
game-dev
MEDIA
0.889147
game-dev
0.906888
1
0.906888
SinlessDevil/UnityGridLevelEditor
5,590
Assets/Plugins/UniTask/Runtime/Linq/Create.cs
using Cysharp.Threading.Tasks.Internal; using System; using System.Threading; namespace Cysharp.Threading.Tasks.Linq { public static partial class UniTaskAsyncEnumerable { public static IUniTaskAsyncEnumerable<T> Create<T>(Func<IAsyncWriter<T>, CancellationToken, UniTask> create) { Error.ThrowArgumentNullException(create, nameof(create)); return new Create<T>(create); } } public interface IAsyncWriter<T> { UniTask YieldAsync(T value); } internal sealed class Create<T> : IUniTaskAsyncEnumerable<T> { readonly Func<IAsyncWriter<T>, CancellationToken, UniTask> create; public Create(Func<IAsyncWriter<T>, CancellationToken, UniTask> create) { this.create = create; } public IUniTaskAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default) { return new _Create(create, cancellationToken); } sealed class _Create : MoveNextSource, IUniTaskAsyncEnumerator<T> { readonly Func<IAsyncWriter<T>, CancellationToken, UniTask> create; readonly CancellationToken cancellationToken; int state = -1; AsyncWriter writer; public _Create(Func<IAsyncWriter<T>, CancellationToken, UniTask> create, CancellationToken cancellationToken) { this.create = create; this.cancellationToken = cancellationToken; TaskTracker.TrackActiveTask(this, 3); } public T Current { get; private set; } public UniTask DisposeAsync() { TaskTracker.RemoveTracking(this); writer.Dispose(); return default; } public UniTask<bool> MoveNextAsync() { if (state == -2) return default; completionSource.Reset(); MoveNext(); return new UniTask<bool>(this, completionSource.Version); } void MoveNext() { try { switch (state) { case -1: // init { writer = new AsyncWriter(this); RunWriterTask(create(writer, cancellationToken)).Forget(); if (Volatile.Read(ref state) == -2) { return; // complete synchronously } state = 0; // wait YieldAsync, it set TrySetResult(true) return; } case 0: writer.SignalWriter(); return; default: goto DONE; } } catch (Exception ex) { state = -2; completionSource.TrySetException(ex); return; } DONE: state = -2; completionSource.TrySetResult(false); return; } async UniTaskVoid RunWriterTask(UniTask task) { try { await task; goto DONE; } catch (Exception ex) { Volatile.Write(ref state, -2); completionSource.TrySetException(ex); return; } DONE: Volatile.Write(ref state, -2); completionSource.TrySetResult(false); } public void SetResult(T value) { Current = value; completionSource.TrySetResult(true); } } sealed class AsyncWriter : IUniTaskSource, IAsyncWriter<T>, IDisposable { readonly _Create enumerator; UniTaskCompletionSourceCore<AsyncUnit> core; public AsyncWriter(_Create enumerator) { this.enumerator = enumerator; } public void Dispose() { var status = core.GetStatus(core.Version); if (status == UniTaskStatus.Pending) { core.TrySetCanceled(); } } public void GetResult(short token) { core.GetResult(token); } public UniTaskStatus GetStatus(short token) { return core.GetStatus(token); } public UniTaskStatus UnsafeGetStatus() { return core.UnsafeGetStatus(); } public void OnCompleted(Action<object> continuation, object state, short token) { core.OnCompleted(continuation, state, token); } public UniTask YieldAsync(T value) { core.Reset(); enumerator.SetResult(value); return new UniTask(this, core.Version); } public void SignalWriter() { core.TrySetResult(AsyncUnit.Default); } } } }
412
0.894321
1
0.894321
game-dev
MEDIA
0.712594
game-dev
0.944956
1
0.944956
open-modding-platform/omp-lswtss
4,655
workspaces/dotnet/galaxy-unleashed-runtime/src/BattleFlag.cs
using System; using System.Numerics; using OMP.LSWTSS.CApi1; namespace OMP.LSWTSS; public partial class GalaxyUnleashed { class BattleFlag : IDisposable { public bool IsDisposed { get; private set; } public Vector3 Position { get; set; } public bool ShouldBeDestroyed { get; set; } V1.PrefabResource? _hologramPrefabResource; ApiEntity.NativeHandle _hologram; ApiTransformComponent.NativeHandle _hologramTransformComponent; NttRenderTTExportObject.NativeHandle _hologramNttRenderTTExportObject; float _hologramRotationY; DateTime? _hologramRotationLastUpdateTime; public BattleFlag(Vector3 position) { IsDisposed = false; Position = position; ShouldBeDestroyed = false; _hologramPrefabResource = null; _hologram = (ApiEntity.NativeHandle)nint.Zero; _hologramTransformComponent = (ApiTransformComponent.NativeHandle)nint.Zero; _hologramNttRenderTTExportObject = (NttRenderTTExportObject.NativeHandle)nint.Zero; _hologramRotationY = 0.0f; _hologramRotationLastUpdateTime = null; } void ThrowIfDisposed() { if (IsDisposed) { throw new InvalidOperationException(); } } void UpdateHologramRotation() { if (_hologramTransformComponent == nint.Zero) { return; } var now = DateTime.Now; var timeSinceLastHologramRotationUpdate = _hologramRotationLastUpdateTime == null ? TimeSpan.Zero : now - _hologramRotationLastUpdateTime.Value; _hologramRotationY = (_hologramRotationY + 0.1f * (float)timeSinceLastHologramRotationUpdate.TotalMilliseconds) % 360.0f; _hologramTransformComponent.SetRotation(0f, _hologramRotationY, 0f); _hologramRotationLastUpdateTime = now; } void UpdateHologram() { if (_hologram == nint.Zero) { if (_hologramPrefabResource == null) { _hologramPrefabResource = new V1.PrefabResource("chars/items/goon_whiteflag.prefab_baked"); } if (!_hologramPrefabResource.FetchIsLoaded()) { return; } var currentApiWorld = V1.GetCApi1CurrentApiWorld(); if (currentApiWorld == nint.Zero) { return; } _hologram = _hologramPrefabResource.FetchCApi1Prefab().Clone(); _hologram.SetNoSerialise(); _hologram.SetParent(currentApiWorld.GetSceneGraphRoot()); _hologramTransformComponent = (ApiTransformComponent.NativeHandle)_hologram.FindComponentByTypeName( ApiTransformComponent.Info.ApiClassName ); _hologramNttRenderTTExportObject = (NttRenderTTExportObject.NativeHandle)_hologram.FindComponentByTypeName( NttRenderTTExportObject.Info.ApiClassName ); if (_hologramNttRenderTTExportObject != nint.Zero) { _hologramNttRenderTTExportObject.RenderAsHologram = true; } } if (_hologram != nint.Zero) { if (!_hologram.IsActive()) { Dispose(); } UpdateHologramRotation(); if (_hologramTransformComponent != nint.Zero) { _hologramTransformComponent.SetPosition(Position.X, Position.Y + 0.1f, Position.Z); } if (_hologramNttRenderTTExportObject != nint.Zero) { _hologramNttRenderTTExportObject.HologramOpacity = _instance!._battle.State.IsActive ? 1.0f : 0.1f; } } } public void Update() { ThrowIfDisposed(); if (ShouldBeDestroyed) { Dispose(); return; } UpdateHologram(); } public void Dispose() { if (IsDisposed) { return; } if (_hologram != nint.Zero && _hologram.IsActive()) { _hologram.DeferredDelete(); } _hologramPrefabResource?.Dispose(); IsDisposed = true; } } }
412
0.857866
1
0.857866
game-dev
MEDIA
0.685875
game-dev,graphics-rendering
0.605794
1
0.605794
moonstream-to/api
5,134
moonstreamdb-v3/moonstreamdbv3/alembic/versions/d816689b786a_add_game7_mainnet_labels.py
"""Add Game7 mainnet labels Revision ID: d816689b786a Revises: 1d53afc1eff4 Create Date: 2024-10-14 15:58:21.374247 """ from typing import Sequence, Union from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision: str = 'd816689b786a' down_revision: Union[str, None] = '1d53afc1eff4' branch_labels: Union[str, Sequence[str], None] = None depends_on: Union[str, Sequence[str], None] = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.create_table('game7_labels', sa.Column('id', sa.UUID(), nullable=False), sa.Column('label', sa.VARCHAR(length=256), nullable=False), sa.Column('transaction_hash', sa.VARCHAR(length=128), nullable=False), sa.Column('log_index', sa.Integer(), nullable=True), sa.Column('block_number', sa.BigInteger(), nullable=False), sa.Column('block_hash', sa.VARCHAR(length=256), nullable=False), sa.Column('block_timestamp', sa.BigInteger(), nullable=False), sa.Column('caller_address', sa.LargeBinary(), nullable=True), sa.Column('origin_address', sa.LargeBinary(), nullable=True), sa.Column('address', sa.LargeBinary(), nullable=False), sa.Column('label_name', sa.Text(), nullable=True), sa.Column('label_type', sa.VARCHAR(length=64), nullable=True), sa.Column('label_data', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text("TIMEZONE('utc', statement_timestamp())"), nullable=False), sa.PrimaryKeyConstraint('id', name=op.f('pk_game7_labels')), sa.UniqueConstraint('id', name=op.f('uq_game7_labels_id')) ) op.create_index('ix_game7_labels_addr_block_num', 'game7_labels', ['address', 'block_number'], unique=False) op.create_index('ix_game7_labels_addr_block_ts', 'game7_labels', ['address', 'block_timestamp'], unique=False) op.create_index(op.f('ix_game7_labels_address'), 'game7_labels', ['address'], unique=False) op.create_index(op.f('ix_game7_labels_block_number'), 'game7_labels', ['block_number'], unique=False) op.create_index(op.f('ix_game7_labels_caller_address'), 'game7_labels', ['caller_address'], unique=False) op.create_index(op.f('ix_game7_labels_label'), 'game7_labels', ['label'], unique=False) op.create_index(op.f('ix_game7_labels_label_name'), 'game7_labels', ['label_name'], unique=False) op.create_index(op.f('ix_game7_labels_label_type'), 'game7_labels', ['label_type'], unique=False) op.create_index(op.f('ix_game7_labels_origin_address'), 'game7_labels', ['origin_address'], unique=False) op.create_index(op.f('ix_game7_labels_transaction_hash'), 'game7_labels', ['transaction_hash'], unique=False) op.create_index('uk_game7_labels_tx_hash_log_idx_evt', 'game7_labels', ['transaction_hash', 'log_index'], unique=True, postgresql_where=sa.text("label='seer' and label_type='event'")) op.create_index('uk_game7_labels_tx_hash_log_idx_evt_raw', 'game7_labels', ['transaction_hash', 'log_index'], unique=True, postgresql_where=sa.text("label='seer-raw' and label_type='event'")) op.create_index('uk_game7_labels_tx_hash_tx_call', 'game7_labels', ['transaction_hash'], unique=True, postgresql_where=sa.text("label='seer' and label_type='tx_call'")) op.create_index('uk_game7_labels_tx_hash_tx_call_raw', 'game7_labels', ['transaction_hash'], unique=True, postgresql_where=sa.text("label='seer-raw' and label_type='tx_call'")) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_index('uk_game7_labels_tx_hash_tx_call_raw', table_name='game7_labels', postgresql_where=sa.text("label='seer-raw' and label_type='tx_call'")) op.drop_index('uk_game7_labels_tx_hash_tx_call', table_name='game7_labels', postgresql_where=sa.text("label='seer' and label_type='tx_call'")) op.drop_index('uk_game7_labels_tx_hash_log_idx_evt_raw', table_name='game7_labels', postgresql_where=sa.text("label='seer-raw' and label_type='event'")) op.drop_index('uk_game7_labels_tx_hash_log_idx_evt', table_name='game7_labels', postgresql_where=sa.text("label='seer' and label_type='event'")) op.drop_index(op.f('ix_game7_labels_transaction_hash'), table_name='game7_labels') op.drop_index(op.f('ix_game7_labels_origin_address'), table_name='game7_labels') op.drop_index(op.f('ix_game7_labels_label_type'), table_name='game7_labels') op.drop_index(op.f('ix_game7_labels_label_name'), table_name='game7_labels') op.drop_index(op.f('ix_game7_labels_label'), table_name='game7_labels') op.drop_index(op.f('ix_game7_labels_caller_address'), table_name='game7_labels') op.drop_index(op.f('ix_game7_labels_block_number'), table_name='game7_labels') op.drop_index(op.f('ix_game7_labels_address'), table_name='game7_labels') op.drop_index('ix_game7_labels_addr_block_ts', table_name='game7_labels') op.drop_index('ix_game7_labels_addr_block_num', table_name='game7_labels') op.drop_table('game7_labels') # ### end Alembic commands ###
412
0.527149
1
0.527149
game-dev
MEDIA
0.625324
game-dev,databases
0.718022
1
0.718022
vayerx/shadowgrounds
3,183
editor/physics_mass.cpp
//#include "precompiled.h" #include "physics_mass.h" #include "parser.h" #include "string_conversions.h" #include "../filesystem/input_file_stream.h" #include "../filesystem/file_package_manager.h" #include "../system/Logger.h" #include <vector> namespace frozenbyte { namespace editor { namespace { std::string fileName = "Editor\\Masses.fbt"; } struct PhysicsMass::Data { struct Mass { std::string name; float value; Mass() : value() { } }; struct MassSorter { bool operator () (const Mass &a, const Mass &b) const { return a.value < b.value; } }; typedef std::vector<Mass> MassList; MassList masses; Data() { parseData(); } void parseData() { Parser parser; filesystem::FilePackageManager::getInstance().getFile(fileName) >> parser; const ParserGroup &globals = parser.getGlobals(); int groups = globals.getSubGroupAmount(); for (int i = 0; i < groups; ++i) { Mass mass; mass.name = globals.getSubGroupName(i); if ( mass.name.empty() ) continue; const ParserGroup &group = globals.getSubGroup(mass.name); const std::string &massString = group.getValue("value"); mass.value = convertFromString<float>(massString, 20.f); masses.push_back(mass); } std::sort( masses.begin(), masses.end(), MassSorter() ); } }; PhysicsMass::PhysicsMass() : data( new Data() ) { } PhysicsMass::~PhysicsMass() { } int PhysicsMass::getMassAmount() const { return data->masses.size(); } std::string PhysicsMass::getMassName(int index) const { assert( index >= 0 && index <= getMassAmount() ); return data->masses[index].name; } int PhysicsMass::getMassIndex(const std::string &name) const { for (int i = 0; i < getMassAmount(); ++i) { if (data->masses[i].name == name) return i; } //assert(!"Name not found! -- conflicts?"); return 0; } float PhysicsMass::getMass(const std::string &name) const { for (int i = 0; i < getMassAmount(); ++i) { if (data->masses[i].name == name) return data->masses[i].value; } //assert(!"Name not found! -- conflicts?"); Logger::getInstance()->warning("PhysicsMass::getMass - Physics mass name not found."); Logger::getInstance()->debug( name.c_str() ); return 20.f; } } // editor } // frozenbyte
412
0.777226
1
0.777226
game-dev
MEDIA
0.574267
game-dev
0.704809
1
0.704809
sndnv/stasis
4,468
client-android/lib/src/test/kotlin/stasis/test/client_android/lib/mocks/MockBackupTracker.kt
package stasis.test.client_android.lib.mocks import stasis.client_android.lib.collection.rules.Rule import stasis.client_android.lib.model.EntityMetadata import stasis.client_android.lib.model.SourceEntity import stasis.client_android.lib.model.server.datasets.DatasetDefinitionId import stasis.client_android.lib.model.server.datasets.DatasetEntryId import stasis.client_android.lib.ops.OperationId import stasis.client_android.lib.tracking.BackupTracker import stasis.client_android.lib.tracking.state.BackupState import stasis.client_android.lib.utils.Either import java.nio.file.Path import java.util.concurrent.atomic.AtomicInteger open class MockBackupTracker : BackupTracker { private val stats: Map<Statistic, AtomicInteger> = mapOf( Statistic.Started to AtomicInteger(0), Statistic.EntityDiscovered to AtomicInteger(0), Statistic.SpecificationProcessed to AtomicInteger(0), Statistic.EntityExamined to AtomicInteger(0), Statistic.EntitySkipped to AtomicInteger(0), Statistic.EntityCollected to AtomicInteger(0), Statistic.EntityProcessingStarted to AtomicInteger(0), Statistic.EntityPartProcessed to AtomicInteger(0), Statistic.EntityProcessed to AtomicInteger(0), Statistic.MetadataCollected to AtomicInteger(0), Statistic.MetadataPushed to AtomicInteger(0), Statistic.FailureEncountered to AtomicInteger(0), Statistic.Completed to AtomicInteger(0) ) override suspend fun stateOf(operation: OperationId): BackupState? = null override fun started(operation: OperationId, definition: DatasetDefinitionId) { stats[Statistic.Started]?.getAndIncrement() } override fun entityDiscovered( operation: OperationId, entity: Path ) { stats[Statistic.EntityDiscovered]?.getAndIncrement() } override fun specificationProcessed( operation: OperationId, unmatched: List<Pair<Rule, Throwable>> ) { stats[Statistic.SpecificationProcessed]?.getAndIncrement() } override fun entityExamined(operation: OperationId, entity: Path) { stats[Statistic.EntityExamined]?.getAndIncrement() } override fun entitySkipped(operation: OperationId, entity: Path) { stats[Statistic.EntitySkipped]?.getAndIncrement() } override fun entityCollected(operation: OperationId, entity: SourceEntity) { stats[Statistic.EntityCollected]?.getAndIncrement() } override fun entityProcessingStarted(operation: OperationId, entity: Path, expectedParts: Int) { stats[Statistic.EntityProcessingStarted]?.getAndIncrement() } override fun entityPartProcessed(operation: OperationId, entity: Path) { stats[Statistic.EntityPartProcessed]?.getAndIncrement() } override fun entityProcessed( operation: OperationId, entity: Path, metadata: Either<EntityMetadata, EntityMetadata> ) { stats[Statistic.EntityProcessed]?.getAndIncrement() } override fun metadataCollected(operation: OperationId) { stats[Statistic.MetadataCollected]?.getAndIncrement() } override fun metadataPushed(operation: OperationId, entry: DatasetEntryId) { stats[Statistic.MetadataPushed]?.getAndIncrement() } override fun failureEncountered(operation: OperationId, entity: Path, failure: Throwable) { stats[Statistic.FailureEncountered]?.getAndIncrement() } override fun failureEncountered(operation: OperationId, failure: Throwable) { stats[Statistic.FailureEncountered]?.getAndIncrement() } override fun completed(operation: OperationId) { stats[Statistic.Completed]?.getAndIncrement() } val statistics: Map<Statistic, Int> get() = stats.mapValues { it.value.get() } sealed class Statistic { object Started : Statistic() object EntityDiscovered : Statistic() object SpecificationProcessed : Statistic() object EntityExamined : Statistic() object EntitySkipped : Statistic() object EntityCollected : Statistic() object EntityProcessingStarted : Statistic() object EntityPartProcessed : Statistic() object EntityProcessed : Statistic() object MetadataCollected : Statistic() object MetadataPushed : Statistic() object FailureEncountered : Statistic() object Completed : Statistic() } }
412
0.908471
1
0.908471
game-dev
MEDIA
0.688726
game-dev
0.922166
1
0.922166
Thinkofname/UniverCity
4,107
src/script/client_bootstrap.lua
safe_global_env.is_client = true function init_module_scope(mod_name, scope) scope.ui = lock_table({ query = function() return ui_root_query() end, add_node = function(node) return ui_add_node(node) end, remove_node = function(node) return ui_remove_node(node) end, load_node = function(key) return ui_load_node(key) end, new = function(name) return ui_new_node(name) end, new_text = function(value) return ui_new_text_node(value) end, from_str = function(str) return ui_new_node_str(str) end, emit_event = function(evt, ...) _G["ui_emit_" .. tostring(select("#", ...))](evt, ...) end, emit_accept = function(node) ui_emit_accept(node) end, emit_cancel = function(node) ui_emit_cancel(node) end, set_cursor = function(sprite) ui_emit_1("set_cursor", sprite) end, -- Tooltip show_tooltip = function(key, node, x, y) ui_show_tooltip(key, node, x, y) end, hide_tooltip = function(key) ui_hide_tooltip(key) end, move_tooltip = function(key, x, y) ui_move_tooltip(key, x, y) end, builder = function(inner) local magic_scope = setmetatable({}, { __metatable = false, __newindex = function() error("Immutable table") end, __index = function(tbl, name) return function(values) local node = scope.ui.new(name) for k, v in pairs(values) do if type(k) ~= "number" then local ty = type(v) if ty == "string" then node:set_property_string(k, v) elseif ty == "number" then node:set_property_float(k, v) elseif ty == "boolean" then node:set_property_bool(k, v) end end end for _, v in ipairs(values) do if type(v) == "string" then node:add_child(scope.ui.new_text(v)) else node:add_child(v) end end return node end end, }) setfenv(inner, magic_scope) return inner() end, }) scope.audio = lock_table({ play_sound = function(sound) audio_play_sound(mod_name, sound) end, play_sound_at = function(sound, x, y) return audio_play_sound_at(mod_name, sound, x, y) end, }) scope.open_url = function(url) try_open_url(url) end scope.new_matrix = function() return new_matrix() end end function clear_module_state(mod_name) end function compile_ui_action(module, sub, func, elm, evt) local scope = get_module_scope(module) local sub = scope.require(sub) local submeta = debug.getmetatable(sub) if submeta.compiled_funcs == nil then submeta.compiled_funcs = {} end local cf = submeta.compiled_funcs[func] if cf ~= nil then return cf end local lfunc, err = loadstring("return function(node, evt)\n" .. func .. "\nend") if err then print(string.format("Failed to perform event for '%s'", module)) error(err) end setfenv(lfunc, sub) local status, ret = xpcall(lfunc, gen_stack) if not status then print(string.format("Failed to perform event for '%s'", module)) error(ret) end submeta.compiled_funcs[func] = ret return ret end
412
0.932195
1
0.932195
game-dev
MEDIA
0.860627
game-dev
0.898257
1
0.898257
shiversoftdev/t8-src
23,771
scripts/zm/zm_escape_util.gsc
// Decompiled by Serious. Credits to Scoba for his original tool, Cerberus, which I heavily upgraded to support remaining features, other games, and other platforms. #using scripts\zm\zm_escape_travel.gsc; #using script_ab862743b3070a; #using scripts\zm_common\zm_zonemgr.gsc; #using scripts\zm_common\zm_vo.gsc; #using scripts\zm_common\zm_utility.gsc; #using scripts\zm_common\zm_score.gsc; #using scripts\zm_common\zm_round_spawning.gsc; #using scripts\zm_common\zm_round_logic.gsc; #using scripts\zm_common\zm_player.gsc; #using scripts\zm_common\zm_items.gsc; #using scripts\zm_common\zm_customgame.gsc; #using scripts\zm_common\zm_crafting.gsc; #using scripts\zm_common\zm_characters.gsc; #using scripts\zm_common\zm_audio.gsc; #using scripts\core_common\ai\zombie_utility.gsc; #using scripts\core_common\math_shared.gsc; #using scripts\core_common\exploder_shared.gsc; #using scripts\core_common\callbacks_shared.gsc; #using scripts\core_common\values_shared.gsc; #using scripts\core_common\util_shared.gsc; #using scripts\core_common\system_shared.gsc; #using scripts\core_common\scene_shared.gsc; #using scripts\core_common\flag_shared.gsc; #using scripts\core_common\array_shared.gsc; #using scripts\core_common\struct.gsc; #using scripts\core_common\clientfield_shared.gsc; #using scripts\core_common\ai_shared.gsc; #namespace zm_escape_util; /* Name: __init__system__ Namespace: zm_escape_util Checksum: 0x8001814B Offset: 0x4A0 Size: 0x44 Parameters: 0 Flags: AutoExec */ function autoexec __init__system__() { system::register(#"zm_escape_util", &__init__, &__main__, undefined); } /* Name: __init__ Namespace: zm_escape_util Checksum: 0x48EF291E Offset: 0x4F0 Size: 0x54 Parameters: 0 Flags: Linked */ function __init__() { level flag::init(#"hash_7039457b1cc827de"); level.lighting_state = 0; callback::on_connect(&function_6a1500f1); } /* Name: __main__ Namespace: zm_escape_util Checksum: 0x50A78331 Offset: 0x550 Size: 0x64 Parameters: 0 Flags: Linked */ function __main__() { level thread function_8164716a(); level thread catwalk_arm_scene_init(); level.gravityspike_position_check = &function_ba62dc81; level thread function_5d3c7c04(); } /* Name: init_clientfields Namespace: zm_escape_util Checksum: 0xB2279EDC Offset: 0x5C0 Size: 0x104 Parameters: 0 Flags: Linked */ function init_clientfields() { clientfield::register("scriptmover", "" + #"hash_7327d0447d656234", 1, 1, "int"); clientfield::register("item", "" + #"hash_76662556681a502c", 1, 1, "int"); clientfield::register("scriptmover", "" + #"hash_59be891b288663cc", 1, 1, "int"); clientfield::register("toplayer", "" + #"hash_257c215ab25a21c5", 1, 1, "counter"); } /* Name: function_28d0cf11 Namespace: zm_escape_util Checksum: 0x9216F0F7 Offset: 0x6D0 Size: 0x246 Parameters: 1 Flags: Linked */ function function_28d0cf11(str_script_noteworthy) { var_95380627 = 0; switch(level.activeplayers.size) { case 1: { n_multiplier = 3; break; } case 2: { n_multiplier = 2; break; } case 3: { n_multiplier = 1; break; } default: { n_multiplier = 1; break; } } var_637f088d = zm_round_logic::get_zombie_count_for_round(level.round_number, level.activeplayers.size) - (level.round_number * n_multiplier); level.var_c843e795 = var_637f088d; if(var_637f088d < 0) { var_637f088d = 0; } else { switch(level.activeplayers.size) { case 1: { if(var_637f088d > 36) { var_637f088d = 36; } break; } case 2: { if(var_637f088d > 37) { var_637f088d = 37; } break; } case 3: { if(var_637f088d > 38) { var_637f088d = 38; } break; } case 4: { if(var_637f088d > 39) { var_637f088d = 39; } break; } } } var_d8036031 = zombie_utility::get_current_zombie_count(); if(var_d8036031 > var_637f088d) { var_95380627 = 1; } return var_95380627; } /* Name: function_f79f494e Namespace: zm_escape_util Checksum: 0x760F9D7 Offset: 0x920 Size: 0x38 Parameters: 0 Flags: None */ function function_f79f494e() { var_1ce4fa50 = zombie_utility::get_current_zombie_count(); if(var_1ce4fa50 >= level.zombie_ai_limit) { return true; } return false; } /* Name: function_24d3ec02 Namespace: zm_escape_util Checksum: 0x2E4F668A Offset: 0x960 Size: 0xCE Parameters: 2 Flags: Linked */ function function_24d3ec02(str_script_noteworthy, var_a61b5e1 = 0) { self endon(#"death"); if(isdefined(str_script_noteworthy)) { self.script_noteworthy = str_script_noteworthy; } self.var_45cec07d = 1; self.ignore_enemy_count = 1; self.exclude_cleanup_adding_to_total = 1; self zombie_utility::set_zombie_run_cycle("sprint"); if(!var_a61b5e1) { self zm_score::function_acaab828(); } self waittill(#"completed_emerging_into_playable_area"); self.no_powerups = 1; } /* Name: function_7273c33d Namespace: zm_escape_util Checksum: 0x7FE0D1B2 Offset: 0xA38 Size: 0x356 Parameters: 2 Flags: Linked */ function function_7273c33d(s_loc, var_2c30f72f = 1) { self endon(#"death"); self.ignore_find_flesh = 1; self.b_ignore_cleanup = 1; self.ignore_enemy_count = 1; self.exclude_cleanup_adding_to_total = 1; self val::set(#"dog_spawn", "ignoreall", 1); self val::set(#"dog_spawn", "ignoreme", 1); self util::magic_bullet_shield(); self setfreecameralockonallowed(0); self forceteleport(s_loc.origin, s_loc.angles); self ghost(); playsoundatposition(#"zmb_hellhound_prespawn", s_loc.origin); wait(1.5); if(var_2c30f72f) { self clientfield::increment("dog_spawn_fx"); playsoundatposition(#"zmb_hellhound_bolt", s_loc.origin); } earthquake(0.5, 0.75, s_loc.origin, 1000); playsoundatposition(#"zmb_hellhound_spawn", s_loc.origin); /# assert(isdefined(self), ""); #/ /# assert(isalive(self), ""); #/ /# assert(zm_utility::is_magic_bullet_shield_enabled(self), ""); #/ self zombie_dog_util::zombie_setup_attack_properties_dog(); self util::stop_magic_bullet_shield(); wait(0.1); self show(); self setfreecameralockonallowed(1); self val::reset(#"dog_spawn", "ignoreme"); self val::reset(#"dog_spawn", "ignoreall"); self notify(#"visible"); } /* Name: catwalk_arm_scene_init Namespace: zm_escape_util Checksum: 0x1FD84590 Offset: 0xD98 Size: 0xBC Parameters: 0 Flags: Linked */ function catwalk_arm_scene_init() { scene::add_scene_func(#"hash_356b958baded5b94", &function_817220a9, "init"); scene::add_scene_func(#"hash_356b988baded60ad", &function_817220a9, "init"); var_b959a637 = struct::get_array("catwalk_arm_scene", "targetname"); array::thread_all(var_b959a637, &function_b5ac159d); } /* Name: function_817220a9 Namespace: zm_escape_util Checksum: 0x22B576A7 Offset: 0xE60 Size: 0x274 Parameters: 1 Flags: Linked */ function function_817220a9(a_ents) { a_ents[#"arm_grasp"] setcandamage(1); a_ents[#"arm_grasp"].health = 10000; var_44ec6b44 = getent(self.target, "targetname"); a_ents[#"arm_grasp"].var_ead5d884 = 1; if(!zm_utility::is_standard()) { var_44ec6b44 thread function_1abf5396(a_ents[#"arm_grasp"]); } while(true) { s_result = undefined; s_result = a_ents[#"arm_grasp"] waittill(#"damage"); if(isplayer(s_result.attacker) && isalive(s_result.attacker)) { if(isdefined(s_result.attacker.var_7e008e0c) && s_result.attacker.var_7e008e0c > 0) { n_points = 10 * s_result.attacker.var_7e008e0c; } else { n_points = 10; } s_result.attacker zm_score::add_to_player_score(n_points); } self thread scene::play("Shot 1"); a_ents[#"arm_grasp"].var_ead5d884 = 0; var_44ec6b44 notify(#"hash_4a3551167bd870c2"); break; } level waittill(#"between_round_over"); self.t_arm setvisibletoall(); } /* Name: function_1abf5396 Namespace: zm_escape_util Checksum: 0xA0461115 Offset: 0x10E0 Size: 0x130 Parameters: 1 Flags: Linked */ function function_1abf5396(var_cba19e17) { self endon(#"death", #"hash_4a3551167bd870c2"); while(true) { waitresult = undefined; waitresult = self waittill(#"trigger"); if(isplayer(waitresult.activator) && var_cba19e17.var_ead5d884) { waitresult.activator dodamage(10, waitresult.activator.origin); waitresult.activator clientfield::increment_to_player("" + #"hash_257c215ab25a21c5"); waitresult.activator playsoundtoplayer(#"hash_75318bcffca7ff06", waitresult.activator); wait(4); } wait(0.1); } } /* Name: function_b5ac159d Namespace: zm_escape_util Checksum: 0x3C155AA6 Offset: 0x1218 Size: 0xB0 Parameters: 0 Flags: Linked */ function function_b5ac159d() { self.t_arm = spawn("trigger_radius_new", self.origin, 0, 256, 96); while(true) { s_result = undefined; s_result = self.t_arm waittill(#"trigger"); if(isplayer(s_result.activator)) { self thread scene::init(); self.t_arm setinvisibletoall(); } } } /* Name: function_8164716a Namespace: zm_escape_util Checksum: 0xEC408E31 Offset: 0x12D0 Size: 0x184 Parameters: 0 Flags: Linked */ function function_8164716a() { level endon(#"hash_7039457b1cc827de"); while(!level flag::get(#"hash_7039457b1cc827de")) { var_5601237b = zm_crafting::function_31d883d7(); foreach(s_blueprint in var_5601237b) { if(s_blueprint.var_54a97edd == getweapon(#"zhield_spectral_dw")) { level flag::set(#"hash_7039457b1cc827de"); break; } } if(zm_items::player_has(level.players[0], zm_crafting::get_component(#"hash_1e5657f6a6f09389"))) { level flag::set(#"hash_7039457b1cc827de"); break; } wait(1); } } /* Name: function_2def6c82 Namespace: zm_escape_util Checksum: 0x33B6A571 Offset: 0x1460 Size: 0xE0 Parameters: 0 Flags: Linked */ function function_2def6c82() { a_mdl_parts = getitemarray(); foreach(mdl_part in a_mdl_parts) { if(mdl_part.item == getweapon(#"hash_1e5656f6a6f091d6")) { mdl_part clientfield::set("" + #"hash_76662556681a502c", 1); } } } /* Name: function_6a1500f1 Namespace: zm_escape_util Checksum: 0xA964CCA6 Offset: 0x1548 Size: 0x37A Parameters: 0 Flags: Linked */ function function_6a1500f1() { level endon(#"hash_40cd2e6f2c496d75"); self endon(#"disconnect"); a_bad_zones = []; a_bad_zones[0] = "zone_model_industries"; a_bad_zones[1] = "zone_studio"; a_bad_zones[2] = "zone_citadel_stairs"; a_bad_zones[3] = "cellblock_shower"; a_bad_zones[4] = "zone_citadel"; a_bad_zones[5] = "zone_infirmary"; a_bad_zones[6] = "zone_infirmary_roof"; a_bad_zones[7] = "zone_citadel_shower"; level flag::wait_till("start_zombie_round_logic"); var_f3b29ae8 = 0; while(true) { wait(randomfloatrange(1, 20)); for(i = 0; i < 2; i++) { if(isdefined(self function_3477b4e6(a_bad_zones)) && self function_3477b4e6(a_bad_zones)) { self.var_3643da89 = 1; self util::set_lighting_state(math::clamp(level.lighting_state + 1, 1, 3)); exploder::exploder("bx_lightning_setup"); } var_cd6bd640 = randomintrange(1, 6); if(var_cd6bd640 === var_f3b29ae8) { var_cd6bd640 = math::clamp(var_cd6bd640 + 1, 1, 6); } var_f3b29ae8 = var_cd6bd640; exploder::exploder("fxexp_script_lightning_0" + var_cd6bd640); level thread function_2d4f5b73(); if(i == 0) { wait(randomfloatrange(0.3, 0.8)); } else { wait(randomfloatrange(0.2, 0.5)); } if(isdefined(self.var_3643da89) && self.var_3643da89) { self util::set_lighting_state(level.lighting_state); self.var_3643da89 = undefined; exploder::stop_exploder("bx_lightning_setup"); } exploder::stop_exploder("fxexp_script_lightning_0" + var_cd6bd640); if(i == 0) { wait(randomfloatrange(0.3, 0.5)); } } } } /* Name: function_2d4f5b73 Namespace: zm_escape_util Checksum: 0x80BD689E Offset: 0x18D0 Size: 0x76 Parameters: 0 Flags: Linked */ function function_2d4f5b73() { if(!isdefined(level.var_4b695095)) { level.var_4b695095 = 0; } if(!level.var_4b695095) { level.var_4b695095 = 1; playsoundatposition("amb_thunder_strike_script", (6559, 17376, 3893)); wait(3); level.var_4b695095 = 0; } } /* Name: function_3477b4e6 Namespace: zm_escape_util Checksum: 0x8DEADA7 Offset: 0x1950 Size: 0x4E Parameters: 1 Flags: Linked */ function function_3477b4e6(a_bad_zones) { str_zone = self zm_zonemgr::get_player_zone(); if(isinarray(a_bad_zones, str_zone)) { return false; } return true; } /* Name: function_a8024c77 Namespace: zm_escape_util Checksum: 0xB28185AB Offset: 0x19A8 Size: 0xE0 Parameters: 0 Flags: Linked */ function function_a8024c77() { var_8e8b6c9b = getentarray("afterlife_shock_box", "targetname"); foreach(var_da5e0bea in var_8e8b6c9b) { if(!zm_utility::is_standard()) { var_da5e0bea.var_91e24690 = 1; var_da5e0bea thread function_dde2edd8(); continue; } var_da5e0bea thread function_ad6125f0(); } } /* Name: function_c2237c03 Namespace: zm_escape_util Checksum: 0x8053AAD6 Offset: 0x1A90 Size: 0x4C Parameters: 0 Flags: Linked */ function function_c2237c03() { self setmodel(#"hash_233df8109c680010"); self thread scene::play(#"p8_fxanim_zm_esc_shockbox_bundle", "Activated", self); } /* Name: function_3ef2d2c6 Namespace: zm_escape_util Checksum: 0xB4824383 Offset: 0x1AE8 Size: 0x4C Parameters: 0 Flags: Linked */ function function_3ef2d2c6() { self setmodel(#"p8_fxanim_zm_esc_shockbox_mod"); self thread scene::play(#"p8_fxanim_zm_esc_shockbox_bundle", "Desactivated", self); } /* Name: function_ad6125f0 Namespace: zm_escape_util Checksum: 0x37764462 Offset: 0x1B40 Size: 0x44 Parameters: 0 Flags: Linked */ function function_ad6125f0() { self setmodel(#"p8_fxanim_zm_esc_shockbox_damaged_mod"); self thread scene::play(#"p8_fxanim_zm_esc_shockbox_damaged_bundle", self); } /* Name: function_dde2edd8 Namespace: zm_escape_util Checksum: 0x2B5A5950 Offset: 0x1B90 Size: 0x162 Parameters: 0 Flags: Linked */ function function_dde2edd8() { self endon(#"hash_7f8e7011812dff48"); while(isdefined(self.var_91e24690) && self.var_91e24690) { s_info = undefined; s_info = self waittill(#"blast_attack"); if(self.script_string == "crane_shock_box") { level.var_a29d2d8 = s_info.e_player; } if(isdefined(self.var_8dfa1155) && self.var_8dfa1155) { continue; } self function_c2237c03(); self notify(#"hash_7e1d78666f0be68b", {#e_player:s_info.e_player}); if(isdefined(self.var_8e350723) && self.var_8e350723) { self waittilltimeout(10, #"turn_off"); } else { self waittill(#"turn_off"); } self function_3ef2d2c6(); self notify(#"hash_57de930eb121052f"); } } /* Name: function_d89227a0 Namespace: zm_escape_util Checksum: 0x482DCF72 Offset: 0x1D00 Size: 0x1BE Parameters: 2 Flags: Linked */ function function_d89227a0(ent_name, message) { a_ents = getentarray(ent_name, "targetname"); foreach(ent in a_ents) { if(isdefined(ent) && isdefined(ent.bundle)) { ent thread scene::play(ent.bundle, "OFF", ent); waitframe(1); } } level flag::wait_till(message); a_ents = getentarray(ent_name, "targetname"); foreach(ent in a_ents) { if(isdefined(ent) && isdefined(ent.bundle)) { ent thread scene::play(ent.bundle, "ON", ent); waitframe(1); } } } /* Name: function_34b291c3 Namespace: zm_escape_util Checksum: 0x4B660FC0 Offset: 0x1EC8 Size: 0x2A2 Parameters: 1 Flags: Linked */ function function_34b291c3(e_player) { var_1ddd5d18 = array("zone_cafeteria_end", "zone_cafeteria", "zone_cellblock_east", "zone_cellblock_entrance", "zone_start", "zone_library", "zone_cellblock_west", "zone_broadway_floor_2", "zone_cellblock_west_barber", "zone_cellblock_west_warden"); if(level flag::get("gondola_doors_moving") || level flag::get("gondola_in_motion") && e_player zm_escape_travel::function_9a8ab327() && !self zm_escape_travel::function_9a8ab327()) { return false; } if(level flag::get("gondola_doors_moving") || level flag::get("gondola_in_motion") && !e_player zm_escape_travel::function_9a8ab327() && self zm_escape_travel::function_9a8ab327()) { return false; } if(isalive(level.var_7b71cdb7) && (isdefined(level.var_7b71cdb7.b_is_visible) && level.var_7b71cdb7.b_is_visible)) { str_zone = e_player zm_zonemgr::get_player_zone(); if(isdefined(str_zone) && array::contains(var_1ddd5d18, str_zone)) { if(self.archetype === #"zombie") { if(e_player === level.var_7b71cdb7) { return true; } return false; } if(self.archetype === #"zombie_dog" || self.archetype === #"brutus") { if(e_player === level.var_7b71cdb7) { return false; } return true; } return true; } return true; } return true; } /* Name: function_cd3a65e0 Namespace: zm_escape_util Checksum: 0x4C33BA87 Offset: 0x2178 Size: 0x282 Parameters: 0 Flags: Linked */ function function_cd3a65e0() { switch(level.dog_round_count) { case 2: { level.next_dog_round = level.round_number + function_21a3a673(5, 7); zm_round_spawning::function_376e51ef(#"zombie_dog", level.next_dog_round + 1); break; } case 3: { level.next_dog_round = level.round_number + function_21a3a673(6, 8); break; } case 4: { level.next_dog_round = level.round_number + function_21a3a673(7, 9); break; } default: { level.next_dog_round = level.round_number + function_21a3a673(8, 10); break; } } foreach(e_player in util::get_active_players()) { if(e_player flag::exists(#"hash_120fbb364796cd32") && e_player flag::exists(#"hash_11ab20934759ebc3") && e_player flag::get(#"hash_120fbb364796cd32") && !e_player flag::get(#"hash_11ab20934759ebc3")) { level.next_dog_round = level.round_number + function_21a3a673(5, 7); } } } /* Name: dog_spawn_func Namespace: zm_escape_util Checksum: 0xC6703AC8 Offset: 0x2408 Size: 0x55A Parameters: 0 Flags: None */ function dog_spawn_func() { s_spawn_loc = undefined; target = zombie_dog_util::function_a5abd591(); if(!isdefined(target)) { return undefined; } if(level.zm_loc_types[#"dog_location"].size > 0) { zone_tag = target zm_zonemgr::get_player_zone(); if(!isdefined(zone_tag)) { return undefined; } target_zone = level.zones[zone_tag]; adj_zone_names = getarraykeys(target_zone.adjacent_zones); var_2057a8c1 = array(target_zone.name); foreach(zone_name in adj_zone_names) { if(target_zone.adjacent_zones[zone_name].is_connected) { if(!isdefined(var_2057a8c1)) { var_2057a8c1 = []; } else if(!isarray(var_2057a8c1)) { var_2057a8c1 = array(var_2057a8c1); } var_2057a8c1[var_2057a8c1.size] = level.zones[zone_name].name; } } var_905a9429 = []; var_51fb0ec7 = []; players = getplayers(); foreach(loc in level.zm_loc_types[#"dog_location"]) { if(array::contains(var_2057a8c1, loc.zone_name)) { spawn_list = 0; foreach(player in players) { if(isdefined(player.am_i_valid) && player.am_i_valid) { sqr_dist = distancesquared(loc.origin, player.origin); if(sqr_dist < 9000000) { if(sqr_dist > 1000000 && spawn_list != 2) { spawn_list = 1; continue; } if(sqr_dist > 250000) { spawn_list = 2; continue; } spawn_list = 0; break; } } } if(spawn_list == 1) { if(!isdefined(var_905a9429)) { var_905a9429 = []; } else if(!isarray(var_905a9429)) { var_905a9429 = array(var_905a9429); } var_905a9429[var_905a9429.size] = loc; continue; } if(spawn_list == 2) { if(!isdefined(var_51fb0ec7)) { var_51fb0ec7 = []; } else if(!isarray(var_51fb0ec7)) { var_51fb0ec7 = array(var_51fb0ec7); } var_51fb0ec7[var_51fb0ec7.size] = loc; } } } if(var_905a9429.size < 3) { foreach(loc in var_51fb0ec7) { if(!isdefined(var_905a9429)) { var_905a9429 = []; } else if(!isarray(var_905a9429)) { var_905a9429 = array(var_905a9429); } var_905a9429[var_905a9429.size] = loc; } } s_spawn_loc = array::random(var_905a9429); } return s_spawn_loc; } /* Name: function_e270dfe4 Namespace: zm_escape_util Checksum: 0xA86CD061 Offset: 0x2970 Size: 0x22 Parameters: 0 Flags: Linked */ function function_e270dfe4() { if(isdefined(self.var_16735873) && self.var_16735873) { return 0; } return undefined; } /* Name: make_wobble Namespace: zm_escape_util Checksum: 0x1AE43E92 Offset: 0x29A0 Size: 0x12C Parameters: 0 Flags: Linked */ function make_wobble() { waittime = randomfloatrange(2.5, 5); yaw = randomint(360); if(yaw > 300) { yaw = 300; } else if(yaw < 60) { yaw = 60; } yaw = self.angles[1] + yaw; new_angles = (-60 + randomint(120), yaw, -45 + randomint(90)); self rotateto(new_angles, waittime, waittime * 0.5, waittime * 0.5); wait(randomfloat(waittime - 0.1)); } /* Name: function_ba62dc81 Namespace: zm_escape_util Checksum: 0x8A80B7DA Offset: 0x2AD8 Size: 0x60 Parameters: 0 Flags: Linked, Private */ function private function_ba62dc81() { if(isdefined(level.e_gondola) && isdefined(level.e_gondola.t_ride) && self istouching(level.e_gondola.t_ride)) { return false; } return true; } /* Name: function_2f9d355c Namespace: zm_escape_util Checksum: 0x6136E4B Offset: 0x2B40 Size: 0x1B0 Parameters: 0 Flags: Linked */ function function_2f9d355c() { foreach(e_player in level.players) { if(e_player inlaststand()) { e_player reviveplayer(); e_player notify(#"stop_revive_trigger"); if(isdefined(e_player.revivetrigger)) { e_player.revivetrigger delete(); e_player.revivetrigger = undefined; } e_player allowjump(1); e_player val::reset(#"laststand", "ignoreme"); e_player.laststand = undefined; e_player clientfield::set("zmbLastStand", 0); e_player notify(#"player_revived", {#reviver:self}); continue; } if(e_player util::is_spectating()) { e_player thread zm_player::spectator_respawn_player(); } } } /* Name: function_37aed203 Namespace: zm_escape_util Checksum: 0xA2B0BB77 Offset: 0x2CF8 Size: 0xDC Parameters: 2 Flags: Linked */ function function_37aed203(var_f1404f73, b_use_spawn_fx = 1) { var_f1404f73.var_db8b3627 = 1; if(b_use_spawn_fx) { var_f1404f73 clientfield::set("brutus_spawn_clientfield", 0); } waitframe(1); var_61a5b0ea = struct::get("s_teleport_br_kill"); var_f1404f73 forceteleport(var_61a5b0ea.origin); wait(0.1); if(isalive(var_f1404f73)) { var_f1404f73 kill(); } } /* Name: function_67710e66 Namespace: zm_escape_util Checksum: 0xF21D51A Offset: 0x2DE0 Size: 0x17C Parameters: 1 Flags: Linked */ function function_67710e66(b_enable = 0) { if(!b_enable) { level zm_audio::function_6191af93(#"brutus", #"react", "", ""); level zm_audio::function_6191af93(#"brutus", #"helm_off", "", ""); level zm_audio::function_6191af93(#"brutus", #"smoke_react", "", ""); } else { level zm_audio::function_e1666976(#"brutus", #"react"); level zm_audio::function_e1666976(#"brutus", #"helm_off"); level zm_audio::function_e1666976(#"brutus", #"smoke_react"); } } /* Name: function_5d3c7c04 Namespace: zm_escape_util Checksum: 0x280C7A2B Offset: 0x2F68 Size: 0x160 Parameters: 0 Flags: Linked, Private */ function private function_5d3c7c04() { while(true) { s_result = undefined; s_result = level waittill(#"brutus_locked", #"unlock_purchased"); if(s_result.s_stub.targetname !== "crafting_trigger") { continue; } if(s_result._notify == #"brutus_locked") { var_89ddd572 = util::spawn_model("tag_origin", s_result.s_stub.origin, s_result.s_stub.angles); var_89ddd572 clientfield::set("" + #"hash_59be891b288663cc", 1); } else if(isdefined(var_89ddd572)) { var_89ddd572 clientfield::set("" + #"hash_59be891b288663cc", 0); var_89ddd572 delete(); } } }
412
0.860568
1
0.860568
game-dev
MEDIA
0.842824
game-dev
0.811446
1
0.811446
NexusForever/NexusForever
3,051
Source/NexusForever.Game/Entity/Appearance.cs
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using NexusForever.Database.Character; using NexusForever.Database.Character.Model; using NexusForever.Game.Abstract.Entity; using NexusForever.Game.Static.Entity; namespace NexusForever.Game.Entity { public class Appearance : IAppearance { [Flags] public enum AppearanceSaveMask { None = 0x0000, Create = 0x0001, Modify = 0x0002, Delete = 0x0004 } public ulong Owner { get; } public ItemSlot ItemSlot { get; } public ushort DisplayId { get => displayId; set { if (displayId != value) { displayId = value; saveMask |= AppearanceSaveMask.Modify; } } } private ushort displayId; public bool PendingDelete => (saveMask & AppearanceSaveMask.Delete) != 0; private AppearanceSaveMask saveMask; /// <summary> /// Create a new <see cref="IAppearance"/> from database model. /// </summary> public Appearance(CharacterAppearanceModel model) { Owner = model.Id; ItemSlot = (ItemSlot)model.Slot; displayId = model.DisplayId; saveMask = AppearanceSaveMask.None; } /// <summary> /// Create a new <see cref="IAppearance"/> from supplied data. /// </summary> public Appearance(ulong characterId, ItemSlot itemSlot, ushort displayId) { Owner = characterId; ItemSlot = itemSlot; this.displayId = displayId; saveMask = AppearanceSaveMask.Create; } public void Save(CharacterContext context) { if (saveMask == AppearanceSaveMask.None) return; var model = new CharacterAppearanceModel { Id = Owner, Slot = (byte)ItemSlot }; EntityEntry<CharacterAppearanceModel> entity = context.Attach(model); if ((saveMask & AppearanceSaveMask.Create) != 0) { model.DisplayId = DisplayId; context.Add(model); } else if ((saveMask & AppearanceSaveMask.Delete) != 0) { context.Entry(model).State = EntityState.Deleted; } else if ((saveMask & AppearanceSaveMask.Modify) != 0) { model.DisplayId = DisplayId; entity.Property(e => e.DisplayId).IsModified = true; } saveMask = AppearanceSaveMask.None; } public void Delete() { if ((saveMask & AppearanceSaveMask.Create) != 0) saveMask = AppearanceSaveMask.None; else saveMask = AppearanceSaveMask.Delete; } } }
412
0.53473
1
0.53473
game-dev
MEDIA
0.967164
game-dev
0.857509
1
0.857509
marqdevx/mm-cs2-scrim
306,550
protobuf/generated/demo.pb.h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: demo.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_demo_2eproto #define GOOGLE_PROTOBUF_INCLUDED_demo_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3021000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3021008 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_bases.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/generated_enum_reflection.h> #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_demo_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_demo_2eproto { static const uint32_t offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_demo_2eproto; class CDemoAnimationData; struct CDemoAnimationDataDefaultTypeInternal; extern CDemoAnimationDataDefaultTypeInternal _CDemoAnimationData_default_instance_; class CDemoClassInfo; struct CDemoClassInfoDefaultTypeInternal; extern CDemoClassInfoDefaultTypeInternal _CDemoClassInfo_default_instance_; class CDemoClassInfo_class_t; struct CDemoClassInfo_class_tDefaultTypeInternal; extern CDemoClassInfo_class_tDefaultTypeInternal _CDemoClassInfo_class_t_default_instance_; class CDemoConsoleCmd; struct CDemoConsoleCmdDefaultTypeInternal; extern CDemoConsoleCmdDefaultTypeInternal _CDemoConsoleCmd_default_instance_; class CDemoCustomData; struct CDemoCustomDataDefaultTypeInternal; extern CDemoCustomDataDefaultTypeInternal _CDemoCustomData_default_instance_; class CDemoCustomDataCallbacks; struct CDemoCustomDataCallbacksDefaultTypeInternal; extern CDemoCustomDataCallbacksDefaultTypeInternal _CDemoCustomDataCallbacks_default_instance_; class CDemoFileHeader; struct CDemoFileHeaderDefaultTypeInternal; extern CDemoFileHeaderDefaultTypeInternal _CDemoFileHeader_default_instance_; class CDemoFileInfo; struct CDemoFileInfoDefaultTypeInternal; extern CDemoFileInfoDefaultTypeInternal _CDemoFileInfo_default_instance_; class CDemoFullPacket; struct CDemoFullPacketDefaultTypeInternal; extern CDemoFullPacketDefaultTypeInternal _CDemoFullPacket_default_instance_; class CDemoPacket; struct CDemoPacketDefaultTypeInternal; extern CDemoPacketDefaultTypeInternal _CDemoPacket_default_instance_; class CDemoSaveGame; struct CDemoSaveGameDefaultTypeInternal; extern CDemoSaveGameDefaultTypeInternal _CDemoSaveGame_default_instance_; class CDemoSendTables; struct CDemoSendTablesDefaultTypeInternal; extern CDemoSendTablesDefaultTypeInternal _CDemoSendTables_default_instance_; class CDemoSpawnGroups; struct CDemoSpawnGroupsDefaultTypeInternal; extern CDemoSpawnGroupsDefaultTypeInternal _CDemoSpawnGroups_default_instance_; class CDemoStop; struct CDemoStopDefaultTypeInternal; extern CDemoStopDefaultTypeInternal _CDemoStop_default_instance_; class CDemoStringTables; struct CDemoStringTablesDefaultTypeInternal; extern CDemoStringTablesDefaultTypeInternal _CDemoStringTables_default_instance_; class CDemoStringTables_items_t; struct CDemoStringTables_items_tDefaultTypeInternal; extern CDemoStringTables_items_tDefaultTypeInternal _CDemoStringTables_items_t_default_instance_; class CDemoStringTables_table_t; struct CDemoStringTables_table_tDefaultTypeInternal; extern CDemoStringTables_table_tDefaultTypeInternal _CDemoStringTables_table_t_default_instance_; class CDemoSyncTick; struct CDemoSyncTickDefaultTypeInternal; extern CDemoSyncTickDefaultTypeInternal _CDemoSyncTick_default_instance_; class CDemoUserCmd; struct CDemoUserCmdDefaultTypeInternal; extern CDemoUserCmdDefaultTypeInternal _CDemoUserCmd_default_instance_; class CGameInfo; struct CGameInfoDefaultTypeInternal; extern CGameInfoDefaultTypeInternal _CGameInfo_default_instance_; class CGameInfo_CDotaGameInfo; struct CGameInfo_CDotaGameInfoDefaultTypeInternal; extern CGameInfo_CDotaGameInfoDefaultTypeInternal _CGameInfo_CDotaGameInfo_default_instance_; class CGameInfo_CDotaGameInfo_CHeroSelectEvent; struct CGameInfo_CDotaGameInfo_CHeroSelectEventDefaultTypeInternal; extern CGameInfo_CDotaGameInfo_CHeroSelectEventDefaultTypeInternal _CGameInfo_CDotaGameInfo_CHeroSelectEvent_default_instance_; class CGameInfo_CDotaGameInfo_CPlayerInfo; struct CGameInfo_CDotaGameInfo_CPlayerInfoDefaultTypeInternal; extern CGameInfo_CDotaGameInfo_CPlayerInfoDefaultTypeInternal _CGameInfo_CDotaGameInfo_CPlayerInfo_default_instance_; PROTOBUF_NAMESPACE_OPEN template<> ::CDemoAnimationData* Arena::CreateMaybeMessage<::CDemoAnimationData>(Arena*); template<> ::CDemoClassInfo* Arena::CreateMaybeMessage<::CDemoClassInfo>(Arena*); template<> ::CDemoClassInfo_class_t* Arena::CreateMaybeMessage<::CDemoClassInfo_class_t>(Arena*); template<> ::CDemoConsoleCmd* Arena::CreateMaybeMessage<::CDemoConsoleCmd>(Arena*); template<> ::CDemoCustomData* Arena::CreateMaybeMessage<::CDemoCustomData>(Arena*); template<> ::CDemoCustomDataCallbacks* Arena::CreateMaybeMessage<::CDemoCustomDataCallbacks>(Arena*); template<> ::CDemoFileHeader* Arena::CreateMaybeMessage<::CDemoFileHeader>(Arena*); template<> ::CDemoFileInfo* Arena::CreateMaybeMessage<::CDemoFileInfo>(Arena*); template<> ::CDemoFullPacket* Arena::CreateMaybeMessage<::CDemoFullPacket>(Arena*); template<> ::CDemoPacket* Arena::CreateMaybeMessage<::CDemoPacket>(Arena*); template<> ::CDemoSaveGame* Arena::CreateMaybeMessage<::CDemoSaveGame>(Arena*); template<> ::CDemoSendTables* Arena::CreateMaybeMessage<::CDemoSendTables>(Arena*); template<> ::CDemoSpawnGroups* Arena::CreateMaybeMessage<::CDemoSpawnGroups>(Arena*); template<> ::CDemoStop* Arena::CreateMaybeMessage<::CDemoStop>(Arena*); template<> ::CDemoStringTables* Arena::CreateMaybeMessage<::CDemoStringTables>(Arena*); template<> ::CDemoStringTables_items_t* Arena::CreateMaybeMessage<::CDemoStringTables_items_t>(Arena*); template<> ::CDemoStringTables_table_t* Arena::CreateMaybeMessage<::CDemoStringTables_table_t>(Arena*); template<> ::CDemoSyncTick* Arena::CreateMaybeMessage<::CDemoSyncTick>(Arena*); template<> ::CDemoUserCmd* Arena::CreateMaybeMessage<::CDemoUserCmd>(Arena*); template<> ::CGameInfo* Arena::CreateMaybeMessage<::CGameInfo>(Arena*); template<> ::CGameInfo_CDotaGameInfo* Arena::CreateMaybeMessage<::CGameInfo_CDotaGameInfo>(Arena*); template<> ::CGameInfo_CDotaGameInfo_CHeroSelectEvent* Arena::CreateMaybeMessage<::CGameInfo_CDotaGameInfo_CHeroSelectEvent>(Arena*); template<> ::CGameInfo_CDotaGameInfo_CPlayerInfo* Arena::CreateMaybeMessage<::CGameInfo_CDotaGameInfo_CPlayerInfo>(Arena*); PROTOBUF_NAMESPACE_CLOSE enum EDemoCommands : int { DEM_Error = -1, DEM_Stop = 0, DEM_FileHeader = 1, DEM_FileInfo = 2, DEM_SyncTick = 3, DEM_SendTables = 4, DEM_ClassInfo = 5, DEM_StringTables = 6, DEM_Packet = 7, DEM_SignonPacket = 8, DEM_ConsoleCmd = 9, DEM_CustomData = 10, DEM_CustomDataCallbacks = 11, DEM_UserCmd = 12, DEM_FullPacket = 13, DEM_SaveGame = 14, DEM_SpawnGroups = 15, DEM_AnimationData = 16, DEM_Max = 17, DEM_IsCompressed = 64 }; bool EDemoCommands_IsValid(int value); constexpr EDemoCommands EDemoCommands_MIN = DEM_Error; constexpr EDemoCommands EDemoCommands_MAX = DEM_IsCompressed; constexpr int EDemoCommands_ARRAYSIZE = EDemoCommands_MAX + 1; const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* EDemoCommands_descriptor(); template<typename T> inline const std::string& EDemoCommands_Name(T enum_t_value) { static_assert(::std::is_same<T, EDemoCommands>::value || ::std::is_integral<T>::value, "Incorrect type passed to function EDemoCommands_Name."); return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( EDemoCommands_descriptor(), enum_t_value); } inline bool EDemoCommands_Parse( ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, EDemoCommands* value) { return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<EDemoCommands>( EDemoCommands_descriptor(), name, value); } // =================================================================== class CDemoFileHeader final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoFileHeader) */ { public: inline CDemoFileHeader() : CDemoFileHeader(nullptr) {} ~CDemoFileHeader() override; explicit PROTOBUF_CONSTEXPR CDemoFileHeader(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoFileHeader(const CDemoFileHeader& from); CDemoFileHeader(CDemoFileHeader&& from) noexcept : CDemoFileHeader() { *this = ::std::move(from); } inline CDemoFileHeader& operator=(const CDemoFileHeader& from) { CopyFrom(from); return *this; } inline CDemoFileHeader& operator=(CDemoFileHeader&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoFileHeader& default_instance() { return *internal_default_instance(); } static inline const CDemoFileHeader* internal_default_instance() { return reinterpret_cast<const CDemoFileHeader*>( &_CDemoFileHeader_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(CDemoFileHeader& a, CDemoFileHeader& b) { a.Swap(&b); } inline void Swap(CDemoFileHeader* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoFileHeader* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoFileHeader* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoFileHeader>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoFileHeader& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoFileHeader& from) { CDemoFileHeader::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoFileHeader* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoFileHeader"; } protected: explicit CDemoFileHeader(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kDemoFileStampFieldNumber = 1, kServerNameFieldNumber = 3, kClientNameFieldNumber = 4, kMapNameFieldNumber = 5, kGameDirectoryFieldNumber = 6, kAddonsFieldNumber = 10, kDemoVersionNameFieldNumber = 11, kDemoVersionGuidFieldNumber = 12, kGameFieldNumber = 14, kNetworkProtocolFieldNumber = 2, kFullpacketsVersionFieldNumber = 7, kAllowClientsideEntitiesFieldNumber = 8, kAllowClientsideParticlesFieldNumber = 9, kBuildNumFieldNumber = 13, }; // required string demo_file_stamp = 1; bool has_demo_file_stamp() const; private: bool _internal_has_demo_file_stamp() const; public: void clear_demo_file_stamp(); const std::string& demo_file_stamp() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_demo_file_stamp(ArgT0&& arg0, ArgT... args); std::string* mutable_demo_file_stamp(); PROTOBUF_NODISCARD std::string* release_demo_file_stamp(); void set_allocated_demo_file_stamp(std::string* demo_file_stamp); private: const std::string& _internal_demo_file_stamp() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_demo_file_stamp(const std::string& value); std::string* _internal_mutable_demo_file_stamp(); public: // optional string server_name = 3; bool has_server_name() const; private: bool _internal_has_server_name() const; public: void clear_server_name(); const std::string& server_name() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_server_name(ArgT0&& arg0, ArgT... args); std::string* mutable_server_name(); PROTOBUF_NODISCARD std::string* release_server_name(); void set_allocated_server_name(std::string* server_name); private: const std::string& _internal_server_name() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_server_name(const std::string& value); std::string* _internal_mutable_server_name(); public: // optional string client_name = 4; bool has_client_name() const; private: bool _internal_has_client_name() const; public: void clear_client_name(); const std::string& client_name() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_client_name(ArgT0&& arg0, ArgT... args); std::string* mutable_client_name(); PROTOBUF_NODISCARD std::string* release_client_name(); void set_allocated_client_name(std::string* client_name); private: const std::string& _internal_client_name() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_client_name(const std::string& value); std::string* _internal_mutable_client_name(); public: // optional string map_name = 5; bool has_map_name() const; private: bool _internal_has_map_name() const; public: void clear_map_name(); const std::string& map_name() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_map_name(ArgT0&& arg0, ArgT... args); std::string* mutable_map_name(); PROTOBUF_NODISCARD std::string* release_map_name(); void set_allocated_map_name(std::string* map_name); private: const std::string& _internal_map_name() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_map_name(const std::string& value); std::string* _internal_mutable_map_name(); public: // optional string game_directory = 6; bool has_game_directory() const; private: bool _internal_has_game_directory() const; public: void clear_game_directory(); const std::string& game_directory() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_game_directory(ArgT0&& arg0, ArgT... args); std::string* mutable_game_directory(); PROTOBUF_NODISCARD std::string* release_game_directory(); void set_allocated_game_directory(std::string* game_directory); private: const std::string& _internal_game_directory() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_game_directory(const std::string& value); std::string* _internal_mutable_game_directory(); public: // optional string addons = 10; bool has_addons() const; private: bool _internal_has_addons() const; public: void clear_addons(); const std::string& addons() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_addons(ArgT0&& arg0, ArgT... args); std::string* mutable_addons(); PROTOBUF_NODISCARD std::string* release_addons(); void set_allocated_addons(std::string* addons); private: const std::string& _internal_addons() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_addons(const std::string& value); std::string* _internal_mutable_addons(); public: // optional string demo_version_name = 11; bool has_demo_version_name() const; private: bool _internal_has_demo_version_name() const; public: void clear_demo_version_name(); const std::string& demo_version_name() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_demo_version_name(ArgT0&& arg0, ArgT... args); std::string* mutable_demo_version_name(); PROTOBUF_NODISCARD std::string* release_demo_version_name(); void set_allocated_demo_version_name(std::string* demo_version_name); private: const std::string& _internal_demo_version_name() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_demo_version_name(const std::string& value); std::string* _internal_mutable_demo_version_name(); public: // optional string demo_version_guid = 12; bool has_demo_version_guid() const; private: bool _internal_has_demo_version_guid() const; public: void clear_demo_version_guid(); const std::string& demo_version_guid() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_demo_version_guid(ArgT0&& arg0, ArgT... args); std::string* mutable_demo_version_guid(); PROTOBUF_NODISCARD std::string* release_demo_version_guid(); void set_allocated_demo_version_guid(std::string* demo_version_guid); private: const std::string& _internal_demo_version_guid() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_demo_version_guid(const std::string& value); std::string* _internal_mutable_demo_version_guid(); public: // optional string game = 14; bool has_game() const; private: bool _internal_has_game() const; public: void clear_game(); const std::string& game() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_game(ArgT0&& arg0, ArgT... args); std::string* mutable_game(); PROTOBUF_NODISCARD std::string* release_game(); void set_allocated_game(std::string* game); private: const std::string& _internal_game() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_game(const std::string& value); std::string* _internal_mutable_game(); public: // optional int32 network_protocol = 2; bool has_network_protocol() const; private: bool _internal_has_network_protocol() const; public: void clear_network_protocol(); int32_t network_protocol() const; void set_network_protocol(int32_t value); private: int32_t _internal_network_protocol() const; void _internal_set_network_protocol(int32_t value); public: // optional int32 fullpackets_version = 7; bool has_fullpackets_version() const; private: bool _internal_has_fullpackets_version() const; public: void clear_fullpackets_version(); int32_t fullpackets_version() const; void set_fullpackets_version(int32_t value); private: int32_t _internal_fullpackets_version() const; void _internal_set_fullpackets_version(int32_t value); public: // optional bool allow_clientside_entities = 8; bool has_allow_clientside_entities() const; private: bool _internal_has_allow_clientside_entities() const; public: void clear_allow_clientside_entities(); bool allow_clientside_entities() const; void set_allow_clientside_entities(bool value); private: bool _internal_allow_clientside_entities() const; void _internal_set_allow_clientside_entities(bool value); public: // optional bool allow_clientside_particles = 9; bool has_allow_clientside_particles() const; private: bool _internal_has_allow_clientside_particles() const; public: void clear_allow_clientside_particles(); bool allow_clientside_particles() const; void set_allow_clientside_particles(bool value); private: bool _internal_allow_clientside_particles() const; void _internal_set_allow_clientside_particles(bool value); public: // optional int32 build_num = 13; bool has_build_num() const; private: bool _internal_has_build_num() const; public: void clear_build_num(); int32_t build_num() const; void set_build_num(int32_t value); private: int32_t _internal_build_num() const; void _internal_set_build_num(int32_t value); public: // @@protoc_insertion_point(class_scope:CDemoFileHeader) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr demo_file_stamp_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr server_name_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr client_name_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr map_name_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr game_directory_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr addons_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr demo_version_name_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr demo_version_guid_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr game_; int32_t network_protocol_; int32_t fullpackets_version_; bool allow_clientside_entities_; bool allow_clientside_particles_; int32_t build_num_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CGameInfo_CDotaGameInfo_CPlayerInfo final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CGameInfo.CDotaGameInfo.CPlayerInfo) */ { public: inline CGameInfo_CDotaGameInfo_CPlayerInfo() : CGameInfo_CDotaGameInfo_CPlayerInfo(nullptr) {} ~CGameInfo_CDotaGameInfo_CPlayerInfo() override; explicit PROTOBUF_CONSTEXPR CGameInfo_CDotaGameInfo_CPlayerInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CGameInfo_CDotaGameInfo_CPlayerInfo(const CGameInfo_CDotaGameInfo_CPlayerInfo& from); CGameInfo_CDotaGameInfo_CPlayerInfo(CGameInfo_CDotaGameInfo_CPlayerInfo&& from) noexcept : CGameInfo_CDotaGameInfo_CPlayerInfo() { *this = ::std::move(from); } inline CGameInfo_CDotaGameInfo_CPlayerInfo& operator=(const CGameInfo_CDotaGameInfo_CPlayerInfo& from) { CopyFrom(from); return *this; } inline CGameInfo_CDotaGameInfo_CPlayerInfo& operator=(CGameInfo_CDotaGameInfo_CPlayerInfo&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CGameInfo_CDotaGameInfo_CPlayerInfo& default_instance() { return *internal_default_instance(); } static inline const CGameInfo_CDotaGameInfo_CPlayerInfo* internal_default_instance() { return reinterpret_cast<const CGameInfo_CDotaGameInfo_CPlayerInfo*>( &_CGameInfo_CDotaGameInfo_CPlayerInfo_default_instance_); } static constexpr int kIndexInFileMessages = 1; friend void swap(CGameInfo_CDotaGameInfo_CPlayerInfo& a, CGameInfo_CDotaGameInfo_CPlayerInfo& b) { a.Swap(&b); } inline void Swap(CGameInfo_CDotaGameInfo_CPlayerInfo* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CGameInfo_CDotaGameInfo_CPlayerInfo* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CGameInfo_CDotaGameInfo_CPlayerInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CGameInfo_CDotaGameInfo_CPlayerInfo>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CGameInfo_CDotaGameInfo_CPlayerInfo& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CGameInfo_CDotaGameInfo_CPlayerInfo& from) { CGameInfo_CDotaGameInfo_CPlayerInfo::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CGameInfo_CDotaGameInfo_CPlayerInfo* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CGameInfo.CDotaGameInfo.CPlayerInfo"; } protected: explicit CGameInfo_CDotaGameInfo_CPlayerInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kHeroNameFieldNumber = 1, kPlayerNameFieldNumber = 2, kSteamidFieldNumber = 4, kIsFakeClientFieldNumber = 3, kGameTeamFieldNumber = 5, }; // optional string hero_name = 1; bool has_hero_name() const; private: bool _internal_has_hero_name() const; public: void clear_hero_name(); const std::string& hero_name() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_hero_name(ArgT0&& arg0, ArgT... args); std::string* mutable_hero_name(); PROTOBUF_NODISCARD std::string* release_hero_name(); void set_allocated_hero_name(std::string* hero_name); private: const std::string& _internal_hero_name() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_hero_name(const std::string& value); std::string* _internal_mutable_hero_name(); public: // optional string player_name = 2; bool has_player_name() const; private: bool _internal_has_player_name() const; public: void clear_player_name(); const std::string& player_name() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_player_name(ArgT0&& arg0, ArgT... args); std::string* mutable_player_name(); PROTOBUF_NODISCARD std::string* release_player_name(); void set_allocated_player_name(std::string* player_name); private: const std::string& _internal_player_name() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_player_name(const std::string& value); std::string* _internal_mutable_player_name(); public: // optional uint64 steamid = 4; bool has_steamid() const; private: bool _internal_has_steamid() const; public: void clear_steamid(); uint64_t steamid() const; void set_steamid(uint64_t value); private: uint64_t _internal_steamid() const; void _internal_set_steamid(uint64_t value); public: // optional bool is_fake_client = 3; bool has_is_fake_client() const; private: bool _internal_has_is_fake_client() const; public: void clear_is_fake_client(); bool is_fake_client() const; void set_is_fake_client(bool value); private: bool _internal_is_fake_client() const; void _internal_set_is_fake_client(bool value); public: // optional int32 game_team = 5; bool has_game_team() const; private: bool _internal_has_game_team() const; public: void clear_game_team(); int32_t game_team() const; void set_game_team(int32_t value); private: int32_t _internal_game_team() const; void _internal_set_game_team(int32_t value); public: // @@protoc_insertion_point(class_scope:CGameInfo.CDotaGameInfo.CPlayerInfo) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr hero_name_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr player_name_; uint64_t steamid_; bool is_fake_client_; int32_t game_team_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CGameInfo_CDotaGameInfo_CHeroSelectEvent final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CGameInfo.CDotaGameInfo.CHeroSelectEvent) */ { public: inline CGameInfo_CDotaGameInfo_CHeroSelectEvent() : CGameInfo_CDotaGameInfo_CHeroSelectEvent(nullptr) {} ~CGameInfo_CDotaGameInfo_CHeroSelectEvent() override; explicit PROTOBUF_CONSTEXPR CGameInfo_CDotaGameInfo_CHeroSelectEvent(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CGameInfo_CDotaGameInfo_CHeroSelectEvent(const CGameInfo_CDotaGameInfo_CHeroSelectEvent& from); CGameInfo_CDotaGameInfo_CHeroSelectEvent(CGameInfo_CDotaGameInfo_CHeroSelectEvent&& from) noexcept : CGameInfo_CDotaGameInfo_CHeroSelectEvent() { *this = ::std::move(from); } inline CGameInfo_CDotaGameInfo_CHeroSelectEvent& operator=(const CGameInfo_CDotaGameInfo_CHeroSelectEvent& from) { CopyFrom(from); return *this; } inline CGameInfo_CDotaGameInfo_CHeroSelectEvent& operator=(CGameInfo_CDotaGameInfo_CHeroSelectEvent&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CGameInfo_CDotaGameInfo_CHeroSelectEvent& default_instance() { return *internal_default_instance(); } static inline const CGameInfo_CDotaGameInfo_CHeroSelectEvent* internal_default_instance() { return reinterpret_cast<const CGameInfo_CDotaGameInfo_CHeroSelectEvent*>( &_CGameInfo_CDotaGameInfo_CHeroSelectEvent_default_instance_); } static constexpr int kIndexInFileMessages = 2; friend void swap(CGameInfo_CDotaGameInfo_CHeroSelectEvent& a, CGameInfo_CDotaGameInfo_CHeroSelectEvent& b) { a.Swap(&b); } inline void Swap(CGameInfo_CDotaGameInfo_CHeroSelectEvent* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CGameInfo_CDotaGameInfo_CHeroSelectEvent* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CGameInfo_CDotaGameInfo_CHeroSelectEvent* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CGameInfo_CDotaGameInfo_CHeroSelectEvent>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CGameInfo_CDotaGameInfo_CHeroSelectEvent& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CGameInfo_CDotaGameInfo_CHeroSelectEvent& from) { CGameInfo_CDotaGameInfo_CHeroSelectEvent::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CGameInfo_CDotaGameInfo_CHeroSelectEvent* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CGameInfo.CDotaGameInfo.CHeroSelectEvent"; } protected: explicit CGameInfo_CDotaGameInfo_CHeroSelectEvent(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kIsPickFieldNumber = 1, kTeamFieldNumber = 2, kHeroIdFieldNumber = 3, }; // optional bool is_pick = 1; bool has_is_pick() const; private: bool _internal_has_is_pick() const; public: void clear_is_pick(); bool is_pick() const; void set_is_pick(bool value); private: bool _internal_is_pick() const; void _internal_set_is_pick(bool value); public: // optional uint32 team = 2; bool has_team() const; private: bool _internal_has_team() const; public: void clear_team(); uint32_t team() const; void set_team(uint32_t value); private: uint32_t _internal_team() const; void _internal_set_team(uint32_t value); public: // optional uint32 hero_id = 3; bool has_hero_id() const; private: bool _internal_has_hero_id() const; public: void clear_hero_id(); uint32_t hero_id() const; void set_hero_id(uint32_t value); private: uint32_t _internal_hero_id() const; void _internal_set_hero_id(uint32_t value); public: // @@protoc_insertion_point(class_scope:CGameInfo.CDotaGameInfo.CHeroSelectEvent) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; bool is_pick_; uint32_t team_; uint32_t hero_id_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CGameInfo_CDotaGameInfo final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CGameInfo.CDotaGameInfo) */ { public: inline CGameInfo_CDotaGameInfo() : CGameInfo_CDotaGameInfo(nullptr) {} ~CGameInfo_CDotaGameInfo() override; explicit PROTOBUF_CONSTEXPR CGameInfo_CDotaGameInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CGameInfo_CDotaGameInfo(const CGameInfo_CDotaGameInfo& from); CGameInfo_CDotaGameInfo(CGameInfo_CDotaGameInfo&& from) noexcept : CGameInfo_CDotaGameInfo() { *this = ::std::move(from); } inline CGameInfo_CDotaGameInfo& operator=(const CGameInfo_CDotaGameInfo& from) { CopyFrom(from); return *this; } inline CGameInfo_CDotaGameInfo& operator=(CGameInfo_CDotaGameInfo&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CGameInfo_CDotaGameInfo& default_instance() { return *internal_default_instance(); } static inline const CGameInfo_CDotaGameInfo* internal_default_instance() { return reinterpret_cast<const CGameInfo_CDotaGameInfo*>( &_CGameInfo_CDotaGameInfo_default_instance_); } static constexpr int kIndexInFileMessages = 3; friend void swap(CGameInfo_CDotaGameInfo& a, CGameInfo_CDotaGameInfo& b) { a.Swap(&b); } inline void Swap(CGameInfo_CDotaGameInfo* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CGameInfo_CDotaGameInfo* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CGameInfo_CDotaGameInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CGameInfo_CDotaGameInfo>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CGameInfo_CDotaGameInfo& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CGameInfo_CDotaGameInfo& from) { CGameInfo_CDotaGameInfo::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CGameInfo_CDotaGameInfo* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CGameInfo.CDotaGameInfo"; } protected: explicit CGameInfo_CDotaGameInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- typedef CGameInfo_CDotaGameInfo_CPlayerInfo CPlayerInfo; typedef CGameInfo_CDotaGameInfo_CHeroSelectEvent CHeroSelectEvent; // accessors ------------------------------------------------------- enum : int { kPlayerInfoFieldNumber = 4, kPicksBansFieldNumber = 6, kRadiantTeamTagFieldNumber = 9, kDireTeamTagFieldNumber = 10, kMatchIdFieldNumber = 1, kGameModeFieldNumber = 2, kGameWinnerFieldNumber = 3, kLeagueidFieldNumber = 5, kRadiantTeamIdFieldNumber = 7, kDireTeamIdFieldNumber = 8, kEndTimeFieldNumber = 11, }; // repeated .CGameInfo.CDotaGameInfo.CPlayerInfo player_info = 4; int player_info_size() const; private: int _internal_player_info_size() const; public: void clear_player_info(); ::CGameInfo_CDotaGameInfo_CPlayerInfo* mutable_player_info(int index); ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CGameInfo_CDotaGameInfo_CPlayerInfo >* mutable_player_info(); private: const ::CGameInfo_CDotaGameInfo_CPlayerInfo& _internal_player_info(int index) const; ::CGameInfo_CDotaGameInfo_CPlayerInfo* _internal_add_player_info(); public: const ::CGameInfo_CDotaGameInfo_CPlayerInfo& player_info(int index) const; ::CGameInfo_CDotaGameInfo_CPlayerInfo* add_player_info(); const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CGameInfo_CDotaGameInfo_CPlayerInfo >& player_info() const; // repeated .CGameInfo.CDotaGameInfo.CHeroSelectEvent picks_bans = 6; int picks_bans_size() const; private: int _internal_picks_bans_size() const; public: void clear_picks_bans(); ::CGameInfo_CDotaGameInfo_CHeroSelectEvent* mutable_picks_bans(int index); ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CGameInfo_CDotaGameInfo_CHeroSelectEvent >* mutable_picks_bans(); private: const ::CGameInfo_CDotaGameInfo_CHeroSelectEvent& _internal_picks_bans(int index) const; ::CGameInfo_CDotaGameInfo_CHeroSelectEvent* _internal_add_picks_bans(); public: const ::CGameInfo_CDotaGameInfo_CHeroSelectEvent& picks_bans(int index) const; ::CGameInfo_CDotaGameInfo_CHeroSelectEvent* add_picks_bans(); const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CGameInfo_CDotaGameInfo_CHeroSelectEvent >& picks_bans() const; // optional string radiant_team_tag = 9; bool has_radiant_team_tag() const; private: bool _internal_has_radiant_team_tag() const; public: void clear_radiant_team_tag(); const std::string& radiant_team_tag() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_radiant_team_tag(ArgT0&& arg0, ArgT... args); std::string* mutable_radiant_team_tag(); PROTOBUF_NODISCARD std::string* release_radiant_team_tag(); void set_allocated_radiant_team_tag(std::string* radiant_team_tag); private: const std::string& _internal_radiant_team_tag() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_radiant_team_tag(const std::string& value); std::string* _internal_mutable_radiant_team_tag(); public: // optional string dire_team_tag = 10; bool has_dire_team_tag() const; private: bool _internal_has_dire_team_tag() const; public: void clear_dire_team_tag(); const std::string& dire_team_tag() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_dire_team_tag(ArgT0&& arg0, ArgT... args); std::string* mutable_dire_team_tag(); PROTOBUF_NODISCARD std::string* release_dire_team_tag(); void set_allocated_dire_team_tag(std::string* dire_team_tag); private: const std::string& _internal_dire_team_tag() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_dire_team_tag(const std::string& value); std::string* _internal_mutable_dire_team_tag(); public: // optional uint64 match_id = 1; bool has_match_id() const; private: bool _internal_has_match_id() const; public: void clear_match_id(); uint64_t match_id() const; void set_match_id(uint64_t value); private: uint64_t _internal_match_id() const; void _internal_set_match_id(uint64_t value); public: // optional int32 game_mode = 2; bool has_game_mode() const; private: bool _internal_has_game_mode() const; public: void clear_game_mode(); int32_t game_mode() const; void set_game_mode(int32_t value); private: int32_t _internal_game_mode() const; void _internal_set_game_mode(int32_t value); public: // optional int32 game_winner = 3; bool has_game_winner() const; private: bool _internal_has_game_winner() const; public: void clear_game_winner(); int32_t game_winner() const; void set_game_winner(int32_t value); private: int32_t _internal_game_winner() const; void _internal_set_game_winner(int32_t value); public: // optional uint32 leagueid = 5; bool has_leagueid() const; private: bool _internal_has_leagueid() const; public: void clear_leagueid(); uint32_t leagueid() const; void set_leagueid(uint32_t value); private: uint32_t _internal_leagueid() const; void _internal_set_leagueid(uint32_t value); public: // optional uint32 radiant_team_id = 7; bool has_radiant_team_id() const; private: bool _internal_has_radiant_team_id() const; public: void clear_radiant_team_id(); uint32_t radiant_team_id() const; void set_radiant_team_id(uint32_t value); private: uint32_t _internal_radiant_team_id() const; void _internal_set_radiant_team_id(uint32_t value); public: // optional uint32 dire_team_id = 8; bool has_dire_team_id() const; private: bool _internal_has_dire_team_id() const; public: void clear_dire_team_id(); uint32_t dire_team_id() const; void set_dire_team_id(uint32_t value); private: uint32_t _internal_dire_team_id() const; void _internal_set_dire_team_id(uint32_t value); public: // optional uint32 end_time = 11; bool has_end_time() const; private: bool _internal_has_end_time() const; public: void clear_end_time(); uint32_t end_time() const; void set_end_time(uint32_t value); private: uint32_t _internal_end_time() const; void _internal_set_end_time(uint32_t value); public: // @@protoc_insertion_point(class_scope:CGameInfo.CDotaGameInfo) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CGameInfo_CDotaGameInfo_CPlayerInfo > player_info_; ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CGameInfo_CDotaGameInfo_CHeroSelectEvent > picks_bans_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr radiant_team_tag_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr dire_team_tag_; uint64_t match_id_; int32_t game_mode_; int32_t game_winner_; uint32_t leagueid_; uint32_t radiant_team_id_; uint32_t dire_team_id_; uint32_t end_time_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CGameInfo final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CGameInfo) */ { public: inline CGameInfo() : CGameInfo(nullptr) {} ~CGameInfo() override; explicit PROTOBUF_CONSTEXPR CGameInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CGameInfo(const CGameInfo& from); CGameInfo(CGameInfo&& from) noexcept : CGameInfo() { *this = ::std::move(from); } inline CGameInfo& operator=(const CGameInfo& from) { CopyFrom(from); return *this; } inline CGameInfo& operator=(CGameInfo&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CGameInfo& default_instance() { return *internal_default_instance(); } static inline const CGameInfo* internal_default_instance() { return reinterpret_cast<const CGameInfo*>( &_CGameInfo_default_instance_); } static constexpr int kIndexInFileMessages = 4; friend void swap(CGameInfo& a, CGameInfo& b) { a.Swap(&b); } inline void Swap(CGameInfo* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CGameInfo* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CGameInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CGameInfo>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CGameInfo& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CGameInfo& from) { CGameInfo::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CGameInfo* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CGameInfo"; } protected: explicit CGameInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- typedef CGameInfo_CDotaGameInfo CDotaGameInfo; // accessors ------------------------------------------------------- enum : int { kDotaFieldNumber = 4, }; // optional .CGameInfo.CDotaGameInfo dota = 4; bool has_dota() const; private: bool _internal_has_dota() const; public: void clear_dota(); const ::CGameInfo_CDotaGameInfo& dota() const; PROTOBUF_NODISCARD ::CGameInfo_CDotaGameInfo* release_dota(); ::CGameInfo_CDotaGameInfo* mutable_dota(); void set_allocated_dota(::CGameInfo_CDotaGameInfo* dota); private: const ::CGameInfo_CDotaGameInfo& _internal_dota() const; ::CGameInfo_CDotaGameInfo* _internal_mutable_dota(); public: void unsafe_arena_set_allocated_dota( ::CGameInfo_CDotaGameInfo* dota); ::CGameInfo_CDotaGameInfo* unsafe_arena_release_dota(); // @@protoc_insertion_point(class_scope:CGameInfo) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::CGameInfo_CDotaGameInfo* dota_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoFileInfo final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoFileInfo) */ { public: inline CDemoFileInfo() : CDemoFileInfo(nullptr) {} ~CDemoFileInfo() override; explicit PROTOBUF_CONSTEXPR CDemoFileInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoFileInfo(const CDemoFileInfo& from); CDemoFileInfo(CDemoFileInfo&& from) noexcept : CDemoFileInfo() { *this = ::std::move(from); } inline CDemoFileInfo& operator=(const CDemoFileInfo& from) { CopyFrom(from); return *this; } inline CDemoFileInfo& operator=(CDemoFileInfo&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoFileInfo& default_instance() { return *internal_default_instance(); } static inline const CDemoFileInfo* internal_default_instance() { return reinterpret_cast<const CDemoFileInfo*>( &_CDemoFileInfo_default_instance_); } static constexpr int kIndexInFileMessages = 5; friend void swap(CDemoFileInfo& a, CDemoFileInfo& b) { a.Swap(&b); } inline void Swap(CDemoFileInfo* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoFileInfo* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoFileInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoFileInfo>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoFileInfo& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoFileInfo& from) { CDemoFileInfo::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoFileInfo* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoFileInfo"; } protected: explicit CDemoFileInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kGameInfoFieldNumber = 4, kPlaybackTimeFieldNumber = 1, kPlaybackTicksFieldNumber = 2, kPlaybackFramesFieldNumber = 3, }; // optional .CGameInfo game_info = 4; bool has_game_info() const; private: bool _internal_has_game_info() const; public: void clear_game_info(); const ::CGameInfo& game_info() const; PROTOBUF_NODISCARD ::CGameInfo* release_game_info(); ::CGameInfo* mutable_game_info(); void set_allocated_game_info(::CGameInfo* game_info); private: const ::CGameInfo& _internal_game_info() const; ::CGameInfo* _internal_mutable_game_info(); public: void unsafe_arena_set_allocated_game_info( ::CGameInfo* game_info); ::CGameInfo* unsafe_arena_release_game_info(); // optional float playback_time = 1; bool has_playback_time() const; private: bool _internal_has_playback_time() const; public: void clear_playback_time(); float playback_time() const; void set_playback_time(float value); private: float _internal_playback_time() const; void _internal_set_playback_time(float value); public: // optional int32 playback_ticks = 2; bool has_playback_ticks() const; private: bool _internal_has_playback_ticks() const; public: void clear_playback_ticks(); int32_t playback_ticks() const; void set_playback_ticks(int32_t value); private: int32_t _internal_playback_ticks() const; void _internal_set_playback_ticks(int32_t value); public: // optional int32 playback_frames = 3; bool has_playback_frames() const; private: bool _internal_has_playback_frames() const; public: void clear_playback_frames(); int32_t playback_frames() const; void set_playback_frames(int32_t value); private: int32_t _internal_playback_frames() const; void _internal_set_playback_frames(int32_t value); public: // @@protoc_insertion_point(class_scope:CDemoFileInfo) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::CGameInfo* game_info_; float playback_time_; int32_t playback_ticks_; int32_t playback_frames_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoPacket final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoPacket) */ { public: inline CDemoPacket() : CDemoPacket(nullptr) {} ~CDemoPacket() override; explicit PROTOBUF_CONSTEXPR CDemoPacket(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoPacket(const CDemoPacket& from); CDemoPacket(CDemoPacket&& from) noexcept : CDemoPacket() { *this = ::std::move(from); } inline CDemoPacket& operator=(const CDemoPacket& from) { CopyFrom(from); return *this; } inline CDemoPacket& operator=(CDemoPacket&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoPacket& default_instance() { return *internal_default_instance(); } static inline const CDemoPacket* internal_default_instance() { return reinterpret_cast<const CDemoPacket*>( &_CDemoPacket_default_instance_); } static constexpr int kIndexInFileMessages = 6; friend void swap(CDemoPacket& a, CDemoPacket& b) { a.Swap(&b); } inline void Swap(CDemoPacket* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoPacket* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoPacket* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoPacket>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoPacket& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoPacket& from) { CDemoPacket::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoPacket* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoPacket"; } protected: explicit CDemoPacket(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kDataFieldNumber = 3, }; // optional bytes data = 3; bool has_data() const; private: bool _internal_has_data() const; public: void clear_data(); const std::string& data() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_data(ArgT0&& arg0, ArgT... args); std::string* mutable_data(); PROTOBUF_NODISCARD std::string* release_data(); void set_allocated_data(std::string* data); private: const std::string& _internal_data() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_data(const std::string& value); std::string* _internal_mutable_data(); public: // @@protoc_insertion_point(class_scope:CDemoPacket) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr data_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoFullPacket final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoFullPacket) */ { public: inline CDemoFullPacket() : CDemoFullPacket(nullptr) {} ~CDemoFullPacket() override; explicit PROTOBUF_CONSTEXPR CDemoFullPacket(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoFullPacket(const CDemoFullPacket& from); CDemoFullPacket(CDemoFullPacket&& from) noexcept : CDemoFullPacket() { *this = ::std::move(from); } inline CDemoFullPacket& operator=(const CDemoFullPacket& from) { CopyFrom(from); return *this; } inline CDemoFullPacket& operator=(CDemoFullPacket&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoFullPacket& default_instance() { return *internal_default_instance(); } static inline const CDemoFullPacket* internal_default_instance() { return reinterpret_cast<const CDemoFullPacket*>( &_CDemoFullPacket_default_instance_); } static constexpr int kIndexInFileMessages = 7; friend void swap(CDemoFullPacket& a, CDemoFullPacket& b) { a.Swap(&b); } inline void Swap(CDemoFullPacket* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoFullPacket* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoFullPacket* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoFullPacket>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoFullPacket& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoFullPacket& from) { CDemoFullPacket::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoFullPacket* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoFullPacket"; } protected: explicit CDemoFullPacket(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kStringTableFieldNumber = 1, kPacketFieldNumber = 2, }; // optional .CDemoStringTables string_table = 1; bool has_string_table() const; private: bool _internal_has_string_table() const; public: void clear_string_table(); const ::CDemoStringTables& string_table() const; PROTOBUF_NODISCARD ::CDemoStringTables* release_string_table(); ::CDemoStringTables* mutable_string_table(); void set_allocated_string_table(::CDemoStringTables* string_table); private: const ::CDemoStringTables& _internal_string_table() const; ::CDemoStringTables* _internal_mutable_string_table(); public: void unsafe_arena_set_allocated_string_table( ::CDemoStringTables* string_table); ::CDemoStringTables* unsafe_arena_release_string_table(); // optional .CDemoPacket packet = 2; bool has_packet() const; private: bool _internal_has_packet() const; public: void clear_packet(); const ::CDemoPacket& packet() const; PROTOBUF_NODISCARD ::CDemoPacket* release_packet(); ::CDemoPacket* mutable_packet(); void set_allocated_packet(::CDemoPacket* packet); private: const ::CDemoPacket& _internal_packet() const; ::CDemoPacket* _internal_mutable_packet(); public: void unsafe_arena_set_allocated_packet( ::CDemoPacket* packet); ::CDemoPacket* unsafe_arena_release_packet(); // @@protoc_insertion_point(class_scope:CDemoFullPacket) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::CDemoStringTables* string_table_; ::CDemoPacket* packet_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoSaveGame final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoSaveGame) */ { public: inline CDemoSaveGame() : CDemoSaveGame(nullptr) {} ~CDemoSaveGame() override; explicit PROTOBUF_CONSTEXPR CDemoSaveGame(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoSaveGame(const CDemoSaveGame& from); CDemoSaveGame(CDemoSaveGame&& from) noexcept : CDemoSaveGame() { *this = ::std::move(from); } inline CDemoSaveGame& operator=(const CDemoSaveGame& from) { CopyFrom(from); return *this; } inline CDemoSaveGame& operator=(CDemoSaveGame&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoSaveGame& default_instance() { return *internal_default_instance(); } static inline const CDemoSaveGame* internal_default_instance() { return reinterpret_cast<const CDemoSaveGame*>( &_CDemoSaveGame_default_instance_); } static constexpr int kIndexInFileMessages = 8; friend void swap(CDemoSaveGame& a, CDemoSaveGame& b) { a.Swap(&b); } inline void Swap(CDemoSaveGame* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoSaveGame* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoSaveGame* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoSaveGame>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoSaveGame& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoSaveGame& from) { CDemoSaveGame::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoSaveGame* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoSaveGame"; } protected: explicit CDemoSaveGame(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kDataFieldNumber = 1, kSteamIdFieldNumber = 2, kSignatureFieldNumber = 3, kVersionFieldNumber = 4, }; // optional bytes data = 1; bool has_data() const; private: bool _internal_has_data() const; public: void clear_data(); const std::string& data() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_data(ArgT0&& arg0, ArgT... args); std::string* mutable_data(); PROTOBUF_NODISCARD std::string* release_data(); void set_allocated_data(std::string* data); private: const std::string& _internal_data() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_data(const std::string& value); std::string* _internal_mutable_data(); public: // optional fixed64 steam_id = 2; bool has_steam_id() const; private: bool _internal_has_steam_id() const; public: void clear_steam_id(); uint64_t steam_id() const; void set_steam_id(uint64_t value); private: uint64_t _internal_steam_id() const; void _internal_set_steam_id(uint64_t value); public: // optional fixed64 signature = 3; bool has_signature() const; private: bool _internal_has_signature() const; public: void clear_signature(); uint64_t signature() const; void set_signature(uint64_t value); private: uint64_t _internal_signature() const; void _internal_set_signature(uint64_t value); public: // optional int32 version = 4; bool has_version() const; private: bool _internal_has_version() const; public: void clear_version(); int32_t version() const; void set_version(int32_t value); private: int32_t _internal_version() const; void _internal_set_version(int32_t value); public: // @@protoc_insertion_point(class_scope:CDemoSaveGame) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr data_; uint64_t steam_id_; uint64_t signature_; int32_t version_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoSyncTick final : public ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase /* @@protoc_insertion_point(class_definition:CDemoSyncTick) */ { public: inline CDemoSyncTick() : CDemoSyncTick(nullptr) {} explicit PROTOBUF_CONSTEXPR CDemoSyncTick(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoSyncTick(const CDemoSyncTick& from); CDemoSyncTick(CDemoSyncTick&& from) noexcept : CDemoSyncTick() { *this = ::std::move(from); } inline CDemoSyncTick& operator=(const CDemoSyncTick& from) { CopyFrom(from); return *this; } inline CDemoSyncTick& operator=(CDemoSyncTick&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoSyncTick& default_instance() { return *internal_default_instance(); } static inline const CDemoSyncTick* internal_default_instance() { return reinterpret_cast<const CDemoSyncTick*>( &_CDemoSyncTick_default_instance_); } static constexpr int kIndexInFileMessages = 9; friend void swap(CDemoSyncTick& a, CDemoSyncTick& b) { a.Swap(&b); } inline void Swap(CDemoSyncTick* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoSyncTick* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoSyncTick* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoSyncTick>(arena); } using ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase::CopyFrom; inline void CopyFrom(const CDemoSyncTick& from) { ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase::CopyImpl(*this, from); } using ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase::MergeFrom; void MergeFrom(const CDemoSyncTick& from) { ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase::MergeImpl(*this, from); } public: private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoSyncTick"; } protected: explicit CDemoSyncTick(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // @@protoc_insertion_point(class_scope:CDemoSyncTick) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoConsoleCmd final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoConsoleCmd) */ { public: inline CDemoConsoleCmd() : CDemoConsoleCmd(nullptr) {} ~CDemoConsoleCmd() override; explicit PROTOBUF_CONSTEXPR CDemoConsoleCmd(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoConsoleCmd(const CDemoConsoleCmd& from); CDemoConsoleCmd(CDemoConsoleCmd&& from) noexcept : CDemoConsoleCmd() { *this = ::std::move(from); } inline CDemoConsoleCmd& operator=(const CDemoConsoleCmd& from) { CopyFrom(from); return *this; } inline CDemoConsoleCmd& operator=(CDemoConsoleCmd&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoConsoleCmd& default_instance() { return *internal_default_instance(); } static inline const CDemoConsoleCmd* internal_default_instance() { return reinterpret_cast<const CDemoConsoleCmd*>( &_CDemoConsoleCmd_default_instance_); } static constexpr int kIndexInFileMessages = 10; friend void swap(CDemoConsoleCmd& a, CDemoConsoleCmd& b) { a.Swap(&b); } inline void Swap(CDemoConsoleCmd* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoConsoleCmd* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoConsoleCmd* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoConsoleCmd>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoConsoleCmd& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoConsoleCmd& from) { CDemoConsoleCmd::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoConsoleCmd* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoConsoleCmd"; } protected: explicit CDemoConsoleCmd(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kCmdstringFieldNumber = 1, }; // optional string cmdstring = 1; bool has_cmdstring() const; private: bool _internal_has_cmdstring() const; public: void clear_cmdstring(); const std::string& cmdstring() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_cmdstring(ArgT0&& arg0, ArgT... args); std::string* mutable_cmdstring(); PROTOBUF_NODISCARD std::string* release_cmdstring(); void set_allocated_cmdstring(std::string* cmdstring); private: const std::string& _internal_cmdstring() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_cmdstring(const std::string& value); std::string* _internal_mutable_cmdstring(); public: // @@protoc_insertion_point(class_scope:CDemoConsoleCmd) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr cmdstring_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoSendTables final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoSendTables) */ { public: inline CDemoSendTables() : CDemoSendTables(nullptr) {} ~CDemoSendTables() override; explicit PROTOBUF_CONSTEXPR CDemoSendTables(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoSendTables(const CDemoSendTables& from); CDemoSendTables(CDemoSendTables&& from) noexcept : CDemoSendTables() { *this = ::std::move(from); } inline CDemoSendTables& operator=(const CDemoSendTables& from) { CopyFrom(from); return *this; } inline CDemoSendTables& operator=(CDemoSendTables&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoSendTables& default_instance() { return *internal_default_instance(); } static inline const CDemoSendTables* internal_default_instance() { return reinterpret_cast<const CDemoSendTables*>( &_CDemoSendTables_default_instance_); } static constexpr int kIndexInFileMessages = 11; friend void swap(CDemoSendTables& a, CDemoSendTables& b) { a.Swap(&b); } inline void Swap(CDemoSendTables* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoSendTables* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoSendTables* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoSendTables>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoSendTables& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoSendTables& from) { CDemoSendTables::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoSendTables* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoSendTables"; } protected: explicit CDemoSendTables(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kDataFieldNumber = 1, }; // optional bytes data = 1; bool has_data() const; private: bool _internal_has_data() const; public: void clear_data(); const std::string& data() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_data(ArgT0&& arg0, ArgT... args); std::string* mutable_data(); PROTOBUF_NODISCARD std::string* release_data(); void set_allocated_data(std::string* data); private: const std::string& _internal_data() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_data(const std::string& value); std::string* _internal_mutable_data(); public: // @@protoc_insertion_point(class_scope:CDemoSendTables) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr data_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoClassInfo_class_t final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoClassInfo.class_t) */ { public: inline CDemoClassInfo_class_t() : CDemoClassInfo_class_t(nullptr) {} ~CDemoClassInfo_class_t() override; explicit PROTOBUF_CONSTEXPR CDemoClassInfo_class_t(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoClassInfo_class_t(const CDemoClassInfo_class_t& from); CDemoClassInfo_class_t(CDemoClassInfo_class_t&& from) noexcept : CDemoClassInfo_class_t() { *this = ::std::move(from); } inline CDemoClassInfo_class_t& operator=(const CDemoClassInfo_class_t& from) { CopyFrom(from); return *this; } inline CDemoClassInfo_class_t& operator=(CDemoClassInfo_class_t&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoClassInfo_class_t& default_instance() { return *internal_default_instance(); } static inline const CDemoClassInfo_class_t* internal_default_instance() { return reinterpret_cast<const CDemoClassInfo_class_t*>( &_CDemoClassInfo_class_t_default_instance_); } static constexpr int kIndexInFileMessages = 12; friend void swap(CDemoClassInfo_class_t& a, CDemoClassInfo_class_t& b) { a.Swap(&b); } inline void Swap(CDemoClassInfo_class_t* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoClassInfo_class_t* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoClassInfo_class_t* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoClassInfo_class_t>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoClassInfo_class_t& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoClassInfo_class_t& from) { CDemoClassInfo_class_t::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoClassInfo_class_t* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoClassInfo.class_t"; } protected: explicit CDemoClassInfo_class_t(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kNetworkNameFieldNumber = 2, kTableNameFieldNumber = 3, kClassIdFieldNumber = 1, }; // optional string network_name = 2; bool has_network_name() const; private: bool _internal_has_network_name() const; public: void clear_network_name(); const std::string& network_name() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_network_name(ArgT0&& arg0, ArgT... args); std::string* mutable_network_name(); PROTOBUF_NODISCARD std::string* release_network_name(); void set_allocated_network_name(std::string* network_name); private: const std::string& _internal_network_name() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_network_name(const std::string& value); std::string* _internal_mutable_network_name(); public: // optional string table_name = 3; bool has_table_name() const; private: bool _internal_has_table_name() const; public: void clear_table_name(); const std::string& table_name() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_table_name(ArgT0&& arg0, ArgT... args); std::string* mutable_table_name(); PROTOBUF_NODISCARD std::string* release_table_name(); void set_allocated_table_name(std::string* table_name); private: const std::string& _internal_table_name() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_table_name(const std::string& value); std::string* _internal_mutable_table_name(); public: // optional int32 class_id = 1; bool has_class_id() const; private: bool _internal_has_class_id() const; public: void clear_class_id(); int32_t class_id() const; void set_class_id(int32_t value); private: int32_t _internal_class_id() const; void _internal_set_class_id(int32_t value); public: // @@protoc_insertion_point(class_scope:CDemoClassInfo.class_t) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr network_name_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr table_name_; int32_t class_id_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoClassInfo final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoClassInfo) */ { public: inline CDemoClassInfo() : CDemoClassInfo(nullptr) {} ~CDemoClassInfo() override; explicit PROTOBUF_CONSTEXPR CDemoClassInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoClassInfo(const CDemoClassInfo& from); CDemoClassInfo(CDemoClassInfo&& from) noexcept : CDemoClassInfo() { *this = ::std::move(from); } inline CDemoClassInfo& operator=(const CDemoClassInfo& from) { CopyFrom(from); return *this; } inline CDemoClassInfo& operator=(CDemoClassInfo&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoClassInfo& default_instance() { return *internal_default_instance(); } static inline const CDemoClassInfo* internal_default_instance() { return reinterpret_cast<const CDemoClassInfo*>( &_CDemoClassInfo_default_instance_); } static constexpr int kIndexInFileMessages = 13; friend void swap(CDemoClassInfo& a, CDemoClassInfo& b) { a.Swap(&b); } inline void Swap(CDemoClassInfo* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoClassInfo* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoClassInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoClassInfo>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoClassInfo& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoClassInfo& from) { CDemoClassInfo::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoClassInfo* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoClassInfo"; } protected: explicit CDemoClassInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- typedef CDemoClassInfo_class_t class_t; // accessors ------------------------------------------------------- enum : int { kClassesFieldNumber = 1, }; // repeated .CDemoClassInfo.class_t classes = 1; int classes_size() const; private: int _internal_classes_size() const; public: void clear_classes(); ::CDemoClassInfo_class_t* mutable_classes(int index); ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoClassInfo_class_t >* mutable_classes(); private: const ::CDemoClassInfo_class_t& _internal_classes(int index) const; ::CDemoClassInfo_class_t* _internal_add_classes(); public: const ::CDemoClassInfo_class_t& classes(int index) const; ::CDemoClassInfo_class_t* add_classes(); const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoClassInfo_class_t >& classes() const; // @@protoc_insertion_point(class_scope:CDemoClassInfo) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoClassInfo_class_t > classes_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoCustomData final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoCustomData) */ { public: inline CDemoCustomData() : CDemoCustomData(nullptr) {} ~CDemoCustomData() override; explicit PROTOBUF_CONSTEXPR CDemoCustomData(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoCustomData(const CDemoCustomData& from); CDemoCustomData(CDemoCustomData&& from) noexcept : CDemoCustomData() { *this = ::std::move(from); } inline CDemoCustomData& operator=(const CDemoCustomData& from) { CopyFrom(from); return *this; } inline CDemoCustomData& operator=(CDemoCustomData&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoCustomData& default_instance() { return *internal_default_instance(); } static inline const CDemoCustomData* internal_default_instance() { return reinterpret_cast<const CDemoCustomData*>( &_CDemoCustomData_default_instance_); } static constexpr int kIndexInFileMessages = 14; friend void swap(CDemoCustomData& a, CDemoCustomData& b) { a.Swap(&b); } inline void Swap(CDemoCustomData* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoCustomData* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoCustomData* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoCustomData>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoCustomData& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoCustomData& from) { CDemoCustomData::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoCustomData* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoCustomData"; } protected: explicit CDemoCustomData(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kDataFieldNumber = 2, kCallbackIndexFieldNumber = 1, }; // optional bytes data = 2; bool has_data() const; private: bool _internal_has_data() const; public: void clear_data(); const std::string& data() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_data(ArgT0&& arg0, ArgT... args); std::string* mutable_data(); PROTOBUF_NODISCARD std::string* release_data(); void set_allocated_data(std::string* data); private: const std::string& _internal_data() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_data(const std::string& value); std::string* _internal_mutable_data(); public: // optional int32 callback_index = 1; bool has_callback_index() const; private: bool _internal_has_callback_index() const; public: void clear_callback_index(); int32_t callback_index() const; void set_callback_index(int32_t value); private: int32_t _internal_callback_index() const; void _internal_set_callback_index(int32_t value); public: // @@protoc_insertion_point(class_scope:CDemoCustomData) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr data_; int32_t callback_index_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoCustomDataCallbacks final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoCustomDataCallbacks) */ { public: inline CDemoCustomDataCallbacks() : CDemoCustomDataCallbacks(nullptr) {} ~CDemoCustomDataCallbacks() override; explicit PROTOBUF_CONSTEXPR CDemoCustomDataCallbacks(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoCustomDataCallbacks(const CDemoCustomDataCallbacks& from); CDemoCustomDataCallbacks(CDemoCustomDataCallbacks&& from) noexcept : CDemoCustomDataCallbacks() { *this = ::std::move(from); } inline CDemoCustomDataCallbacks& operator=(const CDemoCustomDataCallbacks& from) { CopyFrom(from); return *this; } inline CDemoCustomDataCallbacks& operator=(CDemoCustomDataCallbacks&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoCustomDataCallbacks& default_instance() { return *internal_default_instance(); } static inline const CDemoCustomDataCallbacks* internal_default_instance() { return reinterpret_cast<const CDemoCustomDataCallbacks*>( &_CDemoCustomDataCallbacks_default_instance_); } static constexpr int kIndexInFileMessages = 15; friend void swap(CDemoCustomDataCallbacks& a, CDemoCustomDataCallbacks& b) { a.Swap(&b); } inline void Swap(CDemoCustomDataCallbacks* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoCustomDataCallbacks* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoCustomDataCallbacks* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoCustomDataCallbacks>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoCustomDataCallbacks& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoCustomDataCallbacks& from) { CDemoCustomDataCallbacks::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoCustomDataCallbacks* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoCustomDataCallbacks"; } protected: explicit CDemoCustomDataCallbacks(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kSaveIdFieldNumber = 1, }; // repeated string save_id = 1; int save_id_size() const; private: int _internal_save_id_size() const; public: void clear_save_id(); const std::string& save_id(int index) const; std::string* mutable_save_id(int index); void set_save_id(int index, const std::string& value); void set_save_id(int index, std::string&& value); void set_save_id(int index, const char* value); void set_save_id(int index, const char* value, size_t size); std::string* add_save_id(); void add_save_id(const std::string& value); void add_save_id(std::string&& value); void add_save_id(const char* value); void add_save_id(const char* value, size_t size); const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& save_id() const; ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* mutable_save_id(); private: const std::string& _internal_save_id(int index) const; std::string* _internal_add_save_id(); public: // @@protoc_insertion_point(class_scope:CDemoCustomDataCallbacks) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> save_id_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoAnimationData final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoAnimationData) */ { public: inline CDemoAnimationData() : CDemoAnimationData(nullptr) {} ~CDemoAnimationData() override; explicit PROTOBUF_CONSTEXPR CDemoAnimationData(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoAnimationData(const CDemoAnimationData& from); CDemoAnimationData(CDemoAnimationData&& from) noexcept : CDemoAnimationData() { *this = ::std::move(from); } inline CDemoAnimationData& operator=(const CDemoAnimationData& from) { CopyFrom(from); return *this; } inline CDemoAnimationData& operator=(CDemoAnimationData&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoAnimationData& default_instance() { return *internal_default_instance(); } static inline const CDemoAnimationData* internal_default_instance() { return reinterpret_cast<const CDemoAnimationData*>( &_CDemoAnimationData_default_instance_); } static constexpr int kIndexInFileMessages = 16; friend void swap(CDemoAnimationData& a, CDemoAnimationData& b) { a.Swap(&b); } inline void Swap(CDemoAnimationData* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoAnimationData* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoAnimationData* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoAnimationData>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoAnimationData& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoAnimationData& from) { CDemoAnimationData::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoAnimationData* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoAnimationData"; } protected: explicit CDemoAnimationData(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kDataFieldNumber = 4, kEntityIdFieldNumber = 1, kStartTickFieldNumber = 2, kDataChecksumFieldNumber = 5, kEndTickFieldNumber = 3, }; // optional bytes data = 4; bool has_data() const; private: bool _internal_has_data() const; public: void clear_data(); const std::string& data() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_data(ArgT0&& arg0, ArgT... args); std::string* mutable_data(); PROTOBUF_NODISCARD std::string* release_data(); void set_allocated_data(std::string* data); private: const std::string& _internal_data() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_data(const std::string& value); std::string* _internal_mutable_data(); public: // optional sint32 entity_id = 1; bool has_entity_id() const; private: bool _internal_has_entity_id() const; public: void clear_entity_id(); int32_t entity_id() const; void set_entity_id(int32_t value); private: int32_t _internal_entity_id() const; void _internal_set_entity_id(int32_t value); public: // optional int32 start_tick = 2; bool has_start_tick() const; private: bool _internal_has_start_tick() const; public: void clear_start_tick(); int32_t start_tick() const; void set_start_tick(int32_t value); private: int32_t _internal_start_tick() const; void _internal_set_start_tick(int32_t value); public: // optional int64 data_checksum = 5; bool has_data_checksum() const; private: bool _internal_has_data_checksum() const; public: void clear_data_checksum(); int64_t data_checksum() const; void set_data_checksum(int64_t value); private: int64_t _internal_data_checksum() const; void _internal_set_data_checksum(int64_t value); public: // optional int32 end_tick = 3; bool has_end_tick() const; private: bool _internal_has_end_tick() const; public: void clear_end_tick(); int32_t end_tick() const; void set_end_tick(int32_t value); private: int32_t _internal_end_tick() const; void _internal_set_end_tick(int32_t value); public: // @@protoc_insertion_point(class_scope:CDemoAnimationData) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr data_; int32_t entity_id_; int32_t start_tick_; int64_t data_checksum_; int32_t end_tick_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoStringTables_items_t final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoStringTables.items_t) */ { public: inline CDemoStringTables_items_t() : CDemoStringTables_items_t(nullptr) {} ~CDemoStringTables_items_t() override; explicit PROTOBUF_CONSTEXPR CDemoStringTables_items_t(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoStringTables_items_t(const CDemoStringTables_items_t& from); CDemoStringTables_items_t(CDemoStringTables_items_t&& from) noexcept : CDemoStringTables_items_t() { *this = ::std::move(from); } inline CDemoStringTables_items_t& operator=(const CDemoStringTables_items_t& from) { CopyFrom(from); return *this; } inline CDemoStringTables_items_t& operator=(CDemoStringTables_items_t&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoStringTables_items_t& default_instance() { return *internal_default_instance(); } static inline const CDemoStringTables_items_t* internal_default_instance() { return reinterpret_cast<const CDemoStringTables_items_t*>( &_CDemoStringTables_items_t_default_instance_); } static constexpr int kIndexInFileMessages = 17; friend void swap(CDemoStringTables_items_t& a, CDemoStringTables_items_t& b) { a.Swap(&b); } inline void Swap(CDemoStringTables_items_t* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoStringTables_items_t* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoStringTables_items_t* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoStringTables_items_t>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoStringTables_items_t& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoStringTables_items_t& from) { CDemoStringTables_items_t::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoStringTables_items_t* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoStringTables.items_t"; } protected: explicit CDemoStringTables_items_t(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kStrFieldNumber = 1, kDataFieldNumber = 2, }; // optional string str = 1; bool has_str() const; private: bool _internal_has_str() const; public: void clear_str(); const std::string& str() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_str(ArgT0&& arg0, ArgT... args); std::string* mutable_str(); PROTOBUF_NODISCARD std::string* release_str(); void set_allocated_str(std::string* str); private: const std::string& _internal_str() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_str(const std::string& value); std::string* _internal_mutable_str(); public: // optional bytes data = 2; bool has_data() const; private: bool _internal_has_data() const; public: void clear_data(); const std::string& data() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_data(ArgT0&& arg0, ArgT... args); std::string* mutable_data(); PROTOBUF_NODISCARD std::string* release_data(); void set_allocated_data(std::string* data); private: const std::string& _internal_data() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_data(const std::string& value); std::string* _internal_mutable_data(); public: // @@protoc_insertion_point(class_scope:CDemoStringTables.items_t) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr str_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr data_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoStringTables_table_t final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoStringTables.table_t) */ { public: inline CDemoStringTables_table_t() : CDemoStringTables_table_t(nullptr) {} ~CDemoStringTables_table_t() override; explicit PROTOBUF_CONSTEXPR CDemoStringTables_table_t(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoStringTables_table_t(const CDemoStringTables_table_t& from); CDemoStringTables_table_t(CDemoStringTables_table_t&& from) noexcept : CDemoStringTables_table_t() { *this = ::std::move(from); } inline CDemoStringTables_table_t& operator=(const CDemoStringTables_table_t& from) { CopyFrom(from); return *this; } inline CDemoStringTables_table_t& operator=(CDemoStringTables_table_t&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoStringTables_table_t& default_instance() { return *internal_default_instance(); } static inline const CDemoStringTables_table_t* internal_default_instance() { return reinterpret_cast<const CDemoStringTables_table_t*>( &_CDemoStringTables_table_t_default_instance_); } static constexpr int kIndexInFileMessages = 18; friend void swap(CDemoStringTables_table_t& a, CDemoStringTables_table_t& b) { a.Swap(&b); } inline void Swap(CDemoStringTables_table_t* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoStringTables_table_t* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoStringTables_table_t* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoStringTables_table_t>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoStringTables_table_t& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoStringTables_table_t& from) { CDemoStringTables_table_t::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoStringTables_table_t* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoStringTables.table_t"; } protected: explicit CDemoStringTables_table_t(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kItemsFieldNumber = 2, kItemsClientsideFieldNumber = 3, kTableNameFieldNumber = 1, kTableFlagsFieldNumber = 4, }; // repeated .CDemoStringTables.items_t items = 2; int items_size() const; private: int _internal_items_size() const; public: void clear_items(); ::CDemoStringTables_items_t* mutable_items(int index); ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_items_t >* mutable_items(); private: const ::CDemoStringTables_items_t& _internal_items(int index) const; ::CDemoStringTables_items_t* _internal_add_items(); public: const ::CDemoStringTables_items_t& items(int index) const; ::CDemoStringTables_items_t* add_items(); const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_items_t >& items() const; // repeated .CDemoStringTables.items_t items_clientside = 3; int items_clientside_size() const; private: int _internal_items_clientside_size() const; public: void clear_items_clientside(); ::CDemoStringTables_items_t* mutable_items_clientside(int index); ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_items_t >* mutable_items_clientside(); private: const ::CDemoStringTables_items_t& _internal_items_clientside(int index) const; ::CDemoStringTables_items_t* _internal_add_items_clientside(); public: const ::CDemoStringTables_items_t& items_clientside(int index) const; ::CDemoStringTables_items_t* add_items_clientside(); const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_items_t >& items_clientside() const; // optional string table_name = 1; bool has_table_name() const; private: bool _internal_has_table_name() const; public: void clear_table_name(); const std::string& table_name() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_table_name(ArgT0&& arg0, ArgT... args); std::string* mutable_table_name(); PROTOBUF_NODISCARD std::string* release_table_name(); void set_allocated_table_name(std::string* table_name); private: const std::string& _internal_table_name() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_table_name(const std::string& value); std::string* _internal_mutable_table_name(); public: // optional int32 table_flags = 4; bool has_table_flags() const; private: bool _internal_has_table_flags() const; public: void clear_table_flags(); int32_t table_flags() const; void set_table_flags(int32_t value); private: int32_t _internal_table_flags() const; void _internal_set_table_flags(int32_t value); public: // @@protoc_insertion_point(class_scope:CDemoStringTables.table_t) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_items_t > items_; ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_items_t > items_clientside_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr table_name_; int32_t table_flags_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoStringTables final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoStringTables) */ { public: inline CDemoStringTables() : CDemoStringTables(nullptr) {} ~CDemoStringTables() override; explicit PROTOBUF_CONSTEXPR CDemoStringTables(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoStringTables(const CDemoStringTables& from); CDemoStringTables(CDemoStringTables&& from) noexcept : CDemoStringTables() { *this = ::std::move(from); } inline CDemoStringTables& operator=(const CDemoStringTables& from) { CopyFrom(from); return *this; } inline CDemoStringTables& operator=(CDemoStringTables&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoStringTables& default_instance() { return *internal_default_instance(); } static inline const CDemoStringTables* internal_default_instance() { return reinterpret_cast<const CDemoStringTables*>( &_CDemoStringTables_default_instance_); } static constexpr int kIndexInFileMessages = 19; friend void swap(CDemoStringTables& a, CDemoStringTables& b) { a.Swap(&b); } inline void Swap(CDemoStringTables* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoStringTables* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoStringTables* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoStringTables>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoStringTables& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoStringTables& from) { CDemoStringTables::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoStringTables* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoStringTables"; } protected: explicit CDemoStringTables(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- typedef CDemoStringTables_items_t items_t; typedef CDemoStringTables_table_t table_t; // accessors ------------------------------------------------------- enum : int { kTablesFieldNumber = 1, }; // repeated .CDemoStringTables.table_t tables = 1; int tables_size() const; private: int _internal_tables_size() const; public: void clear_tables(); ::CDemoStringTables_table_t* mutable_tables(int index); ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_table_t >* mutable_tables(); private: const ::CDemoStringTables_table_t& _internal_tables(int index) const; ::CDemoStringTables_table_t* _internal_add_tables(); public: const ::CDemoStringTables_table_t& tables(int index) const; ::CDemoStringTables_table_t* add_tables(); const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_table_t >& tables() const; // @@protoc_insertion_point(class_scope:CDemoStringTables) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_table_t > tables_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoStop final : public ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase /* @@protoc_insertion_point(class_definition:CDemoStop) */ { public: inline CDemoStop() : CDemoStop(nullptr) {} explicit PROTOBUF_CONSTEXPR CDemoStop(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoStop(const CDemoStop& from); CDemoStop(CDemoStop&& from) noexcept : CDemoStop() { *this = ::std::move(from); } inline CDemoStop& operator=(const CDemoStop& from) { CopyFrom(from); return *this; } inline CDemoStop& operator=(CDemoStop&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoStop& default_instance() { return *internal_default_instance(); } static inline const CDemoStop* internal_default_instance() { return reinterpret_cast<const CDemoStop*>( &_CDemoStop_default_instance_); } static constexpr int kIndexInFileMessages = 20; friend void swap(CDemoStop& a, CDemoStop& b) { a.Swap(&b); } inline void Swap(CDemoStop* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoStop* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoStop* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoStop>(arena); } using ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase::CopyFrom; inline void CopyFrom(const CDemoStop& from) { ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase::CopyImpl(*this, from); } using ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase::MergeFrom; void MergeFrom(const CDemoStop& from) { ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase::MergeImpl(*this, from); } public: private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoStop"; } protected: explicit CDemoStop(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // @@protoc_insertion_point(class_scope:CDemoStop) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoUserCmd final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoUserCmd) */ { public: inline CDemoUserCmd() : CDemoUserCmd(nullptr) {} ~CDemoUserCmd() override; explicit PROTOBUF_CONSTEXPR CDemoUserCmd(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoUserCmd(const CDemoUserCmd& from); CDemoUserCmd(CDemoUserCmd&& from) noexcept : CDemoUserCmd() { *this = ::std::move(from); } inline CDemoUserCmd& operator=(const CDemoUserCmd& from) { CopyFrom(from); return *this; } inline CDemoUserCmd& operator=(CDemoUserCmd&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoUserCmd& default_instance() { return *internal_default_instance(); } static inline const CDemoUserCmd* internal_default_instance() { return reinterpret_cast<const CDemoUserCmd*>( &_CDemoUserCmd_default_instance_); } static constexpr int kIndexInFileMessages = 21; friend void swap(CDemoUserCmd& a, CDemoUserCmd& b) { a.Swap(&b); } inline void Swap(CDemoUserCmd* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoUserCmd* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoUserCmd* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoUserCmd>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoUserCmd& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoUserCmd& from) { CDemoUserCmd::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoUserCmd* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoUserCmd"; } protected: explicit CDemoUserCmd(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kDataFieldNumber = 2, kCmdNumberFieldNumber = 1, }; // optional bytes data = 2; bool has_data() const; private: bool _internal_has_data() const; public: void clear_data(); const std::string& data() const; template <typename ArgT0 = const std::string&, typename... ArgT> void set_data(ArgT0&& arg0, ArgT... args); std::string* mutable_data(); PROTOBUF_NODISCARD std::string* release_data(); void set_allocated_data(std::string* data); private: const std::string& _internal_data() const; inline PROTOBUF_ALWAYS_INLINE void _internal_set_data(const std::string& value); std::string* _internal_mutable_data(); public: // optional int32 cmd_number = 1; bool has_cmd_number() const; private: bool _internal_has_cmd_number() const; public: void clear_cmd_number(); int32_t cmd_number() const; void set_cmd_number(int32_t value); private: int32_t _internal_cmd_number() const; void _internal_set_cmd_number(int32_t value); public: // @@protoc_insertion_point(class_scope:CDemoUserCmd) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr data_; int32_t cmd_number_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // ------------------------------------------------------------------- class CDemoSpawnGroups final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:CDemoSpawnGroups) */ { public: inline CDemoSpawnGroups() : CDemoSpawnGroups(nullptr) {} ~CDemoSpawnGroups() override; explicit PROTOBUF_CONSTEXPR CDemoSpawnGroups(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CDemoSpawnGroups(const CDemoSpawnGroups& from); CDemoSpawnGroups(CDemoSpawnGroups&& from) noexcept : CDemoSpawnGroups() { *this = ::std::move(from); } inline CDemoSpawnGroups& operator=(const CDemoSpawnGroups& from) { CopyFrom(from); return *this; } inline CDemoSpawnGroups& operator=(CDemoSpawnGroups&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena() #ifdef PROTOBUF_FORCE_COPY_IN_MOVE && GetOwningArena() != nullptr #endif // !PROTOBUF_FORCE_COPY_IN_MOVE ) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const CDemoSpawnGroups& default_instance() { return *internal_default_instance(); } static inline const CDemoSpawnGroups* internal_default_instance() { return reinterpret_cast<const CDemoSpawnGroups*>( &_CDemoSpawnGroups_default_instance_); } static constexpr int kIndexInFileMessages = 22; friend void swap(CDemoSpawnGroups& a, CDemoSpawnGroups& b) { a.Swap(&b); } inline void Swap(CDemoSpawnGroups* other) { if (other == this) return; #ifdef PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() != nullptr && GetOwningArena() == other->GetOwningArena()) { #else // PROTOBUF_FORCE_COPY_IN_SWAP if (GetOwningArena() == other->GetOwningArena()) { #endif // !PROTOBUF_FORCE_COPY_IN_SWAP InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CDemoSpawnGroups* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- CDemoSpawnGroups* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage<CDemoSpawnGroups>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CDemoSpawnGroups& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom( const CDemoSpawnGroups& from) { CDemoSpawnGroups::MergeImpl(*this, from); } private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CDemoSpawnGroups* other); private: friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "CDemoSpawnGroups"; } protected: explicit CDemoSpawnGroups(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kMsgsFieldNumber = 3, }; // repeated bytes msgs = 3; int msgs_size() const; private: int _internal_msgs_size() const; public: void clear_msgs(); const std::string& msgs(int index) const; std::string* mutable_msgs(int index); void set_msgs(int index, const std::string& value); void set_msgs(int index, std::string&& value); void set_msgs(int index, const char* value); void set_msgs(int index, const void* value, size_t size); std::string* add_msgs(); void add_msgs(const std::string& value); void add_msgs(std::string&& value); void add_msgs(const char* value); void add_msgs(const void* value, size_t size); const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& msgs() const; ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* mutable_msgs(); private: const std::string& _internal_msgs(int index) const; std::string* _internal_add_msgs(); public: // @@protoc_insertion_point(class_scope:CDemoSpawnGroups) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; struct Impl_ { ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> msgs_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; }; union { Impl_ _impl_; }; friend struct ::TableStruct_demo_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // CDemoFileHeader // required string demo_file_stamp = 1; inline bool CDemoFileHeader::_internal_has_demo_file_stamp() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CDemoFileHeader::has_demo_file_stamp() const { return _internal_has_demo_file_stamp(); } inline void CDemoFileHeader::clear_demo_file_stamp() { _impl_.demo_file_stamp_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CDemoFileHeader::demo_file_stamp() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.demo_file_stamp) return _internal_demo_file_stamp(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoFileHeader::set_demo_file_stamp(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.demo_file_stamp_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoFileHeader.demo_file_stamp) } inline std::string* CDemoFileHeader::mutable_demo_file_stamp() { std::string* _s = _internal_mutable_demo_file_stamp(); // @@protoc_insertion_point(field_mutable:CDemoFileHeader.demo_file_stamp) return _s; } inline const std::string& CDemoFileHeader::_internal_demo_file_stamp() const { return _impl_.demo_file_stamp_.Get(); } inline void CDemoFileHeader::_internal_set_demo_file_stamp(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.demo_file_stamp_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoFileHeader::_internal_mutable_demo_file_stamp() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.demo_file_stamp_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoFileHeader::release_demo_file_stamp() { // @@protoc_insertion_point(field_release:CDemoFileHeader.demo_file_stamp) if (!_internal_has_demo_file_stamp()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.demo_file_stamp_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.demo_file_stamp_.IsDefault()) { _impl_.demo_file_stamp_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoFileHeader::set_allocated_demo_file_stamp(std::string* demo_file_stamp) { if (demo_file_stamp != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.demo_file_stamp_.SetAllocated(demo_file_stamp, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.demo_file_stamp_.IsDefault()) { _impl_.demo_file_stamp_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoFileHeader.demo_file_stamp) } // optional int32 network_protocol = 2; inline bool CDemoFileHeader::_internal_has_network_protocol() const { bool value = (_impl_._has_bits_[0] & 0x00000200u) != 0; return value; } inline bool CDemoFileHeader::has_network_protocol() const { return _internal_has_network_protocol(); } inline void CDemoFileHeader::clear_network_protocol() { _impl_.network_protocol_ = 0; _impl_._has_bits_[0] &= ~0x00000200u; } inline int32_t CDemoFileHeader::_internal_network_protocol() const { return _impl_.network_protocol_; } inline int32_t CDemoFileHeader::network_protocol() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.network_protocol) return _internal_network_protocol(); } inline void CDemoFileHeader::_internal_set_network_protocol(int32_t value) { _impl_._has_bits_[0] |= 0x00000200u; _impl_.network_protocol_ = value; } inline void CDemoFileHeader::set_network_protocol(int32_t value) { _internal_set_network_protocol(value); // @@protoc_insertion_point(field_set:CDemoFileHeader.network_protocol) } // optional string server_name = 3; inline bool CDemoFileHeader::_internal_has_server_name() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CDemoFileHeader::has_server_name() const { return _internal_has_server_name(); } inline void CDemoFileHeader::clear_server_name() { _impl_.server_name_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000002u; } inline const std::string& CDemoFileHeader::server_name() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.server_name) return _internal_server_name(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoFileHeader::set_server_name(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.server_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoFileHeader.server_name) } inline std::string* CDemoFileHeader::mutable_server_name() { std::string* _s = _internal_mutable_server_name(); // @@protoc_insertion_point(field_mutable:CDemoFileHeader.server_name) return _s; } inline const std::string& CDemoFileHeader::_internal_server_name() const { return _impl_.server_name_.Get(); } inline void CDemoFileHeader::_internal_set_server_name(const std::string& value) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.server_name_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoFileHeader::_internal_mutable_server_name() { _impl_._has_bits_[0] |= 0x00000002u; return _impl_.server_name_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoFileHeader::release_server_name() { // @@protoc_insertion_point(field_release:CDemoFileHeader.server_name) if (!_internal_has_server_name()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000002u; auto* p = _impl_.server_name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.server_name_.IsDefault()) { _impl_.server_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoFileHeader::set_allocated_server_name(std::string* server_name) { if (server_name != nullptr) { _impl_._has_bits_[0] |= 0x00000002u; } else { _impl_._has_bits_[0] &= ~0x00000002u; } _impl_.server_name_.SetAllocated(server_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.server_name_.IsDefault()) { _impl_.server_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoFileHeader.server_name) } // optional string client_name = 4; inline bool CDemoFileHeader::_internal_has_client_name() const { bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool CDemoFileHeader::has_client_name() const { return _internal_has_client_name(); } inline void CDemoFileHeader::clear_client_name() { _impl_.client_name_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000004u; } inline const std::string& CDemoFileHeader::client_name() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.client_name) return _internal_client_name(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoFileHeader::set_client_name(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000004u; _impl_.client_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoFileHeader.client_name) } inline std::string* CDemoFileHeader::mutable_client_name() { std::string* _s = _internal_mutable_client_name(); // @@protoc_insertion_point(field_mutable:CDemoFileHeader.client_name) return _s; } inline const std::string& CDemoFileHeader::_internal_client_name() const { return _impl_.client_name_.Get(); } inline void CDemoFileHeader::_internal_set_client_name(const std::string& value) { _impl_._has_bits_[0] |= 0x00000004u; _impl_.client_name_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoFileHeader::_internal_mutable_client_name() { _impl_._has_bits_[0] |= 0x00000004u; return _impl_.client_name_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoFileHeader::release_client_name() { // @@protoc_insertion_point(field_release:CDemoFileHeader.client_name) if (!_internal_has_client_name()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000004u; auto* p = _impl_.client_name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.client_name_.IsDefault()) { _impl_.client_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoFileHeader::set_allocated_client_name(std::string* client_name) { if (client_name != nullptr) { _impl_._has_bits_[0] |= 0x00000004u; } else { _impl_._has_bits_[0] &= ~0x00000004u; } _impl_.client_name_.SetAllocated(client_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.client_name_.IsDefault()) { _impl_.client_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoFileHeader.client_name) } // optional string map_name = 5; inline bool CDemoFileHeader::_internal_has_map_name() const { bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; return value; } inline bool CDemoFileHeader::has_map_name() const { return _internal_has_map_name(); } inline void CDemoFileHeader::clear_map_name() { _impl_.map_name_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000008u; } inline const std::string& CDemoFileHeader::map_name() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.map_name) return _internal_map_name(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoFileHeader::set_map_name(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000008u; _impl_.map_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoFileHeader.map_name) } inline std::string* CDemoFileHeader::mutable_map_name() { std::string* _s = _internal_mutable_map_name(); // @@protoc_insertion_point(field_mutable:CDemoFileHeader.map_name) return _s; } inline const std::string& CDemoFileHeader::_internal_map_name() const { return _impl_.map_name_.Get(); } inline void CDemoFileHeader::_internal_set_map_name(const std::string& value) { _impl_._has_bits_[0] |= 0x00000008u; _impl_.map_name_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoFileHeader::_internal_mutable_map_name() { _impl_._has_bits_[0] |= 0x00000008u; return _impl_.map_name_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoFileHeader::release_map_name() { // @@protoc_insertion_point(field_release:CDemoFileHeader.map_name) if (!_internal_has_map_name()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000008u; auto* p = _impl_.map_name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.map_name_.IsDefault()) { _impl_.map_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoFileHeader::set_allocated_map_name(std::string* map_name) { if (map_name != nullptr) { _impl_._has_bits_[0] |= 0x00000008u; } else { _impl_._has_bits_[0] &= ~0x00000008u; } _impl_.map_name_.SetAllocated(map_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.map_name_.IsDefault()) { _impl_.map_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoFileHeader.map_name) } // optional string game_directory = 6; inline bool CDemoFileHeader::_internal_has_game_directory() const { bool value = (_impl_._has_bits_[0] & 0x00000010u) != 0; return value; } inline bool CDemoFileHeader::has_game_directory() const { return _internal_has_game_directory(); } inline void CDemoFileHeader::clear_game_directory() { _impl_.game_directory_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000010u; } inline const std::string& CDemoFileHeader::game_directory() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.game_directory) return _internal_game_directory(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoFileHeader::set_game_directory(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000010u; _impl_.game_directory_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoFileHeader.game_directory) } inline std::string* CDemoFileHeader::mutable_game_directory() { std::string* _s = _internal_mutable_game_directory(); // @@protoc_insertion_point(field_mutable:CDemoFileHeader.game_directory) return _s; } inline const std::string& CDemoFileHeader::_internal_game_directory() const { return _impl_.game_directory_.Get(); } inline void CDemoFileHeader::_internal_set_game_directory(const std::string& value) { _impl_._has_bits_[0] |= 0x00000010u; _impl_.game_directory_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoFileHeader::_internal_mutable_game_directory() { _impl_._has_bits_[0] |= 0x00000010u; return _impl_.game_directory_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoFileHeader::release_game_directory() { // @@protoc_insertion_point(field_release:CDemoFileHeader.game_directory) if (!_internal_has_game_directory()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000010u; auto* p = _impl_.game_directory_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.game_directory_.IsDefault()) { _impl_.game_directory_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoFileHeader::set_allocated_game_directory(std::string* game_directory) { if (game_directory != nullptr) { _impl_._has_bits_[0] |= 0x00000010u; } else { _impl_._has_bits_[0] &= ~0x00000010u; } _impl_.game_directory_.SetAllocated(game_directory, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.game_directory_.IsDefault()) { _impl_.game_directory_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoFileHeader.game_directory) } // optional int32 fullpackets_version = 7; inline bool CDemoFileHeader::_internal_has_fullpackets_version() const { bool value = (_impl_._has_bits_[0] & 0x00000400u) != 0; return value; } inline bool CDemoFileHeader::has_fullpackets_version() const { return _internal_has_fullpackets_version(); } inline void CDemoFileHeader::clear_fullpackets_version() { _impl_.fullpackets_version_ = 0; _impl_._has_bits_[0] &= ~0x00000400u; } inline int32_t CDemoFileHeader::_internal_fullpackets_version() const { return _impl_.fullpackets_version_; } inline int32_t CDemoFileHeader::fullpackets_version() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.fullpackets_version) return _internal_fullpackets_version(); } inline void CDemoFileHeader::_internal_set_fullpackets_version(int32_t value) { _impl_._has_bits_[0] |= 0x00000400u; _impl_.fullpackets_version_ = value; } inline void CDemoFileHeader::set_fullpackets_version(int32_t value) { _internal_set_fullpackets_version(value); // @@protoc_insertion_point(field_set:CDemoFileHeader.fullpackets_version) } // optional bool allow_clientside_entities = 8; inline bool CDemoFileHeader::_internal_has_allow_clientside_entities() const { bool value = (_impl_._has_bits_[0] & 0x00000800u) != 0; return value; } inline bool CDemoFileHeader::has_allow_clientside_entities() const { return _internal_has_allow_clientside_entities(); } inline void CDemoFileHeader::clear_allow_clientside_entities() { _impl_.allow_clientside_entities_ = false; _impl_._has_bits_[0] &= ~0x00000800u; } inline bool CDemoFileHeader::_internal_allow_clientside_entities() const { return _impl_.allow_clientside_entities_; } inline bool CDemoFileHeader::allow_clientside_entities() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.allow_clientside_entities) return _internal_allow_clientside_entities(); } inline void CDemoFileHeader::_internal_set_allow_clientside_entities(bool value) { _impl_._has_bits_[0] |= 0x00000800u; _impl_.allow_clientside_entities_ = value; } inline void CDemoFileHeader::set_allow_clientside_entities(bool value) { _internal_set_allow_clientside_entities(value); // @@protoc_insertion_point(field_set:CDemoFileHeader.allow_clientside_entities) } // optional bool allow_clientside_particles = 9; inline bool CDemoFileHeader::_internal_has_allow_clientside_particles() const { bool value = (_impl_._has_bits_[0] & 0x00001000u) != 0; return value; } inline bool CDemoFileHeader::has_allow_clientside_particles() const { return _internal_has_allow_clientside_particles(); } inline void CDemoFileHeader::clear_allow_clientside_particles() { _impl_.allow_clientside_particles_ = false; _impl_._has_bits_[0] &= ~0x00001000u; } inline bool CDemoFileHeader::_internal_allow_clientside_particles() const { return _impl_.allow_clientside_particles_; } inline bool CDemoFileHeader::allow_clientside_particles() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.allow_clientside_particles) return _internal_allow_clientside_particles(); } inline void CDemoFileHeader::_internal_set_allow_clientside_particles(bool value) { _impl_._has_bits_[0] |= 0x00001000u; _impl_.allow_clientside_particles_ = value; } inline void CDemoFileHeader::set_allow_clientside_particles(bool value) { _internal_set_allow_clientside_particles(value); // @@protoc_insertion_point(field_set:CDemoFileHeader.allow_clientside_particles) } // optional string addons = 10; inline bool CDemoFileHeader::_internal_has_addons() const { bool value = (_impl_._has_bits_[0] & 0x00000020u) != 0; return value; } inline bool CDemoFileHeader::has_addons() const { return _internal_has_addons(); } inline void CDemoFileHeader::clear_addons() { _impl_.addons_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000020u; } inline const std::string& CDemoFileHeader::addons() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.addons) return _internal_addons(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoFileHeader::set_addons(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000020u; _impl_.addons_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoFileHeader.addons) } inline std::string* CDemoFileHeader::mutable_addons() { std::string* _s = _internal_mutable_addons(); // @@protoc_insertion_point(field_mutable:CDemoFileHeader.addons) return _s; } inline const std::string& CDemoFileHeader::_internal_addons() const { return _impl_.addons_.Get(); } inline void CDemoFileHeader::_internal_set_addons(const std::string& value) { _impl_._has_bits_[0] |= 0x00000020u; _impl_.addons_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoFileHeader::_internal_mutable_addons() { _impl_._has_bits_[0] |= 0x00000020u; return _impl_.addons_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoFileHeader::release_addons() { // @@protoc_insertion_point(field_release:CDemoFileHeader.addons) if (!_internal_has_addons()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000020u; auto* p = _impl_.addons_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.addons_.IsDefault()) { _impl_.addons_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoFileHeader::set_allocated_addons(std::string* addons) { if (addons != nullptr) { _impl_._has_bits_[0] |= 0x00000020u; } else { _impl_._has_bits_[0] &= ~0x00000020u; } _impl_.addons_.SetAllocated(addons, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.addons_.IsDefault()) { _impl_.addons_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoFileHeader.addons) } // optional string demo_version_name = 11; inline bool CDemoFileHeader::_internal_has_demo_version_name() const { bool value = (_impl_._has_bits_[0] & 0x00000040u) != 0; return value; } inline bool CDemoFileHeader::has_demo_version_name() const { return _internal_has_demo_version_name(); } inline void CDemoFileHeader::clear_demo_version_name() { _impl_.demo_version_name_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000040u; } inline const std::string& CDemoFileHeader::demo_version_name() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.demo_version_name) return _internal_demo_version_name(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoFileHeader::set_demo_version_name(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000040u; _impl_.demo_version_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoFileHeader.demo_version_name) } inline std::string* CDemoFileHeader::mutable_demo_version_name() { std::string* _s = _internal_mutable_demo_version_name(); // @@protoc_insertion_point(field_mutable:CDemoFileHeader.demo_version_name) return _s; } inline const std::string& CDemoFileHeader::_internal_demo_version_name() const { return _impl_.demo_version_name_.Get(); } inline void CDemoFileHeader::_internal_set_demo_version_name(const std::string& value) { _impl_._has_bits_[0] |= 0x00000040u; _impl_.demo_version_name_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoFileHeader::_internal_mutable_demo_version_name() { _impl_._has_bits_[0] |= 0x00000040u; return _impl_.demo_version_name_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoFileHeader::release_demo_version_name() { // @@protoc_insertion_point(field_release:CDemoFileHeader.demo_version_name) if (!_internal_has_demo_version_name()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000040u; auto* p = _impl_.demo_version_name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.demo_version_name_.IsDefault()) { _impl_.demo_version_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoFileHeader::set_allocated_demo_version_name(std::string* demo_version_name) { if (demo_version_name != nullptr) { _impl_._has_bits_[0] |= 0x00000040u; } else { _impl_._has_bits_[0] &= ~0x00000040u; } _impl_.demo_version_name_.SetAllocated(demo_version_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.demo_version_name_.IsDefault()) { _impl_.demo_version_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoFileHeader.demo_version_name) } // optional string demo_version_guid = 12; inline bool CDemoFileHeader::_internal_has_demo_version_guid() const { bool value = (_impl_._has_bits_[0] & 0x00000080u) != 0; return value; } inline bool CDemoFileHeader::has_demo_version_guid() const { return _internal_has_demo_version_guid(); } inline void CDemoFileHeader::clear_demo_version_guid() { _impl_.demo_version_guid_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000080u; } inline const std::string& CDemoFileHeader::demo_version_guid() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.demo_version_guid) return _internal_demo_version_guid(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoFileHeader::set_demo_version_guid(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000080u; _impl_.demo_version_guid_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoFileHeader.demo_version_guid) } inline std::string* CDemoFileHeader::mutable_demo_version_guid() { std::string* _s = _internal_mutable_demo_version_guid(); // @@protoc_insertion_point(field_mutable:CDemoFileHeader.demo_version_guid) return _s; } inline const std::string& CDemoFileHeader::_internal_demo_version_guid() const { return _impl_.demo_version_guid_.Get(); } inline void CDemoFileHeader::_internal_set_demo_version_guid(const std::string& value) { _impl_._has_bits_[0] |= 0x00000080u; _impl_.demo_version_guid_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoFileHeader::_internal_mutable_demo_version_guid() { _impl_._has_bits_[0] |= 0x00000080u; return _impl_.demo_version_guid_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoFileHeader::release_demo_version_guid() { // @@protoc_insertion_point(field_release:CDemoFileHeader.demo_version_guid) if (!_internal_has_demo_version_guid()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000080u; auto* p = _impl_.demo_version_guid_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.demo_version_guid_.IsDefault()) { _impl_.demo_version_guid_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoFileHeader::set_allocated_demo_version_guid(std::string* demo_version_guid) { if (demo_version_guid != nullptr) { _impl_._has_bits_[0] |= 0x00000080u; } else { _impl_._has_bits_[0] &= ~0x00000080u; } _impl_.demo_version_guid_.SetAllocated(demo_version_guid, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.demo_version_guid_.IsDefault()) { _impl_.demo_version_guid_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoFileHeader.demo_version_guid) } // optional int32 build_num = 13; inline bool CDemoFileHeader::_internal_has_build_num() const { bool value = (_impl_._has_bits_[0] & 0x00002000u) != 0; return value; } inline bool CDemoFileHeader::has_build_num() const { return _internal_has_build_num(); } inline void CDemoFileHeader::clear_build_num() { _impl_.build_num_ = 0; _impl_._has_bits_[0] &= ~0x00002000u; } inline int32_t CDemoFileHeader::_internal_build_num() const { return _impl_.build_num_; } inline int32_t CDemoFileHeader::build_num() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.build_num) return _internal_build_num(); } inline void CDemoFileHeader::_internal_set_build_num(int32_t value) { _impl_._has_bits_[0] |= 0x00002000u; _impl_.build_num_ = value; } inline void CDemoFileHeader::set_build_num(int32_t value) { _internal_set_build_num(value); // @@protoc_insertion_point(field_set:CDemoFileHeader.build_num) } // optional string game = 14; inline bool CDemoFileHeader::_internal_has_game() const { bool value = (_impl_._has_bits_[0] & 0x00000100u) != 0; return value; } inline bool CDemoFileHeader::has_game() const { return _internal_has_game(); } inline void CDemoFileHeader::clear_game() { _impl_.game_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000100u; } inline const std::string& CDemoFileHeader::game() const { // @@protoc_insertion_point(field_get:CDemoFileHeader.game) return _internal_game(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoFileHeader::set_game(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000100u; _impl_.game_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoFileHeader.game) } inline std::string* CDemoFileHeader::mutable_game() { std::string* _s = _internal_mutable_game(); // @@protoc_insertion_point(field_mutable:CDemoFileHeader.game) return _s; } inline const std::string& CDemoFileHeader::_internal_game() const { return _impl_.game_.Get(); } inline void CDemoFileHeader::_internal_set_game(const std::string& value) { _impl_._has_bits_[0] |= 0x00000100u; _impl_.game_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoFileHeader::_internal_mutable_game() { _impl_._has_bits_[0] |= 0x00000100u; return _impl_.game_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoFileHeader::release_game() { // @@protoc_insertion_point(field_release:CDemoFileHeader.game) if (!_internal_has_game()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000100u; auto* p = _impl_.game_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.game_.IsDefault()) { _impl_.game_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoFileHeader::set_allocated_game(std::string* game) { if (game != nullptr) { _impl_._has_bits_[0] |= 0x00000100u; } else { _impl_._has_bits_[0] &= ~0x00000100u; } _impl_.game_.SetAllocated(game, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.game_.IsDefault()) { _impl_.game_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoFileHeader.game) } // ------------------------------------------------------------------- // CGameInfo_CDotaGameInfo_CPlayerInfo // optional string hero_name = 1; inline bool CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_has_hero_name() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo_CPlayerInfo::has_hero_name() const { return _internal_has_hero_name(); } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::clear_hero_name() { _impl_.hero_name_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CGameInfo_CDotaGameInfo_CPlayerInfo::hero_name() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.CPlayerInfo.hero_name) return _internal_hero_name(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CGameInfo_CDotaGameInfo_CPlayerInfo::set_hero_name(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.hero_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.CPlayerInfo.hero_name) } inline std::string* CGameInfo_CDotaGameInfo_CPlayerInfo::mutable_hero_name() { std::string* _s = _internal_mutable_hero_name(); // @@protoc_insertion_point(field_mutable:CGameInfo.CDotaGameInfo.CPlayerInfo.hero_name) return _s; } inline const std::string& CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_hero_name() const { return _impl_.hero_name_.Get(); } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_set_hero_name(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.hero_name_.Set(value, GetArenaForAllocation()); } inline std::string* CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_mutable_hero_name() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.hero_name_.Mutable(GetArenaForAllocation()); } inline std::string* CGameInfo_CDotaGameInfo_CPlayerInfo::release_hero_name() { // @@protoc_insertion_point(field_release:CGameInfo.CDotaGameInfo.CPlayerInfo.hero_name) if (!_internal_has_hero_name()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.hero_name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.hero_name_.IsDefault()) { _impl_.hero_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::set_allocated_hero_name(std::string* hero_name) { if (hero_name != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.hero_name_.SetAllocated(hero_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.hero_name_.IsDefault()) { _impl_.hero_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CGameInfo.CDotaGameInfo.CPlayerInfo.hero_name) } // optional string player_name = 2; inline bool CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_has_player_name() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo_CPlayerInfo::has_player_name() const { return _internal_has_player_name(); } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::clear_player_name() { _impl_.player_name_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000002u; } inline const std::string& CGameInfo_CDotaGameInfo_CPlayerInfo::player_name() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.CPlayerInfo.player_name) return _internal_player_name(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CGameInfo_CDotaGameInfo_CPlayerInfo::set_player_name(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.player_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.CPlayerInfo.player_name) } inline std::string* CGameInfo_CDotaGameInfo_CPlayerInfo::mutable_player_name() { std::string* _s = _internal_mutable_player_name(); // @@protoc_insertion_point(field_mutable:CGameInfo.CDotaGameInfo.CPlayerInfo.player_name) return _s; } inline const std::string& CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_player_name() const { return _impl_.player_name_.Get(); } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_set_player_name(const std::string& value) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.player_name_.Set(value, GetArenaForAllocation()); } inline std::string* CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_mutable_player_name() { _impl_._has_bits_[0] |= 0x00000002u; return _impl_.player_name_.Mutable(GetArenaForAllocation()); } inline std::string* CGameInfo_CDotaGameInfo_CPlayerInfo::release_player_name() { // @@protoc_insertion_point(field_release:CGameInfo.CDotaGameInfo.CPlayerInfo.player_name) if (!_internal_has_player_name()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000002u; auto* p = _impl_.player_name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.player_name_.IsDefault()) { _impl_.player_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::set_allocated_player_name(std::string* player_name) { if (player_name != nullptr) { _impl_._has_bits_[0] |= 0x00000002u; } else { _impl_._has_bits_[0] &= ~0x00000002u; } _impl_.player_name_.SetAllocated(player_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.player_name_.IsDefault()) { _impl_.player_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CGameInfo.CDotaGameInfo.CPlayerInfo.player_name) } // optional bool is_fake_client = 3; inline bool CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_has_is_fake_client() const { bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo_CPlayerInfo::has_is_fake_client() const { return _internal_has_is_fake_client(); } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::clear_is_fake_client() { _impl_.is_fake_client_ = false; _impl_._has_bits_[0] &= ~0x00000008u; } inline bool CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_is_fake_client() const { return _impl_.is_fake_client_; } inline bool CGameInfo_CDotaGameInfo_CPlayerInfo::is_fake_client() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.CPlayerInfo.is_fake_client) return _internal_is_fake_client(); } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_set_is_fake_client(bool value) { _impl_._has_bits_[0] |= 0x00000008u; _impl_.is_fake_client_ = value; } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::set_is_fake_client(bool value) { _internal_set_is_fake_client(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.CPlayerInfo.is_fake_client) } // optional uint64 steamid = 4; inline bool CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_has_steamid() const { bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo_CPlayerInfo::has_steamid() const { return _internal_has_steamid(); } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::clear_steamid() { _impl_.steamid_ = uint64_t{0u}; _impl_._has_bits_[0] &= ~0x00000004u; } inline uint64_t CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_steamid() const { return _impl_.steamid_; } inline uint64_t CGameInfo_CDotaGameInfo_CPlayerInfo::steamid() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.CPlayerInfo.steamid) return _internal_steamid(); } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_set_steamid(uint64_t value) { _impl_._has_bits_[0] |= 0x00000004u; _impl_.steamid_ = value; } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::set_steamid(uint64_t value) { _internal_set_steamid(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.CPlayerInfo.steamid) } // optional int32 game_team = 5; inline bool CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_has_game_team() const { bool value = (_impl_._has_bits_[0] & 0x00000010u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo_CPlayerInfo::has_game_team() const { return _internal_has_game_team(); } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::clear_game_team() { _impl_.game_team_ = 0; _impl_._has_bits_[0] &= ~0x00000010u; } inline int32_t CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_game_team() const { return _impl_.game_team_; } inline int32_t CGameInfo_CDotaGameInfo_CPlayerInfo::game_team() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.CPlayerInfo.game_team) return _internal_game_team(); } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::_internal_set_game_team(int32_t value) { _impl_._has_bits_[0] |= 0x00000010u; _impl_.game_team_ = value; } inline void CGameInfo_CDotaGameInfo_CPlayerInfo::set_game_team(int32_t value) { _internal_set_game_team(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.CPlayerInfo.game_team) } // ------------------------------------------------------------------- // CGameInfo_CDotaGameInfo_CHeroSelectEvent // optional bool is_pick = 1; inline bool CGameInfo_CDotaGameInfo_CHeroSelectEvent::_internal_has_is_pick() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo_CHeroSelectEvent::has_is_pick() const { return _internal_has_is_pick(); } inline void CGameInfo_CDotaGameInfo_CHeroSelectEvent::clear_is_pick() { _impl_.is_pick_ = false; _impl_._has_bits_[0] &= ~0x00000001u; } inline bool CGameInfo_CDotaGameInfo_CHeroSelectEvent::_internal_is_pick() const { return _impl_.is_pick_; } inline bool CGameInfo_CDotaGameInfo_CHeroSelectEvent::is_pick() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.CHeroSelectEvent.is_pick) return _internal_is_pick(); } inline void CGameInfo_CDotaGameInfo_CHeroSelectEvent::_internal_set_is_pick(bool value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.is_pick_ = value; } inline void CGameInfo_CDotaGameInfo_CHeroSelectEvent::set_is_pick(bool value) { _internal_set_is_pick(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.CHeroSelectEvent.is_pick) } // optional uint32 team = 2; inline bool CGameInfo_CDotaGameInfo_CHeroSelectEvent::_internal_has_team() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo_CHeroSelectEvent::has_team() const { return _internal_has_team(); } inline void CGameInfo_CDotaGameInfo_CHeroSelectEvent::clear_team() { _impl_.team_ = 0u; _impl_._has_bits_[0] &= ~0x00000002u; } inline uint32_t CGameInfo_CDotaGameInfo_CHeroSelectEvent::_internal_team() const { return _impl_.team_; } inline uint32_t CGameInfo_CDotaGameInfo_CHeroSelectEvent::team() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.CHeroSelectEvent.team) return _internal_team(); } inline void CGameInfo_CDotaGameInfo_CHeroSelectEvent::_internal_set_team(uint32_t value) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.team_ = value; } inline void CGameInfo_CDotaGameInfo_CHeroSelectEvent::set_team(uint32_t value) { _internal_set_team(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.CHeroSelectEvent.team) } // optional uint32 hero_id = 3; inline bool CGameInfo_CDotaGameInfo_CHeroSelectEvent::_internal_has_hero_id() const { bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo_CHeroSelectEvent::has_hero_id() const { return _internal_has_hero_id(); } inline void CGameInfo_CDotaGameInfo_CHeroSelectEvent::clear_hero_id() { _impl_.hero_id_ = 0u; _impl_._has_bits_[0] &= ~0x00000004u; } inline uint32_t CGameInfo_CDotaGameInfo_CHeroSelectEvent::_internal_hero_id() const { return _impl_.hero_id_; } inline uint32_t CGameInfo_CDotaGameInfo_CHeroSelectEvent::hero_id() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.CHeroSelectEvent.hero_id) return _internal_hero_id(); } inline void CGameInfo_CDotaGameInfo_CHeroSelectEvent::_internal_set_hero_id(uint32_t value) { _impl_._has_bits_[0] |= 0x00000004u; _impl_.hero_id_ = value; } inline void CGameInfo_CDotaGameInfo_CHeroSelectEvent::set_hero_id(uint32_t value) { _internal_set_hero_id(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.CHeroSelectEvent.hero_id) } // ------------------------------------------------------------------- // CGameInfo_CDotaGameInfo // optional uint64 match_id = 1; inline bool CGameInfo_CDotaGameInfo::_internal_has_match_id() const { bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo::has_match_id() const { return _internal_has_match_id(); } inline void CGameInfo_CDotaGameInfo::clear_match_id() { _impl_.match_id_ = uint64_t{0u}; _impl_._has_bits_[0] &= ~0x00000004u; } inline uint64_t CGameInfo_CDotaGameInfo::_internal_match_id() const { return _impl_.match_id_; } inline uint64_t CGameInfo_CDotaGameInfo::match_id() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.match_id) return _internal_match_id(); } inline void CGameInfo_CDotaGameInfo::_internal_set_match_id(uint64_t value) { _impl_._has_bits_[0] |= 0x00000004u; _impl_.match_id_ = value; } inline void CGameInfo_CDotaGameInfo::set_match_id(uint64_t value) { _internal_set_match_id(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.match_id) } // optional int32 game_mode = 2; inline bool CGameInfo_CDotaGameInfo::_internal_has_game_mode() const { bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo::has_game_mode() const { return _internal_has_game_mode(); } inline void CGameInfo_CDotaGameInfo::clear_game_mode() { _impl_.game_mode_ = 0; _impl_._has_bits_[0] &= ~0x00000008u; } inline int32_t CGameInfo_CDotaGameInfo::_internal_game_mode() const { return _impl_.game_mode_; } inline int32_t CGameInfo_CDotaGameInfo::game_mode() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.game_mode) return _internal_game_mode(); } inline void CGameInfo_CDotaGameInfo::_internal_set_game_mode(int32_t value) { _impl_._has_bits_[0] |= 0x00000008u; _impl_.game_mode_ = value; } inline void CGameInfo_CDotaGameInfo::set_game_mode(int32_t value) { _internal_set_game_mode(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.game_mode) } // optional int32 game_winner = 3; inline bool CGameInfo_CDotaGameInfo::_internal_has_game_winner() const { bool value = (_impl_._has_bits_[0] & 0x00000010u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo::has_game_winner() const { return _internal_has_game_winner(); } inline void CGameInfo_CDotaGameInfo::clear_game_winner() { _impl_.game_winner_ = 0; _impl_._has_bits_[0] &= ~0x00000010u; } inline int32_t CGameInfo_CDotaGameInfo::_internal_game_winner() const { return _impl_.game_winner_; } inline int32_t CGameInfo_CDotaGameInfo::game_winner() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.game_winner) return _internal_game_winner(); } inline void CGameInfo_CDotaGameInfo::_internal_set_game_winner(int32_t value) { _impl_._has_bits_[0] |= 0x00000010u; _impl_.game_winner_ = value; } inline void CGameInfo_CDotaGameInfo::set_game_winner(int32_t value) { _internal_set_game_winner(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.game_winner) } // repeated .CGameInfo.CDotaGameInfo.CPlayerInfo player_info = 4; inline int CGameInfo_CDotaGameInfo::_internal_player_info_size() const { return _impl_.player_info_.size(); } inline int CGameInfo_CDotaGameInfo::player_info_size() const { return _internal_player_info_size(); } inline void CGameInfo_CDotaGameInfo::clear_player_info() { _impl_.player_info_.Clear(); } inline ::CGameInfo_CDotaGameInfo_CPlayerInfo* CGameInfo_CDotaGameInfo::mutable_player_info(int index) { // @@protoc_insertion_point(field_mutable:CGameInfo.CDotaGameInfo.player_info) return _impl_.player_info_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CGameInfo_CDotaGameInfo_CPlayerInfo >* CGameInfo_CDotaGameInfo::mutable_player_info() { // @@protoc_insertion_point(field_mutable_list:CGameInfo.CDotaGameInfo.player_info) return &_impl_.player_info_; } inline const ::CGameInfo_CDotaGameInfo_CPlayerInfo& CGameInfo_CDotaGameInfo::_internal_player_info(int index) const { return _impl_.player_info_.Get(index); } inline const ::CGameInfo_CDotaGameInfo_CPlayerInfo& CGameInfo_CDotaGameInfo::player_info(int index) const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.player_info) return _internal_player_info(index); } inline ::CGameInfo_CDotaGameInfo_CPlayerInfo* CGameInfo_CDotaGameInfo::_internal_add_player_info() { return _impl_.player_info_.Add(); } inline ::CGameInfo_CDotaGameInfo_CPlayerInfo* CGameInfo_CDotaGameInfo::add_player_info() { ::CGameInfo_CDotaGameInfo_CPlayerInfo* _add = _internal_add_player_info(); // @@protoc_insertion_point(field_add:CGameInfo.CDotaGameInfo.player_info) return _add; } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CGameInfo_CDotaGameInfo_CPlayerInfo >& CGameInfo_CDotaGameInfo::player_info() const { // @@protoc_insertion_point(field_list:CGameInfo.CDotaGameInfo.player_info) return _impl_.player_info_; } // optional uint32 leagueid = 5; inline bool CGameInfo_CDotaGameInfo::_internal_has_leagueid() const { bool value = (_impl_._has_bits_[0] & 0x00000020u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo::has_leagueid() const { return _internal_has_leagueid(); } inline void CGameInfo_CDotaGameInfo::clear_leagueid() { _impl_.leagueid_ = 0u; _impl_._has_bits_[0] &= ~0x00000020u; } inline uint32_t CGameInfo_CDotaGameInfo::_internal_leagueid() const { return _impl_.leagueid_; } inline uint32_t CGameInfo_CDotaGameInfo::leagueid() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.leagueid) return _internal_leagueid(); } inline void CGameInfo_CDotaGameInfo::_internal_set_leagueid(uint32_t value) { _impl_._has_bits_[0] |= 0x00000020u; _impl_.leagueid_ = value; } inline void CGameInfo_CDotaGameInfo::set_leagueid(uint32_t value) { _internal_set_leagueid(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.leagueid) } // repeated .CGameInfo.CDotaGameInfo.CHeroSelectEvent picks_bans = 6; inline int CGameInfo_CDotaGameInfo::_internal_picks_bans_size() const { return _impl_.picks_bans_.size(); } inline int CGameInfo_CDotaGameInfo::picks_bans_size() const { return _internal_picks_bans_size(); } inline void CGameInfo_CDotaGameInfo::clear_picks_bans() { _impl_.picks_bans_.Clear(); } inline ::CGameInfo_CDotaGameInfo_CHeroSelectEvent* CGameInfo_CDotaGameInfo::mutable_picks_bans(int index) { // @@protoc_insertion_point(field_mutable:CGameInfo.CDotaGameInfo.picks_bans) return _impl_.picks_bans_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CGameInfo_CDotaGameInfo_CHeroSelectEvent >* CGameInfo_CDotaGameInfo::mutable_picks_bans() { // @@protoc_insertion_point(field_mutable_list:CGameInfo.CDotaGameInfo.picks_bans) return &_impl_.picks_bans_; } inline const ::CGameInfo_CDotaGameInfo_CHeroSelectEvent& CGameInfo_CDotaGameInfo::_internal_picks_bans(int index) const { return _impl_.picks_bans_.Get(index); } inline const ::CGameInfo_CDotaGameInfo_CHeroSelectEvent& CGameInfo_CDotaGameInfo::picks_bans(int index) const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.picks_bans) return _internal_picks_bans(index); } inline ::CGameInfo_CDotaGameInfo_CHeroSelectEvent* CGameInfo_CDotaGameInfo::_internal_add_picks_bans() { return _impl_.picks_bans_.Add(); } inline ::CGameInfo_CDotaGameInfo_CHeroSelectEvent* CGameInfo_CDotaGameInfo::add_picks_bans() { ::CGameInfo_CDotaGameInfo_CHeroSelectEvent* _add = _internal_add_picks_bans(); // @@protoc_insertion_point(field_add:CGameInfo.CDotaGameInfo.picks_bans) return _add; } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CGameInfo_CDotaGameInfo_CHeroSelectEvent >& CGameInfo_CDotaGameInfo::picks_bans() const { // @@protoc_insertion_point(field_list:CGameInfo.CDotaGameInfo.picks_bans) return _impl_.picks_bans_; } // optional uint32 radiant_team_id = 7; inline bool CGameInfo_CDotaGameInfo::_internal_has_radiant_team_id() const { bool value = (_impl_._has_bits_[0] & 0x00000040u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo::has_radiant_team_id() const { return _internal_has_radiant_team_id(); } inline void CGameInfo_CDotaGameInfo::clear_radiant_team_id() { _impl_.radiant_team_id_ = 0u; _impl_._has_bits_[0] &= ~0x00000040u; } inline uint32_t CGameInfo_CDotaGameInfo::_internal_radiant_team_id() const { return _impl_.radiant_team_id_; } inline uint32_t CGameInfo_CDotaGameInfo::radiant_team_id() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.radiant_team_id) return _internal_radiant_team_id(); } inline void CGameInfo_CDotaGameInfo::_internal_set_radiant_team_id(uint32_t value) { _impl_._has_bits_[0] |= 0x00000040u; _impl_.radiant_team_id_ = value; } inline void CGameInfo_CDotaGameInfo::set_radiant_team_id(uint32_t value) { _internal_set_radiant_team_id(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.radiant_team_id) } // optional uint32 dire_team_id = 8; inline bool CGameInfo_CDotaGameInfo::_internal_has_dire_team_id() const { bool value = (_impl_._has_bits_[0] & 0x00000080u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo::has_dire_team_id() const { return _internal_has_dire_team_id(); } inline void CGameInfo_CDotaGameInfo::clear_dire_team_id() { _impl_.dire_team_id_ = 0u; _impl_._has_bits_[0] &= ~0x00000080u; } inline uint32_t CGameInfo_CDotaGameInfo::_internal_dire_team_id() const { return _impl_.dire_team_id_; } inline uint32_t CGameInfo_CDotaGameInfo::dire_team_id() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.dire_team_id) return _internal_dire_team_id(); } inline void CGameInfo_CDotaGameInfo::_internal_set_dire_team_id(uint32_t value) { _impl_._has_bits_[0] |= 0x00000080u; _impl_.dire_team_id_ = value; } inline void CGameInfo_CDotaGameInfo::set_dire_team_id(uint32_t value) { _internal_set_dire_team_id(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.dire_team_id) } // optional string radiant_team_tag = 9; inline bool CGameInfo_CDotaGameInfo::_internal_has_radiant_team_tag() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo::has_radiant_team_tag() const { return _internal_has_radiant_team_tag(); } inline void CGameInfo_CDotaGameInfo::clear_radiant_team_tag() { _impl_.radiant_team_tag_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CGameInfo_CDotaGameInfo::radiant_team_tag() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.radiant_team_tag) return _internal_radiant_team_tag(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CGameInfo_CDotaGameInfo::set_radiant_team_tag(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.radiant_team_tag_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.radiant_team_tag) } inline std::string* CGameInfo_CDotaGameInfo::mutable_radiant_team_tag() { std::string* _s = _internal_mutable_radiant_team_tag(); // @@protoc_insertion_point(field_mutable:CGameInfo.CDotaGameInfo.radiant_team_tag) return _s; } inline const std::string& CGameInfo_CDotaGameInfo::_internal_radiant_team_tag() const { return _impl_.radiant_team_tag_.Get(); } inline void CGameInfo_CDotaGameInfo::_internal_set_radiant_team_tag(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.radiant_team_tag_.Set(value, GetArenaForAllocation()); } inline std::string* CGameInfo_CDotaGameInfo::_internal_mutable_radiant_team_tag() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.radiant_team_tag_.Mutable(GetArenaForAllocation()); } inline std::string* CGameInfo_CDotaGameInfo::release_radiant_team_tag() { // @@protoc_insertion_point(field_release:CGameInfo.CDotaGameInfo.radiant_team_tag) if (!_internal_has_radiant_team_tag()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.radiant_team_tag_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.radiant_team_tag_.IsDefault()) { _impl_.radiant_team_tag_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CGameInfo_CDotaGameInfo::set_allocated_radiant_team_tag(std::string* radiant_team_tag) { if (radiant_team_tag != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.radiant_team_tag_.SetAllocated(radiant_team_tag, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.radiant_team_tag_.IsDefault()) { _impl_.radiant_team_tag_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CGameInfo.CDotaGameInfo.radiant_team_tag) } // optional string dire_team_tag = 10; inline bool CGameInfo_CDotaGameInfo::_internal_has_dire_team_tag() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo::has_dire_team_tag() const { return _internal_has_dire_team_tag(); } inline void CGameInfo_CDotaGameInfo::clear_dire_team_tag() { _impl_.dire_team_tag_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000002u; } inline const std::string& CGameInfo_CDotaGameInfo::dire_team_tag() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.dire_team_tag) return _internal_dire_team_tag(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CGameInfo_CDotaGameInfo::set_dire_team_tag(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.dire_team_tag_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.dire_team_tag) } inline std::string* CGameInfo_CDotaGameInfo::mutable_dire_team_tag() { std::string* _s = _internal_mutable_dire_team_tag(); // @@protoc_insertion_point(field_mutable:CGameInfo.CDotaGameInfo.dire_team_tag) return _s; } inline const std::string& CGameInfo_CDotaGameInfo::_internal_dire_team_tag() const { return _impl_.dire_team_tag_.Get(); } inline void CGameInfo_CDotaGameInfo::_internal_set_dire_team_tag(const std::string& value) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.dire_team_tag_.Set(value, GetArenaForAllocation()); } inline std::string* CGameInfo_CDotaGameInfo::_internal_mutable_dire_team_tag() { _impl_._has_bits_[0] |= 0x00000002u; return _impl_.dire_team_tag_.Mutable(GetArenaForAllocation()); } inline std::string* CGameInfo_CDotaGameInfo::release_dire_team_tag() { // @@protoc_insertion_point(field_release:CGameInfo.CDotaGameInfo.dire_team_tag) if (!_internal_has_dire_team_tag()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000002u; auto* p = _impl_.dire_team_tag_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.dire_team_tag_.IsDefault()) { _impl_.dire_team_tag_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CGameInfo_CDotaGameInfo::set_allocated_dire_team_tag(std::string* dire_team_tag) { if (dire_team_tag != nullptr) { _impl_._has_bits_[0] |= 0x00000002u; } else { _impl_._has_bits_[0] &= ~0x00000002u; } _impl_.dire_team_tag_.SetAllocated(dire_team_tag, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.dire_team_tag_.IsDefault()) { _impl_.dire_team_tag_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CGameInfo.CDotaGameInfo.dire_team_tag) } // optional uint32 end_time = 11; inline bool CGameInfo_CDotaGameInfo::_internal_has_end_time() const { bool value = (_impl_._has_bits_[0] & 0x00000100u) != 0; return value; } inline bool CGameInfo_CDotaGameInfo::has_end_time() const { return _internal_has_end_time(); } inline void CGameInfo_CDotaGameInfo::clear_end_time() { _impl_.end_time_ = 0u; _impl_._has_bits_[0] &= ~0x00000100u; } inline uint32_t CGameInfo_CDotaGameInfo::_internal_end_time() const { return _impl_.end_time_; } inline uint32_t CGameInfo_CDotaGameInfo::end_time() const { // @@protoc_insertion_point(field_get:CGameInfo.CDotaGameInfo.end_time) return _internal_end_time(); } inline void CGameInfo_CDotaGameInfo::_internal_set_end_time(uint32_t value) { _impl_._has_bits_[0] |= 0x00000100u; _impl_.end_time_ = value; } inline void CGameInfo_CDotaGameInfo::set_end_time(uint32_t value) { _internal_set_end_time(value); // @@protoc_insertion_point(field_set:CGameInfo.CDotaGameInfo.end_time) } // ------------------------------------------------------------------- // CGameInfo // optional .CGameInfo.CDotaGameInfo dota = 4; inline bool CGameInfo::_internal_has_dota() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; PROTOBUF_ASSUME(!value || _impl_.dota_ != nullptr); return value; } inline bool CGameInfo::has_dota() const { return _internal_has_dota(); } inline void CGameInfo::clear_dota() { if (_impl_.dota_ != nullptr) _impl_.dota_->Clear(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const ::CGameInfo_CDotaGameInfo& CGameInfo::_internal_dota() const { const ::CGameInfo_CDotaGameInfo* p = _impl_.dota_; return p != nullptr ? *p : reinterpret_cast<const ::CGameInfo_CDotaGameInfo&>( ::_CGameInfo_CDotaGameInfo_default_instance_); } inline const ::CGameInfo_CDotaGameInfo& CGameInfo::dota() const { // @@protoc_insertion_point(field_get:CGameInfo.dota) return _internal_dota(); } inline void CGameInfo::unsafe_arena_set_allocated_dota( ::CGameInfo_CDotaGameInfo* dota) { if (GetArenaForAllocation() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.dota_); } _impl_.dota_ = dota; if (dota) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:CGameInfo.dota) } inline ::CGameInfo_CDotaGameInfo* CGameInfo::release_dota() { _impl_._has_bits_[0] &= ~0x00000001u; ::CGameInfo_CDotaGameInfo* temp = _impl_.dota_; _impl_.dota_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); if (GetArenaForAllocation() == nullptr) { delete old; } #else // PROTOBUF_FORCE_COPY_IN_RELEASE if (GetArenaForAllocation() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } #endif // !PROTOBUF_FORCE_COPY_IN_RELEASE return temp; } inline ::CGameInfo_CDotaGameInfo* CGameInfo::unsafe_arena_release_dota() { // @@protoc_insertion_point(field_release:CGameInfo.dota) _impl_._has_bits_[0] &= ~0x00000001u; ::CGameInfo_CDotaGameInfo* temp = _impl_.dota_; _impl_.dota_ = nullptr; return temp; } inline ::CGameInfo_CDotaGameInfo* CGameInfo::_internal_mutable_dota() { _impl_._has_bits_[0] |= 0x00000001u; if (_impl_.dota_ == nullptr) { auto* p = CreateMaybeMessage<::CGameInfo_CDotaGameInfo>(GetArenaForAllocation()); _impl_.dota_ = p; } return _impl_.dota_; } inline ::CGameInfo_CDotaGameInfo* CGameInfo::mutable_dota() { ::CGameInfo_CDotaGameInfo* _msg = _internal_mutable_dota(); // @@protoc_insertion_point(field_mutable:CGameInfo.dota) return _msg; } inline void CGameInfo::set_allocated_dota(::CGameInfo_CDotaGameInfo* dota) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { delete _impl_.dota_; } if (dota) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(dota); if (message_arena != submessage_arena) { dota = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, dota, submessage_arena); } _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.dota_ = dota; // @@protoc_insertion_point(field_set_allocated:CGameInfo.dota) } // ------------------------------------------------------------------- // CDemoFileInfo // optional float playback_time = 1; inline bool CDemoFileInfo::_internal_has_playback_time() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CDemoFileInfo::has_playback_time() const { return _internal_has_playback_time(); } inline void CDemoFileInfo::clear_playback_time() { _impl_.playback_time_ = 0; _impl_._has_bits_[0] &= ~0x00000002u; } inline float CDemoFileInfo::_internal_playback_time() const { return _impl_.playback_time_; } inline float CDemoFileInfo::playback_time() const { // @@protoc_insertion_point(field_get:CDemoFileInfo.playback_time) return _internal_playback_time(); } inline void CDemoFileInfo::_internal_set_playback_time(float value) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.playback_time_ = value; } inline void CDemoFileInfo::set_playback_time(float value) { _internal_set_playback_time(value); // @@protoc_insertion_point(field_set:CDemoFileInfo.playback_time) } // optional int32 playback_ticks = 2; inline bool CDemoFileInfo::_internal_has_playback_ticks() const { bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool CDemoFileInfo::has_playback_ticks() const { return _internal_has_playback_ticks(); } inline void CDemoFileInfo::clear_playback_ticks() { _impl_.playback_ticks_ = 0; _impl_._has_bits_[0] &= ~0x00000004u; } inline int32_t CDemoFileInfo::_internal_playback_ticks() const { return _impl_.playback_ticks_; } inline int32_t CDemoFileInfo::playback_ticks() const { // @@protoc_insertion_point(field_get:CDemoFileInfo.playback_ticks) return _internal_playback_ticks(); } inline void CDemoFileInfo::_internal_set_playback_ticks(int32_t value) { _impl_._has_bits_[0] |= 0x00000004u; _impl_.playback_ticks_ = value; } inline void CDemoFileInfo::set_playback_ticks(int32_t value) { _internal_set_playback_ticks(value); // @@protoc_insertion_point(field_set:CDemoFileInfo.playback_ticks) } // optional int32 playback_frames = 3; inline bool CDemoFileInfo::_internal_has_playback_frames() const { bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; return value; } inline bool CDemoFileInfo::has_playback_frames() const { return _internal_has_playback_frames(); } inline void CDemoFileInfo::clear_playback_frames() { _impl_.playback_frames_ = 0; _impl_._has_bits_[0] &= ~0x00000008u; } inline int32_t CDemoFileInfo::_internal_playback_frames() const { return _impl_.playback_frames_; } inline int32_t CDemoFileInfo::playback_frames() const { // @@protoc_insertion_point(field_get:CDemoFileInfo.playback_frames) return _internal_playback_frames(); } inline void CDemoFileInfo::_internal_set_playback_frames(int32_t value) { _impl_._has_bits_[0] |= 0x00000008u; _impl_.playback_frames_ = value; } inline void CDemoFileInfo::set_playback_frames(int32_t value) { _internal_set_playback_frames(value); // @@protoc_insertion_point(field_set:CDemoFileInfo.playback_frames) } // optional .CGameInfo game_info = 4; inline bool CDemoFileInfo::_internal_has_game_info() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; PROTOBUF_ASSUME(!value || _impl_.game_info_ != nullptr); return value; } inline bool CDemoFileInfo::has_game_info() const { return _internal_has_game_info(); } inline void CDemoFileInfo::clear_game_info() { if (_impl_.game_info_ != nullptr) _impl_.game_info_->Clear(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const ::CGameInfo& CDemoFileInfo::_internal_game_info() const { const ::CGameInfo* p = _impl_.game_info_; return p != nullptr ? *p : reinterpret_cast<const ::CGameInfo&>( ::_CGameInfo_default_instance_); } inline const ::CGameInfo& CDemoFileInfo::game_info() const { // @@protoc_insertion_point(field_get:CDemoFileInfo.game_info) return _internal_game_info(); } inline void CDemoFileInfo::unsafe_arena_set_allocated_game_info( ::CGameInfo* game_info) { if (GetArenaForAllocation() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.game_info_); } _impl_.game_info_ = game_info; if (game_info) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:CDemoFileInfo.game_info) } inline ::CGameInfo* CDemoFileInfo::release_game_info() { _impl_._has_bits_[0] &= ~0x00000001u; ::CGameInfo* temp = _impl_.game_info_; _impl_.game_info_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); if (GetArenaForAllocation() == nullptr) { delete old; } #else // PROTOBUF_FORCE_COPY_IN_RELEASE if (GetArenaForAllocation() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } #endif // !PROTOBUF_FORCE_COPY_IN_RELEASE return temp; } inline ::CGameInfo* CDemoFileInfo::unsafe_arena_release_game_info() { // @@protoc_insertion_point(field_release:CDemoFileInfo.game_info) _impl_._has_bits_[0] &= ~0x00000001u; ::CGameInfo* temp = _impl_.game_info_; _impl_.game_info_ = nullptr; return temp; } inline ::CGameInfo* CDemoFileInfo::_internal_mutable_game_info() { _impl_._has_bits_[0] |= 0x00000001u; if (_impl_.game_info_ == nullptr) { auto* p = CreateMaybeMessage<::CGameInfo>(GetArenaForAllocation()); _impl_.game_info_ = p; } return _impl_.game_info_; } inline ::CGameInfo* CDemoFileInfo::mutable_game_info() { ::CGameInfo* _msg = _internal_mutable_game_info(); // @@protoc_insertion_point(field_mutable:CDemoFileInfo.game_info) return _msg; } inline void CDemoFileInfo::set_allocated_game_info(::CGameInfo* game_info) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { delete _impl_.game_info_; } if (game_info) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(game_info); if (message_arena != submessage_arena) { game_info = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, game_info, submessage_arena); } _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.game_info_ = game_info; // @@protoc_insertion_point(field_set_allocated:CDemoFileInfo.game_info) } // ------------------------------------------------------------------- // CDemoPacket // optional bytes data = 3; inline bool CDemoPacket::_internal_has_data() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CDemoPacket::has_data() const { return _internal_has_data(); } inline void CDemoPacket::clear_data() { _impl_.data_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CDemoPacket::data() const { // @@protoc_insertion_point(field_get:CDemoPacket.data) return _internal_data(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoPacket::set_data(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.data_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoPacket.data) } inline std::string* CDemoPacket::mutable_data() { std::string* _s = _internal_mutable_data(); // @@protoc_insertion_point(field_mutable:CDemoPacket.data) return _s; } inline const std::string& CDemoPacket::_internal_data() const { return _impl_.data_.Get(); } inline void CDemoPacket::_internal_set_data(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.data_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoPacket::_internal_mutable_data() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.data_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoPacket::release_data() { // @@protoc_insertion_point(field_release:CDemoPacket.data) if (!_internal_has_data()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.data_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoPacket::set_allocated_data(std::string* data) { if (data != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.data_.SetAllocated(data, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoPacket.data) } // ------------------------------------------------------------------- // CDemoFullPacket // optional .CDemoStringTables string_table = 1; inline bool CDemoFullPacket::_internal_has_string_table() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; PROTOBUF_ASSUME(!value || _impl_.string_table_ != nullptr); return value; } inline bool CDemoFullPacket::has_string_table() const { return _internal_has_string_table(); } inline void CDemoFullPacket::clear_string_table() { if (_impl_.string_table_ != nullptr) _impl_.string_table_->Clear(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const ::CDemoStringTables& CDemoFullPacket::_internal_string_table() const { const ::CDemoStringTables* p = _impl_.string_table_; return p != nullptr ? *p : reinterpret_cast<const ::CDemoStringTables&>( ::_CDemoStringTables_default_instance_); } inline const ::CDemoStringTables& CDemoFullPacket::string_table() const { // @@protoc_insertion_point(field_get:CDemoFullPacket.string_table) return _internal_string_table(); } inline void CDemoFullPacket::unsafe_arena_set_allocated_string_table( ::CDemoStringTables* string_table) { if (GetArenaForAllocation() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.string_table_); } _impl_.string_table_ = string_table; if (string_table) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:CDemoFullPacket.string_table) } inline ::CDemoStringTables* CDemoFullPacket::release_string_table() { _impl_._has_bits_[0] &= ~0x00000001u; ::CDemoStringTables* temp = _impl_.string_table_; _impl_.string_table_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); if (GetArenaForAllocation() == nullptr) { delete old; } #else // PROTOBUF_FORCE_COPY_IN_RELEASE if (GetArenaForAllocation() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } #endif // !PROTOBUF_FORCE_COPY_IN_RELEASE return temp; } inline ::CDemoStringTables* CDemoFullPacket::unsafe_arena_release_string_table() { // @@protoc_insertion_point(field_release:CDemoFullPacket.string_table) _impl_._has_bits_[0] &= ~0x00000001u; ::CDemoStringTables* temp = _impl_.string_table_; _impl_.string_table_ = nullptr; return temp; } inline ::CDemoStringTables* CDemoFullPacket::_internal_mutable_string_table() { _impl_._has_bits_[0] |= 0x00000001u; if (_impl_.string_table_ == nullptr) { auto* p = CreateMaybeMessage<::CDemoStringTables>(GetArenaForAllocation()); _impl_.string_table_ = p; } return _impl_.string_table_; } inline ::CDemoStringTables* CDemoFullPacket::mutable_string_table() { ::CDemoStringTables* _msg = _internal_mutable_string_table(); // @@protoc_insertion_point(field_mutable:CDemoFullPacket.string_table) return _msg; } inline void CDemoFullPacket::set_allocated_string_table(::CDemoStringTables* string_table) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { delete _impl_.string_table_; } if (string_table) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(string_table); if (message_arena != submessage_arena) { string_table = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, string_table, submessage_arena); } _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.string_table_ = string_table; // @@protoc_insertion_point(field_set_allocated:CDemoFullPacket.string_table) } // optional .CDemoPacket packet = 2; inline bool CDemoFullPacket::_internal_has_packet() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; PROTOBUF_ASSUME(!value || _impl_.packet_ != nullptr); return value; } inline bool CDemoFullPacket::has_packet() const { return _internal_has_packet(); } inline void CDemoFullPacket::clear_packet() { if (_impl_.packet_ != nullptr) _impl_.packet_->Clear(); _impl_._has_bits_[0] &= ~0x00000002u; } inline const ::CDemoPacket& CDemoFullPacket::_internal_packet() const { const ::CDemoPacket* p = _impl_.packet_; return p != nullptr ? *p : reinterpret_cast<const ::CDemoPacket&>( ::_CDemoPacket_default_instance_); } inline const ::CDemoPacket& CDemoFullPacket::packet() const { // @@protoc_insertion_point(field_get:CDemoFullPacket.packet) return _internal_packet(); } inline void CDemoFullPacket::unsafe_arena_set_allocated_packet( ::CDemoPacket* packet) { if (GetArenaForAllocation() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.packet_); } _impl_.packet_ = packet; if (packet) { _impl_._has_bits_[0] |= 0x00000002u; } else { _impl_._has_bits_[0] &= ~0x00000002u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:CDemoFullPacket.packet) } inline ::CDemoPacket* CDemoFullPacket::release_packet() { _impl_._has_bits_[0] &= ~0x00000002u; ::CDemoPacket* temp = _impl_.packet_; _impl_.packet_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); if (GetArenaForAllocation() == nullptr) { delete old; } #else // PROTOBUF_FORCE_COPY_IN_RELEASE if (GetArenaForAllocation() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } #endif // !PROTOBUF_FORCE_COPY_IN_RELEASE return temp; } inline ::CDemoPacket* CDemoFullPacket::unsafe_arena_release_packet() { // @@protoc_insertion_point(field_release:CDemoFullPacket.packet) _impl_._has_bits_[0] &= ~0x00000002u; ::CDemoPacket* temp = _impl_.packet_; _impl_.packet_ = nullptr; return temp; } inline ::CDemoPacket* CDemoFullPacket::_internal_mutable_packet() { _impl_._has_bits_[0] |= 0x00000002u; if (_impl_.packet_ == nullptr) { auto* p = CreateMaybeMessage<::CDemoPacket>(GetArenaForAllocation()); _impl_.packet_ = p; } return _impl_.packet_; } inline ::CDemoPacket* CDemoFullPacket::mutable_packet() { ::CDemoPacket* _msg = _internal_mutable_packet(); // @@protoc_insertion_point(field_mutable:CDemoFullPacket.packet) return _msg; } inline void CDemoFullPacket::set_allocated_packet(::CDemoPacket* packet) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { delete _impl_.packet_; } if (packet) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(packet); if (message_arena != submessage_arena) { packet = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, packet, submessage_arena); } _impl_._has_bits_[0] |= 0x00000002u; } else { _impl_._has_bits_[0] &= ~0x00000002u; } _impl_.packet_ = packet; // @@protoc_insertion_point(field_set_allocated:CDemoFullPacket.packet) } // ------------------------------------------------------------------- // CDemoSaveGame // optional bytes data = 1; inline bool CDemoSaveGame::_internal_has_data() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CDemoSaveGame::has_data() const { return _internal_has_data(); } inline void CDemoSaveGame::clear_data() { _impl_.data_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CDemoSaveGame::data() const { // @@protoc_insertion_point(field_get:CDemoSaveGame.data) return _internal_data(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoSaveGame::set_data(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.data_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoSaveGame.data) } inline std::string* CDemoSaveGame::mutable_data() { std::string* _s = _internal_mutable_data(); // @@protoc_insertion_point(field_mutable:CDemoSaveGame.data) return _s; } inline const std::string& CDemoSaveGame::_internal_data() const { return _impl_.data_.Get(); } inline void CDemoSaveGame::_internal_set_data(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.data_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoSaveGame::_internal_mutable_data() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.data_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoSaveGame::release_data() { // @@protoc_insertion_point(field_release:CDemoSaveGame.data) if (!_internal_has_data()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.data_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoSaveGame::set_allocated_data(std::string* data) { if (data != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.data_.SetAllocated(data, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoSaveGame.data) } // optional fixed64 steam_id = 2; inline bool CDemoSaveGame::_internal_has_steam_id() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CDemoSaveGame::has_steam_id() const { return _internal_has_steam_id(); } inline void CDemoSaveGame::clear_steam_id() { _impl_.steam_id_ = uint64_t{0u}; _impl_._has_bits_[0] &= ~0x00000002u; } inline uint64_t CDemoSaveGame::_internal_steam_id() const { return _impl_.steam_id_; } inline uint64_t CDemoSaveGame::steam_id() const { // @@protoc_insertion_point(field_get:CDemoSaveGame.steam_id) return _internal_steam_id(); } inline void CDemoSaveGame::_internal_set_steam_id(uint64_t value) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.steam_id_ = value; } inline void CDemoSaveGame::set_steam_id(uint64_t value) { _internal_set_steam_id(value); // @@protoc_insertion_point(field_set:CDemoSaveGame.steam_id) } // optional fixed64 signature = 3; inline bool CDemoSaveGame::_internal_has_signature() const { bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool CDemoSaveGame::has_signature() const { return _internal_has_signature(); } inline void CDemoSaveGame::clear_signature() { _impl_.signature_ = uint64_t{0u}; _impl_._has_bits_[0] &= ~0x00000004u; } inline uint64_t CDemoSaveGame::_internal_signature() const { return _impl_.signature_; } inline uint64_t CDemoSaveGame::signature() const { // @@protoc_insertion_point(field_get:CDemoSaveGame.signature) return _internal_signature(); } inline void CDemoSaveGame::_internal_set_signature(uint64_t value) { _impl_._has_bits_[0] |= 0x00000004u; _impl_.signature_ = value; } inline void CDemoSaveGame::set_signature(uint64_t value) { _internal_set_signature(value); // @@protoc_insertion_point(field_set:CDemoSaveGame.signature) } // optional int32 version = 4; inline bool CDemoSaveGame::_internal_has_version() const { bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; return value; } inline bool CDemoSaveGame::has_version() const { return _internal_has_version(); } inline void CDemoSaveGame::clear_version() { _impl_.version_ = 0; _impl_._has_bits_[0] &= ~0x00000008u; } inline int32_t CDemoSaveGame::_internal_version() const { return _impl_.version_; } inline int32_t CDemoSaveGame::version() const { // @@protoc_insertion_point(field_get:CDemoSaveGame.version) return _internal_version(); } inline void CDemoSaveGame::_internal_set_version(int32_t value) { _impl_._has_bits_[0] |= 0x00000008u; _impl_.version_ = value; } inline void CDemoSaveGame::set_version(int32_t value) { _internal_set_version(value); // @@protoc_insertion_point(field_set:CDemoSaveGame.version) } // ------------------------------------------------------------------- // CDemoSyncTick // ------------------------------------------------------------------- // CDemoConsoleCmd // optional string cmdstring = 1; inline bool CDemoConsoleCmd::_internal_has_cmdstring() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CDemoConsoleCmd::has_cmdstring() const { return _internal_has_cmdstring(); } inline void CDemoConsoleCmd::clear_cmdstring() { _impl_.cmdstring_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CDemoConsoleCmd::cmdstring() const { // @@protoc_insertion_point(field_get:CDemoConsoleCmd.cmdstring) return _internal_cmdstring(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoConsoleCmd::set_cmdstring(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.cmdstring_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoConsoleCmd.cmdstring) } inline std::string* CDemoConsoleCmd::mutable_cmdstring() { std::string* _s = _internal_mutable_cmdstring(); // @@protoc_insertion_point(field_mutable:CDemoConsoleCmd.cmdstring) return _s; } inline const std::string& CDemoConsoleCmd::_internal_cmdstring() const { return _impl_.cmdstring_.Get(); } inline void CDemoConsoleCmd::_internal_set_cmdstring(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.cmdstring_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoConsoleCmd::_internal_mutable_cmdstring() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.cmdstring_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoConsoleCmd::release_cmdstring() { // @@protoc_insertion_point(field_release:CDemoConsoleCmd.cmdstring) if (!_internal_has_cmdstring()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.cmdstring_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.cmdstring_.IsDefault()) { _impl_.cmdstring_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoConsoleCmd::set_allocated_cmdstring(std::string* cmdstring) { if (cmdstring != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.cmdstring_.SetAllocated(cmdstring, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.cmdstring_.IsDefault()) { _impl_.cmdstring_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoConsoleCmd.cmdstring) } // ------------------------------------------------------------------- // CDemoSendTables // optional bytes data = 1; inline bool CDemoSendTables::_internal_has_data() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CDemoSendTables::has_data() const { return _internal_has_data(); } inline void CDemoSendTables::clear_data() { _impl_.data_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CDemoSendTables::data() const { // @@protoc_insertion_point(field_get:CDemoSendTables.data) return _internal_data(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoSendTables::set_data(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.data_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoSendTables.data) } inline std::string* CDemoSendTables::mutable_data() { std::string* _s = _internal_mutable_data(); // @@protoc_insertion_point(field_mutable:CDemoSendTables.data) return _s; } inline const std::string& CDemoSendTables::_internal_data() const { return _impl_.data_.Get(); } inline void CDemoSendTables::_internal_set_data(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.data_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoSendTables::_internal_mutable_data() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.data_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoSendTables::release_data() { // @@protoc_insertion_point(field_release:CDemoSendTables.data) if (!_internal_has_data()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.data_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoSendTables::set_allocated_data(std::string* data) { if (data != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.data_.SetAllocated(data, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoSendTables.data) } // ------------------------------------------------------------------- // CDemoClassInfo_class_t // optional int32 class_id = 1; inline bool CDemoClassInfo_class_t::_internal_has_class_id() const { bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool CDemoClassInfo_class_t::has_class_id() const { return _internal_has_class_id(); } inline void CDemoClassInfo_class_t::clear_class_id() { _impl_.class_id_ = 0; _impl_._has_bits_[0] &= ~0x00000004u; } inline int32_t CDemoClassInfo_class_t::_internal_class_id() const { return _impl_.class_id_; } inline int32_t CDemoClassInfo_class_t::class_id() const { // @@protoc_insertion_point(field_get:CDemoClassInfo.class_t.class_id) return _internal_class_id(); } inline void CDemoClassInfo_class_t::_internal_set_class_id(int32_t value) { _impl_._has_bits_[0] |= 0x00000004u; _impl_.class_id_ = value; } inline void CDemoClassInfo_class_t::set_class_id(int32_t value) { _internal_set_class_id(value); // @@protoc_insertion_point(field_set:CDemoClassInfo.class_t.class_id) } // optional string network_name = 2; inline bool CDemoClassInfo_class_t::_internal_has_network_name() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CDemoClassInfo_class_t::has_network_name() const { return _internal_has_network_name(); } inline void CDemoClassInfo_class_t::clear_network_name() { _impl_.network_name_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CDemoClassInfo_class_t::network_name() const { // @@protoc_insertion_point(field_get:CDemoClassInfo.class_t.network_name) return _internal_network_name(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoClassInfo_class_t::set_network_name(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.network_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoClassInfo.class_t.network_name) } inline std::string* CDemoClassInfo_class_t::mutable_network_name() { std::string* _s = _internal_mutable_network_name(); // @@protoc_insertion_point(field_mutable:CDemoClassInfo.class_t.network_name) return _s; } inline const std::string& CDemoClassInfo_class_t::_internal_network_name() const { return _impl_.network_name_.Get(); } inline void CDemoClassInfo_class_t::_internal_set_network_name(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.network_name_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoClassInfo_class_t::_internal_mutable_network_name() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.network_name_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoClassInfo_class_t::release_network_name() { // @@protoc_insertion_point(field_release:CDemoClassInfo.class_t.network_name) if (!_internal_has_network_name()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.network_name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.network_name_.IsDefault()) { _impl_.network_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoClassInfo_class_t::set_allocated_network_name(std::string* network_name) { if (network_name != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.network_name_.SetAllocated(network_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.network_name_.IsDefault()) { _impl_.network_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoClassInfo.class_t.network_name) } // optional string table_name = 3; inline bool CDemoClassInfo_class_t::_internal_has_table_name() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CDemoClassInfo_class_t::has_table_name() const { return _internal_has_table_name(); } inline void CDemoClassInfo_class_t::clear_table_name() { _impl_.table_name_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000002u; } inline const std::string& CDemoClassInfo_class_t::table_name() const { // @@protoc_insertion_point(field_get:CDemoClassInfo.class_t.table_name) return _internal_table_name(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoClassInfo_class_t::set_table_name(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.table_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoClassInfo.class_t.table_name) } inline std::string* CDemoClassInfo_class_t::mutable_table_name() { std::string* _s = _internal_mutable_table_name(); // @@protoc_insertion_point(field_mutable:CDemoClassInfo.class_t.table_name) return _s; } inline const std::string& CDemoClassInfo_class_t::_internal_table_name() const { return _impl_.table_name_.Get(); } inline void CDemoClassInfo_class_t::_internal_set_table_name(const std::string& value) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.table_name_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoClassInfo_class_t::_internal_mutable_table_name() { _impl_._has_bits_[0] |= 0x00000002u; return _impl_.table_name_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoClassInfo_class_t::release_table_name() { // @@protoc_insertion_point(field_release:CDemoClassInfo.class_t.table_name) if (!_internal_has_table_name()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000002u; auto* p = _impl_.table_name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.table_name_.IsDefault()) { _impl_.table_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoClassInfo_class_t::set_allocated_table_name(std::string* table_name) { if (table_name != nullptr) { _impl_._has_bits_[0] |= 0x00000002u; } else { _impl_._has_bits_[0] &= ~0x00000002u; } _impl_.table_name_.SetAllocated(table_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.table_name_.IsDefault()) { _impl_.table_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoClassInfo.class_t.table_name) } // ------------------------------------------------------------------- // CDemoClassInfo // repeated .CDemoClassInfo.class_t classes = 1; inline int CDemoClassInfo::_internal_classes_size() const { return _impl_.classes_.size(); } inline int CDemoClassInfo::classes_size() const { return _internal_classes_size(); } inline void CDemoClassInfo::clear_classes() { _impl_.classes_.Clear(); } inline ::CDemoClassInfo_class_t* CDemoClassInfo::mutable_classes(int index) { // @@protoc_insertion_point(field_mutable:CDemoClassInfo.classes) return _impl_.classes_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoClassInfo_class_t >* CDemoClassInfo::mutable_classes() { // @@protoc_insertion_point(field_mutable_list:CDemoClassInfo.classes) return &_impl_.classes_; } inline const ::CDemoClassInfo_class_t& CDemoClassInfo::_internal_classes(int index) const { return _impl_.classes_.Get(index); } inline const ::CDemoClassInfo_class_t& CDemoClassInfo::classes(int index) const { // @@protoc_insertion_point(field_get:CDemoClassInfo.classes) return _internal_classes(index); } inline ::CDemoClassInfo_class_t* CDemoClassInfo::_internal_add_classes() { return _impl_.classes_.Add(); } inline ::CDemoClassInfo_class_t* CDemoClassInfo::add_classes() { ::CDemoClassInfo_class_t* _add = _internal_add_classes(); // @@protoc_insertion_point(field_add:CDemoClassInfo.classes) return _add; } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoClassInfo_class_t >& CDemoClassInfo::classes() const { // @@protoc_insertion_point(field_list:CDemoClassInfo.classes) return _impl_.classes_; } // ------------------------------------------------------------------- // CDemoCustomData // optional int32 callback_index = 1; inline bool CDemoCustomData::_internal_has_callback_index() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CDemoCustomData::has_callback_index() const { return _internal_has_callback_index(); } inline void CDemoCustomData::clear_callback_index() { _impl_.callback_index_ = 0; _impl_._has_bits_[0] &= ~0x00000002u; } inline int32_t CDemoCustomData::_internal_callback_index() const { return _impl_.callback_index_; } inline int32_t CDemoCustomData::callback_index() const { // @@protoc_insertion_point(field_get:CDemoCustomData.callback_index) return _internal_callback_index(); } inline void CDemoCustomData::_internal_set_callback_index(int32_t value) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.callback_index_ = value; } inline void CDemoCustomData::set_callback_index(int32_t value) { _internal_set_callback_index(value); // @@protoc_insertion_point(field_set:CDemoCustomData.callback_index) } // optional bytes data = 2; inline bool CDemoCustomData::_internal_has_data() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CDemoCustomData::has_data() const { return _internal_has_data(); } inline void CDemoCustomData::clear_data() { _impl_.data_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CDemoCustomData::data() const { // @@protoc_insertion_point(field_get:CDemoCustomData.data) return _internal_data(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoCustomData::set_data(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.data_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoCustomData.data) } inline std::string* CDemoCustomData::mutable_data() { std::string* _s = _internal_mutable_data(); // @@protoc_insertion_point(field_mutable:CDemoCustomData.data) return _s; } inline const std::string& CDemoCustomData::_internal_data() const { return _impl_.data_.Get(); } inline void CDemoCustomData::_internal_set_data(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.data_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoCustomData::_internal_mutable_data() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.data_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoCustomData::release_data() { // @@protoc_insertion_point(field_release:CDemoCustomData.data) if (!_internal_has_data()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.data_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoCustomData::set_allocated_data(std::string* data) { if (data != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.data_.SetAllocated(data, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoCustomData.data) } // ------------------------------------------------------------------- // CDemoCustomDataCallbacks // repeated string save_id = 1; inline int CDemoCustomDataCallbacks::_internal_save_id_size() const { return _impl_.save_id_.size(); } inline int CDemoCustomDataCallbacks::save_id_size() const { return _internal_save_id_size(); } inline void CDemoCustomDataCallbacks::clear_save_id() { _impl_.save_id_.Clear(); } inline std::string* CDemoCustomDataCallbacks::add_save_id() { std::string* _s = _internal_add_save_id(); // @@protoc_insertion_point(field_add_mutable:CDemoCustomDataCallbacks.save_id) return _s; } inline const std::string& CDemoCustomDataCallbacks::_internal_save_id(int index) const { return _impl_.save_id_.Get(index); } inline const std::string& CDemoCustomDataCallbacks::save_id(int index) const { // @@protoc_insertion_point(field_get:CDemoCustomDataCallbacks.save_id) return _internal_save_id(index); } inline std::string* CDemoCustomDataCallbacks::mutable_save_id(int index) { // @@protoc_insertion_point(field_mutable:CDemoCustomDataCallbacks.save_id) return _impl_.save_id_.Mutable(index); } inline void CDemoCustomDataCallbacks::set_save_id(int index, const std::string& value) { _impl_.save_id_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set:CDemoCustomDataCallbacks.save_id) } inline void CDemoCustomDataCallbacks::set_save_id(int index, std::string&& value) { _impl_.save_id_.Mutable(index)->assign(std::move(value)); // @@protoc_insertion_point(field_set:CDemoCustomDataCallbacks.save_id) } inline void CDemoCustomDataCallbacks::set_save_id(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); _impl_.save_id_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:CDemoCustomDataCallbacks.save_id) } inline void CDemoCustomDataCallbacks::set_save_id(int index, const char* value, size_t size) { _impl_.save_id_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:CDemoCustomDataCallbacks.save_id) } inline std::string* CDemoCustomDataCallbacks::_internal_add_save_id() { return _impl_.save_id_.Add(); } inline void CDemoCustomDataCallbacks::add_save_id(const std::string& value) { _impl_.save_id_.Add()->assign(value); // @@protoc_insertion_point(field_add:CDemoCustomDataCallbacks.save_id) } inline void CDemoCustomDataCallbacks::add_save_id(std::string&& value) { _impl_.save_id_.Add(std::move(value)); // @@protoc_insertion_point(field_add:CDemoCustomDataCallbacks.save_id) } inline void CDemoCustomDataCallbacks::add_save_id(const char* value) { GOOGLE_DCHECK(value != nullptr); _impl_.save_id_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:CDemoCustomDataCallbacks.save_id) } inline void CDemoCustomDataCallbacks::add_save_id(const char* value, size_t size) { _impl_.save_id_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:CDemoCustomDataCallbacks.save_id) } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& CDemoCustomDataCallbacks::save_id() const { // @@protoc_insertion_point(field_list:CDemoCustomDataCallbacks.save_id) return _impl_.save_id_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* CDemoCustomDataCallbacks::mutable_save_id() { // @@protoc_insertion_point(field_mutable_list:CDemoCustomDataCallbacks.save_id) return &_impl_.save_id_; } // ------------------------------------------------------------------- // CDemoAnimationData // optional sint32 entity_id = 1; inline bool CDemoAnimationData::_internal_has_entity_id() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CDemoAnimationData::has_entity_id() const { return _internal_has_entity_id(); } inline void CDemoAnimationData::clear_entity_id() { _impl_.entity_id_ = 0; _impl_._has_bits_[0] &= ~0x00000002u; } inline int32_t CDemoAnimationData::_internal_entity_id() const { return _impl_.entity_id_; } inline int32_t CDemoAnimationData::entity_id() const { // @@protoc_insertion_point(field_get:CDemoAnimationData.entity_id) return _internal_entity_id(); } inline void CDemoAnimationData::_internal_set_entity_id(int32_t value) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.entity_id_ = value; } inline void CDemoAnimationData::set_entity_id(int32_t value) { _internal_set_entity_id(value); // @@protoc_insertion_point(field_set:CDemoAnimationData.entity_id) } // optional int32 start_tick = 2; inline bool CDemoAnimationData::_internal_has_start_tick() const { bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool CDemoAnimationData::has_start_tick() const { return _internal_has_start_tick(); } inline void CDemoAnimationData::clear_start_tick() { _impl_.start_tick_ = 0; _impl_._has_bits_[0] &= ~0x00000004u; } inline int32_t CDemoAnimationData::_internal_start_tick() const { return _impl_.start_tick_; } inline int32_t CDemoAnimationData::start_tick() const { // @@protoc_insertion_point(field_get:CDemoAnimationData.start_tick) return _internal_start_tick(); } inline void CDemoAnimationData::_internal_set_start_tick(int32_t value) { _impl_._has_bits_[0] |= 0x00000004u; _impl_.start_tick_ = value; } inline void CDemoAnimationData::set_start_tick(int32_t value) { _internal_set_start_tick(value); // @@protoc_insertion_point(field_set:CDemoAnimationData.start_tick) } // optional int32 end_tick = 3; inline bool CDemoAnimationData::_internal_has_end_tick() const { bool value = (_impl_._has_bits_[0] & 0x00000010u) != 0; return value; } inline bool CDemoAnimationData::has_end_tick() const { return _internal_has_end_tick(); } inline void CDemoAnimationData::clear_end_tick() { _impl_.end_tick_ = 0; _impl_._has_bits_[0] &= ~0x00000010u; } inline int32_t CDemoAnimationData::_internal_end_tick() const { return _impl_.end_tick_; } inline int32_t CDemoAnimationData::end_tick() const { // @@protoc_insertion_point(field_get:CDemoAnimationData.end_tick) return _internal_end_tick(); } inline void CDemoAnimationData::_internal_set_end_tick(int32_t value) { _impl_._has_bits_[0] |= 0x00000010u; _impl_.end_tick_ = value; } inline void CDemoAnimationData::set_end_tick(int32_t value) { _internal_set_end_tick(value); // @@protoc_insertion_point(field_set:CDemoAnimationData.end_tick) } // optional bytes data = 4; inline bool CDemoAnimationData::_internal_has_data() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CDemoAnimationData::has_data() const { return _internal_has_data(); } inline void CDemoAnimationData::clear_data() { _impl_.data_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CDemoAnimationData::data() const { // @@protoc_insertion_point(field_get:CDemoAnimationData.data) return _internal_data(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoAnimationData::set_data(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.data_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoAnimationData.data) } inline std::string* CDemoAnimationData::mutable_data() { std::string* _s = _internal_mutable_data(); // @@protoc_insertion_point(field_mutable:CDemoAnimationData.data) return _s; } inline const std::string& CDemoAnimationData::_internal_data() const { return _impl_.data_.Get(); } inline void CDemoAnimationData::_internal_set_data(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.data_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoAnimationData::_internal_mutable_data() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.data_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoAnimationData::release_data() { // @@protoc_insertion_point(field_release:CDemoAnimationData.data) if (!_internal_has_data()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.data_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoAnimationData::set_allocated_data(std::string* data) { if (data != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.data_.SetAllocated(data, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoAnimationData.data) } // optional int64 data_checksum = 5; inline bool CDemoAnimationData::_internal_has_data_checksum() const { bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; return value; } inline bool CDemoAnimationData::has_data_checksum() const { return _internal_has_data_checksum(); } inline void CDemoAnimationData::clear_data_checksum() { _impl_.data_checksum_ = int64_t{0}; _impl_._has_bits_[0] &= ~0x00000008u; } inline int64_t CDemoAnimationData::_internal_data_checksum() const { return _impl_.data_checksum_; } inline int64_t CDemoAnimationData::data_checksum() const { // @@protoc_insertion_point(field_get:CDemoAnimationData.data_checksum) return _internal_data_checksum(); } inline void CDemoAnimationData::_internal_set_data_checksum(int64_t value) { _impl_._has_bits_[0] |= 0x00000008u; _impl_.data_checksum_ = value; } inline void CDemoAnimationData::set_data_checksum(int64_t value) { _internal_set_data_checksum(value); // @@protoc_insertion_point(field_set:CDemoAnimationData.data_checksum) } // ------------------------------------------------------------------- // CDemoStringTables_items_t // optional string str = 1; inline bool CDemoStringTables_items_t::_internal_has_str() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CDemoStringTables_items_t::has_str() const { return _internal_has_str(); } inline void CDemoStringTables_items_t::clear_str() { _impl_.str_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CDemoStringTables_items_t::str() const { // @@protoc_insertion_point(field_get:CDemoStringTables.items_t.str) return _internal_str(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoStringTables_items_t::set_str(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.str_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoStringTables.items_t.str) } inline std::string* CDemoStringTables_items_t::mutable_str() { std::string* _s = _internal_mutable_str(); // @@protoc_insertion_point(field_mutable:CDemoStringTables.items_t.str) return _s; } inline const std::string& CDemoStringTables_items_t::_internal_str() const { return _impl_.str_.Get(); } inline void CDemoStringTables_items_t::_internal_set_str(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.str_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoStringTables_items_t::_internal_mutable_str() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.str_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoStringTables_items_t::release_str() { // @@protoc_insertion_point(field_release:CDemoStringTables.items_t.str) if (!_internal_has_str()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.str_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.str_.IsDefault()) { _impl_.str_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoStringTables_items_t::set_allocated_str(std::string* str) { if (str != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.str_.SetAllocated(str, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.str_.IsDefault()) { _impl_.str_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoStringTables.items_t.str) } // optional bytes data = 2; inline bool CDemoStringTables_items_t::_internal_has_data() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CDemoStringTables_items_t::has_data() const { return _internal_has_data(); } inline void CDemoStringTables_items_t::clear_data() { _impl_.data_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000002u; } inline const std::string& CDemoStringTables_items_t::data() const { // @@protoc_insertion_point(field_get:CDemoStringTables.items_t.data) return _internal_data(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoStringTables_items_t::set_data(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.data_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoStringTables.items_t.data) } inline std::string* CDemoStringTables_items_t::mutable_data() { std::string* _s = _internal_mutable_data(); // @@protoc_insertion_point(field_mutable:CDemoStringTables.items_t.data) return _s; } inline const std::string& CDemoStringTables_items_t::_internal_data() const { return _impl_.data_.Get(); } inline void CDemoStringTables_items_t::_internal_set_data(const std::string& value) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.data_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoStringTables_items_t::_internal_mutable_data() { _impl_._has_bits_[0] |= 0x00000002u; return _impl_.data_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoStringTables_items_t::release_data() { // @@protoc_insertion_point(field_release:CDemoStringTables.items_t.data) if (!_internal_has_data()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000002u; auto* p = _impl_.data_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoStringTables_items_t::set_allocated_data(std::string* data) { if (data != nullptr) { _impl_._has_bits_[0] |= 0x00000002u; } else { _impl_._has_bits_[0] &= ~0x00000002u; } _impl_.data_.SetAllocated(data, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoStringTables.items_t.data) } // ------------------------------------------------------------------- // CDemoStringTables_table_t // optional string table_name = 1; inline bool CDemoStringTables_table_t::_internal_has_table_name() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CDemoStringTables_table_t::has_table_name() const { return _internal_has_table_name(); } inline void CDemoStringTables_table_t::clear_table_name() { _impl_.table_name_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CDemoStringTables_table_t::table_name() const { // @@protoc_insertion_point(field_get:CDemoStringTables.table_t.table_name) return _internal_table_name(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoStringTables_table_t::set_table_name(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.table_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoStringTables.table_t.table_name) } inline std::string* CDemoStringTables_table_t::mutable_table_name() { std::string* _s = _internal_mutable_table_name(); // @@protoc_insertion_point(field_mutable:CDemoStringTables.table_t.table_name) return _s; } inline const std::string& CDemoStringTables_table_t::_internal_table_name() const { return _impl_.table_name_.Get(); } inline void CDemoStringTables_table_t::_internal_set_table_name(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.table_name_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoStringTables_table_t::_internal_mutable_table_name() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.table_name_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoStringTables_table_t::release_table_name() { // @@protoc_insertion_point(field_release:CDemoStringTables.table_t.table_name) if (!_internal_has_table_name()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.table_name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.table_name_.IsDefault()) { _impl_.table_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoStringTables_table_t::set_allocated_table_name(std::string* table_name) { if (table_name != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.table_name_.SetAllocated(table_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.table_name_.IsDefault()) { _impl_.table_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoStringTables.table_t.table_name) } // repeated .CDemoStringTables.items_t items = 2; inline int CDemoStringTables_table_t::_internal_items_size() const { return _impl_.items_.size(); } inline int CDemoStringTables_table_t::items_size() const { return _internal_items_size(); } inline void CDemoStringTables_table_t::clear_items() { _impl_.items_.Clear(); } inline ::CDemoStringTables_items_t* CDemoStringTables_table_t::mutable_items(int index) { // @@protoc_insertion_point(field_mutable:CDemoStringTables.table_t.items) return _impl_.items_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_items_t >* CDemoStringTables_table_t::mutable_items() { // @@protoc_insertion_point(field_mutable_list:CDemoStringTables.table_t.items) return &_impl_.items_; } inline const ::CDemoStringTables_items_t& CDemoStringTables_table_t::_internal_items(int index) const { return _impl_.items_.Get(index); } inline const ::CDemoStringTables_items_t& CDemoStringTables_table_t::items(int index) const { // @@protoc_insertion_point(field_get:CDemoStringTables.table_t.items) return _internal_items(index); } inline ::CDemoStringTables_items_t* CDemoStringTables_table_t::_internal_add_items() { return _impl_.items_.Add(); } inline ::CDemoStringTables_items_t* CDemoStringTables_table_t::add_items() { ::CDemoStringTables_items_t* _add = _internal_add_items(); // @@protoc_insertion_point(field_add:CDemoStringTables.table_t.items) return _add; } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_items_t >& CDemoStringTables_table_t::items() const { // @@protoc_insertion_point(field_list:CDemoStringTables.table_t.items) return _impl_.items_; } // repeated .CDemoStringTables.items_t items_clientside = 3; inline int CDemoStringTables_table_t::_internal_items_clientside_size() const { return _impl_.items_clientside_.size(); } inline int CDemoStringTables_table_t::items_clientside_size() const { return _internal_items_clientside_size(); } inline void CDemoStringTables_table_t::clear_items_clientside() { _impl_.items_clientside_.Clear(); } inline ::CDemoStringTables_items_t* CDemoStringTables_table_t::mutable_items_clientside(int index) { // @@protoc_insertion_point(field_mutable:CDemoStringTables.table_t.items_clientside) return _impl_.items_clientside_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_items_t >* CDemoStringTables_table_t::mutable_items_clientside() { // @@protoc_insertion_point(field_mutable_list:CDemoStringTables.table_t.items_clientside) return &_impl_.items_clientside_; } inline const ::CDemoStringTables_items_t& CDemoStringTables_table_t::_internal_items_clientside(int index) const { return _impl_.items_clientside_.Get(index); } inline const ::CDemoStringTables_items_t& CDemoStringTables_table_t::items_clientside(int index) const { // @@protoc_insertion_point(field_get:CDemoStringTables.table_t.items_clientside) return _internal_items_clientside(index); } inline ::CDemoStringTables_items_t* CDemoStringTables_table_t::_internal_add_items_clientside() { return _impl_.items_clientside_.Add(); } inline ::CDemoStringTables_items_t* CDemoStringTables_table_t::add_items_clientside() { ::CDemoStringTables_items_t* _add = _internal_add_items_clientside(); // @@protoc_insertion_point(field_add:CDemoStringTables.table_t.items_clientside) return _add; } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_items_t >& CDemoStringTables_table_t::items_clientside() const { // @@protoc_insertion_point(field_list:CDemoStringTables.table_t.items_clientside) return _impl_.items_clientside_; } // optional int32 table_flags = 4; inline bool CDemoStringTables_table_t::_internal_has_table_flags() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CDemoStringTables_table_t::has_table_flags() const { return _internal_has_table_flags(); } inline void CDemoStringTables_table_t::clear_table_flags() { _impl_.table_flags_ = 0; _impl_._has_bits_[0] &= ~0x00000002u; } inline int32_t CDemoStringTables_table_t::_internal_table_flags() const { return _impl_.table_flags_; } inline int32_t CDemoStringTables_table_t::table_flags() const { // @@protoc_insertion_point(field_get:CDemoStringTables.table_t.table_flags) return _internal_table_flags(); } inline void CDemoStringTables_table_t::_internal_set_table_flags(int32_t value) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.table_flags_ = value; } inline void CDemoStringTables_table_t::set_table_flags(int32_t value) { _internal_set_table_flags(value); // @@protoc_insertion_point(field_set:CDemoStringTables.table_t.table_flags) } // ------------------------------------------------------------------- // CDemoStringTables // repeated .CDemoStringTables.table_t tables = 1; inline int CDemoStringTables::_internal_tables_size() const { return _impl_.tables_.size(); } inline int CDemoStringTables::tables_size() const { return _internal_tables_size(); } inline void CDemoStringTables::clear_tables() { _impl_.tables_.Clear(); } inline ::CDemoStringTables_table_t* CDemoStringTables::mutable_tables(int index) { // @@protoc_insertion_point(field_mutable:CDemoStringTables.tables) return _impl_.tables_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_table_t >* CDemoStringTables::mutable_tables() { // @@protoc_insertion_point(field_mutable_list:CDemoStringTables.tables) return &_impl_.tables_; } inline const ::CDemoStringTables_table_t& CDemoStringTables::_internal_tables(int index) const { return _impl_.tables_.Get(index); } inline const ::CDemoStringTables_table_t& CDemoStringTables::tables(int index) const { // @@protoc_insertion_point(field_get:CDemoStringTables.tables) return _internal_tables(index); } inline ::CDemoStringTables_table_t* CDemoStringTables::_internal_add_tables() { return _impl_.tables_.Add(); } inline ::CDemoStringTables_table_t* CDemoStringTables::add_tables() { ::CDemoStringTables_table_t* _add = _internal_add_tables(); // @@protoc_insertion_point(field_add:CDemoStringTables.tables) return _add; } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::CDemoStringTables_table_t >& CDemoStringTables::tables() const { // @@protoc_insertion_point(field_list:CDemoStringTables.tables) return _impl_.tables_; } // ------------------------------------------------------------------- // CDemoStop // ------------------------------------------------------------------- // CDemoUserCmd // optional int32 cmd_number = 1; inline bool CDemoUserCmd::_internal_has_cmd_number() const { bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CDemoUserCmd::has_cmd_number() const { return _internal_has_cmd_number(); } inline void CDemoUserCmd::clear_cmd_number() { _impl_.cmd_number_ = 0; _impl_._has_bits_[0] &= ~0x00000002u; } inline int32_t CDemoUserCmd::_internal_cmd_number() const { return _impl_.cmd_number_; } inline int32_t CDemoUserCmd::cmd_number() const { // @@protoc_insertion_point(field_get:CDemoUserCmd.cmd_number) return _internal_cmd_number(); } inline void CDemoUserCmd::_internal_set_cmd_number(int32_t value) { _impl_._has_bits_[0] |= 0x00000002u; _impl_.cmd_number_ = value; } inline void CDemoUserCmd::set_cmd_number(int32_t value) { _internal_set_cmd_number(value); // @@protoc_insertion_point(field_set:CDemoUserCmd.cmd_number) } // optional bytes data = 2; inline bool CDemoUserCmd::_internal_has_data() const { bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CDemoUserCmd::has_data() const { return _internal_has_data(); } inline void CDemoUserCmd::clear_data() { _impl_.data_.ClearToEmpty(); _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CDemoUserCmd::data() const { // @@protoc_insertion_point(field_get:CDemoUserCmd.data) return _internal_data(); } template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CDemoUserCmd::set_data(ArgT0&& arg0, ArgT... args) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.data_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:CDemoUserCmd.data) } inline std::string* CDemoUserCmd::mutable_data() { std::string* _s = _internal_mutable_data(); // @@protoc_insertion_point(field_mutable:CDemoUserCmd.data) return _s; } inline const std::string& CDemoUserCmd::_internal_data() const { return _impl_.data_.Get(); } inline void CDemoUserCmd::_internal_set_data(const std::string& value) { _impl_._has_bits_[0] |= 0x00000001u; _impl_.data_.Set(value, GetArenaForAllocation()); } inline std::string* CDemoUserCmd::_internal_mutable_data() { _impl_._has_bits_[0] |= 0x00000001u; return _impl_.data_.Mutable(GetArenaForAllocation()); } inline std::string* CDemoUserCmd::release_data() { // @@protoc_insertion_point(field_release:CDemoUserCmd.data) if (!_internal_has_data()) { return nullptr; } _impl_._has_bits_[0] &= ~0x00000001u; auto* p = _impl_.data_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CDemoUserCmd::set_allocated_data(std::string* data) { if (data != nullptr) { _impl_._has_bits_[0] |= 0x00000001u; } else { _impl_._has_bits_[0] &= ~0x00000001u; } _impl_.data_.SetAllocated(data, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING if (_impl_.data_.IsDefault()) { _impl_.data_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:CDemoUserCmd.data) } // ------------------------------------------------------------------- // CDemoSpawnGroups // repeated bytes msgs = 3; inline int CDemoSpawnGroups::_internal_msgs_size() const { return _impl_.msgs_.size(); } inline int CDemoSpawnGroups::msgs_size() const { return _internal_msgs_size(); } inline void CDemoSpawnGroups::clear_msgs() { _impl_.msgs_.Clear(); } inline std::string* CDemoSpawnGroups::add_msgs() { std::string* _s = _internal_add_msgs(); // @@protoc_insertion_point(field_add_mutable:CDemoSpawnGroups.msgs) return _s; } inline const std::string& CDemoSpawnGroups::_internal_msgs(int index) const { return _impl_.msgs_.Get(index); } inline const std::string& CDemoSpawnGroups::msgs(int index) const { // @@protoc_insertion_point(field_get:CDemoSpawnGroups.msgs) return _internal_msgs(index); } inline std::string* CDemoSpawnGroups::mutable_msgs(int index) { // @@protoc_insertion_point(field_mutable:CDemoSpawnGroups.msgs) return _impl_.msgs_.Mutable(index); } inline void CDemoSpawnGroups::set_msgs(int index, const std::string& value) { _impl_.msgs_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set:CDemoSpawnGroups.msgs) } inline void CDemoSpawnGroups::set_msgs(int index, std::string&& value) { _impl_.msgs_.Mutable(index)->assign(std::move(value)); // @@protoc_insertion_point(field_set:CDemoSpawnGroups.msgs) } inline void CDemoSpawnGroups::set_msgs(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); _impl_.msgs_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:CDemoSpawnGroups.msgs) } inline void CDemoSpawnGroups::set_msgs(int index, const void* value, size_t size) { _impl_.msgs_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:CDemoSpawnGroups.msgs) } inline std::string* CDemoSpawnGroups::_internal_add_msgs() { return _impl_.msgs_.Add(); } inline void CDemoSpawnGroups::add_msgs(const std::string& value) { _impl_.msgs_.Add()->assign(value); // @@protoc_insertion_point(field_add:CDemoSpawnGroups.msgs) } inline void CDemoSpawnGroups::add_msgs(std::string&& value) { _impl_.msgs_.Add(std::move(value)); // @@protoc_insertion_point(field_add:CDemoSpawnGroups.msgs) } inline void CDemoSpawnGroups::add_msgs(const char* value) { GOOGLE_DCHECK(value != nullptr); _impl_.msgs_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:CDemoSpawnGroups.msgs) } inline void CDemoSpawnGroups::add_msgs(const void* value, size_t size) { _impl_.msgs_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:CDemoSpawnGroups.msgs) } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& CDemoSpawnGroups::msgs() const { // @@protoc_insertion_point(field_list:CDemoSpawnGroups.msgs) return _impl_.msgs_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* CDemoSpawnGroups::mutable_msgs() { // @@protoc_insertion_point(field_mutable_list:CDemoSpawnGroups.msgs) return &_impl_.msgs_; } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) PROTOBUF_NAMESPACE_OPEN template <> struct is_proto_enum< ::EDemoCommands> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::EDemoCommands>() { return ::EDemoCommands_descriptor(); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_demo_2eproto
412
0.642473
1
0.642473
game-dev
MEDIA
0.579947
game-dev
0.645516
1
0.645516
tswow/tswow
4,612
tswow-core/Private/TSLoot.cpp
/* * This file is part of tswow (https://github.com/tswow/). * Copyright (C) 2020 tswow <https://github.com/tswow/> * * 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/>. */ #include "TSLoot.h" #if TRINITY #include "Loot.h" #endif #include "LootMgr.h" #include "ObjectGuid.h" #include "TSMath.h" #include "TSGUID.h" #include "TSItemTemplate.h" TSLoot::TSLoot(Loot *loot) { this->loot = loot; } TSLoot::TSLoot() { this->loot = nullptr; } void TSLoot::Clear() { loot->clear(); } bool TSLoot::IsLooted() { return loot->isLooted(); } void TSLoot::AddItem(uint32 id, uint8 minCount, uint8 maxCount, uint16 lootmode, bool needsQuest, uint8 groupId) { loot->items.reserve(MAX_NR_LOOT_ITEMS); loot->quest_items.reserve(MAX_NR_QUEST_ITEMS); loot->AddItem(LootStoreItem(id,0,100,lootmode,needsQuest,groupId,minCount,maxCount)); } void TSLoot::AddLooter(uint64 looter) { loot->AddLooter(ObjectGuid(looter)); } void TSLoot::RemoveLooter(uint64 looter) { loot->RemoveLooter(ObjectGuid(looter)); } void TSLoot::SetMoney(uint32 money) { loot->gold = money; } TSNumber<uint32> TSLoot::GetMoney() { return loot->gold; } void TSLoot::SetLootType(uint32 lootType) { loot->loot_type = LootType(lootType); } TSNumber<uint32> TSLoot::GetLootType() { return loot->loot_type; } void TSLoot::SetLootOwner(TSGUID const& owner) { loot->lootOwnerGUID = ObjectGuid(owner.asGUID()); } TSGUID TSLoot::GetLootOwnerGUID() { return TSGUID(loot->lootOwnerGUID); } TSLootItem::TSLootItem(LootItem* item) { this->item = item; } TSNumber<uint32> TSLootItem::GetItemID() { return item->itemid; } TSNumber<uint32> TSLootItem::GetRandomSuffix() { return item->randomSuffix; } TSNumber<int32> TSLootItem::GetRandomPropertyID() { return item->randomPropertyId; } TSNumber<uint8> TSLootItem::GetCount() { return item->count; } void TSLootItem::SetItemID(uint32 id) { item->itemid = id; } void TSLootItem::SetRandomSuffix(uint32 randomSuffix) { item->randomSuffix = randomSuffix; } void TSLootItem::SetRandomPropertyID(int32 randomPropertyId) { item->randomPropertyId = randomPropertyId; } void TSLootItem::SetCount(uint8 count) { item->count = count; } TSNumber<uint32> TSLoot::GetItemCount() { return loot->items.size(); } TSNumber<uint32> TSLoot::GetQuestItemCount() { return loot->quest_items.size(); } TSLootItem TSLoot::GetItem(uint32 index) { return TSLootItem(&loot->items[index]); } TSLootItem TSLoot::GetQuestItem(uint32 index) { return TSLootItem(&loot->quest_items[index]); } void TSLoot::Filter(std::function<bool(TSLootItem)> predicate) { auto it = loot->items.begin(); while(it != loot->items.end()) { if(!predicate(TSLootItem(&*it))) { --loot->unlootedCount; it = loot->items.erase(it); } else { ++it; } } it = loot->quest_items.begin(); while(it != loot->quest_items.end()) { if(!predicate(TSLootItem(&*it))) { --loot->unlootedCount; it = loot->quest_items.erase(it); } else { ++it; } } } bool TSLoot::GetGeneratesNormally() { #if TRINITY return loot->generateNormally; #endif } void TSLoot::SetGeneratesNormally(bool generatesNormally) { #if TRINITY loot->generateNormally = generatesNormally; #endif } void TSLoot::LFilter(sol::protected_function predicate) { return Filter([predicate](auto const& v) { return predicate(v); }); } TSNumber<uint32> TSLootItem::GetFakeRandomSuffix() { return item->fakeRandomSuffix; } TSNumber<uint32> TSLootItem::GetFakeRandomPropertyID() { return item->fakeRandomPropertyId; } void TSLootItem::SetFakeRandomSuffix(uint32 fakeRandomSuffix) { item->fakeRandomSuffix = fakeRandomSuffix; } void TSLootItem::SetFakeRandomPropertyID(uint32 fakePropertyId) { item->fakeRandomPropertyId = fakePropertyId; } TSItemTemplate TSLootItem::GetTemplate() { return GetItemTemplate(GetItemID()); }
412
0.907722
1
0.907722
game-dev
MEDIA
0.984291
game-dev
0.963991
1
0.963991
goonstation/goonstation
2,505
assets/maps/random_rooms/5x3/maintbazaar_65.dmm
//MAP CONVERTED BY dmm2tgm.py THIS HEADER COMMENT PREVENTS RECONVERSION, DO NOT REMOVE "a" = ( /obj/item/reagent_containers/food/drinks/bottle/ntbrew{ pixel_x = 8 }, /obj/item/reagent_containers/food/drinks/bottle/ntbrew{ pixel_x = -8 }, /obj/item/reagent_containers/food/drinks/bottle/ntbrew, /obj/item/reagent_containers/food/drinks/bottle/mead{ pixel_x = -4; layer = 3.1 }, /obj/item/reagent_containers/food/drinks/bottle/mead{ pixel_x = 4; layer = 3.1 }, /obj/item/reagent_containers/food/drinks/bottle/champagne/cristal_champagne{ pixel_x = 1; pixel_y = 1; layer = 3.2 }, /obj/storage/crate/wooden{ name = "Surplus Alcohol" }, /turf/simulated/floor/black, /area/dmm_suite/clear_area) "b" = ( /turf/simulated/floor/black, /area/dmm_suite/clear_area) "c" = ( /obj/machinery/vendingframe, /turf/simulated/floor/carpet{ dir = 9; icon_state = "fred6" }, /area/dmm_suite/clear_area) "e" = ( /obj/item/cable_coil{ pixel_x = 8; pixel_y = 7; amount = 10 }, /turf/simulated/floor/carpet{ dir = 10; icon_state = "fred6" }, /area/dmm_suite/clear_area) "k" = ( /obj/machinery/light/small/floor/warm, /turf/simulated/floor/black, /area/dmm_suite/clear_area) "l" = ( /obj/item/screwdriver{ pixel_x = -4; pixel_y = -3 }, /turf/simulated/floor/carpet{ dir = 6; icon_state = "fred6" }, /area/dmm_suite/clear_area) "m" = ( /obj/shrub/random, /obj/item/sheet/glass{ icon_state = "sheet-g_1"; pixel_x = -7 }, /obj/item/sheet/glass{ icon_state = "sheet-g_1"; pixel_x = 6; pixel_y = 9 }, /turf/simulated/floor/black, /area/dmm_suite/clear_area) "o" = ( /obj/table/wood/auto, /obj/item/paper/book/from_file/vendbook{ pixel_y = 5 }, /turf/simulated/floor/black, /area/dmm_suite/clear_area) "t" = ( /obj/machinery/vendingframe, /turf/simulated/floor/carpet{ dir = 5; icon_state = "fred6" }, /area/dmm_suite/clear_area) "w" = ( /obj/item/sheet/glass{ icon_state = "sheet-g_1"; pixel_x = 3 }, /obj/item/sheet/glass{ icon_state = "sheet-g_1"; pixel_x = 7; pixel_y = 5 }, /turf/simulated/floor/black, /area/dmm_suite/clear_area) "L" = ( /obj/item/wrench{ pixel_y = 3; pixel_x = 6 }, /turf/simulated/floor/black, /area/dmm_suite/clear_area) "Q" = ( /obj/shrub/random, /obj/item/machineboard/vending/player, /turf/simulated/floor/black, /area/dmm_suite/clear_area) "W" = ( /obj/stool/chair/comfy{ dir = 4 }, /turf/simulated/floor/black, /area/dmm_suite/clear_area) (1,1,1) = {" c e m "} (2,1,1) = {" t l w "} (3,1,1) = {" b k b "} (4,1,1) = {" W L a "} (5,1,1) = {" o b Q "}
412
0.7746
1
0.7746
game-dev
MEDIA
0.952559
game-dev
0.818974
1
0.818974
CallocGD/GD-2.206-Decompiled
2,210
src/Managers/GJMultiplayerManager.cpp
#include "includes.h" void GJMultiplayerManager::ProcessHttpRequest(std::string p0, std::string p1, std::string p2, GJHttpType p3) { return; } void GJMultiplayerManager::addComment(std::string p0, int p1) { return; } void GJMultiplayerManager::addDLToActive(char const* tag, cocos2d::CCObject* obj) { return; } void GJMultiplayerManager::addDLToActive(char const* tag) { return; } /* Unknown Return: GJMultiplayerManager::createAndAddComment(std::string p0, int p1){}; */ void GJMultiplayerManager::dataLoaded(DS_Dictionary* p0) { return; } void GJMultiplayerManager::encodeDataTo(DS_Dictionary* p0) { return; } /* Unknown Return: GJMultiplayerManager::exitLobby(int p0){}; */ void GJMultiplayerManager::firstSetup() { return; } /* Unknown Return: GJMultiplayerManager::getBasePostString(){}; */ cocos2d::CCObject* GJMultiplayerManager::getDLObject(char const* p0) { return; } /* Unknown Return: GJMultiplayerManager::getLastCommentIDForGame(int p0){}; */ void GJMultiplayerManager::handleIt(bool p0, std::string p1, std::string p2, GJHttpType p3) { return; } void GJMultiplayerManager::handleItDelayed(bool p0, std::string p1, std::string p2, GJHttpType p3) { return; } void GJMultiplayerManager::handleItND(cocos2d::CCNode* p0, void* p1) { return; } bool GJMultiplayerManager::init() { return; } bool GJMultiplayerManager::isDLActive(char const* tag) { return; } /* Unknown Return: GJMultiplayerManager::joinLobby(int p0){}; */ void GJMultiplayerManager::onExitLobbyCompleted(std::string p0, std::string p1) { return; } void GJMultiplayerManager::onJoinLobbyCompleted(std::string p0, std::string p1) { return; } void GJMultiplayerManager::onProcessHttpRequestCompleted(cocos2d::extension::CCHttpClient* p0, cocos2d::extension::CCHttpResponse* p1) { return; } void GJMultiplayerManager::onUploadCommentCompleted(std::string p0, std::string p1) { return; } void GJMultiplayerManager::removeDLFromActive(char const* p0) { return; } GJMultiplayerManager* GJMultiplayerManager::sharedState() { return; } void GJMultiplayerManager::uploadComment(std::string p0, int p1) { return; }
412
0.921192
1
0.921192
game-dev
MEDIA
0.492992
game-dev
0.743381
1
0.743381
OregonCore/OregonCore
18,845
src/collision/TileAssembler.cpp
/* * This file is part of the OregonCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "TileAssembler.h" #include "MapTree.h" #include "BoundingIntervalHierarchy.h" #include "VMapDefinitions.h" #include <set> #include <iomanip> #include <sstream> using G3D::Vector3; using G3D::AABox; using G3D::inf; using std::pair; template<> struct BoundsTrait<VMAP::ModelSpawn*> { static void getBounds(const VMAP::ModelSpawn* const &obj, G3D::AABox& out) { out = obj->getBounds(); } }; namespace VMAP { bool readChunk(FILE* rf, char* dest, const char* compare, uint32 len) { if (fread(dest, sizeof(char), len, rf) != len) return false; return memcmp(dest, compare, len) == 0; } Vector3 ModelPosition::transform(const Vector3& pIn) const { Vector3 out = pIn * iScale; out = iRotation * out; return (out); } //================================================================= TileAssembler::TileAssembler(const std::string& pSrcDirName, const std::string& pDestDirName) { iCurrentUniqueNameId = 0; iFilterMethod = NULL; iSrcDir = pSrcDirName; iDestDir = pDestDirName; //mkdir(iDestDir); //init(); } TileAssembler::~TileAssembler() { //delete iCoordModelMapping; } bool TileAssembler::convertWorld2() { bool success = readMapSpawns(); if (!success) return false; // export Map data for (MapData::iterator map_iter = mapData.begin(); map_iter != mapData.end() && success; ++map_iter) { // build global map tree std::vector<ModelSpawn*> mapSpawns; UniqueEntryMap::iterator entry; printf("Calculating model bounds for map %u...\n", map_iter->first); for (entry = map_iter->second->UniqueEntries.begin(); entry != map_iter->second->UniqueEntries.end(); ++entry) { // M2 models don't have a bound set in WDT/ADT placement data, i still think they're not used for LoS at all on retail if (entry->second.flags & MOD_M2) { if (!calculateTransformedBound(entry->second)) break; } else if (entry->second.flags & MOD_WORLDSPAWN) // WMO maps and terrain maps use different origin, so we need to adapt :/ { // @todo: remove extractor hack and uncomment below line: //entry->second.iPos += Vector3(533.33333f*32, 533.33333f*32, 0.f); entry->second.iBound = entry->second.iBound + Vector3(533.33333f * 32, 533.33333f * 32, 0.f); } mapSpawns.push_back(&(entry->second)); spawnedModelFiles.insert(entry->second.name); } printf("Creating map tree for map %u...\n", map_iter->first); BIH pTree; pTree.build(mapSpawns, BoundsTrait<ModelSpawn*>::getBounds); // ===> possibly move this code to StaticMapTree class std::map<uint32, uint32> modelNodeIdx; for (uint32 i = 0; i < mapSpawns.size(); ++i) modelNodeIdx.insert(pair<uint32, uint32>(mapSpawns[i]->ID, i)); // write map tree file std::stringstream mapfilename; mapfilename << iDestDir << '/' << std::setfill('0') << std::setw(3) << map_iter->first << ".vmtree"; FILE* mapfile = fopen(mapfilename.str().c_str(), "wb"); if (!mapfile) { success = false; printf("Cannot open %s\n", mapfilename.str().c_str()); break; } //general info if (success && fwrite(VMAP_MAGIC, 1, 8, mapfile) != 8) success = false; uint32 globalTileID = StaticMapTree::packTileID(65, 65); pair<TileMap::iterator, TileMap::iterator> globalRange = map_iter->second->TileEntries.equal_range(globalTileID); char isTiled = globalRange.first == globalRange.second; // only maps without terrain (tiles) have global WMO if (success && fwrite(&isTiled, sizeof(char), 1, mapfile) != 1) success = false; // Nodes if (success && fwrite("NODE", 4, 1, mapfile) != 1) success = false; if (success) success = pTree.writeToFile(mapfile); // global map spawns (WDT), if any (most instances) if (success && fwrite("GOBJ", 4, 1, mapfile) != 1) success = false; for (TileMap::iterator glob = globalRange.first; glob != globalRange.second && success; ++glob) success = ModelSpawn::writeToFile(mapfile, map_iter->second->UniqueEntries[glob->second]); fclose(mapfile); // <==== // write map tile files, similar to ADT files, only with extra BSP tree node info TileMap& tileEntries = map_iter->second->TileEntries; TileMap::iterator tile; for (tile = tileEntries.begin(); tile != tileEntries.end(); ++tile) { const ModelSpawn& spawn = map_iter->second->UniqueEntries[tile->second]; if (spawn.flags & MOD_WORLDSPAWN) // WDT spawn, saved as tile 65/65 currently... continue; uint32 nSpawns = tileEntries.count(tile->first); std::stringstream tilefilename; tilefilename.fill('0'); tilefilename << iDestDir << '/' << std::setw(3) << map_iter->first << '_'; uint32 x, y; StaticMapTree::unpackTileID(tile->first, x, y); tilefilename << std::setw(2) << x << '_' << std::setw(2) << y << ".vmtile"; FILE* tilefile = fopen(tilefilename.str().c_str(), "wb"); // file header if (success && fwrite(VMAP_MAGIC, 1, 8, tilefile) != 8) success = false; // write number of tile spawns if (success && fwrite(&nSpawns, sizeof(uint32), 1, tilefile) != 1) success = false; // write tile spawns for (uint32 s = 0; s < nSpawns; ++s) { if (s) { ++tile; if (tile == tileEntries.end()) break; } const ModelSpawn& spawn2 = map_iter->second->UniqueEntries[tile->second]; success = success && ModelSpawn::writeToFile(tilefile, spawn2); // MapTree nodes to update when loading tile: std::map<uint32, uint32>::iterator nIdx = modelNodeIdx.find(spawn2.ID); if (success && fwrite(&nIdx->second, sizeof(uint32), 1, tilefile) != 1) success = false; } fclose(tilefile); } // break; //test, extract only first map; TODO: remvoe this line } // add an object models, listed in temp_gameobject_models file exportGameobjectModels(); // export objects std::cout << "\nConverting Model Files" << std::endl; for (std::set<std::string>::iterator mfile = spawnedModelFiles.begin(); mfile != spawnedModelFiles.end(); ++mfile) { std::cout << "Converting " << *mfile << std::endl; if (!convertRawFile(*mfile)) { std::cout << "error converting " << *mfile << std::endl; success = false; break; } } //cleanup: for (MapData::iterator map_iter = mapData.begin(); map_iter != mapData.end(); ++map_iter) delete map_iter->second; return success; } bool TileAssembler::readMapSpawns() { std::string fname = iSrcDir + "/dir_bin"; FILE* dirf = fopen(fname.c_str(), "rb"); if (!dirf) { printf("Could not read dir_bin file!\n"); return false; } printf("Read coordinate mapping...\n"); uint32 mapID, tileX, tileY, check = 0; G3D::Vector3 v1, v2; ModelSpawn spawn; while (!feof(dirf)) { check = 0; // read mapID, tileX, tileY, Flags, adtID, ID, Pos, Rot, Scale, Bound_lo, Bound_hi, name check += fread(&mapID, sizeof(uint32), 1, dirf); if (check == 0) // EoF... break; check += fread(&tileX, sizeof(uint32), 1, dirf); check += fread(&tileY, sizeof(uint32), 1, dirf); if (!ModelSpawn::readFromFile(dirf, spawn)) break; MapSpawns* current; MapData::iterator map_iter = mapData.find(mapID); if (map_iter == mapData.end()) { printf("spawning Map %d\n", mapID); mapData[mapID] = current = new MapSpawns(); } else current = (*map_iter).second; current->UniqueEntries.insert(pair<uint32, ModelSpawn>(spawn.ID, spawn)); current->TileEntries.insert(pair<uint32, uint32>(StaticMapTree::packTileID(tileX, tileY), spawn.ID)); } bool success = (ferror(dirf) == 0); fclose(dirf); return success; } bool TileAssembler::calculateTransformedBound(ModelSpawn& spawn) { std::string modelFilename(iSrcDir); modelFilename.push_back('/'); modelFilename.append(spawn.name); ModelPosition modelPosition; modelPosition.iDir = spawn.iRot; modelPosition.iScale = spawn.iScale; modelPosition.init(); WorldModel_Raw raw_model; if (!raw_model.Read(modelFilename.c_str())) return false; uint32 groups = raw_model.groupsArray.size(); if (groups != 1) printf("Warning: '%s' does not seem to be a M2 model!\n", modelFilename.c_str()); AABox modelBound; bool boundEmpty = true; for (uint32 g = 0; g < groups; ++g) // should be only one for M2 files... { std::vector<Vector3>& vertices = raw_model.groupsArray[g].vertexArray; if (vertices.empty()) { std::cout << "error: model '" << spawn.name << "' has no geometry!" << std::endl; continue; } uint32 nvectors = vertices.size(); for (uint32 i = 0; i < nvectors; ++i) { Vector3 v = modelPosition.transform(vertices[i]); if (boundEmpty) modelBound = AABox(v, v), boundEmpty = false; else modelBound.merge(v); } } spawn.iBound = modelBound + spawn.iPos; spawn.flags |= MOD_HAS_BOUND; return true; } struct WMOLiquidHeader { int xverts, yverts, xtiles, ytiles; float pos_x; float pos_y; float pos_z; short type; }; //================================================================= bool TileAssembler::convertRawFile(const std::string& pModelFilename) { bool success = true; std::string filename = iSrcDir; if (filename.length() > 0) filename.push_back('/'); filename.append(pModelFilename); WorldModel_Raw raw_model; if (!raw_model.Read(filename.c_str())) return false; // write WorldModel WorldModel model; model.setRootWmoID(raw_model.RootWMOID); if (raw_model.groupsArray.size()) { std::vector<GroupModel> groupsArray; uint32 groups = raw_model.groupsArray.size(); for (uint32 g = 0; g < groups; ++g) { GroupModel_Raw& raw_group = raw_model.groupsArray[g]; groupsArray.push_back(GroupModel(raw_group.mogpflags, raw_group.GroupWMOID, raw_group.bounds )); groupsArray.back().setMeshData(raw_group.vertexArray, raw_group.triangles); groupsArray.back().setLiquidData(raw_group.liquid); } model.setGroupModels(groupsArray); } success = model.writeFile(iDestDir + "/" + pModelFilename + ".vmo"); //std::cout << "readRawFile2: '" << pModelFilename << "' tris: " << nElements << " nodes: " << nNodes << std::endl; return success; } void TileAssembler::exportGameobjectModels() { FILE* model_list = fopen((iSrcDir + "/" + "temp_gameobject_models").c_str(), "rb"); if (!model_list) return; FILE* model_list_copy = fopen((iDestDir + "/" + GAMEOBJECT_MODELS).c_str(), "wb"); if (!model_list_copy) { fclose(model_list); return; } uint32 name_length, displayId; char buff[500]; while (!feof(model_list)) { if (fread(&displayId, sizeof(uint32), 1, model_list) != 1 || fread(&name_length, sizeof(uint32), 1, model_list) != 1 || name_length >= sizeof(buff) || fread(&buff, sizeof(char), name_length, model_list) != name_length) { std::cout << "\nFile 'temp_gameobject_models' seems to be corrupted" << std::endl; break; } std::string model_name(buff, name_length); WorldModel_Raw raw_model; if ( !raw_model.Read((iSrcDir + "/" + model_name).c_str()) ) continue; spawnedModelFiles.insert(model_name); AABox bounds; bool boundEmpty = true; for (uint32 g = 0; g < raw_model.groupsArray.size(); ++g) { std::vector<Vector3>& vertices = raw_model.groupsArray[g].vertexArray; uint32 nvectors = vertices.size(); for (uint32 i = 0; i < nvectors; ++i) { Vector3& v = vertices[i]; if (boundEmpty) bounds = AABox(v, v), boundEmpty = false; else bounds.merge(v); } } fwrite(&displayId,sizeof(uint32),1,model_list_copy); fwrite(&name_length,sizeof(uint32),1,model_list_copy); fwrite(&buff,sizeof(char),name_length,model_list_copy); fwrite(&bounds.low(),sizeof(Vector3),1,model_list_copy); fwrite(&bounds.high(),sizeof(Vector3),1,model_list_copy); } fclose(model_list); fclose(model_list_copy); } // temporary use defines to simplify read/check code (close file and return at fail) #define READ_OR_RETURN(V,S) if (fread((V), (S), 1, rf) != 1) { \ fclose(rf); printf("readfail, op = %i\n", readOperation); return(false); } #define READ_OR_RETURN_WITH_DELETE(V, S) if (fread((V), (S), 1, rf) != 1) { \ fclose(rf); printf("readfail, op = %i\n", readOperation); delete[] V; return(false); }; #define CMP_OR_RETURN(V,S) if (strcmp((V),(S)) != 0) { \ fclose(rf); printf("cmpfail, %s!=%s\n", V, S);return(false); } bool GroupModel_Raw::Read(FILE* rf) { char blockId[5]; blockId[4] = 0; int blocksize; int readOperation = 0; READ_OR_RETURN(&mogpflags, sizeof(uint32)); READ_OR_RETURN(&GroupWMOID, sizeof(uint32)); Vector3 vec1, vec2; READ_OR_RETURN(&vec1, sizeof(Vector3)); READ_OR_RETURN(&vec2, sizeof(Vector3)); bounds.set(vec1, vec2); READ_OR_RETURN(&liquidflags, sizeof(uint32)); // will this ever be used? what is it good for anyway?? uint32 branches; READ_OR_RETURN(&blockId, 4); CMP_OR_RETURN(blockId, "GRP "); READ_OR_RETURN(&blocksize, sizeof(int)); READ_OR_RETURN(&branches, sizeof(uint32)); for (uint32 b = 0; b < branches; ++b) { uint32 indexes; // indexes for each branch (not used jet) READ_OR_RETURN(&indexes, sizeof(uint32)); } // ---- indexes READ_OR_RETURN(&blockId, 4); CMP_OR_RETURN(blockId, "INDX"); READ_OR_RETURN(&blocksize, sizeof(int)); uint32 nindexes; READ_OR_RETURN(&nindexes, sizeof(uint32)); if (nindexes > 0) { uint16* indexarray = new uint16[nindexes]; READ_OR_RETURN_WITH_DELETE(indexarray, nindexes*sizeof(uint16)); triangles.reserve(nindexes / 3); for (uint32 i = 0; i < nindexes; i += 3) triangles.push_back(MeshTriangle(indexarray[i], indexarray[i + 1], indexarray[i + 2])); delete[] indexarray; } // ---- vectors READ_OR_RETURN(&blockId, 4); CMP_OR_RETURN(blockId, "VERT"); READ_OR_RETURN(&blocksize, sizeof(int)); uint32 nvectors; READ_OR_RETURN(&nvectors, sizeof(uint32)); if (nvectors > 0) { float* vectorarray = new float[nvectors * 3]; READ_OR_RETURN_WITH_DELETE(vectorarray, nvectors*sizeof(float)*3); for (uint32 i = 0; i < nvectors; ++i) vertexArray.push_back( Vector3(vectorarray + 3 * i) ); delete[] vectorarray; } // ----- liquid liquid = 0; if (liquidflags & 1) { WMOLiquidHeader hlq; READ_OR_RETURN(&blockId, 4); CMP_OR_RETURN(blockId, "LIQU"); READ_OR_RETURN(&blocksize, sizeof(int)); READ_OR_RETURN(&hlq, sizeof(WMOLiquidHeader)); liquid = new WmoLiquid(hlq.xtiles, hlq.ytiles, Vector3(hlq.pos_x, hlq.pos_y, hlq.pos_z), hlq.type); uint32 size = hlq.xverts * hlq.yverts; READ_OR_RETURN(liquid->GetHeightStorage(), size * sizeof(float)); size = hlq.xtiles * hlq.ytiles; READ_OR_RETURN(liquid->GetFlagsStorage(), size); } return true; } GroupModel_Raw::~GroupModel_Raw() { delete liquid; } bool WorldModel_Raw::Read(const char * path) { FILE* rf = fopen(path, "rb"); if (!rf) { printf("ERROR: Can't open raw model file: %s\n", path); return false; } char ident[8]; int readOperation = 0; READ_OR_RETURN(&ident, 8); CMP_OR_RETURN(ident, RAW_VMAP_MAGIC); // we have to read one int. This is needed during the export and we have to skip it here uint32 tempNVectors; READ_OR_RETURN(&tempNVectors, sizeof(tempNVectors)); uint32 groups; READ_OR_RETURN(&groups, sizeof(uint32)); READ_OR_RETURN(&RootWMOID, sizeof(uint32)); groupsArray.resize(groups); bool succeed = true; for (uint32 g = 0; g < groups && succeed; ++g) succeed = groupsArray[g].Read(rf); if (succeed) // if not, fr was already closed fclose(rf); return succeed; } // drop of temporary use defines #undef READ_OR_RETURN #undef CMP_OR_RETURN }
412
0.961502
1
0.961502
game-dev
MEDIA
0.723129
game-dev
0.962998
1
0.962998
CloudburstMC/Nukkit
1,643
src/main/java/cn/nukkit/level/persistence/impl/PersistentDataContainerBlockWrapper.java
package cn.nukkit.level.persistence.impl; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.level.persistence.ImmutableCompoundTag; import cn.nukkit.level.persistence.PersistentDataContainer; import cn.nukkit.nbt.tag.CompoundTag; public class PersistentDataContainerBlockWrapper implements PersistentDataContainer { private final BlockEntity blockEntity; private CompoundTag storage; public PersistentDataContainerBlockWrapper(BlockEntity blockEntity) { this.blockEntity = blockEntity; } @Override public CompoundTag getReadStorage() { CompoundTag storage = this.getInternalStorage(); if (storage == null) { return ImmutableCompoundTag.EMPTY; } return storage; } @Override public CompoundTag getStorage() { CompoundTag storage = this.getInternalStorage(); if (storage == null) { storage = new CompoundTag(); this.setStorage(storage); } return storage; } private CompoundTag getInternalStorage() { if (this.storage != null) { return this.storage; } if (this.blockEntity.namedTag.contains(STORAGE_TAG)) { return this.storage = this.blockEntity.namedTag.getCompound(STORAGE_TAG); } return null; } @Override public void setStorage(CompoundTag storage) { this.blockEntity.namedTag.putCompound(STORAGE_TAG, storage); this.storage = storage; } @Override public void clearStorage() { this.blockEntity.namedTag.remove(STORAGE_TAG); this.storage = null; } }
412
0.840832
1
0.840832
game-dev
MEDIA
0.832187
game-dev
0.768381
1
0.768381
Sduibek/fixtsrc
13,164
SCRIPTS/PALGUARD.SSL
procedure start; variable SrcObj := 0; variable SrcIsParty := 0; procedure talk_p_proc;// script_action == 11 procedure PalGuard01; procedure PalGuard02; variable line; variable Only_Once; procedure get_reaction; procedure ReactToLevel; procedure LevelToReact; procedure UpReact; procedure DownReact; procedure BottomReact; procedure TopReact; procedure BigUpReact; procedure BigDownReact; procedure UpReactLevel; procedure DownReactLevel; procedure Goodbyes; variable exit_line; procedure start begin if local_var(12) != 1 then begin// Fallout Fixt lvar12 - this code block heals critter to full HP one time (first time player enters the map) to make sure they always start with full HP. if metarule(14, 0) then begin// Fallout Fixt lvar12 - first visit to map? if metarule(22, 0) == 0 then begin// Fallout Fixt lvar12 - Not currently loading a save? if get_critter_stat(self_obj, 7) > 0 then begin critter_heal(self_obj, 999); end// if obj_is_carrying_obj_pid(self_obj, 46) > 0 then begin display_msg("S-bag " + proto_data(obj_pid(self_obj), 1)); end if obj_is_carrying_obj_pid(self_obj, 90) > 0 then begin display_msg("Pack " + proto_data(obj_pid(self_obj), 1)); end if obj_is_carrying_obj_pid(self_obj, 93) > 0 then begin display_msg("M-bag " + proto_data(obj_pid(self_obj), 1)); end if global_var(330) then begin if critter_inven_obj(self_obj, 0) <= 0 then begin// Equip held armor if not currently wearing any. variable A; if obj_carrying_pid_obj(self_obj, 17) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING COMBAT ARMOR..."); A := obj_carrying_pid_obj(self_obj, 17); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 2) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING METAL ARMOR..."); A := obj_carrying_pid_obj(self_obj, 2); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 1) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING LEATHER ARMOR..."); A := obj_carrying_pid_obj(self_obj, 1); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 74) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING LEATHER JACKET..."); A := obj_carrying_pid_obj(self_obj, 74); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end else begin if obj_carrying_pid_obj(self_obj, 113) then begin debug_msg("Fallout Fixt - Warning: CRITTER " + obj_pid(self_obj) + " HAD ARMOR BUT EMPTY ARMOR SLOT. EQUIPPING ROBES..."); A := obj_carrying_pid_obj(self_obj, 113); rm_obj_from_inven(self_obj, A); add_obj_to_inven(self_obj, A); wield_obj_critter(self_obj, A); end end end end end end end set_local_var(12, 1); end end end if (Only_Once == 0) then begin Only_Once := 1; /* TEAM_NUM */ critter_add_trait(self_obj, 1, 6, 44); /* AI_PACKET */ critter_add_trait(self_obj, 1, 5, 65); end if (script_action == 11) then begin//<--- talk_p_proc (Face icon), can also call "do_dialogue" or "do_dialog" call talk_p_proc; end else begin if (script_action == 18) then begin//destroy_p_proc - Object or Critter has been killed or otherwise eradicated. Fall down go boom. rm_timer_event(self_obj); // //BEGIN WEAPON DROP MOD CODE //--original code and mod by:-- // Josan12 (http://www.nma-fallout.com/forum/profile.php?mode=viewprofile&u=18843) and // MIB88 (http://www.nma-fallout.com/forum/profile.php?mode=viewprofile&u=4464) // if global_var(460) and not(global_var(0)) and (critter_inven_obj(self_obj, 1) or critter_inven_obj(self_obj, 2)) then begin// only run if Weapon Drop is enabled, AND Fixes Only is disabled, AND actually holding something variable item1 := 0; variable item2 := 0; variable armor := 0; variable item1PID := 0; variable item2PID := 0; variable armorPID := 0; variable drophex := 0; if global_var(325) then begin debug_msg("Weapon Drop BEGINS"); end if (critter_inven_obj(self_obj, 1) > 0) then begin item1 := critter_inven_obj(self_obj, 1); end if (critter_inven_obj(self_obj, 2) > 0) then begin item2 := critter_inven_obj(self_obj, 2); end if (critter_inven_obj(self_obj, 0) > 0) then begin armor := critter_inven_obj(self_obj, 0); end if item1 then begin item1PID := obj_pid(item1); end if item2 then begin item2PID := obj_pid(item2); end if armor then begin armorPID := obj_pid(armor); end drophex := tile_num_in_direction(tile_num(self_obj), random(0, 5), random(global_var(461), global_var(462))); if (item1PID != 19) and (item1PID != 21) and (item1PID != 79) and (item1PID != 205) and (item1PID != 234) and (item1PID != 235) and (item1PID != 244) and (item2PID != 19) and (item2PID != 21) and (item2PID != 79) and (item2PID != 205) and (item2PID != 234) and (item2PID != 235) and (item2PID != 244) then begin//Don't drop if: Rock (19), Brass Knuckles (21), Flare (79), Lit Flare (205), Spiked Knuckles (234), Power Fist (235), or Gold Nugget (244) if (item1 > 0) then begin if (obj_item_subtype(item1) == 3) then begin rm_obj_from_inven(self_obj, item1); move_to(item1, drophex, elevation(self_obj)); end end if (item2 > 0) then begin if (obj_item_subtype(item2) == 3) then begin rm_obj_from_inven(self_obj, item2); move_to(item2, drophex, elevation(self_obj)); end end if global_var(325) then begin debug_msg("Weapon Drop ENDS"); end end end //END WEAPON DROP MOD CODE // if source_obj > 0 then begin SrcObj := 0; SrcIsParty := 0; SrcObj := obj_pid(source_obj); if party_member_obj(SrcObj) then begin SrcIsParty := 1; end end if (source_obj == dude_obj) or (SrcIsParty == 1) then begin if (((global_var(160) + global_var(159)) >= 25) and ((global_var(159) > (2 * global_var(160))) or (global_var(317) == 1))) then begin set_global_var(317, 1); set_global_var(157, 0); end if (((global_var(160) + global_var(159)) >= 25) and ((global_var(160) > (3 * global_var(159))) or (global_var(157) == 1))) then begin set_global_var(157, 1); set_global_var(317, 0); end set_global_var(159, global_var(159) + 1);// THIS MONSTER WAS A GOOD GUY. INCREASE GoodGuysKilled COUNTER if ((global_var(159) % 2) == 0) then begin set_global_var(155, (global_var(155) - 1)); end end rm_timer_event(self_obj); end else begin if ((script_action == 21) or (script_action == 3)) then begin// 21 is look_at, 3 is description (Binoculars) //NEED TO FIX THIS, DUPLICATE DESCRIPTIONS IS BULLSHIT. --Sduibek script_overrides; display_msg(message_str(317, 100)); end else begin if (script_action == 22) then begin//<-- timed_event_p_proc -- called by ADD_TIMER_EVENT commands. "fixed_param==#" in this procedure is the number of the event in question (i.e. Add_Timer_Event dude,5,1 would be fixed_param 1) -- can also be "timeforwhat" attack_complex(dude_obj, 0, 1, 0, 0, 30000, 0, 0); end end end end end procedure talk_p_proc begin anim(dude_obj, 1000, rotation_to_tile(tile_num(dude_obj), tile_num(self_obj))); call get_reaction; if (local_var(1) < 2) then begin call PalGuard01; end else begin call PalGuard02; end end procedure PalGuard01 begin if (not(line)) then begin line := random(1, 9); end else begin line := line + 1; end if (line > 9) then begin line := 1; end if (line == 1) then begin float_msg(self_obj, message_str(317, 101), 2); end else begin if (line == 2) then begin float_msg(self_obj, message_str(317, 102), 2); end else begin if (line == 3) then begin float_msg(self_obj, message_str(317, 103), 2); end else begin if (line == 4) then begin float_msg(self_obj, message_str(317, 104), 2); end else begin if (line == 5) then begin float_msg(self_obj, message_str(317, 105), 2); end else begin if (line == 6) then begin if (get_critter_stat(dude_obj, 34) == 1) then begin float_msg(self_obj, message_str(317, 106), 2); end else begin line := line + 1; end end else begin if (line == 7) then begin if (global_var(108) == 2) then begin float_msg(self_obj, message_str(317, 107), 2); end else begin line := line + 1; end end else begin if (line == 8) then begin if (global_var(108) < 2) then begin float_msg(self_obj, message_str(317, 108), 2); end else begin line := line + 1; end end else begin if (line == 9) then begin if (global_var(108) < 2) then begin float_msg(self_obj, message_str(317, 109), 2); end else begin line := 1; float_msg(self_obj, message_str(317, 110), 2); end end end end end end end end end end end procedure PalGuard02 begin if (not(line)) then begin line := random(1, 10); end else begin line := line + 1; end if (line > 10) then begin line := 1; end if (line == 1) then begin float_msg(self_obj, message_str(317, 111), 2); end else begin if (line == 2) then begin float_msg(self_obj, message_str(317, 112), 2); end else begin if (line == 3) then begin float_msg(self_obj, message_str(317, 113), 2); end else begin if (line == 4) then begin float_msg(self_obj, message_str(317, 114), 2); end else begin if (line == 5) then begin float_msg(self_obj, message_str(317, 115), 2); end else begin if (line == 7) then begin if (global_var(108) == 2) then begin float_msg(self_obj, message_str(317, 116), 2); end else begin float_msg(self_obj, message_str(317, 117), 2); end end else begin if (line == 7) then begin if (global_var(108) == 2) then begin float_msg(self_obj, message_str(317, 118), 2); end else begin float_msg(self_obj, message_str(317, 119), 2); end end end end end end end end end procedure get_reaction begin if (local_var(2) == 0) then begin set_local_var(0, 50); set_local_var(1, 2); set_local_var(2, 1); set_local_var(0, local_var(0) + (5 * get_critter_stat(dude_obj, 3)) - 25); set_local_var(0, local_var(0) + (10 * has_trait(0, dude_obj, 10))); if (has_trait(0, dude_obj, 39)) then begin if (global_var(155) > 0) then begin set_local_var(0, local_var(0) + global_var(155)); end else begin set_local_var(0, local_var(0) - global_var(155)); end end else begin if (local_var(3) == 1) then begin set_local_var(0, local_var(0) - global_var(155)); end else begin set_local_var(0, local_var(0) + global_var(155)); end end if (global_var(158) >= global_var(545)) then begin set_local_var(0, local_var(0) - 30); end if (((global_var(160) + global_var(159)) >= 25) and ((global_var(160) > (3 * global_var(159))) or (global_var(157) == 1))) then begin set_local_var(0, local_var(0) + 20); end if (((global_var(160) + global_var(159)) >= 25) and ((global_var(159) > (2 * global_var(160))) or (global_var(317) == 1))) then begin set_local_var(0, local_var(0) - 20); end call ReactToLevel; end end procedure ReactToLevel begin if (local_var(0) <= 25) then begin set_local_var(1, 1); end else begin if (local_var(0) <= 75) then begin set_local_var(1, 2); end else begin set_local_var(1, 3); end end end procedure LevelToReact begin if (local_var(1) == 1) then begin set_local_var(0, random(1, 25)); end else begin if (local_var(1) == 2) then begin set_local_var(0, random(26, 75)); end else begin set_local_var(0, random(76, 100)); end end end procedure UpReact begin set_local_var(0, local_var(0) + 10); call ReactToLevel; end procedure DownReact begin set_local_var(0, local_var(0) - 10); call ReactToLevel; end procedure BottomReact begin set_local_var(1, 1); set_local_var(0, 1); end procedure TopReact begin set_local_var(0, 100); set_local_var(1, 3); end procedure BigUpReact begin set_local_var(0, local_var(0) + 25); call ReactToLevel; end procedure BigDownReact begin set_local_var(0, local_var(0) - 25); call ReactToLevel; end procedure UpReactLevel begin set_local_var(1, local_var(1) + 1); if (local_var(1) > 3) then begin set_local_var(1, 3); end call LevelToReact; end procedure DownReactLevel begin set_local_var(1, local_var(1) - 1); if (local_var(1) < 1) then begin set_local_var(1, 1); end call LevelToReact; end procedure Goodbyes begin exit_line := message_str(634, random(100, 105)); end
412
0.827817
1
0.827817
game-dev
MEDIA
0.976803
game-dev
0.912096
1
0.912096
peace-maker/smrpg
4,484
scripting/upgrades/smrpg_upgrade_regen.sp
#pragma semicolon 1 #include <sourcemod> #include <smlib> #pragma newdecls required #include <smrpg> #undef REQUIRE_PLUGIN #include <smrpg_health> #define UPGRADE_SHORTNAME "regen" ConVar g_hCVAmount; ConVar g_hCVAmountIncrease; ConVar g_hCVInterval; ConVar g_hCVIntervalDecrease; Handle g_hRegenerationTimer[MAXPLAYERS+1]; public Plugin myinfo = { name = "SM:RPG Upgrade > Health regeneration", author = "Jannik \"Peace-Maker\" Hartung", description = "Regeneration upgrade for SM:RPG. Regenerates HP every second.", version = SMRPG_VERSION, url = "http://www.wcfan.de/" } public void OnPluginStart() { LoadTranslations("smrpg_stock_upgrades.phrases"); } public void OnPluginEnd() { if(SMRPG_UpgradeExists(UPGRADE_SHORTNAME)) SMRPG_UnregisterUpgradeType(UPGRADE_SHORTNAME); } public void OnAllPluginsLoaded() { OnLibraryAdded("smrpg"); } public void OnLibraryAdded(const char[] name) { // Register this upgrade in SM:RPG if(StrEqual(name, "smrpg")) { SMRPG_RegisterUpgradeType("HP Regeneration", UPGRADE_SHORTNAME, "Regenerates HP regularly.", 0, true, 5, 5, 10); SMRPG_SetUpgradeBuySellCallback(UPGRADE_SHORTNAME, SMRPG_BuySell); SMRPG_SetUpgradeTranslationCallback(UPGRADE_SHORTNAME, SMRPG_TranslateUpgrade); g_hCVAmount = SMRPG_CreateUpgradeConVar(UPGRADE_SHORTNAME, "smrpg_regen_amount", "1", "Specify the base amount of HP which is regenerated at the first level.", 0, true, 0.1); g_hCVAmountIncrease = SMRPG_CreateUpgradeConVar(UPGRADE_SHORTNAME, "smrpg_regen_amount_inc", "1", "Additional HP to regenerate each interval multiplied by level. (base + inc * (level-1))", 0, true, 0.0); g_hCVInterval = SMRPG_CreateUpgradeConVar(UPGRADE_SHORTNAME, "smrpg_regen_interval", "1.0", "Specify the base interval rate at which HP is regenerated in seconds at the first level.", 0, true, 0.1); g_hCVIntervalDecrease = SMRPG_CreateUpgradeConVar(UPGRADE_SHORTNAME, "smrpg_regen_interval_dec", "0.0", "How much is the base interval reduced for each level?", 0, true, 0.0); } } public void OnClientDisconnect(int client) { ClearHandle(g_hRegenerationTimer[client]); } /** * SM:RPG Upgrade callbacks */ public void SMRPG_BuySell(int client, UpgradeQueryType type) { // Change timer interval to correct interval for new level. ClearHandle(g_hRegenerationTimer[client]); int iLevel = SMRPG_GetClientUpgradeLevel(client, UPGRADE_SHORTNAME); if(iLevel <= 0) return; float fInterval = g_hCVInterval.FloatValue - g_hCVIntervalDecrease.FloatValue * (iLevel - 1); g_hRegenerationTimer[client] = CreateTimer(fInterval, Timer_IncreaseHealth, GetClientUserId(client), TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE); } public void SMRPG_TranslateUpgrade(int client, const char[] shortname, TranslationType type, char[] translation, int maxlen) { if(type == TranslationType_Name) Format(translation, maxlen, "%T", UPGRADE_SHORTNAME, client); else if(type == TranslationType_Description) { char sDescriptionKey[MAX_UPGRADE_SHORTNAME_LENGTH+12] = UPGRADE_SHORTNAME; StrCat(sDescriptionKey, sizeof(sDescriptionKey), " description"); Format(translation, maxlen, "%T", sDescriptionKey, client); } } public Action Timer_IncreaseHealth(Handle timer, any userid) { int client = GetClientOfUserId(userid); if(!client) return Plugin_Stop; if(!SMRPG_IsEnabled()) return Plugin_Continue; if(!SMRPG_IsUpgradeEnabled(UPGRADE_SHORTNAME)) return Plugin_Continue; // Are bots allowed to use this upgrade? if(SMRPG_IgnoreBots() && IsFakeClient(client)) return Plugin_Continue; // Only change alive players. if(!IsClientInGame(client) || !IsPlayerAlive(client) || IsClientObserver(client)) return Plugin_Continue; // Player didn't buy this upgrade yet. int iLevel = SMRPG_GetClientUpgradeLevel(client, UPGRADE_SHORTNAME); if(iLevel <= 0) return Plugin_Continue; int iOldHealth = GetClientHealth(client); int iMaxHealth = SMRPG_Health_GetClientMaxHealth(client); // Don't reset the health, if the player gained more by other means. if(iOldHealth >= iMaxHealth) return Plugin_Continue; if(!SMRPG_RunUpgradeEffect(client, UPGRADE_SHORTNAME)) return Plugin_Continue; // Some other plugin doesn't want this effect to run int iIncrease = g_hCVAmount.IntValue + g_hCVAmountIncrease.IntValue * (iLevel - 1); int iNewHealth = iOldHealth + iIncrease; // Limit the regeneration to the maxhealth. if(iNewHealth > iMaxHealth) iNewHealth = iMaxHealth; SetEntityHealth(client, iNewHealth); return Plugin_Continue; }
412
0.716281
1
0.716281
game-dev
MEDIA
0.816169
game-dev
0.96025
1
0.96025
letscontrolit/ESPEasy
4,330
docs/source/Plugin/_plugin_substitutions_p17x.repl
.. |P170_name| replace:: :cyan:`I2C Liquid level sensor` .. |P170_type| replace:: :cyan:`Input` .. |P170_typename| replace:: :cyan:`Input - I2C Liquid level sensor` .. |P170_porttype| replace:: `.` .. |P170_status| replace:: :yellow:`COLLECTION G` .. |P170_github| replace:: P170_Waterlevel.ino .. _P170_github: https://github.com/letscontrolit/ESPEasy/blob/mega/src/_P170_Waterlevel.ino .. |P170_usedby| replace:: `.` .. |P170_shortinfo| replace:: `Seeed Studio I2C Liquid level sensor` .. |P170_maintainer| replace:: `tonhuisman` .. |P170_compileinfo| replace:: `.` .. |P170_usedlibraries| replace:: `.` .. |P172_name| replace:: :cyan:`BMP3xx (SPI)` .. |P172_type| replace:: :cyan:`Environment` .. |P172_typename| replace:: :cyan:`Environment - BMP3xx (SPI)` .. |P172_porttype| replace:: `.` .. |P172_status| replace:: :yellow:`COLLECTION G` :yellow:`CLIMATE` .. |P172_github| replace:: P172_BMP3xx_SPI.ino .. _P172_github: https://github.com/letscontrolit/ESPEasy/blob/mega/src/_P172_BMP3xx_SPI.ino .. |P172_usedby| replace:: `.` .. |P172_shortinfo| replace:: `BMP3xx Temperature and Pressure sensors` .. |P172_maintainer| replace:: `TD-er, tonhuisman` .. |P172_compileinfo| replace:: `.` .. |P172_usedlibraries| replace:: `Adafruit BMP3XX Library` .. |P173_name| replace:: :cyan:`SHTC3` .. |P173_type| replace:: :cyan:`Environment` .. |P173_typename| replace:: :cyan:`Environment - SHTC3` .. |P173_porttype| replace:: `.` .. |P173_status| replace:: :yellow:`COLLECTION G` :yellow:`CLIMATE` .. |P173_github| replace:: P173_SHTC3.ino .. _P173_github: https://github.com/letscontrolit/ESPEasy/blob/mega/src/_P173_SHTC3.ino .. |P173_usedby| replace:: `.` .. |P173_shortinfo| replace:: `SHTC3 Temperature and Humidity sensor` .. |P173_maintainer| replace:: `tonhuisman` .. |P173_compileinfo| replace:: `.` .. |P173_usedlibraries| replace:: `.` .. |P175_name| replace:: :cyan:`PMSx003i (I2C)` .. |P175_type| replace:: :cyan:`Dust` .. |P175_typename| replace:: :cyan:`Dust - PMSx003i (I2C)` .. |P175_porttype| replace:: `I2C` .. |P175_status| replace:: :yellow:`CLIMATE` .. |P175_github| replace:: P175_PMSx003i.ino .. _P175_github: https://github.com/letscontrolit/ESPEasy/blob/mega/src/_P175_PMSx003i.ino .. |P175_usedby| replace:: `.` .. |P175_shortinfo| replace:: `.` .. |P175_maintainer| replace:: `.` .. |P175_compileinfo| replace:: `.` .. |P175_usedlibraries| replace:: `.` .. |P176_name| replace:: :cyan:`Victron VE.Direct` .. |P176_type| replace:: :cyan:`Communication` .. |P176_typename| replace:: :cyan:`Communication - Victron VE.Direct` .. |P176_porttype| replace:: `.` .. |P176_status| replace:: :yellow:`ENERGY` .. |P176_github| replace:: P176_VE_Direct.ino .. _P176_github: https://github.com/letscontrolit/ESPEasy/blob/mega/src/_P176_VE_Direct.ino .. |P176_usedby| replace:: `Victron Energy devices supporting the VE.Direct protocol` .. |P176_shortinfo| replace:: `Victron VE.Direct protocol reader` .. |P176_maintainer| replace:: `tonhuisman` .. |P176_compileinfo| replace:: `.` .. |P176_usedlibraries| replace:: `.` .. |P177_name| replace:: :cyan:`XDB401 I2C Pressure` .. |P177_type| replace:: :cyan:`Environment` .. |P177_typename| replace:: :cyan:`Environment - XDB401 I2C Pressure` .. |P177_porttype| replace:: `.` .. |P177_status| replace:: :yellow:`COLLECTION G` :yellow:`CLIMATE` .. |P177_github| replace:: P177_XDB_pressure.ino .. _P177_github: https://github.com/letscontrolit/ESPEasy/blob/mega/src/_P177_XDB_pressure.ino .. |P177_usedby| replace:: `.` .. |P177_shortinfo| replace:: `XDB401 I2C Pressure and Temperature sensor` .. |P177_maintainer| replace:: `tonhuisman` .. |P177_compileinfo| replace:: `.` .. |P177_usedlibraries| replace:: `.` .. |P178_name| replace:: :cyan:`LU9685 Servo controller` .. |P178_type| replace:: :cyan:`Extra IO` .. |P178_typename| replace:: :cyan:`Extra IO - LU9685 Servo controller` .. |P178_porttype| replace:: `.` .. |P178_status| replace:: :yellow:`COLLECTION G` :yellow:`CLIMATE` .. |P178_github| replace:: P178_LU9685.ino .. _P178_github: https://github.com/letscontrolit/ESPEasy/blob/mega/src/_P178_LU9685.ino .. |P178_usedby| replace:: `LU9685 16/20 channel servo controller` .. |P178_shortinfo| replace:: `LU9685 16/20 channel servo controller` .. |P178_maintainer| replace:: `TD-er` .. |P178_compileinfo| replace:: `.` .. |P178_usedlibraries| replace:: `.`
412
0.71659
1
0.71659
game-dev
MEDIA
0.225932
game-dev
0.50363
1
0.50363
aardappel/lobster
3,777
dev/include/Box2D/Collision/b2Distance.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_DISTANCE_H #define B2_DISTANCE_H #include <Box2D/Common/b2Math.h> class b2Shape; /// A distance proxy is used by the GJK algorithm. /// It encapsulates any shape. struct b2DistanceProxy { b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {} /// Initialize the proxy using the given shape. The shape /// must remain in scope while the proxy is in use. void Set(const b2Shape* shape, int32 index); /// 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; /// Get a vertex by index. Used by b2Distance. const b2Vec2& GetVertex(int32 index) const; b2Vec2 m_buffer[2]; const b2Vec2* m_vertices; int32 m_count; float32 m_radius; }; /// Used to warm start b2Distance. /// Set count to zero on first call. struct b2SimplexCache { float32 metric; ///< length or area uint16 count; uint8 indexA[3]; ///< vertices on shape A uint8 indexB[3]; ///< vertices on shape B }; /// Input for b2Distance. /// You have to option to use the shape radii /// in the computation. Even struct b2DistanceInput { b2DistanceProxy proxyA; b2DistanceProxy proxyB; b2Transform transformA; b2Transform transformB; bool useRadii; }; /// Output for b2Distance. struct b2DistanceOutput { b2Vec2 pointA; ///< closest point on shapeA b2Vec2 pointB; ///< closest point on shapeB float32 distance; int32 iterations; ///< number of GJK iterations used }; /// Compute the closest points between two shapes. Supports any combination of: /// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output. /// On the first call set b2SimplexCache.count to zero. void b2Distance(b2DistanceOutput* output, b2SimplexCache* cache, const b2DistanceInput* input); ////////////////////////////////////////////////////////////////////////// inline int32 b2DistanceProxy::GetVertexCount() const { return m_count; } inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const { b2Assert(0 <= index && index < m_count); return m_vertices[index]; } inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const { int32 bestIndex = 0; float32 bestValue = b2Dot(m_vertices[0], d); for (int32 i = 1; i < m_count; ++i) { float32 value = b2Dot(m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return bestIndex; } inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const { int32 bestIndex = 0; float32 bestValue = b2Dot(m_vertices[0], d); for (int32 i = 1; i < m_count; ++i) { float32 value = b2Dot(m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return m_vertices[bestIndex]; } #endif
412
0.824973
1
0.824973
game-dev
MEDIA
0.511835
game-dev
0.927441
1
0.927441
google/liquidfun
3,695
liquidfun/Box2D/Box2D/Dynamics/Joints/b2MotorJoint.h
/* * Copyright (c) 2006-2012 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_MOTOR_JOINT_H #define B2_MOTOR_JOINT_H #include <Box2D/Dynamics/Joints/b2Joint.h> /// Motor joint definition. struct b2MotorJointDef : public b2JointDef { b2MotorJointDef() { type = e_motorJoint; linearOffset.SetZero(); angularOffset = 0.0f; maxForce = 1.0f; maxTorque = 1.0f; correctionFactor = 0.3f; } /// Initialize the bodies and offsets using the current transforms. void Initialize(b2Body* bodyA, b2Body* bodyB); /// Position of bodyB minus the position of bodyA, in bodyA's frame, in meters. b2Vec2 linearOffset; /// The bodyB angle minus bodyA angle in radians. float32 angularOffset; /// The maximum motor force in N. float32 maxForce; /// The maximum motor torque in N-m. float32 maxTorque; /// Position correction factor in the range [0,1]. float32 correctionFactor; }; /// A motor joint is used to control the relative motion /// between two bodies. A typical usage is to control the movement /// of a dynamic body with respect to the ground. class b2MotorJoint : public b2Joint { public: b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorB() const; b2Vec2 GetReactionForce(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const; /// Set/get the target linear offset, in frame A, in meters. void SetLinearOffset(const b2Vec2& linearOffset); const b2Vec2& GetLinearOffset() const; /// Set/get the target angular offset, in radians. void SetAngularOffset(float32 angularOffset); float32 GetAngularOffset() const; /// Set the maximum friction force in N. void SetMaxForce(float32 force); /// Get the maximum friction force in N. float32 GetMaxForce() const; /// Set the maximum friction torque in N*m. void SetMaxTorque(float32 torque); /// Get the maximum friction torque in N*m. float32 GetMaxTorque() const; /// Set the position correction factor in the range [0,1]. void SetCorrectionFactor(float32 factor); /// Get the position correction factor in the range [0,1]. float32 GetCorrectionFactor() const; /// Dump to b2Log void Dump(); protected: friend class b2Joint; b2MotorJoint(const b2MotorJointDef* def); void InitVelocityConstraints(const b2SolverData& data); void SolveVelocityConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data); // Solver shared b2Vec2 m_linearOffset; float32 m_angularOffset; b2Vec2 m_linearImpulse; float32 m_angularImpulse; float32 m_maxForce; float32 m_maxTorque; float32 m_correctionFactor; // Solver temp int32 m_indexA; int32 m_indexB; b2Vec2 m_rA; b2Vec2 m_rB; b2Vec2 m_localCenterA; b2Vec2 m_localCenterB; b2Vec2 m_linearError; float32 m_angularError; float32 m_invMassA; float32 m_invMassB; float32 m_invIA; float32 m_invIB; b2Mat22 m_linearMass; float32 m_angularMass; }; #endif
412
0.900912
1
0.900912
game-dev
MEDIA
0.995172
game-dev
0.854493
1
0.854493
Unity-Technologies/UnityCsReference
46,261
Editor/Mono/2D/SpriteAtlas/SpriteAtlasImporterInspector.cs
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.IO; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.Rendering; using UnityEngine.U2D; using UnityEditor.Build; using UnityEditor.U2D.Common; using UnityEditor.U2D.Interface; using UnityEditorInternal; using UnityEditor.AssetImporters; namespace UnityEditor.U2D { [CustomEditor(typeof(SpriteAtlasImporter))] internal class SpriteAtlasImporterInspector : AssetImporterEditor { class SpriteAtlasInspectorPlatformSettingView : TexturePlatformSettingsView { private bool m_ShowMaxSizeOption; public SpriteAtlasInspectorPlatformSettingView(bool showMaxSizeOption) { m_ShowMaxSizeOption = showMaxSizeOption; } public override int DrawMaxSize(int defaultValue, bool isMixedValue, bool isDisabled, out bool changed) { if (m_ShowMaxSizeOption) return base.DrawMaxSize(defaultValue, isMixedValue, isDisabled, out changed); else changed = false; return defaultValue; } } class Styles { public readonly GUIStyle preDropDown = "preDropDown"; public readonly GUIStyle previewButton = "preButton"; public readonly GUIStyle previewSlider = "preSlider"; public readonly GUIStyle previewSliderThumb = "preSliderThumb"; public readonly GUIStyle previewLabel = "preLabel"; public readonly GUIContent textureSettingLabel = EditorGUIUtility.TrTextContent("Texture"); public readonly GUIContent variantSettingLabel = EditorGUIUtility.TrTextContent("Variant"); public readonly GUIContent packingParametersLabel = EditorGUIUtility.TrTextContent("Packing"); public readonly GUIContent atlasTypeLabel = EditorGUIUtility.TrTextContent("Type"); public readonly GUIContent defaultPlatformLabel = EditorGUIUtility.TrTextContent("Default"); public readonly GUIContent masterAtlasLabel = EditorGUIUtility.TrTextContent("Master Atlas", "Assigning another Sprite Atlas asset will make this atlas a variant of it."); public readonly GUIContent packerLabel = EditorGUIUtility.TrTextContent("Scriptable Packer", "Scriptable Object that implements custom packing for Sprite-Atlas."); public readonly GUIContent bindAsDefaultLabel = EditorGUIUtility.TrTextContent("Include in Build", "Packed textures will be included in the build by default."); public readonly GUIContent enableRotationLabel = EditorGUIUtility.TrTextContent("Allow Rotation", "Try rotating the sprite to fit better during packing."); public readonly GUIContent enableTightPackingLabel = EditorGUIUtility.TrTextContent("Tight Packing", "Use the mesh outline to fit instead of the whole texture rect during packing."); public readonly GUIContent enableAlphaDilationLabel = EditorGUIUtility.TrTextContent("Alpha Dilation", "Enable Alpha Dilation for SpriteAtlas padding pixels."); public readonly GUIContent paddingLabel = EditorGUIUtility.TrTextContent("Padding", "The amount of extra padding between packed sprites."); public readonly GUIContent generateMipMapLabel = EditorGUIUtility.TrTextContent("Generate Mip Maps"); public readonly GUIContent packPreviewLabel = EditorGUIUtility.TrTextContent("Pack Preview", "Save and preview packed Sprite Atlas textures."); public readonly GUIContent sRGBLabel = EditorGUIUtility.TrTextContent("sRGB", "Texture content is stored in gamma space."); public readonly GUIContent readWrite = EditorGUIUtility.TrTextContent("Read/Write", "Enable to be able to access the raw pixel data from code."); public readonly GUIContent variantMultiplierLabel = EditorGUIUtility.TrTextContent("Scale", "Down scale ratio."); public readonly GUIContent copyMasterButton = EditorGUIUtility.TrTextContent("Copy Master's Settings", "Copy all master's settings into this variant."); public readonly GUIContent disabledPackLabel = EditorGUIUtility.TrTextContent("Sprite Atlas packing is disabled. Enable it in Edit > Project Settings > Editor.", null, EditorGUIUtility.GetHelpIcon(MessageType.Info)); public readonly GUIContent packableListLabel = EditorGUIUtility.TrTextContent("Objects for Packing", "Only accepts Folders, Sprite Sheet (Texture) and Sprite."); public readonly GUIContent notPowerOfTwoWarning = EditorGUIUtility.TrTextContent("This scale will produce a Variant Sprite Atlas with a packed Texture that is NPOT (non - power of two). This may cause visual artifacts in certain compression/Texture formats."); public readonly GUIContent secondaryTextureNameLabel = EditorGUIUtility.TrTextContent("Secondary Texture Name", "The name of the Secondary Texture to apply the following settings to."); public readonly GUIContent platformSettingsDropDownLabel = EditorGUIUtility.TrTextContent("Show Platform Settings For"); public readonly GUIContent smallZoom = EditorGUIUtility.IconContent("PreTextureMipMapLow"); public readonly GUIContent largeZoom = EditorGUIUtility.IconContent("PreTextureMipMapHigh"); public readonly GUIContent alphaIcon = EditorGUIUtility.IconContent("PreTextureAlpha"); public readonly GUIContent RGBIcon = EditorGUIUtility.IconContent("PreTextureRGB"); public readonly GUIContent trashIcon = EditorGUIUtility.TrIconContent("TreeEditor.Trash", "Delete currently selected settings."); public readonly int packableElementHash = "PackableElement".GetHashCode(); public readonly int packableSelectorHash = "PackableSelector".GetHashCode(); public readonly string swapObjectRegisterUndo = L10n.Tr("Swap Packable"); public readonly string secondaryTextureNameTextControlName = "secondary_texture_name_text_field"; public readonly string defaultTextForSecondaryTextureName = L10n.Tr("(Matches the names of the Secondary Textures in your Sprites.)"); public readonly string nameUniquenessWarning = L10n.Tr("Secondary Texture names must be unique within a Sprite or Sprite Atlas."); public readonly int[] atlasTypeValues = { 0, 1 }; public readonly GUIContent[] atlasTypeOptions = { EditorGUIUtility.TrTextContent("Master"), EditorGUIUtility.TrTextContent("Variant"), }; public readonly int[] paddingValues = { 2, 4, 8 }; public readonly GUIContent[] paddingOptions; public Styles() { paddingOptions = new GUIContent[paddingValues.Length]; for (var i = 0; i < paddingValues.Length; ++i) paddingOptions[i] = EditorGUIUtility.TextContent(paddingValues[i].ToString()); } } private static Styles s_Styles; private static Styles styles { get { s_Styles = s_Styles ?? new Styles(); return s_Styles; } } private SpriteAtlasAsset spriteAtlasAsset { get { return m_TargetAsset; } } private SpriteAtlasImporter spriteAtlasImporter { get { return target as SpriteAtlasImporter; } } private enum AtlasType { Undefined = -1, Master = 0, Variant = 1 } private SerializedProperty m_FilterMode; private SerializedProperty m_AnisoLevel; private SerializedProperty m_GenerateMipMaps; private SerializedProperty m_Readable; private SerializedProperty m_UseSRGB; private SerializedProperty m_EnableTightPacking; private SerializedProperty m_EnableAlphaDilation; private SerializedProperty m_EnableRotation; private SerializedProperty m_Padding; private SerializedProperty m_BindAsDefault; private SerializedProperty m_Packables; private SerializedProperty m_MasterAtlas; private SerializedProperty m_VariantScale; private SerializedProperty m_ScriptablePacker; private string m_Hash; private int m_PreviewPage = 0; private int m_TotalPages = 0; private int[] m_OptionValues = null; private string[] m_OptionDisplays = null; private Texture2D[] m_PreviewTextures = null; private Texture2D[] m_PreviewAlphaTextures = null; private bool m_PackableListExpanded = true; private ReorderableList m_PackableList; private SpriteAtlasAsset m_TargetAsset; private string m_AssetPath; private float m_MipLevel = 0; private bool m_ShowAlpha; private bool m_Discard = false; private List<string> m_PlatformSettingsOptions; private int m_SelectedPlatformSettings = 0; private int m_ContentHash = 0; private List<BuildPlatform> m_ValidPlatforms; private Dictionary<string, List<TextureImporterPlatformSettings>> m_TempPlatformSettings; private ITexturePlatformSettingsView m_TexturePlatformSettingsView; private ITexturePlatformSettingsView m_SecondaryTexturePlatformSettingsView; private ITexturePlatformSettingsFormatHelper m_TexturePlatformSettingTextureHelper; private ITexturePlatformSettingsController m_TexturePlatformSettingsController; private SerializedObject m_SerializedAssetObject = null; // The first two options are the main texture and a separator while the last two options are another separator and the new settings menu. private bool secondaryTextureSelected { get { return m_SelectedPlatformSettings >= 2 && m_SelectedPlatformSettings <= m_PlatformSettingsOptions.Count - 3; } } static bool IsPackable(Object o) { return o != null && (o.GetType() == typeof(Sprite) || o.GetType() == typeof(Texture2D) || (o.GetType() == typeof(DefaultAsset) && ProjectWindowUtil.IsFolder(o.GetInstanceID()))); } static Object ValidateObjectForPackableFieldAssignment(Object[] references, System.Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidatorOptions options) { // We only validate and care about the first one as this is a object field assignment. if (references.Length > 0 && IsPackable(references[0])) return references[0]; return null; } bool IsTargetVariant() { return spriteAtlasAsset ? spriteAtlasAsset.isVariant : false; } bool IsTargetMaster() { return spriteAtlasAsset ? !spriteAtlasAsset.isVariant : true; } protected override bool needsApplyRevert => false; internal override string targetTitle { get { return spriteAtlasAsset ? ( Path.GetFileNameWithoutExtension(m_AssetPath) + " (Sprite Atlas)" ) : "SpriteAtlasImporter Settings"; } } private string LoadSourceAsset() { var assetPath = AssetDatabase.GetAssetPath(target); var loadedObjects = InternalEditorUtility.LoadSerializedFileAndForget(assetPath); if (loadedObjects.Length > 0) m_TargetAsset = loadedObjects[0] as SpriteAtlasAsset; return assetPath; } private SerializedObject serializedAssetObject { get { return GetSerializedAssetObject(); } } internal static int SpriteAtlasAssetHash(SerializedObject obj) { int hashCode = 0; if (obj == null) return 0; unchecked { hashCode = (int)2166136261 ^ (int) obj.FindProperty("m_MasterAtlas").contentHash; hashCode = hashCode * 16777619 ^ (int) obj.FindProperty("m_ImporterData").contentHash; hashCode = hashCode * 16777619 ^ (int) obj.FindProperty("m_IsVariant").contentHash; hashCode = hashCode * 16777619 ^ (int)obj.FindProperty("m_ScriptablePacker").contentHash; } return hashCode; } internal static int SpriteAtlasImporterHash(SerializedObject obj) { int hashCode = 0; if (obj == null) return 0; unchecked { hashCode = (int)2166136261 ^ (int)obj.FindProperty("m_PackingSettings").contentHash; hashCode = hashCode * 16777619 ^ (int)obj.FindProperty("m_TextureSettings").contentHash; hashCode = hashCode * 16777619 ^ (int)obj.FindProperty("m_PlatformSettings").contentHash; hashCode = hashCode * 16777619 ^ (int)obj.FindProperty("m_SecondaryTextureSettings").contentHash; hashCode = hashCode * 16777619 ^ (int)obj.FindProperty("m_BindAsDefault").contentHash; hashCode = hashCode * 16777619 ^ (int)obj.FindProperty("m_VariantMultiplier").contentHash; } return hashCode; } internal int GetInspectorHash() { return SpriteAtlasAssetHash(m_SerializedAssetObject) * 16777619 ^ SpriteAtlasImporterHash(m_SerializedObject); } private SerializedObject GetSerializedAssetObject() { if (m_SerializedAssetObject == null) { try { m_SerializedAssetObject = new SerializedObject(spriteAtlasAsset, m_Context); m_SerializedAssetObject.inspectorMode = inspectorMode; m_ContentHash = GetInspectorHash(); m_EnabledProperty = m_SerializedAssetObject.FindProperty("m_Enabled"); } catch (System.ArgumentException e) { m_SerializedAssetObject = null; m_EnabledProperty = null; throw new SerializedObjectNotCreatableException(e.Message); } } return m_SerializedAssetObject; } public override void OnEnable() { base.OnEnable(); m_FilterMode = serializedObject.FindProperty("m_TextureSettings.filterMode"); m_AnisoLevel = serializedObject.FindProperty("m_TextureSettings.anisoLevel"); m_GenerateMipMaps = serializedObject.FindProperty("m_TextureSettings.generateMipMaps"); m_Readable = serializedObject.FindProperty("m_TextureSettings.readable"); m_UseSRGB = serializedObject.FindProperty("m_TextureSettings.sRGB"); m_EnableTightPacking = serializedObject.FindProperty("m_PackingSettings.enableTightPacking"); m_EnableRotation = serializedObject.FindProperty("m_PackingSettings.enableRotation"); m_EnableAlphaDilation = serializedObject.FindProperty("m_PackingSettings.enableAlphaDilation"); m_Padding = serializedObject.FindProperty("m_PackingSettings.padding"); m_BindAsDefault = serializedObject.FindProperty("m_BindAsDefault"); m_VariantScale = serializedObject.FindProperty("m_VariantMultiplier"); PopulatePlatformSettingsOptions(); SyncPlatformSettings(); m_TexturePlatformSettingsView = new SpriteAtlasInspectorPlatformSettingView(IsTargetMaster()); m_TexturePlatformSettingTextureHelper = new TexturePlatformSettingsFormatHelper(); m_TexturePlatformSettingsController = new TexturePlatformSettingsViewController(); // Don't show max size option for secondary textures as they must have the same size as the main texture. m_SecondaryTexturePlatformSettingsView = new SpriteAtlasInspectorPlatformSettingView(false); m_AssetPath = LoadSourceAsset(); if (spriteAtlasAsset == null) return; m_MasterAtlas = serializedAssetObject.FindProperty("m_MasterAtlas"); m_ScriptablePacker = serializedAssetObject.FindProperty("m_ScriptablePacker"); m_Packables = serializedAssetObject.FindProperty("m_ImporterData.packables"); m_PackableList = new ReorderableList(serializedAssetObject, m_Packables, true, true, true, true); m_PackableList.onAddCallback = AddPackable; m_PackableList.drawElementCallback = DrawPackableElement; m_PackableList.elementHeight = EditorGUIUtility.singleLineHeight; m_PackableList.headerHeight = 0f; } // Populate the platform settings dropdown list with secondary texture names found through serialized properties of the Sprite Atlas assets. private void PopulatePlatformSettingsOptions() { m_PlatformSettingsOptions = new List<string> { L10n.Tr("Main Texture"), "", "", L10n.Tr("New Secondary Texture settings.") }; SerializedProperty secondaryPlatformSettings = serializedObject.FindProperty("m_SecondaryTextureSettings"); if (secondaryPlatformSettings != null && !secondaryPlatformSettings.hasMultipleDifferentValues) { int numSecondaryTextures = secondaryPlatformSettings.arraySize; List<string> secondaryTextureNames = new List<string>(numSecondaryTextures); for (int i = 0; i < numSecondaryTextures; ++i) secondaryTextureNames.Add(secondaryPlatformSettings.GetArrayElementAtIndex(i).displayName); // Insert after main texture and the separator. m_PlatformSettingsOptions.InsertRange(2, secondaryTextureNames); } m_SelectedPlatformSettings = 0; } void SyncPlatformSettings() { m_TempPlatformSettings = new Dictionary<string, List<TextureImporterPlatformSettings>>(); string secondaryTextureName = null; if (secondaryTextureSelected) secondaryTextureName = m_PlatformSettingsOptions[m_SelectedPlatformSettings]; // Default platform var defaultSettings = new List<TextureImporterPlatformSettings>(); m_TempPlatformSettings.Add(TextureImporterInspector.s_DefaultPlatformName, defaultSettings); var settings = secondaryTextureSelected ? spriteAtlasImporter.GetSecondaryPlatformSettings(TextureImporterInspector.s_DefaultPlatformName, secondaryTextureName) : spriteAtlasImporter.GetPlatformSettings(TextureImporterInspector.s_DefaultPlatformName); defaultSettings.Add(settings); m_ValidPlatforms = BuildPlatforms.instance.GetValidPlatforms(); foreach (var platform in m_ValidPlatforms) { var platformSettings = new List<TextureImporterPlatformSettings>(); m_TempPlatformSettings.Add(platform.name, platformSettings); var perPlatformSettings = secondaryTextureSelected ? spriteAtlasImporter.GetSecondaryPlatformSettings(platform.name, secondaryTextureName) : spriteAtlasImporter.GetPlatformSettings(platform.name); // setting will be in default state if copy failed platformSettings.Add(perPlatformSettings); } } void RenameSecondaryPlatformSettings(string oldName, string newName) { spriteAtlasImporter.DeleteSecondaryPlatformSettings(oldName); var defaultPlatformSettings = m_TempPlatformSettings[TextureImporterInspector.s_DefaultPlatformName]; spriteAtlasImporter.SetSecondaryPlatformSettings(defaultPlatformSettings[0], newName); foreach (var buildPlatform in m_ValidPlatforms) { var platformSettings = m_TempPlatformSettings[buildPlatform.name]; spriteAtlasImporter.SetSecondaryPlatformSettings(platformSettings[0], newName); } } void AddPackable(ReorderableList list) { ObjectSelector.get.Show(null, typeof(Object), null, false); ObjectSelector.get.searchFilter = "t:sprite t:texture2d t:folder"; ObjectSelector.get.objectSelectorID = styles.packableSelectorHash; } void DrawPackableElement(Rect rect, int index, bool selected, bool focused) { var property = m_Packables.GetArrayElementAtIndex(index); var controlID = EditorGUIUtility.GetControlID(styles.packableElementHash, FocusType.Passive); var previousObject = property.objectReferenceValue; var changedObject = EditorGUI.DoObjectField(rect, rect, controlID, previousObject, target, typeof(Object), ValidateObjectForPackableFieldAssignment, false); if (changedObject != previousObject) { Undo.RegisterCompleteObjectUndo(spriteAtlasAsset, styles.swapObjectRegisterUndo); property.objectReferenceValue = changedObject; } if (GUIUtility.keyboardControl == controlID && !selected) m_PackableList.index = index; } protected override void Apply() { if (HasModified()) { if (spriteAtlasAsset) { SpriteAtlasAsset.Save(spriteAtlasAsset, m_AssetPath); AssetDatabase.ImportAsset(m_AssetPath); } m_ContentHash = GetInspectorHash(); } base.Apply(); } protected override bool useAssetDrawPreview { get { return false; } } protected void PackPreviewGUI() { EditorGUILayout.Space(); using (new GUILayout.HorizontalScope()) { using (new EditorGUI.DisabledScope(!HasModified() || !IsValidAtlas() || Application.isPlaying)) { GUILayout.FlexibleSpace(); if (GUILayout.Button(styles.packPreviewLabel)) { GUI.FocusControl(null); SpriteAtlasUtility.EnableV2Import(true); SaveChanges(); SpriteAtlasUtility.EnableV2Import(false); } } } } private bool IsValidAtlas() { if (IsTargetVariant()) return m_MasterAtlas.objectReferenceValue != null; else return true; } public override bool HasModified() { return !m_Discard && (base.HasModified() || m_ContentHash != GetInspectorHash()); } private void ValidateMasterAtlas() { if (m_MasterAtlas.objectReferenceValue != null) { var assetPath = AssetDatabase.GetAssetPath(m_MasterAtlas.objectReferenceValue); if (assetPath == m_AssetPath) { UnityEngine.Debug.LogWarning("Cannot set itself as MasterAtlas. Please assign a valid MasterAtlas."); m_MasterAtlas.objectReferenceValue = null; } } if (m_MasterAtlas.objectReferenceValue != null) { SpriteAtlas masterAsset = m_MasterAtlas.objectReferenceValue as SpriteAtlas; if (masterAsset != null && masterAsset.isVariant) { UnityEngine.Debug.LogWarning("Cannot set a VariantAtlas as MasterAtlas. Please assign a valid MasterAtlas."); m_MasterAtlas.objectReferenceValue = null; } } } public override void OnInspectorGUI() { // Ensure changes done through script are reflected immediately in Inspector by Syncing m_TempPlatformSettings with Actual Settings. SyncPlatformSettings(); serializedObject.Update(); if (spriteAtlasAsset) { serializedAssetObject.Update(); HandleCommonSettingUI(); } EditorGUILayout.PropertyField(m_BindAsDefault, styles.bindAsDefaultLabel); GUILayout.Space(EditorGUI.kSpacing); bool isTargetMaster = true; if (spriteAtlasAsset) isTargetMaster = IsTargetMaster(); if (isTargetMaster) HandleMasterSettingUI(); if (!spriteAtlasAsset || IsTargetVariant()) HandleVariantSettingUI(); GUILayout.Space(EditorGUI.kSpacing); HandleTextureSettingUI(); GUILayout.Space(EditorGUI.kSpacing); // Only show the packable object list when: // - This is a master atlas. if (targets.Length == 1 && IsTargetMaster() && spriteAtlasAsset) HandlePackableListUI(); serializedObject.ApplyModifiedProperties(); if (spriteAtlasAsset) { serializedAssetObject.ApplyModifiedProperties(); PackPreviewGUI(); } ApplyRevertGUI(); } private void HandleCommonSettingUI() { var atlasType = AtlasType.Undefined; if (IsTargetMaster()) atlasType = AtlasType.Master; else if (IsTargetVariant()) atlasType = AtlasType.Variant; EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = atlasType == AtlasType.Undefined; atlasType = (AtlasType)EditorGUILayout.IntPopup(styles.atlasTypeLabel, (int)atlasType, styles.atlasTypeOptions, styles.atlasTypeValues); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { bool setToVariant = atlasType == AtlasType.Variant; spriteAtlasAsset.SetIsVariant(setToVariant); // Reinit the platform setting view m_TexturePlatformSettingsView = new SpriteAtlasInspectorPlatformSettingView(IsTargetMaster()); } m_ScriptablePacker.objectReferenceValue = EditorGUILayout.ObjectField(styles.packerLabel, m_ScriptablePacker.objectReferenceValue, typeof(UnityEditor.U2D.ScriptablePacker), false); if (atlasType == AtlasType.Variant) { EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(m_MasterAtlas, styles.masterAtlasLabel); if (EditorGUI.EndChangeCheck()) { ValidateMasterAtlas(); // Apply modified properties here to have latest master atlas reflected in native codes. serializedAssetObject.ApplyModifiedPropertiesWithoutUndo(); PopulatePlatformSettingsOptions(); SyncPlatformSettings(); } } } private void HandleVariantSettingUI() { EditorGUILayout.LabelField(styles.variantSettingLabel, EditorStyles.boldLabel); EditorGUILayout.PropertyField(m_VariantScale, styles.variantMultiplierLabel); // Test if the multiplier scale a power of two size (1024) into another power of 2 size. if (!Mathf.IsPowerOfTwo((int)(m_VariantScale.floatValue * 1024))) EditorGUILayout.HelpBox(styles.notPowerOfTwoWarning.text, MessageType.Warning, true); } private void HandleBoolToIntPropertyField(SerializedProperty prop, GUIContent content) { Rect rect = EditorGUILayout.GetControlRect(); EditorGUI.BeginProperty(rect, content, prop); EditorGUI.BeginChangeCheck(); var boolValue = EditorGUI.Toggle(rect, content, prop.boolValue); if (EditorGUI.EndChangeCheck()) prop.boolValue = boolValue; EditorGUI.EndProperty(); } private void HandleMasterSettingUI() { EditorGUILayout.LabelField(styles.packingParametersLabel, EditorStyles.boldLabel); HandleBoolToIntPropertyField(m_EnableRotation, styles.enableRotationLabel); HandleBoolToIntPropertyField(m_EnableTightPacking, styles.enableTightPackingLabel); HandleBoolToIntPropertyField(m_EnableAlphaDilation, styles.enableAlphaDilationLabel); EditorGUILayout.IntPopup(m_Padding, styles.paddingOptions, styles.paddingValues, styles.paddingLabel); GUILayout.Space(EditorGUI.kSpacing); } private void HandleTextureSettingUI() { EditorGUILayout.LabelField(styles.textureSettingLabel, EditorStyles.boldLabel); HandleBoolToIntPropertyField(m_Readable, styles.readWrite); HandleBoolToIntPropertyField(m_GenerateMipMaps, styles.generateMipMapLabel); HandleBoolToIntPropertyField(m_UseSRGB, styles.sRGBLabel); EditorGUILayout.PropertyField(m_FilterMode); var showAniso = !m_FilterMode.hasMultipleDifferentValues && !m_GenerateMipMaps.hasMultipleDifferentValues && (FilterMode)m_FilterMode.intValue != FilterMode.Point && m_GenerateMipMaps.boolValue; if (showAniso) EditorGUILayout.IntSlider(m_AnisoLevel, 0, 16); GUILayout.Space(EditorGUI.kSpacing); // "Show Platform Settings For" dropdown EditorGUILayout.BeginHorizontal(); { EditorGUILayout.PrefixLabel(s_Styles.platformSettingsDropDownLabel); EditorGUI.BeginChangeCheck(); m_SelectedPlatformSettings = EditorGUILayout.Popup(m_SelectedPlatformSettings, m_PlatformSettingsOptions.ToArray(), GUILayout.MaxWidth(150.0f)); if (EditorGUI.EndChangeCheck()) { // New settings option is selected... if (m_SelectedPlatformSettings == m_PlatformSettingsOptions.Count - 1) { m_PlatformSettingsOptions.Insert(m_SelectedPlatformSettings - 1, s_Styles.defaultTextForSecondaryTextureName); m_SelectedPlatformSettings--; EditorGUI.FocusTextInControl(s_Styles.secondaryTextureNameTextControlName); } SyncPlatformSettings(); } if (secondaryTextureSelected) { // trash can button if (GUILayout.Button(s_Styles.trashIcon, EditorStyles.iconButton, GUILayout.ExpandWidth(false))) { EditorGUI.EndEditingActiveTextField(); spriteAtlasImporter.DeleteSecondaryPlatformSettings(m_PlatformSettingsOptions[m_SelectedPlatformSettings]); m_PlatformSettingsOptions.RemoveAt(m_SelectedPlatformSettings); m_SelectedPlatformSettings--; if (m_SelectedPlatformSettings == 1) m_SelectedPlatformSettings = 0; SyncPlatformSettings(); } } } EditorGUILayout.EndHorizontal(); // Texture platform settings UI. EditorGUILayout.BeginHorizontal(); { EditorGUI.indentLevel++; GUILayout.Space(EditorGUI.indent); EditorGUI.indentLevel--; if (m_SelectedPlatformSettings == 0) { GUILayout.Space(EditorGUI.kSpacing); HandlePlatformSettingUI(null); } else { EditorGUILayout.BeginVertical(); { GUILayout.Space(EditorGUI.kSpacing); string oldSecondaryTextureName = m_PlatformSettingsOptions[m_SelectedPlatformSettings]; GUI.SetNextControlName(s_Styles.secondaryTextureNameTextControlName); EditorGUI.BeginChangeCheck(); string textFieldText = EditorGUILayout.DelayedTextField(s_Styles.secondaryTextureNameLabel, oldSecondaryTextureName); if (EditorGUI.EndChangeCheck() && oldSecondaryTextureName != textFieldText) { if (!m_PlatformSettingsOptions.Exists(x => x == textFieldText)) { m_PlatformSettingsOptions[m_SelectedPlatformSettings] = textFieldText; RenameSecondaryPlatformSettings(oldSecondaryTextureName, textFieldText); } else { Debug.LogWarning(s_Styles.nameUniquenessWarning); EditorGUI.FocusTextInControl(s_Styles.secondaryTextureNameTextControlName); } } string secondaryTextureName = m_PlatformSettingsOptions[m_SelectedPlatformSettings]; EditorGUI.BeginChangeCheck(); bool value = EditorGUILayout.Toggle(s_Styles.sRGBLabel, spriteAtlasImporter.GetSecondaryColorSpace(secondaryTextureName)); if (EditorGUI.EndChangeCheck()) spriteAtlasImporter.SetSecondaryColorSpace(secondaryTextureName, value); HandlePlatformSettingUI(textFieldText); } EditorGUILayout.EndVertical(); } } EditorGUILayout.EndHorizontal(); } private void HandlePlatformSettingUI(string secondaryTextureName) { int shownTextureFormatPage = EditorGUILayout.BeginPlatformGrouping(m_ValidPlatforms.ToArray(), styles.defaultPlatformLabel); var defaultPlatformSettings = m_TempPlatformSettings[TextureImporterInspector.s_DefaultPlatformName]; bool isSecondary = secondaryTextureName != null; ITexturePlatformSettingsView view = isSecondary ? m_SecondaryTexturePlatformSettingsView : m_TexturePlatformSettingsView; if (shownTextureFormatPage == -1) { if (m_TexturePlatformSettingsController.HandleDefaultSettings(defaultPlatformSettings, view, m_TexturePlatformSettingTextureHelper)) { for (var i = 0; i < defaultPlatformSettings.Count; ++i) { if (isSecondary) spriteAtlasImporter.SetSecondaryPlatformSettings(defaultPlatformSettings[i], secondaryTextureName); else spriteAtlasImporter.SetPlatformSettings(defaultPlatformSettings[i]); } } } else { var buildPlatform = m_ValidPlatforms[shownTextureFormatPage]; var platformSettings = m_TempPlatformSettings[buildPlatform.name]; for (var i = 0; i < platformSettings.Count; ++i) { var settings = platformSettings[i]; if (!settings.overridden) { if (defaultPlatformSettings[0].format == TextureImporterFormat.Automatic) { settings.format = (TextureImporterFormat)spriteAtlasImporter.GetTextureFormat(buildPlatform.defaultTarget); } else { settings.format = defaultPlatformSettings[0].format; } settings.maxTextureSize = defaultPlatformSettings[0].maxTextureSize; settings.crunchedCompression = defaultPlatformSettings[0].crunchedCompression; settings.compressionQuality = defaultPlatformSettings[0].compressionQuality; } } m_TexturePlatformSettingsView.buildPlatformTitle = buildPlatform.title.text; if (m_TexturePlatformSettingsController.HandlePlatformSettings(buildPlatform.defaultTarget, platformSettings, view, m_TexturePlatformSettingTextureHelper)) { for (var i = 0; i < platformSettings.Count; ++i) { if (isSecondary) spriteAtlasImporter.SetSecondaryPlatformSettings(platformSettings[i], secondaryTextureName); else spriteAtlasImporter.SetPlatformSettings(platformSettings[i]); } } } EditorGUILayout.EndPlatformGrouping(); } private void HandlePackableListUI() { var currentEvent = Event.current; var usedEvent = false; Rect rect = EditorGUILayout.GetControlRect(); var controlID = EditorGUIUtility.s_LastControlID; switch (currentEvent.type) { case EventType.DragExited: if (GUI.enabled) HandleUtility.Repaint(); break; case EventType.DragUpdated: case EventType.DragPerform: if (rect.Contains(currentEvent.mousePosition) && GUI.enabled) { // Check each single object, so we can add multiple objects in a single drag. var didAcceptDrag = false; var references = DragAndDrop.objectReferences; foreach (var obj in references) { if (IsPackable(obj)) { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (currentEvent.type == EventType.DragPerform) { m_Packables.AppendFoldoutPPtrValue(obj); didAcceptDrag = true; DragAndDrop.activeControlID = 0; } else DragAndDrop.activeControlID = controlID; } } if (didAcceptDrag) { GUI.changed = true; DragAndDrop.AcceptDrag(); usedEvent = true; } } break; case EventType.ValidateCommand: if (currentEvent.commandName == ObjectSelector.ObjectSelectorClosedCommand && ObjectSelector.get.objectSelectorID == styles.packableSelectorHash) usedEvent = true; break; case EventType.ExecuteCommand: if (currentEvent.commandName == ObjectSelector.ObjectSelectorClosedCommand && ObjectSelector.get.objectSelectorID == styles.packableSelectorHash) { var obj = ObjectSelector.GetCurrentObject(); if (IsPackable(obj)) { m_Packables.AppendFoldoutPPtrValue(obj); m_PackableList.index = m_Packables.arraySize - 1; } usedEvent = true; } break; } // Handle Foldout after we handle the current event because Foldout might process the drag and drop event and used it. m_PackableListExpanded = EditorGUI.Foldout(rect, m_PackableListExpanded, styles.packableListLabel, true); if (usedEvent) currentEvent.Use(); if (m_PackableListExpanded) { EditorGUI.indentLevel++; m_PackableList.DoLayoutList(); EditorGUI.indentLevel--; } } public override void SaveChanges() { if (!m_Discard) base.SaveChanges(); m_ContentHash = GetInspectorHash(); } public override void DiscardChanges() { m_Discard = true; base.DiscardChanges(); m_ContentHash = GetInspectorHash(); } void CachePreviewTexture() { var spriteAtlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(m_AssetPath); if (spriteAtlas != null) { bool hasPreview = m_PreviewTextures != null && m_PreviewTextures.Length > 0; if (hasPreview) { foreach (var previewTexture in m_PreviewTextures) hasPreview = previewTexture != null; } if (!hasPreview || m_Hash != spriteAtlas.GetHash()) { m_PreviewTextures = spriteAtlas.GetPreviewTextures(); m_PreviewAlphaTextures = spriteAtlas.GetPreviewAlphaTextures(); m_Hash = spriteAtlas.GetHash(); if (m_PreviewTextures != null && m_PreviewTextures.Length > 0 && m_TotalPages != m_PreviewTextures.Length) { m_TotalPages = m_PreviewTextures.Length; m_OptionDisplays = new string[m_TotalPages]; m_OptionValues = new int[m_TotalPages]; for (int i = 0; i < m_TotalPages; ++i) { string texName = m_PreviewTextures[i].name; var pageNum = SpriteAtlasExtensions.GetPageNumberInAtlas(texName); var secondaryName = SpriteAtlasExtensions.GetSecondaryTextureNameInAtlas(texName); m_OptionDisplays[i] = secondaryName == "" ? string.Format("MainTex - Page ({0})", pageNum) : string.Format("{0} - Page ({1})", secondaryName, pageNum); m_OptionValues[i] = i; } } } } } public override string GetInfoString() { if (m_PreviewTextures != null && m_PreviewPage < m_PreviewTextures.Length) { Texture2D t = m_PreviewTextures[m_PreviewPage]; GraphicsFormat format = GraphicsFormatUtility.GetFormat(t); return string.Format("{0}x{1} {2}\n{3}", t.width, t.height, GraphicsFormatUtility.GetFormatString(format), EditorUtility.FormatBytes(TextureUtil.GetStorageMemorySizeLong(t))); } return ""; } public override bool HasPreviewGUI() { CachePreviewTexture(); if (m_PreviewTextures != null && m_PreviewTextures.Length > 0) { Texture2D t = m_PreviewTextures[0]; return t != null; } return false; } public override void OnPreviewSettings() { // Do not allow changing of pages when multiple atlases is selected. if (targets.Length == 1 && m_OptionDisplays != null && m_OptionValues != null && m_TotalPages > 1) m_PreviewPage = EditorGUILayout.IntPopup(m_PreviewPage, m_OptionDisplays, m_OptionValues, styles.preDropDown, GUILayout.MaxWidth(50)); else m_PreviewPage = 0; if (m_PreviewTextures != null) { m_PreviewPage = Mathf.Min(m_PreviewPage, m_PreviewTextures.Length - 1); Texture2D t = m_PreviewTextures[m_PreviewPage]; if (t == null) return; if (GraphicsFormatUtility.HasAlphaChannel(t.format) || (m_PreviewAlphaTextures != null && m_PreviewAlphaTextures.Length > 0)) m_ShowAlpha = GUILayout.Toggle(m_ShowAlpha, m_ShowAlpha ? styles.alphaIcon : styles.RGBIcon, styles.previewButton); int mipCount = Mathf.Max(1, TextureUtil.GetMipmapCount(t)); if (mipCount > 1) { GUILayout.Box(styles.smallZoom, styles.previewLabel); m_MipLevel = Mathf.Round(GUILayout.HorizontalSlider(m_MipLevel, mipCount - 1, 0, styles.previewSlider, styles.previewSliderThumb, GUILayout.MaxWidth(64))); GUILayout.Box(styles.largeZoom, styles.previewLabel); } } } public override void OnPreviewGUI(Rect r, GUIStyle background) { CachePreviewTexture(); if (m_ShowAlpha && m_PreviewAlphaTextures != null && m_PreviewPage < m_PreviewAlphaTextures.Length) { var at = m_PreviewAlphaTextures[m_PreviewPage]; var bias = m_MipLevel - (float)(System.Math.Log(at.width / r.width) / System.Math.Log(2)); EditorGUI.DrawTextureTransparent(r, at, ScaleMode.ScaleToFit, 0, bias); } else if (m_PreviewTextures != null && m_PreviewPage < m_PreviewTextures.Length) { Texture2D t = m_PreviewTextures[m_PreviewPage]; if (t == null) return; float bias = m_MipLevel - (float)(System.Math.Log(t.width / r.width) / System.Math.Log(2)); if (m_ShowAlpha) EditorGUI.DrawTextureAlpha(r, t, ScaleMode.ScaleToFit, 0, bias); else EditorGUI.DrawTextureTransparent(r, t, ScaleMode.ScaleToFit, 0, bias); } } } }
412
0.904305
1
0.904305
game-dev
MEDIA
0.916139
game-dev
0.841644
1
0.841644
decentraland/bronzeage-editor
1,779
Assets/Scripts/Editor/PrefabUtil.cs
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; public class PrefabUtil : MonoBehaviour { #region Exposed fields #endregion Exposed fields #region Internal fields #endregion Internal fields #region Custom Events #endregion Custom Events #region Properties #endregion Properties #region Events methods #endregion Events methods #region Public Methods /// <summary> /// Create prefabs with current selection /// </summary public static GameObject[] CreatePrefabs(string path) { var selectedObjects = Selection.gameObjects; var selectedCount = selectedObjects.Length; // Check for folder var localPath = path; if (!DirUtil.CheckForProjectPath(localPath)) DirUtil.CreateFolderTree(localPath); // Fill array of prefabs var prefabs = new GameObject[selectedCount]; for (int i = 0; i < selectedCount; i++) { var go = selectedObjects[i]; prefabs[i] = PrefabUtility.CreatePrefab(localPath + go.name + ".prefab", go); } return prefabs; } /// <summary> /// Create prefabs with current selection /// </summary public static GameObject CreatePrefabFromActiveGO(string path) { var go = Selection.activeGameObject; // Check for folder var localPath = path; if (!DirUtil.CheckForProjectPath(localPath)) DirUtil.CreateFolderTree(localPath); // Fill array of prefabs var prefab = PrefabUtility.CreatePrefab(localPath + go.name + ".prefab", go); return prefab; } #endregion Methods #region Non Public Methods #endregion Methods }
412
0.865323
1
0.865323
game-dev
MEDIA
0.94575
game-dev
0.78655
1
0.78655
00-Evan/shattered-pixel-dungeon-gdx
2,576
core/src/com/shatteredpixel/shatteredpixeldungeon/levels/traps/FlashingTrap.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.levels.traps; import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.Actor; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Bleeding; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Blindness; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Cripple; import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.Mob; import com.shatteredpixel.shatteredpixeldungeon.levels.Level; import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain; import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene; import com.watabou.noosa.audio.Sample; public class FlashingTrap extends Trap { { color = GREY; shape = STARS; } @Override public void trigger() { if (Dungeon.level.heroFOV[pos]){ Sample.INSTANCE.play(Assets.SND_TRAP); } //this trap is not disarmed by being triggered reveal(); Level.set(pos, Terrain.TRAP); activate(); } @Override public void activate() { Char c = Actor.findChar( pos ); if (c != null) { int damage = Math.max( 0, (4 + Dungeon.depth) - c.drRoll() ); Buff.affect( c, Bleeding.class ).set( damage ); Buff.prolong( c, Blindness.class, 10f ); Buff.prolong( c, Cripple.class, 20f ); if (c instanceof Mob) { if (((Mob)c).state == ((Mob)c).HUNTING) ((Mob)c).state = ((Mob)c).WANDERING; ((Mob)c).beckon( Dungeon.level.randomDestination() ); } } if (Dungeon.level.heroFOV[pos]) { GameScene.flash(0xFFFFFF); Sample.INSTANCE.play( Assets.SND_BLAST ); } } }
412
0.750985
1
0.750985
game-dev
MEDIA
0.991997
game-dev
0.584774
1
0.584774
EmptyBottleInc/DFU-Tanguy-Multiplayer
3,551
Assets/Scripts/Game/MagicAndEffects/Effects/Thaumaturgy/Identify.cs
// Project: Daggerfall Unity // Copyright: Copyright (C) 2009-2022 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: // // Notes: // using DaggerfallConnect; using DaggerfallConnect.Arena2; using DaggerfallWorkshop.Game.Entity; using DaggerfallWorkshop.Game.UserInterface; using DaggerfallWorkshop.Game.UserInterfaceWindows; using DaggerfallWorkshop.Game.Formulas; namespace DaggerfallWorkshop.Game.MagicAndEffects.MagicEffects { /// <summary> /// Identify - currently just opens a free identify window /// </summary> public class Identify : BaseEntityEffect { public static readonly string EffectKey = "Identify"; public override void SetProperties() { properties.Key = EffectKey; properties.ClassicKey = MakeClassicKey(40, 255); properties.SupportChance = true; properties.AllowedTargets = TargetTypes.CasterOnly; properties.AllowedElements = ElementTypes.Magic; properties.AllowedCraftingStations = MagicCraftingStations.SpellMaker; properties.MagicSkill = DFCareer.MagicSkills.Thaumaturgy; properties.ChanceCosts = MakeEffectCosts(40, 100, 28); properties.ChanceFunction = ChanceFunction.Custom; } public override string GroupName => TextManager.Instance.GetLocalizedText("identify"); public override TextFile.Token[] SpellMakerDescription => DaggerfallUnity.Instance.TextProvider.GetRSCTokens(1599); public override TextFile.Token[] SpellBookDescription => DaggerfallUnity.Instance.TextProvider.GetRSCTokens(1299); public override void Start(EntityEffectManager manager, DaggerfallEntityBehaviour caster = null) { base.Start(manager, caster); // Refund spell point cost for this effect before opening trade window // Actual spell point cost is applied when player clicks Identify button in trade window // Any other effects bundled with identify on spell will not have their spell point cost refunded FormulaHelper.SpellCost cost = FormulaHelper.CalculateEffectCosts(this, settings, caster.Entity); if (cost.spellPointCost < 5) cost.spellPointCost = 5; caster.Entity.IncreaseMagicka(cost.spellPointCost); // Get peered entity gameobject DaggerfallEntityBehaviour entityBehaviour = GetPeeredEntityBehaviour(manager); if (!entityBehaviour) return; // Target must be player - no effect on other entities if (entityBehaviour != GameManager.Instance.PlayerEntityBehaviour) return; // Open identify trade window in spell mode UserInterfaceManager uiManager = DaggerfallUI.UIManager as UserInterfaceManager; DaggerfallTradeWindow tradeWindow = (DaggerfallTradeWindow)UIWindowFactory.GetInstanceWithArgs(UIWindowType.Trade, new object[] { uiManager, null, DaggerfallTradeWindow.WindowModes.Identify, null }); tradeWindow.UsingIdentifySpell = true; tradeWindow.IdentifySpellChance = ChanceValue(); tradeWindow.IdentifySpellCost = cost.spellPointCost; uiManager.PushWindow(tradeWindow); } } }
412
0.883337
1
0.883337
game-dev
MEDIA
0.835088
game-dev
0.947997
1
0.947997
pjasicek/OpenClaw
10,562
ThirdParty/sigc++-3.0/sigc++/functors/slot.h
/* * Copyright 2003 - 2016, The libsigc++ Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef SIGC_FUNCTORS_SLOT_H #define SIGC_FUNCTORS_SLOT_H #include <sigc++/trackable.h> #include <sigc++/visit_each.h> #include <sigc++/adaptors/adaptor_trait.h> #include <sigc++/functors/slot_base.h> #include <memory> namespace sigc { namespace internal { /** A typed slot_rep. * A typed slot_rep holds a functor that can be invoked from * slot::operator()(). visit_each() is used to visit the functor's * targets that inherit trackable recursively and register the * notification callback. Consequently the slot_rep object will be * notified when some referred object is destroyed or overwritten. */ template <typename T_functor> struct typed_slot_rep : public slot_rep { private: /* Use an adaptor type so that arguments can be passed as const references * through explicit template instantiation from slot_call#::call_it() */ using adaptor_type = typename adaptor_trait<T_functor>::adaptor_type; public: /** The functor contained by this slot_rep object. */ std::unique_ptr<adaptor_type> functor_; /** Constructs an invalid typed slot_rep object. * The notification callback is registered using visit_each(). * @param functor The functor contained by the new slot_rep object. */ inline explicit typed_slot_rep(const T_functor& functor) : slot_rep(nullptr), functor_(std::make_unique<adaptor_type>(functor)) { sigc::visit_each_trackable(slot_do_bind(this), *functor_); } inline typed_slot_rep(const typed_slot_rep& src) : slot_rep(src.call_), functor_(std::make_unique<adaptor_type>(*src.functor_)) { sigc::visit_each_trackable(slot_do_bind(this), *functor_); } typed_slot_rep& operator=(const typed_slot_rep& src) = delete; typed_slot_rep(typed_slot_rep&& src) = delete; typed_slot_rep& operator=(typed_slot_rep&& src) = delete; ~typed_slot_rep() override { // Call destroy() non-virtually. // It's unwise to make virtual calls in a constructor or destructor. typed_slot_rep::destroy(); } private: /** Detaches the stored functor from the other referred trackables and destroys it. * This does not destroy the base slot_rep object. */ void destroy() override { call_ = nullptr; if (functor_) { sigc::visit_each_trackable(slot_do_unbind(this), *functor_); functor_.reset(nullptr); } /* don't call disconnect() here: destroy() is either called * a) from the parent itself (in which case disconnect() leads to a segfault) or * b) from a parentless slot (in which case disconnect() does nothing) */ } /** Makes a deep copy of the slot_rep object. * Deep copy means that the notification callback of the new * slot_rep object is registered in the referred trackables. * @return A deep copy of the slot_rep object. */ slot_rep* clone() const override { return new typed_slot_rep(*this); } }; /** Abstracts functor execution. * call_it() invokes a functor of type @e T_functor with a list of * parameters whose types are given by the template arguments. * address() forms a function pointer from call_it(). * * The following template arguments are used: * - @e T_functor The functor type. * - @e T_return The return type of call_it(). * - @e T_arg Argument types used in the definition of call_it(). * */ template <typename T_functor, typename T_return, typename... T_arg> struct slot_call { /** Invokes a functor of type @p T_functor. * @param rep slot_rep object that holds a functor of type @p T_functor. * @param a Arguments to be passed on to the functor. * @return The return values of the functor invocation. */ static T_return call_it(slot_rep* rep, type_trait_take_t<T_arg>... a_) { auto typed_rep = static_cast<typed_slot_rep<T_functor>*>(rep); return (*typed_rep->functor_).template operator()<type_trait_take_t<T_arg>...>(a_...); } /** Forms a function pointer from call_it(). * @return A function pointer formed from call_it(). */ static hook address() { return reinterpret_cast<hook>(&call_it); } }; } /* namespace internal */ // Because slot is opaque, visit_each() will not visit its internal members. // Those members are not reachable by visit_each() after the slot has been // constructed. But when a slot contains another slot, the outer slot will become // the parent of the inner slot, with similar results. See the description of // slot's specialization of the visitor struct. /** Converts an arbitrary functor to a unified type which is opaque. * sigc::slot itself is a functor or, to be more precise, a closure. It contains * a single, arbitrary functor (or closure) that is executed in operator()(). * * The template arguments determine the function signature of operator()(): * - @e T_return The return type of operator()(). * - @e T_arg Argument types used in the definition of operator()(). * * For instance, to declare a slot that returns void and takes two parameters * of bool and int: * @code * sigc::slot<void(bool, int)> some_slot; * @endcode * * To use, simply assign the desired functor to the slot. If the functor * is not compatible with the parameter list defined with the template * arguments then compiler errors are triggered. When called, the slot * will invoke the functor with minimal copies. * block() and unblock() can be used to block the functor's invocation * from operator()() temporarily. * * @ingroup slot */ template <typename T_return, typename... T_arg> class slot; template <typename T_return, typename... T_arg> class slot<T_return(T_arg...)> : public slot_base { public: // TODO: using arg_type_ = type_trait_take_t<T_arg>; #ifndef DOXYGEN_SHOULD_SKIP_THIS private: using rep_type = internal::slot_rep; public: using call_type = T_return (*)(rep_type*, type_trait_take_t<T_arg>...); #endif /** Invoke the contained functor unless slot is in blocking state. * @param a Arguments to be passed on to the functor. * @return The return value of the functor invocation. */ inline T_return operator()(type_trait_take_t<T_arg>... a) const { if (!empty() && !blocked()) return (reinterpret_cast<call_type>(slot_base::rep_->call_))(slot_base::rep_, a...); return T_return(); } inline slot() = default; /** Constructs a slot from an arbitrary functor. * @param func The desired functor the new slot should be assigned to. */ template <typename T_functor> slot(const T_functor& func) : slot_base(new internal::typed_slot_rep<T_functor>(func)) { // The slot_base:: is necessary to stop the HP-UX aCC compiler from being confused. murrayc. slot_base::rep_->call_ = internal::slot_call<T_functor, T_return, T_arg...>::address(); } /** Constructs a slot, copying an existing one. * @param src The existing slot to copy. */ slot(const slot& src) = default; /** Constructs a slot, moving an existing one. * If @p src is connected to a parent (e.g. a signal), it is copied, not moved. * @param src The existing slot to move or copy. */ slot(slot&& src) : slot_base(std::move(src)) {} /** Overrides this slot, making a copy from another slot. * @param src The slot from which to make a copy. * @return @p this. */ slot& operator=(const slot& src) = default; /** Overrides this slot, making a move from another slot. * If @p src is connected to a parent (e.g. a signal), it is copied, not moved. * @param src The slot from which to move or copy. * @return @p this. */ slot& operator=(slot&& src) { slot_base::operator=(std::move(src)); return *this; } }; #ifndef DOXYGEN_SHOULD_SKIP_THIS // template specialization of visitor<>::do_visit_each<>(action, functor): /** Performs a functor on each of the targets of a functor. * * There are three function overloads for sigc::slot. * * The first two overloads are very specialized. They handle the (probably unusual) * case when the functor, stored in a slot, contains a slot. They are invoked from * the constructor, destructor or destroy() method of typed_slot_rep. * The first overload, called from the constructor of the outer slot, sets * the outer slot as the parent of the inner slot. The second overload, called from * the destructor or destroy() of the outer slot, unsets the parent of the inner slot. * When an object referenced from the inner slot is deleted, the inner slot calls * its slot_rep::disconnect(), which calls the outer slot's slot_rep::notify_slot_rep_invalidated(). * The outer slot is informed just as if one of its directly referenced objects * had been deleted. Result: The outer slot is disconnected from its parent, * if any (for instance a sigc::signal). * See https://bugzilla.gnome.org/show_bug.cgi?id=755003 * * The third overload is identical to do_visit_each() in visitor's primary template. * * @ingroup slot */ template <typename T_return, typename... T_arg> struct visitor<slot<T_return, T_arg...>> { static void do_visit_each( const internal::limit_trackable_target<internal::slot_do_bind>& action, const slot<T_return, T_arg...>& target) { if (target.rep_ && target.rep_->parent_ == nullptr) target.rep_->set_parent(action.action_.rep_, &internal::slot_rep::notify_slot_rep_invalidated); } static void do_visit_each( const internal::limit_trackable_target<internal::slot_do_unbind>& action, const slot<T_return, T_arg...>& target) { if (target.rep_ && target.rep_->parent_ == action.action_.rep_) target.rep_->unset_parent(); } template <typename T_action> static void do_visit_each(const T_action& action, const slot<T_return, T_arg...>& target) { action(target); } }; #endif // DOXYGEN_SHOULD_SKIP_THIS } /* namespace sigc */ #endif /* SIGC_FUNCTORS_SLOT_H */
412
0.938562
1
0.938562
game-dev
MEDIA
0.478795
game-dev
0.923266
1
0.923266
gabrieldechichi/dmotion
4,912
Tests/Core/ECSTestBase.cs
using System.Linq; using System.Reflection; using NUnit.Framework; using Unity.Collections; using Unity.Core; using Unity.Entities; using UnityEngine; using UnityEngine.TestTools; namespace DMotion.Tests { [RequiresPlayMode(false)] public abstract class ECSTestBase : ECSTestsFixture { protected const float defaultDeltaTime = 1.0f / 60.0f; private float elapsedTime; private NativeArray<SystemHandle> allSystems; private BlobAssetStore blobAssetStore; public override void Setup() { base.Setup(); elapsedTime = Time.time; //Create required systems { var requiredSystemsAttr = GetType().GetCustomAttribute<CreateSystemsForTest>(); if (requiredSystemsAttr != null) { var baseTypeManaged = typeof(SystemBase); var baseType = typeof(ISystem); foreach (var t in requiredSystemsAttr.SystemTypes) { var isValid = baseType.IsAssignableFrom(t) || baseTypeManaged.IsAssignableFrom(t); Assert.IsTrue(isValid, $"Expected {t.Name} to be a subclass of {baseType.Name} or {baseTypeManaged.Name}"); world.CreateSystem(t); } allSystems = world.Unmanaged.GetAllSystems(Allocator.Persistent); } } // //Convert entity prefabs { var bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; var convertPrefabField = GetType() .GetFields(bindingFlags) .Where(f => f.GetCustomAttribute<ConvertGameObjectPrefab>() != null).ToArray(); var createdEntities = new NativeArray<Entity>(convertPrefabField.Length, Allocator.Temp); blobAssetStore = new BlobAssetStore(128); var conversionWorld = new World("Test Conversion World"); //instantiate all entities in a conversion word for (var i = 0; i < convertPrefabField.Length; i++) { var f = convertPrefabField[i]; var value = f.GetValue(this); Assert.IsNotNull(value); GameObject go = null; if (value is GameObject g) { go = g; } else if (value is MonoBehaviour mono) { go = mono.gameObject; } Assert.IsNotNull(go); var entity = BakingTestUtils.ConvertGameObject(conversionWorld, go, blobAssetStore); Assert.AreNotEqual(entity, Entity.Null); createdEntities[i] = entity; } //copy entities from conversionWorld to testWorld var outputEntities = new NativeArray<Entity>(createdEntities.Length, Allocator.Temp); manager.CopyEntitiesFrom(conversionWorld.EntityManager, createdEntities, outputEntities); for (var i = 0; i < convertPrefabField.Length; i++) { var f = convertPrefabField[i]; var entity = outputEntities[i]; var attr = f.GetCustomAttribute<ConvertGameObjectPrefab>(); var receiveField = GetType().GetField(attr.ToFieldName, bindingFlags); Assert.IsNotNull(receiveField, $"Couldn't find field to receive entity prefab ({f.Name}, {attr.ToFieldName})"); receiveField.SetValue(this, entity); } conversionWorld.Dispose(); } } public override void TearDown() { base.TearDown(); if (allSystems.IsCreated) { allSystems.Dispose(); } if (blobAssetStore.IsCreated) { blobAssetStore.Dispose(); } } protected void UpdateWorld(float deltaTime = defaultDeltaTime) { if (world != null && world.IsCreated) { elapsedTime += deltaTime; world.SetTime(new TimeData(elapsedTime, deltaTime)); foreach (var s in allSystems) { s.Update(world.Unmanaged); } //We always want to complete all jobs after update world. Otherwise transformations that test expect to run may not have been run during Assert //This is also necessary for performance tests accuracy. manager.CompleteAllTrackedJobs(); } } } }
412
0.871815
1
0.871815
game-dev
MEDIA
0.662024
game-dev,testing-qa
0.830491
1
0.830491
BigWigsMods/LittleWigs
1,713
Legion/AssaultOnVioletHold/MillificentManastorm.lua
-------------------------------------------------------------------------------- -- Module Declaration -- local mod, CL = BigWigs:NewBoss("Millificent Manastorm", 1544, 1688) if not mod then return end mod:RegisterEnableMob(101976) mod.engageId = 1847 -------------------------------------------------------------------------------- -- Initialization -- function mod:GetOptions() return { 201159, -- Delta Finger Laser X-treme 201240, -- Elementium Squirrel Bomb 201392, -- Thorium Rocket Chicken 201572, -- Millificent's Rage } end function mod:OnBossEnable() self:Log("SPELL_AURA_APPLIED", "DeltaFinger", 201159) self:Log("SPELL_CAST_SUCCESS", "SquirrelBomb", 201240, 201432) -- normal, overloaded self:Log("SPELL_CAST_SUCCESS", "RocketChicken", 201392, 201438) -- normal, reinforced self:Log("SPELL_AURA_APPLIED", "MillificentsRage", 201572) end function mod:OnEngage() self:Bar(201159, 5) -- Delta Finger Laser X-treme self:CDBar(201240, 7) -- Elementium Squirrel Bomb self:CDBar(201392, 24) -- Thorium Rocket Chicken end -------------------------------------------------------------------------------- -- Event Handlers -- function mod:DeltaFinger(args) self:TargetMessageOld(args.spellId, args.destName, "orange") self:Bar(args.spellId, 8.5) end function mod:SquirrelBomb() self:MessageOld(201240, "yellow", "info") self:CDBar(201240, 18) end function mod:RocketChicken(args) self:MessageOld(201392, "red", "alarm") self:CDBar(201392, args.spellId == 201438 and 9.7 or 18) end function mod:MillificentsRage(args) self:MessageOld(args.spellId, "cyan", "warning") self:CDBar(201240, 5) -- Overloaded Squirrel Bomb self:CDBar(201392, 13.5) -- Reinforced Rocket Chicken end
412
0.773024
1
0.773024
game-dev
MEDIA
0.968656
game-dev
0.771152
1
0.771152
RedPandaProjects/STALKERonUE
15,549
gamedata/configs/misc/outfit_upgrades/o_dolg_heavy_outfit_up.ltx
[up_sect_firsta_dolg_heavy_outfit] cost = 1000 value = -6 inv_weight = -6 power_loss = -0.1 [up_sect_firstc_dolg_heavy_outfit] cost = 2000 value = +15 immunities_sect_add = sect_dolg_heavy_outfit_immunities_add [up_sect_firstd_dolg_heavy_outfit] cost = 2000 value = +20 fire_wound_protection = 0.05 bones_koeff_protection_add = actor_armor_heavy_add_2 [up_sect_firste_dolg_heavy_outfit] cost = 3000 value = -30 hit_fraction_actor = -0.07 ;0.55 strike_protection = 0.06 ;0.40 explosion_protection = 0.06 ;0.40 wound_protection = 0.06 ;0.40 [up_sect_firstf_dolg_heavy_outfit] cost = 3000 value = +30 fire_wound_protection = 0.1 bones_koeff_protection_add = actor_armor_heavy_add_3 [up_sect_secona_dolg_heavy_outfit] cost = 1000 value = -10 hit_fraction_actor = -0.05 ;0.55 strike_protection = 0.04 ;0.40 explosion_protection = 0.04 ;0.40 wound_protection = 0.04 ;0.40 [up_sect_seconc_dolg_heavy_outfit] cost = 2000 value = +20 radiation_protection = 0.001 ;0.042 [up_sect_second_dolg_heavy_outfit] cost = 2000 value = +2 power_restore_speed = 0.002 power_loss = -0.1 [up_sect_secone_dolg_heavy_outfit] cost = 4000 value = +30 inv_weight = +0.25 chemical_burn_protection = 0.0050 ;0.042 fire_wound_protection = 0.05 bones_koeff_protection_add = actor_armor_heavy_add_3 [up_sect_thirda_dolg_heavy_outfit] cost = 1500 value = +4 bleeding_restore_speed = 0.004 [up_sect_thirdc_dolg_heavy_outfit] cost = 2000 value = +20 chemical_burn_protection = +0.0050 ;0.042 [up_sect_thirdd_dolg_heavy_outfit] cost = 2000 value = +10 additional_inventory_weight = 10 ; +max_walk_weight additional_inventory_weight2 = 10 power_loss = -0.15 [up_sect_thirde_dolg_heavy_outfit] cost = 4000 value = +3 bleeding_restore_speed = 0.003 health_restore_speed = 0.00045 [up_sect_fourta_dolg_heavy_outfit] cost = 1500 value = +2 power_restore_speed = 0.002 [up_sect_fourtc_dolg_heavy_outfit] cost = 2500 value = +4 bleeding_restore_speed = 0.004 [up_sect_fourte_dolg_heavy_outfit] cost = 4000 value = +6 health_restore_speed = 0.0009 [up_firsta_dolg_heavy_outfit] scheme_index = 0, 0 known = 1 effects = up_gr_firstcd_dolg_heavy_outfit section = up_sect_firsta_dolg_heavy_outfit property = prop_weightoutfit precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_arm_a5_name description = st_up_arm_a5_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_1 [up_firstc_dolg_heavy_outfit] scheme_index = 1, 0 known = 1 effects = up_gr_firstef_dolg_heavy_outfit section = up_sect_firstc_dolg_heavy_outfit property = prop_durability precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_arm_b5_name description = st_up_arm_b5_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_2 [up_firstd_dolg_heavy_outfit] scheme_index = 1, 1 known = 1 effects = up_gr_firstef_dolg_heavy_outfit section = up_sect_firstd_dolg_heavy_outfit property = prop_armor precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_arm_a1_name description = st_up_arm_a1_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_4 [up_firste_dolg_heavy_outfit] scheme_index = 2, 0 known = 1 effects = section = up_sect_firste_dolg_heavy_outfit property = prop_damage precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_arm_c8_name description = st_up_arm_c8_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_3 [up_firstf_dolg_heavy_outfit] scheme_index = 2, 1 known = 1 effects = section = up_sect_firstf_dolg_heavy_outfit property = prop_armor precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_arm_c9_name description = st_up_arm_c9_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_5 [up_secona_dolg_heavy_outfit] scheme_index = 0, 1 known = 1 effects = up_gr_seconcd_dolg_heavy_outfit section = up_sect_secona_dolg_heavy_outfit property = prop_damage precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_kom_a2_name description = st_up_kom_a2_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_6 [up_seconc_dolg_heavy_outfit] scheme_index = 1, 2 known = 1 effects = up_gr_seconef_dolg_heavy_outfit section = up_sect_seconc_dolg_heavy_outfit property = prop_radio precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_kom_b12_name description = st_up_kom_b12_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_7 [up_second_dolg_heavy_outfit] scheme_index = 1, 3 known = 1 effects = up_gr_seconef_dolg_heavy_outfit section = up_sect_second_dolg_heavy_outfit property = prop_power precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_kom_b10_name description = st_up_kom_b10_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_9 [up_secone_dolg_heavy_outfit] scheme_index = 2, 2 known = 1 effects = section = up_sect_secone_dolg_heavy_outfit property = prop_armor, prop_chem precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_kom_c6_name description = st_up_kom_c6_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_8 [up_thirda_dolg_heavy_outfit] scheme_index = 0, 2 known = 1 effects = up_gr_thirdcd_dolg_heavy_outfit section = up_sect_thirda_dolg_heavy_outfit property = prop_restore_bleeding precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_uti_a2_name description = st_up_uti_a2_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_10 [up_thirdc_dolg_heavy_outfit] scheme_index = 1, 4 known = 1 effects = up_gr_thirdef_dolg_heavy_outfit section = up_sect_thirdc_dolg_heavy_outfit property = prop_chem precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_uti_b8_name description = st_up_uti_b8_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_11 [up_thirdd_dolg_heavy_outfit] scheme_index = 1, 5 known = 1 effects = up_gr_thirdef_dolg_heavy_outfit section = up_sect_thirdd_dolg_heavy_outfit property = prop_tonnage precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_uti_b3_name description = st_up_uti_b3_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_13 [up_thirde_dolg_heavy_outfit] scheme_index = 2, 3 known = 1 effects = section = up_sect_thirde_dolg_heavy_outfit property = prop_restore_bleeding, prop_restore_health precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_uti_c3_name description = st_up_uti_c3_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_12 [up_fourta_dolg_heavy_outfit] scheme_index = 0, 3 known = 1 effects = up_gr_fourtcd_dolg_heavy_outfit section = up_sect_fourta_dolg_heavy_outfit property = prop_power precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_tch_a1_name description = st_up_tch_a1_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_14 [up_fourtc_dolg_heavy_outfit] scheme_index = 1, 6 known = 1 effects = up_gr_fourtef_dolg_heavy_outfit section = up_sect_fourtc_dolg_heavy_outfit property = prop_restore_bleeding precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_tch_b1_name description = st_up_tch_b1_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_15 [up_fourte_dolg_heavy_outfit] scheme_index = 2, 4 known = 1 effects = section = up_sect_fourte_dolg_heavy_outfit property = prop_restore_health precondition_functor = inventory_upgrades.precondition_functor_a precondition_parameter = a & b effect_functor = inventory_upgrades.effect_functor_a effect_parameter = something_here prereq_functor = inventory_upgrades.prereq_functor_a prereq_tooltip_functor = inventory_upgrades.prereq_tooltip_functor_a prereq_params = name = st_up_tch_c1_name description = st_up_tch_c1_descr icon = ui_inGame2_upgrade_dolg_heavy_outfit_16 [up_gr_firstab_dolg_heavy_outfit] elements = up_firsta_dolg_heavy_outfit [up_gr_firstcd_dolg_heavy_outfit] elements = up_firstc_dolg_heavy_outfit, up_firstd_dolg_heavy_outfit [up_gr_firstef_dolg_heavy_outfit] elements = up_firste_dolg_heavy_outfit, up_firstf_dolg_heavy_outfit [up_gr_seconab_dolg_heavy_outfit] elements = up_secona_dolg_heavy_outfit [up_gr_seconcd_dolg_heavy_outfit] elements = up_seconc_dolg_heavy_outfit, up_second_dolg_heavy_outfit [up_gr_seconef_dolg_heavy_outfit] elements = up_secone_dolg_heavy_outfit [up_gr_thirdab_dolg_heavy_outfit] elements = up_thirda_dolg_heavy_outfit [up_gr_thirdcd_dolg_heavy_outfit] elements = up_thirdc_dolg_heavy_outfit, up_thirdd_dolg_heavy_outfit [up_gr_thirdef_dolg_heavy_outfit] elements = up_thirde_dolg_heavy_outfit [up_gr_fourtab_dolg_heavy_outfit] elements = up_fourta_dolg_heavy_outfit [up_gr_fourtcd_dolg_heavy_outfit] elements = up_fourtc_dolg_heavy_outfit [up_gr_fourtef_dolg_heavy_outfit] elements = up_fourte_dolg_heavy_outfit
412
0.93064
1
0.93064
game-dev
MEDIA
0.981025
game-dev
0.898189
1
0.898189
mrthinger/wow-voiceover
6,967
AI_VoiceOver/Libs/AceGUI-3.0/widgets/AceGUIWidget-EditBox.lua
--[[----------------------------------------------------------------------------- EditBox Widget -------------------------------------------------------------------------------]] local Type, Version = "EditBox", 28 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local tostring, pairs = tostring, pairs -- WoW APIs local PlaySound = PlaySound local GetCursorInfo, ClearCursor, GetSpellInfo = GetCursorInfo, ClearCursor, GetSpellInfo local CreateFrame, UIParent = CreateFrame, UIParent local _G = _G --[[----------------------------------------------------------------------------- Support functions -------------------------------------------------------------------------------]] if not AceGUIEditBoxInsertLink then -- upgradeable hook hooksecurefunc("ChatEdit_InsertLink", function(...) return _G.AceGUIEditBoxInsertLink(...) end) end function _G.AceGUIEditBoxInsertLink(text) for i = 1, AceGUI:GetWidgetCount(Type) do local editbox = _G["AceGUI-3.0EditBox"..i] if editbox and editbox:IsVisible() and editbox:HasFocus() then editbox:Insert(text) return true end end end local function ShowButton(self) if not self.disablebutton then self.button:Show() self.editbox:SetTextInsets(0, 20, 3, 3) end end local function HideButton(self) self.button:Hide() self.editbox:SetTextInsets(0, 0, 3, 3) end --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function Control_OnEnter(frame) frame.obj:Fire("OnEnter") end local function Control_OnLeave(frame) frame.obj:Fire("OnLeave") end local function Frame_OnShowFocus(frame) frame.obj.editbox:SetFocus() frame:SetScript("OnShow", nil) end local function EditBox_OnEscapePressed(frame) AceGUI:ClearFocus() end local function EditBox_OnEnterPressed(frame) local self = frame.obj local value = frame:GetText() local cancel = self:Fire("OnEnterPressed", value) if not cancel then PlaySound(856) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON HideButton(self) end end local function EditBox_OnReceiveDrag(frame) local self = frame.obj local type, id, info = GetCursorInfo() local name if type == "item" then name = info elseif type == "spell" then name = GetSpellInfo(id, info) elseif type == "macro" then name = GetMacroInfo(id) end if name then self:SetText(name) self:Fire("OnEnterPressed", name) ClearCursor() HideButton(self) AceGUI:ClearFocus() end end local function EditBox_OnTextChanged(frame) local self = frame.obj local value = frame:GetText() if tostring(value) ~= tostring(self.lasttext) then self:Fire("OnTextChanged", value) self.lasttext = value ShowButton(self) end end local function EditBox_OnFocusGained(frame) AceGUI:SetFocus(frame.obj) end local function Button_OnClick(frame) local editbox = frame.obj.editbox editbox:ClearFocus() EditBox_OnEnterPressed(editbox) end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) -- height is controlled by SetLabel self:SetWidth(200) self:SetDisabled(false) self:SetLabel() self:SetText() self:DisableButton(false) self:SetMaxLetters(0) end, ["OnRelease"] = function(self) self:ClearFocus() end, ["SetDisabled"] = function(self, disabled) self.disabled = disabled if disabled then self.editbox:EnableMouse(false) self.editbox:ClearFocus() self.editbox:SetTextColor(0.5,0.5,0.5) self.label:SetTextColor(0.5,0.5,0.5) else self.editbox:EnableMouse(true) self.editbox:SetTextColor(1,1,1) self.label:SetTextColor(1,.82,0) end end, ["SetText"] = function(self, text) self.lasttext = text or "" self.editbox:SetText(text or "") self.editbox:SetCursorPosition(0) HideButton(self) end, ["GetText"] = function(self, text) return self.editbox:GetText() end, ["SetLabel"] = function(self, text) if text and text ~= "" then self.label:SetText(text) self.label:Show() self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,-18) self:SetHeight(44) self.alignoffset = 30 else self.label:SetText("") self.label:Hide() self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,0) self:SetHeight(26) self.alignoffset = 12 end end, ["DisableButton"] = function(self, disabled) self.disablebutton = disabled if disabled then HideButton(self) end end, ["SetMaxLetters"] = function (self, num) self.editbox:SetMaxLetters(num or 0) end, ["ClearFocus"] = function(self) self.editbox:ClearFocus() self.frame:SetScript("OnShow", nil) end, ["SetFocus"] = function(self) self.editbox:SetFocus() if not self.frame:IsShown() then self.frame:SetScript("OnShow", Frame_OnShowFocus) end end, ["HighlightText"] = function(self, from, to) self.editbox:HighlightText(from, to) end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local num = AceGUI:GetNextWidgetNum(Type) local frame = CreateFrame("Frame", nil, UIParent) frame:Hide() local editbox = CreateFrame("EditBox", "AceGUI-3.0EditBox"..num, frame, "InputBoxTemplate") editbox:SetAutoFocus(false) editbox:SetFontObject(ChatFontNormal) editbox:SetScript("OnEnter", Control_OnEnter) editbox:SetScript("OnLeave", Control_OnLeave) editbox:SetScript("OnEscapePressed", EditBox_OnEscapePressed) editbox:SetScript("OnEnterPressed", EditBox_OnEnterPressed) editbox:SetScript("OnTextChanged", EditBox_OnTextChanged) editbox:SetScript("OnReceiveDrag", EditBox_OnReceiveDrag) editbox:SetScript("OnMouseDown", EditBox_OnReceiveDrag) editbox:SetScript("OnEditFocusGained", EditBox_OnFocusGained) editbox:SetTextInsets(0, 0, 3, 3) editbox:SetMaxLetters(256) editbox:SetPoint("BOTTOMLEFT", 6, 0) editbox:SetPoint("BOTTOMRIGHT") editbox:SetHeight(19) local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") label:SetPoint("TOPLEFT", 0, -2) label:SetPoint("TOPRIGHT", 0, -2) label:SetJustifyH("LEFT") label:SetHeight(18) local button = CreateFrame("Button", nil, editbox, "UIPanelButtonTemplate") button:SetWidth(40) button:SetHeight(20) button:SetPoint("RIGHT", -2, 0) button:SetText(OKAY) button:SetScript("OnClick", Button_OnClick) button:Hide() local widget = { alignoffset = 30, editbox = editbox, label = label, button = button, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end editbox.obj, button.obj = widget, widget return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
412
0.913854
1
0.913854
game-dev
MEDIA
0.934921
game-dev
0.892689
1
0.892689
OxideWaveLength/Minecraft-Hack-BaseClient
1,957
minecraft/net/minecraft/client/renderer/entity/RenderCreeper.java
package net.minecraft.client.renderer.entity; import net.minecraft.client.model.ModelCreeper; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.entity.layers.LayerCreeperCharge; import net.minecraft.entity.monster.EntityCreeper; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; public class RenderCreeper extends RenderLiving<EntityCreeper> { private static final ResourceLocation creeperTextures = new ResourceLocation("textures/entity/creeper/creeper.png"); public RenderCreeper(RenderManager renderManagerIn) { super(renderManagerIn, new ModelCreeper(), 0.5F); this.addLayer(new LayerCreeperCharge(this)); } /** * Allows the render to do any OpenGL state modifications necessary before the * model is rendered. Args: entityLiving, partialTickTime */ protected void preRenderCallback(EntityCreeper entitylivingbaseIn, float partialTickTime) { float f = entitylivingbaseIn.getCreeperFlashIntensity(partialTickTime); float f1 = 1.0F + MathHelper.sin(f * 100.0F) * f * 0.01F; f = MathHelper.clamp_float(f, 0.0F, 1.0F); f = f * f; f = f * f; float f2 = (1.0F + f * 0.4F) * f1; float f3 = (1.0F + f * 0.1F) / f1; GlStateManager.scale(f2, f3, f2); } /** * Returns an ARGB int color back. Args: entityLiving, lightBrightness, * partialTickTime */ protected int getColorMultiplier(EntityCreeper entitylivingbaseIn, float lightBrightness, float partialTickTime) { float f = entitylivingbaseIn.getCreeperFlashIntensity(partialTickTime); if ((int) (f * 10.0F) % 2 == 0) { return 0; } else { int i = (int) (f * 0.2F * 255.0F); i = MathHelper.clamp_int(i, 0, 255); return i << 24 | 16777215; } } /** * Returns the location of an entity's texture. Doesn't seem to be called unless * you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityCreeper entity) { return creeperTextures; } }
412
0.852642
1
0.852642
game-dev
MEDIA
0.855774
game-dev,graphics-rendering
0.973009
1
0.973009
CrypticMonkey33/ArchipelagoExplorersOfSky
6,142
worlds/jakanddaxter/items.py
from enum import IntEnum from BaseClasses import Item, ItemClassification from .game_id import jak1_name, jak1_max from .locs import (orb_locations as orbs, cell_locations as cells, scout_locations as scouts, special_locations as specials, orb_cache_locations as caches) class OrbAssoc(IntEnum): """ Identifies an item's association to unlocking new sources of Precursor Orbs. For example, Double Jump will unlock new orbs, but Freed the Green Sage will not. Power Cells conditionally unlock new orbs if they get you across connector levels. """ NEVER_UNLOCKS_ORBS = 0 ALWAYS_UNLOCKS_ORBS = 1 IS_POWER_CELL = 2 class JakAndDaxterItem(Item): game: str = jak1_name orb_assoc: OrbAssoc orb_amount: int # Only non-zero for Orb Bundle items. def __init__(self, name: str, classification: ItemClassification, code: int | None, player: int, orb_assoc: OrbAssoc = OrbAssoc.NEVER_UNLOCKS_ORBS, orb_amount: int = 0): super().__init__(name, classification, code, player) self.orb_assoc = orb_assoc self.orb_amount = orb_amount # Power Cells are generic, fungible, interchangeable items. Every cell is indistinguishable from every other. cell_item_table = { 0: "Power Cell", } # Scout flies are interchangeable within their respective sets of 7. Notice the level name after each item. # Also, notice that their Item ID equals their respective Power Cell's Location ID. This is necessary for # game<->archipelago communication. scout_item_table = { 95: "Scout Fly - Geyser Rock", 75: "Scout Fly - Sandover Village", 7: "Scout Fly - Forbidden Jungle", 20: "Scout Fly - Sentinel Beach", 28: "Scout Fly - Misty Island", 68: "Scout Fly - Fire Canyon", 76: "Scout Fly - Rock Village", 57: "Scout Fly - Precursor Basin", 49: "Scout Fly - Lost Precursor City", 43: "Scout Fly - Boggy Swamp", 88: "Scout Fly - Mountain Pass", 77: "Scout Fly - Volcanic Crater", 85: "Scout Fly - Spider Cave", 65: "Scout Fly - Snowy Mountain", 90: "Scout Fly - Lava Tube", 91: "Scout Fly - Citadel", # Had to shorten, it was >32 characters. } # Orbs are also generic and interchangeable. # These items are only used by Orbsanity, and only one of these # items will be used corresponding to the chosen bundle size. orb_item_table = { 1: "1 Precursor Orb", 2: "2 Precursor Orbs", 4: "4 Precursor Orbs", 5: "5 Precursor Orbs", 8: "8 Precursor Orbs", 10: "10 Precursor Orbs", 16: "16 Precursor Orbs", 20: "20 Precursor Orbs", 25: "25 Precursor Orbs", 40: "40 Precursor Orbs", 50: "50 Precursor Orbs", 80: "80 Precursor Orbs", 100: "100 Precursor Orbs", 125: "125 Precursor Orbs", 200: "200 Precursor Orbs", 250: "250 Precursor Orbs", 400: "400 Precursor Orbs", 500: "500 Precursor Orbs", 1000: "1000 Precursor Orbs", 2000: "2000 Precursor Orbs", } # These are special items representing unique unlocks in the world. Notice that their Item ID equals their # respective Location ID. Like scout flies, this is necessary for game<->archipelago communication. special_item_table = { 5: "Fisherman's Boat", # Unlocks Misty Island 4: "Jungle Elevator", # Unlocks the Forbidden Jungle Temple 2: "Blue Eco Switch", # Unlocks Blue Eco Vents 17: "Flut Flut", # Unlocks Flut Flut sections in Boggy Swamp and Snowy Mountain 33: "Warrior's Pontoons", # Unlocks Boggy Swamp and everything post-Rock Village 105: "Snowy Mountain Gondola", # Unlocks Snowy Mountain 60: "Yellow Eco Switch", # Unlocks Yellow Eco Vents 63: "Snowy Fort Gate", # Unlocks the Snowy Mountain Fort 71: "Freed The Blue Sage", # 1 of 3 unlocks for the final staircase in Citadel 72: "Freed The Red Sage", # 1 of 3 unlocks for the final staircase in Citadel 73: "Freed The Yellow Sage", # 1 of 3 unlocks for the final staircase in Citadel 70: "Freed The Green Sage", # Unlocks the final boss elevator in Citadel } # These are the move items for move randomizer. Notice that their Item ID equals some of the Orb Cache Location ID's. # This was 100% arbitrary. There's no reason to tie moves to orb caches except that I need a place to put them. ;_; move_item_table = { 10344: "Crouch", 10369: "Crouch Jump", 11072: "Crouch Uppercut", 12634: "Roll", 12635: "Roll Jump", 10945: "Double Jump", 14507: "Jump Dive", 14838: "Jump Kick", 23348: "Punch", 23349: "Punch Uppercut", 23350: "Kick", # 24038: "Orb Cache at End of Blast Furnace", # Hold onto these ID's for future use. # 24039: "Orb Cache at End of Launch Pad Room", # 24040: "Orb Cache at Start of Launch Pad Room", } # These are trap items. Their Item ID is to be subtracted from the base game ID. They do not have corresponding # game locations because they are intended to replace other items that have been marked as filler. trap_item_table = { 1: "Trip Trap", 2: "Slippery Trap", 3: "Gravity Trap", 4: "Camera Trap", 5: "Darkness Trap", 6: "Earthquake Trap", 7: "Teleport Trap", 8: "Despair Trap", 9: "Pacifism Trap", 10: "Ecoless Trap", 11: "Health Trap", 12: "Ledge Trap", 13: "Zoomer Trap", 14: "Mirror Trap", } # All Items # While we're here, do all the ID conversions needed. item_table = { **{cells.to_ap_id(k): name for k, name in cell_item_table.items()}, **{scouts.to_ap_id(k): name for k, name in scout_item_table.items()}, **{specials.to_ap_id(k): name for k, name in special_item_table.items()}, **{caches.to_ap_id(k): name for k, name in move_item_table.items()}, **{orbs.to_ap_id(k): name for k, name in orb_item_table.items()}, **{jak1_max - k: name for k, name in trap_item_table.items()}, jak1_max: "Green Eco Pill" # Filler item. }
412
0.844559
1
0.844559
game-dev
MEDIA
0.964768
game-dev
0.716552
1
0.716552
ThePaperLuigi/The-Stars-Above
1,071
Items/Materials/BoltOfStarsilk.cs
using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace StarsAbove.Items.Materials { public class BoltOfStarsilk : ModItem { public override void SetStaticDefaults() { // DisplayName.SetDefault("Bolt of Starsilk"); /* Tooltip.SetDefault("Utilized to craft Starfarer Attire" + "\n'A texture akin to twinkling stars'"); */ Terraria.GameContent.Creative.CreativeItemSacrificesCatalog.Instance.SacrificeCountNeededByItemId[Type] = 1; ItemID.Sets.ItemNoGravity[Item.type] = false; } public override void SetDefaults() { Item.width = 20; Item.height = 20; Item.value = 100; Item.rare = ItemRarityID.Red; Item.maxStack = 999; } public override Color? GetAlpha(Color lightColor) { return Color.White; } public override void AddRecipes() { CreateRecipe(1) .AddIngredient(ItemID.AncientCloth, 1) .AddIngredient(ItemID.Silk, 1) .AddIngredient(ItemID.MeteoriteBar, 2) .AddIngredient(ItemID.FallenStar, 3) .AddTile(TileID.Loom) .Register(); } } }
412
0.748814
1
0.748814
game-dev
MEDIA
0.977398
game-dev
0.799851
1
0.799851
Pulsar4xDevs/Pulsar4x
6,279
Pulsar4X/GameEngine/Movement/MoveToNearestAction.cs
using System; using System.Collections.Generic; using System.Linq; using Pulsar4X.Orbital; using Pulsar4X.DataStructures; using Pulsar4X.Extensions; using Pulsar4X.Fleets; using Pulsar4X.Orbits; using Pulsar4X.Ships; using Pulsar4X.Galaxy; using Pulsar4X.Engine.Orders; using Pulsar4X.Engine; namespace Pulsar4X.Movement { public class MoveToNearestAction : EntityCommand { public override string Name => "Move to Nearest"; public override string Details => "Moves the fleet to the nearest X by filter."; public override ActionLaneTypes ActionLanes { get; } = ActionLaneTypes.IneteractWithSelf | ActionLaneTypes.InteractWithEntitySameFleet | ActionLaneTypes.Movement; public override bool IsBlocking => true; /// <summary> /// Entity commanding is a fleet in this action /// </summary> protected Entity _entityCommanding; internal override Entity EntityCommanding { get { return _entityCommanding; } } public EntityManager.FilterEntities Filter { get; protected set; } public delegate Entity EntitySelector(Entity entity); public EntitySelector? TargetSelector { get; protected set; } public EntityFilter EntityFactionFilter { get; protected set; } = EntityFilter.Friendly | EntityFilter.Neutral | EntityFilter.Hostile; private List<EntityCommand> _shipCommands = new List<EntityCommand>(); internal override bool IsFinished() { return _isFinished = ShipsFinishedWarping(); } internal override void Execute(DateTime atDateTime) { if(!IsRunning) FindNearestAndSetupWarpCommands(); } private void FindNearestAndSetupWarpCommands() { if(!EntityCommanding.TryGetDatablob<FleetDB>(out var fleetDB)) return; if(fleetDB.FlagShipID == -1) return; if(!EntityCommanding.Manager.TryGetEntityById(fleetDB.FlagShipID, out var flagship)) return; if(!flagship.TryGetDatablob<PositionDB>(out var flagshipPositionDB)) return; // Get all entites based on the filter List<Entity> filteredEntities = EntityCommanding.Manager.GetFilteredEntities( EntityFactionFilter, RequestingFactionGuid, Filter); Entity? closestValidEntity = null; double closestDistance = double.MaxValue; // Find the closest colony foreach(var entity in filteredEntities) { if(!entity.TryGetDatablob<PositionDB>(out var positionDB)) { continue; } var distance = positionDB.GetDistanceTo_m(flagshipPositionDB); if(distance < closestDistance) { closestDistance = distance; closestValidEntity = entity; } } if(closestValidEntity == null) return; var targetEntity = TargetSelector == null ? closestValidEntity : TargetSelector(closestValidEntity); if(!targetEntity.TryGetDatablob<PositionDB>(out var targetEntityPositionDB)) { return; } if(targetEntityPositionDB.Parent == null) return; double targetSMA = OrbitMath.LowOrbitRadius(targetEntityPositionDB.Parent); // Get all the ships we need to add the movement command to var ships = fleetDB.Children.Where(c => c.HasDataBlob<ShipInfoDB>()); foreach(var ship in ships) { if(!ship.HasDataBlob<WarpAbilityDB>()) continue; if(!ship.TryGetDatablob<PositionDB>(out var shipPositionDB)) continue; if(shipPositionDB.Parent == targetEntityPositionDB.OwningEntity) continue; var shipMass = ship.GetDataBlob<MassVolumeDB>().MassTotal; (Vector3 position, DateTime _) = WarpMath.GetInterceptPosition ( ship, targetEntity.GetDataBlob<OrbitDB>(), EntityCommanding.StarSysDateTime ); //var maxRangeRate = CargoTransferProcessor.GetMaxRangeRate(targetEntity, ship); // Create the movement order var cmd = WarpMoveCommand.CreateCommandEZ( ship, targetEntity, EntityCommanding.StarSysDateTime); _shipCommands.Add(cmd); ship.Manager.Game.OrderHandler.HandleOrder(cmd); } IsRunning = true; } private bool ShipsFinishedWarping() { if(!IsRunning) return false; foreach(var command in _shipCommands) { if(!command.IsFinished()) return false; } return true; } internal override bool IsValidCommand(Game game) { return true; } protected MoveToNearestAction() { } protected static T CreateCommand<T>(int factionId, Entity commandingEntity) where T : MoveToNearestAction, new() { var command = new T() { _entityCommanding = commandingEntity, UseActionLanes = true, RequestingFactionGuid = factionId, EntityCommandingGuid = commandingEntity.Id, }; return command; } public override EntityCommand Clone() { var command = new MoveToNearestAction() { _entityCommanding = this._entityCommanding, Filter = this.Filter, UseActionLanes = this.UseActionLanes, RequestingFactionGuid = this.RequestingFactionGuid, EntityCommandingGuid = this.EntityCommandingGuid, CreatedDate = this.CreatedDate, ActionOnDate = this.ActionOnDate, ActionedOnDate = this.ActionedOnDate, IsRunning = this.IsRunning, TargetSelector = this.TargetSelector }; return command; } } }
412
0.906897
1
0.906897
game-dev
MEDIA
0.952169
game-dev
0.920012
1
0.920012
space-wizards/space-station-14
1,709
Content.Client/Overlays/ShowHealthBarsSystem.cs
using Content.Shared.Inventory.Events; using Content.Shared.Overlays; using Robust.Client.Graphics; using System.Linq; using Robust.Client.Player; using Robust.Shared.Prototypes; namespace Content.Client.Overlays; /// <summary> /// Adds a health bar overlay. /// </summary> public sealed class ShowHealthBarsSystem : EquipmentHudSystem<ShowHealthBarsComponent> { [Dependency] private readonly IOverlayManager _overlayMan = default!; [Dependency] private readonly IPrototypeManager _prototype = default!; private EntityHealthBarOverlay _overlay = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<ShowHealthBarsComponent, AfterAutoHandleStateEvent>(OnHandleState); _overlay = new(EntityManager, _prototype); } private void OnHandleState(Entity<ShowHealthBarsComponent> ent, ref AfterAutoHandleStateEvent args) { RefreshOverlay(); } protected override void UpdateInternal(RefreshEquipmentHudEvent<ShowHealthBarsComponent> component) { base.UpdateInternal(component); foreach (var comp in component.Components) { foreach (var damageContainerId in comp.DamageContainers) { _overlay.DamageContainers.Add(damageContainerId); } _overlay.StatusIcon = comp.HealthStatusIcon; } if (!_overlayMan.HasOverlay<EntityHealthBarOverlay>()) { _overlayMan.AddOverlay(_overlay); } } protected override void DeactivateInternal() { base.DeactivateInternal(); _overlay.DamageContainers.Clear(); _overlayMan.RemoveOverlay(_overlay); } }
412
0.897711
1
0.897711
game-dev
MEDIA
0.534798
game-dev
0.846528
1
0.846528
CloudburstMC/Nukkit
7,631
src/main/java/cn/nukkit/level/format/anvil/Anvil.java
package cn.nukkit.level.format.anvil; import cn.nukkit.Server; import cn.nukkit.level.Level; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.format.generic.BaseFullChunk; import cn.nukkit.level.format.generic.BaseLevelProvider; import cn.nukkit.level.format.generic.BaseRegionLoader; import cn.nukkit.level.generator.Generator; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.utils.ChunkException; import it.unimi.dsi.fastutil.objects.ObjectIterator; import java.io.File; import java.io.IOException; import java.nio.ByteOrder; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; /** * @author MagicDroidX * Nukkit Project */ public class Anvil extends BaseLevelProvider { public Anvil(Level level, String path) throws IOException { super(level, path); } @SuppressWarnings("unused") public static String getProviderName() { return "anvil"; } @SuppressWarnings("unused") public static boolean usesChunkSection() { return true; } public static boolean isValid(String path) { boolean isValid = (new File(path + "/level.dat").exists()) && new File(path + "/region/").isDirectory(); if (isValid) { for (File file : new File(path + "/region/").listFiles((dir, name) -> Pattern.matches("^.+\\.mc[r|a]$", name))) { if (!file.getName().endsWith(".mca")) { isValid = false; break; } } } return isValid; } public static void generate(String path, String name, long seed, Class<? extends Generator> generator) throws IOException { generate(path, name, seed, generator, new HashMap<>()); } public static void generate(String path, String name, long seed, Class<? extends Generator> generator, Map<String, String> options) throws IOException { if (!new File(path + "/region").exists()) { new File(path + "/region").mkdirs(); } CompoundTag levelData = new CompoundTag("Data") .putCompound("GameRules", new CompoundTag()) .putLong("DayTime", 0) .putInt("GameType", 0) .putString("generatorName", Generator.getGeneratorName(generator)) .putString("generatorOptions", options.getOrDefault("preset", "")) .putInt("generatorVersion", 1) .putBoolean("hardcore", false) .putBoolean("initialized", true) .putLong("LastPlayed", System.currentTimeMillis() / 1000) .putString("LevelName", name) .putBoolean("raining", false) .putInt("rainTime", 0) .putLong("RandomSeed", seed) .putInt("SpawnX", 128) .putInt("SpawnY", 70) .putInt("SpawnZ", 128) .putBoolean("thundering", false) .putInt("thunderTime", 0) .putInt("version", 19133) .putLong("Time", 0) .putLong("SizeOnDisk", 0); NBTIO.writeGZIPCompressed(new CompoundTag().putCompound("Data", levelData), Files.newOutputStream(Paths.get(path + "level.dat")), ByteOrder.BIG_ENDIAN); } @Override public Chunk getEmptyChunk(int chunkX, int chunkZ) { return Chunk.getEmptyChunk(chunkX, chunkZ, this); } @Override public void requestChunkTask(int x, int z) throws ChunkException { Chunk chunk = (Chunk) this.getChunk(x, z, false); if (chunk == null) { throw new ChunkException("Invalid chunk set (" + x + ", " + z + ')'); } long timestamp = chunk.getChanges(); level.asyncChunk(chunk.cloneForChunkSending(), timestamp, x, z); } private int lastPosition = 0; @Override public void doGarbageCollection(long time) { long start = System.currentTimeMillis(); int maxIterations = size(); if (lastPosition > maxIterations) lastPosition = 0; int i; synchronized (chunks) { ObjectIterator<BaseFullChunk> iter = chunks.values().iterator(); if (lastPosition != 0) iter.skip(lastPosition); for (i = 0; i < maxIterations; i++) { if (!iter.hasNext()) { iter = chunks.values().iterator(); } if (!iter.hasNext()) break; BaseFullChunk chunk = iter.next(); if (chunk == null) continue; if (chunk.isGenerated() && chunk.isPopulated() && chunk instanceof Chunk) { chunk.compress(); if (System.currentTimeMillis() - start >= time) break; } } } lastPosition += i; } @Override public synchronized BaseFullChunk loadChunk(long index, int chunkX, int chunkZ, boolean create) { int regionX = getRegionIndexX(chunkX); int regionZ = getRegionIndexZ(chunkZ); BaseRegionLoader region = this.loadRegion(regionX, regionZ); BaseFullChunk chunk = null; try { // Note: We don't want to ignore corrupted regions here as those would eventually cause problems when chunks are saved chunk = region.readChunk(chunkX - (regionX << 5), chunkZ - (regionZ << 5)); } catch (IOException ex) { Server.getInstance().getLogger().error("Failed to read chunk " + chunkX + ", " + chunkZ, ex); } if (chunk == null) { if (create) { chunk = this.getEmptyChunk(chunkX, chunkZ); putChunk(index, chunk); } } else { putChunk(index, chunk); } return chunk; } @Override public synchronized void saveChunk(int X, int Z) { BaseFullChunk chunk = this.getChunk(X, Z); if (chunk != null) { try { this.loadRegion(X >> 5, Z >> 5).writeChunk(chunk); } catch (Exception e) { throw new ChunkException("Error saving chunk (" + X + ", " + Z + ')', e); } } } @Override public synchronized void saveChunk(int x, int z, FullChunk chunk) { if (!(chunk instanceof Chunk)) { throw new ChunkException("Invalid chunk class (" + x + ", " + z + ')'); } int regionX = x >> 5; int regionZ = z >> 5; this.loadRegion(regionX, regionZ); chunk.setX(x); chunk.setZ(z); try { this.getRegion(regionX, regionZ).writeChunk(chunk); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("unused") public static ChunkSection createChunkSection(int y) { return new ChunkSection(y); } protected synchronized BaseRegionLoader loadRegion(int x, int z) { BaseRegionLoader tmp = lastRegion.get(); if (tmp != null && x == tmp.getX() && z == tmp.getZ()) { return tmp; } long index = Level.chunkHash(x, z); synchronized (regions) { BaseRegionLoader region = this.regions.get(index); if (region == null) { try { region = new RegionLoader(this, x, z); } catch (IOException e) { throw new RuntimeException(e); } this.regions.put(index, region); } lastRegion.set(region); return region; } } }
412
0.934735
1
0.934735
game-dev
MEDIA
0.930088
game-dev
0.956277
1
0.956277
isledecomp/isle
17,340
LEGO1/lego/legoomni/src/common/legoplantmanager.cpp
#include "legoplantmanager.h" #include "3dmanager/lego3dmanager.h" #include "legocharactermanager.h" #include "legoentity.h" #include "legoplants.h" #include "legovideomanager.h" #include "legoworld.h" #include "misc.h" #include "misc/legostorage.h" #include "mxdebug.h" #include "mxmisc.h" #include "mxticklemanager.h" #include "mxtimer.h" #include "scripts.h" #include "sndanim_actions.h" #include "viewmanager/viewmanager.h" #include <stdio.h> #include <vec.h> DECOMP_SIZE_ASSERT(LegoPlantManager, 0x2c) DECOMP_SIZE_ASSERT(LegoPlantManager::AnimEntry, 0x0c) // GLOBAL: LEGO1 0x100f1660 const char* g_plantLodNames[4][5] = { {"flwrwht", "flwrblk", "flwryel", "flwrred", "flwrgrn"}, {"treewht", "treeblk", "treeyel", "treered", "tree"}, {"bushwht", "bushblk", "bushyel", "bushred", "bush"}, {"palmwht", "palmblk", "palmyel", "palmred", "palm"} }; // GLOBAL: LEGO1 0x100f16b0 float g_heightPerCount[] = {0.1f, 0.7f, 0.5f, 0.9f}; // GLOBAL: LEGO1 0x100f16c0 MxU8 g_counters[] = {1, 2, 2, 3}; // GLOBAL: LEGO1 0x100f315c MxU32 LegoPlantManager::g_maxSound = 8; // GLOBAL: LEGO1 0x100f3160 MxU32 g_plantSoundIdOffset = 56; // GLOBAL: LEGO1 0x100f3164 MxU32 g_plantSoundIdMoodOffset = 66; // GLOBAL: LEGO1 0x100f3168 MxS32 LegoPlantManager::g_maxMove[4] = {3, 3, 3, 3}; // GLOBAL: LEGO1 0x100f3178 MxU32 g_plantAnimationId[4] = {30, 33, 36, 39}; // GLOBAL: LEGO1 0x100f3188 // GLOBAL: BETA10 0x101f4e70 char* LegoPlantManager::g_customizeAnimFile = NULL; // GLOBAL: LEGO1 0x10103180 // GLOBAL: BETA10 0x1020f4c0 LegoPlantInfo g_plantInfo[81]; // FUNCTION: LEGO1 0x10026220 // FUNCTION: BETA10 0x100c4f90 LegoPlantManager::LegoPlantManager() { // Note that Init() is inlined in BETA10 and the class did not inherit from MxCore, // so the BETA10 match is much better on Init(). Init(); } // FUNCTION: LEGO1 0x100262c0 // FUNCTION: BETA10 0x100c5002 LegoPlantManager::~LegoPlantManager() { delete[] g_customizeAnimFile; } // // FUNCTION: BETA10 0x100c4f90 -- see the constructor // FUNCTION: LEGO1 0x10026330 void LegoPlantManager::Init() { for (MxS32 i = 0; i < sizeOfArray(g_plantInfo); i++) { g_plantInfo[i] = g_plantInfoInit[i]; } m_worldId = LegoOmni::e_undefined; m_boundariesDetermined = FALSE; m_numEntries = 0; } // FUNCTION: LEGO1 0x10026360 // FUNCTION: BETA10 0x100c5032 void LegoPlantManager::LoadWorldInfo(LegoOmni::World p_worldId) { m_worldId = p_worldId; LegoWorld* world = CurrentWorld(); for (MxS32 i = 0; i < sizeOfArray(g_plantInfo); i++) { CreatePlant(i, world, p_worldId); } m_boundariesDetermined = FALSE; } // FUNCTION: LEGO1 0x100263a0 // FUNCTION: BETA10 0x100c5093 void LegoPlantManager::Reset(LegoOmni::World p_worldId) { MxU32 i; DeleteObjects(g_sndAnimScript, SndanimScript::c_AnimC1, SndanimScript::c_AnimBld18); for (i = 0; i < m_numEntries; i++) { delete m_entries[i]; } m_numEntries = 0; for (i = 0; i < sizeOfArray(g_plantInfo); i++) { RemovePlant(i, p_worldId); } m_worldId = LegoOmni::e_undefined; m_boundariesDetermined = FALSE; } // FUNCTION: LEGO1 0x10026410 // FUNCTION: BETA10 0x100c50e9 MxResult LegoPlantManager::DetermineBoundaries() { // similar to LegoBuildingManager::FUN_10030630() LegoWorld* world = CurrentWorld(); if (world == NULL) { return FAILURE; } for (MxS32 i = 0; i < sizeOfArray(g_plantInfo); i++) { if (g_plantInfo[i].m_entity != NULL && g_plantInfo[i].m_name != NULL) { g_plantInfo[i].m_boundary = world->FindPathBoundary(g_plantInfo[i].m_name); if (g_plantInfo[i].m_boundary != NULL) { Mx3DPointFloat position(g_plantInfo[i].m_x, g_plantInfo[i].m_y, g_plantInfo[i].m_z); LegoPathBoundary* boundary = g_plantInfo[i].m_boundary; for (MxS32 j = 0; j < boundary->GetNumEdges(); j++) { Mx4DPointFloat* normal = boundary->GetEdgeNormal(j); if (position.Dot(*normal, position) + (*normal).index_operator(3) < -0.001) { MxTrace( "Plant %d shot location (%g, %g, %g) is not in boundary %s.\n", i, position[0], position[1], position[2], boundary->GetName() ); g_plantInfo[i].m_boundary = NULL; break; } } if (g_plantInfo[i].m_boundary != NULL) { Mx4DPointFloat& unk0x14 = *g_plantInfo[i].m_boundary->GetUp(); if (position.Dot(position, unk0x14) + unk0x14.index_operator(3) > 0.001 || position.Dot(position, unk0x14) + unk0x14.index_operator(3) < -0.001) { g_plantInfo[i].m_y = -((position[0] * unk0x14.index_operator(0) + unk0x14.index_operator(3) + position[2] * unk0x14.index_operator(2)) / unk0x14.index_operator(1)); MxTrace( "Plant %d shot location (%g, %g, %g) is not on plane of boundary %s...adjusting to (%g, " "%g, " "%g)\n", i, position[0], position[1], position[2], g_plantInfo[i].m_boundary->GetName(), position[0], g_plantInfo[i].m_y, position[2] ); } } } else { MxTrace("Plant %d is in boundary %s that does not exist.\n", i, g_plantInfo[i].m_name); } } } m_boundariesDetermined = TRUE; return SUCCESS; } // FUNCTION: LEGO1 0x10026570 // FUNCTION: BETA10 0x100c55e0 LegoPlantInfo* LegoPlantManager::GetInfoArray(MxS32& p_length) { if (!m_boundariesDetermined) { DetermineBoundaries(); } p_length = sizeOfArray(g_plantInfo); return g_plantInfo; } // FUNCTION: LEGO1 0x10026590 // FUNCTION: BETA10 0x100c561e LegoEntity* LegoPlantManager::CreatePlant(MxS32 p_index, LegoWorld* p_world, LegoOmni::World p_worldId) { LegoEntity* entity = NULL; if (p_index < sizeOfArray(g_plantInfo)) { MxU32 world = 1 << (MxU8) p_worldId; if (g_plantInfo[p_index].m_worlds & world && g_plantInfo[p_index].m_counter != 0) { if (g_plantInfo[p_index].m_entity == NULL) { char name[256]; char lodName[256]; sprintf(name, "plant%d", p_index); sprintf(lodName, "%s", g_plantLodNames[g_plantInfo[p_index].m_variant][g_plantInfo[p_index].m_color]); LegoROI* roi = CharacterManager()->CreateAutoROI(name, lodName, TRUE); roi->SetVisibility(TRUE); entity = roi->GetEntity(); entity->SetLocation( g_plantInfo[p_index].m_position, g_plantInfo[p_index].m_direction, g_plantInfo[p_index].m_up, FALSE ); entity->SetType(LegoEntity::e_plant); g_plantInfo[p_index].m_entity = entity; } else { entity = g_plantInfo[p_index].m_entity; } } } return entity; } // FUNCTION: LEGO1 0x100266c0 // FUNCTION: BETA10 0x100c5859 void LegoPlantManager::RemovePlant(MxS32 p_index, LegoOmni::World p_worldId) { if (p_index < sizeOfArray(g_plantInfo)) { MxU32 world = 1 << (MxU8) p_worldId; if (g_plantInfo[p_index].m_worlds & world && g_plantInfo[p_index].m_entity != NULL) { CharacterManager()->ReleaseAutoROI(g_plantInfo[p_index].m_entity->GetROI()); g_plantInfo[p_index].m_entity = NULL; } } } // FUNCTION: LEGO1 0x10026720 // FUNCTION: BETA10 0x100c5918 MxResult LegoPlantManager::Write(LegoStorage* p_storage) { MxResult result = FAILURE; for (MxS32 i = 0; i < sizeOfArray(g_plantInfo); i++) { LegoPlantInfo* info = &g_plantInfo[i]; if (p_storage->Write(&info->m_variant, sizeof(info->m_variant)) != SUCCESS) { goto done; } if (p_storage->Write(&info->m_sound, sizeof(info->m_sound)) != SUCCESS) { goto done; } if (p_storage->Write(&info->m_move, sizeof(info->m_move)) != SUCCESS) { goto done; } if (p_storage->Write(&info->m_mood, sizeof(info->m_mood)) != SUCCESS) { goto done; } if (p_storage->Write(&info->m_color, sizeof(info->m_color)) != SUCCESS) { goto done; } if (p_storage->Write(&info->m_initialCounter, sizeof(info->m_initialCounter)) != SUCCESS) { goto done; } } result = SUCCESS; done: return result; } // FUNCTION: LEGO1 0x100267b0 // FUNCTION: BETA10 0x100c5a76 MxResult LegoPlantManager::Read(LegoStorage* p_storage) { MxResult result = FAILURE; for (MxS32 i = 0; i < sizeOfArray(g_plantInfo); i++) { LegoPlantInfo* info = &g_plantInfo[i]; if (p_storage->Read(&info->m_variant, sizeof(MxU8)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_sound, sizeof(MxU32)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_move, sizeof(MxU32)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_mood, sizeof(MxU8)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_color, sizeof(MxU8)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_counter, sizeof(MxS8)) != SUCCESS) { goto done; } info->m_initialCounter = info->m_counter; AdjustHeight(i); } result = SUCCESS; done: return result; } // FUNCTION: LEGO1 0x10026860 // FUNCTION: BETA10 0x100c5be0 void LegoPlantManager::AdjustHeight(MxS32 p_index) { MxU8 variant = g_plantInfo[p_index].m_variant; if (g_plantInfo[p_index].m_counter >= 0) { float value = g_counters[variant] - g_plantInfo[p_index].m_counter; g_plantInfo[p_index].m_position[1] = g_plantInfoInit[p_index].m_position[1] - value * g_heightPerCount[variant]; } else { g_plantInfo[p_index].m_position[1] = g_plantInfoInit[p_index].m_position[1]; } } // FUNCTION: LEGO1 0x100268d0 // FUNCTION: BETA10 0x100c5c7a MxS32 LegoPlantManager::GetNumPlants() { return sizeOfArray(g_plantInfo); } // FUNCTION: LEGO1 0x100268e0 // FUNCTION: BETA10 0x100c5c95 LegoPlantInfo* LegoPlantManager::GetInfo(LegoEntity* p_entity) { MxS32 i; for (i = 0; i < sizeOfArray(g_plantInfo); i++) { if (g_plantInfo[i].m_entity == p_entity) { break; } } if (i < sizeOfArray(g_plantInfo)) { return &g_plantInfo[i]; } return NULL; } // FUNCTION: LEGO1 0x10026920 // FUNCTION: BETA10 0x100c5dc9 MxBool LegoPlantManager::SwitchColor(LegoEntity* p_entity) { LegoPlantInfo* info = GetInfo(p_entity); if (info == NULL) { return FALSE; } LegoROI* roi = p_entity->GetROI(); info->m_color++; if (info->m_color > LegoPlantInfo::e_green) { info->m_color = LegoPlantInfo::e_white; } ViewLODList* lodList = GetViewLODListManager()->Lookup(g_plantLodNames[info->m_variant][info->m_color]); if (roi->GetLodLevel() >= 0) { VideoManager()->Get3DManager()->GetLego3DView()->GetViewManager()->RemoveROIDetailFromScene(roi); } roi->SetLODList(lodList); lodList->Release(); CharacterManager()->UpdateBoundingSphereAndBox(roi); return TRUE; } // FUNCTION: LEGO1 0x100269e0 // FUNCTION: BETA10 0x100c5ee2 MxBool LegoPlantManager::SwitchVariant(LegoEntity* p_entity) { LegoPlantInfo* info = GetInfo(p_entity); if (info == NULL || info->m_counter != -1) { return FALSE; } LegoROI* roi = p_entity->GetROI(); info->m_variant++; if (info->m_variant > LegoPlantInfo::e_palm) { info->m_variant = LegoPlantInfo::e_flower; } ViewLODList* lodList = GetViewLODListManager()->Lookup(g_plantLodNames[info->m_variant][info->m_color]); if (roi->GetLodLevel() >= 0) { VideoManager()->Get3DManager()->GetLego3DView()->GetViewManager()->RemoveROIDetailFromScene(roi); } roi->SetLODList(lodList); lodList->Release(); CharacterManager()->UpdateBoundingSphereAndBox(roi); if (info->m_move != 0 && info->m_move >= g_maxMove[info->m_variant]) { info->m_move = g_maxMove[info->m_variant] - 1; } return TRUE; } // FUNCTION: LEGO1 0x10026ad0 // FUNCTION: BETA10 0x100c6049 MxBool LegoPlantManager::SwitchSound(LegoEntity* p_entity) { MxBool result = FALSE; LegoPlantInfo* info = GetInfo(p_entity); if (info != NULL) { info->m_sound++; if (info->m_sound >= g_maxSound) { info->m_sound = 0; } result = TRUE; } return result; } // FUNCTION: LEGO1 0x10026b00 // FUNCTION: BETA10 0x100c60a7 MxBool LegoPlantManager::SwitchMove(LegoEntity* p_entity) { MxBool result = FALSE; LegoPlantInfo* info = GetInfo(p_entity); if (info != NULL) { info->m_move++; if (info->m_move >= g_maxMove[info->m_variant]) { info->m_move = 0; } result = TRUE; } return result; } // FUNCTION: LEGO1 0x10026b40 // FUNCTION: BETA10 0x100c610e MxBool LegoPlantManager::SwitchMood(LegoEntity* p_entity) { MxBool result = FALSE; LegoPlantInfo* info = GetInfo(p_entity); if (info != NULL) { info->m_mood++; if (info->m_mood > 3) { info->m_mood = 0; } result = TRUE; } return result; } // FUNCTION: LEGO1 0x10026b70 // FUNCTION: BETA10 0x100c6168 MxU32 LegoPlantManager::GetAnimationId(LegoEntity* p_entity) { LegoPlantInfo* info = GetInfo(p_entity); if (info != NULL) { return g_plantAnimationId[info->m_variant] + info->m_move; } return 0; } // FUNCTION: LEGO1 0x10026ba0 // FUNCTION: BETA10 0x100c61ba MxU32 LegoPlantManager::GetSoundId(LegoEntity* p_entity, MxBool p_basedOnMood) { LegoPlantInfo* info = GetInfo(p_entity); if (p_basedOnMood) { return (info->m_mood & 1) + g_plantSoundIdMoodOffset; } if (info != NULL) { return info->m_sound + g_plantSoundIdOffset; } return 0; } // FUNCTION: LEGO1 0x10026be0 // FUNCTION: BETA10 0x100c62bc void LegoPlantManager::SetCustomizeAnimFile(const char* p_value) { if (g_customizeAnimFile != NULL) { delete[] g_customizeAnimFile; } if (p_value != NULL) { g_customizeAnimFile = new char[strlen(p_value) + 1]; if (g_customizeAnimFile != NULL) { strcpy(g_customizeAnimFile, p_value); } } else { g_customizeAnimFile = NULL; } } // FUNCTION: LEGO1 0x10026c50 // FUNCTION: BETA10 0x100c6349 MxBool LegoPlantManager::DecrementCounter(LegoEntity* p_entity) { LegoPlantInfo* info = GetInfo(p_entity); if (info == NULL) { return FALSE; } return DecrementCounter(info - g_plantInfo); } // FUNCTION: LEGO1 0x10026c80 // FUNCTION: BETA10 0x100c63eb MxBool LegoPlantManager::DecrementCounter(MxS32 p_index) { if (p_index >= sizeOfArray(g_plantInfo)) { return FALSE; } LegoPlantInfo* info = &g_plantInfo[p_index]; if (info == NULL) { return FALSE; } MxBool result = TRUE; if (info->m_counter < 0) { info->m_counter = g_counters[info->m_variant]; } if (info->m_counter > 0) { LegoROI* roi = info->m_entity->GetROI(); info->m_counter--; if (info->m_counter == 1) { info->m_counter = 0; } if (info->m_counter == 0) { roi->SetVisibility(FALSE); } else { AdjustHeight(info - g_plantInfo); info->m_entity->SetLocation(info->m_position, info->m_direction, info->m_up, FALSE); } } else { result = FALSE; } return result; } // FUNCTION: LEGO1 0x10026d70 void LegoPlantManager::ScheduleAnimation(LegoEntity* p_entity, MxLong p_length) { m_world = CurrentWorld(); if (m_numEntries == 0) { TickleManager()->RegisterClient(this, 50); } AnimEntry* entry = m_entries[m_numEntries] = new AnimEntry; m_numEntries++; entry->m_entity = p_entity; entry->m_roi = p_entity->GetROI(); MxLong time = Timer()->GetTime(); time += p_length; entry->m_time = time + 1000; AdjustCounter(p_entity, -1); } // FUNCTION: LEGO1 0x10026e00 MxResult LegoPlantManager::Tickle() { MxLong time = Timer()->GetTime(); if (m_numEntries != 0) { for (MxS32 i = 0; i < m_numEntries; i++) { AnimEntry** ppEntry = &m_entries[i]; AnimEntry* entry = *ppEntry; if (m_world != CurrentWorld() || !entry->m_entity) { delete entry; m_numEntries--; if (m_numEntries != i) { m_entries[i] = m_entries[m_numEntries]; m_entries[m_numEntries] = NULL; } break; } if (entry->m_time - time > 1000) { break; } MxMatrix local90; MxMatrix local48; MxMatrix locald8(entry->m_roi->GetLocal2World()); Mx3DPointFloat localec(locald8[3]); ZEROVEC3(locald8[3]); locald8[1][0] = sin(((entry->m_time - time) * 2) * 0.0062832f) * 0.2; locald8[1][2] = sin(((entry->m_time - time) * 4) * 0.0062832f) * 0.2; locald8.Scale(1.03f, 0.95f, 1.03f); SET3(locald8[3], localec); entry->m_roi->SetLocal2World(locald8); entry->m_roi->WrappedUpdateWorldData(); if (entry->m_time < time) { LegoPlantInfo* info = GetInfo(entry->m_entity); if (info->m_counter == 0) { entry->m_roi->SetVisibility(FALSE); } else { AdjustHeight(info - g_plantInfo); info->m_entity->SetLocation(info->m_position, info->m_direction, info->m_up, FALSE); } delete entry; m_numEntries--; if (m_numEntries != i) { i--; *ppEntry = m_entries[m_numEntries]; m_entries[m_numEntries] = NULL; } } } } else { TickleManager()->UnregisterClient(this); } return SUCCESS; } // FUNCTION: LEGO1 0x10027120 void LegoPlantManager::ClearCounters() { LegoWorld* world = CurrentWorld(); for (MxS32 i = 0; i < sizeOfArray(g_plantInfo); i++) { g_plantInfo[i].m_counter = -1; g_plantInfo[i].m_initialCounter = -1; AdjustHeight(i); if (g_plantInfo[i].m_entity != NULL) { g_plantInfo[i].m_entity->SetLocation( g_plantInfo[i].m_position, g_plantInfo[i].m_direction, g_plantInfo[i].m_up, FALSE ); } } } // FUNCTION: LEGO1 0x100271b0 void LegoPlantManager::AdjustCounter(LegoEntity* p_entity, MxS32 p_adjust) { LegoPlantInfo* info = GetInfo(p_entity); if (info != NULL) { if (info->m_counter < 0) { info->m_counter = g_counters[info->m_variant]; } if (info->m_counter > 0) { info->m_counter += p_adjust; if (info->m_counter <= 1 && p_adjust < 0) { info->m_counter = 0; } } } } // FUNCTION: LEGO1 0x10027200 void LegoPlantManager::SetInitialCounters() { for (MxU32 i = 0; i < sizeOfArray(g_plantInfo); i++) { g_plantInfo[i].m_initialCounter = g_plantInfo[i].m_counter; } }
412
0.795751
1
0.795751
game-dev
MEDIA
0.512784
game-dev,desktop-app
0.710159
1
0.710159
ixray-team/ixray-1.6-stcop
2,734
src/3rd-party/MagicSoftware/FreeMagic/Include/MgcCommand.h
// Magic Software, Inc. // http://www.magic-software.com // Copyright (c) 2000-2002. All Rights Reserved // // Source code from Magic Software is supplied under the terms of a license // agreement and may not be copied or disclosed except in accordance with the // terms of that agreement. The various license agreements may be found at // the Magic Software web site. This file is subject to the license // // FREE SOURCE CODE // http://www.magic-software.com/License/free.pdf #ifndef MGCCOMMAND_H #define MGCCOMMAND_H #include "MagicFMLibType.h" namespace Mgc { class MAGICFM Command { public: Command (int iQuantity, char** apcArgument); Command (char* acCmdline); ~Command (); // return value is index of first excess argument int ExcessArguments (); // Set bounds for numerical arguments. If bounds are required, they must // be set for each argument. Command& Min (double dValue); Command& Max (double dValue); Command& Inf (double dValue); Command& Sup (double dValue); // The return value of the following methods is the option index within // the argument array. // Use the boolean methods for options which take no argument, for // example in // myprogram -debug -x 10 -y 20 filename // the option -debug has no argument. int Boolean (char* acName); // returns existence of option int Boolean (char* acName, bool& rbValue); int Integer (char* acName, int& riValue); int Float (char* acName, float& rfValue); int Double (char* acName, double& rdValue); int String (char* acName, char*& racValue); int Filename (char*& racName); // last error reporting const char* GetLastError (); protected: // constructor support void Initialize (); // command line information int m_iQuantity; // number of arguments char** m_apcArgument; // argument list (array of strings) char* m_acCmdline; // argument list (single string) bool* m_abUsed; // keeps track of arguments already processed // parameters for bounds checking double m_dSmall; // lower bound for numerical argument (min or inf) double m_dLarge; // upper bound for numerical argument (max or sup) bool m_bMinSet; // if true, compare: small <= arg bool m_bMaxSet; // if true, compare: arg <= large bool m_bInfSet; // if true, compare: small < arg bool m_bSupSet; // if true, compare: arg < large // last error strings const char* m_acLastError; static char ms_acOptionNotFound[]; static char ms_acArgumentRequired[]; static char ms_acArgumentOutOfRange[]; static char ms_acFilenameNotFound[]; }; } // namespace Mgc #endif
412
0.640929
1
0.640929
game-dev
MEDIA
0.442492
game-dev
0.599191
1
0.599191
Nextpeer/Nextpeer-UFORUN
6,316
cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeShapes.h
/* * Copyright (c) 2006-2010 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef EDGE_SHAPES_H #define EDGE_SHAPES_H class EdgeShapesCallback : public b2RayCastCallback { public: EdgeShapesCallback() { m_fixture = NULL; } float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction) { m_fixture = fixture; m_point = point; m_normal = normal; return fraction; } b2Fixture* m_fixture; b2Vec2 m_point; b2Vec2 m_normal; }; class EdgeShapes : public Test { public: enum { e_maxBodies = 256 }; EdgeShapes() { // Ground body { b2BodyDef bd; b2Body* ground = m_world->CreateBody(&bd); float32 x1 = -20.0f; float32 y1 = 2.0f * cosf(x1 / 10.0f * b2_pi); for (int32 i = 0; i < 80; ++i) { float32 x2 = x1 + 0.5f; float32 y2 = 2.0f * cosf(x2 / 10.0f * b2_pi); b2EdgeShape shape; shape.Set(b2Vec2(x1, y1), b2Vec2(x2, y2)); ground->CreateFixture(&shape, 0.0f); x1 = x2; y1 = y2; } } { b2Vec2 vertices[3]; vertices[0].Set(-0.5f, 0.0f); vertices[1].Set(0.5f, 0.0f); vertices[2].Set(0.0f, 1.5f); m_polygons[0].Set(vertices, 3); } { b2Vec2 vertices[3]; vertices[0].Set(-0.1f, 0.0f); vertices[1].Set(0.1f, 0.0f); vertices[2].Set(0.0f, 1.5f); m_polygons[1].Set(vertices, 3); } { float32 w = 1.0f; float32 b = w / (2.0f + b2Sqrt(2.0f)); float32 s = b2Sqrt(2.0f) * b; b2Vec2 vertices[8]; vertices[0].Set(0.5f * s, 0.0f); vertices[1].Set(0.5f * w, b); vertices[2].Set(0.5f * w, b + s); vertices[3].Set(0.5f * s, w); vertices[4].Set(-0.5f * s, w); vertices[5].Set(-0.5f * w, b + s); vertices[6].Set(-0.5f * w, b); vertices[7].Set(-0.5f * s, 0.0f); m_polygons[2].Set(vertices, 8); } { m_polygons[3].SetAsBox(0.5f, 0.5f); } { m_circle.m_radius = 0.5f; } m_bodyIndex = 0; memset(m_bodies, 0, sizeof(m_bodies)); m_angle = 0.0f; } void Create(int32 index) { if (m_bodies[m_bodyIndex] != NULL) { m_world->DestroyBody(m_bodies[m_bodyIndex]); m_bodies[m_bodyIndex] = NULL; } b2BodyDef bd; float32 x = RandomFloat(-10.0f, 10.0f); float32 y = RandomFloat(10.0f, 20.0f); bd.position.Set(x, y); bd.angle = RandomFloat(-b2_pi, b2_pi); bd.type = b2_dynamicBody; if (index == 4) { bd.angularDamping = 0.02f; } m_bodies[m_bodyIndex] = m_world->CreateBody(&bd); if (index < 4) { b2FixtureDef fd; fd.shape = m_polygons + index; fd.friction = 0.3f; fd.density = 20.0f; m_bodies[m_bodyIndex]->CreateFixture(&fd); } else { b2FixtureDef fd; fd.shape = &m_circle; fd.friction = 0.3f; fd.density = 20.0f; m_bodies[m_bodyIndex]->CreateFixture(&fd); } m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; } void DestroyBody() { for (int32 i = 0; i < e_maxBodies; ++i) { if (m_bodies[i] != NULL) { m_world->DestroyBody(m_bodies[i]); m_bodies[i] = NULL; return; } } } void Keyboard(unsigned char key) { switch (key) { case '1': case '2': case '3': case '4': case '5': Create(key - '1'); break; case 'd': DestroyBody(); break; } } void Step(Settings* settings) { bool advanceRay = settings->pause == 0 || settings->singleStep; Test::Step(settings); m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stuff"); m_textLine += 15; float32 L = 25.0f; b2Vec2 point1(0.0f, 10.0f); b2Vec2 d(L * cosf(m_angle), -L * b2Abs(sinf(m_angle))); b2Vec2 point2 = point1 + d; EdgeShapesCallback callback; m_world->RayCast(&callback, point1, point2); if (callback.m_fixture) { m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f)); m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f)); b2Vec2 head = callback.m_point + 0.5f * callback.m_normal; m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f)); } else { m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f)); } if (advanceRay) { m_angle += 0.25f * b2_pi / 180.0f; } } static Test* Create() { return new EdgeShapes; } int32 m_bodyIndex; b2Body* m_bodies[e_maxBodies]; b2PolygonShape m_polygons[4]; b2CircleShape m_circle; float32 m_angle; }; #endif
412
0.968815
1
0.968815
game-dev
MEDIA
0.84108
game-dev
0.941473
1
0.941473
CobbleSword/NachoSpigot
4,126
NachoSpigot-API/src/main/java/org/bukkit/event/entity/EntityTargetEvent.java
package org.bukkit.event.entity; import org.bukkit.entity.Entity; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; /** * Called when a creature targets or untargets another entity */ public class EntityTargetEvent extends EntityEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancel = false; private Entity target; private final TargetReason reason; public EntityTargetEvent(final Entity entity, final Entity target, final TargetReason reason) { super(entity); this.target = target; this.reason = reason; } public boolean isCancelled() { return cancel; } public void setCancelled(boolean cancel) { this.cancel = cancel; } /** * Returns the reason for the targeting * * @return The reason */ public TargetReason getReason() { return reason; } /** * Get the entity that this is targeting. * <p> * This will be null in the case that the event is called when the mob * forgets its target. * * @return The entity */ public Entity getTarget() { return target; } /** * Set the entity that you want the mob to target instead. * <p> * It is possible to be null, null will cause the entity to be * target-less. * <p> * This is different from cancelling the event. Cancelling the event will * cause the entity to keep an original target, while setting to be null * will cause the entity to be reset. * * @param target The entity to target */ public void setTarget(Entity target) { this.target = target; } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } /** * An enum to specify the reason for the targeting */ public enum TargetReason { /** * When the entity's target has died, and so it no longer targets it */ TARGET_DIED, /** * When the entity doesn't have a target, so it attacks the nearest * player */ CLOSEST_PLAYER, /** * When the target attacks the entity, so entity targets it */ TARGET_ATTACKED_ENTITY, /** * When the target attacks a fellow pig zombie, so the whole group * will target him with this reason. */ PIG_ZOMBIE_TARGET, /** * When the target is forgotten for whatever reason. * <p> * Currently only occurs in with spiders when there is a high * brightness. */ FORGOT_TARGET, /** * When the target attacks the owner of the entity, so the entity * targets it. */ TARGET_ATTACKED_OWNER, /** * When the owner of the entity attacks the target attacks, so the * entity targets it. */ OWNER_ATTACKED_TARGET, /** * When the entity has no target, so the entity randomly chooses one. */ RANDOM_TARGET, /** * When an entity selects a target while defending a village. */ DEFEND_VILLAGE, /** * When the target attacks a nearby entity of the same type, so the entity targets it */ TARGET_ATTACKED_NEARBY_ENTITY, /** * When a zombie targeting an entity summons reinforcements, so the reinforcements target the same entity */ REINFORCEMENT_TARGET, /** * When an entity targets another entity after colliding with it. */ COLLISION, /** * For custom calls to the event. */ CUSTOM, /** * When the entity doesn't have a target, so it attacks the nearest * entity */ CLOSEST_ENTITY, /** * A currently unknown reason for the entity changing target. */ UNKNOWN; } }
412
0.896436
1
0.896436
game-dev
MEDIA
0.97323
game-dev
0.792873
1
0.792873
strongcourage/uafbench
4,099
CVE-2018-20623/gdb/common/btrace-common.c
/* Copyright (C) 2014-2019 Free Software Foundation, Inc. Contributed by Intel Corp. <markus.t.metzger@intel.com> This file is part of GDB. 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/>. */ #include "common-defs.h" #include "btrace-common.h" /* See btrace-common.h. */ const char * btrace_format_string (enum btrace_format format) { switch (format) { case BTRACE_FORMAT_NONE: return _("No or unknown format"); case BTRACE_FORMAT_BTS: return _("Branch Trace Store"); case BTRACE_FORMAT_PT: return _("Intel Processor Trace"); } internal_error (__FILE__, __LINE__, _("Unknown branch trace format")); } /* See btrace-common.h. */ const char * btrace_format_short_string (enum btrace_format format) { switch (format) { case BTRACE_FORMAT_NONE: return "unknown"; case BTRACE_FORMAT_BTS: return "bts"; case BTRACE_FORMAT_PT: return "pt"; } internal_error (__FILE__, __LINE__, _("Unknown branch trace format")); } /* See btrace-common.h. */ void btrace_data::fini () { switch (format) { case BTRACE_FORMAT_NONE: /* Nothing to do. */ return; case BTRACE_FORMAT_BTS: VEC_free (btrace_block_s, variant.bts.blocks); return; case BTRACE_FORMAT_PT: xfree (variant.pt.data); return; } internal_error (__FILE__, __LINE__, _("Unkown branch trace format.")); } /* See btrace-common.h. */ bool btrace_data::empty () const { switch (format) { case BTRACE_FORMAT_NONE: return true; case BTRACE_FORMAT_BTS: return VEC_empty (btrace_block_s, variant.bts.blocks); case BTRACE_FORMAT_PT: return (variant.pt.size == 0); } internal_error (__FILE__, __LINE__, _("Unkown branch trace format.")); } /* See btrace-common.h. */ void btrace_data::clear () { fini (); format = BTRACE_FORMAT_NONE; } /* See btrace-common.h. */ int btrace_data_append (struct btrace_data *dst, const struct btrace_data *src) { switch (src->format) { case BTRACE_FORMAT_NONE: return 0; case BTRACE_FORMAT_BTS: switch (dst->format) { default: return -1; case BTRACE_FORMAT_NONE: dst->format = BTRACE_FORMAT_BTS; dst->variant.bts.blocks = NULL; /* Fall-through. */ case BTRACE_FORMAT_BTS: { unsigned int blk; /* We copy blocks in reverse order to have the oldest block at index zero. */ blk = VEC_length (btrace_block_s, src->variant.bts.blocks); while (blk != 0) { btrace_block_s *block; block = VEC_index (btrace_block_s, src->variant.bts.blocks, --blk); VEC_safe_push (btrace_block_s, dst->variant.bts.blocks, block); } } } return 0; case BTRACE_FORMAT_PT: switch (dst->format) { default: return -1; case BTRACE_FORMAT_NONE: dst->format = BTRACE_FORMAT_PT; dst->variant.pt.data = NULL; dst->variant.pt.size = 0; /* fall-through. */ case BTRACE_FORMAT_PT: { gdb_byte *data; size_t size; size = src->variant.pt.size + dst->variant.pt.size; data = (gdb_byte *) xmalloc (size); memcpy (data, dst->variant.pt.data, dst->variant.pt.size); memcpy (data + dst->variant.pt.size, src->variant.pt.data, src->variant.pt.size); xfree (dst->variant.pt.data); dst->variant.pt.data = data; dst->variant.pt.size = size; } } return 0; } internal_error (__FILE__, __LINE__, _("Unkown branch trace format.")); }
412
0.801222
1
0.801222
game-dev
MEDIA
0.358897
game-dev
0.908707
1
0.908707
psforever/PSF-LoginServer
4,917
src/main/scala/net/psforever/objects/zones/ZoneDeployableActor.scala
// Copyright (c) 2017 PSForever package net.psforever.objects.zones import akka.actor.Actor import net.psforever.objects.Player import net.psforever.actors.zone.ZoneActor import net.psforever.objects.ce.Deployable import net.psforever.objects.serverobject.deploy.Interference import net.psforever.objects.sourcing.ObjectSource import net.psforever.objects.vehicles.MountedWeapons import net.psforever.objects.vital.SpawningActivity import net.psforever.packet.game.ChatMsg import net.psforever.services.local.{LocalAction, LocalServiceMessage} import net.psforever.types.ChatMessageType import scala.annotation.tailrec import scala.collection.mutable import scala.collection.mutable.ListBuffer /** * na * @param zone the `Zone` object */ class ZoneDeployableActor( zone: Zone, deployableList: ListBuffer[Deployable], turretToMount: mutable.HashMap[Int, Int] ) extends Actor { import ZoneDeployableActor._ private[this] val log = org.log4s.getLogger def receive: Receive = { case Zone.Deployable.Build(obj) => if (DeployableBuild(zone, obj, deployableList)) { obj.Zone = zone obj match { case mounting: MountedWeapons => val dguid = obj.GUID.guid mounting .Weapons .values .flatten { _.Equipment.map { _.GUID.guid } } .foreach { guid => turretToMount.put(guid, dguid) } case _ => () } obj.Definition.Initialize(obj, context) obj.LogActivity(SpawningActivity(ObjectSource(obj), zone.Number, None)) obj.Actor ! Zone.Deployable.Setup() } else { log.warn(s"failed to build a ${obj.Definition.Name}") sender() ! Zone.Deployable.IsDismissed(obj) } case Zone.Deployable.BuildByOwner(obj, owner, tool) => if (DeployableBuild(zone, obj, deployableList)) { obj.Zone = zone obj match { case mounting: MountedWeapons => val dguid = obj.GUID.guid mounting .Weapons .values .flatten { _.Equipment.map { _.GUID.guid } } .foreach { guid => turretToMount.put(guid, dguid) } case _ => () } obj.Definition.Initialize(obj, context) obj.LogActivity(SpawningActivity(ObjectSource(obj), zone.Number, None)) owner.Actor ! Player.BuildDeployable(obj, tool) } else { log.warn(s"failed to build a ${obj.Definition.Name} belonging to ${obj.OwnerName.getOrElse("no one")}") sender() ! Zone.Deployable.IsDismissed(obj) } case Zone.Deployable.Dismiss(obj) => if (DeployableDismiss(zone, obj, deployableList)) { obj match { case _: MountedWeapons => val dguid = obj.GUID.guid turretToMount.filterInPlace { case (_, guid) => guid != dguid } case _ => () } obj.Actor ! Zone.Deployable.IsDismissed(obj) obj.Definition.Uninitialize(obj, context) obj.ClearHistory() } case Zone.Deployable.IsBuilt(_) => () case Zone.Deployable.IsDismissed(_) => () case _ => () } } object ZoneDeployableActor { def DeployableBuild( zone: Zone, obj: Deployable, deployableList: ListBuffer[Deployable] ): Boolean = { val position = obj.Position deployableList.find(_ eq obj) match { case _ if Interference.Test(zone, obj).nonEmpty => zone.LocalEvents ! LocalServiceMessage( obj.OwnerName.getOrElse(""), LocalAction.SendResponse(ChatMsg(ChatMessageType.UNK_227, "@nomove_intersecting")) ) //may not be the correct message but is sufficient at explaining why the deployable can not be built false case None => deployableList += obj zone.actor ! ZoneActor.AddToBlockMap(obj, position) true case _ => false } } def DeployableDismiss( zone: Zone, obj: Deployable, deployableList: ListBuffer[Deployable] ): Boolean = { recursiveFindDeployable(deployableList.iterator, obj) match { case None => false case Some(index) => deployableList.remove(index) zone.actor ! ZoneActor.RemoveFromBlockMap(obj) true } } @tailrec final def recursiveFindDeployable( iter: Iterator[Deployable], target: Deployable, index: Int = 0 ): Option[Int] = { if (!iter.hasNext) { None } else { if (iter.next() == target) { Some(index) } else { recursiveFindDeployable(iter, target, index + 1) } } } }
412
0.531495
1
0.531495
game-dev
MEDIA
0.893458
game-dev
0.887463
1
0.887463
hogsy/OniFoxed
21,596
BungieFrameWork/BFW_ToolSource/Common/Imp/Imp_Dialog.c
// ====================================================================== // Imp_Dialog.c // ====================================================================== // ====================================================================== // Includes // ====================================================================== #include "BFW.h" #include "BFW_DialogManager.h" #include "BFW_TM_Construction.h" #include "BFW_Group.h" #include "BFW_ViewManager.h" #include "Imp_Common.h" #include "Imp_Dialog.h" #include "Imp_Texture.h" #include "Imp_View.h" // ====================================================================== // defines // ====================================================================== #define cMaxTextureNameLength 32 #define cMaxDialogFlags 32 // ====================================================================== // typedef // ====================================================================== typedef UUtError (*IMPrViewProc)( GRtGroup *inGroup, TMtPlaceHolder *outViewData); typedef struct tViewProc { char name[32]; IMPrViewProc view_proc; } tViewProc; // ====================================================================== // globals // ====================================================================== static char* gDialogCompileTime = __DATE__" "__TIME__; static AUtFlagElement IMPgDialogFlags[] = { { "none", DMcDialogFlag_None }, { "dialog_centered", DMcDialogFlag_Centered }, { "dialog_show_cursor", DMcDialogFlag_ShowCursor }, { NULL, 0 } }; static AUtFlagElement IMPgViewFlags[] = { { "none", VMcViewFlag_None }, { "view_visible", VMcViewFlag_Visible }, { "view_enabled", VMcViewFlag_Enabled }, { "view_active", VMcViewFlag_Active }, { NULL, 0 } }; static tViewProc IMPgViewProc[] = { { "dialog", IMPrView_Process_Dialog }, { "button", IMPrView_Process_Button }, { "checkbox", IMPrView_Process_CheckBox }, { "EditField", IMPrView_Process_EditField }, { "Picture", IMPrView_Process_Picture }, { "Scrollbar", IMPrView_Process_Scrollbar }, { "Slider", IMPrView_Process_Slider }, { "Tab", IMPrView_Process_Tab }, { "Text", IMPrView_Process_Text }, { NULL, NULL } }; // ====================================================================== // functions // ====================================================================== // ---------------------------------------------------------------------- /*static UUtError iProcessControls( GRtGroup *inGroup, DMtDialog *inDialog) { UUtError error; UUtUns16 num_controls; GRtElementArray *control_list; GRtElementType element_type; UUtUns16 i; // get pointer to control list error = GRrGroup_GetElement( inGroup, "controlList", &element_type, &control_list); if ((error != UUcError_None) || (element_type != GRcElementType_Array)) { Imp_PrintWarning("Could not get the control list"); return error; } // get the number of controls in the control_list num_controls = (UUtUns16)GRrGroup_Array_GetLength(control_list); // create a new control list template error = TMrConstruction_Instance_NewUnique( DMcTemplate_ControlList, num_controls, &inDialog->dialog_controls); IMPmError_ReturnOnError(error); // process the controls for (i = 0; i < num_controls; i++) { DMtControl *control; GRtGroup *control_group; char *control_name; // get the control element error = GRrGroup_Array_GetElement( control_list, i, &element_type, &control_group); if ((error != UUcError_None) || (element_type != GRcElementType_Group)) { Imp_PrintWarning("Could not get the control group"); return error; } // create an instance of this control error = TMrConstruction_Instance_NewUnique( DMcTemplate_Control, 0, &control); UUmError_ReturnOnError(error); // initialize the fields control->flags = 0; // get the width error = GRrGroup_GetUns16( control_group, "width", &control->width); IMPmError_ReturnOnError(error); // get the height error = GRrGroup_GetUns16( control_group, "height", &control->height); IMPmError_ReturnOnError(error); // get the controls location error = Imp_ProcessLocation(control_group, &control->location); if (error != UUcError_None) { Imp_PrintWarning("Could not process the control's location"); return error; } // get the controls id number error = GRrGroup_GetUns16( control_group, "control_id", &control->id); if (error != UUcError_None) { Imp_PrintWarning("Could not get the controls id number"); return error; } // get the controls name error = GRrGroup_GetString( control_group, "control_name", &control_name); IMPmError_ReturnOnErrorMsg(error, "Cound not get the controls name"); // process the control flags error = Imp_ProcessDialogFlags(control_group, IMPgControlFlags, &control->flags); IMPmError_ReturnOnErrorMsg(error, "Error processing the flags."); // what type of control are we dealing with if (strncmp(control_name, "button", strlen("button")) == 0) { error = TMrConstruction_Instance_GetPlaceHolder( DMcTemplate_Control_Button, control_name, (TMtPlaceHolder*)&control->control_ref); } else if (strncmp(control_name, "edit", strlen("edit")) == 0) { error = TMrConstruction_Instance_GetPlaceHolder( DMcTemplate_Control_EditField, control_name, (TMtPlaceHolder*)&control->control_ref); } else if (strncmp(control_name, "picture", strlen("picture")) == 0) { error = TMrConstruction_Instance_GetPlaceHolder( DMcTemplate_Control_Picture, control_name, (TMtPlaceHolder*)&control->control_ref); } else if (strncmp(control_name, "text", strlen("text")) == 0) { error = TMrConstruction_Instance_GetPlaceHolder( DMcTemplate_Control_Text, control_name, (TMtPlaceHolder*)&control->control_ref); } else { error = UUcError_Generic; } if (error != UUcError_None) { Imp_PrintWarning("Could not get the control's control_ref"); return error; } // set the control inDialog->dialog_controls->controls[i] = control; } return UUcError_None; }*/ // ====================================================================== #if 0 #pragma mark - #endif // ====================================================================== // ---------------------------------------------------------------------- UUtError Imp_ProcessDialogFlags( GRtGroup *inGroup, AUtFlagElement *inFlagList, UUtUns16 *outFlags) { UUtError error; GRtElementType element_type; GRtElementArray *flag_array; UUtUns32 flags; // init the flags *outFlags = 0; flags = 0; // get the flag string error = GRrGroup_GetElement( inGroup, "flags", &element_type, &flag_array); if (error != UUcError_None) return error; if (element_type != GRcElementType_Array) { IMPmError_ReturnOnErrorMsg(error, "Error getting flags"); } // process the flags error = AUrFlags_ParseFromGroupArray( inFlagList, element_type, flag_array, &flags); if ((error != UUcError_None) && (error != AUcError_FlagNotFound)) { IMPmError_ReturnOnErrorMsg(error, "Unable to parse the flags."); } // set the outgoing string *outFlags = flags; return UUcError_None; } // ---------------------------------------------------------------------- UUtError Imp_ProcessLocation( GRtGroup *inGroup, IMtPoint2D *outLocation) { UUtError error; GRtElementType element_type; GRtGroup *location; // initialize outLocation outLocation->x = 0; outLocation->y = 0; // get the location group error = GRrGroup_GetElement( inGroup, "location", &element_type, &location); if (error != UUcError_None) { return error; } if (element_type != GRcElementType_Group) { Imp_PrintWarning("Could not get location"); return UUcError_Generic; } // get the location x error = GRrGroup_GetUns16(location, "x", (UUtUns16*)&outLocation->x); IMPmError_ReturnOnError(error); // get the location y error = GRrGroup_GetUns16(location, "y", (UUtUns16*)&outLocation->y); IMPmError_ReturnOnError(error); return UUcError_None; } // ---------------------------------------------------------------------- UUtError Imp_ProcessTextures( BFtFileRef* inSourceFile, GRtGroup *inGroup, DMtTextureList **inTextureList, char *inTextureListName) { UUtError error; UUtUns16 num_textures; GRtElementArray *texture_list; GRtElementType element_type; UUtUns16 i; // get pointer to texture list // it is okay for the list not to exist error = GRrGroup_GetElement( inGroup, inTextureListName, &element_type, &texture_list); if (error != UUcError_None) return UUcError_None; if (element_type != GRcElementType_Array) { Imp_PrintWarning("Could not get the texture list"); return UUcError_Generic; } // get the number of textures in the texture_list num_textures = (UUtUns16)GRrGroup_Array_GetLength(texture_list); // create a new texture list template error = TMrConstruction_Instance_NewUnique( DMcTemplate_TextureList, num_textures, inTextureList); IMPmError_ReturnOnError(error); // process the textures for (i = 0; i < num_textures; i++) { char *texture_file; BFtFileRef *texture_file_ref; char *texture_name; TMtPlaceHolder texture_ref; // get the name of texture[i] error = GRrGroup_Array_GetElement( texture_list, i, &element_type, &texture_file); if ((error != UUcError_None) || (element_type != GRcElementType_String)) { Imp_PrintWarning("Could not get the texture file name"); return UUcError_Generic; } // create a new file ref using the texture's file name error = BFrFileRef_DuplicateAndReplaceName( inSourceFile, texture_file, &texture_file_ref); IMPmError_ReturnOnErrorMsg(error, "texture file was not found"); // set the textures name texture_name = BFrFileRef_GetLeafName(texture_file_ref); // process the texture map file error = Imp_ProcessTexture_Big_File(texture_file_ref, texture_name, &texture_ref); IMPmError_ReturnOnErrorMsg(error, "Could not import the texture file."); // save the texture ref (*inTextureList)->textures[i].texture_ref = (void*)texture_ref; // dispose of the file ref BFrFileRef_Dispose(texture_file_ref); } return UUcError_None; } // ====================================================================== #if 0 #pragma mark - #endif // ====================================================================== // ---------------------------------------------------------------------- UUtError Imp_AddView( BFtFileRef* inSourceFile, UUtUns32 inSourceFileModDate, GRtGroup* inGroup, char* inInstanceName) { UUtError error; UUtBool bool_result; UUtBool build_instance; UUtUns32 create_date; UUtUns32 compile_date; // check to see if the dialogs need to be built bool_result = TMrConstruction_Instance_CheckExists( VMcTemplate_View, inInstanceName, &create_date); if (bool_result) { compile_date = UUrConvertStrToSecsSince1900(gDialogCompileTime); build_instance = (UUtBool)(create_date < inSourceFileModDate || create_date < compile_date); } else { build_instance = UUcTrue; } if (build_instance) { UUtUns16 id; UUtUns16 type; char *type_name; UUtUns16 flags; IMtPoint2D location; UUtInt16 width; UUtInt16 height; GRtElementType element_type; GRtElementArray *views_array; UUtUns16 num_child_views; VMtView *view; TMtPlaceHolder view_data; UUtUns16 i; tViewProc *viewproc; // get the id error = GRrGroup_GetUns16( inGroup, "id", &id); IMPmError_ReturnOnErrorMsg(error, "Unable to get view id"); // get the type name error = GRrGroup_GetString( inGroup, "type", &type_name); IMPmError_ReturnOnErrorMsg(error, "Unable to get view type"); // get the flags error = Imp_ProcessDialogFlags( inGroup, IMPgViewFlags, &flags); IMPmError_ReturnOnErrorMsg(error, "Unable to get view flags"); // get the location error = Imp_ProcessLocation( inGroup, &location); IMPmError_ReturnOnErrorMsg(error, "Unable to get view location"); // get the width error = GRrGroup_GetInt16( inGroup, "width", &width); IMPmError_ReturnOnErrorMsg(error, "Unable to get view width"); // get the height error = GRrGroup_GetInt16( inGroup, "height", &height); IMPmError_ReturnOnErrorMsg(error, "Unable to get view height"); // get the view data view_data = NULL; for (viewproc = IMPgViewProc; viewproc->name != NULL; viewproc++) { if (!strncmp(type_name, viewproc->name, strlen(viewproc->name))) { viewproc->view_proc(inGroup, &view_data); } } // get the views array error = GRrGroup_GetElement( inGroup, "view_list", &element_type, &views_array); if ((error != UUcError_None) && (element_type != GRcElementType_Array)) { if (error != GRcError_ElementNotFound) { IMPmError_ReturnOnErrorMsg( error, "Unable to get view views array"); } else { views_array = NULL; } } // get the number of elements in the views array if (views_array) num_child_views = (UUtUns16)GRrGroup_Array_GetLength(views_array); else num_child_views = 0; // create an view template instance error = TMrConstruction_Instance_Renew( VMcTemplate_View, inInstanceName, num_child_views, &view); IMPmError_ReturnOnErrorMsg(error, "Could not create a view template"); // set the fields of view view->id = id; view->type = type; view->flags = flags; view->location = location; view->width = width; view->height = height; view->view_data = (TMtPlaceHolder*)view_data; // copy the views from the views_array for (i = 0; i < num_child_views; i++) { void *view_description; TMtPlaceHolder view_ref; char *instance_name; // get the name of the view error = GRrGroup_Array_GetElement( views_array, i, &element_type, &view_description); IMPmError_ReturnOnErrorMsg(error, "Could not get view ref name"); if (element_type == GRcElementType_String) { instance_name = view_description; } else if (element_type == GRcElementType_Group) { // get the instance name error = GRrGroup_GetString( view_description, "instance", &instance_name); IMPmError_ReturnOnErrorMsg(error, "Could not get instance name"); // process the group error = Imp_AddView( inSourceFile, inSourceFileModDate, view_description, instance_name); IMPmError_ReturnOnErrorMsg(error, "Could not get instance name"); } // get a place holder for the view error = TMrConstruction_Instance_GetPlaceHolder( VMcTemplate_View, instance_name, &view_ref); IMPmError_ReturnOnErrorMsg(error, "Could not get view placeholder for dialog"); view->child_views[i].view_ref = (void*)view_ref; } } return UUcError_None; } // ---------------------------------------------------------------------- UUtError Imp_AddDialogData( BFtFileRef* inSourceFile, UUtUns32 inSourceFileModDate, GRtGroup* inGroup, char* inInstanceName) { /* UUtError error; UUtBool bool_result; UUtBool build_instance; UUtUns32 create_date; UUtUns32 compile_date; DMtDialogData *dialogdata; // check to see if the dialogs need to be built bool_result = TMrConstruction_Instance_CheckExists( DMcTemplate_DialogData, inInstanceName, &create_date); if (bool_result) { compile_date = UUrConvertStrToSecsSince1900(gDialogCompileTime); build_instance = (UUtBool)(create_date < inSourceFileModDate || create_date < compile_date); } else { build_instance = UUcTrue; } // build the dialogs if necessary if (build_instance) { // create a new dialog template error = TMrConstruction_Instance_Renew( DMcTemplate_DialogData, inInstanceName, 0, &dialogdata); IMPmError_ReturnOnErrorMsg(error, "Could not create a dialogdata template"); // get the animation rate error = GRrGroup_GetUns16( inGroup, "animation_rate", &dialogdata->animation_rate); if (error != UUcError_None) { if (error != GRcError_ElementNotFound) { IMPmError_ReturnOnErrorMsg( error, "Unable to process animation rate for dialog data"); } else { dialogdata->animation_rate = 0; } } // import the background error = Imp_ProcessTextures( inSourceFile, inGroup, &dialogdata->dialog_textures, "textures"); IMPmError_ReturnOnErrorMsg(error, "Could not get dialogdata textures"); // import the location error = Imp_ProcessDialogFlags( inGroup, IMPgDialogFlags, &dialogdata->flags); IMPmError_ReturnOnErrorMsg(error, "Unable to get the dialogdata location"); }*/ return UUcError_None; } // ---------------------------------------------------------------------- UUtError Imp_AddDialog( BFtFileRef* inSourceFile, UUtUns32 inSourceFileModDate, GRtGroup* inGroup, char* inInstanceName) { UUtError error; UUtBool bool_result; UUtBool build_instance; UUtUns32 create_date; UUtUns32 compile_date; DMtDialog *dialog; // check to see if the dialogs need to be built bool_result = TMrConstruction_Instance_CheckExists( DMcTemplate_Dialog, inInstanceName, &create_date); if (bool_result) { compile_date = UUrConvertStrToSecsSince1900(gDialogCompileTime); build_instance = (UUtBool)(create_date < inSourceFileModDate || create_date < compile_date); } else { build_instance = UUcTrue; } // build the dialogs if necessary if (build_instance) { char *view_name; // create a new dialog template error = TMrConstruction_Instance_Renew( DMcTemplate_Dialog, inInstanceName, 0, &dialog); IMPmError_ReturnOnErrorMsg(error, "Could not create a dialog template"); // get the name of the view error = GRrGroup_GetString( inGroup, "view", &view_name); IMPmError_ReturnOnErrorMsg(error, "Could not find a view in the dialog ins file"); // get a place holder for the view error = TMrConstruction_Instance_GetPlaceHolder( VMcTemplate_View, view_name, (TMtPlaceHolder*)&dialog->view_ref); IMPmError_ReturnOnErrorMsg(error, "Could not get view placeholder for dialog"); } return UUcError_None; } // ---------------------------------------------------------------------- UUtError Imp_AddDialogTypeList( BFtFileRef* inSourceFile, UUtUns32 inSourceFileModDate, GRtGroup* inGroup, char* inInstanceName) { UUtError error; UUtBool bool_result; UUtBool build_instance; UUtUns32 create_date; UUtUns32 compile_date; // check to see if the dialogs need to be built bool_result = TMrConstruction_Instance_CheckExists( DMcTemplate_DialogTypeList, inInstanceName, &create_date); if (bool_result) { compile_date = UUrConvertStrToSecsSince1900(gDialogCompileTime); build_instance = (UUtBool)(create_date < inSourceFileModDate || create_date < compile_date); } else { build_instance = UUcTrue; } // build the dialogs if necessary if (build_instance) { DMtDialogTypeList *dialog_type_list; GRtElementArray *dialog_type_array; GRtElementType element_type; UUtUns16 i; UUtUns16 num_pairs; DMtDialogType dialog_type; char *dialog_name; GRtGroup *pair; // get a pointer to the dialog_type_array error = GRrGroup_GetElement( inGroup, "dialog_type_list", &element_type, &dialog_type_array); if ((error != UUcError_None) || (element_type != GRcElementType_Array)) { Imp_PrintWarning("Could not get the dialog type array"); return UUcError_Generic; } // get the number of pairs in the dialog_type_array num_pairs = (UUtUns16)GRrGroup_Array_GetLength(dialog_type_array); // create a new dialog template error = TMrConstruction_Instance_Renew( DMcTemplate_DialogTypeList, inInstanceName, num_pairs, &dialog_type_list); IMPmError_ReturnOnError(error); // process the pairs for (i = 0; i < num_pairs; i++) { UUtUns16 j; // get pair[i] error = GRrGroup_Array_GetElement( dialog_type_array, i, &element_type, &pair); if ((error != UUcError_None) || (element_type != GRcElementType_Group)) { Imp_PrintWarning("Could not get the pair"); return UUcError_Generic; } // get the type of the pair error = GRrGroup_GetUns16(pair, "dialog_type", &dialog_type); IMPmError_ReturnOnError(error); // check for duplicates for (j = 0; j < i; j++) { if (dialog_type_list->dialog_type_pair[j].dialog_type == dialog_type) { Imp_PrintWarning("WARNING: Two dialogs have the same dialog type."); } } dialog_type_list->dialog_type_pair[i].dialog_type = dialog_type; // get the name of the pair error = GRrGroup_GetString(pair, "dialog_name", &dialog_name); IMPmError_ReturnOnError(error); UUrString_Copy( dialog_type_list->dialog_type_pair[i].dialog_name, dialog_name, DMcMaxDialogNameLength); } } return UUcError_None; }
412
0.952439
1
0.952439
game-dev
MEDIA
0.567436
game-dev,desktop-app
0.933699
1
0.933699
kwonganding/winform.controls
1,384
TTX.Framework.WindowUI/TX.Framework.WindowUI/AppCode/{Template}/Expression/Expressions/UnaryMinusExpression.cs
#region COPYRIGHT // // THIS IS GENERATED BY TEMPLATE // // AUTHOR : ROYE // DATE : 2010 // // COPYRIGHT (C) 2010, TIANXIAHOTEL TECHNOLOGIES CO., LTD. ALL RIGHTS RESERVED. // #endregion using System; using System.Collections.Generic; using System.Text; namespace System.Text.Template { public class UnaryMinusExpression : Expression { private readonly Expression _value; public UnaryMinusExpression(Expression value) { _value = value; } public override ValueExpression Evaluate(ITemplateContext context) { ValueExpression value = _value.Evaluate(context); if (value.Type == typeof(decimal)) return Expression.Value(-(decimal)value.Value); if (value.Type == typeof(double)) return Expression.Value(-(double)value.Value); if (value.Type == typeof(float)) return Expression.Value(-(float)value.Value); if (value.Type == typeof(uint)) return Expression.Value(-(uint)value.Value); if (value.Type == typeof(int)) return Expression.Value(-(int)value.Value); if (value.Type == typeof(long)) return Expression.Value(-(long)value.Value); throw new OverflowException(); } } }
412
0.748295
1
0.748295
game-dev
MEDIA
0.267207
game-dev
0.814683
1
0.814683
blendogames/thirtyflightsofloving
70,849
tfol/g_monster.c
/* Copyright (C) 1997-2001 Id Software, Inc. Copyright (C) 2000-2002 Mr. Hyde and Mad Dog This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "g_local.h" void InitiallyDead (edict_t *self); // Lazarus: If worldspawn CORPSE_SINK effects flag is set, // monsters/actors fade out and sink into the floor // 30 seconds after death #define SINKAMT 1 void FadeSink (edict_t *ent) { ent->count++; ent->s.origin[2]-=SINKAMT; ent->think=FadeSink; if (ent->count==5) { ent->s.renderfx &= ~RF_TRANSLUCENT; ent->s.effects |= EF_SPHERETRANS; } if (ent->count==10) ent->think=G_FreeEdict; ent->nextthink=level.time+FRAMETIME; } void FadeDieSink (edict_t *ent) { ent->takedamage = DAMAGE_NO; // can't gib 'em once they start sinking ent->s.effects &= ~EF_FLIES; ent->s.sound = 0; ent->s.origin[2]-=SINKAMT; ent->s.renderfx=RF_TRANSLUCENT; ent->think=FadeSink; ent->nextthink=level.time+FRAMETIME; ent->count=0; } // Lazarus: M_SetDeath is used to restore the death movement, // bounding box, and a few other parameters for dead // monsters that change levels with a trigger_transition qboolean M_SetDeath(edict_t *self, mmove_t **deathmoves) { mmove_t *move=NULL; mmove_t *dmove; if(self->health > 0) return false; while(*deathmoves && !move) { dmove = *deathmoves; if( (self->s.frame >= dmove->firstframe) && (self->s.frame <= dmove->lastframe) ) move = dmove; else deathmoves++; } if(move) { self->monsterinfo.currentmove = move; if(self->monsterinfo.currentmove->endfunc) self->monsterinfo.currentmove->endfunc(self); self->s.frame = move->lastframe; self->s.skinnum |= 1; return true; } return false; } // // monster weapons // //FIXME monsters should call these with a totally accurate direction // and we can mess it up based on skill. Spread should be for normal // and we can tighten or loosen based on skill. We could muck with // the damages too, but I'm not sure that's such a good idea. void monster_fire_bullet (edict_t *self, vec3_t start, vec3_t dir, int damage, int kick, int hspread, int vspread, int flashtype) { fire_bullet (self, start, dir, damage, kick, hspread, vspread, MOD_UNKNOWN); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } void monster_fire_shotgun (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int kick, int hspread, int vspread, int count, int flashtype) { fire_shotgun (self, start, aimdir, damage, kick, hspread, vspread, count, MOD_UNKNOWN); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } void monster_fire_blaster (edict_t *self, vec3_t start, vec3_t dir, int damage, int speed, int flashtype, int effect, int color) { fire_blaster (self, start, dir, damage, speed, effect, false, color); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } void monster_fire_grenade (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int speed, int flashtype) { fire_grenade (self, start, aimdir, damage, speed, 2.5, damage+40, false); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } void monster_fire_rocket (edict_t *self, vec3_t start, vec3_t dir, int damage, int speed, int flashtype, edict_t *homing_target) { fire_rocket (self, start, dir, damage, speed, damage+20, damage, homing_target); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } void monster_fire_railgun (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int kick, int flashtype) { fire_rail (self, start, aimdir, damage, kick); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } void monster_fire_bfg (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int speed, int kick, float damage_radius, int flashtype) { fire_bfg (self, start, aimdir, damage, speed, damage_radius); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } // // Monster utility functions // void M_FliesOff (edict_t *self) { self->s.effects &= ~EF_FLIES; self->s.sound = 0; } void M_FliesOn (edict_t *self) { if (self->waterlevel) return; self->s.effects |= EF_FLIES; self->s.sound = gi.soundindex ("infantry/inflies1.wav"); self->think = M_FliesOff; self->nextthink = level.time + 60; } void M_FlyCheck (edict_t *self) { //Knightmare- keep running lava check self->postthink = deadmonster_think; if (self->monsterinfo.flies > 1.0) { // should ALREADY have flies self->think = M_FliesOff; self->nextthink = level.time + 60; return; } if (self->waterlevel) return; if (random() > self->monsterinfo.flies) return; if (world->effects & FX_WORLDSPAWN_CORPSEFADE) return; self->think = M_FliesOn; self->nextthink = level.time + 5 + 10 * random(); } void AttackFinished (edict_t *self, float time) { self->monsterinfo.attack_finished = level.time + time; } void M_CheckGround (edict_t *ent) { vec3_t point; trace_t trace; if (level.time < ent->gravity_debounce_time) return; if (ent->flags & (FL_SWIM|FL_FLY)) return; if (ent->velocity[2] > 100) { ent->groundentity = NULL; return; } // if the hull point one-quarter unit down is solid the entity is on ground point[0] = ent->s.origin[0]; point[1] = ent->s.origin[1]; point[2] = ent->s.origin[2] - 0.25; trace = gi.trace (ent->s.origin, ent->mins, ent->maxs, point, ent, MASK_MONSTERSOLID); // check steepness if ( trace.plane.normal[2] < 0.7 && !trace.startsolid) { ent->groundentity = NULL; return; } // Lazarus: The following 2 lines were in the original code and commented out // by id. However, the effect of this is that a player walking over // a dead monster who is laying on a brush model will cause the // dead monster to drop through the brush model. This change *may* // have other consequences, though, so watch out for this. ent->groundentity = trace.ent; ent->groundentity_linkcount = trace.ent->linkcount; // if (!trace.startsolid && !trace.allsolid) // VectorCopy (trace.endpos, ent->s.origin); if (!trace.startsolid && !trace.allsolid) { VectorCopy (trace.endpos, ent->s.origin); ent->groundentity = trace.ent; ent->groundentity_linkcount = trace.ent->linkcount; // ent->velocity[2] = 0; Lazarus: what if the groundentity is moving? ent->velocity[2] = trace.ent->velocity[2]; } } void M_CatagorizePosition (edict_t *ent) { vec3_t point; int cont; // // get waterlevel // // Lazarus... more broken code because of origin being screwed up // point[0] = ent->s.origin[0]; // point[1] = ent->s.origin[1]; // point[2] = ent->s.origin[2] + ent->mins[2] + 1; point[0] = (ent->absmax[0] + ent->absmin[0])/2; point[1] = (ent->absmax[1] + ent->absmin[1])/2; point[2] = ent->absmin[2] + 2; cont = gi.pointcontents (point); if (!(cont & MASK_WATER)) { ent->waterlevel = 0; ent->watertype = 0; return; } ent->watertype = cont; ent->waterlevel = 1; point[2] += 26; cont = gi.pointcontents (point); if (!(cont & MASK_WATER)) return; ent->waterlevel = 2; point[2] += 22; cont = gi.pointcontents (point); if (cont & MASK_WATER) ent->waterlevel = 3; } void M_WorldEffects (edict_t *ent) { int dmg; if (ent->health > 0) { if (!(ent->flags & FL_SWIM)) { if (ent->waterlevel < 3) { ent->air_finished = level.time + 12; } else if (ent->air_finished < level.time) { // drown! if (ent->pain_debounce_time < level.time) { dmg = 2 + 2 * floor(level.time - ent->air_finished); if (dmg > 15) dmg = 15; T_Damage (ent, world, world, vec3_origin, ent->s.origin, vec3_origin, dmg, 0, DAMAGE_NO_ARMOR, MOD_WATER); ent->pain_debounce_time = level.time + 1; } } } else { if (ent->waterlevel > 0) { ent->air_finished = level.time + 9; } else if (ent->air_finished < level.time) { // suffocate! if (ent->pain_debounce_time < level.time) { dmg = 2 + 2 * floor(level.time - ent->air_finished); if (dmg > 15) dmg = 15; T_Damage (ent, world, world, vec3_origin, ent->s.origin, vec3_origin, dmg, 0, DAMAGE_NO_ARMOR, MOD_WATER); ent->pain_debounce_time = level.time + 1; } } } } if (ent->waterlevel == 0) { if (ent->flags & FL_INWATER) { if (ent->watertype & CONTENTS_MUD) gi.sound (ent, CHAN_BODY, gi.soundindex("mud/mud_out1.wav"), 1, ATTN_NORM, 0); else gi.sound (ent, CHAN_BODY, gi.soundindex("player/watr_out.wav"), 1, ATTN_NORM, 0); ent->flags &= ~FL_INWATER; } return; } if ((ent->watertype & CONTENTS_LAVA) && !(ent->flags & FL_IMMUNE_LAVA)) { if (ent->damage_debounce_time < level.time) { ent->damage_debounce_time = level.time + 0.2; T_Damage (ent, world, world, vec3_origin, ent->s.origin, vec3_origin, 10*ent->waterlevel, 0, 0, MOD_LAVA); } } // slime doesn't damage dead monsters if ((ent->watertype & CONTENTS_SLIME) && !(ent->flags & FL_IMMUNE_SLIME) && !(ent->svflags & SVF_DEADMONSTER)) { if (ent->damage_debounce_time < level.time) { ent->damage_debounce_time = level.time + 1; T_Damage (ent, world, world, vec3_origin, ent->s.origin, vec3_origin, 4*ent->waterlevel, 0, 0, MOD_SLIME); } } if ( !(ent->flags & FL_INWATER) ) { if (!(ent->svflags & SVF_DEADMONSTER)) { if (ent->watertype & CONTENTS_LAVA) if (random() <= 0.5) gi.sound (ent, CHAN_BODY, gi.soundindex("player/lava1.wav"), 1, ATTN_NORM, 0); else gi.sound (ent, CHAN_BODY, gi.soundindex("player/lava2.wav"), 1, ATTN_NORM, 0); else if (ent->watertype & CONTENTS_SLIME) gi.sound (ent, CHAN_BODY, gi.soundindex("player/watr_in.wav"), 1, ATTN_NORM, 0); else if (ent->watertype & CONTENTS_MUD) gi.sound (ent, CHAN_BODY, gi.soundindex("mud/mud_in2.wav"), 1, ATTN_NORM, 0); else if (ent->watertype & CONTENTS_WATER) gi.sound (ent, CHAN_BODY, gi.soundindex("player/watr_in.wav"), 1, ATTN_NORM, 0); } ent->flags |= FL_INWATER; ent->old_watertype = ent->watertype; ent->damage_debounce_time = 0; } } void M_droptofloor (edict_t *ent) { vec3_t end; trace_t trace; ent->s.origin[2] += 1; VectorCopy (ent->s.origin, end); end[2] -= 256; trace = gi.trace (ent->s.origin, ent->mins, ent->maxs, end, ent, MASK_MONSTERSOLID); if (trace.fraction == 1 || trace.allsolid) return; VectorCopy (trace.endpos, ent->s.origin); gi.linkentity (ent); M_CheckGround (ent); M_CatagorizePosition (ent); } void M_SetEffects (edict_t *ent) { ent->s.effects &= ~(EF_COLOR_SHELL|EF_POWERSCREEN); ent->s.renderfx &= ~(RF_SHELL_RED|RF_SHELL_GREEN|RF_SHELL_BLUE); if (ent->monsterinfo.aiflags & AI_RESURRECTING) { ent->s.effects |= EF_COLOR_SHELL; ent->s.renderfx |= RF_SHELL_RED; } if (ent->health <= 0) return; if (ent->powerarmor_time > level.time) { if (ent->monsterinfo.power_armor_type == POWER_ARMOR_SCREEN) { ent->s.effects |= EF_POWERSCREEN; } else if (ent->monsterinfo.power_armor_type == POWER_ARMOR_SHIELD) { ent->s.effects |= EF_COLOR_SHELL; ent->s.renderfx |= RF_SHELL_GREEN; } } } void M_MoveFrame (edict_t *self) { mmove_t *move; int index; // Lazarus: For live monsters weaker than gladiator who aren't already running from // something, evade live grenades on the ground. if((self->health > 0) && (self->max_health < 400) && !(self->monsterinfo.aiflags & AI_CHASE_THING) && self->monsterinfo.run) Grenade_Evade (self); move = self->monsterinfo.currentmove; self->nextthink = level.time + FRAMETIME; if ((self->monsterinfo.nextframe) && (self->monsterinfo.nextframe >= move->firstframe) && (self->monsterinfo.nextframe <= move->lastframe)) { self->s.frame = self->monsterinfo.nextframe; self->monsterinfo.nextframe = 0; } else { if (self->s.frame == move->lastframe) { if (move->endfunc) { move->endfunc (self); // regrab move, endfunc is very likely to change it move = self->monsterinfo.currentmove; // check for death if (self->svflags & SVF_DEADMONSTER) return; } } if (self->s.frame < move->firstframe || self->s.frame > move->lastframe) { self->monsterinfo.aiflags &= ~AI_HOLD_FRAME; self->s.frame = move->firstframe; } else { if (!(self->monsterinfo.aiflags & AI_HOLD_FRAME)) { self->s.frame++; if (self->s.frame > move->lastframe) self->s.frame = move->firstframe; } } } index = self->s.frame - move->firstframe; if (move->frame[index].aifunc) if (!(self->monsterinfo.aiflags & AI_HOLD_FRAME)) move->frame[index].aifunc (self, move->frame[index].dist * self->monsterinfo.scale); else move->frame[index].aifunc (self, 0); if (move->frame[index].thinkfunc) move->frame[index].thinkfunc (self); } void monster_think (edict_t *self) { M_MoveFrame (self); if (self->linkcount != self->monsterinfo.linkcount) { self->monsterinfo.linkcount = self->linkcount; M_CheckGround (self); } M_CatagorizePosition (self); M_WorldEffects (self); M_SetEffects (self); } // Knightmare- for dead monsters to check // if they've fallen into lava, etc. void deadmonster_think (edict_t *self) { M_CatagorizePosition (self); M_WorldEffects (self); M_SetEffects (self); } /* ================ monster_use Using a monster makes it angry at the current activator ================ */ void monster_use (edict_t *self, edict_t *other, edict_t *activator) { if (self->enemy) return; if (self->health <= 0) return; if (activator->flags & FL_NOTARGET) return; if (!(activator->client) && !(activator->monsterinfo.aiflags & AI_GOOD_GUY)) return; if (activator->flags & FL_DISGUISED) return; // if monster is "used" by player, turn off good guy stuff if (activator->client) { self->spawnflags &= ~SF_MONSTER_GOODGUY; self->monsterinfo.aiflags &= ~(AI_GOOD_GUY + AI_FOLLOW_LEADER); if(self->dmgteam && !Q_stricmp(self->dmgteam,"player")) self->dmgteam = NULL; } // delay reaction so if the monster is teleported, its sound is still heard self->enemy = activator; FoundTarget (self); } void monster_start_go (edict_t *self); void monster_triggered_spawn (edict_t *self) { self->s.origin[2] += 1; KillBox (self); self->solid = SOLID_BBOX; self->movetype = MOVETYPE_STEP; self->svflags &= ~SVF_NOCLIENT; self->air_finished = level.time + 12; gi.linkentity (self); monster_start_go (self); if (self->enemy && !(self->spawnflags & SF_MONSTER_SIGHT) && !(self->enemy->flags & FL_NOTARGET)) { if(!(self->enemy->flags & FL_DISGUISED)) FoundTarget (self); else self->enemy = NULL; } else self->enemy = NULL; } void monster_triggered_spawn_use (edict_t *self, edict_t *other, edict_t *activator) { // we have a one frame delay here so we don't telefrag the guy who activated us self->think = monster_triggered_spawn; self->nextthink = level.time + FRAMETIME; // Knightmare- good guy monsters shouldn't have an enemy from this if (activator->client && !(self->monsterinfo.aiflags & AI_GOOD_GUY)) self->enemy = activator; // Lazarus: Add 'em up if(!(self->monsterinfo.aiflags & AI_GOOD_GUY)) level.total_monsters++; self->use = monster_use; } void monster_triggered_start (edict_t *self) { self->solid = SOLID_NOT; self->movetype = MOVETYPE_NONE; self->svflags |= SVF_NOCLIENT; self->nextthink = 0; self->use = monster_triggered_spawn_use; // Lazarus self->spawnflags &= ~SF_MONSTER_TRIGGER_SPAWN; } /* ================ monster_death_use When a monster dies, it fires all of its targets with the current enemy as activator. ================ */ void monster_death_use (edict_t *self) { edict_t *player; int i; self->flags &= ~(FL_FLY|FL_SWIM); self->monsterinfo.aiflags &= AI_GOOD_GUY; // Lazarus: If actor/monster is being used as a camera by a player, // turn camera off for that player for (i=0,player=g_edicts+1; i<maxclients->value; i++, player++) { if(player->client && player->client->spycam == self) camera_off(player); } if (self->item) { Drop_Item (self, self->item); self->item = NULL; } if (self->deathtarget) self->target = self->deathtarget; if (!self->target) return; G_UseTargets (self, self->enemy); } //============================================================================ qboolean monster_start (edict_t *self) { if (deathmatch->value) { G_FreeEdict (self); return false; } // Lazarus: Already gibbed monsters passed across levels via trigger_transition: if ( (self->max_health > 0) && (self->health <= self->gib_health) && !(self->spawnflags & SF_MONSTER_NOGIB) ) { void SP_gibhead(edict_t *); SP_gibhead(self); return true; } // Lazarus: Good guys if (self->spawnflags & SF_MONSTER_GOODGUY) { self->monsterinfo.aiflags |= AI_GOOD_GUY; if(!self->dmgteam) { self->dmgteam = gi.TagMalloc(8*sizeof(char), TAG_LEVEL); strcpy(self->dmgteam,"player"); } } // Lazarus: Max range for sight/attack if(st.distance) self->monsterinfo.max_range = max(500,st.distance); else self->monsterinfo.max_range = 1600; // Q2 default is 1000. We're mean. // Lazarus: We keep SIGHT to mean what old AMBUSH does, and AMBUSH additionally // now means don't play idle sounds /* if ((self->spawnflags & MONSTER_SIGHT) && !(self->monsterinfo.aiflags & AI_GOOD_GUY)) { self->spawnflags &= ~MONSTER_SIGHT; self->spawnflags |= MONSTER_AMBUSH; } */ if ((self->spawnflags & SF_MONSTER_AMBUSH) && !(self->monsterinfo.aiflags & AI_GOOD_GUY)) self->spawnflags |= SF_MONSTER_SIGHT; // Lazarus: Don't add trigger spawned monsters until they are actually spawned if (!(self->monsterinfo.aiflags & AI_GOOD_GUY) && !(self->spawnflags & SF_MONSTER_TRIGGER_SPAWN)) level.total_monsters++; self->nextthink = level.time + FRAMETIME; self->svflags |= SVF_MONSTER; self->s.renderfx |= RF_FRAMELERP; self->air_finished = level.time + 12; self->use = monster_use; // Lazarus - don't reset max_health unnecessarily if(!self->max_health) self->max_health = self->health; if (self->health < (self->max_health / 2)) self->s.skinnum |= 1; else self->s.skinnum &= ~1; self->clipmask = MASK_MONSTERSOLID; if (self->s.skinnum < 1) // Knightmare added self->s.skinnum = 0; self->deadflag = DEAD_NO; self->svflags &= ~SVF_DEADMONSTER; if(self->monsterinfo.flies > 1.0) { self->s.effects |= EF_FLIES; self->s.sound = gi.soundindex ("infantry/inflies1.wav"); } // Lazarus if(self->health <=0) { self->svflags |= SVF_DEADMONSTER; self->movetype = MOVETYPE_TOSS; self->takedamage = DAMAGE_YES; self->monsterinfo.pausetime = 100000000; self->monsterinfo.aiflags &= ~AI_RESPAWN_FINDPLAYER; if(self->max_health > 0) { // This must be a dead monster who changed levels // via trigger_transition self->nextthink = 0; self->deadflag = DEAD_DEAD; } if(self->s.effects & EF_FLIES && self->monsterinfo.flies <= 1.0) { self->think = M_FliesOff; self->nextthink = level.time + 1 + random()*60; } return true; } else { // make sure red shell is turned off in case medic got confused: self->monsterinfo.aiflags &= ~AI_RESURRECTING; self->svflags &= ~SVF_DEADMONSTER; self->takedamage = DAMAGE_AIM; } if (!self->monsterinfo.checkattack) self->monsterinfo.checkattack = M_CheckAttack; VectorCopy (self->s.origin, self->s.old_origin); if (st.item) { self->item = FindItemByClassname (st.item); if (!self->item) gi.dprintf("%s at %s has bad item: %s\n", self->classname, vtos(self->s.origin), st.item); } // randomize what frame they start on // Lazarus: preserve frame if set for monsters changing levels if (!self->s.frame) { if (self->monsterinfo.currentmove) self->s.frame = self->monsterinfo.currentmove->firstframe + (rand() % (self->monsterinfo.currentmove->lastframe - self->monsterinfo.currentmove->firstframe + 1)); } return true; } void monster_start_go (edict_t *self) { vec3_t v; if (self->health <= 0) { if (self->max_health <= 0) InitiallyDead(self); return; } // Lazarus: move_origin for func_monitor if(!VectorLength(self->move_origin)) VectorSet(self->move_origin,0,0,self->viewheight); // check for target to point_combat and change to combattarget if (self->target) { qboolean notcombat; qboolean fixup; edict_t *target; target = NULL; notcombat = false; fixup = false; while ((target = G_Find (target, FOFS(targetname), self->target)) != NULL) { if (strcmp(target->classname, "point_combat") == 0) { self->combattarget = self->target; fixup = true; } else { notcombat = true; } } if (notcombat && self->combattarget) gi.dprintf("%s at %s has target with mixed types\n", self->classname, vtos(self->s.origin)); if (fixup) self->target = NULL; } // validate combattarget if (self->combattarget) { edict_t *target; target = NULL; while ((target = G_Find (target, FOFS(targetname), self->combattarget)) != NULL) { if (strcmp(target->classname, "point_combat") != 0) { gi.dprintf("%s at (%i %i %i) has a bad combattarget %s : %s at (%i %i %i)\n", self->classname, (int)self->s.origin[0], (int)self->s.origin[1], (int)self->s.origin[2], self->combattarget, target->classname, (int)target->s.origin[0], (int)target->s.origin[1], (int)target->s.origin[2]); } } } if (self->target) { self->goalentity = self->movetarget = G_PickTarget(self->target); if (!self->movetarget) { gi.dprintf ("%s can't find target %s at %s\n", self->classname, self->target, vtos(self->s.origin)); self->target = NULL; self->monsterinfo.pausetime = 100000000; self->monsterinfo.stand (self); } else if (strcmp (self->movetarget->classname, "path_corner") == 0) { // Lazarus: Don't wipe out target for trigger spawned monsters // that aren't triggered yet if( ! (self->spawnflags & SF_MONSTER_TRIGGER_SPAWN) ) { VectorSubtract (self->goalentity->s.origin, self->s.origin, v); self->ideal_yaw = self->s.angles[YAW] = vectoyaw(v); self->monsterinfo.walk (self); self->target = NULL; } } else { self->goalentity = self->movetarget = NULL; self->monsterinfo.pausetime = 100000000; self->monsterinfo.stand (self); } } else { self->monsterinfo.pausetime = 100000000; self->monsterinfo.stand (self); } self->think = monster_think; self->nextthink = level.time + FRAMETIME; } void walkmonster_start_go (edict_t *self) { if (!(self->spawnflags & SF_MONSTER_TRIGGER_SPAWN) && level.time < 1) { M_droptofloor (self); if (self->groundentity) if (!M_walkmove (self, 0, 0)) gi.dprintf ("%s in solid at %s\n", self->classname, vtos(self->s.origin)); } if (!self->yaw_speed) self->yaw_speed = 20; self->viewheight = 25; monster_start_go (self); if (self->spawnflags & SF_MONSTER_TRIGGER_SPAWN) monster_triggered_start (self); } void walkmonster_start (edict_t *self) { self->think = walkmonster_start_go; monster_start (self); } void flymonster_start_go (edict_t *self) { if (!M_walkmove (self, 0, 0)) gi.dprintf ("%s in solid at %s\n", self->classname, vtos(self->s.origin)); if (!self->yaw_speed) self->yaw_speed = 10; self->viewheight = 25; self->monsterinfo.flies = 0.0; monster_start_go (self); if (self->spawnflags & SF_MONSTER_TRIGGER_SPAWN) monster_triggered_start (self); } void flymonster_start (edict_t *self) { self->flags |= FL_FLY; self->think = flymonster_start_go; monster_start (self); } void swimmonster_start_go (edict_t *self) { if (!self->yaw_speed) self->yaw_speed = 10; self->viewheight = 10; monster_start_go (self); if (self->spawnflags & SF_MONSTER_TRIGGER_SPAWN) monster_triggered_start (self); } void swimmonster_start (edict_t *self) { self->flags |= FL_SWIM; self->think = swimmonster_start_go; monster_start (self); } //=============================================================== // Following functions unique to Lazarus void InitiallyDead (edict_t *self) { int damage; if(self->max_health > 0) return; // gi.dprintf("InitiallyDead on %s at %s\n",self->classname,vtos(self->s.origin)); // initially dead bad guys shouldn't count against totals if((self->max_health <= 0) && !(self->monsterinfo.aiflags & AI_GOOD_GUY)) { level.total_monsters--; if(self->deadflag != DEAD_DEAD) level.killed_monsters--; } if(self->deadflag != DEAD_DEAD) { damage = 1 - self->health; self->health = 1; T_Damage (self, world, world, vec3_origin, self->s.origin, vec3_origin, damage, 0, DAMAGE_NO_ARMOR, 0); if(self->svflags & SVF_MONSTER) { self->svflags |= SVF_DEADMONSTER; self->think = monster_think; self->nextthink = level.time + FRAMETIME; } } gi.linkentity(self); } #define MAX_SKINS 24 //max is 32, but we only need 24 #define MAX_SKINNAME 64 #ifdef _WIN32 #include <direct.h> #else #include <unistd.h> #define _mkdir mkdir #endif #include "pak.h" int PatchMonsterModel (char *modelname) { cvar_t *gamedir; int j; int numskins; // number of skin entries char skins[MAX_SKINS][MAX_SKINNAME]; // skin entries char infilename[MAX_OSPATH]; char outfilename[MAX_OSPATH]; char *p; FILE *infile; FILE *outfile; dmdl_t model; // model header byte *data; // model data int datasize; // model data size (bytes) int newoffset; // model data offset (after skins) qboolean is_tank=false; qboolean is_soldier=false; // get game (moddir) name gamedir = gi.cvar("game", "", 0); if (!*gamedir->string) return 0; // we're in baseq2 sprintf (outfilename, "%s/%s", gamedir->string, modelname); if (outfile = fopen (outfilename, "rb")) { // output file already exists, move along fclose (outfile); // gi.dprintf ("PatchMonsterModel: Could not save %s, file already exists\n", outfilename); return 0; } numskins = 8; // special cases if(!strcmp(modelname,"models/monsters/tank/tris.md2")) { is_tank = true; numskins = 16; } else if(!strcmp(modelname,"models/monsters/soldier/tris.md2")) { is_soldier = true; numskins = 24; } for (j=0; j<numskins; j++) { memset (skins[j], 0, MAX_SKINNAME); strcpy( skins[j], modelname ); p = strstr( skins[j], "tris.md2" ); if(!p) { fclose (outfile); gi.dprintf( "Error patching %s\n",modelname); return 0; } *p = 0; if(is_soldier) { switch (j) { case 0: strcat (skins[j], "skin_lt.pcx"); break; case 1: strcat (skins[j], "skin_ltp.pcx"); break; case 2: strcat (skins[j], "skin.pcx"); break; case 3: strcat (skins[j], "pain.pcx"); break; case 4: strcat (skins[j], "skin_ss.pcx"); break; case 5: strcat (skins[j], "skin_ssp.pcx"); break; case 6: strcat (skins[j], "custom1_lt.pcx"); break; case 7: strcat (skins[j], "custompain1_lt.pcx"); break; case 8: strcat (skins[j], "custom1.pcx"); break; case 9: strcat (skins[j], "custompain1.pcx"); break; case 10: strcat (skins[j], "custom1_ss.pcx"); break; case 11: strcat (skins[j], "custompain1_ss.pcx"); break; case 12: strcat (skins[j], "custom2_lt.pcx"); break; case 13: strcat (skins[j], "custompain2_lt.pcx"); break; case 14: strcat (skins[j], "custom2.pcx"); break; case 15: strcat (skins[j], "custompain2.pcx"); break; case 16: strcat (skins[j], "custom2_ss.pcx"); break; case 17: strcat (skins[j], "custompain2_ss.pcx"); break; case 18: strcat (skins[j], "custom3_lt.pcx"); break; case 19: strcat (skins[j], "custompain3_lt.pcx"); break; case 20: strcat (skins[j], "custom3.pcx"); break; case 21: strcat (skins[j], "custompain3.pcx"); break; case 22: strcat (skins[j], "custom3_ss.pcx"); break; case 23: strcat (skins[j], "custompain3_ss.pcx"); break; } } else if(is_tank) { switch (j) { case 0: strcat (skins[j], "skin.pcx"); break; case 1: strcat (skins[j], "pain.pcx"); break; case 2: strcat (skins[j], "../ctank/skin.pcx"); break; case 3: strcat (skins[j], "../ctank/pain.pcx"); break; case 4: strcat (skins[j], "custom1.pcx"); break; case 5: strcat (skins[j], "custompain1.pcx"); break; case 6: strcat (skins[j], "../ctank/custom1.pcx"); break; case 7: strcat (skins[j], "../ctank/custompain1.pcx"); break; case 8: strcat (skins[j], "custom2.pcx"); break; case 9: strcat (skins[j], "custompain2.pcx"); break; case 10: strcat (skins[j], "../ctank/custom2.pcx"); break; case 11: strcat (skins[j], "../ctank/custompain2.pcx"); break; case 12: strcat (skins[j], "custom3.pcx"); break; case 13: strcat (skins[j], "custompain3.pcx"); break; case 14: strcat (skins[j], "../ctank/custom3.pcx"); break; case 15: strcat (skins[j], "../ctank/custompain3.pcx"); break; } } else { switch (j) { case 0: strcat (skins[j], "skin.pcx"); break; case 1: strcat (skins[j], "pain.pcx"); break; case 2: strcat (skins[j], "custom1.pcx"); break; case 3: strcat (skins[j], "custompain1.pcx"); break; case 4: strcat (skins[j], "custom2.pcx"); break; case 5: strcat (skins[j], "custompain2.pcx"); break; case 6: strcat (skins[j], "custom3.pcx"); break; case 7: strcat (skins[j], "custompain3.pcx"); break; } } } // load original model sprintf (infilename, "baseq2/%s", modelname); if ( !(infile = fopen (infilename, "rb")) ) { // If file doesn't exist on user's hard disk, it must be in // pak0.pak pak_header_t pakheader; pak_item_t pakitem; FILE *fpak; int k, numitems; fpak = fopen("baseq2/pak0.pak","rb"); if(!fpak) { cvar_t *cddir; char pakfile[MAX_OSPATH]; cddir = gi.cvar("cddir", "", 0); sprintf(pakfile,"%s/baseq2/pak0.pak",cddir->string); fpak = fopen(pakfile,"rb"); if(!fpak) { gi.dprintf("PatchMonsterModel: Cannot find pak0.pak\n"); return 0; } } fread(&pakheader,1,sizeof(pak_header_t),fpak); numitems = pakheader.dsize/sizeof(pak_item_t); fseek(fpak,pakheader.dstart,SEEK_SET); data = NULL; for(k=0; k<numitems && !data; k++) { fread(&pakitem,1,sizeof(pak_item_t),fpak); if(!stricmp(pakitem.name,modelname)) { fseek(fpak,pakitem.start,SEEK_SET); fread(&model, sizeof(dmdl_t), 1, fpak); datasize = model.ofs_end - model.ofs_skins; if ( !(data = malloc (datasize)) ) // make sure freed locally { fclose(fpak); gi.dprintf ("PatchMonsterModel: Could not allocate memory for model\n"); return 0; } fread (data, sizeof (byte), datasize, fpak); } } fclose(fpak); if(!data) { gi.dprintf("PatchMonsterModel: Could not find %s in baseq2/pak0.pak\n",modelname); return 0; } } else { fread (&model, sizeof (dmdl_t), 1, infile); datasize = model.ofs_end - model.ofs_skins; if ( !(data = malloc (datasize)) ) // make sure freed locally { gi.dprintf ("PatchMonsterModel: Could not allocate memory for model\n"); return 0; } fread (data, sizeof (byte), datasize, infile); fclose (infile); } // update model info model.num_skins = numskins; newoffset = numskins * MAX_SKINNAME; model.ofs_st += newoffset; model.ofs_tris += newoffset; model.ofs_frames += newoffset; model.ofs_glcmds += newoffset; model.ofs_end += newoffset; // save new model sprintf (outfilename, "%s/models", gamedir->string); // make some dirs if needed _mkdir (outfilename); strcat (outfilename,"/monsters"); _mkdir (outfilename); sprintf (outfilename, "%s/%s", gamedir->string, modelname); p = strstr(outfilename,"/tris.md2"); *p = 0; _mkdir (outfilename); sprintf (outfilename, "%s/%s", gamedir->string, modelname); if ( !(outfile = fopen (outfilename, "wb")) ) { // file couldn't be created for some other reason gi.dprintf ("PatchMonsterModel: Could not save %s\n", outfilename); free (data); return 0; } fwrite (&model, sizeof (dmdl_t), 1, outfile); fwrite (skins, sizeof (char), newoffset, outfile); fwrite (data, sizeof (byte), datasize, outfile); fclose (outfile); gi.dprintf ("PatchMonsterModel: Saved %s\n", outfilename); free (data); return 1; } void HintTestNext (edict_t *self, edict_t *hint) { edict_t *next=NULL; edict_t *e; vec3_t dir; self->monsterinfo.aiflags &= ~AI_HINT_TEST; if(self->goalentity == hint) self->goalentity = NULL; if(self->movetarget == hint) self->movetarget = NULL; if(self->monsterinfo.pathdir == 1) { if(hint->hint_chain) next = hint->hint_chain; else self->monsterinfo.pathdir = -1; } if(self->monsterinfo.pathdir == -1) { e = hint_chain_starts[hint->hint_chain_id]; while(e) { if(e->hint_chain == hint) { next = e; break; } e = e->hint_chain; } } if(!next) { self->monsterinfo.pathdir = 1; next = hint->hint_chain; } if(next) { self->hint_chain_id = next->hint_chain_id; VectorSubtract(next->s.origin, self->s.origin, dir); self->ideal_yaw = vectoyaw(dir); self->goalentity = self->movetarget = next; self->monsterinfo.pausetime = 0; self->monsterinfo.aiflags = AI_HINT_TEST; // run for it self->monsterinfo.run (self); gi.dprintf("%s (%s): Reached hint_path %s,\nsearching for hint_path %s at %s. %s\n", self->classname, (self->targetname ? self->targetname : "<noname>"), (hint->targetname ? hint->targetname : "<noname>"), (next->targetname ? next->targetname : "<noname>"), vtos(next->s.origin), (visible(self,next) ? "I see it." : "I don't see it.")); } else { self->monsterinfo.pausetime = level.time + 100000000; self->monsterinfo.stand (self); gi.dprintf("%s (%s): Error finding next/previous hint_path from %s at %s.\n", self->classname, (self->targetname ? self->targetname : "<noname>"), (hint->targetname ? hint->targetname : "<noname>"), vtos(hint->s.origin)); } } int HintTestStart (edict_t *self) { edict_t *e; edict_t *hint=NULL; float dist; vec3_t dir; int i; float bestdistance=99999; if (!hint_chains_exist) return 0; for(i=game.maxclients+1; i<globals.num_edicts; i++) { e = &g_edicts[i]; if(!e->inuse) continue; if(Q_stricmp(e->classname,"hint_path")) continue; if(!visible(self,e)) continue; if(!canReach(self,e)) continue; VectorSubtract(e->s.origin,self->s.origin,dir); dist = VectorLength(dir); if(dist < bestdistance) { hint = e; bestdistance = dist; } } if(hint) { self->hint_chain_id = hint->hint_chain_id; if(!self->monsterinfo.pathdir) self->monsterinfo.pathdir = 1; VectorSubtract(hint->s.origin, self->s.origin, dir); self->ideal_yaw = vectoyaw(dir); self->enemy = self->oldenemy = NULL; self->goalentity = self->movetarget = hint; self->monsterinfo.pausetime = 0; self->monsterinfo.aiflags = AI_HINT_TEST; // run for it self->monsterinfo.run (self); return 1; } else return -1; } void reynard_thinkforward(edict_t *self) { if (self->s.frame < 64) self->s.frame++; if (self->s.frame==8) { //disarm player. edict_t *player; player = &g_edicts[1]; if (player) { player->client->pers.inventory[ITEM_INDEX(FindItem("No Weapon"))] = 1; player->client->newweapon = FindItem ("No Weapon"); if (player->client->pers.inventory[ITEM_INDEX(FindItem("BFG10K"))] > 0) player->client->pers.inventory[ITEM_INDEX(FindItem("BFG10K"))] = 0; } } if (self->s.frame==9) { gi.sound (self, CHAN_BODY, gi.soundindex("objects/ching.wav"), 1.0, ATTN_NORM, 0); } if (self->s.frame==10) { //attach glass model to reynard. self->s.modelindex2 = gi.modelindex ("models/monsters/reynard/glass.md2"); } else if (self->s.frame==16) self->s.skinnum=1; else if ((self->s.frame==17)||(self->s.frame==26)||(self->s.frame==35)||(self->s.frame==44)) gi.sound (self, CHAN_BODY, gi.soundindex("monsters/gulp.wav"), 1, ATTN_NORM, 0); else if (self->s.frame==46) self->s.skinnum=0; else if (self->s.frame==47) self->s.modelindex2 = NULL; else if (self->s.frame==49) { vec3_t forward,right,org; int tempevent; AngleVectors (self->s.angles, forward, right, NULL); VectorCopy(self->s.origin,org); org[2] +=42.5; VectorMA(org, 7, right, org); VectorMA(org, 5, forward, org); tempevent = TE_BURPGAS; gi.WriteByte (svc_temp_entity); gi.WriteByte (tempevent); gi.WritePosition (org); gi.WriteDir (vec3_origin); gi.multicast (org, MULTICAST_ALL); gi.sound (self, CHAN_BODY, gi.soundindex("monsters/burp.wav"), 1, ATTN_NORM, 0); self->s.skinnum=1; } else if (self->s.frame==63) { if (self->s.skinnum != 0) { edict_t *player; self->s.skinnum=0; player = &g_edicts[1]; if (player) G_UseTargets (self,player); } //gi.dprintf("fdsaflkas\n"); } self->think = reynard_thinkforward; self->nextthink = level.time + FRAMETIME; } void reynard_use(edict_t *self) { if (self->s.frame != 0) return; self->think = reynard_thinkforward; self->nextthink = level.time + FRAMETIME; } void SP_monster_reynard(edict_t *self) { if (!self->startframe) self->startframe=0; if (!self->framenumbers) self->framenumbers=1; self->s.modelindex = gi.modelindex ("models/monsters/reynard/tris.md2"); /* if (self->pathtarget) { sprintf(modelname, "models/%s", self->pathtarget); self->s.modelindex2 = gi.modelindex (modelname); }*/ if (!self->style) self->style = 0; self->solid = SOLID_NOT; self->use = reynard_use; self->takedamage = DAMAGE_NO; gi.linkentity (self); } void guard_think(edict_t *self) { edict_t *player; player = &g_edicts[1]; if (player) { //found player. //face the player. vec3_t playervec; float ymin,ymax; VectorCopy (player->s.origin, playervec); playervec[2] += 14; //they focus on your head. VectorSubtract (playervec, self->s.origin, playervec); vectoangles(playervec,playervec); ymin = self->pos2[1] - self->radius; ymax = self->pos2[1] + self->radius; if (playervec[YAW] > ymax || playervec[YAW] < ymin) { //player out of fov. snap back to default position. VectorCopy(self->pos2,playervec); } VectorCopy (playervec, self->s.angles); } self->think = guard_think; self->nextthink = level.time + FRAMETIME; } void SP_monster_guard(edict_t *self) { edict_t *zbody; edict_t *player; player = &g_edicts[1]; // Gotta be, since this is SP only //BC baboo if (skill->value >= 2) { self->s.skinnum = 7; } //GravityBone hack. if(Q_stricmp(level.mapname, "parlo1") == 0) self->s.modelindex = gi.modelindex ("models/monsters/guard/tris.md2"); else self->s.modelindex = gi.modelindex ("models/monsters/npc/head.md2"); self->solid = SOLID_NOT; //self->use = reynard_use; self->takedamage = DAMAGE_NO; if (!self->radius) self->radius = 89; if (!self->attenuation) self->attenuation = 38; self->s.origin[2] += self->attenuation; VectorCopy(self->s.angles, self->pos2); self->think = guard_think; self->nextthink = level.time + FRAMETIME; gi.linkentity (self); if (!self->startframe && (Q_stricmp(level.mapname, "parlo1") != 0)) self->startframe = 115; if (skill->value >= 2) { //spawn mathman audio dummy. edict_t *mathEnt; mathEnt = G_Spawn(); VectorCopy (self->s.origin, mathEnt->s.origin); mathEnt->s.origin[2] += 1; SP_target_mathaudio(mathEnt); } zbody = G_Spawn(); if(Q_stricmp(level.mapname, "parlo1") == 0) gi.setmodel (zbody, "models/monsters/guard/body.md2"); else gi.setmodel (zbody, "models/monsters/npc/tris.md2"); zbody->s.frame = self->startframe; zbody->solid = SOLID_NOT; zbody->takedamage = DAMAGE_NO; zbody->s.origin[0] = self->s.origin[0]; zbody->s.origin[1] = self->s.origin[1]; zbody->s.origin[2] = self->s.origin[2]-38; zbody->s.angles[1] = self->s.angles[1]; zbody->s.skinnum = self->s.skinnum; gi.linkentity (zbody); } qboolean infront2 (edict_t *self, edict_t *other) { vec3_t vec; float dot; vec3_t forward; if (!self || !other) // Knightmare- crash protect return false; AngleVectors (self->pos2, forward, NULL, NULL); VectorSubtract (other->s.origin, self->s.origin, vec); VectorNormalize (vec); dot = DotProduct (vec, forward); if (dot > -0.5) return true; return false; } void dinnerguest_think(edict_t *self) { edict_t *player; player = &g_edicts[1]; if (player) { if (infront2(self,player)) { //face the player. vec3_t playervec; float ymin,ymax; VectorCopy (player->s.origin, playervec); playervec[2] += 14; //they focus on your head. VectorSubtract (playervec, self->s.origin, playervec); vectoangles(playervec,playervec); VectorCopy (playervec, self->s.angles); } else { VectorCopy (self->pos2, self->s.angles); } //make heads rumble and roll. if ((rand()&3 == 0) || (self->bobframe > 5)) { VectorCopy(self->offset,self->s.origin); self->bobframe = 0; self->s.angles[2] = 0.0; } else { self->s.origin[0] += -0.5 + random() * 1.0; self->s.origin[1] += -0.5 + random() * 1.0; self->s.origin[2] += -1.0 + random() * 2.0; //nice bobble-head effect self->s.angles[2] += -10.0 + random() * 20.0; self->bobframe++; } } self->think = dinnerguest_think; self->nextthink = level.time + FRAMETIME; } void SP_monster_dinnerguest(edict_t *self) { edict_t *zbody; int skin; self->s.modelindex = gi.modelindex ("models/monsters/dinnerguest/head.md2"); self->solid = SOLID_NOT; //self->use = reynard_use; self->takedamage = DAMAGE_NO; self->s.origin[2] += 36; //keep base angle VectorCopy(self->s.angles, self->pos2); //keep base origin VectorCopy(self->s.origin, self->offset); self->think = dinnerguest_think; self->nextthink = level.time + FRAMETIME; self->s.renderfx |= self->renderfx; gi.linkentity (self); zbody = G_Spawn(); gi.setmodel (zbody, "models/monsters/dinnerguest/body.md2"); zbody->solid = SOLID_NOT; zbody->takedamage = DAMAGE_NO; zbody->s.origin[0] = self->s.origin[0]; zbody->s.origin[1] = self->s.origin[1]; zbody->s.origin[2] = self->s.origin[2]-36; zbody->s.angles[1] = self->s.angles[1]; zbody->s.renderfx |= self->renderfx; if (self->s.skinnum == -1) { skin = rand()&3; self->s.skinnum = skin; zbody->s.skinnum = skin; } gi.linkentity (zbody); } void zsmoke_think1(edict_t *self) { int tempevent; vec3_t org; vec3_t forward,right; edict_t *tempent; tempent = G_Find (NULL, FOFS(targetname), "olive1"); VectorCopy(tempent->s.origin,self->s.origin); VectorCopy(tempent->s.angles,self->s.angles); tempevent = TE_CIGSMOKE; AngleVectors (self->s.angles, forward, right, NULL); VectorCopy(self->s.origin,org); if (self->style==0) { org[2] +=38.1; VectorMA(org, 0.8, right, org); VectorMA(org, 10.1, forward, org); } else if (self->style==1) { org[2] +=31.9; VectorMA(org, 0.6, right, org); VectorMA(org, 12.9, forward, org); } else if (self->style==2) { org[2] +=11.9; VectorMA(org, 9.4, right, org); VectorMA(org, 8.7, forward, org); } else { self->think = G_FreeEdict; self->nextthink = level.time + FRAMETIME; } gi.WriteByte (svc_temp_entity); gi.WriteByte (tempevent); gi.WritePosition (org); gi.WriteDir (vec3_origin); gi.multicast (org, MULTICAST_ALL); gi.WriteByte (svc_temp_entity); gi.WriteByte (tempevent); gi.WritePosition (org); gi.WriteDir (vec3_origin); gi.multicast (org, MULTICAST_ALL); if (self->style < 3) { self->think = zsmoke_think1; self->nextthink = level.time + FRAMETIME; } } void zsmoke_think(edict_t *self) { int tempevent; vec3_t org; vec3_t forward,right; tempevent = TE_CIGSMOKE; AngleVectors (self->s.angles, forward, right, NULL); VectorCopy(self->s.origin,org); org[2] +=18.2; VectorMA(org, 11, right, org); VectorMA(org, 4.7, forward, org); gi.WriteByte (svc_temp_entity); gi.WriteByte (tempevent); gi.WritePosition (org); gi.WriteDir (vec3_origin); gi.multicast (org, MULTICAST_PVS); self->think = zsmoke_think; self->nextthink = level.time + FRAMETIME; } void zsmoke_think2(edict_t *self) { int tempevent; vec3_t org; vec3_t forward,right; tempevent = TE_CIGSMOKE; AngleVectors (self->s.angles, forward, right, NULL); VectorCopy(self->s.origin,org); org[2] +=38.1; VectorMA(org, 0.8, right, org); VectorMA(org, 17.6, forward, org); gi.WriteByte (svc_temp_entity); gi.WriteByte (tempevent); gi.WritePosition (org); gi.WriteDir (vec3_origin); gi.multicast (org, MULTICAST_PVS); self->think = zsmoke_think2; self->nextthink = level.time + FRAMETIME; } void zbigsmoke_think(edict_t *self) { int tempevent; vec3_t org; vec3_t forward,right; tempevent = TE_CIGBIGSMOKE; AngleVectors (self->s.angles, forward, right, NULL); VectorCopy(self->s.origin,org); org[2] +=31.7; VectorMA(org, 3.4, right, org); VectorMA(org, 14, forward, org); //gi.dprintf("bigsmoke\n"); gi.WriteByte (svc_temp_entity); gi.WriteByte (tempevent); gi.WritePosition (org); gi.WriteDir (vec3_origin); gi.multicast (org, MULTICAST_ALL); self->think = zbigsmoke_think; self->nextthink = level.time + FRAMETIME; } void faceangle(edict_t *self, char *targ) { edict_t *tempent; tempent = G_Find (NULL, FOFS(targetname), targ); if (tempent) { vec3_t playervec; VectorCopy (tempent->s.origin, playervec); playervec[2] = self->s.origin[2]; VectorSubtract (playervec, self->s.origin, playervec); vectoangles(playervec,playervec); VectorCopy (playervec, self->s.angles); } else gi.dprintf("ERROR: couldn't find %s\n",targ); } void olive_freeplayer(edict_t *self) { edict_t *player; //player rises up from the ground. just pop up player origin. player = &g_edicts[1]; if (player) { player->s.origin[2] += 42; } //destroy this olive, make the next olive. self->think = G_FreeEdict; self->nextthink = level.time + FRAMETIME; } void olive_windowjump(edict_t *self) { if (self->s.frame < 41) { self->s.frame++; self->think = olive_windowjump; self->nextthink = level.time + FRAMETIME; //hide camera. if (self->s.frame > 37) self->s.modelindex3 = gi.modelindex("sprites/point.sp2"); } else { //has crossed the window threshold edict_t *player; player = &g_edicts[1]; if (player) { //player->s.origin[2] += 41; player->client->ps.stats[STAT_FREEZE] = 0; gi.sound (player, CHAN_WEAPON, gi.soundindex("player/pain3.wav"), 1.0, ATTN_NONE, 0); self->s.origin[2] -= 32; self->think = olive_freeplayer; self->nextthink = level.time + 0.3; } } } void olive_runtowindow(edict_t *self) { edict_t *tempent; if (self->s.frame < 6) self->s.frame++; else self->s.frame=3; tempent = G_Find (NULL, FOFS(targetname), "olivewindow1"); if (tempent) { vec3_t tempentvec; float tempentdist; VectorSubtract (tempent->s.origin, self->s.origin, tempentvec); tempentdist = VectorLength(tempentvec); if (tempentdist < 10) { VectorSet(self->velocity,0,0,0); self->s.frame = 29; //hide gun. self->s.modelindex2 = gi.modelindex("sprites/point.sp2"); self->think = olive_windowjump; self->nextthink = level.time + FRAMETIME; } else { self->think = olive_runtowindow; self->nextthink = level.time + FRAMETIME; } } } void olive_gotowindow(edict_t *self) { edict_t *tempent; vec3_t playervec,forward; tempent = G_Find (NULL, FOFS(targetname), "olivewindow1"); if (tempent) { self->s.origin[2] += 1; self->movetype = MOVETYPE_FLY; VectorCopy (tempent->s.origin, playervec); playervec[2] = self->s.origin[2]; VectorSubtract (playervec, self->s.origin, playervec); vectoangles(playervec,playervec); VectorCopy (playervec, self->s.angles); AngleVectors (self->s.angles, forward, NULL, NULL); VectorCopy(forward,self->movedir); VectorScale (forward, 96, self->velocity); } tempent = G_Find (NULL, FOFS(targetname), "viewlock4"); if (tempent) { tempent->use (tempent, self, self); } self->think = olive_runtowindow; self->nextthink = level.time + FRAMETIME; } void olive_glassbreak(edict_t *self) { edict_t *tempent; tempent = G_Find (NULL, FOFS(targetname), "glasssound1"); if (tempent) { tempent->use (tempent, self, self); } tempent = G_Find (NULL, FOFS(targetname), "raintrigger"); if (tempent) { tempent->use (tempent, self, self); } //turn off the existing view lock. tempent = G_Find (NULL, FOFS(targetname), "windowclip1"); if (tempent) { tempent->think = G_FreeEdict; tempent->nextthink = level.time + FRAMETIME; } tempent = G_Find (NULL, FOFS(targetname), "glassexplode1"); if (tempent) { tempent->use (tempent, self, self); } tempent = G_Find (NULL, FOFS(targetname), "glassexplode2"); if (tempent) { tempent->use (tempent, self, self); } tempent = G_Find (NULL, FOFS(targetname), "glass1"); if (tempent) { tempent->think = G_FreeEdict; tempent->nextthink = level.time + FRAMETIME; } tempent = G_Find (NULL, FOFS(targetname), "glass2"); if (tempent) { tempent->think = G_FreeEdict; tempent->nextthink = level.time + FRAMETIME; } self->think = olive_gotowindow; self->nextthink = level.time + FRAMETIME; } void olive_fire1(edict_t *self) { vec3_t forward,right,org; AngleVectors (self->s.angles, forward, right, NULL); VectorCopy(self->s.origin,org); org[2] +=39.6; VectorMA(org, -2.3, right, org); VectorMA(org, 34.7, forward, org); gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_SHOTGUN); gi.WritePosition (org); gi.WriteDir (forward); gi.multicast (org, MULTICAST_PVS); gi.sound (self, CHAN_WEAPON, gi.soundindex("weapons/pistol.wav"), 1.0, ATTN_NONE, 0); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (MZ2_GUNNER_GRENADE_1); gi.multicast (self->s.origin, MULTICAST_PVS); self->style++; if (self->style < 3) { self->think = olive_fire1; self->nextthink = level.time + 0.25; } else { edict_t *tempent; //turn off the existing view lock. tempent = G_Find (NULL, FOFS(targetname), "lockview"); if (tempent) { tempent->use (tempent, self, self); } //turn on the next view lock. tempent = G_Find (NULL, FOFS(targetname), "viewlock4"); if (tempent) { gi.sound(self, CHAN_BODY, gi.soundindex("weapons/whoosh.wav"), 1.0, ATTN_NORM, 0); tempent->use (tempent, self, self); self->think = olive_glassbreak; self->nextthink = level.time + 0.1; } } } void olive_stand2(edict_t *self) { if (self->s.frame < 28) { if (self->s.frame==25) { edict_t *player; vec3_t playervec; edict_t *tempent; //turn olive to look at the window. player = G_Find (NULL, FOFS(targetname), "windowtarget"); VectorCopy (player->s.origin, playervec); playervec[2] = self->s.origin[2]; VectorSubtract (playervec, self->s.origin, playervec); vectoangles(playervec,playervec); VectorCopy (playervec, self->s.angles); gi.sound(self, CHAN_AUTO, gi.soundindex("weapons/w_pkup.wav"), 1.0, ATTN_NORM, 0); } self->s.frame++; self->think = olive_stand2; self->nextthink = level.time + 0.1; } else { self->style=0; self->think = olive_fire1; self->nextthink = level.time + 0.5; } } void olive_stand1(edict_t *self) { //standing up. vec3_t forward,org; AngleVectors (self->s.angles, forward, NULL, NULL); VectorCopy(self->s.origin,org); VectorMA(org, -14, forward, org); VectorCopy(org,self->s.origin); self->s.frame = 25; gi.sound(self, CHAN_AUTO, gi.soundindex("monsters/wah4.wav"), 1.0, ATTN_NORM, 0); self->think = olive_stand2; self->nextthink = level.time + 2.5; } void olive_lean4(edict_t *self) { self->s.frame = 24; self->think = olive_stand1; self->nextthink = level.time + 1.0; } void olive_lean3(edict_t *self) { gi.sound(self, CHAN_AUTO, gi.soundindex("weapons/card_up.wav"), 1.0, ATTN_NORM, 0); self->think = olive_lean4; self->nextthink = level.time + 0.8; self->s.modelindex3 = gi.modelindex ("models/objects/camera/tris.md2"); } void olive_lean2(edict_t *self) { gi.sound(self, CHAN_AUTO, gi.soundindex("monsters/search.wav"), 1.0, ATTN_NORM, 0); self->think = olive_lean3; self->nextthink = level.time + 0.7; } void olive_lean1(edict_t *self) { if (self->s.frame < 22) { self->s.frame++; if (self->s.frame==17) { vec3_t forward,org; AngleVectors (self->s.angles, forward, NULL, NULL); VectorCopy(self->s.origin,org); VectorMA(org, 9, forward, org); VectorCopy(org,self->s.origin); } self->think = olive_lean1; self->nextthink = level.time + FRAMETIME; } else { self->think = olive_lean2; self->nextthink = level.time + 0.1; } } void olive_puff2(edict_t *self) { if (self->s.frame==12) { edict_t *tempent; tempent = G_Find (NULL, FOFS(targetname), "olivesmoke1"); if (tempent) tempent->style=3; tempent = G_Find (NULL, FOFS(targetname), "olivebigsmoke"); if (tempent) { tempent->think = G_FreeEdict; tempent->nextthink = level.time + FRAMETIME; } gi.sound(self, CHAN_AUTO, gi.soundindex("monsters/wah5.wav"), 1.0, ATTN_NORM, 0); } if (self->s.frame < 16) { self->s.frame++; self->think = olive_puff2; self->nextthink = level.time + FRAMETIME; } else { self->s.skinnum = 0; self->think = olive_lean1; self->nextthink = level.time + 2; } } void olive_puff1(edict_t *self) { edict_t *tempent; edict_t *zsmoke; self->s.skinnum = 1; self->s.frame=12; self->think = olive_puff2; self->nextthink = level.time + 2; gi.sound(self, CHAN_BODY, gi.soundindex("monsters/cig.wav"), 1.0, ATTN_NORM, 0); tempent = G_Find (NULL, FOFS(targetname), "olivesmoke1"); if (tempent) tempent->style=2; zsmoke = G_Spawn(); VectorCopy(self->s.origin, zsmoke->s.origin); VectorCopy(self->s.angles, zsmoke->s.angles); zsmoke->movetype = MOVETYPE_NONE; zsmoke->think = zbigsmoke_think; zsmoke->nextthink = level.time + FRAMETIME; zsmoke->targetname = "olivebigsmoke"; gi.linkentity (zsmoke); } void olive_kneel1(edict_t *self) { edict_t *player; vec3_t playervec; edict_t *tempent; self->s.frame=11; player = &g_edicts[1]; VectorCopy (player->s.origin, playervec); playervec[2] = self->s.origin[2]; VectorSubtract (playervec, self->s.origin, playervec); vectoangles(playervec,playervec); VectorCopy (playervec, self->s.angles); gi.sound(self, CHAN_BODY, gi.soundindex("weapons/whoosh.wav"), 0.6, ATTN_NORM, 0); tempent = G_Find (NULL, FOFS(targetname), "olivesmoke1"); if (tempent) tempent->style=1; self->think = olive_puff1; self->nextthink = level.time + 1.3; } void olive_walkthink(edict_t *self) { edict_t *player; vec3_t playervec; float playerdist; player = &g_edicts[1]; if (self->style==3) { if (self->s.frame > 9) self->s.frame=7; else self->s.frame++; } else { if (self->s.frame > 5) self->s.frame=3; else self->s.frame++; } if ((self->s.frame==3) || (self->s.frame==7)) gi.sound (self, CHAN_BODY, gi.soundindex("monsters/step1.wav"), 1.0, ATTN_NORM, 0); else if ((self->s.frame==5)||(self->s.frame==9)) gi.sound (self, CHAN_BODY, gi.soundindex("monsters/step2.wav"), 1.0, ATTN_NORM, 0); //stop moving. if (player) VectorSubtract (player->s.origin, self->s.origin, playervec); playerdist = VectorLength(playervec); //if (playerdist) // gi.dprintf("%f\n",playerdist); if (playerdist < 40) { self->s.frame=7; VectorSet(self->velocity,0,0,0); VectorCopy (player->s.origin, playervec); //playervec[2] += 14; //they focus on your head. playervec[2] = self->s.origin[2]; VectorSubtract (playervec, self->s.origin, playervec); vectoangles(playervec,playervec); VectorCopy (playervec, self->s.angles); self->think = olive_kneel1; self->nextthink = level.time + 1; } else { self->think = olive_walkthink; self->nextthink = level.time + 0.2; } } void olive_talkthink(edict_t *self) { if (self->health2 > 0) { self->health2--; self->think = olive_talkthink; self->nextthink = level.time + 1.4; } else { self->s.frame=1; } } void olive_action(edict_t *self, edict_t *other) { if ((self->health2 <= 0) && (self->s.frame==1)) { self->s.frame=2; self->health2 = 1; self->think = olive_talkthink; self->nextthink = level.time + FRAMETIME; if (self->count==0) gi.sound (self, CHAN_BODY, gi.soundindex("monsters/wah3.wav"), 1.0, ATTN_NORM, 0); else if (self->count==1) gi.sound (self, CHAN_BODY, gi.soundindex("monsters/wah4.wav"), 1.0, ATTN_NORM, 0); else gi.sound (self, CHAN_BODY, gi.soundindex("monsters/wah5.wav"), 1.0, ATTN_NORM, 0); self->count++; if (self->count >2) self->count=0; } } void olive_use (edict_t *self, edict_t *other, edict_t *activator) { vec3_t forward,right,org; edict_t *tempent; //self->use = NULL; if (self->solid != SOLID_NOT) { self->solid = SOLID_NOT; } if (self->style==0) { edict_t *player; player = &g_edicts[1]; self->style = 1; self->s.frame = 3; //disarm the player. remove everything. if (player->client->pers.inventory[ITEM_INDEX(FindItem("No Weapon"))] > 0) { player->client->pers.inventory[ITEM_INDEX(FindItem("No Weapon"))] = 1; } player->client->newweapon = FindItem ("No Weapon"); if (player->client->pers.inventory[ITEM_INDEX(FindItem("card"))] > 0) player->client->pers.inventory[ITEM_INDEX(FindItem("card"))] = 0; if (player->client->pers.inventory[ITEM_INDEX(FindItem("BFG10K"))] > 0) player->client->pers.inventory[ITEM_INDEX(FindItem("BFG10K"))] = 0; if (player->client->pers.inventory[ITEM_INDEX(FindItem("Blaster"))] > 0) player->client->pers.inventory[ITEM_INDEX(FindItem("Blaster"))] = 0; if (player->client->pers.inventory[ITEM_INDEX(FindItem("Shotgun"))] > 0) player->client->pers.inventory[ITEM_INDEX(FindItem("Shotgun"))] = 0; if (player->client->pers.inventory[ITEM_INDEX(FindItem("Machinegun"))] > 0) player->client->pers.inventory[ITEM_INDEX(FindItem("Machinegun"))] = 0; player->client->pers.selected_item = 0; //kill the book. tempent = G_Find (NULL, FOFS(targetname), "olivebook"); if (tempent) { tempent->think = G_FreeEdict; tempent->nextthink = level.time + FRAMETIME; } //kill the cig smoke. tempent = G_Find (NULL, FOFS(targetname), "olivesmoke"); if (tempent) { tempent->think = G_FreeEdict; tempent->nextthink = level.time + FRAMETIME; } //move olive to a better position. AngleVectors (self->s.angles, forward, right, NULL); VectorCopy(self->s.origin,org); VectorMA(org, -4, right, org); VectorMA(org, 6, forward, org); self->s.angles[1] = 240; VectorCopy(org,self->s.origin); //give her a gun. self->s.modelindex2 = gi.modelindex ("models/monsters/olive/olivegun.md2"); //self->s.modelindex2 = gi.modelindex ("models/monsters/olive/olivegun.md2"); //self->s.frame = 3; if (player) { //found player. //face the player. vec3_t playervec; //float ymin,ymax; //vec3_t oldangles; vec3_t forward; VectorCopy (player->s.origin, playervec); //playervec[2] += 14; //they focus on your head. playervec[2] = self->s.origin[2]; VectorSubtract (playervec, self->s.origin, playervec); vectoangles(playervec,playervec); VectorCopy (playervec, self->s.angles); AngleVectors (self->s.angles, forward, NULL, NULL); VectorCopy(forward,self->movedir); VectorScale (forward, 28, self->velocity); self->think = olive_walkthink; self->nextthink = level.time + FRAMETIME; } self->s.origin[2] -= 1; } else if ((self->style==1)||(self->style==2)) { //edict_t *zsmoke; edict_t *player; vec3_t org; vec3_t forward,right; if (self->style==1) { edict_t *zsmoke; zsmoke = G_Spawn(); VectorCopy(self->s.origin, zsmoke->s.origin); VectorCopy(self->s.angles, zsmoke->s.angles); zsmoke->movetype = MOVETYPE_NONE; zsmoke->think = zsmoke_think1; zsmoke->nextthink = level.time + FRAMETIME; zsmoke->targetname = "olivesmoke1"; gi.linkentity (zsmoke); } player = &g_edicts[1]; //zot //gi.dprintf("bang!!!!!!!\n"); G_UseTargets (self, player); //gi.sound (self, CHAN_WEAPON, gi.soundindex("weapons/pistol.wav"), 1.0, ATTN_NONE, 0); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (MZ2_GUNNER_GRENADE_1); gi.multicast (self->s.origin, MULTICAST_PVS); AngleVectors (self->s.angles, forward, right, NULL); VectorCopy(self->s.origin,org); org[2] +=37; VectorMA(org, -6, right, org); VectorMA(org, 30, forward, org); gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_SHOTGUN); gi.WritePosition (org); gi.WriteDir (vec3_origin); gi.multicast (org, MULTICAST_PVS); if (self->style==2) { gi.sound (player, CHAN_WEAPON, gi.soundindex("player/falldown.wav"), 1.0, ATTN_NONE, 0); player->s.origin[2] -= 40; tempent = G_Find (NULL, FOFS(targetname), "musictrack"); if (tempent) { tempent->use (tempent, self, self); } } self->style++; } } void SP_monster_olive(edict_t *self) { edict_t *zbody; edict_t *zsmoke; self->svflags |= SVF_DEADMONSTER; VectorSet(self->mins, -11, -11, 0.0); VectorSet(self->maxs, 11, 11, 53.0); self->health2 = 0; self->s.modelindex = gi.modelindex ("models/monsters/olive/tris.md2"); self->solid = SOLID_BBOX; self->style = 0; self->use = olive_use; self->takedamage = DAMAGE_NO; self->s.frame = 1; self->movetype = MOVETYPE_FLY; VectorCopy(self->s.angles, self->pos2); //self->think = zsmoke_think; //self->nextthink = level.time + 1; gi.linkentity (self); zsmoke = G_Spawn(); zsmoke->style = TE_EXPLOSION1; VectorCopy(self->s.origin, zsmoke->s.origin); VectorCopy(self->s.angles, zsmoke->s.angles); zsmoke->movetype = MOVETYPE_NONE; zsmoke->think = zsmoke_think; zsmoke->nextthink = level.time + 1; zsmoke->targetname = "olivesmoke"; gi.linkentity (zsmoke); zbody = G_Spawn(); gi.setmodel (zbody, "models/monsters/olive/olivebook.md2"); VectorCopy(self->s.origin, zbody->s.origin); VectorCopy(self->s.angles, zbody->s.angles); zbody->solid = SOLID_NOT; zbody->takedamage = DAMAGE_NO; zbody->targetname = "olivebook"; gi.linkentity (zbody); } void oliveshooter_fire1(edict_t *self) { vec3_t forward,right,org; AngleVectors (self->s.angles, forward, right, NULL); VectorCopy(self->s.origin,org); org[2] +=39.6; VectorMA(org, -2.3, right, org); VectorMA(org, 34.7, forward, org); gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_SHOTGUN); gi.WritePosition (org); gi.WriteDir (forward); gi.multicast (org, MULTICAST_PVS); gi.sound (self, CHAN_WEAPON, gi.soundindex("weapons/pistol.wav"), 1.0, ATTN_NONE, 0); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (MZ2_GUNNER_GRENADE_1); gi.multicast (self->s.origin, MULTICAST_PVS); } void oliveshooter_think(edict_t *self) { edict_t *player; player = &g_edicts[1]; if (player) { //face the player. vec3_t playervec; float ymin,ymax; VectorCopy (player->s.origin, playervec); playervec[2] -= 14; //they focus on your head. VectorSubtract (playervec, self->s.origin, playervec); vectoangles(playervec,playervec); //playervec[0]=0; //playervec[2]=0; VectorCopy (playervec, self->s.angles); } self->think = oliveshooter_think; self->nextthink = level.time + FRAMETIME; } void oliveshooter_use (edict_t *self, edict_t *other, edict_t *activator) { if (self->style==0) { self->style++; self->s.modelindex = gi.modelindex ("models/monsters/olive/tris.md2"); self->s.modelindex2 = gi.modelindex ("models/monsters/olive/olivegun.md2"); self->think = oliveshooter_think; self->nextthink = level.time + FRAMETIME; } else if (self->style==1) { edict_t *tempent; self->style++; oliveshooter_fire1(self); tempent = G_Find (NULL, FOFS(targetname), "musicoff"); if (tempent) { tempent->use (tempent, self, self); } gi.sound (self, CHAN_WEAPON, gi.soundindex("player/pain1.wav"), 1.0, ATTN_NONE, 0); } else { oliveshooter_fire1(self); } } void SP_monster_oliveshooter(edict_t *self) { self->svflags |= SVF_DEADMONSTER; VectorSet(self->mins, -11, -11, 0.0); VectorSet(self->maxs, 11, 11, 53.0); self->health2 = 0; //self->s.modelindex = gi.modelindex ("models/monsters/olive/tris.md2"); self->s.modelindex = gi.modelindex("sprites/point.sp2"); //self->s.modelindex2 = gi.modelindex ("models/monsters/olive/olivegun.md2"); self->solid = SOLID_BBOX; self->style = 0; self->use = oliveshooter_use; self->takedamage = DAMAGE_NO; self->s.frame = 28; self->movetype = MOVETYPE_FLY; VectorCopy(self->s.angles, self->pos2); //self->think = zsmoke_think; //self->nextthink = level.time + 1; gi.linkentity (self); } void goonfire1(edict_t *self) { vec3_t forward,right,org; AngleVectors (self->s.angles, forward, right, NULL); VectorCopy(self->s.origin,org); org[2] +=40; VectorMA(org, -2.3, right, org); VectorMA(org, 35, forward, org); gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_SHOTGUN); gi.WritePosition (org); gi.WriteDir (forward); gi.multicast (org, MULTICAST_PVS); gi.sound (self, CHAN_WEAPON, gi.soundindex("weapons/pistol.wav"), 1.0, ATTN_NORM, 0); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (MZ2_GUNNER_GRENADE_1); gi.multicast (self->s.origin, MULTICAST_PVS); } void goon_fire(edict_t *self) { if (self->s.frame < 5) { if (self->s.frame==1) { goonfire1(self); } self->s.frame++; self->think = goon_fire; self->nextthink = level.time + FRAMETIME; } else { self->s.frame=0; self->think = goon_fire; self->nextthink = level.time + FRAMETIME+ (0.7 * random()); } } void SP_monster_goon(edict_t *self) { self->svflags |= SVF_DEADMONSTER; VectorSet(self->mins, -11, -11, 0.0); VectorSet(self->maxs, 11, 11, 53.0); self->s.modelindex = gi.modelindex ("models/monsters/goon/tris.md2"); self->s.modelindex2 = gi.modelindex ("models/monsters/goon/goongun.md2"); self->solid = SOLID_BBOX; self->style = 0; self->takedamage = DAMAGE_NO; self->movetype = MOVETYPE_FLY; self->think = goon_fire; self->nextthink = level.time + 1; gi.linkentity (self); } void olivesmoker_bigsmoke(edict_t *self) { int tempevent; vec3_t org; vec3_t forward,right; tempevent = TE_CIGBIGSMOKE; AngleVectors (self->s.angles, forward, right, NULL); VectorCopy(self->s.origin,org); org[2] +=45.8; VectorMA(org, -3.4, right, org); VectorMA(org, 23, forward, org); //gi.dprintf("bigsmoke\n"); gi.WriteByte (svc_temp_entity); gi.WriteByte (tempevent); gi.WritePosition (org); gi.WriteDir (vec3_origin); gi.multicast (org, MULTICAST_ALL); gi.WriteByte (svc_temp_entity); gi.WriteByte (tempevent); gi.WritePosition (org); gi.WriteDir (vec3_origin); gi.multicast (org, MULTICAST_ALL); } void olivesmoker_use (edict_t *self, edict_t *other, edict_t *activator) { if (self->s.frame==55) { edict_t *tempent; self->s.frame=56; self->s.skinnum = 1; gi.sound(self, CHAN_BODY, gi.soundindex("monsters/cig.wav"), 1.0, ATTN_NORM, 0); tempent = G_Find (NULL, FOFS(targetname), "olivesmokeidle"); if (tempent) { tempent->think = G_FreeEdict; tempent->nextthink = level.time + FRAMETIME; } olivesmoker_bigsmoke(self); } else { self->think=G_FreeEdict; self->nextthink=level.time+FRAMETIME; } } //zz void SP_monster_olivesmoker(edict_t *self) { edict_t *zsmoke; self->svflags |= SVF_DEADMONSTER; VectorSet(self->mins, -11, -11, 0.0); VectorSet(self->maxs, 11, 11, 53.0); self->health2 = 0; self->s.modelindex = gi.modelindex ("models/monsters/olive/tris.md2"); self->solid = SOLID_BBOX; self->style = 0; self->use = olivesmoker_use; self->takedamage = DAMAGE_NO; self->s.frame = 55; self->movetype = MOVETYPE_FLY; self->s.modelindex2 = gi.modelindex ("models/monsters/olive/olivegun.md2"); VectorCopy(self->s.angles, self->pos2); //self->think = zsmoke_think; //self->nextthink = level.time + 1; gi.linkentity (self); zsmoke = G_Spawn(); zsmoke->style = TE_EXPLOSION1; VectorCopy(self->s.origin, zsmoke->s.origin); VectorCopy(self->s.angles, zsmoke->s.angles); zsmoke->movetype = MOVETYPE_NONE; zsmoke->think = zsmoke_think2; zsmoke->nextthink = level.time + 1; zsmoke->targetname = "olivesmokeidle"; gi.linkentity (zsmoke); } void worker_action(edict_t *self, edict_t *other) { gi.sound (self, CHAN_BODY, gi.soundindex("monsters/wah3.wav"), 1.0, ATTN_NORM, 0); } void worker_think(edict_t *self) { edict_t *player; vec3_t playervec; float playerdist; player = &g_edicts[1]; if (player) VectorSubtract (player->s.origin, self->s.origin, playervec); playerdist = VectorLength(playervec); //if (playerdist) // gi.dprintf("%f\n",playerdist); if ((playerdist > 180) && (self->s.frame==0)) { gi.sound(self, CHAN_BODY, gi.soundindex("weapons/whoosh.wav"), 0.6, ATTN_NORM, 0); if (self->style==0) self->s.frame=1; else self->s.frame=2; } else if ((playerdist <= 180) && (self->s.frame!=0)) { gi.sound(self, CHAN_BODY, gi.soundindex("weapons/whoosh.wav"), 0.6, ATTN_NORM, 0); self->s.frame=0; } self->think = worker_think; self->nextthink = level.time + 0.7; } void SP_monster_worker(edict_t *self) { self->svflags |= SVF_DEADMONSTER; VectorSet(self->mins, -8, -8, 0.0); VectorSet(self->maxs, 8, 8, 53.0); self->s.modelindex = gi.modelindex ("models/monsters/worker/tris.md2"); self->solid = SOLID_BBOX; self->takedamage = DAMAGE_NO; self->s.frame = 0; self->think = worker_think; self->nextthink = level.time+1; gi.linkentity (self); }
412
0.918156
1
0.918156
game-dev
MEDIA
0.989608
game-dev
0.98721
1
0.98721
NebulaSS13/Nebula
1,748
code/_onclick/hud/screen/screen_radial.dm
/obj/screen/radial icon = 'icons/screen/radial.dmi' layer = HUD_ABOVE_ITEM_LAYER plane = HUD_PLANE requires_owner = FALSE requires_ui_style = FALSE var/datum/radial_menu/parent /obj/screen/radial/Destroy() parent = null return ..() /obj/screen/radial/slice icon_state = "radial_slice" var/choice var/next_page = FALSE var/tooltips = FALSE /obj/screen/radial/slice/MouseEntered(location, control, params) . = ..() icon_state = "radial_slice_focus" if(tooltips) openToolTip(usr, src, params, title = name) /obj/screen/radial/slice/MouseExited(location, control, params) . = ..() icon_state = "radial_slice" if(tooltips) closeToolTip(usr) /obj/screen/radial/slice/handle_click(mob/user, params) if(parent && user.client == parent.current_user) if(next_page) parent.next_page() else parent.element_chosen(choice, user) /obj/screen/radial/center name = "Close Menu" icon_state = "radial_center" /obj/screen/radial/center/MouseEntered(location, control, params) . = ..() icon_state = "radial_center_focus" /obj/screen/radial/center/MouseExited(location, control, params) . = ..() icon_state = "radial_center" /obj/screen/radial/center/handle_click(mob/user, params) if(user.client == parent.current_user) parent.finished = TRUE /obj/screen/radial/persistent/center name = "Close Menu" icon_state = "radial_center" /obj/screen/radial/persistent/center/handle_click(mob/user, params) if(user.client == parent.current_user) parent.element_chosen(null,user) /obj/screen/radial/persistent/center/MouseEntered(location, control, params) . = ..() icon_state = "radial_center_focus" /obj/screen/radial/persistent/center/MouseExited(location, control, params) . = ..() icon_state = "radial_center"
412
0.956756
1
0.956756
game-dev
MEDIA
0.884384
game-dev
0.875717
1
0.875717
KTRosenberg/DrawTalking
1,985
apple_platforms/Make The Thing/Make The Thing/box2d/src/constraint_graph.h
// SPDX-FileCopyrightText: 2023 Erin Catto // SPDX-License-Identifier: MIT #pragma once #include "array.h" #include "bitset.h" #include "constants.h" typedef struct b2Body b2Body; typedef struct b2ContactSim b2ContactSim; typedef struct b2Contact b2Contact; typedef struct b2ContactConstraint b2ContactConstraint; typedef struct b2ContactConstraintSIMD b2ContactConstraintSIMD; typedef struct b2JointSim b2JointSim; typedef struct b2Joint b2Joint; typedef struct b2StepContext b2StepContext; typedef struct b2World b2World; // This holds constraints that cannot fit the graph color limit. This happens when a single dynamic body // is touching many other bodies. #define B2_OVERFLOW_INDEX (B2_GRAPH_COLOR_COUNT - 1) typedef struct b2GraphColor { // This bitset is indexed by bodyId so this is over-sized to encompass static bodies // however I never traverse these bits or use the bit count for anything // This bitset is unused on the overflow color. // todo consider having a uint_16 per body that tracks the graph color membership b2BitSet bodySet; // cache friendly arrays b2ContactSimArray contactSims; b2JointSimArray jointSims; // transient union { b2ContactConstraintSIMD* simdConstraints; b2ContactConstraint* overflowConstraints; }; } b2GraphColor; typedef struct b2ConstraintGraph { // including overflow at the end b2GraphColor colors[B2_GRAPH_COLOR_COUNT]; } b2ConstraintGraph; void b2CreateGraph( b2ConstraintGraph* graph, int bodyCapacity ); void b2DestroyGraph( b2ConstraintGraph* graph ); void b2AddContactToGraph( b2World* world, b2ContactSim* contactSim, b2Contact* contact ); void b2RemoveContactFromGraph( b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex ); b2JointSim* b2CreateJointInGraph( b2World* world, b2Joint* joint ); void b2AddJointToGraph( b2World* world, b2JointSim* jointSim, b2Joint* joint ); void b2RemoveJointFromGraph( b2World* world, int bodyIdA, int bodyIdB, int colorIndex, int localIndex );
412
0.771145
1
0.771145
game-dev
MEDIA
0.349788
game-dev
0.808604
1
0.808604
Samsung/Tizen-CSharp-Samples
4,874
Wearable_obsolete/Xamarin.Forms/RotaryTimer/src/RotaryTimer/RotaryTimer/Models/TimerModel.cs
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Timers; namespace RotaryTimer.Models { /// <summary> /// Provides time values storage. /// This is singleton. Instance is accessible via <see cref="TimerModel.Instance">Instance</see></cref> property. /// </summary> public sealed class TimerModel { #region fields /// <summary> /// System timer instance. /// </summary> private Timer _timer; /// <summary> /// Main model instance. /// </summary> private static TimerModel _instance; /// <summary> /// Running timer indicator. /// </summary> private bool _isTimerRunning; /// <summary> /// Timer start date. /// </summary> private DateTime _startTime; /// <summary> /// Number of seconds for which the timer is set. /// </summary> private int _timerSecondsInitial; #endregion #region properties /// <summary> /// Event invoked on every timer's tick. /// </summary> public event EventHandler TimerElapsed; /// <summary> /// Event invoked when timer finished. /// </summary> public event EventHandler TimerCompleted; /// <summary> /// Event invoked when timer is stopped. /// </summary> public event EventHandler TimerStopped; /// <summary> /// Hours value. /// </summary> public int Hours { get; set; } /// <summary> /// Minutes value. /// </summary> public int Minutes { get; set; } /// <summary> /// Seconds value. /// </summary> public int Seconds { get; set; } /// <summary> /// Main model instance. /// </summary> public static TimerModel Instance { get => _instance ?? (_instance = new TimerModel()); } #endregion #region methods /// <summary> /// Class constructor. /// </summary> private TimerModel() { _timer = new Timer(100); _timer.Elapsed += TimerElapsedHandler; } /// <summary> /// Sets time values to initial. /// </summary> public void SetInitialTime() { Seconds = _timerSecondsInitial % 60; Minutes = (int)Math.Floor((float)_timerSecondsInitial / 60) % 60; Hours = (int)Math.Floor((float)_timerSecondsInitial / 3600); } /// <summary> /// Calculates remaining time values. /// </summary> public void CalculateTimeValues() { long secondsElapsed = (DateTime.UtcNow.Ticks - _startTime.Ticks) / TimeSpan.TicksPerSecond; long secondsRemaining = _timerSecondsInitial - secondsElapsed; if (secondsRemaining < 0) { StopTimer(); TimerCompleted?.Invoke(this, null); } Seconds = (int)(secondsRemaining % 60); Minutes = (int)Math.Floor((float)secondsRemaining / 60) % 60; Hours = (int)Math.Floor((float)secondsRemaining / 3600); } /// <summary> /// Handles timer elapsed event. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments.</param> private void TimerElapsedHandler(object sender, EventArgs e) { CalculateTimeValues(); if (!_isTimerRunning) { _timer.Stop(); } TimerElapsed?.Invoke(this, null); } /// <summary> /// Starts timer. /// </summary> public void StartTimer() { _startTime = DateTime.UtcNow; _timerSecondsInitial = Hours * 3600 + Minutes * 60 + Seconds; _timer.Start(); _isTimerRunning = true; } /// <summary> /// Stops timer. /// </summary> public void StopTimer() { _isTimerRunning = false; TimerStopped?.Invoke(this, null); } #endregion } }
412
0.746869
1
0.746869
game-dev
MEDIA
0.547969
game-dev
0.681437
1
0.681437
frzyc/genshin-optimizer
2,019
libs/gi/db/src/Database/DataManagers/GeneratedBuildListDataManager.ts
import { objKeyMap } from '@genshin-optimizer/common/util' import { type ArtifactSlotKey, allArtifactSlotKeys, } from '@genshin-optimizer/gi/consts' import type { ArtCharDatabase } from '../ArtCharDatabase' import { DataManager } from '../DataManager' export interface GeneratedBuild { weaponId?: string artifactIds: Record<ArtifactSlotKey, string | undefined> } export interface GeneratedBuildList { builds: GeneratedBuild[] buildDate: number } export class GeneratedBuildListDataManager extends DataManager< string, 'generatedBuildList', GeneratedBuildList, GeneratedBuildList, ArtCharDatabase > { constructor(database: ArtCharDatabase) { super(database, 'generatedBuildList') } override validate(obj: unknown): GeneratedBuildList | undefined { if (typeof obj !== 'object' || obj === null) return undefined let { builds, buildDate } = obj as GeneratedBuildList if (!Array.isArray(builds)) { builds = [] buildDate = 0 } else { builds = builds .map((build) => { if (typeof build !== 'object' || build === null) return undefined const { artifactIds: artifactIdsRaw } = build as GeneratedBuild if (typeof artifactIdsRaw !== 'object' || artifactIdsRaw === null) return undefined let { weaponId } = build as GeneratedBuild if (weaponId && !this.database.weapons.get(weaponId)) weaponId = undefined const artifactIds = objKeyMap(allArtifactSlotKeys, (slotKey) => this.database.arts.get(artifactIdsRaw[slotKey])?.slotKey === slotKey ? artifactIdsRaw[slotKey] : undefined ) return { artifactIds, weaponId } }) .filter((build) => build !== undefined) if (!Number.isInteger(buildDate)) buildDate = 0 } return { buildDate, builds, } } new(data: GeneratedBuildList) { const id = this.generateKey() this.set(id, { ...data }) return id } }
412
0.863321
1
0.863321
game-dev
MEDIA
0.952673
game-dev
0.876143
1
0.876143
Darkrp-community/OpenKeep
5,610
code/game/turfs/open/space/space.dm
/turf/open/space icon = 'icons/turf/space.dmi' icon_state = "0" name = "\proper phlogiston" intact = 0 temperature = TCMB thermal_conductivity = OPEN_HEAT_TRANSFER_COEFFICIENT heat_capacity = 700000 var/destination_z var/destination_x var/destination_y var/static/datum/gas_mixture/immutable/space/space_gas = new plane = PLANE_SPACE layer = SPACE_LAYER light_power = 0.25 dynamic_lighting = DYNAMIC_LIGHTING_DISABLED bullet_bounce_sound = null /turf/open/space/basic/New() //Do not convert to Initialize //This is used to optimize the map loader return /turf/open/space/Initialize() ..() icon_state = SPACE_ICON_STATE // air = space_gas vis_contents.Cut() //removes inherited overlays // if(flags_1 & INITIALIZED_1) // stack_trace("Warning: [src]([type]) initialized multiple times!") // flags_1 |= INITIALIZED_1 var/area/A = loc if(!IS_DYNAMIC_LIGHTING(src) && IS_DYNAMIC_LIGHTING(A)) add_overlay(/obj/effect/fullbright) // if(requires_activation) // SSair.add_to_active(src) if (light_system == STATIC_LIGHT && light_power && (light_outer_range || light_inner_range)) update_light() if (opacity) has_opaque_atom = TRUE ComponentInitialize() return INITIALIZE_HINT_NORMAL //ATTACK GHOST IGNORING PARENT RETURN VALUE /turf/open/space/attack_ghost(mob/dead/observer/user) if(destination_z) var/turf/T = locate(destination_x, destination_y, destination_z) user.forceMove(T) /turf/open/space/Initalize_Atmos(times_fired) return /turf/open/space/TakeTemperature(temp) /turf/open/space/RemoveLattice() return /turf/open/space/AfterChange() ..() atmos_overlay_types = null /turf/open/space/Assimilate_Air() return /turf/open/space/proc/update_starlight() if(CONFIG_GET(flag/starlight)) for(var/t in RANGE_TURFS(1,src)) //RANGE_TURFS is in code\__HELPERS\game.dm if(isspaceturf(t)) //let's NOT update this that much pls continue set_light(2) return set_light(0) /turf/open/space/attack_paw(mob/user) return attack_hand(user) /turf/open/space/proc/CanBuildHere() return TRUE /turf/open/space/handle_slip() return /turf/open/space/attackby(obj/item/C, mob/user, params) ..() if(!CanBuildHere()) return if(istype(C, /obj/item/stack/rods)) var/obj/item/stack/rods/R = C var/obj/structure/lattice/L = locate(/obj/structure/lattice, src) var/obj/structure/lattice/catwalk/W = locate(/obj/structure/lattice/catwalk, src) if(W) to_chat(user, "<span class='warning'>There is already a catwalk here!</span>") return if(L) if(R.use(1)) to_chat(user, "<span class='notice'>I construct a catwalk.</span>") playsound(src, 'sound/blank.ogg', 50, TRUE) new/obj/structure/lattice/catwalk(src) else to_chat(user, "<span class='warning'>I need two rods to build a catwalk!</span>") return if(R.use(1)) to_chat(user, "<span class='notice'>I construct a lattice.</span>") playsound(src, 'sound/blank.ogg', 50, TRUE) ReplaceWithLattice() else to_chat(user, "<span class='warning'>I need one rod to build a lattice.</span>") return if(istype(C, /obj/item/stack/tile/plasteel)) var/obj/structure/lattice/L = locate(/obj/structure/lattice, src) if(L) var/obj/item/stack/tile/plasteel/S = C if(S.use(1)) qdel(L) playsound(src, 'sound/blank.ogg', 50, TRUE) to_chat(user, "<span class='notice'>I build a floor.</span>") PlaceOnTop(/turf/open/floor/plating, flags = CHANGETURF_INHERIT_AIR) else to_chat(user, "<span class='warning'>I need one floor tile to build a floor!</span>") else to_chat(user, "<span class='warning'>The plating is going to need some support! Place metal rods first.</span>") /turf/open/space/Entered(atom/movable/A) ..() if ((!(A) || src != A.loc)) return if(destination_z && destination_x && destination_y && !(A.pulledby || !A.can_be_z_moved)) var/tx = destination_x var/ty = destination_y var/turf/DT = locate(tx, ty, destination_z) var/itercount = 0 while(DT.density || istype(DT.loc,/area/shuttle)) // Extend towards the center of the map, trying to look for a better place to arrive if (itercount++ >= 100) log_game("SPACE Z-TRANSIT ERROR: Could not find a safe place to land [A] within 100 iterations.") break if (tx < 128) tx++ else tx-- if (ty < 128) ty++ else ty-- DT = locate(tx, ty, destination_z) var/atom/movable/AM = A.pulling A.forceMove(DT) if(AM) var/turf/T = get_step(A.loc,turn(A.dir, 180)) AM.can_be_z_moved = FALSE AM.forceMove(T) A.start_pulling(AM) AM.can_be_z_moved = TRUE //now we're on the new z_level, proceed the space drifting stoplag()//Let a diagonal move finish, if necessary A.newtonian_move(A.inertia_dir) /turf/open/space/MakeSlippery(wet_setting, min_wet_time, wet_time_to_add, max_wet_time, permanent) return /turf/open/space/singularity_act() return /turf/open/space/can_have_cabling() if(locate(/obj/structure/lattice/catwalk, src)) return 1 return 0 /turf/open/space/is_transition_turf() if(destination_x || destination_y || destination_z) return 1 /turf/open/space/acid_act(acidpwr, acid_volume) return 0 /turf/open/space/get_smooth_underlay_icon(mutable_appearance/underlay_appearance, turf/asking_turf, adjacency_dir) underlay_appearance.icon = 'icons/turf/space.dmi' underlay_appearance.icon_state = SPACE_ICON_STATE underlay_appearance.plane = PLANE_SPACE return TRUE /turf/open/space/ReplaceWithLattice() var/dest_x = destination_x var/dest_y = destination_y var/dest_z = destination_z ..() destination_x = dest_x destination_y = dest_y destination_z = dest_z
412
0.954552
1
0.954552
game-dev
MEDIA
0.836433
game-dev
0.987924
1
0.987924
AM2R-Community-Developers/AM2R-Community-Updates
9,315
objects/oScoreScreen.object.gmx
<!--This Document is generated by GameMaker, if you edit it by hand then you do so at your own risk!--> <object> <spriteName>sIBeamFX</spriteName> <solid>0</solid> <visible>-1</visible> <depth>0</depth> <persistent>0</persistent> <parentName>&lt;undefined&gt;</parentName> <maskName>&lt;undefined&gt;</maskName> <events> <event eventtype="0" enumb="0"> <action> <libid>1</libid> <id>603</id> <kind>7</kind> <userelative>0</userelative> <isquestion>0</isquestion> <useapplyto>-1</useapplyto> <exetype>2</exetype> <functionname></functionname> <codestring></codestring> <whoName>self</whoName> <relative>0</relative> <isnot>0</isnot> <arguments> <argument> <kind>1</kind> <string>playerx = 350; playertgtx = -50; if (oControl.mod_fusion == 1) playertgtx = 5; playery = 18; glow1x = -33; glow1y = 28; glow2x = 29; glow2y = 105; glow3x = 17; glow3y = 209; glow4x = -50; glow4y = 18; glow_alpha = 0; bgx = 0; bgtgtx = -80; bgy = 0; tx1x = 250; tx1y = 70; tx2x = 307; tx2y = 220; tx1_alpha = 0; tx2_alpha = 0; i = 0; ralpha = 0; fadeout = 0; walpha = 0; text1 = get_text("ScoreScreen", "ClearTime"); text1a = steps_to_time2(global.gametime); text2 = get_text("ScoreScreen", "ItemCollection"); text2a = string(round(global.itemstaken / 88 * 100)) + "%"; text3 = get_text("ScoreScreen", "SeeYouNextMission"); text4 = get_text("ScoreScreen", "TheLastMonster"); text5 = get_text("ScoreScreen", "ToBeContinued"); statetime = 0; state = 0; if (global.difficulty == 0) { ending = 276; unlock_gallery(0); } else { if (global.gametime &gt;= 864000) { ending = 276; unlock_gallery(0); } if (global.gametime &gt;= 432000 &amp;&amp; global.gametime &lt; 864000) { ending = 277; unlock_gallery(1); unlock_gallery(0); } if (global.gametime &lt; 432000) { ending = 278; unlock_gallery(2); unlock_gallery(1); unlock_gallery(0); } } if (global.difficulty == 0) unlock_set(0); if (global.difficulty == 1) unlock_set(1); if (global.difficulty &gt; 1) unlock_set(2); widespace = oControl.widescreen*53; //transitiontime = 1000; </string> </argument> </arguments> </action> </event> <event eventtype="3" enumb="0"> <action> <libid>1</libid> <id>603</id> <kind>7</kind> <userelative>0</userelative> <isquestion>0</isquestion> <useapplyto>-1</useapplyto> <exetype>2</exetype> <functionname></functionname> <codestring></codestring> <whoName>self</whoName> <relative>0</relative> <isnot>0</isnot> <arguments> <argument> <kind>1</kind> <string>var j; if (state == 0) { if (playerx != playertgtx) playerx = lerp(playerx, playertgtx, 0.02); if (bgx != bgtgtx) bgx = lerp(bgx, bgtgtx, 0.02); glow1x = playerx + 17; glow2x = playerx + 79; glow3x = playerx + 67; glow4x = playerx; if (statetime &gt; 200) { if (tx1_alpha &lt; 1) tx1_alpha += 0.05; } if (statetime &gt; 300) { if (tx2_alpha &lt; 1) tx2_alpha += 0.05; } if (statetime &gt; 120 &amp;&amp; statetime &lt; 1000 &amp;&amp; (oControl.kMenu1 || oControl.kMenu2 || oControl.kStart)) { } if (statetime &gt; 1000) { if (walpha &lt; 1) { walpha += 0.01; } else { state = 1; statetime = 0; tx1_alpha = 0; } } i += 0.02; if (i &gt; 99999999) i = 0; j = 0.02 + abs(sin(i)); if (j &gt; 1) j = 1; glow_alpha = j; } // if (state == 0) if (state == 1) { if (statetime &gt; 300 &amp;&amp; statetime &lt; 1000 &amp;&amp; (oControl.kMenu1 || oControl.kMenu2 || oControl.kStart)) statetime = 1000; if (statetime &gt; 180) { if (tx1_alpha &lt; 1) tx1_alpha += 0.05; } if (statetime &gt; 1000) { if (fadeout == 0) fadeout = 1; } if (statetime == 1300) { state = 2; statetime = 0; tx1_alpha = 0; tx2_alpha = 0; ralpha = 0; fadeout = 0; } if (fadeout) { if (ralpha &lt; 1) ralpha += 0.01; } if (walpha &gt; 0) walpha -= 0.01; } if (state == 2) { if (statetime &gt; 0) { if (tx1_alpha &lt; 1) tx1_alpha += 0.05; } if (statetime &gt; 350) { if (tx2_alpha &lt; 1) tx2_alpha += 0.05; } if (statetime == 60) sfx_play(sndTLM); if (statetime == 600) fadeout = 1; if (statetime == 900) event_user(0); if (fadeout) { if (ralpha &lt; 1) ralpha += 0.01; } } statetime += 1; </string> </argument> </arguments> </action> </event> <event eventtype="7" enumb="10"> <action> <libid>1</libid> <id>603</id> <kind>7</kind> <userelative>0</userelative> <isquestion>0</isquestion> <useapplyto>-1</useapplyto> <exetype>2</exetype> <functionname></functionname> <codestring></codestring> <whoName>self</whoName> <relative>0</relative> <isnot>0</isnot> <arguments> <argument> <kind>1</kind> <string>//room_change(titleroom, 1); //room_goto(titleroom); if(round((global.itemstaken / 88) * 100) &lt; 100) { room_change(titleroom, 1); //room_goto(titleroom); } else { room_goto(rm_secretEnding); } </string> </argument> </arguments> </action> </event> <event eventtype="8" enumb="0"> <action> <libid>1</libid> <id>603</id> <kind>7</kind> <userelative>0</userelative> <isquestion>0</isquestion> <useapplyto>-1</useapplyto> <exetype>2</exetype> <functionname></functionname> <codestring></codestring> <whoName>self</whoName> <relative>0</relative> <isnot>0</isnot> <arguments> <argument> <kind>1</kind> <string>if (state == 0) { draw_background(bgScoreScreenBG, bgx - (oControl.widescreen_space/2), bgy); if (oControl.mod_fusion == 1) { draw_background(bgScoreScreenPlayer_fusion, playerx, playery); } else draw_background(bgScoreScreenPlayer, playerx, playery); draw_set_blend_mode(bm_add); if (oControl.mod_fusion == 1) { draw_background_ext(bgScoreScreenPlayerGlow4, glow4x, glow4y, 1, 1, 0, -1, glow_alpha); } else { draw_background_ext(bgScoreScreenPlayerGlow1, glow1x, glow1y, 1, 1, 0, -1, glow_alpha); draw_background_ext(bgScoreScreenPlayerGlow2, glow2x, glow2y, 1, 1, 0, -1, glow_alpha); draw_background_ext(bgScoreScreenPlayerGlow3, glow3x, glow3y, 1, 1, 0, -1, glow_alpha); } draw_set_blend_mode(bm_normal); draw_set_color(c_white); draw_set_font(fontGUI2); draw_set_halign(fa_center); draw_set_alpha(tx1_alpha); draw_text(tx1x, tx1y, text1); draw_text(tx1x, tx1y + 12, text1a); draw_set_alpha(tx2_alpha); draw_text(tx1x, tx1y + 40, text2); draw_text(tx1x, tx1y + 52, text2a); draw_set_halign(fa_left); } if (state == 1) { draw_background(ending, -53, 0); // -53 is a widescreen image correction draw_set_font(fontGUI2); draw_set_halign(fa_right); draw_set_color(c_black); draw_set_alpha(tx1_alpha); draw_text(tx2x - 1 + widespace, tx2y - 1, text3); draw_text(tx2x - 1 + widespace, tx2y + 1, text3); draw_text(tx2x + 1 + widespace, tx2y - 1, text3); draw_text(tx2x + 1 + widespace, tx2y + 1, text3); draw_text(tx2x - 1 + widespace, tx2y, text3); draw_text(tx2x + 1 + widespace, tx2y, text3); draw_set_color(c_white); draw_set_alpha(tx1_alpha); draw_text(tx2x + widespace, tx2y, text3); draw_set_halign(fa_left); } if (state == 2) { draw_set_font(fontGUI2); draw_set_halign(fa_center); draw_set_color(c_white); draw_set_alpha(tx1_alpha); draw_text(160, 100, text4); draw_set_halign(fa_right); draw_set_font(fontMenuSmall2); draw_set_alpha(tx2_alpha); draw_text(307 + widespace, 220, text5); draw_set_halign(fa_left); } if (fadeout) { draw_set_alpha(ralpha); draw_set_color(c_black); draw_rectangle(-53, 0, 1000, 1000, false); draw_set_alpha(1); } if (walpha &gt; 0) { draw_set_alpha(walpha); draw_set_color(c_white); draw_rectangle(-53, 0, 1000, 1000, false); draw_set_alpha(1); } </string> </argument> </arguments> </action> </event> </events> <PhysicsObject>0</PhysicsObject> <PhysicsObjectSensor>0</PhysicsObjectSensor> <PhysicsObjectShape>0</PhysicsObjectShape> <PhysicsObjectDensity>0.5</PhysicsObjectDensity> <PhysicsObjectRestitution>0.100000001490116</PhysicsObjectRestitution> <PhysicsObjectGroup>0</PhysicsObjectGroup> <PhysicsObjectLinearDamping>0.100000001490116</PhysicsObjectLinearDamping> <PhysicsObjectAngularDamping>0.100000001490116</PhysicsObjectAngularDamping> <PhysicsObjectFriction>0.200000002980232</PhysicsObjectFriction> <PhysicsObjectAwake>-1</PhysicsObjectAwake> <PhysicsObjectKinematic>-1</PhysicsObjectKinematic> <PhysicsShapePoints/> </object>
412
0.812107
1
0.812107
game-dev
MEDIA
0.627605
game-dev
0.870873
1
0.870873
rism-digital/verovio
15,253
src/expansionmap.cpp
///////////////////////////////////////////////////////////////////////////// // Name: expansionmap.cpp // Author: Werner Goebl // Created: 2019 // Copyright (c) Authors and others. All rights reserved. ///////////////////////////////////////////////////////////////////////////// #include "expansionmap.h" //---------------------------------------------------------------------------- #include <cassert> #include <iostream> //---------------------------------------------------------------------------- #include "editorial.h" #include "ending.h" #include "expansion.h" #include "lem.h" #include "linkinginterface.h" #include "plistinterface.h" #include "rdg.h" #include "section.h" #include "timeinterface.h" #include "vrv.h" namespace vrv { //---------------------------------------------------------------------------- // ExpansionMap //---------------------------------------------------------------------------- ExpansionMap::ExpansionMap() {} ExpansionMap::~ExpansionMap() {} void ExpansionMap::Reset() { m_map.clear(); } void ExpansionMap::Expand(Expansion *expansion, xsdAnyURI_List &existingList, Object *prevSect, xsdAnyURI_List &deletionList, bool deleteList = false) { assert(expansion); assert(expansion->GetParent()); xsdAnyURI_List expansionPlist = expansion->GetPlist(); if (expansionPlist.empty()) { LogWarning("ExpansionMap::Expand: Expansion element %s has empty @plist. Nothing expanded.", expansion->GetID().c_str()); return; } assert(prevSect); assert(prevSect->GetParent()); Object *insertHere = nullptr; // cloned parent container // If expansion parent already exists, create a new empty such element if (std::find(existingList.begin(), existingList.end(), expansion->GetParent()->GetID()) != existingList.end()) { Object *newContainer; // check type of expansion parent if (expansion->GetParent()->Is(SECTION)) { newContainer = static_cast<Object *>(new Section()); } else if (expansion->GetParent()->Is(ENDING)) { newContainer = static_cast<Object *>(new Ending()); } else if (expansion->GetParent()->Is(LEM)) { newContainer = static_cast<Object *>(new Lem()); } else if (expansion->GetParent()->Is(RDG)) { newContainer = static_cast<Object *>(new Rdg()); } else { LogWarning( "ExpansionMap::Expand: Expansion element %s has unsupported parent type.", expansion->GetID().c_str()); return; } prevSect->GetParent()->InsertAfter(prevSect, newContainer); GeneratePredictableIDs(expansion->GetParent(), newContainer); LogDebug("Creating new container <%s> for expansion element %s", newContainer->GetClassName().c_str(), newContainer->GetID().c_str()); insertHere = newContainer; } else if (std::find(existingList.begin(), existingList.end(), expansion->GetParent()->GetID()) == existingList.end()) { existingList.push_back(expansion->GetParent()->GetID()); } // find and add all relevant (and new) expansion sibling ids to deletionList for (Object *siblings : expansion->GetParent()->GetChildren()) { if (siblings->Is({ SECTION, ENDING, LEM, RDG }) && std::count(deletionList.begin(), deletionList.end(), siblings->GetID()) == 0) { deletionList.push_back(siblings->GetID()); } } // iterate over expansion plist for (std::string id : expansionPlist) { LogDebug("Looking for element in @plist: %s", id.c_str()); if (id.rfind("#", 0) == 0) id = id.substr(1, id.size() - 1); // remove leading hash from id Object *currSect = expansion->GetParent()->FindDescendantByID(id); // find section pointer for id string if (currSect == NULL) { // Warn about referenced element not found and continue LogWarning("ExpansionMap::Expand: Element referenced in @plist not found: %s", id.c_str()); continue; } if (currSect->Is(EXPANSION)) { // if id is itself an expansion, resolve it recursively Expansion *currExpansion = vrv_cast<Expansion *>(currSect); assert(currExpansion); this->Expand(currExpansion, existingList, prevSect, deletionList); } else { // id already in existingList or currSect is not in expansion parent, clone object, update ids, insert it if (std::find(existingList.begin(), existingList.end(), id) != existingList.end() || (insertHere != NULL && currSect->GetParent() != insertHere)) { // clone current section/ending/rdg/lem and rename it, adding -"rend2" for the first repetition etc. Object *clonedObject = currSect->Clone(); clonedObject->CloneReset(); this->GeneratePredictableIDs(currSect, clonedObject); // get IDs of old and new sections and add them to m_map std::vector<std::string> oldIds; oldIds.push_back(currSect->GetID()); this->GetIDList(currSect, oldIds); std::vector<std::string> clonedIds; clonedIds.push_back(clonedObject->GetID()); this->GetIDList(clonedObject, clonedIds); for (int i = 0; (i < (int)oldIds.size()) && (i < (int)clonedIds.size()); ++i) { this->AddExpandedIDToExpansionMap(oldIds.at(i), clonedIds.at(i)); } // go through cloned objects, find TimePointing/SpanningInterface, PListInterface, LinkingInterface this->UpdateIDs(clonedObject); LogDebug("Cloning element in @plist: %s", clonedObject->GetID().c_str()); if (insertHere != NULL) { insertHere->AddChild(clonedObject); // add to new container, if it exists } else { prevSect->GetParent()->InsertAfter(prevSect, clonedObject); // or add after previous section } prevSect = clonedObject; } else { // add to existingList, remember previous element, re-order if necessary bool moveCurrentElement = false; int prevIdx = prevSect->GetIdx(); int childCount = prevSect->GetParent()->GetChildCount(); int currIdx = currSect->GetIdx(); // check re-order when within same parent if (currSect->GetParent()->GetID() == prevSect->GetParent()->GetID()) { // If prevSect has a next element and if it is different than the currSect or has no next element, // move it to after the currSect. if (prevIdx < childCount - 1) { Object *nextElement = prevSect->GetParent()->GetChild(prevIdx + 1); assert(nextElement); if (nextElement->Is({ SECTION, ENDING, LEM, RDG }) && nextElement != currSect) { moveCurrentElement = true; } } else { moveCurrentElement = true; } } // move prevSect to after currSect if (moveCurrentElement && currIdx < prevIdx && prevIdx < childCount) { LogDebug( "Re-ordering element %s to after %s", currSect->GetID().c_str(), prevSect->GetID().c_str()); currSect->GetParent()->RotateChildren(currIdx, currIdx + 1, prevIdx + 1); } else { LogDebug("Leaving existing element %s", currSect->GetID().c_str()); } prevSect = currSect; existingList.push_back(id); } } } // at the very end, remove unused sections from structure if not in existingList if (deleteList) { for (std::string del : deletionList) { long cnt = std::count(existingList.begin(), existingList.end(), del); if (cnt == 0) { Object *currSect = expansion->GetParent()->FindDescendantByID(del); // find section pointer for id string assert(currSect); int idx = currSect->GetIdx(); LogDebug("ExpansionMap::Expand: Removing unused section/ending/rdg/lem with id %s", del.c_str()); currSect->GetParent()->DetachChild(idx); } } } } bool ExpansionMap::UpdateIDs(Object *object) { for (Object *o : object->GetChildren()) { o->IsExpansion(true); if (o->HasInterface(INTERFACE_TIME_POINT)) { TimePointInterface *interface = o->GetTimePointInterface(); assert(interface); // @startid std::string oldStartId = interface->GetStartid(); if (oldStartId.rfind("#", 0) == 0) oldStartId = oldStartId.substr(1, oldStartId.size() - 1); std::string newStartId = this->GetExpansionIDsForElement(oldStartId).back(); if (!newStartId.empty()) interface->SetStartid("#" + newStartId); } if (o->HasInterface(INTERFACE_TIME_SPANNING)) { TimeSpanningInterface *interface = o->GetTimeSpanningInterface(); assert(interface); // @startid std::string oldStartId = interface->GetStartid(); if (oldStartId.rfind("#", 0) == 0) oldStartId = oldStartId.substr(1, oldStartId.size() - 1); std::string newStartId = this->GetExpansionIDsForElement(oldStartId).back(); if (!newStartId.empty()) interface->SetStartid("#" + newStartId); // @endid oldStartId = interface->GetEndid(); if (oldStartId.rfind("#", 0) == 0) oldStartId = oldStartId.substr(1, oldStartId.size() - 1); std::string newEndId = this->GetExpansionIDsForElement(oldStartId).back(); if (!newEndId.empty()) interface->SetEndid("#" + newEndId); } if (o->HasInterface(INTERFACE_PLIST)) { PlistInterface *interface = o->GetPlistInterface(); // @plist assert(interface); xsdAnyURI_List oldList = interface->GetPlist(); xsdAnyURI_List newList; for (std::string oldRefString : oldList) { if (oldRefString.rfind("#", 0) == 0) oldRefString = oldRefString.substr(1, oldRefString.size() - 1); newList.push_back("#" + this->GetExpansionIDsForElement(oldRefString).back()); } interface->SetPlist(newList); } else if (o->HasInterface(INTERFACE_LINKING)) { LinkingInterface *interface = o->GetLinkingInterface(); assert(interface); // @sameas std::string oldIdString = interface->GetSameas(); if (oldIdString.rfind("#", 0) == 0) oldIdString = oldIdString.substr(1, oldIdString.size() - 1); std::string newIdString = this->GetExpansionIDsForElement(oldIdString).back(); if (!newIdString.empty()) interface->SetSameas("#" + newIdString); // @next oldIdString = interface->GetNext(); if (oldIdString.rfind("#", 0) == 0) oldIdString = oldIdString.substr(1, oldIdString.size() - 1); newIdString = this->GetExpansionIDsForElement(oldIdString).back(); if (!newIdString.empty()) interface->SetNext("#" + newIdString); // @prev oldIdString = interface->GetPrev(); if (oldIdString.rfind("#", 0) == 0) oldIdString = oldIdString.substr(1, oldIdString.size() - 1); newIdString = this->GetExpansionIDsForElement(oldIdString).back(); if (!newIdString.empty()) interface->SetPrev("#" + newIdString); // @copyof oldIdString = interface->GetCopyof(); if (oldIdString.rfind("#", 0) == 0) oldIdString = oldIdString.substr(1, oldIdString.size() - 1); newIdString = this->GetExpansionIDsForElement(oldIdString).back(); if (!newIdString.empty()) interface->SetCopyof("#" + newIdString); // @corresp oldIdString = interface->GetCorresp(); if (oldIdString.rfind("#", 0) == 0) oldIdString = oldIdString.substr(1, oldIdString.size() - 1); newIdString = this->GetExpansionIDsForElement(oldIdString).back(); if (!newIdString.empty()) interface->SetCorresp("#" + newIdString); // @synch oldIdString = interface->GetSynch(); if (oldIdString.rfind("#", 0) == 0) oldIdString = oldIdString.substr(1, oldIdString.size() - 1); newIdString = this->GetExpansionIDsForElement(oldIdString).back(); if (!newIdString.empty()) interface->SetSynch("#" + newIdString); } this->UpdateIDs(o); } return true; } bool ExpansionMap::AddExpandedIDToExpansionMap(const std::string &origXmlId, std::string newXmlId) { auto list = m_map.find(origXmlId); if (list != m_map.end()) { list->second.push_back(newXmlId); // add to existing key for (std::string s : list->second) { if (s != list->second.front() && s != list->second.back()) { m_map.at(s).push_back(newXmlId); // add to middle keys } } m_map.insert({ newXmlId, m_map.at(origXmlId) }); // add new as key } else { std::vector<std::string> s; s.push_back(origXmlId); s.push_back(newXmlId); m_map.insert({ origXmlId, s }); m_map.insert({ newXmlId, s }); } return true; } std::vector<std::string> ExpansionMap::GetExpansionIDsForElement(const std::string &xmlId) { if (m_map.contains(xmlId)) { return m_map.at(xmlId); } else { std::vector<std::string> ids; ids.push_back(xmlId.c_str()); return ids; } } bool ExpansionMap::HasExpansionMap() { return (m_map.empty()) ? false : true; } void ExpansionMap::GetIDList(Object *object, std::vector<std::string> &idList) { for (Object *o : object->GetChildren()) { idList.push_back(o->GetID()); this->GetIDList(o, idList); } } void ExpansionMap::GeneratePredictableIDs(Object *source, Object *target) { target->SetID( source->GetID() + "-rend" + std::to_string(this->GetExpansionIDsForElement(source->GetID()).size() + 1)); ArrayOfObjects sourceObjects = source->GetChildren(); ArrayOfObjects targetObjects = target->GetChildren(); if (sourceObjects.size() <= 0 || sourceObjects.size() != targetObjects.size()) return; unsigned i = 0; for (Object *s : sourceObjects) { this->GeneratePredictableIDs(s, targetObjects.at(i++)); } } void ExpansionMap::ToJson(std::string &output) { jsonxx::Object expansionmap; for (auto &[id, ids] : m_map) { jsonxx::Array expandedIds; for (auto i : ids) expandedIds << i; expansionmap << id << expandedIds; ; } output = expansionmap.json(); } } // namespace vrv
412
0.949509
1
0.949509
game-dev
MEDIA
0.445199
game-dev,desktop-app
0.984819
1
0.984819
hocha113/CalamityOverhaul
5,001
Content/Projectiles/Weapons/Summon/GhostFires.cs
using CalamityMod; using Microsoft.Xna.Framework.Graphics; using System; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace CalamityOverhaul.Content.Projectiles.Weapons.Summon { internal class GhostFires : ModProjectile { public bool ableToHit = true; public NPC target; public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; public override void SetStaticDefaults() { ProjectileID.Sets.MinionShot[Projectile.type] = true; ProjectileID.Sets.TrailingMode[Projectile.type] = 0; ProjectileID.Sets.TrailCacheLength[Projectile.type] = 20; } public override void SetDefaults() { Projectile.width = Projectile.height = 16; Projectile.friendly = true; Projectile.tileCollide = false; Projectile.penetrate = 200; Projectile.extraUpdates = 3; Projectile.timeLeft = 600; Projectile.usesLocalNPCImmunity = true; Projectile.localNPCHitCooldown = 50; Projectile.DamageType = DamageClass.Summon; } public override bool? CanDamage() { return !ableToHit ? false : null; } public override void AI() { Player player = Main.player[Projectile.owner]; Projectile.localAI[0] += 1f / (Projectile.extraUpdates + 1); if (Projectile.penetrate < 200) { if (Projectile.timeLeft > 60) { Projectile.timeLeft = 60; } Projectile.velocity *= 0.88f; } else if (Projectile.localAI[0] < 60f) { Projectile.velocity *= 0.93f; } else { FindTarget(player); } if (Projectile.timeLeft <= 20) { ableToHit = false; } } public void FindTarget(Player player) { float num = 3000f; bool flag = false; if (player.HasMinionAttackTargetNPC) { NPC nPC = Main.npc[player.MinionAttackTargetNPC]; if (nPC.CanBeChasedBy(Projectile)) { float num2 = Vector2.Distance(nPC.Center, Projectile.Center); if (num2 < num) { num = num2; flag = true; target = nPC; } } } if (!flag) { for (int i = 0; i < Main.maxNPCs; i++) { NPC nPC2 = Main.npc[i]; if (nPC2.CanBeChasedBy(Projectile)) { float num3 = Vector2.Distance(nPC2.Center, Projectile.Center); if (num3 < num) { num = num3; flag = true; target = nPC2; } } } } if (!flag) { Projectile.velocity *= 0.98f; } else { KillTheThing(target); } } public void KillTheThing(NPC npc) { Projectile.velocity = Projectile.SuperhomeTowardsTarget(npc, 50f / (Projectile.extraUpdates + 1), 60f / (Projectile.extraUpdates + 1), 1f / (Projectile.extraUpdates + 1)); } public override bool PreDraw(ref Color lightColor) { Texture2D value = ModContent.Request<Texture2D>("CalamityMod/ExtraTextures/SmallGreyscaleCircle").Value; for (int i = 0; i < Projectile.oldPos.Length; i++) { float amount = MathF.Cos(Projectile.timeLeft / 32f + Main.GlobalTimeWrappedHourly / 20f + i / (float)Projectile.oldPos.Length * MathF.PI) * 0.5f + 0.5f; Color color = Color.Lerp(Color.Cyan, Color.LightBlue, amount) * 0.4f; color.A = 0; Vector2 position = Projectile.oldPos[i] + value.Size() * 0.5f - Main.screenPosition + new Vector2(0f, Projectile.gfxOffY) + new Vector2(-28f, -28f); Color color2 = color; Color color3 = color * 0.5f; float num = 0.9f + 0.15f * MathF.Cos(Main.GlobalTimeWrappedHourly % 60f * MathHelper.TwoPi); num *= MathHelper.Lerp(0.15f, 1f, 1f - i / (float)Projectile.oldPos.Length); if (Projectile.timeLeft <= 60) { num *= Projectile.timeLeft / 60f; } Vector2 vector = new Vector2(1f) * num; Vector2 vector2 = new Vector2(1f) * num * 0.7f; color2 *= num; color3 *= num; Main.EntitySpriteDraw(value, position, null, color2, 0f, value.Size() * 0.5f, vector * 0.6f, SpriteEffects.None); Main.EntitySpriteDraw(value, position, null, color3, 0f, value.Size() * 0.5f, vector2 * 0.6f, SpriteEffects.None); } return false; } } }
412
0.875262
1
0.875262
game-dev
MEDIA
0.99132
game-dev
0.990244
1
0.990244
ajvincent/es-membrane
1,285
projects/ts-morph-structures/stage_2_snapshot/snapshot/source/structures/type/TupleTypeStructureImpl.ts
import { TypeStructureKind, type TypeStructures } from "../../exports.js"; import { type CloneableTypeStructure, TypeStructureClassesMap, TypeStructuresWithChildren, } from "../../internal-exports.js"; /** * @example * `[number, boolean]` * * @see `ArrayTypeStructureImpl` for `boolean[]` * @see `IndexedAccessTypeStructureImpl` for `Foo["index"]` */ export default class TupleTypeStructureImpl extends TypeStructuresWithChildren< TypeStructureKind.Tuple, TypeStructures[] > { static clone(other: TupleTypeStructureImpl): TupleTypeStructureImpl { return new TupleTypeStructureImpl( TypeStructureClassesMap.cloneArray(other.childTypes), ); } readonly kind = TypeStructureKind.Tuple; protected readonly objectType: null = null; public childTypes: TypeStructures[]; protected readonly startToken = "["; protected readonly joinChildrenToken = ", "; protected readonly endToken = "]"; protected readonly maxChildCount = Infinity; constructor(childTypes: TypeStructures[] = []) { super(); this.childTypes = childTypes; this.registerCallbackForTypeStructure(); } } TupleTypeStructureImpl satisfies CloneableTypeStructure<TupleTypeStructureImpl>; TypeStructureClassesMap.set(TypeStructureKind.Tuple, TupleTypeStructureImpl);
412
0.858449
1
0.858449
game-dev
MEDIA
0.20343
game-dev
0.780049
1
0.780049
soartech/jsoar
7,084
jsoar-performance-testing/src/main/resources/APT/all-test/Pyramid/instruct/execute-solve-procedure/execute-step/execute-action.soar
sp {execute-step*propose*execute-action (state <s> ^name execute-step -^alternate-action ^current-problem <cp>) (<cp> ^current-step.action <a> -^completed-action <a>) --> (<s> ^operator <op> + =) (<op> ^name execute-action ^action <a>) } sp {execute-step*propose*alternate-action (state <s> ^name execute-step ^alternate-action <a>) --> (<s> ^operator <op> + =) (<op> ^name execute-action ^action <a>) } ########## SET sp {apply*execute-action*set*from-constant (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^command set ^variable <var> ^value <constant> ^value-type constant) --> (<cp> ^<var> <constant> ^completed-action <a> ^terms <t>) (<t> ^term-name <var> ^type intermediate ^term-initial-value <constant>) (write |Set ^| <var> | | <constant>) } sp {apply*execute-action*set*from-variable (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^command set ^variable <var> ^value <from-var> ^value-type variable) (<cp> ^<from-var> <value>) --> (<cp> ^<var> <value> ^terms <t>) (<t> ^term-name <var> ^type intermediate ^term-initial-value <value>) (write |Set ^| <var> | | <value>) (<cp> ^completed-action <a>) } sp {apply*execute-action*set*list (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^command set ^variable <var> ^value-type list) --> (<cp> ^<var> <head>) (<head> ^current <x> ^next <x>) (<cp> ^completed-action <a>) (write |Create List ^| <var> | | <head>) } ########## ADD sp {apply*execute-action*add*from-constant (state <s> ^operator <op> ^current-problem <cp> ^superstate <ss>) (<op> ^name execute-action ^action <a>) (<a> ^command add ^variable <var> ^value <value> ^value-type constant) (<cp> ^<var> <old-value>) --> (<cp> ^<var> <old-value> - (+ <old-value> <value>) ^completed-action <a>) (write (crlf) |Add ^| <var> | | <old-value> | + | <value> | = | (+ <old-value> <value>)) } sp {apply*execute-action*add*from-variable (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^command add ^variable <var> ^value <from-var> ^value-type variable) (<cp> ^<var> <old-value> ^<from-var> { <> 0 <value> }) --> (write (crlf) |Add ^| <var> | | <old-value> | + | <from-var> |: | <value> | = | (+ <old-value> <value>)) (<cp> ^<var> <old-value> -) (<cp> ^<var> (+ <old-value> <value>) ^completed-action <a>)} sp {apply*execute-action*add*from-variable*zero (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^command add ^variable <var> ^value <from-var> ^value-type variable) (<cp> ^<var> <old-value> ^<from-var> 0) --> (<cp> ^completed-action <a>) (write |Add ^| <var> | | <old-value> | + | <from-var> |: 0 = | <old-value>) } ########## SUBTRACT sp {apply*execute-action*subtract*from-constant (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^command subtract ^variable <var> ^value <value> ^value-type constant) (<cp> ^<var> <old-value>) --> (<cp> ^<var> <old-value> - (- <old-value> <value>) ^completed-action <a>) (write |Subtract ^| <var> | | <old-value> | - | <value> | = | (- <old-value> <value>)) } sp {apply*execute-action*subtract*from-variable (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^command subtract ^variable <var> ^value <from-var> ^value-type variable) (<cp> ^<var> <old-value> ^<from-var> <value>) --> (<cp> ^<var> <old-value> - (- <old-value> <value>) ^completed-action <a>) (write |Subtract ^| <var> | | <old-value> | - | <from-var> |: | <value> | = | (- <old-value> <value>)) } ########## INCREMENT sp {apply*execute-action*increment (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^command increment ^variable <var>) (<cp> ^<var> <old-value>) --> (<cp> ^<var> <old-value> - (+ <old-value> 1) ^completed-action <a>) (write |Increment ^| <var> | | <old-value> | = | (+ <old-value> 1)) } ########## DECREMENT sp {apply*execute-action*decrement (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^command decrement ^variable <var>) (<cp> ^<var> <old-value>) --> (<cp> ^<var> <old-value> - (- <old-value> 1) ^completed-action <a>) (write |Decrement ^| <var> | | <old-value> | = | (- <old-value> 1)) } ########## WRITE - Add to a linked list? sp {apply*execute-action*write (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^command write ^variable <var> ^save-command <action> ^list <list>) (<cp> ^<list> <item> ^<var> <value>) (<item> ^current <c>) --> (<item> ^current <c> - <nc>) (<c> ^command <action> ^value <value> ^variable <var> ^next <nc>) (<cp> ^completed-action <a>) (write |write: | <var> |: | <action> | (| <value> |)|) } ########## GOAL-TEST sp {apply*execute-action*goal-test*equal*variable (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^command goal-test ^relation equal ^variable <var> ^value <value> ^value-type variable) (<cp> ^<var> <x> ^<value> <x>) --> (<cp> ^goal-test-success <a> ^completed-action <a>) (write |Success!|) } sp {apply*execute-action*goal-test*equal*variable*not-equal (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^command goal-test ^relation equal ^variable <var> ^value <value> ^value-type variable) (<cp> ^<var> <x> -^<value> <x>) --> (<cp> ^completed-action <a>) (write |Failure!|) } sp {substitute-elaborate (state <s> ^operator <op> ^current-problem <cp>) (<op> ^name execute-action ^action <a>) (<a> ^substitute <a1>) (<cp> ^completed-action <a>) --> (<s> ^alternate-action <a> -) (<cp> ^completed-action <a> - <a1>) }
412
0.630759
1
0.630759
game-dev
MEDIA
0.42989
game-dev
0.602579
1
0.602579
SlimeKnights/Mantle
3,938
src/main/java/slimeknights/mantle/data/loadable/mapping/MapLoadable.java
package slimeknights.mantle.data.loadable.mapping; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.util.GsonHelper; import slimeknights.mantle.data.loadable.Loadable; import slimeknights.mantle.data.loadable.field.LoadableField; import slimeknights.mantle.data.loadable.primitive.StringLoadable; import slimeknights.mantle.util.typed.TypedMap; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.function.Function; /** * Loadable for a map type. * @param <K> Key type * @param <V> Value type */ public class MapLoadable<K, V> implements Loadable<Map<K,V>> { protected final StringLoadable<K> keyLoadable; protected final Loadable<V> valueLoadable; protected final int minSize; /** * Creates a new map loadable * @param keyLoadable Loadable for the map keys, parsed from strings * @param valueLoadable Loadable for map values, parsed from elements * @param minSize Minimum size for the map to be valid */ public MapLoadable(StringLoadable<K> keyLoadable, Loadable<V> valueLoadable, int minSize) { this.keyLoadable = keyLoadable; this.valueLoadable = valueLoadable; this.minSize = minSize; } /** Builds the final map, given the passed mutable map. */ protected Map<K,V> build(Map<K,V> builder) { return Map.copyOf(builder); } /** Creates a new builder instance for the given expected size */ protected Map<K,V> createBuilder(int size) { return new HashMap<>(size); } @Override public Map<K,V> convert(JsonElement element, String key, TypedMap context) { JsonObject json = GsonHelper.convertToJsonObject(element, key); if (json.size() < minSize) { throw new JsonSyntaxException(key + " must have at least " + minSize + " elements"); } Map<K,V> builder = createBuilder(json.size()); String mapKey = key + "'s key"; for (Entry<String, JsonElement> entry : json.entrySet()) { String entryKey = entry.getKey(); builder.put( keyLoadable.parseString(entryKey, mapKey), valueLoadable.convert(entry.getValue(), entryKey, context)); } return build(builder); } @Override public JsonElement serialize(Map<K,V> map) { if (map.size() < minSize) { throw new RuntimeException("Collection must have at least " + minSize + " elements"); } JsonObject json = new JsonObject(); for (Entry<K,V> entry : map.entrySet()) { json.add( keyLoadable.getString(entry.getKey()), valueLoadable.serialize(entry.getValue())); } return json; } @Override public Map<K,V> decode(FriendlyByteBuf buffer, TypedMap context) { int size = buffer.readVarInt(); Map<K,V> builder = createBuilder(size); for (int i = 0; i < size; i++) { builder.put( keyLoadable.decode(buffer, context), valueLoadable.decode(buffer, context)); } return build(builder); } @Override public void encode(FriendlyByteBuf buffer, Map<K,V> map) { buffer.writeVarInt(map.size()); for (Entry<K,V> entry : map.entrySet()) { keyLoadable.encode(buffer, entry.getKey()); valueLoadable.encode(buffer, entry.getValue()); } } /** Creates a field that defaults to empty */ public <P> LoadableField<Map<K,V>,P> emptyField(String key, boolean serializeEmpty, Function<P,Map<K,V>> getter) { return defaultField(key, Map.of(), serializeEmpty, getter); } /** Creates a field that defaults to empty */ public <P> LoadableField<Map<K,V>,P> emptyField(String key, Function<P,Map<K,V>> getter) { return emptyField(key, false, getter); } @Override public String toString() { return "MapLoadable[keyLoadable=" + keyLoadable + ", " + "valueLoadable=" + valueLoadable + ", " + "minSize=" + minSize + ']'; } }
412
0.891659
1
0.891659
game-dev
MEDIA
0.415462
game-dev
0.933787
1
0.933787
Pearlism/Fortnite-External-source
7,734
game/drawing.h
#pragma once #include "../imgui/imgui.h" #define DEBUG_DISPLAY(name, value) \ if (!(value)) ImGui::TextColored(ImVec4(1, 0, 0, 1), "Failed to read " name "!"); \ else ImGui::TextColored(ImVec4(0, 1, 0, 1), name ": 0x%llX", value); void outlinetext(ImFont* font, float fontSize, ImVec2 position, ImColor color, const char* text) { ImGui::GetForegroundDrawList()->AddText(font, fontSize, ImVec2(position.x - 1, position.y - 1), ImColor(0, 0, 0), text); ImGui::GetForegroundDrawList()->AddText(font, fontSize, ImVec2(position.x + 1, position.y - 1), ImColor(0, 0, 0), text); ImGui::GetForegroundDrawList()->AddText(font, fontSize, ImVec2(position.x - 1, position.y + 1), ImColor(0, 0, 0), text); ImGui::GetForegroundDrawList()->AddText(font, fontSize, ImVec2(position.x + 1, position.y + 1), ImColor(0, 0, 0), text); ImGui::GetForegroundDrawList()->AddText(font, fontSize, position, color, text); } void drawbox(int x, int y, int w, int h, const ImColor color) { ImGui::GetForegroundDrawList()->AddRect(ImVec2(x + 1, y + 1), ImVec2(x + w - 1, y + h - 1), ImColor(0, 0, 0), 0, 0, 1.0f); ImGui::GetForegroundDrawList()->AddRect(ImVec2(x - 1, y - 1), ImVec2(x + w + 1, y + h + 1), ImColor(0, 0, 0), 0, 0, 1.0f); ImGui::GetForegroundDrawList()->AddRect(ImVec2(x + 1, y - 1), ImVec2(x + w - 1, y + h + 1), ImColor(0, 0, 0), 0, 0, 1.0f); ImGui::GetForegroundDrawList()->AddRect(ImVec2(x - 1, y + 1), ImVec2(x + w + 1, y + h - 1), ImColor(0, 0, 0), 0, 0, 1.0f); ImGui::GetForegroundDrawList()->AddRect(ImVec2(x, y), ImVec2(x + w, y + h), color, 0, 0, 1.0f); } static void drawcornerbox(float x, float y, float w, float h, ImColor color) { ImGui::GetForegroundDrawList()->AddLine(ImVec2(x - 1, y - 1), ImVec2(x - 1, y + (h / 3) - 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x - 1, y - 1), ImVec2(x + (w / 3) - 1, y - 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + w - (w / 3) + 1, y - 1), ImVec2(x + w + 1, y - 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + w + 1, y - 1), ImVec2(x + w + 1, y + (h / 3) - 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x - 1, y + h - (h / 3) + 1), ImVec2(x - 1, y + h + 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x - 1, y + h + 1), ImVec2(x + (w / 3) - 1, y + h + 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + w - (w / 3) + 1, y + h + 1), ImVec2(x + w + 1, y + h + 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + w + 1, y + h - (h / 3) + 1), ImVec2(x + w + 1, y + h + 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + 1, y + 1), ImVec2(x + 1, y + (h / 3) + 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + 1, y + 1), ImVec2(x + (w / 3) + 1, y + 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + w - (w / 3) - 1, y + 1), ImVec2(x + w - 1, y + 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + w - 1, y + 1), ImVec2(x + w - 1, y + (h / 3) + 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + 1, y + h - (h / 3) - 1), ImVec2(x + 1, y + h - 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + 1, y + h - 1), ImVec2(x + (w / 3) + 1, y + h - 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + w - (w / 3) - 1, y + h - 1), ImVec2(x + w - 1, y + h - 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + w - 1, y + h - (h / 3) - 1), ImVec2(x + w - 1, y + h - 1), ImColor(0, 0, 0), 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x, y), ImVec2(x, y + (h / 3)), color, 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x, y), ImVec2(x + (w / 3), y), color, 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + w - (w / 3), y), ImVec2(x + w, y), color, 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + w, y), ImVec2(x + w, y + (h / 3)), color, 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x, y + h - (h / 3)), ImVec2(x, y + h), color, 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x, y + h), ImVec2(x + (w / 3), y + h), color, 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + w - (w / 3), y + h), ImVec2(x + w, y + h), color, 1.0f); ImGui::GetForegroundDrawList()->AddLine(ImVec2(x + w, y + h - (h / 3)), ImVec2(x + w, y + h), color, 1.0f); } void DrawBezier(ImVec2 p0, ImVec2 p1, ImVec2 p2, ImVec2 p3, ImU32 color, float thickness, int segments = 20) { std::vector<ImVec2> points; for (int i = 0; i <= segments; ++i) { float t = (float)i / (float)segments; float u = 1.0f - t; float x = u * u * u * p0.x + 3 * u * u * t * p1.x + 3 * u * t * t * p2.x + t * t * t * p3.x; float y = u * u * u * p0.y + 3 * u * u * t * p1.y + 3 * u * t * t * p2.y + t * t * t * p3.y; points.push_back(ImVec2(x, y)); } ImGui::GetForegroundDrawList()->AddPolyline(points.data(), points.size(), color, false, thickness); } namespace updater { void run() { while (true) { auto uworld = read<uintptr_t>(kernel->ProcessBase + UWORLD); auto owning_game_instance = read<uintptr_t>(uworld + GAME_INSTANCE); auto local_player = read<uintptr_t>(read<uintptr_t>(owning_game_instance + LOCAL_PLAYERS)); auto player_controller = read<uintptr_t>(local_player + PLAYER_CONTROLLER); auto local_pawn = read<uintptr_t>(player_controller + LOCAL_PAWN); auto player_state = read<uintptr_t>(local_pawn + PLAYER_STATE); auto root_component = read<uintptr_t>(local_pawn + ROOT_COMPONENT); // Store local data cache::uworld = uworld; cache::local_pawn = local_pawn; cache::my_team_id = read<int>(player_state + TEAM_INDEX); auto game_state = read<uintptr_t>(uworld + GAME_STATE); tarray<uintptr_t> player_array(game_state + PLAYER_ARRAY); auto player_list = player_array.get_all(); udata::world_t.game_state = game_state; udata::world_t.player_array = player_list; std::vector<udata::actor> actors; actors.reserve(player_list.size()); udata::world_t.mesh = NULL; for (const auto& player_state : player_list) { if (!player_state) continue; auto team_id = read<int>(player_state + TEAM_INDEX); if (team_id == cache::my_team_id) continue; auto pawn_private = read<uintptr_t>(player_state + PAWN_PRIVATE); if (!pawn_private || pawn_private == cache::local_pawn) continue; auto mesh = read<uintptr_t>(pawn_private + MESH); if (!mesh) continue; actors.emplace_back(player_state, pawn_private, mesh, team_id); } udata::actor_t = std::move(actors); Sleep(1200); } } uintptr_t RootComponent(uintptr_t actor) { return read<uintptr_t>(actor + ROOT_COMPONENT); } Vector3 GetLocation(uintptr_t actor) { return read<Vector3>(RootComponent(actor) + RELATIVE_LOCATION); } } //void DrawLoot() //{ // if (!kernel || !ImGui::GetBackgroundDrawList()) // return; // // ImDrawList* drawList = ImGui::GetBackgroundDrawList(); // // for (const auto& loot : item_pawns) // { // if (loot.actor == 0 || !loot.is_pickup) // continue; // // auto rootComp = read<uintptr_t>(loot.actor + ROOT_COMPONENT); // if (rootComp == 0) continue; // // Vector3 worldPos = read<Vector3>(rootComp + RELATIVE_LOCATION); // Vector2 screenPos = project_world_to_screen(worldPos); // if (screenPos.x <= 0 || screenPos.y <= 0) // continue; // // ImColor lootColor = ImColor(255, 255, 0); // char buf[128]; // snprintf(buf, sizeof(buf), "[%.fm] %s", loot.distance, loot.name.c_str()); // // drawList->AddText(ImVec2(screenPos.x, screenPos.y), lootColor, buf); // } //}
412
0.640296
1
0.640296
game-dev
MEDIA
0.462563
game-dev
0.759982
1
0.759982
MaurycyLiebner/eZeus
126,245
engine/egameboard.cpp
 #include "egameboard.h" #include "buildings/eagorabase.h" #include "characters/echaracter.h" #include "buildings/ebuilding.h" #include "spawners/espawner.h" #include "buildings/estoragebuilding.h" #include "characters/esoldier.h" #include "characters/esoldierbanner.h" #include "buildings/etradepost.h" #include "buildings/esmallhouse.h" #include "buildings/epalace.h" #include "buildings/epalacetile.h" #include "buildings/ehorseranch.h" #include "engine/boardData/eheatmaptask.h" #include "missiles/emissile.h" #include "missiles/ewavemissile.h" #include "missiles/elavamissile.h" #include "missiles/edustmissile.h" #include "etilehelper.h" #include "emessages.h" #include "spawners/emonsterpoint.h" #include "spawners/elandinvasionpoint.h" #include "buildings/eheatgetters.h" #include "fileIO/ebuildingreader.h" #include "fileIO/ebuildingwriter.h" #include "eevent.h" #include "emessageeventtype.h" #include "gameEvents/egodattackevent.h" #include "gameEvents/emonsterunleashedevent.h" #include "gameEvents/einvasionevent.h" #include "gameEvents/epaytributeevent.h" #include "gameEvents/emakerequestevent.h" #include "gameEvents/egifttoevent.h" #include "gameEvents/egiftfromevent.h" #include "gameEvents/ereceiverequestevent.h" #include "gameEvents/erequestaidevent.h" #include "gameEvents/eplayerconquesteventbase.h" #include "gameEvents/etroopsrequestevent.h" #include "gameEvents/earmyreturnevent.h" #include "eeventdata.h" #include "einvasionhandler.h" #include "characters/actions/emonsteraction.h" #include "evectorhelpers.h" #include "egifthelpers.h" #include "estringhelpers.h" #include "buildings/eheroshall.h" #include "buildings/emuseum.h" #include "buildings/estadium.h" #include "buildings/eagoraspace.h" #include "buildings/evendor.h" #include "buildings/eroad.h" #include "buildings/egatehouse.h" #include "eplague.h" #include "audio/emusic.h" #include "ecampaign.h" #include "eiteratesquare.h" #include "ecolonymonumentaction.h" #include "textures/emarbletile.h" #include "elanguage.h" #include "enumbers.h" #include "characters/actions/eanimalaction.h" #include "buildings/eanimalbuilding.h" #include "buildings/eplaceholder.h" #include "buildings/sanctuaries/ezeussanctuary.h" #include "buildings/sanctuaries/ehephaestussanctuary.h" #include "buildings/sanctuaries/eartemissanctuary.h" #include "buildings/sanctuaries/estairsrenderer.h" #include "buildings/sanctuaries/etempletilebuilding.h" #include "buildings/sanctuaries/etemplestatuebuilding.h" #include "buildings/sanctuaries/etemplemonumentbuilding.h" #include "buildings/sanctuaries/etemplealtarbuilding.h" #include "buildings/sanctuaries/etemplebuilding.h" #include "characters/etrireme.h" #include "buildings/pyramids/epyramid.h" #ifndef uint #define uint unsigned int #endif eGameBoard::eGameBoard(eWorldBoard& world) : mWorld(world), mThreadPool(*this) { const auto types = eResourceTypeHelpers::extractResourceTypes( eResourceType::allBasic); for(const auto type : types) { mPrices[type] = eResourceTypeHelpers::defaultPrice(type); } } eGameBoard::~eGameBoard() { mRegisterBuildingsEnabled = false; clear(); } void eGameBoard::initialize(const int w, const int h) { waitUntilFinished(); mThreadPool.initialize(w, h); clear(); mTiles.reserve(w); for(int x = 0; x < w; x++) { auto& yArr = mTiles.emplace_back(); yArr.reserve(h); for(int y = 0; y < h; y++) { int tx; int ty; eTileHelper::dtileIdToTileId(x, y, tx, ty); const auto tile = new eTile(tx, ty, x, y, *this); yArr.push_back(tile); } } mWidth = w; mHeight = h; mAppealMap.initialize(0, 0, w, h); updateNeighbours(); // updateMarbleTiles(); scheduleTerrainUpdate(); for(const auto& c : mCitiesOnBoard) { c->clearTiles(); } } void eGameBoard::resize(const int w, const int h) { waitUntilFinished(); mThreadPool.initialize(w, h); mTiles.reserve(w); for(int x = w; x < mWidth; x++) { mTiles.pop_back(); } for(int x = 0; x < w; x++) { auto& yArr = mTiles[x]; for(int y = h; y < mHeight; y++) { yArr.pop_back(); } } for(int x = 0; x < w; x++) { auto& yArr = x < mWidth ? mTiles[x] : mTiles.emplace_back(); yArr.reserve(h); for(int y = 0; y < h; y++) { if(x < mWidth && y < mHeight) continue; int tx; int ty; eTileHelper::dtileIdToTileId(x, y, tx, ty); const auto tile = new eTile(tx, ty, x, y, *this); yArr.push_back(tile); } } mWidth = w; mHeight = h; mAppealMap.initialize(0, 0, w, h); updateNeighbours(); // updateMarbleTiles(); scheduleTerrainUpdate(); updateTerritoryBorders(); } void eGameBoard::clear() { for(const auto c : mCharacters) { c->kill(); } emptyRubbish(); for(const auto& c : mCitiesOnBoard) { c->clearHippodromes(); } for(const auto& x : mTiles) { for(const auto y : x) { delete y; } } mTiles.clear(); mWidth = 0; mHeight = 0; emptyRubbish(); std::vector<stdsptr<eBoardCity>> cities; std::swap(mCitiesOnBoard, cities); cities.clear(); mPlayersOnBoard.clear(); mDefeatedBy.clear(); mEarthquakes.clear(); mTidalWaves.clear(); mGoals.clear(); emptyRubbish(); } void eGameBoard::setWorldDirection(const eWorldDirection dir) { mDirection = dir; scheduleTerrainUpdate(); } eTile* eGameBoard::rotateddtile(const int x, const int y) const { int rx; int ry; eTileHelper::rotatedDTileIdToDTileId( x, y, rx, ry, mDirection, mWidth, mHeight); return dtile(rx, ry); } int eGameBoard::rotatedWidth() const { if(mDirection == eWorldDirection::N) { return mWidth; } else if(mDirection == eWorldDirection::E) { return mHeight/2; } else if(mDirection == eWorldDirection::S) { return mWidth; } else { // if(mDirection == eWorldDirection::W) { return mHeight/2; }} int eGameBoard::rotatedHeight() const { if(mDirection == eWorldDirection::N) { return mHeight; } else if(mDirection == eWorldDirection::E) { return 2*mWidth; } else if(mDirection == eWorldDirection::S) { return mHeight; } else { // if(mDirection == eWorldDirection::W) { return 2*mWidth; } } void eGameBoard::iterateOverAllTiles(const eTileAction& a) { const int height = rotatedHeight(); const int width = rotatedWidth(); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { const auto t = rotateddtile(x, y); if(!t) continue; a(t); } } } void eGameBoard::scheduleAppealMapUpdate(const eCityId cid) { if(mEditorMode) return; mUpdateAppeal[cid].fV = true; } void eGameBoard::updateAppealMapIfNeeded() { for(auto& c : mUpdateAppeal) { bool& fV = c.second.fV; if(!fV) continue; fV = false; const auto cid = c.first; const auto finish = [this, cid](eHeatMap& map) { const auto c = boardCityWithId(cid); const auto& tiles = c->tiles(); for(const auto t : tiles) { const int dx = t->dx(); const int dy = t->dy(); const bool e = map.enabled(dx, dy); const double h = map.heat(dx, dy); mAppealMap.set(dx, dy, e, h); } }; const auto cc = boardCityWithId(cid); const auto rect = cc->tileBRect(); const auto task = new eHeatMapTask(cid, rect, eHeatGetters::appeal, finish); mThreadPool.queueTask(task); } } void eGameBoard::enlistForces(const eEnlistedForces& forces) { for(const auto& b : forces.fSoldiers) { b->goAbroad(); } const auto cids = citiesOnBoard(); for(const auto h : forces.fHeroes) { const auto hh = heroHall(h.first, h.second); if(!hh) continue; hh->sendHeroOnQuest(); } for(const auto& a : forces.fAllies) { a->setAbroad(true); } } void eGameBoard::clearBannerSelection() { for(const auto s : mSelectedBanners) { s->setSelected(false); } mSelectedBanners.clear(); } void eGameBoard::deselectBanner(eSoldierBanner* const c) { eVectorHelpers::remove(mSelectedBanners, c); c->setSelected(false); } void eGameBoard::selectBanner(eSoldierBanner* const c) { mSelectedBanners.push_back(c); c->setSelected(true); } void eGameBoard::clearTriremeSelection() { for(const auto s : mSelectedTriremes) { s->setSelected(false); } mSelectedTriremes.clear(); } void eGameBoard::deselectTrireme(eTrireme * const c) { eVectorHelpers::remove(mSelectedTriremes, c); c->setSelected(false); } void eGameBoard::selectTrireme(eTrireme * const c) { if(!c->selectable()) return; mSelectedTriremes.push_back(c); c->setSelected(true); } void eGameBoard::bannersGoHome() { const auto triremes = mSelectedTriremes; for(const auto t : triremes) { t->goHome(); } std::map<eCityId, std::vector<stdsptr<eSoldierBanner>>> armyReturn; const auto banners = mSelectedBanners; for(const auto b : banners) { if(b->militaryAid() && b->isAbroad()) { const auto cid = b->cityId(); armyReturn[cid].push_back(b->ref<eSoldierBanner>()); } b->goHome(); } for(const auto& r : armyReturn) { const auto c = boardCityWithId(r.first); if(!c) continue; if(r.second.empty()) return; const auto fromCid = r.second[0]->onCityId(); const auto fromC = mWorld.cityWithId(fromCid); const auto e = e::make_shared<eArmyReturnEvent>( r.first, eGameEventBranch::root, *this); const auto boardDate = date(); const int period = eNumbers::sReinforcementsTravelTime; const auto date = boardDate + period; e->initializeDate(date, period, 1); eEnlistedForces forces; forces.fSoldiers = r.second; e->initialize(forces, fromC); c->addRootGameEvent(e); } } void eGameBoard::bannersBackFromHome() { for(const auto b : mSelectedBanners) { b->backFromHome(); } } void eGameBoard::setRegisterBuildingsEnabled(const bool e) { mRegisterBuildingsEnabled = e; } void eGameBoard::setButtonsVisUpdater(const eAction& u) { mButtonVisUpdater = u; } eBuilding* eGameBoard::buildingAt(const int x, const int y) const { const auto t = tile(x, y); if(!t) return nullptr; return t->underBuilding(); } bool eGameBoard::isShutDown(const eCityId cid, const eResourceType type) const { const auto c = boardCityWithId(cid); if(!c) return false; return c->isShutDown(type); } bool eGameBoard::isShutDown(const eCityId cid, const eBuildingType type) const { const auto c = boardCityWithId(cid); if(!c) return false; return c->isShutDown(type); } std::vector<eBuilding*> eGameBoard::buildings( const eCityId cid, const eBuildingValidator& v) const { const auto c = boardCityWithId(cid); if(!c) return {}; return c->buildings(v); } std::vector<eBuilding*> eGameBoard::buildings( const eCityId cid, const eBuildingType type) const { const auto c = boardCityWithId(cid); if(!c) return {}; return c->buildings(type); } int eGameBoard::countBuildings( const eCityId cid, const eBuildingValidator& v) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->countBuildings(v); } int eGameBoard::countBuildings( const eCityId cid, const eBuildingType t) const { const auto c = boardCityWithId(cid); if(!c) return {}; return c->countBuildings(t); } bool eGameBoard::hasBuilding( const eCityId cid, const eBuildingType t) const { const auto c = boardCityWithId(cid); if(!c) return false; return c->hasBuilding(t); } int eGameBoard::countAllowed( const eCityId cid, const eBuildingType t) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->countAllowed(t); } eBuilding* eGameBoard::randomBuilding( const eCityId cid, const eBuildingValidator& v) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->randomBuilding(v); } std::vector<eBuilding*> eGameBoard::commemorativeBuildings( const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return {}; return c->commemorativeBuildings(); } bool eGameBoard::supportsBuilding(const eCityId cid, const eBuildingMode mode) const { const auto c = boardCityWithId(cid); if(!c) return false; return c->supportsBuilding(mode); } bool eGameBoard::availableBuilding(const eCityId cid, const eBuildingType type, const int id) const { const auto c = boardCityWithId(cid); if(!c) return false; return c->availableBuilding(type, id); } void eGameBoard::built(const eCityId cid, const eBuildingType type, const int id) { const auto c = boardCityWithId(cid); if(!c) return; return c->built(type, id); } void eGameBoard::destroyed(const eCityId cid, const eBuildingType type, const int id) { const auto c = boardCityWithId(cid); if(!c) return; return c->destroyed(type, id); } void eGameBoard::allow(const eCityId cid, const eBuildingType type, const int id) { const auto c = boardCityWithId(cid); if(!c) return; return c->allow(type, id); } void eGameBoard::disallow(const eCityId cid, const eBuildingType type, const int id) { const auto c = boardCityWithId(cid); if(!c) return; return c->disallow(type, id); } void eGameBoard::updateButtonsVisibility() { if(mButtonVisUpdater) mButtonVisUpdater(); } bool eGameBoard::supportsResource( const eCityId cid, const eResourceType rt) const { const auto c = boardCityWithId(cid); if(!c) return false; return c->supportsResource(rt); } eResourceType eGameBoard::supportedResources(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return eResourceType::none; return c->supportedResources(); } int eGameBoard::wonGames(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->wonGames(); } int eGameBoard::horses() const { int h = 0; for(const auto b : mTimedBuildings) { if(b->type() != eBuildingType::horseRanch) continue; const auto r = static_cast<eHorseRanch*>(b); h += r->horseCount(); } return h; } void eGameBoard::planAction(ePlannedAction* const a) { mPlannedActions.emplace_back(a); } void eGameBoard::restockMarbleTiles() { for(const auto& mt : mMarbleTiles) { mt.restock(); } } bool eGameBoard::eMarbleTiles::contains(eTile* const tile) const { return eVectorHelpers::contains(fTiles, tile); } void eGameBoard::eMarbleTiles::add(eTile* const tile) { fTiles.push_back(tile); } void eGameBoard::eMarbleTiles::addWithNeighbours(eTile* const tile) { for(int x = -1; x <= 1; x++) { for(int y = -1; y <= 1; y++) { const auto n = tile->tileRel<eTile>(x, y); const auto terr = n->terrain(); if(terr != eTerrain::marble) return; const bool c = contains(n); if(c) continue; add(n); addWithNeighbours(n); } } } void eGameBoard::eMarbleTiles::restock() const { int maxLevel = 0; for(const auto t : fTiles) { if(t->resource() > 0) return; const int l = t->marbleLevel(); if(l > maxLevel) maxLevel = l; } for(const auto t : fTiles) { const int l = t->marbleLevel(); if(l == maxLevel) { if(maxLevel == 2) { t->setResource(99999); } else { const bool e = eMarbleTile::edge(t); if(!e) t->setResource(1); } } } } void eGameBoard::updateMarbleTiles() { mMarbleTiles.clear(); iterateOverAllTiles([&](eTile* const t) { const auto terr = t->terrain(); if(terr != eTerrain::marble) return; for(const auto& mt : mMarbleTiles) { const bool c = mt.contains(t); if(c) return; } auto& mt = mMarbleTiles.emplace_back(); mt.addWithNeighbours(t); }); } void eGameBoard::restockBlackMarbleTiles() { for(const auto& mt : mMarbleTiles) { mt.restock(); } } void eGameBoard::updateBlackMarbleTiles() { mBlackMarbleTiles.clear(); iterateOverAllTiles([&](eTile* const t) { const auto terr = t->terrain(); if(terr != eTerrain::blackMarble) return; for(const auto& mt : mBlackMarbleTiles) { const bool c = mt.contains(t); if(c) return; } auto& mt = mBlackMarbleTiles.emplace_back(); mt.addWithNeighbours(t); }); } void eGameBoard::allowHero(const eCityId cid, const eHeroType heroType, const std::string& reason) { const auto hallType = eHerosHall::sHeroTypeToHallType(heroType); allow(cid, hallType); const auto& inst = eMessages::instance; const auto hm = inst.heroMessages(heroType); if(!hm) return; eEventData ed(cid); auto msg = hm->fHallAvailable; eStringHelpers::replaceAll(msg.fFull.fText, "[reason_phrase]", reason.empty() ? msg.fNoReason : reason); showMessage(ed, msg); } eBuilding* eGameBoard::buildingWithIOID(const int id) const { if(id == -1) return nullptr; for(const auto b : mAllBuildings) { const int bio = b->ioID(); if(bio == id) return b; } return nullptr; } eCharacter* eGameBoard::characterWithIOID(const int id) const { if(id == -1) return nullptr; for(const auto c : mCharacters) { const int bio = c->ioID(); if(bio == id) return c; } return nullptr; } eCharacterAction* eGameBoard::characterActionWithIOID(const int id) const { if(id == -1) return nullptr; for(const auto ca : mCharacterActions) { const int bio = ca->ioID(); if(bio == id) return ca; } return nullptr; } eBanner* eGameBoard::bannerWithIOID(const int id) const { if(id == -1) return nullptr; for(const auto b : mBanners) { const int bio = b->ioID(); if(bio == id) return b; } return nullptr; } eSoldierBanner* eGameBoard::soldierBannerWithIOID(const int id) const { if(id == -1) return nullptr; for(const auto b : mAllSoldierBanners) { const int bio = b->ioID(); if(bio == id) return b; } return nullptr; } eGameEvent* eGameBoard::eventWithIOID(const int id) const { if(id == -1) return nullptr; for(const auto e : mAllGameEvents) { const int eio = e->ioID(); if(eio == id) return e; } return nullptr; } eInvasionHandler* eGameBoard::invasionHandlerWithIOID(const int id) const { for(const auto& c : mCitiesOnBoard) { const auto i = c->invasionHandlerWithIOID(id); if(i) return i; } return nullptr; } eTile* eGameBoard::monsterTile(const eCityId cid, const int id) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->monsterTile(id); } eTile* eGameBoard::landInvasionTile(const eCityId cid, const int id) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->landInvasionTile(id); } eTile* eGameBoard::seaInvasionTile(const eCityId cid, const int id) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->seaInvasionTile(id); } eTile* eGameBoard::invasionTile(const eCityId cid, const int id) const { if(id > 7) return seaInvasionTile(cid, id); return landInvasionTile(cid, id); } eTile* eGameBoard::disasterTile(const eCityId cid, const int id) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->disasterTile(id); } eTile *eGameBoard::landSlideTile(const eCityId cid, const int id) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->landSlideTile(id); } std::vector<eInvasionHandler*> eGameBoard::invasionHandlers( const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return {}; return c->invasionHandlers(); } void eGameBoard::addInvasionHandler(const eCityId cid, eInvasionHandler* const i) { const auto c = boardCityWithId(cid); if(!c) return; c->addInvasionHandler(i); updateMusic(); } void eGameBoard::removeInvasionHandler(const eCityId cid, eInvasionHandler* const i) { const auto c = boardCityWithId(cid); if(!c) return; c->removeInvasionHandler(i); updateMusic(); } bool eGameBoard::hasActiveInvasions(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return false; return c->hasActiveInvasions(); } int eGameBoard::addResource(const eCityId cid, const eResourceType type, const int count) { const auto c = boardCityWithId(cid); if(!c) return 0; return c->addResource(type, count); } int eGameBoard::spaceForResource(const eCityId cid, const eResourceType type) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->spaceForResource(type); } int eGameBoard::maxSingleSpaceForResource( const eCityId cid, const eResourceType type, eStorageBuilding** b) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->maxSingleSpaceForResource(type, b); } int eGameBoard::maxMonumentSpaceForResource( const eCityId cid, eMonument** b) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->maxMonumentSpaceForResource(b); } void eGameBoard::planGiftFrom(const stdsptr<eWorldCity>& c, const eResourceType type, const int count, const int delay) { const auto e = e::make_shared<eGiftFromEvent>( currentCityId(), eGameEventBranch::root, *this); e->initialize(true, type, count, c); const auto date = mDate + delay; e->initializeDate(date); addRootGameEvent(e); } void eGameBoard::request(const stdsptr<eWorldCity>& c, const eResourceType type, const eCityId cid) { const auto e = e::make_shared<eMakeRequestEvent>( cid, eGameEventBranch::root, *this); e->initialize(true, type, c); const auto date = mDate + 90; e->initializeDate(date); addRootGameEvent(e); const auto pid = cityIdToPlayerId(cid); const auto& cts = mWorld.cities(); for(const auto& ct : cts) { if(ct->isCurrentCity()) continue; ct->incAttitude(-10, pid); } c->incAttitude(-10, pid); } void eGameBoard::requestAid(const stdsptr<eWorldCity>& c, const eCityId cid) { const auto e = e::make_shared<eRequestAidEvent>( cid, eGameEventBranch::root, *this); e->setCity(c); const auto date = mDate + 30; e->initializeDate(date); addRootGameEvent(e); } void eGameBoard::tributeFrom(const ePlayerId pid, const stdsptr<eWorldCity>& c, const bool postpone) { const auto type = c->tributeType(); const int count = c->tributeCount(); eEventData ed(pid); ed.fType = eMessageEventType::requestTributeGranted; ed.fCity = c; if(type == eResourceType::drachmas) { ed.fA0 = [this, c, count, pid]() { // accept const auto p = boardPlayerWithId(pid); if(p) p->incDrachmas(count, eFinanceTarget::tributeReceived); return count; }; } else { const auto cids = playerCitiesOnBoard(pid); for(const auto cid : cids) { ed.fCSpaceCount[cid] = spaceForResource(cid, type); ed.fCityNames[cid] = cityName(cid); ed.fCCA0[cid] = [this, cid, c, type, count, pid]() { // accept const int a = addResource(cid, type, count); if(a == count) return; eEventData ed(pid); ed.fType = eMessageEventType::resourceGranted; ed.fCity = c; ed.fResourceType = type; ed.fResourceCount = a; event(eEvent::tributeAccepted, ed); }; } } ed.fResourceType = type; ed.fResourceCount = count; if(postpone) { ed.fA1 = [this, c, type, count, pid]() { // postpone eEventData ed(pid); ed.fType = eMessageEventType::resourceGranted; ed.fCity = c; ed.fResourceType = type; ed.fResourceCount = count; event(eEvent::tributePostponed, ed); const auto e = e::make_shared<ePayTributeEvent>( currentCityId(), eGameEventBranch::root, *this); e->initialize(c); const auto date = mDate + 31; e->initializeDate(date); addRootGameEvent(e); }; } ed.fA2 = [this, c, type, count, pid]() { // decline eEventData ed(pid); ed.fType = eMessageEventType::resourceGranted; ed.fCity = c; ed.fResourceType = type; ed.fResourceCount = count; event(eEvent::tributeDeclined, ed); }; event(eEvent::tributePaid, ed); } bool eGameBoard::giftTo(const stdsptr<eWorldCity>& c, const eResourceType type, const int count, const eCityId cid) { const auto cc = boardCityWithId(cid); const int has = cc->resourceCount(type); if(has < count) return false; cc->takeResource(type, count); const auto e = e::make_shared<eGiftToEvent>( cid, eGameEventBranch::root, *this); e->initialize(c, type, count); const auto date = mDate + 90; e->initializeDate(date); addRootGameEvent(e); return true; } void eGameBoard::giftToReceived(const stdsptr<eWorldCity>& c, const eResourceType type, const int count, const ePlayerId pid) { const bool a = c->acceptsGift(type, count); eEventData ed(pid); ed.fType = eMessageEventType::resourceGranted; ed.fCity = c; ed.fResourceType = type; ed.fResourceCount = count; if(a) { const int mult = count/eGiftHelpers::giftCount(type); const bool b = c->buys(type); const bool s = c->sells(type); if(type == eResourceType::drachmas) { event(eEvent::giftReceivedDrachmas, ed); c->incAttitude(3*mult, pid); } else if(b) { event(eEvent::giftReceivedNeeded, ed); c->incAttitude(3*mult, pid); } else if(s) { event(eEvent::giftReceivedSells, ed); c->incAttitude(1.5*mult, pid); } else { event(eEvent::giftReceivedNotNeeded, ed); c->incAttitude(1.5*mult, pid); } c->gifted(type, count); } else { event(eEvent::giftReceivedRefuse, ed); } } void eGameBoard::waitUntilFinished() { while(!mThreadPool.finished()) { mThreadPool.waitFinished(); mThreadPool.handleFinished(); } } void eGameBoard::addFulfilledQuest(const ePlayerId pid, const eGodQuest q) { const auto p = boardPlayerWithId(pid); if(!p) return; p->addFulfilledQuest(q); } void eGameBoard::addSlayedMonster(const eCityId cid, const eMonsterType m) { const auto c = boardCityWithId(cid); if(!c) return; c->monsterSlayed(m); const auto pid = cityIdToPlayerId(cid); const auto p = boardPlayerWithId(pid); if(!p) return; p->addSlayedMonster(m); } std::vector<eGodQuest> eGameBoard::fulfilledQuests(const ePlayerId pid) const { const auto p = boardPlayerWithId(pid); if(!p) return {}; return p->fulfilledQuests(); } std::vector<eMonsterType> eGameBoard::slayedMonsters(const ePlayerId pid) const { const auto p = boardPlayerWithId(pid); if(!p) return {}; return p->slayedMonsters(); } bool eGameBoard::wasHeroSummoned(const eCityId cid, const eHeroType hero) const { const auto c = boardCityWithId(cid); if(!c) return false; return c->wasHeroSummoned(hero); } void eGameBoard::heroSummoned(const eCityId cid, const eHeroType hero) { const auto c = boardCityWithId(cid); if(!c) return; c->heroSummoned(hero); } int eGameBoard::price(const eResourceType type) const { const auto it = mPrices.find(type); if(it == mPrices.end()) return 0; return it->second; } void eGameBoard::incPrice(const eResourceType type, const int by) { mPrices[type] += by; } void eGameBoard::changeWage(const int per) { const double mult = 1 + per/100.; mWageMultiplier *= mult; } void eGameBoard::updateTerritoryBorders() { iterateOverAllTiles([](eTile* const tile) { tile->updateTerritoryBorder(); }); for(const auto& c : mCitiesOnBoard) { c->updateTiles(); } } void eGameBoard::assignAllTerritory(const eCityId cid) { iterateOverAllTiles([cid](eTile* const tile) { tile->setCityId(cid); }); updateTerritoryBorders(); } std::vector<eCityId> eGameBoard::personPlayerCitiesOnBoard() const { return playerCitiesOnBoard(personPlayer()); } ePlayerId eGameBoard::cityIdToPlayerId(const eCityId cid) const { return mWorld.cityIdToPlayerId(cid); } eTeamId eGameBoard::cityIdToTeamId(const eCityId cid) const { const auto pid = cityIdToPlayerId(cid); return playerIdToTeamId(pid); } eTeamId eGameBoard::playerIdToTeamId(const ePlayerId pid) const { return mWorld.playerIdToTeamId(pid); } void eGameBoard::moveCityToPlayer(const eCityId cid, const ePlayerId pid) { const auto oldPid = cityIdToPlayerId(cid); const auto c = boardCityWithId(cid); if(c) { if(oldPid == ePlayerId::neutralAggresive || oldPid == ePlayerId::neutralFriendly) { mActiveCitiesOnBoard.push_back(c); c->acquired(); } c->sendAllReinforcementsHome(); } return mWorld.moveCityToPlayer(cid, pid); } void eGameBoard::setPlayerTeam(const ePlayerId pid, const eTeamId tid) { mWorld.setPlayerTeam(pid, tid); } std::vector<eCityId> eGameBoard::playerCities(const ePlayerId pid) const { return mWorld.playerCities(pid); } eCityId eGameBoard::currentCityId() const { return mWorld.currentCityId(); } stdsptr<eWorldCity> eGameBoard::currentCity() const { return mWorld.currentCity(); } eCityId eGameBoard::playerCapital(const ePlayerId pid) const { return mWorld.playerCapital(pid); } std::vector<eCityId> eGameBoard::playerCitiesOnBoard(const ePlayerId pid) const { std::vector<eCityId> result; for(const auto& c : mCitiesOnBoard) { const auto cid = c->id(); const auto ppid = cityIdToPlayerId(cid); if(pid == ppid) { result.push_back(cid); } } return result; } ePlayerId eGameBoard::personPlayer() const { return mWorld.personPlayer(); } eCityId eGameBoard::personPlayerCapital() const { const auto ppid = personPlayer(); return playerCapital(ppid); } eBoardCity* eGameBoard::boardCityWithId(const eCityId cid) const { for(const auto& c : mCitiesOnBoard) { if(c->id() == cid) return c.get(); } return nullptr; } SDL_Rect eGameBoard::boardCityTileBRect(const eCityId cid) const { for(const auto& c : mCitiesOnBoard) { if(c->id() == cid) return c->tileBRect(); } return SDL_Rect{0, 0, 0, 0}; } eBoardPlayer* eGameBoard::boardPlayerWithId(const ePlayerId pid) const { for(const auto& p : mPlayersOnBoard) { if(p->id() == pid) return p.get(); } return nullptr; } std::vector<eCityId> eGameBoard::citiesOnBoard() const { std::vector<eCityId> result; for(const auto& c : mCitiesOnBoard) { result.push_back(c->id()); } return result; } std::vector<ePlayerId> eGameBoard::playersOnBoard() const { std::vector<ePlayerId> result; for(const auto& c : mCitiesOnBoard) { const auto cid = c->id(); const auto pid = cityIdToPlayerId(cid); if(pid == ePlayerId::neutralFriendly || pid == ePlayerId::neutralAggresive) continue; if(eVectorHelpers::contains(result, pid)) continue; result.push_back(pid); } return result; } std::string eGameBoard::cityName(const eCityId cid) const { return mWorld.cityName(cid); } std::vector<eCityId> eGameBoard::allyCidsNotOnBoard(const ePlayerId pid) const { std::vector<eCityId> result; const auto tid = playerIdToTeamId(pid); const auto& cities = mWorld.cities(); for(const auto& c : cities) { const bool onBoard = c->isOnBoard(); if(onBoard) continue; const auto cid = c->cityId(); const auto cpid = cityIdToPlayerId(cid); if(cpid == pid) continue; const auto ctid = playerIdToTeamId(cpid); if(tid != ctid) continue; result.push_back(cid); } return result; } std::vector<eCityId> eGameBoard::enemyCidsOnBoard(const eTeamId ptid) const { std::vector<eCityId> result; for(const auto c : mActiveCitiesOnBoard) { const auto cid = c->id(); const auto ctid = cityIdToTeamId(cid); if(ctid == eTeamId::neutralFriendly) continue; if(ctid == eTeamId::neutralAggresive) continue; if(ctid == ptid) continue; result.push_back(cid); } return result; } void eGameBoard::updatePlayersOnBoard() { const auto ps = mPlayersOnBoard; for(const auto& p : ps) { const auto pid = p->id(); const auto cids = playerCitiesOnBoard(pid); if(cids.empty()) removePlayerFromBoard(pid); } for(const auto& c : mCitiesOnBoard) { const auto cid = c->id(); const auto pid = cityIdToPlayerId(cid); if(pid == ePlayerId::neutralAggresive || pid == ePlayerId::neutralFriendly) continue; const auto p = boardPlayerWithId(pid); if(p) continue; addPlayerToBoard(pid); } } eBoardPlayer* eGameBoard::addPlayerToBoard(const ePlayerId pid) { const auto p = std::make_shared<eBoardPlayer>(pid, *this); mPlayersOnBoard.push_back(p); return p.get(); } void eGameBoard::removePlayerFromBoard(const ePlayerId pid) { for(auto it = mPlayersOnBoard.begin(); it < mPlayersOnBoard.end(); it++) { const auto p = it->get(); if(p->id() != pid) continue; mPlayersOnBoard.erase(it); return; } } eBoardCity* eGameBoard::addCityToBoard(const eCityId cid) { const auto c = std::make_shared<eBoardCity>(cid, *this); mCitiesOnBoard.push_back(c); const auto pid = cityIdToPlayerId(cid); if(pid != ePlayerId::neutralFriendly && pid != ePlayerId::neutralAggresive) { mActiveCitiesOnBoard.push_back(c.get()); } mThreadPool.addBoard(cid); return c.get(); } void eGameBoard::removeCityFromBoard(const eCityId cid) { for(auto it = mActiveCitiesOnBoard.begin(); it < mActiveCitiesOnBoard.end(); it++) { const auto c = *it; if(c->id() != cid) continue; mActiveCitiesOnBoard.erase(it); break; } for(auto it = mCitiesOnBoard.begin(); it < mCitiesOnBoard.end(); it++) { const auto c = it->get(); if(c->id() != cid) continue; mCitiesOnBoard.erase(it); break; } mThreadPool.removeBoard(cid); } void eGameBoard::killCommonFolks(const eCityId cid, int toKill) { const auto c = boardCityWithId(cid); if(!c) return; c->killCommonFolks(toKill); } void eGameBoard::walkerKilled(const eCityId cid) { const auto c = boardCityWithId(cid); if(!c) return; c->walkerKilled(); } void eGameBoard::rockThrowerKilled(const eCityId cid) { const auto c = boardCityWithId(cid); if(!c) return; c->rockThrowerKilled(); } void eGameBoard::hopliteKilled(const eCityId cid) { const auto c = boardCityWithId(cid); if(!c) return; c->hopliteKilled(); } void eGameBoard::horsemanKilled(const eCityId cid) { const auto c = boardCityWithId(cid); if(!c) return; c->horsemanKilled(); } eEnlistedForces eGameBoard::getEnlistableForces(const ePlayerId pid) const { eEnlistedForces result; const auto cids = playerCitiesOnBoard(pid); for(const auto cid : cids) { const auto c = boardCityWithId(cid); const auto e = c->getEnlistableForces(); result.add(e); } const auto& cts = mWorld.cities(); for(const auto& c : cts) { if(!c->active()) continue; const auto cpid = c->playerId(); if(c->isOnBoard() && cpid == pid) continue; const auto type = c->type(); const auto rel = c->relationship(); const bool e = type == eCityType::colony || (type == eCityType::foreignCity && (rel == eForeignCityRelationship::ally || rel == eForeignCityRelationship::vassal)); if(e && c->attitude(pid) > 50) { result.fAllies.push_back(c); } } return result; } void eGameBoard::addMonsterEvent(const eMonsterType type, eMonsterInvasionEventBase * const e) { const auto cid = e->cityId(); const auto c = boardCityWithId(cid); if(!c) return; c->addMonsterEvent(type, e); } void eGameBoard::removeMonsterEvent(eMonsterInvasionEventBase * const e) { const auto cid = e->cityId(); const auto c = boardCityWithId(cid); if(!c) return; c->removeMonsterEvent(e); } eGameBoard::eQuests eGameBoard::godQuests(const ePlayerId pid) const { const auto p = boardPlayerWithId(pid); if(!p) return {}; return p->godQuests(); } void eGameBoard::addGodQuest(eGodQuestEvent* const q) { const auto cid = q->cityId(); const auto pid = cityIdToPlayerId(cid); const auto p = boardPlayerWithId(pid); if(!p) return; p->addGodQuest(q); if(mRequestUpdateHandler) mRequestUpdateHandler(); } void eGameBoard::removeGodQuest(eGodQuestEvent* const q) { const auto cid = q->cityId(); const auto pid = cityIdToPlayerId(cid); const auto p = boardPlayerWithId(pid); if(!p) return; p->removeGodQuest(q); if(mRequestUpdateHandler) mRequestUpdateHandler(); } eGameBoard::eRequests eGameBoard::cityRequests(const ePlayerId pid) const { const auto p = boardPlayerWithId(pid); if(!p) return {}; return p->cityRequests(); } void eGameBoard::addCityRequest(eReceiveRequestEvent* const q) { const auto cid = q->cityId(); const auto pid = cityIdToPlayerId(cid); const auto p = boardPlayerWithId(pid); if(!p) return; p->addCityRequest(q); if(mRequestUpdateHandler) mRequestUpdateHandler(); } void eGameBoard::removeCityRequest(eReceiveRequestEvent* const q) { const auto cid = q->cityId(); const auto pid = cityIdToPlayerId(cid); const auto p = boardPlayerWithId(pid); if(!p) return; p->removeCityRequest(q); if(mRequestUpdateHandler) mRequestUpdateHandler(); } eGameBoard::eTroopsRequests eGameBoard::cityTroopsRequests(const ePlayerId pid) const { const auto p = boardPlayerWithId(pid); if(!p) return {}; return p->cityTroopsRequests(); } void eGameBoard::addCityTroopsRequest(eTroopsRequestEvent* const q) { const auto cid = q->cityId(); const auto pid = cityIdToPlayerId(cid); const auto p = boardPlayerWithId(pid); if(!p) return; p->addCityTroopsRequest(q); if(mRequestUpdateHandler) mRequestUpdateHandler(); } void eGameBoard::removeCityTroopsRequest(eTroopsRequestEvent* const q) { const auto cid = q->cityId(); const auto pid = cityIdToPlayerId(cid); const auto p = boardPlayerWithId(pid); if(!p) return; p->removeCityTroopsRequest(q); if(mRequestUpdateHandler) mRequestUpdateHandler(); } eGameBoard::eConquests eGameBoard::conquests(const ePlayerId pid) const { const auto p = boardPlayerWithId(pid); if(!p) return {}; return p->conquests(); } void eGameBoard::addConquest(ePlayerConquestEventBase* const q) { const auto cid = q->cityId(); const auto pid = cityIdToPlayerId(cid); const auto p = boardPlayerWithId(pid); if(!p) return; p->addConquest(q); } void eGameBoard::removeConquest(ePlayerConquestEventBase* const q) { const auto cid = q->cityId(); const auto pid = cityIdToPlayerId(cid); const auto p = boardPlayerWithId(pid); if(!p) return; p->removeConquest(q); } eInvasionEvent* eGameBoard::invasionToDefend(const eCityId cid) const { const auto date = eGameBoard::date(); for(const auto i : mInvasions) { const auto icid = i->cityId(); if(icid != cid) continue; const auto t = i->landInvasionTile(); if(!t) continue; const auto sDate = i->nextDate(); if(sDate - date < 120) { return i; } } return nullptr; } void eGameBoard::addInvasion(eInvasionEvent* const i) { mInvasions.push_back(i); } void eGameBoard::removeInvasion(eInvasionEvent* const i) { eVectorHelpers::remove(mInvasions, i); } eGameBoard::eArmyEvents eGameBoard::armyEvents() const { return mArmyEvents; } void eGameBoard::addArmyEvent(eArmyEventBase* const q) { mArmyEvents.push_back(q); } void eGameBoard::removeArmyEvent(eArmyEventBase* const q) { eVectorHelpers::remove(mArmyEvents, q); } std::vector<eMonster*> eGameBoard::monsters(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return {}; return c->monsters(); } eGameBoard::eChars eGameBoard::attackingGods( const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return {}; return c->attackingGods(); } void eGameBoard::registerAttackingGod(const eCityId cid, eCharacter* const c) { const auto cc = boardCityWithId(cid); if(!c) return; cc->registerAttackingGod(c); updateMusic(); } void eGameBoard::startPlague(eSmallHouse* const h) { if(!h) return; const auto cid = h->cityId(); const auto c = boardCityWithId(cid); if(!c) return; c->startPlague(h); eEventData ed(cid); ed.fTile = h->centerTile(); event(eEvent::plague, ed); } stdsptr<ePlague> eGameBoard::plagueForHouse(eSmallHouse* const h) { if(!h) return nullptr; const auto cid = h->cityId(); const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->plagueForHouse(h); } void eGameBoard::healPlague(const stdsptr<ePlague>& p) { if(!p) return; const auto cid = p->cityId(); const auto c = boardCityWithId(cid); if(!c) return; return c->healPlague(p); } void eGameBoard::healHouse(eSmallHouse* const h) { const auto p = plagueForHouse(h); if(p) { if(p->houseCount() == 1) healPlague(p); else p->healHouse(h); } else { h->setPlague(false); } } eGameBoard::ePlagues eGameBoard::plagues(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return {}; return c->plagues(); } stdsptr<ePlague> eGameBoard::nearestPlague( const eCityId cid, const int tx, const int ty, int& dist) const { dist = 100000; const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->nearestPlague(tx, ty, dist); } void eGameBoard::updateMusic() { bool battle = false; const auto cids = personPlayerCitiesOnBoard(); for(const auto cid : cids) { const auto c = boardCityWithId(cid); if(!c) continue; const bool i = c->hasActiveInvasions(); if(i) { battle = true; break; } const bool a = !c->attackingGods().empty(); if(a) { battle = true; break; } for(const auto m : c->monsters()) { const auto a = m->action(); if(const auto ma = dynamic_cast<eMonsterAction*>(a)) { const auto stage = ma->stage(); if(stage == eMonsterAttackStage::none || stage == eMonsterAttackStage::wait) { continue; } battle = true; break; } } if(battle) break; } if(battle) { eMusic::playRandomBattleMusic(); } else { eMusic::playRandomMusic(); } } eTile* eGameBoard::entryPoint(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->entryPoint(); } eTile* eGameBoard::exitPoint(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->exitPoint(); } eTile *eGameBoard::riverEntryPoint(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->riverEntryPoint(); } eTile *eGameBoard::riverExitPoint(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->riverExitPoint(); } void eGameBoard::editorClearBuildings() { for(const auto& c : mCitiesOnBoard) { c->editorClearBuildings(); } } void eGameBoard::editorDisplayBuildings() { for(const auto& c : mCitiesOnBoard) { c->editorDisplayBuildings(); } } void eGameBoard::saveEditorCityPlan() { for(const auto& c : mCitiesOnBoard) { c->saveEditorCityPlan(); } } void eGameBoard::setCurrentDistrictId(const int id) { mCurrentDistrictId = id; for(const auto& c : mCitiesOnBoard) { c->setCurrentDistrictId(id); } } bool eGameBoard::atlantean(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return false; return c->atlantean(); } bool eGameBoard::setAtlantean(const eCityId cid, const bool a) { const auto c = boardCityWithId(cid); if(!c) return false; c->setAtlantean(a); return true; } void eGameBoard::registerSoldierBanner(const stdsptr<eSoldierBanner>& b) { if(b->militaryAid()) return; const auto cid = b->cityId(); const auto c = boardCityWithId(cid); if(!c) return; c->registerSoldierBanner(b); } bool eGameBoard::unregisterSoldierBanner(const stdsptr<eSoldierBanner>& b) { eVectorHelpers::remove(mSelectedBanners, b.get()); const auto cid = b->cityId(); const auto c = boardCityWithId(cid); if(!c) return false; return c->unregisterSoldierBanner(b); } void eGameBoard::addRootGameEvent(const stdsptr<eGameEvent>& e) { const auto cid = e->cityId(); const auto c = boardCityWithId(cid); c->addRootGameEvent(e); } void eGameBoard::removeRootGameEvent(const stdsptr<eGameEvent>& e) { const auto cid = e->cityId(); const auto c = boardCityWithId(cid); c->removeRootGameEvent(e); } void eGameBoard::addGameEvent(eGameEvent* const e) { mAllGameEvents.push_back(e); } void eGameBoard::removeGameEvent(eGameEvent* const e) { eVectorHelpers::remove(mAllGameEvents, e); } void eGameBoard::handleGamesBegin(const eGames game) { eGameMessages* msgs = nullptr; switch(game) { case eGames::isthmian: msgs = &eMessages::instance.fIsthmianGames; break; case eGames::nemean: msgs = &eMessages::instance.fNemeanGames; break; case eGames::pythian: msgs = &eMessages::instance.fPythianGames; break; case eGames::olympian: msgs = &eMessages::instance.fOlympianGames; break; } const auto pcids = personPlayerCitiesOnBoard(); for(const auto cid : pcids) { const auto c = boardCityWithId(cid); if(c->atlantean()) continue; const double chance = c->winningChance(game); eEventData ed(cid); if(chance > 0) { showMessage(ed, msgs->fBegin); } else { showMessage(ed, msgs->fNoPart); } } } void eGameBoard::handleGamesEnd(const eGames game) { eGameMessages* msgs = nullptr; switch(game) { case eGames::isthmian: msgs = &eMessages::instance.fIsthmianGames; break; case eGames::nemean: msgs = &eMessages::instance.fNemeanGames; break; case eGames::pythian: msgs = &eMessages::instance.fPythianGames; break; case eGames::olympian: msgs = &eMessages::instance.fOlympianGames; break; } using eCityChance = std::pair<eCityId, double>; std::vector<eCityChance> chances; for(const auto c : mActiveCitiesOnBoard) { if(c->atlantean()) continue; const auto id = c->id(); const double chance = c->winningChance(game); chances.push_back(eCityChance{id, chance}); } if(chances.empty()) return; std::random_shuffle(chances.begin(), chances.end()); eCityId winner = eCityId::neutralFriendly; for(const auto& c : chances) { const bool won = eRand::rand() % 101 < 100*c.second; if(!won) continue; const auto cid = c.first; const auto city = boardCityWithId(cid); if(won) { winner = cid; eEventData ed(cid); showMessage(ed, msgs->fWon); city->incWonGames(); int id = 0; switch(game) { case eGames::isthmian: id = 8; break; case eGames::nemean: id = 3; break; case eGames::pythian: id = 8; break; case eGames::olympian: { const auto pid = cityIdToPlayerId(cid); const auto& cs = mWorld.cities(); for(const auto& c : cs) { c->incAttitude(10., pid); } id = 8; } break; } allow(c.first, eBuildingType::commemorative, id); } break; } eCityId secondCid = eCityId::neutralFriendly; for(const auto& c : chances) { const auto cid = c.first; if(cid == winner) continue; const bool second = eRand::rand() % 101 < 200*c.second; eEventData ed(cid); if(second && secondCid == eCityId::neutralFriendly) { secondCid = cid; showMessage(ed, msgs->fSecond); } else { showMessage(ed, msgs->fLost); } } } bool eGameBoard::handleEpisodeCompleteEvents() { bool r = false; for(const auto& c : mCitiesOnBoard) { r = c->handleEpisodeCompleteEvents() || r; } return r; } eTile* eGameBoard::tile(const int x, const int y) const { int dtx; int dty; eTileHelper::tileIdToDTileId(x, y, dtx, dty); return dtile(dtx, dty); } eTile* eGameBoard::dtile(const int x, const int y) const { if(x < 0 || x >= mWidth) return nullptr; if(y < 0 || y >= mHeight) return nullptr; return mTiles[x][y]; } double eGameBoard::taxRateF(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 1.; return city->taxRateF(); } eTaxRate eGameBoard::taxRate(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return eTaxRate::normal; return city->taxRate(); } eWageRate eGameBoard::wageRate(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return eWageRate::normal; return city->wageRate(); } void eGameBoard::setTaxRate(const eCityId cid, const eTaxRate tr) { const auto city = boardCityWithId(cid); if(!city) return; return city->setTaxRate(tr); } void eGameBoard::setWageRate(const eCityId cid, const eWageRate wr) { const auto city = boardCityWithId(cid); if(!city) return; return city->setWageRate(wr); } int eGameBoard::taxesPaidThisYear(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 0; return city->taxesPaidThisYear(); } int eGameBoard::taxesPaidLastYear(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 0; return city->taxesPaidThisYear(); } int eGameBoard::peoplePaidTaxesThisYear(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 0; return city->taxesPaidThisYear(); } int eGameBoard::peoplePaidTaxesLastYear(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 0; return city->taxesPaidThisYear(); } int eGameBoard::philosophyResearchCoverage(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 0; return city->philosophyResearchCoverage(); } int eGameBoard::athleticsLearningCoverage(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 0; return city->athleticsLearningCoverage(); } int eGameBoard::dramaAstronomyCoverage(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 0; return city->dramaAstronomyCoverage(); } int eGameBoard::allCultureScienceCoverage(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 0; return city->allCultureScienceCoverage(); } int eGameBoard::taxesCoverage(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 0; return city->philosophyResearchCoverage(); } int eGameBoard::unrest(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 0; return city->unrest(); } int eGameBoard::popularity(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 0; return city->popularity(); } int eGameBoard::health(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return 0; return city->health(); } eCityFinances eGameBoard::finances(const eCityId cid) const { const auto pid = cityIdToPlayerId(cid); const auto p = boardPlayerWithId(pid); if(!p) return eCityFinances(); return p->finances(); } int eGameBoard::drachmas(const ePlayerId pid) const { const auto player = boardPlayerWithId(pid); if(!player) return 0; return player->drachmas(); } void eGameBoard::incDrachmas(const ePlayerId pid, const int by, const eFinanceTarget t) { const auto player = boardPlayerWithId(pid); if(!player) return; return player->incDrachmas(by, t); } void eGameBoard::setDrachmas(const ePlayerId pid, const int to) { const auto player = boardPlayerWithId(pid); if(!player) return; return player->setDrachmas(to); } void eGameBoard::registerCharacter(eCharacter* const c) { mCharacters.push_back(c); } bool eGameBoard::unregisterCharacter(eCharacter* const c) { bool updateMusic = false; for(const auto& cc : mCitiesOnBoard) { const bool r = cc->unregisterAttackingGod(c); updateMusic = updateMusic || r; } eVectorHelpers::remove(mSelectedTriremes, static_cast<eTrireme*>(c)); if(updateMusic) this->updateMusic(); return eVectorHelpers::remove(mCharacters, c); } void eGameBoard::registerCharacterAction(eCharacterAction* const ca) { mCharacterActions.push_back(ca); } bool eGameBoard::unregisterCharacterAction(eCharacterAction* const ca) { return eVectorHelpers::remove(mCharacterActions, ca); } void eGameBoard::registerSoldier(eSoldier* const c) { mSoldiers.push_back(c); } bool eGameBoard::unregisterSoldier(eSoldier* const c) { return eVectorHelpers::remove(mSoldiers, c); } void eGameBoard::registerBuilding(eBuilding* const b) { if(!mRegisterBuildingsEnabled) return; mAllBuildings.push_back(b); const auto bt = b->type(); if(eBuilding::sTimedBuilding(bt)) { mTimedBuildings.push_back(b); } const auto cid = b->cityId(); const auto city = boardCityWithId(cid); if(!city) return; city->registerBuilding(b); scheduleAppealMapUpdate(cid); } bool eGameBoard::unregisterBuilding(eBuilding* const b) { if(!mRegisterBuildingsEnabled) return false; eVectorHelpers::remove(mAllBuildings, b); const auto cid = b->cityId(); const auto city = boardCityWithId(cid); if(!city) return false; city->unregisterBuilding(b); eVectorHelpers::remove(mTimedBuildings, b); scheduleAppealMapUpdate(cid); return true; } bool eGameBoard::unregisterCommonHouse(eSmallHouse* const ch) { if(!mRegisterBuildingsEnabled) return false; const auto cid = ch->cityId(); const auto city = boardCityWithId(cid); return city->unregisterCommonHouse(ch); } void eGameBoard::registerEmplBuilding(eEmployingBuilding* const b) { if(!mRegisterBuildingsEnabled) return; const auto cid = b->cityId(); const auto city = boardCityWithId(cid); city->registerEmplBuilding(b); } bool eGameBoard::unregisterEmplBuilding(eEmployingBuilding* const b) { if(!mRegisterBuildingsEnabled) return false; const auto cid = b->cityId(); const auto city = boardCityWithId(cid); return city->unregisterEmplBuilding(b); } void eGameBoard::registerTradePost(eTradePost* const b) { if(!mRegisterBuildingsEnabled) return; const auto cid = b->cityId(); const auto city = boardCityWithId(cid); city->registerTradePost(b); if(mButtonVisUpdater) mButtonVisUpdater(); } bool eGameBoard::unregisterTradePost(eTradePost* const b) { if(!mRegisterBuildingsEnabled) return false; const auto cid = b->cityId(); const auto city = boardCityWithId(cid); const bool r = city->unregisterTradePost(b); if(r && mButtonVisUpdater) mButtonVisUpdater(); return r; } bool eGameBoard::hasTradePost(const eCityId cid, const eWorldCity& city) { const auto c = boardCityWithId(cid); if(!c) return false; return c->hasTradePost(city); } void eGameBoard::registerSpawner(eSpawner* const s) { mSpawners.push_back(s); } bool eGameBoard::unregisterSpawner(eSpawner* const s) { return eVectorHelpers::remove(mSpawners, s);; } void eGameBoard::registerStadium(eStadium* const s) { if(!mRegisterBuildingsEnabled) return; const auto cid = s->cityId(); const auto city = boardCityWithId(cid); city->registerStadium(s); if(mButtonVisUpdater) mButtonVisUpdater(); } void eGameBoard::unregisterStadium(const eCityId cid) { if(!mRegisterBuildingsEnabled) return; const auto city = boardCityWithId(cid); city->unregisterStadium(); if(mButtonVisUpdater) mButtonVisUpdater(); } void eGameBoard::registerMuseum(eMuseum* const s) { if(!mRegisterBuildingsEnabled) return; const auto cid = s->cityId(); const auto city = boardCityWithId(cid); city->registerMuseum(s); if(mButtonVisUpdater) mButtonVisUpdater(); } void eGameBoard::unregisterMuseum(const eCityId cid) { if(!mRegisterBuildingsEnabled) return; const auto city = boardCityWithId(cid); city->unregisterMuseum(); if(mButtonVisUpdater) mButtonVisUpdater(); } void eGameBoard::registerStorBuilding(eStorageBuilding* const b) { if(!mRegisterBuildingsEnabled) return; const auto cid = b->cityId(); const auto city = boardCityWithId(cid); city->registerStorBuilding(b); } bool eGameBoard::unregisterStorBuilding(eStorageBuilding* const b) { if(!mRegisterBuildingsEnabled) return false; const auto cid = b->cityId(); const auto city = boardCityWithId(cid); return city->unregisterStorBuilding(b); } void eGameBoard::registerSanctuary(eSanctuary* const b) { if(!mRegisterBuildingsEnabled) return; const auto cid = b->cityId(); const auto city = boardCityWithId(cid); city->registerSanctuary(b); if(mButtonVisUpdater) mButtonVisUpdater(); } bool eGameBoard::unregisterSanctuary(eSanctuary* const b) { if(!mRegisterBuildingsEnabled) return false; const auto cid = b->cityId(); const auto city = boardCityWithId(cid); const bool r = city->unregisterSanctuary(b); if(r && mButtonVisUpdater) mButtonVisUpdater(); return r; } void eGameBoard::registerMonument(eMonument* const b) { if(!mRegisterBuildingsEnabled) return; const auto cid = b->cityId(); const auto city = boardCityWithId(cid); city->registerMonument(b); if(mButtonVisUpdater) mButtonVisUpdater(); } bool eGameBoard::unregisterMonument(eMonument* const b) { if(!mRegisterBuildingsEnabled) return false; const auto cid = b->cityId(); const auto city = boardCityWithId(cid); const bool r = city->unregisterMonument(b); if(r && mButtonVisUpdater) mButtonVisUpdater(); return r; } void eGameBoard::registerHeroHall(eHerosHall* const b) { if(!mRegisterBuildingsEnabled) return; const auto cid = b->cityId(); const auto city = boardCityWithId(cid); city->registerHeroHall(b); } bool eGameBoard::unregisterHeroHall(eHerosHall* const b) { if(!mRegisterBuildingsEnabled) return false; const auto cid = b->cityId(); const auto city = boardCityWithId(cid); const bool r = city->unregisterHeroHall(b); if(r && mButtonVisUpdater) mButtonVisUpdater(); return r; } void eGameBoard::registerMissile(eMissile* const m) { mMissiles.push_back(m); } bool eGameBoard::unregisterMissile(eMissile* const m) { return eVectorHelpers::remove(mMissiles, m); } bool eGameBoard::hasStadium(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return false; return city->hasStadium(); } bool eGameBoard::hasMuseum(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return false; return city->hasMuseum(); } eStadium* eGameBoard::stadium(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return nullptr; return city->stadium(); } eMuseum* eGameBoard::museum(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return nullptr; return city->museum(); } void eGameBoard::registerPalace(ePalace* const p) { if(!mRegisterBuildingsEnabled) return; const auto cid = p->cityId(); const auto city = boardCityWithId(cid); if(!city) return; city->registerPalace(p); if(mButtonVisUpdater) mButtonVisUpdater(); } void eGameBoard::unregisterPalace(const eCityId cid) { if(!mRegisterBuildingsEnabled) return; const auto city = boardCityWithId(cid); if(!city) return; city->unregisterPalace(); if(mButtonVisUpdater) mButtonVisUpdater(); } void eGameBoard::registerMonster(const eCityId cid, eMonster* const m) { const auto c = boardCityWithId(cid); if(!c) return; return c->registerMonster(m); } void eGameBoard::unregisterMonster(const eCityId cid, eMonster* const m) { const auto c = boardCityWithId(cid); if(!c) return; return c->unregisterMonster(m); updateMusic(); } eBanner* eGameBoard::banner(const eCityId cid, const eBannerTypeS type, const int id) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->banner(type, id); } void eGameBoard::registerBanner(eBanner* const b) { const auto t = b->tile(); const auto cid = t->cityId(); const auto c = boardCityWithId(cid); if(!c) return; mBanners.push_back(b); return c->registerBanner(b); } void eGameBoard::unregisterBanner(eBanner* const b) { const auto t = b->tile(); const auto cid = t->cityId(); const auto c = boardCityWithId(cid); if(!c) return; eVectorHelpers::remove(mBanners, b); return c->unregisterBanner(b); } void eGameBoard::registerAllSoldierBanner(eSoldierBanner* const b) { mAllSoldierBanners.push_back(b); } void eGameBoard::unregisterAllSoldierBanner(eSoldierBanner* const b) { eVectorHelpers::remove(mAllSoldierBanners, b); eVectorHelpers::remove(mSelectedBanners, b); } bool eGameBoard::manTowers(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return false; return city->manTowers(); } void eGameBoard::setManTowers(const eCityId cid, const bool m) { const auto city = boardCityWithId(cid); if(!city) return; city->setManTowers(m); } std::vector<eAgoraBase*> eGameBoard::agoras(const eCityId cid) const { const auto city = boardCityWithId(cid); if(!city) return {}; return city->agoras(); } void eGameBoard::incTime(const int by) { if(mEpisodeLost) return; const int dayLen = eNumbers::sDayLength; { // autosave const int time = mTime + by; bool nextMonth = false; bool nextYear = false; const int nd = time/dayLen; auto date = mDate; date.nextDays(nd, nextMonth, nextYear); if(nextYear && date.year() > mSavedYear) { mSavedYear = date.year(); if(mAutosaver) mAutosaver(); } } const int iMax = mPlannedActions.size() - 1; for(int i = iMax; i >= 0; i--) { const auto a = mPlannedActions[i]; a->incTime(by, *this); if(a->finished()) { mPlannedActions.erase(mPlannedActions.begin() + i); delete a; } } // if(mTotalTime == 0) { //// receiveRequest(mWorldBoard->cities()[0], //// eResourceType::fleece, 9, 0); // planGiftFrom(mWorldBoard->cities()[0], // eResourceType::fleece, 16); // } // for(const auto& p : mPlagues) { // const int r = eRand::rand() % 5000; // const bool spread = r/by == 0; // if(spread) p->randomSpread(); // } mProgressEarthquakes += by; const int earthquakeWait = eNumbers::sEarthquakeProgressPeriod; if(mProgressEarthquakes > earthquakeWait) { mProgressEarthquakes -= earthquakeWait; progressEarthquakes(); } mProgressWaves += by; const int tidalWaveWait = 250; if(mProgressWaves > tidalWaveWait) { mProgressWaves -= tidalWaveWait; progressTidalWaves(); } mProgressLavaFlows += by; const int lavaFlowWait = 250; if(mProgressLavaFlows > lavaFlowWait) { mProgressLavaFlows -= lavaFlowWait; progressLavaFlow(); } mProgressLandSlides += by; const int landSlideWait = 250; if(mProgressLandSlides > landSlideWait) { mProgressLandSlides -= landSlideWait; progressLandSlide(); } mSoldiersUpdate += by; const int sup = 1000; if(mSoldiersUpdate > sup) { mSoldiersUpdate -= sup; for(const auto& c : mCitiesOnBoard) { c->soldierBannersUpdate(); } } for(const auto& c : mActiveCitiesOnBoard) { c->incTime(by); } for(const auto& p : mPlayersOnBoard) { p->incTime(by); if(mTotalTime == 0) { // start building AI cities p->nextMonth(); } } mTime += by; mTotalTime += by; bool nextMonth = false; bool nextYear = false; const int nd = mTime/dayLen; mDate.nextDays(nd, nextMonth, nextYear); mTime -= nd*dayLen; if(nextYear) { for(auto& y : mYearlyProduction) { auto& p = y.second; p.fLastYear = p.fThisYear; p.fThisYear = 0; if(p.fLastYear > p.fBest) p.fBest = p.fLastYear; } for(const auto& c : mActiveCitiesOnBoard) { c->nextYear(); } const auto ppcs = personPlayerCitiesOnBoard(); for(const auto cid : ppcs) { auto& defs = mDefeatedBy[cid]; for(const auto& cc : defs) { if(!cc->isRival()) continue; const auto rr = e::make_shared<eReceiveRequestEvent>( cid, eGameEventBranch::root, *this); const auto type = cc->recTributeType(); const int count = cc->recTributeCount(); rr->initialize(0, type, count, cc, false); rr->setRequestType(eReceiveRequestType::tribute); rr->initializeDate(mDate); addRootGameEvent(rr); } } } if(nextMonth) { for(const auto& c : mActiveCitiesOnBoard) { c->nextMonth(); } for(const auto& p : mPlayersOnBoard) { p->nextMonth(); } const auto m = mDate.month(); const int ng = std::abs(mDate.year() % 4); const auto game = static_cast<eGames>(ng); if(m == eMonth::june) { handleGamesBegin(game); } else if(m == eMonth::august) { handleGamesEnd(game); } } const int ect = 5000; mEmploymentCheckTime += by; if(mEmploymentCheckTime > ect) { mEmploymentCheckTime -= ect; const auto ppcs = personPlayerCitiesOnBoard(); for(const auto cid : ppcs) { const auto c = boardCityWithId(cid); const auto& emplData = c->employmentData(); const double employable = emplData.employable(); const double jobVacs = emplData.totalJobVacancies(); int emplState = 0; if(employable < jobVacs*0.75) { emplState = 1; } else if(employable > jobVacs*1.25) { emplState = -1; } else { emplState = 0; } auto& les = mLastEmploymentState[cid]; if(les.fV != emplState) { const auto& inst = eMessages::instance; eEventData ed(cid); if(emplState == -1) { // unemployed showMessage(ed, inst.fUnemployment); } else if(emplState == 1) { // employed showMessage(ed, inst.fEmployees); } } les.fV = emplState; } } if(nextMonth) { mWorld.nextMonth(this); } if(nextYear) { mWorld.nextYear(); const auto ppid = personPlayer(); const auto cs = mWorld.getTribute(); for(const auto& c : cs) { if(c->conqueredByRival()) continue; tributeFrom(ppid, c, true); } } const auto chars = mCharacters; for(const auto c : chars) { if(c->isSoldier()) continue; c->incTime(by); } const auto solds = mSoldiers; for(const auto c : solds) { c->incTime(by); } const auto build = mTimedBuildings; for(const auto b : build) { b->incTime(by); if(nextMonth) b->nextMonth(); } for(const auto s : mSpawners) { s->incTime(by); } const auto missiles = mMissiles; for(const auto m : missiles) { m->incTime(by); } const int goalsCheckWait = 5050; mGoalsCheckTime += by; if(mGoalsCheckTime > goalsCheckWait) { mGoalsCheckTime -= goalsCheckWait; const bool f = checkGoalsFulfilled(); if(f || mGoalsFulfilled) { mGoalsFulfilled = true; const bool r = handleEpisodeCompleteEvents(); if(!r && mEpisodeFinishedHandler) { mGoalsFulfilled = false; mEpisodeFinishedHandler(); } else { mGoalsCheckTime = goalsCheckWait; } } } for(const auto& c : mActiveCitiesOnBoard) { c->incDistributeEmployees(by); } } void eGameBoard::incFrame() { mFrame++; } void eGameBoard::handleFinishedTasks() { mThreadPool.handleFinished(); } void eGameBoard::scheduleDataUpdate() { mThreadPool.scheduleDataUpdate(); } int eGameBoard::population(const ePlayerId pid) const { int result = 0; const auto cids = playerCitiesOnBoard(pid); for(const auto cid : cids) { result += population(cid); } return result; } int eGameBoard::population(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->population(); } ePopulationData* eGameBoard::populationData(const eCityId cid) { const auto c = boardCityWithId(cid); if(!c) return nullptr; return &c->populationData(); } eHusbandryData* eGameBoard::husbandryData(const eCityId cid) { const auto c = boardCityWithId(cid); if(!c) return nullptr; return &c->husbandryData(); } eEmploymentData* eGameBoard::employmentData(const eCityId cid) { const auto c = boardCityWithId(cid); if(!c) return nullptr; return &c->employmentData(); } eEmploymentDistributor* eGameBoard::employmentDistributor(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return &c->employmentDistributor(); } void eGameBoard::addShutDown(const eCityId cid, const eResourceType type) { const auto c = boardCityWithId(cid); if(!c) return; c->addShutDown(type); } void eGameBoard::removeShutDown(const eCityId cid, const eResourceType type) { const auto c = boardCityWithId(cid); if(!c) return; c->removeShutDown(type); } int eGameBoard::industryJobVacancies(const eCityId cid, const eResourceType type) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->industryJobVacancies(type); } void eGameBoard::distributeEmployees( const eCityId cid, const eSector s) { const auto c = boardCityWithId(cid); if(!c) return; c->distributeEmployees(s); } void eGameBoard::distributeEmployees(const eCityId cid) { const auto c = boardCityWithId(cid); if(!c) return; c->distributeEmployees(); } void eGameBoard::payTaxes(const eCityId cid, const int d, const int people) { const auto c = boardCityWithId(cid); if(!c) return; c->payTaxes(d, people); const auto pid = cityIdToPlayerId(cid); const auto p = boardPlayerWithId(pid); if(!p) return; p->incDrachmas(d, eFinanceTarget::taxesIn); } void eGameBoard::setDifficulty(const eDifficulty d) { std::map<eDifficulty, eDifficulty> rivalDiff = {{eDifficulty::beginner, eDifficulty::olympian}, {eDifficulty::mortal, eDifficulty::titan}, {eDifficulty::hero, eDifficulty::hero}, {eDifficulty::titan, eDifficulty::mortal}, {eDifficulty::olympian, eDifficulty::beginner}}; std::map<eDifficulty, eDifficulty> allyDiff = {{eDifficulty::beginner, eDifficulty::beginner}, {eDifficulty::mortal, eDifficulty::mortal}, {eDifficulty::hero, eDifficulty::hero}, {eDifficulty::titan, eDifficulty::titan}, {eDifficulty::olympian, eDifficulty::olympian}}; const auto ppid = personPlayer(); const auto ptid = playerIdToTeamId(ppid); for(const auto& p : mPlayersOnBoard) { const auto pid = p->id(); eDifficulty pd; if(pid == ppid) { pd = d; } else { const auto tid = playerIdToTeamId(pid); if(tid == ptid) { pd = allyDiff[d]; } else { pd = rivalDiff[d]; } } setDifficulty(pid, pd); } } void eGameBoard::setDifficulty(const ePlayerId pid, const eDifficulty d) { const auto p = boardPlayerWithId(pid); if(!p) return; p->setDifficulty(d); } eDifficulty eGameBoard::personPlayerDifficulty() const { return difficulty(personPlayer()); } eDifficulty eGameBoard::difficulty(const ePlayerId pid) const { const auto p = boardPlayerWithId(pid); if(!p) return eDifficulty::beginner; return p->difficulty(); } void eGameBoard::setDate(const eDate& d) { mDate = d; } double eGameBoard::appeal(const int tx, const int ty) const { return mAppealMap.heat(tx, ty); } void eGameBoard::addRubbish(const stdsptr<eObject>& o) { mRubbish.push_back(o); } void eGameBoard::emptyRubbish() { while(!mRubbish.empty()) { std::vector<stdsptr<eObject>> r; std::swap(mRubbish, r); } } void eGameBoard::setRequestUpdateHandler(const eAction& ru) { mRequestUpdateHandler = ru; } void eGameBoard::setEventHandler(const eEventHandler& eh) { mEventHandler = eh; } void eGameBoard::event(const eEvent e, eEventData& ed) { if(mEventHandler) mEventHandler(e, ed); } void eGameBoard::setEpisodeFinishedHandler(const eAction& a) { mEpisodeFinishedHandler = a; } void eGameBoard::setAutosaver(const eAction& a) { mAutosaver = a; } void eGameBoard::setVisibilityChecker(const eVisibilityChecker& vc) { mVisibilityChecker = vc; } void eGameBoard::setTipShower(const eTipShower& ts) { mTipShower = ts; } void eGameBoard::showTip(const ePlayerCityTarget& target, const std::string& tip) const { if(mTipShower) mTipShower(target, tip); } void eGameBoard::setEnlistForcesRequest(const eEnlistRequest& req) { mEnlistRequester = req; } void eGameBoard::requestForces(const eEnlistAction& action, const std::vector<eResourceType>& plunderResources, const std::vector<stdsptr<eWorldCity>>& exclude, const bool onlySoldiers) { if(mEnlistRequester) { const auto ppid = personPlayer(); const auto baseCids = playerCitiesOnBoard(ppid); std::vector<eCityId> cids; for(const auto cid : baseCids) { bool e = false; for(const auto& ee : exclude) { const auto eCid = ee->cityId(); if(cid == eCid) { e = true; break; } } if(e) continue; cids.push_back(cid); } std::vector<std::string> cnames; for(const auto cid : cids) { const auto n = cityName(cid); cnames.push_back(n); } auto f = getEnlistableForces(ppid); if(onlySoldiers) { f.fHeroes.clear(); f.fAllies.clear(); f.fAres = false; } const auto ss = f.fSoldiers; for(const auto& c : exclude) { const auto cid = c->cityId(); for(const auto& s : ss) { const auto sCid = s->cityId(); if(cid != sCid) continue; eVectorHelpers::remove(f.fSoldiers, s); } } std::vector<eHeroType> heroesAbroad; for(const auto h : f.fHeroes) { const auto hh = heroHall(h.first, h.second); const bool abroad = !hh ? true : hh->heroOnQuest(); if(abroad) heroesAbroad.push_back(h.second); } for(const auto& e : exclude) { eVectorHelpers::remove(f.fAllies, e); } mEnlistRequester(f, cids, cnames, heroesAbroad, action, plunderResources); } } bool eGameBoard::ifVisible(eTile* const tile, const eAction& func) const { if(!tile) return false; if(!mVisibilityChecker) return false; const bool r = mVisibilityChecker(tile); if(r) func(); return r; } void eGameBoard::setMessageShower(const eMessageShower& msg) { mMsgShower = msg; } void eGameBoard::showMessage(eEventData& ed, const eMessageType& msg) { mMsgShower(ed, msg); } void eGameBoard::updateNeighbours() { for(int x = 0; x < mWidth; x++) { for(int y = 0; y < mHeight; y++) { const auto t = mTiles[x][y]; { const int dx = y % 2 == 0 ? -1 : 0; t->setTopLeft(dtile(x + dx, y - 1)); t->setBottomLeft(dtile(x + dx, y + 1)); } { const int dx = y % 2 == 0 ? 0 : 1; t->setTopRight(dtile(x + dx, y - 1)); t->setBottomRight(dtile(x + dx, y + 1)); } } } } void eGameBoard::updateResources(const eCityId cid) { const auto c = boardCityWithId(cid); if(!c) return; return c->updateResources(); } const eGameBoard::eResources* eGameBoard::resources(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return &c->resources(); } ePalace* eGameBoard::palace(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->palace(); } bool eGameBoard::hasPalace(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return false; return c->hasPalace(); } int eGameBoard::resourceCount(const eCityId cid, const eResourceType type) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->resourceCount(type); } int eGameBoard::takeResource(const eCityId cid, const eResourceType type, const int count) { const auto c = boardCityWithId(cid); if(!c) return 0; return c->takeResource(type, count); } int eGameBoard::eliteHouses(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->eliteHouses(); } int eGameBoard::maxSanctuaries(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->maxSanctuaries(); } std::vector<eSanctuary*> eGameBoard::sanctuaries(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return {}; return c->sanctuaries(); } eSanctuary* eGameBoard::sanctuary(const eCityId cid, const eGodType god) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->sanctuary(god); } std::vector<ePyramid*> eGameBoard::pyramids(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return {}; return c->pyramids(); } ePyramid* eGameBoard::pyramid(const eCityId cid, const eBuildingType type) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->pyramid(type); } std::vector<eHerosHall*> eGameBoard::heroHalls(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return {}; return c->heroHalls(); } eHerosHall* eGameBoard::heroHall(const eCityId cid, const eHeroType hero) const { const auto c = boardCityWithId(cid); if(!c) return nullptr; return c->heroHall(hero); } std::vector<stdsptr<eSoldierBanner>> eGameBoard::banners(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return {}; return c->banners(); } int eGameBoard::countBanners(const eBannerType bt, const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->countBanners(bt); } int eGameBoard::countSoldiers(const eBannerType bt, const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->countSoldiers(bt); } int eGameBoard::countWorkingTriremes(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return 0; return c->countWorkingTriremes(); } void eGameBoard::startEpisode(eEpisode* const e, const eWC& lastPlayedColony) { if(mTimedBuildings.empty()) { // first episode for(const auto s : mSpawners) { const auto type = s->type(); if(type == eBannerTypeS::boar || type == eBannerTypeS::deer || type == eBannerTypeS::wolf) { s->spawnMax(); } } } mDefeatedBy.clear(); for(const auto& c : mCitiesOnBoard) { c->clearAfterLastEpisode(); } mGoals.clear(); const auto& date = e->fStartDate; mSavedYear = date.year(); setDate(date); for(const auto& d : e->fDrachmas) { setDrachmas(d.first, d.second); } mWageMultiplier = e->fWageMultiplier; mPrices = e->fPrices; for(const auto& c : mCitiesOnBoard) { c->startEpisode(e); } const auto& gs = e->fGoals; for(const auto& g : gs) { const auto gg = g->makeCopy(); gg->initializeDate(*this); gg->update(*this); mGoals.push_back(gg); } if(lastPlayedColony) { const auto a = new eColonyMonumentAction(lastPlayedColony); planAction(a); } loadResources(); } void eGameBoard::loadResources() { for(const auto& c : mCitiesOnBoard) { c->loadResources(); } } bool eGameBoard::checkGoalsFulfilled() const { if(mGoals.empty()) return false; bool result = true; for(const auto& g : mGoals) { g->update(*this); const bool m = g->met(); if(!m) result = false; } return result; } void eGameBoard::musterAllSoldiers(const eCityId cid) { const auto c = boardCityWithId(cid); if(!c) return; c->musterAllSoldiers(); } void eGameBoard::sendAllSoldiersHome(const eCityId cid) { const auto c = boardCityWithId(cid); if(!c) return; c->sendAllSoldiersHome(); } void eGameBoard::incPopulation(const eCityId cid, const int by) { const auto c = boardCityWithId(cid); if(!c) return; return c->incPopulation(by); } void eGameBoard::topElevationExtremas(int& min, int& max) const { min = 10000; max = -10000; for(int x = 0; x < mWidth; x++) { const auto t = dtile(x, 0); const int a = t->altitude(); min = std::min(min, a); max = std::max(max, a); } } void eGameBoard::rightElevationExtremas(int& min, int& max) const { min = 10000; max = -10000; for(int y = 0; y < mHeight; y++) { const auto t = dtile(mWidth - 1, y); const int a = t->altitude(); min = std::min(min, a); max = std::max(max, a); } } void eGameBoard::bottomElevationExtremas(int& min, int& max) const { min = 10000; max = -10000; for(int x = 0; x < mWidth; x++) { const auto t = dtile(x, mHeight - 1); const int a = t->altitude(); min = std::min(min, a); max = std::max(max, a); } } void eGameBoard::leftElevationExtremas(int& min, int& max) const { min = 10000; max = -10000; for(int y = 0; y < mHeight; y++) { const auto t = dtile(0, y); const int a = t->altitude(); min = std::min(min, a); max = std::max(max, a); } } void eGameBoard::minMaxAltitude(int& min, int& max) const { min = 10000; max = -10000; for(int x = 0; x < mWidth; x++) { for(int y = 0; y < mHeight; y++) { const auto t = dtile(x, y); const int a = t->altitude(); if(a > max) max = a; if(a < min) min = a; } } } bool eGameBoard::landTradeShutdown(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return false; return c->landTradeShutdown(); } void eGameBoard::setLandTradeShutdown( const eCityId cid, const bool s) { const auto c = boardCityWithId(cid); if(!c) return; return c->setLandTradeShutdown(s); } bool eGameBoard::seaTradeShutdown(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return false; return c->seaTradeShutdown(); } void eGameBoard::setSeaTradeShutdown( const eCityId cid, const bool s) { const auto c = boardCityWithId(cid); if(!c) return; return c->setSeaTradeShutdown(s); } eMilitaryAid* eGameBoard::militaryAid(const eCityId cid, const stdsptr<eWorldCity>& c) const { const auto cc = boardCityWithId(cid); if(!cc) return nullptr; return cc->militaryAid(c); } void eGameBoard::removeMilitaryAid(const eCityId cid, const stdsptr<eWorldCity>& c) { const auto cc = boardCityWithId(cid); if(!cc) return; cc->removeMilitaryAid(c); } void eGameBoard::addMilitaryAid(const eCityId cid, const stdsptr<eMilitaryAid>& a) { const auto c = boardCityWithId(cid); if(!c) return; c->addMilitaryAid(a); } void eGameBoard::setEpisodeLost() const { mEpisodeLost = true; } int eGameBoard::tradingPartners() const { int n = 0; const auto ppid = personPlayer(); const auto& wrld = world(); for(const auto& c : wrld.cities()) { if(c->isRival()) continue; if(c->isCurrentCity()) continue; if(!c->active()) continue; if(!c->visible()) continue; const auto tradeCid = c->cityId(); const auto tradePid = cityIdToPlayerId(tradeCid); const auto tradeTid = playerIdToTeamId(tradePid); const auto tid = playerIdToTeamId(ppid); if(eTeamIdHelpers::isEnemy(tradeTid, tid)) continue; n++; } return n; } eOrientation randomOrientation() { std::vector<eOrientation> os{eOrientation::topRight, eOrientation::bottomRight, eOrientation::bottomLeft, eOrientation::topLeft}; return os[eRand::rand() % os.size()]; } void eGameBoard::earthquake(eTile* const startTile, const int size) { struct eQuakeEnd { eTile* fTile = nullptr; eOrientation fLastO = randomOrientation(); }; const auto quake = std::make_shared<eEarthquake>(); mEarthquakes.push_back(quake); std::queue<eQuakeEnd> ends; quake->fStartTile = startTile; auto& tiles = quake->fTiles; tiles.push_back(startTile); ends.push({startTile}); // std::vector<eOrientation> os{eOrientation::topRight, // eOrientation::bottomRight, // eOrientation::bottomLeft, // eOrientation::topLeft}; // std::random_shuffle(os.begin(), os.end()); // for(int i = 0; i < 2; i++) { // const auto o = os[i]; // const auto tt = startTile->neighbour<eTile>(o); // ends.push({tt}); // mEarthquake.push_back(tt); // } while((int)tiles.size() < size && !ends.empty()) { const auto t = ends.front(); ends.pop(); std::vector<eOrientation> os{eOrientation::topRight, eOrientation::bottomRight, eOrientation::bottomLeft, eOrientation::topLeft}; std::random_shuffle(os.begin(), os.end()); if(eRand::rand() % 7) { os.insert(os.begin(), t.fLastO); } for(const auto o : os) { const auto tt = t.fTile->neighbour<eTile>(o); if(!tt) continue; const auto terr = tt->terrain(); if(terr == eTerrain::dry || terr == eTerrain::fertile || terr == eTerrain::forest || terr == eTerrain::choppedForest) { ends.push({tt, o}); tiles.push_back(tt); if(eRand::rand() % 5 == 0) { ends.push({tt}); } break; } } } } bool eGameBoard::duringEarthquake() const { return !mEarthquakes.empty(); } void eGameBoard::defeatedBy(const eCityId defeated, const stdsptr<eWorldCity>& by) { auto& defs = mDefeatedBy[defeated]; const bool r = eVectorHelpers::contains(defs, by); if(r) { const auto ccid = currentCityId(); if(defeated == ccid) setEpisodeLost(); } else { defs.push_back(by); } } eImmigrationLimitedBy eGameBoard::immigrationLimit(const eCityId cid) const { const auto c = boardCityWithId(cid); if(!c) return eImmigrationLimitedBy::none; return c->immigrationLimit(); } void eGameBoard::earthquakeWaveCollapse(eTile* const t) { bool playSound = true; if(const auto ub = t->underBuilding()) { const auto type = ub->type(); const bool s = eBuilding::sSanctuaryBuilding(type); if(s) { } else if(type == eBuildingType::ruins) { ub->erase(); } else { if(const auto as = dynamic_cast<eAgoraSpace*>(ub)) { const auto a = as->agora(); a->collapse(); } else if(const auto v = dynamic_cast<eVendor*>(ub)) { const auto a = v->agora(); a->collapse(); } else if(const auto r = dynamic_cast<eRoad*>(ub)) { const auto a = r->underAgora(); if(a) a->collapse(); const auto g = r->underGatehouse(); if(g) g->collapse(); r->eBuilding::erase(); playSound = a || g; } else { if(type == eBuildingType::park) { scheduleTerrainUpdate(); } ub->collapse(); } if(playSound) eSounds::playCollapseSound(); } } for(const auto& c : t->characters()) { c->killWithCorpse(); } } void eGameBoard::progressEarthquakes() { if(mEarthquakes.empty()) return; eSounds::playEarthquakeSound(); for(int i = 0; i < (int)mEarthquakes.size(); i++) { const auto& e = mEarthquakes[i]; const auto st = e->fStartTile; const int stx = st->x(); const int sty = st->y(); const auto prcs = [this, e, stx, sty](const int x, const int y) { const int tx = stx + x; const int ty = sty + y; const auto t = tile(tx, ty); if(!t) return false; const bool r = eVectorHelpers::contains(e->fTiles, t); if(!r) return false; t->setTerrain(eTerrain::quake); t->scheduleNeighboursTerrainUpdate(); const auto cid = t->cityId(); const auto c = boardCityWithId(cid); if(c) c->incTerrainState(); earthquakeWaveCollapse(t); eVectorHelpers::removeAll(e->fTiles, t); return false; }; eIterateSquare::iterateSquare(e->fLastDim, prcs); e->fLastDim++; if(e->fTiles.empty() || e->fLastDim > 50) { eVectorHelpers::remove(mEarthquakes, e); i--; } } } void eGameBoard::progressTidalWaves() { if(mTidalWaves.empty()) return; eSounds::playBeachSound(); for(int i = 0; i < (int)mTidalWaves.size(); i++) { const auto& w = mTidalWaves[i]; if(w->fLastId >= 0 && w->fLastId < (int)w->fTiles.size()) { const std::vector<eWaveDirection>& tiles = w->fTiles[w->fLastId]; for(const auto& wd : tiles) { const auto t = wd.fTile; const auto o = wd.fO; std::vector<ePathPoint> path; eTile* from = nullptr; eTile* to = nullptr; if(w->fRegres) { from = t; to = t->neighbour<eTile>(!o); t->setTerrain(wd.fSaved); } else { from = t->neighbour<eTile>(!o); to = t; t->setTerrain(eTerrain::water); } earthquakeWaveCollapse(t); const auto cid = t->cityId(); const auto c = boardCityWithId(cid); if(c) c->incTerrainState(); t->scheduleNeighboursTerrainUpdate(2); path.push_back({(double)from->x(), (double)from->y(), 0.}); path.push_back({(double)to->x(), (double)to->y(), 0.}); const auto m = e::make_shared<eWaveMissile>(*this, path); m->incTime(0); } } if(w->fRegres) w->fLastId--; else w->fLastId++; if(w->fLastId < 0 || w->fLastId >= (int)w->fTiles.size()) { if(w->fPermanent || w->fRegres) { eVectorHelpers::remove(mTidalWaves, w); i--; } else { w->fLastId--; w->fRegres = true; } } } } void eGameBoard::sinkLand(const eCityId cid, const int amount) { std::vector<eTile*> shore; { std::vector<eTile*> used; std::function<void(eTile* const)> addShore; addShore = [&](eTile* const t) { const auto tcid = t->cityId(); if(tcid != cid) return; const bool c = eVectorHelpers::contains(used, t); if(c) return; used.push_back(t); if(t->isShoreTile()) shore.push_back(t); const auto ns = t->neighbours(nullptr); for(const auto& n : ns) { addShore(static_cast<eTile*>(n.second)); } }; const auto c = boardCityWithId(cid); if(!c) return; const auto& tiles = c->tiles(); if(tiles.empty()) return; addShore(tiles[tiles.size()/2]); } const auto w = std::make_shared<eTidalWave>(); { std::vector<eTile*> used; const auto addNeighs = [&](eTile* const t, const int dist) { const auto ns = t->neighbours(nullptr); for(const auto& n : ns) { const auto tt = static_cast<eTile*>(n.second); if(tt->hasWater()) continue; const bool c = eVectorHelpers::contains(used, tt); if(c) continue; while((int)w->fTiles.size() < dist + 1) { w->fTiles.emplace_back(); } used.push_back(tt); w->fTiles[dist].push_back({tt, tt->terrain(), n.first}); } }; for(const auto s : shore) { addNeighs(s, 0); } for(int i = 0; i < (int)w->fTiles.size() && i < amount - 1; i++) { for(const auto t : w->fTiles[i]) { addNeighs(t.fTile, i + 1); } } } if(w->fTiles.empty()) return; w->fPermanent = true; mTidalWaves.push_back(w); } void eGameBoard::addTidalWave(eTile* const startTile, const bool permanent) { std::vector<eTile*> shore; { std::vector<eTile*> used; std::function<void(eTile* const)> addShore; addShore = [&](eTile* const t) { const bool c = eVectorHelpers::contains(used, t); if(c) return; used.push_back(t); if(t->isShoreTile()) shore.push_back(t); if(!t->tidalWaveZone()) return; const auto ns = t->neighbours(nullptr); for(const auto& n : ns) { addShore(static_cast<eTile*>(n.second)); } }; addShore(startTile); } const auto w = std::make_shared<eTidalWave>(); { std::vector<eTile*> used; const auto addNeighs = [&](eTile* const t, const int dist) { const auto ns = t->neighbours(nullptr); for(const auto& n : ns) { const auto tt = static_cast<eTile*>(n.second); if(!tt->tidalWaveZone()) continue; if(tt->hasWater()) continue; const bool c = eVectorHelpers::contains(used, tt); if(c) continue; while((int)w->fTiles.size() < dist + 1) { w->fTiles.emplace_back(); } used.push_back(tt); w->fTiles[dist].push_back({tt, tt->terrain(), n.first}); } }; for(const auto s : shore) { addNeighs(s, 0); } for(int i = 0; i < (int)w->fTiles.size(); i++) { for(const auto t : w->fTiles[i]) { addNeighs(t.fTile, i + 1); } } } if(w->fTiles.empty()) return; w->fPermanent = permanent; mTidalWaves.push_back(w); } bool eGameBoard::duringTidalWave() const { return !mTidalWaves.empty(); } void eGameBoard::addLandSlide(eTile * const startTile) { if(!startTile) return; const int baseAltitude = startTile->altitude(); const int newAltitude = baseAltitude + 1; std::vector<eTile*> shore; { std::vector<eTile*> used; std::function<void(eTile* const)> addShore; addShore = [&](eTile* const t) { const bool c = eVectorHelpers::contains(used, t); if(c) return; used.push_back(t); if(t->isElevationTile()) shore.push_back(t); if(!t->landSlideZone()) return; const auto ns = t->neighbours(nullptr); for(const auto& n : ns) { addShore(static_cast<eTile*>(n.second)); } }; addShore(startTile); } const auto w = std::make_shared<eLandSlide>(); { std::vector<eTile*> used; using eTiles = std::vector<std::vector<eLandSlideDirection>>; const auto addNeighs = [&](eTile* const t, const int dist, eTiles& tiles, const bool downTiles, int& maxTileDist, int& minTileDist) { const auto ns = t->neighbours(nullptr); for(const auto& n : ns) { const auto tt = static_cast<eTile*>(n.second); const int a = tt->altitude(); if(downTiles && a != baseAltitude) continue; if(!downTiles && a != baseAltitude + 2) continue; if(downTiles && !tt->landSlideZone()) continue; const bool c = eVectorHelpers::contains(used, tt); if(c) continue; while((int)tiles.size() < dist + 1) { tiles.emplace_back(); } { const int dx = tt->x() - startTile->x(); const int dy = tt->y() - startTile->y(); const int tileDist = dx*dx + dy*dy; if(tileDist > maxTileDist) { if(downTiles) { maxTileDist = tileDist; } else { continue; } } if(downTiles && tileDist < minTileDist) { minTileDist = tileDist; } } used.push_back(tt); tiles[dist].push_back({tt, newAltitude, n.first}); } }; int dMaxTileDist = 0; int dShoreMinTileDist = 0; eTiles downTiles; for(const auto s : shore) { addNeighs(s, 0, downTiles, true, dMaxTileDist, dShoreMinTileDist); } for(uint i = 0; i < downTiles.size(); i++) { for(const auto t : downTiles[i]) { int minTileDist = 0; addNeighs(t.fTile, i + 1, downTiles, true, dMaxTileDist, minTileDist); } } dMaxTileDist += dShoreMinTileDist; eTiles upTiles; for(const auto s : shore) { int minTileDist = 0; addNeighs(s, 0, upTiles, false, dMaxTileDist, minTileDist); } for(uint i = 0; i < downTiles.size(); i++) { if(i >= upTiles.size()) break; for(const auto t : upTiles[i]) { int minTileDist = 0; addNeighs(t.fTile, i + 1, upTiles, false, dMaxTileDist, minTileDist); } } const int dMax = downTiles.size(); const int uMax = upTiles.size(); const int iMax = std::max(dMax, uMax); for(int i = 0; i < iMax; i++) { auto& v = w->fTiles.emplace_back(); if(i < dMax) { auto& dv = downTiles[i]; for(const auto& d : dv) { v.push_back(d); } } if(i < uMax) { auto& uv = upTiles[i]; for(const auto& u : uv) { v.push_back(u); } } } } if(w->fTiles.empty()) return; mLandSlides.push_back(w); } bool eGameBoard::duringLandSlide() const { return !mLandSlides.empty(); } void eGameBoard::progressLandSlide() { if(mLandSlides.empty()) return; eSounds::playEarthquakeSound(); for(int i = 0; i < (int)mLandSlides.size(); i++) { const auto& w = mLandSlides[i]; if(w->fLastId >= 0 && w->fLastId < (int)w->fTiles.size()) { const std::vector<eLandSlideDirection>& tiles = w->fTiles[w->fLastId]; for(const auto& wd : tiles) { const auto t = wd.fTile; const auto o = wd.fO; std::vector<ePathPoint> path; eTile* from = nullptr; eTile* to = nullptr; from = t->neighbour<eTile>(!o); to = t; to->setAltitude(wd.fNewAltitude); t->setTerrain(eTerrain::dry); earthquakeWaveCollapse(t); const auto cid = t->cityId(); const auto c = boardCityWithId(cid); if(c) c->incTerrainState(); t->scheduleNeighboursTerrainUpdate(2); path.push_back({(double)from->x(), (double)from->y(), 0.}); path.push_back({(double)to->x(), (double)to->y(), 0.}); const auto m = e::make_shared<eDustMissile>(*this, path); m->incTime(0); } } w->fLastId++; if(w->fLastId < 0 || w->fLastId >= (int)w->fTiles.size()) { eVectorHelpers::remove(mLandSlides, w); } } } void eGameBoard::progressLavaFlow() { if(mLavaFlows.empty()) return; eSounds::playLavaSound(); for(int i = 0; i < (int)mLavaFlows.size(); i++) { const auto& w = mLavaFlows[i]; if(w->fLastId >= 0 && w->fLastId < (int)w->fTiles.size()) { const std::vector<eLavaDirection>& tiles = w->fTiles[w->fLastId]; for(const auto& wd : tiles) { const auto t = wd.fTile; const auto o = wd.fO; std::vector<ePathPoint> path; eTile* from = nullptr; eTile* to = nullptr; from = t->neighbour<eTile>(!o); to = t; t->setTerrain(eTerrain::lava); earthquakeWaveCollapse(t); const auto cid = t->cityId(); const auto c = boardCityWithId(cid); if(c) c->incTerrainState(); t->scheduleNeighboursTerrainUpdate(2); path.push_back({(double)from->x(), (double)from->y(), 0.}); path.push_back({(double)to->x(), (double)to->y(), 0.}); const auto m = e::make_shared<eLavaMissile>(*this, path); m->incTime(0); } } w->fLastId++; if(w->fLastId < 0 || w->fLastId >= (int)w->fTiles.size()) { eVectorHelpers::remove(mLavaFlows, w); } } } void eGameBoard::addLavaFlow(eTile * const startTile) { const auto w = std::make_shared<eLavaFlow>(); { std::vector<eTile*> used; std::function<void(eTile* const, const int)> addNeighs; addNeighs = [&](eTile* const t, const int dist) { const auto ns = t->neighbours(nullptr); for(const auto& n : ns) { const auto tt = static_cast<eTile*>(n.second); if(!tt->lavaZone()) continue; if(tt->hasLava()) continue; const bool c = eVectorHelpers::contains(used, tt); if(c) continue; while((int)w->fTiles.size() < dist + 1) { w->fTiles.emplace_back(); } used.push_back(tt); w->fTiles[dist].push_back({tt, n.first}); } }; addNeighs(startTile, 0); for(int i = 0; i < (int)w->fTiles.size(); i++) { for(const auto t : w->fTiles[i]) { addNeighs(t.fTile, i + 1); } } } if(w->fTiles.empty()) return; mLavaFlows.push_back(w); } bool eGameBoard::duringLavaFlow() const { return !mLavaFlows.empty(); } void centerTile(const int minX, const int minY, const int sw, const int sh, int& tx, int& ty) { tx = minX; ty = minY; if(sw == 2 && sh == 2) { ty += 1; } else if(sw == 3 && sh == 3) { tx += 1; ty += 1; } else if(sw == 4 || sh == 4) { tx += 1; ty += 2; } else if(sw == 5 || sh == 5) { tx += 2; ty += 2; } else if(sw == 6 || sh == 6) { tx += 2; ty += 2; } } void eGameBoard::sBuildTiles(int& minX, int& minY, int& maxX, int& maxY, const int tx, const int ty, const int sw, const int sh) { minX = tx; minY = ty; if(sw == 2 && sh == 2) { minY -= 1; } else if(sw == 3 && sh == 3) { minX -= 1; minY -= 1; } else if(sw == 4 || sh == 4) { minX -= 1; minY -= 2; } else if(sw == 5 || sh == 5) { minX -= 2; minY -= 2; } else if(sw == 6 || sh == 6) { minX -= 2; minY -= 2; } maxX = minX + sw; maxY = minY + sh; } bool eGameBoard::canBuildAvenue(eTile* const t, const eCityId cid, const ePlayerId pid, const bool forestAllowed) const { const int tx = t->x(); const int ty = t->y(); const bool cb = canBuildBase(tx, tx + 1, ty, ty + 1, forestAllowed, cid, pid); if(!cb) return false; const auto tr = t->topRight<eTile>(); const auto br = t->bottomRight<eTile>(); const auto bl = t->bottomLeft<eTile>(); const auto tl = t->topLeft<eTile>(); const auto tt = t->top<eTile>(); const auto r = t->right<eTile>(); const auto b = t->bottom<eTile>(); const auto l = t->left<eTile>(); const bool hr = (tr && tr->hasRoad()) || (br && br->hasRoad()) || (bl && bl->hasRoad()) || (tl && tl->hasRoad()) || (tt && tt->hasRoad()) || (r && r->hasRoad()) || (b && b->hasRoad()) || (l && l->hasRoad()); return hr; } bool eGameBoard::canBuildBase(const int minX, const int maxX, const int minY, const int maxY, const bool forestAllowed, const eCityId cid, const ePlayerId pid, const bool fertile, const bool flat, const int allowedWater) const { if(pid != cityIdToPlayerId(cid) && !mEditorMode) return false; int waterCount = 0; bool fertileFound = false; for(int x = minX; x < maxX; x++) { for(int y = minY; y < maxY; y++) { const auto t = tile(x, y); if(!t) return false; if(t->cityId() != cid) return false; if(t->underBuilding()) return false; const auto& banners = t->banners(); for(const auto& b : banners) { if(!b->buildable()) return false; } const auto ttt = t->terrain(); if(fertile && ttt == eTerrain::fertile) { fertileFound = true; } if(ttt == eTerrain::water) { waterCount++; if(waterCount > allowedWater) return false; } else { const auto ttta = forestAllowed ? ttt & eTerrain::buildableAfterClear : ttt & eTerrain::buildable; if(!static_cast<bool>(ttta)) return false; } if(!t->walkableElev() && t->isElevationTile()) return false; if(!flat) { const auto& chars = t->characters(); if(!chars.empty()) return false; } } } if(fertile) return fertileFound; return true; } bool eGameBoard::canBuild(const int tx, const int ty, const int sw, const int sh, const bool forestAllowed, const eCityId cid, const ePlayerId pid, const bool fertile, const bool flat) const { int minX; int minY; int maxX; int maxY; sBuildTiles(minX, minY, maxX, maxY, tx, ty, sw, sh); return canBuildBase(minX, maxX, minY, maxY, forestAllowed, cid, pid, fertile, flat); } bool eGameBoard::buildBase(const int minX, const int minY, const int maxX, const int maxY, const eBuildingCreator& bc, const ePlayerId pid, const eCityId cid, const bool editorDisplay, const bool fertile, const bool flat, const int allowWater) { const int sw = maxX - minX + 1; const int sh = maxY - minY + 1; const bool cb = canBuildBase(minX, maxX + 1, minY, maxY + 1, editorDisplay, cid, pid, fertile, flat, allowWater); if(!cb) return false; if(!bc) return false; const auto b = bc(); if(!b) return false; const bool isRoad = b->type() == eBuildingType::road; if(!isRoad) { for(int x = minX; x <= maxX; x++) { for(int y = minY; y <= maxY; y++) { const auto t = tile(x, y); if(!t) return false; if(t->isElevationTile()) return false; } } } int tx; int ty; centerTile(minX, minY, sw, sh, tx, ty); const auto tile = this->tile(tx, ty); if(!tile) return false; b->setCenterTile(tile); b->setTileRect({minX, minY, sw, sh}); for(int x = minX; x <= maxX; x++) { for(int y = minY; y <= maxY; y++) { const auto t = this->tile(x, y); if(t) { t->setUnderBuilding(b); b->addUnderBuilding(t); } } } if(!editorDisplay) { const auto diff = difficulty(pid); const int cost = eDifficultyHelpers::buildingCost(diff, b->type()); incDrachmas(pid, -cost, eFinanceTarget::construction); } return true; } bool eGameBoard::build(const int tx, const int ty, const int sw, const int sh, const eCityId cid, const ePlayerId pid, const bool editorDisplay, const eBuildingCreator& bc, const bool fertile, const bool flat) { const auto tile = this->tile(tx, ty); if(!tile) return false; int minX; int minY; int maxX; int maxY; sBuildTiles(minX, minY, maxX, maxY, tx, ty, sw, sh); return buildBase(minX, minY, maxX - 1, maxY - 1, bc, pid, cid, editorDisplay, fertile, flat); } bool eGameBoard::buildAnimal(eTile* const tile, const eBuildingType type, const eAnimalCreator& creator, const eCityId cid, const ePlayerId pid, const bool editorDisplay) { const int tx = tile->x(); const int ty = tile->y(); const bool cb = canBuild(tx, ty, 1, 2, editorDisplay, cid, pid, true, true); if(!cb) return false; const auto sh = creator(*this); sh->changeTile(tile); const auto o = static_cast<eOrientation>(eRand::rand() % 8); sh->setOrientation(o); const auto w = eWalkableObject::sCreateFertile(); const auto a = e::make_shared<eAnimalAction>(sh.get(), tx, ty, w); sh->setAction(a); return build(tx, ty, 1, 2, cid, pid, editorDisplay, [this, sh, type, cid]() { return e::make_shared<eAnimalBuilding>( *this, sh.get(), type, cid); }, true, true); } void eGameBoard::removeAllBuildings() { for(const auto& b : mAllBuildings) { b->erase(); } } bool eGameBoard::buildPyramid(const int minX, const int maxX, const int minY, const int maxY, const eBuildingType type, const bool rotate, const eCityId cid, const ePlayerId pid, const bool editorDisplay) { (void)rotate; const bool cb = canBuildBase(minX, maxX, minY, maxY, editorDisplay, cid, pid); if(!cb) return false; int sw; int sh; ePyramid::sDimensions(type, sw, sh); const auto p = e::make_shared<ePyramid>(*this, type, sw, sh, cid); p->setTileRect({minX, minY, sw, sh}); const auto mint = this->tile(minX, minY); const int a = mint->altitude(); p->setAltitude(a); const auto ct = this->tile((minX + maxX)/2, (minY + maxY)/2); p->setCenterTile(ct); const auto c = boardCityWithId(cid); const auto levels = c->pyramidLevels(type); p->initialize(levels); if(!editorDisplay) { const auto diff = difficulty(pid); const int cost = eDifficultyHelpers::buildingCost(diff, type); incDrachmas(pid, -cost, eFinanceTarget::construction); const int m = eBuilding::sInitialMarbleCost(type); takeResource(cid, eResourceType::marble, m); } built(cid, type); return true; } bool eGameBoard::buildSanctuary(const int minX, const int maxX, const int minY, const int maxY, const eBuildingType type, const bool rotate, const eCityId cid, const ePlayerId pid, const bool editorDisplay) { const bool cb = canBuildBase(minX, maxX, minY, maxY, editorDisplay, cid, pid); if(!cb) return false; const auto h = eSanctBlueprints::sSanctuaryBlueprint(type, rotate); const int sw = h->fW; const int sh = h->fH; const auto b = eSanctuary::sCreate(type, sw, sh, *this, cid); b->setRotated(rotate); const auto god = b->godType(); if(!editorDisplay) { const auto diff = difficulty(pid); const int cost = eDifficultyHelpers::buildingCost(diff, type); incDrachmas(pid, -cost, eFinanceTarget::construction); const int m = eBuilding::sInitialMarbleCost(type); takeResource(cid, eResourceType::marble, m); } built(cid, type); const auto mint = this->tile(minX, minY); const int a = mint->altitude(); b->setAltitude(a); const SDL_Rect sanctRect{minX, minY, sw, sh}; b->setTileRect(sanctRect); const auto ct = this->tile((minX + maxX)/2, (minY + maxY)/2); b->setCenterTile(ct); for(const auto& tv : h->fTiles) { for(const auto& t : tv) { const int tx = minX + t.fX; const int ty = minY + t.fY; const auto tile = this->tile(tx, ty); eGodType statueType; switch(t.fType) { case eSanctEleType::aphroditeStatue: statueType = eGodType::aphrodite; break; case eSanctEleType::apolloStatue: statueType = eGodType::apollo; break; case eSanctEleType::aresStatue: statueType = eGodType::ares; break; case eSanctEleType::artemisStatue: statueType = eGodType::artemis; break; case eSanctEleType::athenaStatue: statueType = eGodType::athena; break; case eSanctEleType::atlasStatue: statueType = eGodType::atlas; break; case eSanctEleType::demeterStatue: statueType = eGodType::demeter; break; case eSanctEleType::dionysusStatue: statueType = eGodType::dionysus; break; case eSanctEleType::hadesStatue: statueType = eGodType::hades; break; case eSanctEleType::hephaestusStatue: statueType = eGodType::hephaestus; break; case eSanctEleType::heraStatue: statueType = eGodType::hera; break; case eSanctEleType::hermesStatue: statueType = eGodType::hermes; break; case eSanctEleType::poseidonStatue: statueType = eGodType::poseidon; break; case eSanctEleType::zeusStatue: statueType = eGodType::zeus; break; default: statueType = god; } switch(t.fType) { case eSanctEleType::copper: case eSanctEleType::silver: case eSanctEleType::oliveTree: case eSanctEleType::vine: case eSanctEleType::orangeTree: { build(tile->x(), tile->y(), 1, 1, cid, pid, editorDisplay, [this, cid]() { return e::make_shared<ePlaceholder>(*this, cid); }); b->addSpecialTile(tile); } break; case eSanctEleType::defaultStatue: case eSanctEleType::aphroditeStatue: case eSanctEleType::apolloStatue: case eSanctEleType::aresStatue: case eSanctEleType::artemisStatue: case eSanctEleType::athenaStatue: case eSanctEleType::atlasStatue: case eSanctEleType::demeterStatue: case eSanctEleType::dionysusStatue: case eSanctEleType::hadesStatue: case eSanctEleType::hephaestusStatue: case eSanctEleType::heraStatue: case eSanctEleType::hermesStatue: case eSanctEleType::poseidonStatue: case eSanctEleType::zeusStatue: { const auto tt = e::make_shared<eTempleStatueBuilding>( statueType, t.fId, *this, cid); tt->setMonument(b.get()); this->build(tx, ty, 1, 1, cid, pid, editorDisplay, [tt]() { return tt; }); b->registerElement(tt); } break; case eSanctEleType::monument: { const auto tt = e::make_shared<eTempleMonumentBuilding>( god, t.fId, *this, cid); tt->setMonument(b.get()); const int d = rotate ? 1 : 0; this->build(tx - d, ty + d, 2, 2, cid, pid, editorDisplay, [tt]() { return tt; }); b->registerElement(tt); } break; case eSanctEleType::altar: { const auto tt = e::make_shared<eTempleAltarBuilding>( *this, cid); tt->setMonument(b.get()); const int d = rotate ? 1 : 0; this->build(tx - d, ty + d, 2, 2, cid, pid, editorDisplay, [tt]() { return tt; }); b->registerElement(tt); } break; case eSanctEleType::sanctuary: { const auto tb = e::make_shared<eTempleBuilding>( t.fId, *this, cid); tb->setMonument(b.get()); b->registerElement(tb); if(rotate) { this->build(tx - 2, ty + 2, 4, 4, cid, pid, editorDisplay, [tb]() { return tb; }); } else { this->build(tx + 1, ty - 1, 4, 4, cid, pid, editorDisplay, [tb]() { return tb; }); } } break; case eSanctEleType::tile: { const auto tt = e::make_shared<eTempleTileBuilding>( t.fId, *this, cid); tt->setMonument(b.get()); this->build(tx, ty, 1, 1, cid, pid, editorDisplay, [tt]() { return tt; }); b->registerElement(tt); if(t.fWarrior) b->addWarriorTile(tile); } break; case eSanctEleType::stairs: { tile->setSeed(t.fId); tile->setWalkableElev(true); } break; case eSanctEleType::none: break; } } } for(const auto& tv : h->fTiles) { for(const auto& t : tv) { const int tx = minX + t.fX; const int ty = minY + t.fY; const auto tile = this->tile(tx, ty); tile->setAltitude(tile->altitude() + t.fA); const auto trr = tile->terrain(); const bool bldbl = static_cast<bool>( trr & eTerrain::buildable); if(!tile->underBuilding() && bldbl) { tile->setUnderBuilding(b); b->addUnderBuilding(tile); } } } b->buildingProgressed(); return true; } int eGameBoard::bestYearlyProduction(const eResourceType type) const { const auto it = mYearlyProduction.find(type); if(it == mYearlyProduction.end()) return 0; return it->second.fBest; } void eGameBoard::incProduced(const eResourceType type, const int by) { mYearlyProduction[type].fThisYear += by; } eDistrictIdTmp::eDistrictIdTmp(eGameBoard& board) : mBoard(board), mTmpId(board.currentDistrictId()) {} eDistrictIdTmp::~eDistrictIdTmp() { mBoard.setCurrentDistrictId(mTmpId); }
412
0.953475
1
0.953475
game-dev
MEDIA
0.98017
game-dev
0.819177
1
0.819177
PaperMC/Paper
3,074
paper-server/src/generated/java/org/bukkit/craftbukkit/block/impl/CraftSculkVein.java
package org.bukkit.craftbukkit.block.impl; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import io.papermc.paper.annotation.GeneratedClass; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import net.minecraft.world.level.block.SculkVeinBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import org.bukkit.block.BlockFace; import org.bukkit.block.data.type.SculkVein; import org.bukkit.craftbukkit.block.data.CraftBlockData; import org.jspecify.annotations.NullMarked; @NullMarked @GeneratedClass public class CraftSculkVein extends CraftBlockData implements SculkVein { private static final BooleanProperty WATERLOGGED = SculkVeinBlock.WATERLOGGED; private static final Map<BlockFace, BooleanProperty> PROPERTY_BY_DIRECTION = Map.of( BlockFace.DOWN, BlockStateProperties.DOWN, BlockFace.EAST, BlockStateProperties.EAST, BlockFace.NORTH, BlockStateProperties.NORTH, BlockFace.SOUTH, BlockStateProperties.SOUTH, BlockFace.UP, BlockStateProperties.UP, BlockFace.WEST, BlockStateProperties.WEST ); public CraftSculkVein(BlockState state) { super(state); } @Override public boolean isWaterlogged() { return this.get(WATERLOGGED); } @Override public void setWaterlogged(final boolean waterlogged) { this.set(WATERLOGGED, waterlogged); } @Override public boolean hasFace(final BlockFace blockFace) { Preconditions.checkArgument(blockFace != null, "blockFace cannot be null!"); BooleanProperty property = PROPERTY_BY_DIRECTION.get(blockFace); Preconditions.checkArgument(property != null, "Invalid blockFace, only %s are allowed!", PROPERTY_BY_DIRECTION.keySet().stream().map(Enum::name).collect(Collectors.joining(", "))); return this.get(property); } @Override public void setFace(final BlockFace blockFace, final boolean face) { Preconditions.checkArgument(blockFace != null, "blockFace cannot be null!"); BooleanProperty property = PROPERTY_BY_DIRECTION.get(blockFace); Preconditions.checkArgument(property != null, "Invalid blockFace, only %s are allowed!", PROPERTY_BY_DIRECTION.keySet().stream().map(Enum::name).collect(Collectors.joining(", "))); this.set(property, face); } @Override public Set<BlockFace> getFaces() { ImmutableSet.Builder<BlockFace> faces = ImmutableSet.builder(); for (Map.Entry<BlockFace, BooleanProperty> entry : PROPERTY_BY_DIRECTION.entrySet()) { if (this.get(entry.getValue())) { faces.add(entry.getKey()); } } return faces.build(); } @Override public Set<BlockFace> getAllowedFaces() { return Collections.unmodifiableSet(PROPERTY_BY_DIRECTION.keySet()); } }
412
0.775811
1
0.775811
game-dev
MEDIA
0.965072
game-dev
0.885628
1
0.885628
Fluorohydride/ygopro-scripts
3,058
c72192100.lua
--デスルークデーモン function c72192100.initial_effect(c) --maintain local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EVENT_PHASE+PHASE_STANDBY) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCondition(c72192100.mtcon) e1:SetOperation(c72192100.mtop) c:RegisterEffect(e1) --disable and destroy local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_DICE) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_CHAIN_SOLVING) e2:SetRange(LOCATION_MZONE) e2:SetOperation(c72192100.disop) c:RegisterEffect(e2) --special summon local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetDescription(aux.Stringid(72192100,0)) e3:SetType(EFFECT_TYPE_QUICK_O) e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP) e3:SetCode(EVENT_TO_GRAVE) e3:SetRange(LOCATION_HAND) e3:SetCost(c72192100.spcost) e3:SetTarget(c72192100.sptg) e3:SetOperation(c72192100.spop) c:RegisterEffect(e3) end function c72192100.mtcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c72192100.mtop(e,tp,eg,ep,ev,re,r,rp) if Duel.CheckLPCost(tp,500) or Duel.IsPlayerAffectedByEffect(tp,94585852) then if not Duel.IsPlayerAffectedByEffect(tp,94585852) or not Duel.SelectEffectYesNo(tp,e:GetHandler(),aux.Stringid(94585852,1)) then Duel.PayLPCost(tp,500) end else Duel.Destroy(e:GetHandler(),REASON_COST) end end function c72192100.disop(e,tp,eg,ep,ev,re,r,rp) if ep==tp then return end if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return false end local tg=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS) if not tg or not tg:IsContains(e:GetHandler()) or not Duel.IsChainDisablable(ev) then return false end local rc=re:GetHandler() local dc=Duel.TossDice(tp,1) if dc~=3 then return end if Duel.NegateEffect(ev,true) and rc:IsRelateToEffect(re) then Duel.Destroy(rc,REASON_EFFECT) end end function c72192100.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end Duel.SendtoGrave(e:GetHandler(),REASON_COST) end function c72192100.filter(c,e,tp) return c:IsCode(35975813) and c:IsPreviousControler(tp) and c:IsPreviousLocation(LOCATION_ONFIELD) and c:IsCanBeEffectTarget(e) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c72192100.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return eg:IsContains(chkc) and c72192100.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and eg:IsExists(c72192100.filter,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=eg:FilterSelect(tp,c72192100.filter,1,1,nil,e,tp) Duel.SetTargetCard(g) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c72192100.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
412
0.910886
1
0.910886
game-dev
MEDIA
0.986699
game-dev
0.902553
1
0.902553
Embarcadero/RADStudio10.3Demos
2,202
Object Pascal/Database/FireDAC/Samples/DBMS Specific/InterBase/ChangeView/Pharmacy/Pharmacy/dmDelta.dfm
object dtmdlDelta: TdtmdlDelta OldCreateOrder = False Height = 442 Width = 433 object FDTransactionDelta: TFDTransaction Options.Isolation = xiSnapshot Options.DisconnectAction = xdRollback Left = 136 Top = 80 end object qrySubscriptionActive: TFDQuery Transaction = FDTransactionDelta SQL.Strings = ( 'set subscription sub_medicineupdates at '#39'P1'#39' active;' '') Left = 120 Top = 144 end object qryCategory: TFDQuery Left = 40 Top = 16 end object qryMedicine: TFDQuery Left = 136 Top = 16 end object qryMedicineCategories: TFDQuery Left = 248 Top = 16 end object qryCategoryDelta: TFDQuery Transaction = FDTransactionDelta Left = 40 Top = 216 end object qryMedicineDelta: TFDQuery Transaction = FDTransactionDelta Left = 136 Top = 216 end object qryMedicineCategoriesDelta: TFDQuery Transaction = FDTransactionDelta Left = 248 Top = 216 end object mtCategoryMerged: TFDMemTable FilterChanges = [rtModified, rtInserted, rtDeleted, rtUnmodified] FetchOptions.AssignedValues = [evMode] FetchOptions.Mode = fmAll ResourceOptions.AssignedValues = [rvSilentMode] ResourceOptions.SilentMode = True UpdateOptions.AssignedValues = [uvCheckRequired] UpdateOptions.CheckRequired = False Left = 40 Top = 296 end object mtMedicineMerged: TFDMemTable FilterChanges = [rtModified, rtInserted, rtDeleted, rtUnmodified] FetchOptions.AssignedValues = [evMode] FetchOptions.Mode = fmAll ResourceOptions.AssignedValues = [rvSilentMode] ResourceOptions.SilentMode = True UpdateOptions.AssignedValues = [uvCheckRequired] UpdateOptions.CheckRequired = False Left = 152 Top = 280 end object mtMedicineCategoriesMerged: TFDMemTable FilterChanges = [rtModified, rtInserted, rtDeleted, rtUnmodified] FetchOptions.AssignedValues = [evMode] FetchOptions.Mode = fmAll ResourceOptions.AssignedValues = [rvSilentMode] ResourceOptions.SilentMode = True UpdateOptions.AssignedValues = [uvCheckRequired] UpdateOptions.CheckRequired = False Left = 248 Top = 304 end end
412
0.61432
1
0.61432
game-dev
MEDIA
0.201848
game-dev
0.694488
1
0.694488