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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PaulStoffregen/cores | 7,605 | usb_flightsim/usb_api.h | #ifndef USBserial_h_
#define USBserial_h_
#include <inttypes.h>
#include "Print.h"
#include "Stream.h"
#include "elapsedMillis.h"
class FlightSimClass;
class FlightSimCommand;
class FlightSimInteger;
class _XpRefStr_;
#define XPlaneRef(str) ((const _XpRefStr_ *)(PSTR(str)))
class FlightSimClass
{
public:
FlightSimClass();
static void update(void);
static bool isEnabled(void);
static unsigned long getFrameCount(void) { return frameCount; }
private:
static uint8_t request_id_messages;
static uint8_t enabled;
static elapsedMillis enableTimeout;
static unsigned long frameCount;
static void enable(void) { enabled = 1; enableTimeout = 0; }
static void disable(void) { enabled = 0; }
static uint8_t recv(uint8_t *buffer);
static void xmit(const uint8_t *p1, uint8_t n1);
static void xmit(const uint8_t *p1, uint8_t n1, const uint8_t *p2, uint8_t n2);
static void xmit(const uint8_t *p1, uint8_t n1, const _XpRefStr_ *p2, uint16_t n2);
static void xmit_big_packet(const uint8_t *p1, uint8_t n1, const _XpRefStr_ *p2, uint16_t n2);
friend class FlightSimCommand;
friend class FlightSimInteger;
friend class FlightSimFloat;
};
class FlightSimCommand
{
public:
FlightSimCommand();
void assign(const _XpRefStr_ *s) { name = s; if (FlightSimClass::enabled) identify(); }
FlightSimCommand & operator = (const _XpRefStr_ *s) { assign(s); return *this; }
void begin(void) { sendcmd(4); }
void end(void) { sendcmd(5); }
FlightSimCommand & operator = (int n) { sendcmd((n) ? 4 : 5); return *this; }
void once(void) { sendcmd(6); }
void identify(void);
private:
unsigned int id;
const _XpRefStr_ *name;
void sendcmd(uint8_t n);
FlightSimCommand *next;
static FlightSimCommand *first;
static FlightSimCommand *last;
friend class FlightSimClass;
};
class FlightSimInteger
{
public:
FlightSimInteger();
void assign(const _XpRefStr_ *s) { name = s; if (FlightSimClass::enabled) identify(); }
FlightSimInteger & operator = (const _XpRefStr_ *s) { assign(s); return *this; }
void write(long val);
FlightSimInteger & operator = (char n) { write((long)n); return *this; }
FlightSimInteger & operator = (int n) { write((long)n); return *this; }
FlightSimInteger & operator = (long n) { write(n); return *this; }
FlightSimInteger & operator = (unsigned char n) { write((long)n); return *this; }
FlightSimInteger & operator = (unsigned int n) { write((long)n); return *this; }
FlightSimInteger & operator = (unsigned long n) { write((long)n); return *this; }
FlightSimInteger & operator = (float n) { write((long)n); return *this; }
FlightSimInteger & operator = (double n) { write((long)n); return *this; }
long read(void) const { return value; }
operator long () const { return value; }
void identify(void);
void update(long val);
static FlightSimInteger * find(unsigned int n);
void onChange(void (*fptr)(long)) {
hasCallbackInfo=false;
change_callback = fptr;
}
void onChange(void (*fptr)(long,void*), void* info) {
hasCallbackInfo=true;
change_callback = (void (*)(long))fptr;
callbackInfo = info;
}
// TODO: math operators.... + - * / % ++ --
private:
unsigned int id;
const _XpRefStr_ *name;
long value;
void (*change_callback)(long);
void* callbackInfo;
bool hasCallbackInfo;
FlightSimInteger *next;
static FlightSimInteger *first;
static FlightSimInteger *last;
friend class FlightSimClass;
};
class FlightSimFloat
{
public:
FlightSimFloat();
void assign(const _XpRefStr_ *s) { name = s; if (FlightSimClass::enabled) identify(); }
FlightSimFloat & operator = (const _XpRefStr_ *s) { assign(s); return *this; }
void write(float val);
FlightSimFloat & operator = (char n) { write((float)n); return *this; }
FlightSimFloat & operator = (int n) { write((float)n); return *this; }
FlightSimFloat & operator = (long n) { write((float)n); return *this; }
FlightSimFloat & operator = (unsigned char n) { write((float)n); return *this; }
FlightSimFloat & operator = (unsigned int n) { write((float)n); return *this; }
FlightSimFloat & operator = (unsigned long n) { write((float)n); return *this; }
FlightSimFloat & operator = (float n) { write(n); return *this; }
FlightSimFloat & operator = (double n) { write((float)n); return *this; }
float read(void) const { return value; }
operator float () const { return value; }
void identify(void);
void update(float val);
static FlightSimFloat * find(unsigned int n);
void onChange(void (*fptr)(float)) {
hasCallbackInfo=false;
change_callback = fptr;
}
void onChange(void (*fptr)(float,void*), void* info) {
hasCallbackInfo=true;
change_callback = (void (*)(float))fptr;
callbackInfo = info;
}
// TODO: math operators.... + - * / % ++ --
private:
unsigned int id;
const _XpRefStr_ *name;
float value;
void (*change_callback)(float);
void* callbackInfo;
bool hasCallbackInfo;
FlightSimFloat *next;
static FlightSimFloat *first;
static FlightSimFloat *last;
friend class FlightSimClass;
};
class FlightSimElapsedFrames
{
private:
unsigned long count;
public:
FlightSimElapsedFrames(void) { count = FlightSimClass::getFrameCount(); }
FlightSimElapsedFrames(unsigned long val) { count = FlightSimClass::getFrameCount() - val; }
FlightSimElapsedFrames(const FlightSimElapsedFrames &orig) { count = orig.count; }
operator unsigned long () const { return FlightSimClass::getFrameCount() - count; }
FlightSimElapsedFrames & operator = (const FlightSimElapsedFrames &rhs) { count = rhs.count; return *this; }
FlightSimElapsedFrames & operator = (unsigned long val) { count = FlightSimClass::getFrameCount() - val; return *this; }
FlightSimElapsedFrames & operator -= (unsigned long val) { count += val; return *this; }
FlightSimElapsedFrames & operator += (unsigned long val) { count -= val; return *this; }
FlightSimElapsedFrames operator - (int val) const { FlightSimElapsedFrames r(*this); r.count += val; return r; }
FlightSimElapsedFrames operator - (unsigned int val) const { FlightSimElapsedFrames r(*this); r.count += val; return r; }
FlightSimElapsedFrames operator - (long val) const { FlightSimElapsedFrames r(*this); r.count += val; return r; }
FlightSimElapsedFrames operator - (unsigned long val) const { FlightSimElapsedFrames r(*this); r.count += val; return r; }
FlightSimElapsedFrames operator + (int val) const { FlightSimElapsedFrames r(*this); r.count -= val; return r; }
FlightSimElapsedFrames operator + (unsigned int val) const { FlightSimElapsedFrames r(*this); r.count -= val; return r; }
FlightSimElapsedFrames operator + (long val) const { FlightSimElapsedFrames r(*this); r.count -= val; return r; }
FlightSimElapsedFrames operator + (unsigned long val) const { FlightSimElapsedFrames r(*this); r.count -= val; return r; }
};
extern FlightSimClass FlightSim;
#if 0
class usb_rawhid_class
{
public:
int available(void);
int recv(void *buffer, uint16_t timeout);
int send(const void *buffer, uint16_t timeout);
};
extern usb_rawhid_class RawHID;
#endif
class usb_serial_class : public Stream
{
public:
// standard Arduino functions
void begin(long);
void end();
virtual int available();
virtual int read();
virtual int peek();
virtual void flush();
#if ARDUINO >= 100
virtual size_t write(uint8_t);
#else
virtual void write(uint8_t);
#endif
using Print::write;
operator bool();
// Teensy extensions
void send_now(void);
uint32_t baud(void);
uint8_t stopbits(void);
uint8_t paritytype(void);
uint8_t numbits(void);
uint8_t dtr(void);
uint8_t rts(void);
private:
uint8_t readnext(void);
};
extern usb_serial_class Serial;
#endif
| 0 | 0.874174 | 1 | 0.874174 | game-dev | MEDIA | 0.569998 | game-dev | 0.708567 | 1 | 0.708567 |
AS3NUI/airkinect-2-core | 1,328 | native/src/AKUtilityFunctions.h | /*
* Copyright 2012 AS3NUI
*
* 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.
*/
#ifndef KinectExtension_AKUtilityFunctions_h
#define KinectExtension_AKUtilityFunctions_h
#ifdef AIRKINECT_OS_WINDOWS
#include "FlashRuntimeExtensions.h"
#else
#include <Adobe AIR/Adobe AIR.h>
#endif
unsigned int createUnsignedIntFromFREObject(FREObject freObject);
double createDoubleFromFREObject(FREObject freObject);
bool createBoolFromFREObject(FREObject freObject);
FREObject createFREObjectForUTF8(const char* str);
FREObject createFREObjectForUnsignedInt(unsigned int i);
FREObject createFREObjectForDouble(double d);
FREObject createFREObjectForBool(bool b);
#ifdef AIRKINECT_TARGET_MSSDK
NUI_IMAGE_RESOLUTION getNuiImageResolutionForGivenWidthAndHeight(int width, int height);
#endif
#endif | 0 | 0.629486 | 1 | 0.629486 | game-dev | MEDIA | 0.405897 | game-dev | 0.669562 | 1 | 0.669562 |
Waterdish/Shipwright-Android | 7,018 | soh/src/overlays/actors/ovl_En_Nutsball/z_en_nutsball.c | /*
* File: z_en_nutsball.c
* Overlay: ovl_En_Nutsball
* Description: Projectile fired by deku scrubs
*/
#include "z_en_nutsball.h"
#include "overlays/effects/ovl_Effect_Ss_Hahen/z_eff_ss_hahen.h"
#include "objects/object_gi_nuts/object_gi_nuts.h"
#include "objects/object_dekunuts/object_dekunuts.h"
#include "objects/object_hintnuts/object_hintnuts.h"
#include "objects/object_shopnuts/object_shopnuts.h"
#include "objects/object_dns/object_dns.h"
#include "objects/object_dnk/object_dnk.h"
#define FLAGS ACTOR_FLAG_UPDATE_CULLING_DISABLED
void EnNutsball_Init(Actor* thisx, PlayState* play);
void EnNutsball_Destroy(Actor* thisx, PlayState* play);
void EnNutsball_Update(Actor* thisx, PlayState* play);
void EnNutsball_Draw(Actor* thisx, PlayState* play);
void func_80ABBB34(EnNutsball* this, PlayState* play);
void func_80ABBBA8(EnNutsball* this, PlayState* play);
const ActorInit En_Nutsball_InitVars = {
ACTOR_EN_NUTSBALL,
ACTORCAT_PROP,
FLAGS,
OBJECT_GAMEPLAY_KEEP,
sizeof(EnNutsball),
(ActorFunc)EnNutsball_Init,
(ActorFunc)EnNutsball_Destroy,
(ActorFunc)EnNutsball_Update,
(ActorFunc)NULL,
NULL,
};
static ColliderCylinderInit sCylinderInit = {
{
COLTYPE_NONE,
AT_ON | AT_TYPE_ENEMY,
AC_ON | AC_TYPE_PLAYER,
OC1_ON | OC1_TYPE_ALL,
OC2_TYPE_2,
COLSHAPE_CYLINDER,
},
{
ELEMTYPE_UNK0,
{ 0xFFCFFFFF, 0x00, 0x08 },
{ 0xFFCFFFFF, 0x00, 0x00 },
TOUCH_ON | TOUCH_SFX_WOOD,
BUMP_ON,
OCELEM_ON,
},
{ 13, 13, 0, { 0 } },
};
static s16 sObjectIDs[] = {
OBJECT_DEKUNUTS, OBJECT_HINTNUTS, OBJECT_SHOPNUTS, OBJECT_DNS, OBJECT_DNK,
};
static Gfx* sDListsNew[] = {
gGiNutDL, gGiNutDL, gGiNutDL, gGiNutDL, gGiNutDL,
};
static Gfx* sDLists[] = {
gDekuNutsDekuNutDL, gHintNutsNutDL, gBusinessScrubDekuNutDL, gDntJijiNutDL, gDntStageNutDL,
};
void EnNutsball_Init(Actor* thisx, PlayState* play) {
EnNutsball* this = (EnNutsball*)thisx;
s32 pad;
ActorShape_Init(&this->actor.shape, 400.0f, ActorShadow_DrawCircle, 13.0f);
Collider_InitCylinder(play, &this->collider);
Collider_SetCylinder(play, &this->collider, &this->actor, &sCylinderInit);
if (CVarGetInteger(CVAR_ENHANCEMENT("RandomizedEnemies"), 0)) {
this->objBankIndex = 0;
} else {
this->objBankIndex = Object_GetIndex(&play->objectCtx, sObjectIDs[this->actor.params]);
}
if (this->objBankIndex < 0) {
Actor_Kill(&this->actor);
} else {
this->actionFunc = func_80ABBB34;
}
}
void EnNutsball_Destroy(Actor* thisx, PlayState* play) {
EnNutsball* this = (EnNutsball*)thisx;
Collider_DestroyCylinder(play, &this->collider);
}
void func_80ABBB34(EnNutsball* this, PlayState* play) {
if (Object_IsLoaded(&play->objectCtx, this->objBankIndex)) {
this->actor.objBankIndex = this->objBankIndex;
this->actor.draw = EnNutsball_Draw;
this->actor.shape.rot.y = 0;
this->timer = 30;
this->actionFunc = func_80ABBBA8;
this->actor.speedXZ = 10.0f;
}
}
void func_80ABBBA8(EnNutsball* this, PlayState* play) {
Player* player = GET_PLAYER(play);
Vec3s sp4C;
Vec3f sp40;
this->timer--;
if (this->timer == 0) {
this->actor.gravity = -1.0f;
}
this->actor.home.rot.z += 0x2AA8;
if ((this->actor.bgCheckFlags & 8) || (this->actor.bgCheckFlags & 1) || (this->collider.base.atFlags & AT_HIT) ||
(this->collider.base.acFlags & AC_HIT) || (this->collider.base.ocFlags1 & OC1_HIT)) {
// Checking if the player is using a shield that reflects projectiles
// And if so, reflects the projectile on impact
if ((player->currentShield == PLAYER_SHIELD_DEKU) ||
((player->currentShield == PLAYER_SHIELD_HYLIAN) && LINK_IS_ADULT)) {
if ((this->collider.base.atFlags & AT_HIT) && (this->collider.base.atFlags & AT_TYPE_ENEMY) &&
(this->collider.base.atFlags & AT_BOUNCED)) {
this->collider.base.atFlags &= ~AT_TYPE_ENEMY & ~AT_BOUNCED & ~AT_HIT;
this->collider.base.atFlags |= AT_TYPE_PLAYER;
this->collider.info.toucher.dmgFlags = 2;
Matrix_MtxFToYXZRotS(&player->shieldMf, &sp4C, 0);
this->actor.world.rot.y = sp4C.y + 0x8000;
this->timer = 30;
return;
}
}
sp40.x = this->actor.world.pos.x;
sp40.y = this->actor.world.pos.y + 4;
sp40.z = this->actor.world.pos.z;
EffectSsHahen_SpawnBurst(play, &sp40, 6.0f, 0, 7, 3, 15, HAHEN_OBJECT_DEFAULT, 10, NULL);
SoundSource_PlaySfxAtFixedWorldPos(play, &this->actor.world.pos, 20, NA_SE_EN_OCTAROCK_ROCK);
Actor_Kill(&this->actor);
} else {
if (this->timer == -300) {
Actor_Kill(&this->actor);
}
}
}
void EnNutsball_Update(Actor* thisx, PlayState* play) {
EnNutsball* this = (EnNutsball*)thisx;
Player* player = GET_PLAYER(play);
s32 pad;
if (!(player->stateFlags1 &
(PLAYER_STATE1_TALKING | PLAYER_STATE1_DEAD | PLAYER_STATE1_IN_ITEM_CS | PLAYER_STATE1_IN_CUTSCENE)) ||
(this->actionFunc == func_80ABBB34)) {
this->actionFunc(this, play);
Actor_MoveXZGravity(&this->actor);
Actor_UpdateBgCheckInfo(play, &this->actor, 10, sCylinderInit.dim.radius, sCylinderInit.dim.height, 5);
Collider_UpdateCylinder(&this->actor, &this->collider);
this->actor.flags |= ACTOR_FLAG_SFX_FOR_PLAYER_BODY_HIT;
CollisionCheck_SetAT(play, &play->colChkCtx, &this->collider.base);
CollisionCheck_SetAC(play, &play->colChkCtx, &this->collider.base);
CollisionCheck_SetOC(play, &play->colChkCtx, &this->collider.base);
}
}
void EnNutsball_Draw(Actor* thisx, PlayState* play) {
s32 pad;
OPEN_DISPS(play->state.gfxCtx);
if (CVarGetInteger(CVAR_ENHANCEMENT("NewDrops"), 0) != 0) {
Gfx_SetupDL_25Opa(play->state.gfxCtx);
gSPSegment(POLY_OPA_DISP++, 0x08,
Gfx_TwoTexScroll(play->state.gfxCtx, 0, 1 * (play->state.frames * 6), 1 * (play->state.frames * 6),
32, 32, 1, 1 * (play->state.frames * 6), 1 * (play->state.frames * 6), 32, 32));
Matrix_Scale(25.0f, 25.0f, 25.0f, MTXMODE_APPLY);
Matrix_RotateX(thisx->home.rot.z * 9.58738e-05f, MTXMODE_APPLY);
gSPMatrix(POLY_OPA_DISP++, MATRIX_NEWMTX(play->state.gfxCtx), G_MTX_MODELVIEW | G_MTX_LOAD);
gSPDisplayList(POLY_OPA_DISP++, sDListsNew[thisx->params]);
} else {
Gfx_SetupDL_25Opa(play->state.gfxCtx);
Matrix_Mult(&play->billboardMtxF, MTXMODE_APPLY);
Matrix_RotateZ(thisx->home.rot.z * 9.58738e-05f, MTXMODE_APPLY);
gSPMatrix(POLY_OPA_DISP++, MATRIX_NEWMTX(play->state.gfxCtx), G_MTX_MODELVIEW | G_MTX_LOAD);
gSPDisplayList(POLY_OPA_DISP++, sDLists[thisx->params]);
}
CLOSE_DISPS(play->state.gfxCtx);
}
| 0 | 0.668263 | 1 | 0.668263 | game-dev | MEDIA | 0.900616 | game-dev | 0.905777 | 1 | 0.905777 |
fredakilla/GPlayEngine | 17,534 | thirdparty/bullet/src/LinearMath/btIDebugDraw.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_IDEBUG_DRAW__H
#define BT_IDEBUG_DRAW__H
#include "btVector3.h"
#include "btTransform.h"
///The btIDebugDraw interface class allows hooking up a debug renderer to visually debug simulations.
///Typical use case: create a debug drawer object, and assign it to a btCollisionWorld or btDynamicsWorld using setDebugDrawer and call debugDrawWorld.
///A class that implements the btIDebugDraw interface has to implement the drawLine method at a minimum.
///For color arguments the X,Y,Z components refer to Red, Green and Blue each in the range [0..1]
class btIDebugDraw
{
public:
ATTRIBUTE_ALIGNED16(struct) DefaultColors
{
btVector3 m_activeObject;
btVector3 m_deactivatedObject;
btVector3 m_wantsDeactivationObject;
btVector3 m_disabledDeactivationObject;
btVector3 m_disabledSimulationObject;
btVector3 m_aabb;
btVector3 m_contactPoint;
DefaultColors()
: m_activeObject(1,1,1),
m_deactivatedObject(0,1,0),
m_wantsDeactivationObject(0,1,1),
m_disabledDeactivationObject(1,0,0),
m_disabledSimulationObject(1,1,0),
m_aabb(1,0,0),
m_contactPoint(1,1,0)
{
}
};
enum DebugDrawModes
{
DBG_NoDebug=0,
DBG_DrawWireframe = 1,
DBG_DrawAabb=2,
DBG_DrawFeaturesText=4,
DBG_DrawContactPoints=8,
DBG_NoDeactivation=16,
DBG_NoHelpText = 32,
DBG_DrawText=64,
DBG_ProfileTimings = 128,
DBG_EnableSatComparison = 256,
DBG_DisableBulletLCP = 512,
DBG_EnableCCD = 1024,
DBG_DrawConstraints = (1 << 11),
DBG_DrawConstraintLimits = (1 << 12),
DBG_FastWireframe = (1<<13),
DBG_DrawNormals = (1<<14),
DBG_DrawFrames = (1<<15),
DBG_MAX_DEBUG_DRAW_MODE
};
virtual ~btIDebugDraw() {};
virtual DefaultColors getDefaultColors() const { DefaultColors colors; return colors; }
///the default implementation for setDefaultColors has no effect. A derived class can implement it and store the colors.
virtual void setDefaultColors(const DefaultColors& /*colors*/) {}
virtual void drawLine(const btVector3& from,const btVector3& to,const btVector3& color)=0;
virtual void drawLine(const btVector3& from,const btVector3& to, const btVector3& fromColor, const btVector3& toColor)
{
(void) toColor;
drawLine (from, to, fromColor);
}
virtual void drawSphere(btScalar radius, const btTransform& transform, const btVector3& color)
{
btVector3 center = transform.getOrigin();
btVector3 up = transform.getBasis().getColumn(1);
btVector3 axis = transform.getBasis().getColumn(0);
btScalar minTh = -SIMD_HALF_PI;
btScalar maxTh = SIMD_HALF_PI;
btScalar minPs = -SIMD_HALF_PI;
btScalar maxPs = SIMD_HALF_PI;
btScalar stepDegrees = 30.f;
drawSpherePatch(center, up, axis, radius,minTh, maxTh, minPs, maxPs, color, stepDegrees ,false);
drawSpherePatch(center, up, -axis, radius,minTh, maxTh, minPs, maxPs, color, stepDegrees,false );
}
virtual void drawSphere (const btVector3& p, btScalar radius, const btVector3& color)
{
btTransform tr;
tr.setIdentity();
tr.setOrigin(p);
drawSphere(radius,tr,color);
}
virtual void drawTriangle(const btVector3& v0,const btVector3& v1,const btVector3& v2,const btVector3& /*n0*/,const btVector3& /*n1*/,const btVector3& /*n2*/,const btVector3& color, btScalar alpha)
{
drawTriangle(v0,v1,v2,color,alpha);
}
virtual void drawTriangle(const btVector3& v0,const btVector3& v1,const btVector3& v2,const btVector3& color, btScalar /*alpha*/)
{
drawLine(v0,v1,color);
drawLine(v1,v2,color);
drawLine(v2,v0,color);
}
virtual void drawContactPoint(const btVector3& PointOnB,const btVector3& normalOnB,btScalar distance,int lifeTime,const btVector3& color)=0;
virtual void reportErrorWarning(const char* warningString) = 0;
virtual void draw3dText(const btVector3& location,const char* textString) = 0;
virtual void setDebugMode(int debugMode) =0;
virtual int getDebugMode() const = 0;
virtual void drawAabb(const btVector3& from,const btVector3& to,const btVector3& color)
{
btVector3 halfExtents = (to-from)* 0.5f;
btVector3 center = (to+from) *0.5f;
int i,j;
btVector3 edgecoord(1.f,1.f,1.f),pa,pb;
for (i=0;i<4;i++)
{
for (j=0;j<3;j++)
{
pa = btVector3(edgecoord[0]*halfExtents[0], edgecoord[1]*halfExtents[1],
edgecoord[2]*halfExtents[2]);
pa+=center;
int othercoord = j%3;
edgecoord[othercoord]*=-1.f;
pb = btVector3(edgecoord[0]*halfExtents[0], edgecoord[1]*halfExtents[1],
edgecoord[2]*halfExtents[2]);
pb+=center;
drawLine(pa,pb,color);
}
edgecoord = btVector3(-1.f,-1.f,-1.f);
if (i<3)
edgecoord[i]*=-1.f;
}
}
virtual void drawTransform(const btTransform& transform, btScalar orthoLen)
{
btVector3 start = transform.getOrigin();
drawLine(start, start+transform.getBasis() * btVector3(orthoLen, 0, 0), btVector3(1.f,0.3,0.3));
drawLine(start, start+transform.getBasis() * btVector3(0, orthoLen, 0), btVector3(0.3,1.f, 0.3));
drawLine(start, start+transform.getBasis() * btVector3(0, 0, orthoLen), btVector3(0.3, 0.3,1.f));
}
virtual void drawArc(const btVector3& center, const btVector3& normal, const btVector3& axis, btScalar radiusA, btScalar radiusB, btScalar minAngle, btScalar maxAngle,
const btVector3& color, bool drawSect, btScalar stepDegrees = btScalar(10.f))
{
const btVector3& vx = axis;
btVector3 vy = normal.cross(axis);
btScalar step = stepDegrees * SIMD_RADS_PER_DEG;
int nSteps = (int)btFabs((maxAngle - minAngle) / step);
if(!nSteps) nSteps = 1;
btVector3 prev = center + radiusA * vx * btCos(minAngle) + radiusB * vy * btSin(minAngle);
if(drawSect)
{
drawLine(center, prev, color);
}
for(int i = 1; i <= nSteps; i++)
{
btScalar angle = minAngle + (maxAngle - minAngle) * btScalar(i) / btScalar(nSteps);
btVector3 next = center + radiusA * vx * btCos(angle) + radiusB * vy * btSin(angle);
drawLine(prev, next, color);
prev = next;
}
if(drawSect)
{
drawLine(center, prev, color);
}
}
virtual void drawSpherePatch(const btVector3& center, const btVector3& up, const btVector3& axis, btScalar radius,
btScalar minTh, btScalar maxTh, btScalar minPs, btScalar maxPs, const btVector3& color, btScalar stepDegrees = btScalar(10.f),bool drawCenter = true)
{
btVector3 vA[74];
btVector3 vB[74];
btVector3 *pvA = vA, *pvB = vB, *pT;
btVector3 npole = center + up * radius;
btVector3 spole = center - up * radius;
btVector3 arcStart;
btScalar step = stepDegrees * SIMD_RADS_PER_DEG;
const btVector3& kv = up;
const btVector3& iv = axis;
btVector3 jv = kv.cross(iv);
bool drawN = false;
bool drawS = false;
if(minTh <= -SIMD_HALF_PI)
{
minTh = -SIMD_HALF_PI + step;
drawN = true;
}
if(maxTh >= SIMD_HALF_PI)
{
maxTh = SIMD_HALF_PI - step;
drawS = true;
}
if(minTh > maxTh)
{
minTh = -SIMD_HALF_PI + step;
maxTh = SIMD_HALF_PI - step;
drawN = drawS = true;
}
int n_hor = (int)((maxTh - minTh) / step) + 1;
if(n_hor < 2) n_hor = 2;
btScalar step_h = (maxTh - minTh) / btScalar(n_hor - 1);
bool isClosed = false;
if(minPs > maxPs)
{
minPs = -SIMD_PI + step;
maxPs = SIMD_PI;
isClosed = true;
}
else if((maxPs - minPs) >= SIMD_PI * btScalar(2.f))
{
isClosed = true;
}
else
{
isClosed = false;
}
int n_vert = (int)((maxPs - minPs) / step) + 1;
if(n_vert < 2) n_vert = 2;
btScalar step_v = (maxPs - minPs) / btScalar(n_vert - 1);
for(int i = 0; i < n_hor; i++)
{
btScalar th = minTh + btScalar(i) * step_h;
btScalar sth = radius * btSin(th);
btScalar cth = radius * btCos(th);
for(int j = 0; j < n_vert; j++)
{
btScalar psi = minPs + btScalar(j) * step_v;
btScalar sps = btSin(psi);
btScalar cps = btCos(psi);
pvB[j] = center + cth * cps * iv + cth * sps * jv + sth * kv;
if(i)
{
drawLine(pvA[j], pvB[j], color);
}
else if(drawS)
{
drawLine(spole, pvB[j], color);
}
if(j)
{
drawLine(pvB[j-1], pvB[j], color);
}
else
{
arcStart = pvB[j];
}
if((i == (n_hor - 1)) && drawN)
{
drawLine(npole, pvB[j], color);
}
if (drawCenter)
{
if(isClosed)
{
if(j == (n_vert-1))
{
drawLine(arcStart, pvB[j], color);
}
}
else
{
if(((!i) || (i == (n_hor-1))) && ((!j) || (j == (n_vert-1))))
{
drawLine(center, pvB[j], color);
}
}
}
}
pT = pvA; pvA = pvB; pvB = pT;
}
}
virtual void drawBox(const btVector3& bbMin, const btVector3& bbMax, const btVector3& color)
{
drawLine(btVector3(bbMin[0], bbMin[1], bbMin[2]), btVector3(bbMax[0], bbMin[1], bbMin[2]), color);
drawLine(btVector3(bbMax[0], bbMin[1], bbMin[2]), btVector3(bbMax[0], bbMax[1], bbMin[2]), color);
drawLine(btVector3(bbMax[0], bbMax[1], bbMin[2]), btVector3(bbMin[0], bbMax[1], bbMin[2]), color);
drawLine(btVector3(bbMin[0], bbMax[1], bbMin[2]), btVector3(bbMin[0], bbMin[1], bbMin[2]), color);
drawLine(btVector3(bbMin[0], bbMin[1], bbMin[2]), btVector3(bbMin[0], bbMin[1], bbMax[2]), color);
drawLine(btVector3(bbMax[0], bbMin[1], bbMin[2]), btVector3(bbMax[0], bbMin[1], bbMax[2]), color);
drawLine(btVector3(bbMax[0], bbMax[1], bbMin[2]), btVector3(bbMax[0], bbMax[1], bbMax[2]), color);
drawLine(btVector3(bbMin[0], bbMax[1], bbMin[2]), btVector3(bbMin[0], bbMax[1], bbMax[2]), color);
drawLine(btVector3(bbMin[0], bbMin[1], bbMax[2]), btVector3(bbMax[0], bbMin[1], bbMax[2]), color);
drawLine(btVector3(bbMax[0], bbMin[1], bbMax[2]), btVector3(bbMax[0], bbMax[1], bbMax[2]), color);
drawLine(btVector3(bbMax[0], bbMax[1], bbMax[2]), btVector3(bbMin[0], bbMax[1], bbMax[2]), color);
drawLine(btVector3(bbMin[0], bbMax[1], bbMax[2]), btVector3(bbMin[0], bbMin[1], bbMax[2]), color);
}
virtual void drawBox(const btVector3& bbMin, const btVector3& bbMax, const btTransform& trans, const btVector3& color)
{
drawLine(trans * btVector3(bbMin[0], bbMin[1], bbMin[2]), trans * btVector3(bbMax[0], bbMin[1], bbMin[2]), color);
drawLine(trans * btVector3(bbMax[0], bbMin[1], bbMin[2]), trans * btVector3(bbMax[0], bbMax[1], bbMin[2]), color);
drawLine(trans * btVector3(bbMax[0], bbMax[1], bbMin[2]), trans * btVector3(bbMin[0], bbMax[1], bbMin[2]), color);
drawLine(trans * btVector3(bbMin[0], bbMax[1], bbMin[2]), trans * btVector3(bbMin[0], bbMin[1], bbMin[2]), color);
drawLine(trans * btVector3(bbMin[0], bbMin[1], bbMin[2]), trans * btVector3(bbMin[0], bbMin[1], bbMax[2]), color);
drawLine(trans * btVector3(bbMax[0], bbMin[1], bbMin[2]), trans * btVector3(bbMax[0], bbMin[1], bbMax[2]), color);
drawLine(trans * btVector3(bbMax[0], bbMax[1], bbMin[2]), trans * btVector3(bbMax[0], bbMax[1], bbMax[2]), color);
drawLine(trans * btVector3(bbMin[0], bbMax[1], bbMin[2]), trans * btVector3(bbMin[0], bbMax[1], bbMax[2]), color);
drawLine(trans * btVector3(bbMin[0], bbMin[1], bbMax[2]), trans * btVector3(bbMax[0], bbMin[1], bbMax[2]), color);
drawLine(trans * btVector3(bbMax[0], bbMin[1], bbMax[2]), trans * btVector3(bbMax[0], bbMax[1], bbMax[2]), color);
drawLine(trans * btVector3(bbMax[0], bbMax[1], bbMax[2]), trans * btVector3(bbMin[0], bbMax[1], bbMax[2]), color);
drawLine(trans * btVector3(bbMin[0], bbMax[1], bbMax[2]), trans * btVector3(bbMin[0], bbMin[1], bbMax[2]), color);
}
virtual void drawCapsule(btScalar radius, btScalar halfHeight, int upAxis, const btTransform& transform, const btVector3& color)
{
int stepDegrees = 30;
btVector3 capStart(0.f,0.f,0.f);
capStart[upAxis] = -halfHeight;
btVector3 capEnd(0.f,0.f,0.f);
capEnd[upAxis] = halfHeight;
// Draw the ends
{
btTransform childTransform = transform;
childTransform.getOrigin() = transform * capStart;
{
btVector3 center = childTransform.getOrigin();
btVector3 up = childTransform.getBasis().getColumn((upAxis+1)%3);
btVector3 axis = -childTransform.getBasis().getColumn(upAxis);
btScalar minTh = -SIMD_HALF_PI;
btScalar maxTh = SIMD_HALF_PI;
btScalar minPs = -SIMD_HALF_PI;
btScalar maxPs = SIMD_HALF_PI;
drawSpherePatch(center, up, axis, radius,minTh, maxTh, minPs, maxPs, color, btScalar(stepDegrees) ,false);
}
}
{
btTransform childTransform = transform;
childTransform.getOrigin() = transform * capEnd;
{
btVector3 center = childTransform.getOrigin();
btVector3 up = childTransform.getBasis().getColumn((upAxis+1)%3);
btVector3 axis = childTransform.getBasis().getColumn(upAxis);
btScalar minTh = -SIMD_HALF_PI;
btScalar maxTh = SIMD_HALF_PI;
btScalar minPs = -SIMD_HALF_PI;
btScalar maxPs = SIMD_HALF_PI;
drawSpherePatch(center, up, axis, radius,minTh, maxTh, minPs, maxPs, color, btScalar(stepDegrees) ,false);
}
}
// Draw some additional lines
btVector3 start = transform.getOrigin();
for (int i=0;i<360;i+=stepDegrees)
{
capEnd[(upAxis+1)%3] = capStart[(upAxis+1)%3] = btSin(btScalar(i)*SIMD_RADS_PER_DEG)*radius;
capEnd[(upAxis+2)%3] = capStart[(upAxis+2)%3] = btCos(btScalar(i)*SIMD_RADS_PER_DEG)*radius;
drawLine(start+transform.getBasis() * capStart,start+transform.getBasis() * capEnd, color);
}
}
virtual void drawCylinder(btScalar radius, btScalar halfHeight, int upAxis, const btTransform& transform, const btVector3& color)
{
btVector3 start = transform.getOrigin();
btVector3 offsetHeight(0,0,0);
offsetHeight[upAxis] = halfHeight;
int stepDegrees=30;
btVector3 capStart(0.f,0.f,0.f);
capStart[upAxis] = -halfHeight;
btVector3 capEnd(0.f,0.f,0.f);
capEnd[upAxis] = halfHeight;
for (int i=0;i<360;i+=stepDegrees)
{
capEnd[(upAxis+1)%3] = capStart[(upAxis+1)%3] = btSin(btScalar(i)*SIMD_RADS_PER_DEG)*radius;
capEnd[(upAxis+2)%3] = capStart[(upAxis+2)%3] = btCos(btScalar(i)*SIMD_RADS_PER_DEG)*radius;
drawLine(start+transform.getBasis() * capStart,start+transform.getBasis() * capEnd, color);
}
// Drawing top and bottom caps of the cylinder
btVector3 yaxis(0,0,0);
yaxis[upAxis] = btScalar(1.0);
btVector3 xaxis(0,0,0);
xaxis[(upAxis+1)%3] = btScalar(1.0);
drawArc(start-transform.getBasis()*(offsetHeight),transform.getBasis()*yaxis,transform.getBasis()*xaxis,radius,radius,0,SIMD_2_PI,color,false,btScalar(10.0));
drawArc(start+transform.getBasis()*(offsetHeight),transform.getBasis()*yaxis,transform.getBasis()*xaxis,radius,radius,0,SIMD_2_PI,color,false,btScalar(10.0));
}
virtual void drawCone(btScalar radius, btScalar height, int upAxis, const btTransform& transform, const btVector3& color)
{
int stepDegrees = 30;
btVector3 start = transform.getOrigin();
btVector3 offsetHeight(0,0,0);
btScalar halfHeight = height * btScalar(0.5);
offsetHeight[upAxis] = halfHeight;
btVector3 offsetRadius(0,0,0);
offsetRadius[(upAxis+1)%3] = radius;
btVector3 offset2Radius(0,0,0);
offset2Radius[(upAxis+2)%3] = radius;
btVector3 capEnd(0.f,0.f,0.f);
capEnd[upAxis] = -halfHeight;
for (int i=0;i<360;i+=stepDegrees)
{
capEnd[(upAxis+1)%3] = btSin(btScalar(i)*SIMD_RADS_PER_DEG)*radius;
capEnd[(upAxis+2)%3] = btCos(btScalar(i)*SIMD_RADS_PER_DEG)*radius;
drawLine(start+transform.getBasis() * (offsetHeight),start+transform.getBasis() * capEnd, color);
}
drawLine(start+transform.getBasis() * (offsetHeight),start+transform.getBasis() * (-offsetHeight+offsetRadius),color);
drawLine(start+transform.getBasis() * (offsetHeight),start+transform.getBasis() * (-offsetHeight-offsetRadius),color);
drawLine(start+transform.getBasis() * (offsetHeight),start+transform.getBasis() * (-offsetHeight+offset2Radius),color);
drawLine(start+transform.getBasis() * (offsetHeight),start+transform.getBasis() * (-offsetHeight-offset2Radius),color);
// Drawing the base of the cone
btVector3 yaxis(0,0,0);
yaxis[upAxis] = btScalar(1.0);
btVector3 xaxis(0,0,0);
xaxis[(upAxis+1)%3] = btScalar(1.0);
drawArc(start-transform.getBasis()*(offsetHeight),transform.getBasis()*yaxis,transform.getBasis()*xaxis,radius,radius,0,SIMD_2_PI,color,false,10.0);
}
virtual void drawPlane(const btVector3& planeNormal, btScalar planeConst, const btTransform& transform, const btVector3& color)
{
btVector3 planeOrigin = planeNormal * planeConst;
btVector3 vec0,vec1;
btPlaneSpace1(planeNormal,vec0,vec1);
btScalar vecLen = 100.f;
btVector3 pt0 = planeOrigin + vec0*vecLen;
btVector3 pt1 = planeOrigin - vec0*vecLen;
btVector3 pt2 = planeOrigin + vec1*vecLen;
btVector3 pt3 = planeOrigin - vec1*vecLen;
drawLine(transform*pt0,transform*pt1,color);
drawLine(transform*pt2,transform*pt3,color);
}
virtual void flushLines()
{
}
};
#endif //BT_IDEBUG_DRAW__H
| 0 | 0.9038 | 1 | 0.9038 | game-dev | MEDIA | 0.779539 | game-dev | 0.976934 | 1 | 0.976934 |
PotRooms/AzurPromiliaData | 2,014 | Lua/lang/kr/lang_buff_info.lua | local buff_info = {}
local key_to_index_map = {}
local index_to_key_map = {}
for k, v in pairs(key_to_index_map) do
index_to_key_map[v] = k
end
local value_to_index_map = {}
local index_to_value_map = {}
for k, v in pairs(value_to_index_map) do
index_to_value_map[v] = k
end
local function SetReadonlyTable(t)
for k, v in pairs(t) do
if type(v) == "table" then
t[k] = SetReadonlyTable(v)
end
end
local mt = {
__data = t,
__index_to_key_map = index_to_key_map,
__key_to_index_map = key_to_index_map,
__index_to_value_map = index_to_value_map,
__index = function(t, k)
local tmt = getmetatable(t)
local data = tmt.__data
local value_index
if tmt.__key_to_index_map[k] ~= nil then
value_index = data[tmt.__key_to_index_map[k]]
else
value_index = data[k]
end
if type(value_index) == "table" then
return value_index
else
return tmt.__index_to_value_map[value_index]
end
end,
__newindex = function(t, k, v)
errorf("attempt to modify a read-only talbe!", 2)
end,
__pairs = function(t, k)
return function(t, k)
local tmt = getmetatable(t)
local data = tmt.__data
local nk, nv
if tmt.__key_to_index_map[k] ~= nil then
local iter_key = tmt.__key_to_index_map[k]
nk, nv = next(data, iter_key)
else
nk, nv = next(data, k)
end
local key, value
if tmt.__index_to_key_map[nk] ~= nil then
key = tmt.__index_to_key_map[nk]
else
key = nk
end
if type(nv) == "table" then
value = nv
else
value = tmt.__index_to_value_map[nv]
end
return key, value
end, t, nil
end,
__len = function(t)
local tmt = getmetatable(t)
local data = tmt.__data
return #data
end
}
t = setmetatable({}, mt)
return t
end
buff_info = SetReadonlyTable(buff_info)
return buff_info
| 0 | 0.689289 | 1 | 0.689289 | game-dev | MEDIA | 0.552124 | game-dev | 0.842958 | 1 | 0.842958 |
AM2R-Community-Developers/AM2R-Community-Updates | 6,133 | objects/oSubScreenMisc.object.gmx | <!--This Document is generated by GameMaker, if you edit it by hand then you do so at your own risk!-->
<object>
<spriteName>sSubScrMisc</spriteName>
<solid>0</solid>
<visible>-1</visible>
<depth>-10</depth>
<persistent>0</persistent>
<parentName>oSubScreenSuit</parentName>
<maskName><undefined></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>event_inherited();
misc = get_text("ItemsMenu", "Misc");
morph = get_text("ItemsMenu", "MorphBall");
spider = get_text("ItemsMenu", "SpiderBall");
spring = get_text("ItemsMenu", "SpringBall");
bomb = get_text("ItemsMenu", "Bombs");
pgrip = get_text("ItemsMenu", "PowerGrip");
sattack = get_text("ItemsMenu", "ScrewAttack");
</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>draw_sprite(sprite_index, -1, x, y);
draw_set_color(c_white);
draw_set_font(fontMenuTiny);
draw_set_alpha(1);
draw_sprite(sSubScrButton, global.morphball, x - 28, y + 16);
draw_text(x - 20, y + 15 + oControl.subScrItemOffset, morph);
if (global.item[2]) {
draw_sprite(sSubScrButton, global.spiderball, x - 28, y + 25);
draw_text(x - 20, y + 24 + oControl.subScrItemOffset, spider);
}
if (global.item[3]) {
draw_sprite(sSubScrButton, global.jumpball, x - 28, y + 34);
draw_text(x - 20, y + 33 + oControl.subScrItemOffset, spring);
}
if (global.item[0]) {
draw_sprite(sSubScrButton, global.bomb, x - 28, y + 43);
draw_text(x - 20, y + 42 + oControl.subScrItemOffset, bomb);
}
if (global.item[1]) {
draw_sprite(sSubScrButton, global.powergrip, x - 28, y + 52);
draw_text(x - 20, y + 51 + oControl.subScrItemOffset, pgrip);
}
if (global.item[8]) {
draw_sprite(sSubScrButton, global.screwattack, x - 28, y + 61);
draw_text(x - 20, y + 60 + oControl.subScrItemOffset, sattack);
}
if (drawlines) {
if (global.curropt == 8) {
draw_sprite_ext(sSubScrHilight, -1, x - 28, y + 16, 1, 1, 0, -1, halpha);
draw_line(x - 34, y + 18, x - 50, y + 18);
draw_line(x - 50, y + 18, oSubScrPlayer.x, oSubScrPlayer.y + 60);
draw_sprite_ext(sSubScrItem, -1, oSubScrPlayer.x, oSubScrPlayer.y + 60, 1, 1, 0, -1, 1);
}
if (global.curropt == 9) {
draw_sprite_ext(sSubScrHilight, -1, x - 28, y + 25, 1, 1, 0, -1, halpha);
draw_line(x - 34, y + 27, x - 50, y + 27);
draw_line(x - 50, y + 27, oSubScrPlayer.x, oSubScrPlayer.y + 60);
draw_sprite_ext(sSubScrItem, -1, oSubScrPlayer.x, oSubScrPlayer.y + 60, 1, 1, 0, -1, 1);
}
if (global.curropt == 10) {
draw_sprite_ext(sSubScrHilight, -1, x - 28, y + 34, 1, 1, 0, -1, halpha);
draw_line(x - 34, y + 36, x - 50, y + 36);
draw_line(x - 50, y + 36, oSubScrPlayer.x, oSubScrPlayer.y + 60);
draw_sprite_ext(sSubScrItem, -1, oSubScrPlayer.x, oSubScrPlayer.y + 60, 1, 1, 0, -1, 1);
}
if (global.curropt == 11) {
draw_sprite_ext(sSubScrHilight, -1, x - 28, y + 43, 1, 1, 0, -1, halpha);
draw_line(x - 34, y + 45, x - 50, y + 45);
draw_line(x - 50, y + 45, oSubScrPlayer.x, oSubScrPlayer.y + 60);
draw_sprite_ext(sSubScrItem, -1, oSubScrPlayer.x, oSubScrPlayer.y + 60, 1, 1, 0, -1, 1);
}
if (global.curropt == 12) {
draw_sprite_ext(sSubScrHilight, -1, x - 28, y + 52, 1, 1, 0, -1, halpha);
draw_line(x - 34, y + 54, x - 50, y + 54);
draw_line(x - 50, y + 54, oSubScrPlayer.x + 35, oSubScrPlayer.y + 95);
draw_sprite_ext(sSubScrItem, -1, oSubScrPlayer.x + 35, oSubScrPlayer.y + 95, 1, 1, 0, -1, 1);
}
if (global.curropt == 13) {
draw_sprite_ext(sSubScrHilight, -1, x - 28, y + 61, 1, 1, 0, -1, halpha);
draw_line(x - 34, y + 63, x - 50, y + 63);
draw_line(x - 50, y + 63, oSubScrPlayer.x, oSubScrPlayer.y + 43);
draw_sprite_ext(sSubScrItem, -1, oSubScrPlayer.x, oSubScrPlayer.y + 43, 1, 1, 0, -1, 1);
}
} // if (drawlines)
draw_set_alpha(1);
draw_set_font(fontSubScr);
draw_set_halign(fa_left);
draw_set_color(c_black);
//draw_text(x + 1 - 30, y + 4 - 1, "SUIT");
//draw_text(x + 1 - 30, y + 4 - 63, "BEAM");
draw_text(x + 1 - 30, y + 4 - 1 + oControl.subScrHeaderOffset, misc);
//draw_text(x + 1 - 30, y + 4 - 45, "BOOTS");
draw_set_color(c_white);
//draw_text(x - 30, y + 3 - 1, "SUIT");
//draw_text(x - 30, y + 3 - 63, "BEAM");
draw_text(x - 30, y + 3 - 1 + oControl.subScrHeaderOffset, misc);
//draw_text(x - 30, y + 3 - 45, "BOOTS");
</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>
| 0 | 0.718709 | 1 | 0.718709 | game-dev | MEDIA | 0.830775 | game-dev | 0.56594 | 1 | 0.56594 |
vfx-dev/SwanSong | 9,138 | src/main/java/com/ventooth/swansong/mixin/mixins/client/hooks/MixinRenderBlocks.java | /*
* Swansong
*
* Copyright 2025 Ven, FalsePattern
*
* This software is licensed under the Open Software License version
* 3.0. The full text of this license can be found in https://opensource.org/licenses/OSL-3.0
* or in the LICENSES directory which is distributed along with the software.
*/
package com.ventooth.swansong.mixin.mixins.client.hooks;
import com.ventooth.swansong.shader.ShaderEngine;
import com.ventooth.swansong.shader.ShaderEntityData;
import com.ventooth.swansong.shader.ShaderState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.Slice;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFlowerPot;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.world.IBlockAccess;
@Mixin(value = RenderBlocks.class,
priority = 1010)
public abstract class MixinRenderBlocks {
@Shadow
public IBlockAccess blockAccess;
@Unique
private final ShaderEntityData swansong$entityData = ShaderEntityData.get();
@Inject(method = "renderBlockByRenderType",
at = @At("HEAD"),
require = 1)
private void state_pushEntityBlock(Block block, int posX, int posY, int posZ, CallbackInfoReturnable<Boolean> cir) {
if (ShaderEngine.isInitialized()) {
swansong$entityData.pushEntity(block, blockAccess.getBlockMetadata(posX, posY, posZ));
}
}
@Inject(method = "renderBlockByRenderType",
at = @At("RETURN"),
require = 1)
private void state_popEntityBlock(CallbackInfoReturnable<Boolean> cir) {
if (ShaderEngine.isInitialized()) {
swansong$entityData.popEntity();
}
}
@Inject(method = "renderBlockFlowerpot",
at = @At("HEAD"),
require = 1)
private void state_pushEntityBlockFlowerpot0(BlockFlowerPot block,
int posX,
int posY,
int posZ,
CallbackInfoReturnable<Boolean> cir) {
if (ShaderEngine.isInitialized()) {
swansong$entityData.pushEntity(block, blockAccess.getBlockMetadata(posX, posY, posZ));
}
}
@Inject(method = "renderBlockFlowerpot",
at = @At("RETURN"),
require = 1)
private void state_popEntityBlockFlowerpot0(CallbackInfoReturnable<Boolean> cir) {
if (ShaderEngine.isInitialized()) {
swansong$entityData.popEntity();
}
}
@Redirect(method = "renderBlockFlowerpot",
at = @At(value = "INVOKE",
target = "Lnet/minecraft/block/Block;getRenderType()I"),
require = 1)
private int state_pushEntityBlockFlowerpot1(Block block) {
if (ShaderEngine.isInitialized()) {
swansong$entityData.pushEntity(block);
}
return block.getRenderType();
}
@Inject(method = "renderBlockFlowerpot",
at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/renderer/Tessellator;addTranslation(FFF)V",
shift = At.Shift.AFTER,
ordinal = 1),
require = 1)
private void state_popEntityBlockFlowerpot1(CallbackInfoReturnable<Boolean> cir) {
if (ShaderEngine.isInitialized()) {
swansong$entityData.popEntity();
}
}
// region Block Light Level
@ModifyConstant(method = {"renderBlockBed(Lnet/minecraft/block/Block;III)Z",
"renderBlockDoor(Lnet/minecraft/block/Block;III)Z",
"renderBlockLiquid(Lnet/minecraft/block/Block;III)Z",
"renderBlockCactusImpl(Lnet/minecraft/block/Block;IIIFFF)Z",
"renderStandardBlockWithColorMultiplier(Lnet/minecraft/block/Block;IIIFFF)Z",
"renderBlockSandFalling(Lnet/minecraft/block/Block;Lnet/minecraft/world/World;IIII)V"},
constant = @Constant(floatValue = 0.5F),
require = 6)
public float state_blockSingleLightLevel05(float constant) {
return ShaderEngine.isInitialized() ? ShaderState.blockLightLevel(constant) : constant;
}
@ModifyConstant(method = {"renderBlockBed(Lnet/minecraft/block/Block;III)Z",
"renderBlockLiquid(Lnet/minecraft/block/Block;III)Z",
"renderBlockDoor(Lnet/minecraft/block/Block;III)Z",
"renderBlockCactusImpl(Lnet/minecraft/block/Block;IIIFFF)Z",
"renderStandardBlockWithColorMultiplier(Lnet/minecraft/block/Block;IIIFFF)Z",
"renderBlockSandFalling(Lnet/minecraft/block/Block;Lnet/minecraft/world/World;IIII)V"},
constant = @Constant(floatValue = 0.6F),
expect = 6)
public float state_blockSingleLightLevel06(float constant) {
return ShaderEngine.isInitialized() ? ShaderState.blockLightLevel(constant) : constant;
}
@ModifyConstant(method = {"renderBlockBed(Lnet/minecraft/block/Block;III)Z",
"renderBlockLiquid(Lnet/minecraft/block/Block;III)Z",
"renderBlockDoor(Lnet/minecraft/block/Block;III)Z",
"renderBlockCactusImpl(Lnet/minecraft/block/Block;IIIFFF)Z",
"renderStandardBlockWithColorMultiplier(Lnet/minecraft/block/Block;IIIFFF)Z",
"renderBlockSandFalling(Lnet/minecraft/block/Block;Lnet/minecraft/world/World;IIII)V"},
constant = @Constant(floatValue = 0.8F),
expect = 6)
public float state_blockSingleLightLevel08(float constant) {
return ShaderEngine.isInitialized() ? ShaderState.blockLightLevel(constant) : constant;
}
@ModifyConstant(method = "renderPistonExtension(Lnet/minecraft/block/Block;IIIZ)Z",
constant = @Constant(floatValue = 0.5F),
slice = @Slice(from = @At(value = "FIELD",
target = "Lnet/minecraft/client/renderer/RenderBlocks;uvRotateEast:I")),
expect = 4)
public float state_pistonBlockLightLevel05(float constant) {
return ShaderEngine.isInitialized() ? ShaderState.blockLightLevel(constant) : constant;
}
@ModifyConstant(method = "renderPistonExtension(Lnet/minecraft/block/Block;IIIZ)Z",
constant = @Constant(floatValue = 0.6F),
expect = 12)
public float state_pistonBlockLightLevel06(float constant) {
return ShaderEngine.isInitialized() ? ShaderState.blockLightLevel(constant) : constant;
}
@ModifyConstant(method = "renderPistonExtension(Lnet/minecraft/block/Block;IIIZ)Z",
constant = @Constant(floatValue = 0.8F),
expect = 4)
public float state_pistonBlockLightLevel08(float constant) {
return ShaderEngine.isInitialized() ? ShaderState.blockLightLevel(constant) : constant;
}
@ModifyConstant(method = {"renderStandardBlockWithAmbientOcclusionPartial(Lnet/minecraft/block/Block;IIIFFF)Z",
"renderStandardBlockWithAmbientOcclusion(Lnet/minecraft/block/Block;IIIFFF)Z"},
constant = @Constant(floatValue = 0.5F),
expect = 12)
public float state_multipleBlockLightLevel05(float constant) {
return ShaderEngine.isInitialized() ? ShaderState.blockLightLevel(constant) : constant;
}
@ModifyConstant(method = {"renderStandardBlockWithAmbientOcclusionPartial(Lnet/minecraft/block/Block;IIIFFF)Z",
"renderStandardBlockWithAmbientOcclusion(Lnet/minecraft/block/Block;IIIFFF)Z"},
constant = @Constant(floatValue = 0.6F),
expect = 24)
public float state_multipleBlockLightLevel06(float constant) {
return ShaderEngine.isInitialized() ? ShaderState.blockLightLevel(constant) : constant;
}
@ModifyConstant(method = {"renderStandardBlockWithAmbientOcclusionPartial(Lnet/minecraft/block/Block;IIIFFF)Z",
"renderStandardBlockWithAmbientOcclusion(Lnet/minecraft/block/Block;IIIFFF)Z"},
constant = @Constant(floatValue = 0.8F),
expect = 24)
public float state_multipleBlockLightLevel08(float constant) {
return ShaderEngine.isInitialized() ? ShaderState.blockLightLevel(constant) : constant;
}
// endregion
}
| 0 | 0.897937 | 1 | 0.897937 | game-dev | MEDIA | 0.957709 | game-dev | 0.870168 | 1 | 0.870168 |
gamedevware/charon-unity3d | 73,861 | src/GameDevWare.Charon.Unity/Packages/com.gamedevware.charon/Editor/Cli/CharonCli.cs | /*
Copyright (c) 2025 GameDevWare, Denis Zykov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GameDevWare.Charon.Editor.Services.ServerApi;
using GameDevWare.Charon.Editor.Utils;
using JetBrains.Annotations;
using UnityEngine;
#if JSON_NET_3_0_2_OR_NEWER
using Newtonsoft.Json;
using JsonObject = Newtonsoft.Json.Linq.JObject;
using JsonValue = Newtonsoft.Json.Linq.JToken;
#else
using GameDevWare.Charon.Editor.Json;
#endif
// ReSharper disable UseAwaitUsing
namespace GameDevWare.Charon.Editor.Cli
{
/// <summary>
/// Provides a convenient interface for running Charon.exe command line operations.
/// This class encapsulates functionality for creating, updating, deleting, importing, exporting, and finding documents
/// within a specified GameData URL, either file-based or server-based. It simplifies interactions
/// with the Charon command line tool, offering methods that return tasks representing the operations.
/// For more detailed documentation of each method, refer to the Charon command line documentation at
/// https://gamedevware.github.io/charon/advanced/command_line.html
/// </summary>
[PublicAPI, UsedImplicitly(ImplicitUseTargetFlags.WithMembers)]
public static class CharonCli
{
private static readonly string[] EmptyParameters = Array.Empty<string>();
private static bool ScriptFilesAreCopied;
public const string FORMAT_JSON = "json";
public const string FORMAT_BSON = "bson";
public const string FORMAT_MESSAGE_PACK = "msgpack";
public const string FORMAT_XLSX = "xlsx";
public const string FORMAT_XLIFF2 = "xliff2";
public const string FORMAT_XLIFF1 = "xliff1";
private const string SOURCE_STANDARD_INPUT = "in";
private const string TARGET_STANDARD_OUTPUT = "out";
private const string TARGET_STANDARD_ERROR = "err";
private const string TARGET_NULL = "null";
internal static async Task<CharonServerProcess> StartServerAsync
(
string gameDataPath,
int port,
string lockFilePath = null,
CharonLogLevel? logsVerbosity = null,
Action<string, float> progressCallback = null
)
{
if (string.IsNullOrEmpty(gameDataPath)) throw new ArgumentException("Value cannot be null or empty.", nameof(gameDataPath));
if (port <= 0 || port > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(port));
logsVerbosity ??= CharonEditorModule.Instance.Settings.LogLevel;
gameDataPath = Path.GetFullPath(gameDataPath);
if (File.Exists(gameDataPath) == false) throw new IOException($"File '{gameDataPath}' doesn't exists.");
progressCallback?.Invoke(Resources.UI_UNITYPLUGIN_WINDOW_EDITOR_LAUNCHING_EXECUTABLE, 0.30f);
var listenAddress = new Uri("http://localhost:" + port);
lockFilePath ??= Path.Combine(CharonFileUtils.LibraryCharonPath, CharonServerProcess.GetLockFileNameFor(gameDataPath));
var settings = CharonEditorModule.Instance.Settings;
var charonPath = EnsureCharonRunScript("RunCharon");
var idleTimeout = settings.IdleCloseTimeout;
var unityPid = Process.GetCurrentProcess().Id;
var runResult = await CommandLineUtils.RunAsync(
new ToolRunOptions
(
charonPath,
ToolRunOptions.FlattenArguments(
"SERVER", "START",
"--dataBase", Path.GetFullPath(gameDataPath),
"--port", port.ToString(),
"--watchPid", unityPid.ToString(),
"--lockFile", Path.GetFullPath(lockFilePath),
"--maxIdleTime", idleTimeout.ToString(), // auto-close idle editor
"--log", logsVerbosity == CharonLogLevel.None ? TARGET_NULL : TARGET_STANDARD_OUTPUT,
logsVerbosity == CharonLogLevel.Verbose ? "--verbose" : null
)
) {
CaptureStandardError = true,
CaptureStandardOutput = false,
ExecutionTimeout = TimeSpan.Zero,
WaitForExit = false,
StartInfo = {
EnvironmentVariables = {
{ "DOTNET_CONTENTROOT", CharonFileUtils.CharonAppContentPath },
{ "STANDALONE__GAMEASSETSPATH", Path.GetFullPath("./") },
//
{ "CHARON_API_SERVER", settings.GetServerAddressUrl().OriginalString },
{ "CHARON_API_KEY", "" },
{ "SERILOG__WRITETO__0__NAME", "File" }, {
"SERILOG__WRITETO__0__ARGS__PATH", Path.GetFullPath(Path.Combine(CharonFileUtils.LibraryCharonLogsPath,
$"{DateTime.UtcNow:yyyy_MM_dd_hh}.charon.unity.log"))
},
}
}
}
);
progressCallback?.Invoke(Resources.UI_UNITYPLUGIN_WINDOW_EDITOR_LAUNCHING_EXECUTABLE, 1.0f);
return new CharonServerProcess(runResult, gameDataPath, listenAddress, lockFilePath);
}
/// <summary>
/// Init the specified GameData file.
/// https://gamedevware.github.io/charon/advanced/commands/init.html
/// </summary>
/// <param name="gameDataPath">The path of the GameData file.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The created document.</returns>
public static async Task InitGameDataAsync
(
string gameDataPath,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataPath == null) throw new ArgumentNullException(nameof(gameDataPath));
using var _ = await RunCharonAsync
(
string.Empty, logsVerbosity,
ToolRunOptions.FlattenArguments(
"INIT", gameDataPath
),
configureTool
);
}
/// <summary>
/// Creates a document in the specified GameData URL.
/// https://gamedevware.github.io/charon/advanced/commands/data_create.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNameOrId">The schema name or ID of the document.</param>
/// <param name="document">The document to create as a shared reference to a JsonObject.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The created document.</returns>
public static async Task<JsonObject> CreateDocumentAsync
(
string gameDataUrl,
string apiKey,
string schemaNameOrId,
JsonObject document,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNameOrId == null) throw new ArgumentNullException(nameof(schemaNameOrId));
if (document == null) throw new ArgumentNullException(nameof(document));
var inputFileName = WriteJsonInput(document);
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "CREATE", gameDataUrl,
"--schema", schemaNameOrId,
"--input", inputFileName,
"--inputFormat", "json",
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return (JsonObject)ReadOutputJson(outputFileName);
}
/// <summary>
/// Updates a document in the specified GameData URL.
/// https://gamedevware.github.io/charon/advanced/commands/data_update.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNameOrId">The schema name or ID of the document.</param>
/// <param name="document">The document to update as a shared reference to a JsonObject.</param>
/// <param name="id">Optional ID of the document to update if not present in the Document object.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The updated document.</returns>
public static async Task<JsonObject> UpdateDocumentAsync
(
string gameDataUrl,
string apiKey,
string schemaNameOrId,
JsonObject document,
string id = null,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNameOrId == null) throw new ArgumentNullException(nameof(schemaNameOrId));
if (document == null) throw new ArgumentNullException(nameof(document));
var inputFileName = WriteJsonInput(document);
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "UPDATE", gameDataUrl,
"--schema", schemaNameOrId,
string.IsNullOrEmpty(id) ? EmptyParameters : new[] { "--id", id },
"--input", inputFileName,
"--inputFormat", "json",
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return (JsonObject)ReadOutputJson(outputFileName);
}
/// <summary>
/// Deletes a document in the specified GameData URL.
/// https://gamedevware.github.io/charon/advanced/commands/data_delete.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNameOrId">The schema name or ID of the document.</param>
/// <param name="document">The document to delete, only the ID is used for deletion.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The deleted document or null in case of failure.</returns>
public static async Task<JsonObject> DeleteDocumentAsync
(
string gameDataUrl,
string apiKey,
string schemaNameOrId,
JsonObject document,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNameOrId == null) throw new ArgumentNullException(nameof(schemaNameOrId));
if (document == null) throw new ArgumentNullException(nameof(document));
var outputFileName = CreateTemporaryFile("json");
var id = document["Id"]?.ToString();
if (string.IsNullOrEmpty(id))
{
throw new ArgumentException("Document missing Id property.", nameof(document));
}
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "DELETE", gameDataUrl,
"--schema", schemaNameOrId,
"--id", id,
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return (JsonObject)ReadOutputJson(outputFileName);
}
/// <summary>
/// Deletes a document in the specified GameData URL by ID.
/// https://gamedevware.github.io/charon/advanced/commands/data_delete.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNameOrId">The schema name or ID of the document.</param>
/// <param name="id">The ID of the document to delete.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The deleted document or null in case of failure.</returns>
public static async Task<JsonObject> DeleteDocumentAsync
(
string gameDataUrl,
string apiKey,
string schemaNameOrId,
string id,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNameOrId == null) throw new ArgumentNullException(nameof(schemaNameOrId));
if (id == null) throw new ArgumentNullException(nameof(id));
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "DELETE", gameDataUrl,
"--schema", schemaNameOrId,
"--id", id,
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return (JsonObject)ReadOutputJson(outputFileName);
}
/// <summary>
/// Finds a document in the specified GameData URL by ID.
/// https://gamedevware.github.io/charon/advanced/commands/data_find.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNameOrId">The schema name or ID of the document.</param>
/// <param name="id">The ID of the document to find.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The found document or null in case of failure.</returns>
public static async Task<JsonObject> FindDocumentAsync
(
string gameDataUrl,
string apiKey,
string schemaNameOrId,
string id,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNameOrId == null) throw new ArgumentNullException(nameof(schemaNameOrId));
if (id == null) throw new ArgumentNullException(nameof(id));
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "FIND", gameDataUrl,
"--schema", schemaNameOrId,
"--id", id,
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return (JsonObject)ReadOutputJson(outputFileName);
}
/// <summary>
/// Lists documents in the specified GameData URL.
/// https://gamedevware.github.io/charon/advanced/commands/data_list.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNameOrId">The schema name or ID of the document.</param>
/// <param name="filters">Filters for documents to list.</param>
/// <param name="sorters">Sorters for documents to list.</param>
/// <param name="path">Limit search only to embedded documents with specified path.</param>
/// <param name="skip">Number of documents to skip before writing to output.</param>
/// <param name="take">Number of documents to take after 'skip' for output.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The found documents.</returns>
public static async Task<JsonObject> ListDocumentsAsync
(
string gameDataUrl,
string apiKey,
string schemaNameOrId,
IReadOnlyList<ListFilter> filters = null,
IReadOnlyList<ListSorter> sorters = null,
string path = null,
uint? skip = null,
uint? take = null,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNameOrId == null) throw new ArgumentNullException(nameof(schemaNameOrId));
var outputFileName = CreateTemporaryFile("json");
var filtersList = new List<string>();
if (filters != null && filters.Count > 0)
{
filtersList.Add("--filters");
foreach (var listFilter in filters)
{
filtersList.Add(listFilter.PropertyName);
filtersList.Add(listFilter.GetOperationName());
filtersList.Add(listFilter.GetValueQuoted());
}
}
var sortersList = new List<string>();
if (sorters != null && sorters.Count > 0)
{
sortersList.Add("--sorters");
foreach (var listSorter in sorters)
{
sortersList.Add(listSorter.PropertyName);
sortersList.Add(listSorter.GetDirectionName());
}
}
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "LIST", gameDataUrl,
"--schema", schemaNameOrId,
filtersList,
sortersList,
string.IsNullOrEmpty(path) ? EmptyParameters : new[] { "--path", path },
skip.GetValueOrDefault() == 0 ? EmptyParameters : new[] { "--skip", skip.ToString() },
take == null ? EmptyParameters : new[] { "--take", take.ToString() },
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return (JsonObject)ReadOutputJson(outputFileName);
}
/// <summary>
/// Imports documents grouped by schema into a specified GameDataUrl file or server.
/// https://gamedevware.github.io/charon/advanced/commands/data_import.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNamesOrIds">Names or IDs of schemas to import from DocumentsBySchemaNameOrId. Can be empty or '*' to import all documents.</param>
/// <param name="documentsBySchemaNameOrId">The documents to be imported, grouped by schema name or ID.</param>
/// <param name="importMode">The mode of import operation, see ImportMode for details.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task<ImportReport> ImportAsync
(
string gameDataUrl,
string apiKey,
IReadOnlyList<string> schemaNamesOrIds,
JsonObject documentsBySchemaNameOrId,
ImportMode importMode,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNamesOrIds == null) throw new ArgumentNullException(nameof(schemaNamesOrIds));
if (documentsBySchemaNameOrId == null) throw new ArgumentNullException(nameof(documentsBySchemaNameOrId));
var inputFileName = WriteJsonInput(documentsBySchemaNameOrId);
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "IMPORT", gameDataUrl,
"--schemas", schemaNamesOrIds,
"--mode", (int)importMode,
"--input", inputFileName,
"--inputFormat", "json",
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return ReadOutputJson(outputFileName).ToObject<ImportReport>();
}
/// <summary>
/// Imports documents from a file into a specified GameDataUrl file or server.
/// https://gamedevware.github.io/charon/advanced/commands/data_import.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNamesOrIds">Names or IDs of schemas to import. Can be empty or '*' to import all documents.</param>
/// <param name="importMode">The mode of import operation, see ImportMode for details.</param>
/// <param name="documentsBySchemaNameOrIdFilePath">File path to the documents to import.</param>
/// <param name="format">The format of the imported documents ('json', 'bson', 'msgpack', 'xlsx').</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task<ImportReport> ImportFromFileAsync
(
string gameDataUrl,
string apiKey,
IReadOnlyList<string> schemaNamesOrIds,
ImportMode importMode,
string documentsBySchemaNameOrIdFilePath,
ExportFormat format = ExportFormat.Json,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNamesOrIds == null) throw new ArgumentNullException(nameof(schemaNamesOrIds));
if (documentsBySchemaNameOrIdFilePath == null) throw new ArgumentNullException(nameof(documentsBySchemaNameOrIdFilePath));
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "IMPORT", gameDataUrl,
"--schemas", schemaNamesOrIds,
"--mode", (int)importMode,
"--input", documentsBySchemaNameOrIdFilePath,
"--inputFormat", format.GetFormatName(),
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return ReadOutputJson(outputFileName).ToObject<ImportReport>();
}
/// <summary>
/// Exports documents from a GameDataUrl file or server.
/// https://gamedevware.github.io/charon/advanced/commands/data_export.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNamesOrIds">Names or IDs of schemas to export. Can be empty or '*' to export all documents.</param>
/// <param name="properties">Names, IDs, types of properties in schemas to include in the export. Can be empty or '*' to export all properties.</param>
/// <param name="languages">Language tags (BCP 47) to include in the export of localized text. Can be empty or '*' to export all languages.</param>
/// <param name="exportMode">The mode of export operation, see ExportMode for details.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The exported documents.</returns>
public static async Task<JsonObject> ExportAsync
(
string gameDataUrl,
string apiKey,
IReadOnlyList<string> schemaNamesOrIds,
IReadOnlyList<string> properties,
IReadOnlyList<string> languages,
ExportMode exportMode,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNamesOrIds == null) throw new ArgumentNullException(nameof(schemaNamesOrIds));
if (properties == null) throw new ArgumentNullException(nameof(properties));
if (languages == null) throw new ArgumentNullException(nameof(languages));
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "EXPORT", gameDataUrl,
schemaNamesOrIds.Count == 0 ? EmptyParameters : "--schemas", schemaNamesOrIds,
properties.Count == 0 ? EmptyParameters : "--properties", properties,
languages.Count == 0 ? EmptyParameters : "--languages", languages,
"--mode", (int)exportMode,
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return (JsonObject)ReadOutputJson(outputFileName);
}
/// <summary>
/// Exports documents from a GameDataUrl file or server to a file.
/// https://gamedevware.github.io/charon/advanced/commands/data_export.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNamesOrIds">Names or IDs of schemas to export. Can be empty or '*' to export all documents.</param>
/// <param name="properties">Names, IDs, types of properties in schemas to include in the export. Can be empty or '*' to export all properties.</param>
/// <param name="languages">Language tags (BCP 47) to include in the export of localized text. Can be empty or '*' to export all languages.</param>
/// <param name="exportMode">The mode of export operation, see ExportMode for details.</param>
/// <param name="exportedDocumentsFilePath">File path where the exported documents will be saved.</param>
/// <param name="format">The format in which to save the exported data ('json', 'bson', 'msgpack', 'xlsx').</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task ExportToFileAsync
(
string gameDataUrl,
string apiKey,
IReadOnlyList<string> schemaNamesOrIds,
IReadOnlyList<string> properties,
IReadOnlyList<string> languages,
ExportMode exportMode,
string exportedDocumentsFilePath,
ExportFormat format = ExportFormat.Json,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNamesOrIds == null) throw new ArgumentNullException(nameof(schemaNamesOrIds));
if (properties == null) throw new ArgumentNullException(nameof(properties));
if (languages == null) throw new ArgumentNullException(nameof(languages));
if (exportedDocumentsFilePath == null) throw new ArgumentNullException(nameof(exportedDocumentsFilePath));
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "EXPORT", gameDataUrl,
schemaNamesOrIds.Count == 0 ? EmptyParameters : "--schemas", schemaNamesOrIds,
properties.Count == 0 ? EmptyParameters : "--properties", properties,
languages.Count == 0 ? EmptyParameters : "--languages", languages,
"--mode", (int)exportMode,
"--output", exportedDocumentsFilePath,
"--outputFormat", format.GetFormatName()
),
configureTool
);
}
/// <summary>
/// Imports translated documents grouped by schema into a specified GameDataUrl file or server.
/// https://gamedevware.github.io/charon/advanced/commands/data_i18n_import.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNamesOrIds">Names or IDs of schemas to import from DocumentsBySchemaNameOrId. Can be empty or '*' to import all documents.</param>
/// <param name="languages">Language tags (BCP 47) to import into localized text. Can be empty or '*' to import all languages.</param>
/// <param name="documentsBySchemaNameOrId">The documents to be imported, grouped by schema name or ID.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task<ImportReport> I18NImportAsync
(
string gameDataUrl,
string apiKey,
IReadOnlyList<string> schemaNamesOrIds,
IReadOnlyList<string> languages,
JsonObject documentsBySchemaNameOrId,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNamesOrIds == null) throw new ArgumentNullException(nameof(schemaNamesOrIds));
if (languages == null) throw new ArgumentNullException(nameof(languages));
if (documentsBySchemaNameOrId == null) throw new ArgumentNullException(nameof(documentsBySchemaNameOrId));
var inputFileName = WriteJsonInput(documentsBySchemaNameOrId);
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "I18N", "IMPORT", gameDataUrl,
"--schemas", schemaNamesOrIds,
languages.Count == 0 ? EmptyParameters : "--languages", languages,
"--input", inputFileName,
"--inputFormat", "json",
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return ReadOutputJson(outputFileName).ToObject<ImportReport>();
}
/// <summary>
/// Imports documents from a file into a specified GameDataUrl file or server.
/// https://gamedevware.github.io/charon/advanced/commands/data_i18n_import.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNamesOrIds">Names or IDs of schemas to import. Can be empty or '*' to import all documents.</param>
/// <param name="languages">Language tags (BCP 47) to import into localized text. Can be empty or '*' to import all languages.</param>
/// <param name="documentsBySchemaNameOrIdFilePath">File path to the documents to import.</param>
/// <param name="format">The format of the imported documents ('xliff', 'xliff2', 'xliff1', 'xlsx', 'json').</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task<ImportReport> I18NImportFromFileAsync
(
string gameDataUrl,
string apiKey,
IReadOnlyList<string> schemaNamesOrIds,
IReadOnlyList<string> languages,
string documentsBySchemaNameOrIdFilePath,
ExportFormat format = ExportFormat.Json,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNamesOrIds == null) throw new ArgumentNullException(nameof(schemaNamesOrIds));
if (languages == null) throw new ArgumentNullException(nameof(languages));
if (documentsBySchemaNameOrIdFilePath == null) throw new ArgumentNullException(nameof(documentsBySchemaNameOrIdFilePath));
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "I18N", "IMPORT", gameDataUrl,
"--schemas", schemaNamesOrIds,
languages.Count == 0 ? EmptyParameters : "--languages", languages,
"--input", documentsBySchemaNameOrIdFilePath,
"--inputFormat", format.GetFormatName(),
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return ReadOutputJson(outputFileName).ToObject<ImportReport>();
}
/// <summary>
/// Exports documents from a GameDataUrl file or server.
/// https://gamedevware.github.io/charon/advanced/commands/data_i18n_export.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNamesOrIds">Names or IDs of schemas to export. Can be empty or '*' to export all documents.</param>
/// <param name="sourceLanguage">Language tag (BCP 47) to include in the export as source of translation.</param>
/// <param name="targetLanguage">Language tag (BCP 47) to include in the export as target of translation.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The exported documents.</returns>
public static async Task<JsonObject> I18NExportAsync
(
string gameDataUrl,
string apiKey,
IReadOnlyList<string> schemaNamesOrIds,
string sourceLanguage,
string targetLanguage,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNamesOrIds == null) throw new ArgumentNullException(nameof(schemaNamesOrIds));
if (sourceLanguage == null) throw new ArgumentNullException(nameof(sourceLanguage));
if (targetLanguage == null) throw new ArgumentNullException(nameof(targetLanguage));
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "I18N", "EXPORT", gameDataUrl,
schemaNamesOrIds.Count == 0 ? EmptyParameters : "--schemas", schemaNamesOrIds,
"--sourceLanguage", sourceLanguage,
"--targetLanguage", targetLanguage,
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return (JsonObject)ReadOutputJson(outputFileName);
}
/// <summary>
/// Exports documents from a GameDataUrl file or server to a file.
/// https://gamedevware.github.io/charon/advanced/commands/data_i18n_export.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="schemaNamesOrIds">Names or IDs of schemas to export. Can be empty or '*' to export all documents.</param>
/// <param name="sourceLanguage">Language tag (BCP 47) to include in the export as source of translation.</param>
/// <param name="targetLanguage">Language tag (BCP 47) to include in the export as target of translation.</param>
/// <param name="exportedDocumentsFilePath">File path where the exported documents will be saved.</param>
/// <param name="format">The format in which to save the exported data ('xliff', 'xliff2', 'xliff1', 'xlsx', 'json').</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task I18NExportToFileAsync
(
string gameDataUrl,
string apiKey,
IReadOnlyList<string> schemaNamesOrIds,
string sourceLanguage,
string targetLanguage,
string exportedDocumentsFilePath,
ExportFormat format = ExportFormat.Json,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (schemaNamesOrIds == null) throw new ArgumentNullException(nameof(schemaNamesOrIds));
if (sourceLanguage == null) throw new ArgumentNullException(nameof(sourceLanguage));
if (targetLanguage == null) throw new ArgumentNullException(nameof(targetLanguage));
if (exportedDocumentsFilePath == null) throw new ArgumentNullException(nameof(exportedDocumentsFilePath));
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "I18N", "EXPORT", gameDataUrl,
schemaNamesOrIds.Count == 0 ? EmptyParameters : "--schemas", schemaNamesOrIds,
"--sourceLanguage", sourceLanguage,
"--targetLanguage", targetLanguage,
"--output", exportedDocumentsFilePath,
"--outputFormat", format.GetFormatName()
),
configureTool
);
}
/// <summary>
/// Add translation language to a GameDataUrl file or server.
/// https://gamedevware.github.io/charon/advanced/commands/data_i18n_add_language.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="languages">Language tags (BCP 47) to add in project's translation language list.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task I18NAddLanguageAsync
(
string gameDataUrl,
string apiKey,
string[] languages,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (languages == null) throw new ArgumentNullException(nameof(languages));
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "I18N", "ADDLANGUAGE", gameDataUrl,
"--languages", languages
),
configureTool
);
}
/// <summary>
/// List translation languages in a GameDataUrl file or server.
/// https://gamedevware.github.io/charon/advanced/commands/data_i18n_languages.html
/// </summary>
/// <param name="gameDataUrl">The URL of the GameData file or server.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task<string[]> I18NListLanguagesAsync
(
string gameDataUrl,
string apiKey,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
var outputFileName = CreateTemporaryFile("text");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "I18N", "LANGUAGES", gameDataUrl,
"--output", outputFileName,
"--outputFormat", "list"
),
configureTool
);
return (await File.ReadAllTextAsync(outputFileName)).Split(" ", StringSplitOptions.RemoveEmptyEntries);
}
/// <summary>
/// Compares all documents in two GameData URLs and creates a patch representing the difference.
/// https://gamedevware.github.io/charon/advanced/commands/data_create_patch.html
/// </summary>
/// <param name="gameDataUrl1">The first GameData URL for comparison.</param>
/// <param name="gameDataUrl2">The second GameData URL for comparison.</param>
/// <param name="apiKey">Authentication credentials if the GameData URLs are servers, otherwise empty.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The patch data.</returns>
public static async Task<JsonObject> CreatePatchAsync
(
string gameDataUrl1,
string gameDataUrl2,
string apiKey,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl1 == null) throw new ArgumentNullException(nameof(gameDataUrl1));
if (gameDataUrl2 == null) throw new ArgumentNullException(nameof(gameDataUrl2));
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
arguments: ToolRunOptions.FlattenArguments(
"DATA", "CREATEPATCH", gameDataUrl1, gameDataUrl2,
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return (JsonObject)ReadOutputJson(outputFileName);
}
/// <summary>
/// Compares all documents in two GameData URLs and creates a patch representing the difference.
/// https://gamedevware.github.io/charon/advanced/commands/data_create_patch.html
/// </summary>
/// <param name="gameDataUrl1">The first GameData URL for comparison.</param>
/// <param name="gameDataUrl2">The second GameData URL for comparison.</param>
/// <param name="apiKey">Authentication credentials if the GameData URLs are servers, otherwise empty.</param>
/// <param name="exportedDocumentsFilePath">File path where the path will be saved.</param>
/// <param name="format">The format in which to save the patch ('json', 'msgpack').</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The patch data.</returns>
public static async Task CreatePatchToFileAsync
(
string gameDataUrl1,
string gameDataUrl2,
string apiKey,
string exportedDocumentsFilePath,
BackupFormat format = BackupFormat.Json,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl1 == null) throw new ArgumentNullException(nameof(gameDataUrl1));
if (gameDataUrl2 == null) throw new ArgumentNullException(nameof(gameDataUrl2));
if (exportedDocumentsFilePath == null) throw new ArgumentNullException(nameof(exportedDocumentsFilePath));
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
arguments: ToolRunOptions.FlattenArguments(
"DATA", "CREATEPATCH", gameDataUrl1, gameDataUrl2,
"--output", exportedDocumentsFilePath,
"--outputFormat", format.GetFormatName()
),
configureTool
);
}
/// <summary>
/// Applies a patch created by CreatePatch to a specified GameData URL.
/// https://gamedevware.github.io/charon/advanced/commands/data_apply_patch.html
/// </summary>
/// <param name="gameDataUrl">The GameData URL to apply the patch to.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="gameDataPatch">The patch document created by CreatePatch.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task ApplyPatchAsync
(
string gameDataUrl,
string apiKey,
JsonObject gameDataPatch,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (gameDataPatch == null) throw new ArgumentNullException(nameof(gameDataPatch));
var inputFileName = WriteJsonInput(gameDataPatch);
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "APPLYPATCH", gameDataUrl,
"--input", inputFileName,
"--inputFormat", "json"
),
configureTool
);
}
/// <summary>
/// Applies a patch created by CreatePatch to a specified GameData URL.
/// https://gamedevware.github.io/charon/advanced/commands/data_apply_patch.html
/// </summary>
/// <param name="gameDataUrl">The GameData URL to apply the patch to.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="gameDataPatchFilePath">The patch file created by CreatePatch.</param>
/// <param name="format">The format of the imported patch ('json', 'msgpack' or 'auto').</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task ApplyPatchFromFileAsync
(
string gameDataUrl,
string apiKey,
string gameDataPatchFilePath,
BackupFormat format = BackupFormat.Json,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (gameDataPatchFilePath == null) throw new ArgumentNullException(nameof(gameDataPatchFilePath));
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "APPLYPATCH", gameDataUrl,
"--input", gameDataPatchFilePath,
"--inputFormat", format.GetFormatName()
),
configureTool
);
}
/// <summary>
/// Backups game data with all documents and their metadata.
/// https://gamedevware.github.io/charon/advanced/commands/data_backup.html
/// </summary>
/// <param name="gameDataUrl">The GameData URL to backup.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The backup data.</returns>
public static async Task<JsonObject> BackupAsync
(
string gameDataUrl,
string apiKey,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "Backup", gameDataUrl,
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return (JsonObject)ReadOutputJson(outputFileName);
}
/// <summary>
/// Backups game data to a file with all documents and their metadata.
/// https://gamedevware.github.io/charon/advanced/commands/data_backup.html
/// </summary>
/// <param name="gameDataUrl">The GameData URL to backup.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="gameDataFilePath">File path where the backup will be saved.</param>
/// <param name="format">The format for saving data ('json', 'msgpack').</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task BackupToFileAsync
(
string gameDataUrl,
string apiKey,
string gameDataFilePath,
BackupFormat format = BackupFormat.Json,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (gameDataFilePath == null) throw new ArgumentNullException(nameof(gameDataFilePath));
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "Backup", gameDataUrl,
"--output", gameDataFilePath,
"--outputFormat", format.GetFormatName()
),
configureTool
);
}
/// <summary>
/// Restores game data with all documents and their metadata.
/// https://gamedevware.github.io/charon/advanced/commands/data_restore.html
/// </summary>
/// <param name="gameDataUrl">The GameData URL to restore.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="gameData">Previously backed up data.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task RestoreAsync
(
string gameDataUrl,
string apiKey,
JsonObject gameData,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (gameData == null) throw new ArgumentNullException(nameof(gameData));
var inputFileName = WriteJsonInput(gameData);
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "RESTORE", gameDataUrl,
"--input", inputFileName,
"--inputFormat", "json"
),
configureTool
);
}
/// <summary>
/// Restores game data from a file with all documents and their metadata.
/// https://gamedevware.github.io/charon/advanced/commands/data_restore.html
/// </summary>
/// <param name="gameDataUrl">The GameData URL to restore.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="gameDataFilePath">File path with previously backed up data.</param>
/// <param name="format">The format for the backed up data ('json', 'msgpack').</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task RestoreFromFileAsync
(
string gameDataUrl,
string apiKey,
string gameDataFilePath,
BackupFormat format = BackupFormat.Json,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (gameDataFilePath == null) throw new ArgumentNullException(nameof(gameDataFilePath));
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "RESTORE", gameDataUrl,
"--input", gameDataFilePath,
"--inputFormat", format.GetFormatName()
),
configureTool
);
}
/// <summary>
/// Checks all documents in the specified GameData URL and returns a report with any issues.
/// https://gamedevware.github.io/charon/advanced/commands/data_validate.html
/// </summary>
/// <param name="gameDataUrl">The GameData URL to validate.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="validationOptions">A list of checks to perform during validation, see ValidationOption for details.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The report of issues.</returns>
public static async Task<ValidationReport> ValidateAsync
(
string gameDataUrl,
string apiKey,
ValidationOptions validationOptions,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
var outputFileName = CreateTemporaryFile("json");
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments(
"DATA", "VALIDATE", gameDataUrl,
"--validationOptions", ((int)validationOptions).ToString(),
"--output", outputFileName,
"--outputFormat", "json"
),
configureTool
);
return ReadOutputJson(outputFileName).ToObject<ValidationReport>();
}
/// <summary>
/// Generates C# source code for loading game data from a GameDataUrl into a game's runtime.
/// https://gamedevware.github.io/charon/advanced/commands/generate_csharp_code.html
/// </summary>
/// <param name="gameDataUrl">The GameData URL from which to generate source code.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="outputDirectory">Directory to place generated files, preferably empty.</param>
/// <param name="documentClassName">Name for the base class for all documents.</param>
/// <param name="gameDataClassName">Name for the main class from which all documents are accessible.</param>
/// <param name="gameDataNamespace">Namespace for generated code.</param>
/// <param name="defineConstants">Additional defines for all generated files.</param>
/// <param name="sourceCodeGenerationOptimizations">List of enabled optimizations in the generated code, see SourceCodeGenerationOptimizations for details.</param>
/// <param name="sourceCodeIndentation">Indentation style for the generated code.</param>
/// <param name="sourceCodeLineEndings">Line endings for the generated code.</param>
/// <param name="clearOutputDirectory">Whether to clear the output directory from generated code before generating files.</param>
/// <param name="splitFiles">Split code into multiple files instead of keeping one huge file.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task GenerateCSharpCodeAsync
(
string gameDataUrl,
string apiKey,
string outputDirectory,
string documentClassName = "Document",
string gameDataClassName = "GameData",
string gameDataNamespace = "GameParameters",
string defineConstants = null,
SourceCodeGenerationOptimizations sourceCodeGenerationOptimizations = default,
SourceCodeIndentation sourceCodeIndentation = SourceCodeIndentation.Tabs,
SourceCodeLineEndings sourceCodeLineEndings = SourceCodeLineEndings.OsDefault,
bool clearOutputDirectory = true,
bool splitFiles = false,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
if (outputDirectory == null) throw new ArgumentNullException(nameof(outputDirectory));
if (documentClassName == null) throw new ArgumentNullException(nameof(documentClassName));
if (gameDataClassName == null) throw new ArgumentNullException(nameof(gameDataClassName));
if (gameDataNamespace == null) throw new ArgumentNullException(nameof(gameDataNamespace));
sourceCodeGenerationOptimizations |= SourceCodeGenerationOptimizations.DisableFormulaCompilation;
if (sourceCodeLineEndings == SourceCodeLineEndings.OsDefault)
{
sourceCodeLineEndings = SystemInfo.operatingSystemFamily == OperatingSystemFamily.Windows ?
SourceCodeLineEndings.Windows : SourceCodeLineEndings.Unix;
}
var optimizationsList = new List<string>();
foreach (SourceCodeGenerationOptimizations optimization in Enum.GetValues(typeof(SourceCodeGenerationOptimizations)))
{
if ((sourceCodeGenerationOptimizations & optimization) != 0)
{
optimizationsList.Add(optimization.ToString());
}
}
if (optimizationsList.Count > 0)
{
optimizationsList.Insert(0, "--optimizations");
}
using var _ = await RunCharonAsync
(
apiKey, logsVerbosity,
ToolRunOptions.FlattenArguments
(
"GENERATE", "CSHARPCODE", gameDataUrl,
"--outputDirectory", outputDirectory,
"--documentClassName", documentClassName,
"--gameDataClassName", gameDataClassName,
"--namespace", gameDataNamespace,
string.IsNullOrEmpty(defineConstants) ? EmptyParameters : new[] { "--defineConstants", defineConstants },
clearOutputDirectory ? "--clearOutputDirectory" : null,
"--indentation", sourceCodeIndentation.ToString(),
"--lineEndings", sourceCodeLineEndings.ToString(),
optimizationsList,
splitFiles ? "--splitFiles" : null
),
configureTool
);
}
/// <summary>
/// Dumps T4 code generation templates used to generate source code into a specified directory.
/// https://gamedevware.github.io/charon/advanced/commands/generate_templates.html
/// </summary>
/// <param name="outputDirectory">The directory where the templates will be dumped.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
public static async Task DumpTemplatesAsync(string outputDirectory, Action<ToolRunOptions> configureTool = null)
{
if (outputDirectory == null) throw new ArgumentNullException(nameof(outputDirectory));
using var _ = await RunCharonAsync
(
apiKey: string.Empty, CharonLogLevel.Normal,
arguments: ToolRunOptions.FlattenArguments
(
"GENERATE", "TEMPLATES",
"--outputDirectory", outputDirectory
),
configureTool
);
}
/// <summary>
/// Gets the version number of the charon tool executable.
/// https://gamedevware.github.io/charon/advanced/commands/version.html
/// </summary>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The version number as a string.</returns>
public static async Task<string> GetVersionAsync(Action<ToolRunOptions> configureTool = null)
{
using var runResult = await RunCharonAsync(
apiKey: string.Empty, CharonLogLevel.None,
arguments: ToolRunOptions.FlattenArguments
(
"VERSION"
),
configureTool
);
var versionString = runResult.GetOutputData();
return string.IsNullOrEmpty(versionString) ? "0.0.0.0" : versionString;
}
/// <summary>
/// Gets the version of the charon tool executable used to create the specified GameData URL.
/// </summary>
/// <param name="gameDataUrl">The GameData URL to check.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is a server, otherwise empty.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The version number as a <see cref="Version"/>.</returns>
public static async Task<Version> GetGameDataToolVersionAsync
(
string gameDataUrl,
string apiKey,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (gameDataUrl == null) throw new ArgumentNullException(nameof(gameDataUrl));
using var runResult = await RunCharonAsync(
apiKey: apiKey, logsVerbosity,
arguments: ToolRunOptions.FlattenArguments
(
"DATA", "VERSION", gameDataUrl
),
configureTool
);
return new Version(runResult.GetOutputData());
}
/// <summary>
/// Run specified command with charon tool.
/// https://gamedevware.github.io/charon/advanced/command_line.html
/// Example:
/// <code>
/// var runResult = await CharonCli.RunAsync
/// (
/// new[] { "DATA", "BACKUP", "--dataBase", "/var/gamedata.json", "--output", "/var/gamedata_BACKUP.bson"},
/// logsVerbosity: CharonLogLevel.Verbose
/// );
/// // runResult.ExitCode == 0 -> success
/// </code>
/// </summary>
/// <param name="commandsAndOptions">List of commands and options to pass to charon tool.</param>
/// <param name="apiKey">Authentication credentials if GameDataUrl is used, and it is a server, otherwise empty.</param>
/// <param name="logsVerbosity">The verbosity level of logs. Defaults to CharonLogLevel.Normal.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>The version number as a <see cref="Version"/>.</returns>
public static Task<ToolRunResult> RunCharonAsync
(
string[] commandsAndOptions,
string apiKey,
CharonLogLevel? logsVerbosity = null,
Action<ToolRunOptions> configureTool = null
)
{
if (commandsAndOptions == null) throw new ArgumentNullException(nameof(commandsAndOptions));
return RunCharonAsync
(
apiKey: apiKey, logsVerbosity,
arguments: commandsAndOptions,
configureTool
);
}
/// <summary>
/// Run dotnet-t4 command-line tool for processing T4 templates. It is a general-purpose way to generate text or code files using C#.
/// https://github.com/mono/t4/blob/main/dotnet-t4/readme.md
/// </summary>
/// <param name="templateFile">The path of the template .tt file.</param>
/// <param name="referencedAssemblies">An assembly reference by path or assembly name. It will be resolved from the framework and assembly directories.</param>
/// <param name="usings">A namespace imports which generate a using statement in template source code.</param>
/// <param name="includeDirectories">A directory to be searched when resolving included files.</param>
/// <param name="assemblyLookupDirectories">A directory to be searched when resolving assemblies.</param>
/// <param name="parameters">Set session parameter <see cref="KeyValuePair{TKey,TValue}.Key"/> to <see cref="KeyValuePair{TKey,TValue}.Value"/>.
/// The value is accessed from the template's Session dictionary, or from a property declared with a parameter directive: <#@ parameter name='[name]' type='[type]' #>.
/// If the name matches a parameter with a non-string type, the value will be converted to that type.
/// </param>
/// <param name="useRelativeLinePragmas">Use relative paths in line pragmas.</param>
/// <param name="debugMode">Generate debug symbols and keep temporary files.</param>
/// <param name="verboseLogs">Output additional diagnostic information to stdout.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>Instance of running tool process. Check <see cref="ToolRunResult.ExitCode"/> for 0 to assess results.</returns>
// ReSharper disable once FunctionComplexityOverflow
public static Task<ToolRunResult> RunT4Async
(
string templateFile,
IEnumerable<string> referencedAssemblies = null,
IEnumerable<string> usings = null,
IEnumerable<string> includeDirectories = null,
IEnumerable<string> assemblyLookupDirectories = null,
IEnumerable<KeyValuePair<string, string>> parameters = null,
bool useRelativeLinePragmas = false,
bool debugMode = false,
bool verboseLogs = false,
Action<ToolRunOptions> configureTool = null
)
{
if (templateFile == null) throw new ArgumentNullException(nameof(templateFile));
var t4Path = EnsureCharonRunScript("RunT4");
var arguments = new List<string>();
foreach (var referencedAssembly in referencedAssemblies ?? Array.Empty<string>())
{
arguments.Add("-r=" + referencedAssembly);
}
foreach (var usingStatement in usings ?? Array.Empty<string>())
{
arguments.Add("-u=" + usingStatement);
}
foreach (var includeDirectory in includeDirectories ?? Array.Empty<string>())
{
arguments.Add("-I=" + includeDirectory);
}
foreach (var assemblyLookupDirectory in assemblyLookupDirectories ?? Array.Empty<string>())
{
arguments.Add("-P=" + assemblyLookupDirectory);
}
foreach (var parameter in parameters ?? Array.Empty<KeyValuePair<string, string>>())
{
arguments.Add($"-p={parameter.Key}={parameter.Value}");
}
if (useRelativeLinePragmas)
{
arguments.Add("-l");
}
if (debugMode)
{
arguments.Add("--debug");
}
if (verboseLogs)
{
arguments.Add("--verbose");
}
arguments.Add(templateFile);
var runOptions = new ToolRunOptions(t4Path, arguments.ToArray()) {
CaptureStandardOutput = true,
CaptureStandardError = true,
ExecutionTimeout = TimeSpan.FromSeconds(30),
WaitForExit = true
};
configureTool?.Invoke(runOptions);
return CommandLineUtils.RunAsync(runOptions);
}
/// <summary>
/// Run dotnet-t4 command-line tool for processing T4 templates. It is a general-purpose way to generate text or code files using C#.
/// https://github.com/mono/t4/blob/main/dotnet-t4/readme.md
/// </summary>
/// <param name="templateFile">The path of the template .tt file.</param>
/// <param name="outputFile">The name or path of the output file. It defaults to the input filename with its extension changed to .txt, or to match the generated code when preprocessing, and may be overridden by template settings. Use - instead of a filename to write to stdout.</param>
/// <param name="usings">A namespace imports which generate a using statement in template source code.</param>
/// <param name="templateClassName">Preprocess the template into class name for use as a runtime template. The class name may include a namespace.</param>
/// <param name="useRelativeLinePragmas">Use relative paths in line pragmas.</param>
/// <param name="debugMode">Generate debug symbols and keep temporary files.</param>
/// <param name="verboseLogs">Output additional diagnostic information to stdout.</param>
/// <param name="configureTool">Optional configuration delegate for tool process.</param>
/// <returns>Instance of running tool process. Check <see cref="ToolRunResult.ExitCode"/> for 0 to assess results.</returns>
// ReSharper disable once FunctionComplexityOverflow
public static Task<ToolRunResult> PreprocessT4Async
(
string templateFile,
string outputFile,
string templateClassName,
IEnumerable<string> usings = null,
bool useRelativeLinePragmas = false,
bool debugMode = false,
bool verboseLogs = false,
Action<ToolRunOptions> configureTool = null
)
{
if (templateFile == null) throw new ArgumentNullException(nameof(templateFile));
var t4Path = EnsureCharonRunScript("RunT4");
var arguments = new List<string>();
if (!string.IsNullOrEmpty(outputFile))
{
arguments.Add("--out=" + outputFile);
}
foreach (var usingStatement in usings ?? Array.Empty<string>())
{
arguments.Add("-u=" + usingStatement);
}
if (!string.IsNullOrEmpty(templateClassName))
{
arguments.Add("-c=" + templateClassName);
}
if (useRelativeLinePragmas)
{
arguments.Add("-l");
}
if (debugMode)
{
arguments.Add("--debug");
}
if (verboseLogs)
{
arguments.Add("--verbose");
}
arguments.Add(templateFile);
var runOptions = new ToolRunOptions(t4Path, arguments.ToArray()) {
CaptureStandardOutput = true,
CaptureStandardError = true,
ExecutionTimeout = TimeSpan.FromSeconds(30),
WaitForExit = true
};
configureTool?.Invoke(runOptions);
return CommandLineUtils.RunAsync(runOptions);
}
internal static void CleanUpLogsDirectory()
{
if (string.IsNullOrEmpty(CharonFileUtils.LibraryCharonLogsPath) || Directory.Exists(CharonFileUtils.LibraryCharonLogsPath) == false)
{
return;
}
var logger = CharonEditorModule.Instance.Logger;
var logsRetentionTime = TimeSpan.FromDays(2);
foreach (var logFile in Directory.GetFiles(CharonFileUtils.LibraryCharonLogsPath))
{
if (DateTime.UtcNow - File.GetLastWriteTimeUtc(logFile) <= logsRetentionTime)
{
continue; // not old enough
}
try
{
logger.Log(LogType.Assert, $"Deleting old log file at '{logFile}'.");
File.Delete(logFile);
}
catch (Exception deleteError)
{
logger.Log(LogType.Warning, $"Failed to delete log file at '{logFile}'.");
logger.Log(LogType.Warning, deleteError);
}
}
}
private static async Task<ToolRunResult> RunCharonAsync(string apiKey, CharonLogLevel? logsVerbosity, string[] arguments, Action<ToolRunOptions> configureTool)
{
if (arguments == null) throw new ArgumentNullException(nameof(arguments));
var charonPath = EnsureCharonRunScript("RunCharon");
logsVerbosity ??= CharonEditorModule.Instance.Settings.LogLevel;
arguments = arguments.Concat(new[] { logsVerbosity == CharonLogLevel.Verbose ? "--verbose" : "" }).ToArray();
var runOptions = new ToolRunOptions(charonPath, arguments) {
CaptureStandardOutput = true,
CaptureStandardError = true,
ExecutionTimeout = TimeSpan.FromSeconds(30),
WaitForExit = true,
StartInfo = {
EnvironmentVariables = {
{ "DOTNET_CONTENTROOT", CharonFileUtils.CharonAppContentPath },
{ "CHARON_API_KEY", apiKey ?? string.Empty },
{ "STANDALONE__GAMEASSETSPATH", Path.GetFullPath("./") },
{ "SERILOG__WRITETO__0__NAME", "File" }, {
"SERILOG__WRITETO__0__ARGS__PATH", Path.GetFullPath(Path.Combine(CharonFileUtils.LibraryCharonLogsPath,
$"{DateTime.UtcNow:yyyy_MM_dd_hh}.charon.unity.log"))
},
}
}
};
configureTool?.Invoke(runOptions);
var runResult = await CommandLineUtils.RunAsync(runOptions);
if (runResult.ExitCode != 0)
{
throw new InvalidOperationException((runResult.GetErrorData() ??
"An error occurred.") +
$" Process exit code: {runResult.ExitCode}.");
}
return runResult;
}
private static string WriteJsonInput(JsonValue jsonValue, [CallerMemberName] string memberName = "Command")
{
var tempFilePath = CreateTemporaryFile("json", memberName);
using var fileStream = File.Create(tempFilePath);
using var textWriter = new StreamWriter(fileStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), 4096, leaveOpen: true);
#if JSON_NET_3_0_2_OR_NEWER
using var jsonWriter = new JsonTextWriter(textWriter);
jsonWriter.CloseOutput = false;
jsonWriter.Formatting = Formatting.Indented;
jsonValue.WriteTo(jsonWriter);
#else
jsonValue.Save(textWriter, pretty: true);
#endif
return tempFilePath;
}
private static JsonValue ReadOutputJson(string filePath)
{
using var textReader = new StreamReader(filePath, Encoding.UTF8, detectEncodingFromByteOrderMarks: false);
#if JSON_NET_3_0_2_OR_NEWER
using var jsonReader = new JsonTextReader(textReader);
jsonReader.CloseInput = false;
return JsonValue.ReadFrom(jsonReader);
#else
return JsonValue.Load(textReader);
#endif
}
private static string CreateTemporaryFile(string extension, [CallerMemberName] string memberName = "Command")
{
var tempFileName = Path.GetFullPath(Path.Combine(Path.Combine(CharonFileUtils.TempPath, "charoncli"),
memberName + "_" + Guid.NewGuid().ToString().Replace("-", "") + "." + extension));
if (!Directory.Exists(Path.GetDirectoryName(tempFileName)))
{
Directory.CreateDirectory(Path.GetDirectoryName(tempFileName)!);
}
return tempFileName;
}
private static string EnsureCharonRunScript(string scriptName)
{
if (scriptName == null) throw new ArgumentNullException(nameof(scriptName));
if (!ScriptFilesAreCopied)
{
CopyScriptFiles(scriptName);
ScriptFilesAreCopied = true;
}
foreach (var scriptFilePath in Directory.GetFiles(CharonFileUtils.LibraryCharonPath))
{
if (string.Equals(Path.GetFileNameWithoutExtension(Path.GetFileName(scriptFilePath)), scriptName, StringComparison.OrdinalIgnoreCase))
{
return scriptFilePath;
}
}
throw new InvalidOperationException($"Unable to find '{scriptName}' script in '{CharonFileUtils.LibraryCharonPath}' directory.");
}
private static void CopyScriptFiles(string scriptName)
{
var oldExtension = "windows";
var newExtension = default(string);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
oldExtension = "windows";
newExtension = "bat";
}
else
{
oldExtension = "unix";
newExtension = "sh";
}
foreach (var sourceFilePath in Directory.GetFiles(Path.Combine(CharonFileUtils.PluginBasePath, "Scripts"), "*." + oldExtension))
{
var targetFilePath = Path.Combine(CharonFileUtils.LibraryCharonPath, Path.ChangeExtension(Path.GetFileName(sourceFilePath), newExtension));
var targetDirectoryPath = Path.GetDirectoryName(targetFilePath) ?? "";
if (CharonFileUtils.HasSameContent(sourceFilePath, targetFilePath))
{
continue;
}
if (File.Exists(targetFilePath))
{
try { File.Delete(targetFilePath); }
catch { continue; /* skip busy file */ }
}
if (!Directory.Exists(targetDirectoryPath))
{
Directory.CreateDirectory(targetDirectoryPath);
}
File.Copy(sourceFilePath, targetFilePath);
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Chmod(targetFilePath, "+x", deleteFileOnFail: true);
}
}
}
private static void Chmod(string filePath, string permissions, bool deleteFileOnFail)
{
try
{
var processStartInfo = new ProcessStartInfo
{
FileName = "chmod",
Arguments = $"\"{permissions}\" \"{filePath}\"",
UseShellExecute = true,
CreateNoWindow = true,
};
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
using var process = Process.Start(processStartInfo)!;
timeout.Token.Register(process.EndGracefully);
process.WaitForExit();
}
catch
{
CharonFileUtils.SafeFileDelete(filePath); // delete file because it doesn't have proper permissions
throw;
}
}
}
}
| 0 | 0.933803 | 1 | 0.933803 | game-dev | MEDIA | 0.408199 | game-dev | 0.906796 | 1 | 0.906796 |
ecilasun/tinysys | 18,551 | software/samples/doom/src/p_pspr.c | // Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// $Id:$
//
// Copyright (C) 1993-1996 by id Software, Inc.
//
// 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.
//
// $Log:$
//
// DESCRIPTION:
// Weapon sprite animation, weapon objects.
// Action functions for weapons.
//
//-----------------------------------------------------------------------------
static const char __attribute__((unused))
rcsid[] = "$Id: p_pspr.c,v 1.5 1997/02/03 22:45:12 b1 Exp $";
#include "doomdef.h"
#include "d_event.h"
#include "m_random.h"
#include "p_local.h"
#include "s_sound.h"
// State.
#include "doomstat.h"
// Data.
#include "sounds.h"
#include "p_pspr.h"
#define LOWERSPEED FRACUNIT*6
#define RAISESPEED FRACUNIT*6
#define WEAPONBOTTOM 128*FRACUNIT
#define WEAPONTOP 32*FRACUNIT
// plasma cells for a bfg attack
#define BFGCELLS 40
//
// P_SetPsprite
//
void
P_SetPsprite
( player_t* player,
int position,
statenum_t stnum )
{
pspdef_t* psp;
state_t* state;
psp = &player->psprites[position];
do
{
if (!stnum)
{
// object removed itself
psp->state = NULL;
break;
}
state = &states[stnum];
psp->state = state;
psp->tics = state->tics; // could be 0
if (state->misc1)
{
// coordinate set
psp->sx = state->misc1 << FRACBITS;
psp->sy = state->misc2 << FRACBITS;
}
// Call action routine.
// Modified handling.
if (state->action.acp2)
{
state->action.acp2(player, psp);
if (!psp->state)
break;
}
stnum = psp->state->nextstate;
} while (!psp->tics);
// an initial state of 0 could cycle through
}
//
// P_CalcSwing
//
fixed_t swingx;
fixed_t swingy;
void P_CalcSwing (player_t* player)
{
fixed_t swing;
int angle;
// OPTIMIZE: tablify this.
// A LUT would allow for different modes,
// and add flexibility.
swing = player->bob;
angle = (FINEANGLES/70*leveltime)&FINEMASK;
swingx = FixedMul ( swing, finesine[angle]);
angle = (FINEANGLES/70*leveltime+FINEANGLES/2)&FINEMASK;
swingy = -FixedMul ( swingx, finesine[angle]);
}
//
// P_BringUpWeapon
// Starts bringing the pending weapon up
// from the bottom of the screen.
// Uses player
//
void P_BringUpWeapon (player_t* player)
{
statenum_t newstate;
if (player->pendingweapon == wp_nochange)
player->pendingweapon = player->readyweapon;
if (player->pendingweapon == wp_chainsaw)
S_StartSound (player->mo, sfx_sawup);
newstate = weaponinfo[player->pendingweapon].upstate;
player->pendingweapon = wp_nochange;
player->psprites[ps_weapon].sy = WEAPONBOTTOM;
P_SetPsprite (player, ps_weapon, newstate);
}
//
// P_CheckAmmo
// Returns true if there is enough ammo to shoot.
// If not, selects the next weapon to use.
//
boolean P_CheckAmmo (player_t* player)
{
ammotype_t ammo;
int count;
ammo = weaponinfo[player->readyweapon].ammo;
// Minimal amount for one shot varies.
if (player->readyweapon == wp_bfg)
count = BFGCELLS;
else if (player->readyweapon == wp_supershotgun)
count = 2; // Double barrel.
else
count = 1; // Regular.
// Some do not need ammunition anyway.
// Return if current ammunition sufficient.
if (ammo == am_noammo || player->ammo[ammo] >= count)
return true;
// Out of ammo, pick a weapon to change to.
// Preferences are set here.
do
{
if (player->weaponowned[wp_plasma]
&& player->ammo[am_cell]
&& (gamemode != shareware) )
{
player->pendingweapon = wp_plasma;
}
else if (player->weaponowned[wp_supershotgun]
&& player->ammo[am_shell]>2
&& (gamemode == commercial) )
{
player->pendingweapon = wp_supershotgun;
}
else if (player->weaponowned[wp_chaingun]
&& player->ammo[am_clip])
{
player->pendingweapon = wp_chaingun;
}
else if (player->weaponowned[wp_shotgun]
&& player->ammo[am_shell])
{
player->pendingweapon = wp_shotgun;
}
else if (player->ammo[am_clip])
{
player->pendingweapon = wp_pistol;
}
else if (player->weaponowned[wp_chainsaw])
{
player->pendingweapon = wp_chainsaw;
}
else if (player->weaponowned[wp_missile]
&& player->ammo[am_misl])
{
player->pendingweapon = wp_missile;
}
else if (player->weaponowned[wp_bfg]
&& player->ammo[am_cell]>40
&& (gamemode != shareware) )
{
player->pendingweapon = wp_bfg;
}
else
{
// If everything fails.
player->pendingweapon = wp_fist;
}
} while (player->pendingweapon == wp_nochange);
// Now set appropriate weapon overlay.
P_SetPsprite (player,
ps_weapon,
weaponinfo[player->readyweapon].downstate);
return false;
}
//
// P_FireWeapon.
//
void P_FireWeapon (player_t* player)
{
statenum_t newstate;
if (!P_CheckAmmo (player))
return;
P_SetMobjState (player->mo, S_PLAY_ATK1);
newstate = weaponinfo[player->readyweapon].atkstate;
P_SetPsprite (player, ps_weapon, newstate);
P_NoiseAlert (player->mo, player->mo);
}
//
// P_DropWeapon
// Player died, so put the weapon away.
//
void P_DropWeapon (player_t* player)
{
P_SetPsprite (player,
ps_weapon,
weaponinfo[player->readyweapon].downstate);
}
//
// A_WeaponReady
// The player can fire the weapon
// or change to another weapon at this time.
// Follows after getting weapon up,
// or after previous attack/fire sequence.
//
void
A_WeaponReady
( player_t* player,
pspdef_t* psp )
{
statenum_t newstate;
int angle;
// get out of attack state
if (player->mo->state == &states[S_PLAY_ATK1]
|| player->mo->state == &states[S_PLAY_ATK2] )
{
P_SetMobjState (player->mo, S_PLAY);
}
if (player->readyweapon == wp_chainsaw
&& psp->state == &states[S_SAW])
{
S_StartSound (player->mo, sfx_sawidl);
}
// check for change
// if player is dead, put the weapon away
if (player->pendingweapon != wp_nochange || !player->health)
{
// change weapon
// (pending weapon should allready be validated)
newstate = weaponinfo[player->readyweapon].downstate;
P_SetPsprite (player, ps_weapon, newstate);
return;
}
// check for fire
// the missile launcher and bfg do not auto fire
if (player->cmd.buttons & BT_ATTACK)
{
if ( !player->attackdown
|| (player->readyweapon != wp_missile
&& player->readyweapon != wp_bfg) )
{
player->attackdown = true;
P_FireWeapon (player);
return;
}
}
else
player->attackdown = false;
// bob the weapon based on movement speed
angle = (128*leveltime)&FINEMASK;
psp->sx = FRACUNIT + FixedMul (player->bob, finecosine[angle]);
angle &= FINEANGLES/2-1;
psp->sy = WEAPONTOP + FixedMul (player->bob, finesine[angle]);
}
//
// A_ReFire
// The player can re-fire the weapon
// without lowering it entirely.
//
void A_ReFire
( player_t* player,
pspdef_t* psp )
{
// check for fire
// (if a weaponchange is pending, let it go through instead)
if ( (player->cmd.buttons & BT_ATTACK)
&& player->pendingweapon == wp_nochange
&& player->health)
{
player->refire++;
P_FireWeapon (player);
}
else
{
player->refire = 0;
P_CheckAmmo (player);
}
}
void
A_CheckReload
( player_t* player,
pspdef_t* psp )
{
P_CheckAmmo (player);
#if 0
if (player->ammo[am_shell]<2)
P_SetPsprite (player, ps_weapon, S_DSNR1);
#endif
}
//
// A_Lower
// Lowers current weapon,
// and changes weapon at bottom.
//
void
A_Lower
( player_t* player,
pspdef_t* psp )
{
psp->sy += LOWERSPEED;
// Is already down.
if (psp->sy < WEAPONBOTTOM )
return;
// Player is dead.
if (player->playerstate == PST_DEAD)
{
psp->sy = WEAPONBOTTOM;
// don't bring weapon back up
return;
}
// The old weapon has been lowered off the screen,
// so change the weapon and start raising it
if (!player->health)
{
// Player is dead, so keep the weapon off screen.
P_SetPsprite (player, ps_weapon, S_NULL);
return;
}
player->readyweapon = player->pendingweapon;
P_BringUpWeapon (player);
}
//
// A_Raise
//
void
A_Raise
( player_t* player,
pspdef_t* psp )
{
statenum_t newstate;
psp->sy -= RAISESPEED;
if (psp->sy > WEAPONTOP )
return;
psp->sy = WEAPONTOP;
// The weapon has been raised all the way,
// so change to the ready state.
newstate = weaponinfo[player->readyweapon].readystate;
P_SetPsprite (player, ps_weapon, newstate);
}
//
// A_GunFlash
//
void
A_GunFlash
( player_t* player,
pspdef_t* psp )
{
P_SetMobjState (player->mo, S_PLAY_ATK2);
P_SetPsprite (player,ps_flash,weaponinfo[player->readyweapon].flashstate);
}
//
// WEAPON ATTACKS
//
//
// A_Punch
//
void
A_Punch
( player_t* player,
pspdef_t* psp )
{
angle_t angle;
int damage;
int slope;
damage = (P_Random ()%10+1)<<1;
if (player->powers[pw_strength])
damage *= 10;
angle = player->mo->angle;
angle += (P_Random()-P_Random())<<18;
slope = P_AimLineAttack (player->mo, angle, MELEERANGE);
P_LineAttack (player->mo, angle, MELEERANGE, slope, damage);
// turn to face target
if (linetarget)
{
S_StartSound (player->mo, sfx_punch);
player->mo->angle = R_PointToAngle2 (player->mo->x,
player->mo->y,
linetarget->x,
linetarget->y);
}
}
//
// A_Saw
//
void
A_Saw
( player_t* player,
pspdef_t* psp )
{
angle_t angle;
int damage;
int slope;
damage = 2*(P_Random ()%10+1);
angle = player->mo->angle;
angle += (P_Random()-P_Random())<<18;
// use meleerange + 1 se the puff doesn't skip the flash
slope = P_AimLineAttack (player->mo, angle, MELEERANGE+1);
P_LineAttack (player->mo, angle, MELEERANGE+1, slope, damage);
if (!linetarget)
{
S_StartSound (player->mo, sfx_sawful);
return;
}
S_StartSound (player->mo, sfx_sawhit);
// turn to face target
angle = R_PointToAngle2 (player->mo->x, player->mo->y,
linetarget->x, linetarget->y);
if (angle - player->mo->angle > ANG180)
{
if (angle - player->mo->angle < -ANG90/20)
player->mo->angle = angle + ANG90/21;
else
player->mo->angle -= ANG90/20;
}
else
{
if (angle - player->mo->angle > ANG90/20)
player->mo->angle = angle - ANG90/21;
else
player->mo->angle += ANG90/20;
}
player->mo->flags |= MF_JUSTATTACKED;
}
//
// A_FireMissile
//
void
A_FireMissile
( player_t* player,
pspdef_t* psp )
{
player->ammo[weaponinfo[player->readyweapon].ammo]--;
P_SpawnPlayerMissile (player->mo, MT_ROCKET);
}
//
// A_FireBFG
//
void
A_FireBFG
( player_t* player,
pspdef_t* psp )
{
player->ammo[weaponinfo[player->readyweapon].ammo] -= BFGCELLS;
P_SpawnPlayerMissile (player->mo, MT_BFG);
}
//
// A_FirePlasma
//
void
A_FirePlasma
( player_t* player,
pspdef_t* psp )
{
player->ammo[weaponinfo[player->readyweapon].ammo]--;
P_SetPsprite (player,
ps_flash,
weaponinfo[player->readyweapon].flashstate+(P_Random ()&1) );
P_SpawnPlayerMissile (player->mo, MT_PLASMA);
}
//
// P_BulletSlope
// Sets a slope so a near miss is at aproximately
// the height of the intended target
//
fixed_t bulletslope;
void P_BulletSlope (mobj_t* mo)
{
angle_t an;
// see which target is to be aimed at
an = mo->angle;
bulletslope = P_AimLineAttack (mo, an, 16*64*FRACUNIT);
if (!linetarget)
{
an += 1<<26;
bulletslope = P_AimLineAttack (mo, an, 16*64*FRACUNIT);
if (!linetarget)
{
an -= 2<<26;
bulletslope = P_AimLineAttack (mo, an, 16*64*FRACUNIT);
}
}
}
//
// P_GunShot
//
void
P_GunShot
( mobj_t* mo,
boolean accurate )
{
angle_t angle;
int damage;
damage = 5*(P_Random ()%3+1);
angle = mo->angle;
if (!accurate)
angle += (P_Random()-P_Random())<<18;
P_LineAttack (mo, angle, MISSILERANGE, bulletslope, damage);
}
//
// A_FirePistol
//
void
A_FirePistol
( player_t* player,
pspdef_t* psp )
{
S_StartSound (player->mo, sfx_pistol);
P_SetMobjState (player->mo, S_PLAY_ATK2);
player->ammo[weaponinfo[player->readyweapon].ammo]--;
P_SetPsprite (player,
ps_flash,
weaponinfo[player->readyweapon].flashstate);
P_BulletSlope (player->mo);
P_GunShot (player->mo, !player->refire);
}
//
// A_FireShotgun
//
void
A_FireShotgun
( player_t* player,
pspdef_t* psp )
{
int i;
S_StartSound (player->mo, sfx_shotgn);
P_SetMobjState (player->mo, S_PLAY_ATK2);
player->ammo[weaponinfo[player->readyweapon].ammo]--;
P_SetPsprite (player,
ps_flash,
weaponinfo[player->readyweapon].flashstate);
P_BulletSlope (player->mo);
for (i=0 ; i<7 ; i++)
P_GunShot (player->mo, false);
}
//
// A_FireShotgun2
//
void
A_FireShotgun2
( player_t* player,
pspdef_t* psp )
{
int i;
angle_t angle;
int damage;
S_StartSound (player->mo, sfx_dshtgn);
P_SetMobjState (player->mo, S_PLAY_ATK2);
player->ammo[weaponinfo[player->readyweapon].ammo]-=2;
P_SetPsprite (player,
ps_flash,
weaponinfo[player->readyweapon].flashstate);
P_BulletSlope (player->mo);
for (i=0 ; i<20 ; i++)
{
damage = 5*(P_Random ()%3+1);
angle = player->mo->angle;
angle += (P_Random()-P_Random())<<19;
P_LineAttack (player->mo,
angle,
MISSILERANGE,
bulletslope + ((P_Random()-P_Random())<<5), damage);
}
}
//
// A_FireCGun
//
void
A_FireCGun
( player_t* player,
pspdef_t* psp )
{
S_StartSound (player->mo, sfx_pistol);
if (!player->ammo[weaponinfo[player->readyweapon].ammo])
return;
P_SetMobjState (player->mo, S_PLAY_ATK2);
player->ammo[weaponinfo[player->readyweapon].ammo]--;
P_SetPsprite (player,
ps_flash,
weaponinfo[player->readyweapon].flashstate
+ psp->state
- &states[S_CHAIN1] );
P_BulletSlope (player->mo);
P_GunShot (player->mo, !player->refire);
}
//
// ?
//
void A_Light0 (player_t *player, pspdef_t *psp)
{
player->extralight = 0;
}
void A_Light1 (player_t *player, pspdef_t *psp)
{
player->extralight = 1;
}
void A_Light2 (player_t *player, pspdef_t *psp)
{
player->extralight = 2;
}
//
// A_BFGSpray
// Spawn a BFG explosion on every monster in view
//
void A_BFGSpray (mobj_t* mo)
{
int i;
int j;
int damage;
angle_t an;
// offset angles from its attack angle
for (i=0 ; i<40 ; i++)
{
an = mo->angle - ANG90/2 + ANG90/40*i;
// mo->target is the originator (player)
// of the missile
P_AimLineAttack (mo->target, an, 16*64*FRACUNIT);
if (!linetarget)
continue;
P_SpawnMobj (linetarget->x,
linetarget->y,
linetarget->z + (linetarget->height>>2),
MT_EXTRABFG);
damage = 0;
for (j=0;j<15;j++)
damage += (P_Random()&7) + 1;
P_DamageMobj (linetarget, mo->target,mo->target, damage);
}
}
//
// A_BFGsound
//
void
A_BFGsound
( player_t* player,
pspdef_t* psp )
{
S_StartSound (player->mo, sfx_bfg);
}
//
// P_SetupPsprites
// Called at start of level for each player.
//
void P_SetupPsprites (player_t* player)
{
int i;
// remove all psprites
for (i=0 ; i<NUMPSPRITES ; i++)
player->psprites[i].state = NULL;
// spawn the gun
player->pendingweapon = player->readyweapon;
P_BringUpWeapon (player);
}
//
// P_MovePsprites
// Called every tic by player thinking routine.
//
void P_MovePsprites (player_t* player)
{
int i;
pspdef_t* psp;
state_t* state;
psp = &player->psprites[0];
for (i=0 ; i<NUMPSPRITES ; i++, psp++)
{
// a null state means not active
if ( (state = psp->state) )
{
// drop tic count and possibly change state
// a -1 tic count never changes
if (psp->tics != -1)
{
psp->tics--;
if (!psp->tics)
P_SetPsprite (player, i, psp->state->nextstate);
}
}
}
player->psprites[ps_flash].sx = player->psprites[ps_weapon].sx;
player->psprites[ps_flash].sy = player->psprites[ps_weapon].sy;
}
| 0 | 0.967757 | 1 | 0.967757 | game-dev | MEDIA | 0.988931 | game-dev | 0.880584 | 1 | 0.880584 |
Cataclysm-TLG/Cataclysm-TLG | 70,721 | src/monstergenerator.cpp | #include "mattack_common.h" // IWYU pragma: associated
#include "monstergenerator.h" // IWYU pragma: associated
#include <algorithm>
#include <cstdlib>
#include <limits>
#include <new>
#include <optional>
#include <set>
#include <string>
#include <utility>
#include "assign.h"
#include "bodypart.h"
#include "cached_options.h"
#include "calendar.h"
#include "catacharset.h"
#include "creature.h"
#include "damage.h"
#include "debug.h"
#include "enum_conversions.h"
#include "field_type.h"
#include "generic_factory.h"
#include "item.h"
#include "item_group.h"
#include "json.h"
#include "make_static.h"
#include "mattack_actors.h"
#include "monattack.h"
#include "mondeath.h"
#include "mondefense.h"
#include "mongroup.h"
#include "options.h"
#include "pathfinding.h"
#include "rng.h"
#include "translations.h"
#include "type_id.h"
#include "units.h"
#include "weakpoint.h"
static const material_id material_flesh( "flesh" );
static const speed_description_id speed_description_DEFAULT( "DEFAULT" );
static const spell_id spell_pseudo_dormant_trap_setup( "pseudo_dormant_trap_setup" );
namespace
{
generic_factory<mon_flag> mon_flags( "monster flags" );
} // namespace
namespace behavior
{
class node_t;
} // namespace behavior
namespace io
{
template<>
std::string enum_to_string<mon_trigger>( mon_trigger data )
{
switch( data ) {
// *INDENT-OFF*
case mon_trigger::STALK: return "STALK";
case mon_trigger::HOSTILE_WEAK: return "PLAYER_WEAK";
case mon_trigger::HOSTILE_CLOSE: return "PLAYER_CLOSE";
case mon_trigger::HOSTILE_SEEN: return "HOSTILE_SEEN";
case mon_trigger::HURT: return "HURT";
case mon_trigger::FIRE: return "FIRE";
case mon_trigger::FRIEND_DIED: return "FRIEND_DIED";
case mon_trigger::FRIEND_ATTACKED: return "FRIEND_ATTACKED";
case mon_trigger::SOUND: return "SOUND";
case mon_trigger::PLAYER_NEAR_BABY: return "PLAYER_NEAR_BABY";
case mon_trigger::MATING_SEASON: return "MATING_SEASON";
case mon_trigger::BRIGHT_LIGHT: return "BRIGHT_LIGHT";
// *INDENT-ON*
case mon_trigger::LAST:
break;
}
cata_fatal( "Invalid mon_trigger" );
}
template<>
std::string enum_to_string<mdeath_type>( mdeath_type data )
{
switch( data ) {
case mdeath_type::NORMAL:
return "NORMAL";
case mdeath_type::SPLATTER:
return "SPLATTER";
case mdeath_type::BROKEN:
return "BROKEN";
case mdeath_type::NO_CORPSE:
return "NO_CORPSE";
case mdeath_type::LAST:
break;
}
cata_fatal( "Invalid mdeath_type" );
}
} // namespace io
/** @relates string_id */
template<>
const mtype &string_id<mtype>::obj() const
{
return MonsterGenerator::generator().mon_templates->obj( *this );
}
/** @relates string_id */
template<>
bool string_id<mtype>::is_valid() const
{
return MonsterGenerator::generator().mon_templates->is_valid( *this );
}
/** @relates string_id */
template<>
const species_type &string_id<species_type>::obj() const
{
return MonsterGenerator::generator().mon_species->obj( *this );
}
/** @relates string_id */
template<>
bool string_id<species_type>::is_valid() const
{
return MonsterGenerator::generator().mon_species->is_valid( *this );
}
/** @relates int_id */
template<>
bool int_id<mon_flag>::is_valid() const
{
return mon_flags.is_valid( *this );
}
/** @relates int_id */
template<>
const mon_flag &int_id<mon_flag>::obj() const
{
return mon_flags.obj( *this );
}
/** @relates int_id */
template<>
const string_id<mon_flag> &int_id<mon_flag>::id() const
{
return mon_flags.convert( *this );
}
/** @relates int_id */
template<>
int_id<mon_flag> string_id<mon_flag>::id() const
{
return mon_flags.convert( *this, int_id<mon_flag>( 0 ) );
}
/** @relates int_id */
template<>
int_id<mon_flag>::int_id( const string_id<mon_flag> &id ) : _id( id.id() )
{
}
/** @relates string_id */
template<>
const mon_flag &string_id<mon_flag>::obj() const
{
return mon_flags.obj( *this );
}
/** @relates string_id */
template<>
bool string_id<mon_flag>::is_valid() const
{
return mon_flags.is_valid( *this );
}
std::optional<mon_action_death> MonsterGenerator::get_death_function( const std::string &f ) const
{
const auto it = death_map.find( f );
return it != death_map.cend()
? std::optional<mon_action_death>( it->second )
: std::optional<mon_action_death>();
}
MonsterGenerator::MonsterGenerator()
: mon_templates( "monster type" )
, mon_species( "species" )
{
mon_templates->insert( mtype() );
mon_species->insert( species_type() );
init_phases();
init_attack();
init_defense();
}
MonsterGenerator::~MonsterGenerator() = default;
void MonsterGenerator::reset()
{
mon_templates->reset();
mon_templates->insert( mtype() );
mon_species->reset();
mon_species->insert( species_type() );
hallucination_monsters.clear();
attack_map.clear();
// Hardcode attacks need to be re-added here
// TODO: Move initialization from constructor to init()
init_attack();
}
static int calc_bash_skill( const mtype &t )
{
// IOW, the critter's max bashing damage
int ret = t.melee_dice * t.melee_sides;
// This is for stuff that goes through solid rock: minerbots, dark wyrms, etc
if( t.has_flag( mon_flag_BORES ) ) {
ret *= 15;
} else if( t.has_flag( mon_flag_DESTROYS ) ) {
ret *= 2.5;
} else if( !t.has_flag( mon_flag_BASHES ) ) {
ret = 0;
}
return ret;
}
// TODO: size_to_volume and volume_to_size should be made into a single consistent function.
// TODO: Volume max should be tiny: 10679, small: 27358, medium: 90134, large: 150299
// TODO: This would necessitate increasing vpart capacity and resizing almost every monster in the game.
// See Character::get_average_character_volume() etc.
static creature_size volume_to_size( const units::volume &vol )
{
if( vol <= 7500_ml ) {
return creature_size::tiny;
} else if( vol <= 46250_ml ) {
return creature_size::small;
} else if( vol <= 108000_ml ) {
return creature_size::medium;
} else if( vol <= 483750_ml ) {
return creature_size::large;
}
return creature_size::huge;
}
struct monster_adjustment {
species_id species;
std::string stat;
float stat_adjust = 0.0f;
std::string flag;
bool flag_val = false;
std::string special;
void apply( mtype &mon ) const;
};
void monster_adjustment::apply( mtype &mon ) const
{
if( !mon.in_species( species ) ) {
return;
}
if( !stat.empty() ) {
if( stat == "speed" ) {
mon.speed *= stat_adjust;
} else if( stat == "hp" ) {
mon.hp *= stat_adjust;
} else if( stat == "bleed_rate" ) {
mon.bleed_rate *= stat_adjust;
}
}
if( !flag.empty() ) {
mon.set_flag( mon_flag_id( flag ), flag_val );
}
if( !special.empty() ) {
if( special == "nightvision" ) {
mon.vision_night = mon.vision_day;
}
}
}
static std::vector<monster_adjustment> adjustments;
void reset_monster_adjustment()
{
adjustments.clear();
}
void load_monster_adjustment( const JsonObject &jsobj )
{
monster_adjustment adj;
adj.species = species_id( jsobj.get_string( "species" ) );
if( jsobj.has_member( "stat" ) ) {
JsonObject stat = jsobj.get_object( "stat" );
stat.read( "name", adj.stat );
stat.read( "modifier", adj.stat_adjust );
}
if( jsobj.has_member( "flag" ) ) {
JsonObject flag = jsobj.get_object( "flag" );
flag.read( "name", adj.flag );
flag.read( "value", adj.flag_val );
}
if( jsobj.has_member( "special" ) ) {
jsobj.read( "special", adj.special );
}
adjustments.push_back( adj );
}
static void build_behavior_tree( mtype &type )
{
type.set_strategy();
for( const std::pair<const std::string, mtype_special_attack> &attack : type.special_attacks ) {
if( string_id<behavior::node_t>( attack.first ).is_valid() ) {
type.add_goal( attack.first );
} /* TODO: Make this an error once all the special attacks are migrated. */
}
}
void MonsterGenerator::finalize_mtypes()
{
mon_templates->finalize();
std::vector<mtype> extra_mtypes;
for( const mtype &elem : mon_templates->get_all() ) {
mtype &mon = const_cast<mtype &>( elem );
if( !mon.default_faction.is_valid() ) {
debugmsg( "Monster type '%s' has invalid default_faction: '%s'. "
"Add this faction to json as MONSTER_FACTION type.",
mon.id.str(), mon.default_faction.str() );
}
mon.flags.clear();
for( const mon_flag_str_id &mf : mon.pre_flags_ ) {
mon.flags.emplace( mf );
}
apply_species_attributes( mon );
validate_species_ids( mon );
mon.size = volume_to_size( mon.volume );
for( const monster_adjustment &adj : adjustments ) {
adj.apply( mon );
}
if( mon.bash_skill < 0 ) {
mon.bash_skill = calc_bash_skill( mon );
}
finalize_damage_map( mon.armor.resist_vals, true );
if( mon.armor_proportional.has_value() ) {
finalize_damage_map( mon.armor_proportional->resist_vals, false, 1.f );
for( std::pair<const damage_type_id, float> &dt : mon.armor.resist_vals ) {
const auto iter = mon.armor_proportional->resist_vals.find( dt.first );
if( iter != mon.armor_proportional->resist_vals.end() ) {
dt.second *= iter->second;
}
}
}
if( mon.armor_relative.has_value() ) {
finalize_damage_map( mon.armor_relative->resist_vals, false, 0.f );
for( std::pair<const damage_type_id, float> &dt : mon.armor.resist_vals ) {
const auto iter = mon.armor_relative->resist_vals.find( dt.first );
if( iter != mon.armor_relative->resist_vals.end() ) {
dt.second += iter->second;
}
}
}
float melee_dmg_total = mon.melee_damage.total_damage();
float armor_diff = 3.0f;
for( const auto &dt : mon.armor.resist_vals ) {
if( dt.first->mon_difficulty ) {
armor_diff += dt.second;
}
}
std::unordered_set<std::string> blacklisted_specials{"PARROT", "PARROT_AT_DANGER", "GRAZE", "EAT_CROP", "EAT_FOOD", "EAT_CARRION"};
int special_attacks_diff = 0;
for( const auto &special : mon.special_attacks ) {
if( !blacklisted_specials.count( special.first ) ) {
special_attacks_diff++;
}
}
mon.difficulty = ( mon.melee_skill + 1 ) * mon.melee_dice * ( melee_dmg_total + mon.melee_sides ) *
0.04 + ( mon.sk_dodge + 1 ) * armor_diff * 0.04 +
( mon.difficulty_base + special_attacks_diff + 8 * mon.emit_fields.size() );
mon.difficulty *= ( mon.hp + mon.speed - mon.attack_cost + ( mon.morale + mon.agro ) * 0.1 ) * 0.01
+ ( mon.vision_day + 2 * mon.vision_night ) * 0.01;
mon.difficulty = std::max( 1, mon.difficulty );
if( mon.status_chance_multiplier < 0 ) {
mon.status_chance_multiplier = 0;
}
// Check if trap_ids are valid
for( trap_str_id trap_avoid_id : mon.trap_avoids ) {
if( !trap_avoid_id.is_valid() ) {
debugmsg( "Invalid trap '%s'", trap_avoid_id.str() );
}
}
// Lower bound for hp scaling
mon.hp = std::max( mon.hp, 1 );
//If the result monster is blacklisted no need to have the original monster look like it can revive
if( !mon.zombify_into.is_empty() &&
MonsterGroupManager::monster_is_blacklisted( mon.zombify_into ) ) {
mon.zombify_into = mtype_id();
}
build_behavior_tree( mon );
finalize_pathfinding_settings( mon );
mon.mdeath_effect.has_effect = mon.mdeath_effect.sp.is_valid();
mon.weakpoints.clear();
for( const weakpoints_id &wpset : mon.weakpoints_deferred ) {
mon.weakpoints.add_from_set( wpset, true );
}
if( !mon.weakpoints_deferred_inline.weakpoint_list.empty() ) {
mon.weakpoints_deferred_inline.finalize();
mon.weakpoints.add_from_set( mon.weakpoints_deferred_inline, true );
}
for( const std::string &wp_del : mon.weakpoints_deferred_deleted ) {
for( auto iter = mon.weakpoints.weakpoint_list.begin();
iter != mon.weakpoints.weakpoint_list.end(); ) {
if( iter->id == wp_del ) {
iter = mon.weakpoints.weakpoint_list.erase( iter );
} else {
iter++;
}
}
}
mon.weakpoints.finalize();
// check lastly to make extra fake monsters.
if( mon.has_flag( mon_flag_GEN_DORMANT ) ) {
extra_mtypes.push_back( generate_fake_pseudo_dormant_monster( mon ) );
}
}
for( const mtype &mon : mon_templates->get_all() ) {
if( !mon.has_flag( mon_flag_NOT_HALLUCINATION ) ) {
hallucination_monsters.push_back( mon.id );
}
}
// now add the fake monsters to the mon_templates
for( mtype &mon : extra_mtypes ) {
mon_templates->insert( mon );
}
}
mtype MonsterGenerator::generate_fake_pseudo_dormant_monster( const mtype &mon )
{
// this is what we are trying to build. Example for mon_zombie
//{
// "id": "pseudo_dormant_mon_zombie",
// "type" : "MONSTER",
// "name" : { "str": "zombie" },
// "description" : "Fake zombie used for spawning dormant zombies. If you see this, open an issue on github.",
// "copy-from" : "mon_zombie",
// "looks_like" : "corpse_mon_zombie",
// "hp" : 5,
// "speed" : 1,
// "flags" : ["FILTHY", "REVIVES", "DORMANT", "QUIETDEATH"] ,
// "zombify_into" : "mon_zombie",
// "special_attacks" : [
// {
// "id": "pseudo_dormant_trap_setup_attk",
// "type" : "spell",
// "spell_data" : { "id": "pseudo_dormant_trap_setup", "hit_self" : true },
// "cooldown" : 1,
// "allow_no_target" : true,
// "monster_message" : ""
// }
// ]
//},
mtype fake_mon = mtype( mon );
fake_mon.id = mtype_id( "pseudo_dormant_" + mon.id.str() );
// allowed (optional) flags: [ "FILTHY" ],
// delete all others.
// then add [ "DORMANT", "QUIETDEATH", "REVIVES", "REVIVES_HEALTHY" ]
bool has_filthy = fake_mon.has_flag( mon_flag_FILTHY );
fake_mon.flags.clear();
fake_mon.flags.emplace( mon_flag_DORMANT );
fake_mon.flags.emplace( mon_flag_QUIETDEATH );
fake_mon.flags.emplace( mon_flag_REVIVES );
fake_mon.flags.emplace( mon_flag_REVIVES_HEALTHY );
if( has_filthy ) {
fake_mon.flags.emplace( mon_flag_FILTHY );
}
// zombify into the original mon
fake_mon.zombify_into = mon.id;
// looks like "corpse" + original mon
fake_mon.looks_like = "corpse_" + mon.id.str();
// set the hp to 5
fake_mon.hp = 5;
// set the speed to 1
fake_mon.speed = 1;
// now ensure that monster will always die instantly. Nuke all resistances and dodges.
// before this monsters like zombie predators could periodically resist the killing effect for a while.
// clear dodge
fake_mon.sk_dodge = 0;
// clear regenerate
fake_mon.regenerates = 0;
fake_mon.regenerates_in_dark = false;
// clear armor
for( const auto &dam : fake_mon.armor.resist_vals ) {
fake_mon.armor.resist_vals[dam.first] = 0;
}
// add the special attack.
// first make a new mon_spellcasting_actor actor
std::unique_ptr<mon_spellcasting_actor> new_actor( new mon_spellcasting_actor() );
new_actor->allow_no_target = true;
new_actor->cooldown.min.dbl_val = 1;
new_actor->spell_data.id = spell_pseudo_dormant_trap_setup;
new_actor->spell_data.self = true;
// create the special attack now using the actor
// use this constructor
// explicit mtype_special_attack( std::unique_ptr<mattack_actor> f ) : actor( std::move( f ) ) { }
std::unique_ptr<mattack_actor> base_actor = std::move( new_actor );
mtype_special_attack new_attack( std::move( base_actor ) );
std::pair<const std::string, mtype_special_attack> new_pair{
std::string( "pseudo_dormant_trap_setup_attk" ),
std::move( new_attack )
};
fake_mon.special_attacks.emplace( std::move( new_pair ) );
fake_mon.special_attacks_names.emplace_back( "pseudo_dormant_trap_setup_attk" );
return fake_mon;
}
void MonsterGenerator::apply_species_attributes( mtype &mon )
{
for( const auto &spec : mon.species ) {
if( !spec.is_valid() ) {
continue;
}
const species_type &mspec = spec.obj();
for( const mon_flag_str_id &f : mspec.flags ) {
mon.flags.emplace( f );
mon.pre_flags_.emplace( f );
}
mon.anger |= mspec.anger;
mon.fear |= mspec.fear;
mon.placate |= mspec.placate;
}
}
void MonsterGenerator::finalize_pathfinding_settings( mtype &mon )
{
if( mon.path_settings.max_length < 0 ) {
mon.path_settings.max_length = mon.path_settings.max_dist * 5;
}
if( mon.path_settings.bash_strength < 0 ) {
mon.path_settings.bash_strength = mon.bash_skill;
}
if( mon.has_flag( mon_flag_CLIMBS ) ) {
mon.path_settings.climb_cost = 3;
}
}
void MonsterGenerator::init_phases()
{
phase_map["NULL"] = phase_id::PNULL;
phase_map["SOLID"] = phase_id::SOLID;
phase_map["LIQUID"] = phase_id::LIQUID;
phase_map["GAS"] = phase_id::GAS;
phase_map["PLASMA"] = phase_id::PLASMA;
}
void MonsterGenerator::init_attack()
{
add_hardcoded_attack( "NONE", mattack::none );
add_hardcoded_attack( "ABSORB_ITEMS", mattack::absorb_items );
add_hardcoded_attack( "SPLIT", mattack::split );
add_hardcoded_attack( "BROWSE", mattack::browse );
add_hardcoded_attack( "EAT_CARRION", mattack::eat_carrion );
add_hardcoded_attack( "EAT_CROP", mattack::eat_crop );
add_hardcoded_attack( "EAT_FOOD", mattack::eat_food );
add_hardcoded_attack( "GRAZE", mattack::graze );
add_hardcoded_attack( "CHECK_UP", mattack::nurse_check_up );
add_hardcoded_attack( "ASSIST", mattack::nurse_assist );
add_hardcoded_attack( "OPERATE", mattack::nurse_operate );
add_hardcoded_attack( "PAID_BOT", mattack::check_money_left );
add_hardcoded_attack( "SHRIEK", mattack::shriek );
add_hardcoded_attack( "SHRIEK_ALERT", mattack::shriek_alert );
add_hardcoded_attack( "SHRIEK_STUN", mattack::shriek_stun );
add_hardcoded_attack( "RATTLE", mattack::rattle );
add_hardcoded_attack( "HOWL", mattack::howl );
add_hardcoded_attack( "ACID", mattack::acid );
add_hardcoded_attack( "ACID_BARF", mattack::acid_barf );
add_hardcoded_attack( "SHOCKSTORM", mattack::shockstorm );
add_hardcoded_attack( "PULL_METAL_WEAPON", mattack::pull_metal_weapon );
add_hardcoded_attack( "BOOMER", mattack::boomer );
add_hardcoded_attack( "BOOMER_GLOW", mattack::boomer_glow );
add_hardcoded_attack( "PULL_METAL_WEAPON", mattack::pull_metal_weapon );
add_hardcoded_attack( "PULL_METAL_AOE", mattack::pull_metal_aoe );
add_hardcoded_attack( "RESURRECT", mattack::resurrect );
add_hardcoded_attack( "SMASH", mattack::smash );
add_hardcoded_attack( "SCIENCE", mattack::science );
add_hardcoded_attack( "GROWPLANTS", mattack::growplants );
add_hardcoded_attack( "GROW_VINE", mattack::grow_vine );
add_hardcoded_attack( "VINE", mattack::vine );
add_hardcoded_attack( "SPIT_SAP", mattack::spit_sap );
add_hardcoded_attack( "TRIFFID_HEARTBEAT", mattack::triffid_heartbeat );
add_hardcoded_attack( "FUNGUS", mattack::fungus );
add_hardcoded_attack( "FUNGUS_HAZE", mattack::fungus_haze );
add_hardcoded_attack( "FUNGUS_BIG_BLOSSOM", mattack::fungus_big_blossom );
add_hardcoded_attack( "FUNGUS_INJECT", mattack::fungus_inject );
add_hardcoded_attack( "FUNGUS_BRISTLE", mattack::fungus_bristle );
add_hardcoded_attack( "FUNGUS_SPROUT", mattack::fungus_sprout );
add_hardcoded_attack( "FUNGUS_FORTIFY", mattack::fungus_fortify );
add_hardcoded_attack( "FUNGAL_TRAIL", mattack::fungal_trail );
add_hardcoded_attack( "PLANT", mattack::plant );
add_hardcoded_attack( "DISAPPEAR", mattack::disappear );
add_hardcoded_attack( "DEPART", mattack::depart );
add_hardcoded_attack( "FORMBLOB", mattack::formblob );
add_hardcoded_attack( "CALLBLOBS", mattack::callblobs );
add_hardcoded_attack( "DOGTHING", mattack::dogthing );
add_hardcoded_attack( "PARA_STING", mattack::para_sting );
add_hardcoded_attack( "TRIFFID_GROWTH", mattack::triffid_growth );
add_hardcoded_attack( "PHOTOGRAPH", mattack::photograph );
add_hardcoded_attack( "TAZER", mattack::tazer );
add_hardcoded_attack( "SEARCHLIGHT", mattack::searchlight );
add_hardcoded_attack( "SPEAKER", mattack::speaker );
add_hardcoded_attack( "FLAMETHROWER", mattack::flamethrower );
add_hardcoded_attack( "COPBOT", mattack::copbot );
add_hardcoded_attack( "CHICKENBOT", mattack::chickenbot );
add_hardcoded_attack( "MULTI_ROBOT", mattack::multi_robot );
add_hardcoded_attack( "RATKING", mattack::ratking );
add_hardcoded_attack( "GENERATOR", mattack::generator );
add_hardcoded_attack( "UPGRADE", mattack::upgrade );
add_hardcoded_attack( "FLESH_GOLEM", mattack::flesh_golem );
add_hardcoded_attack( "ABSORB_MEAT", mattack::absorb_meat );
add_hardcoded_attack( "LUNGE", mattack::lunge );
add_hardcoded_attack( "PARROT", mattack::parrot );
add_hardcoded_attack( "PARROT_AT_DANGER", mattack::parrot_at_danger );
add_hardcoded_attack( "BLOW_WHISTLE", mattack::blow_whistle );
add_hardcoded_attack( "DARKMAN", mattack::darkman );
add_hardcoded_attack( "SLIMESPRING", mattack::slimespring );
add_hardcoded_attack( "EVOLVE_KILL_STRIKE", mattack::evolve_kill_strike );
add_hardcoded_attack( "TINDALOS_TELEPORT", mattack::tindalos_teleport );
add_hardcoded_attack( "FLESH_TENDRIL", mattack::flesh_tendril );
add_hardcoded_attack( "BIO_OP_BIOJUTSU", mattack::bio_op_random_biojutsu );
add_hardcoded_attack( "BIO_OP_TAKEDOWN", mattack::bio_op_takedown );
add_hardcoded_attack( "BIO_OP_IMPALE", mattack::bio_op_impale );
add_hardcoded_attack( "BIO_OP_DISARM", mattack::bio_op_disarm );
add_hardcoded_attack( "SUICIDE", mattack::suicide );
add_hardcoded_attack( "KAMIKAZE", mattack::kamikaze );
add_hardcoded_attack( "GRENADIER", mattack::grenadier );
add_hardcoded_attack( "GRENADIER_ELITE", mattack::grenadier_elite );
add_hardcoded_attack( "RIOTBOT", mattack::riotbot );
add_hardcoded_attack( "STRETCH_ATTACK", mattack::stretch_attack );
add_hardcoded_attack( "DOOT", mattack::doot );
add_hardcoded_attack( "ZOMBIE_FUSE", mattack::zombie_fuse );
}
void MonsterGenerator::init_defense()
{
// No special attack-back
defense_map["NONE"] = &mdefense::none;
// Shock attacker on hit
defense_map["ZAPBACK"] = &mdefense::zapback;
// Splash acid on the attacker
defense_map["ACIDSPLASH"] = &mdefense::acidsplash;
// Blind fire on unseen attacker
defense_map["RETURN_FIRE"] = &mdefense::return_fire;
}
void MonsterGenerator::validate_species_ids( mtype &mon )
{
for( const auto &s : mon.species ) {
if( !s.is_valid() ) {
debugmsg( "Tried to assign species %s to monster %s, but no entry for the species exists",
s.c_str(), mon.id.c_str() );
}
}
}
void MonsterGenerator::load_monster( const JsonObject &jo, const std::string &src )
{
mon_templates->load( jo, src );
}
mon_effect_data::mon_effect_data() :
chance( 100.0f ),
permanent( false ),
affect_hit_bp( false ),
bp( bodypart_str_id::NULL_ID() ),
duration( 1, 1 ),
intensity( 0, 0 ) {}
void mon_effect_data::load( const JsonObject &jo )
{
mandatory( jo, false, "id", id );
optional( jo, false, "chance", chance, 100.f );
optional( jo, false, "permanent", permanent, false );
optional( jo, false, "affect_hit_bp", affect_hit_bp, false );
optional( jo, false, "bp", bp, bodypart_str_id::NULL_ID() );
optional( jo, false, "message", message );
// Support shorthand for a single value.
if( jo.has_int( "duration" ) ) {
int i = 1;
mandatory( jo, false, "duration", i );
duration = { i, i };
} else {
optional( jo, false, "duration", duration, std::pair<int, int> { 1, 1 } );
}
if( jo.has_int( "intensity" ) ) {
int i = 1;
mandatory( jo, false, "intensity", i );
intensity = { i, i };
} else {
optional( jo, false, "intensity", intensity, std::pair<int, int> { 1, 1 } );
}
if( chance > 100.f || chance < 0.f ) {
float chance_wrong = chance;
chance = clamp<float>( chance, 0.f, 100.f );
jo.throw_error_at( "chance",
string_format( "\"chance\" is defined as %f, "
"but must be a decimal number between 0.0 and 100.0", chance_wrong ) );
}
}
void mtype::load( const JsonObject &jo, const std::string &src )
{
bool strict = src == "tlg";
MonsterGenerator &gen = MonsterGenerator::generator();
name.make_plural();
mandatory( jo, was_loaded, "name", name );
optional( jo, was_loaded, "description", description );
assign( jo, "ascii_picture", picture_id );
if( jo.has_member( "material" ) ) {
mat.clear();
for( const std::string &m : jo.get_tags( "material" ) ) {
mat.emplace( m, 1 );
mat_portion_total += 1;
}
}
if( mat.empty() ) { // Assign a default "flesh" material to prevent crash (#48988)
mat.emplace( material_flesh, 1 );
mat_portion_total += 1;
}
optional( jo, was_loaded, "species", species, string_id_reader<::species_type> {} );
optional( jo, was_loaded, "categories", categories, auto_flags_reader<> {} );
// See monfaction.cpp
if( !was_loaded || jo.has_member( "default_faction" ) ) {
default_faction = mfaction_str_id( jo.get_string( "default_faction" ) );
}
if( !was_loaded || jo.has_member( "symbol" ) ) {
sym = jo.get_string( "symbol" );
if( utf8_width( sym ) != 1 ) {
jo.throw_error_at( "symbol", "monster symbol should be exactly one console cell width" );
}
}
if( was_loaded && jo.has_member( "copy-from" ) && looks_like.empty() ) {
looks_like = jo.get_string( "copy-from" );
}
jo.read( "looks_like", looks_like );
assign( jo, "bodytype", bodytype );
assign( jo, "color", color );
assign( jo, "volume", volume, strict, 0_ml );
assign( jo, "weight", weight, strict, 0_gram );
optional( jo, was_loaded, "phase", phase, make_flag_reader( gen.phase_map, "phase id" ),
phase_id::SOLID );
assign( jo, "diff", difficulty_base, strict, 0 );
assign( jo, "hp", hp, strict, 1 );
assign( jo, "speed", speed, strict, 0 );
assign( jo, "aggression", agro, strict, -100, 100 );
assign( jo, "morale", morale, strict );
assign( jo, "stomach_size", stomach_size, strict );
assign( jo, "amount_eaten", amount_eaten, strict );
assign( jo, "tracking_distance", tracking_distance, strict, 3 );
assign( jo, "mountable_weight_ratio", mountable_weight_ratio, strict );
assign( jo, "attack_cost", attack_cost, strict, 0 );
assign( jo, "melee_skill", melee_skill, strict, 0 );
assign( jo, "melee_dice", melee_dice, strict, 0 );
assign( jo, "melee_dice_sides", melee_sides, strict, 0 );
assign( jo, "grab_strength", grab_strength, strict, 0 );
assign( jo, "dodge", sk_dodge, strict, 0 );
if( jo.has_object( "armor" ) ) {
armor = load_resistances_instance( jo.get_object( "armor" ) );
}
if( was_loaded && jo.has_object( "extend" ) ) {
JsonObject ext = jo.get_object( "extend" );
ext.allow_omitted_members();
if( ext.has_object( "armor" ) ) {
armor = extend_resistances_instance( armor, ext.get_object( "armor" ) );
}
}
armor_proportional.reset();
if( jo.has_object( "proportional" ) ) {
JsonObject jprop = jo.get_object( "proportional" );
jprop.allow_omitted_members();
if( jprop.has_object( "armor" ) ) {
armor_proportional = load_resistances_instance( jprop.get_object( "armor" ) );
}
}
armor_relative.reset();
if( jo.has_object( "relative" ) ) {
JsonObject jrel = jo.get_object( "relative" );
jrel.allow_omitted_members();
if( jrel.has_object( "armor" ) ) {
armor_relative = load_resistances_instance( jrel.get_object( "armor" ) );
}
}
optional( jo, was_loaded, "trap_avoids", trap_avoids );
if( !was_loaded ) {
weakpoints_deferred.clear();
weakpoints_deferred_inline.clear();
}
weakpoints_deferred_deleted.clear();
// Load each set of weakpoints.
// Each subsequent weakpoint set overwrites
// matching weakpoints from the previous set.
if( jo.has_array( "weakpoint_sets" ) ) {
weakpoints_deferred.clear();
for( JsonValue jval : jo.get_array( "weakpoint_sets" ) ) {
weakpoints_deferred.emplace_back( jval.get_string() );
}
}
// Finally, inline weakpoints overwrite
// any matching weakpoints from the previous sets.
if( jo.has_array( "weakpoints" ) ) {
weakpoints_deferred_inline.clear();
::weakpoints tmp_wp;
tmp_wp.load( jo.get_array( "weakpoints" ) );
weakpoints_deferred_inline.add_from_set( tmp_wp, true );
}
if( jo.has_object( "extend" ) ) {
JsonObject tmp = jo.get_object( "extend" );
tmp.allow_omitted_members();
if( tmp.has_array( "weakpoint_sets" ) ) {
for( JsonValue jval : tmp.get_array( "weakpoint_sets" ) ) {
weakpoints_deferred.emplace_back( jval.get_string() );
}
}
if( tmp.has_array( "weakpoints" ) ) {
::weakpoints tmp_wp;
tmp_wp.load( tmp.get_array( "weakpoints" ) );
weakpoints_deferred_inline.add_from_set( tmp_wp, true );
}
}
if( jo.has_object( "delete" ) ) {
JsonObject tmp = jo.get_object( "delete" );
tmp.allow_omitted_members();
if( tmp.has_array( "weakpoint_sets" ) ) {
for( JsonValue jval : tmp.get_array( "weakpoint_sets" ) ) {
weakpoints_id set_id( jval.get_string() );
auto iter = std::find( weakpoints_deferred.begin(), weakpoints_deferred.end(), set_id );
if( iter != weakpoints_deferred.end() ) {
weakpoints_deferred.erase( iter );
}
}
}
if( tmp.has_array( "weakpoints" ) ) {
::weakpoints tmp_wp;
tmp_wp.load( tmp.get_array( "weakpoints" ) );
for( const weakpoint &wp_del : tmp_wp.weakpoint_list ) {
weakpoints_deferred_deleted.emplace( wp_del.id );
}
weakpoints_deferred_inline.del_from_set( tmp_wp );
}
}
assign( jo, "status_chance_multiplier", status_chance_multiplier, strict, 0.0f, 5.0f );
if( !was_loaded || jo.has_array( "families" ) ) {
families.clear();
families.load( jo.get_array( "families" ) );
} else {
if( jo.has_object( "extend" ) ) {
JsonObject tmp = jo.get_object( "extend" );
tmp.allow_omitted_members();
if( tmp.has_array( "families" ) ) {
families.load( tmp.get_array( "families" ) );
}
}
if( jo.has_object( "delete" ) ) {
JsonObject tmp = jo.get_object( "delete" );
tmp.allow_omitted_members();
if( tmp.has_array( "families" ) ) {
families.remove( tmp.get_array( "families" ) );
}
}
}
optional( jo, was_loaded, "absorb_ml_per_hp", absorb_ml_per_hp, 250 );
optional( jo, was_loaded, "split_move_cost", split_move_cost, 200 );
optional( jo, was_loaded, "absorb_move_cost_per_ml", absorb_move_cost_per_ml, 0.025f );
optional( jo, was_loaded, "absorb_move_cost_min", absorb_move_cost_min, 1 );
optional( jo, was_loaded, "absorb_move_cost_max", absorb_move_cost_max, -1 );
if( jo.has_member( "absorb_material" ) ) {
absorb_material.clear();
if( jo.has_array( "absorb_material" ) ) {
for( std::string mat : jo.get_string_array( "absorb_material" ) ) {
absorb_material.emplace_back( mat );
}
} else {
absorb_material.emplace_back( jo.get_string( "absorb_material" ) );
}
}
if( jo.has_member( "no_absorb_material" ) ) {
no_absorb_material.clear();
if( jo.has_array( "no_absorb_material" ) ) {
for( std::string mat : jo.get_string_array( "no_absorb_material" ) ) {
no_absorb_material.emplace_back( mat );
}
} else {
no_absorb_material.emplace_back( jo.get_string( "no_absorb_material" ) );
}
}
optional( jo, was_loaded, "bleed_rate", bleed_rate, 100 );
optional( jo, was_loaded, "petfood", petfood );
assign( jo, "vision_day", vision_day, strict, 0 );
assign( jo, "vision_night", vision_night, strict, 0 );
optional( jo, was_loaded, "regenerates", regenerates, 0 );
optional( jo, was_loaded, "regenerates_in_dark", regenerates_in_dark, false );
optional( jo, was_loaded, "regen_morale", regen_morale, false );
if( !was_loaded || jo.has_member( "regeneration_modifiers" ) ) {
regeneration_modifiers.clear();
add_regeneration_modifiers( jo, "regeneration_modifiers", src );
} else {
// Note: regeneration_modifers left as is, new modifiers are added to it!
// Note: member name prefixes are compatible with those used by generic_typed_reader
if( jo.has_object( "extend" ) ) {
JsonObject tmp = jo.get_object( "extend" );
tmp.allow_omitted_members();
add_regeneration_modifiers( tmp, "regeneration_modifiers", src );
}
if( jo.has_object( "delete" ) ) {
JsonObject tmp = jo.get_object( "delete" );
tmp.allow_omitted_members();
remove_regeneration_modifiers( tmp, "regeneration_modifiers", src );
}
}
optional( jo, was_loaded, "starting_ammo", starting_ammo );
assign( jo, "luminance", luminance, true );
optional( jo, was_loaded, "revert_to_itype", revert_to_itype, itype_id() );
optional( jo, was_loaded, "mech_weapon", mech_weapon, itype_id() );
optional( jo, was_loaded, "mech_str_bonus", mech_str_bonus, 0 );
optional( jo, was_loaded, "mech_battery", mech_battery, itype_id() );
if( jo.has_object( "mount_items" ) ) {
JsonObject jo_mount_items = jo.get_object( "mount_items" );
optional( jo_mount_items, was_loaded, "tied", mount_items.tied, itype_id() );
optional( jo_mount_items, was_loaded, "tack", mount_items.tack, itype_id() );
optional( jo_mount_items, was_loaded, "armor", mount_items.armor, itype_id() );
optional( jo_mount_items, was_loaded, "storage", mount_items.storage, itype_id() );
}
if( jo.has_array( "revive_forms" ) ) {
revive_type foo;
for( JsonObject jo_form : jo.get_array( "revive_forms" ) ) {
read_condition( jo_form, "condition", foo.condition, true );
if( jo_form.has_string( "monster" ) ) {
mandatory( jo_form, was_loaded, "monster", foo.revive_mon );
} else {
mandatory( jo_form, was_loaded, "monster_group", foo.revive_monster_group );
}
revive_types.push_back( foo );
}
}
optional( jo, was_loaded, "zombify_into", zombify_into, string_id_reader<::mtype> {},
mtype_id() );
optional( jo, was_loaded, "fungalize_into", fungalize_into, string_id_reader<::mtype> {},
mtype_id() );
optional( jo, was_loaded, "aggro_character", aggro_character, true );
if( jo.has_array( "attack_effs" ) ) {
atk_effs.clear();
for( const JsonObject effect_jo : jo.get_array( "attack_effs" ) ) {
mon_effect_data effect;
effect.load( effect_jo );
atk_effs.push_back( std::move( effect ) );
}
}
optional( jo, was_loaded, "melee_damage", melee_damage );
if( jo.has_array( "scents_tracked" ) ) {
for( const std::string line : jo.get_array( "scents_tracked" ) ) {
scents_tracked.emplace( line );
}
}
if( jo.has_array( "scents_ignored" ) ) {
for( const std::string line : jo.get_array( "scents_ignored" ) ) {
scents_ignored.emplace( line );
}
}
if( jo.has_member( "death_drops" ) ) {
death_drops =
item_group::load_item_group( jo.get_member( "death_drops" ), "distribution",
"death_drops for mtype " + id.str() );
}
assign( jo, "harvest", harvest );
optional( jo, was_loaded, "dissect", dissect );
optional( jo, was_loaded, "decay", decay );
if( jo.has_array( "shearing" ) ) {
std::vector<shearing_entry> entries;
for( JsonObject shearing_entry : jo.get_array( "shearing" ) ) {
struct shearing_entry entry {};
entry.load( shearing_entry );
entries.emplace_back( entry );
}
shearing = shearing_data( entries );
}
optional( jo, was_loaded, "speed_description", speed_desc, speed_description_DEFAULT );
optional( jo, was_loaded, "death_function", mdeath_effect );
if( jo.has_array( "emit_fields" ) ) {
JsonArray jar = jo.get_array( "emit_fields" );
if( jar.has_string( 0 ) ) { // TEMPORARY until 0.F
for( const std::string id : jar ) {
emit_fields.emplace( emit_id( id ), 1_seconds );
}
} else {
while( jar.has_more() ) {
JsonObject obj = jar.next_object();
emit_fields.emplace( emit_id( obj.get_string( "emit_id" ) ),
read_from_json_string<time_duration>( obj.get_member( "delay" ), time_duration::units ) );
}
}
}
if( jo.has_member( "special_when_hit" ) ) {
JsonArray jsarr = jo.get_array( "special_when_hit" );
const auto iter = gen.defense_map.find( jsarr.get_string( 0 ) );
if( iter == gen.defense_map.end() ) {
jsarr.throw_error( "Invalid monster defense function" );
}
sp_defense = iter->second;
def_chance = jsarr.get_int( 1 );
} else if( !was_loaded ) {
sp_defense = &mdefense::none;
def_chance = 0;
}
if( !was_loaded || jo.has_member( "special_attacks" ) ) {
special_attacks.clear();
special_attacks_names.clear();
add_special_attacks( jo, "special_attacks", src );
} else {
// Note: special_attacks left as is, new attacks are added to it!
// Note: member name prefixes are compatible with those used by generic_typed_reader
if( jo.has_object( "extend" ) ) {
JsonObject tmp = jo.get_object( "extend" );
tmp.allow_omitted_members();
add_special_attacks( tmp, "special_attacks", src );
}
if( jo.has_object( "delete" ) ) {
JsonObject tmp = jo.get_object( "delete" );
tmp.allow_omitted_members();
remove_special_attacks( tmp, "special_attacks", src );
}
}
optional( jo, was_loaded, "melee_training_cap", melee_training_cap, std::min( melee_skill + 2,
MAX_SKILL ) );
optional( jo, was_loaded, "chat_topics", chat_topics );
// Disable upgrading when JSON contains `"upgrades": false`, but fallback to the
// normal behavior (including error checking) if "upgrades" is not boolean or not `false`.
if( jo.has_bool( "upgrades" ) && !jo.get_bool( "upgrades" ) ) {
upgrade_group = mongroup_id::NULL_ID();
upgrade_into = mtype_id::NULL_ID();
upgrades = false;
upgrade_null_despawn = false;
} else if( jo.has_member( "upgrades" ) ) {
JsonObject up = jo.get_object( "upgrades" );
optional( up, was_loaded, "half_life", half_life, -1 );
optional( up, was_loaded, "age_grow", age_grow, -1 );
if( up.has_string( "into_group" ) ) {
if( up.has_string( "into" ) ) {
jo.throw_error_at( "upgrades", "Cannot specify both into_group and into." );
}
mandatory( up, was_loaded, "into_group", upgrade_group, string_id_reader<::MonsterGroup> {} );
upgrade_into = mtype_id::NULL_ID();
} else if( up.has_string( "into" ) ) {
mandatory( up, was_loaded, "into", upgrade_into, string_id_reader<::mtype> {} );
upgrade_group = mongroup_id::NULL_ID();
}
bool multi = !!upgrade_multi_range;
optional( up, was_loaded, "multiple_spawns", multi, false );
if( multi && jo.has_bool( "multiple_spawns" ) ) {
mandatory( up, was_loaded, "spawn_range", upgrade_multi_range );
} else if( multi ) {
optional( up, was_loaded, "spawn_range", upgrade_multi_range );
} else {
jo.get_int( "spawn_range", 0 ); // ignore if defined
}
optional( up, was_loaded, "despawn_when_null", upgrade_null_despawn, false );
upgrades = true;
}
//Reproduction
if( jo.has_member( "reproduction" ) ) {
JsonObject repro = jo.get_object( "reproduction" );
optional( repro, was_loaded, "baby_count", baby_count, -1 );
if( repro.has_int( "baby_timer" ) ) {
baby_timer = time_duration::from_days( repro.get_int( "baby_timer" ) );
} else if( repro.has_string( "baby_timer" ) ) {
baby_timer = read_from_json_string<time_duration>( repro.get_member( "baby_timer" ),
time_duration::units );
}
optional( repro, was_loaded, "baby_monster", baby_monster, string_id_reader<::mtype> {},
mtype_id::NULL_ID() );
optional( repro, was_loaded, "baby_monster_group", baby_monster_group, mongroup_id::NULL_ID() );
optional( repro, was_loaded, "baby_egg", baby_egg, string_id_reader<::itype> {},
itype_id::NULL_ID() );
reproduces = true;
}
if( jo.has_member( "baby_flags" ) ) {
// Because this determines mating season and some monsters have a mating season but not in-game offspring, declare this separately
baby_flags.clear();
for( const std::string line : jo.get_array( "baby_flags" ) ) {
baby_flags.push_back( line );
}
}
if( jo.has_member( "biosignature" ) ) {
JsonObject biosig = jo.get_object( "biosignature" );
if( biosig.has_int( "biosig_timer" ) ) {
biosig_timer = time_duration::from_days( biosig.get_int( "biosig_timer" ) );
} else if( biosig.has_string( "biosig_timer" ) ) {
biosig_timer = read_from_json_string<time_duration>( biosig.get_member( "biosig_timer" ),
time_duration::units );
}
optional( biosig, was_loaded, "biosig_item", biosig_item, string_id_reader<::itype> {},
itype_id::NULL_ID() );
biosignatures = true;
}
optional( jo, was_loaded, "burn_into", burn_into, string_id_reader<::mtype> {},
mtype_id::NULL_ID() );
if( jo.has_member( "flags" ) ) {
pre_flags_.clear();
if( jo.has_string( "flags" ) ) {
pre_flags_.emplace( jo.get_string( "flags" ) );
} else {
for( JsonValue jval : jo.get_array( "flags" ) ) {
pre_flags_.emplace( jval.get_string() );
}
}
} else {
if( jo.has_member( "extend" ) ) {
JsonObject exjo = jo.get_object( "extend" );
exjo.allow_omitted_members();
if( exjo.has_member( "flags" ) ) {
if( exjo.has_string( "flags" ) ) {
pre_flags_.emplace( exjo.get_string( "flags" ) );
} else {
for( JsonValue jval : exjo.get_array( "flags" ) ) {
pre_flags_.emplace( jval.get_string() );
}
}
}
}
if( jo.has_member( "delete" ) ) {
JsonObject deljo = jo.get_object( "delete" );
deljo.allow_omitted_members();
if( deljo.has_member( "flags" ) ) {
if( deljo.has_string( "flags" ) ) {
auto iter = pre_flags_.find( mon_flag_str_id( deljo.get_string( "flags" ) ) );
if( iter != pre_flags_.end() ) {
pre_flags_.erase( iter );
}
} else {
for( JsonValue jval : deljo.get_array( "flags" ) ) {
auto iter = pre_flags_.find( mon_flag_str_id( jval.get_string() ) );
if( iter != pre_flags_.end() ) {
pre_flags_.erase( iter );
}
}
}
}
}
}
// Can't calculate yet - we want all flags first
optional( jo, was_loaded, "bash_skill", bash_skill, -1 );
const auto trigger_reader = enum_flags_reader<mon_trigger> { "monster trigger" };
optional( jo, was_loaded, "anger_triggers", anger, trigger_reader );
optional( jo, was_loaded, "placate_triggers", placate, trigger_reader );
optional( jo, was_loaded, "fear_triggers", fear, trigger_reader );
if( jo.has_member( "path_settings" ) ) {
JsonObject jop = jo.get_object( "path_settings" );
// Here rather than in pathfinding.cpp because we want monster-specific defaults and was_loaded
optional( jop, was_loaded, "max_dist", path_settings.max_dist, 0 );
optional( jop, was_loaded, "max_length", path_settings.max_length, -1 );
optional( jop, was_loaded, "bash_strength", path_settings.bash_strength, -1 );
optional( jop, was_loaded, "allow_open_doors", path_settings.allow_open_doors, false );
optional( jop, was_loaded, "avoid_traps", path_settings.avoid_traps, false );
optional( jop, was_loaded, "allow_climb_stairs", path_settings.allow_climb_stairs, true );
optional( jop, was_loaded, "avoid_sharp", path_settings.avoid_sharp, false );
optional( jop, was_loaded, "avoid_dangerous_fields", path_settings.avoid_dangerous_fields, false );
}
}
void MonsterGenerator::load_species( const JsonObject &jo, const std::string &src )
{
mon_species->load( jo, src );
}
void species_type::load( const JsonObject &jo, const std::string_view )
{
optional( jo, was_loaded, "description", description );
optional( jo, was_loaded, "footsteps", footsteps, to_translation( "footsteps." ) );
if( jo.has_member( "flags" ) ) {
flags.clear();
if( jo.has_string( "flags" ) ) {
flags.emplace( jo.get_string( "flags" ) );
} else {
for( JsonValue jval : jo.get_array( "flags" ) ) {
flags.emplace( jval.get_string() );
}
}
} else {
if( jo.has_member( "extend" ) ) {
JsonObject exjo = jo.get_object( "extend" );
exjo.allow_omitted_members();
if( exjo.has_member( "flags" ) ) {
if( exjo.has_string( "flags" ) ) {
flags.emplace( exjo.get_string( "flags" ) );
} else {
for( JsonValue jval : exjo.get_array( "flags" ) ) {
flags.emplace( jval.get_string() );
}
}
}
}
if( jo.has_member( "delete" ) ) {
JsonObject deljo = jo.get_object( "delete" );
deljo.allow_omitted_members();
if( deljo.has_member( "flags" ) ) {
if( deljo.has_string( "flags" ) ) {
auto iter = flags.find( mon_flag_str_id( deljo.get_string( "flags" ) ) );
if( iter != flags.end() ) {
flags.erase( iter );
}
} else {
for( JsonValue jval : deljo.get_array( "flags" ) ) {
auto iter = flags.find( mon_flag_str_id( jval.get_string() ) );
if( iter != flags.end() ) {
flags.erase( iter );
}
}
}
}
}
}
const auto trigger_reader = enum_flags_reader<mon_trigger> { "monster trigger" };
optional( jo, was_loaded, "anger_triggers", anger, trigger_reader );
optional( jo, was_loaded, "placate_triggers", placate, trigger_reader );
optional( jo, was_loaded, "fear_triggers", fear, trigger_reader );
optional( jo, was_loaded, "bleeds", bleeds, string_id_reader<::field_type> {}, fd_null );
}
void mon_flag::load_mon_flags( const JsonObject &jo, const std::string &src )
{
mon_flags.load( jo, src );
}
void mon_flag::load( const JsonObject &jo, std::string_view )
{
mandatory( jo, was_loaded, "id", id );
}
const std::vector<mtype> &MonsterGenerator::get_all_mtypes() const
{
return mon_templates->get_all();
}
const std::vector<mon_flag> &mon_flag::get_all()
{
return mon_flags.get_all();
}
void mon_flag::reset()
{
mon_flags.reset();
}
mtype_id MonsterGenerator::get_valid_hallucination() const
{
return random_entry( hallucination_monsters );
}
class mattack_hardcoded_wrapper : public mattack_actor
{
private:
mon_action_attack cpp_function;
public:
mattack_hardcoded_wrapper( const mattack_id &id, const mon_action_attack f )
: mattack_actor( id )
, cpp_function( f ) { }
~mattack_hardcoded_wrapper() override = default;
bool call( monster &m ) const override {
return cpp_function( &m );
}
std::unique_ptr<mattack_actor> clone() const override {
return std::make_unique<mattack_hardcoded_wrapper>( *this );
}
void load_internal( const JsonObject &, const std::string & ) override {}
};
mtype_special_attack::mtype_special_attack( const mattack_id &id, const mon_action_attack f )
: mtype_special_attack( std::make_unique<mattack_hardcoded_wrapper>( id, f ) ) {}
void MonsterGenerator::add_hardcoded_attack( const std::string &type, const mon_action_attack f )
{
add_attack( mtype_special_attack( type, f ) );
}
void MonsterGenerator::add_attack( std::unique_ptr<mattack_actor> ptr )
{
add_attack( mtype_special_attack( std::move( ptr ) ) );
}
void MonsterGenerator::add_attack( const mtype_special_attack &wrapper )
{
if( attack_map.count( wrapper->id ) > 0 ) {
if( test_mode ) {
debugmsg( "Overwriting monster attack with id %s", wrapper->id.c_str() );
}
attack_map.erase( wrapper->id );
}
attack_map.emplace( wrapper->id, wrapper );
}
mtype_special_attack MonsterGenerator::create_actor( const JsonObject &obj,
const std::string &src ) const
{
// Legacy support: tolerate attack types being specified as the type
const std::string type = obj.get_string( "type", "monster_attack" );
const std::string attack_type = obj.get_string( "attack_type", type );
if( type != "monster_attack" && attack_type != type ) {
obj.throw_error_at(
"type",
R"(Specifying "attack_type" is only allowed when "type" is "monster_attack" or not specified)" );
}
std::unique_ptr<mattack_actor> new_attack;
if( attack_type == "monster_attack" ) {
const std::string id = obj.get_string( "id" );
const auto &iter = attack_map.find( id );
if( iter == attack_map.end() ) {
obj.throw_error_at( "type", "Monster attacks must specify type and/or id" );
}
new_attack = iter->second->clone();
} else if( attack_type == "leap" ) {
new_attack = std::make_unique<leap_actor>();
} else if( attack_type == "melee" ) {
new_attack = std::make_unique<melee_actor>();
} else if( attack_type == "bite" ) {
new_attack = std::make_unique<bite_actor>();
} else if( attack_type == "gun" ) {
new_attack = std::make_unique<gun_actor>();
} else if( attack_type == "spell" ) {
new_attack = std::make_unique<mon_spellcasting_actor>();
} else {
obj.throw_error_at( "attack_type", "unknown monster attack" );
}
new_attack->load( obj, src );
return mtype_special_attack( std::move( new_attack ) );
}
void mattack_actor::load( const JsonObject &jo, const std::string &src )
{
// Legacy support
if( !jo.has_string( "id" ) ) {
id = jo.get_string( "type" );
} else {
// Loading ids can't be strict at the moment, since it has to match the stored version
assign( jo, "id", id, false );
}
cooldown = get_dbl_or_var( jo, "cooldown", false, 0.0 );
load_internal( jo, src );
// Set was_loaded manually because we don't have generic_factory to do it for us
was_loaded = true;
}
void MonsterGenerator::load_monster_attack( const JsonObject &jo, const std::string &src )
{
add_attack( create_actor( jo, src ) );
}
void mtype::add_special_attack( const JsonObject &obj, const std::string &src )
{
mtype_special_attack new_attack = MonsterGenerator::generator().create_actor( obj, src );
if( special_attacks.count( new_attack->id ) > 0 ) {
special_attacks.erase( new_attack->id );
const auto iter = std::find( special_attacks_names.begin(), special_attacks_names.end(),
new_attack->id );
if( iter != special_attacks_names.end() ) {
special_attacks_names.erase( iter );
}
debugmsg( "%s specifies more than one attack of (sub)type %s, ignoring all but the last. Add different `id`s to each attack of this type to prevent this.",
id.c_str(), new_attack->id.c_str() );
}
special_attacks.emplace( new_attack->id, new_attack );
special_attacks_names.push_back( new_attack->id );
}
void mtype::add_special_attack( const JsonArray &inner, const std::string_view )
{
MonsterGenerator &gen = MonsterGenerator::generator();
const std::string name = inner.get_string( 0 );
const auto iter = gen.attack_map.find( name );
if( iter == gen.attack_map.end() ) {
inner.throw_error( "Invalid special_attacks" );
}
if( special_attacks.count( name ) > 0 ) {
special_attacks.erase( name );
const auto iter = std::find( special_attacks_names.begin(), special_attacks_names.end(), name );
if( iter != special_attacks_names.end() ) {
special_attacks_names.erase( iter );
}
if( test_mode ) {
debugmsg( "%s specifies more than one attack of (sub)type %s, ignoring all but the last",
id.c_str(), name );
}
}
mtype_special_attack new_attack = mtype_special_attack( iter->second );
if( inner.has_array( 1 ) ) {
new_attack.actor->cooldown.min = get_dbl_or_var_part( inner.get_array( 1 )[0] );
new_attack.actor->cooldown.max = get_dbl_or_var_part( inner.get_array( 1 )[1] );
} else {
new_attack.actor->cooldown.min = get_dbl_or_var_part( inner[1] );
}
special_attacks.emplace( name, new_attack );
special_attacks_names.push_back( name );
}
void mtype::add_special_attacks( const JsonObject &jo, const std::string_view member,
const std::string &src )
{
if( !jo.has_array( member ) ) {
return;
}
for( const JsonValue entry : jo.get_array( member ) ) {
if( entry.test_array() ) {
add_special_attack( entry.get_array(), src );
} else if( entry.test_object() ) {
add_special_attack( entry.get_object(), src );
} else {
entry.throw_error( "array element is neither array nor object." );
}
}
}
void mtype::remove_special_attacks( const JsonObject &jo, const std::string_view member_name,
const std::string_view )
{
for( const std::string &name : jo.get_tags( member_name ) ) {
special_attacks.erase( name );
const auto iter = std::find( special_attacks_names.begin(), special_attacks_names.end(), name );
if( iter != special_attacks_names.end() ) {
special_attacks_names.erase( iter );
}
}
}
void mtype::add_regeneration_modifier( const JsonArray &inner, const std::string_view )
{
const std::string effect_name = inner.get_string( 0 );
const efftype_id effect( effect_name );
//TODO: if invalid effect, throw error
// inner.throw_error( "Invalid regeneration_modifiers" );
if( regeneration_modifiers.count( effect ) > 0 ) {
regeneration_modifiers.erase( effect );
if( test_mode ) {
debugmsg( "%s specifies more than one regeneration modifier for effect %s, ignoring all but the last",
id.c_str(), effect_name );
}
}
int amount = inner.get_int( 1 );
regeneration_modifiers.emplace( effect, amount );
}
void mtype::add_regeneration_modifiers( const JsonObject &jo, const std::string_view member,
const std::string_view src )
{
if( !jo.has_array( member ) ) {
return;
}
for( const JsonValue entry : jo.get_array( member ) ) {
if( entry.test_array() ) {
add_regeneration_modifier( entry.get_array(), src );
// TODO: add support for regeneration_modifer objects
//} else if ( entry.test_object() ) {
// add_regeneration_modifier( entry.get_object(), src );
} else {
entry.throw_error( "array element is not an array " );
}
}
}
void mtype::remove_regeneration_modifiers( const JsonObject &jo, const std::string_view member_name,
const std::string_view )
{
for( const std::string &name : jo.get_tags( member_name ) ) {
const efftype_id effect( name );
regeneration_modifiers.erase( effect );
}
}
void MonsterGenerator::check_monster_definitions() const
{
for( const mtype &mon : mon_templates->get_all() ) {
if( !mon.src.empty() && mon.src.back().second.str() == "tlg" ) {
std::string mon_id = mon.id.str();
std::string suffix_id = mon_id.substr( 0, mon_id.find( '_' ) );
if( suffix_id != "mon" && suffix_id != "pseudo" ) {
debugmsg( "monster %s is missing mon_ (or pseudo_) prefix from id", mon.id.c_str() );
}
}
if( mon.harvest.is_null() && !mon.has_flag( mon_flag_ELECTRONIC ) && !mon.id.is_null() ) {
debugmsg( "monster %s has no harvest entry", mon.id.c_str(), mon.harvest.c_str() );
}
if( mon.has_flag( mon_flag_MILKABLE ) && mon.starting_ammo.empty() ) {
debugmsg( "monster %s is flagged milkable, but has no starting ammo", mon.id.c_str() );
}
if( mon.has_flag( mon_flag_MILKABLE ) && !mon.starting_ammo.empty() &&
!item( mon.starting_ammo.begin()->first ).made_of( phase_id::LIQUID ) ) {
debugmsg( "monster %s is flagged milkable, but starting ammo %s is not a liquid type",
mon.id.c_str(), mon.starting_ammo.begin()->first.str() );
}
if( mon.has_flag( mon_flag_MILKABLE ) && mon.starting_ammo.size() > 1 ) {
debugmsg( "monster %s is flagged milkable, but has multiple starting_ammo defined",
mon.id.c_str() );
}
for( const species_id &spec : mon.species ) {
if( !spec.is_valid() ) {
debugmsg( "monster %s has invalid species %s", mon.id.c_str(), spec.c_str() );
}
}
if( !mon.death_drops.is_empty() && !item_group::group_is_defined( mon.death_drops ) ) {
debugmsg( "monster %s has unknown death drop item group: %s", mon.id.c_str(),
mon.death_drops.c_str() );
}
for( const auto &m : mon.mat ) {
if( m.first.str() == "null" || !m.first.is_valid() ) {
debugmsg( "monster %s has unknown material: %s", mon.id.c_str(), m.first.c_str() );
}
}
if( !mon.revert_to_itype.is_empty() && !item::type_is_defined( mon.revert_to_itype ) ) {
debugmsg( "monster %s has unknown revert_to_itype: %s", mon.id.c_str(),
mon.revert_to_itype.c_str() );
}
if( !mon.zombify_into.is_empty() && !mon.zombify_into.is_valid() ) {
debugmsg( "monster %s has unknown zombify_into: %s", mon.id.c_str(),
mon.zombify_into.c_str() );
}
if( !mon.fungalize_into.is_empty() && !mon.fungalize_into.is_valid() ) {
debugmsg( "monster %s has unknown fungalize_into: %s", mon.id.c_str(),
mon.fungalize_into.c_str() );
}
if( !mon.picture_id.is_empty() && !mon.picture_id.is_valid() ) {
debugmsg( "monster %s has unknown ascii_picture: %s", mon.id.c_str(),
mon.picture_id.c_str() );
}
if( !mon.mech_weapon.is_empty() && !item::type_is_defined( mon.mech_weapon ) ) {
debugmsg( "monster %s has unknown mech_weapon: %s", mon.id.c_str(),
mon.mech_weapon.c_str() );
}
if( !mon.mech_battery.is_empty() && !item::type_is_defined( mon.mech_battery ) ) {
debugmsg( "monster %s has unknown mech_battery: %s", mon.id.c_str(),
mon.mech_battery.c_str() );
}
if( !mon.mount_items.tied.is_empty() && !item::type_is_defined( mon.mount_items.tied ) ) {
debugmsg( "monster %s has unknown mount_items.tied: %s", mon.id.c_str(),
mon.mount_items.tied.c_str() );
}
if( !mon.mount_items.tack.is_empty() && !item::type_is_defined( mon.mount_items.tack ) ) {
debugmsg( "monster %s has unknown mount_items.tack: %s", mon.id.c_str(),
mon.mount_items.tack.c_str() );
}
if( !mon.mount_items.armor.is_empty() && !item::type_is_defined( mon.mount_items.armor ) ) {
debugmsg( "monster %s has unknown mount_items.armor: %s", mon.id.c_str(),
mon.mount_items.armor.c_str() );
}
if( !mon.mount_items.storage.is_empty() && !item::type_is_defined( mon.mount_items.storage ) ) {
debugmsg( "monster %s has unknown mount_items.storage: %s", mon.id.c_str(),
mon.mount_items.storage.c_str() );
}
if( !mon.harvest.is_valid() ) {
debugmsg( "monster %s has invalid harvest_entry: %s", mon.id.c_str(), mon.harvest.c_str() );
}
if( !mon.dissect.is_empty() && !mon.dissect.is_valid() ) {
debugmsg( "monster %s has invalid dissection harvest_entry: %s", mon.id.c_str(),
mon.dissect.c_str() );
}
if( mon.has_flag( mon_flag_WATER_CAMOUFLAGE ) && !monster( mon.id ).can_submerge() ) {
debugmsg( "monster %s has WATER_CAMOUFLAGE but cannot submerge", mon.id.c_str() );
}
for( const scenttype_id &s_id : mon.scents_tracked ) {
if( !s_id.is_empty() && !s_id.is_valid() ) {
debugmsg( "monster %s has unknown scents_tracked %s", mon.id.c_str(), s_id.c_str() );
}
}
for( const scenttype_id &s_id : mon.scents_ignored ) {
if( !s_id.is_empty() && !s_id.is_valid() ) {
debugmsg( "monster %s has unknown scents_ignored %s", mon.id.c_str(), s_id.c_str() );
}
}
for( const std::pair<const itype_id, int> &s : mon.starting_ammo ) {
if( !item::type_is_defined( s.first ) ) {
debugmsg( "starting ammo %s of monster %s is unknown", s.first.c_str(), mon.id.c_str() );
}
}
for( const mon_effect_data &e : mon.atk_effs ) {
if( !e.id.is_valid() ) {
debugmsg( "attack effect %s of monster %s is unknown", e.id.c_str(), mon.id.c_str() );
}
}
for( const std::pair<const emit_id, time_duration> &e : mon.emit_fields ) {
const emit_id emid = e.first;
if( !emid.is_valid() ) {
debugmsg( "monster %s has invalid emit source %s", mon.id.c_str(), emid.c_str() );
}
}
if( mon.upgrades ) {
if( mon.half_life < 0 && mon.age_grow < 0 ) {
debugmsg( "half_life %d and age_grow %d (<0) of monster %s is invalid",
mon.half_life, mon.age_grow, mon.id.c_str() );
}
if( !mon.upgrade_into && !mon.upgrade_group ) {
debugmsg( "no into nor into_group defined for monster %s", mon.id.c_str() );
}
if( mon.upgrade_into && mon.upgrade_group ) {
debugmsg( "both into and into_group defined for monster %s", mon.id.c_str() );
}
if( !mon.upgrade_into.is_valid() ) {
debugmsg( "upgrade_into %s of monster %s is not a valid monster id",
mon.upgrade_into.c_str(), mon.id.c_str() );
}
if( !mon.upgrade_group.is_valid() ) {
debugmsg( "upgrade_group %s of monster %s is not a valid monster group id",
mon.upgrade_group.c_str(), mon.id.c_str() );
}
}
if( mon.reproduces ) {
if( !mon.baby_timer || *mon.baby_timer <= 0_seconds ) {
debugmsg( "Time between reproductions (%d) is invalid for %s",
mon.baby_timer ? to_turns<int>( *mon.baby_timer ) : -1, mon.id.c_str() );
}
if( mon.baby_count < 1 ) {
debugmsg( "Number of children (%d) is invalid for %s",
mon.baby_count, mon.id.c_str() );
}
if( !mon.baby_monster && mon.baby_egg.is_null() && !mon.baby_monster_group ) {
debugmsg( "No baby, baby group, or egg defined for monster %s", mon.id.c_str() );
}
if( mon.baby_monster && !mon.baby_egg.is_null() ) {
debugmsg( "Both an egg and a live birth baby are defined for %s", mon.id.c_str() );
}
if( mon.baby_monster_group && !mon.baby_egg.is_null() ) {
debugmsg( "Both an egg and a baby group are defined for %s", mon.id.c_str() );
}
if( mon.baby_monster && mon.baby_monster_group ) {
debugmsg( "Both baby and a baby group are defined for %s", mon.id.c_str() );
}
if( !mon.baby_monster.is_valid() ) {
debugmsg( "baby_monster %s of monster %s is not a valid monster id",
mon.baby_monster.c_str(), mon.id.c_str() );
}
if( !mon.baby_monster_group.is_valid() ) {
debugmsg( "baby_monster_group %s of monster %s is not a valid monster group id",
mon.baby_monster.c_str(), mon.id.c_str() );
}
if( !item::type_is_defined( mon.baby_egg ) ) {
debugmsg( "item_id %s of monster %s is not a valid item id",
mon.baby_egg.c_str(), mon.id.c_str() );
}
}
if( mon.biosignatures ) {
if( !mon.biosig_timer || *mon.biosig_timer <= 0_seconds ) {
debugmsg( "Time between biosignature drops (%d) is invalid for %s",
mon.biosig_timer ? to_turns<int>( *mon.biosig_timer ) : -1, mon.id.c_str() );
}
if( mon.biosig_item.is_null() ) {
debugmsg( "No biosignature drop defined for monster %s", mon.id.c_str() );
}
if( !item::type_is_defined( mon.biosig_item ) ) {
debugmsg( "item_id %s of monster %s is not a valid item id",
mon.biosig_item.c_str(), mon.id.c_str() );
}
}
for( const std::pair<const damage_type_id, float> &dt : mon.armor.resist_vals ) {
if( !dt.first.is_valid() ) {
debugmsg( "Invalid armor type \"%s\" for monster %s", dt.first.c_str(), mon.id.c_str() );
}
}
for( const std::pair<const std::string, mtype_special_attack> &spatk : mon.special_attacks ) {
const melee_actor *atk = dynamic_cast<const melee_actor *>( &*spatk.second );
if( !atk ) {
continue;
}
for( const damage_unit &dt : atk->damage_max_instance.damage_units ) {
if( !dt.type.is_valid() ) {
debugmsg( "Invalid monster attack damage type \"%s\" for monster %s", dt.type.c_str(),
mon.id.c_str() );
}
}
}
mon.weakpoints.check();
}
}
void monster_death_effect::load( const JsonObject &jo )
{
optional( jo, was_loaded, "message", death_message, to_translation( "The %s dies!" ) );
optional( jo, was_loaded, "effect", sp );
optional( jo, was_loaded, "corpse_type", corpse_type, mdeath_type::NORMAL );
optional( jo, was_loaded, "eoc", eoc );
}
void monster_death_effect::deserialize( const JsonObject &data )
{
load( data );
}
void pet_food_data::load( const JsonObject &jo )
{
mandatory( jo, was_loaded, "food", food );
optional( jo, was_loaded, "feed", feed );
optional( jo, was_loaded, "pet", pet );
}
void pet_food_data::deserialize( const JsonObject &data )
{
load( data );
}
| 0 | 0.971047 | 1 | 0.971047 | game-dev | MEDIA | 0.881705 | game-dev | 0.981277 | 1 | 0.981277 |
magefree/mage | 1,429 | Mage.Sets/src/mage/cards/g/GraveExchange.java | package mage.cards.g;
import mage.abilities.effects.common.ReturnFromGraveyardToHandTargetEffect;
import mage.abilities.effects.common.SacrificeEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.filter.StaticFilters;
import mage.target.TargetPlayer;
import mage.target.common.TargetCardInYourGraveyard;
import mage.target.targetpointer.SecondTargetPointer;
import java.util.UUID;
/**
* @author North
*/
public final class GraveExchange extends CardImpl {
public GraveExchange(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{4}{B}{B}");
// Return target creature card from your graveyard to your hand.
this.getSpellAbility().addEffect(new ReturnFromGraveyardToHandTargetEffect());
this.getSpellAbility().addTarget(new TargetCardInYourGraveyard(StaticFilters.FILTER_CARD_CREATURE_YOUR_GRAVEYARD));
// Target player sacrifices a creature.
this.getSpellAbility().addEffect(new SacrificeEffect(StaticFilters.FILTER_PERMANENT_CREATURE, 1, "Target player")
.setTargetPointer(new SecondTargetPointer()));
this.getSpellAbility().addTarget(new TargetPlayer());
}
private GraveExchange(final GraveExchange card) {
super(card);
}
@Override
public GraveExchange copy() {
return new GraveExchange(this);
}
}
| 0 | 0.972636 | 1 | 0.972636 | game-dev | MEDIA | 0.960662 | game-dev | 0.872198 | 1 | 0.872198 |
Field-Robotics-Lab/dave | 23,018 | gazebo/dave_gazebo_world_plugins/src/ocean_current_world_plugin.cc | // Copyright (c) 2016 The UUV Simulator Authors.
// 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.
/// \file ocean_current_world_plugin.cc
#include <math.h>
#include <dave_gazebo_world_plugins/ocean_current_world_plugin.h>
#include <StratifiedCurrentVelocity.pb.h>
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <gazebo/gazebo.hh>
#include <gazebo/msgs/msgs.hh>
#include <gazebo/physics/Link.hh>
#include <gazebo/physics/Model.hh>
#include <gazebo/physics/PhysicsEngine.hh>
#include <gazebo/physics/World.hh>
#include <gazebo/transport/TransportTypes.hh>
#include <sdf/sdf.hh>
namespace gazebo {
/////////////////////////////////////////////////
UnderwaterCurrentPlugin::UnderwaterCurrentPlugin()
{
// Doing nothing for now
}
/////////////////////////////////////////////////
UnderwaterCurrentPlugin::~UnderwaterCurrentPlugin()
{
#if GAZEBO_MAJOR_VERSION >= 8
this->updateConnection.reset();
#else
event::Events::DisconnectWorldUpdateBegin(this->updateConnection);
#endif
}
/////////////////////////////////////////////////
void UnderwaterCurrentPlugin::
Load(physics::WorldPtr _world, sdf::ElementPtr _sdf)
{
GZ_ASSERT(_world != NULL, "World pointer is invalid");
GZ_ASSERT(_sdf != NULL, "SDF pointer is invalid");
this->world = _world;
this->sdf = _sdf;
// Read the namespace for topics and services
this->ns = _sdf->Get<std::string>("namespace");
gzmsg << "Loading underwater world..." << std::endl;
// Initializing the transport node
this->node = transport::NodePtr(new transport::Node());
#if GAZEBO_MAJOR_VERSION >= 8
this->node->Init(this->world->Name());
#else
this->node->Init(this->world->GetName());
#endif
// Initialize the time update
#if GAZEBO_MAJOR_VERSION >= 8
this->lastUpdate = this->world->SimTime();
#else
this->lastUpdate = this->world->GetSimTime();
#endif
this->LoadGlobalCurrentConfig();
this->LoadStratifiedCurrentDatabase();
if (this->sdf->HasElement("tidal_oscillation"))
{
this->LoadTidalOscillationDatabase();
}
// Connect the update event
this->updateConnection = event::Events::ConnectWorldUpdateBegin(
boost::bind(&UnderwaterCurrentPlugin::Update,
this, _1));
gzmsg << "Underwater current plugin loaded!" << std::endl
<< "\tWARNING: Current velocity calculated in the ENU frame"
<< std::endl;
}
/////////////////////////////////////////////////
void UnderwaterCurrentPlugin::Init()
{
// Doing nothing for now
}
/////////////////////////////////////////////////
void UnderwaterCurrentPlugin::Update(const common::UpdateInfo & /** _info */)
{
#if GAZEBO_MAJOR_VERSION >= 8
common::Time time = this->world->SimTime();
#else
common::Time time = this->world->GetSimTime();
#endif
// Calculate the flow velocity and the direction using the Gauss-Markov
// model
// Update current velocity
double currentVelMag = this->currentVelModel.Update(time.Double());
// Update current horizontal direction around z axis of flow frame
double horzAngle = this->currentHorzAngleModel.Update(time.Double());
// Update current horizontal direction around z axis of flow frame
double vertAngle = this->currentVertAngleModel.Update(time.Double());
// Generating the current velocity vector as in the NED frame
this->currentVelocity = ignition::math::Vector3d(
currentVelMag * cos(horzAngle) * cos(vertAngle),
currentVelMag * sin(horzAngle) * cos(vertAngle),
currentVelMag * sin(vertAngle));
// Generate the depth-specific velocities
this->currentStratifiedVelocity.clear();
for (int i = 0; i < this->stratifiedDatabase.size(); i++)
{
double depth = this->stratifiedDatabase[i].Z();
currentVelMag =
this->stratifiedCurrentModels[i][0].Update(time.Double());
horzAngle =
this->stratifiedCurrentModels[i][1].Update(time.Double());
vertAngle =
this->stratifiedCurrentModels[i][2].Update(time.Double());
ignition::math::Vector4d depthVel(
currentVelMag * cos(horzAngle) * cos(vertAngle),
currentVelMag * sin(horzAngle) * cos(vertAngle),
currentVelMag * sin(vertAngle),
depth);
this->currentStratifiedVelocity.push_back(depthVel);
}
// Update time stamp
this->lastUpdate = time;
this->PublishCurrentVelocity();
this->PublishStratifiedCurrentVelocity();
}
/////////////////////////////////////////////////
void UnderwaterCurrentPlugin::LoadGlobalCurrentConfig()
{
// NOTE: The plugin currently requires stratified current, so the
// global current set up in this method is potentially
// inconsistent or redundant.
// Consider setting it up as one or the other, but not both?
// Retrieve the velocity configuration, if existent
GZ_ASSERT(this->sdf->HasElement("constant_current"),
"Current configuration not available");
sdf::ElementPtr currentVelocityParams = this->sdf->GetElement(
"constant_current");
// Read the topic names from the SDF file
if (currentVelocityParams->HasElement("topic"))
this->currentVelocityTopic =
currentVelocityParams->Get<std::string>("topic");
else
this->currentVelocityTopic = "current_velocity";
GZ_ASSERT(!this->currentVelocityTopic.empty(),
"Empty ocean current velocity topic");
if (currentVelocityParams->HasElement("velocity"))
{
sdf::ElementPtr elem = currentVelocityParams->GetElement("velocity");
if (elem->HasElement("mean"))
this->currentVelModel.mean = elem->Get<double>("mean");
if (elem->HasElement("min"))
this->currentVelModel.min = elem->Get<double>("min");
if (elem->HasElement("max"))
this->currentVelModel.max = elem->Get<double>("max");
if (elem->HasElement("mu"))
this->currentVelModel.mu = elem->Get<double>("mu");
if (elem->HasElement("noiseAmp"))
this->currentVelModel.noiseAmp = elem->Get<double>("noiseAmp");
GZ_ASSERT(this->currentVelModel.min < this->currentVelModel.max,
"Invalid current velocity limits");
GZ_ASSERT(this->currentVelModel.mean >= this->currentVelModel.min,
"Mean velocity must be greater than minimum");
GZ_ASSERT(this->currentVelModel.mean <= this->currentVelModel.max,
"Mean velocity must be smaller than maximum");
GZ_ASSERT(this->currentVelModel.mu >= 0 && this->currentVelModel.mu < 1,
"Invalid process constant");
GZ_ASSERT(this->currentVelModel.noiseAmp < 1 &&
this->currentVelModel.noiseAmp >= 0,
"Noise amplitude has to be smaller than 1");
}
this->currentVelModel.var = this->currentVelModel.mean;
gzmsg << "Current velocity [m/s] Gauss-Markov process model:" << std::endl;
this->currentVelModel.Print();
if (currentVelocityParams->HasElement("horizontal_angle"))
{
sdf::ElementPtr elem =
currentVelocityParams->GetElement("horizontal_angle");
if (elem->HasElement("mean"))
this->currentHorzAngleModel.mean = elem->Get<double>("mean");
if (elem->HasElement("min"))
this->currentHorzAngleModel.min = elem->Get<double>("min");
if (elem->HasElement("max"))
this->currentHorzAngleModel.max = elem->Get<double>("max");
if (elem->HasElement("mu"))
this->currentHorzAngleModel.mu = elem->Get<double>("mu");
if (elem->HasElement("noiseAmp"))
this->currentHorzAngleModel.noiseAmp = elem->Get<double>("noiseAmp");
GZ_ASSERT(this->currentHorzAngleModel.min <
this->currentHorzAngleModel.max,
"Invalid current horizontal angle limits");
GZ_ASSERT(this->currentHorzAngleModel.mean >=
this->currentHorzAngleModel.min,
"Mean horizontal angle must be greater than minimum");
GZ_ASSERT(this->currentHorzAngleModel.mean <=
this->currentHorzAngleModel.max,
"Mean horizontal angle must be smaller than maximum");
GZ_ASSERT(this->currentHorzAngleModel.mu >= 0 &&
this->currentHorzAngleModel.mu < 1,
"Invalid process constant");
GZ_ASSERT(this->currentHorzAngleModel.noiseAmp < 1 &&
this->currentHorzAngleModel.noiseAmp >= 0,
"Noise amplitude for horizontal angle has to be between 0 and 1");
}
this->currentHorzAngleModel.var = this->currentHorzAngleModel.mean;
gzmsg <<
"Current velocity horizontal angle [rad] Gauss-Markov process model:"
<< std::endl;
this->currentHorzAngleModel.Print();
if (currentVelocityParams->HasElement("vertical_angle"))
{
sdf::ElementPtr elem = currentVelocityParams->GetElement("vertical_angle");
if (elem->HasElement("mean"))
this->currentVertAngleModel.mean = elem->Get<double>("mean");
if (elem->HasElement("min"))
this->currentVertAngleModel.min = elem->Get<double>("min");
if (elem->HasElement("max"))
this->currentVertAngleModel.max = elem->Get<double>("max");
if (elem->HasElement("mu"))
this->currentVertAngleModel.mu = elem->Get<double>("mu");
if (elem->HasElement("noiseAmp"))
this->currentVertAngleModel.noiseAmp = elem->Get<double>("noiseAmp");
GZ_ASSERT(this->currentVertAngleModel.min <
this->currentVertAngleModel.max, "Invalid current vertical angle limits");
GZ_ASSERT(this->currentVertAngleModel.mean >=
this->currentVertAngleModel.min,
"Mean vertical angle must be greater than minimum");
GZ_ASSERT(this->currentVertAngleModel.mean <=
this->currentVertAngleModel.max,
"Mean vertical angle must be smaller than maximum");
GZ_ASSERT(this->currentVertAngleModel.mu >= 0 &&
this->currentVertAngleModel.mu < 1,
"Invalid process constant");
GZ_ASSERT(this->currentVertAngleModel.noiseAmp < 1 &&
this->currentVertAngleModel.noiseAmp >= 0,
"Noise amplitude for vertical angle has to be between 0 and 1");
}
this->currentVertAngleModel.var = this->currentVertAngleModel.mean;
gzmsg <<
"Current velocity vertical angle [rad] Gauss-Markov process model:"
<< std::endl;
this->currentVertAngleModel.Print();
this->currentVelModel.lastUpdate = this->lastUpdate.Double();
this->currentHorzAngleModel.lastUpdate = this->lastUpdate.Double();
this->currentVertAngleModel.lastUpdate = this->lastUpdate.Double();
// Advertise the current velocity & stratified current velocity topics
this->publishers[this->currentVelocityTopic] =
this->node->Advertise<msgs::Vector3d>(
this->ns + "/" + this->currentVelocityTopic);
gzmsg << "Current velocity topic name: " <<
this->ns + "/" + this->currentVelocityTopic << std::endl;
}
/////////////////////////////////////////////////
void UnderwaterCurrentPlugin::LoadStratifiedCurrentDatabase()
{
GZ_ASSERT(this->sdf->HasElement("transient_current"),
"Transient current configuration not available");
sdf::ElementPtr transientCurrentParams = this->sdf->GetElement(
"transient_current");
if (transientCurrentParams->HasElement("topic_stratified"))
this->stratifiedCurrentVelocityTopic =
transientCurrentParams->Get<std::string>("topic_stratified");
else
this->stratifiedCurrentVelocityTopic = "stratified_current_velocity";
GZ_ASSERT(!this->stratifiedCurrentVelocityTopic.empty(),
"Empty stratified ocean current velocity topic");
// Read the depth dependent ocean current file path from the SDF file
if (transientCurrentParams->HasElement("databasefilePath"))
this->databaseFilePath =
transientCurrentParams->Get<std::string>("databasefilePath");
else
{
this->databaseFilePath = "transientOceanCurrentDatabase.csv";
}
GZ_ASSERT(!this->databaseFilePath.empty(),
"Empty stratified ocean current database file path");
gzmsg << this->databaseFilePath << std::endl;
#if GAZEBO_MAJOR_VERSION >= 8
this->lastUpdate = this->world->SimTime();
#else
this->lastUpdate = this->world->GetSimTime();
#endif
// Read database
std::ifstream csvFile;
std::string line;
csvFile.open(this->databaseFilePath);
if (!csvFile)
{
common::SystemPaths *paths = common::SystemPaths::Instance();
this->databaseFilePath =
paths->FindFile(this->databaseFilePath, true);
csvFile.open(this->databaseFilePath);
}
GZ_ASSERT(csvFile, "Stratified Ocean database file does not exist");
gzmsg << "Statified Ocean Current Database loaded : "
<< this->databaseFilePath << std::endl;
// skip the 3 lines
getline(csvFile, line);
getline(csvFile, line);
getline(csvFile, line);
while (getline(csvFile, line))
{
if (line.empty()) // skip empty lines:
{
continue;
}
std::istringstream iss(line);
std::string lineStream;
std::string::size_type sz;
std::vector <long double> row;
while (getline(iss, lineStream, ','))
{
row.push_back(stold(lineStream, &sz)); // convert to double
}
ignition::math::Vector3d read;
read.X() = row[0];
read.Y() = row[1];
read.Z() = row[2];
this->stratifiedDatabase.push_back(read);
// Create Gauss-Markov processes for the stratified currents
// Means are the database-specified magnitudes & angles, and
// the other values come from the constant current models
// TODO: Vertical angle currently set to 0 (not in database)
GaussMarkovProcess magnitudeModel;
magnitudeModel.mean = hypot(row[1], row[0]);
magnitudeModel.var = magnitudeModel.mean;
magnitudeModel.max = this->currentVelModel.max;
magnitudeModel.min = 0.0;
magnitudeModel.mu = this->currentVelModel.mu;
magnitudeModel.noiseAmp = this->currentVelModel.noiseAmp;
magnitudeModel.lastUpdate = this->lastUpdate.Double();
GaussMarkovProcess hAngleModel;
hAngleModel.mean = atan2(row[1], row[0]);
hAngleModel.var = hAngleModel.mean;
hAngleModel.max = M_PI;
hAngleModel.min = -M_PI;
hAngleModel.mu = this->currentHorzAngleModel.mu;
hAngleModel.noiseAmp = this->currentHorzAngleModel.noiseAmp;
hAngleModel.lastUpdate = this->lastUpdate.Double();
GaussMarkovProcess vAngleModel;
vAngleModel.mean = 0.0;
vAngleModel.var = vAngleModel.mean;
vAngleModel.max = M_PI/2.0;
vAngleModel.min = -M_PI/2.0;
vAngleModel.mu = this->currentVertAngleModel.mu;
vAngleModel.noiseAmp = this->currentVertAngleModel.noiseAmp;
vAngleModel.lastUpdate = this->lastUpdate.Double();
std::vector<GaussMarkovProcess> depthModels;
depthModels.push_back(magnitudeModel);
depthModels.push_back(hAngleModel);
depthModels.push_back(vAngleModel);
this->stratifiedCurrentModels.push_back(depthModels);
}
csvFile.close();
this->publishers[this->stratifiedCurrentVelocityTopic] =
this->node->Advertise<
dave_gazebo_world_plugins_msgs::msgs::StratifiedCurrentVelocity>(
this->ns + "/" + this->stratifiedCurrentVelocityTopic);
gzmsg << "Stratified current velocity topic name: " <<
this->ns + "/" + this->stratifiedCurrentVelocityTopic << std::endl;
}
/////////////////////////////////////////////////
void UnderwaterCurrentPlugin::LoadTidalOscillationDatabase()
{
this->tideFlag = true;
this->tidalHarmonicFlag = false;
sdf::ElementPtr tidalOscillationParams =
this->sdf->GetElement("tidal_oscillation");
sdf::ElementPtr tidalHarmonicParams;
// Read the tidal oscillation parameter from the SDF file
if (tidalOscillationParams->HasElement("databasefilePath"))
{
this->tidalFilePath =
tidalOscillationParams->Get<std::string>("databasefilePath");
gzmsg << "Tidal current database configuration found" << std::endl;
}
else
{
if (tidalOscillationParams->HasElement("harmonic_constituents"))
{
tidalHarmonicParams =
tidalOscillationParams->GetElement("harmonic_constituents");
gzmsg << "Tidal harmonic constituents "
<< "configuration found" << std::endl;
tidalHarmonicFlag = true;
}
else
this->tidalFilePath = ros::package::getPath("dave_worlds") +
"/worlds/ACT1951_predictionMaxSlack_2021-02-24.csv";
}
// Read the tidal oscillation direction from the SDF file
GZ_ASSERT(tidalOscillationParams->HasElement("mean_direction"),
"Tidal mean direction not defined");
if (tidalOscillationParams->HasElement("mean_direction"))
{
sdf::ElementPtr elem =
tidalOscillationParams->GetElement("mean_direction");
GZ_ASSERT(elem->HasElement("ebb"),
"Tidal mean ebb direction not defined");
this->ebbDirection = elem->Get<double>("ebb");
this->floodDirection = elem->Get<double>("flood");
GZ_ASSERT(elem->HasElement("flood"),
"Tidal mean flood direction not defined");
}
// Read the world start time (GMT) from the SDF file
GZ_ASSERT(tidalOscillationParams->HasElement("world_start_time_GMT"),
"World start time (GMT) not defined");
if (tidalOscillationParams->HasElement("world_start_time_GMT"))
{
sdf::ElementPtr elem =
tidalOscillationParams->GetElement("world_start_time_GMT");
GZ_ASSERT(elem->HasElement("day"),
"World start time (day) not defined");
this->world_start_time_day = elem->Get<double>("day");
GZ_ASSERT(elem->HasElement("month"),
"World start time (month) not defined");
this->world_start_time_month = elem->Get<double>("month");
GZ_ASSERT(elem->HasElement("year"),
"World start time (year) not defined");
this->world_start_time_year = elem->Get<double>("year");
GZ_ASSERT(elem->HasElement("hour"),
"World start time (hour) not defined");
this->world_start_time_hour = elem->Get<double>("hour");
if (elem->HasElement("minute"))
this->world_start_time_minute = elem->Get<double>("minute");
else
this->world_start_time_minute = 0;
}
if (tidalHarmonicFlag)
{
// Read harmonic constituents
GZ_ASSERT(tidalHarmonicParams->HasElement("M2"),
"Harcomnic constituents M2 not found");
sdf::ElementPtr M2Params = tidalHarmonicParams->GetElement("M2");
this->M2_amp = M2Params->Get<double>("amp");
this->M2_phase = M2Params->Get<double>("phase");
this->M2_speed = M2Params->Get<double>("speed");
GZ_ASSERT(tidalHarmonicParams->HasElement("S2"),
"Harcomnic constituents S2 not found");
sdf::ElementPtr S2Params = tidalHarmonicParams->GetElement("S2");
this->S2_amp = S2Params->Get<double>("amp");
this->S2_phase = S2Params->Get<double>("phase");
this->S2_speed = S2Params->Get<double>("speed");
GZ_ASSERT(tidalHarmonicParams->HasElement("N2"),
"Harcomnic constituents N2 not found");
sdf::ElementPtr N2Params = tidalHarmonicParams->GetElement("N2");
this->N2_amp = N2Params->Get<double>("amp");
this->N2_phase = N2Params->Get<double>("phase");
this->N2_speed = N2Params->Get<double>("speed");
gzmsg << "Tidal harmonic constituents loaded : " << std::endl;
gzmsg << "M2 amp: " << this->M2_amp << " phase: " << this->M2_phase
<< " speed: " << this->M2_speed << std::endl;
gzmsg << "S2 amp: " << this->S2_amp << " phase: " << this->S2_phase
<< " speed: " << this->S2_speed << std::endl;
gzmsg << "N2 amp: " << this->N2_amp << " phase: " << this->N2_phase
<< " speed: " << this->N2_speed << std::endl;
}
else
{
// Read database
std::ifstream csvFile;
std::string line;
csvFile.open(this->tidalFilePath);
if (!csvFile)
{
common::SystemPaths *paths = common::SystemPaths::Instance();
this->tidalFilePath =
paths->FindFile(this->tidalFilePath, true);
csvFile.open(this->tidalFilePath);
}
GZ_ASSERT(csvFile, "Tidal Oscillation database file does not exist");
gzmsg << "Tidal Oscillation Database loaded : "
<< this->tidalFilePath << std::endl;
// skip the first line
getline(csvFile, line);
while (getline(csvFile, line))
{
if (line.empty()) // skip empty lines:
{
continue;
}
std::istringstream iss(line);
std::string lineStream;
std::string::size_type sz;
std::vector<std::string> row;
std::array<int, 5> tmpDateArray;
while (getline(iss, lineStream, ','))
{
row.push_back(lineStream);
}
if (strcmp(row[1].c_str(), " slack")) // skip 'slack' category
{
tmpDateArray[0] = std::stoi(row[0].substr(0, 4));
tmpDateArray[1] = std::stoi(row[0].substr(5, 7));
tmpDateArray[2] = std::stoi(row[0].substr(8, 10));
tmpDateArray[3] = std::stoi(row[0].substr(11, 13));
tmpDateArray[4] = std::stoi(row[0].substr(14, 16));
this->dateGMT.push_back(tmpDateArray);
this->speedcmsec.push_back(stold(row[2], &sz));
}
}
csvFile.close();
// Eliminate data with same consecutive type
std::vector<int> duplicated;
for (int i = 0; i <this->dateGMT.size() - 1; i++)
{
// delete latter if same sign
if (((this->speedcmsec[i] > 0) - (this->speedcmsec[i] < 0))
== ((this->speedcmsec[i+1] > 0) - (this->speedcmsec[i+1] < 0)))
{
duplicated.push_back(i+1);
}
}
int eraseCount = 0;
for (int i = 0; i < duplicated.size(); i++)
{
this->dateGMT.erase(
this->dateGMT.begin()+duplicated[i]-eraseCount);
this->speedcmsec.erase(
this->speedcmsec.begin()+duplicated[i]-eraseCount);
eraseCount++;
}
}
}
/////////////////////////////////////////////////
void UnderwaterCurrentPlugin::PublishCurrentVelocity()
{
msgs::Vector3d currentVel;
msgs::Set(¤tVel, ignition::math::Vector3d(this->currentVelocity.X(),
this->currentVelocity.Y(),
this->currentVelocity.Z()));
this->publishers[this->currentVelocityTopic]->Publish(currentVel);
}
/////////////////////////////////////////////////
void UnderwaterCurrentPlugin::PublishStratifiedCurrentVelocity()
{
dave_gazebo_world_plugins_msgs::msgs::StratifiedCurrentVelocity currentVel;
for (std::vector<ignition::math::Vector4d>::iterator it =
this->currentStratifiedVelocity.begin();
it != this->currentStratifiedVelocity.end(); ++it)
{
msgs::Set(currentVel.add_velocity(),
ignition::math::Vector3d(it->X(), it->Y(), it->Z()));
currentVel.add_depth(it->W());
}
if (currentVel.velocity_size() == 0)
return;
this->publishers[this->stratifiedCurrentVelocityTopic]->Publish(currentVel);
}
GZ_REGISTER_WORLD_PLUGIN(UnderwaterCurrentPlugin)
}
| 0 | 0.956812 | 1 | 0.956812 | game-dev | MEDIA | 0.313561 | game-dev | 0.693004 | 1 | 0.693004 |
randomguy3725/MoonLight | 4,837 | src/main/java/net/minecraft/client/model/ModelEnderman.java | package net.minecraft.client.model;
import net.minecraft.entity.Entity;
public class ModelEnderman extends ModelBiped
{
public boolean isCarrying;
public boolean isAttacking;
public ModelEnderman(float p_i46305_1_)
{
super(0.0F, -14.0F, 64, 32);
float f = -14.0F;
this.bipedHeadwear = new ModelRenderer(this, 0, 16);
this.bipedHeadwear.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, p_i46305_1_ - 0.5F);
this.bipedHeadwear.setRotationPoint(0.0F, 0.0F + f, 0.0F);
this.bipedBody = new ModelRenderer(this, 32, 16);
this.bipedBody.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, p_i46305_1_);
this.bipedBody.setRotationPoint(0.0F, 0.0F + f, 0.0F);
this.bipedRightArm = new ModelRenderer(this, 56, 0);
this.bipedRightArm.addBox(-1.0F, -2.0F, -1.0F, 2, 30, 2, p_i46305_1_);
this.bipedRightArm.setRotationPoint(-3.0F, 2.0F + f, 0.0F);
this.bipedLeftArm = new ModelRenderer(this, 56, 0);
this.bipedLeftArm.mirror = true;
this.bipedLeftArm.addBox(-1.0F, -2.0F, -1.0F, 2, 30, 2, p_i46305_1_);
this.bipedLeftArm.setRotationPoint(5.0F, 2.0F + f, 0.0F);
this.bipedRightLeg = new ModelRenderer(this, 56, 0);
this.bipedRightLeg.addBox(-1.0F, 0.0F, -1.0F, 2, 30, 2, p_i46305_1_);
this.bipedRightLeg.setRotationPoint(-2.0F, 12.0F + f, 0.0F);
this.bipedLeftLeg = new ModelRenderer(this, 56, 0);
this.bipedLeftLeg.mirror = true;
this.bipedLeftLeg.addBox(-1.0F, 0.0F, -1.0F, 2, 30, 2, p_i46305_1_);
this.bipedLeftLeg.setRotationPoint(2.0F, 12.0F + f, 0.0F);
}
public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn)
{
super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn);
this.bipedHead.showModel = true;
float f = -14.0F;
this.bipedBody.rotateAngleX = 0.0F;
this.bipedBody.rotationPointY = f;
this.bipedBody.rotationPointZ = -0.0F;
this.bipedRightLeg.rotateAngleX -= 0.0F;
this.bipedLeftLeg.rotateAngleX -= 0.0F;
this.bipedRightArm.rotateAngleX = (float)((double)this.bipedRightArm.rotateAngleX * 0.5D);
this.bipedLeftArm.rotateAngleX = (float)((double)this.bipedLeftArm.rotateAngleX * 0.5D);
this.bipedRightLeg.rotateAngleX = (float)((double)this.bipedRightLeg.rotateAngleX * 0.5D);
this.bipedLeftLeg.rotateAngleX = (float)((double)this.bipedLeftLeg.rotateAngleX * 0.5D);
float f1 = 0.4F;
if (this.bipedRightArm.rotateAngleX > f1)
{
this.bipedRightArm.rotateAngleX = f1;
}
if (this.bipedLeftArm.rotateAngleX > f1)
{
this.bipedLeftArm.rotateAngleX = f1;
}
if (this.bipedRightArm.rotateAngleX < -f1)
{
this.bipedRightArm.rotateAngleX = -f1;
}
if (this.bipedLeftArm.rotateAngleX < -f1)
{
this.bipedLeftArm.rotateAngleX = -f1;
}
if (this.bipedRightLeg.rotateAngleX > f1)
{
this.bipedRightLeg.rotateAngleX = f1;
}
if (this.bipedLeftLeg.rotateAngleX > f1)
{
this.bipedLeftLeg.rotateAngleX = f1;
}
if (this.bipedRightLeg.rotateAngleX < -f1)
{
this.bipedRightLeg.rotateAngleX = -f1;
}
if (this.bipedLeftLeg.rotateAngleX < -f1)
{
this.bipedLeftLeg.rotateAngleX = -f1;
}
if (this.isCarrying)
{
this.bipedRightArm.rotateAngleX = -0.5F;
this.bipedLeftArm.rotateAngleX = -0.5F;
this.bipedRightArm.rotateAngleZ = 0.05F;
this.bipedLeftArm.rotateAngleZ = -0.05F;
}
this.bipedRightArm.rotationPointZ = 0.0F;
this.bipedLeftArm.rotationPointZ = 0.0F;
this.bipedRightLeg.rotationPointZ = 0.0F;
this.bipedLeftLeg.rotationPointZ = 0.0F;
this.bipedRightLeg.rotationPointY = 9.0F + f;
this.bipedLeftLeg.rotationPointY = 9.0F + f;
this.bipedHead.rotationPointZ = -0.0F;
this.bipedHead.rotationPointY = f + 1.0F;
this.bipedHeadwear.rotationPointX = this.bipedHead.rotationPointX;
this.bipedHeadwear.rotationPointY = this.bipedHead.rotationPointY;
this.bipedHeadwear.rotationPointZ = this.bipedHead.rotationPointZ;
this.bipedHeadwear.rotateAngleX = this.bipedHead.rotateAngleX;
this.bipedHeadwear.rotateAngleY = this.bipedHead.rotateAngleY;
this.bipedHeadwear.rotateAngleZ = this.bipedHead.rotateAngleZ;
if (this.isAttacking)
{
float f2 = 1.0F;
this.bipedHead.rotationPointY -= f2 * 5.0F;
}
}
}
| 0 | 0.785127 | 1 | 0.785127 | game-dev | MEDIA | 0.601623 | game-dev,graphics-rendering | 0.873818 | 1 | 0.873818 |
TeamWizardry/Wizardry | 1,992 | src/main/java/com/teamwizardry/wizardry/common/network/PacketRenderSpell.java | package com.teamwizardry.wizardry.common.network;
import com.teamwizardry.librarianlib.core.LibrarianLib;
import com.teamwizardry.librarianlib.features.network.PacketBase;
import com.teamwizardry.librarianlib.features.saving.SaveMethodGetter;
import com.teamwizardry.librarianlib.features.saving.SaveMethodSetter;
import com.teamwizardry.wizardry.api.spell.SpellData;
import com.teamwizardry.wizardry.api.spell.SpellRing;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import javax.annotation.Nonnull;
/**
* Created by Demoniaque.
*/
public class PacketRenderSpell extends PacketBase {
public NBTTagCompound spellData;
public SpellRing spellRing;
public PacketRenderSpell() {
}
public PacketRenderSpell(SpellData spellData, SpellRing spellRing) {
this.spellData = spellData.serializeNBT();
this.spellRing = spellRing;
}
@SaveMethodGetter(saveName = "module_saver")
public NBTTagCompound getter() {
NBTTagCompound compound = new NBTTagCompound();
if (spellData == null || spellRing == null) return compound;
compound.setTag("spell_data", spellData);
compound.setTag("spell_ring", spellRing.serializeNBT());
return compound;
}
@SaveMethodSetter(saveName = "module_saver")
public void setter(NBTTagCompound compound) {
if (compound.hasKey("spell_data")) spellData = compound.getCompoundTag("spell_data");
if (compound.hasKey("spell_ring")) spellRing = SpellRing.deserializeRing(compound.getCompoundTag("spell_ring"));
}
@Override
public void handle(@Nonnull MessageContext messageContext) {
if (messageContext.side.isServer()) return;
World world = LibrarianLib.PROXY.getClientPlayer().world;
if (world == null || spellRing == null || spellData == null) return;
SpellData data = new SpellData();
data.deserializeNBT(spellData);
if (spellRing.getModule() != null) {
spellRing.getModule().renderSpell(world, data, spellRing);
}
}
}
| 0 | 0.858224 | 1 | 0.858224 | game-dev | MEDIA | 0.379576 | game-dev | 0.921527 | 1 | 0.921527 |
plankes-projects/BaseWar | 1,463 | client/Classes/Model/Skills/ManaBurnSkill.cpp | /*
* InstantSplashAttack.cpp
*
* Created on: 30.05.2013
* Author: Planke
*/
#include "ManaBurnSkill.h"
#include "../Units/Unit.h"
#include "../Model.h"
#include "../../Tools/Tools.h"
ManaBurnSkill::~ManaBurnSkill() {
}
std::string ManaBurnSkill::getSkillInfo() {
return "Burns " + Tools::toString((int) _manaCost * _manaBurnPerManaUsed) + " mana of an enemy. (Range: "
+ Tools::toString((int) _range) + "; ";
}
ManaBurnSkill::ManaBurnSkill(float manaCost, float rechargeTime, float range, float manaBurnPerManaUsed) :
Skill(manaCost, rechargeTime) {
_range = range;
_manaBurnPerManaUsed = manaBurnPerManaUsed;
}
Skill* ManaBurnSkill::clone() {
return new ManaBurnSkill(_manaCost, _rechargeTime, _range, _manaBurnPerManaUsed);
}
bool ManaBurnSkill::perform(Unit* owner) {
//search enemy with max mana in range
Unit* unitWithMaxMana = NULL;
std::list<Unit*> enemyUnits = Model::getInstance()->getEnemyArmy(owner->getArmyType())->getUnits();
for (std::list<Unit*>::iterator it = enemyUnits.begin(); it != enemyUnits.end(); ++it) {
if ((*it)->getHitpoints() > 0 && owner->distanceTo((*it)) <= _range) {
if (unitWithMaxMana == NULL || unitWithMaxMana->getMana() < (*it)->getMana())
unitWithMaxMana = (*it);
}
}
if(unitWithMaxMana == NULL)
return false;
//burn mana now
float burn = _manaCost * _manaBurnPerManaUsed;
unitWithMaxMana->reduceManaBy(burn);
unitWithMaxMana->Receivedamage(burn, MAGIC);
return true;
}
| 0 | 0.673982 | 1 | 0.673982 | game-dev | MEDIA | 0.981659 | game-dev | 0.83086 | 1 | 0.83086 |
DK22Pac/plugin-sdk | 5,828 | plugin_vc/game_vc/meta/meta.CRouteNode.h | /*
Plugin-SDK (Grand Theft Auto Vice City) header file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "PluginBase.h"
namespace plugin {
META_BEGIN(CRouteNode::GetRouteThisPointIsOn)
static int address;
static int global_address;
static const int id = 0x52FC50;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x52FC50, 0x52FC70, 0x52FB40>;
// total references count: 10en (2), 11en (2), steam (2)
using refs_t = RefList<0x51CA08,100,0,0x51C9E0,1, 0x521E81,100,0,0x521D10,1, 0x51CA28,110,0,0x51CA00,1, 0x521EA1,110,0,0x521D30,1, 0x51C8F8,120,0,0x51C8D0,1, 0x521D71,120,0,0x521C00,1>;
using def_t = short(short);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<short>, 0>;
META_END
META_BEGIN(CRouteNode::GetPointPosition)
static int address;
static int global_address;
static const int id = 0x52FC60;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x52FC60, 0x52FC80, 0x52FB50>;
// total references count: 10en (2), 11en (2), steam (2)
using refs_t = RefList<0x51D7A0,100,0,0x51CA70,1, 0x521EDE,100,0,0x521D10,1, 0x51D7C0,110,0,0x51CA90,1, 0x521EFE,110,0,0x521D30,1, 0x51D690,120,0,0x51C960,1, 0x521DCE,120,0,0x521C00,1>;
using def_t = CVector *(CVector *, short);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<CVector *,short>, 0,1>;
META_END
META_BEGIN(CRouteNode::GetRouteStart)
static int address;
static int global_address;
static const int id = 0x52FC80;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x52FC80, 0x52FCA0, 0x52FB70>;
// total references count: 10en (1), 11en (1), steam (1)
using refs_t = RefList<0x521E2D,100,0,0x521D10,1, 0x521E4D,110,0,0x521D30,1, 0x521D1D,120,0,0x521C00,1>;
using def_t = short(short);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<short>, 0>;
META_END
META_BEGIN(CRouteNode::AddRoutePoint)
static int address;
static int global_address;
static const int id = 0x52FCA0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x52FCA0, 0x52FCC0, 0x52FB90>;
// total references count: 10en (1), 11en (1), steam (1)
using refs_t = RefList<0x4531AD,100,0,0x451F90,1, 0x4531AD,110,0,0x451F90,1, 0x45308D,120,0,0x451E70,1>;
using def_t = void(short, CVector);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<short,CVector>, 0,1>;
META_END
META_BEGIN(CRouteNode::RemoveRoute)
static int address;
static int global_address;
static const int id = 0x52FCF0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x52FCF0, 0x52FD10, 0x52FBE0>;
// total references count: 10en (1), 11en (1), steam (1)
using refs_t = RefList<0x459C52,100,0,0x458EC0,1, 0x459C52,110,0,0x458EC0,1, 0x459B32,120,0,0x458DA0,1>;
using def_t = void(short);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<short>, 0>;
META_END
META_BEGIN(CRouteNode::Initialise)
static int address;
static int global_address;
static const int id = 0x52FE40;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x52FE40, 0x52FE60, 0x52FD30>;
// total references count: 10en (2), 11en (2), steam (2)
using refs_t = RefList<0x451599,100,0,0x451550,1, 0x4A4DD1,100,0,0x4A4B10,1, 0x451599,110,0,0x451550,1, 0x4A4DF1,110,0,0x4A4B30,1, 0x4514A9,120,0,0x451460,1, 0x4A4C9E,120,0,0x4A49D0,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
CTOR_META_BEGIN(CRouteNode)
static int address;
static int global_address;
static const int id = 0x52FFB0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x52FFB0, 0x52FFD0, 0x52FEA0>;
// total references count: 10en (1), 11en (1), steam (1)
using refs_t = RefList<0x52FF9A,100,2,0,1, 0x52FFBA,110,2,0,1, 0x52FE8A,120,2,0,1>;
using def_t = CRouteNode *(CRouteNode *);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Thiscall;
using args_t = ArgPick<ArgTypes<CRouteNode *>, 0>;
META_END
template<>
struct stack_object<CRouteNode> : stack_object_no_default<CRouteNode> {
SUPPORTED_10EN_11EN_STEAM stack_object() {
plugin::CallMethodDynGlobal<CRouteNode *>(ctor_gaddr(CRouteNode), reinterpret_cast<CRouteNode *>(objBuff));
}
};
template <>
SUPPORTED_10EN_11EN_STEAM inline CRouteNode *operator_new<CRouteNode>() {
void *objData = operator new(sizeof(CRouteNode));
CRouteNode *obj = reinterpret_cast<CRouteNode *>(objData);
plugin::CallMethodDynGlobal<CRouteNode *>(ctor_gaddr(CRouteNode), obj);
return obj;
}
template <>
SUPPORTED_10EN_11EN_STEAM inline CRouteNode *operator_new_array<CRouteNode>(unsigned int objCount) {
void *objData = operator new(sizeof(CRouteNode) * objCount + 4);
*reinterpret_cast<unsigned int *>(objData) = objCount;
CRouteNode *objArray = reinterpret_cast<CRouteNode *>(reinterpret_cast<unsigned int>(objData) + 4);
for (unsigned int i = 0; i < objCount; i++)
plugin::CallMethodDynGlobal<CRouteNode *>(ctor_gaddr(CRouteNode), &objArray[i]);
return objArray;
}
}
| 0 | 0.797408 | 1 | 0.797408 | game-dev | MEDIA | 0.767639 | game-dev | 0.618594 | 1 | 0.618594 |
DenizenScript/Denizen | 3,575 | plugin/src/main/java/com/denizenscript/denizen/scripts/containers/core/EntityScriptHelper.java | package com.denizenscript.denizen.scripts.containers.core;
import com.denizenscript.denizen.Denizen;
import com.denizenscript.denizen.utilities.DataPersistenceHelper;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import com.denizenscript.denizen.events.entity.EntityDespawnScriptEvent;
import com.denizenscript.denizen.objects.EntityTag;
import com.denizenscript.denizencore.objects.ObjectTag;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.core.ScriptTag;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.world.EntitiesUnloadEvent;
import java.util.HashMap;
public class EntityScriptHelper implements Listener {
public static HashMap<String, EntityScriptContainer> scripts = new HashMap<>();
public EntityScriptHelper() {
Denizen.getInstance().getServer().getPluginManager()
.registerEvents(this, Denizen.getInstance());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDeath(EntityDeathEvent event) {
Entity entity = event.getEntity();
EntityTag.rememberEntity(entity);
EntityDespawnScriptEvent.instance.entity = new EntityTag(entity);
EntityDespawnScriptEvent.instance.cause = new ElementTag("DEATH");
EntityDespawnScriptEvent.instance.fire();
EntityTag.forgetEntity(entity);
}
@EventHandler
public void onChunkUnload(EntitiesUnloadEvent event) {
for (Entity ent : event.getEntities()) {
if (!(ent instanceof LivingEntity) || ((LivingEntity) ent).getRemoveWhenFarAway()) {
EntityTag.rememberEntity(ent);
EntityDespawnScriptEvent.instance.entity = new EntityTag(ent);
EntityDespawnScriptEvent.instance.cause = new ElementTag("CHUNK_UNLOAD");
EntityDespawnScriptEvent.instance.fire();
EntityTag.forgetEntity(ent);
}
}
}
/**
* Indicates whether a specified entity has a custom entity script.
*/
public static boolean entityHasScript(Entity ent) {
return getEntityScript(ent) != null;
}
/**
* Returns the name of the entity script that defined this entity, or null if none.
*/
public static String getEntityScript(Entity ent) {
if (ent == null) {
return null;
}
if (!DataPersistenceHelper.hasDenizenKey(ent, "entity_script")) {
return null;
}
ObjectTag scriptObject = DataPersistenceHelper.getDenizenKey(ent, "entity_script");
if (!(scriptObject instanceof ScriptTag)) {
return null;
}
return ((ScriptTag) scriptObject).getName();
}
/**
* Marks the entity as having been created by a specified script.
*/
public static void setEntityScript(Entity ent, String script) {
if (ent == null || ent.getUniqueId() == null || script == null) {
return;
}
ScriptTag scriptObj = ScriptTag.valueOf(script, CoreUtilities.basicContext);
if (scriptObj == null) {
Debug.echoError("Can't set entity script to '" + script + "': not a valid script!");
}
DataPersistenceHelper.setDenizenKey(ent, "entity_script", scriptObj);
return;
}
}
| 0 | 0.918555 | 1 | 0.918555 | game-dev | MEDIA | 0.956758 | game-dev | 0.873885 | 1 | 0.873885 |
ProjectEQ/projecteqquests | 8,712 | halas/Artisan_Kjell_Sunrunner.lua | -- Newer Cultural Tradeskill Armor Quest -- Barbarian
local task_array = {};
function event_say(e)
-- Setup Task Array
table_setup(e);
if e.other:GetBaseRace() == e.self:GetBaseRace() then
if e.message:findi("hail") then
e.other:Message(MT.NPCQuestSay, "Artisan Kjell Sunrunner says, 'Aye, hail,' the barbarian says as he raises a fist in salute. 'Have you returned for the [funeral], "..e.other:GetCleanName() .."?'");
elseif e.message:findi("funeral") then
e.other:Message(MT.NPCQuestSay, "Artisan Kjell Sunrunner says, 'The funeral of Fellroon Skene. He's one of the last of the Skene clan. The lad fell in battle. It was a proud death, a warrior's death! Too bad there are so few of his kin left to mourn him. That's why I've returned to Halas, to pay tribute to a great [warrior]!'");
elseif e.message:findi("warrior") then
e.other:Message(MT.NPCQuestSay, "Artisan Kjell Sunrunner says, 'Aye, all the Skenes had a penchant for warfare. That's probably why there are so few of them left. Before he died, Fellroon told me where to find his clan's armor pattern book. Their ancestral designs were a long kept secret, but Fellroon said he didn't want these patterns to die with him. He told me to pass them on to all Barbarians across Norrath. Would you be interested in a pattern [book] or perhaps some armor [patterns]?'");
elseif e.message:findi("book") then
e.other:Message(MT.NPCQuestSay, "Artisan Kjell Sunrunner says, 'Very well then. To make a pattern book, I require a fire beetle carapace for the cover, a patch of zombie skin for the pages, a golden bandit tooth for the clasp, and a lion tail to grind down and make a salve which will protect and preserve the finished product. I have heard these resources can be found in Western Karana. Return to me when you have these items and the armor patterns shall be yours.'");
elseif e.message:findi("patterns") then
e.other:Message(MT.NPCQuestSay, "Artisan Kjell Sunrunner says, 'Well then, Lamudan. Now that the Fellroon is dead, a tribute is important. Take this impression book and make impressions of certain parts of critters that you slay in your heroic deeds. This magical book can make impression of objects with depth to them or just of the pattern on the surface of an object. Take as many of the tasks I offer you as you would like.'");
eq.task_selector(task_array);
end
else
e.other:Message(MT.NPCQuestSay, "Artisan Kjell Sunrunner says, 'Greetings, "..e.other:GetCleanName() ..". I'm afraid I do not have time to talk at the moment. Please leave me to my work. If your looking for work yourself, I suggest you return to your home city and seek out your own kind.'");
end
end
function table_setup(e)
local player_level = e.other:GetLevel();
task_array = {}; -- Clear Table
-- Below are fully supported by EQEmu
if eq.is_current_expansion_dragons_of_norrath() then
if player_level >= 15 then
table.insert(task_array, 5786); -- Task: Blessed Impressions -- Variant A
end
if player_level >= 35 then
table.insert(task_array, 5789); -- Task: Revered Impressions -- Variant A
end
if player_level >= 55 then
table.insert(task_array, 5790); -- Task: Sacred Impressions -- All Races
end
if player_level >= 65 then
table.insert(task_array, 5791); -- Task: Eminent Impressions -- All Races
end
end
-- Below are not officially supported by EQEmu currently
if eq.is_current_expansion_the_serpents_spine() and player_level >= 70 then
table.insert(task_array, 5792); -- Task: Exalted Impressions -- All Races
end
if eq.is_current_expansion_secrets_of_faydwer() and player_level >= 75 then
table.insert(task_array, 5793); -- Task: Sublime Impressions -- All Races
end
if eq.is_current_expansion_underfoot() and player_level >= 85 then
table.insert(task_array, 6955); -- Task: Venerable Impressions -- All Races
end
if eq.is_current_expansion_house_of_thule() and player_level >= 85 then
table.insert(task_array, 7070); -- Task: Illustrious Impressions -- All Races
end
if eq.is_current_expansion_veil_of_alaris() and player_level >= 85 then
table.insert(task_array, 7071); -- Task: Numinous Impressions -- All Races
end
if eq.is_current_expansion_veil_of_alaris() and player_level >= 85 then
table.insert(task_array, 7078); -- Task: Transcendent Impressions -- All Races
end
if eq.is_current_expansion_depths_of_darkhollow() then
table.insert(task_array, 10044); -- Task: Darkhollow Geode -- All Races
end
end
function event_task_accepted(e)
-- Supported
if e.task_id == 5784 or e.task_id == 5785 or e.task_id == 5786 then -- Blessed Impressions A/B/C
e.other:SummonItem(34997) -- Item: Blessed Impression Book
elseif e.task_id == 5787 or e.task_id == 5788 or e.task_id == 5789 then -- Revered Impressions A/B/C
e.other:SummonItem(34998) -- Item: Revered Impression Book
elseif e.task_id == 5790 then -- Sacred Impressions
e.other:SummonItem(34999) -- Item: Sacred Impression Book
elseif e.task_id == 5791 then -- Eminent Impressions
e.other:SummonItem(35000) -- Item: Eminent Impression Book
-- Not Supported
elseif e.task_id == 5792 then -- Exalted Impressions
e.other:SummonItem(35017) -- Item: Exalted Impression Book
elseif e.task_id == 5793 then -- Sublime Impressions
e.other:SummonItem(35018) -- Item: Sublime Impression Book
elseif e.task_id == 6955 then -- Venerable Impressions
e.other:SummonItem(88388) -- Item: Venerable Impression Book
elseif e.task_id == 7070 then -- Illustrious Impressions
e.other:SummonItem(17835) -- Item: Illustrious Impression Book
elseif e.task_id == 7071 then -- Numinous Impressions
e.other:SummonItem(54449) -- Item: Numinous Impression Book
elseif e.task_id == 7078 then -- Transcendent Impressions
e.other:SummonItem(55727) -- Item: Transcendent Impression Book
end
end
function event_trade(e)
local item_lib = require("items");
if e.other:GetBaseRace() == e.self:GetBaseRace() then
-- Supported
if e.other:IsTaskActivityActive(5786,4) and item_lib.check_turn_in(e.trade, {item1 = 34997}) then -- Blessed Impression Book
e.other:UpdateTaskActivity(5786,4,1);
e.other:QuestReward(e.self,{itemid = 38408}); -- Item: Blessed Book of Barbarian Culture
elseif e.other:IsTaskActivityActive(5789,4) and item_lib.check_turn_in(e.trade, {item1 = 34998}) then -- Revered Impression Book
e.other:UpdateTaskActivity(5789,4,1);
e.other:QuestReward(e.self,{itemid = 38409}); -- Item: Revered Book of Barbarian Culture
elseif e.other:IsTaskActivityActive(5790,4) and item_lib.check_turn_in(e.trade, {item1 = 34999}) then -- Sacred Impression Book
e.other:UpdateTaskActivity(5790,4,1);
e.other:QuestReward(e.self,{itemid = 38410}); -- Item: Sacred Book of Barbarian Culture
elseif e.other:IsTaskActivityActive(5791,4) and item_lib.check_turn_in(e.trade, {item1 = 35000}) then -- Eminent Impression Book
e.other:UpdateTaskActivity(5791,4,1);
e.other:QuestReward(e.self,{itemid = 38411}); -- Item: Eminent Book of Barbarian Culture
-- Not Supported
elseif e.other:IsTaskActivityActive(5792,4) and item_lib.check_turn_in(e.trade, {item1 = 35017}) then -- Exalted Impression Book
e.other:UpdateTaskActivity(5792,4,1);
e.other:QuestReward(e.self,{itemid = 35739}); -- Item: Exalted Book of Barbarian Culture
elseif e.other:IsTaskActivityActive(5793,4) and item_lib.check_turn_in(e.trade, {item1 = 35018}) then -- Sublime Impression Book
e.other:UpdateTaskActivity(5793,4,1);
e.other:QuestReward(e.self,{itemid = 35740}); -- Item: Sublime Book of Barbarian Culture
elseif e.other:IsTaskActivityActive(6955,4) and item_lib.check_turn_in(e.trade, {item1 = 88388}) then -- Venerable Impression Book
e.other:UpdateTaskActivity(6955,4,1);
e.other:QuestReward(e.self,{itemid = 49959}); -- Item: Venerable Book of Barbarian Culture
elseif e.other:IsTaskActivityActive(7070,4) and item_lib.check_turn_in(e.trade, {item1 = 17835}) then -- Illustrious Impression Book
e.other:UpdateTaskActivity(7070,4,1);
e.other:QuestReward(e.self,{itemid = 123411}); -- Item: Illustrious Book of Barbarian Culture
elseif e.other:IsTaskActivityActive(7071,4) and item_lib.check_turn_in(e.trade, {item1 = 54449}) then -- Numinous Impression Book
e.other:UpdateTaskActivity(7071,4,1);
e.other:QuestReward(e.self,{itemid = 112545}); -- Item: Numinous Book of Barbarian Culture
elseif e.other:IsTaskActivityActive(7078,4) and item_lib.check_turn_in(e.trade, {item1 = 55727}) then -- Transcendent Impression Book
e.other:UpdateTaskActivity(7078,4,1);
e.other:QuestReward(e.self,{itemid = 134594}); -- Item: Transcendent Book of Barbarian Culture
end
end
item_lib.return_items(e.self, e.other, e.trade)
end
| 0 | 0.755059 | 1 | 0.755059 | game-dev | MEDIA | 0.568113 | game-dev | 0.776051 | 1 | 0.776051 |
sergiobd/ViveTrackerUtilities | 8,930 | Assets/SteamVR/InteractionSystem/Teleport/Scripts/TeleportPoint.cs | //======= Copyright (c) Valve Corporation, All rights reserved. ===============
//
// Purpose: Single location that the player can teleport to
//
//=============================================================================
using UnityEngine;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Valve.VR.InteractionSystem
{
//-------------------------------------------------------------------------
public class TeleportPoint : TeleportMarkerBase
{
public enum TeleportPointType
{
MoveToLocation,
SwitchToNewScene
};
//Public variables
public TeleportPointType teleportType = TeleportPointType.MoveToLocation;
public string title;
public string switchToScene;
public Color titleVisibleColor;
public Color titleHighlightedColor;
public Color titleLockedColor;
public bool playerSpawnPoint = false;
//Private data
private bool gotReleventComponents = false;
private MeshRenderer markerMesh;
private MeshRenderer switchSceneIcon;
private MeshRenderer moveLocationIcon;
private MeshRenderer lockedIcon;
private MeshRenderer pointIcon;
private Transform lookAtJointTransform;
private new Animation animation;
private Text titleText;
private Player player;
private Vector3 lookAtPosition = Vector3.zero;
private int tintColorID = 0;
private Color tintColor = Color.clear;
private Color titleColor = Color.clear;
private float fullTitleAlpha = 0.0f;
//Constants
private const string switchSceneAnimation = "switch_scenes_idle";
private const string moveLocationAnimation = "move_location_idle";
private const string lockedAnimation = "locked_idle";
//-------------------------------------------------
public override bool showReticle
{
get
{
return false;
}
}
//-------------------------------------------------
void Awake()
{
GetRelevantComponents();
animation = GetComponent<Animation>();
tintColorID = Shader.PropertyToID( "_TintColor" );
moveLocationIcon.gameObject.SetActive( false );
switchSceneIcon.gameObject.SetActive( false );
lockedIcon.gameObject.SetActive( false );
UpdateVisuals();
}
//-------------------------------------------------
void Start()
{
player = Player.instance;
}
//-------------------------------------------------
void Update()
{
if ( Application.isPlaying )
{
lookAtPosition.x = player.hmdTransform.position.x;
lookAtPosition.y = lookAtJointTransform.position.y;
lookAtPosition.z = player.hmdTransform.position.z;
lookAtJointTransform.LookAt( lookAtPosition );
}
}
//-------------------------------------------------
public override bool ShouldActivate( Vector3 playerPosition )
{
return ( Vector3.Distance( transform.position, playerPosition ) > 1.0f );
}
//-------------------------------------------------
public override bool ShouldMovePlayer()
{
return true;
}
//-------------------------------------------------
public override void Highlight( bool highlight )
{
if ( !locked )
{
if ( highlight )
{
SetMeshMaterials( Teleport.instance.pointHighlightedMaterial, titleHighlightedColor );
}
else
{
SetMeshMaterials( Teleport.instance.pointVisibleMaterial, titleVisibleColor );
}
}
if ( highlight )
{
pointIcon.gameObject.SetActive( true );
animation.Play();
}
else
{
pointIcon.gameObject.SetActive( false );
animation.Stop();
}
}
//-------------------------------------------------
public override void UpdateVisuals()
{
if ( !gotReleventComponents )
{
return;
}
if ( locked )
{
SetMeshMaterials( Teleport.instance.pointLockedMaterial, titleLockedColor );
pointIcon = lockedIcon;
animation.clip = animation.GetClip( lockedAnimation );
}
else
{
SetMeshMaterials( Teleport.instance.pointVisibleMaterial, titleVisibleColor );
switch ( teleportType )
{
case TeleportPointType.MoveToLocation:
{
pointIcon = moveLocationIcon;
animation.clip = animation.GetClip( moveLocationAnimation );
}
break;
case TeleportPointType.SwitchToNewScene:
{
pointIcon = switchSceneIcon;
animation.clip = animation.GetClip( switchSceneAnimation );
}
break;
}
}
titleText.text = title;
}
//-------------------------------------------------
public override void SetAlpha( float tintAlpha, float alphaPercent )
{
tintColor = markerMesh.material.GetColor( tintColorID );
tintColor.a = tintAlpha;
markerMesh.material.SetColor( tintColorID, tintColor );
switchSceneIcon.material.SetColor( tintColorID, tintColor );
moveLocationIcon.material.SetColor( tintColorID, tintColor );
lockedIcon.material.SetColor( tintColorID, tintColor );
titleColor.a = fullTitleAlpha * alphaPercent;
titleText.color = titleColor;
}
//-------------------------------------------------
public void SetMeshMaterials( Material material, Color textColor )
{
markerMesh.material = material;
switchSceneIcon.material = material;
moveLocationIcon.material = material;
lockedIcon.material = material;
titleColor = textColor;
fullTitleAlpha = textColor.a;
titleText.color = titleColor;
}
//-------------------------------------------------
public void TeleportToScene()
{
if ( !string.IsNullOrEmpty( switchToScene ) )
{
Debug.Log( "TeleportPoint: Hook up your level loading logic to switch to new scene: " + switchToScene );
}
else
{
Debug.LogError( "TeleportPoint: Invalid scene name to switch to: " + switchToScene );
}
}
//-------------------------------------------------
public void GetRelevantComponents()
{
markerMesh = transform.Find( "teleport_marker_mesh" ).GetComponent<MeshRenderer>();
switchSceneIcon = transform.Find( "teleport_marker_lookat_joint/teleport_marker_icons/switch_scenes_icon" ).GetComponent<MeshRenderer>();
moveLocationIcon = transform.Find( "teleport_marker_lookat_joint/teleport_marker_icons/move_location_icon" ).GetComponent<MeshRenderer>();
lockedIcon = transform.Find( "teleport_marker_lookat_joint/teleport_marker_icons/locked_icon" ).GetComponent<MeshRenderer>();
lookAtJointTransform = transform.Find( "teleport_marker_lookat_joint" );
titleText = transform.Find( "teleport_marker_lookat_joint/teleport_marker_canvas/teleport_marker_canvas_text" ).GetComponent<Text>();
gotReleventComponents = true;
}
//-------------------------------------------------
public void ReleaseRelevantComponents()
{
markerMesh = null;
switchSceneIcon = null;
moveLocationIcon = null;
lockedIcon = null;
lookAtJointTransform = null;
titleText = null;
}
//-------------------------------------------------
public void UpdateVisualsInEditor()
{
if ( Application.isPlaying )
{
return;
}
GetRelevantComponents();
if ( locked )
{
lockedIcon.gameObject.SetActive( true );
moveLocationIcon.gameObject.SetActive( false );
switchSceneIcon.gameObject.SetActive( false );
markerMesh.sharedMaterial = Teleport.instance.pointLockedMaterial;
lockedIcon.sharedMaterial = Teleport.instance.pointLockedMaterial;
titleText.color = titleLockedColor;
}
else
{
lockedIcon.gameObject.SetActive( false );
markerMesh.sharedMaterial = Teleport.instance.pointVisibleMaterial;
switchSceneIcon.sharedMaterial = Teleport.instance.pointVisibleMaterial;
moveLocationIcon.sharedMaterial = Teleport.instance.pointVisibleMaterial;
titleText.color = titleVisibleColor;
switch ( teleportType )
{
case TeleportPointType.MoveToLocation:
{
moveLocationIcon.gameObject.SetActive( true );
switchSceneIcon.gameObject.SetActive( false );
}
break;
case TeleportPointType.SwitchToNewScene:
{
moveLocationIcon.gameObject.SetActive( false );
switchSceneIcon.gameObject.SetActive( true );
}
break;
}
}
titleText.text = title;
ReleaseRelevantComponents();
}
}
#if UNITY_EDITOR
//-------------------------------------------------------------------------
[CustomEditor( typeof( TeleportPoint ) )]
public class TeleportPointEditor : Editor
{
//-------------------------------------------------
void OnEnable()
{
if ( Selection.activeTransform )
{
TeleportPoint teleportPoint = Selection.activeTransform.GetComponent<TeleportPoint>();
teleportPoint.UpdateVisualsInEditor();
}
}
//-------------------------------------------------
public override void OnInspectorGUI()
{
DrawDefaultInspector();
if ( Selection.activeTransform )
{
TeleportPoint teleportPoint = Selection.activeTransform.GetComponent<TeleportPoint>();
if ( GUI.changed )
{
teleportPoint.UpdateVisualsInEditor();
}
}
}
}
#endif
}
| 0 | 0.923866 | 1 | 0.923866 | game-dev | MEDIA | 0.96748 | game-dev | 0.988165 | 1 | 0.988165 |
QuestionableM/SM-ProximityVoiceChat | 6,427 | Dependencies/bullet3/BulletCollision/CollisionShapes/btCylinderShape.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_CYLINDER_MINKOWSKI_H
#define BT_CYLINDER_MINKOWSKI_H
#include "btBoxShape.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types
#include "LinearMath/btVector3.h"
/// The btCylinderShape class implements a cylinder shape primitive, centered around the origin. Its central axis aligned with the Y axis. btCylinderShapeX is aligned with the X axis and btCylinderShapeZ around the Z axis.
ATTRIBUTE_ALIGNED16(class)
btCylinderShape : public btConvexInternalShape
{
protected:
int m_upAxis;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btVector3 getHalfExtentsWithMargin() const
{
btVector3 halfExtents = getHalfExtentsWithoutMargin();
btVector3 margin(getMargin(), getMargin(), getMargin());
halfExtents += margin;
return halfExtents;
}
const btVector3& getHalfExtentsWithoutMargin() const
{
return m_implicitShapeDimensions; //changed in Bullet 2.63: assume the scaling and margin are included
}
btCylinderShape(const btVector3& halfExtents);
void getAabb(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const;
virtual void calculateLocalInertia(btScalar mass, btVector3 & inertia) const;
virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec) const;
virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors, btVector3* supportVerticesOut, int numVectors) const;
virtual void setMargin(btScalar collisionMargin)
{
//correct the m_implicitShapeDimensions for the margin
btVector3 oldMargin(getMargin(), getMargin(), getMargin());
btVector3 implicitShapeDimensionsWithMargin = m_implicitShapeDimensions + oldMargin;
btConvexInternalShape::setMargin(collisionMargin);
btVector3 newMargin(getMargin(), getMargin(), getMargin());
m_implicitShapeDimensions = implicitShapeDimensionsWithMargin - newMargin;
}
virtual btVector3 localGetSupportingVertex(const btVector3& vec) const
{
btVector3 supVertex;
supVertex = localGetSupportingVertexWithoutMargin(vec);
if (getMargin() != btScalar(0.))
{
btVector3 vecnorm = vec;
if (vecnorm.length2() < (SIMD_EPSILON * SIMD_EPSILON))
{
vecnorm.setValue(btScalar(-1.), btScalar(-1.), btScalar(-1.));
}
vecnorm.normalize();
supVertex += getMargin() * vecnorm;
}
return supVertex;
}
//use box inertia
// virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const;
int getUpAxis() const
{
return m_upAxis;
}
virtual btVector3 getAnisotropicRollingFrictionDirection() const
{
btVector3 aniDir(0, 0, 0);
aniDir[getUpAxis()] = 1;
return aniDir;
}
virtual btScalar getRadius() const
{
return getHalfExtentsWithMargin().getX();
}
virtual void setLocalScaling(const btVector3& scaling)
{
btVector3 oldMargin(getMargin(), getMargin(), getMargin());
btVector3 implicitShapeDimensionsWithMargin = m_implicitShapeDimensions + oldMargin;
btVector3 unScaledImplicitShapeDimensionsWithMargin = implicitShapeDimensionsWithMargin / m_localScaling;
btConvexInternalShape::setLocalScaling(scaling);
m_implicitShapeDimensions = (unScaledImplicitShapeDimensionsWithMargin * m_localScaling) - oldMargin;
}
//debugging
virtual const char* getName() const
{
return "CylinderY";
}
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const;
};
class btCylinderShapeX : public btCylinderShape
{
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btCylinderShapeX(const btVector3& halfExtents);
virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec) const;
virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors, btVector3* supportVerticesOut, int numVectors) const;
//debugging
virtual const char* getName() const
{
return "CylinderX";
}
virtual btScalar getRadius() const
{
return getHalfExtentsWithMargin().getY();
}
};
class btCylinderShapeZ : public btCylinderShape
{
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btCylinderShapeZ(const btVector3& halfExtents);
virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec) const;
virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors, btVector3* supportVerticesOut, int numVectors) const;
//debugging
virtual const char* getName() const
{
return "CylinderZ";
}
virtual btScalar getRadius() const
{
return getHalfExtentsWithMargin().getX();
}
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btCylinderShapeData
{
btConvexInternalShapeData m_convexInternalShapeData;
int m_upAxis;
char m_padding[4];
};
SIMD_FORCE_INLINE int btCylinderShape::calculateSerializeBufferSize() const
{
return sizeof(btCylinderShapeData);
}
///fills the dataBuffer and returns the struct name (and 0 on failure)
SIMD_FORCE_INLINE const char* btCylinderShape::serialize(void* dataBuffer, btSerializer* serializer) const
{
btCylinderShapeData* shapeData = (btCylinderShapeData*)dataBuffer;
btConvexInternalShape::serialize(&shapeData->m_convexInternalShapeData, serializer);
shapeData->m_upAxis = m_upAxis;
// Fill padding with zeros to appease msan.
shapeData->m_padding[0] = 0;
shapeData->m_padding[1] = 0;
shapeData->m_padding[2] = 0;
shapeData->m_padding[3] = 0;
return "btCylinderShapeData";
}
#endif //BT_CYLINDER_MINKOWSKI_H
| 0 | 0.933551 | 1 | 0.933551 | game-dev | MEDIA | 0.984496 | game-dev | 0.966256 | 1 | 0.966256 |
subho406/Infinite-Runner-Ultimate | 14,153 | Assets/Infinite Runner Ultimate 3D/Scripts/Level Generation/TrackObstacle.cs | /*
Infinite Runner Ultimate Presented by Black Gear Studio ©
Programmed by Subhojeet Pramanik
This script creates and recycles objects at runtime based on given procedures
*/
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class TrackObstacle : MonoBehaviour {
public bool useother=false;
public bool staticSeperation = false;
public PropPoolManager poolManager;
public List<Obstacles> obstacles=new List<Obstacles>();
public List<bool>showobject=new List<bool>();
public float mainprobab=0.5f;
public enum transenum {X=0, Y=1,Z=2, None=3};
public int FramesMod=2;
public int currentMin=0;
public bool PointsFoldout = false;
public int AddValue=0;
public int currentMax=0;
private bool Worktodo=false;
public GameObject gam;
public Mesh mesh;
bool probabnotadded=false;
public int PooledAmount=2;
Vector3[] verts;
public List<Transform> points=new List<Transform>();
public PointSets pointSet;
public int pointsCount = 0;
public bool useCustomPoints = false;
List<float> probabs=new List<float>();
int[] indices;
GameObject temp;
public List<int> updatableIndexes = new List<int>();
List<Vector3> previouspoint = new List<Vector3>();
List<int> obstacleIndex = new List<int>();
#if UNITY_EDITOR
public void createm (){
GameObject Cube=new GameObject();
GameObject plane=GameObject.CreatePrimitive(PrimitiveType.Plane);
DestroyImmediate(plane.GetComponent<MeshCollider>());
Selection.activeObject = SceneView.currentDrawingSceneView;
Camera sceneCam = SceneView.currentDrawingSceneView.camera;
Vector3 spawnPos = sceneCam.ViewportToWorldPoint(new Vector3(0.5f,0.5f,10f));
plane.transform.position=spawnPos;
Cube.transform.position=spawnPos;
Cube.transform.rotation=Quaternion.identity;
plane.transform.rotation=Cube.transform.rotation;
plane.transform.parent=Cube.transform;
Cube.AddComponent<TrackObstacle>();
Cube.GetComponent<TrackObstacle>().gam=plane;
Cube.name="TrackObstacle";
plane.name="mesh";
PrefabUtility.InstantiatePrefab(Cube);
}
#endif
void Awake() {
//Always reset scale of transform object to Unity to avoid bugs
probabnotadded=false;
if(useCustomPoints==false)
mesh=gam.GetComponent<MeshFilter>().mesh;
if (staticSeperation)
previouspoint = LevelMaker.previouspoint;
else
previouspoint=new List<Vector3>();
if(useother==false){
if(mesh){
for(int i=0; i<obstacles.Count;++i){
for(int j=0; j<PooledAmount; ++j){
obstacles[i].poolTrack.Add((GameObject)Instantiate(obstacles[i].obstacle,Vector3.zero,Quaternion.identity));
obstacles[i].poolTrack[j].transform.parent=transform;
obstacles[i].poolTrack[j].SetActive(false);
}
}
}else{
Debug.LogError("Mesh Has not been assigned");
}
}
if(useother==true){
poolManager=GameObject.FindGameObjectWithTag("PoolManager").GetComponent<PropPoolManager>();
}
}
void Start(){
transform.localScale=Vector3.one;
}
void LateUpdate(){
if(Worktodo==true){
// Recycle();
seedobstacle();
}
}
public void Recycle(){
if(useother==false){
for(int i=0; i<obstacles.Count;++i){
for(int j=0; j<obstacles[i].poolTrack.Count; ++j){
obstacles[i].poolTrack[j].SetActive(false);
}
}
if(!staticSeperation)
previouspoint.Clear();
obstacleIndex.Clear();
}else {
for(int i=0; i<obstacles.Count;++i){
for(int j=0; j<obstacles[i].poolTrack.Count;++j){
obstacles[i].poolTrack[j].SetActive(false);
obstacles[i].poolTrack[j].transform.parent=poolManager.transform;
}
obstacles[i].poolTrack.Clear();
}
if(!staticSeperation)
previouspoint.Clear ();
obstacleIndex.Clear();
}
}
public void UpdatePoints(List<Transform> transforms)
{
points.Clear();
foreach(Transform t in transforms)
{
points.Add(t);
}
}
public void seedobstacle() {
if(probabnotadded==false)
{
if (useCustomPoints == false)
{
verts = mesh.vertices;
indices = mesh.triangles;
}
poolManager =GameObject.FindGameObjectWithTag("PoolManager").GetComponent<PropPoolManager>();
temp=new GameObject();
temp.transform.parent=transform;
probabnotadded=true;
for (int i = 0; i < obstacles.Count; ++i) //Probabilities are variables hence need to be added evrytime
{
probabs.Add(obstacles[i].probability);
if (obstacles[i].ZingVariableObject) //If it is a variable object then add its index so that next time when seedobstacle is called Probabilities are updated
updatableIndexes.Add(i);
}
}
if (useCustomPoints == false)
{
if (Worktodo == false)
{
Worktodo = true;
currentMin = 0;
AddValue = mesh.triangles.Length / FramesMod;
currentMax = mesh.triangles.Length / FramesMod;
}
if (currentMax > mesh.triangles.Length)
{
Worktodo = false;
return;
}
}
else
{
if (Worktodo == false)
{
Worktodo = true;
currentMin = 0;
AddValue = points.Count;
currentMax = points.Count;
}
if (currentMax > points.Count)
{
Worktodo = false;
return;
}
}
for(int i = 0; i < currentMax;)
{
Vector3 pos, rot;
if (useCustomPoints == false)
{
Vector3 P1 = verts[indices[i++]];
Vector3 P2 = verts[indices[i++]];
Vector3 P3 = verts[indices[i++]];
pos = gam.transform.TransformPoint((P1 + P2 + P3) / 3);
Vector3 n1 = verts[indices[i++]];
Vector3 n2 = verts[indices[i++]];
Vector3 n3 = verts[indices[i++]];
rot = gam.transform.TransformDirection((n1 + n2 + n3) / 3);
}
else
{
pos = points[currentMin+i].position;
rot = points[currentMin+i].position;
i++;
}
int Randtrack=Probability(probabs,probabs.Count);
if (Randtrack == -1)
{
Worktodo = false;
return;
}
bool b=true;
transenum trans=obstacles[Randtrack].trans;
float value=Random.value;
temp.transform.position=pos;
if (useCustomPoints == true)
temp.transform.rotation = points[currentMin + i - 1].rotation;
else
temp.transform.localRotation=Quaternion.identity;
switch (trans){
case transenum.X:
temp.transform.localPosition=new Vector3(0,temp.transform.localPosition.y,temp.transform.localPosition.z);
break;
case transenum.Y:
temp.transform.localPosition=new Vector3(temp.transform.localPosition.x,0,temp.transform.localPosition.z);
break;
case transenum.Z:
temp.transform.localPosition=new Vector3(temp.transform.localPosition.x,temp.transform.localPosition.y,0);
break;
case transenum.None:
break;
default:
break;
}
for(int x=0; x<obstacles[Randtrack].procedures.Count;++x){
doProcedure(obstacles[Randtrack].procedures[x],temp,rot);
}
int j = previouspoint.Count - 10;
if (j < 0)
j = 0;
for(j=0; j<previouspoint.Count;++j){
bool contains = false;
bool canContinue = true;
for (int x = 0; x < obstacles[Randtrack].SpecificSeperation.Count; x++)
{
if (obstacles[Randtrack].SpecificSeperation[x].index == obstacleIndex[j])
{
contains = true;
if (Vector3.Distance(temp.transform.position, previouspoint[j]) < obstacles[Randtrack].SpecificSeperation[x].sepDist)
{
b = false;
canContinue = false;
break;
}
}
}
if(contains==false&&Vector3.Distance(temp.transform.position,previouspoint[j])<obstacles[Randtrack].sepdist){
b=false;
break;
}
if (!canContinue)
break;
}
if(b==true) {
if(value<mainprobab){
GameObject temp2=CheckPool(Randtrack);
temp2.transform.position=temp.transform.position;
temp2.transform.rotation=temp.transform.rotation;
previouspoint.Add(temp2.transform.position);
obstacleIndex.Add(Randtrack);
temp2.SetActive(true);
temp2.transform.parent=transform;
obstacles[Randtrack].poolTrack.Add(temp2);
}else{
//temp.transform.parent=GameObject.FindGameObjectWithTag("PoolManager").transform;
//temp.SetActive(false);
}
}else {
//temp.transform.parent=GameObject.FindGameObjectWithTag("PoolManager").transform;
//temp.SetActive(false);
}
}
if (useCustomPoints == false) {
currentMin+=AddValue;
if(currentMax==mesh.triangles.Length){
currentMax+=1;
}
else if(currentMax+AddValue>mesh.triangles.Length){
currentMax=mesh.triangles.Length;
}else{
currentMax+=AddValue;
}
}
else
{
Worktodo = false;
return;
}
}
public GameObject CheckPool (int randtrack){
if(useother==true){
for(int i=0; i<poolManager.pObstacle[obstacles[randtrack].otherID].pools.Count;++i){
if(poolManager.pObstacle[obstacles[randtrack].otherID].pools[i].activeInHierarchy==false){
return poolManager.pObstacle[obstacles[randtrack].otherID].pools[i];
}
}
} else {
for(int i=0; i<obstacles[randtrack].poolTrack.Count;++i){
if(obstacles[randtrack].poolTrack[i].activeInHierarchy==false){
return obstacles[randtrack].poolTrack[i];
}
}
}
if(useother==false){
obstacles[randtrack].poolTrack.Add((GameObject)Instantiate(obstacles[randtrack].obstacle,Vector3.zero,Quaternion.identity));
obstacles[randtrack].poolTrack[obstacles[randtrack].poolTrack.Count-1].transform.parent=transform;
}else {
poolManager=GameObject.FindGameObjectWithTag("PoolManager").GetComponent<PropPoolManager>();
GameObject temp=(GameObject)Instantiate(poolManager.pObstacle[obstacles[randtrack].otherID].obstacle,Vector3.zero,Quaternion.identity);
temp.transform.parent=poolManager.transform;
poolManager.pObstacle[obstacles[randtrack].otherID].pools.Add(temp);
temp.SetActive(false);
return temp;
}
return obstacles[randtrack].poolTrack[obstacles[randtrack].poolTrack.Count-1];
}
public void doProcedure(Procedures p,GameObject temp,Vector3 rot){
switch(p.id){
case 0:
temp.transform.up=rot;
break;
case 1:
temp.transform.Rotate(p.rot);
break;
case 2:
temp.transform.localPosition+=p.add;
break;
case 3:
float x=Random.Range(p.RandomRotmin.x,p.RandomRotmax.x);
float y=Random.Range(p.RandomRotmin.y,p.RandomRotmax.y);
float z=Random.Range(p.RandomRotmin.z,p.RandomRotmax.z);
temp.transform.Rotate(new Vector3(x,y,z));
break;
case 4:
float x1=Random.Range(p.RandomPosmin.x,p.RandomPosmax.x);
float y1=Random.Range(p.RandomPosmin.y,p.RandomPosmax.y);
float z1=Random.Range(p.RandomPosmin.z,p.RandomPosmax.z);
temp.transform.localPosition+=new Vector3(x1,y1,z1);
break;
case 5:
temp.transform.LookAt(p.rotaxis.position);
break;
case 6:
float x2=Random.Range(p.Randomtransmin.x,p.Randomtransmax.x);
float y2=Random.Range(p.Randomtransmin.y,p.Randomtransmax.y);
float z2=Random.Range(p.Randomtransmin.z,p.Randomtransmax.z);
temp.transform.Translate(x2,y2,z2);
break;
case 7:
temp.transform.Translate(p.TransformVector);
break;
case 8:
temp.transform.rotation=p.rotatevector.rotation;
break;
};
}
//Maths functions section
int Probability(List<float> probabs, int size){
float sum=0f;
for (int i=0; i<size;++i) {
sum+=probabs[i];
}
float value = sum* Random.value;
if (sum == 0f)
return -1;
float sum2=probabs[0];
for ( int i=0; i< size; ++i){
if(sum2>value){
return 0;
}else if(size-i==1){
return i;
}
else if( value>sum2&&value<sum2+probabs[i+1]){
return i+1;
}
sum2+=probabs[i+1];
}
return -1;
}
}
[System.Serializable]
public class Obstacles {
public List<GameObject> poolTrack=new List<GameObject>();
public GameObject obstacle;
public int otherID=0;
public float probability=1;
public float sepdist=2;
public bool ZingVariableObject = false;
public string Name;
public TrackObstacle.transenum trans=TrackObstacle.transenum.None;
public List<Procedures> procedures=new List<Procedures>();
public bool hasNormals=false;
public List<bool> showProcedures=new List<bool>();
public List<Specific_Seperation> SpecificSeperation = new List<Specific_Seperation>();
}
[System.Serializable]
public class Specific_Seperation
{
public int index;
public float sepDist = 10f;
}
[System.Serializable]
public class Procedures {
public int id=0;
public Vector3 rot;
public Transform rotaxis;
public Vector3 add;
public Transform rotatevector;
public Vector3 Randomtransmin=Vector3.zero;
public Vector3 Randomtransmax=Vector3.one;
public Vector3 RandomRotmin=Vector3.zero;
public Vector3 RandomRotmax=Vector3.one;
public Vector3 TransformVector=Vector3.zero;
public Vector3 RandomPosmin=Vector3.zero;
public Vector3 RandomPosmax=Vector3.one;
}
| 0 | 0.908888 | 1 | 0.908888 | game-dev | MEDIA | 0.884183 | game-dev | 0.982867 | 1 | 0.982867 |
magefree/mage | 1,226 | Mage.Sets/src/mage/cards/t/TroveTracker.java | package mage.cards.t;
import mage.MageInt;
import mage.abilities.common.DiesSourceTriggeredAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.abilities.keyword.EncoreAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class TroveTracker extends CardImpl {
public TroveTracker(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{U}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.PIRATE);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// When Trove Tracker dies, draw a card.
this.addAbility(new DiesSourceTriggeredAbility(new DrawCardSourceControllerEffect(1)));
// Encore {5}{U}{U}
this.addAbility(new EncoreAbility(new ManaCostsImpl<>("{5}{U}{U}")));
}
private TroveTracker(final TroveTracker card) {
super(card);
}
@Override
public TroveTracker copy() {
return new TroveTracker(this);
}
}
| 0 | 0.99255 | 1 | 0.99255 | game-dev | MEDIA | 0.889763 | game-dev | 0.994826 | 1 | 0.994826 |
FrictionalGames/OALWrapper | 3,242 | sources/OAL_LoggerObject.cpp | /*
* Copyright 2007-2010 (C) - Frictional Games
*
* This file is part of OALWrapper
*
* For conditions of distribution and use, see copyright notice in LICENSE
*/
#include "OALWrapper/OAL_LoggerObject.h"
#include "OALWrapper/OAL_Helper.h"
#include <cstdlib>
#include <cstdio>
#include <cstdarg>
#if defined(WIN32)
#define UNICODE
#include <shlobj.h>
#endif
using namespace std;
static wstring BuildLogFilename ( const string& asFilename );
bool iOAL_LoggerObject::mbLogEnabled = false;
eOAL_LogOutput iOAL_LoggerObject::mLogOutput = eOAL_LogOutput_File;
eOAL_LogVerbose iOAL_LoggerObject::mLogVerboseLevel = eOAL_LogVerbose_Low;
wstring iOAL_LoggerObject::msLogFile = BuildLogFilename("OAL.log");
//---------------------------------------------------------------------------------------
void iOAL_LoggerObject::SetLogFilename ( const string& asLogFilename )
{
msLogFile = BuildLogFilename ( asLogFilename );
}
//---------------------------------------------------------------------------------------
void iOAL_LoggerObject::LogMsg(const string& asIDStr, eOAL_LogVerbose aVerbose, eOAL_LogMsg aType, const char* asMessage, ...)
{
if(!mbLogEnabled)
return;
if(mLogVerboseLevel < aVerbose)
return;
if(asMessage==NULL)
return;
string sMessage;
char text[2048];
va_list ap;
va_start(ap, asMessage);
vsprintf(text, asMessage, ap);
va_end(ap);
switch(aType)
{
case eOAL_LogMsg_Command:
sMessage.append("[COMMAND] ");
break;
case eOAL_LogMsg_Info:
sMessage.append("[INFO] ");
break;
case eOAL_LogMsg_Error:
sMessage.append("[ERROR] ");
}
sMessage.append(asIDStr.c_str()).append(text);
Write(sMessage);
}
//---------------------------------------------------------------------------------------
void iOAL_LoggerObject::Write( const string& asMessage )
{
if (!mbLogEnabled)
return;
FILE* fLog;
switch(mLogOutput)
{
case eOAL_LogOutput_File:
fLog = OpenFileW(msLogFile, L"a");
if (fLog != NULL)
{
fwrite(asMessage.c_str(), sizeof(char), asMessage.size(), fLog);
fclose(fLog);
}
break;
case eOAL_LogOutput_Console:
printf("%s",asMessage.c_str());
break;
default:
break;
}
}
//---------------------------------------------------------------------------------------
wstring BuildLogFilename ( const string& asFilename )
{
wstring wsName;
wstring wsTemp;
wsName = String2WString(asFilename);
#if defined(WIN32)
WCHAR sPath[MAX_PATH];
if(SUCCEEDED(SHGetFolderPath(NULL,
CSIDL_PERSONAL | CSIDL_FLAG_CREATE,
NULL,0,sPath)))
{
wsTemp = wstring(sPath).append(L"/").append(wsName);
}
else
{
return L"";
}
#else
string home = string(getenv("HOME"));
wsTemp = String2WString(home);
wsTemp.append(L"/").append(wsName);
#endif
FILE* pTempFile = NULL;
wchar_t buffer[100];
for (unsigned int i = 1; i != 0; i++)
{
swprintf(buffer, 100, L"_%d.log", i);
pTempFile = OpenFileW(wstring(wsTemp).append(wstring(buffer)),L"r");
if (pTempFile)
{
fclose(pTempFile);
//_wremove (iOAL_LoggerObject::GetLogFilename().c_str());
}
else
{
wsTemp.append(wstring(buffer));
break;
}
}
return wsTemp;
}
//---------------------------------------------------------------------------------------
| 0 | 0.978127 | 1 | 0.978127 | game-dev | MEDIA | 0.2691 | game-dev | 0.986971 | 1 | 0.986971 |
MisterJulsen/Create-Pantographs-and-Wires | 3,529 | common/src/main/java/de/mrjulsen/paw/block/abstractions/AbstractRotatableWireConnectorBlock.java | package de.mrjulsen.paw.block.abstractions;
import com.simibubi.create.foundation.block.IBE;
import com.simibubi.create.foundation.utility.VecHelper;
import de.mrjulsen.paw.util.Utils;
import de.mrjulsen.wires.block.IWireConnector;
import de.mrjulsen.wires.block.WireConnectorBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction.Axis;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.RenderShape;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.MapColor;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
public abstract class AbstractRotatableWireConnectorBlock<T extends WireConnectorBlockEntity> extends AbstractRotatableBlock implements IBE<T>, IWireConnector {
public AbstractRotatableWireConnectorBlock(Properties properties) {
super(Properties.of().mapColor(MapColor.METAL)
.noOcclusion());
}
@Override
public RenderShape getRenderShape(BlockState pState) {
return RenderShape.MODEL;
}
/**
* Rotates the wire attachment vector for the current block rotation.
* @param level The level the connector is in
* @param pos The position of the connector
* @param state The connector state
* @param itemData Additional item data
* @param firstPoint Whether this is the first connector
* @param func The function for the raw attach point calculation
* @return The transformed vector of the given function
*/
protected Vec3 transformWireAttachPoint(Level level, BlockPos pos, BlockState state, CompoundTag itemData, boolean firstPoint, IWireRenderDataCallback func) {
if (state.getBlock() instanceof IWireConnector && state.getBlock() instanceof IRotatableBlock rot) {
Vec2 pivot = rot.getRotationPivotPoint(state);
Vec2 rotPivot = rot.rotatedPivotPoint(state);
Vec2 offset = rot.getOffset(state);
Vec3 result = VecHelper.rotate(func.run(level, pos, state, itemData, firstPoint).subtract(pivot.x, 0, pivot.y), getYRotation(state), Axis.Y)
.add(rotPivot.x, 0, rotPivot.y)
.add(offset.x, 0, offset.y)
;
return result;
}
return Vec3.ZERO;
}
@Override
public CompoundTag wireRenderData(Level level, BlockPos pos, BlockState state, CompoundTag itemData, boolean firstPoint) {
CompoundTag nbt = new CompoundTag();
Utils.putNbtVec3(nbt, IWireConnector.NBT_WIRE_ATTACH_POINT, transformWireAttachPoint(level, pos, state, itemData, firstPoint, this::defaultWireAttachPoint));
return nbt;
}
/**
* The relative coordinates where a wire should be attached to.
* @param level The current level.
* @param pos The pos of the connector block.
* @param state The state of the connector block.
* @param itemData Additional data stored in the wire item created while placing it.
* @param firstPoint Whether this is the first or second connector block
* @return The relative coordinates from the block's center.
*/
protected abstract Vec3 defaultWireAttachPoint(Level level, BlockPos pos, BlockState state, CompoundTag itemData, boolean firstPoint);
@FunctionalInterface
protected static interface IWireRenderDataCallback {
Vec3 run(Level level, BlockPos pos, BlockState state, CompoundTag itemData, boolean firstPoint);
}
}
| 0 | 0.853575 | 1 | 0.853575 | game-dev | MEDIA | 0.972583 | game-dev | 0.907777 | 1 | 0.907777 |
daid/EmptyEpsilon | 6,960 | src/screenComponents/targetsContainer.cpp | #include "targetsContainer.h"
#include "playerInfo.h"
#include "systems/collision.h"
#include "components/hull.h"
#include "components/collision.h"
#include "components/scanning.h"
#include "components/radar.h"
#include "ecs/query.h"
TargetsContainer::TargetsContainer()
{
waypoint_selection_index = -1;
allow_waypoint_selection = false;
}
void TargetsContainer::clear()
{
waypoint_selection_index = -1;
entries.clear();
}
void TargetsContainer::add(sp::ecs::Entity obj)
{
if (!obj)
return;
for(auto e : entries)
if (e == obj)
return;
entries.push_back(obj);
}
void TargetsContainer::set(sp::ecs::Entity obj)
{
if (obj)
{
entries = {obj};
}
else
{
clear();
}
waypoint_selection_index = -1;
}
void TargetsContainer::set(const std::vector<sp::ecs::Entity>& objs)
{
waypoint_selection_index = -1;
entries = objs;
}
std::vector<sp::ecs::Entity> TargetsContainer::getTargets()
{
return entries;
}
sp::ecs::Entity TargetsContainer::get()
{
if (entries.empty())
return {};
return entries[0];
}
void TargetsContainer::setToClosestTo(glm::vec2 position, float max_range, ESelectionType selection_type)
{
sp::ecs::Entity target;
glm::vec2 target_position;
for(auto entity : sp::CollisionSystem::queryArea(position - glm::vec2(max_range, max_range), position + glm::vec2(max_range, max_range)))
{
auto transform = entity.getComponent<sp::Transform>();
if (!transform) continue;
if (!isValidTarget(entity, selection_type)) continue;
if (!target || glm::length2(position - transform->getPosition()) < glm::length2(position - target_position)) {
target = entity;
target_position = transform->getPosition();
}
}
if (allow_waypoint_selection)
{
if (auto lrr = my_spaceship.getComponent<LongRangeRadar>()) {
for(size_t n=0; n<lrr->waypoints.size(); n++)
{
if (glm::length2(lrr->waypoints[n] - position) < max_range*max_range)
{
if (!target || glm::length2(position - lrr->waypoints[n]) < glm::length2(position - target_position))
{
clear();
waypoint_selection_index = n;
waypoint_selection_position = lrr->waypoints[n];
return;
}
}
}
}
}
set(target);
}
int TargetsContainer::getWaypointIndex()
{
auto lrr = my_spaceship.getComponent<LongRangeRadar>();
if (!lrr || waypoint_selection_index < 0 || waypoint_selection_index >= int(lrr->waypoints.size()))
waypoint_selection_index = -1;
else if (lrr->waypoints[waypoint_selection_index] != waypoint_selection_position)
waypoint_selection_index = -1;
return waypoint_selection_index;
}
void TargetsContainer::setWaypointIndex(int index)
{
auto lrr = my_spaceship.getComponent<LongRangeRadar>();
waypoint_selection_index = index;
if (lrr && index >= 0 && index < (int)lrr->waypoints.size())
waypoint_selection_position = lrr->waypoints[index];
}
void TargetsContainer::setNext(glm::vec2 position, float max_range, ESelectionType selection_type)
{
std::vector<sp::ecs::Entity> entities;
for(auto [entity, transform] : sp::ecs::Query<sp::Transform>()) {
if(isValidTarget(entity, selection_type) && glm::distance(position, transform.getPosition()) <= max_range) {
entities.push_back(entity);
}
}
sortByDistance(position, entities);
setNext(position, max_range, entities);
}
void TargetsContainer::setNext(glm::vec2 position, float max_range, ESelectionType selection_type, FactionRelation relation)
{
std::vector<sp::ecs::Entity> entities;
for(auto [entity, transform] : sp::ecs::Query<sp::Transform>()) {
if(isValidTarget(entity, selection_type) && glm::distance(position, transform.getPosition()) <= max_range && Faction::getRelation(my_spaceship, entity) == relation) {
entities.push_back(entity);
}
}
sortByDistance(position, entities);
setNext(position, max_range, entities);
}
void TargetsContainer::setNext(glm::vec2 position, float max_range, std::vector<sp::ecs::Entity> &entities)
{
sp::ecs::Entity default_target;
sp::ecs::Entity current_target;
glm::vec2 default_target_position;
for (auto entity : entities) {
auto transform = entity.getComponent<sp::Transform>();
if (!transform)
continue;
// Start collecting nearest relevant entities in case we never run into a previous target
if (!default_target ||
glm::length2(position - transform->getPosition()) <
glm::length2(position - default_target_position)) {
default_target = entity;
default_target_position = transform->getPosition();
}
// if we set a current target in the last iteration (condition below)
// the set the entity to be this next entity in the list.
if (current_target) {
set(entity);
my_player_info->commandSetTarget(get());
return;
}
if (get() == entity) {
current_target = entity;
}
}
// If we didn't short-circuit because of an existing target above, set the
// target to be the default_target (closest to `position`)
set(default_target);
my_player_info->commandSetTarget(get());
}
void TargetsContainer::sortByDistance(glm::vec2 position, std::vector<sp::ecs::Entity>& entities)
{
sort(entities.begin(), entities.end(), [position](sp::ecs::Entity a, sp::ecs::Entity b) {
auto transform_a = a.getComponent<sp::Transform>();
auto transform_b = b.getComponent<sp::Transform>();
if (!transform_a)
return bool(transform_b);
if (!transform_b)
return bool(transform_a);
return glm::distance(position, transform_a->getPosition()) < glm::distance(position, transform_b->getPosition());
});
}
bool TargetsContainer::isValidTarget(sp::ecs::Entity entity, ESelectionType selection_type)
{
if (entity == my_spaceship) return false;
switch(selection_type)
{
case Selectable:
if (entity.hasComponent<Hull>()) return true;
if (entity.getComponent<ScanState>()) return true;
if (entity.getComponent<ShareShortRangeRadar>()) return true;
break;
case Targetable:
if (entity.hasComponent<Hull>()) return true;
break;
case Scannable:
if (entity.hasComponent<Hull>()) return true;
if (entity.getComponent<ScanState>()) return true;
if (entity.getComponent<ScienceDescription>()) return true;
if (entity.getComponent<ShareShortRangeRadar>()) return true;
break;
}
return false;
}
| 0 | 0.929211 | 1 | 0.929211 | game-dev | MEDIA | 0.831649 | game-dev | 0.980853 | 1 | 0.980853 |
TheLimeGlass/Skellett | 2,590 | src/main/java/com/gmail/thelimeglass/Expressions/ExprPistonPower.java | package com.gmail.thelimeglass.Expressions;
import org.bukkit.Bukkit;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.event.Event;
import org.bukkit.material.MaterialData;
import org.bukkit.material.PistonBaseMaterial;
import org.eclipse.jdt.annotation.Nullable;
import com.gmail.thelimeglass.Utils.Annotations.Config;
import com.gmail.thelimeglass.Utils.Annotations.PropertyType;
import com.gmail.thelimeglass.Utils.Annotations.Syntax;
import ch.njol.skript.classes.Changer;
import ch.njol.skript.classes.Changer.ChangeMode;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.ExpressionType;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
import ch.njol.util.coll.CollectionUtils;
@Syntax({"[skellett] piston[s] (power|toggle) [state] of %block%", "%block%'s piston (power|toggle) [state]"})
@Config("PistonPower")
@PropertyType(ExpressionType.COMBINED)
public class ExprPistonPower extends SimpleExpression<Boolean>{
private Expression<Block> block;
@Override
public Class<? extends Boolean> getReturnType() {
return Boolean.class;
}
@Override
public boolean isSingle() {
return true;
}
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] e, int arg1, Kleenean arg2, ParseResult arg3) {
block = (Expression<Block>) e[0];
return true;
}
@Override
public String toString(@Nullable Event e, boolean arg1) {
return "[skellett] piston[s] (power|toggle) [state] of %block%";
}
@Override
@Nullable
protected Boolean[] get(Event e) {
MaterialData piston = block.getSingle(e).getState().getData();
if (piston instanceof PistonBaseMaterial) {
return new Boolean[]{((PistonBaseMaterial)piston).isPowered()};
}
return null;
}
@Override
public void change(Event e, Object[] delta, Changer.ChangeMode mode){
if (mode == ChangeMode.SET) {
BlockState state = block.getSingle(e).getState();
MaterialData piston = state.getData();
if (piston instanceof PistonBaseMaterial) {
((PistonBaseMaterial)piston).setPowered((Boolean)delta[0]);
state.setData(piston);
state.update(true, false);
Bukkit.getLogger().info(((PistonBaseMaterial)piston).isPowered() + " TEST1");
Bukkit.getLogger().info(((PistonBaseMaterial)block.getSingle(e).getState().getData()).isPowered() + " TEST2");
}
}
}
@Override
public Class<?>[] acceptChange(final Changer.ChangeMode mode) {
if (mode == ChangeMode.SET) {
return CollectionUtils.array(Boolean.class);
}
return null;
}
} | 0 | 0.757461 | 1 | 0.757461 | game-dev | MEDIA | 0.736356 | game-dev | 0.837456 | 1 | 0.837456 |
kreezii/jsgam | 1,844 | src/class/logo.js | import { gsap } from "gsap";
class Logo{
constructor(game){
this.game=game;
this.index=0;
this.timeoutID=null;
this.tween=null;
this.image=new PIXI.Sprite(
PIXI.Texture.from(this.game.settings.Logos[this.index]));
this.image.anchor.set(0.5,0.5)
this.image.position.set(this.game.width/2,this.game.height/2)
this.image.interactive=true;
this.image.buttonMode=true;
this.image.on('pointertap',this.fadeOut.bind(this));
this.image.alpha=0;
}
show(){
this.game.app.stage.addChild(this.image);
this.fadeIn();
}
fadeIn(){
if(this.tween) this.tween.kill();
this.tween=gsap.set(this.image,{alpha:0});
this.tween=gsap.fromTo(this.image, {alpha:0}, {duration:1, alpha:1, onComplete:this.timer.bind(this)});
}
timer(){
this.timeoutID = setTimeout(this.fadeOut.bind(this), 3*1000);
}
fadeOut(){
this.image.interactive=false;
if(this.tween) this.tween.kill();
this.tween=gsap.fromTo(this.image, {alpha:1}, {duration:1, alpha:0, onComplete:this.next.bind(this)});
}
next(){
this.image.interactive=true;
if(this.timeoutID) clearTimeout(this.timeoutID);
this.index++;
if(this.game.settings.Logos[this.index]!==undefined)
{
this.image.texture=(PIXI.Texture.from
(this.game.settings.Logos[this.index]));
this.fadeIn();
}
else this.end();
}
end(){
if(this.timeoutID) clearTimeout(this.timeoutID);
if(this.tween) this.tween.kill();
this.game.app.stage.removeChild(this.image);
//Set Title as the first scene to show
this.game.setScene(this.game.titleLabel);
this.game.fadeIn();
if(this.game.options!==null){
this.game.app.stage.addChild(this.game.options.icon);
this.game.app.stage.addChild(this.game.options.container);
}
}
}
export default Logo;
| 0 | 0.577201 | 1 | 0.577201 | game-dev | MEDIA | 0.640263 | game-dev | 0.816266 | 1 | 0.816266 |
inglettronald/DulkirMod | 1,586 | src/main/kotlin/dulkirmod/features/chat/AbiphoneDND.kt | package dulkirmod.features.chat
import dulkirmod.config.DulkirConfig
import dulkirmod.utils.TextUtils
import net.minecraftforge.client.event.ClientChatReceivedEvent
import net.minecraftforge.client.event.sound.PlaySoundEvent
import net.minecraftforge.fml.common.eventhandler.EventPriority
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
private val abiphoneFormat = "✆ (\\w+) ✆ ".toRegex()
private var lastRing: Long = 0
object AbiphoneDND {
//BLOCK ABIPHONE SOUNDS
@SubscribeEvent(receiveCanceled = false, priority = EventPriority.LOW)
fun onSound(event: PlaySoundEvent) {
if (!DulkirConfig.abiDND) return
if (System.currentTimeMillis() - lastRing < 5000) {
if (event.name == "note.pling" && event.sound.volume == 0.69f && event.sound.pitch == 1.6666666f) {
event.result = null
}
}
}
fun handle(event: ClientChatReceivedEvent, unformatted: String) {
if (!DulkirConfig.abiDND) return
if (unformatted matches abiphoneFormat && !unformatted.contains("Elle") && !unformatted.contains("Dean")) {
val matchResult = abiphoneFormat.find(unformatted)
event.isCanceled = true
lastRing = System.currentTimeMillis()
if (DulkirConfig.abiCallerID) {
val blocked = if (Math.random() < .001) "Breefing"
else matchResult?.groups?.get(1)?.value
TextUtils.info("§6Call blocked from $blocked!")
}
}
if (unformatted.startsWith("✆ Ring...") && unformatted.endsWith("[PICK UP]")
&& System.currentTimeMillis() - lastRing < 5000
) {
event.isCanceled = true
}
}
} | 0 | 0.863331 | 1 | 0.863331 | game-dev | MEDIA | 0.355166 | game-dev | 0.867064 | 1 | 0.867064 |
defold/defold | 11,012 | external/bullet3d/package/bullet-2.77/src/BulletCollision/CollisionShapes/btHeightfieldTerrainShape.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btHeightfieldTerrainShape.h"
#include "LinearMath/btTransformUtil.h"
btHeightfieldTerrainShape::btHeightfieldTerrainShape
(
int heightStickWidth, int heightStickLength, void* heightfieldData,
btScalar heightScale, btScalar minHeight, btScalar maxHeight,int upAxis,
PHY_ScalarType hdt, bool flipQuadEdges
)
{
initialize(heightStickWidth, heightStickLength, heightfieldData,
heightScale, minHeight, maxHeight, upAxis, hdt,
flipQuadEdges);
}
btHeightfieldTerrainShape::btHeightfieldTerrainShape(int heightStickWidth, int heightStickLength,void* heightfieldData,btScalar maxHeight,int upAxis,bool useFloatData,bool flipQuadEdges)
{
// legacy constructor: support only float or unsigned char,
// and min height is zero
PHY_ScalarType hdt = (useFloatData) ? PHY_FLOAT : PHY_UCHAR;
btScalar minHeight = 0.0;
// previously, height = uchar * maxHeight / 65535.
// So to preserve legacy behavior, heightScale = maxHeight / 65535
btScalar heightScale = maxHeight / 65535;
initialize(heightStickWidth, heightStickLength, heightfieldData,
heightScale, minHeight, maxHeight, upAxis, hdt,
flipQuadEdges);
}
void btHeightfieldTerrainShape::initialize
(
int heightStickWidth, int heightStickLength, void* heightfieldData,
btScalar heightScale, btScalar minHeight, btScalar maxHeight, int upAxis,
PHY_ScalarType hdt, bool flipQuadEdges
)
{
// validation
btAssert(heightStickWidth > 1 && "bad width");
btAssert(heightStickLength > 1 && "bad length");
btAssert(heightfieldData && "null heightfield data");
// btAssert(heightScale) -- do we care? Trust caller here
btAssert(minHeight <= maxHeight && "bad min/max height");
btAssert(upAxis >= 0 && upAxis < 3 &&
"bad upAxis--should be in range [0,2]");
btAssert(hdt != PHY_UCHAR || hdt != PHY_FLOAT || hdt != PHY_SHORT &&
"Bad height data type enum");
// initialize member variables
m_shapeType = TERRAIN_SHAPE_PROXYTYPE;
m_heightStickWidth = heightStickWidth;
m_heightStickLength = heightStickLength;
m_minHeight = minHeight;
m_maxHeight = maxHeight;
m_width = (btScalar) (heightStickWidth - 1);
m_length = (btScalar) (heightStickLength - 1);
m_heightScale = heightScale;
m_heightfieldDataUnknown = heightfieldData;
m_heightDataType = hdt;
m_flipQuadEdges = flipQuadEdges;
m_useDiamondSubdivision = false;
m_upAxis = upAxis;
m_localScaling.setValue(btScalar(1.), btScalar(1.), btScalar(1.));
// determine min/max axis-aligned bounding box (aabb) values
switch (m_upAxis)
{
case 0:
{
m_localAabbMin.setValue(m_minHeight, 0, 0);
m_localAabbMax.setValue(m_maxHeight, m_width, m_length);
break;
}
case 1:
{
m_localAabbMin.setValue(0, m_minHeight, 0);
m_localAabbMax.setValue(m_width, m_maxHeight, m_length);
break;
};
case 2:
{
m_localAabbMin.setValue(0, 0, m_minHeight);
m_localAabbMax.setValue(m_width, m_length, m_maxHeight);
break;
}
default:
{
//need to get valid m_upAxis
btAssert(0 && "Bad m_upAxis");
}
}
// remember origin (defined as exact middle of aabb)
m_localOrigin = btScalar(0.5) * (m_localAabbMin + m_localAabbMax);
}
btHeightfieldTerrainShape::~btHeightfieldTerrainShape()
{
}
void btHeightfieldTerrainShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
{
btVector3 halfExtents = (m_localAabbMax-m_localAabbMin)* m_localScaling * btScalar(0.5);
btVector3 localOrigin(0, 0, 0);
localOrigin[m_upAxis] = (m_minHeight + m_maxHeight) * btScalar(0.5);
localOrigin *= m_localScaling;
btMatrix3x3 abs_b = t.getBasis().absolute();
btVector3 center = t.getOrigin();
btVector3 extent = btVector3(abs_b[0].dot(halfExtents),
abs_b[1].dot(halfExtents),
abs_b[2].dot(halfExtents));
extent += btVector3(getMargin(),getMargin(),getMargin());
aabbMin = center - extent;
aabbMax = center + extent;
}
/// This returns the "raw" (user's initial) height, not the actual height.
/// The actual height needs to be adjusted to be relative to the center
/// of the heightfield's AABB.
btScalar
btHeightfieldTerrainShape::getRawHeightFieldValue(int x,int y) const
{
btScalar val = 0.f;
switch (m_heightDataType)
{
case PHY_FLOAT:
{
val = m_heightfieldDataFloat[(y*m_heightStickWidth)+x];
break;
}
case PHY_UCHAR:
{
unsigned char heightFieldValue = m_heightfieldDataUnsignedChar[(y*m_heightStickWidth)+x];
val = heightFieldValue * m_heightScale;
break;
}
case PHY_SHORT:
{
short hfValue = m_heightfieldDataShort[(y * m_heightStickWidth) + x];
val = hfValue * m_heightScale;
break;
}
default:
{
btAssert(!"Bad m_heightDataType");
}
}
return val;
}
/// this returns the vertex in bullet-local coordinates
void btHeightfieldTerrainShape::getVertex(int x,int y,btVector3& vertex) const
{
btAssert(x>=0);
btAssert(y>=0);
btAssert(x<m_heightStickWidth);
btAssert(y<m_heightStickLength);
btScalar height = getRawHeightFieldValue(x,y);
switch (m_upAxis)
{
case 0:
{
vertex.setValue(
height - m_localOrigin.getX(),
(-m_width/btScalar(2.0)) + x,
(-m_length/btScalar(2.0) ) + y
);
break;
}
case 1:
{
vertex.setValue(
(-m_width/btScalar(2.0)) + x,
height - m_localOrigin.getY(),
(-m_length/btScalar(2.0)) + y
);
break;
};
case 2:
{
vertex.setValue(
(-m_width/btScalar(2.0)) + x,
(-m_length/btScalar(2.0)) + y,
height - m_localOrigin.getZ()
);
break;
}
default:
{
//need to get valid m_upAxis
btAssert(0);
}
}
vertex*=m_localScaling;
}
static inline int
getQuantized
(
btScalar x
)
{
if (x < 0.0) {
return (int) (x - 0.5);
}
return (int) (x + 0.5);
}
/// given input vector, return quantized version
/**
This routine is basically determining the gridpoint indices for a given
input vector, answering the question: "which gridpoint is closest to the
provided point?".
"with clamp" means that we restrict the point to be in the heightfield's
axis-aligned bounding box.
*/
void btHeightfieldTerrainShape::quantizeWithClamp(int* out, const btVector3& point,int /*isMax*/) const
{
btVector3 clampedPoint(point);
clampedPoint.setMax(m_localAabbMin);
clampedPoint.setMin(m_localAabbMax);
out[0] = getQuantized(clampedPoint.getX());
out[1] = getQuantized(clampedPoint.getY());
out[2] = getQuantized(clampedPoint.getZ());
}
/// process all triangles within the provided axis-aligned bounding box
/**
basic algorithm:
- convert input aabb to local coordinates (scale down and shift for local origin)
- convert input aabb to a range of heightfield grid points (quantize)
- iterate over all triangles in that subset of the grid
*/
void btHeightfieldTerrainShape::processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const
{
// scale down the input aabb's so they are in local (non-scaled) coordinates
btVector3 localAabbMin = aabbMin*btVector3(1.f/m_localScaling[0],1.f/m_localScaling[1],1.f/m_localScaling[2]);
btVector3 localAabbMax = aabbMax*btVector3(1.f/m_localScaling[0],1.f/m_localScaling[1],1.f/m_localScaling[2]);
// account for local origin
localAabbMin += m_localOrigin;
localAabbMax += m_localOrigin;
//quantize the aabbMin and aabbMax, and adjust the start/end ranges
int quantizedAabbMin[3];
int quantizedAabbMax[3];
quantizeWithClamp(quantizedAabbMin, localAabbMin,0);
quantizeWithClamp(quantizedAabbMax, localAabbMax,1);
// expand the min/max quantized values
// this is to catch the case where the input aabb falls between grid points!
for (int i = 0; i < 3; ++i) {
quantizedAabbMin[i]--;
quantizedAabbMax[i]++;
}
int startX=0;
int endX=m_heightStickWidth-1;
int startJ=0;
int endJ=m_heightStickLength-1;
switch (m_upAxis)
{
case 0:
{
if (quantizedAabbMin[1]>startX)
startX = quantizedAabbMin[1];
if (quantizedAabbMax[1]<endX)
endX = quantizedAabbMax[1];
if (quantizedAabbMin[2]>startJ)
startJ = quantizedAabbMin[2];
if (quantizedAabbMax[2]<endJ)
endJ = quantizedAabbMax[2];
break;
}
case 1:
{
if (quantizedAabbMin[0]>startX)
startX = quantizedAabbMin[0];
if (quantizedAabbMax[0]<endX)
endX = quantizedAabbMax[0];
if (quantizedAabbMin[2]>startJ)
startJ = quantizedAabbMin[2];
if (quantizedAabbMax[2]<endJ)
endJ = quantizedAabbMax[2];
break;
};
case 2:
{
if (quantizedAabbMin[0]>startX)
startX = quantizedAabbMin[0];
if (quantizedAabbMax[0]<endX)
endX = quantizedAabbMax[0];
if (quantizedAabbMin[1]>startJ)
startJ = quantizedAabbMin[1];
if (quantizedAabbMax[1]<endJ)
endJ = quantizedAabbMax[1];
break;
}
default:
{
//need to get valid m_upAxis
btAssert(0);
}
}
for(int j=startJ; j<endJ; j++)
{
for(int x=startX; x<endX; x++)
{
btVector3 vertices[3];
if (m_flipQuadEdges || (m_useDiamondSubdivision && !((j+x) & 1)))
{
//first triangle
getVertex(x,j,vertices[0]);
getVertex(x+1,j,vertices[1]);
getVertex(x+1,j+1,vertices[2]);
callback->processTriangle(vertices,x,j);
//second triangle
getVertex(x,j,vertices[0]);
getVertex(x+1,j+1,vertices[1]);
getVertex(x,j+1,vertices[2]);
callback->processTriangle(vertices,x,j);
} else
{
//first triangle
getVertex(x,j,vertices[0]);
getVertex(x,j+1,vertices[1]);
getVertex(x+1,j,vertices[2]);
callback->processTriangle(vertices,x,j);
//second triangle
getVertex(x+1,j,vertices[0]);
getVertex(x,j+1,vertices[1]);
getVertex(x+1,j+1,vertices[2]);
callback->processTriangle(vertices,x,j);
}
}
}
}
void btHeightfieldTerrainShape::calculateLocalInertia(btScalar ,btVector3& inertia) const
{
//moving concave objects not supported
inertia.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
}
void btHeightfieldTerrainShape::setLocalScaling(const btVector3& scaling)
{
m_localScaling = scaling;
}
const btVector3& btHeightfieldTerrainShape::getLocalScaling() const
{
return m_localScaling;
}
| 0 | 0.978348 | 1 | 0.978348 | game-dev | MEDIA | 0.983137 | game-dev | 0.996691 | 1 | 0.996691 |
ps2dev/ps2sdk-ports | 3,140 | sdl/include/SDL.h | /*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2004 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Sam Lantinga
slouken@libsdl.org
*/
#ifdef SAVE_RCSID
static char rcsid =
"@(#) $Id$";
#endif
/* Main include header for the SDL library */
#ifndef _SDL_H
#define _SDL_H
#include "SDL_main.h"
#include "SDL_types.h"
#include "SDL_getenv.h"
#include "SDL_error.h"
#include "SDL_rwops.h"
#include "SDL_timer.h"
#include "SDL_audio.h"
#include "SDL_cdrom.h"
#include "SDL_joystick.h"
#include "SDL_events.h"
#include "SDL_video.h"
#include "SDL_byteorder.h"
#include "SDL_version.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* As of version 0.5, SDL is loaded dynamically into the application */
/* These are the flags which may be passed to SDL_Init() -- you should
specify the subsystems which you will be using in your application.
*/
#define SDL_INIT_TIMER 0x00000001
#define SDL_INIT_AUDIO 0x00000010
#define SDL_INIT_VIDEO 0x00000020
#define SDL_INIT_CDROM 0x00000100
#define SDL_INIT_JOYSTICK 0x00000200
#define SDL_INIT_NOPARACHUTE 0x00100000 /* Don't catch fatal signals */
#define SDL_INIT_EVENTTHREAD 0x01000000 /* Not supported on all OS's */
#define SDL_INIT_EVERYTHING 0x0000FFFF
/* This function loads the SDL dynamically linked library and initializes
* the subsystems specified by 'flags' (and those satisfying dependencies)
* Unless the SDL_INIT_NOPARACHUTE flag is set, it will install cleanup
* signal handlers for some commonly ignored fatal signals (like SIGSEGV)
*/
extern DECLSPEC int SDLCALL SDL_Init(Uint32 flags);
/* This function initializes specific SDL subsystems */
extern DECLSPEC int SDLCALL SDL_InitSubSystem(Uint32 flags);
/* This function cleans up specific SDL subsystems */
extern DECLSPEC void SDLCALL SDL_QuitSubSystem(Uint32 flags);
/* This function returns mask of the specified subsystems which have
been initialized.
If 'flags' is 0, it returns a mask of all initialized subsystems.
*/
extern DECLSPEC Uint32 SDLCALL SDL_WasInit(Uint32 flags);
/* This function cleans up all initialized subsystems and unloads the
* dynamically linked library. You should call it upon all exit conditions.
*/
extern DECLSPEC void SDLCALL SDL_Quit(void);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* _SDL_H */
| 0 | 0.783796 | 1 | 0.783796 | game-dev | MEDIA | 0.459627 | game-dev | 0.515448 | 1 | 0.515448 |
TheAnswer/Core3 | 4,097 | MMOCoreORB/src/server/zone/objects/creature/commands/RegisterWithLocationCommand.h | /*
Copyright <SWGEmu>
See file COPYING for copying conditions.*/
#ifndef REGISTERWITHLOCATIONCOMMAND_H_
#define REGISTERWITHLOCATIONCOMMAND_H_
#include "templates/building/SharedBuildingObjectTemplate.h"
class RegisterWithLocationCommand : public QueueCommand {
public:
RegisterWithLocationCommand(const String& name, ZoneProcessServer* server)
: QueueCommand(name, server) {
}
int doQueueCommand(CreatureObject* player, const uint64& target, const UnicodeString& arguments) const {
if (!checkStateMask(player))
return INVALIDSTATE;
if (!checkInvalidLocomotions(player))
return INVALIDLOCOMOTION;
if (!player->isPlayerCreature())
return GENERALERROR;
ManagedReference<BuildingObject*> building = cast<BuildingObject*>(player->getRootParent());
// If outside don't bother doing anything ...
if (building == nullptr) {
player->sendSystemMessage("@faction/faction_hq/faction_hq_response:no_support"); // This location does not support active/inactive registration status.
return GENERALERROR;
}
bool medBuilding = isInMedicalBuilding(player, building);
bool entBuilding = isInEntertainingBuilding(player, building);
bool novDoc = isNoviceDoctor(player);
bool novEnt = isNoviceEntertainer(player);
if (medBuilding && entBuilding) {
if (novDoc || novEnt) {
addPlayerToBuilding(player, building);
return SUCCESS;
}
} else if (medBuilding) {
if (novDoc) {
addPlayerToBuilding(player, building);
return SUCCESS;
} else {
player->sendSystemMessage("@faction/faction_hq/faction_hq_response:no_skills"); // You lack the appropriate skill-set to activate this location.
return GENERALERROR;
}
} else if (entBuilding) {
if (novEnt) {
addPlayerToBuilding(player, building);
return SUCCESS;
} else {
player->sendSystemMessage("@faction/faction_hq/faction_hq_response:no_skills"); // You lack the appropriate skill-set to activate this location.
return GENERALERROR;
}
} else {
player->sendSystemMessage("@faction/faction_hq/faction_hq_response:no_support"); // This location does not support active/inactive registration status.
return GENERALERROR;
}
return SUCCESS;
}
void addPlayerToBuilding(CreatureObject* player, BuildingObject* building) const {
Locker blocker(building, player);
building->registerProfessional(player);
}
bool isNoviceDoctor(CreatureObject* player) const {
return player->hasSkill("science_doctor_novice");
}
bool isNoviceEntertainer(CreatureObject* player) const {
return (player->hasSkill("social_musician_novice") || player->hasSkill("social_dancer_novice"));
}
bool isInMedicalBuilding(CreatureObject* player, BuildingObject* building) const {
const PlanetMapCategory* pmc = building->getPlanetMapCategory();
if (pmc == nullptr)
return false;
String categoryName = pmc->getName();
if (categoryName == "medicalcenter" || categoryName == "tavern")
return true;
if (categoryName == "imperial" || categoryName == "rebel") {
const SharedBuildingObjectTemplate* buildingTemplate = cast<const SharedBuildingObjectTemplate*>(building->getObjectTemplate());
if (buildingTemplate != nullptr && buildingTemplate->getSkillMod("private_medical_rating") > 0) {
return true;
}
}
return false;
}
bool isInEntertainingBuilding(CreatureObject* player, BuildingObject* building) const {
const PlanetMapCategory* pmc = building->getPlanetMapCategory();
if (pmc == nullptr)
return false;
String categoryName = pmc->getName();
if (categoryName == "hotel" || categoryName == "cantina" || categoryName == "theater" || categoryName == "guild_theater" || categoryName == "tavern")
return true;
if (categoryName == "imperial" || categoryName == "rebel") {
const SharedBuildingObjectTemplate* buildingTemplate = cast<const SharedBuildingObjectTemplate*>(building->getObjectTemplate());
if (buildingTemplate != nullptr && buildingTemplate->getSkillMod("private_med_battle_fatigue") > 0) {
return true;
}
}
return false;
}
};
#endif //REGISTERWITHLOCATIONCOMMAND_H_
| 0 | 0.8299 | 1 | 0.8299 | game-dev | MEDIA | 0.971571 | game-dev | 0.757581 | 1 | 0.757581 |
Lux-AI-Challenge/Lux-Design-S1 | 6,340 | kits/cpp/simple-transpiled/lux/kit.hpp | // source ../LuxAI/transpilers/emsdk/emsdk_env.sh
// emcc -s FORCE_FILESYSTEM=1 --pre-js init_fs.js hello.cpp
#ifndef kit_h
#define kit_h
#include <ostream>
#include <string>
#include <iostream>
#include <vector>
#include "map.hpp"
#include "lux_io.hpp"
#include "game_objects.hpp"
#include "annotate.hpp"
#include "city.hpp"
namespace kit
{
using namespace std;
static string getline()
{
// exit if stdin is bad now
if (!cin.good())
exit(0);
char str[2048], ch;
int i = 0;
ch = getchar();
while (ch != '\n')
{
str[i] = ch;
i++;
ch = getchar();
}
str[i] = '\0';
// return the line
return string(str);
}
static vector<string> tokenize(string s, string del = " ")
{
vector<string> strings = vector<string>();
int start = 0;
int end = s.find(del);
while (end != -1)
{
strings.push_back(s.substr(start, end - start));
start = end + del.size();
end = s.find(del, start);
}
strings.push_back(s.substr(start, end - start));
return strings;
}
class Agent
{
public:
int id;
int turn = -1;
int mapWidth = -1;
int mapHeight = -1;
lux::GameMap map;
lux::Player players[2] = {lux::Player(0), lux::Player(1)};
Agent()
{
}
/**
* Initialize Agent for the `Match`
* User should edit this according to their `Design`
*/
void initialize()
{
// get agent ID
id = stoi(kit::getline());
string map_info = kit::getline();
vector<string> map_parts = kit::tokenize(map_info, " ");
mapWidth = stoi(map_parts[0]);
mapHeight = stoi(map_parts[1]);
map = lux::GameMap(mapWidth, mapHeight);
}
// end a turn
static void end_turn()
{
cout << "D_FINISH" << endl
<< std::flush;
}
/**
* Updates agent's own known state of `Match`.
* User should edit this according to their `Design`.
*/
void update()
{
turn++;
resetPlayerStates();
map = lux::GameMap(mapWidth, mapHeight);
while (true)
{
string updateInfo = kit::getline();
if (updateInfo == INPUT_CONSTANTS::DONE)
{
break;
}
vector<string> updates = kit::tokenize(updateInfo, " ");
string input_identifier = updates[0];
if (input_identifier == INPUT_CONSTANTS::RESEARCH_POINTS)
{
int team = stoi(updates[1]);
players[team].researchPoints = stoi(updates[2]);
}
else if (input_identifier == INPUT_CONSTANTS::RESOURCES)
{
string type = updates[1];
int x = stoi(updates[2]);
int y = stoi(updates[3]);
int amt = stoi(updates[4]);
lux::ResourceType rtype = lux::ResourceType(type.at(0));
map._setResource(rtype, x, y, amt);
}
else if (input_identifier == INPUT_CONSTANTS::UNITS)
{
int i = 1;
int unittype = stoi(updates[i++]);
int team = stoi(updates[i++]);
string unitid = updates[i++];
int x = stoi(updates[i++]);
int y = stoi(updates[i++]);
float cooldown = stof(updates[i++]);
int wood = stoi(updates[i++]);
int coal = stoi(updates[i++]);
int uranium = stoi(updates[i++]);
lux::Unit unit = lux::Unit(team, unittype, unitid, x, y, cooldown, wood, coal, uranium);
players[team].units.push_back(unit);
}
else if (input_identifier == INPUT_CONSTANTS::CITY)
{
int i = 1;
int team = stoi(updates[i++]);
string cityid = updates[i++];
float fuel = stof(updates[i++]);
float lightUpkeep = stof(updates[i++]);
players[team].cities[cityid] = lux::City(team, cityid, fuel, lightUpkeep);
}
else if (input_identifier == INPUT_CONSTANTS::CITY_TILES)
{
int i = 1;
int team = stoi(updates[i++]);
string cityid = updates[i++];
int x = stoi(updates[i++]);
int y = stoi(updates[i++]);
float cooldown = stof(updates[i++]);
lux::City * city = &players[team].cities[cityid];
city->addCityTile(x, y, cooldown);
players[team].cityTileCount += 1;
}
else if (input_identifier == INPUT_CONSTANTS::ROADS)
{
int i = 1;
int x = stoi(updates[i++]);
int y = stoi(updates[i++]);
float road = stof(updates[i++]);
lux::Cell * cell = map.getCell(x, y);
cell->road = road;
}
}
for (lux::Player &player : players)
{
for (auto &element : player.cities)
{
lux::City &city = element.second;
for (lux::CityTile &citytile : city.citytiles)
{
const lux::Position &pos = citytile.pos;
map.getCell(pos.x, pos.y)->citytile = &citytile;
}
}
}
}
private:
void resetPlayerStates()
{
for (int team = 0; team < 2; team++)
{
players[team].units.clear();
players[team].cities.clear();
players[team].cityTileCount = 0;
}
}
};
}
#endif
| 0 | 0.898659 | 1 | 0.898659 | game-dev | MEDIA | 0.899216 | game-dev | 0.984856 | 1 | 0.984856 |
aajiwani/EasyNDK-for-cocos2dx | 3,033 | Chartboost iOS Sample Project/SampleNDK/libs/extensions/GUI/CCEditBox/CCEditBoxImpl.h | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2012 James Chen
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCEditBoxIMPL_H__
#define __CCEditBoxIMPL_H__
#include "cocos2d.h"
#include "ExtensionMacros.h"
#include "CCEditBox.h"
NS_CC_EXT_BEGIN
class CCEditBoxImpl
{
public:
CCEditBoxImpl(CCEditBox* pEditBox) : m_pEditBox(pEditBox), m_pDelegate(NULL) {}
virtual ~CCEditBoxImpl() {}
virtual bool initWithSize(const CCSize& size) = 0;
virtual void setFontColor(const ccColor3B& color) = 0;
virtual void setPlaceholderFontColor(const ccColor3B& color) = 0;
virtual void setInputMode(EditBoxInputMode inputMode) = 0;
virtual void setInputFlag(EditBoxInputFlag inputFlag) = 0;
virtual void setMaxLength(int maxLength) = 0;
virtual int getMaxLength() = 0;
virtual void setReturnType(KeyboardReturnType returnType) = 0;
virtual bool isEditing() = 0;
virtual void setText(const char* pText) = 0;
virtual const char* getText(void) = 0;
virtual void setPlaceHolder(const char* pText) = 0;
virtual void doAnimationWhenKeyboardMove(float duration, float distance) = 0;
virtual void openKeyboard() = 0;
virtual void closeKeyboard() = 0;
virtual void setPosition(const CCPoint& pos) = 0;
virtual void setContentSize(const CCSize& size) = 0;
virtual void visit(void) = 0;
void setDelegate(CCEditBoxDelegate* pDelegate) { m_pDelegate = pDelegate; };
CCEditBoxDelegate* getDelegate() { return m_pDelegate; };
CCEditBox* getCCEditBox() { return m_pEditBox; };
protected:
CCEditBoxDelegate* m_pDelegate;
CCEditBox* m_pEditBox;
};
// This method must be implemented at each subclass of CCEditBoxImpl.
extern CCEditBoxImpl* __createSystemEditBox(CCEditBox* pEditBox);
NS_CC_EXT_END
#endif /* __CCEditBoxIMPL_H__ */
| 0 | 0.852769 | 1 | 0.852769 | game-dev | MEDIA | 0.808057 | game-dev | 0.519798 | 1 | 0.519798 |
PlayFab/UnrealMarketplacePlugin | 22,016 | 5.5/PlayFabPlugin/PlayFab/Source/PlayFabCpp/Public/Core/PlayFabDataDataModels.h | //////////////////////////////////////////////////////
// Copyright (C) Microsoft. 2018. All rights reserved.
//////////////////////////////////////////////////////
// This is automatically generated by PlayFab SDKGenerator. DO NOT modify this manually!
#pragma once
#include "CoreMinimal.h"
#include "PlayFabCppBaseModel.h"
namespace PlayFab
{
namespace DataModels
{
struct PLAYFABCPP_API FEntityKey : public PlayFab::FPlayFabCppBaseModel
{
// Unique ID of the entity.
FString Id;
// [optional] Entity type. See https://docs.microsoft.com/gaming/playfab/features/data/entities/available-built-in-entity-types
FString Type;
FEntityKey() :
FPlayFabCppBaseModel(),
Id(),
Type()
{}
FEntityKey(const FEntityKey& src) = default;
FEntityKey(const TSharedPtr<FJsonObject>& obj) : FEntityKey()
{
readFromValue(obj);
}
~FEntityKey();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FAbortFileUploadsRequest : public PlayFab::FPlayFabCppRequestCommon
{
// [optional] The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
TMap<FString, FString> CustomTags;
// The entity to perform this action on.
FEntityKey Entity;
// Names of the files to have their pending uploads aborted.
TArray<FString> FileNames;
/**
* [optional] The expected version of the profile, if set and doesn't match the current version of the profile the operation will not
* be performed.
*/
Boxed<int32> ProfileVersion;
FAbortFileUploadsRequest() :
FPlayFabCppRequestCommon(),
CustomTags(),
Entity(),
FileNames(),
ProfileVersion()
{}
FAbortFileUploadsRequest(const FAbortFileUploadsRequest& src) = default;
FAbortFileUploadsRequest(const TSharedPtr<FJsonObject>& obj) : FAbortFileUploadsRequest()
{
readFromValue(obj);
}
~FAbortFileUploadsRequest();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FAbortFileUploadsResponse : public PlayFab::FPlayFabCppResultCommon
{
// [optional] The entity id and type.
TSharedPtr<FEntityKey> Entity;
// The current version of the profile, can be used for concurrency control during updates.
int32 ProfileVersion;
FAbortFileUploadsResponse() :
FPlayFabCppResultCommon(),
Entity(nullptr),
ProfileVersion(0)
{}
FAbortFileUploadsResponse(const FAbortFileUploadsResponse& src) = default;
FAbortFileUploadsResponse(const TSharedPtr<FJsonObject>& obj) : FAbortFileUploadsResponse()
{
readFromValue(obj);
}
~FAbortFileUploadsResponse();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FDeleteFilesRequest : public PlayFab::FPlayFabCppRequestCommon
{
// [optional] The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
TMap<FString, FString> CustomTags;
// The entity to perform this action on.
FEntityKey Entity;
// Names of the files to be deleted.
TArray<FString> FileNames;
/**
* [optional] The expected version of the profile, if set and doesn't match the current version of the profile the operation will not
* be performed.
*/
Boxed<int32> ProfileVersion;
FDeleteFilesRequest() :
FPlayFabCppRequestCommon(),
CustomTags(),
Entity(),
FileNames(),
ProfileVersion()
{}
FDeleteFilesRequest(const FDeleteFilesRequest& src) = default;
FDeleteFilesRequest(const TSharedPtr<FJsonObject>& obj) : FDeleteFilesRequest()
{
readFromValue(obj);
}
~FDeleteFilesRequest();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FDeleteFilesResponse : public PlayFab::FPlayFabCppResultCommon
{
// [optional] The entity id and type.
TSharedPtr<FEntityKey> Entity;
// The current version of the profile, can be used for concurrency control during updates.
int32 ProfileVersion;
FDeleteFilesResponse() :
FPlayFabCppResultCommon(),
Entity(nullptr),
ProfileVersion(0)
{}
FDeleteFilesResponse(const FDeleteFilesResponse& src) = default;
FDeleteFilesResponse(const TSharedPtr<FJsonObject>& obj) : FDeleteFilesResponse()
{
readFromValue(obj);
}
~FDeleteFilesResponse();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FFinalizeFileUploadsRequest : public PlayFab::FPlayFabCppRequestCommon
{
// [optional] The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
TMap<FString, FString> CustomTags;
// The entity to perform this action on.
FEntityKey Entity;
// Names of the files to be finalized. Restricted to a-Z, 0-9, '(', ')', '_', '-' and '.'
TArray<FString> FileNames;
// The current version of the profile, can be used for concurrency control during updates.
int32 ProfileVersion;
FFinalizeFileUploadsRequest() :
FPlayFabCppRequestCommon(),
CustomTags(),
Entity(),
FileNames(),
ProfileVersion(0)
{}
FFinalizeFileUploadsRequest(const FFinalizeFileUploadsRequest& src) = default;
FFinalizeFileUploadsRequest(const TSharedPtr<FJsonObject>& obj) : FFinalizeFileUploadsRequest()
{
readFromValue(obj);
}
~FFinalizeFileUploadsRequest();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FGetFileMetadata : public PlayFab::FPlayFabCppBaseModel
{
// [optional] Checksum value for the file, can be used to check if the file on the server has changed.
FString Checksum;
// [optional] Download URL where the file can be retrieved
FString DownloadUrl;
// [optional] Name of the file
FString FileName;
// Last UTC time the file was modified
FDateTime LastModified;
// Storage service's reported byte count
int32 Size;
FGetFileMetadata() :
FPlayFabCppBaseModel(),
Checksum(),
DownloadUrl(),
FileName(),
LastModified(0),
Size(0)
{}
FGetFileMetadata(const FGetFileMetadata& src) = default;
FGetFileMetadata(const TSharedPtr<FJsonObject>& obj) : FGetFileMetadata()
{
readFromValue(obj);
}
~FGetFileMetadata();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FFinalizeFileUploadsResponse : public PlayFab::FPlayFabCppResultCommon
{
// [optional] The entity id and type.
TSharedPtr<FEntityKey> Entity;
// [optional] Collection of metadata for the entity's files
TMap<FString, FGetFileMetadata> Metadata;
// The current version of the profile, can be used for concurrency control during updates.
int32 ProfileVersion;
FFinalizeFileUploadsResponse() :
FPlayFabCppResultCommon(),
Entity(nullptr),
Metadata(),
ProfileVersion(0)
{}
FFinalizeFileUploadsResponse(const FFinalizeFileUploadsResponse& src) = default;
FFinalizeFileUploadsResponse(const TSharedPtr<FJsonObject>& obj) : FFinalizeFileUploadsResponse()
{
readFromValue(obj);
}
~FFinalizeFileUploadsResponse();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FGetFilesRequest : public PlayFab::FPlayFabCppRequestCommon
{
// [optional] The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
TMap<FString, FString> CustomTags;
// The entity to perform this action on.
FEntityKey Entity;
FGetFilesRequest() :
FPlayFabCppRequestCommon(),
CustomTags(),
Entity()
{}
FGetFilesRequest(const FGetFilesRequest& src) = default;
FGetFilesRequest(const TSharedPtr<FJsonObject>& obj) : FGetFilesRequest()
{
readFromValue(obj);
}
~FGetFilesRequest();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FGetFilesResponse : public PlayFab::FPlayFabCppResultCommon
{
// [optional] The entity id and type.
TSharedPtr<FEntityKey> Entity;
// [optional] Collection of metadata for the entity's files
TMap<FString, FGetFileMetadata> Metadata;
// The current version of the profile, can be used for concurrency control during updates.
int32 ProfileVersion;
FGetFilesResponse() :
FPlayFabCppResultCommon(),
Entity(nullptr),
Metadata(),
ProfileVersion(0)
{}
FGetFilesResponse(const FGetFilesResponse& src) = default;
FGetFilesResponse(const TSharedPtr<FJsonObject>& obj) : FGetFilesResponse()
{
readFromValue(obj);
}
~FGetFilesResponse();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FGetObjectsRequest : public PlayFab::FPlayFabCppRequestCommon
{
// [optional] The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
TMap<FString, FString> CustomTags;
// The entity to perform this action on.
FEntityKey Entity;
/**
* [optional] Determines whether the object will be returned as an escaped JSON string or as a un-escaped JSON object. Default is JSON
* object.
*/
Boxed<bool> EscapeObject;
FGetObjectsRequest() :
FPlayFabCppRequestCommon(),
CustomTags(),
Entity(),
EscapeObject()
{}
FGetObjectsRequest(const FGetObjectsRequest& src) = default;
FGetObjectsRequest(const TSharedPtr<FJsonObject>& obj) : FGetObjectsRequest()
{
readFromValue(obj);
}
~FGetObjectsRequest();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FObjectResult : public PlayFab::FPlayFabCppBaseModel
{
// [optional] Un-escaped JSON object, if EscapeObject false or default.
FJsonKeeper DataObject;
// [optional] Escaped string JSON body of the object, if EscapeObject is true.
FString EscapedDataObject;
// [optional] Name of the object. Restricted to a-Z, 0-9, '(', ')', '_', '-' and '.'
FString ObjectName;
FObjectResult() :
FPlayFabCppBaseModel(),
DataObject(),
EscapedDataObject(),
ObjectName()
{}
FObjectResult(const FObjectResult& src) = default;
FObjectResult(const TSharedPtr<FJsonObject>& obj) : FObjectResult()
{
readFromValue(obj);
}
~FObjectResult();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FGetObjectsResponse : public PlayFab::FPlayFabCppResultCommon
{
// [optional] The entity id and type.
TSharedPtr<FEntityKey> Entity;
// [optional] Requested objects that the calling entity has access to
TMap<FString, FObjectResult> Objects;
// The current version of the profile, can be used for concurrency control during updates.
int32 ProfileVersion;
FGetObjectsResponse() :
FPlayFabCppResultCommon(),
Entity(nullptr),
Objects(),
ProfileVersion(0)
{}
FGetObjectsResponse(const FGetObjectsResponse& src) = default;
FGetObjectsResponse(const TSharedPtr<FJsonObject>& obj) : FGetObjectsResponse()
{
readFromValue(obj);
}
~FGetObjectsResponse();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FInitiateFileUploadMetadata : public PlayFab::FPlayFabCppBaseModel
{
// [optional] Name of the file.
FString FileName;
// [optional] Location the data should be sent to via an HTTP PUT operation.
FString UploadUrl;
FInitiateFileUploadMetadata() :
FPlayFabCppBaseModel(),
FileName(),
UploadUrl()
{}
FInitiateFileUploadMetadata(const FInitiateFileUploadMetadata& src) = default;
FInitiateFileUploadMetadata(const TSharedPtr<FJsonObject>& obj) : FInitiateFileUploadMetadata()
{
readFromValue(obj);
}
~FInitiateFileUploadMetadata();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FInitiateFileUploadsRequest : public PlayFab::FPlayFabCppRequestCommon
{
// [optional] The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
TMap<FString, FString> CustomTags;
// The entity to perform this action on.
FEntityKey Entity;
// Names of the files to be set. Restricted to a-Z, 0-9, '(', ')', '_', '-' and '.'
TArray<FString> FileNames;
/**
* [optional] The expected version of the profile, if set and doesn't match the current version of the profile the operation will not
* be performed.
*/
Boxed<int32> ProfileVersion;
FInitiateFileUploadsRequest() :
FPlayFabCppRequestCommon(),
CustomTags(),
Entity(),
FileNames(),
ProfileVersion()
{}
FInitiateFileUploadsRequest(const FInitiateFileUploadsRequest& src) = default;
FInitiateFileUploadsRequest(const TSharedPtr<FJsonObject>& obj) : FInitiateFileUploadsRequest()
{
readFromValue(obj);
}
~FInitiateFileUploadsRequest();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FInitiateFileUploadsResponse : public PlayFab::FPlayFabCppResultCommon
{
// [optional] The entity id and type.
TSharedPtr<FEntityKey> Entity;
// The current version of the profile, can be used for concurrency control during updates.
int32 ProfileVersion;
// [optional] Collection of file names and upload urls
TArray<FInitiateFileUploadMetadata> UploadDetails;
FInitiateFileUploadsResponse() :
FPlayFabCppResultCommon(),
Entity(nullptr),
ProfileVersion(0),
UploadDetails()
{}
FInitiateFileUploadsResponse(const FInitiateFileUploadsResponse& src) = default;
FInitiateFileUploadsResponse(const TSharedPtr<FJsonObject>& obj) : FInitiateFileUploadsResponse()
{
readFromValue(obj);
}
~FInitiateFileUploadsResponse();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
enum OperationTypes
{
OperationTypesCreated,
OperationTypesUpdated,
OperationTypesDeleted,
OperationTypesNone
};
PLAYFABCPP_API void writeOperationTypesEnumJSON(OperationTypes enumVal, JsonWriter& writer);
PLAYFABCPP_API OperationTypes readOperationTypesFromValue(const TSharedPtr<FJsonValue>& value);
PLAYFABCPP_API OperationTypes readOperationTypesFromValue(const FString& value);
struct PLAYFABCPP_API FSetObject : public PlayFab::FPlayFabCppBaseModel
{
/**
* [optional] Body of the object to be saved. If empty and DeleteObject is true object will be deleted if it exists, or no operation
* will occur if it does not exist. Only one of Object or EscapedDataObject fields may be used.
*/
FJsonKeeper DataObject;
// [optional] Flag to indicate that this object should be deleted. Both DataObject and EscapedDataObject must not be set as well.
Boxed<bool> DeleteObject;
/**
* [optional] Body of the object to be saved as an escaped JSON string. If empty and DeleteObject is true object will be deleted if it
* exists, or no operation will occur if it does not exist. Only one of DataObject or EscapedDataObject fields may be used.
*/
FString EscapedDataObject;
// Name of object. Restricted to a-Z, 0-9, '(', ')', '_', '-' and '.'.
FString ObjectName;
FSetObject() :
FPlayFabCppBaseModel(),
DataObject(),
DeleteObject(),
EscapedDataObject(),
ObjectName()
{}
FSetObject(const FSetObject& src) = default;
FSetObject(const TSharedPtr<FJsonObject>& obj) : FSetObject()
{
readFromValue(obj);
}
~FSetObject();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FSetObjectInfo : public PlayFab::FPlayFabCppBaseModel
{
// [optional] Name of the object
FString ObjectName;
// [optional] Optional reason to explain why the operation was the result that it was.
FString OperationReason;
// [optional] Indicates which operation was completed, either Created, Updated, Deleted or None.
Boxed<OperationTypes> SetResult;
FSetObjectInfo() :
FPlayFabCppBaseModel(),
ObjectName(),
OperationReason(),
SetResult()
{}
FSetObjectInfo(const FSetObjectInfo& src) = default;
FSetObjectInfo(const TSharedPtr<FJsonObject>& obj) : FSetObjectInfo()
{
readFromValue(obj);
}
~FSetObjectInfo();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FSetObjectsRequest : public PlayFab::FPlayFabCppRequestCommon
{
// [optional] The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
TMap<FString, FString> CustomTags;
// The entity to perform this action on.
FEntityKey Entity;
/**
* [optional] Optional field used for concurrency control. By specifying the previously returned value of ProfileVersion from
* GetProfile API, you can ensure that the object set will only be performed if the profile has not been updated by any
* other clients since the version you last loaded.
*/
Boxed<int32> ExpectedProfileVersion;
// Collection of objects to set on the profile.
TArray<FSetObject> Objects;
FSetObjectsRequest() :
FPlayFabCppRequestCommon(),
CustomTags(),
Entity(),
ExpectedProfileVersion(),
Objects()
{}
FSetObjectsRequest(const FSetObjectsRequest& src) = default;
FSetObjectsRequest(const TSharedPtr<FJsonObject>& obj) : FSetObjectsRequest()
{
readFromValue(obj);
}
~FSetObjectsRequest();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
struct PLAYFABCPP_API FSetObjectsResponse : public PlayFab::FPlayFabCppResultCommon
{
// New version of the entity profile.
int32 ProfileVersion;
// [optional] New version of the entity profile.
TArray<FSetObjectInfo> SetResults;
FSetObjectsResponse() :
FPlayFabCppResultCommon(),
ProfileVersion(0),
SetResults()
{}
FSetObjectsResponse(const FSetObjectsResponse& src) = default;
FSetObjectsResponse(const TSharedPtr<FJsonObject>& obj) : FSetObjectsResponse()
{
readFromValue(obj);
}
~FSetObjectsResponse();
void writeJSON(JsonWriter& writer) const override;
bool readFromValue(const TSharedPtr<FJsonObject>& obj) override;
};
}
}
| 0 | 0.613177 | 1 | 0.613177 | game-dev | MEDIA | 0.665457 | game-dev | 0.684494 | 1 | 0.684494 |
rjkiv/dc3-decomp | 3,675 | src/system/flow/FlowNode.h | #pragma once
#include "obj/Object.h"
// #include "flow/DrivenPropertyEntry.h"
#include "utl/MemMgr.h"
class Flow;
class DrivenPropertyEntry;
/** "A flow node" */
class FlowNode : public virtual Hmx::Object {
public:
enum QueueState {
/** "If we're activated, ignore the activation" */
kIgnore = 0,
/** "New activations go in the queue and are executed when this one finishes" */
kQueue = 1,
/** "New activations go into a one deep queue and are executed when this one
* finishes" */
kQueueOne = 2,
/** "Forcably stop what we're doing and restart" */
kImmediate = 3,
/** "Ask our children to stop, then run again when they finish" */
kWhenAble = 4
};
enum StopMode {
/** "Stop immediately." */
kStopImmediate = 0,
/** "Stop at the end of this action." */
kStopLastFrame = 1,
/** "Stop at the next stop marker (stop) or at the end of this action." */
kStopOnMarker = 2,
/** "Stop if between a stop and no_stop marker, or at the end of the action." */
kStopBetweenMarkers = 3,
/** "When asked to stop, release but leave the sound playing." */
kReleaseAndContinue = 4
};
enum OperatorType {
kEqual,
kNotEqual,
kGreaterThan,
kGreaterThanOrEqual,
kLessThan,
kLessThanOrEqual,
kTransition
};
// Hmx::Object
virtual ~FlowNode();
OBJ_CLASSNAME(FlowNode)
OBJ_SET_TYPE(FlowNode)
virtual DataNode Handle(DataArray *, bool);
virtual bool SyncProperty(DataNode &, DataArray *, int, PropOp);
virtual void Save(BinStream &);
virtual void Copy(const Hmx::Object *, CopyType);
virtual void Load(BinStream &);
virtual const char *FindPathName();
// FlowNode
virtual void SetParent(FlowNode *, bool);
virtual FlowNode *GetParent() { return mParent; }
virtual bool Activate();
virtual void Deactivate(bool);
virtual void ChildFinished(FlowNode *);
virtual void RequestStop();
virtual void RequestStopCancel();
virtual void Execute(QueueState) {}
virtual bool IsRunning();
virtual Flow *GetOwnerFlow();
virtual void MiloPreRun();
virtual void MoveIntoDir(ObjectDir *, ObjectDir *);
virtual void UpdateIntensity();
OBJ_MEM_OVERLOAD(0x9F)
NEW_OBJ(FlowNode)
static FlowNode *DuplicateChild(FlowNode *);
static Hmx::Object *LoadObjectFromMainOrDir(BinStream &, ObjectDir *);
bool HasRunningNode(FlowNode *);
DrivenPropertyEntry *GetDrivenEntry(Symbol);
DrivenPropertyEntry *GetDrivenEntry(DataArray *);
Flow *GetTopFlow();
protected:
FlowNode();
static bool sPushDrivenProperties;
static float sIntensity;
void ActivateChild(FlowNode *);
void PushDrivenProperties(void);
bool mDebugOutput; // 0x8
String mDebugComment; // 0xc
ObjPtrVec<FlowNode> mVec1; // 0x14
ObjPtrList<FlowNode> mRunningNodes; // 0x30
FlowNode *mParent; // 0x44
ObjVector<DrivenPropertyEntry> mDrivenPropEntries; // 0x48
bool unk58; // 0x58
};
#define FLOW_LOG(...) \
if (mDebugOutput) { \
MILO_LOG("%s: %s", ClassName(), MakeString(__VA_ARGS__)); \
if (!mDebugComment.empty()) { \
MILO_LOG("Debug comment: %s\n", mDebugComment.c_str()); \
} \
}
| 0 | 0.968579 | 1 | 0.968579 | game-dev | MEDIA | 0.51133 | game-dev | 0.807233 | 1 | 0.807233 |
b1inkie/dst-api | 1,530 | scripts_619045/prefabs/quagmire_salt_rack.lua | local assets =
{
Asset("ANIM", "anim/quagmire_salt_rack.zip"),
}
local prefabs =
{
"quagmire_salt_rack_item",
"quagmire_saltrock",
"collapse_small",
"splash",
}
local prefabs_item =
{
"quagmire_salt_rack",
}
local function fn()
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()
inst.entity:AddNetwork()
inst.AnimState:SetBank("quagmire_salt_rack")
inst.AnimState:SetBuild("quagmire_salt_rack")
inst.AnimState:PlayAnimation("idle", true)
inst.AnimState:Hide("salt")
MakeObstaclePhysics(inst, 1.95)
MakeSnowCoveredPristine(inst)
inst.entity:SetPristine()
if not TheWorld.ismastersim then
return inst
end
event_server_data("quagmire", "prefabs/quagmire_salt_rack").master_postinit(inst)
return inst
end
local function itemfn()
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddAnimState()
inst.entity:AddNetwork()
MakeInventoryPhysics(inst)
inst.AnimState:SetBank("quagmire_pot_hanger")
inst.AnimState:SetBuild("quagmire_pot_hanger")
inst.AnimState:PlayAnimation("item")
inst.entity:SetPristine()
if not TheWorld.ismastersim then
return inst
end
event_server_data("quagmire", "prefabs/quagmire_salt_rack").master_postinit_item(inst)
return inst
end
return Prefab("quagmire_salt_rack", fn, assets, prefabs),
Prefab("quagmire_salt_rack_item", itemfn, assets, prefabs_item)
| 0 | 0.66045 | 1 | 0.66045 | game-dev | MEDIA | 0.966706 | game-dev | 0.644657 | 1 | 0.644657 |
magefree/mage | 1,748 | Mage.Sets/src/mage/cards/e/EternalSkylord.java | package mage.cards.e;
import mage.MageInt;
import mage.abilities.common.EntersBattlefieldTriggeredAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.continuous.GainAbilityControlledEffect;
import mage.abilities.effects.keyword.AmassEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.SubType;
import mage.filter.FilterPermanent;
import mage.filter.predicate.permanent.TokenPredicate;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class EternalSkylord extends CardImpl {
private static final FilterPermanent filter
= new FilterPermanent(SubType.ZOMBIE, "Zombie tokens");
static {
filter.add(TokenPredicate.TRUE);
}
public EternalSkylord(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{U}");
this.subtype.add(SubType.ZOMBIE);
this.subtype.add(SubType.WIZARD);
this.power = new MageInt(3);
this.toughness = new MageInt(3);
// When Eternal Skylord enters the batttlefield, amass 2.
this.addAbility(new EntersBattlefieldTriggeredAbility(new AmassEffect(2, SubType.ZOMBIE)));
// Zombie tokens you control have flying.
this.addAbility(new SimpleStaticAbility(new GainAbilityControlledEffect(
FlyingAbility.getInstance(), Duration.WhileOnBattlefield, filter
)));
}
private EternalSkylord(final EternalSkylord card) {
super(card);
}
@Override
public EternalSkylord copy() {
return new EternalSkylord(this);
}
}
| 0 | 0.911347 | 1 | 0.911347 | game-dev | MEDIA | 0.942275 | game-dev | 0.979496 | 1 | 0.979496 |
Eaglercraft-Archive/Eaglercraftx-1.8.8-src | 1,853 | patches/minecraft/net/minecraft/client/renderer/ChunkRenderContainer.edit.java |
# Eagler Context Redacted Diff
# Copyright (c) 2025 lax1dude. All rights reserved.
# Version: 1.0
# Author: lax1dude
> DELETE 2 @ 2 : 3
> CHANGE 1 : 7 @ 1 : 2
~
~ import com.google.common.collect.Lists;
~
~ import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager;
~ import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager;
~ import net.lax1dude.eaglercraft.v1_8.opengl.ext.dynamiclights.DynamicLightsStateManager;
> INSERT 3 : 4 @ 3
+ import net.minecraft.util.MathHelper;
> CHANGE 16 : 17 @ 16 : 17
~ public void preRenderChunk(RenderChunk renderChunkIn, EnumWorldBlockLayer enumworldblocklayer) {
> CHANGE 1 : 16 @ 1 : 4
~ float posX = (float) ((double) blockpos.getX() - this.viewEntityX);
~ float posY = (float) ((double) blockpos.getY() - this.viewEntityY);
~ float posZ = (float) ((double) blockpos.getZ() - this.viewEntityZ);
~ GlStateManager.translate(posX, posY, posZ);
~ if (DeferredStateManager.isInForwardPass()) {
~ posX = (float) (blockpos.getX() - (MathHelper.floor_double(this.viewEntityX / 16.0) << 4));
~ posY = (float) (blockpos.getY() - (MathHelper.floor_double(this.viewEntityY / 16.0) << 4));
~ posZ = (float) (blockpos.getZ() - (MathHelper.floor_double(this.viewEntityZ / 16.0) << 4));
~ DeferredStateManager.reportForwardRenderObjectPosition((int) posX, (int) posY, (int) posZ);
~ } else if (DynamicLightsStateManager.isInDynamicLightsPass()) {
~ posX = (float) (blockpos.getX() - (MathHelper.floor_double(this.viewEntityX / 16.0) << 4));
~ posY = (float) (blockpos.getY() - (MathHelper.floor_double(this.viewEntityY / 16.0) << 4));
~ posZ = (float) (blockpos.getZ() - (MathHelper.floor_double(this.viewEntityZ / 16.0) << 4));
~ DynamicLightsStateManager.reportForwardRenderObjectPosition((int) posX, (int) posY, (int) posZ);
~ }
> EOF
| 0 | 0.858718 | 1 | 0.858718 | game-dev | MEDIA | 0.681507 | game-dev,graphics-rendering | 0.933134 | 1 | 0.933134 |
gkursi/Pulse-client | 2,480 | src/main/java/xyz/qweru/pulse/client/systems/modules/impl/misc/TotemDupe.java | package xyz.qweru.pulse.client.systems.modules.impl.misc;
import net.minecraft.item.Items;
import net.minecraft.world.WorldEvents;
import xyz.qweru.pulse.client.systems.modules.Category;
import xyz.qweru.pulse.client.systems.modules.ClientModule;
import xyz.qweru.pulse.client.systems.modules.settings.impl.BooleanSetting;
import xyz.qweru.pulse.client.systems.modules.settings.impl.NumberSetting;
import xyz.qweru.pulse.client.utils.Util;
import xyz.qweru.pulse.client.utils.player.ChatUtil;
import xyz.qweru.pulse.client.utils.player.InventoryUtils;
import xyz.qweru.pulse.client.utils.player.SlotUtil;
import xyz.qweru.pulse.client.utils.thread.ThreadManager;
import static xyz.qweru.pulse.client.PulseClient.mc;
public class TotemDupe extends ClientModule {
private final NumberSetting dupeItemCount = new NumberSetting("Dupe item count", "How many times should dupe", 1f, 64f, 16f, true);
private final NumberSetting delay = new NumberSetting("Delay", "time in ms between actions", 0f, 1000f, 50f, true);
// todo
// BooleanSetting auto = booleanSetting()
// .name("Auto")
// .description("Automatically dupe once totem count is below the set number")
// .build();
//
// private final NumberSetting autoC = new NumberSetting("Trigger Count",
// "if auto is enabled, totems will be automatically duped if the total count is smaller or equal to this number",
// 1f, 36f, 10f, true);
public TotemDupe() {
builder()
.name("Totem Dupe")
.description("On play.dupeanarchy.com, bypass for quickly duping totems")
.category(Category.MISC)
.settings(dupeItemCount, delay);
dupeItemCount.setValueModifier((value -> (int) value));
delay.setValueModifier((value -> (int) value));
}
@Override
public void enable() {
super.enable();
toggle();
ThreadManager.cachedPool.submit(() -> {
if(Util.nullCheck()) return;
int c = dupeItemCount.getValueInt();
int slot = InventoryUtils.getItemSlotAll(Items.TOTEM_OF_UNDYING);
if(slot == -1) return;
int to = mc.player.getInventory().selectedSlot;
SlotUtil.swapInv(slot, to);
Util.sleep(delay.getValueLong());
ChatUtil.sendServerMsg("/dupe " + c);
Util.sleep(delay.getValueLong());
SlotUtil.swapBack();
});
}
}
| 0 | 0.903074 | 1 | 0.903074 | game-dev | MEDIA | 0.851737 | game-dev | 0.955312 | 1 | 0.955312 |
KC3Kai/KC3Kai | 1,982 | src/library/modules/BattlePrediction/Battle.js | (function () {
const battle = {};
const { pipe, juxt, flatten, reduce } = KC3BattlePrediction;
/*--------------------------------------------------------*/
/* ----------------------[ PUBLIC ]---------------------- */
/*--------------------------------------------------------*/
battle.simulateBattle = (battleData, initalFleets, battleType) => {
const { battle: { getPhases }, fleets: { simulateAttack } } = KC3BattlePrediction;
battle.battleType = battleType;
return pipe(
juxt(getPhases(battleType)),
flatten,
reduce(simulateAttack, initalFleets)
)(battleData);
};
battle.simulateBattlePartially = (battleData, initalFleets, battlePhases = []) => {
const { fleets: { simulateAttack } } = KC3BattlePrediction;
const { getPhaseParser } = KC3BattlePrediction.battle;
// User-defined phases only used by SupportFleet/LBAS analyzing for now, build a pseudo battleType here
battle.battleType = {
player: KC3BattlePrediction.Player.SINGLE,
enemy: KC3BattlePrediction.Enemy.SINGLE,
time: KC3BattlePrediction.Time.DAY,
phases: battlePhases
};
return pipe(
juxt(battlePhases.map(getPhaseParser)),
flatten,
reduce(simulateAttack, initalFleets)
)(battleData);
};
battle.getBattleType = () => {
return battle.battleType || {};
};
/*--------------------------------------------------------*/
/* ---------------------[ INTERNAL ]--------------------- */
/*--------------------------------------------------------*/
battle.getPhases = (battleType) => {
const { getBattlePhases, getPhaseParser } = KC3BattlePrediction.battle;
return getBattlePhases(battleType).map(getPhaseParser);
};
/*--------------------------------------------------------*/
/* ---------------------[ EXPORTS ]---------------------- */
/*--------------------------------------------------------*/
Object.assign(window.KC3BattlePrediction.battle, battle);
}());
| 0 | 0.684132 | 1 | 0.684132 | game-dev | MEDIA | 0.772547 | game-dev | 0.543394 | 1 | 0.543394 |
cubk1/vapev3-opensource | 1,931 | gg/vape/module/none/Friends.java | package gg.vape.module.none;
import gg.vape.Vape;
import gg.vape.event.impl.EventChat;
import gg.vape.event.impl.EventNameFormat;
import gg.vape.friend.Friend;
import gg.vape.module.Category;
import gg.vape.module.Mod;
import gg.vape.wrapper.impl.TextComponentString;
import java.util.Iterator;
public class Friends extends Mod {
public Friends() {
super("Friends", 0, 0, Category.None, null);
}
public void c8731() {
this.c141();
}
public void onNameFormat(EventNameFormat event) {
if (Vape.instance.getFriendManager().forceAlias.getValue()) {
Friend var2 = Vape.instance.getFriendManager().c6216(event.c4561(), false);
if (Vape.instance.getFriendManager().forceAlias.getValue()) {
if (var2 != null && var2.inFriends()) {
event.c6485(var2.c5811());
}
} else {
event.c6485(event.c1336());
}
}
}
public void onChat(EventChat event) {
if (Vape.instance.getFriendManager().forceAlias.getValue()) {
Iterator var2 = Vape.instance.getFriendManager().getFriends().iterator();
while(true) {
Friend var3;
do {
do {
if (!var2.hasNext()) {
return;
}
var3 = (Friend)var2.next();
} while(!var3.inFriends());
} while(!event.c8633().c376().toLowerCase().contains(var3.c3125().toLowerCase()));
String var4 = event.c8633().c693();
for(int var5 = var4.toLowerCase().indexOf(var3.c3125().toLowerCase()); var5 >= 0; var5 = var4.toLowerCase().indexOf(var3.c3125())) {
String var6 = var4.substring(var5, var5 + var3.c3125().toLowerCase().length());
var4 = var4.replaceAll(var6, var3.c3501());
}
event.c4469(TextComponentString.c546(var4));
}
}
}
}
| 0 | 0.795379 | 1 | 0.795379 | game-dev | MEDIA | 0.785584 | game-dev | 0.609394 | 1 | 0.609394 |
AirFoundation/Naven-NoAuth | 3,930 | src/main/java/net/minecraft/client/resources/SimpleReloadableResourceManager.java | package net.minecraft.client.resources;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.minecraft.client.resources.data.IMetadataSerializer;
import net.minecraft.util.ResourceLocation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class SimpleReloadableResourceManager implements IReloadableResourceManager {
private static final Logger logger = LogManager.getLogger();
private static final Joiner joinerResourcePacks = Joiner.on(", ");
private final Map<String, FallbackResourceManager> domainResourceManagers = Maps.newHashMap();
private final List<IResourceManagerReloadListener> reloadListeners = Lists.newArrayList();
private final Set<String> setResourceDomains = Sets.newLinkedHashSet();
private final IMetadataSerializer rmMetadataSerializer;
public SimpleReloadableResourceManager(IMetadataSerializer rmMetadataSerializerIn) {
this.rmMetadataSerializer = rmMetadataSerializerIn;
}
public void reloadResourcePack(IResourcePack resourcePack) {
for (String s : resourcePack.getResourceDomains()) {
this.setResourceDomains.add(s);
FallbackResourceManager fallbackresourcemanager = this.domainResourceManagers.get(s);
if (fallbackresourcemanager == null) {
fallbackresourcemanager = new FallbackResourceManager(this.rmMetadataSerializer);
this.domainResourceManagers.put(s, fallbackresourcemanager);
}
fallbackresourcemanager.addResourcePack(resourcePack);
}
}
public Set<String> getResourceDomains() {
return this.setResourceDomains;
}
public IResource getResource(ResourceLocation location) throws IOException {
IResourceManager iresourcemanager = this.domainResourceManagers.get(location.getResourceDomain());
if (iresourcemanager != null) {
return iresourcemanager.getResource(location);
} else {
throw new FileNotFoundException(location.toString());
}
}
public List<IResource> getAllResources(ResourceLocation location) throws IOException {
IResourceManager iresourcemanager = this.domainResourceManagers.get(location.getResourceDomain());
if (iresourcemanager != null) {
return iresourcemanager.getAllResources(location);
} else {
throw new FileNotFoundException(location.toString());
}
}
private void clearResources() {
this.domainResourceManagers.clear();
this.setResourceDomains.clear();
}
public void reloadResources(List<IResourcePack> resourcesPacksList) {
this.clearResources();
logger.info("Reloading ResourceManager: " + joinerResourcePacks.join(Iterables.transform(resourcesPacksList, new Function<IResourcePack, String>() {
public String apply(IResourcePack p_apply_1_) {
return p_apply_1_.getPackName();
}
})));
for (IResourcePack iresourcepack : resourcesPacksList) {
this.reloadResourcePack(iresourcepack);
}
this.notifyReloadListeners();
}
public void registerReloadListener(IResourceManagerReloadListener reloadListener) {
this.reloadListeners.add(reloadListener);
reloadListener.onResourceManagerReload(this);
}
private void notifyReloadListeners() {
for (IResourceManagerReloadListener iresourcemanagerreloadlistener : this.reloadListeners) {
iresourcemanagerreloadlistener.onResourceManagerReload(this);
}
}
}
| 0 | 0.915299 | 1 | 0.915299 | game-dev | MEDIA | 0.467164 | game-dev | 0.990305 | 1 | 0.990305 |
qcdong2016/QCEditor | 11,080 | cocos2d/extensions/physics-nodes/CCPhysicsSprite.cpp | /* Copyright (c) 2012 Scott Lembcke and Howling Moon Software
* Copyright (c) 2012 cocos2d-x.org
* Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "CCPhysicsSprite.h"
#include "base/CCDirector.h"
#include "base/CCEventDispatcher.h"
#if (CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION)
#if (CC_ENABLE_CHIPMUNK_INTEGRATION && CC_ENABLE_BOX2D_INTEGRATION)
#error "Either Chipmunk or Box2d should be enabled, but not both at the same time"
#endif
#if CC_ENABLE_CHIPMUNK_INTEGRATION
#include "chipmunk/chipmunk.h"
#elif CC_ENABLE_BOX2D_INTEGRATION
#include "Box2D/Box2D.h"
#endif
NS_CC_EXT_BEGIN
PhysicsSprite::PhysicsSprite()
: _ignoreBodyRotation(false)
, _CPBody(nullptr)
, _pB2Body(nullptr)
, _PTMRatio(0.0f)
, _syncTransform(nullptr)
{}
PhysicsSprite* PhysicsSprite::create()
{
PhysicsSprite* pRet = new (std::nothrow) PhysicsSprite();
if (pRet && pRet->init())
{
pRet->autorelease();
}
else
{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
PhysicsSprite* PhysicsSprite::createWithTexture(Texture2D *pTexture)
{
PhysicsSprite* pRet = new (std::nothrow) PhysicsSprite();
if (pRet && pRet->initWithTexture(pTexture))
{
pRet->autorelease();
}
else
{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
PhysicsSprite* PhysicsSprite::createWithTexture(Texture2D *pTexture, const Rect& rect)
{
PhysicsSprite* pRet = new (std::nothrow) PhysicsSprite();
if (pRet && pRet->initWithTexture(pTexture, rect))
{
pRet->autorelease();
}
else
{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
PhysicsSprite* PhysicsSprite::createWithSpriteFrame(SpriteFrame *pSpriteFrame)
{
PhysicsSprite* pRet = new (std::nothrow) PhysicsSprite();
if (pRet && pRet->initWithSpriteFrame(pSpriteFrame))
{
pRet->autorelease();
}
else
{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
PhysicsSprite* PhysicsSprite::createWithSpriteFrameName(const char *pszSpriteFrameName)
{
PhysicsSprite* pRet = new (std::nothrow) PhysicsSprite();
if (pRet && pRet->initWithSpriteFrameName(pszSpriteFrameName))
{
pRet->autorelease();
}
else
{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
PhysicsSprite* PhysicsSprite::create(const char *pszFileName)
{
PhysicsSprite* pRet = new (std::nothrow) PhysicsSprite();
if (pRet && pRet->initWithFile(pszFileName))
{
pRet->autorelease();
}
else
{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
PhysicsSprite* PhysicsSprite::create(const char *pszFileName, const Rect& rect)
{
PhysicsSprite* pRet = new (std::nothrow) PhysicsSprite();
if (pRet && pRet->initWithFile(pszFileName, rect))
{
pRet->autorelease();
}
else
{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
// this method will only get called if the sprite is batched.
// return YES if the physic's values (angles, position ) changed.
// If you return NO, then getNodeToParentTransform won't be called.
bool PhysicsSprite::isDirty() const
{
return true;
}
bool PhysicsSprite::isIgnoreBodyRotation() const
{
return _ignoreBodyRotation;
}
void PhysicsSprite::setIgnoreBodyRotation(bool bIgnoreBodyRotation)
{
_ignoreBodyRotation = bIgnoreBodyRotation;
}
// Override the setters and getters to always reflect the body's properties.
const Vec2& PhysicsSprite::getPosition() const
{
return getPosFromPhysics();
}
void PhysicsSprite::getPosition(float* x, float* y) const
{
if (x == nullptr || y == nullptr) {
return;
}
const Vec2& pos = getPosFromPhysics();
*x = pos.x;
*y = pos.y;
}
float PhysicsSprite::getPositionX() const
{
return getPosFromPhysics().x;
}
float PhysicsSprite::getPositionY() const
{
return getPosFromPhysics().y;
}
Vec3 PhysicsSprite::getPosition3D() const
{
Vec2 pos = getPosFromPhysics();
return Vec3(pos.x, pos.y, 0);
}
//
// Chipmunk only
//
cpBody* PhysicsSprite::getCPBody() const
{
#if CC_ENABLE_CHIPMUNK_INTEGRATION
return _CPBody;
#else
CCASSERT(false, "Can't call chipmunk methods when Chipmunk is disabled");
return nullptr;
#endif
}
void PhysicsSprite::setCPBody(cpBody *pBody)
{
#if CC_ENABLE_CHIPMUNK_INTEGRATION
_CPBody = pBody;
#else
CCASSERT(false, "Can't call chipmunk methods when Chipmunk is disabled");
#endif
}
b2Body* PhysicsSprite::getB2Body() const
{
#if CC_ENABLE_BOX2D_INTEGRATION
return _pB2Body;
#else
CCASSERT(false, "Can't call box2d methods when Box2d is disabled");
return nullptr;
#endif
}
void PhysicsSprite::setB2Body(b2Body *pBody)
{
#if CC_ENABLE_BOX2D_INTEGRATION
_pB2Body = pBody;
#else
CC_UNUSED_PARAM(pBody);
CCASSERT(false, "Can't call box2d methods when Box2d is disabled");
#endif
}
float PhysicsSprite::getPTMRatio() const
{
#if CC_ENABLE_BOX2D_INTEGRATION
return _PTMRatio;
#else
CCASSERT(false, "Can't call box2d methods when Box2d is disabled");
return 0;
#endif
}
void PhysicsSprite::setPTMRatio(float fRatio)
{
#if CC_ENABLE_BOX2D_INTEGRATION
_PTMRatio = fRatio;
#else
CC_UNUSED_PARAM(fRatio);
CCASSERT(false, "Can't call box2d methods when Box2d is disabled");
#endif
}
//
// Common to Box2d and Chipmunk
//
const Vec2& PhysicsSprite::getPosFromPhysics() const
{
static Vec2 s_physicPosion;
#if CC_ENABLE_CHIPMUNK_INTEGRATION
cpVect cpPos = cpBodyGetPosition(_CPBody);
s_physicPosion = Vec2(cpPos.x, cpPos.y);
#elif CC_ENABLE_BOX2D_INTEGRATION
b2Vec2 pos = _pB2Body->GetPosition();
float x = pos.x * _PTMRatio;
float y = pos.y * _PTMRatio;
s_physicPosion.set(x,y);
#endif
return s_physicPosion;
}
void PhysicsSprite::setPosition(float x, float y)
{
#if CC_ENABLE_CHIPMUNK_INTEGRATION
cpVect cpPos = cpv(x, y);
cpBodySetPosition(_CPBody, cpPos);
#elif CC_ENABLE_BOX2D_INTEGRATION
float angle = _pB2Body->GetAngle();
_pB2Body->SetTransform(b2Vec2(x / _PTMRatio, y / _PTMRatio), angle);
#endif
}
void PhysicsSprite::setPosition(const Vec2 &pos)
{
setPosition(pos.x, pos.y);
}
void PhysicsSprite::setPositionX(float x)
{
setPosition(x, getPositionY());
}
void PhysicsSprite::setPositionY(float y)
{
setPosition(getPositionX(), y);
}
void PhysicsSprite::setPosition3D(const Vec3& position)
{
setPosition(position.x, position.y);
}
float PhysicsSprite::getRotation() const
{
#if CC_ENABLE_CHIPMUNK_INTEGRATION
return (_ignoreBodyRotation ? Sprite::getRotation() : -CC_RADIANS_TO_DEGREES(cpBodyGetAngle(_CPBody)));
#elif CC_ENABLE_BOX2D_INTEGRATION
return (_ignoreBodyRotation ? Sprite::getRotation() :
CC_RADIANS_TO_DEGREES(_pB2Body->GetAngle()));
#else
return 0.0f;
#endif
}
void PhysicsSprite::setRotation(float fRotation)
{
if (_ignoreBodyRotation)
{
Sprite::setRotation(fRotation);
}
#if CC_ENABLE_CHIPMUNK_INTEGRATION
else
{
cpBodySetAngle(_CPBody, -CC_DEGREES_TO_RADIANS(fRotation));
}
#elif CC_ENABLE_BOX2D_INTEGRATION
else
{
b2Vec2 p = _pB2Body->GetPosition();
float radians = CC_DEGREES_TO_RADIANS(fRotation);
_pB2Body->SetTransform(p, radians);
}
#endif
}
void PhysicsSprite::syncPhysicsTransform() const
{
// Although scale is not used by physics engines, it is calculated just in case
// the sprite is animated (scaled up/down) using actions.
// For more info see: http://www.cocos2d-iphone.org/forum/topic/68990
#if CC_ENABLE_CHIPMUNK_INTEGRATION
cpVect rot = (_ignoreBodyRotation ? cpvforangle(-CC_DEGREES_TO_RADIANS(_rotationX)) : cpBodyGetRotation(_CPBody));
float x = cpBodyGetPosition(_CPBody).x + rot.x * -_anchorPointInPoints.x * _scaleX - rot.y * -_anchorPointInPoints.y * _scaleY;
float y = cpBodyGetPosition(_CPBody).y + rot.y * -_anchorPointInPoints.x * _scaleX + rot.x * -_anchorPointInPoints.y * _scaleY;
if (_ignoreAnchorPointForPosition)
{
x += _anchorPointInPoints.x;
y += _anchorPointInPoints.y;
}
float mat[] = { (float)rot.x * _scaleX, (float)rot.y * _scaleX, 0, 0,
(float)-rot.y * _scaleY, (float)rot.x * _scaleY, 0, 0,
0, 0, 1, 0,
x, y, 0, 1};
_transform.set(mat);
#elif CC_ENABLE_BOX2D_INTEGRATION
b2Vec2 pos = _pB2Body->GetPosition();
float x = pos.x * _PTMRatio;
float y = pos.y * _PTMRatio;
if (_ignoreAnchorPointForPosition)
{
x += _anchorPointInPoints.x;
y += _anchorPointInPoints.y;
}
// Make matrix
float radians = _pB2Body->GetAngle();
float c = cosf(radians);
float s = sinf(radians);
if (!_anchorPointInPoints.isZero())
{
x += ((c * -_anchorPointInPoints.x * _scaleX) + (-s * -_anchorPointInPoints.y * _scaleY));
y += ((s * -_anchorPointInPoints.x * _scaleX) + (c * -_anchorPointInPoints.y * _scaleY));
}
// Rot, Translate Matrix
float mat[] = { (float)c * _scaleX, (float)s * _scaleX, 0, 0,
(float)-s * _scaleY, (float)c * _scaleY, 0, 0,
0, 0, 1, 0,
x, y, 0, 1};
_transform.set(mat);
#endif
}
void PhysicsSprite::onEnter()
{
Node::onEnter();
_syncTransform = Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_AFTER_UPDATE, std::bind(&PhysicsSprite::afterUpdate, this, std::placeholders::_1));
_syncTransform->retain();
}
void PhysicsSprite::onExit()
{
if (_syncTransform != nullptr)
{
Director::getInstance()->getEventDispatcher()->removeEventListener(_syncTransform);
_syncTransform->release();
}
Node::onExit();
}
void PhysicsSprite::afterUpdate(EventCustom* /*event*/)
{
syncPhysicsTransform();
_transformDirty = false;
_transformUpdated = true;
setDirtyRecursively(true);
}
NS_CC_EXT_END
#endif // CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION
| 0 | 0.854807 | 1 | 0.854807 | game-dev | MEDIA | 0.666867 | game-dev | 0.881448 | 1 | 0.881448 |
ikpil/UniRecast | 6,059 | Runtime/DotRecast.Detour.Dynamic/Io/DtVoxelFileReader.cs | /*
recast4j copyright (c) 2021 Piotr Piastucki piotr@jtilia.org
DotRecast Copyright (c) 2023-2024 Choi Ikpil ikpil@naver.com
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.
*/
using System.IO;
using DotRecast.Core;
using DotRecast.Core.Numerics;
namespace DotRecast.Detour.Dynamic.Io
{
public class DtVoxelFileReader
{
private readonly IRcCompressor _compressor;
public DtVoxelFileReader(IRcCompressor compressor)
{
_compressor = compressor;
}
public DtVoxelFile Read(BinaryReader stream)
{
RcByteBuffer buf = RcIO.ToByteBuffer(stream);
DtVoxelFile file = new DtVoxelFile();
int magic = buf.GetInt();
if (magic != DtVoxelFile.MAGIC)
{
magic = RcIO.SwapEndianness(magic);
if (magic != DtVoxelFile.MAGIC)
{
throw new IOException("Invalid magic");
}
buf.Order(buf.Order() == RcByteOrder.BIG_ENDIAN ? RcByteOrder.LITTLE_ENDIAN : RcByteOrder.BIG_ENDIAN);
}
file.version = buf.GetInt();
bool isExportedFromAstar = (file.version & DtVoxelFile.VERSION_EXPORTER_MASK) == 0;
bool compression = (file.version & DtVoxelFile.VERSION_COMPRESSION_MASK) == DtVoxelFile.VERSION_COMPRESSION_LZ4;
file.walkableRadius = buf.GetFloat();
file.walkableHeight = buf.GetFloat();
file.walkableClimb = buf.GetFloat();
file.walkableSlopeAngle = buf.GetFloat();
file.cellSize = buf.GetFloat();
file.maxSimplificationError = buf.GetFloat();
file.maxEdgeLen = buf.GetFloat();
file.minRegionArea = (int)buf.GetFloat();
if (!isExportedFromAstar)
{
file.regionMergeArea = buf.GetFloat();
file.vertsPerPoly = buf.GetInt();
file.buildMeshDetail = buf.Get() != 0;
file.detailSampleDistance = buf.GetFloat();
file.detailSampleMaxError = buf.GetFloat();
}
else
{
file.regionMergeArea = 6 * file.minRegionArea;
file.vertsPerPoly = 6;
file.buildMeshDetail = true;
file.detailSampleDistance = file.maxEdgeLen * 0.5f;
file.detailSampleMaxError = file.maxSimplificationError * 0.8f;
}
file.useTiles = buf.Get() != 0;
file.tileSizeX = buf.GetInt();
file.tileSizeZ = buf.GetInt();
file.rotation.X = buf.GetFloat();
file.rotation.Y = buf.GetFloat();
file.rotation.Z = buf.GetFloat();
file.bounds[0] = buf.GetFloat();
file.bounds[1] = buf.GetFloat();
file.bounds[2] = buf.GetFloat();
file.bounds[3] = buf.GetFloat();
file.bounds[4] = buf.GetFloat();
file.bounds[5] = buf.GetFloat();
if (isExportedFromAstar)
{
// bounds are saved as center + size
file.bounds[0] -= 0.5f * file.bounds[3];
file.bounds[1] -= 0.5f * file.bounds[4];
file.bounds[2] -= 0.5f * file.bounds[5];
file.bounds[3] += file.bounds[0];
file.bounds[4] += file.bounds[1];
file.bounds[5] += file.bounds[2];
}
int tileCount = buf.GetInt();
for (int tile = 0; tile < tileCount; tile++)
{
int tileX = buf.GetInt();
int tileZ = buf.GetInt();
int width = buf.GetInt();
int depth = buf.GetInt();
int borderSize = buf.GetInt();
RcVec3f boundsMin = new RcVec3f();
boundsMin.X = buf.GetFloat();
boundsMin.Y = buf.GetFloat();
boundsMin.Z = buf.GetFloat();
RcVec3f boundsMax = new RcVec3f();
boundsMax.X = buf.GetFloat();
boundsMax.Y = buf.GetFloat();
boundsMax.Z = buf.GetFloat();
if (isExportedFromAstar)
{
// bounds are local
boundsMin.X += file.bounds[0];
boundsMin.Y += file.bounds[1];
boundsMin.Z += file.bounds[2];
boundsMax.X += file.bounds[0];
boundsMax.Y += file.bounds[1];
boundsMax.Z += file.bounds[2];
}
float cellSize = buf.GetFloat();
float cellHeight = buf.GetFloat();
int voxelSize = buf.GetInt();
int position = buf.Position();
byte[] bytes = buf.ReadBytes(voxelSize).ToArray();
if (compression)
{
bytes = _compressor.Decompress(bytes);
}
RcByteBuffer data = new RcByteBuffer(bytes);
data.Order(buf.Order());
file.AddTile(new DtVoxelTile(tileX, tileZ, width, depth, boundsMin, boundsMax, cellSize, cellHeight, borderSize, data));
buf.Position(position + voxelSize);
}
return file;
}
}
} | 0 | 0.883622 | 1 | 0.883622 | game-dev | MEDIA | 0.764827 | game-dev | 0.982778 | 1 | 0.982778 |
supernova-ws/SuperNova | 12,759 | design/templates/OpenGame/universe.tpl.html | <script type="text/javascript" src="js/sn_universe.min.js?{C_var_db_update}"></script>
<script type="text/javascript" src="js/sn_ajax_send_fleet.min.js?{C_var_db_update}"></script>
<!-- INCLUDE fleet_javascript -->
<script type="text/javascript"><!--
var uni_missile_planet = 0;
var uni_user_galaxy = "{curPlanetG}";
var uni_user_system = "{curPlanetS}";
var uni_user_planet = "{curPlanetP}";
var uni_user_planet_type = "{curPlanetPT}";
var uni_galaxy = {galaxy};
var uni_system = {system};
var user_id = {USER_ID};
var game_user_count = Math.intVal("{userCount}");
var game_ally_count = Math.intVal("{ALLY_COUNT}");
var opt_uni_avatar_user = '{opt_uni_avatar_user}';
var opt_uni_avatar_ally = '{opt_uni_avatar_ally}';
var opt_uni_tooltip_time = parseInt('{opt_uni_tooltip_time}') ? parseInt('{opt_uni_tooltip_time}') : 500;
var uni_phalanx = '{PLANET_PHALANX}';
var uni_spies = '{ACT_SPIO}';
var uni_death_stars = '{deathStars}';
var uni_missiles = parseInt('{MIPs}') ? parseInt('{MIPs}') : 0;
var PLANET_RECYCLERS = {PLANET_RECYCLERS};
var MT_MISSILE = {D_MT_MISSILE};
var MT_RECYCLE = {D_MT_RECYCLE};
var PT_DEBRIS = {D_PT_DEBRIS};
var PLAYER_OPTION_UNIVERSE_OLD = parseInt('{PLAYER_OPTION_UNIVERSE_OLD}') ? parseInt('{PLAYER_OPTION_UNIVERSE_OLD}') : 0;
jQuery.extend(language, {
sys_ships: '{L_uni_incoming_fleets}',
sys_planet: '{L_sys_planet_type[D_PT_PLANET]}',
sys_moon: '{L_sys_planet_type[D_PT_MOON]}',
sys_planet_short: '{L_sys_planet_type_sh[D_PT_PLANET]}',
sys_moon_short: '{L_sys_planet_type_sh[D_PT_MOON]}',
});
var users = new Array();
<!-- BEGIN users --><!-- IF users.ID -->
users[{users.ID}] = {
name: '{users.NAME_JS}',
rank: '{users.RANK}',
ally_id: parseInt('{users.ALLY_ID}') ? parseInt('{users.ALLY_ID}') : 0,
ally_tag: '{users.ALLY_TAG}',
ally_title: '{users.ALLY_TITLE}',
avatar: '{users.AVATAR}'
};
<!-- ENDIF --><!-- END users -->
var allies = new Array();
<!-- BEGIN alliances --><!-- IF alliances.ID -->
allies[{alliances.ID}] = {
'name': '{alliances.NAME_JS}',
'rank' : '{alliances.RANK}',
'members': '{alliances.MEMBERS}',
'url': '{alliances.URL}',
avatar: '{alliances.AVATAR}'
};
<!-- ENDIF --><!-- END alliances -->
var uni_row = new Array();
<!-- BEGIN galaxyrow --><!-- IF galaxyrow.PLANET_NUM -->
uni_row[{galaxyrow.PLANET_NUM}] = {
owner: '{galaxyrow.USER_ID}',
planet: '{galaxyrow.PLANET_NUM}',
planet_name: '{galaxyrow.PLANET_NAME_JS}',
planet_image: '{galaxyrow.PLANET_IMAGE}',
planet_fleet_id: '{galaxyrow.PLANET_FLEET_ID}',
planet_diameter: '{galaxyrow.PLANET_DIAMETER}',
planet_destroyed: '{galaxyrow.PLANET_DESTROYED}',
moon_name: '{galaxyrow.MOON_NAME_JS}',
moon_diameter: '{galaxyrow.MOON_DIAMETER}',
moon_image: '{galaxyrow.MOON_IMAGE}',
moon_fleet_id: '{galaxyrow.MOON_FLEET_ID}',
debris: '{galaxyrow.DEBRIS}',
debris_metal: '{galaxyrow.DEBRIS_METAL}',
debris_crystal: '{galaxyrow.DEBRIS_CRYSTAL}',
debris_reserved: '{galaxyrow.DEBRIS_RESERVED}',
debris_reserved_percent: '{galaxyrow.DEBRIS_RESERVED_PERCENT}',
debris_will_gather: '{galaxyrow.DEBRIS_WILL_GATHER}',
debris_will_gather_percent: '{galaxyrow.DEBRIS_WILL_GATHER_PERCENT}',
debris_gather_total: '{galaxyrow.DEBRIS_GATHER_TOTAL}',
debris_gather_total_percent: '{galaxyrow.DEBRIS_GATHER_TOTAL_PERCENT}',
};
<!-- ENDIF --><!-- END galaxyrow -->
// --></script>
<!-- IF UNIVERSE_SCAN_MODE -->
<!-- DEFINE $SCAN_CLASS = 'uni_scan' -->
<!-- DEFINE $SCAN_CLASS_NO_BORDER = 'no_border_image' -->
<!-- ENDIF -->
<br />
<!-- INCLUDE universe_navigation -->
<!-- IF PLAYER_OPTION_UNIVERSE_OLD || UNIVERSE_SCAN_MODE -->
<!-- INCLUDE universe_old -->
<!-- ELSE -->
<!-- INCLUDE universe_new -->
<!-- ENDIF -->
<form id="uni_missile_form" style="display: none;" name="uni_missile_form" method=POST>
<br>
<table style="border: 2em solid red">
<tr>
<td class=c colspan=3>
<span class="fl">{L_gm_launch} [{galaxy}:{system}:<span id="uni_missile_planet">{planet}</span>]</span>
<span class="fr">{L_gal_mis_rest}<span id="missile2">{MIPs}</span></span>
</td>
</tr>
<tr>
<th class=c>{L_gal_mis_toLaunch} <input type=text value="{MIPs}" name="SendMI" id="SendMI" size=7 maxlength=7 /></th>
<th class=c>{L_gm_target}
<select name=Target>
<option value=0 selected>{L_gm_all}</option>
<!-- BEGIN defense_active -->
<option value={defense_active.ID}>{defense_active.NAME}</option>
<!-- END defense_active -->
</select>
</th>
<th class=c>
<input type="button" value="{L_gal_mis_launch}" onclick="doit({D_MT_MISSILE}, uni_missile_planet, {D_PT_PLANET}, document.uni_missile_form.SendMI.value);jQuery('#uni_missile_form').hide();">
</th>
</tr>
</table>
</form>
<span style="display: none">
<span id="legend_template">
<table class="legend_template no_border_image">
<tr><th class="c_l" colspan=2>{L_sys_planet}</th></tr>
<tr class=myplanet><td colspan=2>{L_uni_legend_myplanet}</td></tr>
<tr class=allymember><td colspan=2>{L_uni_legend_allyplanet}</td></tr>
<tr><th class="c_l" colspan=2>{L_sys_player}</th></tr>
<tr><td>{L_sys_birthday}</td><td><span class="birthday"> </span></td></tr>
<tr><td colspan="2"><span class=vacation>{L_Way_vacation}</span></td></tr>
<tr class=protected><td>{L_uni_protected_player}</td><td>{L_uni_protected_player_shortcut}</td></tr>
<tr class=noob><td>{L_Weak_player}</td><td>{L_weak_player_shortcut}</td></tr>
<tr class=strong><td>{L_Strong_player}</td><td>{L_strong_player_shortcut}</td></tr>
<tr class="banned"><td colspan="2">{L_Pendent_user}</td></tr>
<tr class=player_active><td>{L_Active}</td><td>{L_active_shortcut}</td></tr>
<tr class=inactive><td>{L_Inactive_7_days}</td><td>{L_inactif_7_shortcut}</td></tr>
<tr class=longinactive><td>{L_Inactive_28_days}</td><td>{L_inactif_28_shortcut}</td></tr>
<!-- IF SHOW_ADMIN -->
<tr class=admin><td>{L_user_level[3]}</td><td>{L_user_level_shortcut[3]}</td></tr>
<tr class=admin><td>{L_user_level[2]}</td><td>{L_user_level_shortcut[2]}</td></tr>
<tr class=admin><td>{L_user_level[1]}</td><td>{L_user_level_shortcut[1]}</td></tr>
<!-- ENDIF -->
<tr><th class="c_l" colspan=2>{L_Actions}</th></tr>
<tr><td>{L_gl_espionner}</td><td><img src="design/images/icon_espionage.png" border=0 style="height: 1.5em" /> </td></tr>
<tr><td>{L_gl_mipattack}</td><td><img src="design/images/icon_missile.png" border=0 style="height: 1.5em" /></td></tr>
<tr><td>{L_stat_details}</td><td><img src="{I_menu_empire_emperor}" border=0 style="height: 1.5em" /></td></tr>
<tr><td>{L_gl_sendmess}</td><td><img src="design/images/icon_mail.gif" border=0 style="height: 1.5em" /></td></tr>
<tr><td>{L_gl_buddyreq}</td><td><img src="{I_icon_buddy}" border=0 style="height: 1.5em" /></td></tr>
<tr><td>{L_gl_stats}</td><td><img src="design/images/icon_statistics.png" border=0 style="height: 1.5em" /></td></tr>
</table>
</span>
<span id="planet_template">
<table class="planet_template no_border_image">
<tr>
<th class="c_c" colspan="2">
[{galaxy}:{system}:[PLANET_POS]] [PLANET_TYPE_TEXT_SHORT] [PLANET_NAME]
</th>
</tr>
<tr>
<td class="c_c">
<div class="uni_popup_planet">
<img src="{I_PLANET_IMAGE_SMALL}" />
<div>∅ [PLANET_DIAMETER]</div>
</div>
</td>
<td class="c_c" planet_planet="[PLANET_POS]" planet_type="[PLANET_TYPE]">
<div class="owndeploy button_pseudo" style="[HIDE_PLANET_RELOCATE]" go="fleet" mission="{D_MT_RELOCATE}">{L_type_mission[D_MT_RELOCATE]}</div>
<div class="owntransport button_pseudo" go="fleet" mission="{D_MT_TRANSPORT}">{L_type_mission[D_MT_TRANSPORT]}</div>
<div class="ownhold button_pseudo" style="[HIDE_PLANET_HOLD]" go="fleet" mission="{D_MT_HOLD}">{L_type_mission[D_MT_HOLD]}</div>
<div class="owndestroy button_pseudo" style="[HIDE_PLANET_DESTROY]" go="fleet" mission="{D_MT_DESTROY}">{L_type_mission[D_MT_DESTROY]}</div>
<div class="ownattack button_pseudo" style="[HIDE_PLANET_ATTACK]" go="fleet" mission="{D_MT_ATTACK}">{L_type_mission[D_MT_ATTACK]}</div>
<div class="ownespionage button_pseudo" style="[HIDE_PLANET_SPY]" onclick="doit({D_MT_SPY}, [PLANET_POS], [PLANET_TYPE], {ACT_SPIO});">{L_type_mission[D_MT_SPY]}</div>
<div class="ownmissile button_pseudo" style="[HIDE_PLANET_MISSILE]">{L_type_mission[D_MT_MISSILE]}</div>
<div class="button_pseudo" style="[HIDE_PLANET_PHALANX]" go="phalanx" target="_blank">{L_gl_phalanx}</div>
</td>
</tr>
</table>
[FLEET_TABLE]
</span>
<span id="debris_template">
<table width=100% class="debris_template no_border_image">
<tr><th class="c_c" colspan="4">[{galaxy}:{system}:[CURRENT_PLANET]] {L_sys_planet_type[D_PT_DEBRIS]}</th></tr>
<tr><td class="c_c" rowspan="7"><img src="{I_debris}" style="width: 7em; font-size: 1em;" /></td></tr>
<tr>
<th class="c_l">{L_gl_ressource}</th>
<th class="c_r">[DEBRIS]</th>
<th class="c_r">100%</th>
</tr>
<tr>
<td class="c_l">{L_sys_metal}</td>
<td class="c_r">[DEBRIS_METAL]</td>
<td class="c_r">[DEBRIS_METAL_PERCENT]%</td>
</tr>
<tr>
<td class="c_l">{L_sys_crystal}</td>
<td class="c_r">[DEBRIS_CRYSTAL]</td>
<td class="c_r">[DEBRIS_CRYSTAL_PERCENT]%</td>
</tr>
<tr>
<th class="c_l">{L_uni_debris_recyclable}</th>
<th class="c_r">[DEBRIS_GATHER_TOTAL]</th>
<th class="c_r">[DEBRIS_GATHER_TOTAL_PERCENT]%</th>
</tr>
<tr>
<td class="c_l">{L_uni_debris_incoming_recyclers}</td>
<td class="c_r">[DEBRIS_RESERVED]</td>
<td class="c_r">[DEBRIS_RESERVED_PERCENT]%</td>
</tr>
<tr>
<td class="c_l">{L_uni_debris_on_planet}</td>
<td class="c_r">[DEBRIS_WILL_GATHER]</td>
<td class="c_r">[DEBRIS_WILL_GATHER_PERCENT]%</td>
</tr>
<tr class="link c_c" style="[HIDE_RECYCLER_LINK]" >
<th colspan="4">
<div class="button_pseudo ownharvest" planet_planet="[CURRENT_PLANET]">
{L_uni_recyclers_send}
</div>
</th>
</tr>
</table>
</span>
<span id="user_template">
<table class="user_template no_border_image">
<tr>
<th class="c_c" colspan="[USER_COLSPAN]">
[USER_NAME]
</th>
</tr>
<tr>
<td class="c_c subheader" style="[HIDE_USER_ALLY]" colspan="[USER_COLSPAN]">
[USER_ALLY_NAME]<br />
[USER_ALLY_TITLE]
</td>
</tr>
<tr>
<td class="c_c" style="[HIDE_USER_AVATAR]">
<div><img src="{D_SN_ROOT_VIRTUAL}images/avatar/avatar_[USER_ID].png" style="width: 9em;" /></div>
</td>
<td class="c_c" user_id="[USER_ID]">
<div class="button_pseudo" go="stat" rank="[USER_RANK]">
{L_gl_stats}: {L_Place} [USER_RANK]/{userCount}
</div>
<div class="button_pseudo" go="imperator">
{L_stat_details}
</div>
<div class="button_pseudo" go="messages" mode="write">
{L_gl_sendmess}
</div>
<div class="button_pseudo" go="buddy">
{L_gl_buddyreq}
</div>
</td>
</tr>
</table>
</span>
<span id="ally_template">
<table class="ally_template no_border_image">
<tr>
<th class="c_c" colspan="[ALLY_COLSPAN]">
[ALLY_NAME]
</th>
</tr>
<tr>
<td class="c_c" rowspan="4" style="[HIDE_ALLY_AVATAR]">
<img src="{D_SN_ROOT_VIRTUAL}images/avatar/ally_[ALLY_ID].png" style="width: 9em;" />
</td>
<td class="c_c">
{L_gal_sys_members} [ALLY_MEMBERS]
</td>
</tr>
<tr>
<td class="c_c" ally_id="[ALLY_ID]">
<div class="button_pseudo" go="stat" rank="[ALLY_RANK]" who="2">
{L_gl_stats}: {L_Place} [ALLY_RANK]/{ALLY_COUNT}
</div>
<div class="button_pseudo" go="alliance" mode="ainfo">
{L_gl_ally_internal}
</div>
<a class="link" style="[HIDE_ALLY_URL]" href="[ALLY_URL]" target="_new">{L_gl_ally_web}</a>
</td>
</tr>
</table>
</span>
<span id="message_template">
<table>
<tr>
<td class="c_c [CLASS]" style="padding: 0.5em 1em;">
[MESSAGE]
</td>
</tr>
</table>
</span>
</span>
<!-- IF ! UNIVERSE_SCAN_MODE -->
<!-- INCLUDE page_hint -->
<!-- ENDIF -->
| 0 | 0.578172 | 1 | 0.578172 | game-dev | MEDIA | 0.417327 | game-dev,web-frontend | 0.605284 | 1 | 0.605284 |
MohistMC/Youer | 2,170 | src/main/java/org/bukkit/loot/Lootable.java | package org.bukkit.loot;
import org.jetbrains.annotations.Nullable;
/**
* Represents a {@link org.bukkit.block.Container} or a
* {@link org.bukkit.entity.Mob} that can have a loot table.
* <br>
* Container loot will only generate upon opening, and only when the container
* is <i>first</i> opened.
* <br>
* Entities will only generate loot upon death.
*/
public interface Lootable {
/**
* Set the loot table for a container or entity.
* <br>
* To remove a loot table use null. Do not use {@link LootTables#EMPTY} to
* clear a LootTable.
*
* @param table the Loot Table this {@link org.bukkit.block.Container} or
* {@link org.bukkit.entity.Mob} will have.
*/
void setLootTable(@Nullable LootTable table);
/**
* Gets the Loot Table attached to this block or entity.
* <br>
*
* If an block/entity does not have a loot table, this will return null, NOT
* an empty loot table.
*
* @return the Loot Table attached to this block or entity.
*/
@Nullable
LootTable getLootTable();
// Paper start
/**
* Set the loot table and seed for a container or entity at the same time.
*
* @param table the Loot Table this {@link org.bukkit.block.Container} or {@link org.bukkit.entity.Mob} will have.
* @param seed the seed to used to generate loot. Default is 0.
*/
void setLootTable(final @Nullable LootTable table, final long seed);
/**
* Returns whether or not this object has a Loot Table
* @return Has a loot table
*/
default boolean hasLootTable() {
return this.getLootTable() != null;
}
/**
* Clears the associated Loot Table to this object
*/
default void clearLootTable() {
this.setLootTable(null);
}
// Paper end
/**
* Set the seed used when this Loot Table generates loot.
*
* @param seed the seed to used to generate loot. Default is 0.
*/
void setSeed(long seed);
/**
* Get the Loot Table's seed.
* <br>
* The seed is used when generating loot.
*
* @return the seed
*/
long getSeed();
}
| 0 | 0.741294 | 1 | 0.741294 | game-dev | MEDIA | 0.998085 | game-dev | 0.807329 | 1 | 0.807329 |
cmangos/mangos-cata | 13,215 | src/game/AI/ScriptDevAI/scripts/kalimdor/caverns_of_time/old_hillsbrad/instance_old_hillsbrad.cpp | /* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Instance_Old_Hillsbrad
SD%Complete: 75
SDComment: Thrall reset on server restart is not supported, because of core limitation.
SDCategory: Caverns of Time, Old Hillsbrad Foothills
EndScriptData */
#include "AI/ScriptDevAI/include/precompiled.h"
#include "old_hillsbrad.h"
instance_old_hillsbrad::instance_old_hillsbrad(Map* pMap) : ScriptedInstance(pMap),
m_uiBarrelCount(0),
m_uiThrallEventCount(0),
m_uiThrallResetTimer(0)
{
Initialize();
}
void instance_old_hillsbrad::Initialize()
{
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
}
void instance_old_hillsbrad::OnPlayerEnter(Player* pPlayer)
{
// ToDo: HandleThrallRelocation();
// Note: this isn't yet supported because of the grid load / unload
// Spawn Drake if necessary
if (GetData(TYPE_DRAKE) == DONE || GetData(TYPE_BARREL_DIVERSION) != DONE)
return;
if (GetSingleCreatureFromStorage(NPC_DRAKE, true))
return;
pPlayer->SummonCreature(NPC_DRAKE, aDrakeSummonLoc[0], aDrakeSummonLoc[1], aDrakeSummonLoc[2], aDrakeSummonLoc[3], TEMPSPAWN_DEAD_DESPAWN, 0);
}
void instance_old_hillsbrad::OnCreatureCreate(Creature* pCreature)
{
switch (pCreature->GetEntry())
{
case NPC_THRALL:
case NPC_TARETHA:
case NPC_EROZION:
case NPC_ARMORER:
case NPC_TARREN_MILL_PROTECTOR:
case NPC_TARREN_MILL_LOOKOUT:
case NPC_YOUNG_BLANCHY:
case NPC_DRAKE:
case NPC_SKARLOC:
case NPC_EPOCH:
m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid();
break;
case NPC_ORC_PRISONER:
// Sort the orcs which are inside the houses
if (pCreature->GetPositionZ() > 53.4f)
{
if (pCreature->GetPositionY() > 150.0f)
m_lLeftPrisonersList.push_back(pCreature->GetObjectGuid());
else
m_lRightPrisonersList.push_back(pCreature->GetObjectGuid());
}
break;
}
}
void instance_old_hillsbrad::OnCreatureDeath(Creature* pCreature)
{
switch (pCreature->GetEntry())
{
case NPC_DRAKE: SetData(TYPE_DRAKE, DONE); break;
case NPC_SKARLOC: SetData(TYPE_SKARLOC, DONE); break;
case NPC_EPOCH: SetData(TYPE_EPOCH, DONE); break;
}
}
void instance_old_hillsbrad::OnCreatureEnterCombat(Creature* pCreature)
{
switch (pCreature->GetEntry())
{
case NPC_DRAKE:
SetData(TYPE_DRAKE, IN_PROGRESS);
DoUpdateWorldState(WORLD_STATE_OH, 0);
break;
case NPC_SKARLOC: SetData(TYPE_SKARLOC, IN_PROGRESS); break;
case NPC_EPOCH: SetData(TYPE_EPOCH, IN_PROGRESS); break;
}
}
void instance_old_hillsbrad::OnCreatureEvade(Creature* pCreature)
{
switch (pCreature->GetEntry())
{
case NPC_DRAKE: SetData(TYPE_DRAKE, FAIL); break;
case NPC_SKARLOC: SetData(TYPE_SKARLOC, FAIL); break;
case NPC_EPOCH: SetData(TYPE_EPOCH, FAIL); break;
}
}
void instance_old_hillsbrad::OnObjectCreate(GameObject* pGo)
{
if (pGo->GetEntry() == GO_ROARING_FLAME)
m_lRoaringFlamesList.push_back(pGo->GetObjectGuid());
else if (pGo->GetEntry() == GO_PRISON_DOOR)
m_mGoEntryGuidStore[GO_PRISON_DOOR] = pGo->GetObjectGuid();
}
void instance_old_hillsbrad::HandleThrallRelocation()
{
// reset instance data
SetData(TYPE_THRALL_EVENT, IN_PROGRESS);
if (Creature* pThrall = GetSingleCreatureFromStorage(NPC_THRALL))
{
debug_log("SD2: Instance Old Hillsbrad: Thrall relocation");
if (!pThrall->isAlive())
pThrall->Respawn();
// epoch failed, reloc to inn
if (GetData(TYPE_ESCORT_INN) == DONE)
pThrall->GetMap()->CreatureRelocation(pThrall, 2660.57f, 659.173f, 61.9370f, 5.76f);
// barn to inn failed, reloc to barn
else if (GetData(TYPE_ESCORT_BARN) == DONE)
pThrall->GetMap()->CreatureRelocation(pThrall, 2486.91f, 626.356f, 58.0761f, 4.66f);
// keep to barn failed, reloc to keep
else if (GetData(TYPE_SKARLOC) == DONE)
pThrall->GetMap()->CreatureRelocation(pThrall, 2063.40f, 229.509f, 64.4883f, 2.23f);
// prison to keep failed, reloc to prison
else
pThrall->GetMap()->CreatureRelocation(pThrall, 2231.89f, 119.95f, 82.2979f, 4.21f);
}
}
void instance_old_hillsbrad::SetData(uint32 uiType, uint32 uiData)
{
switch (uiType)
{
case TYPE_BARREL_DIVERSION:
m_auiEncounter[uiType] = uiData;
if (uiData == IN_PROGRESS)
{
if (m_uiBarrelCount >= MAX_BARRELS)
return;
// Update barrels used and world state
++m_uiBarrelCount;
DoUpdateWorldState(WORLD_STATE_OH, m_uiBarrelCount);
debug_log("SD2: Instance Old Hillsbrad: go_barrel_old_hillsbrad count %u", m_uiBarrelCount);
// Set encounter to done, and spawn Liutenant Drake
if (m_uiBarrelCount == MAX_BARRELS)
{
UpdateLodgeQuestCredit();
if (Player* pPlayer = GetPlayerInMap())
{
pPlayer->SummonCreature(NPC_DRAKE, aDrakeSummonLoc[0], aDrakeSummonLoc[1], aDrakeSummonLoc[2], aDrakeSummonLoc[3], TEMPSPAWN_DEAD_DESPAWN, 0);
// set the houses on fire
for (GuidList::const_iterator itr = m_lRoaringFlamesList.begin(); itr != m_lRoaringFlamesList.end(); ++itr)
DoRespawnGameObject(*itr, 30 * MINUTE);
// move the orcs outside the houses
float fX, fY, fZ;
for (GuidList::const_iterator itr = m_lRightPrisonersList.begin(); itr != m_lRightPrisonersList.end(); ++itr)
{
if (Creature* pOrc = instance->GetCreature(*itr))
{
pOrc->GetRandomPoint(afInstanceLoc[0][0], afInstanceLoc[0][1], afInstanceLoc[0][2], 10.0f, fX, fY, fZ);
pOrc->SetWalk(false);
pOrc->GetMotionMaster()->MovePoint(0, fX, fY, fZ);
}
}
for (GuidList::const_iterator itr = m_lLeftPrisonersList.begin(); itr != m_lLeftPrisonersList.end(); ++itr)
{
if (Creature* pOrc = instance->GetCreature(*itr))
{
pOrc->GetRandomPoint(afInstanceLoc[1][0], afInstanceLoc[1][1], afInstanceLoc[1][2], 10.0f, fX, fY, fZ);
pOrc->SetWalk(false);
pOrc->GetMotionMaster()->MovePoint(0, fX, fY, fZ);
}
}
}
else
debug_log("SD2: Instance Old Hillsbrad: SetData (Type: %u Data %u) cannot find any pPlayer.", uiType, uiData);
SetData(TYPE_BARREL_DIVERSION, DONE);
}
}
break;
case TYPE_THRALL_EVENT:
// nothing to do if already done and thrall respawn
if (GetData(TYPE_THRALL_EVENT) == DONE)
return;
m_auiEncounter[uiType] = uiData;
if (uiData == FAIL)
{
// despawn the bosses if necessary
if (Creature* pSkarloc = GetSingleCreatureFromStorage(NPC_SKARLOC, true))
pSkarloc->ForcedDespawn();
if (Creature* pEpoch = GetSingleCreatureFromStorage(NPC_EPOCH, true))
pEpoch->ForcedDespawn();
if (m_uiThrallEventCount <= MAX_WIPE_COUNTER)
{
++m_uiThrallEventCount;
debug_log("SD2: Instance Old Hillsbrad: Thrall event failed %u times.", m_uiThrallEventCount);
// reset Thrall on timer
m_uiThrallResetTimer = 30000;
}
// If we already respawned Thrall too many times, the event is failed for good
else if (m_uiThrallEventCount > MAX_WIPE_COUNTER)
debug_log("SD2: Instance Old Hillsbrad: Thrall event failed %u times. Reset instance required.", m_uiThrallEventCount);
}
break;
case TYPE_DRAKE:
case TYPE_SKARLOC:
case TYPE_ESCORT_BARN:
case TYPE_ESCORT_INN:
case TYPE_EPOCH:
m_auiEncounter[uiType] = uiData;
debug_log("SD2: Instance Old Hillsbrad: Thrall event type %u adjusted to data %u.", uiType, uiData);
break;
}
if (uiData == DONE)
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1] << " " << m_auiEncounter[2] << " "
<< m_auiEncounter[3] << " " << m_auiEncounter[4] << " " << m_auiEncounter[5] << " "
<< m_auiEncounter[6];
m_strInstData = saveStream.str();
SaveToDB();
OUT_SAVE_INST_DATA_COMPLETE;
}
}
uint32 instance_old_hillsbrad::GetData(uint32 uiType) const
{
if (uiType < MAX_ENCOUNTER)
return m_auiEncounter[uiType];
return 0;
}
void instance_old_hillsbrad::Load(const char* chrIn)
{
if (!chrIn)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(chrIn);
std::istringstream loadStream(chrIn);
loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3]
>> m_auiEncounter[4] >> m_auiEncounter[5] >> m_auiEncounter[6];
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
{
if (m_auiEncounter[i] == IN_PROGRESS)
m_auiEncounter[i] = NOT_STARTED;
}
// custom reload - if the escort event or the Epoch event are not done, then reset the escort
// this is done, because currently we cannot handle Thrall relocation on server reset
if (m_auiEncounter[5] != DONE)
{
m_auiEncounter[2] = NOT_STARTED;
m_auiEncounter[3] = NOT_STARTED;
m_auiEncounter[4] = NOT_STARTED;
}
OUT_LOAD_INST_DATA_COMPLETE;
}
void instance_old_hillsbrad::UpdateLodgeQuestCredit()
{
Map::PlayerList const& players = instance->GetPlayers();
if (!players.isEmpty())
{
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
{
if (Player* pPlayer = itr->getSource())
pPlayer->KilledMonsterCredit(NPC_LODGE_QUEST_TRIGGER);
}
}
}
void instance_old_hillsbrad::Update(uint32 uiDiff)
{
if (m_uiThrallResetTimer)
{
if (m_uiThrallResetTimer <= uiDiff)
{
HandleThrallRelocation();
m_uiThrallResetTimer = 0;
}
else
m_uiThrallResetTimer -= uiDiff;
}
}
InstanceData* GetInstanceData_instance_old_hillsbrad(Map* pMap)
{
return new instance_old_hillsbrad(pMap);
}
bool ProcessEventId_event_go_barrel_old_hillsbrad(uint32 /*uiEventId*/, Object* pSource, Object* pTarget, bool bIsStart)
{
if (bIsStart && pSource->GetTypeId() == TYPEID_PLAYER)
{
if (instance_old_hillsbrad* pInstance = (instance_old_hillsbrad*)((Player*)pSource)->GetInstanceData())
{
if (pInstance->GetData(TYPE_BARREL_DIVERSION) == DONE)
return true;
pInstance->SetData(TYPE_BARREL_DIVERSION, IN_PROGRESS);
// Don't allow players to use same object twice
if (pTarget->GetTypeId() == TYPEID_GAMEOBJECT)
((GameObject*)pTarget)->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NO_INTERACT);
return true;
}
}
return false;
}
void AddSC_instance_old_hillsbrad()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "instance_old_hillsbrad";
pNewScript->GetInstanceData = &GetInstanceData_instance_old_hillsbrad;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "event_go_barrel_old_hillsbrad";
pNewScript->pProcessEventId = &ProcessEventId_event_go_barrel_old_hillsbrad;
pNewScript->RegisterSelf();
}
| 0 | 0.991797 | 1 | 0.991797 | game-dev | MEDIA | 0.970744 | game-dev | 0.992819 | 1 | 0.992819 |
splhack/Hello-LWF-Cocos2d-x | 23,382 | cocos2d/cocos/editor-support/cocostudio/WidgetReader/NodeReader/NodeReader.cpp | /****************************************************************************
Copyright (c) 2014 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "NodeReader.h"
#include "cocostudio/CSParseBinary_generated.h"
#include "cocostudio/ActionTimeline/CCActionTimeline.h"
#include "cocostudio/CCObjectExtensionData.h"
#include "tinyxml2.h"
#include "flatbuffers/flatbuffers.h"
#include "ui/UILayoutComponent.h"
USING_NS_CC;
using namespace flatbuffers;
namespace cocostudio
{
const char* Layout_PositionPercentXEnabled = "PositionPercentXEnabled";
const char* Layout_PositionPercentYEnabled = "PositionPercentYEnabled";
const char* Layout_PercentWidthEnable = "PercentWidthEnabled";
const char* Layout_PercentHeightEnable = "PercentHeightEnabled";
const char* Layout_StretchWidthEnable = "StretchWidthEnable";
const char* Layout_StretchHeightEnable = "StretchHeightEnable";
const char* Layout_HorizontalEdge = "HorizontalEdge";
const char* Layout_VerticalEdge = "VerticalEdge";
const char* Layout_LeftMargin = "LeftMargin";
const char* Layout_RightMargin = "RightMargin";
const char* Layout_TopMargin = "TopMargin";
const char* Layout_BottomMargin = "BottomMargin";
const char* Layout_BothEdge = "BothEdge";
const char* Layout_LeftEdge = "LeftEdge";
const char* Layout_RightEdge = "RightEdge";
const char* Layout_TopEdge = "TopEdge";
const char* Layout_BottomEdge = "BottomEdge";
IMPLEMENT_CLASS_NODE_READER_INFO(NodeReader)
NodeReader::NodeReader()
{
}
NodeReader::~NodeReader()
{
}
static NodeReader* _instanceNodeReader = nullptr;
NodeReader* NodeReader::getInstance()
{
if (!_instanceNodeReader)
{
_instanceNodeReader = new NodeReader();
}
return _instanceNodeReader;
}
void NodeReader::destroyInstance()
{
CC_SAFE_DELETE(_instanceNodeReader);
}
Offset<Table> NodeReader::createOptionsWithFlatBuffers(const tinyxml2::XMLElement *objectData,
flatbuffers::FlatBufferBuilder *builder)
{
std::string name = "";
long actionTag = 0;
Vec2 rotationSkew;
int zOrder = 0;
bool visible = true;
GLubyte alpha = 255;
int tag = 0;
Vec2 position;
Vec2 scale(1.0f, 1.0f);
Vec2 anchorPoint;
Color4B color(255, 255, 255, 255);
Vec2 size;
bool flipX = false;
bool flipY = false;
bool ignoreSize = false;
bool touchEnabled = false;
std::string frameEvent = "";
std::string customProperty = "";
bool positionXPercentEnabled = false;
bool positionYPercentEnabled = false;
float positionXPercent = 0;
float positionYPercent = 0;
bool sizeXPercentEnable = false;
bool sizeYPercentEnable = false;
float sizeXPercent = 0;
float sizeYPercent = 0;
bool stretchHorizontalEnabled = false;
bool stretchVerticalEnabled = false;
std::string horizontalEdge;
std::string verticalEdge;
float leftMargin = 0;
float rightMargin = 0;
float topMargin = 0;
float bottomMargin = 0;
// attributes
const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute();
while (attribute)
{
std::string attriname = attribute->Name();
std::string value = attribute->Value();
if (attriname == "Name")
{
name = value;
}
else if (attriname == "ActionTag")
{
actionTag = atol(value.c_str());
}
else if (attriname == "RotationSkewX")
{
rotationSkew.x = atof(value.c_str());
}
else if (attriname == "RotationSkewY")
{
rotationSkew.y = atof(value.c_str());
}
else if (attriname == "Rotation")
{
// rotation = atoi(value.c_str());
}
else if (attriname == "FlipX")
{
flipX = (value == "True") ? true : false;
}
else if (attriname == "FlipY")
{
flipY = (value == "True") ? true : false;
}
else if (attriname == "ZOrder")
{
zOrder = atoi(value.c_str());
}
else if (attriname == "Visible")
{
// visible = (value == "True") ? true : false;
}
else if (attriname == "VisibleForFrame")
{
visible = (value == "True") ? true : false;
}
else if (attriname == "Alpha")
{
alpha = atoi(value.c_str());
}
else if (attriname == "Tag")
{
tag = atoi(value.c_str());
}
else if (attriname == "TouchEnable")
{
touchEnabled = (value == "True") ? true : false;
}
else if (attriname == "UserData")
{
customProperty = value;
}
else if (attriname == "FrameEvent")
{
frameEvent = value;
}
else if (attriname == Layout_PositionPercentXEnabled)
{
positionXPercentEnabled = value == "True";
}
else if (attriname == Layout_PositionPercentYEnabled)
{
positionYPercentEnabled = value == "True";
}
else if (attriname == Layout_PercentWidthEnable)
{
sizeXPercentEnable = value == "True";
}
else if (attriname == Layout_PercentHeightEnable)
{
sizeYPercentEnable = value == "True";
}
else if (attriname == Layout_StretchWidthEnable)
{
stretchHorizontalEnabled = value == "True";
}
else if (attriname == Layout_StretchHeightEnable)
{
stretchVerticalEnabled = value == "True";
}
else if (attriname == Layout_HorizontalEdge)
{
horizontalEdge = value;
}
else if (attriname == Layout_VerticalEdge)
{
verticalEdge = value;
}
else if (attriname == Layout_LeftMargin)
{
leftMargin = atof(value.c_str());
}
else if (attriname == Layout_RightMargin)
{
rightMargin = atof(value.c_str());
}
else if (attriname == Layout_TopMargin)
{
topMargin = atof(value.c_str());
}
else if (attriname == Layout_BottomMargin)
{
bottomMargin = atof(value.c_str());
}
attribute = attribute->Next();
}
const tinyxml2::XMLElement* child = objectData->FirstChildElement();
while (child)
{
std::string attriname = child->Name();
if (attriname == "Position")
{
attribute = child->FirstAttribute();
while (attribute)
{
attriname = attribute->Name();
std::string value = attribute->Value();
if (attriname == "X")
{
position.x = atof(value.c_str());
}
else if (attriname == "Y")
{
position.y = atof(value.c_str());
}
attribute = attribute->Next();
}
}
else if (attriname == "Scale")
{
attribute = child->FirstAttribute();
while (attribute)
{
attriname = attribute->Name();
std::string value = attribute->Value();
if (attriname == "ScaleX")
{
scale.x = atof(value.c_str());
}
else if (attriname == "ScaleY")
{
scale.y = atof(value.c_str());
}
attribute = attribute->Next();
}
}
else if (attriname == "AnchorPoint")
{
attribute = child->FirstAttribute();
while (attribute)
{
attriname = attribute->Name();
std::string value = attribute->Value();
if (attriname == "ScaleX")
{
anchorPoint.x = atof(value.c_str());
}
else if (attriname == "ScaleY")
{
anchorPoint.y = atof(value.c_str());
}
attribute = attribute->Next();
}
}
else if (attriname == "CColor")
{
attribute = child->FirstAttribute();
while (attribute)
{
attriname = attribute->Name();
std::string value = attribute->Value();
if (attriname == "A")
{
color.a = atoi(value.c_str());
}
else if (attriname == "R")
{
color.r = atoi(value.c_str());
}
else if (attriname == "G")
{
color.g = atoi(value.c_str());
}
else if (attriname == "B")
{
color.b = atoi(value.c_str());
}
attribute = attribute->Next();
}
}
else if (attriname == "Size")
{
attribute = child->FirstAttribute();
while (attribute)
{
attriname = attribute->Name();
std::string value = attribute->Value();
if (attriname == "X")
{
size.x = atof(value.c_str());
}
else if (attriname == "Y")
{
size.y = atof(value.c_str());
}
attribute = attribute->Next();
}
}
else if (attriname == "PrePosition")
{
attribute = child->FirstAttribute();
while (attribute)
{
attriname = attribute->Name();
std::string value = attribute->Value();
if (attriname == "X")
{
positionXPercent = atof(value.c_str());
}
else if (attriname == "Y")
{
positionYPercent = atof(value.c_str());
}
attribute = attribute->Next();
}
}
else if (attriname == "PreSize")
{
attribute = child->FirstAttribute();
while (attribute)
{
attriname = attribute->Name();
std::string value = attribute->Value();
if (attriname == "X")
{
sizeXPercent = atof(value.c_str());
}
else if (attriname == "Y")
{
sizeYPercent = atof(value.c_str());
}
attribute = attribute->Next();
}
}
child = child->NextSiblingElement();
}
RotationSkew f_rotationskew(rotationSkew.x, rotationSkew.y);
Position f_position(position.x, position.y);
Scale f_scale(scale.x, scale.y);
AnchorPoint f_anchortpoint(anchorPoint.x, anchorPoint.y);
Color f_color(color.a, color.r, color.g, color.b);
FlatSize f_size(size.x, size.y);
auto f_layoutComponent = CreateLayoutComponentTable(*builder,
positionXPercentEnabled,
positionYPercentEnabled,
positionXPercent,
positionYPercent,
sizeXPercentEnable,
sizeYPercentEnable,
sizeXPercent,
sizeYPercent,
stretchHorizontalEnabled,
stretchVerticalEnabled,
builder->CreateString(horizontalEdge),
builder->CreateString(verticalEdge),
leftMargin,
rightMargin,
topMargin,
bottomMargin);
auto options = CreateWidgetOptions(*builder,
builder->CreateString(name),
(int)actionTag,
&f_rotationskew,
zOrder,
visible,
alpha,
tag,
&f_position,
&f_scale,
&f_anchortpoint,
&f_color,
&f_size,
flipX,
flipY,
ignoreSize,
touchEnabled,
builder->CreateString(frameEvent),
builder->CreateString(customProperty),
0,
0,
f_layoutComponent);
return *(Offset<Table>*)(&options);
}
void NodeReader::setPropsWithFlatBuffers(cocos2d::Node *node,
const flatbuffers::Table* nodeOptions)
{
auto options = (WidgetOptions*)(nodeOptions);
std::string name = options->name()->c_str();
float x = options->position()->x();
float y = options->position()->y();
float scalex = options->scale()->scaleX();
float scaley = options->scale()->scaleY();
// float rotation = options.rotation();
float rotationSkewX = options->rotationSkew()->rotationSkewX();
float rotationSkewY = options->rotationSkew()->rotationSkewY();
float anchorx = options->anchorPoint()->scaleX();
float anchory = options->anchorPoint()->scaleY();
int zorder = options->zOrder();
int tag = options->tag();
int actionTag = options->actionTag();
bool visible = options->visible() != 0;
float w = options->size()->width();
float h = options->size()->height();
int alpha = options->alpha();
Color3B color(options->color()->r(), options->color()->g(), options->color()->b());
std::string customProperty = options->customProperty()->c_str();
node->setName(name);
// if(x != 0 || y != 0)
node->setPosition(Point(x, y));
if(scalex != 1)
node->setScaleX(scalex);
if(scaley != 1)
node->setScaleY(scaley);
// if (rotation != 0)
// node->setRotation(rotation);
if (rotationSkewX != 0)
node->setRotationSkewX(rotationSkewX);
if (rotationSkewY != 0)
node->setRotationSkewY(rotationSkewY);
if(anchorx != 0.5f || anchory != 0.5f)
node->setAnchorPoint(Point(anchorx, anchory));
if(zorder != 0)
node->setLocalZOrder(zorder);
if(visible != true)
node->setVisible(visible);
// if (w != 0 || h != 0)
node->setContentSize(Size(w, h));
if (alpha != 255)
node->setOpacity(alpha);
node->setColor(color);
node->setTag(tag);
ObjectExtensionData* extensionData = ObjectExtensionData::create();
extensionData->setCustomProperty(customProperty);
extensionData->setActionTag(actionTag);
node->setUserObject(extensionData);
node->setCascadeColorEnabled(true);
node->setCascadeOpacityEnabled(true);
setLayoutComponentPropsWithFlatBuffers(node, nodeOptions);
}
void NodeReader::setLayoutComponentPropsWithFlatBuffers(cocos2d::Node* node, const flatbuffers::Table* nodeOptions)
{
auto layoutComponentTable = ((WidgetOptions*)nodeOptions)->layoutComponent();
if (!layoutComponentTable) return;
auto layoutComponent = ui::LayoutComponent::bindLayoutComponent(node);
bool positionXPercentEnabled = layoutComponentTable->positionXPercentEnabled() != 0;
bool positionYPercentEnabled = layoutComponentTable->positionYPercentEnabled() != 0;
float positionXPercent = layoutComponentTable->positionXPercent();
float positionYPercent = layoutComponentTable->positionYPercent();
bool sizeXPercentEnable = layoutComponentTable->sizeXPercentEnable() != 0;
bool sizeYPercentEnable = layoutComponentTable->sizeYPercentEnable() != 0;
float sizeXPercent = layoutComponentTable->sizeXPercent();
float sizeYPercent = layoutComponentTable->sizeYPercent();
bool stretchHorizontalEnabled = layoutComponentTable->stretchHorizontalEnabled() != 0;
bool stretchVerticalEnabled = layoutComponentTable->stretchVerticalEnabled() != 0;
std::string horizontalEdge = layoutComponentTable->horizontalEdge()->c_str();
std::string verticalEdge = layoutComponentTable->verticalEdge()->c_str();
float leftMargin = layoutComponentTable->leftMargin();
float rightMargin = layoutComponentTable->rightMargin();
float topMargin = layoutComponentTable->topMargin();
float bottomMargin = layoutComponentTable->bottomMargin();
layoutComponent->setPositionPercentXEnabled(positionXPercentEnabled);
layoutComponent->setPositionPercentYEnabled(positionYPercentEnabled);
layoutComponent->setPositionPercentX(positionXPercent);
layoutComponent->setPositionPercentY(positionYPercent);
layoutComponent->setPercentWidthEnabled(sizeXPercentEnable);
layoutComponent->setPercentHeightEnabled(sizeYPercentEnable);
layoutComponent->setPercentWidth(sizeXPercent);
layoutComponent->setPercentHeight(sizeYPercent);
layoutComponent->setStretchWidthEnabled(stretchHorizontalEnabled);
layoutComponent->setStretchHeightEnabled(stretchVerticalEnabled);
ui::LayoutComponent::HorizontalEdge horizontalEdgeType = ui::LayoutComponent::HorizontalEdge::None;
if (horizontalEdge == Layout_LeftEdge)
{
horizontalEdgeType = ui::LayoutComponent::HorizontalEdge::Left;
}
else if (horizontalEdge == Layout_RightEdge)
{
horizontalEdgeType = ui::LayoutComponent::HorizontalEdge::Right;
}
else if (horizontalEdge == Layout_BothEdge)
{
horizontalEdgeType = ui::LayoutComponent::HorizontalEdge::Center;
}
layoutComponent->setHorizontalEdge(horizontalEdgeType);
ui::LayoutComponent::VerticalEdge verticalEdgeType = ui::LayoutComponent::VerticalEdge::None;
if (verticalEdge == Layout_TopEdge)
{
verticalEdgeType = ui::LayoutComponent::VerticalEdge::Top;
}
else if (verticalEdge == Layout_BottomEdge)
{
verticalEdgeType = ui::LayoutComponent::VerticalEdge::Bottom;
}
else if (verticalEdge == Layout_BothEdge)
{
verticalEdgeType = ui::LayoutComponent::VerticalEdge::Center;
}
layoutComponent->setVerticalEdge(verticalEdgeType);
layoutComponent->setTopMargin(topMargin);
layoutComponent->setBottomMargin(bottomMargin);
layoutComponent->setLeftMargin(leftMargin);
layoutComponent->setRightMargin(rightMargin);
}
Node* NodeReader::createNodeWithFlatBuffers(const flatbuffers::Table *nodeOptions)
{
Node* node = Node::create();
setPropsWithFlatBuffers(node, nodeOptions);
return node;
}
}
| 0 | 0.987182 | 1 | 0.987182 | game-dev | MEDIA | 0.864727 | game-dev | 0.965887 | 1 | 0.965887 |
Netflix/genie | 7,455 | genie-common-internal/src/test/groovy/com/netflix/genie/common/internal/dtos/CommandRequestSpec.groovy | /*
*
* Copyright 2018 Netflix, Inc.
*
* 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.
*
*/
package com.netflix.genie.common.internal.dtos
import spock.lang.Specification
/**
* Specifications for the {@link CommandRequest} class.
*
* @author tgianos
*/
class CommandRequestSpec extends Specification {
def "Can build immutable command request"() {
def metadata = new CommandMetadata.Builder(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
CommandStatus.ACTIVE
).build()
def requestedId = UUID.randomUUID().toString()
def resources = new ExecutionEnvironment(null, null, UUID.randomUUID().toString())
def executable = [UUID.randomUUID().toString(), UUID.randomUUID().toString()]
def clusterCriteria = [
new Criterion.Builder().withId(UUID.randomUUID().toString()).build(),
new Criterion.Builder().withName(UUID.randomUUID().toString()).build(),
new Criterion.Builder().withStatus(UUID.randomUUID().toString()).build(),
new Criterion.Builder().withVersion(UUID.randomUUID().toString()).build(),
new Criterion.Builder().withTags([UUID.randomUUID().toString()].toSet()).build()
]
def computeResources = DtoSpecUtils.getRandomComputeResources()
def images = [
foo: DtoSpecUtils.getRandomImage(),
bar: DtoSpecUtils.getRandomImage()
]
CommandRequest request
when:
request = new CommandRequest.Builder(metadata, executable)
.withRequestedId(requestedId)
.withResources(resources)
.withClusterCriteria(clusterCriteria)
.withComputeResources(computeResources)
.withImages(images)
.build()
then:
request.getMetadata() == metadata
request.getRequestedId().orElse(UUID.randomUUID().toString()) == requestedId
request.getResources() == resources
request.getExecutable() == executable
request.getClusterCriteria() == clusterCriteria
request.getComputeResources() == Optional.ofNullable(computeResources)
request.getImages() == images
when:
request = new CommandRequest.Builder(metadata, executable).build()
then:
request.getMetadata() == metadata
!request.getRequestedId().isPresent()
request.getResources() != null
request.getExecutable() == executable
request.getClusterCriteria().isEmpty()
!request.getComputeResources().isPresent()
request.getImages().isEmpty()
when: "Optional fields are blank they're ignored"
def newExecutable = new ArrayList(executable)
newExecutable.add("\t")
newExecutable.add(" ")
newExecutable.add("")
request = new CommandRequest.Builder(metadata, newExecutable)
.withRequestedId(" ")
.withResources(resources)
.withClusterCriteria(null)
.withComputeResources(null)
.withImages(null)
.build()
then:
request.getMetadata() == metadata
!request.getRequestedId().isPresent()
request.getResources() == resources
request.getExecutable() == executable
request.getClusterCriteria().isEmpty()
!request.getComputeResources().isPresent()
request.getImages().isEmpty()
}
def "Test equals"() {
def base = DtoSpecUtils.getRandomCommandRequest()
Object comparable
when:
comparable = base
then:
base == comparable
when:
comparable = null
then:
base != comparable
when:
comparable = new CommandRequest.Builder(Mock(CommandMetadata), [UUID.randomUUID().toString()])
.withRequestedId(UUID.randomUUID().toString())
.toString()
then:
base != comparable
when:
comparable = "I'm definitely not the right type of object"
then:
base != comparable
when:
def name = UUID.randomUUID().toString()
def user = UUID.randomUUID().toString()
def version = UUID.randomUUID().toString()
def status = CommandStatus.INACTIVE
def binary = UUID.randomUUID().toString()
def baseMetadata = new CommandMetadata.Builder(name, user, version, status).build()
def comparableMetadata = new CommandMetadata.Builder(name, user, version, status).build()
base = new CommandRequest.Builder(baseMetadata, [binary]).build()
comparable = new CommandRequest.Builder(comparableMetadata, [binary]).build()
then:
base == comparable
}
def "Test hashCode"() {
CommandRequest one
CommandRequest two
when:
one = DtoSpecUtils.getRandomCommandRequest()
two = one
then:
one.hashCode() == two.hashCode()
when:
one = DtoSpecUtils.getRandomCommandRequest()
two = DtoSpecUtils.getRandomCommandRequest()
then:
one.hashCode() != two.hashCode()
when:
def name = UUID.randomUUID().toString()
def user = UUID.randomUUID().toString()
def version = UUID.randomUUID().toString()
def status = CommandStatus.INACTIVE
def binary = UUID.randomUUID().toString()
def baseMetadata = new CommandMetadata.Builder(name, user, version, status).build()
def comparableMetadata = new CommandMetadata.Builder(name, user, version, status).build()
one = new CommandRequest.Builder(baseMetadata, [binary]).build()
two = new CommandRequest.Builder(comparableMetadata, [binary]).build()
then:
one.hashCode() == two.hashCode()
}
def "toString is consistent"() {
CommandRequest one
CommandRequest two
when:
one = DtoSpecUtils.getRandomCommandRequest()
two = one
then:
one.toString() == two.toString()
when:
one = DtoSpecUtils.getRandomCommandRequest()
two = DtoSpecUtils.getRandomCommandRequest()
then:
one.toString() != two.toString()
when:
def name = UUID.randomUUID().toString()
def user = UUID.randomUUID().toString()
def version = UUID.randomUUID().toString()
def status = CommandStatus.INACTIVE
def binary = UUID.randomUUID().toString()
def baseMetadata = new CommandMetadata.Builder(name, user, version, status).build()
def comparableMetadata = new CommandMetadata.Builder(name, user, version, status).build()
one = new CommandRequest.Builder(baseMetadata, [binary]).build()
two = new CommandRequest.Builder(comparableMetadata, [binary]).build()
then:
one.toString() == two.toString()
}
}
| 0 | 0.816219 | 1 | 0.816219 | game-dev | MEDIA | 0.560587 | game-dev | 0.79111 | 1 | 0.79111 |
Azure/azure-remote-rendering | 14,216 | Unity/Showcase/App/Assets/App/Sharing/Framework/Avatars/AvatarHandMovement.cs | // Copyright(c) Microsoft Corporation.All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Extensions.Sharing.Communication
{
public class AvatarHandMovement : MonoBehaviour
{
private Quaternion _reorientation;
private AvatarJoint[] _joints = null;
private Matrix4x4 _originToWorld;
#region Serialized Fields
[Header("Joint Transforms")]
[SerializeField]
[Tooltip("The hand joints transforms")]
private AvatarHandTransforms transforms = null;
/// <summary>
/// The hand joint transforms
/// </summary>
public AvatarHandTransforms Transforms
{
get => transforms;
set
{
if (transforms != value)
{
RemoveTransformsHandlers();
transforms = value;
InitializeJoints();
AddTransformsHandlers();
}
}
}
[Header("Joint Serialization Settings")]
[SerializeField]
[Tooltip("The settings for what and how joints should be serialized.")]
private AvatarSerialization avatarSerialization;
/// <summary>
/// The settings for what and how joints should be serialized
/// </summary>
public AvatarSerialization AvatarSerialization
{
get => avatarSerialization;
set
{
if (avatarSerialization != value)
{
RemoveTransformsHandlers();
avatarSerialization = value;
InitializeJoints();
AddTransformsHandlers();
}
}
}
[Header("Joint Smoothing")]
[SerializeField]
[Tooltip("The speed of the joint interpolation")]
private float interpolateLerpSpeed = 1.0f;
/// <summary>
/// The speed of the joint interpolation.
/// </summary>
public float InterpolateLerpSpeed
{
get => interpolateLerpSpeed;
set => interpolateLerpSpeed = value;
}
[Header("Advance Model Adjustments")]
[SerializeField]
[Tooltip("If non-zero, this vector and the modelPalmFacing vector " +
"will be used to re-orient the Transform bones in the hand rig, to " +
"compensate for bone axis discrepancies between tracked bones and model " +
"bones.")]
private Vector3 modelFingerPointing = new Vector3(0, 0, 0);
/// <summary>
/// If non-zero, this vector and the modelPalmFacing vector
/// will be used to re-orient the Transform bones in the hand rig, to
/// compensate for bone axis discrepancies between tracked bones and model
/// bones.
/// </summary>
public Vector3 ModelFingerPointing
{
get => modelFingerPointing;
set
{
modelFingerPointing = value;
UpdateReorientation();
}
}
[SerializeField]
[Tooltip("If non-zero, this vector and the modelFingerPointing vector " +
"will be used to re-orient the Transform bones in the hand rig, to " +
"compensate for bone axis discrepancies between tracked bones and model " +
"bones.")]
private Vector3 modelPalmFacing = new Vector3(0, 0, 0);
/// <summary>
/// If non-zero, this vector and the modelFingerPointing vector
/// will be used to re-orient the Transform bones in the hand rig, to
/// compensate for bone axis discrepancies between tracked bones and model
/// bones.
/// </summary>
public Vector3 ModelPalmFacing
{
get => modelPalmFacing;
set
{
modelPalmFacing = value;
UpdateReorientation();
}
}
#endregion Serialized Fields
#region Public Properties
public Transform Primary
{
get
{
if (transforms == null || transforms.Transforms == null)
{
return null;
}
else
{
transforms.Transforms.TryGetValue(
AvatarHandDescription.Primary.Joint,
out Transform primary);
return primary;
}
}
}
/// <summary>
/// The handedness.
/// </summary>
public Handedness Handedness
{
get => transforms?.Handedness ?? Handedness.Right;
}
#endregion Public Properties
#region MonoBehaviours Functions
private void OnValidate()
{
if (Application.isPlaying && Application.isEditor)
{
UpdateReorientation();
}
}
private void Start()
{
AddTransformsHandlers();
UpdateReorientation();
InitializeJoints();
}
private void LateUpdate()
{
float interpolatationTime = Mathf.Clamp01(
Time.deltaTime * interpolateLerpSpeed);
for (int i = 0; i < _joints.Length; i++)
{
UpdateJoint(i, interpolatationTime);
}
}
private void OnDestroy()
{
RemoveTransformsHandlers();
}
#endregion MonoBehavior Functions
#region Public Functions
public void SetPose(AvatarPose pose, Matrix4x4 originToWorld)
{
if (!isActiveAndEnabled || _joints == null)
{
return;
}
_originToWorld = originToWorld;
for (int i = 0; i < _joints.Length; i++)
{
UpdateJointGoal(pose, i);
}
}
public Transform GetTransform(TrackedHandJoint joint)
{
Transforms.Transforms.TryGetValue(joint, out Transform result);
return result;
}
#endregion Public Functions
#region Private Functions
/// <summary>
/// Add transforms handlers
/// </summary>
private void AddTransformsHandlers()
{
if (transforms != null)
{
transforms.TransformsChanged += OnTransformsChanged;
}
}
/// <summary>
/// Remove transforms handlers
/// </summary>
private void RemoveTransformsHandlers()
{
if (transforms != null)
{
transforms.TransformsChanged -= OnTransformsChanged;
}
}
/// <summary>
/// Initialize joint dictionary with their corresponding joint transforms
/// </summary>
private void InitializeJoints()
{
if (Transforms == null || AvatarSerialization == null)
{
return;
}
// find joint transforms
var transforms = Transforms.Transforms;
if (transforms == null)
{
return;
}
// find the hand description
var handDescription = AvatarSerialization.HandDescription;
if (handDescription == null)
{
return;
}
// create serializable joint data
int index = 0;
_joints = new AvatarJoint[handDescription.SerializableJoints.Length];
foreach (var joint in handDescription.SerializableJoints)
{
if (transforms.TryGetValue(joint.Joint, out Transform jointTransform))
{
var avatarJoint = AvatarJoint.Create(joint, jointTransform);
_joints[index++] = avatarJoint;
}
}
if (index != _joints.Length)
{
Array.Resize(ref _joints, index);
}
}
private void UpdateJointGoal(AvatarPose pose, int index)
{
AvatarJoint joint = _joints[index];
if (joint.hasPose)
{
if (pose.TryGetJoint(Handedness, joint.joint, out Pose jointPose))
{
jointPose.position = ToWorld(jointPose.position);
jointPose.rotation = ToWorld(jointPose.rotation) * _reorientation;
joint.Goal(jointPose);
}
else
{
joint.Reset();
}
}
else if (pose.TryGetJoint(Handedness, joint.joint, out Quaternion rotation))
{
joint.Goal(ToWorld(rotation) * _reorientation);
}
else
{
joint.Reset();
}
}
private void UpdateJoint(int index, float interpolatationTime)
{
_joints[index].Update(interpolatationTime);
}
private Vector3 ToWorld(Vector3 position)
{
return _originToWorld.MultiplyPoint(position);
}
private Quaternion ToWorld(Quaternion rotation)
{
return _originToWorld.rotation * rotation;
}
private void UpdateReorientation()
{
if (modelFingerPointing == Vector3.zero || modelPalmFacing == Vector3.zero)
{
_reorientation = Quaternion.identity;
}
else
{
_reorientation = Quaternion.Inverse(Quaternion.LookRotation(modelFingerPointing, -modelPalmFacing));
}
}
/// <summary>
/// Handle transform changes
/// </summary>
/// <param name="sender"></param>
/// <param name="transforms"></param>
private void OnTransformsChanged(AvatarHandTransforms sender, IReadOnlyDictionary<TrackedHandJoint, Transform> transforms)
{
InitializeJoints();
}
#endregion Private Functions
#region Private Classes
private class AvatarJoint
{
public readonly TrackedHandJoint joint;
public readonly bool isHand;
public readonly bool hasPose;
public readonly bool isSerialized;
public readonly Transform transform;
public readonly Pose defaultLocalPose;
private bool targetPoseLocal;
private Pose targetPose;
private AvatarJoint(TrackedHandJoint joint, bool isSerialized, bool isHand, bool hasPose, Transform transform)
{
this.joint = joint;
this.isHand = isHand;
this.hasPose = hasPose;
this.transform = transform;
this.isSerialized = isSerialized;
this.targetPose = new Pose(Vector3.negativeInfinity, Quaternion.identity);
this.defaultLocalPose = transform == null ?
Pose.identity :
new Pose(transform.localPosition, transform.localRotation);
}
public static AvatarJoint Create(AvatarJointDescription jointDescription, Transform transform)
{
return new AvatarJoint(
joint: jointDescription.Joint,
isSerialized: true,
isHand: false,
hasPose: jointDescription.HasPose,
transform: transform);
}
public void Goal(Quaternion rotation)
{
targetPoseLocal = false;
targetPose.rotation = rotation;
}
public void Goal(Pose pose)
{
targetPoseLocal = false;
targetPose = pose;
}
public void Reset()
{
targetPoseLocal = true;
targetPose.position = defaultLocalPose.position;
targetPose.rotation = defaultLocalPose.rotation;
}
public void Update(float interpolatationTime)
{
if (transform == null || !targetPose.position.IsValidVector())
{
return;
}
if (targetPoseLocal)
{
UpdateLocal(interpolatationTime);
}
else
{
UpdateGlobal(interpolatationTime);
}
}
public void UpdateGlobal(float interpolatationTime)
{
Quaternion rotation = Quaternion.Lerp(
transform.rotation,
targetPose.rotation,
interpolatationTime);
if (hasPose)
{
Vector3 position = Vector3.Lerp(
transform.position,
targetPose.position,
interpolatationTime);
transform.SetPositionAndRotation(position, rotation);
}
else
{
transform.rotation = rotation;
}
}
public void UpdateLocal(float interpolatationTime)
{
transform.localRotation = Quaternion.Lerp(
transform.localRotation,
targetPose.rotation,
interpolatationTime);
if (hasPose)
{
transform.localPosition = Vector3.Lerp(
transform.localPosition,
targetPose.position,
interpolatationTime);
}
}
}
#endregion Private Classes
}
}
| 0 | 0.981908 | 1 | 0.981908 | game-dev | MEDIA | 0.87539 | game-dev | 0.952942 | 1 | 0.952942 |
bijington/orbit | 2,608 | games/ChooseYourOwnAdventure/ChooseYourOwnAdventure/Slides/SlideCombined.xaml.cs | using Orbit.Engine;
namespace BuildingGames.Slides;
public partial class SlideCombined : SlidePageBase
{
private readonly IDispatcher dispatcher;
private readonly CancellationTokenSource cancellationTokenSource;
public SlideCombined(IDispatcher dispatcher, IGameSceneManager gameSceneManager, ControllerManager controllerManager) : base(gameSceneManager, controllerManager)
{
InitializeComponent();
this.dispatcher = dispatcher;
cancellationTokenSource = new CancellationTokenSource();
}
protected override void OnNavigatedTo(NavigatedToEventArgs args)
{
base.OnNavigatedTo(args);
PerformAnimation();
}
protected override void OnNavigatingFrom(NavigatingFromEventArgs args)
{
base.OnNavigatingFrom(args);
cancellationTokenSource.Cancel();
}
private void PerformAnimation()
{
dispatcher.DispatchDelayed(
TimeSpan.FromSeconds(2),
async () =>
{
try
{
Tile.Scale = 1;
Tile.IsVisible = true;
await Task.Delay(TimeSpan.FromMilliseconds(500), cancellationTokenSource.Token);
await Tile.RotateXTo(90, 100, Easing.BounceIn);
Tile.Content.IsVisible = !Tile.Content.IsVisible;
await Tile.RotateXTo(0, 100, Easing.BounceIn);
await Task.Delay(TimeSpan.FromMilliseconds(500), cancellationTokenSource.Token);
var animation = new Animation
{
{ 0.0, 0.2, new Animation(v => Tile.Scale = v, 1, 0.9) },
{ 0.2, 0.75, new Animation(v => Tile.Scale = v, 0.9, 1.2) },
{ 0.75, 1.0, new Animation(v => Tile.Scale = v, 1.2, 0) }
};
animation.Commit(
Tile,
"SuccessfulMatch",
length: 500,
easing: Easing.SpringIn,
finished: (v, f) =>
{
Tile.IsVisible = false;
ParticleEmitter.Emit();
if (cancellationTokenSource.IsCancellationRequested is false)
{
PerformAnimation();
}
});
}
catch (OperationCanceledException)
{
}
});
}
} | 0 | 0.925492 | 1 | 0.925492 | game-dev | MEDIA | 0.753387 | game-dev | 0.991737 | 1 | 0.991737 |
CalamityTeam/CalamityModPublic | 3,384 | Systems/BiomeTileCounterSystem.cs | using System;
using CalamityMod.Tiles.Abyss;
using CalamityMod.Tiles.Astral;
using CalamityMod.Tiles.AstralDesert;
using CalamityMod.Tiles.AstralSnow;
using CalamityMod.Tiles.Crags;
using CalamityMod.Tiles.DraedonStructures;
using CalamityMod.Tiles.Ores;
using CalamityMod.Tiles.SunkenSea;
using Terraria;
using Terraria.ModLoader;
namespace CalamityMod.Systems
{
public class BiomeTileCounterSystem : ModSystem
{
public static int BrimstoneCragTiles = 0;
public static int SulphurTiles = 0;
public static int AbyssTiles = 0;
public static int AstralTiles = 0;
public static int SunkenSeaTiles = 0;
public static int ArsenalLabTiles = 0;
public static int Layer1Tiles = 0;
public static int Layer2Tiles = 0;
public static int Layer3Tiles = 0;
public static int Layer4Tiles = 0;
public override void ResetNearbyTileEffects()
{
BrimstoneCragTiles = 0;
AstralTiles = 0;
SunkenSeaTiles = 0;
SulphurTiles = 0;
AbyssTiles = 0;
ArsenalLabTiles = 0;
Layer1Tiles = 0;
Layer2Tiles = 0;
Layer3Tiles = 0;
Layer4Tiles = 0;
}
public override void TileCountsAvailable(ReadOnlySpan<int> tileCounts)
{
BrimstoneCragTiles = tileCounts[ModContent.TileType<InfernalSuevite>()] + tileCounts[ModContent.TileType<BrimstoneSlag>()];
SunkenSeaTiles = tileCounts[ModContent.TileType<EutrophicSand>()] + tileCounts[ModContent.TileType<Navystone>()] + tileCounts[ModContent.TileType<SeaPrism>()];
AbyssTiles = tileCounts[ModContent.TileType<AbyssGravel>()] + tileCounts[ModContent.TileType<Voidstone>()];
SulphurTiles = tileCounts[ModContent.TileType<SulphurousSand>()] + tileCounts[ModContent.TileType<SulphurousSandstone>()] + tileCounts[ModContent.TileType<HardenedSulphurousSandstone>()];
ArsenalLabTiles = tileCounts[ModContent.TileType<LaboratoryPanels>()] + tileCounts[ModContent.TileType<LaboratoryPlating>()] + tileCounts[ModContent.TileType<HazardChevronPanels>()];
Layer1Tiles = tileCounts[ModContent.TileType<SulphurousShale>()];
Layer2Tiles = tileCounts[ModContent.TileType<AbyssGravel>()] + tileCounts[ModContent.TileType<PlantyMush>()];
Layer3Tiles = tileCounts[ModContent.TileType<PyreMantle>()];
Layer4Tiles = tileCounts[ModContent.TileType<Voidstone>()];
int astralDesertTiles = tileCounts[ModContent.TileType<AstralSand>()] + tileCounts[ModContent.TileType<AstralSandstone>()] + tileCounts[ModContent.TileType<HardenedAstralSand>()] + tileCounts[ModContent.TileType<CelestialRemains>()];
int astralSnowTiles = tileCounts[ModContent.TileType<AstralIce>()] + tileCounts[ModContent.TileType<AstralSnow>()];
Main.SceneMetrics.SandTileCount += astralDesertTiles;
Main.SceneMetrics.SnowTileCount += astralSnowTiles;
AstralTiles = astralDesertTiles + astralSnowTiles + tileCounts[ModContent.TileType<AstralDirt>()] + tileCounts[ModContent.TileType<AstralStone>()] + tileCounts[ModContent.TileType<AstralGrass>()] + tileCounts[ModContent.TileType<AstralOre>()] + tileCounts[ModContent.TileType<NovaeSlag>()] + tileCounts[ModContent.TileType<AstralClay>()];
}
}
}
| 0 | 0.633614 | 1 | 0.633614 | game-dev | MEDIA | 0.838889 | game-dev | 0.714957 | 1 | 0.714957 |
StyledStrike/gmod-glide | 5,130 | lua/glide/client/events.lua | local cvarIsMouseVisible = CreateConVar( "cl_glide_is_mouse_visible", "0", { FCVAR_USERINFO, FCVAR_DONTRECORD } )
concommand.Add( "glide_switch_seat", function( ply, _, args )
if ply ~= LocalPlayer() then return end
if #args == 0 then return end
local seatIndex = tonumber( args[1] )
if not seatIndex then return end
local vehicle = ply:GlideGetVehicle()
if not IsValid( vehicle ) then return end
Glide.StartCommand( Glide.CMD_SWITCH_SEATS )
net.WriteUInt( seatIndex, 5 )
net.SendToServer()
end, nil, "Switch seats while inside a Glide vehicle." )
----- Check if the local player has entered/left a Glide vehicle.
local hideComponent = {
["CHudHealth"] = true,
["CHudBattery"] = true
}
local function HUDShouldDraw( name )
if hideComponent[name] then return false end
end
-- Block (some) binds that uses the same buttons as Glide
local ACTION_FILTER = {
["countermeasures"] = true,
["landing_gear"] = true,
["shift_up"] = true,
["shift_down"] = true,
["shift_neutral"] = true
}
local usedButtons = {}
hook.Add( "Glide_OnConfigChange", "Glide.BlockBindConflicts", function()
table.Empty( usedButtons )
for _, actions in pairs( Glide.Config.binds ) do
for action, button in pairs( actions ) do
if ACTION_FILTER[action] then
usedButtons[button] = true
end
end
end
end )
local DONT_BLOCK = {
["+use"] = true,
["+reload"] = true,
["+attack"] = true,
["+attack2"] = true,
["+attack3"] = true,
["+walk"] = true
}
local function BlockBinds( _, bind, _, code )
if usedButtons[code] and not DONT_BLOCK[bind] then
return true
end
end
local ScrW, ScrH = ScrW, ScrH
local activeVehicle, activeSeatIndex = NULL, 0
local cvarDrawHud = GetConVar( "cl_drawhud" )
local function DrawVehicleHUD()
if
IsValid( activeVehicle ) and
cvarDrawHud:GetBool() and
hook.Run( "Glide_CanDrawHUD", activeVehicle ) ~= false
then
activeVehicle:DrawVehicleHUD( ScrW(), ScrH() )
end
end
local function OnEnter( vehicle, seatIndex )
vehicle:OnLocalPlayerEnter( seatIndex )
vehicle.isLocalPlayerInVehicle = true
vehicle.headlightState = 0
activeVehicle = vehicle
activeSeatIndex = seatIndex
Glide.currentVehicle = vehicle
Glide.currentSeatIndex = seatIndex
hook.Add( "PlayerBindPress", "Glide.BlockBinds", BlockBinds )
hook.Add( "HUDShouldDraw", "Glide.HideDefaultHealth", HUDShouldDraw )
hook.Add( "HUDPaint", "Glide.DrawVehicleHUD", DrawVehicleHUD )
hook.Run( "Glide_OnLocalEnterVehicle", vehicle, seatIndex )
timer.Create( "Glide.CheckMouseVisibility", 0.25, 0, function()
cvarIsMouseVisible:SetInt( vgui.CursorVisible() and 1 or 0 )
end )
if vehicle.VehicleType == Glide.VEHICLE_TYPE.HELICOPTER and system.IsLinux() then
Glide.Print( "Linux system detected, setting snd_fixed_rate to 1" )
RunConsoleCommand( "snd_fixed_rate", "1" )
end
-- Simple ThirdPerson compatibility
local func = hook.GetTable()["CalcView"]["SimpleTP.CameraView"]
if func then
Glide.simpleThirdPersonHook = func
hook.Remove( "CalcView", "SimpleTP.CameraView" )
end
end
local function OnLeave( ply )
if IsValid( activeVehicle ) then
activeVehicle:OnLocalPlayerExit()
activeVehicle.isLocalPlayerInVehicle = false
activeVehicle.headlightState = 0
end
activeVehicle = nil
activeSeatIndex = 0
Glide.currentVehicle = nil
Glide.currentSeatIndex = nil
Glide.ResetBoneManipulations( ply )
hook.Remove( "PlayerBindPress", "Glide.BlockBinds" )
hook.Remove( "HUDShouldDraw", "Glide.HideDefaultHealth" )
hook.Remove( "HUDPaint", "Glide.DrawVehicleHUD" )
hook.Run( "Glide_OnLocalExitVehicle" )
if system.IsLinux() then
Glide.Print( "Linux system detected, setting snd_fixed_rate to 0" )
RunConsoleCommand( "snd_fixed_rate", "0" )
end
-- Simple ThirdPerson compatibility
if Glide.simpleThirdPersonHook then
hook.Add( "CalcView", "SimpleTP.CameraView", Glide.simpleThirdPersonHook )
end
timer.Remove( "Glide.CheckMouseVisibility" )
cvarIsMouseVisible:SetInt( 0 )
end
local IsValid = IsValid
local LocalPlayer = LocalPlayer
hook.Add( "Tick", "Glide.CheckCurrentVehicle", function()
local ply = LocalPlayer()
if not IsValid( ply ) then return end
local seat = ply:GetVehicle()
if not IsValid( seat ) then
if activeSeatIndex > 0 then
OnLeave( ply )
end
return
end
local parent = seat:GetParent()
if not IsValid( parent ) or not parent.IsGlideVehicle then
if activeSeatIndex > 0 then
OnLeave( ply )
end
return
end
local seatIndex = ply:GlideGetSeatIndex()
if activeSeatIndex ~= seatIndex then
if activeSeatIndex > 0 then
OnLeave( ply )
end
activeSeatIndex = seatIndex
if seatIndex > 0 then
OnEnter( parent, seatIndex )
end
end
end )
| 0 | 0.799548 | 1 | 0.799548 | game-dev | MEDIA | 0.964255 | game-dev | 0.910928 | 1 | 0.910928 |
showlab/BYOC | 1,361 | BlendshapeToolkit/Library/PackageCache/com.unity.visualscripting@1.8.0/Runtime/VisualScripting.Flow/Framework/Collections/Lists/GetListItem.cs | using System.Collections;
namespace Unity.VisualScripting
{
/// <summary>
/// Gets the item at the specified index of a list.
/// </summary>
[UnitCategory("Collections/Lists")]
[UnitSurtitle("List")]
[UnitShortTitle("Get Item")]
[UnitOrder(0)]
[TypeIcon(typeof(IList))]
public sealed class GetListItem : Unit
{
/// <summary>
/// The list.
/// </summary>
[DoNotSerialize]
[PortLabelHidden]
public ValueInput list { get; private set; }
/// <summary>
/// The zero-based index.
/// </summary>
[DoNotSerialize]
public ValueInput index { get; private set; }
/// <summary>
/// The item.
/// </summary>
[DoNotSerialize]
[PortLabelHidden]
public ValueOutput item { get; private set; }
protected override void Definition()
{
list = ValueInput<IList>(nameof(list));
index = ValueInput(nameof(index), 0);
item = ValueOutput(nameof(item), Get);
Requirement(list, item);
Requirement(index, item);
}
public object Get(Flow flow)
{
var list = flow.GetValue<IList>(this.list);
var index = flow.GetValue<int>(this.index);
return list[index];
}
}
}
| 0 | 0.801972 | 1 | 0.801972 | game-dev | MEDIA | 0.661647 | game-dev | 0.686165 | 1 | 0.686165 |
FTL13/FTL13 | 2,981 | code/modules/mob/living/carbon/alien/humanoid/humanoid_defense.dm |
/mob/living/carbon/alien/humanoid/grabbedby(mob/living/carbon/user, supress_message = 0)
if(user == src && pulling && grab_state >= GRAB_AGGRESSIVE && !pulling.anchored && iscarbon(pulling))
devour_mob(pulling, devour_time = 60)
else
..()
/mob/living/carbon/alien/humanoid/attack_hulk(mob/living/carbon/human/user, does_attack_animation = 0)
if(user.a_intent == INTENT_HARM)
..(user, 1)
adjustBruteLoss(15)
var/hitverb = "punched"
if(mob_size < MOB_SIZE_LARGE)
step_away(src,user,15)
sleep(1)
step_away(src,user,15)
hitverb = "slammed"
playsound(loc, "punch", 25, 1, -1)
visible_message("<span class='danger'>[user] has [hitverb] [src]!</span>", \
"<span class='userdanger'>[user] has [hitverb] [src]!</span>", null, COMBAT_MESSAGE_RANGE)
return 1
/mob/living/carbon/alien/humanoid/attack_hand(mob/living/carbon/human/M)
if(..())
switch(M.a_intent)
if ("harm")
var/damage = rand(1, 9)
if (prob(90))
playsound(loc, "punch", 25, 1, -1)
visible_message("<span class='danger'>[M] has punched [src]!</span>", \
"<span class='userdanger'>[M] has punched [src]!</span>", null, COMBAT_MESSAGE_RANGE)
if ((stat != DEAD) && (damage > 9 || prob(5)))//Regular humans have a very small chance of knocking an alien down.
Unconscious(40)
visible_message("<span class='danger'>[M] has knocked [src] down!</span>", \
"<span class='userdanger'>[M] has knocked [src] down!</span>")
var/obj/item/bodypart/affecting = get_bodypart(ran_zone(M.zone_selected))
apply_damage(damage, BRUTE, affecting)
add_logs(M, src, "attacked")
else
playsound(loc, 'sound/weapons/punchmiss.ogg', 25, 1, -1)
visible_message("<span class='userdanger'>[M] has attempted to punch [src]!</span>", \
"<span class='userdanger'>[M] has attempted to punch [src]!</span>", null, COMBAT_MESSAGE_RANGE)
if ("disarm")
if (!lying)
if (prob(5))
Unconscious(40)
playsound(loc, 'sound/weapons/thudswoosh.ogg', 50, 1, -1)
add_logs(M, src, "pushed")
visible_message("<span class='danger'>[M] has pushed down [src]!</span>", \
"<span class='userdanger'>[M] has pushed down [src]!</span>")
else
if (prob(50))
drop_item()
playsound(loc, 'sound/weapons/thudswoosh.ogg', 50, 1, -1)
visible_message("<span class='danger'>[M] has disarmed [src]!</span>", \
"<span class='userdanger'>[M] has disarmed [src]!</span>", null, COMBAT_MESSAGE_RANGE)
else
playsound(loc, 'sound/weapons/punchmiss.ogg', 25, 1, -1)
visible_message("<span class='userdanger'>[M] has attempted to disarm [src]!</span>",\
"<span class='userdanger'>[M] has attempted to disarm [src]!</span>", null, COMBAT_MESSAGE_RANGE)
/mob/living/carbon/alien/humanoid/do_attack_animation(atom/A, visual_effect_icon, obj/item/used_item, no_effect, end_pixel_y)
if(!no_effect && !visual_effect_icon)
visual_effect_icon = ATTACK_EFFECT_CLAW
..()
| 0 | 0.900692 | 1 | 0.900692 | game-dev | MEDIA | 0.998573 | game-dev | 0.854179 | 1 | 0.854179 |
Kosmonaut3d/DeferredEngine | 4,964 | HelperSuite/GUI/GUITextBlockToggle.cs | using System;
using System.Reflection;
using HelperSuite.GUIHelper;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace HelperSuite.GUI
{
public class GUITextBlockToggle : GUITextBlock
{
public bool Toggle;
private const float ToggleIndicatorSize = 20;
private const float ToggleIndicatorBorder = 10;
public PropertyInfo ToggleProperty;
public FieldInfo ToggleField;
public object ToggleObject;
public GUITextBlockToggle(GUIStyle guitStyle, String text) : this(
position: Vector2.Zero,
dimensions: guitStyle.DimensionsStyle,
text: text,
font: guitStyle.TextFontStyle,
blockColor: guitStyle.BlockColorStyle,
textColor: guitStyle.TextColorStyle,
textAlignment: guitStyle.TextAlignmentStyle,
textBorder: guitStyle.TextBorderStyle,
layer: 0,
alignment: guitStyle.GuiAlignmentStyle,
parentDimensions: guitStyle.ParentDimensionsStyle)
{ }
public GUITextBlockToggle(Vector2 position, Vector2 dimensions, String text, SpriteFont font, Color blockColor, Color textColor, GUIStyle.TextAlignment textAlignment = GUIStyle.TextAlignment.Left, Vector2 textBorder = default(Vector2), int layer = 0, GUIStyle.GUIAlignment alignment = GUIStyle.GUIAlignment.None, Vector2 parentDimensions = default(Vector2)) : base(position, dimensions, text, font, blockColor, textColor, textAlignment, textBorder, layer)
{
}
public void SetField(Object obj, string field)
{
ToggleObject = obj;
ToggleField = obj.GetType().GetField(field);
Toggle = (bool)ToggleField.GetValue(obj);
}
public void SetProperty(Object obj, string property)
{
ToggleObject = obj;
ToggleProperty = obj.GetType().GetProperty(property);
Toggle = (bool)ToggleProperty.GetValue(obj);
}
protected override void ComputeFontPosition()
{
if (Text == null) return;
Vector2 textDimensions = TextFont.MeasureString(Text);
FontWrap(ref textDimensions, Dimensions - Vector2.UnitX * (ToggleIndicatorSize + ToggleIndicatorBorder * 2));
switch (TextAlignment)
{
case GUIStyle.TextAlignment.Left:
_fontPosition = (Dimensions - Vector2.UnitX * (ToggleIndicatorSize + ToggleIndicatorBorder * 2)) / 2 * Vector2.UnitY + _textBorder * Vector2.UnitX - textDimensions / 2 * Vector2.UnitY;
break;
case GUIStyle.TextAlignment.Center:
_fontPosition = (Dimensions - Vector2.UnitX * (ToggleIndicatorSize + ToggleIndicatorBorder * 2)) / 2 - textDimensions / 2;
break;
case GUIStyle.TextAlignment.Right:
_fontPosition = (Dimensions - Vector2.UnitX * (ToggleIndicatorSize + ToggleIndicatorBorder * 2)) * new Vector2(1, 0.5f) - _textBorder * Vector2.UnitX - textDimensions / 2;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
public override void Draw(GUIRenderer.GUIRenderer guiRenderer, Vector2 parentPosition, Vector2 mousePosition)
{
guiRenderer.DrawQuad(parentPosition + Position, Dimensions, BlockColor);
guiRenderer.DrawQuad(parentPosition + Position + Dimensions * new Vector2(1, 0.5f) - ToggleIndicatorBorder * Vector2.UnitX - ToggleIndicatorSize * new Vector2(1,0.5f) , Vector2.One * ToggleIndicatorSize, Toggle ? Color.LimeGreen : Color.Red);
guiRenderer.DrawText(parentPosition + Position + _fontPosition, Text, TextFont, TextColor);
}
public override void Update(GameTime gameTime, Vector2 mousePosition, Vector2 parentPosition)
{
if (!GUIControl.WasLMBClicked()) return;
Vector2 bound1 = Position + parentPosition;
Vector2 bound2 = bound1 + Dimensions;
if (mousePosition.X >= bound1.X && mousePosition.Y >= bound1.Y && mousePosition.X < bound2.X &&
mousePosition.Y < bound2.Y)
{
Toggle = !Toggle;
GUIControl.UIWasUsed = true;
if (ToggleObject != null)
{
if (ToggleField != null) ToggleField.SetValue(ToggleObject, Toggle, BindingFlags.Public, null, null);
if (ToggleProperty != null) ToggleProperty.SetValue(ToggleObject, Toggle);
}
else
{
if (ToggleField != null) ToggleField.SetValue(null, Toggle, BindingFlags.Static | BindingFlags.Public, null, null);
if (ToggleProperty != null) ToggleProperty.SetValue(null, Toggle);
}
}
}
}
} | 0 | 0.938538 | 1 | 0.938538 | game-dev | MEDIA | 0.64279 | game-dev,desktop-app | 0.976143 | 1 | 0.976143 |
Hork-Engine/Hork-Source | 10,897 | Hork/Runtime/World/GameObject.h | /*
Hork Engine Source Code
MIT License
Copyright (C) 2017-2025 Alexander Samusev.
This file is part of the Hork Engine Source Code.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include <Hork/Core/Containers/ObjectStorage.h>
#include <Hork/Math/Transform.h>
#include "Component.h"
#include "ComponentManager.h"
HK_NAMESPACE_BEGIN
class World;
using GameObjectHandle = Handle32<class GameObject>;
struct GameObjectDesc
{
StringID Name;
GameObjectHandle Parent;
Float3 Position;
Quat Rotation;
Float3 Scale = Float3(1);
bool AbsolutePosition{};
bool AbsoluteRotation{};
bool AbsoluteScale{};
bool IsDynamic{};
};
class GameObject final
{
friend class World;
friend class ComponentManagerBase;
friend class ObjectStorage<GameObject, 64, ObjectStorageType::Compact, HEAP_WORLD_OBJECTS>;
public:
enum
{
INPLACE_COMPONENT_COUNT = 8
};
using ComponentVector = SmallVector<Component*, INPLACE_COMPONENT_COUNT>;
GameObjectHandle GetHandle() const;
StringID GetName() const;
World* GetWorld();
World const* GetWorld() const;
/// Если объект динамический, то к нему можно аттачить и статические, и динамические компоненты.
/// Если объект статический, то к нему можно аттачить только статические компоненты.
/// При попытке к статичесеому объекту присоединить динамический компонент, объект автоматически становится динамическим.
/// Динамический компонент меняет трансформу у своего владельца (управляет им), например DynamicBodyComponent, CharacterControllerComponent и т.п.
/// Статический компонент не меняет трансформу у соего владельца, но ничто не мешает ему менять трансформы других объектов,
/// правда для этого нужно учитывать являются ли эти объекты динамическими.
void SetDynamic(bool dynamic);
bool IsStatic() const;
bool IsDynamic() const;
template <typename ComponentType>
Handle32<ComponentType> CreateComponent();
template <typename ComponentType>
Handle32<ComponentType> CreateComponent(ComponentType*& component);
template <typename ComponentType>
ComponentType* GetComponent();
template <typename ComponentType>
Handle32<ComponentType> GetComponentHandle();
Component* GetComponent(ComponentTypeID id);
template <typename ComponentType>
void GetAllComponents(Vector<ComponentType*>& components);
void GetAllComponents(ComponentTypeID id, Vector<Component*>& components);
ComponentVector const& GetComponents() const;
enum class TransformRule
{
KeepRelative,
KeepWorld
};
void SetParent(GameObjectHandle handle, TransformRule transformRule = TransformRule::KeepRelative);
void SetParent(GameObject* parent, TransformRule transformRule = TransformRule::KeepRelative);
GameObject* GetParent();
struct ChildIterator
{
friend class GameObject;
private:
GameObject* m_Object;
World const* m_World;
public:
ChildIterator(GameObject* first, World const* world);
GameObject& operator*();
GameObject* operator->();
operator GameObject*();
bool IsValid() const;
void operator++();
};
struct ConstChildIterator
{
friend class GameObject;
private:
GameObject const* m_Object;
World const* m_World;
public:
ConstChildIterator(GameObject const* first, World const* world);
GameObject const& operator*() const;
GameObject const* operator->() const;
operator GameObject const*() const;
bool IsValid() const;
void operator++();
};
ChildIterator GetChildren();
ConstChildIterator GetChildren() const;
void SetPosition(Float3 const& position);
void SetRotation(Quat const& rotation);
void SetScale(Float3 const& scale);
void SetPositionAndRotation(Float3 const& position, Quat const& rotation);
void SetTransform(Float3 const& position, Quat const& rotation, Float3 const& scale);
void SetTransform(Transform const& transform);
void SetAngles(Angl const& angles);
void SetDirection(Float3 const& direction);
void SetWorldPosition(Float3 const& position);
void SetWorldRotation(Quat const& rotation);
void SetWorldScale(Float3 const& scale);
void SetWorldPositionAndRotation(Float3 const& position, Quat const& rotation);
void SetWorldTransform(Float3 const& position, Quat const& rotation, Float3 const& scale);
void SetWorldTransform(Transform const& transform);
void SetWorldAngles(Angl const& angles);
void SetWorldDirection(Float3 const& direction);
void SetAbsolutePosition(bool absolutePosition);
void SetAbsoluteRotation(bool absoluteRotation);
void SetAbsoluteScale(bool absoluteScale);
bool HasAbsolutePosition() const;
bool HasAbsoluteRotation() const;
bool HasAbsoluteScale() const;
Float3 const& GetPosition() const;
Quat const& GetRotation() const;
Float3 const& GetScale() const;
Float3 GetRightVector() const;
Float3 GetLeftVector() const;
Float3 GetUpVector() const;
Float3 GetDownVector() const;
Float3 GetBackVector() const;
Float3 GetForwardVector() const;
Float3 GetDirection() const;
void GetVectors(Float3* right, Float3* up, Float3* back) const;
Float3 const& GetWorldPosition() const;
Quat const& GetWorldRotation() const;
Float3 const& GetWorldScale() const;
Float3x4 const& GetWorldTransformMatrix() const;
Float3 GetWorldRightVector() const;
Float3 GetWorldLeftVector() const;
Float3 GetWorldUpVector() const;
Float3 GetWorldDownVector() const;
Float3 GetWorldBackVector() const;
Float3 GetWorldForwardVector() const;
Float3 GetWorldDirection() const;
void GetWorldVectors(Float3* right, Float3* up, Float3* back) const;
void Rotate(float degrees, Float3 const& normalizedAxis);
void Move(Float3 const& dir);
void UpdateWorldTransform();
void UpdateChildrenWorldTransform();
void SetLockWorldPositionAndRotation(bool lock);
GameObject* FindChildren(StringID name);
GameObject* FindChildrenRecursive(StringID name);
private:
GameObject() = default;
GameObject(GameObject const& rhs) = delete;
GameObject(GameObject&& rhs);
GameObject& operator=(GameObject const& rhs) = delete;
GameObject& operator=(GameObject&& rhs) = delete;
void AddComponent(Component* component);
void RemoveComponent(Component* component);
void PatchComponentPointer(Component* oldPointer, Component* newPointer);
void LinkToParent();
void UnlinkFromParent();
GameObjectHandle m_Handle;
union
{
uint32_t m_FlagBits = 0;
struct
{
bool IsDynamic : 1;
bool IsDestroyed : 1;
} m_Flags;
};
World* m_World = nullptr;
GameObjectHandle m_Parent = 0;
GameObjectHandle m_FirstChild = 0;
GameObjectHandle m_LastChild = 0;
GameObjectHandle m_NextSibling = 0;
GameObjectHandle m_PrevSibling = 0;
uint16_t m_ChildCount = 0;
uint16_t m_HierarchyLevel = 0;
struct TransformData
{
GameObject* Owner{};
TransformData* Parent{};
bool LockWorldPositionAndRotation{};
bool AbsolutePosition{};
bool AbsoluteRotation{};
bool AbsoluteScale{};
Float3 Position;
Quat Rotation;
Float3 Scale = Float3(1.0f);
Float3 WorldPosition;
Quat WorldRotation;
Float3 WorldScale = Float3(1.0f);
Float3x4 WorldTransform;
void UpdateWorldTransformMatrix();
void UpdateWorldTransform_r();
void UpdateWorldTransform();
};
TransformData* m_TransformData{};
ComponentVector m_Components;
StringID m_Name;
};
HK_NAMESPACE_END
#include "GameObject.inl"
| 0 | 0.823639 | 1 | 0.823639 | game-dev | MEDIA | 0.983743 | game-dev | 0.650424 | 1 | 0.650424 |
Stencyl/stencyl-engine | 2,125 | com/stencyl/models/scene/AutotileFormat.hx | package com.stencyl.models.scene;
//import haxe.ds.HashMap;
import openfl.geom.Point;
class AutotileFormat
{
public var autotileArrayLength:Int;
public var defaultAnimationIndex:Int = 0;
public var name:String;
public var id:Int;
public var tilesAcross:Int;
public var tilesDown:Int;
/** Maps full 0-255 autotile flag to its index in an array of animations / CornerSets. */
public var animIndex:Array<Int> = [];
/** Maps animation index to the set of corners needed for that animation. */
public var animCorners:Array<Corners>;
public function new(name:String, id:Int, tilesAcross:Int, tilesDown:Int, corners:Array<Corners>)
{
this.name = name;
this.id = id;
this.tilesAcross = tilesAcross;
this.tilesDown = tilesDown;
var arrayIndex = 0;
//Can't use Haxe's HashMap because it only works with hashCode and not equality.
//HashCode collisions cause this to break.
var cornerIndices = new Map<Corners, Int>();
for(i in 0x00...0xFF + 1)
{
if(cornerIndices.exists(corners[i]))
{
animIndex[i] = cornerIndices.get(corners[i]);
continue;
}
animIndex[i] = arrayIndex;
cornerIndices.set(corners[i], arrayIndex);
++arrayIndex;
}
defaultAnimationIndex = animIndex[0xFF];
autotileArrayLength = arrayIndex;
animCorners = [];
for(i in 0x00...0xFF + 1)
{
animCorners[animIndex[i]] = corners[i];
}
}
}
class Corners
{
public function new(tl:Point, tr:Point, bl:Point, br:Point)
{
this.tl = tl;
this.tr = tr;
this.bl = bl;
this.br = br;
}
public var tl:Point;
public var tr:Point;
public var bl:Point;
public var br:Point;
/*
public function hashCode():Int
{
var result = 7;
result = 17 * result + pointHash(tl);
result = 17 * result + pointHash(tr);
result = 17 * result + pointHash(bl);
result = 17 * result + pointHash(br);
return result;
}
private function pointHash(p:Point):Int
{
var result = 17;
result = 37 * result + Std.int(p.x);
result = 37 * result + Std.int(p.y);
return result;
}
*/
public function toString():String
{
return 'TL: $tl, TR: $tr, BL: $bl, BR: $br';
}
} | 0 | 0.873049 | 1 | 0.873049 | game-dev | MEDIA | 0.751671 | game-dev | 0.874219 | 1 | 0.874219 |
Sduibek/fixtsrc | 20,713 | SCRIPTS/TGUARD.SSL | procedure start; variable SrcObj := 0; variable SrcIsParty := 0;
procedure combat_p_proc;// script_action == 13
procedure critter_p_proc;// script_action == 12
procedure description_p_proc;// script_action == 3
procedure destroy_p_proc;// script_action == 18
procedure look_at_p_proc;// script_action == 21
procedure pickup_p_proc;// script_action == 4
procedure talk_p_proc;// script_action == 11
procedure timed_event_p_proc;// script_action == 22
procedure guard00;
procedure guard01;
procedure guard02;
procedure guard03;
procedure guard04;
procedure guard05;
procedure guard06;
procedure guard06a;
procedure guard07a;
procedure guard07_1;
procedure guard07;
procedure guard08;
procedure guard09;
procedure guard10;
procedure guard11;
procedure guard12;
procedure guard13;
procedure guardend;
procedure set_sleep_tile;
procedure sleeping;
variable night_person;
variable wake_time;
variable sleep_time;
variable home_tile;
variable sleep_tile;
variable hostile;
variable initialized := 0;
variable round_counter;
variable Warned_Tile;
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 items_held;
variable RightHand := 0;
variable LeftHand := 0;
variable PIDright := 0;
variable PIDleft := 0;
variable SubtypeWEP := 0;
procedure PickDeadBodyType;
variable DeathType := 56;
procedure start
begin
if metarule(14, 0) then begin
if tile_num(self_obj) == 18931 then begin
variable KillBox_ptr := 0;
KillBox_ptr := create_object_sid(16777527, 0, 0, -1);// <-- Dead Traveler (Ghoul) Was: create_object_sid(165, 0, 0, -1);// <-- Bob's Iguana Stand. MAX_SIZE = 1000, biggest of all containers. -1 = NO SCRIPT ATTACHED.
move_to(KillBox_ptr, 0, 0);
inven_unwield;
move_obj_inven_to_obj(self_obj, KillBox_ptr);
destroy_object(KillBox_ptr);
move_to(self_obj, 0, 0);
destroy_object(self_obj);
end
end
if global_var(12) then begin
if (cur_map_index == 25) or (cur_map_index == 26) then begin // SHADY SANDS - EAST OR WEST
if (local_var(6) != 1) then begin
set_local_var(6, 1);
call PickDeadBodyType;
kill_critter(self_obj, DeathType);
end
end
end
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 not(initialized) then begin
initialized := 1;
/* TEAM_NUM */ critter_add_trait(self_obj, 1, 6, 2);
/* AI_PACKET */ critter_add_trait(self_obj, 1, 5, 4);
if (local_var(10) == 0) then begin
set_local_var(10, tile_num(self_obj));
end
home_tile := local_var(10);
end
if (script_action == 13) then begin//<-- combat_p_proc , basically does COMBAT_IS_INITIALIZED == 1
call combat_p_proc;
end
else begin
if (script_action == 12) then begin//<-- critter_p_proc - (can also be "Critter_Action") - do they see you, should they wander, should they attack you, etc..
call critter_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.
call destroy_p_proc;
end
else begin
if (script_action == 21) then begin//MOUSE-OVER DESCRIPTION -- look_at_p_proc - (usually brief length. hovered mouse over object, haven't clicked on it.)
call look_at_p_proc;
end
else begin
if (script_action == 4) then begin//<---caught stealing! (pickup_p_proc)
call pickup_p_proc;
end
else begin
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 == 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"
call timed_event_p_proc;
end
end
end
end
end
end
end
end
procedure items_held
begin
SubtypeWEP := 0;
if critter_inven_obj(dude_obj, 1) then begin
RightHand := critter_inven_obj(dude_obj, 1);
PIDright := obj_pid(RightHand);
if obj_item_subtype(RightHand) == 3 then begin
SubtypeWEP := 1;
end
end
else begin
RightHand := 0;
PIDright := 0;
end
if critter_inven_obj(dude_obj, 2) then begin
LeftHand := critter_inven_obj(dude_obj, 2);
PIDleft := obj_pid(LeftHand);
if obj_item_subtype(LeftHand) == 3 then begin
SubtypeWEP := 1;
end
end
else begin
LeftHand := 0;
PIDleft := 0;
end
end
procedure combat_p_proc
begin
if (fixed_param == 4) then begin
round_counter := round_counter + 1;
end
if (round_counter > 3) then begin
if not(global_var(246)) then begin//Shady Sands is NOT hostile to player; i.e. globalvar ENEMY_SHADY_SANDS is not enabled
set_global_var(246, 1);//Set ENEMY_SHADY_SANDS to True
set_global_var(155, global_var(155) - 5);
end
end
end
procedure critter_p_proc
begin
if (obj_can_see_obj(self_obj, dude_obj)) then begin
if global_var(246) then begin// Is Shady Sands hostile to player?
hostile := 1;
end
else begin
call items_held;
if (PIDright != 79) and (PIDright != 205) and (PIDleft != 79) and (PIDleft != 205) and (SubtypeWEP == 1) then begin
if (map_var(0) == 0) then begin
call guard11;
end
end
end
end
if (local_var(7) == 1) then begin
if (tile_distance(tile_num(self_obj), tile_num(dude_obj)) < tile_distance(tile_num(self_obj), Warned_Tile)) then begin
hostile := 1;
end
end
if (hostile) then begin// This must come FIRST as an if/then/else before "attack dude" type code, otherwise it runs too soon and can override other attack calls
hostile := 0;
attack_complex(dude_obj, 0, 1, 0, 0, 30000, 0, 0);
end
end
procedure description_p_proc
begin
script_overrides;
display_msg(message_str(113, 100));
end
procedure destroy_p_proc
begin
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
set_global_var(246, 1);//Set ENEMY_SHADY_SANDS to True
end
if source_obj == dude_obj then begin
set_global_var(159, global_var(159) + 1);// THIS MONSTER WAS A GOOD GUY. INCREASE GoodGuysKilled COUNTER
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
if ((global_var(159) % 2) == 0) then begin
set_global_var(155, (global_var(155) - 1));
end
end
rm_timer_event(self_obj);
end
procedure look_at_p_proc
begin
script_overrides;
display_msg(message_str(113, 100));
end
procedure pickup_p_proc
begin
hostile := 1;
end
procedure talk_p_proc
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
call get_reaction;
if (local_var(9) == 1) then begin
float_msg(self_obj, message_str(185, 166), 0);
end
else begin
if global_var(246) then begin// Is player ENEMY_SHADY_SANDS?
set_local_var(4, 1);
call guard00;
end
else begin
if (global_var(26) == 1) then begin
set_local_var(4, 1);
call guard01;
end
else begin
if ((global_var(26) == 2) and (local_var(8) == 0)) then begin
set_local_var(4, 1);
call guard02;
end
else begin
if (global_var(26) == 3) then begin
set_local_var(4, 1);
call guard03;
end
else begin
if (local_var(4) == 1) then begin
if (local_var(1) < 2) then begin
call guard13;
end
else begin
call guard12;
end
end
else begin
set_local_var(4, 1);
if (local_var(1) < 2) then begin
call guard10;
end
else begin
start_gdialog(113, self_obj, 4, -1, -1);
gsay_start;
call guard04;
gsay_end;
end_dialogue;
end
end
end
end
end
end
end
end
procedure timed_event_p_proc
begin
call items_held;
if (PIDright != 79) and (PIDright != 205) and (PIDleft != 79) and (PIDleft != 205) and (SubtypeWEP == 1) then begin
hostile := 1;
end
else begin
set_map_var(0, 0);
end
end
procedure guard00
begin
float_msg(self_obj, message_str(113, 101), 7);
Warned_Tile := tile_num(dude_obj);
set_local_var(7, 1);
end
procedure guard01
begin
float_msg(self_obj, message_str(113, 102), 8);
end
procedure guard02
begin
float_msg(self_obj, message_str(113, 103), 8);
set_local_var(8, 1);
call TopReact;
end
procedure guard03
begin
float_msg(self_obj, message_str(113, 104), 8);
end
procedure guard04
begin
gsay_reply(113, 105);
giq_option(4, 113, 106, guard05, 50);
giq_option(5, 113, 107, guard07, 50);
giq_option(-3, 113, 108, guard05, 50);
end
procedure guard05
begin
gsay_reply(113, 109);
giq_option(4, 113, 110, guard06, 50);
giq_option(-3, 113, 111, guardend, 50);
end
procedure guard06
begin
gsay_reply(113, 112);
giq_option(4, 113, 114, guard06a, 50);
giq_option(4, 113, 113, guardend, 50);
end
procedure guard07
begin
gsay_reply(113, 115);
gsay_option(113, 126, guard07_1, 50);
end
procedure guard08
begin
gsay_reply(113, 118);
giq_option(4, 113, 120, DownReact, 50);
giq_option(4, 113, 119, guardend, 50);
end
procedure guard09
begin
gsay_reply(113, 121);
call Goodbyes;
giq_option(4, 113, exit_line, guardend, 50);
end
procedure guard10
begin
float_msg(self_obj, message_str(113, 122), 7);
end
procedure guard11
begin
float_msg(self_obj, message_str(113, 123), 7);
add_timer_event(self_obj, game_ticks(10), 1);
set_map_var(0, 1);
end
procedure guard12
begin
float_msg(self_obj, message_str(113, 124), 8);
end
procedure guard13
begin
float_msg(self_obj, message_str(113, 125), 7);
end
procedure guard06a
begin
hostile := 1;
call BottomReact;
end
procedure guard07a
begin
if (is_success(roll_vs_skill(dude_obj, 14, 0))) then begin
call guard09;
end
else begin
call guard08;
end
end
procedure guard07_1
begin
gsay_reply(113, 116);
giq_option(5, 113, 117, guard07a, 50);
end
procedure guardend
begin
end
procedure set_sleep_tile
begin
if (home_tile == 15283) then begin
sleep_tile := 14685;
end
else begin
if (home_tile == 15886) then begin
sleep_tile := 14479;
end
else begin
if (home_tile == 15881) then begin
sleep_tile := 15479;
end
end
end
wake_time := random(610, 650);
sleep_time := random(2110, 2150);
end
procedure sleeping
begin
if (local_var(9) == 1) then begin
if (not(night_person) and (game_time_hour >= wake_time) and (game_time_hour < sleep_time) or (night_person and ((game_time_hour >= wake_time) or (game_time_hour < sleep_time)))) then begin
if (((game_time_hour - wake_time) < 10) and ((game_time_hour - wake_time) > 0)) then begin
if (tile_num(self_obj) != home_tile) then begin
animate_move_obj_to_tile(self_obj, home_tile, 0);
end
else begin
set_local_var(9, 0);
end
end
else begin
move_to(self_obj, home_tile, elevation(self_obj));
if (tile_num(self_obj) == home_tile) then begin
set_local_var(9, 0);
end
end
end
end
else begin
if (night_person and (game_time_hour >= sleep_time) and (game_time_hour < wake_time) or (not(night_person) and ((game_time_hour >= sleep_time) or (game_time_hour < wake_time)))) then begin
if (((game_time_hour - sleep_time) < 10) and ((game_time_hour - sleep_time) > 0)) then begin
if (tile_num(self_obj) != sleep_tile) then begin
animate_move_obj_to_tile(self_obj, self_obj, 0);
end
else begin
set_local_var(9, 1);
end
end
else begin
if (tile_num(self_obj) != sleep_tile) then begin
move_to(self_obj, sleep_tile, elevation(self_obj));
end
else begin
set_local_var(9, 1);
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
procedure PickDeadBodyType
begin
variable LVar0 := 0;
LVar0 := (random(0, 6) + random(0, 6) + random(0, 6));
//
if (LVar0 <= 5) then begin// 31.5%
DeathType := 57;// burnt, face down [FLAMER]
end
else begin
if (LVar0 <= 10) then begin// 26%
DeathType := 56;// cut in half [LASER RIFLE, GATLING LASER]
end
else begin
if (LVar0 <= 14) then begin// 21%
DeathType := 53;// head & arm gone - full auto [MINIGUN]
end
else begin
if (LVar0 <= 16) then begin// 10.5%
DeathType := 63;// face down, blood pool (generic death, no weapon associated)
end
else begin// <-------------------- 16%
variable LVar1 := 0;
LVar1 := random(0, 2);
if (LVar1 == 0) then begin
DeathType := 54;// bullet holes - full auto partial hit
end
else begin
if (LVar1 == 1) then begin
DeathType := 59;// exploded [ROCKET LAUNCHER]
end
else begin
if (LVar1 == 2) then begin
DeathType := 60;// melted pile [PLASMA RIFLE]
end
end
end
end
end
end
end
end
| 0 | 0.896686 | 1 | 0.896686 | game-dev | MEDIA | 0.970529 | game-dev | 0.92642 | 1 | 0.92642 |
gdt050579/AppCUI-rs | 15,896 | examples/games/pacman/pacman_game.rs | use appcui::prelude::*;
use rand::Rng;
use std::time::Duration;
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum GameState {
Playing,
Paused,
GameOver,
Victory,
}
#[derive(Copy, Clone, PartialEq, Eq)]
enum Direction {
Up,
Down,
Left,
Right,
}
#[derive(Copy, Clone, PartialEq, Eq)]
enum CellType {
Wall(char),
Food,
Cherry,
Empty,
}
impl CellType {
#[inline(always)]
fn is_wall(&self) -> bool {
matches!(self, CellType::Wall(_))
}
}
struct Ghost {
position: Point,
direction: Direction,
}
impl Ghost {
fn new(x: i32, y: i32) -> Self {
Self {
position: Point::new(x, y),
direction: Direction::Up,
}
}
}
const BOARD_WIDTH: usize = 55;
const BOARD_HEIGHT: usize = 22;
static MAZE_PATTERN: &[&str; BOARD_HEIGHT] = &[
"┌────────────┬┬────────────┐",
"│..c.........││............│",
"│.┌──┐.┌───┐.└┘.┌───┐.┌──┐.│",
"│.│ │.│ │....│ │.│ │.│",
"│.└──┘.└───┘.┌┐.└───┘.└──┘.│",
"│............││.c..........│",
"│.┌──┐.┌─────┘└─────┐.┌──┐.│",
"│.└──┘.└────────────┘.└──┘.│",
"│..........................│",
"├──┐.┌───┐.┌ G ┐.┌───┐.┌──┤",
"├──┘.└───┘.│G G│.└───┘.└──┤",
"│..........└────┘..........│",
"│.┌──┐.┌─┐ P ┌─┐.┌──┐.│",
"│.└──┘.└─┘.┌────┐.└─┘.└──┘.│",
"│..c.......│ │..........│",
"│.┌──┐.┌───┘ └───┐.┌──┐.│",
"│.└──┘.└────────────┘.└──┘.│",
"│.......................c..│",
"├──┐.┌───┐.┌────┐.┌───┐.┌──┤",
"├──┘.└───┘.└────┘.└───┘.└──┤",
"│..........................│",
"└──────────────────────────┘",
];
#[CustomControl(overwrite = OnPaint+OnKeyPressed, events = TimerEvents)]
pub struct PacmanGame {
board: [[CellType; BOARD_WIDTH]; BOARD_HEIGHT],
pacman_pos: Point,
pacman_direction: Direction,
ghosts: Vec<Ghost>,
state: GameState,
score: u32,
high_score: u32,
food_count: u32,
total_food: u32,
}
impl PacmanGame {
pub fn new() -> Self {
let mut game = Self {
base: ControlBase::new(layout!("d:f"), true),
board: [[CellType::Empty; BOARD_WIDTH]; BOARD_HEIGHT],
pacman_pos: Point::ORIGIN,
pacman_direction: Direction::Right,
ghosts: Vec::new(),
state: GameState::Playing,
score: 0,
high_score: 0,
food_count: 0,
total_food: 0,
};
if let Some(timer) = game.timer() {
timer.start(Duration::from_millis(250));
}
game.create_board();
game
}
fn create_board(&mut self) {
self.food_count = 0;
self.ghosts.clear();
for (y, row) in MAZE_PATTERN.iter().enumerate() {
if y >= BOARD_HEIGHT {
break;
}
for (x, ch) in row.chars().enumerate() {
if x >= BOARD_WIDTH {
break;
}
let cell_type = match ch {
'┌' | '┐' | '└' | '┘' | '├' | '┤' | '┬' | '┴' | '┼' | '─' | '│' => CellType::Wall(ch),
'.' => CellType::Food,
'c' => CellType::Cherry,
'G' => {
self.ghosts.push(Ghost::new(x as i32, y as i32));
CellType::Empty
}
'P' => {
self.pacman_pos = Point::new(x as i32, y as i32);
CellType::Empty
}
_ => CellType::Empty,
};
self.board[y][x] = cell_type;
if cell_type == CellType::Food {
self.food_count += 1;
}
}
}
self.total_food = self.food_count;
}
pub fn start_game(&mut self) {
self.state = GameState::Playing;
self.score = 0;
if self.board[self.pacman_pos.y as usize][self.pacman_pos.x as usize].is_wall() {
for y in 1..BOARD_HEIGHT - 1 {
for x in 1..BOARD_WIDTH - 1 {
if !self.board[y][x].is_wall() {
self.pacman_pos = Point::new(x as i32, y as i32);
return;
}
}
}
}
}
fn move_pacman(&mut self) {
if self.state != GameState::Playing {
return;
}
let (dx, dy) = match self.pacman_direction {
Direction::Up => (0, -1),
Direction::Down => (0, 1),
Direction::Left => (-1, 0),
Direction::Right => (1, 0),
};
let new_x = self.pacman_pos.x + dx;
let new_y = self.pacman_pos.y + dy;
if new_x >= 0
&& new_y >= 0
&& new_x < BOARD_WIDTH as i32
&& new_y < BOARD_HEIGHT as i32
&& !self.board[new_y as usize][new_x as usize].is_wall()
{
match self.board[new_y as usize][new_x as usize] {
CellType::Food => {
self.score += 10;
self.food_count -= 1;
self.board[new_y as usize][new_x as usize] = CellType::Empty;
if self.food_count == 0 {
self.state = GameState::Victory;
if self.score > self.high_score {
self.high_score = self.score;
}
}
}
CellType::Cherry => {
self.score += 50;
self.board[new_y as usize][new_x as usize] = CellType::Empty;
}
_ => {}
}
self.pacman_pos = Point::new(new_x, new_y);
for ghost in &self.ghosts {
if ghost.position == self.pacman_pos {
self.state = GameState::GameOver;
if self.score > self.high_score {
self.high_score = self.score;
}
return;
}
}
}
}
fn move_ghosts(&mut self) {
if self.state != GameState::Playing {
return;
}
let directions = [Direction::Up, Direction::Down, Direction::Left, Direction::Right];
let mut rng = rand::thread_rng();
let mut possible_moves = Vec::with_capacity(4);
for ghost in &mut self.ghosts {
possible_moves.clear();
for &dir in &directions {
let (dx, dy) = match dir {
Direction::Up => (0, -1),
Direction::Down => (0, 1),
Direction::Left => (-1, 0),
Direction::Right => (1, 0),
};
let new_x = ghost.position.x + dx;
let new_y = ghost.position.y + dy;
if new_x >= 0
&& new_y >= 0
&& new_x < BOARD_WIDTH as i32
&& new_y < BOARD_HEIGHT as i32
&& !self.board[new_y as usize][new_x as usize].is_wall()
{
possible_moves.push((new_x, new_y, dir));
}
}
if !possible_moves.is_empty() {
let target_move = if rng.gen_bool(0.7) {
let mut best_move = possible_moves[0];
let mut best_distance = (best_move.0 - self.pacman_pos.x).abs() + (best_move.1 - self.pacman_pos.y).abs();
for &(x, y, dir) in &possible_moves {
let distance = (x - self.pacman_pos.x).abs() + (y - self.pacman_pos.y).abs();
if distance < best_distance {
best_distance = distance;
best_move = (x, y, dir);
}
}
best_move
} else {
possible_moves[rng.gen_range(0..possible_moves.len())]
};
ghost.position = Point::new(target_move.0, target_move.1);
ghost.direction = target_move.2;
if ghost.position == self.pacman_pos {
self.state = GameState::GameOver;
if self.score > self.high_score {
self.high_score = self.score;
}
return;
}
}
}
}
fn can_move_in_direction(&self, direction: Direction) -> bool {
let (dx, dy) = match direction {
Direction::Up => (0, -1),
Direction::Down => (0, 1),
Direction::Left => (-1, 0),
Direction::Right => (1, 0),
};
let new_x = self.pacman_pos.x + dx;
let new_y = self.pacman_pos.y + dy;
if new_x < 0 || new_y < 0 || new_x >= BOARD_WIDTH as i32 || new_y >= BOARD_HEIGHT as i32 {
return false;
}
!self.board[new_y as usize][new_x as usize].is_wall()
}
fn paint_board(&self, surface: &mut Surface) {
let r = Rect::with_size(0, 2, (BOARD_WIDTH * 2) as u16, BOARD_HEIGHT as u16);
surface.fill_rect(r, char!("' ',black,black"));
let cherry = Character::with_attributes('🍒', CharAttribute::with_color(Color::Red, Color::Black));
let food = Character::with_attributes('·', CharAttribute::with_color(Color::Gray, Color::Black));
let line = Character::with_attributes(SpecialChar::BoxHorizontalSingleLine, charattr!("blue,black"));
for y in 0..BOARD_HEIGHT {
for x in 0..BOARD_WIDTH {
let screen_x = x as i32 * 2;
let screen_y = y as i32 + 2;
match self.board[y][x] {
CellType::Wall(ch) => {
let c = Character::with_attributes(ch, CharAttribute::with_color(Color::Blue, Color::Black));
surface.write_char(screen_x, screen_y, c);
if ch == '─' || ch == '┌' || ch == '└' || ch == '├' || ch == '┬' {
surface.write_char(screen_x + 1, screen_y, line);
}
}
CellType::Food => surface.write_char(screen_x, screen_y, food),
CellType::Cherry => surface.write_char(screen_x, screen_y, cherry),
CellType::Empty => {} //Character::with_attributes(' ', charattr!("black,black")),
};
}
}
surface.write_char(
self.pacman_pos.x * 2,
self.pacman_pos.y + 2,
Character::with_attributes('⚫', CharAttribute::with_color(Color::Yellow, Color::Black)),
);
for ghost in &self.ghosts {
surface.write_char(
ghost.position.x * 2,
ghost.position.y + 2,
Character::with_attributes('👻', CharAttribute::with_color(Color::Aqua, Color::Black)),
);
}
}
fn paint_final_message(&self, surface: &mut Surface, message: &str, back_color: Color) {
const X: i32 = 8;
const Y: i32 = 7;
const W: i32 = 40;
let r = Rect::with_size(X, Y, W as u16, 6);
surface.fill_rect(r, Character::new(' ', Color::White, back_color, CharFlags::None));
surface.write_string(X + W / 2 - (message.len() / 2) as i32, Y, message, charattr!("white"), false);
surface.draw_horizontal_line_with_size(X + 1, Y + 1, (W - 2) as u32, LineType::Single, charattr!("gray"));
surface.write_string(X + 1, Y + 2, "Score", charattr!("silver"), false);
surface.write_string(X + W - 4, Y + 2, format!("{:3}", self.score).as_str(), charattr!("yellow"), false);
surface.write_string(X + 1, Y + 3, "High score", charattr!("silver"), false);
surface.write_string(X + W - 4, Y + 2, format!("{:3}", self.high_score).as_str(), charattr!("yellow"), false);
surface.draw_horizontal_line_with_size(X + 1, Y + 4, (W - 2) as u32, LineType::Single, charattr!("gray"));
surface.write_string(X + 6, Y + 5, "Press SPACE to start again !", charattr!("white"), false);
surface.write_string(X + 12, Y + 5, "SPACE", charattr!("yellow, flags: underline+bold"), false);
}
}
impl OnPaint for PacmanGame {
fn on_paint(&self, surface: &mut Surface, theme: &Theme) {
surface.clear(char!("' ',black,black"));
self.paint_board(surface);
match self.state {
GameState::GameOver => {
surface.clear(Character::with_color(Color::Gray, Color::Black));
self.paint_final_message(surface, "Game Over!", Color::DarkRed);
}
GameState::Victory => {
surface.clear(Character::with_color(Color::Gray, Color::Black));
self.paint_final_message(surface, "Victory !", Color::DarkGreen);
}
GameState::Playing | GameState::Paused => {
surface.write_string(0, 0, format!("Score: {}", self.score).as_str(), theme.symbol.checked, false);
surface.write_string(15, 0, format!("High Score: {}", self.high_score).as_str(), theme.symbol.checked, false);
surface.write_string(35, 0, format!("Food Left: {}", self.food_count).as_str(), theme.symbol.checked, false);
if self.state == GameState::Paused {
surface.clear(Character::with_color(Color::Gray, Color::Black));
surface.write_string(15, 11, "PAUSED - Press P to resume", charattr!("white,black"), false);
}
}
}
}
}
impl TimerEvents for PacmanGame {
fn on_update(&mut self, _: u64) -> EventProcessStatus {
if self.state == GameState::Playing {
self.move_pacman();
self.move_ghosts();
}
EventProcessStatus::Processed
}
}
impl OnKeyPressed for PacmanGame {
fn on_key_pressed(&mut self, key: Key, _character: char) -> EventProcessStatus {
match key.value() {
key!("Up") => {
if self.can_move_in_direction(Direction::Up) {
self.pacman_direction = Direction::Up;
}
EventProcessStatus::Processed
}
key!("Down") => {
if self.can_move_in_direction(Direction::Down) {
self.pacman_direction = Direction::Down;
}
EventProcessStatus::Processed
}
key!("Left") => {
if self.can_move_in_direction(Direction::Left) {
self.pacman_direction = Direction::Left;
}
EventProcessStatus::Processed
}
key!("Right") => {
if self.can_move_in_direction(Direction::Right) {
self.pacman_direction = Direction::Right;
}
EventProcessStatus::Processed
}
key!("Space") => {
match self.state {
GameState::GameOver => {
self.create_board();
self.start_game();
}
GameState::Victory => {
self.create_board();
self.start_game();
}
_ => {}
}
EventProcessStatus::Processed
}
key!("P") => {
if self.state == GameState::Playing {
self.state = GameState::Paused;
} else if self.state == GameState::Paused {
self.state = GameState::Playing;
}
EventProcessStatus::Processed
}
_ => EventProcessStatus::Ignored,
}
}
}
| 0 | 0.854183 | 1 | 0.854183 | game-dev | MEDIA | 0.85663 | game-dev | 0.986876 | 1 | 0.986876 |
Nenkai/PDTools | 3,897 | PDTools.Files/Sound/Jam/JamProgChunk.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Syroot.BinaryData;
namespace PDTools.Files.Sound.Jam;
// Game code refers to this as "JamSplitChunk"
// JAM original documents refer to this as "SplitBlock"
public class JamProgChunk
{
// 0xFF = has ALL notes provided for a certain range
// notes in ranges can still be empty
public byte CountOrFlag { get; set; }
public byte Volume { get; set; }
public byte field_0x02 { get; set; }
public byte field_0x03 { get; set; }
public byte field_0x04 { get; set; }
public byte capacityMaybe { get; set; }
public byte FullRangeMin { get; set; }
public byte FullRangeMax { get; set; }
public List<JamSplitChunk> SplitChunks { get; set; } = [];
public void Read(BinaryStream bs)
{
CountOrFlag = bs.Read1Byte();
Volume = bs.Read1Byte();
field_0x02 = bs.Read1Byte();
field_0x03 = bs.Read1Byte();
field_0x04 = bs.Read1Byte();
capacityMaybe = bs.Read1Byte();
FullRangeMin = bs.Read1Byte();
FullRangeMax = bs.Read1Byte();
if (CountOrFlag == 0xFF)
{
int cnt = (FullRangeMax - FullRangeMin) + 1;
for (int i = 0; i < cnt; i++)
{
var splitChunk = new JamSplitChunk();
splitChunk.Read(bs);
SplitChunks.Add(splitChunk);
}
}
else
{
int cnt = (CountOrFlag & 0x0F) + 1;
for (int i = 0; i < cnt; i++)
{
var splitChunk = new JamSplitChunk();
splitChunk.Read(bs);
SplitChunks.Add(splitChunk);
}
}
}
}
public class JamSplitChunk
{
public byte NoteMin { get; set; }
public byte NoteMax { get; set; }
public byte BaseNoteMaybe { get; set; }
public byte field_0x03 { get; set; }
/* ?? = 0x01
* SetNoiseShiftFrequency = 0x02, // SE only
PitchModulateSpeedAndDepth = 0x20,
??? = 0x40
Reverb = 0x80,
possibly more unknown
*/
public byte Flags { get; set; }
/// <summary>
/// Multiply by 0x10 for sample data offset starting from bd offset
/// </summary>
public uint SsaOffset { get; set; }
public short field_0x08 { get; set; }
public short field_0x0A { get; set; }
public short field_0x0C { get; set; }
public byte field_0x0E { get; set; }
/// <summary>
/// 0x7F = no lfo in use
/// </summary>
public byte LfoTableIndex { get; set; }
public void Read(BinaryStream bs)
{
NoteMin = bs.Read1Byte();
NoteMax = bs.Read1Byte();
BaseNoteMaybe = bs.Read1Byte();
field_0x03 = bs.Read1Byte();
Flags = bs.Read1Byte();
SsaOffset = (uint)((bs.Read1Byte() << 16) | bs.ReadUInt16()); // Game code refers to the offset to audio as Ssa
field_0x08 = bs.ReadInt16();
field_0x0A = bs.ReadInt16();
field_0x0C = bs.ReadInt16();
field_0x0E = bs.Read1Byte();
LfoTableIndex = bs.Read1Byte();
}
public byte[] GetData(BinaryStream bs)
{
// Size of vag is not provided, we must find it using vag flags
long basePos = bs.Position;
long absoluteSsaOffset = basePos + (SsaOffset * 0x10);
bs.Position = absoluteSsaOffset;
int sampleIndex = 1;
while (bs.Position < bs.Length)
{
byte decodingCoef = bs.Read1Byte();
byte flag = bs.Read1Byte();
if (flag == 1 || flag == 3)
break;
sampleIndex++;
bs.Position += 0x0E;
}
bs.Position = absoluteSsaOffset;
return bs.ReadBytes(0x10 * sampleIndex);
}
public override string ToString()
{
return $"{NoteMin}->{NoteMax}";
}
}
| 0 | 0.818326 | 1 | 0.818326 | game-dev | MEDIA | 0.70942 | game-dev,audio-video-media | 0.794419 | 1 | 0.794419 |
AztechMC/Modern-Industrialization | 3,759 | src/main/java/aztech/modern_industrialization/thirdparty/fabrictransfer/impl/fluid/FluidVariantImpl.java | /*
* MIT License
*
* Copyright (c) 2020 Azercoco & Technici4n
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package aztech.modern_industrialization.thirdparty.fabrictransfer.impl.fluid;
import aztech.modern_industrialization.thirdparty.fabrictransfer.api.fluid.FluidVariant;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import net.minecraft.core.component.DataComponentPatch;
import net.minecraft.world.level.material.Fluid;
import net.neoforged.neoforge.fluids.FluidStack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FluidVariantImpl implements FluidVariant {
private static final Map<Fluid, FluidVariant> noTagCache = new ConcurrentHashMap<>();
public static FluidVariant of(Fluid fluid) {
Objects.requireNonNull(fluid, "Fluid may not be null.");
return noTagCache.computeIfAbsent(fluid, f -> new FluidVariantImpl(new FluidStack(f, 1)));
}
public static FluidVariant of(FluidStack stack) {
Objects.requireNonNull(stack);
if (stack.isComponentsPatchEmpty() || stack.isEmpty()) {
return of(stack.getFluid());
} else {
return new FluidVariantImpl(stack);
}
}
private static final Logger LOGGER = LoggerFactory.getLogger("fabric-transfer-api-v1/fluid");
private final FluidStack stack;
private final int hashCode;
public FluidVariantImpl(FluidStack stack) {
this.stack = stack.copyWithAmount(1); // defensive copy
this.hashCode = FluidStack.hashFluidAndComponents(stack);
}
@Override
public Fluid getObject() {
return this.stack.getFluid();
}
@Override
public DataComponentPatch getComponentsPatch() {
return this.stack.getComponentsPatch();
}
@Override
public boolean matches(FluidStack stack) {
return FluidStack.isSameFluidSameComponents(this.stack, stack);
}
@Override
public FluidStack toStack(int count) {
return this.stack.copyWithAmount(count);
}
@Override
public boolean isBlank() {
return this.stack.isEmpty();
}
@Override
public String toString() {
return "FluidVariant{stack=" + stack + '}';
}
@Override
public boolean equals(Object o) {
// succeed fast with == check
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
FluidVariantImpl fluidVariant = (FluidVariantImpl) o;
// fail fast with hash code
return hashCode == fluidVariant.hashCode && matches(fluidVariant.stack);
}
@Override
public int hashCode() {
return hashCode;
}
}
| 0 | 0.855689 | 1 | 0.855689 | game-dev | MEDIA | 0.437594 | game-dev | 0.848281 | 1 | 0.848281 |
756915370/LuaRuntimeHotfix | 1,357 | Tolua_RuntimeHotfix/Assets/ToLua/BaseType/System_Collections_Generic_KeyValuePairWrap.cs | using System;
using LuaInterface;
using System.Collections.Generic;
public class System_Collections_Generic_KeyValuePairWrap
{
public static void Register(LuaState L)
{
L.BeginClass(typeof(KeyValuePair<,>), null, "KeyValuePair");
L.RegFunction("__tostring", ToLua.op_ToString);
L.RegVar("Key", get_Key, null);
L.RegVar("Value", get_Value, null);
L.EndClass();
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_Key(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
object ret = LuaMethodCache.CallSingleMethod("get_Key", o);
ToLua.Push(L, ret);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index Key on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_Value(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
object ret = LuaMethodCache.CallSingleMethod("get_Value", o);
ToLua.Push(L, ret);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index Value on a nil value");
}
}
}
| 0 | 0.738964 | 1 | 0.738964 | game-dev | MEDIA | 0.801834 | game-dev | 0.6661 | 1 | 0.6661 |
Gaby-Station/Gaby-Station | 2,324 | Content.Client/Placement/Modes/WallmountLight.cs | // SPDX-FileCopyrightText: 2021 Acruid <shatter66@gmail.com>
// SPDX-FileCopyrightText: 2021 Alex Evgrashin <aevgrashin@yandex.ru>
// SPDX-FileCopyrightText: 2021 DrSmugleaf <DrSmugleaf@users.noreply.github.com>
// SPDX-FileCopyrightText: 2022 mirrorcult <lunarautomaton6@gmail.com>
// SPDX-FileCopyrightText: 2023 metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Piras314 <p1r4s@proton.me>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using System.Numerics;
using Robust.Client.Placement;
using Robust.Shared.Map;
namespace Content.Client.Placement.Modes
{
public sealed class WallmountLight : PlacementMode
{
public WallmountLight(PlacementManager pMan) : base(pMan)
{
}
public override void AlignPlacementMode(ScreenCoordinates mouseScreen)
{
MouseCoords = ScreenToCursorGrid(mouseScreen);
CurrentTile = GetTileRef(MouseCoords);
if (pManager.CurrentPermission!.IsTile)
{
return;
}
var tileCoordinates = new EntityCoordinates(MouseCoords.EntityId, CurrentTile.GridIndices);
Vector2 offset;
switch (pManager.Direction)
{
case Direction.North:
offset = new Vector2(0.5f, 1f);
break;
case Direction.South:
offset = new Vector2(0.5f, 0f);
break;
case Direction.East:
offset = new Vector2(1f, 0.5f);
break;
case Direction.West:
offset = new Vector2(0f, 0.5f);
break;
default:
return;
}
tileCoordinates = tileCoordinates.Offset(offset);
MouseCoords = tileCoordinates;
}
public override bool IsValidPosition(EntityCoordinates position)
{
if (pManager.CurrentPermission!.IsTile)
{
return false;
}
else if (!RangeCheck(position))
{
return false;
}
return true;
}
}
} | 0 | 0.965147 | 1 | 0.965147 | game-dev | MEDIA | 0.689662 | game-dev | 0.984531 | 1 | 0.984531 |
axmolengine/axmol | 27,292 | extensions/scripting/lua-bindings/manual/physics3d/axlua_physics3d_manual.cpp | /****************************************************************************
Copyright (c) 2014-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
Copyright (c) 2019-present Axmol Engine contributors (see AUTHORS.md).
https://axmol.dev/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "axmol/platform/PlatformConfig.h"
#include "axmol/base/Config.h"
#if defined(AX_ENABLE_3D_PHYSICS)
# include "lua-bindings/manual/physics3d/axlua_physics3d_manual.h"
# include "lua-bindings/auto/axlua_physics3d_auto.hpp"
# include "lua-bindings/manual/tolua_fix.h"
# include "lua-bindings/manual/LuaBasicConversions.h"
# include "lua-bindings/manual/LuaEngine.h"
# include "axmol/physics3d/Physics3D.h"
bool luaval_to_Physics3DRigidBodyDes(lua_State* L, int lo, ax::Physics3DRigidBodyDes* outValue, const char* funcName)
{
if (nullptr == L || nullptr == outValue)
return false;
bool ok = true;
tolua_Error tolua_err;
if (!tolua_istable(L, lo, 0, &tolua_err))
{
# if _AX_DEBUG >= 1
luaval_to_native_err(L, "#ferror:", &tolua_err, funcName);
# endif
ok = false;
}
if (ok)
{
lua_pushstring(L, "mass");
lua_gettable(L, lo);
outValue->mass = lua_isnil(L, -1) ? 0.0f : (float)lua_tonumber(L, -1);
lua_pop(L, 1);
lua_pushstring(L, "localInertia");
lua_gettable(L, lo);
if (!lua_istable(L, -1))
{
outValue->localInertia = ax::Vec3(0.0, 0.0, 0.0);
}
else
{
luaval_to_vec3(L, lua_gettop(L), &outValue->localInertia);
}
lua_pop(L, 1);
lua_pushstring(L, "shape");
lua_gettable(L, lo);
if (!tolua_isusertype(L, -1, "ax.Physics3DShape", 0, &tolua_err))
{
outValue->shape = nullptr;
}
else
{
outValue->shape = static_cast<ax::Physics3DShape*>(tolua_tousertype(L, lua_gettop(L), nullptr));
}
lua_pop(L, 1);
lua_pushstring(L, "originalTransform");
lua_gettable(L, lo);
if (!lua_istable(L, -1))
{
outValue->originalTransform = ax::Mat4();
}
else
{
luaval_to_mat4(L, lua_gettop(L), &outValue->originalTransform);
}
lua_pop(L, 1);
lua_pushstring(L, "disableSleep");
lua_gettable(L, lo);
outValue->disableSleep = lua_isnil(L, -1) ? false : lua_toboolean(L, -1);
lua_pop(L, 1);
}
return ok;
}
bool luaval_to_Physics3DWorld_HitResult(lua_State* L,
int lo,
ax::Physics3DWorld::HitResult* outValue,
const char* funcName)
{
if (nullptr == L || nullptr == outValue)
return false;
bool ok = true;
tolua_Error tolua_err;
if (!tolua_istable(L, lo, 0, &tolua_err))
{
# if _AX_DEBUG >= 1
luaval_to_native_err(L, "#ferror:", &tolua_err, funcName);
# endif
ok = false;
}
if (ok)
{
lua_pushstring(L, "hitPosition");
lua_gettable(L, lo);
if (!lua_istable(L, -1))
{
outValue->hitPosition = ax::Vec3();
}
else
{
luaval_to_vec3(L, lua_gettop(L), &(outValue->hitPosition));
}
lua_pop(L, 1);
lua_pushstring(L, "hitNormal");
lua_gettable(L, lo);
if (!lua_istable(L, -1))
{
outValue->hitNormal = ax::Vec3();
}
else
{
luaval_to_vec3(L, lua_gettop(L), &(outValue->hitNormal));
}
lua_pop(L, 1);
lua_pushstring(L, "hitObj");
lua_gettable(L, lo);
if (!tolua_isusertype(L, -1, "ax.Physics3DObject", 0, &tolua_err))
{
outValue->hitObj = nullptr;
}
else
{
outValue->hitObj = static_cast<ax::Physics3DObject*>(tolua_tousertype(L, lua_gettop(L), nullptr));
}
lua_pop(L, 1);
}
return true;
}
void Physics3DWorld_HitResult_to_luaval(lua_State* L, const ax::Physics3DWorld::HitResult& hitResult)
{
if (nullptr == L)
return;
lua_newtable(L);
lua_pushstring(L, "hitPosition");
vec3_to_luaval(L, hitResult.hitPosition);
lua_rawset(L, -3);
lua_pushstring(L, "hitNormal");
vec3_to_luaval(L, hitResult.hitNormal);
lua_rawset(L, -3);
lua_pushstring(L, "hitObj");
if (nullptr == hitResult.hitObj)
{
lua_pushnil(L);
}
else
{
object_to_luaval<ax::Physics3DObject>(L, "ax.Physics3DObject", hitResult.hitObj);
}
lua_rawset(L, -3);
}
int axlua_physics3d_PhysicsMeshRenderer_create(lua_State* L)
{
int argc = 0;
bool ok = true;
# if _AX_DEBUG >= 1
tolua_Error tolua_err;
# endif
# if _AX_DEBUG >= 1
if (!tolua_isusertable(L, 1, "ax.PhysicsMeshRenderer", 0, &tolua_err))
goto tolua_lerror;
# endif
argc = lua_gettop(L) - 1;
if (argc == 2)
{
std::string arg0;
ax::Physics3DRigidBodyDes arg1;
ok &= luaval_to_std_string(L, 2, &arg0, "ax.PhysicsMeshRenderer:create");
ok &= luaval_to_Physics3DRigidBodyDes(L, 3, &arg1, "ax.PhysicsMeshRenderer:create");
if (!ok)
{
tolua_error(L, "invalid arguments in function 'axlua_physics3d_PhysicsMeshRenderer_create'", nullptr);
return 0;
}
ax::PhysicsMeshRenderer* ret = ax::PhysicsMeshRenderer::create(arg0, &arg1);
object_to_luaval<ax::PhysicsMeshRenderer>(L, "ax.PhysicsMeshRenderer", (ax::PhysicsMeshRenderer*)ret);
return 1;
}
if (argc == 3)
{
std::string arg0;
ax::Physics3DRigidBodyDes arg1;
ax::Vec3 arg2;
ok &= luaval_to_std_string(L, 2, &arg0, "ax.PhysicsMeshRenderer:create");
ok &= luaval_to_Physics3DRigidBodyDes(L, 3, &arg1, "ax.PhysicsMeshRenderer:create");
ok &= luaval_to_vec3(L, 4, &arg2, "ax.PhysicsMeshRenderer:create");
if (!ok)
{
tolua_error(L, "invalid arguments in function 'axlua_physics3d_PhysicsMeshRenderer_create'", nullptr);
return 0;
}
ax::PhysicsMeshRenderer* ret = ax::PhysicsMeshRenderer::create(arg0, &arg1, arg2);
object_to_luaval<ax::PhysicsMeshRenderer>(L, "ax.PhysicsMeshRenderer", (ax::PhysicsMeshRenderer*)ret);
return 1;
}
if (argc == 4)
{
std::string arg0;
ax::Physics3DRigidBodyDes arg1;
ax::Vec3 arg2;
ax::Quaternion arg3;
ok &= luaval_to_std_string(L, 2, &arg0, "ax.PhysicsMeshRenderer:create");
ok &= luaval_to_Physics3DRigidBodyDes(L, 3, &arg1, "ax.PhysicsMeshRenderer:create");
ok &= luaval_to_vec3(L, 4, &arg2, "ax.PhysicsMeshRenderer:create");
ok &= luaval_to_quaternion(L, 5, &arg3);
if (!ok)
{
tolua_error(L, "invalid arguments in function 'axlua_physics3d_PhysicsMeshRenderer_create'", nullptr);
return 0;
}
ax::PhysicsMeshRenderer* ret = ax::PhysicsMeshRenderer::create(arg0, &arg1, arg2, arg3);
object_to_luaval<ax::PhysicsMeshRenderer>(L, "ax.PhysicsMeshRenderer", (ax::PhysicsMeshRenderer*)ret);
return 1;
}
luaL_error(L, "%s has wrong number of arguments: %d, was expecting %d\n ", "ax.PhysicsMeshRenderer:create", argc,
2);
return 0;
# if _AX_DEBUG >= 1
tolua_lerror:
tolua_error(L, "#ferror in function 'axlua_physics3d_PhysicsMeshRenderer_create'.", &tolua_err);
# endif
return 0;
}
void extendPhysicsMeshRenderer(lua_State* L)
{
lua_pushstring(L, "ax.PhysicsMeshRenderer");
lua_rawget(L, LUA_REGISTRYINDEX);
if (lua_istable(L, -1))
{
tolua_function(L, "create", axlua_physics3d_PhysicsMeshRenderer_create);
}
lua_pop(L, 1);
}
int axlua_physics3d_Physics3DRigidBody_create(lua_State* L)
{
int argc = 0;
bool ok = true;
# if _AX_DEBUG >= 1
tolua_Error tolua_err;
# endif
# if _AX_DEBUG >= 1
if (!tolua_isusertable(L, 1, "ax.Physics3DRigidBody", 0, &tolua_err))
goto tolua_lerror;
# endif
argc = lua_gettop(L) - 1;
if (argc == 1)
{
ax::Physics3DRigidBodyDes arg0;
ok &= luaval_to_Physics3DRigidBodyDes(L, 2, &arg0, "ax.Physics3DRigidBody:create");
if (!ok)
{
tolua_error(L, "invalid arguments in function 'axlua_physics3d_Physics3DRigidBody_create'", nullptr);
return 0;
}
ax::Physics3DRigidBody* ret = ax::Physics3DRigidBody::create(&arg0);
object_to_luaval<ax::Physics3DRigidBody>(L, "ax.Physics3DRigidBody", (ax::Physics3DRigidBody*)ret);
return 1;
}
luaL_error(L, "%s has wrong number of arguments: %d, was expecting %d\n ", "ax.Physics3DRigidBody:create", argc, 1);
return 0;
# if _AX_DEBUG >= 1
tolua_lerror:
tolua_error(L, "#ferror in function 'axlua_physics3d_Physics3DRigidBody_create'.", &tolua_err);
# endif
return 0;
}
void extendPhysics3DRigidBody(lua_State* L)
{
lua_pushstring(L, "ax.Physics3DRigidBody");
lua_rawget(L, LUA_REGISTRYINDEX);
if (lua_istable(L, -1))
{
tolua_function(L, "create", axlua_physics3d_Physics3DRigidBody_create);
}
lua_pop(L, 1);
}
int axlua_physics3d_Physics3DComponent_create(lua_State* L)
{
int argc = 0;
bool ok = true;
# if _AX_DEBUG >= 1
tolua_Error tolua_err;
# endif
# if _AX_DEBUG >= 1
if (!tolua_isusertable(L, 1, "ax.Physics3DComponent", 0, &tolua_err))
goto tolua_lerror;
# endif
argc = lua_gettop(L) - 1;
do
{
if (argc == 1)
{
ax::Physics3DObject* arg0;
ok &= luaval_to_object<ax::Physics3DObject>(L, 2, "ax.Physics3DObject", &arg0);
if (!ok)
{
break;
}
ax::Physics3DComponent* ret = ax::Physics3DComponent::create(arg0);
object_to_luaval<ax::Physics3DComponent>(L, "ax.Physics3DComponent", (ax::Physics3DComponent*)ret);
return 1;
}
} while (0);
ok = true;
do
{
if (argc == 2)
{
ax::Physics3DObject* arg0;
ok &= luaval_to_object<ax::Physics3DObject>(L, 2, "ax.Physics3DObject", &arg0);
if (!ok)
{
break;
}
ax::Vec3 arg1;
ok &= luaval_to_vec3(L, 3, &arg1, "ax.Physics3DComponent:create");
if (!ok)
{
break;
}
ax::Physics3DComponent* ret = ax::Physics3DComponent::create(arg0, arg1);
object_to_luaval<ax::Physics3DComponent>(L, "ax.Physics3DComponent", (ax::Physics3DComponent*)ret);
return 1;
}
} while (0);
ok = true;
do
{
if (argc == 3)
{
ax::Physics3DObject* arg0;
ok &= luaval_to_object<ax::Physics3DObject>(L, 2, "ax.Physics3DObject", &arg0);
if (!ok)
{
break;
}
ax::Vec3 arg1;
ok &= luaval_to_vec3(L, 3, &arg1, "ax.Physics3DComponent:create");
if (!ok)
{
break;
}
ax::Quaternion arg2;
ok &= luaval_to_quaternion(L, 4, &arg2);
if (!ok)
{
break;
}
ax::Physics3DComponent* ret = ax::Physics3DComponent::create(arg0, arg1, arg2);
object_to_luaval<ax::Physics3DComponent>(L, "ax.Physics3DComponent", (ax::Physics3DComponent*)ret);
return 1;
}
} while (0);
ok = true;
do
{
if (argc == 0)
{
ax::Physics3DComponent* ret = ax::Physics3DComponent::create();
object_to_luaval<ax::Physics3DComponent>(L, "ax.Physics3DComponent", (ax::Physics3DComponent*)ret);
return 1;
}
} while (0);
ok = true;
luaL_error(L, "%s has wrong number of arguments: %d, was expecting %d", "ax.Physics3DComponent:create", argc, 0);
return 0;
# if _AX_DEBUG >= 1
tolua_lerror:
tolua_error(L, "#ferror in function 'axlua_physics3d_Physics3DComponent_create'.", &tolua_err);
# endif
return 0;
}
void extendPhysics3DComponent(lua_State* L)
{
lua_pushstring(L, "ax.Physics3DComponent");
lua_rawget(L, LUA_REGISTRYINDEX);
if (lua_istable(L, -1))
{
tolua_function(L, "create", axlua_physics3d_Physics3DComponent_create);
}
lua_pop(L, 1);
}
int axlua_physics3d_Physics3DWorld_rayCast(lua_State* L)
{
int argc = 0;
ax::Physics3DWorld* obj = nullptr;
bool ok = true;
# if _AX_DEBUG >= 1
tolua_Error tolua_err;
# endif
# if _AX_DEBUG >= 1
if (!tolua_isusertype(L, 1, "ax.Physics3DWorld", 0, &tolua_err))
goto tolua_lerror;
# endif
obj = (ax::Physics3DWorld*)tolua_tousertype(L, 1, 0);
# if _AX_DEBUG >= 1
if (!obj)
{
tolua_error(L, "invalid 'obj' in function 'axlua_physics3d_Physics3DWorld_rayCast'", nullptr);
return 0;
}
# endif
argc = lua_gettop(L) - 1;
if (argc == 3)
{
ax::Vec3 arg0;
ax::Vec3 arg1;
ax::Physics3DWorld::HitResult arg2;
ok &= luaval_to_vec3(L, 2, &arg0, "ax.Physics3DWorld:rayCast");
ok &= luaval_to_vec3(L, 3, &arg1, "ax.Physics3DWorld:rayCast");
ok &= luaval_to_Physics3DWorld_HitResult(L, 4, &arg2, "ax.Physics3DWorld:rayCast");
if (!ok)
{
tolua_error(L, "invalid arguments in function 'axlua_physics3d_Physics3DWorld_rayCast'", nullptr);
return 0;
}
bool ret = obj->rayCast(arg0, arg1, &arg2);
tolua_pushboolean(L, (bool)ret);
Physics3DWorld_HitResult_to_luaval(L, arg2);
return 2;
}
luaL_error(L, "%s has wrong number of arguments: %d, was expecting %d \n", "ax.Physics3DWorld:rayCast", argc, 3);
return 0;
# if _AX_DEBUG >= 1
tolua_lerror:
tolua_error(L, "#ferror in function 'axlua_physics3d_Physics3DWorld_rayCast'.", &tolua_err);
# endif
return 0;
}
void extendPhysics3DWorld(lua_State* L)
{
lua_pushstring(L, "ax.Physics3DWorld");
lua_rawget(L, LUA_REGISTRYINDEX);
if (lua_istable(L, -1))
{
tolua_function(L, "rayCast", axlua_physics3d_Physics3DWorld_rayCast);
}
lua_pop(L, 1);
}
int axlua_physics3d_Physics3DShape_createMesh(lua_State* L)
{
int argc = 0;
bool ok = true;
# if _AX_DEBUG >= 1
tolua_Error tolua_err;
# endif
# if _AX_DEBUG >= 1
if (!tolua_isusertable(L, 1, "ax.Physics3DShape", 0, &tolua_err))
goto tolua_lerror;
# endif
argc = lua_gettop(L) - 1;
if (argc == 2)
{
std::vector<Vec3> arg0;
int arg1;
ok &= luaval_to_std_vector_vec3(L, 2, &arg0, "ax.Physics3DShape:createMesh");
ok &= luaval_to_int(L, 3, (int*)&arg1, "ax.Physics3DShape:createMesh");
if (!ok)
{
tolua_error(L, "invalid arguments in function 'axlua_physics3d_Physics3DShape_createMesh'", nullptr);
return 0;
}
ax::Physics3DShape* ret = ax::Physics3DShape::createMesh(&arg0[0], arg1);
object_to_luaval<ax::Physics3DShape>(L, "ax.Physics3DShape", (ax::Physics3DShape*)ret);
return 1;
}
luaL_error(L, "%s has wrong number of arguments: %d, was expecting %d\n ", "ax.Physics3DShape:createMesh", argc, 2);
return 0;
# if _AX_DEBUG >= 1
tolua_lerror:
tolua_error(L, "#ferror in function 'axlua_physics3d_Physics3DShape_createMesh'.", &tolua_err);
# endif
return 0;
}
int axlua_physics3d_Physics3DShape_createHeightfield(lua_State* L)
{
int argc = 0;
bool ok = true;
# if _AX_DEBUG >= 1
tolua_Error tolua_err;
# endif
# if _AX_DEBUG >= 1
if (!tolua_isusertable(L, 1, "ax.Physics3DShape", 0, &tolua_err))
goto tolua_lerror;
# endif
argc = lua_gettop(L) - 1;
if (argc == 8)
{
int arg0;
int arg1;
std::vector<float> arg2;
double arg3;
double arg4;
double arg5;
bool arg6;
bool arg7;
ok &= luaval_to_int(L, 2, (int*)&arg0, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_int(L, 3, (int*)&arg1, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_std_vector_float(L, 4, &arg2, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_number(L, 5, &arg3, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_number(L, 6, &arg4, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_number(L, 7, &arg5, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_boolean(L, 8, &arg6, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_boolean(L, 9, &arg7, "ax.Physics3DShape:createHeightfield");
if (!ok)
{
tolua_error(L, "invalid arguments in function 'axlua_physics3d_Physics3DShape_createHeightfield'", nullptr);
return 0;
}
ax::Physics3DShape* ret = ax::Physics3DShape::createHeightfield(arg0, arg1, &arg2[0], (float)arg3, (float)arg4,
(float)arg5, arg6, arg7);
object_to_luaval<ax::Physics3DShape>(L, "ax.Physics3DShape", (ax::Physics3DShape*)ret);
return 1;
}
if (argc == 9)
{
int arg0;
int arg1;
std::vector<float> arg2;
double arg3;
double arg4;
double arg5;
bool arg6;
bool arg7;
bool arg8;
ok &= luaval_to_int(L, 2, (int*)&arg0, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_int(L, 3, (int*)&arg1, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_std_vector_float(L, 4, &arg2, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_number(L, 5, &arg3, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_number(L, 6, &arg4, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_number(L, 7, &arg5, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_boolean(L, 8, &arg6, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_boolean(L, 9, &arg7, "ax.Physics3DShape:createHeightfield");
ok &= luaval_to_boolean(L, 10, &arg8, "ax.Physics3DShape:createHeightfield");
if (!ok)
{
tolua_error(L, "invalid arguments in function 'axlua_physics3d_Physics3DShape_createHeightfield'", nullptr);
return 0;
}
ax::Physics3DShape* ret = ax::Physics3DShape::createHeightfield(arg0, arg1, &arg2[0], (float)arg3, (float)arg4,
(float)arg5, arg6, arg7, arg8);
object_to_luaval<ax::Physics3DShape>(L, "ax.Physics3DShape", (ax::Physics3DShape*)ret);
return 1;
}
luaL_error(L, "%s has wrong number of arguments: %d, was expecting %d\n ", "ax.Physics3DShape:createHeightfield",
argc, 8);
return 0;
# if _AX_DEBUG >= 1
tolua_lerror:
tolua_error(L, "#ferror in function 'axlua_physics3d_Physics3DShape_createHeightfield'.", &tolua_err);
# endif
return 0;
}
int axlua_physics3d_Physics3DShape_createCompoundShape(lua_State* L)
{
int argc = 0;
bool ok = true;
tolua_Error tolua_err;
# if _AX_DEBUG >= 1
if (!tolua_isusertable(L, 1, "ax.Physics3DShape", 0, &tolua_err))
goto tolua_lerror;
# endif
argc = lua_gettop(L) - 1;
if (argc == 1)
{
std::vector<std::pair<ax::Physics3DShape*, ax::Mat4>> shapes;
if (!tolua_istable(L, 2, 0, &tolua_err))
{
# if _AX_DEBUG >= 1
luaval_to_native_err(L, "#ferror:", &tolua_err, "ax.Physics3DShape:createCompoundShape");
# endif
ok = false;
}
if (ok)
{
size_t len = lua_objlen(L, 2);
ax::Physics3DShape* shape = nullptr;
ax::Mat4 mat;
for (size_t i = 0; i < len; i++)
{
lua_pushnumber(L, i + 1);
lua_gettable(L, 2);
if (lua_istable(L, -1))
{
lua_pushnumber(L, 1);
lua_gettable(L, -2);
luaval_to_object(L, lua_gettop(L), "ax.Physics3DShape", &shape);
lua_pop(L, 1);
lua_pushnumber(L, 2);
lua_gettable(L, -2);
luaval_to_mat4(L, lua_gettop(L), &mat);
lua_pop(L, 1);
shapes.emplace_back(std::make_pair(shape, mat));
}
lua_pop(L, 1);
}
}
ax::Physics3DShape* ret = ax::Physics3DShape::createCompoundShape(shapes);
object_to_luaval<ax::Physics3DShape>(L, "ax.Physics3DShape", (ax::Physics3DShape*)ret);
return 1;
}
luaL_error(L, "%s has wrong number of arguments: %d, was expecting %d\n ", "ax.Physics3DShape:createCompoundShape",
argc, 1);
return 0;
# if _AX_DEBUG >= 1
tolua_lerror:
tolua_error(L, "#ferror in function 'axlua_physics3d_Physics3DShape_createCompoundShape'.", &tolua_err);
# endif
return 0;
}
void extendPhysics3DShape(lua_State* L)
{
lua_pushstring(L, "ax.Physics3DShape");
lua_rawget(L, LUA_REGISTRYINDEX);
if (lua_istable(L, -1))
{
tolua_function(L, "createMesh", axlua_physics3d_Physics3DShape_createMesh);
tolua_function(L, "createHeightfield", axlua_physics3d_Physics3DShape_createHeightfield);
tolua_function(L, "createCompoundShape", axlua_physics3d_Physics3DShape_createCompoundShape);
}
lua_pop(L, 1);
}
void CollisionPoint_to_luaval(lua_State* L, const ax::Physics3DCollisionInfo::CollisionPoint& collisionPoint)
{
if (nullptr == L)
return;
lua_newtable(L);
lua_pushstring(L, "localPositionOnA");
vec3_to_luaval(L, collisionPoint.localPositionOnA);
lua_rawset(L, -3);
lua_pushstring(L, "worldPositionOnA");
vec3_to_luaval(L, collisionPoint.worldPositionOnA);
lua_rawset(L, -3);
lua_pushstring(L, "localPositionOnB");
vec3_to_luaval(L, collisionPoint.localPositionOnB);
lua_rawset(L, -3);
lua_pushstring(L, "worldPositionOnB");
vec3_to_luaval(L, collisionPoint.worldPositionOnB);
lua_rawset(L, -3);
lua_pushstring(L, "worldNormalOnB");
vec3_to_luaval(L, collisionPoint.worldNormalOnB);
lua_rawset(L, -3);
}
int axlua_physics3d_Physics3DObject_setCollisionCallback(lua_State* L)
{
int argc = 0;
ax::Physics3DObject* obj = nullptr;
# if _AX_DEBUG >= 1
tolua_Error tolua_err;
# endif
# if _AX_DEBUG >= 1
if (!tolua_isusertype(L, 1, "ax.Physics3DObject", 0, &tolua_err))
goto tolua_lerror;
# endif
obj = (ax::Physics3DObject*)tolua_tousertype(L, 1, 0);
# if _AX_DEBUG >= 1
if (!obj)
{
tolua_error(L, "invalid 'obj' in function 'axlua_physics3d_Physics3DObject_setCollisionCallback'", nullptr);
return 0;
}
# endif
argc = lua_gettop(L) - 1;
if (argc == 1)
{
# if _AX_DEBUG >= 1
if (!toluafix_isfunction(L, 2, "LUA_FUNCTION", 0, &tolua_err))
{
goto tolua_lerror;
}
# endif
LUA_FUNCTION handler = toluafix_ref_function(L, 2, 0);
obj->setCollisionCallback([=](const ax::Physics3DCollisionInfo& ci) {
auto stack = LuaEngine::getInstance()->getLuaStack();
auto Ls = stack->getLuaState();
lua_newtable(Ls);
lua_pushstring(Ls, "objA");
if (nullptr == ci.objA)
{
lua_pushnil(Ls);
}
else
{
object_to_luaval(Ls, "ax.Physics3DObject", ci.objA);
}
lua_rawset(Ls, -3);
lua_pushstring(Ls, "objB");
if (nullptr == ci.objB)
{
lua_pushnil(Ls);
}
else
{
object_to_luaval(Ls, "ax.Physics3DObject", ci.objB);
}
lua_rawset(Ls, -3);
lua_pushstring(Ls, "collisionPointList");
if (ci.collisionPointList.empty())
{
lua_pushnil(Ls);
}
else
{
int vecIndex = 1;
lua_newtable(Ls);
for (const auto& value : ci.collisionPointList)
{
lua_pushnumber(Ls, vecIndex);
CollisionPoint_to_luaval(Ls, value);
lua_rawset(Ls, -3);
++vecIndex;
}
}
lua_rawset(Ls, -3);
stack->executeFunctionByHandler(handler, 1);
});
ScriptHandlerMgr::getInstance()->addCustomHandler((void*)obj, handler);
return 0;
}
luaL_error(L, "%s has wrong number of arguments: %d, was expecting %d \n",
"ax.Physics3DObject:setCollisionCallback", argc, 1);
return 0;
# if _AX_DEBUG >= 1
tolua_lerror:
tolua_error(L, "#ferror in function 'axlua_physics3d_Physics3DObject_setCollisionCallback'.", &tolua_err);
# endif
return 0;
}
void extendPhysics3DObject(lua_State* L)
{
lua_pushstring(L, "ax.Physics3DObject");
lua_rawget(L, LUA_REGISTRYINDEX);
if (lua_istable(L, -1))
{
tolua_function(L, "setCollisionCallback", axlua_physics3d_Physics3DObject_setCollisionCallback);
}
lua_pop(L, 1);
}
int register_all_physics3d_manual(lua_State* L)
{
if (nullptr == L)
return 0;
extendPhysicsMeshRenderer(L);
extendPhysics3DRigidBody(L);
extendPhysics3DComponent(L);
extendPhysics3DWorld(L);
extendPhysics3DShape(L);
extendPhysics3DObject(L);
return 1;
}
int register_physics3d_module(lua_State* L)
{
lua_getglobal(L, "_G");
if (lua_istable(L, -1)) // stack:...,_G,
{
register_all_ax_physics3d(L);
register_all_physics3d_manual(L);
}
lua_pop(L, 1);
return 1;
}
#endif
| 0 | 0.7794 | 1 | 0.7794 | game-dev | MEDIA | 0.795565 | game-dev | 0.5985 | 1 | 0.5985 |
foxnne/aftersun | 5,406 | src/ecs/systems/use.zig | const std = @import("std");
const zmath = @import("zmath");
const ecs = @import("zflecs");
const game = @import("../../aftersun.zig");
const components = game.components;
pub fn groupBy(world: *ecs.world_t, table: *ecs.table_t, id: ecs.entity_t, ctx: ?*anyopaque) callconv(.C) ecs.entity_t {
_ = ctx;
var match: ecs.entity_t = 0;
if (ecs.search(world, table, ecs.pair(id, ecs.Wildcard), &match) != -1) {
return ecs.pair_second(match);
}
return 0;
}
pub fn system(world: *ecs.world_t) ecs.system_desc_t {
var desc: ecs.system_desc_t = .{};
desc.query.filter.terms[0] = .{ .id = ecs.id(components.Player) };
desc.query.filter.terms[1] = .{ .id = ecs.id(components.Position) };
desc.query.filter.terms[2] = .{ .id = ecs.pair(ecs.id(components.Request), ecs.id(components.Use)) };
desc.run = run;
var ctx_desc: ecs.query_desc_t = .{};
ctx_desc.filter.terms[0] = .{ .id = ecs.pair(ecs.id(components.Cell), ecs.Wildcard) };
ctx_desc.filter.terms[1] = .{ .id = ecs.id(components.Position) };
ctx_desc.group_by = groupBy;
ctx_desc.group_by_id = ecs.id(components.Cell);
ctx_desc.order_by = orderBy;
ctx_desc.order_by_component = ecs.id(components.Position);
desc.ctx = ecs.query_init(world, &ctx_desc) catch unreachable;
return desc;
}
pub fn run(it: *ecs.iter_t) callconv(.C) void {
const world = it.world;
while (ecs.iter_next(it)) {
var i: usize = 0;
while (i < it.count()) : (i += 1) {
const entity = it.entities()[i];
if (ecs.field(it, components.Position, 2)) |positions| {
if (ecs.field(it, components.Use, 3)) |uses| {
const dist_x = @abs(uses[i].target.x - positions[i].tile.x);
const dist_y = @abs(uses[i].target.y - positions[i].tile.y);
if (dist_x <= 1 and dist_y <= 1) {
var target_entity: ?ecs.entity_t = null;
var target_tile: components.Tile = .{};
var counter: u64 = 0;
if (it.ctx) |ctx| {
const query = @as(*ecs.query_t, @ptrCast(ctx));
var query_it = ecs.query_iter(world, query);
if (game.state.cells.get(uses[i].target.toCell())) |cell_entity| {
ecs.query_set_group(&query_it, cell_entity);
}
while (ecs.iter_next(&query_it)) {
var j: usize = 0;
while (j < query_it.count()) : (j += 1) {
if (ecs.field(&query_it, components.Position, 2)) |start_positions| {
if (query_it.entities()[j] == entity)
continue;
if (start_positions[j].tile.x == uses[i].target.x and start_positions[j].tile.y == uses[i].target.y and start_positions[j].tile.z == uses[i].target.z) {
if (start_positions[j].tile.counter > counter) {
counter = start_positions[j].tile.counter;
target_entity = query_it.entities()[j];
target_tile = start_positions[j].tile;
}
}
}
}
}
}
if (target_entity) |target| {
if (ecs.has_id(world, target, ecs.id(components.Useable))) {
if (ecs.has_id(world, target, ecs.id(components.Consumeable))) {
if (ecs.get_mut(world, target, components.Stack)) |stack| {
stack.count -= 1;
ecs.modified_id(world, target, ecs.id(components.Stack));
} else {
ecs.delete(world, target);
}
}
if (ecs.get(world, target, components.Toggleable)) |toggle| {
const new = ecs.new_w_id(world, ecs.pair(ecs.IsA, if (toggle.state) toggle.off_prefab else toggle.on_prefab));
_ = ecs.set(world, new, components.Position, target_tile.toPosition(.tile));
ecs.delete(world, target);
}
}
}
}
ecs.remove_pair(world, entity, ecs.id(components.Request), ecs.id(components.Use));
}
}
}
}
}
fn orderBy(_: ecs.entity_t, c1: ?*const anyopaque, _: ecs.entity_t, c2: ?*const anyopaque) callconv(.C) c_int {
const pos_1 = ecs.cast(components.Position, c1);
const pos_2 = ecs.cast(components.Position, c2);
return @as(c_int, @intCast(@intFromBool(pos_1.tile.counter > pos_2.tile.counter))) - @as(c_int, @intCast(@intFromBool(pos_1.tile.counter < pos_2.tile.counter)));
}
| 0 | 0.74904 | 1 | 0.74904 | game-dev | MEDIA | 0.363308 | game-dev | 0.874644 | 1 | 0.874644 |
bucaps/marss-riscv | 6,340 | src/ramulator/src/GDDR5.h | #ifndef __GDDR5_H
#define __GDDR5_H
#include "DRAM.h"
#include "Request.h"
#include <vector>
#include <functional>
using namespace std;
namespace ramulator
{
class GDDR5
{
public:
static string standard_name;
enum class Org;
enum class Speed;
GDDR5(Org org, Speed speed);
GDDR5(const string& org_str, const string& speed_str);
static map<string, enum Org> org_map;
static map<string, enum Speed> speed_map;
/*** Level ***/
enum class Level : int
{
Channel, Rank, BankGroup, Bank, Row, Column, MAX
};
static std::string level_str [int(Level::MAX)];
/*** Command ***/
enum class Command : int
{
ACT, PRE, PREA,
RD, WR, RDA, WRA,
REF, PDE, PDX, SRE, SRX,
MAX
};
string command_name[int(Command::MAX)] = {
"ACT", "PRE", "PREA",
"RD", "WR", "RDA", "WRA",
"REF", "PDE", "PDX", "SRE", "SRX"
};
Level scope[int(Command::MAX)] = {
Level::Row, Level::Bank, Level::Rank,
Level::Column, Level::Column, Level::Column, Level::Column,
Level::Rank, Level::Rank, Level::Rank, Level::Rank, Level::Rank
};
bool is_opening(Command cmd)
{
switch(int(cmd)) {
case int(Command::ACT):
return true;
default:
return false;
}
}
bool is_accessing(Command cmd)
{
switch(int(cmd)) {
case int(Command::RD):
case int(Command::WR):
case int(Command::RDA):
case int(Command::WRA):
return true;
default:
return false;
}
}
bool is_closing(Command cmd)
{
switch(int(cmd)) {
case int(Command::RDA):
case int(Command::WRA):
case int(Command::PRE):
case int(Command::PREA):
return true;
default:
return false;
}
}
bool is_refreshing(Command cmd)
{
switch(int(cmd)) {
case int(Command::REF):
return true;
default:
return false;
}
}
/* State */
enum class State : int
{
Opened, Closed, PowerUp, ActPowerDown, PrePowerDown, SelfRefresh, MAX
} start[int(Level::MAX)] = {
State::MAX, State::PowerUp, State::MAX, State::Closed, State::Closed, State::MAX
};
/* Translate */
Command translate[int(Request::Type::MAX)] = {
Command::RD, Command::WR,
Command::REF, Command::PDE, Command::SRE
};
/* Prerequisite */
function<Command(DRAM<GDDR5>*, Command cmd, int)> prereq[int(Level::MAX)][int(Command::MAX)];
// SAUGATA: added function object container for row hit status
/* Row hit */
function<bool(DRAM<GDDR5>*, Command cmd, int)> rowhit[int(Level::MAX)][int(Command::MAX)];
function<bool(DRAM<GDDR5>*, Command cmd, int)> rowopen[int(Level::MAX)][int(Command::MAX)];
/* Timing */
struct TimingEntry
{
Command cmd;
int dist;
int val;
bool sibling;
};
vector<TimingEntry> timing[int(Level::MAX)][int(Command::MAX)];
/* Lambda */
function<void(DRAM<GDDR5>*, int)> lambda[int(Level::MAX)][int(Command::MAX)];
/* Organization */
enum class Org : int
{
GDDR5_512Mb_x16, GDDR5_512Mb_x32,
GDDR5_1Gb_x16, GDDR5_1Gb_x32,
GDDR5_2Gb_x16, GDDR5_2Gb_x32,
GDDR5_4Gb_x16, GDDR5_4Gb_x32,
GDDR5_8Gb_x16, GDDR5_8Gb_x32,
MAX
};
struct OrgEntry {
int size;
int dq;
int count[int(Level::MAX)];
} org_table[int(Org::MAX)] = {
// fixed to have 1 rank
// in GDDR5 the column address is unique for a burst. e.g. 64 column addresses correspond with
// 256 column addresses actually. So we multiply 8 to the original address bit number in JEDEC standard
{ 512, 16, {0, 1, 4, 2, 1<<12, 1<<(7+3)}}, { 512, 32, {0, 1, 4, 2, 1<<12, 1<<(6+3)}},
{1<<10, 16, {0, 1, 4, 4, 1<<12, 1<<(7+3)}}, {1<<10, 32, {0, 1, 4, 4, 1<<12, 1<<(6+3)}},
{2<<10, 16, {0, 1, 4, 4, 1<<13, 1<<(7+3)}}, {2<<10, 32, {0, 1, 4, 4, 1<<13, 1<<(6+3)}},
{4<<10, 16, {0, 1, 4, 4, 1<<14, 1<<(7+3)}}, {2<<10, 32, {0, 1, 4, 4, 1<<14, 1<<(6+3)}},
{8<<10, 16, {0, 1, 4, 4, 1<<14, 1<<(8+3)}}, {8<<10, 32, {0, 1, 4, 4, 1<<14, 1<<(7+3)}}
}, org_entry;
void set_channel_number(int channel);
void set_rank_number(int rank);
/* Speed */
enum class Speed : int
{
GDDR5_4000, GDDR5_4500,
GDDR5_5000, GDDR5_5500,
GDDR5_6000, GDDR5_6500,
GDDR5_7000,
MAX
};
int prefetch_size = 8; // 8n prefetch QDR
int channel_width = 64;
struct SpeedEntry {
int rate;
double freq, tCK;
int nBL, nCCDS, nCCDL;
int nCL, nRCDR, nRCDW, nRP, nCWL;
int nRAS, nRC;
int nPPD, nRTP, nWTR, nWR;
int nRRD, nFAW, n32AW;
int nRFC, nREFI;
int nPD, nXPN, nLK;
int nCKESR, nXS, nXSDLL;
} speed_table[int(Speed::MAX)] = {
{4000, 8*500/4, 8.0/8, 2, 2, 3, 12, 12, 10, 12, 3, 28, 40, 1, 2, 5, 12, 6, 23, 184, 0, 0, 10, 10, 0, 0, 0, 0},
{4500, 9*500/4, 8.0/9, 2, 2, 3, 14, 14, 12, 14, 4, 32, 46, 2, 2, 6, 14, 7, 26, 207, 0, 0, 10, 10, 0, 0, 0, 0},
{5000, 10*500/4, 8.0/10, 2, 2, 3, 15, 15, 13, 15, 4, 35, 50, 2, 2, 7, 15, 7, 29, 230, 0, 0, 10, 10, 0, 0, 0, 0},
{5500, 11*500/4, 8.0/11, 2, 2, 3, 17, 17, 14, 17, 5, 39, 56, 2, 2, 7, 17, 8, 32, 253, 0, 0, 10, 10, 0, 0, 0, 0},
{6000, 12*500/4, 8.0/12, 2, 2, 3, 18, 18, 15, 18, 5, 42, 60, 2, 2, 8, 18, 9, 35, 276, 0, 0, 10, 10, 0, 0, 0, 0},
{6500, 13*500/4, 8.0/13, 2, 2, 3, 20, 20, 17, 20, 5, 46, 66, 2, 2, 9, 20, 9, 38, 299, 0, 0, 10, 10, 0, 0, 0, 0},
{7000, 14*500/4, 8.0/14, 2, 2, 3, 21, 21, 18, 21, 6, 49, 70, 2, 2, 9, 21, 10, 41, 322, 0, 0, 10, 10, 0, 0, 0, 0}
}, speed_entry;
int read_latency;
private:
void init_speed();
void init_lambda();
void init_prereq();
void init_rowhit(); // SAUGATA: added function to check for row hits
void init_rowopen();
void init_timing();
};
} /*namespace ramulator*/
#endif /*__GDDR5_H*/
| 0 | 0.792061 | 1 | 0.792061 | game-dev | MEDIA | 0.288171 | game-dev | 0.741871 | 1 | 0.741871 |
magefree/mage | 1,771 | Mage.Sets/src/mage/cards/c/ChainedBrute.java | package mage.cards.c;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.ActivateIfConditionActivatedAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.condition.common.MyTurnCondition;
import mage.abilities.costs.common.SacrificeTargetCost;
import mage.abilities.costs.mana.GenericManaCost;
import mage.abilities.effects.common.DontUntapInControllersUntapStepSourceEffect;
import mage.abilities.effects.common.UntapSourceEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.filter.StaticFilters;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class ChainedBrute extends CardImpl {
public ChainedBrute(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{R}");
this.subtype.add(SubType.DEVIL);
this.power = new MageInt(4);
this.toughness = new MageInt(3);
// Chained Brute doesn't untap during your untap step.
this.addAbility(new SimpleStaticAbility(new DontUntapInControllersUntapStepSourceEffect()));
// {1}, Sacrifice another creature: Untap Chained Brute. Activate this ability only during your turn.
Ability ability = new ActivateIfConditionActivatedAbility(
new UntapSourceEffect(), new GenericManaCost(1), MyTurnCondition.instance
);
ability.addCost(new SacrificeTargetCost(StaticFilters.FILTER_CONTROLLED_ANOTHER_CREATURE));
this.addAbility(ability);
}
private ChainedBrute(final ChainedBrute card) {
super(card);
}
@Override
public ChainedBrute copy() {
return new ChainedBrute(this);
}
}
| 0 | 0.974406 | 1 | 0.974406 | game-dev | MEDIA | 0.968185 | game-dev | 0.986038 | 1 | 0.986038 |
Grimrukh/SoulsAI | 16,685 | ai_scripts/m18_01_00_00/255000_battle.lua | REGISTER_GOAL(GOAL_HusiHeavy_Spear255000_Battle, "HusiHeavy_Spear255000Battle")
local Att3000_Dist_min = 0
local Att3000_Dist_max = 2.8
local Att3003_Dist_min = 0
local Att3003_Dist_max = 2
local Att3005_Dist_min = 2.5
local Att3005_Dist_max = 4.4
local Att3007_Dist_min = 0
local Att3007_Dist_max = 3.15
local Att3008_Dist_min = 2.5
local Att3008_Dist_max = 4.5
local Att3009_Dist_min = 0
local Att3009_Dist_max = 1.8
REGISTER_GOAL_NO_UPDATE(GOAL_HusiHeavy_Spear255000_Battle, 1)
Att3000_Dist_min = Att3009_Dist_max
Att3000_Dist_min = Att3007_Dist_max
function OnIf_255000(ai, goal, codeNo)
local targetDist = ai:GetDist(TARGET_ENE_0)
local fate = ai:GetRandam_Int(1, 100)
local fate2 = ai:GetRandam_Int(1, 100)
if codeNo == 0 then
if ai:IsTargetGuard(TARGET_ENE_0) == true then
if fate <= 20 and targetDist <= 2.8 then
local approachDist = Att3009_Dist_max
local dashDist = Att3009_Dist_max + 2
local Odds_Guard = 100
Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard)
goal:AddSubGoal(GOAL_COMMON_GuardBreakAttack, 10, 3009, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, Att3007_Dist_max, TARGET_SELF, true, -1)
goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3007, TARGET_ENE_0, DIST_Middle, 0)
else
goal:AddSubGoal(GOAL_COMMON_SidewayMove, ai:GetRandam_Float(3, 3.5), TARGET_ENE_0, ai:GetRandam_Int(0, 1), ai:GetRandam_Float(30, 50), true, true, 9910)
end
elseif 4.4 <= targetDist then
goal:AddSubGoal(GOAL_COMMON_SidewayMove, ai:GetRandam_Float(3, 3.5), TARGET_ENE_0, ai:GetRandam_Int(0, 1), ai:GetRandam_Float(30, 50), true, true, 9910)
elseif 2.8 <= targetDist then
if fate <= 30 then
if fate2 <= 50 then
goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3005, TARGET_ENE_0, DIST_Middle, 0)
else
goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3005, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3006, TARGET_ENE_0, DIST_Middle, 0)
end
else
goal:AddSubGoal(GOAL_COMMON_SidewayMove, ai:GetRandam_Float(3, 3.5), TARGET_ENE_0, ai:GetRandam_Int(0, 1), ai:GetRandam_Float(30, 50), true, true, 9910)
end
elseif 1.5 <= targetDist then
if fate <= 60 then
if fate2 <= 30 then
goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0)
elseif fate2 <= 70 then
goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3001, TARGET_ENE_0, DIST_Middle, 0)
else
goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3002, TARGET_ENE_0, DIST_Middle, 0)
end
else
goal:AddSubGoal(GOAL_COMMON_SidewayMove, ai:GetRandam_Float(3, 3.5), TARGET_ENE_0, ai:GetRandam_Int(0, 1), ai:GetRandam_Float(30, 50), true, true, 9910)
end
elseif fate <= 95 then
if fate2 <= 20 then
goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0)
elseif fate2 <= 50 then
goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3001, TARGET_ENE_0, DIST_Middle, 0)
else
goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3002, TARGET_ENE_0, DIST_Middle, 0)
end
else
goal:AddSubGoal(GOAL_COMMON_SidewayMove, ai:GetRandam_Float(3, 3.5), TARGET_ENE_0, ai:GetRandam_Int(0, 1), ai:GetRandam_Float(30, 50), true, true, 9910)
end
elseif codeNo == 1 then
if 2.5 <= targetDist then
if fate <= 50 then
goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3005, TARGET_ENE_0, DIST_Middle, 0)
else
goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3005, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3006, TARGET_ENE_0, DIST_Middle, 0)
end
elseif fate <= 30 then
goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0)
elseif fate <= 70 then
goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3001, TARGET_ENE_0, DIST_Middle, 0)
else
goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3002, TARGET_ENE_0, DIST_Middle, 0)
end
elseif codeNo == 2 then
if ai:HasSpecialEffectId(TARGET_SELF, 3151) then
ai:SetTimer(1, 120)
else
ai:SetTimer(1, 30)
end
end
return
end
Att3000_Dist_min = Att3003_Dist_max
Att3000_Dist_min = Att3007_Dist_max
Att3000_Dist_min = Att3009_Dist_max
function HusiHeavy_Spear255000Battle_Activate(ai, goal)
local hprate = ai:GetHpRate(TARGET_SELF)
local targetDist = ai:GetDist(TARGET_ENE_0)
local fate = ai:GetRandam_Int(1, 100)
local fate2 = ai:GetRandam_Int(1, 100)
local fate3 = ai:GetRandam_Int(1, 100)
local fate4 = ai:GetRandam_Int(1, 100)
local Berserk = ai:GetTimer(0)
local est = ai:GetTimer(1)
local Act01Per = 0
local Act02Per = 0
local Act03Per = 0
local Act04Per = 0
local Act05Per = 0
local Act06Per = 0
if hprate <= 0.4 and ai:IsFinishTimer(1) == true then
if 8 <= targetDist then
Act06Per = 200
elseif 2.5 <= targetDist then
Act06Per = 100
else
Act06Per = 50
end
end
if Berserk <= 0 then
Act01Per = 100
elseif ai:IsTargetGuard(TARGET_ENE_0) == true then
if 8 <= targetDist then
Act02Per = 30
Act03Per = 30
Act04Per = 40
Act05Per = 0
elseif 2.5 <= targetDist then
Act02Per = 35
Act03Per = 35
Act04Per = 20
Act05Per = 10
else
Act02Per = 40
Act03Per = 40
Act04Per = 0
Act05Per = 20
end
elseif 8 <= targetDist then
Act02Per = 25
Act03Per = 15
Act04Per = 60
Act05Per = 0
elseif 2.5 <= targetDist then
Act02Per = 30
Act03Per = 50
Act04Per = 20
Act05Per = 0
else
Act02Per = 40
Act03Per = 60
Act04Per = 0
Act05Per = 0
end
local doAdmirer = ai:GetExcelParam(AI_EXCEL_THINK_PARAM_TYPE__thinkAttr_doAdmirer)
local role = ai:GetTeamOrder(ORDER_TYPE_Role)
local Odds_Guard = 100
if doAdmirer == 1 and role == ROLE_TYPE_Torimaki then
Torimaki_Act(ai, goal, Odds_Guard)
elseif doAdmirer == 1 and role == ROLE_TYPE_Kankyaku then
Kankyaku_Act(ai, goal, Odds_Guard)
else
local fateAct = ai:GetRandam_Int(1, Act01Per + Act02Per + Act03Per + Act04Per + Act05Per + Act06Per)
if fateAct <= Act01Per then
local fateLeave = ai:GetRandam_Int(1, 100)
if 4.5 <= targetDist then
goal:AddSubGoal(GOAL_COMMON_ApproachTarget, 5, TARGET_ENE_0, ai:GetRandam_Float(3, 4), TARGET_SELF, true, 9910)
elseif targetDist <= 1.5 and fateLeave <= 50 then
goal:AddSubGoal(GOAL_COMMON_LeaveTarget, ai:GetRandam_Float(3, 3.5), TARGET_ENE_0, ai:GetRandam_Float(2.5, 3.5), TARGET_ENE_0, true, 9910)
elseif targetDist <= 0.5 and fateLeave <= 90 then
goal:AddSubGoal(GOAL_COMMON_LeaveTarget, ai:GetRandam_Float(3, 3.5), TARGET_ENE_0, ai:GetRandam_Float(2.5, 3.5), TARGET_ENE_0, true, 9910)
end
goal:AddSubGoal(GOAL_COMMON_SidewayMove, ai:GetRandam_Float(3, 3.5), TARGET_ENE_0, ai:GetRandam_Int(0, 1), ai:GetRandam_Float(30, 50), true, true, 9910)
goal:AddSubGoal(GOAL_COMMON_SidewayMove, ai:GetRandam_Float(3, 3.5), TARGET_ENE_0, ai:GetRandam_Int(0, 1), ai:GetRandam_Float(30, 50), true, true, 9910)
goal:AddSubGoal(GOAL_COMMON_If, 10, 0)
elseif fateAct <= Act01Per + Act02Per then
local approachDist = Att3003_Dist_max
local dashDist = Att3003_Dist_max + 0
local Odds_Guard = 0
Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard)
if fate <= 25 then
goal:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3003, TARGET_ENE_0, DIST_Middle, -1, 60)
else
goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, DIST_Middle, -1, 60)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3004, TARGET_ENE_0, DIST_Middle, 0)
end
HusiHeavy_Spear255000_AfterAttackAct01(ai, goal)
elseif fateAct <= Act01Per + Act02Per + Act03Per then
local approachDist = Att3007_Dist_max
local dashDist = Att3007_Dist_max + 0
local Odds_Guard = 0
Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard)
goal:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3007, TARGET_ENE_0, DIST_Middle, -1, 15)
HusiHeavy_Spear255000_AfterAttackAct01(ai, goal)
elseif fateAct <= Act01Per + Act02Per + Act03Per + Act04Per then
local approachDist = Att3007_Dist_max
local dashDist = Att3007_Dist_max + 0
local Odds_Guard = 0
Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard)
goal:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3008, TARGET_ENE_0, DIST_Middle, -1, 30)
HusiHeavy_Spear255000_AfterAttackAct01(ai, goal)
elseif fateAct <= Act01Per + Act02Per + Act03Per + Act04Per + Act05Per then
local approachDist = Att3009_Dist_max
local dashDist = Att3009_Dist_max + 0
local Odds_Guard = 0
Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard)
goal:AddSubGoal(GOAL_COMMON_GuardBreakAttack, 10, 3009, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, Att3007_Dist_max, TARGET_SELF, true, -1)
goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3007, TARGET_ENE_0, DIST_Middle, 0)
HusiHeavy_Spear255000_AfterAttackAct01(ai, goal)
else
if fate <= 40 then
goal:AddSubGoal(GOAL_COMMON_LeaveTarget, 5, TARGET_ENE_0, 4.5, TARGET_ENE_0, true, 9910)
goal:AddSubGoal(GOAL_COMMON_NonspinningAttack, 10, 3200, TARGET_ENE_0, DIST_None)
else
goal:AddSubGoal(GOAL_COMMON_SpinStep, 5, 701, TARGET_ENE_0, -1, AI_DIR_TYPE_B, 3.6)
goal:AddSubGoal(GOAL_COMMON_NonspinningAttack, 10, 3200, TARGET_ENE_0, DIST_None)
end
goal:AddSubGoal(GOAL_COMMON_If, 15, 2)
end
end
return
end
function HusiHeavy_Spear255000_AfterAttackAct01(ai, goal)
local Odds_Guard = 0
local Odds_NoAct = 85
local Odds_BackAndSide = 0
local Odds_Back = 0
local Odds_BitWait = 0
local Odds_Backstep = 5
local Odds_Sidestep = 10
GetWellSpace_Act_IncludeSidestep(ai, goal, Odds_Guard, Odds_NoAct, Odds_BackAndSide, Odds_Back, Odds_BitWait, Odds_Backstep, Odds_Sidestep)
return
end
function HusiHeavy_Spear255000Battle_Update(ai, goal)
return GOAL_RESULT_Continue
end
function HusiHeavy_Spear255000Battle_Terminate(ai, goal)
return
end
function HusiHeavy_Spear255000Battle_Interupt(ai, goal)
if ai:IsLadderAct(TARGET_SELF) then
return false
end
local fate = ai:GetRandam_Int(1, 100)
local fate2 = ai:GetRandam_Int(1, 100)
local fate3 = ai:GetRandam_Int(1, 100)
local targetDist = ai:GetDist(TARGET_ENE_0)
local hprate = ai:GetHpRate(TARGET_SELF)
if ai:IsInterupt(INTERUPT_Damaged) then
local Berserk = ai:GetTimer(0)
if 0.15 <= hprate and hprate <= 0.9 then
goal:ClearSubGoal()
ai:SetTimer(0, 11)
goal:AddSubGoal(GOAL_COMMON_Wait, 0.1, TARGET_SELF)
return true
elseif targetDist <= 3 and fate <= 40 then
goal:ClearSubGoal()
local Odds_Guard = 100
local Odds_NoAct = 0
local Odds_BackAndSide = 30
local Odds_Back = 40
local Odds_BitWait = 0
local Odds_Backstep = 15
local Odds_Sidestep = 15
GetWellSpace_Act_IncludeSidestep(ai, goal, Odds_Guard, Odds_NoAct, Odds_BackAndSide, Odds_Back, Odds_BitWait, Odds_Backstep, Odds_Sidestep)
return true
end
end
if ai:IsInterupt(INTERUPT_SuccessGuard) then
local Berserk = ai:GetTimer(0)
if Berserk <= 0 and targetDist <= 4.4 and fate <= 50 then
goal:ClearSubGoal()
if 2.5 <= targetDist then
goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3005, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3006, TARGET_ENE_0, DIST_Middle, 0)
elseif fate <= 30 then
goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0)
elseif fate <= 70 then
goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3001, TARGET_ENE_0, DIST_Middle, 0)
else
goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3000, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3002, TARGET_ENE_0, DIST_Middle, 0)
end
return true
end
end
local distResponse = 3
local oddsResponse = 15
local oddsStep = 30
local bkStepPer = 40
local leftStepPer = 30
local rightStepPer = 30
local safetyDist = 3.5
local oddsLeaveAndSide = 50
local timeSide = 3.5
local distLeave = 2.5
if FindAttack_Step_or_Guard(ai, goal, distResponse, oddsResponse, oddsStep, bkStepPer, leftStepPer, rightStepPer, safetyDist, oddsLeaveAndSide, timeSide, distLeave) then
return true
else
local distMissSwing_Int = 4.4
local oddsMissSwing_Int = 30
if MissSwing_Int(ai, goal, distMissSwing_Int, oddsMissSwing_Int) then
if targetDist <= 2 then
goal:AddSubGoal(GOAL_COMMON_Attack, 10, 3003, TARGET_ENE_0, DIST_Middle, 0)
else
goal:AddSubGoal(GOAL_COMMON_ComboAttack, 10, 3005, TARGET_ENE_0, DIST_Middle, 0)
goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3006, TARGET_ENE_0, DIST_Middle, 0)
end
return true
else
local distResNear = 12
local distResFar = 20
local oddsResNear = 0
local oddsResFar = 30
local ResBehavID = Shoot_2dist(ai, goal, distResNear, distResFar, oddsResNear, oddsResFar)
if ResBehavID == 1 then
goal:AddSubGoal(GOAL_COMMON_SidewayMove, 3, TARGET_ENE_0, ai:GetRandam_Int(0, 1), ai:GetRandam_Int(30, 45), true, true, 9910)
return true
elseif ResBehavID == 2 then
goal:AddSubGoal(GOAL_COMMON_SidewayMove, 3, TARGET_ENE_0, ai:GetRandam_Int(0, 1), ai:GetRandam_Int(30, 45), true, true, 9910)
return true
else
local oddsResponse = 20
local bkStepPer = 40
local leftStepPer = 30
local rightStepPer = 30
local safetyDist = 3.5
if RebByOpGuard_Step(ai, goal, oddsResponse, bkStepPer, leftStepPer, rightStepPer, safetyDist) then
return true
else
return false
end
end
end
end
end
return
| 0 | 0.749826 | 1 | 0.749826 | game-dev | MEDIA | 0.907727 | game-dev | 0.781743 | 1 | 0.781743 |
HbmMods/Hbm-s-Nuclear-Tech-GIT | 1,502 | src/main/java/api/hbm/item/IGasMask.java | package api.hbm.item;
import java.util.ArrayList;
import com.hbm.util.ArmorRegistry.HazardClass;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
public interface IGasMask {
/**
* Returns a list of HazardClasses which can not be protected against by this mask (e.g. chlorine gas for half masks)
* @param stack
* @param entity
* @return an empty list if there's no blacklist
*/
public ArrayList<HazardClass> getBlacklist(ItemStack stack, EntityLivingBase entity);
/**
* Returns the loaded filter, if there is any
* @param stack
* @param entity
* @return null if no filter is installed
*/
public ItemStack getFilter(ItemStack stack, EntityLivingBase entity);
/**
* Checks whether the provided filter can be screwed into the mask, does not take already applied filters into account (those get ejected)
* @param stack
* @param entity
* @param filter
* @return
*/
public boolean isFilterApplicable(ItemStack stack, EntityLivingBase entity, ItemStack filter);
/**
* This will write the filter to the stack's NBT, it ignores any previously installed filter and won't eject those
* @param stack
* @param entity
* @param filter
*/
public void installFilter(ItemStack stack, EntityLivingBase entity, ItemStack filter);
/**
* Damages the installed filter, if there is one
* @param stack
* @param entity
* @param damage
*/
public void damageFilter(ItemStack stack, EntityLivingBase entity, int damage);
}
| 0 | 0.775286 | 1 | 0.775286 | game-dev | MEDIA | 0.642532 | game-dev | 0.591235 | 1 | 0.591235 |
Minecraft-LightLand/Youkai-Homecoming | 1,226 | src/main/java/dev/xkmc/youkaishomecoming/mixin/CopyMealFunctionMixin.java | package dev.xkmc.youkaishomecoming.mixin;
import dev.xkmc.youkaishomecoming.content.pot.base.BasePotBlockEntity;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import vectorwing.farmersdelight.common.loot.function.CopyMealFunction;
@Mixin(CopyMealFunction.class)
public class CopyMealFunctionMixin {
@Inject(at = @At("HEAD"), method = "run", cancellable = true)
public void youkaishomecoming$run(ItemStack stack, LootContext context, CallbackInfoReturnable<ItemStack> cir) {
BlockEntity tile = context.getParamOrNull(LootContextParams.BLOCK_ENTITY);
if (tile instanceof BasePotBlockEntity be) {
CompoundTag tag = be.writeMeal(new CompoundTag());
if (!tag.isEmpty()) {
stack.addTagElement("BlockEntityTag", tag);
}
cir.setReturnValue(stack);
}
}
}
| 0 | 0.905359 | 1 | 0.905359 | game-dev | MEDIA | 0.998693 | game-dev | 0.935888 | 1 | 0.935888 |
thedarkcolour/ForestryCE | 2,229 | src/main/java/forestry/core/owner/OwnerHandler.java | /*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.core.owner;
import com.mojang.authlib.GameProfile;
import forestry.api.core.INbtReadable;
import forestry.api.core.INbtWritable;
import forestry.core.network.IStreamable;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.network.FriendlyByteBuf;
import javax.annotation.Nullable;
import java.util.UUID;
public class OwnerHandler implements IOwnerHandler, IStreamable, INbtWritable, INbtReadable {
@Nullable
private GameProfile owner = null;
@Override
@Nullable
public GameProfile getOwner() {
return this.owner;
}
@Override
public void setOwner(GameProfile owner) {
this.owner = owner;
}
@Override
public void writeData(FriendlyByteBuf data) {
if (this.owner == null) {
data.writeBoolean(false);
} else {
data.writeBoolean(true);
data.writeLong(this.owner.getId().getMostSignificantBits());
data.writeLong(this.owner.getId().getLeastSignificantBits());
data.writeUtf(this.owner.getName());
}
}
@Override
public void readData(FriendlyByteBuf data) {
if (data.readBoolean()) {
GameProfile owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUtf());
setOwner(owner);
}
}
@Override
public void read(CompoundTag data) {
if (data.contains("owner")) {
GameProfile owner = NbtUtils.readGameProfile(data.getCompound("owner"));
if (owner != null) {
setOwner(owner);
}
}
}
@Override
public CompoundTag write(CompoundTag data) {
if (this.owner != null) {
CompoundTag nbt = new CompoundTag();
NbtUtils.writeGameProfile(nbt, this.owner);
data.put("owner", nbt);
}
return data;
}
}
| 0 | 0.713387 | 1 | 0.713387 | game-dev | MEDIA | 0.966932 | game-dev | 0.827307 | 1 | 0.827307 |
snozbot/fungus | 1,324 | Assets/Fungus/Scripts/Commands/Collection/CollectionCommandAddAll.cs | // This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
namespace Fungus
{
/// <summary>
/// Add all items in given rhs collection to target collection
/// </summary>
[CommandInfo("Collection",
"Add All",
"Add all items in given rhs collection to target collection")]
[AddComponentMenu("")]
public class CollectionCommandAddAll : CollectionBaseTwoCollectionCommand
{
[Tooltip("Only add if the item does not already exist in the collection")]
[SerializeField]
protected BooleanData onlyIfUnique = new BooleanData(false);
protected override void OnEnterInner()
{
if (onlyIfUnique.Value)
collection.Value.AddUnique(rhsCollection);
else
collection.Value.Add(rhsCollection);
}
public override bool HasReference(Variable variable)
{
return onlyIfUnique.booleanRef == variable || base.HasReference(variable);
}
public override string GetSummary()
{
return base.GetSummary() + (onlyIfUnique.Value ? " Unique" : "");
}
}
} | 0 | 0.811329 | 1 | 0.811329 | game-dev | MEDIA | 0.354611 | game-dev | 0.713145 | 1 | 0.713145 |
jlnaudin/x-drone | 5,057 | MissionPlanner-master/ExtLibs/GeoUtility/Transformation/UTMMGR.cs | //===================================================================================================
// Source Control URL : $HeadURL: file:///D:/svn/branch/3.1.7.0/GeoUtility/Transformation/UTMMGR.cs $
// Last changed by : $LastChangedBy: sh $
// Revision : $LastChangedRevision: 255 $
// Last changed date : $LastChangedDate: 2011-04-30 11:15:00 +0200 (Sat, 30. Apr 2011) $
// Author : $Author: sh $
// Copyright : Copyight (c) 2009-2011 Steffen Habermehl
// Contact : geoutility@freenet.de
// License : GNU GENERAL PUBLIC LICENSE Ver. 3, GPLv3
// 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/>.
//
// File description : Klasse Transformation, Funktion: UTMMGR
//===================================================================================================
using System;
using GeoUtility.GeoSystem;
namespace GeoUtility
{
internal partial class Transformation
{
/// <summary><para>Die Funktion wandelt zivile UTM Koordinaten in militärische Koordinaten um.
/// <para>Die Funktion ist nur für interne Berechnungen bestimmt.</para></para></summary>
/// <remarks><para>
/// Hintergründe zum Problem der Koordinatentransformationen sowie entsprechende mathematische
/// Formeln können den einschlägigen Fachbüchern oder dem Internet entnommen werden.<p />
/// Quellen:
/// Bundesamt für Kartographie und Geodäsie<br />
/// <a href="http://www.bkg.bund.de" target="_blank">http://www.bkg.bund.de</a><br />
/// <a href="http://crs.bkg.bund.de" target="_blank">http://crs.bkg.bund.de</a><br />
/// </para></remarks>
///
/// <param name="utm">Ein <see cref="GeoUtility.GeoSystem.UTM"/>-Objekt.</param>
/// <returns>Ein <see cref="GeoUtility.GeoSystem.MGRS"/>-Objekt (UTMREF/MGRS).</returns>
internal MGRS UTMMGR(UTM utm)
{
int zone = utm.Zone;
string band = utm.Band;
char cz2 = band.ToCharArray()[0];
char[] sep = { ',', '.' };
// Die höchsten Stellen der East und North Koordinate werden für die Berechnung des Planquadrates benötigt.
string e = utm.EastString.Split(sep)[0];
int east_plan = int.Parse(e.Substring(0, 1)); // 1. Stelle des Ostwertes
string n = utm.NorthString.Split(sep)[0];
int north_plan = int.Parse(n.Substring(0, 2)); // 1. und 2. Stelle des Nordwertes
// East Koordinate
string east = ((int)Math.Round(utm.East)).ToString();
if (east.Length > 2) east = east.Remove(0, 1);
// North Koordinate
string north = ((int)Math.Round(utm.North)).ToString();
if (north.Length > 2) north = north.Remove(0, 2);
// Anzahl Stellen bei East und North müssen gleich sein
if (east.Length < north.Length)
{
east = east.PadLeft(north.Length, '0');
}
else if (north.Length < east.Length)
{
north = north.PadLeft(east.Length, '0');
}
if (zone < MIN_ZONE || zone > MAX_ZONE || cz2 < MIN_BAND || cz2 > MAX_BAND)
{
throw new ErrorProvider.GeoException(new ErrorProvider.ErrorMessage("ERROR_UTM_ZONE"));
}
// Berechnung des Indexes für die Ost-Planquadrat Komponente
int eastgrid = 0;
int i = zone % 3;
if (i == 1) eastgrid = east_plan - 1;
if (i == 2) eastgrid = east_plan + 7;
if (i == 0) eastgrid = east_plan + 15;
// Berechnung des Indexes für die Nord-Planquadrat Komponente
int northgrid = 0;
i = zone % 2;
if (i != 1) northgrid = 5;
i = north_plan;
while (i - 20 >= 0)
{
i = i - 20;
}
northgrid += i;
if (northgrid > 19) northgrid = northgrid - 20;
// Planquadrat aus den vorher berechneten Indizes zusammensetzen
string plan = MGRS_EAST.Substring(eastgrid, 1) + MGRS_NORTH1.Substring(northgrid, 1);
return new MGRS(utm.Zone, utm.Band, plan, double.Parse(east), double.Parse(north));
}
}
}
| 0 | 0.884589 | 1 | 0.884589 | game-dev | MEDIA | 0.511636 | game-dev | 0.940553 | 1 | 0.940553 |
remindmodel/remind | 3,111 | modules/51_internalizeDamages/TCitr/postsolve.gms | *** | (C) 2006-2024 Potsdam Institute for Climate Impact Research (PIK)
*** | authors, and contributors see CITATION.cff file. This file is part
*** | of REMIND and licensed under AGPL-3.0-or-later. Under Section 7 of
*** | AGPL-3.0, you are granted additional permissions described in the
*** | REMIND License Exception, version 1.0 (see LICENSE file).
*** | Contact: remind@pik-potsdam.de
*** SOF ./modules/51_internalizeDamages/TCitr/postsolve.gms
* this is the third sum in Eq. (1). computed seperately for computational effectiveness. (this is still expensive, at a couple of seconds!)
p51_marginalDamageCumul(tall,tall2,iso) = 0;
p51_marginalDamageCumul(tall,tall2,isoTC)$((tall2.val ge tall.val) and (tall.val le 2250) and (tall2.val le 2250)) =
sum(tall3$((tall3.val ge tall.val) and (tall3.val le tall2.val)),
pm_temperatureImpulseResponseCO2(tall3,tall) * pm_damageMarginal(tall3,isoTC)
/ (1+pm_damageGrowthRateIso(tall3,isoTC))*(-1)
)
;
p51_sccLastItr(tall) = p51_scc(tall);
p51_sccParts(tall,tall2,regi2) = 0;
p51_sccParts(tall,tall2,regi2)$((tall.val ge 2010) and (tall.val le 2150) and (tall2.val ge tall.val) and (tall2.val le 2250)) =
* sum(regi2isoTC(regi2,isoTC),
* p50_damage(tall2,isoTC) * pm_GDPGrossIso(tall2,isoTC) * p51_marginalDamageCumul(tall,tall2,isoTC)
sum(regi2iso(regi2,iso),
pm_damageIso(tall2,iso) * pm_GDPGrossIso(tall2,iso) * p51_marginalDamageCumul(tall,tall2,iso)
)
;
p51_scc(tall)$((tall.val ge 2020) and (tall.val le 2150)) = 1000 *
sum(regi2,
sum(tall2$( (tall2.val ge tall.val) and (tall2.val le (tall.val + cm_damages_SccHorizon))), !! add this for limiting horizon of damage consideration: and (tall2.val le 2150)
(1 + pm_prtp(regi2) )**(-(tall2.val - tall.val))
* (pm_consPC(tall,regi2)/(pm_consPC(tall2,regi2) + sm_eps))**(1/pm_ies(regi2))
* p51_sccParts(tall,tall2,regi2)
)
)
;
*if(cm_iterative_target_adj eq 10 and cm_emiscen eq 9 and mod(iteration.val,2) eq 1, !! update only every uneven iteration to prevent zig-zagging
*p51_scc(tall) = p51_sccLastItr(tall) * max(0, min(1.4,max(0.6, (p51_scc(tall)/max(p51_sccLastItr(tall),1e-8))**0.7 )));
p51_scc(tall) = p51_sccLastItr(tall) * min(max( (p51_scc(tall)/max(p51_sccLastItr(tall),1e-8)),1 - 0.5*0.95**iteration.val),1 + 0.95**iteration.val);
pm_taxCO2eqSCC(ttot,regi) = 0;
pm_taxCO2eqSCC(t,regi)$(t.val ge 2025) = max(0, p51_scc(t) * sm_c_2_co2/1000);
*);
*optional: prevent drastic decline towards the final periods
*pm_taxCO2eqSCC(ttot,regi)$(ttot.val gt 2100) = pm_taxCO2eqSCC("2100",regi);
*optional: dampen price adjustment to ease convergence
*pm_taxCO2eqSCC(ttot,regi)$(ttot.val gt 2110) = pm_taxCO2eqSCC("2110",regi) + (ttot.val - 2110) * (pm_taxCO2eqSCC("2110",regi) - pm_taxCO2eqSCC("2100",regi))/10;
display p51_scc,pm_taxCO2eqSCC;
* convergence indicator:
pm_sccConvergenceMaxDeviation = 100 * smax(tall$(tall.val ge cm_startyear and tall.val lt 2150),abs(p51_scc(tall)/max(p51_sccLastItr(tall),1e-8) - 1) );
display pm_sccConvergenceMaxDeviation;
*** EOF ./modules/51_internalizeDamages/TCitr/postsolve.gms
| 0 | 0.557855 | 1 | 0.557855 | game-dev | MEDIA | 0.486865 | game-dev | 0.632158 | 1 | 0.632158 |
qnpiiz/rich-2.0 | 3,248 | src/main/java/net/minecraft/client/particle/PortalParticle.java | package net.minecraft.client.particle;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.particles.BasicParticleType;
public class PortalParticle extends SpriteTexturedParticle
{
private final double portalPosX;
private final double portalPosY;
private final double portalPosZ;
protected PortalParticle(ClientWorld world, double x, double y, double z, double motionX, double motionY, double motionZ)
{
super(world, x, y, z);
this.motionX = motionX;
this.motionY = motionY;
this.motionZ = motionZ;
this.posX = x;
this.posY = y;
this.posZ = z;
this.portalPosX = this.posX;
this.portalPosY = this.posY;
this.portalPosZ = this.posZ;
this.particleScale = 0.1F * (this.rand.nextFloat() * 0.2F + 0.5F);
float f = this.rand.nextFloat() * 0.6F + 0.4F;
this.particleRed = f * 0.9F;
this.particleGreen = f * 0.3F;
this.particleBlue = f;
this.maxAge = (int)(Math.random() * 10.0D) + 40;
}
public IParticleRenderType getRenderType()
{
return IParticleRenderType.PARTICLE_SHEET_OPAQUE;
}
public void move(double x, double y, double z)
{
this.setBoundingBox(this.getBoundingBox().offset(x, y, z));
this.resetPositionToBB();
}
public float getScale(float scaleFactor)
{
float f = ((float)this.age + scaleFactor) / (float)this.maxAge;
f = 1.0F - f;
f = f * f;
f = 1.0F - f;
return this.particleScale * f;
}
public int getBrightnessForRender(float partialTick)
{
int i = super.getBrightnessForRender(partialTick);
float f = (float)this.age / (float)this.maxAge;
f = f * f;
f = f * f;
int j = i & 255;
int k = i >> 16 & 255;
k = k + (int)(f * 15.0F * 16.0F);
if (k > 240)
{
k = 240;
}
return j | k << 16;
}
public void tick()
{
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
if (this.age++ >= this.maxAge)
{
this.setExpired();
}
else
{
float f = (float)this.age / (float)this.maxAge;
float f1 = -f + f * f * 2.0F;
float f2 = 1.0F - f1;
this.posX = this.portalPosX + this.motionX * (double)f2;
this.posY = this.portalPosY + this.motionY * (double)f2 + (double)(1.0F - f);
this.posZ = this.portalPosZ + this.motionZ * (double)f2;
}
}
public static class Factory implements IParticleFactory<BasicParticleType>
{
private final IAnimatedSprite spriteSet;
public Factory(IAnimatedSprite spriteSet)
{
this.spriteSet = spriteSet;
}
public Particle makeParticle(BasicParticleType typeIn, ClientWorld worldIn, double x, double y, double z, double xSpeed, double ySpeed, double zSpeed)
{
PortalParticle portalparticle = new PortalParticle(worldIn, x, y, z, xSpeed, ySpeed, zSpeed);
portalparticle.selectSpriteRandomly(this.spriteSet);
return portalparticle;
}
}
}
| 0 | 0.767247 | 1 | 0.767247 | game-dev | MEDIA | 0.761658 | game-dev,graphics-rendering | 0.949416 | 1 | 0.949416 |
cinder/Cinder | 13,171 | blocks/Box2D/src/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Joints/b2RevoluteJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2TimeStep.h>
// Point-to-point constraint
// C = p2 - p1
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Motor constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor)
{
bodyA = bA;
bodyB = bB;
localAnchorA = bodyA->GetLocalPoint(anchor);
localAnchorB = bodyB->GetLocalPoint(anchor);
referenceAngle = bodyB->GetAngle() - bodyA->GetAngle();
}
b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def)
: b2Joint(def)
{
m_localAnchorA = def->localAnchorA;
m_localAnchorB = def->localAnchorB;
m_referenceAngle = def->referenceAngle;
m_impulse.SetZero();
m_motorImpulse = 0.0f;
m_lowerAngle = def->lowerAngle;
m_upperAngle = def->upperAngle;
m_maxMotorTorque = def->maxMotorTorque;
m_motorSpeed = def->motorSpeed;
m_enableLimit = def->enableLimit;
m_enableMotor = def->enableMotor;
m_limitState = e_inactiveLimit;
}
void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 cB = data.positions[m_indexB].c;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
bool fixedRotation = (iA + iB == 0.0f);
m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB;
m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB;
m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB;
m_mass.ex.y = m_mass.ey.x;
m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB;
m_mass.ez.y = m_rA.x * iA + m_rB.x * iB;
m_mass.ex.z = m_mass.ez.x;
m_mass.ey.z = m_mass.ez.y;
m_mass.ez.z = iA + iB;
m_motorMass = iA + iB;
if (m_motorMass > 0.0f)
{
m_motorMass = 1.0f / m_motorMass;
}
if (m_enableMotor == false || fixedRotation)
{
m_motorImpulse = 0.0f;
}
if (m_enableLimit && fixedRotation == false)
{
float32 jointAngle = aB - aA - m_referenceAngle;
if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop)
{
m_limitState = e_equalLimits;
}
else if (jointAngle <= m_lowerAngle)
{
if (m_limitState != e_atLowerLimit)
{
m_impulse.z = 0.0f;
}
m_limitState = e_atLowerLimit;
}
else if (jointAngle >= m_upperAngle)
{
if (m_limitState != e_atUpperLimit)
{
m_impulse.z = 0.0f;
}
m_limitState = e_atUpperLimit;
}
else
{
m_limitState = e_inactiveLimit;
m_impulse.z = 0.0f;
}
}
else
{
m_limitState = e_inactiveLimit;
}
if (data.step.warmStarting)
{
// Scale impulses to support a variable time step.
m_impulse *= data.step.dtRatio;
m_motorImpulse *= data.step.dtRatio;
b2Vec2 P(m_impulse.x, m_impulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z);
}
else
{
m_impulse.SetZero();
m_motorImpulse = 0.0f;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
bool fixedRotation = (iA + iB == 0.0f);
// Solve motor constraint.
if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false)
{
float32 Cdot = wB - wA - m_motorSpeed;
float32 impulse = -m_motorMass * Cdot;
float32 oldImpulse = m_motorImpulse;
float32 maxImpulse = data.step.dt * m_maxMotorTorque;
m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_motorImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve limit constraint.
if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false)
{
b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
float32 Cdot2 = wB - wA;
b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2);
b2Vec3 impulse = -m_mass.Solve33(Cdot);
if (m_limitState == e_equalLimits)
{
m_impulse += impulse;
}
else if (m_limitState == e_atLowerLimit)
{
float32 newImpulse = m_impulse.z + impulse.z;
if (newImpulse < 0.0f)
{
b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y);
b2Vec2 reduced = m_mass.Solve22(rhs);
impulse.x = reduced.x;
impulse.y = reduced.y;
impulse.z = -m_impulse.z;
m_impulse.x += reduced.x;
m_impulse.y += reduced.y;
m_impulse.z = 0.0f;
}
else
{
m_impulse += impulse;
}
}
else if (m_limitState == e_atUpperLimit)
{
float32 newImpulse = m_impulse.z + impulse.z;
if (newImpulse > 0.0f)
{
b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y);
b2Vec2 reduced = m_mass.Solve22(rhs);
impulse.x = reduced.x;
impulse.y = reduced.y;
impulse.z = -m_impulse.z;
m_impulse.x += reduced.x;
m_impulse.y += reduced.y;
m_impulse.z = 0.0f;
}
else
{
m_impulse += impulse;
}
}
b2Vec2 P(impulse.x, impulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + impulse.z);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + impulse.z);
}
else
{
// Solve point-to-point constraint
b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
b2Vec2 impulse = m_mass.Solve22(-Cdot);
m_impulse.x += impulse.x;
m_impulse.y += impulse.y;
vA -= mA * impulse;
wA -= iA * b2Cross(m_rA, impulse);
vB += mB * impulse;
wB += iB * b2Cross(m_rB, impulse);
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data)
{
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 cB = data.positions[m_indexB].c;
float32 aB = data.positions[m_indexB].a;
b2Rot qA(aA), qB(aB);
float32 angularError = 0.0f;
float32 positionError = 0.0f;
bool fixedRotation = (m_invIA + m_invIB == 0.0f);
// Solve angular limit constraint.
if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false)
{
float32 angle = aB - aA - m_referenceAngle;
float32 limitImpulse = 0.0f;
if (m_limitState == e_equalLimits)
{
// Prevent large angular corrections
float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection);
limitImpulse = -m_motorMass * C;
angularError = b2Abs(C);
}
else if (m_limitState == e_atLowerLimit)
{
float32 C = angle - m_lowerAngle;
angularError = -C;
// Prevent large angular corrections and allow some slop.
C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f);
limitImpulse = -m_motorMass * C;
}
else if (m_limitState == e_atUpperLimit)
{
float32 C = angle - m_upperAngle;
angularError = C;
// Prevent large angular corrections and allow some slop.
C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection);
limitImpulse = -m_motorMass * C;
}
aA -= m_invIA * limitImpulse;
aB += m_invIB * limitImpulse;
}
// Solve point-to-point constraint.
{
qA.Set(aA);
qB.Set(aB);
b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
b2Vec2 C = cB + rB - cA - rA;
positionError = C.Length();
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
b2Mat22 K;
K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y;
K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x;
b2Vec2 impulse = -K.Solve(C);
cA -= mA * impulse;
aA -= iA * b2Cross(rA, impulse);
cB += mB * impulse;
aB += iB * b2Cross(rB, impulse);
}
data.positions[m_indexA].c = cA;
data.positions[m_indexA].a = aA;
data.positions[m_indexB].c = cB;
data.positions[m_indexB].a = aB;
return positionError <= b2_linearSlop && angularError <= b2_angularSlop;
}
b2Vec2 b2RevoluteJoint::GetAnchorA() const
{
return m_bodyA->GetWorldPoint(m_localAnchorA);
}
b2Vec2 b2RevoluteJoint::GetAnchorB() const
{
return m_bodyB->GetWorldPoint(m_localAnchorB);
}
b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const
{
b2Vec2 P(m_impulse.x, m_impulse.y);
return inv_dt * P;
}
float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const
{
return inv_dt * m_impulse.z;
}
float32 b2RevoluteJoint::GetJointAngle() const
{
b2Body* bA = m_bodyA;
b2Body* bB = m_bodyB;
return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle;
}
float32 b2RevoluteJoint::GetJointSpeed() const
{
b2Body* bA = m_bodyA;
b2Body* bB = m_bodyB;
return bB->m_angularVelocity - bA->m_angularVelocity;
}
bool b2RevoluteJoint::IsMotorEnabled() const
{
return m_enableMotor;
}
void b2RevoluteJoint::EnableMotor(bool flag)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_enableMotor = flag;
}
float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const
{
return inv_dt * m_motorImpulse;
}
void b2RevoluteJoint::SetMotorSpeed(float32 speed)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_motorSpeed = speed;
}
void b2RevoluteJoint::SetMaxMotorTorque(float32 torque)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_maxMotorTorque = torque;
}
bool b2RevoluteJoint::IsLimitEnabled() const
{
return m_enableLimit;
}
void b2RevoluteJoint::EnableLimit(bool flag)
{
if (flag != m_enableLimit)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_enableLimit = flag;
m_impulse.z = 0.0f;
}
}
float32 b2RevoluteJoint::GetLowerLimit() const
{
return m_lowerAngle;
}
float32 b2RevoluteJoint::GetUpperLimit() const
{
return m_upperAngle;
}
void b2RevoluteJoint::SetLimits(float32 lower, float32 upper)
{
b2Assert(lower <= upper);
if (lower != m_lowerAngle || upper != m_upperAngle)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_impulse.z = 0.0f;
m_lowerAngle = lower;
m_upperAngle = upper;
}
}
void b2RevoluteJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Log(" b2RevoluteJointDef jd;\n");
b2Log(" jd.bodyA = bodies[%d];\n", indexA);
b2Log(" jd.bodyB = bodies[%d];\n", indexB);
b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y);
b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y);
b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle);
b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit);
b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle);
b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle);
b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor);
b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed);
b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| 0 | 0.973226 | 1 | 0.973226 | game-dev | MEDIA | 0.929009 | game-dev | 0.989381 | 1 | 0.989381 |
cmss13-devs/cmss13 | 6,097 | code/game/machinery/iv_drip.dm | /obj/structure/machinery/iv_drip
name = "\improper IV drip"
icon = 'icons/obj/structures/machinery/iv_drip.dmi'
anchored = FALSE
density = FALSE
drag_delay = 1
base_pixel_x = 15
base_pixel_y = -2
var/mob/living/carbon/attached = null
var/mode = 1 // 1 is injecting, 0 is taking blood.
var/obj/item/reagent_container/beaker = null
var/datum/beam/current_beam
//make it so that IV doesn't require power to function.
use_power = USE_POWER_NONE
needs_power = FALSE
/obj/structure/machinery/iv_drip/update_icon()
if(attached)
icon_state = "hooked"
else
icon_state = ""
overlays = null
if(beaker)
var/datum/reagents/reagents = beaker.reagents
if(reagents.total_volume)
var/image/filling = image('icons/obj/structures/machinery/iv_drip.dmi', src, "reagent")
var/percent = floor((reagents.total_volume / beaker.volume) * 100)
switch(percent)
if(0 to 9)
filling.icon_state = "reagent0"
if(10 to 24)
filling.icon_state = "reagent10"
if(25 to 49)
filling.icon_state = "reagent25"
if(50 to 74)
filling.icon_state = "reagent50"
if(75 to 79)
filling.icon_state = "reagent75"
if(80 to 90)
filling.icon_state = "reagent80"
if(91 to INFINITY)
filling.icon_state = "reagent100"
filling.color = mix_color_from_reagents(reagents.reagent_list)
overlays += filling
/obj/structure/machinery/iv_drip/proc/update_beam()
if(current_beam && !attached)
QDEL_NULL(current_beam)
else if(!current_beam && attached && !QDELETED(src))
current_beam = beam(attached, "iv_tube")
/obj/structure/machinery/iv_drip/Destroy()
attached?.active_transfusions -= src
attached = null
update_beam()
. = ..()
/obj/structure/machinery/iv_drip/MouseDrop(over_object, src_location, over_location)
..()
if(ishuman(usr))
var/mob/living/carbon/human/user = usr
if(user.is_mob_incapacitated() || get_dist(user, src) > 1 || user.blinded)
return
if(!skillcheck(user, SKILL_SURGERY, SKILL_SURGERY_NOVICE))
to_chat(user, SPAN_WARNING("You don't know how to [attached ? "disconnect" : "connect"] this!"))
return
if(attached)
user.visible_message("[user] detaches \the [src] from \the [attached].",
"You detach \the [src] from \the [attached].")
attached.active_transfusions -= src
attached = null
update_beam()
update_icon()
stop_processing()
return
if(in_range(src, usr) && iscarbon(over_object) && get_dist(over_object, src) <= 1)
user.visible_message("[user] attaches \the [src] to \the [over_object].",
"You attach \the [src] to \the [over_object].")
attached = over_object
attached.active_transfusions += src
update_beam()
update_icon()
start_processing()
/obj/structure/machinery/iv_drip/attackby(obj/item/container, mob/living/user)
if (istype(container, /obj/item/reagent_container))
if(beaker)
to_chat(user, SPAN_WARNING("There is already a reagent container loaded!"))
return
if((!istype(container, /obj/item/reagent_container/blood) && !istype(container, /obj/item/reagent_container/glass)) || istype(container, /obj/item/reagent_container/glass/bucket))
to_chat(user, SPAN_WARNING("That won't fit!"))
return
if(user.drop_inv_item_to_loc(container, src))
beaker = container
var/reagentnames = ""
for(var/datum/reagent/chem in beaker.reagents.reagent_list)
reagentnames += ";[chem.name]"
log_admin("[key_name(user)] put \a [beaker] into [src], containing [reagentnames] at ([src.loc.x],[src.loc.y],[src.loc.z]).")
to_chat(user, "You attach \the [container] to \the [src].")
update_beam()
update_icon()
return
else
return ..()
/obj/structure/machinery/iv_drip/process()
if(src.attached)
if(!(get_dist(src, src.attached) <= 1 && isturf(src.attached.loc)))
visible_message("The needle is ripped out of [src.attached], doesn't that hurt?")
attached.apply_damage(3, BRUTE, pick("r_arm", "l_arm"))
if(attached.pain.feels_pain)
attached.emote("scream")
attached.active_transfusions -= src
attached = null
update_beam()
update_icon()
stop_processing()
return
if(attached && beaker)
// Give blood
if(mode)
if(beaker.volume > 0)
var/transfer_amount = REAGENTS_METABOLISM
if(istype(src.beaker, /obj/item/reagent_container/blood))
// speed up transfer on blood packs
transfer_amount = 4
attached.inject_blood(beaker, transfer_amount)
update_icon()
// Take blood
else
var/amount = beaker.reagents.maximum_volume - beaker.reagents.total_volume
amount = min(amount, 4)
// If the beaker is full, ping
if(amount == 0)
if(prob(5))
visible_message("\The [src] pings.")
return
var/mob/living/carbon/patient = attached
if(!istype(patient))
return
if(ishuman(patient))
var/mob/living/carbon/human/human_patient = patient
if(human_patient.species && human_patient.species.flags & NO_BLOOD)
return
// If the human is losing too much blood, beep.
if(patient.blood_volume < BLOOD_VOLUME_SAFE && prob(5))
visible_message("\The [src] beeps loudly.")
patient.take_blood(beaker,amount)
update_icon()
/obj/structure/machinery/iv_drip/attack_hand(mob/user as mob)
if(src.beaker)
src.beaker.forceMove(get_turf(src))
src.beaker = null
update_icon()
else
return ..()
/obj/structure/machinery/iv_drip/verb/toggle_mode()
set category = "Object"
set name = "Toggle Mode"
set src in view(1)
if(!istype(usr, /mob/living))
return
if(usr.stat || usr.is_mob_incapacitated())
return
mode = !mode
to_chat(usr, "The IV drip is now [mode ? "injecting" : "taking blood"].")
/obj/structure/machinery/iv_drip/get_examine_text(mob/user)
. = ..()
. += "The IV drip is [mode ? "injecting" : "taking blood"]."
if(beaker)
if(beaker.reagents && length(beaker.reagents.reagent_list))
. += SPAN_NOTICE(" Attached is \a [beaker] with [beaker.reagents.total_volume] units of liquid.")
else
. += SPAN_NOTICE(" Attached is an empty [beaker].")
else
. += SPAN_NOTICE(" No chemicals are attached.")
. += SPAN_NOTICE(" [attached ? attached : "No one"] is attached.")
| 0 | 0.94384 | 1 | 0.94384 | game-dev | MEDIA | 0.758462 | game-dev | 0.873825 | 1 | 0.873825 |
freeors/War-Of-Kingdom | 1,485 | kingdom-src/kingdom/kingdom/gui/dialogs/mp_create_game_set_password.cpp | /* $Id: mp_create_game_set_password.cpp 48936 2011-03-19 21:04:04Z mordante $ */
/*
Copyright (C) 2010 - 2011 by Ignacio Riquelme Morelle <shadowm2006@gmail.com>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
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.
See the COPYING file for more details.
*/
#define GETTEXT_DOMAIN "kingdom-lib"
#include "gui/dialogs/mp_create_game_set_password.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
namespace gui2 {
/*WIKI
* @page = GUIWindowDefinitionWML
* @order = 2_mp_create_game_set_password
*
* == Create Game: Set Password ==
*
* Dialog for setting a join password for MP games.
*
* @begin{table}{dialog_widgets}
*
* password & & text_box & m &
* Input field for the game password. $
*
* @end{table}
*/
REGISTER_DIALOG(mp_create_game_set_password)
tmp_create_game_set_password::tmp_create_game_set_password(
std::string& password)
{
register_text("password", true, password, true);
}
void tmp_create_game_set_password::pre_show(CVideo& /*video*/, twindow& window)
{
window.set_canvas_variable("border", variant("default-border"));
}
} // namespace gui2
| 0 | 0.678665 | 1 | 0.678665 | game-dev | MEDIA | 0.933482 | game-dev | 0.535719 | 1 | 0.535719 |
oceancx/CXEngine | 26,514 | scripts/client/addon/props.lua | local ui_is_show_props = false
function ui_toggle_show_props()
ui_is_show_props = not ui_is_show_props
return ui_is_show_props
end
local selected_actor_uid = 0
local edit_prop_lv = 0
local edit_health = 0
local edit_magic = 0
local edit_force = 0
local edit_stamina = 0
local edit_agility = 0
function draw_prop_bar(actor, prop, total, edit_prop)
local remain = total - edit_health - edit_magic - edit_force - edit_stamina - edit_agility
imgui.Text(prop[1].. ': '.. prop[3])
imgui.SameLine()
imgui.PushItemWidth(80)
local res
if remain+edit_prop == 0 then
res, edit_prop = imgui.DragInt('##bar'..prop[1], edit_prop, 1, -1, 0)
else
res, edit_prop = imgui.DragInt('##bar'..prop[1], edit_prop, 1, 0, remain + edit_prop)
end
imgui.PopItemWidth()
return edit_prop
end
function draw_prop_points_panel(actor, lv)
local res
local total = (lv+1) * 5
edit_health = actor:GetProperty(PROP_ASSIGN_HEALTH)
edit_magic = actor:GetProperty(PROP_ASSIGN_MAGIC)
edit_force = actor:GetProperty(PROP_ASSIGN_FORCE)
edit_stamina = actor:GetProperty(PROP_ASSIGN_STAMINA)
edit_agility = actor:GetProperty(PROP_ASSIGN_AGILITY)
imgui.BeginGroup()
imgui.Dummy(30,20)
local prop_bars = {
{'体质', PROP_ASSIGN_HEALTH, actor:GetHealthProp()},
{'魔力', PROP_ASSIGN_MAGIC, actor:GetMagicProp()},
{'力量', PROP_ASSIGN_FORCE, actor:GetForceProp()},
{'耐力', PROP_ASSIGN_STAMINA, actor:GetStaminaProp()},
{'敏捷', PROP_ASSIGN_AGILITY, actor:GetAgilityProp()},
}
edit_health = draw_prop_bar(actor, prop_bars[1], total, edit_health)
edit_magic = draw_prop_bar(actor, prop_bars[2], total, edit_magic)
edit_force = draw_prop_bar(actor, prop_bars[3], total, edit_force)
edit_stamina = draw_prop_bar(actor, prop_bars[4], total, edit_stamina)
edit_agility = draw_prop_bar(actor, prop_bars[5], total, edit_agility)
actor:SetProperty(PROP_ASSIGN_HEALTH, edit_health)
actor:SetProperty(PROP_ASSIGN_MAGIC, edit_magic)
actor:SetProperty(PROP_ASSIGN_FORCE, edit_force)
actor:SetProperty(PROP_ASSIGN_STAMINA, edit_stamina)
actor:SetProperty(PROP_ASSIGN_AGILITY, edit_agility)
imgui.EndGroup()
imgui.Text('剩余点:'.. actor:GetRemainPropPoints())
imgui.SameLine()
if imgui.Button('重新加点') then
net_manager_player_dostring(string.format([[
local actor = actor_manager_fetch_player_by_id(%d)
actor:ClearAssignPoints()
]], actor:GetID()))
end
imgui.SameLine()
if imgui.Button('确认加点') then
net_manager_player_dostring(string.format([[
local actor = actor_manager_fetch_player_by_id(%d)
actor:SetProperty(PROP_ASSIGN_HEALTH, %d)
actor:SetProperty(PROP_ASSIGN_MAGIC, %d)
actor:SetProperty(PROP_ASSIGN_FORCE, %d)
actor:SetProperty(PROP_ASSIGN_STAMINA, %d)
actor:SetProperty(PROP_ASSIGN_AGILITY, %d)
]], actor:GetID(), edit_health, edit_magic, edit_force, edit_stamina, edit_agility))
end
end
local prop_school_skill_lv_hp = 0
local prop_school_skill_lv_mp = 0
local prop_school_skill_lv_targethit = 0
local prop_school_skill_lv_damage = 0
local prop_school_skill_lv_defend = 0
local prop_school_skill_lv_spiritual = 0
local prop_school_skill_lv_speed = 0
local prop_school_skill_lv_dodge = 0
function draw_player_skill_bar(actor, bar)
local actor_lv = actor:GetProperty(PROP_LV)
imgui.PushItemWidth(50)
local res, lv = imgui.DragInt(bar[1].. '技能等级', actor:GetProperty(bar[2]) , 1.0, 0, actor_lv+10)
imgui.PopItemWidth()
if res then
actor:SetProperty(bar[2], lv)
net_manager_player_dostring(string.format([[
local actor = actor_manager_fetch_player_by_id(%d)
actor:SetProperty(%d, %d)
]], actor:GetID(), bar[2], lv))
end
end
local pannel = {
{'HP', PROP_SCHOOL_SKILL_LV_HP },
{'MP', PROP_SCHOOL_SKILL_LV_MP },
{'命中', PROP_SCHOOL_SKILL_LV_TARGETHIT },
{'伤害', PROP_SCHOOL_SKILL_LV_DAMAGE },
{'防御', PROP_SCHOOL_SKILL_LV_DEFEND },
{'灵力', PROP_SCHOOL_SKILL_LV_SPIRITUAL },
{'速度', PROP_SCHOOL_SKILL_LV_SPEED },
{'闪避', PROP_SCHOOL_SKILL_LV_DODGE },
}
function draw_player_skill_pannel(actor)
imgui.BeginGroup()
draw_player_skill_bar(actor, pannel[1])
draw_player_skill_bar(actor, pannel[2])
draw_player_skill_bar(actor, pannel[3])
draw_player_skill_bar(actor, pannel[4])
draw_player_skill_bar(actor, pannel[5])
draw_player_skill_bar(actor, pannel[6])
draw_player_skill_bar(actor, pannel[7])
draw_player_skill_bar(actor, pannel[8])
imgui.EndGroup()
end
function draw_player_equip_pannel(actor)
-- prop_equip_hp float 0 1
-- prop_equip_mp float 0 1
-- prop_equip_target float 0 1
-- prop_equip_damage float 0 1
-- prop_equip_defend float 0 1
-- prop_equip_spiritual float 0 1
-- prop_equip_agile float 0 1
imgui.Text('头盔')
imgui.Text('项链')
imgui.Text('武器')
imgui.Text('衣服')
imgui.Text('腰带')
imgui.Text('鞋子')
end
function draw_player_practice_lv(actor)
function draw_practice_lv_bar(label, enum)
local actor_lv = actor:GetProperty(PROP_LV)
imgui.PushItemWidth(50)
local res, lv = imgui.DragInt(label, actor:GetProperty(enum) , 1.0, 0, math.min(25,actor_lv//5-4))
imgui.PopItemWidth()
if res then
actor:SetProperty(enum, lv)
net_manager_player_dostring(string.format([[
local actor = actor_manager_fetch_player_by_id(%d)
actor:SetProperty(%d, %d)
]], actor:GetID(), enum, lv))
end
end
draw_practice_lv_bar('攻击修炼等级' , PROP_ATK_PRACTICE_SKILL_LV)
draw_practice_lv_bar('防御修炼等级' , PROP_ATK_RESISTANCE_SKILL_LV)
draw_practice_lv_bar('法术修炼等级' , PROP_SPELL_PRACTICE_SKILL_LV)
draw_practice_lv_bar('法抗修炼等级' , PROP_SPELL_RESISTANCE_SKILL_LV)
end
function actor_type_tostring(actor_type)
if actor_type == ACTOR_TYPE_PLAYER then
return '玩家'
elseif actor_type == ACTOR_TYPE_NPC then
return 'NPC'
elseif actor_type == ACTOR_TYPE_SUMMON then
return '召唤兽'
else
return '其他类型'
end
end
function fetch_weapon_keys(tbl, avatar_key)
local weapon_keys = {}
local strs= utils_string_split(avatar_key,'-')
local role_key , weapon_key = strs[1], strs[2]
for k, v in pairs(tbl) do
if role_key == v.role and weapon_key == v.type then
table.insert(weapon_keys,k)
end
end
table.sort(weapon_keys)
return weapon_keys
end
local team_info_select_actor
local ActorNameSB = imgui.CreateStrbuf('test',256)
function ui_show_props()
if not ui_is_show_props then return end
local player = actor_manager_fetch_local_player()
if not player then return end
imgui.Begin('ActorEditor')
imgui.BeginChild('LEFT_PANNEL#uishoprops',100)
local actors = actor_manager_fetch_all_actors()
local drawbutton = function(actor)
if imgui.Button(actor:GetName()..'##'..actor:GetID()) then
selected_actor_uid = actor:GetID()
prop_school_skill_lv_hp = actor:GetProperty(PROP_SCHOOL_SKILL_LV_HP)
prop_school_skill_lv_mp = actor:GetProperty(PROP_SCHOOL_SKILL_LV_MP)
prop_school_skill_lv_targethit = actor:GetProperty(PROP_SCHOOL_SKILL_LV_TARGETHIT)
prop_school_skill_lv_damage = actor:GetProperty(PROP_SCHOOL_SKILL_LV_DAMAGE)
prop_school_skill_lv_defend = actor:GetProperty(PROP_SCHOOL_SKILL_LV_DEFEND)
prop_school_skill_lv_spiritual = actor:GetProperty(PROP_SCHOOL_SKILL_LV_SPIRITUAL)
prop_school_skill_lv_speed = actor:GetProperty(PROP_SCHOOL_SKILL_LV_SPEED)
prop_school_skill_lv_dodge = actor:GetProperty(PROP_SCHOOL_SKILL_LV_DODGE)
prop_atk_practice_skill_lv = actor:GetProperty(PROP_ATK_PRACTICE_SKILL_LV)
prop_atk_resistance_skill_lv = actor:GetProperty(PROP_ATK_RESISTANCE_SKILL_LV)
prop_spell_practice_skill_lv = actor:GetProperty(PROP_SPELL_PRACTICE_SKILL_LV)
prop_spell_resistance_skill_lv = actor:GetProperty(PROP_SPELL_RESISTANCE_SKILL_LV)
ActorNameSB:reset(actor:GetName())
end
end
imgui.Text('玩家')
for i,actor in pairs(actors) do
if actor:IsPlayer() then
drawbutton(actor)
end
end
imgui.Text('召唤兽')
for i,actor in pairs(actors) do
if actor:IsSummon() then
drawbutton(actor)
end
end
imgui.EndChild()
local actor = actor_manager_fetch_player_by_id(selected_actor_uid)
if actor then
imgui.SameLine()
imgui.BeginChild('RightPanel##uiprops')
if imgui.Button('创建') then
local req = {}
req.pid = player:GetID()
req.props = actor:GetProperties()
net_send_message(PTO_C2S_CREATE_ACTOR, cjson.encode(req))
end
imgui.SameLine()
if imgui.Button('删除') then
net_send_message(PTO_C2S_DELETE_ACTOR, cjson.encode({
pid = player:GetID(),
delete_pid = actor:GetID()
}
))
selected_actor_uid = nil
imgui.EndChild()
imgui.End()
return
end
imgui.SameLine()
if imgui.Button('保存') then
net_send_message(PTO_C2C_SAVE_ACTORS, cjson.encode({}))
end
imgui.SameLine()
if imgui.Button('传送') then
net_manager_player_dostring(string.format([[
player:SetPos(%.f, %.f)
]], actor:GetPos()))
player:SetPos(actor:GetPos())
end
imgui.SameLine()
if imgui.Button('摆怪') then
local x,y = player:GetPos()
net_manager_actor_dostring(actor:GetID(),[[
actor:SetPos(%.f, %.f)
]],x,y)
actor:SetPos(player:GetPos())
end
imgui.SameLine()
if imgui.Button('SetLocal') then
actor_manager_set_local_player(actor:GetID())
end
imgui.PushItemWidth(100)
imgui.InputText("名字", ActorNameSB)
imgui.PopItemWidth()
imgui.SameLine()
if imgui.Button('改名##change_name') then
net_manager_actor_dostring(actor:GetID(),[[
actor:SetProperty(PROP_NAME, '%s')
]], ActorNameSB:str() )
end
imgui.Button('Actor类型')
imgui.SameLine()
local actor_type = actor:GetProperty(PROP_ACTOR_TYPE)
if imgui.RadioButton('玩家##TYPE_PLAYER', actor_type == ACTOR_TYPE_PLAYER) then
net_manager_actor_dostring(actor:GetID(),[[
actor:SetProperty(PROP_ACTOR_TYPE, %d)
]], ACTOR_TYPE_PLAYER)
end
imgui.SameLine()
if imgui.RadioButton('召唤兽##TYPE_SUMMON', actor_type == ACTOR_TYPE_SUMMON) then
net_manager_actor_dostring(actor:GetID(),[[
actor:SetProperty(PROP_ACTOR_TYPE, %d)
]], ACTOR_TYPE_SUMMON)
end
imgui.SameLine()
if imgui.RadioButton('其他类型##TYPE_OTHER',
actor_type~= ACTOR_TYPE_PLAYER
and actor_type ~= ACTOR_TYPE_SUMMON
and actor_type ~= ACTOR_TYPE_NPC
) then
net_manager_actor_dostring(actor:GetID(),[[
actor:SetProperty(PROP_ACTOR_TYPE, %d)
]], ACTOR_TYPE_DEFAULT)
end
if actor_type == ACTOR_TYPE_SUMMON then
local owner = actor:GetSummonOwner()
if owner then
imgui.Text('Owner:'..owner:GetName())
imgui.SameLine()
if imgui.Button('ClearOwner') then
net_manager_actor_dostring(actor:GetID(),[[
actor:RemoveSummonOwner()
]])
end
end
end
local auto_cmd = actor:GetProperty(PROP_IS_AUTO_COMMAND)
if imgui.Checkbox('自动战斗', auto_cmd) then
auto_cmd = not auto_cmd
net_manager_actor_dostring(actor:GetID(),[[
actor:SetProperty(PROP_IS_AUTO_COMMAND, %s)
]], auto_cmd)
end
if imgui.Button(actor:GetProperty(PROP_AVATAR_ID)) then
imgui.OpenPopup('PopupAvatar')
end
if imgui.BeginPopup('PopupAvatar') then
local avatar_tbl
if actor_type == ACTOR_TYPE_PLAYER then
avatar_tbl = content_system_get_table('avatar_role')
elseif actor_type == ACTOR_TYPE_SUMMON then
avatar_tbl = content_system_get_table('avatar_npc')
local tmp = {}
for id, row in pairs(avatar_tbl) do
if row.can_take == 1 then
tmp[row.ID] = row
end
end
avatar_tbl = tmp
end
local role_keys = utils_fetch_sort_keys(avatar_tbl)
imgui.HorizontalLayout(role_keys,next,function(k,v)
if imgui.Button(v ..'##rolekey') then
net_manager_actor_dostring(actor:GetID(),[[
actor:SetProperty(PROP_ACTOR_TYPE, %d)
actor:SetProperty(PROP_AVATAR_ID, '%s')
actor:SetProperty(PROP_WEAPON_AVATAR_ID,'')
]], actor_type, v)
imgui.CloseCurrentPopup()
end
end,300)
imgui.EndPopup()
end
if actor:IsPlayer() then
imgui.SameLine()
if imgui.Button(actor:GetProperty(PROP_WEAPON_AVATAR_ID)) then
imgui.OpenPopup('PopupWeaponAvatar')
end
if imgui.BeginPopup('PopupWeaponAvatar') then
local avatar_weapon_tbl = content_system_get_table('avatar_weapon')
local avatar_key = actor:GetProperty(PROP_AVATAR_ID)
local keys = fetch_weapon_keys(avatar_weapon_tbl,avatar_key)
imgui.HorizontalLayout(keys,next,function(k,v)
if imgui.Button(v ..'##weaponkey') then
net_manager_actor_dostring(actor:GetID(),[[
actor:SetProperty(PROP_WEAPON_AVATAR_ID,'%s')
]], v)
imgui.CloseCurrentPopup()
end
end,300)
imgui.EndPopup()
end
end
if actor:GetProperty(PROP_ACTOR_TYPE) == ACTOR_TYPE_PLAYER then
if imgui.Button('添加召唤兽') then
imgui.OpenPopup('PopupAddSummon')
end
if imgui.BeginPopup('PopupAddSummon') then
local actors = actor_manager_fetch_all_actors()
local all_summons = {}
for i,_actor_ in ipairs(actors) do
if _actor_:IsSummon() then
if not _actor_:GetSummonOwner() then
table.insert(all_summons, _actor_)
end
end
end
table.sort(all_summons, function(a,b) return a:GetID() < b:GetID() end)
imgui.HorizontalLayout(all_summons,next,function(k,v)
if imgui.Button(v:GetName()..'##summon'..v:GetID()) then
net_manager_actor_dostring(actor:GetID(),[[
local summon = actor_manager_fetch_player_by_id(%d)
if not summon then return end
summon:SetSummonOwner(actor)
local uids_str = actor:GetProperty(PROP_SUMMON_UIDS)
local uids = cjson.decode(uids_str)
table.insert(uids, summon:GetID())
actor:SetProperty(PROP_SUMMON_UIDS, cjson.encode(uids))
]], v:GetID())
imgui.CloseCurrentPopup()
end
end)
imgui.EndPopup()
end
imgui.SameLine()
if imgui.Button('移除召唤兽') then
imgui.OpenPopup('PopupRemoveSummon')
end
if imgui.BeginPopup('PopupRemoveSummon') then
local summons = actor:GetSummons()
imgui.HorizontalLayout(summons,next,function(k,v)
if imgui.Button(v:GetName()..'##'..v:GetID()) then
net_manager_actor_dostring(actor:GetID(),[[
local summon = actor_manager_fetch_player_by_id(%d)
if not summon then return end
local uids_str = actor:GetProperty(PROP_SUMMON_UIDS)
local uids = cjson.decode(uids_str)
if #uids == 0 then return end
for i,uid in pairs(uids) do
if uid == summon:GetID() then
table.remove(uids, i)
break
end
end
summon:RemoveSummonOwner()
actor:SetProperty(PROP_SUMMON_UIDS, cjson.encode(uids))
]], v:GetID())
imgui.CloseCurrentPopup()
end
end)
imgui.EndPopup()
end
imgui.SameLine()
if imgui.Button('清空召唤兽') then
net_manager_actor_dostring(actor:GetID(),[[
local summons = actor:GetSummons()
for i,summon in ipairs(summons) do
summon:RemoveSummonOwner()
end
actor:SetProperty(PROP_SUMMON_UIDS, '[]')
]])
end
imgui.Text('召唤兽信息')
local summons = actor:GetSummons()
imgui.HorizontalLayout(summons,next,function(k,v)
if imgui.Button(v:GetName()..'##summon info') then
end
end)
imgui.Button('队伍信息')
local team = actor:GetTeam()
if team then
imgui.Checkbox('队长', actor:IsTeamLeader())
imgui.SameLine()
for i, member in ipairs(team:GetMembers()) do
if imgui.Button(member:GetName()) then
team_info_select_actor = member
end
imgui.SameLine()
end
if imgui.Button('离队') then
if team_info_select_actor then
team_info_select_actor:LeaveTeam()
end
end
imgui.SameLine()
if imgui.Button('加人') then
imgui.OpenPopup('PopupTeamInfoAddMember')
end
if imgui.BeginPopup('PopupTeamInfoAddMember') then
local players = actor_manager_fetch_all_players()
imgui.HorizontalLayout(players,next,function(k,v)
local v_team = v:GetTeam()
if v_team then return end
if imgui.Button(v:GetName()..'##'..v:GetID()) then
-- if actor:IsTeamLeader() then
actor:AddTeamMember(v)
-- end
end
end)
imgui.EndPopup()
end
else
if imgui.Button('创建队伍') then
actor:CreateTeam()
end
end
end
edit_prop_lv = actor:GetProperty(PROP_LV)
imgui.PushItemWidth(80)
local lv_changed , new_prop_lv = imgui.DragInt('等级', edit_prop_lv)
imgui.PopItemWidth()
if lv_changed then
actor:SetProperty(PROP_LV, new_prop_lv)
net_manager_actor_dostring(actor:GetID(),[[
actor:SetProperty(PROP_LV, %d)
actor:ClearAssignPoints()
if actor:GetProperty(PROP_ACTOR_TYPE)==ACTOR_TYPE_SUMMON then
actor:ApplySummonQual('芙蓉仙子')
else
local lv = actor:GetProperty(PROP_LV)
actor:SetProperty(PROP_SCHOOL_SKILL_LV_TARGETHIT, lv)
actor:SetProperty(PROP_SCHOOL_SKILL_LV_DAMAGE, lv)
actor:SetProperty(PROP_SCHOOL_SKILL_LV_DEFEND, lv)
actor:SetProperty(PROP_SCHOOL_SKILL_LV_SPEED, lv)
actor:SetProperty(PROP_SCHOOL_SKILL_LV_DODGE, lv)
actor:SetProperty(PROP_SCHOOL_SKILL_LV_SPIRITUAL, lv)
actor:SetGlobalStandardEquip(lv)
end
actor:SetProperty(PROP_HP, actor:GetMaxHP())
]],new_prop_lv)
end
imgui.SameLine()
if actor:GetProperty(PROP_ACTOR_TYPE) == ACTOR_TYPE_PLAYER then
imgui.Text('种族:'..actor:GetRaceName())
imgui.SameLine()
if imgui.Button('门派') then
imgui.OpenPopup('SchoolSelector')
end
imgui.SameLine()
imgui.Text(actor:GetSchoolName())
end
if imgui.BeginPopup('SchoolSelector') then
local school = content_system_get_table('school')
imgui.HorizontalLayout(school,next,function(k,v)
if imgui.Button(v.name..'##'..v.ID) then
net_manager_player_dostring(string.format([[
local actor = actor_manager_fetch_player_by_id(%d)
actor:SetProperty(PROP_SCHOOL, %d)
]],actor:GetID(), v.ID))
imgui.CloseCurrentPopup()
end
end)
imgui.EndPopup('SchoolSelector')
end
if imgui.Button('满状态') then
net_manager_player_dostring(string.format([[
local actor = actor_manager_fetch_player_by_id(%d)
actor:SetProperty(PROP_HP, actor:GetMaxHP())
actor:SetProperty(PROP_MP, actor:GetMaxMP())
actor:SetProperty(PROP_SP, 150)
]], actor:GetID() ))
end
imgui.SameLine()
imgui.Text(string.format('HP:%.f/%.f',actor:GetProperty(PROP_HP), actor:GetMaxHP()))
imgui.SameLine()
imgui.Text(string.format('MP:%.0f/%.0f',actor:GetProperty(PROP_MP),actor:GetMaxMP()))
if actor:GetProperty(PROP_ACTOR_TYPE) == ACTOR_TYPE_PLAYER then
imgui.SameLine()
imgui.Text(string.format('SP:%.0f/%.0f',actor:GetProperty(PROP_SP), 150))
end
imgui.Separator()
imgui.BeginGroup()
imgui.Dummy(30,20)
if actor:GetProperty(PROP_ACTOR_TYPE) == ACTOR_TYPE_PLAYER then
imgui.Text(string.format('命中 %.1f', actor:CalcTargetHit()) )
end
imgui.Text(string.format('攻击 %.1f', actor:CalcAttack()) )
imgui.Text(string.format('防御 %.1f', actor:CalcDefend()) )
imgui.Text(string.format('灵力 %.1f', actor:CalcSpiritual()) )
imgui.Text(string.format('速度 %.1f', actor:CalcSpeed()) )
imgui.Text(string.format('躲闪 %.1f', actor:CalcDodge()) )
imgui.EndGroup()
imgui.SameLine()
imgui.Dummy(30,10)
imgui.SameLine()
draw_prop_points_panel(actor, edit_prop_lv)
imgui.Dummy(30,10)
if actor:GetProperty(PROP_ACTOR_TYPE) == ACTOR_TYPE_PLAYER then
if imgui.CollapsingHeader('师门技能等级') then
draw_player_skill_pannel(actor)
end
if imgui.CollapsingHeader('装备') then
draw_player_equip_pannel(actor)
end
if imgui.CollapsingHeader('修炼等级') then
draw_player_practice_lv(actor)
end
end
if actor:GetProperty(PROP_ACTOR_TYPE) == ACTOR_TYPE_SUMMON then
if imgui.CollapsingHeader('修炼等级') then
draw_player_practice_lv(actor)
end
imgui.BeginGroup()
imgui.Text('攻击资质 '..actor:GetProperty(PROP_SUMMON_ATK_QUAL))
imgui.Text('防御资质 '..actor:GetProperty(PROP_SUMMON_DEF_QUAL))
imgui.Text('体力资质 '..actor:GetProperty(PROP_SUMMON_HEALTH_QUAL))
imgui.Text('法力资质 '..actor:GetProperty(PROP_SUMMON_MAGIC_QUAL))
imgui.Text('速度资质 '..actor:GetProperty(PROP_SUMMON_SPEED_QUAL))
imgui.Text('躲闪资质 '..actor:GetProperty(PROP_SUMMON_DODGE_QUAL))
imgui.Text(string.format('成长 %.4f', actor:GetProperty(PROP_SUMMON_GROW_COEF)))
imgui.EndGroup()
if imgui.Button('BB资质模板') then
imgui.OpenPopup('BBQualSelector')
end
if imgui.BeginPopup('BBQualSelector') then
local tbl = content_system_get_table('summon_quality')
imgui.HorizontalLayout(tbl,next,function(k,v)
if imgui.Button(k..'##bb_templ') then
net_manager_player_dostring(string.format([[
local actor = actor_manager_fetch_player_by_id(%d)
actor:SetProperty(PROP_SUMMON_ATK_QUAL, %d)
actor:SetProperty(PROP_SUMMON_DEF_QUAL, %d)
actor:SetProperty(PROP_SUMMON_HEALTH_QUAL, %d)
actor:SetProperty(PROP_SUMMON_MAGIC_QUAL, %d)
actor:SetProperty(PROP_SUMMON_SPEED_QUAL, %d)
actor:SetProperty(PROP_SUMMON_DODGE_QUAL, %d)
actor:SetProperty(PROP_SUMMON_GROW_COEF, %f)
]], actor:GetID(), v.atk_qual, v.def_qual, v.health_qual,v.magic_qual,v.speed_qual,v.dodge_qual,v.grow_coef))
imgui.CloseCurrentPopup()
end
end)
imgui.EndPopup('BBQualSelector')
end
end
imgui.EndChild()
end
imgui.End()
end | 0 | 0.641987 | 1 | 0.641987 | game-dev | MEDIA | 0.961346 | game-dev | 0.771432 | 1 | 0.771432 |
jonathan-laurent/AlphaZero.jl | 3,251 | src/minmax.jl | #####
##### A simple minmax player to be used as a baseline
#####
"""
A simple implementation of the minmax tree search algorithm, to be used as
a baseline against AlphaZero. Heuristic board values are provided by the
[`GameInterface.heuristic_value`](@ref) function.
"""
module MinMax
using ..AlphaZero
amplify(r) = iszero(r) ? r : Inf * sign(r)
# Return the value of the current state for the player playing
function value(player, game, depth)
if GI.game_terminated(game)
return 0.
elseif depth == 0
return GI.heuristic_value(game)
else
qs = [qvalue(player, game, a, depth) for a in GI.available_actions(game)]
return maximum(qs)
end
end
function qvalue(player, game, action, depth)
@assert !GI.game_terminated(game)
next = GI.clone(game)
GI.play!(next, action)
wr = GI.white_reward(next)
r = GI.white_playing(game) ? wr : -wr
if player.amplify_rewards
r = amplify(r)
end
nextv = value(player, next, depth - 1)
if GI.white_playing(game) != GI.white_playing(next)
nextv = -nextv
end
return r + player.gamma * nextv
end
function minmax(player, game, actions, depth)
return argmax([qvalue(player, game, a, player.depth) for a in actions])
end
"""
MinMax.Player <: AbstractPlayer
A stochastic minmax player, to be used as a baseline.
MinMax.Player(;depth, amplify_rewards, τ=0.)
The minmax player explores the game tree exhaustively at depth `depth`
to build an estimate of the Q-value of each available action. Then, it
chooses an action as follows:
- If there are winning moves (with value `Inf`), one of them is picked
uniformly at random.
- If all moves are losing (with value `-Inf`), one of them is picked
uniformly at random.
Otherwise,
- If the temperature `τ` is zero, a move is picked uniformly among those
with maximal Q-value (there is usually only one choice).
- If the temperature `τ` is nonzero, the probability of choosing
action ``a`` is proportional to ``e^{\\frac{q_a}{Cτ}}`` where ``q_a`` is the
Q value of action ``a`` and ``C`` is the maximum absolute value of all
finite Q values, making the decision invariant to rescaling of
[`GameInterface.heuristic_value`](@ref).
If the `amplify_rewards` option is set to true, every received positive reward
is converted to ``∞`` and every negative reward is converted to ``-∞``.
"""
struct Player <: AbstractPlayer
depth :: Int
amplify_rewards :: Bool
τ :: Float64
gamma :: Float64
function Player(;depth, amplify_rewards, τ=0., γ=1.)
return new(depth, amplify_rewards, τ, γ)
end
end
function AlphaZero.think(p::Player, game)
actions = GI.available_actions(game)
n = length(actions)
qs = [qvalue(p, game, a, p.depth) for a in actions]
winning = findall(==(Inf), qs)
if isempty(winning)
notlosing = findall(>(-Inf), qs)
best = argmax(qs)
if isempty(notlosing)
π = ones(n)
elseif iszero(p.τ)
π = zeros(n)
all_best = findall(==(qs[best]), qs)
π[all_best] .= 1.
else
qmax = qs[best]
@assert qmax > -Inf
C = maximum(abs(qs[a]) for a in notlosing) + eps()
π = exp.((qs .- qmax) ./ C)
π .^= (1 / p.τ)
end
else
π = zeros(n)
π[winning] .= 1.
end
π ./= sum(π)
return actions, π
end
end
| 0 | 0.892195 | 1 | 0.892195 | game-dev | MEDIA | 0.976585 | game-dev | 0.943766 | 1 | 0.943766 |
MARUI-PlugIn/BlenderXR | 7,611 | blender/extern/bullet2/src/BulletDynamics/MLCPSolvers/btLemkeSolver.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///original version written by Erwin Coumans, October 2013
#ifndef BT_LEMKE_SOLVER_H
#define BT_LEMKE_SOLVER_H
#include "btMLCPSolverInterface.h"
#include "btLemkeAlgorithm.h"
///The btLemkeSolver is based on "Fast Implementation of Lemkes Algorithm for Rigid Body Contact Simulation (John E. Lloyd) "
///It is a slower but more accurate solver. Increase the m_maxLoops for better convergence, at the cost of more CPU time.
///The original implementation of the btLemkeAlgorithm was done by Kilian Grundl from the MBSim team
class btLemkeSolver : public btMLCPSolverInterface
{
protected:
public:
btScalar m_maxValue;
int m_debugLevel;
int m_maxLoops;
bool m_useLoHighBounds;
btLemkeSolver()
:m_maxValue(100000),
m_debugLevel(0),
m_maxLoops(1000),
m_useLoHighBounds(true)
{
}
virtual bool solveMLCP(const btMatrixXu & A, const btVectorXu & b, btVectorXu& x, const btVectorXu & lo,const btVectorXu & hi,const btAlignedObjectArray<int>& limitDependency, int numIterations, bool useSparsity = true)
{
if (m_useLoHighBounds)
{
BT_PROFILE("btLemkeSolver::solveMLCP");
int n = A.rows();
if (0==n)
return true;
bool fail = false;
btVectorXu solution(n);
btVectorXu q1;
q1.resize(n);
for (int row=0;row<n;row++)
{
q1[row] = -b[row];
}
// cout << "A" << endl;
// cout << A << endl;
/////////////////////////////////////
//slow matrix inversion, replace with LU decomposition
btMatrixXu A1;
btMatrixXu B(n,n);
{
BT_PROFILE("inverse(slow)");
A1.resize(A.rows(),A.cols());
for (int row=0;row<A.rows();row++)
{
for (int col=0;col<A.cols();col++)
{
A1.setElem(row,col,A(row,col));
}
}
btMatrixXu matrix;
matrix.resize(n,2*n);
for (int row=0;row<n;row++)
{
for (int col=0;col<n;col++)
{
matrix.setElem(row,col,A1(row,col));
}
}
btScalar ratio,a;
int i,j,k;
for(i = 0; i < n; i++){
for(j = n; j < 2*n; j++){
if(i==(j-n))
matrix.setElem(i,j,1.0);
else
matrix.setElem(i,j,0.0);
}
}
for(i = 0; i < n; i++){
for(j = 0; j < n; j++){
if(i!=j)
{
btScalar v = matrix(i,i);
if (btFuzzyZero(v))
{
a = 0.000001f;
}
ratio = matrix(j,i)/matrix(i,i);
for(k = 0; k < 2*n; k++){
matrix.addElem(j,k,- ratio * matrix(i,k));
}
}
}
}
for(i = 0; i < n; i++){
a = matrix(i,i);
if (btFuzzyZero(a))
{
a = 0.000001f;
}
btScalar invA = 1.f/a;
for(j = 0; j < 2*n; j++){
matrix.mulElem(i,j,invA);
}
}
for (int row=0;row<n;row++)
{
for (int col=0;col<n;col++)
{
B.setElem(row,col,matrix(row,n+col));
}
}
}
btMatrixXu b1(n,1);
btMatrixXu M(n*2,n*2);
for (int row=0;row<n;row++)
{
b1.setElem(row,0,-b[row]);
for (int col=0;col<n;col++)
{
btScalar v =B(row,col);
M.setElem(row,col,v);
M.setElem(n+row,n+col,v);
M.setElem(n+row,col,-v);
M.setElem(row,n+col,-v);
}
}
btMatrixXu Bb1 = B*b1;
// q = [ (-B*b1 - lo)' (hi + B*b1)' ]'
btVectorXu qq;
qq.resize(n*2);
for (int row=0;row<n;row++)
{
qq[row] = -Bb1(row,0)-lo[row];
qq[n+row] = Bb1(row,0)+hi[row];
}
btVectorXu z1;
btMatrixXu y1;
y1.resize(n,1);
btLemkeAlgorithm lemke(M,qq,m_debugLevel);
{
BT_PROFILE("lemke.solve");
lemke.setSystem(M,qq);
z1 = lemke.solve(m_maxLoops);
}
for (int row=0;row<n;row++)
{
y1.setElem(row,0,z1[2*n+row]-z1[3*n+row]);
}
btMatrixXu y1_b1(n,1);
for (int i=0;i<n;i++)
{
y1_b1.setElem(i,0,y1(i,0)-b1(i,0));
}
btMatrixXu x1;
x1 = B*(y1_b1);
for (int row=0;row<n;row++)
{
solution[row] = x1(row,0);//n];
}
int errorIndexMax = -1;
int errorIndexMin = -1;
float errorValueMax = -1e30;
float errorValueMin = 1e30;
for (int i=0;i<n;i++)
{
x[i] = solution[i];
volatile btScalar check = x[i];
if (x[i] != check)
{
//printf("Lemke result is #NAN\n");
x.setZero();
return false;
}
//this is some hack/safety mechanism, to discard invalid solutions from the Lemke solver
//we need to figure out why it happens, and fix it, or detect it properly)
if (x[i]>m_maxValue)
{
if (x[i]> errorValueMax)
{
fail = true;
errorIndexMax = i;
errorValueMax = x[i];
}
////printf("x[i] = %f,",x[i]);
}
if (x[i]<-m_maxValue)
{
if (x[i]<errorValueMin)
{
errorIndexMin = i;
errorValueMin = x[i];
fail = true;
//printf("x[i] = %f,",x[i]);
}
}
}
if (fail)
{
int m_errorCountTimes = 0;
if (errorIndexMin<0)
errorValueMin = 0.f;
if (errorIndexMax<0)
errorValueMax = 0.f;
m_errorCountTimes++;
// printf("Error (x[%d] = %f, x[%d] = %f), resetting %d times\n", errorIndexMin,errorValueMin, errorIndexMax, errorValueMax, errorCountTimes++);
for (int i=0;i<n;i++)
{
x[i]=0.f;
}
}
return !fail;
} else
{
int dimension = A.rows();
if (0==dimension)
return true;
// printf("================ solving using Lemke/Newton/Fixpoint\n");
btVectorXu q;
q.resize(dimension);
for (int row=0;row<dimension;row++)
{
q[row] = -b[row];
}
btLemkeAlgorithm lemke(A,q,m_debugLevel);
lemke.setSystem(A,q);
btVectorXu solution = lemke.solve(m_maxLoops);
//check solution
bool fail = false;
int errorIndexMax = -1;
int errorIndexMin = -1;
float errorValueMax = -1e30;
float errorValueMin = 1e30;
for (int i=0;i<dimension;i++)
{
x[i] = solution[i+dimension];
volatile btScalar check = x[i];
if (x[i] != check)
{
x.setZero();
return false;
}
//this is some hack/safety mechanism, to discard invalid solutions from the Lemke solver
//we need to figure out why it happens, and fix it, or detect it properly)
if (x[i]>m_maxValue)
{
if (x[i]> errorValueMax)
{
fail = true;
errorIndexMax = i;
errorValueMax = x[i];
}
////printf("x[i] = %f,",x[i]);
}
if (x[i]<-m_maxValue)
{
if (x[i]<errorValueMin)
{
errorIndexMin = i;
errorValueMin = x[i];
fail = true;
//printf("x[i] = %f,",x[i]);
}
}
}
if (fail)
{
static int errorCountTimes = 0;
if (errorIndexMin<0)
errorValueMin = 0.f;
if (errorIndexMax<0)
errorValueMax = 0.f;
printf("Error (x[%d] = %f, x[%d] = %f), resetting %d times\n", errorIndexMin,errorValueMin, errorIndexMax, errorValueMax, errorCountTimes++);
for (int i=0;i<dimension;i++)
{
x[i]=0.f;
}
}
return !fail;
}
return true;
}
};
#endif //BT_LEMKE_SOLVER_H
| 0 | 0.868164 | 1 | 0.868164 | game-dev | MEDIA | 0.502872 | game-dev | 0.989419 | 1 | 0.989419 |
Luxon98/Super-Mario-Bros-game | 18,219 | Mario/Player.cpp | #include "Player.h"
#include "SoundController.h"
#include "World.h"
#include "Camera.h"
#include "CollisionHandling.h"
#include "UtilityFunctions.h"
#include "SDL_Utility.h"
std::array<SDL_Surface*, 140> Player::playerImages;
Player::Statistics::Statistics()
{
points = 0;
coins = 0;
lives = 3;
}
Player::Flags::Flags()
{
orientationFlag = true;
aliveFlag = true;
removeLivesFlag = false;
armedFlag = false;
slideFlag = false;
changeDirectionFlag = false;
downPipeFlag = false;
inAirFlag = false;
rejumpFlag = false;
}
void Player::Flags::setDefaultFlags(bool armedFlag)
{
orientationFlag = true;
aliveFlag = true;
removeLivesFlag = false;
this->armedFlag = armedFlag;
slideFlag = false;
changeDirectionFlag = false;
downPipeFlag = false;
inAirFlag = false;
rejumpFlag = false;
}
Player::StepsCounter::StepsCounter()
{
stepsLeft = 0;
stepsRight = 0;
stepsUp = 0;
}
int Player::computeImageIndexWhenSliding() const
{
if (currentState == PlayerState::Small) {
return (68 + 70 * flags.orientationFlag);
}
else if (currentState >= PlayerState::ImmortalSmallFirst && currentState <= PlayerState::ImmortalSmallFourth) {
return (69 + 70 * flags.orientationFlag);
}
else if (currentState == PlayerState::Tall) {
return (66 + 70 * flags.orientationFlag);
}
else {
return (67 + 70 * flags.orientationFlag);
}
}
int Player::computeImageIndex() const
{
if (flags.slideFlag) {
return computeImageIndexWhenSliding();
}
else {
if (currentState >= PlayerState::Small && currentState <= PlayerState::ImmortalSmallFourth) {
return (model + 70 * flags.orientationFlag + 5 * (static_cast<int>(currentState) - 1));
}
else if (currentState == PlayerState::ImmortalFourth) {
return (model + 70 * flags.orientationFlag + 10);
}
else {
return (70 * flags.orientationFlag + 65);
}
}
}
int Player::getModelDuringFall() const
{
if (changeModelCounter <= 2) {
return 1;
}
else if (changeModelCounter == 3) {
return 2;
}
else {
return 3;
}
}
void Player::changeStateDuringAnimation()
{
auto timePoint = std::chrono::steady_clock::now();
auto difference = std::chrono::duration_cast<std::chrono::milliseconds>(timePoint - animationStartTime).count();
if (currentAnimationState == PlayerAnimation::Growing) {
performGrowingAnimation(static_cast<int>(difference));
}
else if (currentAnimationState == PlayerAnimation::Shrinking) {
performShrinkingAnimation(static_cast<int>(difference));
}
else if (currentAnimationState == PlayerAnimation::Arming) {
performArmingAnimation(static_cast<int>(difference));
}
else if (currentAnimationState == PlayerAnimation::Immortal) {
performImmortalAnimation(static_cast<int>(difference));
}
else if (currentAnimationState == PlayerAnimation::ImmortalSmall) {
performSmallImmortalAnimation(static_cast<int>(difference));
}
}
void Player::performGrowingAnimation(int difference)
{
movementBlock = true;
model = 0;
if ((difference >= 100 && difference <= 200 && lastDifference < 100)
|| (difference >= 300 && difference <= 400 && lastDifference < 300)
|| (difference >= 700 && difference <= 800 && lastDifference < 700)) {
size.setHeight(48);
position.setY(position.getY() - 8);
lastDifference = difference;
currentState = PlayerState::Average;
}
else if ((difference > 200 && difference < 300 && lastDifference < 200)
|| (difference > 600 && difference < 700 && lastDifference < 600)) {
size.setHeight(32);
position.setY(position.getY() + 8);
lastDifference = difference;
currentState = PlayerState::Small;
}
else if ((difference > 400 && difference < 500 && lastDifference < 400)
|| (difference > 800 && difference <= 900 && lastDifference < 800)) {
size.setHeight(64);
position.setY(position.getY() - 8);
lastDifference = difference;
currentState = PlayerState::Tall;
}
else if (difference >= 500 && difference <= 600 && lastDifference < 500) {
size.setHeight(48);
position.setY(position.getY() + 8);
lastDifference = difference;
currentState = PlayerState::Average;
}
else if (difference > 900) {
currentAnimationState = PlayerAnimation::NoAnimation;
lastDifference = 0;
movementBlock = false;
resetMovement();
}
}
void Player::performShrinkingAnimation(int difference)
{
if (difference <= 100 && lastDifference < 10) {
size.setHeight(32);
lastDifference = difference;
currentState = PlayerState::Insensitive;
resetSteps();
}
else if (difference >= 2000) {
currentAnimationState = PlayerAnimation::NoAnimation;
currentState = PlayerState::Small;
lastDifference = 0;
}
}
void Player::performArmingAnimation(int difference)
{
movementBlock = true;
if (isDifferenceInInterval(difference, 0, 600, 3)) {
currentState = PlayerState::ArmedFirst;
}
else if (isDifferenceInInterval(difference, 150, 600, 3)) {
currentState = PlayerState::Tall;
}
else if (isDifferenceInInterval(difference, 300, 600, 3)) {
currentState = PlayerState::ArmedSecond;
}
else if (isDifferenceInInterval(difference, 450, 600, 3)) {
currentState = PlayerState::ArmedThird;
}
else {
currentAnimationState = PlayerAnimation::NoAnimation;
currentState = PlayerState::ArmedFirst;
flags.armedFlag = true;
lastDifference = 0;
movementBlock = false;
resetMovement();
}
}
void Player::performImmortalAnimation(int difference)
{
if (isDifferenceInInterval(difference, 0, 600, 20)) {
currentState = PlayerState::ImmortalFirst;
}
else if (isDifferenceInInterval(difference, 150, 600, 20)) {
currentState = PlayerState::ImmortalSecond;
}
else if (isDifferenceInInterval(difference, 300, 600, 20)) {
currentState = PlayerState::ImmortalThird;
}
else if (isDifferenceInInterval(difference, 450, 600, 20)) {
currentState = PlayerState::ImmortalFourth;
}
else {
currentAnimationState = PlayerAnimation::NoAnimation;
currentState = (flags.armedFlag ? PlayerState::ArmedFirst : PlayerState::Tall);
lastDifference = 0;
SoundController::playBackgroundMusic();
}
}
void Player::performSmallImmortalAnimation(int difference)
{
if (isDifferenceInInterval(difference, 0, 600, 20)) {
currentState = PlayerState::ImmortalSmallFirst;
}
else if (isDifferenceInInterval(difference, 150, 600, 20)) {
currentState = PlayerState::ImmortalSmallSecond;
}
else if (isDifferenceInInterval(difference, 300, 600, 20)) {
currentState = PlayerState::ImmortalSmallThird;
}
else if (isDifferenceInInterval(difference, 450, 600, 20)) {
currentState = PlayerState::ImmortalSmallFourth;
}
else {
currentAnimationState = PlayerAnimation::NoAnimation;
currentState = PlayerState::Small;
lastDifference = 0;
SoundController::playBackgroundMusic();
}
}
void Player::resetMovement()
{
resetSteps();
}
void Player::changeModel(World &world)
{
if (!isCharacterStandingOnSomething(*this, world)) {
if (flags.inAirFlag) {
model = 4;
}
else {
model = getModelDuringFall();
}
return;
}
if (stepsCounter.stepsLeft == 0 && stepsCounter.stepsRight == 0) {
model = 0;
return;
}
++changeModelCounter;
if (changeModelCounter % 12 == 0) {
++model;
if (model > 3) {
model = 1;
}
changeModelCounter = 0;
}
}
bool Player::isHittingCeiling(int distance) const
{
return (position.getY() - distance - (getHeight() / 2) < -25);
}
bool Player::isFallingIntoAbyss(int distance) const
{
return (position.getY() + distance + (getHeight() / 2) > World::WORLD_HEIGHT);
}
bool Player::isGoingBeyondCamera(int distance) const
{
if (position.getX() - camera->getBeginningOfCamera() - distance <= getWidth() / 2) {
return true;
}
return false;
}
bool Player::isHittingBlock(int alignment, Direction direction) const
{
if (alignment > 0 && direction == Direction::Up) {
return true;
}
return false;
}
bool Player::isDuringAnimation() const
{
return (currentAnimationState != PlayerAnimation::NoAnimation);
}
bool Player::isAbleToDestroyBlock() const
{
if ((currentState >= PlayerState::Tall && currentState <= PlayerState::ImmortalThird)
|| currentState == PlayerState::ImmortalFourth) {
return true;
}
return false;
}
void Player::moveLeft(World &world)
{
int alignment = computeHorizontalAlignment(Direction::Left, movement.getSpeed(), *this, world);
int distance = movement.getSpeed() - alignment;
if (!isGoingBeyondCamera(distance)) {
position.setX(position.getX() - distance);
}
if (alignment != 0 && stepsCounter.stepsUp == 0) {
stepsCounter.stepsLeft = 0;
}
else {
--stepsCounter.stepsLeft;
}
flags.orientationFlag = false;
}
void Player::moveRight(World &world)
{
int alignment = computeHorizontalAlignment(Direction::Right, movement.getSpeed(), *this, world);
int distance = movement.getSpeed() - alignment;
position.setX(position.getX() + distance);
if (alignment != 0 && stepsCounter.stepsUp == 0) {
stepsCounter.stepsRight = 0;
}
else {
--stepsCounter.stepsRight;
}
flags.orientationFlag = true;
}
void Player::moveUp(World &world)
{
int alignment = computeVerticalAlignment(Direction::Up, movement.getVerticalSpeed(), *this, world);
int distance = movement.getVerticalSpeed() - alignment;
if (distance < 0) {
stepsCounter.stepsUp = 0;
return;
}
if (!isHittingCeiling(distance)) {
position.setY(position.getY() - distance);
}
else {
stepsCounter.stepsUp = 1;
}
if (isHittingBlock(alignment, Direction::Up)) {
hitBlock(world);
stepsCounter.stepsUp = 0;
}
else {
--stepsCounter.stepsUp;
}
if (isCharacterStandingOnSomething(*this, world)) {
model = 0;
}
else if (!flags.rejumpFlag) {
flags.inAirFlag = true;
}
}
void Player::moveDown(World &world)
{
int alignment = computeVerticalAlignment(Direction::Down, movement.getVerticalSpeed(), *this, world);
int distance = movement.getVerticalSpeed() - alignment;
if (!isFallingIntoAbyss(distance)) {
position.setY(position.getY() + distance);
}
else {
if (!flags.removeLivesFlag) {
flags.removeLivesFlag = true;
--statistics.lives;
flags.aliveFlag = false;
}
}
}
void Player::slide(World &world)
{
int alignment = computeVerticalAlignment(Direction::Down, movement.getVerticalSpeed(), *this, world);
int distance = movement.getVerticalSpeed() - alignment;
if (distance == 0 && !flags.changeDirectionFlag) {
flags.orientationFlag = false;
flags.changeDirectionFlag = true;
position.setX(position.getX() + 16);
}
else {
position.setY(position.getY() + distance);
}
}
Player::Player(Position position)
{
size = Size(32, 32);
movement = Movement(1, 1, Direction::None, Direction::None);
statistics = Statistics();
flags = Flags();
stepsCounter = StepsCounter();
this->position = position;
model = 0;
changeModelCounter = 0;
lastDifference = 0;
currentAnimationState = PlayerAnimation::NoAnimation;
currentState = PlayerState::Small;
movementBlock = false;
}
void Player::loadPlayerImages(SDL_Surface* display)
{
for (std::size_t i = 0; i < playerImages.size() / 2; ++i) {
std::string filename = "./img/mario_imgs/mario_left";
filename += std::to_string(i + 1);
filename += ".png";
playerImages[i] = loadPNG(filename, display);
filename.replace(23, 4, "right");
playerImages[i + (playerImages.size() / 2)] = loadPNG(filename, display);
}
}
int Player::getPoints() const
{
return statistics.points;
}
int Player::getCoins() const
{
return statistics.coins;
}
int Player::getLives() const
{
return statistics.lives;
}
int Player::getDeadMarioImageIndex() const
{
if (currentState == PlayerState::ArmedFirst || currentState == PlayerState::ImmortalFourth
|| currentState == PlayerState::ImmortalSmallFourth) {
return 1;
}
else if (currentState == PlayerState::ImmortalFirst || currentState == PlayerState::ImmortalSmallFirst) {
return 2;
}
else if (currentState == PlayerState::ImmortalSecond || currentState == PlayerState::ImmortalSmallSecond) {
return 3;
}
else if (currentState == PlayerState::ImmortalThird || currentState == PlayerState::ImmortalSmallThird) {
return 4;
}
return 0;
}
bool Player::isSmall() const
{
return (currentState == PlayerState::Small);
}
bool Player::isArmed() const
{
return flags.armedFlag;
}
bool Player::isInsensitive() const
{
if (currentState == PlayerState::Insensitive || currentAnimationState == PlayerAnimation::Growing) {
return true;
}
return false;
}
bool Player::isImmortal() const
{
return ((currentState >= PlayerState::ImmortalFirst && currentState <= PlayerState::ImmortalFourth)
&& currentState != PlayerState::Insensitive);
}
bool Player::isDead() const
{
return !flags.aliveFlag;
}
bool Player::isTurnedRight() const
{
return flags.orientationFlag;
}
bool Player::isPerformingJumpAsSmall() const
{
if (isSmall() || isInsensitive()) {
return true;
}
else if (currentState >= PlayerState::ImmortalSmallFirst && currentState <= PlayerState::ImmortalSmallFourth) {
return true;
}
return false;
}
bool Player::isGoingToPipe() const
{
if (flags.downPipeFlag && stepsCounter.stepsUp == 0 && currentState != PlayerState::Insensitive) {
return true;
}
return false;
}
bool Player::isNotJumpingUp() const
{
if (stepsCounter.stepsUp < 50) {
return true;
}
return false;
}
bool Player::isStillRunning()
{
return (stepsCounter.stepsRight != 0);
}
SDL_Surface* Player::getImage() const
{
return playerImages[computeImageIndex()];
}
void Player::incrementCoins()
{
if (statistics.coins == 99) {
statistics.coins = 0;
++statistics.lives;
SoundController::playNewLiveAddedEffect();
}
else {
++statistics.coins;
}
}
void Player::incrementLives()
{
++statistics.lives;
}
void Player::addPoints(int pts)
{
statistics.points += pts;
}
void Player::setCurrentAnimation(PlayerAnimation animation)
{
currentAnimationState = animation;
animationStartTime = std::chrono::steady_clock::now();
}
void Player::setCamera(std::shared_ptr<Camera> camera)
{
this->camera = std::move(camera);
}
void Player::draw(SDL_Surface* display, int beginningOfCamera, int endOfCamera) const
{
int index = computeImageIndex();
SDL_Surface* playerImg = playerImages[index];
drawSurface(display, playerImg, position.getX() - beginningOfCamera, position.getY());
}
void Player::forceMovement(Direction direction)
{
if (direction == Direction::Left) {
if (!isGoingBeyondCamera(1)) {
position.setX(position.getX() - 1);
}
}
else if (direction == Direction::Right) {
position.setX(position.getX() + 1);
}
else if (direction == Direction::Up) {
if (!isHittingCeiling(1)) {
position.setY(position.getY() - 1);
}
}
else {
if (!isFallingIntoAbyss(1)) {
position.setY(position.getY() + 1);
}
}
}
void Player::hitBlock(World &world)
{
if (isAbleToDestroyBlock() && world.getLastTouchedBlockType() == BlockType::Destructible) {
world.destroyLastTouchedBlock();
}
else {
world.handleBlockHitting();
}
}
void Player::loseBonusOrLife()
{
if (currentState == PlayerState::Tall || currentState == PlayerState::ArmedFirst) {
currentAnimationState = PlayerAnimation::Shrinking;
flags.armedFlag = false;
animationStartTime = std::chrono::steady_clock::now();
SoundController::playBonusLostEffect();
}
else if (!isDuringAnimation()) {
if (!flags.removeLivesFlag) {
flags.removeLivesFlag = true;
--statistics.lives;
flags.aliveFlag = false;
}
}
}
void Player::performAdditionalJump()
{
stepsCounter.stepsUp = 40;
flags.rejumpFlag = true;
}
void Player::move(World &world)
{
if (isDuringAnimation()) {
changeStateDuringAnimation();
}
if (!movementBlock) {
if (flags.slideFlag) {
slide(world);
}
else {
if (stepsCounter.stepsUp > 0) {
moveUp(world);
}
else if (!isCharacterStandingOnSomething(*this, world)) {
moveDown(world);
}
else {
flags.inAirFlag = false;
flags.rejumpFlag = false;
}
if (stepsCounter.stepsLeft > 0) {
moveLeft(world);
}
else if (stepsCounter.stepsRight > 0) {
moveRight(world);
}
changeModel(world);
}
flags.downPipeFlag = false;
}
}
void Player::setPositionXY(int level)
{
if (level == 1) {
position.setXY(35, 400);
}
else if (level == 2) {
position.setXY(80, 140);
}
else if (level == 3) {
position.setXY(80, 400);
}
else if (level == 4) {
int posY = (this->isSmall() ? 208 : 192);
position.setXY(50, posY);
}
else if (level == 77) {
position.setXY(145, 400);
}
else if (level == 88) {
position.setXY(245, 160);
}
}
void Player::setPositionXY(int level, int checkPointMark)
{
int posY = (this->isSmall() ? 337 : 321);
if (level == 1) {
if (checkPointMark == 1) {
position.setXY(70, 60);
}
else if (checkPointMark == 2) {
position.setXY(5246, posY);
}
}
else if (level == 2) {
if (checkPointMark == 1) {
position.setXY(70, 60);
}
else if (checkPointMark == 2) {
position.setXY(3712, posY);
}
else if (checkPointMark == 3) {
position.setXY(128, posY);
}
}
else if (level == 77) {
if (checkPointMark == 1) {
position.setXY(85, 60);
}
else if (checkPointMark == 2) {
position.setXY(6960, posY);
}
else if (checkPointMark == 3) {
position.setXY(77, posY - 32);
}
}
else if (level == 88) {
if (checkPointMark == 1 || checkPointMark == 4) {
position.setXY(96, posY);
}
else if (checkPointMark == 2) {
position.setXY(3184, posY - 224);
}
else if (checkPointMark == 3 || checkPointMark == 5) {
position.setXY(160, posY);
}
else if (checkPointMark == 6) {
position.setXY(304, posY - 128);
}
}
}
void Player::reborn(int level)
{
size.setSize(32, 32);
setPositionXY(level);
model = 0;
changeModelCounter = 0;
flags.setDefaultFlags(false);
lastDifference = 0;
currentState = PlayerState::Small;
currentAnimationState = PlayerAnimation::NoAnimation;
movementBlock = false;
resetMovement();
}
void Player::resetModel()
{
model = 0;
flags.orientationFlag = true;
}
void Player::resetSteps()
{
stepsCounter.stepsLeft = 0;
stepsCounter.stepsRight = 0;
stepsCounter.stepsUp = 0;
}
void Player::setSlidingParameters()
{
resetSteps();
flags.slideFlag = true;
position.setX(position.getX() - 8);
}
void Player::setFinishingRunParameters(int distance)
{
resetMovement();
stepsCounter.stepsRight = distance;
changeModelCounter = 0;
model = 0;
flags.setDefaultFlags(flags.armedFlag);
} | 0 | 0.919478 | 1 | 0.919478 | game-dev | MEDIA | 0.973903 | game-dev | 0.96527 | 1 | 0.96527 |
away3d/awayphysics-core-fp11 | 5,454 | Bullet/BulletDynamics/ConstraintSolver/btContactSolverInfo.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_CONTACT_SOLVER_INFO
#define BT_CONTACT_SOLVER_INFO
#include "LinearMath/btScalar.h"
enum btSolverMode
{
SOLVER_RANDMIZE_ORDER = 1,
SOLVER_FRICTION_SEPARATE = 2,
SOLVER_USE_WARMSTARTING = 4,
SOLVER_USE_2_FRICTION_DIRECTIONS = 16,
SOLVER_ENABLE_FRICTION_DIRECTION_CACHING = 32,
SOLVER_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION = 64,
SOLVER_CACHE_FRIENDLY = 128,
SOLVER_SIMD = 256,
SOLVER_INTERLEAVE_CONTACT_AND_FRICTION_CONSTRAINTS = 512,
SOLVER_ALLOW_ZERO_LENGTH_FRICTION_DIRECTIONS = 1024
};
struct btContactSolverInfoData
{
btScalar m_tau;
btScalar m_damping;//global non-contact constraint damping, can be locally overridden by constraints during 'getInfo2'.
btScalar m_friction;
btScalar m_timeStep;
btScalar m_restitution;
int m_numIterations;
btScalar m_maxErrorReduction;
btScalar m_sor;
btScalar m_erp;//used as Baumgarte factor
btScalar m_erp2;//used in Split Impulse
btScalar m_globalCfm;//constraint force mixing
int m_splitImpulse;
btScalar m_splitImpulsePenetrationThreshold;
btScalar m_splitImpulseTurnErp;
btScalar m_linearSlop;
btScalar m_warmstartingFactor;
int m_solverMode;
int m_restingContactRestitutionThreshold;
int m_minimumSolverBatchSize;
btScalar m_maxGyroscopicForce;
btScalar m_singleAxisRollingFrictionThreshold;
};
struct btContactSolverInfo : public btContactSolverInfoData
{
inline btContactSolverInfo()
{
m_tau = btScalar(0.6);
m_damping = btScalar(1.0);
m_friction = btScalar(0.3);
m_timeStep = btScalar(1.f/60.f);
m_restitution = btScalar(0.);
m_maxErrorReduction = btScalar(20.);
m_numIterations = 10;
m_erp = btScalar(0.2);
m_erp2 = btScalar(0.8);
m_globalCfm = btScalar(0.);
m_sor = btScalar(1.);
m_splitImpulse = true;
m_splitImpulsePenetrationThreshold = -.04f;
m_splitImpulseTurnErp = 0.1f;
m_linearSlop = btScalar(0.0);
m_warmstartingFactor=btScalar(0.85);
//m_solverMode = SOLVER_USE_WARMSTARTING | SOLVER_SIMD | SOLVER_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION|SOLVER_USE_2_FRICTION_DIRECTIONS|SOLVER_ENABLE_FRICTION_DIRECTION_CACHING;// | SOLVER_RANDMIZE_ORDER;
m_solverMode = SOLVER_USE_WARMSTARTING | SOLVER_SIMD;// | SOLVER_RANDMIZE_ORDER;
m_restingContactRestitutionThreshold = 2;//unused as of 2.81
m_minimumSolverBatchSize = 128; //try to combine islands until the amount of constraints reaches this limit
m_maxGyroscopicForce = 100.f; ///only used to clamp forces for bodies that have their BT_ENABLE_GYROPSCOPIC_FORCE flag set (using btRigidBody::setFlag)
m_singleAxisRollingFrictionThreshold = 1e30f;///if the velocity is above this threshold, it will use a single constraint row (axis), otherwise 3 rows.
}
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btContactSolverInfoDoubleData
{
double m_tau;
double m_damping;//global non-contact constraint damping, can be locally overridden by constraints during 'getInfo2'.
double m_friction;
double m_timeStep;
double m_restitution;
double m_maxErrorReduction;
double m_sor;
double m_erp;//used as Baumgarte factor
double m_erp2;//used in Split Impulse
double m_globalCfm;//constraint force mixing
double m_splitImpulsePenetrationThreshold;
double m_splitImpulseTurnErp;
double m_linearSlop;
double m_warmstartingFactor;
double m_maxGyroscopicForce;
double m_singleAxisRollingFrictionThreshold;
int m_numIterations;
int m_solverMode;
int m_restingContactRestitutionThreshold;
int m_minimumSolverBatchSize;
int m_splitImpulse;
char m_padding[4];
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btContactSolverInfoFloatData
{
float m_tau;
float m_damping;//global non-contact constraint damping, can be locally overridden by constraints during 'getInfo2'.
float m_friction;
float m_timeStep;
float m_restitution;
float m_maxErrorReduction;
float m_sor;
float m_erp;//used as Baumgarte factor
float m_erp2;//used in Split Impulse
float m_globalCfm;//constraint force mixing
float m_splitImpulsePenetrationThreshold;
float m_splitImpulseTurnErp;
float m_linearSlop;
float m_warmstartingFactor;
float m_maxGyroscopicForce;
float m_singleAxisRollingFrictionThreshold;
int m_numIterations;
int m_solverMode;
int m_restingContactRestitutionThreshold;
int m_minimumSolverBatchSize;
int m_splitImpulse;
char m_padding[4];
};
#endif //BT_CONTACT_SOLVER_INFO
| 0 | 0.951599 | 1 | 0.951599 | game-dev | MEDIA | 0.96797 | game-dev | 0.963834 | 1 | 0.963834 |
CIDARLAB/cello | 1,370 | src/main/java/org/cellocad/adaptors/ucfwriters/ucf_writers_Eco1C1G1T0/collection_writer_motif_library.java | package org.cellocad.adaptors.ucfwriters.ucf_writers_Eco1C1G1T0;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
public class collection_writer_motif_library extends collection_writer {
@Override
public ArrayList<Map> getObjects() {
ArrayList<Map> objects = new ArrayList<>();
FileReader reader = null;
try {
reader = new FileReader("resources/netsynthResources/netlist_in3out1_OUTPUT_OR.json");
try {
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
for(int i=0; i<jsonArray.size(); ++i) {
Map obj = (Map) jsonArray.get(i);
objects.add(obj);
}
} catch (IOException e) {
e.printStackTrace();
return objects;
} catch (ParseException e) {
e.printStackTrace();
return objects;
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
return objects;
}
return objects;
}
}
| 0 | 0.666819 | 1 | 0.666819 | game-dev | MEDIA | 0.187226 | game-dev | 0.518471 | 1 | 0.518471 |
echurchill/CityWorld | 33,927 | old stuff/Support/SupportBlocks.java | package me.daddychurchill.CityWorld.Support;
import me.daddychurchill.CityWorld.CityWorldGenerator;
import me.daddychurchill.CityWorld.Context.DataContext;
import me.daddychurchill.CityWorld.Plugins.LootProvider;
import me.daddychurchill.CityWorld.Plugins.LootProvider.LootLocation;
import me.daddychurchill.CityWorld.Support.Odds.ColorSet;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.TreeSpecies;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.material.Chest;
import org.bukkit.material.Colorable;
import org.bukkit.material.Directional;
import org.bukkit.material.Ladder;
import org.bukkit.Material.BIRCH_LEAVES;
import org.bukkit.material.MaterialData;
import org.bukkit.Material.STONE_SLAB;
import org.bukkit.material.TexturedMaterial;
import org.bukkit.material.Tree;
import org.bukkit.material.Vine;
import org.bukkit.material.WoodenStep;
public abstract class SupportBlocks extends AbstractBlocks {
private boolean doPhysics;
private boolean doClearData;
public SupportBlocks(CityWorldGenerator generator) {
super(generator);
doPhysics = false;
doClearData = false;
}
public abstract Block getActualBlock(int x, int y, int z);
public final boolean getDoPhysics() {
return doPhysics;
}
public final void setDoPhysics(boolean dophysics) {
doPhysics = dophysics;
}
public final boolean getDoClearData() {
return doClearData;
}
public final void setDoClearData(boolean docleardata) {
doClearData = docleardata;
}
@Override
public final void setBlockIfEmpty(int x, int y, int z, Material material) {
Block block = getActualBlock(x, y, z);
if (block.isEmpty() && !getActualBlock(x, y - 1, z).isEmpty())
block.setType(material);
}
public final void setBlockIfAir(int x, int y, int z, Material material, MaterialData data) {
Block block = getActualBlock(x, y, z);
if (block.isEmpty() && !getActualBlock(x, y - 1, z).isEmpty())
setActualBlock(block, material, data);
}
public final void setActualBlock(Block block, Material material, MaterialData data) {
BlockState state = block.getState();
state.setType(material);
state.setData(data);
state.update(true, doPhysics);
}
public final Block getActualBlock(int x, int y, int z, MaterialData data) {
Block block = getActualBlock(x, y, z);
setActualBlock(block, data.getItemType(), data);
return block;
}
@Override
public final void setBlock(int x, int y, int z, Material material) {
if (doClearData) {
BlockState state = getActualBlock(x, y, z).getState();
// if (state.getType() != material) {
state.setType(material);
state.setData(new MaterialData(material));
state.update(true, doPhysics);
// }
} else {
getActualBlock(x, y, z).setType(material);
// BlockState state = getActualBlock(x, y, z).getState();
// if (state.getType() != material) {
// state.setType(material);
// state.update(true, doPhysics);
// }
}
}
@Override
public void setBlock(int x, int y, int z, MaterialData material) {
setActualBlock(getActualBlock(x, y, z), material.getItemType(), material);
}
public final void setBlock(int x, int y, int z, Material material, MaterialData data) {
setActualBlock(getActualBlock(x, y, z), material, data);
}
protected final boolean isType(Block block, Material ... types) {
Material type = block.getType();
for (Material test : types)
if (type == test)
return true;
return false;
}
public final boolean isType(int x, int y, int z, Material type) {
return getActualBlock(x, y, z).getType() == type;
}
public final boolean isOfTypes(int x, int y, int z, Material ... types) {
return isType(getActualBlock(x, y, z), types);
}
public final void setBlockIfNot(int x, int y, int z, Material ... types) {
if (!isOfTypes(x, y, z, types))
setBlock(x, y, z, types[0]);
}
@Override
public final boolean isEmpty(int x, int y, int z) {
return getActualBlock(x, y, z).isEmpty();
}
public final boolean isPartiallyEmpty(int x, int y1, int y2, int z) {
for (int y = y1; y < y2; y++) {
if (isEmpty(x, y, z))
return true;
}
return false;
}
public final boolean isPartiallyEmpty(int x1, int x2, int y1, int y2, int z1, int z2) {
for (int x = x1; x < x2; x++) {
for (int y = y1; y < y2; y++) {
for (int z = z1; z < z2; z++) {
if (isEmpty(x, y, z))
return true;
}
}
}
return false;
}
public abstract boolean isSurroundedByEmpty(int x, int y, int z);
public final boolean isWater(int x, int y, int z) {
return isOfTypes(x, y, z, Material.WATER, Material.WATER);
// return getActualBlock(x, y, z).isLiquid();
}
public abstract boolean isByWater(int x, int y, int z);
public final Location getBlockLocation(int x, int y, int z) {
return getActualBlock(x, y, z).getLocation();
}
@Override
public final void clearBlock(int x, int y, int z) {
getActualBlock(x, y, z).setType(Material.AIR);
}
//================ x, y1, y2, z
@Override
public final void setBlocks(int x, int y1, int y2, int z, Material material) {
for (int y = y1; y < y2; y++)
setBlock(x, y, z, material);
}
public final void setBlocks(int x, int y1, int y2, int z, Material material, MaterialData data) {
for (int y = y1; y < y2; y++)
setBlock(x, y, z, material, data);
}
//================ x1, x2, y1, y2, z1, z2
@Override
public final void setBlocks(int x1, int x2, int y1, int y2, int z1, int z2, Material material) {
for (int x = x1; x < x2; x++) {
for (int y = y1; y < y2; y++) {
for (int z = z1; z < z2; z++) {
setBlock(x, y, z, material);
}
}
}
}
public final void setBlocks(int x1, int x2, int y1, int y2, int z1, int z2, Material material, MaterialData data) {
for (int x = x1; x < x2; x++) {
for (int y = y1; y < y2; y++) {
for (int z = z1; z < z2; z++) {
setBlock(x, y, z, material, data);
}
}
}
}
public final void setBlocks(int x1, int x2, int y1, int y2, int z1, int z2, Material material,
Odds odds, MaterialData data1, MaterialData data2) {
for (int x = x1; x < x2; x++) {
for (int y = y1; y < y2; y++) {
for (int z = z1; z < z2; z++) {
if (odds.playOdds(Odds.oddsPrettyLikely))
setBlock(x, y, z, material, data1);
else
setBlock(x, y, z, material, data2);
}
}
}
}
//================ x1, x2, y, z1, z2
@Override
public final void setBlocks(int x1, int x2, int y, int z1, int z2, Material material) {
for (int x = x1; x < x2; x++) {
for (int z = z1; z < z2; z++) {
setBlock(x, y, z, material);
}
}
}
public final void setBlocks(int x1, int x2, int y, int z1, int z2, Material material, MaterialData data) {
for (int x = x1; x < x2; x++) {
for (int z = z1; z < z2; z++) {
setBlock(x, y, z, material, data);
}
}
}
@Override
public final void setWalls(int x1, int x2, int y1, int y2, int z1, int z2, Material material) {
setBlocks(x1, x2, y1, y2, z1, z1 + 1, material);
setBlocks(x1, x2, y1, y2, z2 - 1, z2, material);
setBlocks(x1, x1 + 1, y1, y2, z1 + 1, z2 - 1, material);
setBlocks(x2 - 1, x2, y1, y2, z1 + 1, z2 - 1, material);
}
public final void setWalls(int x1, int x2, int y, int z1, int z2, Material material, MaterialData data) {
setWalls(x1, x2, y, y + 1, z1, z2, material, data);
}
public final void setWalls(int x1, int x2, int y1, int y2, int z1, int z2, Material material, MaterialData data) {
setBlocks(x1, x2, y1, y2, z1, z1 + 1, material, data);
setBlocks(x1, x2, y1, y2, z2 - 1, z2, material, data);
setBlocks(x1, x1 + 1, y1, y2, z1 + 1, z2 - 1, material, data);
setBlocks(x2 - 1, x2, y1, y2, z1 + 1, z2 - 1, material, data);
}
@Override
public final int setLayer(int blocky, Material material) {
setBlocks(0, width, blocky, blocky + 1, 0, width, material);
return blocky + 1;
}
@Override
public final int setLayer(int blocky, int height, Material material) {
setBlocks(0, width, blocky, blocky + height, 0, width, material);
return blocky + height;
}
@Override
public final int setLayer(int blocky, int height, int inset, Material material) {
setBlocks(inset, width - inset, blocky, blocky + height, inset, width - inset, material);
return blocky + height;
}
@Override
public final boolean setEmptyBlock(int x, int y, int z, Material material) {
Block block = getActualBlock(x, y, z);
if (block.isEmpty()) {
block.setType(material);
return true;
} else
return false;
}
@Override
public final void setEmptyBlocks(int x1, int x2, int y, int z1, int z2, Material material) {
for (int x = x1; x < x2; x++) {
for (int z = z1; z < z2; z++) {
Block block = getActualBlock(x, y, z);
if (block.isEmpty())
block.setType(material);
}
}
}
private void drawCircleBlocks(int cx, int cz, int x, int z, int y, Material material, DyeColor color) {
// Ref: Notes/BCircle.PDF
setBlockTypeAndColor(cx + x, y, cz + z, material, color); // point in octant 1
setBlockTypeAndColor(cx + z, y, cz + x, material, color); // point in octant 2
setBlockTypeAndColor(cx - z - 1, y, cz + x, material, color); // point in octant 3
setBlockTypeAndColor(cx - x - 1, y, cz + z, material, color); // point in octant 4
setBlockTypeAndColor(cx - x - 1, y, cz - z - 1, material, color); // point in octant 5
setBlockTypeAndColor(cx - z - 1, y, cz - x - 1, material, color); // point in octant 6
setBlockTypeAndColor(cx + z, y, cz - x - 1, material, color); // point in octant 7
setBlockTypeAndColor(cx + x, y, cz - z - 1, material, color); // point in octant 8
}
private void drawCircleBlocks(int cx, int cz, int x, int z, int y1, int y2, Material material, DyeColor color) {
for (int y = y1; y < y2; y++) {
drawCircleBlocks(cx, cz, x, z, y, material, color);
}
}
private void fillCircleBlocks(int cx, int cz, int x, int z, int y, Material material, DyeColor color) {
// Ref: Notes/BCircle.PDF
setBlocksTypeAndColor(cx - x - 1, cx - x, y, cz - z - 1, cz + z + 1, material, color); // point in octant 5
setBlocksTypeAndColor(cx - z - 1, cx - z, y, cz - x - 1, cz + x + 1, material, color); // point in octant 6
setBlocksTypeAndColor(cx + z, cx + z + 1, y, cz - x - 1, cz + x + 1, material, color); // point in octant 7
setBlocksTypeAndColor(cx + x, cx + x + 1, y, cz - z - 1, cz + z + 1, material, color); // point in octant 8
}
private void fillCircleBlocks(int cx, int cz, int x, int z, int y1, int y2, Material material, DyeColor color) {
for (int y = y1; y < y2; y++) {
fillCircleBlocks(cx, cz, x, z, y, material, color);
}
}
public final void setCircle(int cx, int cz, int r, int y, Material material, DyeColor color) {
setCircle(cx, cz, r, y, y + 1, material, color, false);
}
public final void setCircle(int cx, int cz, int r, int y, Material material, DyeColor color, boolean fill) {
setCircle(cx, cz, r, y, y + 1, material, color, fill);
}
public final void setCircle(int cx, int cz, int r, int y1, int y2, Material material, DyeColor color) {
setCircle(cx, cz, r, y1, y2, material, color, false);
}
public final void setCircle(int cx, int cz, int r, int y1, int y2, Material material, DyeColor color, boolean fill) {
// Ref: Notes/BCircle.PDF
int x = r;
int z = 0;
int xChange = 1 - 2 * r;
int zChange = 1;
int rError = 0;
while (x >= z) {
if (fill)
fillCircleBlocks(cx, cz, x, z, y1, y2, material, color);
else
drawCircleBlocks(cx, cz, x, z, y1, y2, material, color);
z++;
rError += zChange;
zChange += 2;
if (2 * rError + xChange > 0) {
x--;
rError += xChange;
xChange += 2;
}
}
}
public final boolean isNonstackableBlock(Block block) { // either because it really isn't or it just doesn't look good
switch (block.getType()) {
default:
return true;
case STONE:
case GRASS:
case DIRT:
case COBBLESTONE:
case WOOD:
case SAND:
case GRAVEL:
case COAL_ORE:
case DIAMOND_ORE:
case EMERALD_ORE:
case GOLD_ORE:
case IRON_ORE:
case LAPIS_ORE:
case QUARTZ_ORE:
case REDSTONE_ORE:
case COAL_BLOCK:
case DIAMOND_BLOCK:
case EMERALD_BLOCK:
case GOLD_BLOCK:
case HAY_BLOCK:
case IRON_BLOCK:
case LAPIS_BLOCK:
case PURPUR_BLOCK:
case QUARTZ_BLOCK:
case SLIME_BLOCK:
case SNOW_BLOCK:
case LOG:
case LOG_2:
case SPONGE:
case SANDSTONE:
case RED_SANDSTONE:
case SOUL_SAND:
case STAINED_CLAY:
case HARD_CLAY:
case CLAY:
case WOOL:
case DOUBLE_STEP:
case WOOD_DOUBLE_STEP:
case DOUBLE_STONE_SLAB2:
case PURPUR_DOUBLE_SLAB:
case BRICK:
case END_BRICKS:
case NETHER_BRICK:
case SMOOTH_BRICK:
case BOOKSHELF:
case MOSSY_COBBLESTONE:
case OBSIDIAN:
case SOIL:
case ICE:
case PACKED_ICE:
case FROSTED_ICE:
case NETHERRACK:
case ENDER_STONE:
case MYCEL:
case PRISMARINE:
case GRASS_PATH:
case BEDROCK:
return false;
}
// return isType(block, Material.STONE_SLAB, Material.WOOD_STEP,
// Material.GLASS, Material.GLASS_PANE,
// Material.SNOW, Material.CARPET, Material.SIGN,
// Material.WOOD_DOOR, Material.TRAP_DOOR,
// Material.WHITE_STAINED_GLASS, Material.WHITE_STAINED_GLASS_PANE,
// Material.SPRUCE_FENCE, Material.SPRUCE_FENCE_GATE,
// Material.STONE_PRESSURE_PLATE, Material.BIRCH_PRESSURE_PLATE,
// Material.TRIPWIRE, Material.TRIPWIRE_HOOK,
// Material.IRON_DOOR_BLOCK, Material.IRON_BARS);
}
public final boolean isNonstackableBlock(int x, int y, int z) {
return isNonstackableBlock(getActualBlock(x, y, z));
}
private boolean isColorable(Material material) {
switch (material) {
default:
return false;
case STAINED_CLAY:
case STAINED_GLASS:
case STAINED_GLASS_PANE:
case WOOL:
case CARPET:
case CONCRETE:
case CONCRETE_POWDER:
return true;
}
}
public void setBlockTypeAndColor(int x, int y, int z, Material material, DyeColor color) {
BlockState state = getActualBlock(x, y, z).getState();
state.setType(material);
if (isColorable(material)) {
MaterialData data = state.getData();
if (data instanceof Colorable)
((Colorable)state.getData()).setColor(color);
else
BlackMagic.setBlockStateColor(state, color); //BUKKIT: none of the newly colorable blocks materials are colorable
state.update(true, doPhysics);
}
}
public void setBlockIfTypeThenColor(int x, int y, int z, Material material, DyeColor color) {
BlockState state = getActualBlock(x, y, z).getState();
if (state.getType() == material && isColorable(material)) {
MaterialData data = state.getData();
if (data instanceof Colorable)
((Colorable)state.getData()).setColor(color);
else
BlackMagic.setBlockStateColor(state, color); //BUKKIT: none of the newly colorable blocks materials are colorable
state.update(true, doPhysics);
}
}
public void setBlocksTypeAndColor(int x, int y1, int y2, int z, Material material, DyeColor color) {
if (isColorable(material))
for (int y = y1; y < y2; y++)
setBlockTypeAndColor(x, y, z, material, color);
else
setBlocks(x, y1, y2, z, material);
}
public void setBlocksTypeAndColor(int x1, int x2, int y, int z1, int z2, Material material, DyeColor color) {
if (isColorable(material))
for (int x = x1; x < x2; x++) {
for (int z = z1; z < z2; z++) {
setBlockTypeAndColor(x, y, z, material, color);
}
}
else
setBlocks(x1, x2, y, z1, z2, material);
}
public void setBlocksTypeAndColor(int x1, int x2, int y1, int y2, int z1, int z2, Material material, DyeColor color) {
if (isColorable(material))
for (int x = x1; x < x2; x++) {
for (int y = y1; y < y2; y++) {
for (int z = z1; z < z2; z++) {
setBlockTypeAndColor(x, y, z, material, color);
}
}
}
else
setBlocks(x1, x2, y1, y2, z1, z2, material);
}
public void setBlockTypeAndDirection(int x, int y, int z, Material material, BlockFace facing) {
BlockState state = getActualBlock(x, y, z).getState();
state.setType(material);
MaterialData data = state.getData();
if (data instanceof Directional)
((Directional)state.getData()).setFacingDirection(facing);
state.update(true, doPhysics);
}
public void setBlocksTypeAndDirection(int x1, int x2, int y1, int y2, int z1, int z2, Material material, BlockFace facing) {
for (int x = x1; x < x2; x++) {
for (int y = y1; y < y2; y++) {
for (int z = z1; z < z2; z++) {
setBlockTypeAndDirection(x, y, z, material, facing);
}
}
}
}
public void setBlockTypeAndTexture(int x, int y, int z, Material material, Material texture) {
BlockState state = getActualBlock(x, y, z).getState();
state.setType(material);
MaterialData data = state.getData();
if (data instanceof TexturedMaterial)
((TexturedMaterial)state.getData()).setMaterial(texture);
state.update(true, doPhysics);
}
private int clamp(int value, int max) {
return Math.max(Math.min(value, max), 0);
}
public final void setSnowCover(int x, int y, int z, int level) {
Block block = getActualBlock(x, y, z);
if (block.isEmpty())
BlackMagic.setBlockType(block, Material.SNOW, clamp(level, BlackMagic.maxSnowLevel));
}
public final void setCauldron(int x, int y, int z, int level) {
Block block = getActualBlock(x, y, z);
BlackMagic.setBlockType(block, Material.CAULDRON, clamp(level, BlackMagic.maxCauldronLevel));
}
public final void setCauldron(int x, int y, int z, Odds odds) {
setCauldron(x, y, z, odds.getCauldronLevel());
}
public final void setWool(int x, int y, int z, DyeColor color) {
setBlockTypeAndColor(x, y, z, Material.WHITE_WOOL, color);
}
public final void setWool(int x1, int x2, int y1, int y2, int z1, int z2, DyeColor color) {
setBlocksTypeAndColor(x1, x2, y1, y2, z1, z2, Material.WHITE_WOOL, color);
}
public final void setClay(int x, int y, int z, DyeColor color) {
setBlockTypeAndColor(x, y, z, Material.WHITE_TERRACOTTA, color);
}
public final void setClay(int x, int y1, int y2, int z, DyeColor color) {
setBlocksTypeAndColor(x, x + 1, y1, y2, z, z + 1, Material.WHITE_TERRACOTTA, color);
}
public final void setClay(int x1, int x2, int y, int z1, int z2, DyeColor color) {
setBlocksTypeAndColor(x1, x2, y, y + 1, z1, z2, Material.WHITE_TERRACOTTA, color);
}
public final void setClay(int x1, int x2, int y1, int y2, int z1, int z2, DyeColor color) {
setBlocksTypeAndColor(x1, x2, y1, y2, z1, z2, Material.WHITE_TERRACOTTA, color);
}
public final void setClayWalls(int x1, int x2, int y1, int y2, int z1, int z2, DyeColor color) {
setBlocksTypeAndColor(x1, x2, y1, y2, z1, z1 + 1, Material.WHITE_TERRACOTTA, color);
setBlocksTypeAndColor(x1, x2, y1, y2, z2 - 1, z2, Material.WHITE_TERRACOTTA, color);
setBlocksTypeAndColor(x1, x1 + 1, y1, y2, z1 + 1, z2 - 1, Material.WHITE_TERRACOTTA, color);
setBlocksTypeAndColor(x2 - 1, x2, y1, y2, z1 + 1, z2 - 1, Material.WHITE_TERRACOTTA, color);
}
public final void camoClay(int x1, int x2, int y1, int y2, int z1, int z2, Odds odds, ColorSet colors) {
for (int x = x1; x < x2; x++) {
for (int y = y1; y < y2; y++) {
for (int z = z1; z < z2; z++) {
setBlockIfTypeThenColor(x, y, z, Material.WHITE_TERRACOTTA, odds.getRandomColor(colors));
}
}
}
}
public final void setGlass(int x, int y, int z, DyeColor color) {
setBlockTypeAndColor(x, y, z, Material.WHITE_STAINED_GLASS, color);
}
public final void setGlass(int x1, int x2, int y1, int y2, int z1, int z2, DyeColor color) {
setBlocksTypeAndColor(x1, x2, y1, y2, z1, z2, Material.WHITE_STAINED_GLASS, color);
}
public final void setGlassWalls(int x1, int x2, int y1, int y2, int z1, int z2, DyeColor color) {
setBlocksTypeAndColor(x1, x2, y1, y2, z1, z1 + 1, Material.WHITE_STAINED_GLASS, color);
setBlocksTypeAndColor(x1, x2, y1, y2, z2 - 1, z2, Material.WHITE_STAINED_GLASS, color);
setBlocksTypeAndColor(x1, x1 + 1, y1, y2, z1 + 1, z2 - 1, Material.WHITE_STAINED_GLASS, color);
setBlocksTypeAndColor(x2 - 1, x2, y1, y2, z1 + 1, z2 - 1, Material.WHITE_STAINED_GLASS, color);
}
public final void setThinGlass(int x, int y, int z, DyeColor color) {
setBlockTypeAndColor(x, y, z, Material.WHITE_STAINED_GLASS_PANE, color);
}
public final void setThinGlass(int x1, int x2, int y1, int y2, int z1, int z2, DyeColor color) {
setBlocksTypeAndColor(x1, x2, y1, y2, z1, z2, Material.WHITE_STAINED_GLASS_PANE, color);
}
public final void setThinGlassWalls(int x1, int x2, int y1, int y2, int z1, int z2, DyeColor color) {
setBlocksTypeAndColor(x1, x2, y1, y2, z1, z1 + 1, Material.WHITE_STAINED_GLASS_PANE, color);
setBlocksTypeAndColor(x1, x2, y1, y2, z2 - 1, z2, Material.WHITE_STAINED_GLASS_PANE, color);
setBlocksTypeAndColor(x1, x1 + 1, y1, y2, z1 + 1, z2 - 1, Material.WHITE_STAINED_GLASS_PANE, color);
setBlocksTypeAndColor(x2 - 1, x2, y1, y2, z1 + 1, z2 - 1, Material.WHITE_STAINED_GLASS_PANE, color);
}
public final void setVines(int x, int y1, int y2, int z, BlockFace... faces) {
Vine data = new Vine(faces);
for (int y = y1; y < y2; y++) {
Block block = getActualBlock(x, y, z);
if (block.getType() == Material.VINE) {
BlockState state = block.getState();
Vine vines = (Vine)(state.getData());
for (BlockFace face: faces)
vines.putOnFace(face);
state.update();
} else
setActualBlock(getActualBlock(x, y, z), Material.VINE, data);
}
}
public final void setSlab(int x, int y, int z, Material material, boolean inverted) {
Step data = new Step(material);
data.setInverted(inverted);
setBlock(x, y, z, Material.STONE_SLAB, data);
}
public final void setSlabs(int x1, int x2, int y, int z1, int z2, Material material, boolean inverted) {
Step data = new Step(material);
data.setInverted(inverted);
setBlocks(x1, x2, y, z1, z2, Material.STONE_SLAB, data);
}
public final void setSlabs(int x1, int x2, int y1, int y2, int z1, int z2, Material material, boolean inverted) {
Step data = new Step(material);
data.setInverted(inverted);
setBlocks(x1, x2, y1, y2, z1, z2, Material.STONE_SLAB, data);
}
public final void setSlab(int x, int y, int z, TreeSpecies species, boolean inverted) {
WoodenStep data = new WoodenStep(species);
data.setInverted(inverted);
setBlock(x, y, z, Material.STONE_SLAB, data);
}
public final void setSlabs(int x1, int x2, int y, int z1, int z2, TreeSpecies species, boolean inverted) {
WoodenStep data = new WoodenStep(species);
data.setInverted(inverted);
setBlocks(x1, x2, y, z1, z2, Material.WOOD_STEP, data);
}
public final void setSlabs(int x1, int x2, int y1, int y2, int z1, int z2, TreeSpecies species, boolean inverted) {
WoodenStep data = new WoodenStep(species);
data.setInverted(inverted);
setBlocks(x1, x2, y1, y2, z1, z2, Material.WOOD_STEP, data);
}
public final void setWood(int x, int y, int z, TreeSpecies species) {
Tree data = new Tree(species);
setBlock(x, y, z, Material.SPRUCE_WOOD, data);
}
public final void setLog(int x, int y, int z, Material material, TreeSpecies species, BlockFace facing) {
Tree data = new Tree(species, facing);
setBlock(x, y, z, material, data);
}
public final void setLogs(int x, int y1, int y2, int z, Material material, TreeSpecies species, BlockFace facing) {
Tree data = new Tree(species, facing);
setBlocks(x, x + 1, y1, y2, z, z + 1, material, data);
}
public final void setLogs(int x1, int x2, int y1, int y2, int z1, int z2, Material material, TreeSpecies species, BlockFace facing) {
Tree data = new Tree(species, facing);
setBlocks(x1, x2, y1, y2, z1, z2, material, data);
}
public final void setLeave(int x, int y, int z, Material material, TreeSpecies species) {
Leaves data = new Leaves(species);
setBlock(x, y, z, material, data);
}
public final void setLeaves(int x, int y1, int y2, int z, Material material, TreeSpecies species) {
Leaves data = new Leaves(species);
setBlocks(x, x + 1, y1, y2, z, z + 1, material, data);
}
public final void setLeaves(int x1, int x2, int y1, int y2, int z1, int z2, Material material, TreeSpecies species) {
Leaves data = new Leaves(species);
setBlocks(x1, x2, y1, y2, z1, z2, material, data);
}
public final void drawCrane(DataContext context, Odds odds, int x, int y, int z) {
// vertical bit
setBlocks(x, y, y + 8, z, Material.IRON_BARS);
setBlocks(x - 1, y, y + 8, z, Material.IRON_BARS); // 1.9 shows iron fences very thin now
setBlocks(x, y + 8, y + 10, z, Material.DOUBLE_STEP);
setBlocks(x - 1, y + 8, y + 10, z, Material.STONE_SLAB);
setBlockTypeAndDirection(x, y + 10, z, context.torchMat, BlockFace.UP);
// horizontal bit
setBlock(x + 1, y + 8, z, Material.GLASS);
setBlocks(x + 2, x + 11, y + 8, y + 9, z, z + 1, Material.IRON_BARS);
setBlocks(x + 1, x + 10, y + 9, y + 10, z, z + 1, Material.STONE_SLAB);
setStair(x + 10, y + 9, z, Material.STONE_BRICK_STAIRS, BlockFace.WEST);
// counter weight
setBlock(x - 2, y + 9, z, Material.STONE_SLAB);
setStair(x - 3, y + 9, z, Material.STONE_BRICK_STAIRS, BlockFace.EAST);
setWool(x - 3, x - 1, y + 7, y + 9, z, z + 1, odds.getRandomColor());
}
public final void setTable(int x1, int x2, int y, int z1, int z2) {
setTable(x1, x2, y, z1, z2, Material.STONE_PRESSURE_PLATE);
}
public final void setTable(int x, int y, int z) {
setTable(x, y, z, Material.STONE_PRESSURE_PLATE);
}
public final void setTable(int x1, int x2, int y, int z1, int z2, Material tableTop) {
setTable(x1, x2, y, z1, z2, Material.SPRUCE_FENCE, tableTop);
}
public final void setTable(int x, int y, int z, Material tableTop) {
setTable(x, y, z, Material.SPRUCE_FENCE, tableTop);
}
public final void setTable(int x1, int x2, int y, int z1, int z2, Material tableLeg, Material tableTop) {
for (int x = x1; x < x2; x++) {
for (int z = z1; z < z2; z++) {
setTable(x, y, z, tableLeg, tableTop);
}
}
}
public final void setTable(int x, int y, int z, Material tableLeg, Material tableTop) {
setBlock(x, y, z, tableLeg);
setBlock(x, y + 1, z, tableTop);
}
public void setDoor(int x, int y, int z, Material material, BadMagic.Door direction) {
byte orentation = 0;
byte hinge = 0;
// orientation
switch (direction) {
case NORTHBYNORTHEAST:
case NORTH_NORTH_WEST:
orentation = 1;
break;
case SOUTH_SOUTH_EAST:
case SOUTHBYSOUTHWEST:
orentation = 3;
break;
case WEST_NORTH_WEST:
case WESTBYSOUTHWEST:
orentation = 0;
break;
case EAST_NORTH_EAST:
case EASTBYSOUTHEAST:
orentation = 2;
break;
}
// hinge?
switch (direction) {
case SOUTH_SOUTH_EAST:
case NORTH_NORTH_WEST:
case WESTBYSOUTHWEST:
case EAST_NORTH_EAST:
hinge = 8 + 0;
break;
case NORTHBYNORTHEAST:
case SOUTHBYSOUTHWEST:
case WEST_NORTH_WEST:
case EASTBYSOUTHEAST:
hinge = 8 + 1;
break;
}
// set the door
BlackMagic.setBlockType(getActualBlock(x, y , z), material, orentation, true, false);
BlackMagic.setBlockType(getActualBlock(x, y + 1, z), material, hinge, true, true);
}
public final void setWoodenDoor(int x, int y, int z, BadMagic.Door direction) {
setDoor(x, y, z, Material.OAK_DOOR, direction);
}
public final void setIronDoor(int x, int y, int z, BadMagic.Door direction) {
setDoor(x, y, z, Material.IRON_DOOR_BLOCK, direction);
}
public final void setTrapDoor(int x, int y, int z, BadMagic.TrapDoor direction) {
BlackMagic.setBlock(this, x, y, z, Material.TRAP_DOOR, direction.getData());
}
public final void setStoneSlab(int x, int y, int z, BadMagic.StoneSlab direction) {
BlackMagic.setBlock(this, x, y, z, Material.STONE_SLAB, direction.getData());
}
public final void setLadder(int x, int y1, int y2, int z, BlockFace direction) {
int offsetX = 0;
int offsetZ = 0;
switch (direction) {
case WEST:
offsetX = -1;
break;
case EAST:
offsetX = 1;
break;
case NORTH:
offsetZ = -1;
break;
case SOUTH:
default:
offsetZ = 1;
break;
}
for (int y = y1; y < y2; y++) {
if (!isEmpty(x + offsetX, y, z + offsetZ)) {
Ladder data = new Ladder();
data.setFacingDirection(direction);
setBlock(x, y, z, Material.LADDER, data);
}
}
}
public final void setStair(int x, int y, int z, Material material, BadMagic.Stair direction) {
BlackMagic.setBlock(this, x, y, z, material, direction.getData());
}
public final void setStairs(int x1, int x2, int y, int z1, int z2, Material material, BadMagic.Stair direction) {
for (int x = x1; x < x2; x++)
for (int z = z1; z < z2; z++)
setStair(x, y, z, material, direction);
}
public static final Material filterStairMaterial(Material material) {
switch (material) {
case BRICK:
case BRICK_STAIRS:
return Material.BRICK_STAIRS;
case COBBLESTONE:
case MOSSY_COBBLESTONE:
case COBBLESTONE_STAIRS:
return Material.COBBLESTONE_STAIRS;
case NETHERRACK:
case NETHER_BRICK:
case NETHER_BRICK_STAIRS:
return Material.NETHER_BRICK_STAIRS;
case PURPUR_BLOCK:
case PURPUR_SLAB:
case PURPUR_DOUBLE_SLAB:
case PURPUR_STAIRS:
return Material.PURPUR_STAIRS;
case RED_SANDSTONE:
case RED_SANDSTONE_STAIRS:
return Material.RED_SANDSTONE_STAIRS;
case SAND:
case SANDSTONE:
case SANDSTONE_STAIRS:
return Material.SANDSTONE_STAIRS;
case SMOOTH_BRICK:
case STONE_BRICK_STAIRS:
return Material.STONE_BRICK_STAIRS;
case WOOL: // it is white too!
case QUARTZ_BLOCK:
case QUARTZ_STAIRS:
return Material.QUARTZ_STAIRS;
default:
// case WOOD:
return Material.BIRCH_STAIRS;
}
}
public final void setVine(int x, int y, int z, BadMagic.Vine direction) {
BlackMagic.setBlock(this, x, y, z, Material.VINE, direction.getData());
}
public final void setTorch(int x, int y, int z, Material material, BadMagic.Torch direction) {
BlackMagic.setBlock(this, x, y, z, material, direction.getData());
}
public final void setFurnace(int x, int y, int z, BadMagic.General direction) {
BlackMagic.setBlock(this, x, y, z, Material.FURNACE, direction.getData());
}
public final void setChest(CityWorldGenerator generator, int x, int y, int z, BadMagic.General direction, Odds odds, LootProvider lootProvider, LootLocation lootLocation) {
Block block = getActualBlock(x, y, z);
if (BlackMagic.setBlockType(block, Material.CHEST, direction.getData())) {
if (block.getType() == Material.CHEST) {
lootProvider.setLoot(generator, odds, world.getName(), lootLocation, block);
}
}
}
// public final void setVine(int x, int y, int z, BlockFace ... facing) {
// setBlock(x, y, z, new Vine(facing));
// }
//
// public final void setTorch(int x, int y, int z, Material material, BlockFace facing) {
// setBlock(x, y, z, new Torch(material, facing));
// }
//
// public final void setFurnace(int x, int y, int z, BlockFace facing) {
// setBlock(x, y, z, new Furnace(facing));
// }
public final void setChest(CityWorldGenerator generator, int x, int y, int z, BlockFace facing, Odds odds, LootProvider lootProvider, LootLocation lootLocation) {
Block block = getActualBlock(x, y, z, new Chest(facing));
if (isType(block, Material.CHEST))
lootProvider.setLoot(generator, odds, world.getName(), lootLocation, block);
}
public final void setDoubleChest(CityWorldGenerator generator, int x, int y, int z, BadMagic.General direction, Odds odds, LootProvider lootProvider, LootLocation lootLocation) {
switch (direction) {
case EAST:
case WEST:
setChest(generator, x, y, z, direction, odds, lootProvider, lootLocation);
setChest(generator, x, y, z + 1, direction, odds, lootProvider, lootLocation);
break;
case NORTH:
case SOUTH:
setChest(generator, x, y, z, direction, odds, lootProvider, lootLocation);
setChest(generator, x + 1, y, z, direction, odds, lootProvider, lootLocation);
break;
}
}
public final void setWallSign(int x, int y, int z, BadMagic.General direction, String[] text) {
Block block = getActualBlock(x, y, z);
if (BlackMagic.setBlockType(block, Material.WALL_SIGN, direction.getData())) {
if (block.getType() == Material.WALL_SIGN) {
Sign sign = (Sign) block.getState();
for (int i = 0; i < text.length && i < 4; i++)
sign.setLine(i, text[i]);
sign.update(true);
}
}
}
// WE SHOULD BE USING THIS, INSTEAD OF setWallSign
// public final void setSignPost(int x, int y, int z, BlockFace direction, String ... text) {
// Block block = getActualBlock(x, y, z);
// block.setType(Material.SIGN_POST);
// if (block.getType() == Material.SIGN_POST) {
// Sign signState = (Sign) block.getState();
//
// org.bukkit.material.Sign signDirection = new org.bukkit.material.Sign();
// signDirection.setFacingDirection(direction);
// signState.setData(signDirection);
//
// for (int i = 0; i < text.length && i < 4; i++)
// signState.setLine(i, text[i]);
//
// signState.update();
// }
// }
public final void setBed(int x, int y, int z, Facing direction) {
switch (direction) {
case EAST:
BlackMagic.setBlockType(getActualBlock(x, y, z), Material.BED_BLOCK, (byte)(0x1 + 0x8), true, false);
BlackMagic.setBlockType(getActualBlock(x + 1, y, z), Material.BED_BLOCK, (byte)(0x1), true, true);
break;
case SOUTH:
BlackMagic.setBlockType(getActualBlock(x, y, z), Material.BED_BLOCK, (byte)(0x2 + 0x8), true, false);
BlackMagic.setBlockType(getActualBlock(x, y, z + 1), Material.BED_BLOCK, (byte)(0x2), true, true);
break;
case WEST:
BlackMagic.setBlockType(getActualBlock(x, y, z), Material.BED_BLOCK, (byte)(0x3 + 0x8), true, false);
BlackMagic.setBlockType(getActualBlock(x + 1, y, z), Material.BED_BLOCK, (byte)(0x3), true, true);
break;
case NORTH:
BlackMagic.setBlockType(getActualBlock(x, y, z), Material.BED_BLOCK, (byte)(0x0 + 0x8), true, false);
BlackMagic.setBlockType(getActualBlock(x, y, z + 1), Material.BED_BLOCK, (byte)(0x0), true, true);
break;
}
}
}
| 0 | 0.941425 | 1 | 0.941425 | game-dev | MEDIA | 0.585916 | game-dev | 0.905837 | 1 | 0.905837 |
Tp0t-Team/Tp0tOJ | 3,511 | server/services/database/resolvers/gameEvent.go | package resolvers
import (
"errors"
"gorm.io/gorm"
"log"
"server/entity"
"time"
)
func AddEvent(eventAction int, eventTime time.Time) bool {
event := entity.GameEvent{
Time: eventTime,
Action: uint64(eventAction),
}
result := db.Create(&event)
if result.Error != nil {
log.Println(result.Error)
return false
}
return true
}
func UpdateEvent(eventId uint64, eventTime time.Time) bool {
var event entity.GameEvent
result := db.Where(map[string]interface{}{"event_id": eventId}).First(&event)
if result.Error != nil {
log.Println(errors.New("Update Event error:\n" + result.Error.Error()))
return false
}
event.Time = eventTime
result = db.Save(&event)
if result.Error != nil {
log.Println(result.Error)
return false
}
return true
}
func DeleteEvent(eventId uint64) bool {
var event entity.GameEvent
result := db.Where(map[string]interface{}{"event_id": eventId}).First(&event)
if result.Error != nil {
log.Println(errors.New("Update Event error:\n" + result.Error.Error()))
return false
}
result = db.Delete(&event)
if result.Error != nil {
log.Println(result.Error)
return false
}
return true
}
func GetAllEvents() []entity.GameEvent {
var events []entity.GameEvent
result := db.Where(map[string]interface{}{}).Find(&events)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return []entity.GameEvent{}
} else if result.Error != nil {
log.Println(result.Error)
return nil
}
return events
}
func IsGameRunning(outsideTX *gorm.DB) bool {
if outsideTX == nil {
outsideTX = db
}
currentTime := time.Now()
var currentEvent entity.GameEvent
var events []entity.GameEvent
result := outsideTX.Where(map[string]interface{}{"action": entity.PauseEvent}).Or(map[string]interface{}{"action": entity.ResumeEvent}).Find(&events)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return true
} else if result.Error != nil {
log.Println(result.Error)
return false
}
if len(events) == 0 {
return true
}
result = outsideTX.Where(
outsideTX.Where(map[string]interface{}{"action": entity.PauseEvent}).Or(map[string]interface{}{"action": entity.ResumeEvent}),
).Where("time <= ?", currentTime).Order("time desc").First(¤tEvent)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return false
} else if result.Error != nil {
log.Println(result.Error)
return false
}
if currentEvent.Action == entity.ResumeEvent {
return true
} else {
return false
}
}
func IsRegistryAllow(outsideTX *gorm.DB) bool {
if outsideTX == nil {
outsideTX = db
}
currentTime := time.Now()
var currentEvent entity.GameEvent
var events []entity.GameEvent
result := outsideTX.Where(map[string]interface{}{"action": entity.AllowRegistrationEvent}).Or(map[string]interface{}{"action": entity.DenyRegistrationEvent}).Find(&events)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return true
} else if result.Error != nil {
log.Println(result.Error)
return false
}
if len(events) == 0 {
return true
}
result = outsideTX.Where(
outsideTX.Where(map[string]interface{}{"action": entity.AllowRegistrationEvent}).Or(map[string]interface{}{"action": entity.DenyRegistrationEvent}),
).Where("time <= ?", currentTime).Order("time desc").First(¤tEvent)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return false
} else if result.Error != nil {
log.Println(result.Error)
return false
}
if currentEvent.Action == entity.AllowRegistrationEvent {
return true
} else {
return false
}
}
| 0 | 0.832506 | 1 | 0.832506 | game-dev | MEDIA | 0.883522 | game-dev | 0.797503 | 1 | 0.797503 |
MangosServer/MangosSharp | 11,598 | src/server/Mangos.World/Objects/WS_DynamicObjects.cs | //
// Copyright (C) 2013-2025 getMaNGOS <https://www.getmangos.eu>
//
// 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
//
using Mangos.Common.Enums.Global;
using Mangos.Common.Globals;
using Mangos.World.Globals;
using Mangos.World.Maps;
using Mangos.World.Player;
using Mangos.World.Spells;
using Microsoft.VisualBasic.CompilerServices;
using System;
using System.Collections.Generic;
namespace Mangos.World.Objects;
public class WS_DynamicObjects
{
public class DynamicObject : WS_Base.BaseObject, IDisposable
{
public int SpellID;
public List<WS_Spells.SpellEffect> Effects;
public int Duration;
public float Radius;
public WS_Base.BaseUnit Caster;
public int CastTime;
public int Bytes;
private bool _disposedValue;
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
WorldServiceLocator.WorldServer.WORLD_DYNAMICOBJECTs.Remove(GUID);
}
_disposedValue = true;
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
void IDisposable.Dispose()
{
//ILSpy generated this explicit interface implementation from .override directive in Dispose
Dispose();
}
public DynamicObject(ref WS_Base.BaseUnit Caster_, int SpellID_, float PosX, float PosY, float PosZ, int Duration_, float Radius_)
{
SpellID = 0;
Effects = new List<WS_Spells.SpellEffect>();
Duration = 0;
Radius = 0f;
CastTime = 0;
Bytes = 1;
GUID = WorldServiceLocator.WSDynamicObjects.GetNewGUID();
WorldServiceLocator.WorldServer.WORLD_DYNAMICOBJECTs.Add(GUID, this);
Caster = Caster_;
SpellID = SpellID_;
positionX = PosX;
positionY = PosY;
positionZ = PosZ;
orientation = 0f;
MapID = Caster.MapID;
instance = Caster.instance;
Duration = Duration_;
Radius = Radius_;
CastTime = WorldServiceLocator.NativeMethods.timeGetTime("");
}
public void FillAllUpdateFlags(ref Packets.UpdateClass Update)
{
Update.SetUpdateFlag(0, GUID);
Update.SetUpdateFlag(2, 65);
Update.SetUpdateFlag(4, 0.5f * Radius);
Update.SetUpdateFlag(6, Caster.GUID);
Update.SetUpdateFlag(8, Bytes);
Update.SetUpdateFlag(9, SpellID);
Update.SetUpdateFlag(10, Radius);
Update.SetUpdateFlag(11, positionX);
Update.SetUpdateFlag(12, positionY);
Update.SetUpdateFlag(13, positionZ);
Update.SetUpdateFlag(14, orientation);
}
public void AddToWorld()
{
WorldServiceLocator.WSMaps.GetMapTile(positionX, positionY, ref CellX, ref CellY);
if (WorldServiceLocator.WSMaps.Maps[MapID].Tiles[CellX, CellY] == null)
{
WorldServiceLocator.WSCharMovement.MAP_Load(CellX, CellY, MapID);
}
try
{
WorldServiceLocator.WSMaps.Maps[MapID].Tiles[CellX, CellY].DynamicObjectsHere.Add(GUID);
}
catch (Exception projectError)
{
ProjectData.SetProjectError(projectError);
WorldServiceLocator.WorldServer.Log.WriteLine(LogType.WARNING, "AddToWorld failed MapId: {0} Tile XY: {1} {2} GUID: {3}", MapID, CellX, CellY, GUID);
ProjectData.ClearProjectError();
return;
}
Packets.PacketClass packet = new(Opcodes.SMSG_UPDATE_OBJECT);
packet.AddInt32(1);
packet.AddInt8(0);
Packets.UpdateClass tmpUpdate = new(WorldServiceLocator.GlobalConstants.FIELD_MASK_SIZE_DYNAMICOBJECT);
FillAllUpdateFlags(ref tmpUpdate);
var updateClass = tmpUpdate;
var updateObject = this;
updateClass.AddToPacket(ref packet, ObjectUpdateType.UPDATETYPE_CREATE_OBJECT_SELF, ref updateObject);
tmpUpdate.Dispose();
short i = -1;
checked
{
do
{
short j = -1;
do
{
if ((short)unchecked(CellX + i) >= 0 && (short)unchecked(CellX + i) <= 63 && (short)unchecked(CellY + j) >= 0 && (short)unchecked(CellY + j) <= 63 && WorldServiceLocator.WSMaps.Maps[MapID].Tiles[(short)unchecked(CellX + i), (short)unchecked(CellY + j)] != null && WorldServiceLocator.WSMaps.Maps[MapID].Tiles[(short)unchecked(CellX + i), (short)unchecked(CellY + j)].PlayersHere.Count > 0)
{
var tMapTile = WorldServiceLocator.WSMaps.Maps[MapID].Tiles[(short)unchecked(CellX + i), (short)unchecked(CellY + j)];
var list = tMapTile.PlayersHere.ToArray();
var array = list;
foreach (var plGUID in array)
{
int num;
if (WorldServiceLocator.WorldServer.CHARACTERs.ContainsKey(plGUID))
{
var characterObject = WorldServiceLocator.WorldServer.CHARACTERs[plGUID];
WS_Base.BaseObject objCharacter = this;
num = characterObject.CanSee(ref objCharacter) ? 1 : 0;
}
else
{
num = 0;
}
if (num != 0)
{
WorldServiceLocator.WorldServer.CHARACTERs[plGUID].client.SendMultiplyPackets(ref packet);
WorldServiceLocator.WorldServer.CHARACTERs[plGUID].dynamicObjectsNear.Add(GUID);
SeenBy.Add(plGUID);
}
}
}
j = (short)unchecked(j + 1);
}
while (j <= 1);
i = (short)unchecked(i + 1);
}
while (i <= 1);
packet.Dispose();
}
}
public void RemoveFromWorld()
{
WorldServiceLocator.WSMaps.GetMapTile(positionX, positionY, ref CellX, ref CellY);
WorldServiceLocator.WSMaps.Maps[MapID].Tiles[CellX, CellY].DynamicObjectsHere.Remove(GUID);
var array = SeenBy.ToArray();
foreach (var plGUID in array)
{
if (WorldServiceLocator.WorldServer.CHARACTERs[plGUID].dynamicObjectsNear.Contains(GUID))
{
WorldServiceLocator.WorldServer.CHARACTERs[plGUID].guidsForRemoving_Lock.AcquireWriterLock(WorldServiceLocator.GlobalConstants.DEFAULT_LOCK_TIMEOUT);
WorldServiceLocator.WorldServer.CHARACTERs[plGUID].guidsForRemoving.Add(GUID);
WorldServiceLocator.WorldServer.CHARACTERs[plGUID].guidsForRemoving_Lock.ReleaseWriterLock();
WorldServiceLocator.WorldServer.CHARACTERs[plGUID].dynamicObjectsNear.Remove(GUID);
}
}
}
public void AddEffect(WS_Spells.SpellEffect EffectInfo)
{
Effects.Add(EffectInfo);
}
public void RemoveEffect(WS_Spells.SpellEffect EffectInfo)
{
Effects.Remove(EffectInfo);
}
public bool Update()
{
if (Caster == null)
{
return true;
}
var DeleteThis = false;
checked
{
if (Duration > 1000)
{
Duration -= 1000;
}
else
{
DeleteThis = true;
}
}
foreach (var effect in Effects)
{
var Effect = effect;
if (Effect.GetRadius == 0f)
{
if (Effect.Amplitude == 0 || checked(WorldServiceLocator.WSSpells.SPELLs[SpellID].GetDuration - Duration) % Effect.Amplitude == 0)
{
var obj = WorldServiceLocator.WSSpells.AURAs[Effect.ApplyAuraIndex];
ref var caster = ref Caster;
WS_Base.BaseObject baseObject = this;
obj(ref caster, ref baseObject, ref Effect, SpellID, 1, AuraAction.AURA_UPDATE);
}
continue;
}
var Targets = WorldServiceLocator.WSSpells.GetEnemyAtPoint(ref Caster, positionX, positionY, positionZ, Effect.GetRadius);
foreach (var item in Targets)
{
var Target = item;
if (Effect.Amplitude == 0 || checked(WorldServiceLocator.WSSpells.SPELLs[SpellID].GetDuration - Duration) % Effect.Amplitude == 0)
{
var obj2 = WorldServiceLocator.WSSpells.AURAs[Effect.ApplyAuraIndex];
WS_Base.BaseObject baseObject = this;
obj2(ref Target, ref baseObject, ref Effect, SpellID, 1, AuraAction.AURA_UPDATE);
}
}
}
if (DeleteThis)
{
Caster.dynamicObjects.Remove(this);
return true;
}
return false;
}
public void Spawn()
{
AddToWorld();
Packets.PacketClass packet = new(Opcodes.SMSG_GAMEOBJECT_SPAWN_ANIM);
packet.AddUInt64(GUID);
SendToNearPlayers(ref packet);
packet.Dispose();
}
public void Delete()
{
if (Caster != null && Caster.dynamicObjects.Contains(this))
{
Caster.dynamicObjects.Remove(this);
}
Packets.PacketClass packet = new(Opcodes.SMSG_GAMEOBJECT_DESPAWN_ANIM);
packet.AddUInt64(GUID);
SendToNearPlayers(ref packet);
packet.Dispose();
RemoveFromWorld();
Dispose();
}
}
private ulong GetNewGUID()
{
ref var dynamicObjectsGUIDCounter = ref WorldServiceLocator.WorldServer.DynamicObjectsGUIDCounter;
dynamicObjectsGUIDCounter = Convert.ToUInt64(decimal.Add(new decimal(dynamicObjectsGUIDCounter), 1m));
return WorldServiceLocator.WorldServer.DynamicObjectsGUIDCounter;
}
}
| 0 | 0.861457 | 1 | 0.861457 | game-dev | MEDIA | 0.943622 | game-dev | 0.951302 | 1 | 0.951302 |
supertuxkart/stk-code | 5,134 | lib/bullet/src/LinearMath/btQuickprof.h |
/***************************************************************************************************
**
** Real-Time Hierarchical Profiling for Game Programming Gems 3
**
** by Greg Hjelstrom & Byon Garrabrant
**
***************************************************************************************************/
// Credits: The Clock class was inspired by the Timer classes in
// Ogre (www.ogre3d.org).
#ifndef BT_QUICK_PROF_H
#define BT_QUICK_PROF_H
//To disable built-in profiling, please comment out next line
#define BT_NO_PROFILE 1
#ifndef BT_NO_PROFILE
#include <stdio.h>//@todo remove this, backwards compatibility
#include "btScalar.h"
#include "btAlignedAllocator.h"
#include <new>
#define USE_BT_CLOCK 1
#ifdef USE_BT_CLOCK
///The btClock is a portable basic clock that measures accurate time in seconds, use for profiling.
class btClock
{
public:
btClock();
btClock(const btClock& other);
btClock& operator=(const btClock& other);
~btClock();
/// Resets the initial reference time.
void reset();
/// Returns the time in ms since the last call to reset or since
/// the btClock was created.
unsigned long int getTimeMilliseconds();
/// Returns the time in us since the last call to reset or since
/// the Clock was created.
unsigned long int getTimeMicroseconds();
private:
struct btClockData* m_data;
};
#endif //USE_BT_CLOCK
///A node in the Profile Hierarchy Tree
class CProfileNode {
public:
CProfileNode( const char * name, CProfileNode * parent );
~CProfileNode( void );
CProfileNode * Get_Sub_Node( const char * name );
CProfileNode * Get_Parent( void ) { return Parent; }
CProfileNode * Get_Sibling( void ) { return Sibling; }
CProfileNode * Get_Child( void ) { return Child; }
void CleanupMemory();
void Reset( void );
void Call( void );
bool Return( void );
const char * Get_Name( void ) { return Name; }
int Get_Total_Calls( void ) { return TotalCalls; }
float Get_Total_Time( void ) { return TotalTime; }
void* GetUserPointer() const {return m_userPtr;}
void SetUserPointer(void* ptr) { m_userPtr = ptr;}
protected:
const char * Name;
int TotalCalls;
float TotalTime;
unsigned long int StartTime;
int RecursionCounter;
CProfileNode * Parent;
CProfileNode * Child;
CProfileNode * Sibling;
void* m_userPtr;
};
///An iterator to navigate through the tree
class CProfileIterator
{
public:
// Access all the children of the current parent
void First(void);
void Next(void);
bool Is_Done(void);
bool Is_Root(void) { return (CurrentParent->Get_Parent() == 0); }
void Enter_Child( int index ); // Make the given child the new parent
void Enter_Largest_Child( void ); // Make the largest child the new parent
void Enter_Parent( void ); // Make the current parent's parent the new parent
// Access the current child
const char * Get_Current_Name( void ) { return CurrentChild->Get_Name(); }
int Get_Current_Total_Calls( void ) { return CurrentChild->Get_Total_Calls(); }
float Get_Current_Total_Time( void ) { return CurrentChild->Get_Total_Time(); }
void* Get_Current_UserPointer( void ) { return CurrentChild->GetUserPointer(); }
void Set_Current_UserPointer(void* ptr) {CurrentChild->SetUserPointer(ptr);}
// Access the current parent
const char * Get_Current_Parent_Name( void ) { return CurrentParent->Get_Name(); }
int Get_Current_Parent_Total_Calls( void ) { return CurrentParent->Get_Total_Calls(); }
float Get_Current_Parent_Total_Time( void ) { return CurrentParent->Get_Total_Time(); }
protected:
CProfileNode * CurrentParent;
CProfileNode * CurrentChild;
CProfileIterator( CProfileNode * start );
friend class CProfileManager;
};
///The Manager for the Profile system
class CProfileManager {
public:
static void Start_Profile( const char * name );
static void Stop_Profile( void );
static void CleanupMemory(void)
{
Root.CleanupMemory();
}
static void Reset( void );
static void Increment_Frame_Counter( void );
static int Get_Frame_Count_Since_Reset( void ) { return FrameCounter; }
static float Get_Time_Since_Reset( void );
static CProfileIterator * Get_Iterator( void )
{
return new CProfileIterator( &Root );
}
static void Release_Iterator( CProfileIterator * iterator ) { delete ( iterator); }
static void dumpRecursive(CProfileIterator* profileIterator, int spacing);
static void dumpAll();
private:
static CProfileNode Root;
static CProfileNode * CurrentNode;
static int FrameCounter;
static unsigned long int ResetTime;
};
///ProfileSampleClass is a simple way to profile a function's scope
///Use the BT_PROFILE macro at the start of scope to time
class CProfileSample {
public:
CProfileSample( const char * name )
{
CProfileManager::Start_Profile( name );
}
~CProfileSample( void )
{
CProfileManager::Stop_Profile();
}
};
#define BT_PROFILE( name ) CProfileSample __profile( name )
#else
#define BT_PROFILE( name )
#endif //#ifndef BT_NO_PROFILE
#endif //BT_QUICK_PROF_H
| 0 | 0.970767 | 1 | 0.970767 | game-dev | MEDIA | 0.775238 | game-dev | 0.895652 | 1 | 0.895652 |
It-Life/Deer_GameFramework_Wolong | 4,137 | Assets/GameFramework/Libraries/Event/EventManager.cs | //------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------
using System;
namespace GameFramework.Event
{
/// <summary>
/// 事件管理器。
/// </summary>
internal sealed class EventManager : GameFrameworkModule, IEventManager
{
private readonly EventPool<GameEventArgs> m_EventPool;
/// <summary>
/// 初始化事件管理器的新实例。
/// </summary>
public EventManager()
{
m_EventPool = new EventPool<GameEventArgs>(EventPoolMode.AllowNoHandler | EventPoolMode.AllowMultiHandler);
}
/// <summary>
/// 获取事件处理函数的数量。
/// </summary>
public int EventHandlerCount
{
get
{
return m_EventPool.EventHandlerCount;
}
}
/// <summary>
/// 获取事件数量。
/// </summary>
public int EventCount
{
get
{
return m_EventPool.EventCount;
}
}
/// <summary>
/// 获取游戏框架模块优先级。
/// </summary>
/// <remarks>优先级较高的模块会优先轮询,并且关闭操作会后进行。</remarks>
internal override int Priority
{
get
{
return 7;
}
}
/// <summary>
/// 事件管理器轮询。
/// </summary>
/// <param name="elapseSeconds">逻辑流逝时间,以秒为单位。</param>
/// <param name="realElapseSeconds">真实流逝时间,以秒为单位。</param>
internal override void Update(float elapseSeconds, float realElapseSeconds)
{
m_EventPool.Update(elapseSeconds, realElapseSeconds);
}
/// <summary>
/// 关闭并清理事件管理器。
/// </summary>
internal override void Shutdown()
{
m_EventPool.Shutdown();
}
/// <summary>
/// 获取事件处理函数的数量。
/// </summary>
/// <param name="id">事件类型编号。</param>
/// <returns>事件处理函数的数量。</returns>
public int Count(int id)
{
return m_EventPool.Count(id);
}
/// <summary>
/// 检查是否存在事件处理函数。
/// </summary>
/// <param name="id">事件类型编号。</param>
/// <param name="handler">要检查的事件处理函数。</param>
/// <returns>是否存在事件处理函数。</returns>
public bool Check(int id, EventHandler<GameEventArgs> handler)
{
return m_EventPool.Check(id, handler);
}
/// <summary>
/// 订阅事件处理函数。
/// </summary>
/// <param name="id">事件类型编号。</param>
/// <param name="handler">要订阅的事件处理函数。</param>
public void Subscribe(int id, EventHandler<GameEventArgs> handler)
{
m_EventPool.Subscribe(id, handler);
}
/// <summary>
/// 取消订阅事件处理函数。
/// </summary>
/// <param name="id">事件类型编号。</param>
/// <param name="handler">要取消订阅的事件处理函数。</param>
public void Unsubscribe(int id, EventHandler<GameEventArgs> handler)
{
m_EventPool.Unsubscribe(id, handler);
}
/// <summary>
/// 设置默认事件处理函数。
/// </summary>
/// <param name="handler">要设置的默认事件处理函数。</param>
public void SetDefaultHandler(EventHandler<GameEventArgs> handler)
{
m_EventPool.SetDefaultHandler(handler);
}
/// <summary>
/// 抛出事件,这个操作是线程安全的,即使不在主线程中抛出,也可保证在主线程中回调事件处理函数,但事件会在抛出后的下一帧分发。
/// </summary>
/// <param name="sender">事件源。</param>
/// <param name="e">事件参数。</param>
public void Fire(object sender, GameEventArgs e)
{
m_EventPool.Fire(sender, e);
}
/// <summary>
/// 抛出事件立即模式,这个操作不是线程安全的,事件会立刻分发。
/// </summary>
/// <param name="sender">事件源。</param>
/// <param name="e">事件参数。</param>
public void FireNow(object sender, GameEventArgs e)
{
m_EventPool.FireNow(sender, e);
}
}
}
| 0 | 0.697525 | 1 | 0.697525 | game-dev | MEDIA | 0.878546 | game-dev | 0.830663 | 1 | 0.830663 |
SleepyTrousers/EnderCore | 21,099 | src/main/java/com/enderio/core/common/config/AbstractConfigHandler.java | package com.enderio.core.common.config;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import javax.annotation.Nonnull;
import com.enderio.core.EnderCore;
import com.enderio.core.api.common.config.IConfigHandler;
import com.enderio.core.common.Lang;
import com.enderio.core.common.event.ConfigFileChangedEvent;
import com.enderio.core.common.util.Bound;
import com.enderio.core.common.util.NullHelper;
import com.google.common.collect.ImmutableList;
import net.minecraft.client.Minecraft;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.common.config.Property.Type;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public abstract class AbstractConfigHandler implements IConfigHandler {
/**
* Represents a section in a config handler.
*/
public class Section {
public final String name;
public final String lang;
public Section(String name, String lang) {
this.name = name;
this.lang = "section." + lang;
}
Section register() {
sections.add(this);
return this;
}
public String lc() {
return name.toLowerCase(Locale.US);
}
}
public enum RestartReqs {
/**
* No restart needed for this config to be applied. Default value.
*/
NONE,
/**
* This config requires the world to be restarted to take effect.
*/
REQUIRES_WORLD_RESTART,
/**
* This config requires the game to be restarted to take effect. {@code REQUIRES_WORLD_RESTART} is implied when using this.
*/
REQUIRES_MC_RESTART;
public Property apply(Property prop) {
if (this == REQUIRES_MC_RESTART) {
prop.setRequiresMcRestart(true);
} else if (this == REQUIRES_WORLD_RESTART) {
prop.setRequiresWorldRestart(true);
}
return prop;
}
}
@Nonnull
String modid;
private Configuration config;
@Nonnull
List<Section> sections = new ArrayList<Section>();
private Section activeSection = null;
protected AbstractConfigHandler(@Nonnull String modid) {
this.modid = modid;
MinecraftForge.EVENT_BUS.register(this);
EnderCore.instance.configs.add(this);
}
@Override
public final void initialize(@Nonnull File cfg) {
config = new Configuration(cfg);
init();
reloadAllConfigs();
saveConfigFile();
}
@Nonnull
Configuration getConfig() {
return NullHelper.notnull(config, "Configuration getConfig()");
}
protected void loadConfigFile() {
getConfig().load();
}
protected void saveConfigFile() {
getConfig().save();
}
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) {
if (event.getModID().equals(modid)) {
EnderCore.logger.info("Reloading all configs for modid: " + modid);
if (NullHelper.untrust(Minecraft.getMinecraft().world) == null) {
reloadNonIngameConfigs();
}
reloadIngameConfigs();
saveConfigFile();
}
}
@SubscribeEvent
public void onConfigFileChanged(ConfigFileChangedEvent event) {
if (event.getModID().equals(modid)) {
EnderCore.logger.info("Reloading ingame configs for modid: " + modid);
loadConfigFile();
reloadAllConfigs();
event.setSuccessful();
saveConfigFile();
}
}
// convenience for reloading all configs
protected final void reloadAllConfigs() {
reloadNonIngameConfigs();
reloadIngameConfigs();
}
/**
* Called after config is loaded, but before properties are processed.
* <p>
* Use this method to add your sections and do other setup.
*/
protected abstract void init();
/**
* Refresh all config values that can only be loaded when NOT in-game.
* <p>
* {@code reloadIngameConfigs()} will be called after this, do not duplicate calls in this method and that one.
*/
protected abstract void reloadNonIngameConfigs();
/**
* Refresh all config values that can only be loaded when in-game.
* <p>
* This is separated from {@code reloadNonIngameConfigs()} because some values may not be able to be modified at runtime.
*/
protected abstract void reloadIngameConfigs();
/**
* Adds a section to your config to be used later
*
* @param sectionName
* The name of the section. Will also be used as language key.
* @return A {@link Section} representing your section in the config
*/
protected Section addSection(String sectionName) {
return addSection(sectionName, sectionName, null);
}
/**
* Adds a section to your config to be used later
*
* @param sectionName
* The name of the section
* @param langKey
* The language key to use to display your section name in the Config GUI
* @return A {@link Section} representing your section in the config
*/
protected Section addSection(String sectionName, String langKey) {
return addSection(sectionName, langKey, null);
}
/**
* Adds a section to your config to be used later
*
* @param sectionName
* The name of the section
* @param langKey
* The language key to use to display your section name in the Config GUI
* @param comment
* The section comment
* @return A {@link Section} representing your section in the config
*/
protected Section addSection(String sectionName, String langKey, String comment) {
Section section = new Section(sectionName, langKey);
if (activeSection == null && sections.isEmpty()) {
activeSection = section;
}
if (comment != null) {
getConfig().addCustomCategoryComment(sectionName, comment);
}
return section.register();
}
private void checkInitialized() {
if (activeSection == null) {
throw new IllegalStateException("No section is active!");
}
}
/**
* Activates a section
*
* @param sectionName
* The name of the section
*
* @throws IllegalArgumentException
* if {@code sectionName} is not valid
*/
protected void activateSection(String sectionName) {
Section section = getSectionByName(sectionName);
if (section == null) {
throw new IllegalArgumentException("Section " + sectionName + " does not exist!");
}
activateSection(section);
}
/**
* Activates a section
*
* @param section
* The section to activate
*/
protected void activateSection(Section section) {
activeSection = section;
}
/**
* Gets a {@link Section} for a name
*
* @param sectionName
* The name of the section
* @return A section object representing the section in your config with this name
*/
protected Section getSectionByName(String sectionName) {
for (Section s : sections) {
if (s.name.equalsIgnoreCase(sectionName)) {
return s;
}
}
return null;
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param defaultVal
* Default value so a new property can be created
* @return The value of the property
*
* @throws IllegalArgumentException
* If defaultVal is not a valid property type
* @throws IllegalStateException
* If there is no active section
*/
protected <T> T getValue(String key, T defaultVal) {
return getValue(key, defaultVal, RestartReqs.NONE);
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param defaultVal
* Default value so a new property can be created
* @param req
* Restart requirement of the property to be created
* @return The value of the property
*
* @throws IllegalArgumentException
* If defaultVal is not a valid property type
* @throws IllegalStateException
* If there is no active section
*/
protected <T> T getValue(String key, T defaultVal, RestartReqs req) {
return getValue(key, null, defaultVal, req);
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param defaultVal
* Default value so a new property can be created
* @param bound
* The bounds to set on this property
* @return The value of the property
*
* @throws IllegalArgumentException
* If defaultVal is not a valid property type
* @throws IllegalStateException
* If there is no active section
*/
protected <T> T getValue(String key, T defaultVal, Bound<? extends Number> bound) {
return getValue(key, null, defaultVal, bound);
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param comment
* The comment to put on this property
* @param defaultVal
* Default value so a new property can be created
* @return The value of the property
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> T getValue(String key, String comment, T defaultVal) {
return getValue(key, comment, defaultVal, RestartReqs.NONE);
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param comment
* The comment to put on this property
* @param defaultVal
* Default value so a new property can be created
* @param req
* Restart requirement of the property to be created
* @return The value of the property
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> T getValue(String key, String comment, T defaultVal, RestartReqs req) {
return getValue(key, comment, defaultVal, req, null);
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param comment
* The comment to put on this property
* @param defaultVal
* Default value so a new property can be created
* @param bound
* The bounds to set on this property
* @return The value of the property
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> T getValue(String key, String comment, T defaultVal, Bound<? extends Number> bound) {
return getValue(key, comment, defaultVal, RestartReqs.NONE, bound);
}
/**
* Gets a value from this config handler
*
* @param key
* Name of the key for this property
* @param comment
* The comment to put on this property
* @param defaultVal
* Default value so a new property can be created
* @param req
* Restart requirement of the property to be created
* @param bound
* The bounds to set on this property
* @return The value of the property
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> T getValue(String key, String comment, T defaultVal, RestartReqs req, Bound<? extends Number> bound) {
Property prop = getProperty(key, defaultVal, req);
prop.setComment(comment);
return getValue(prop, defaultVal, bound);
}
/**
* Gets a value from a property
*
* @param prop
* Property to get value from
* @param defaultVal
* Default value so a new property can be created
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> T getValue(Property prop, T defaultVal) {
return getValue(prop, defaultVal, null);
}
/**
* Gets a value from a property
*
* @param prop
* Property to get value from
* @param defaultVal
* Default value so a new property can be created
* @param bound
* The bounds to set on this property
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
@SuppressWarnings("unchecked")
// we check type of defaultVal but compiler still complains about a cast to T
protected <T> T getValue(Property prop, T defaultVal, Bound<? extends Number> bound) {
checkInitialized();
final @Nonnull Bound<? extends Number> realbound;
if (bound != null) {
realbound = bound;
setBounds(prop, realbound);
} else {
realbound = Bound.MAX_BOUND;
}
addCommentDetails(prop, realbound);
if (defaultVal instanceof Integer) {
Bound<Integer> b = Bound.of(realbound.min.intValue(), realbound.max.intValue());
return (T) boundValue(prop, b, (Integer) defaultVal);
}
if (defaultVal instanceof Float) {
Bound<Float> b = Bound.of(realbound.min.floatValue(), realbound.max.floatValue());
return (T) boundValue(prop, b, (Float) defaultVal);
}
if (defaultVal instanceof Double) {
Bound<Double> b = Bound.of(realbound.min.doubleValue(), realbound.max.doubleValue());
return (T) boundValue(prop, b, (Double) defaultVal);
}
if (defaultVal instanceof Boolean) {
return (T) Boolean.valueOf(prop.getBoolean());
}
if (defaultVal instanceof int[]) {
return (T) prop.getIntList();
}
if (defaultVal instanceof String) {
return (T) prop.getString();
}
if (defaultVal instanceof String[]) {
return (T) prop.getStringList();
}
throw new IllegalArgumentException("default value is not a config value type.");
}
static void setBounds(Property prop, Bound<?> bound) throws IllegalArgumentException {
if (bound.equals(Bound.MAX_BOUND)) {
return;
}
if (prop.getType() == Type.INTEGER) {
Bound<Integer> b = Bound.of(bound.min.intValue(), bound.max.intValue());
prop.setMinValue(b.min);
prop.setMaxValue(b.max);
} else if (prop.getType() == Type.DOUBLE) {
Bound<Double> b = Bound.of(bound.min.doubleValue(), bound.max.doubleValue());
prop.setMinValue(b.min);
prop.setMaxValue(b.max);
} else {
throw new IllegalArgumentException(String.format("A mod tried to set bounds %s on a property that was not either of Integer of Double type.", bound));
}
}
static int[] boundIntArr(Property prop, Bound<Integer> bound) {
int[] prev = prop.getIntList();
int[] res = new int[prev.length];
for (int i = 0; i < prev.length; i++) {
res[i] = bound.clamp(prev[i]);
}
prop.set(res);
return res;
}
static double[] boundDoubleArr(Property prop, Bound<Double> bound) {
double[] prev = prop.getDoubleList();
double[] res = new double[prev.length];
for (int i = 0; i < prev.length; i++) {
res[i] = bound.clamp(prev[i]);
}
prop.set(res);
return res;
}
@SuppressWarnings("unchecked")
static <T extends Number & Comparable<T>> T boundValue(Property prop, Bound<T> bound, T defVal) throws IllegalArgumentException {
Object b = bound;
if (defVal instanceof Integer) {
return (T) boundInt(prop, (Bound<Integer>) b);
}
if (defVal instanceof Double) {
return (T) boundDouble(prop, (Bound<Double>) b);
}
if (defVal instanceof Float) {
return (T) boundFloat(prop, (Bound<Float>) b);
}
throw new IllegalArgumentException(bound.min.getClass().getName() + " is not a valid config type.");
}
private static Integer boundInt(Property prop, Bound<Integer> bound) {
prop.set(bound.clamp(prop.getInt()));
return Integer.valueOf(prop.getInt());
}
private static Double boundDouble(Property prop, Bound<Double> bound) {
prop.set(bound.clamp(prop.getDouble()));
return Double.valueOf(prop.getDouble());
}
private static Float boundFloat(Property prop, Bound<Float> bound) {
return boundDouble(prop, Bound.of(bound.min.doubleValue(), bound.max.doubleValue())).floatValue();
}
private static Lang fmlLang = new Lang("fml.configgui.tooltip");
static void addCommentDetails(Property prop, Bound<?> bound) {
prop.setComment(prop.getComment() + (prop.getComment().isEmpty() ? "" : "\n"));
if (bound.equals(Bound.MAX_BOUND)) {
prop.setComment(prop.getComment() + fmlLang.localize("default", prop.isList() ? Arrays.toString(prop.getDefaults()) : prop.getDefault()));
} else {
boolean minIsInt = bound.min.doubleValue() == bound.min.intValue();
boolean maxIsInt = bound.max.doubleValue() == bound.max.intValue();
prop.setComment(prop.getComment() + fmlLang.localize("defaultNumeric", minIsInt ? bound.min.intValue() : bound.min,
maxIsInt ? bound.max.intValue() : bound.max, prop.isList() ? Arrays.toString(prop.getDefaults()) : prop.getDefault()));
}
}
/**
* Gets a property from this config handler
*
* @param key
* name of the key for this property
* @param defaultVal
* default value so a new property can be created
* @return The property in the config
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> Property getProperty(String key, T defaultVal) {
return getProperty(key, defaultVal, RestartReqs.NONE);
}
/**
* Gets a property from this config handler
*
* @param key
* name of the key for this property
* @param defaultVal
* default value so a new property can be created
* @return The property in the config
*
* @throws IllegalArgumentException
* if defaultVal is not a valid property type
* @throws IllegalStateException
* if there is no active section
*/
protected <T> Property getProperty(String key, T defaultVal, RestartReqs req) {
checkInitialized();
Section section = activeSection;
Property prop = null;
// @formatter:off
// same logic as above method, mostly
if (defaultVal instanceof Integer)
{
prop = getConfig().get(section.name, key, (Integer) defaultVal);
}
if (defaultVal instanceof Boolean)
{
prop = getConfig().get(section.name, key, (Boolean) defaultVal);
}
if (defaultVal instanceof int[])
{
prop = getConfig().get(section.name, key, (int[]) defaultVal);
}
if (defaultVal instanceof String)
{
prop = getConfig().get(section.name, key, (String) defaultVal);
}
if (defaultVal instanceof String[])
{
prop = getConfig().get(section.name, key, (String[]) defaultVal);
}
// @formatter:on
if (defaultVal instanceof Float || defaultVal instanceof Double) {
double val = defaultVal instanceof Float ? ((Float) defaultVal).doubleValue() : ((Double) defaultVal).doubleValue();
prop = getConfig().get(section.name, key, val);
}
if (prop != null) {
return req.apply(prop);
}
throw new IllegalArgumentException("default value is not a config value type.");
}
/**
* @return If this config handler should recieve {@link #initHook()} and {@link #postInitHook()} during config reload events. If this returns false, these
* methods will only be called on load.
* <p>
* Defaults to false.
*/
protected boolean shouldHookOnReload() {
return true;
}
/* IConfigHandler impl */
@Override
public void initHook() {
}
@Override
public void postInitHook() {
}
// no need to override these, they are merely utilities, and reference private fields anyways
@Override
public final @Nonnull List<Section> getSections() {
return ImmutableList.copyOf(sections);
}
@Override
public final @Nonnull ConfigCategory getCategory(String name) {
final ConfigCategory category = getConfig().getCategory(name);
if (category == null) {
throw new NullPointerException("Forge is rejecting to create a config category '" + name + "'");
}
return category;
}
@Override
public final @Nonnull String getModID() {
return modid;
}
}
| 0 | 0.951677 | 1 | 0.951677 | game-dev | MEDIA | 0.920574 | game-dev | 0.867209 | 1 | 0.867209 |
iluwatar/java-design-patterns | 3,210 | lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Feind.java | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.lockableobject.domain;
import com.iluwatar.lockableobject.Lockable;
import java.security.SecureRandom;
import lombok.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** A Feind is a creature that wants to possess a Lockable object. */
public class Feind implements Runnable {
private final Creature creature;
private final Lockable target;
private final SecureRandom random;
private static final Logger LOGGER = LoggerFactory.getLogger(Feind.class.getName());
/**
* public constructor.
*
* @param feind as the creature to lock to he lockable.
* @param target as the target object.
*/
public Feind(@NonNull Creature feind, @NonNull Lockable target) {
this.creature = feind;
this.target = target;
this.random = new SecureRandom();
}
@Override
public void run() {
if (!creature.acquire(target)) {
fightForTheSword(creature, target.getLocker(), target);
} else {
LOGGER.info("{} has acquired the sword!", target.getLocker().getName());
}
}
/**
* Keeps on fighting until the Lockable is possessed.
*
* @param reacher as the source creature.
* @param holder as the foe.
* @param sword as the Lockable to possess.
*/
private void fightForTheSword(Creature reacher, @NonNull Creature holder, Lockable sword) {
LOGGER.info("A duel between {} and {} has been started!", reacher.getName(), holder.getName());
boolean randBool;
while (this.target.isLocked() && reacher.isAlive() && holder.isAlive()) {
randBool = random.nextBoolean();
if (randBool) {
reacher.attack(holder);
} else {
holder.attack(reacher);
}
}
if (reacher.isAlive()) {
if (!reacher.acquire(sword)) {
fightForTheSword(reacher, sword.getLocker(), sword);
} else {
LOGGER.info("{} has acquired the sword!", reacher.getName());
}
}
}
}
| 0 | 0.76981 | 1 | 0.76981 | game-dev | MEDIA | 0.50805 | game-dev | 0.734651 | 1 | 0.734651 |
FlintMC/FlintMC | 4,822 | mcapi/src/v1_16_5/java/net/flintmc/mcapi/v1_16_5/world/biome/VersionedBiomeMapper.java | /*
* FlintMC
* Copyright (C) 2020-2021 LabyMedia GmbH and contributors
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.flintmc.mcapi.v1_16_5.world.biome;
import com.google.inject.Singleton;
import net.flintmc.framework.inject.implement.Implement;
import net.flintmc.mcapi.world.biome.BiomeCategory;
import net.flintmc.mcapi.world.biome.BiomeMapper;
import net.flintmc.mcapi.world.biome.RainType;
import net.flintmc.mcapi.world.biome.TemperatureCategory;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.Biome.Category;
@Singleton
@Implement(BiomeMapper.class)
public class VersionedBiomeMapper implements BiomeMapper {
/**
* {@inheritDoc}
*/
@Override
public BiomeCategory fromMinecraftBiomeCategory(Object category) {
switch ((Category) category) {
case NONE:
return BiomeCategory.NONE;
case TAIGA:
return BiomeCategory.TAIGA;
case EXTREME_HILLS:
return BiomeCategory.EXTREME_HILLS;
case JUNGLE:
return BiomeCategory.JUNGLE;
case MESA:
return BiomeCategory.MESA;
case PLAINS:
return BiomeCategory.PLAINS;
case SAVANNA:
return BiomeCategory.SAVANNA;
case ICY:
return BiomeCategory.ICY;
case THEEND:
return BiomeCategory.THE_END;
case BEACH:
return BiomeCategory.BEACH;
case FOREST:
return BiomeCategory.FOREST;
case OCEAN:
return BiomeCategory.OCEAN;
case DESERT:
return BiomeCategory.DESERT;
case RIVER:
return BiomeCategory.RIVER;
case SWAMP:
return BiomeCategory.SWAMP;
case MUSHROOM:
return BiomeCategory.MUSHROOM;
case NETHER:
return BiomeCategory.NETHER;
default:
throw new IllegalStateException("Unexpected value: " + category);
}
}
/**
* {@inheritDoc}
*/
@Override
public Object toMinecraftBiomeCategory(BiomeCategory category) {
switch (category) {
case NONE:
return Category.NONE;
case TAIGA:
return Category.TAIGA;
case EXTREME_HILLS:
return Category.EXTREME_HILLS;
case JUNGLE:
return Category.JUNGLE;
case MESA:
return Category.MESA;
case PLAINS:
return Category.PLAINS;
case SAVANNA:
return Category.SAVANNA;
case ICY:
return Category.ICY;
case THE_END:
return Category.THEEND;
case BEACH:
return Category.BEACH;
case FOREST:
return Category.FOREST;
case OCEAN:
return Category.OCEAN;
case DESERT:
return Category.DESERT;
case RIVER:
return Category.RIVER;
case SWAMP:
return Category.SWAMP;
case MUSHROOM:
return Category.MUSHROOM;
case NETHER:
return Category.NETHER;
default:
throw new IllegalStateException("Unexpected value: " + category);
}
}
/**
* {@inheritDoc}
*/
@Override
public RainType fromMinecraftRainType(Object rainType) {
switch ((Biome.RainType) rainType) {
case NONE:
return RainType.NONE;
case RAIN:
return RainType.RAIN;
case SNOW:
return RainType.SNOW;
default:
throw new IllegalStateException("Unexpected value: " + rainType);
}
}
/**
* {@inheritDoc}
*/
@Override
public Object toMinecraftRainType(RainType rainType) {
switch (rainType) {
case NONE:
return Biome.RainType.NONE;
case RAIN:
return Biome.RainType.RAIN;
case SNOW:
return Biome.RainType.SNOW;
default:
throw new IllegalStateException("Unexpected value: " + rainType);
}
}
/**
* {@inheritDoc}
*/
@Override
public TemperatureCategory fromMinecraftTemperatureCategory(Object category) {
throw new UnsupportedOperationException("Not supported in 1.16.5");
}
/**
* {@inheritDoc}
*/
@Override
public Object toMinecraftTemperatureCategory(TemperatureCategory category) {
throw new UnsupportedOperationException("Not supported in 1.16.5");
}
}
| 0 | 0.637391 | 1 | 0.637391 | game-dev | MEDIA | 0.788341 | game-dev | 0.685094 | 1 | 0.685094 |
afhverjuekki/tolvera | 2,618 | src/tolvera/vera/particle_life.py | """Particle Life model."""
import taichi as ti
from ..utils import CONSTS
@ti.data_oriented
class ParticleLife():
"""Particle Life model.
The Particle Life model is a simple model of particle behaviour, where
particles are either attracted or repelled by other particles, depending
on their species. Popularised by Jeffrey Ventrella (Clusters), Tom Mohr
and others:
https://www.ventrella.com/Clusters/
https://github.com/tom-mohr/particle-life-app
"""
def __init__(self, tolvera, **kwargs) -> None:
"""Initialise the Particle Life model.
'plife' stores the species rule matrix.
Args:
tolvera (Tolvera): A Tolvera instance.
**kwargs: Keyword arguments (currently none).
"""
self.tv = tolvera
self.kwargs = kwargs
self.CONSTS = CONSTS({
"V": (ti.f32, 0.25),
})
self.tv.s.plife = {
"state": {
"attract": (ti.f32, -.5, .5),
"radius": (ti.f32, 100., 300.0),
},
"shape": (self.tv.sn, self.tv.sn),
"randomise": True,
}
@ti.kernel
def step(self, particles: ti.template(), weight: ti.f32):
"""Step the Particle Life model.
Args:
particles (Particles.field): The particles to step.
weight (ti.f32): The weight of the step.
"""
for i in range(particles.shape[0]):
if particles[i].active == 0.: continue
p1 = particles[i]
fx, fy = 0., 0.
for j in range(particles.shape[0]):
if particles[j].active == 0.: continue
p2 = particles[j]
s = self.tv.s.plife[p1.species, p2.species]
dx = p1.pos[0] - p2.pos[0]
dy = p1.pos[1] - p2.pos[1]
d = ti.sqrt(dx*dx + dy*dy)
if 0. < d and d < s.radius:
F = s.attract/d
fx += F*dx
fy += F*dy
# particles[i].vel = (particles[i].vel + ti.Vector([fx, fy])) * self.CONSTS.V * weight
# particles[i].pos += (particles[i].vel * p1.speed * p1.active * weight)
particles[i].vel = (particles[i].vel + ti.Vector([fx, fy])) * self.CONSTS.V * weight * p1.speed * p1.active
particles[i].pos += particles[i].vel
def __call__(self, particles, weight: ti.f32 = 1.0):
"""Call the Particle Life model.
Args:
particles (Particles): The particles to step.
"""
self.step(particles.field, weight)
| 0 | 0.849164 | 1 | 0.849164 | game-dev | MEDIA | 0.375675 | game-dev | 0.860195 | 1 | 0.860195 |
RaiderIO/keystone.guru | 16,804 | app/Models/MapIconType.php | <?php
namespace App\Models;
use App\Models\Traits\SeederModel;
use Eloquent;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* @property int $id
* @property string $name
* @property string $key
* @property int $width
* @property int $height
* @property bool $admin_only
* @property string $icon_url
*
* @property MapIcon $mapIcons
*
* @mixin Eloquent
*/
class MapIconType extends CacheModel
{
use SeederModel;
public $timestamps = false;
protected $fillable = [
'name',
'key',
'width',
'height',
'admin_only',
];
protected $appends = [
'icon_url',
];
public const MAP_ICON_TYPE_UNKNOWN = 'unknown';
public const MAP_ICON_TYPE_COMMENT = 'comment';
public const MAP_ICON_TYPE_DOOR = 'door';
public const MAP_ICON_TYPE_DOOR_DOWN = 'door_down';
public const MAP_ICON_TYPE_DOOR_LEFT = 'door_left';
public const MAP_ICON_TYPE_DOOR_LOCKED = 'door_locked';
public const MAP_ICON_TYPE_DOOR_RIGHT = 'door_right';
public const MAP_ICON_TYPE_DOOR_UP = 'door_up';
public const MAP_ICON_TYPE_DOT_YELLOW = 'dot_yellow';
public const MAP_ICON_TYPE_DUNGEON_START = 'dungeon_start';
public const MAP_ICON_TYPE_GATEWAY = 'gateway';
public const MAP_ICON_TYPE_GRAVEYARD = 'graveyard';
public const MAP_ICON_TYPE_GREASEBOT = 'greasebot';
public const MAP_ICON_TYPE_SHOCKBOT = 'shockbot';
public const MAP_ICON_TYPE_WARLOCK_GATEWAY = 'warlock_gateway';
public const MAP_ICON_TYPE_WELDINGBOT = 'weldingbot';
public const MAP_ICON_TYPE_AWAKENED_OBELISK_BRUTAL = 'awakened_obelisk_brutal';
public const MAP_ICON_TYPE_AWAKENED_OBELISK_CURSED = 'awakened_obelisk_cursed';
public const MAP_ICON_TYPE_AWAKENED_OBELISK_DEFILED = 'awakened_obelisk_defiled';
public const MAP_ICON_TYPE_AWAKENED_OBELISK_ENTROPIC = 'awakened_obelisk_entropic';
public const MAP_ICON_TYPE_SKIP_FLIGHT = 'skip_flight';
public const MAP_ICON_TYPE_SKIP_TELEPORT = 'skip_teleport';
public const MAP_ICON_TYPE_SKIP_WALK = 'skip_walk';
public const MAP_ICON_TYPE_RAID_MARKER_STAR = 'raid_marker_star';
public const MAP_ICON_TYPE_RAID_MARKER_CIRCLE = 'raid_marker_circle';
public const MAP_ICON_TYPE_RAID_MARKER_DIAMOND = 'raid_marker_diamond';
public const MAP_ICON_TYPE_RAID_MARKER_TRIANGLE = 'raid_marker_triangle';
public const MAP_ICON_TYPE_RAID_MARKER_MOON = 'raid_marker_moon';
public const MAP_ICON_TYPE_RAID_MARKER_SQUARE = 'raid_marker_square';
public const MAP_ICON_TYPE_RAID_MARKER_CROSS = 'raid_marker_cross';
public const MAP_ICON_TYPE_RAID_MARKER_SKULL = 'raid_marker_skull';
public const MAP_ICON_TYPE_SPELL_BLOODLUST = 'spell_bloodlust';
public const MAP_ICON_TYPE_SPELL_HEROISM = 'spell_heroism';
public const MAP_ICON_TYPE_SPELL_SHADOWMELD = 'spell_shadowmeld';
public const MAP_ICON_TYPE_SPELL_SHROUD_OF_CONCEALMENT = 'spell_shroud_of_concealment';
public const MAP_ICON_TYPE_ITEM_INVISIBILITY = 'item_invisibility';
public const MAP_ICON_TYPE_ITEM_DRUMS_OF_SPEED = 'item_drums_of_speed';
public const MAP_ICON_TYPE_ITEM_FREE_ACTION_POTION = 'item_free_action_potion';
public const MAP_ICON_TYPE_ITEM_GLOBAL_THERMAL_SAPPER_CHARGE = 'item_global_thermal_sapper_charge';
public const MAP_ICON_TYPE_ITEM_ROCKET_BOOTS_XTREME = 'item_rocket_boots_xtreme';
public const MAP_ICON_TYPE_QUESTION_YELLOW = 'question_yellow';
public const MAP_ICON_TYPE_QUESTION_BLUE = 'question_blue';
public const MAP_ICON_TYPE_QUESTION_ORANGE = 'question_orange';
public const MAP_ICON_TYPE_EXCLAMATION_YELLOW = 'exclamation_yellow';
public const MAP_ICON_TYPE_EXCLAMATION_BLUE = 'exclamation_blue';
public const MAP_ICON_TYPE_EXCLAMATION_ORANGE = 'exclamation_orange';
public const MAP_ICON_TYPE_NEONBUTTON_BLUE = 'neonbutton_blue';
public const MAP_ICON_TYPE_NEONBUTTON_CYAN = 'neonbutton_cyan';
public const MAP_ICON_TYPE_NEONBUTTON_GREEN = 'neonbutton_green';
public const MAP_ICON_TYPE_NEONBUTTON_ORANGE = 'neonbutton_orange';
public const MAP_ICON_TYPE_NEONBUTTON_PINK = 'neonbutton_pink';
public const MAP_ICON_TYPE_NEONBUTTON_PURPLE = 'neonbutton_purple';
public const MAP_ICON_TYPE_NEONBUTTON_RED = 'neonbutton_red';
public const MAP_ICON_TYPE_NEONBUTTON_YELLOW = 'neonbutton_yellow';
public const MAP_ICON_TYPE_NEONBUTTON_DARKRED = 'neonbutton_darkred';
public const MAP_ICON_TYPE_NEONBUTTON_DARKGREEN = 'neonbutton_darkgreen';
public const MAP_ICON_TYPE_NEONBUTTON_DARKBLUE = 'neonbutton_darkblue';
public const MAP_ICON_TYPE_SPELL_MIND_SOOTHE = 'spell_mind_soothe';
public const MAP_ICON_TYPE_SPELL_COMBUSTION = 'spell_combustion';
public const MAP_ICON_TYPE_COVENANT_KYRIAN = 'covenant_kyrian';
public const MAP_ICON_TYPE_COVENANT_NECROLORDS = 'covenant_necrolords';
public const MAP_ICON_TYPE_COVENANT_NIGHTFAE = 'covenant_nightfae';
public const MAP_ICON_TYPE_COVENANT_VENTHYR = 'covenant_venthyr';
public const MAP_ICON_TYPE_PORTAL_BLUE = 'portal_blue';
public const MAP_ICON_TYPE_PORTAL_GREEN = 'portal_green';
public const MAP_ICON_TYPE_PORTAL_ORANGE = 'portal_orange';
public const MAP_ICON_TYPE_PORTAL_PINK = 'portal_pink';
public const MAP_ICON_TYPE_PORTAL_RED = 'portal_red';
public const MAP_ICON_TYPE_NW_ITEM_ANIMA = 'nw_item_anima';
public const MAP_ICON_TYPE_NW_ITEM_GOLIATH = 'nw_item_goliath';
public const MAP_ICON_TYPE_NW_ITEM_HAMMER = 'nw_item_hammer';
public const MAP_ICON_TYPE_NW_ITEM_SHIELD = 'nw_item_shield';
public const MAP_ICON_TYPE_NW_ITEM_SPEAR = 'nw_item_spear';
public const MAP_ICON_TYPE_SPELL_INCARNATION = 'spell_incarnation';
public const MAP_ICON_TYPE_SPELL_MISDIRECTION = 'spell_misdirection';
public const MAP_ICON_TYPE_SPELL_TRICKS_OF_THE_TRADE = 'spell_tricks_of_the_trade';
public const MAP_ICON_TYPE_ROLE_TANK = 'role_tank';
public const MAP_ICON_TYPE_ROLE_HEALER = 'role_healer';
public const MAP_ICON_TYPE_ROLE_DPS = 'role_dps';
public const MAP_ICON_TYPE_CLASS_WARRIOR = 'class_warrior';
public const MAP_ICON_TYPE_CLASS_HUNTER = 'class_hunter';
public const MAP_ICON_TYPE_CLASS_DEATH_KNIGHT = 'class_deathknight';
public const MAP_ICON_TYPE_CLASS_MAGE = 'class_mage';
public const MAP_ICON_TYPE_CLASS_PRIEST = 'class_priest';
public const MAP_ICON_TYPE_CLASS_MONK = 'class_monk';
public const MAP_ICON_TYPE_CLASS_ROGUE = 'class_rogue';
public const MAP_ICON_TYPE_CLASS_WARLOCK = 'class_warlock';
public const MAP_ICON_TYPE_CLASS_SHAMAN = 'class_shaman';
public const MAP_ICON_TYPE_CLASS_PALADIN = 'class_paladin';
public const MAP_ICON_TYPE_CLASS_DRUID = 'class_druid';
public const MAP_ICON_TYPE_CLASS_DEMON_HUNTER = 'class_demonhunter';
public const MAP_ICON_TYPE_CLASS_EVOKER = 'class_evoker';
public const MAP_ICON_TYPE_CHEST = 'chest';
public const MAP_ICON_TYPE_CHEST_LOCKED = 'chest_locked';
public const MAP_ICON_TYPE_MISTS_STATSHROOM = 'mists_item_statshroom';
public const MAP_ICON_TYPE_MISTS_TOUGHSHROOM = 'mists_item_toughshroom';
public const MAP_ICON_TYPE_MISTS_OVERGROWN_ROOTS = 'mists_item_overgrown_roots';
public const MAP_ICON_TYPE_COT_SHADECASTER = 'cot_item_shadecaster';
public const MAP_ICON_TYPE_SV_IMBUED_IRON_ENERGY = 'sv_item_imbued_iron_energy';
public const MAP_ICON_TYPE_ARA_KARA_SILK_WRAP = 'ara_kara_item_silk_wrap';
public const MAP_ICON_TYPE_KARAZHAN_CRYPTS_SPIDER_NEST = 'karazhan_crypts_spider_nest';
public const MAP_ICON_TYPE_PRIORY_BLESSING_OF_THE_SACRED_FLAME = 'priory_blessing_of_the_sacred_flame';
public const MAP_ICON_TYPE_FLOODGATE_WEAPONS_STOCKPILE_EXPLOSION = 'floodgate_weapons_stockpile_explosion';
public const MAP_ICON_TYPE_GATE_OF_THE_SETTING_SUN_BRAZIER = 'gate_of_the_setting_sun_brazier';
public const MAP_ICON_TYPE_ECO_DOME_AL_DANI_SHATTER_CONDUIT = 'eco_dome_al_dani_shatter_conduit';
public const MAP_ICON_TYPE_ECO_DOME_AL_DANI_DISRUPTION_GRENADE = 'eco_dome_al_dani_disruption_grenade';
public const MAP_ICON_TYPE_ECO_DOME_AL_DANI_KARESHI_SURGE = 'eco_dome_al_dani_kareshi_surge';
public const ALL = [
self::MAP_ICON_TYPE_UNKNOWN => 1,
self::MAP_ICON_TYPE_COMMENT => 2,
self::MAP_ICON_TYPE_DOOR => 3,
self::MAP_ICON_TYPE_DOOR_DOWN => 4,
self::MAP_ICON_TYPE_DOOR_LEFT => 5,
self::MAP_ICON_TYPE_DOOR_LOCKED => 6,
self::MAP_ICON_TYPE_DOOR_RIGHT => 7,
self::MAP_ICON_TYPE_DOOR_UP => 8,
self::MAP_ICON_TYPE_DOT_YELLOW => 9,
self::MAP_ICON_TYPE_DUNGEON_START => 10,
self::MAP_ICON_TYPE_GATEWAY => 11,
self::MAP_ICON_TYPE_GRAVEYARD => 12,
self::MAP_ICON_TYPE_GREASEBOT => 13,
self::MAP_ICON_TYPE_SHOCKBOT => 14,
self::MAP_ICON_TYPE_WARLOCK_GATEWAY => 15,
self::MAP_ICON_TYPE_WELDINGBOT => 16,
self::MAP_ICON_TYPE_AWAKENED_OBELISK_BRUTAL => 17,
self::MAP_ICON_TYPE_AWAKENED_OBELISK_CURSED => 18,
self::MAP_ICON_TYPE_AWAKENED_OBELISK_DEFILED => 19,
self::MAP_ICON_TYPE_AWAKENED_OBELISK_ENTROPIC => 20,
self::MAP_ICON_TYPE_SKIP_FLIGHT => 21,
self::MAP_ICON_TYPE_SKIP_TELEPORT => 22,
self::MAP_ICON_TYPE_SKIP_WALK => 23,
self::MAP_ICON_TYPE_RAID_MARKER_STAR => 24,
self::MAP_ICON_TYPE_RAID_MARKER_CIRCLE => 25,
self::MAP_ICON_TYPE_RAID_MARKER_DIAMOND => 26,
self::MAP_ICON_TYPE_RAID_MARKER_TRIANGLE => 27,
self::MAP_ICON_TYPE_RAID_MARKER_MOON => 28,
self::MAP_ICON_TYPE_RAID_MARKER_SQUARE => 29,
self::MAP_ICON_TYPE_RAID_MARKER_CROSS => 30,
self::MAP_ICON_TYPE_RAID_MARKER_SKULL => 31,
self::MAP_ICON_TYPE_SPELL_BLOODLUST => 32,
self::MAP_ICON_TYPE_SPELL_HEROISM => 33,
self::MAP_ICON_TYPE_SPELL_SHADOWMELD => 34,
self::MAP_ICON_TYPE_SPELL_SHROUD_OF_CONCEALMENT => 35,
self::MAP_ICON_TYPE_ITEM_INVISIBILITY => 36,
self::MAP_ICON_TYPE_QUESTION_YELLOW => 37,
self::MAP_ICON_TYPE_QUESTION_BLUE => 38,
self::MAP_ICON_TYPE_QUESTION_ORANGE => 39,
self::MAP_ICON_TYPE_EXCLAMATION_YELLOW => 40,
self::MAP_ICON_TYPE_EXCLAMATION_BLUE => 41,
self::MAP_ICON_TYPE_EXCLAMATION_ORANGE => 42,
self::MAP_ICON_TYPE_NEONBUTTON_BLUE => 43,
self::MAP_ICON_TYPE_NEONBUTTON_CYAN => 44,
self::MAP_ICON_TYPE_NEONBUTTON_GREEN => 45,
self::MAP_ICON_TYPE_NEONBUTTON_ORANGE => 46,
self::MAP_ICON_TYPE_NEONBUTTON_PINK => 47,
self::MAP_ICON_TYPE_NEONBUTTON_PURPLE => 48,
self::MAP_ICON_TYPE_NEONBUTTON_RED => 49,
self::MAP_ICON_TYPE_NEONBUTTON_YELLOW => 50,
self::MAP_ICON_TYPE_NEONBUTTON_DARKRED => 51,
self::MAP_ICON_TYPE_NEONBUTTON_DARKGREEN => 52,
self::MAP_ICON_TYPE_NEONBUTTON_DARKBLUE => 53,
self::MAP_ICON_TYPE_SPELL_MIND_SOOTHE => 54,
self::MAP_ICON_TYPE_SPELL_COMBUSTION => 55,
self::MAP_ICON_TYPE_COVENANT_KYRIAN => 56,
self::MAP_ICON_TYPE_COVENANT_NECROLORDS => 57,
self::MAP_ICON_TYPE_COVENANT_NIGHTFAE => 58,
self::MAP_ICON_TYPE_COVENANT_VENTHYR => 59,
self::MAP_ICON_TYPE_PORTAL_BLUE => 60,
self::MAP_ICON_TYPE_PORTAL_GREEN => 61,
self::MAP_ICON_TYPE_PORTAL_ORANGE => 62,
self::MAP_ICON_TYPE_PORTAL_PINK => 63,
self::MAP_ICON_TYPE_PORTAL_RED => 64,
self::MAP_ICON_TYPE_NW_ITEM_ANIMA => 65,
self::MAP_ICON_TYPE_NW_ITEM_GOLIATH => 66,
self::MAP_ICON_TYPE_NW_ITEM_HAMMER => 67,
self::MAP_ICON_TYPE_NW_ITEM_SHIELD => 68,
self::MAP_ICON_TYPE_NW_ITEM_SPEAR => 69,
self::MAP_ICON_TYPE_SPELL_INCARNATION => 70,
self::MAP_ICON_TYPE_ITEM_DRUMS_OF_SPEED => 71,
self::MAP_ICON_TYPE_ITEM_FREE_ACTION_POTION => 72,
self::MAP_ICON_TYPE_ITEM_GLOBAL_THERMAL_SAPPER_CHARGE => 73,
self::MAP_ICON_TYPE_ITEM_ROCKET_BOOTS_XTREME => 74,
self::MAP_ICON_TYPE_SPELL_MISDIRECTION => 75,
self::MAP_ICON_TYPE_SPELL_TRICKS_OF_THE_TRADE => 76,
self::MAP_ICON_TYPE_ROLE_TANK => 77,
self::MAP_ICON_TYPE_ROLE_HEALER => 78,
self::MAP_ICON_TYPE_ROLE_DPS => 79,
self::MAP_ICON_TYPE_CLASS_WARRIOR => 80,
self::MAP_ICON_TYPE_CLASS_HUNTER => 81,
self::MAP_ICON_TYPE_CLASS_DEATH_KNIGHT => 82,
self::MAP_ICON_TYPE_CLASS_MAGE => 83,
self::MAP_ICON_TYPE_CLASS_PRIEST => 84,
self::MAP_ICON_TYPE_CLASS_MONK => 85,
self::MAP_ICON_TYPE_CLASS_ROGUE => 86,
self::MAP_ICON_TYPE_CLASS_WARLOCK => 87,
self::MAP_ICON_TYPE_CLASS_SHAMAN => 88,
self::MAP_ICON_TYPE_CLASS_PALADIN => 89,
self::MAP_ICON_TYPE_CLASS_DRUID => 90,
self::MAP_ICON_TYPE_CLASS_DEMON_HUNTER => 91,
self::MAP_ICON_TYPE_CLASS_EVOKER => 92,
self::MAP_ICON_TYPE_CHEST => 93,
self::MAP_ICON_TYPE_CHEST_LOCKED => 94,
self::MAP_ICON_TYPE_MISTS_STATSHROOM => 95,
self::MAP_ICON_TYPE_MISTS_TOUGHSHROOM => 96,
self::MAP_ICON_TYPE_MISTS_OVERGROWN_ROOTS => 100,
self::MAP_ICON_TYPE_COT_SHADECASTER => 97,
self::MAP_ICON_TYPE_SV_IMBUED_IRON_ENERGY => 98,
self::MAP_ICON_TYPE_ARA_KARA_SILK_WRAP => 99,
self::MAP_ICON_TYPE_KARAZHAN_CRYPTS_SPIDER_NEST => 101,
self::MAP_ICON_TYPE_PRIORY_BLESSING_OF_THE_SACRED_FLAME => 102,
self::MAP_ICON_TYPE_FLOODGATE_WEAPONS_STOCKPILE_EXPLOSION => 103,
self::MAP_ICON_TYPE_GATE_OF_THE_SETTING_SUN_BRAZIER => 104,
self::MAP_ICON_TYPE_ECO_DOME_AL_DANI_SHATTER_CONDUIT => 105,
self::MAP_ICON_TYPE_ECO_DOME_AL_DANI_DISRUPTION_GRENADE => 106,
self::MAP_ICON_TYPE_ECO_DOME_AL_DANI_KARESHI_SURGE => 107,
];
public function getIconUrlAttribute(): string
{
return ksgAssetImage(sprintf('mapicon/%s.png', $this->key));
}
public function mapIcons(): HasMany
{
return $this->hasMany(MapIcon::class);
}
}
| 0 | 0.771356 | 1 | 0.771356 | game-dev | MEDIA | 0.904948 | game-dev | 0.612214 | 1 | 0.612214 |
jeremyflores/cocosMNC | 11,945 | cocosMNCTest/libs/cocos2d/CCSprite.h | /*
* cocos2d for iPhone: http://www.cocos2d-iphone.org
*
* Copyright (c) 2008-2010 Ricardo Quesada
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#import "CCNode.h"
#import "CCProtocols.h"
#import "CCTextureAtlas.h"
@class CCSpriteSheet;
@class CCSpriteFrame;
@class CCAnimation;
#pragma mark CCSprite
enum {
/// CCSprite invalid index on the CCSpriteSheet
CCSpriteIndexNotInitialized = 0xffffffff,
};
/**
Whether or not an CCSprite will rotate, scale or translate with it's parent.
Useful in health bars, when you want that the health bar translates with it's parent but you don't
want it to rotate with its parent.
@since v0.99.0
*/
typedef enum {
//! Translate with it's parent
CC_HONOR_PARENT_TRANSFORM_TRANSLATE = 1 << 0,
//! Rotate with it's parent
CC_HONOR_PARENT_TRANSFORM_ROTATE = 1 << 1,
//! Scale with it's parent
CC_HONOR_PARENT_TRANSFORM_SCALE = 1 << 2,
//! All possible transformation enabled. Default value.
CC_HONOR_PARENT_TRANSFORM_ALL = CC_HONOR_PARENT_TRANSFORM_TRANSLATE | CC_HONOR_PARENT_TRANSFORM_ROTATE | CC_HONOR_PARENT_TRANSFORM_SCALE,
} ccHonorParentTransform;
/** CCSprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) )
*
* CCSprite can be created with an image, or with a sub-rectangle of an image.
*
* If the parent or any of its ancestors is a CCSpriteSheet then the following features/limitations are valid
* - Features when the parent is a CCSpriteSheet:
* - MUCH faster rendering, specially if the CCSpriteSheet has many children. All the children will be drawn in a single batch.
*
* - Limitations
* - Camera is not supported yet (eg: CCOrbitCamera action doesn't work)
* - GridBase actions are not supported (eg: CCLens, CCRipple, CCTwirl)
* - The Alias/Antialias property belongs to CCSpriteSheet, so you can't individually set the aliased property.
* - The Blending function property belongs to CCSpriteSheet, so you can't individually set the blending function property.
* - Parallax scroller is not supported, but can be simulated with a "proxy" sprite.
*
* If the parent is an standard CCNode, then CCSprite behaves like any other CCNode:
* - It supports blending functions
* - It supports aliasing / antialiasing
* - But the rendering will be slower: 1 draw per children.
*
*/
@interface CCSprite : CCNode <CCRGBAProtocol, CCTextureProtocol>
{
//
// Data used when the sprite is rendered using a CCSpriteSheet
//
CCTextureAtlas *textureAtlas_; // Sprite Sheet texture atlas (weak reference)
NSUInteger atlasIndex_; // Absolute (real) Index on the SpriteSheet
CCSpriteSheet *spriteSheet_; // Used spritesheet (weak reference)
ccHonorParentTransform honorParentTransform_; // whether or not to transform according to its parent transformations
BOOL dirty_; // Sprite needs to be updated
BOOL recursiveDirty_; // Subchildren needs to be updated
BOOL hasChildren_; // optimization to check if it contain children
//
// Data used when the sprite is self-rendered
//
ccBlendFunc blendFunc_; // Needed for the texture protocol
CCTexture2D *texture_; // Texture used to render the sprite
//
// Shared data
//
// whether or not it's parent is a CCSpriteSheet
BOOL usesSpriteSheet_;
// texture pixels
CGRect rect_;
// Offset Position (used by Zwoptex)
CGPoint offsetPosition_; // absolute
CGPoint unflippedOffsetPositionFromCenter_;
// vertex coords, texture coords and color info
ccV3F_C4B_T2F_Quad quad_;
// opacity and RGB protocol
GLubyte opacity_;
ccColor3B color_;
ccColor3B colorUnmodified_;
BOOL opacityModifyRGB_;
// image is flipped
BOOL flipX_;
BOOL flipY_;
// Animations that belong to the sprite
NSMutableDictionary *animations_;
}
/** whether or not the Sprite needs to be updated in the Atlas */
@property (nonatomic,readwrite) BOOL dirty;
/** the quad (tex coords, vertex coords and color) information */
@property (nonatomic,readonly) ccV3F_C4B_T2F_Quad quad;
/** The index used on the TextureATlas. Don't modify this value unless you know what you are doing */
@property (nonatomic,readwrite) NSUInteger atlasIndex;
/** returns the rect of the CCSprite */
@property (nonatomic,readonly) CGRect textureRect;
/** whether or not the sprite is flipped horizontally.
It only flips the texture of the sprite, and not the texture of the sprite's children.
Also, flipping the texture doesn't alter the anchorPoint.
If you want to flip the anchorPoint too, and/or to flip the children too use:
sprite.scaleX *= -1;
*/
@property (nonatomic,readwrite) BOOL flipX;
/** whether or not the sprite is flipped vertically.
It only flips the texture of the sprite, and not the texture of the sprite's children.
Also, flipping the texture doesn't alter the anchorPoint.
If you want to flip the anchorPoint too, and/or to flip the children too use:
sprite.scaleY *= -1;
*/
@property (nonatomic,readwrite) BOOL flipY;
/** opacity: conforms to CCRGBAProtocol protocol */
@property (nonatomic,readwrite) GLubyte opacity;
/** RGB colors: conforms to CCRGBAProtocol protocol */
@property (nonatomic,readwrite) ccColor3B color;
/** whether or not the Sprite is rendered using a CCSpriteSheet */
@property (nonatomic,readwrite) BOOL usesSpriteSheet;
/** weak reference of the CCTextureAtlas used when the sprite is rendered using a CCSpriteSheet */
@property (nonatomic,readwrite,assign) CCTextureAtlas *textureAtlas;
/** weak reference to the CCSpriteSheet that renders the CCSprite */
@property (nonatomic,readwrite,assign) CCSpriteSheet *spriteSheet;
/** whether or not to transform according to its parent transfomrations.
Useful for health bars. eg: Don't rotate the health bar, even if the parent rotates.
IMPORTANT: Only valid if it is rendered using an CCSpriteSheet.
@since v0.99.0
*/
@property (nonatomic,readwrite) ccHonorParentTransform honorParentTransform;
/** offset position of the sprite. Calculated automatically by editors like Zwoptex.
@since v0.99.0
*/
@property (nonatomic,readonly) CGPoint offsetPosition;
/** conforms to CCTextureProtocol protocol */
@property (nonatomic,readwrite) ccBlendFunc blendFunc;
#pragma mark CCSprite - Initializers
/** Creates an sprite with a texture.
The rect used will be the size of the texture.
The offset will be (0,0).
*/
+(id) spriteWithTexture:(CCTexture2D*)texture;
/** Creates an sprite with a texture and a rect.
The offset will be (0,0).
*/
+(id) spriteWithTexture:(CCTexture2D*)texture rect:(CGRect)rect;
/** Creates an sprite with a texture, a rect and offset.
*/
+(id) spriteWithTexture:(CCTexture2D*)texture rect:(CGRect)rect offset:(CGPoint)offset;
/** Creates an sprite with an sprite frame.
*/
+(id) spriteWithSpriteFrame:(CCSpriteFrame*)spriteFrame;
/** Creates an sprite with an sprite frame name.
An CCSpriteFrame will be fetched from the CCSpriteFrameCache by name.
If the CCSpriteFrame doesn't exist it will raise an exception.
@since v0.9
*/
+(id) spriteWithSpriteFrameName:(NSString*)spriteFrameName;
/** Creates an sprite with an image filename.
The rect used will be the size of the image.
The offset will be (0,0).
*/
+(id) spriteWithFile:(NSString*)filename;
/** Creates an sprite with an image filename and a rect.
The offset will be (0,0).
*/
+(id) spriteWithFile:(NSString*)filename rect:(CGRect)rect;
/** Creates an sprite with a CGImageRef.
@deprecated Use spriteWithCGImage:key: instead. Will be removed in v1.0 final
*/
+(id) spriteWithCGImage: (CGImageRef)image DEPRECATED_ATTRIBUTE;
/** Creates an sprite with a CGImageRef and a key.
The key is used by the CCTextureCache to know if a texture was already created with this CGImage.
For example, a valid key is: @"sprite_frame_01".
If key is nil, then a new texture will be created each time by the CCTextureCache.
@since v0.99.0
*/
+(id) spriteWithCGImage: (CGImageRef)image key:(NSString*)key;
/** Creates an sprite with an CCSpriteSheet and a rect
*/
+(id) spriteWithSpriteSheet:(CCSpriteSheet*)spritesheet rect:(CGRect)rect;
/** Initializes an sprite with a texture.
The rect used will be the size of the texture.
The offset will be (0,0).
*/
-(id) initWithTexture:(CCTexture2D*)texture;
/** Initializes an sprite with a texture and a rect.
The offset will be (0,0).
*/
-(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect;
/** Initializes an sprite with an sprite frame.
*/
-(id) initWithSpriteFrame:(CCSpriteFrame*)spriteFrame;
/** Initializes an sprite with an sprite frame name.
An CCSpriteFrame will be fetched from the CCSpriteFrameCache by name.
If the CCSpriteFrame doesn't exist it will raise an exception.
@since v0.9
*/
-(id) initWithSpriteFrameName:(NSString*)spriteFrameName;
/** Initializes an sprite with an image filename.
The rect used will be the size of the image.
The offset will be (0,0).
*/
-(id) initWithFile:(NSString*)filename;
/** Initializes an sprite with an image filename, and a rect.
The offset will be (0,0).
*/
-(id) initWithFile:(NSString*)filename rect:(CGRect)rect;
/** Initializes an sprite with a CGImageRef
@deprecated Use spriteWithCGImage:key: instead. Will be removed in v1.0 final
*/
-(id) initWithCGImage: (CGImageRef)image DEPRECATED_ATTRIBUTE;
/** Initializes an sprite with a CGImageRef and a key
The key is used by the CCTextureCache to know if a texture was already created with this CGImage.
For example, a valid key is: @"sprite_frame_01".
If key is nil, then a new texture will be created each time by the CCTextureCache.
@since v0.99.0
*/
-(id) initWithCGImage:(CGImageRef)image key:(NSString*)key;
/** Initializes an sprite with an CCSpriteSheet and a rect
*/
-(id) initWithSpriteSheet:(CCSpriteSheet*)spritesheet rect:(CGRect)rect;
#pragma mark CCSprite - SpriteSheet methods
/** updates the quad according the the rotation, position, scale values.
*/
-(void)updateTransform;
/** updates the texture rect of the CCSprite.
*/
-(void) setTextureRect:(CGRect) rect;
/** tell the sprite to use self-render.
@since v0.99.0
*/
-(void) useSelfRender;
/** tell the sprite to use sprite sheet render.
@since v0.99.0
*/
-(void) useSpriteSheetRender:(CCSpriteSheet*)spriteSheet;
#pragma mark CCSprite - Frames
/** sets a new display frame to the CCSprite. */
-(void) setDisplayFrame:(CCSpriteFrame*)newFrame;
/** returns whether or not a CCSpriteFrame is being displayed */
-(BOOL) isFrameDisplayed:(CCSpriteFrame*)frame;
/** returns the current displayed frame. */
-(CCSpriteFrame*) displayedFrame;
#pragma mark CCSprite - Animation
/** changes the display frame based on an animation and an index. */
-(void) setDisplayFrame: (NSString*) animationName index:(int) frameIndex;
/** returns an Animation given it's name. */
-(CCAnimation*)animationByName: (NSString*) animationName;
/** adds an Animation to the Sprite. */
-(void) addAnimation: (CCAnimation*) animation;
@end
| 0 | 0.908397 | 1 | 0.908397 | game-dev | MEDIA | 0.862455 | game-dev,graphics-rendering | 0.759492 | 1 | 0.759492 |
manisha-v/Number-Cruncher | 1,729 | Codes/Minor2d/Library/PackageCache/com.unity.2d.spriteshape@3.0.17/Samples~/Extras/Scripts/GenerateSpriteShapes.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.U2D;
// Please add this Component to Camera or some top level object on each loadable scene.
public class GenerateSpriteShapes : MonoBehaviour
{
// Once all SpriteShapes are rendered, remove this Component if On or remove it from elsewhere.
public bool destroyOnCompletion = true;
void OnGUI()
{
// Loop all invisible SpriteShapeRenderers and generate geometry.
SpriteShapeRenderer[] spriteShapeRenderers = (SpriteShapeRenderer[]) GameObject.FindObjectsOfType (typeof(SpriteShapeRenderer));
CommandBuffer rc = new CommandBuffer();
rc.GetTemporaryRT(0, 256, 256, 0);
rc.SetRenderTarget(0);
foreach (var spriteShapeRenderer in spriteShapeRenderers)
{
var spriteShapeController = spriteShapeRenderer.gameObject.GetComponent<SpriteShapeController>();
if (spriteShapeRenderer != null && spriteShapeController != null)
{
if (!spriteShapeRenderer.isVisible)
{
spriteShapeController.BakeMesh();
rc.DrawRenderer(spriteShapeRenderer, spriteShapeRenderer.sharedMaterial);
// Debug.Log("generating shape for " + spriteShapeRenderer.gameObject.name);
}
}
}
rc.ReleaseTemporaryRT(0);
Graphics.ExecuteCommandBuffer(rc);
// SpriteShape Renderers are generated. This component is no longer needed. Delete this [or] remove this Component from elsewhere.
if (destroyOnCompletion)
Destroy(this);
}
} | 0 | 0.781232 | 1 | 0.781232 | game-dev | MEDIA | 0.944556 | game-dev | 0.589447 | 1 | 0.589447 |
pms67/HadesFCS | 50,624 | Flight Simulator/UAVSim/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_BaseEditorPanel.cs | using UnityEngine;
using UnityEditor;
namespace TMPro.EditorUtilities
{
public abstract class TMP_BaseEditorPanel : Editor
{
//Labels and Tooltips
static readonly GUIContent k_RtlToggleLabel = new GUIContent("Enable RTL Editor", "Reverses text direction and allows right to left editing.");
static readonly GUIContent k_MainSettingsLabel = new GUIContent("Main Settings");
static readonly GUIContent k_FontAssetLabel = new GUIContent("Font Asset", "The Font Asset containing the glyphs that can be rendered for this text.");
static readonly GUIContent k_MaterialPresetLabel = new GUIContent("Material Preset", "The material used for rendering. Only materials created from the Font Asset can be used.");
static readonly GUIContent k_AutoSizeLabel = new GUIContent("Auto Size", "Auto sizes the text to fit the available space.");
static readonly GUIContent k_FontSizeLabel = new GUIContent("Font Size", "The size the text will be rendered at in points.");
static readonly GUIContent k_AutoSizeOptionsLabel = new GUIContent("Auto Size Options");
static readonly GUIContent k_MinLabel = new GUIContent("Min", "The minimum font size.");
static readonly GUIContent k_MaxLabel = new GUIContent("Max", "The maximum font size.");
static readonly GUIContent k_WdLabel = new GUIContent("WD%", "Compresses character width up to this value before reducing font size.");
static readonly GUIContent k_LineLabel = new GUIContent("Line", "Negative value only. Compresses line height down to this value before reducing font size.");
static readonly GUIContent k_FontStyleLabel = new GUIContent("Font Style", "Styles to apply to the text such as Bold or Italic.");
static readonly GUIContent k_BoldLabel = new GUIContent("B", "Bold");
static readonly GUIContent k_ItalicLabel = new GUIContent("I", "Italic");
static readonly GUIContent k_UnderlineLabel = new GUIContent("U", "Underline");
static readonly GUIContent k_StrikethroughLabel = new GUIContent("S", "Strikethrough");
static readonly GUIContent k_LowercaseLabel = new GUIContent("ab", "Lowercase");
static readonly GUIContent k_UppercaseLabel = new GUIContent("AB", "Uppercase");
static readonly GUIContent k_SmallcapsLabel = new GUIContent("SC", "Smallcaps");
static readonly GUIContent k_ColorModeLabel = new GUIContent("Color Mode", "The type of gradient to use.");
static readonly GUIContent k_BaseColorLabel = new GUIContent("Vertex Color", "The base color of the text vertices.");
static readonly GUIContent k_ColorPresetLabel = new GUIContent("Color Preset", "A Color Preset which override the local color settings.");
static readonly GUIContent k_ColorGradientLabel = new GUIContent("Color Gradient", "The gradient color applied over the Vertex Color. Can be locally set or driven by a Gradient Asset.");
static readonly GUIContent k_CorenerColorsLabel = new GUIContent("Colors", "The color composition of the gradient.");
static readonly GUIContent k_OverrideTagsLabel = new GUIContent("Override Tags", "Whether the color settings override the <color> tag.");
static readonly GUIContent k_SpacingOptionsLabel = new GUIContent("Spacing Options", "Spacing adjustments between different elements of the text.");
static readonly GUIContent k_CharacterSpacingLabel = new GUIContent("Character");
static readonly GUIContent k_WordSpacingLabel = new GUIContent("Word");
static readonly GUIContent k_LineSpacingLabel = new GUIContent("Line");
static readonly GUIContent k_ParagraphSpacingLabel = new GUIContent("Paragraph");
static readonly GUIContent k_AlignmentLabel = new GUIContent("Alignment", "Horizontal and vertical aligment of the text within its container.");
static readonly GUIContent k_WrapMixLabel = new GUIContent("Wrap Mix (W <-> C)", "How much to favor words versus characters when distributing the text.");
static readonly GUIContent k_WrappingLabel = new GUIContent("Wrapping", "Wraps text to the next line when reaching the edge of the container.");
static readonly GUIContent[] k_WrappingOptions = { new GUIContent("Disabled"), new GUIContent("Enabled") };
static readonly GUIContent k_OverflowLabel = new GUIContent("Overflow", "How to display text which goes past the edge of the container.");
static readonly GUIContent k_MarginsLabel = new GUIContent("Margins", "The space between the text and the edge of its container.");
static readonly GUIContent k_GeometrySortingLabel = new GUIContent("Geometry Sorting", "The order in which text geometry is sorted. Used to adjust the way overlapping characters are displayed.");
static readonly GUIContent k_RichTextLabel = new GUIContent("Rich Text", "Enables the use of rich text tags such as <color> and <font>.");
static readonly GUIContent k_EscapeCharactersLabel = new GUIContent("Parse Escape Characters", "Whether to display strings such as \"\\n\" as is or replace them by the character they represent.");
static readonly GUIContent k_VisibleDescenderLabel = new GUIContent("Visible Descender", "Compute descender values from visible characters only. Used to adjust layout behavior when hiding and revealing characters dynamically.");
static readonly GUIContent k_SpriteAssetLabel = new GUIContent("Sprite Asset", "The Sprite Asset used when NOT specifically referencing one using <sprite=\"Sprite Asset Name\">.");
static readonly GUIContent k_HorizontalMappingLabel = new GUIContent("Horizontal Mapping", "Horizontal UV mapping when using a shader with a texture face option.");
static readonly GUIContent k_VerticalMappingLabel = new GUIContent("Vertical Mapping", "Vertical UV mapping when using a shader with a texture face option.");
static readonly GUIContent k_LineOffsetLabel = new GUIContent("Line Offset", "Adds an horizontal offset to each successive line. Used for slanted texturing.");
static readonly GUIContent k_KerningLabel = new GUIContent("Kerning", "Enables character specific spacing between pairs of characters.");
static readonly GUIContent k_PaddingLabel = new GUIContent("Extra Padding", "Adds some padding between the characters and the edge of the text mesh. Can reduce graphical errors when displaying small text.");
static readonly GUIContent k_LeftLabel = new GUIContent("Left");
static readonly GUIContent k_TopLabel = new GUIContent("Top");
static readonly GUIContent k_RightLabel = new GUIContent("Right");
static readonly GUIContent k_BottomLabel = new GUIContent("Bottom");
protected static readonly GUIContent k_ExtraSettingsLabel = new GUIContent("Extra Settings");
protected struct Foldout
{
// Track Inspector foldout panel states, globally.
public static bool extraSettings = false;
public static bool materialInspector = true;
}
protected static int s_EventId;
public int selAlignGridA;
public int selAlignGridB;
protected SerializedProperty m_TextProp;
protected SerializedProperty m_IsRightToLeftProp;
protected string m_RtlText;
protected SerializedProperty m_FontAssetProp;
protected SerializedProperty m_FontSharedMaterialProp;
protected Material[] m_MaterialPresets;
protected GUIContent[] m_MaterialPresetNames;
protected int m_MaterialPresetSelectionIndex;
protected bool m_IsPresetListDirty;
protected SerializedProperty m_FontStyleProp;
protected SerializedProperty m_FontColorProp;
protected SerializedProperty m_EnableVertexGradientProp;
protected SerializedProperty m_FontColorGradientProp;
protected SerializedProperty m_FontColorGradientPresetProp;
protected SerializedProperty m_OverrideHtmlColorProp;
protected SerializedProperty m_FontSizeProp;
protected SerializedProperty m_FontSizeBaseProp;
protected SerializedProperty m_AutoSizingProp;
protected SerializedProperty m_FontSizeMinProp;
protected SerializedProperty m_FontSizeMaxProp;
protected SerializedProperty m_LineSpacingMaxProp;
protected SerializedProperty m_CharWidthMaxAdjProp;
protected SerializedProperty m_CharacterSpacingProp;
protected SerializedProperty m_WordSpacingProp;
protected SerializedProperty m_LineSpacingProp;
protected SerializedProperty m_ParagraphSpacingProp;
protected SerializedProperty m_TextAlignmentProp;
protected SerializedProperty m_HorizontalMappingProp;
protected SerializedProperty m_VerticalMappingProp;
protected SerializedProperty m_UvLineOffsetProp;
protected SerializedProperty m_EnableWordWrappingProp;
protected SerializedProperty m_WordWrappingRatiosProp;
protected SerializedProperty m_TextOverflowModeProp;
protected SerializedProperty m_PageToDisplayProp;
protected SerializedProperty m_LinkedTextComponentProp;
protected SerializedProperty m_IsLinkedTextComponentProp;
protected SerializedProperty m_EnableKerningProp;
protected SerializedProperty m_IsRichTextProp;
protected SerializedProperty m_HasFontAssetChangedProp;
protected SerializedProperty m_EnableExtraPaddingProp;
protected SerializedProperty m_CheckPaddingRequiredProp;
protected SerializedProperty m_EnableEscapeCharacterParsingProp;
protected SerializedProperty m_UseMaxVisibleDescenderProp;
protected SerializedProperty m_GeometrySortingOrderProp;
protected SerializedProperty m_SpriteAssetProp;
protected SerializedProperty m_MarginProp;
protected SerializedProperty m_ColorModeProp;
protected bool m_HavePropertiesChanged;
protected TMP_Text m_TextComponent;
protected RectTransform m_RectTransform;
protected Material m_TargetMaterial;
protected Vector3[] m_RectCorners = new Vector3[4];
protected Vector3[] m_HandlePoints = new Vector3[4];
protected virtual void OnEnable()
{
m_TextProp = serializedObject.FindProperty("m_text");
m_IsRightToLeftProp = serializedObject.FindProperty("m_isRightToLeft");
m_FontAssetProp = serializedObject.FindProperty("m_fontAsset");
m_FontSharedMaterialProp = serializedObject.FindProperty("m_sharedMaterial");
m_FontStyleProp = serializedObject.FindProperty("m_fontStyle");
m_FontSizeProp = serializedObject.FindProperty("m_fontSize");
m_FontSizeBaseProp = serializedObject.FindProperty("m_fontSizeBase");
m_AutoSizingProp = serializedObject.FindProperty("m_enableAutoSizing");
m_FontSizeMinProp = serializedObject.FindProperty("m_fontSizeMin");
m_FontSizeMaxProp = serializedObject.FindProperty("m_fontSizeMax");
m_LineSpacingMaxProp = serializedObject.FindProperty("m_lineSpacingMax");
m_CharWidthMaxAdjProp = serializedObject.FindProperty("m_charWidthMaxAdj");
// Colors & Gradient
m_FontColorProp = serializedObject.FindProperty("m_fontColor");
m_EnableVertexGradientProp = serializedObject.FindProperty("m_enableVertexGradient");
m_FontColorGradientProp = serializedObject.FindProperty("m_fontColorGradient");
m_FontColorGradientPresetProp = serializedObject.FindProperty("m_fontColorGradientPreset");
m_OverrideHtmlColorProp = serializedObject.FindProperty("m_overrideHtmlColors");
m_CharacterSpacingProp = serializedObject.FindProperty("m_characterSpacing");
m_WordSpacingProp = serializedObject.FindProperty("m_wordSpacing");
m_LineSpacingProp = serializedObject.FindProperty("m_lineSpacing");
m_ParagraphSpacingProp = serializedObject.FindProperty("m_paragraphSpacing");
m_TextAlignmentProp = serializedObject.FindProperty("m_textAlignment");
m_HorizontalMappingProp = serializedObject.FindProperty("m_horizontalMapping");
m_VerticalMappingProp = serializedObject.FindProperty("m_verticalMapping");
m_UvLineOffsetProp = serializedObject.FindProperty("m_uvLineOffset");
m_EnableWordWrappingProp = serializedObject.FindProperty("m_enableWordWrapping");
m_WordWrappingRatiosProp = serializedObject.FindProperty("m_wordWrappingRatios");
m_TextOverflowModeProp = serializedObject.FindProperty("m_overflowMode");
m_PageToDisplayProp = serializedObject.FindProperty("m_pageToDisplay");
m_LinkedTextComponentProp = serializedObject.FindProperty("m_linkedTextComponent");
m_IsLinkedTextComponentProp = serializedObject.FindProperty("m_isLinkedTextComponent");
m_EnableKerningProp = serializedObject.FindProperty("m_enableKerning");
m_EnableExtraPaddingProp = serializedObject.FindProperty("m_enableExtraPadding");
m_IsRichTextProp = serializedObject.FindProperty("m_isRichText");
m_CheckPaddingRequiredProp = serializedObject.FindProperty("checkPaddingRequired");
m_EnableEscapeCharacterParsingProp = serializedObject.FindProperty("m_parseCtrlCharacters");
m_UseMaxVisibleDescenderProp = serializedObject.FindProperty("m_useMaxVisibleDescender");
m_GeometrySortingOrderProp = serializedObject.FindProperty("m_geometrySortingOrder");
m_SpriteAssetProp = serializedObject.FindProperty("m_spriteAsset");
m_MarginProp = serializedObject.FindProperty("m_margin");
m_HasFontAssetChangedProp = serializedObject.FindProperty("m_hasFontAssetChanged");
m_ColorModeProp = serializedObject.FindProperty("m_colorMode");
m_TextComponent = (TMP_Text)target;
m_RectTransform = m_TextComponent.rectTransform;
// Create new Material Editor if one does not exists
m_TargetMaterial = m_TextComponent.fontSharedMaterial;
// Set material inspector visibility
if (m_TargetMaterial != null)
UnityEditorInternal.InternalEditorUtility.SetIsInspectorExpanded(m_TargetMaterial, Foldout.materialInspector);
// Find all Material Presets matching the current Font Asset Material
m_MaterialPresetNames = GetMaterialPresets();
// Initialize the Event Listener for Undo Events.
Undo.undoRedoPerformed += OnUndoRedo;
}
protected virtual void OnDisable()
{
// Set material inspector visibility
if (m_TargetMaterial != null)
Foldout.materialInspector = UnityEditorInternal.InternalEditorUtility.GetIsInspectorExpanded(m_TargetMaterial);
if (Undo.undoRedoPerformed != null)
Undo.undoRedoPerformed -= OnUndoRedo;
}
public override void OnInspectorGUI()
{
// Make sure Multi selection only includes TMP Text objects.
if (IsMixSelectionTypes()) return;
serializedObject.Update();
DrawTextInput();
DrawMainSettings();
DrawExtraSettings();
EditorGUILayout.Space();
if (m_HavePropertiesChanged)
{
m_HavePropertiesChanged = false;
m_TextComponent.havePropertiesChanged = true;
m_TextComponent.ComputeMarginSize();
EditorUtility.SetDirty(target);
}
serializedObject.ApplyModifiedProperties();
}
public void OnSceneGUI()
{
if (IsMixSelectionTypes()) return;
// Margin Frame & Handles
m_RectTransform.GetWorldCorners(m_RectCorners);
Vector4 marginOffset = m_TextComponent.margin;
Vector3 lossyScale = m_RectTransform.lossyScale;
m_HandlePoints[0] = m_RectCorners[0] + m_RectTransform.TransformDirection(new Vector3(marginOffset.x * lossyScale.x, marginOffset.w * lossyScale.y, 0));
m_HandlePoints[1] = m_RectCorners[1] + m_RectTransform.TransformDirection(new Vector3(marginOffset.x * lossyScale.x, -marginOffset.y * lossyScale.y, 0));
m_HandlePoints[2] = m_RectCorners[2] + m_RectTransform.TransformDirection(new Vector3(-marginOffset.z * lossyScale.x, -marginOffset.y * lossyScale.y, 0));
m_HandlePoints[3] = m_RectCorners[3] + m_RectTransform.TransformDirection(new Vector3(-marginOffset.z * lossyScale.x, marginOffset.w * lossyScale.y, 0));
Handles.DrawSolidRectangleWithOutline(m_HandlePoints, new Color32(255, 255, 255, 0), new Color32(255, 255, 0, 255));
// Draw & process FreeMoveHandles
// LEFT HANDLE
Vector3 oldLeft = (m_HandlePoints[0] + m_HandlePoints[1]) * 0.5f;
Vector3 newLeft = Handles.FreeMoveHandle(oldLeft, Quaternion.identity, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap);
bool hasChanged = false;
if (oldLeft != newLeft)
{
float delta = oldLeft.x - newLeft.x;
marginOffset.x += -delta / lossyScale.x;
//Debug.Log("Left Margin H0:" + handlePoints[0] + " H1:" + handlePoints[1]);
hasChanged = true;
}
// TOP HANDLE
Vector3 oldTop = (m_HandlePoints[1] + m_HandlePoints[2]) * 0.5f;
Vector3 newTop = Handles.FreeMoveHandle(oldTop, Quaternion.identity, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap);
if (oldTop != newTop)
{
float delta = oldTop.y - newTop.y;
marginOffset.y += delta / lossyScale.y;
//Debug.Log("Top Margin H1:" + handlePoints[1] + " H2:" + handlePoints[2]);
hasChanged = true;
}
// RIGHT HANDLE
Vector3 oldRight = (m_HandlePoints[2] + m_HandlePoints[3]) * 0.5f;
Vector3 newRight = Handles.FreeMoveHandle(oldRight, Quaternion.identity, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap);
if (oldRight != newRight)
{
float delta = oldRight.x - newRight.x;
marginOffset.z += delta / lossyScale.x;
hasChanged = true;
//Debug.Log("Right Margin H2:" + handlePoints[2] + " H3:" + handlePoints[3]);
}
// BOTTOM HANDLE
Vector3 oldBottom = (m_HandlePoints[3] + m_HandlePoints[0]) * 0.5f;
Vector3 newBottom = Handles.FreeMoveHandle(oldBottom, Quaternion.identity, HandleUtility.GetHandleSize(m_RectTransform.position) * 0.05f, Vector3.zero, Handles.DotHandleCap);
if (oldBottom != newBottom)
{
float delta = oldBottom.y - newBottom.y;
marginOffset.w += -delta / lossyScale.y;
hasChanged = true;
//Debug.Log("Bottom Margin H0:" + handlePoints[0] + " H3:" + handlePoints[3]);
}
if (hasChanged)
{
Undo.RecordObjects(new Object[] {m_RectTransform, m_TextComponent }, "Margin Changes");
m_TextComponent.margin = marginOffset;
EditorUtility.SetDirty(target);
}
}
protected void DrawTextInput()
{
EditorGUILayout.Space();
// If the text component is linked, disable the text input box.
if (m_IsLinkedTextComponentProp.boolValue)
{
EditorGUILayout.HelpBox("The Text Input Box is disabled due to this text component being linked to another.", MessageType.Info);
}
else
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_TextProp);
if (EditorGUI.EndChangeCheck() || (m_IsRightToLeftProp.boolValue && string.IsNullOrEmpty(m_RtlText)))
{
m_TextComponent.m_inputSource = TMP_Text.TextInputSources.Text;
m_TextComponent.m_isInputParsingRequired = true;
m_HavePropertiesChanged = true;
// Handle Left to Right or Right to Left Editor
if (m_IsRightToLeftProp.boolValue)
{
m_RtlText = string.Empty;
string sourceText = m_TextProp.stringValue;
// Reverse Text displayed in Text Input Box
for (int i = 0; i < sourceText.Length; i++)
{
m_RtlText += sourceText[sourceText.Length - i - 1];
}
}
}
// Toggle showing Rich Tags
m_IsRightToLeftProp.boolValue = EditorGUILayout.Toggle(k_RtlToggleLabel, m_IsRightToLeftProp.boolValue);
if (m_IsRightToLeftProp.boolValue)
{
EditorGUI.BeginChangeCheck();
m_RtlText = EditorGUILayout.TextArea(m_RtlText, TMP_UIStyleManager.wrappingTextArea, GUILayout.Height(EditorGUI.GetPropertyHeight(m_TextProp) - EditorGUIUtility.singleLineHeight), GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck())
{
// Convert RTL input
string sourceText = string.Empty;
// Reverse Text displayed in Text Input Box
for (int i = 0; i < m_RtlText.Length; i++)
{
sourceText += m_RtlText[m_RtlText.Length - i - 1];
}
m_TextProp.stringValue = sourceText;
}
}
}
}
protected void DrawMainSettings()
{
// MAIN SETTINGS SECTION
GUILayout.Label(k_MainSettingsLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel += 1;
DrawFont();
DrawColor();
DrawSpacing();
DrawAlignment();
DrawWrappingOverflow();
DrawTextureMapping();
EditorGUI.indentLevel -= 1;
}
void DrawFont()
{
// Update list of material presets if needed.
if (m_IsPresetListDirty)
m_MaterialPresetNames = GetMaterialPresets();
// FONT ASSET
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_FontAssetProp, k_FontAssetLabel);
if (EditorGUI.EndChangeCheck())
{
m_HavePropertiesChanged = true;
m_HasFontAssetChangedProp.boolValue = true;
m_IsPresetListDirty = true;
m_MaterialPresetSelectionIndex = 0;
}
Rect rect;
// MATERIAL PRESET
if (m_MaterialPresetNames != null)
{
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false, 17);
float oldHeight = EditorStyles.popup.fixedHeight;
EditorStyles.popup.fixedHeight = rect.height;
int oldSize = EditorStyles.popup.fontSize;
EditorStyles.popup.fontSize = 11;
m_MaterialPresetSelectionIndex = EditorGUI.Popup(rect, k_MaterialPresetLabel, m_MaterialPresetSelectionIndex, m_MaterialPresetNames);
if (EditorGUI.EndChangeCheck())
{
m_FontSharedMaterialProp.objectReferenceValue = m_MaterialPresets[m_MaterialPresetSelectionIndex];
m_HavePropertiesChanged = true;
}
//Make sure material preset selection index matches the selection
if (m_MaterialPresetSelectionIndex < m_MaterialPresetNames.Length && m_TargetMaterial != m_MaterialPresets[m_MaterialPresetSelectionIndex] && !m_HavePropertiesChanged)
m_IsPresetListDirty = true;
EditorStyles.popup.fixedHeight = oldHeight;
EditorStyles.popup.fontSize = oldSize;
}
// FONT STYLE
EditorGUI.BeginChangeCheck();
int v1, v2, v3, v4, v5, v6, v7;
if (EditorGUIUtility.wideMode)
{
rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight + 2f);
EditorGUI.PrefixLabel(rect, k_FontStyleLabel);
int styleValue = m_FontStyleProp.intValue;
rect.x += EditorGUIUtility.labelWidth;
rect.width -= EditorGUIUtility.labelWidth;
rect.width = Mathf.Max(25f, rect.width / 7f);
v1 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 1) == 1, k_BoldLabel, TMP_UIStyleManager.alignmentButtonLeft) ? 1 : 0; // Bold
rect.x += rect.width;
v2 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 2) == 2, k_ItalicLabel, TMP_UIStyleManager.alignmentButtonMid) ? 2 : 0; // Italics
rect.x += rect.width;
v3 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 4) == 4, k_UnderlineLabel, TMP_UIStyleManager.alignmentButtonMid) ? 4 : 0; // Underline
rect.x += rect.width;
v7 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 64) == 64, k_StrikethroughLabel, TMP_UIStyleManager.alignmentButtonRight) ? 64 : 0; // Strikethrough
rect.x += rect.width;
int selected = 0;
EditorGUI.BeginChangeCheck();
v4 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 8) == 8, k_LowercaseLabel, TMP_UIStyleManager.alignmentButtonLeft) ? 8 : 0; // Lowercase
if (EditorGUI.EndChangeCheck() && v4 > 0)
{
selected = v4;
}
rect.x += rect.width;
EditorGUI.BeginChangeCheck();
v5 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 16) == 16, k_UppercaseLabel, TMP_UIStyleManager.alignmentButtonMid) ? 16 : 0; // Uppercase
if (EditorGUI.EndChangeCheck() && v5 > 0)
{
selected = v5;
}
rect.x += rect.width;
EditorGUI.BeginChangeCheck();
v6 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 32) == 32, k_SmallcapsLabel, TMP_UIStyleManager.alignmentButtonRight) ? 32 : 0; // Smallcaps
if (EditorGUI.EndChangeCheck() && v6 > 0)
{
selected = v6;
}
if (selected > 0)
{
v4 = selected == 8 ? 8 : 0;
v5 = selected == 16 ? 16 : 0;
v6 = selected == 32 ? 32 : 0;
}
}
else
{
rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight + 2f);
EditorGUI.PrefixLabel(rect, k_FontStyleLabel);
int styleValue = m_FontStyleProp.intValue;
rect.x += EditorGUIUtility.labelWidth;
rect.width -= EditorGUIUtility.labelWidth;
rect.width = Mathf.Max(25f, rect.width / 4f);
v1 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 1) == 1, k_BoldLabel, TMP_UIStyleManager.alignmentButtonLeft) ? 1 : 0; // Bold
rect.x += rect.width;
v2 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 2) == 2, k_ItalicLabel, TMP_UIStyleManager.alignmentButtonMid) ? 2 : 0; // Italics
rect.x += rect.width;
v3 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 4) == 4, k_UnderlineLabel, TMP_UIStyleManager.alignmentButtonMid) ? 4 : 0; // Underline
rect.x += rect.width;
v7 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 64) == 64, k_StrikethroughLabel, TMP_UIStyleManager.alignmentButtonRight) ? 64 : 0; // Strikethrough
rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight + 2f);
rect.x += EditorGUIUtility.labelWidth;
rect.width -= EditorGUIUtility.labelWidth;
rect.width = Mathf.Max(25f, rect.width / 4f);
int selected = 0;
EditorGUI.BeginChangeCheck();
v4 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 8) == 8, k_LowercaseLabel, TMP_UIStyleManager.alignmentButtonLeft) ? 8 : 0; // Lowercase
if (EditorGUI.EndChangeCheck() && v4 > 0)
{
selected = v4;
}
rect.x += rect.width;
EditorGUI.BeginChangeCheck();
v5 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 16) == 16, k_UppercaseLabel, TMP_UIStyleManager.alignmentButtonMid) ? 16 : 0; // Uppercase
if (EditorGUI.EndChangeCheck() && v5 > 0)
{
selected = v5;
}
rect.x += rect.width;
EditorGUI.BeginChangeCheck();
v6 = TMP_EditorUtility.EditorToggle(rect, (styleValue & 32) == 32, k_SmallcapsLabel, TMP_UIStyleManager.alignmentButtonRight) ? 32 : 0; // Smallcaps
if (EditorGUI.EndChangeCheck() && v6 > 0)
{
selected = v6;
}
if (selected > 0)
{
v4 = selected == 8 ? 8 : 0;
v5 = selected == 16 ? 16 : 0;
v6 = selected == 32 ? 32 : 0;
}
}
if (EditorGUI.EndChangeCheck())
{
m_FontStyleProp.intValue = v1 + v2 + v3 + v4 + v5 + v6 + v7;
m_HavePropertiesChanged = true;
}
// FONT SIZE
EditorGUI.BeginChangeCheck();
EditorGUI.BeginDisabledGroup(m_AutoSizingProp.boolValue);
EditorGUILayout.PropertyField(m_FontSizeProp, k_FontSizeLabel, GUILayout.MaxWidth(EditorGUIUtility.labelWidth + 50f));
EditorGUI.EndDisabledGroup();
if (EditorGUI.EndChangeCheck())
{
m_FontSizeBaseProp.floatValue = m_FontSizeProp.floatValue;
m_HavePropertiesChanged = true;
}
EditorGUI.indentLevel += 1;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AutoSizingProp, k_AutoSizeLabel);
if (EditorGUI.EndChangeCheck())
{
if (m_AutoSizingProp.boolValue == false)
m_FontSizeProp.floatValue = m_FontSizeBaseProp.floatValue;
m_HavePropertiesChanged = true;
}
// Show auto sizing options
if (m_AutoSizingProp.boolValue)
{
rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight);
EditorGUI.PrefixLabel(rect, k_AutoSizeOptionsLabel);
int previousIndent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
rect.width = (rect.width - EditorGUIUtility.labelWidth) / 4f;
rect.x += EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 24;
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(rect, m_FontSizeMinProp, k_MinLabel);
if (EditorGUI.EndChangeCheck())
{
m_FontSizeMinProp.floatValue = Mathf.Min(m_FontSizeMinProp.floatValue, m_FontSizeMaxProp.floatValue);
m_HavePropertiesChanged = true;
}
rect.x += rect.width;
EditorGUIUtility.labelWidth = 27;
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(rect, m_FontSizeMaxProp, k_MaxLabel);
if (EditorGUI.EndChangeCheck())
{
m_FontSizeMaxProp.floatValue = Mathf.Max(m_FontSizeMinProp.floatValue, m_FontSizeMaxProp.floatValue);
m_HavePropertiesChanged = true;
}
rect.x += rect.width;
EditorGUI.BeginChangeCheck();
EditorGUIUtility.labelWidth = 36;
EditorGUI.PropertyField(rect, m_CharWidthMaxAdjProp, k_WdLabel);
rect.x += rect.width;
EditorGUIUtility.labelWidth = 28;
EditorGUI.PropertyField(rect, m_LineSpacingMaxProp, k_LineLabel);
EditorGUIUtility.labelWidth = 0;
if (EditorGUI.EndChangeCheck())
{
m_CharWidthMaxAdjProp.floatValue = Mathf.Clamp(m_CharWidthMaxAdjProp.floatValue, 0, 50);
m_LineSpacingMaxProp.floatValue = Mathf.Min(0, m_LineSpacingMaxProp.floatValue);
m_HavePropertiesChanged = true;
}
EditorGUI.indentLevel = previousIndent;
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DrawColor()
{
// FACE VERTEX COLOR
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_FontColorProp, k_BaseColorLabel);
EditorGUILayout.PropertyField(m_EnableVertexGradientProp, k_ColorGradientLabel);
if (EditorGUI.EndChangeCheck())
{
m_HavePropertiesChanged = true;
}
EditorGUIUtility.fieldWidth = 0;
if (m_EnableVertexGradientProp.boolValue)
{
EditorGUI.indentLevel += 1;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_FontColorGradientPresetProp, k_ColorPresetLabel);
SerializedObject obj = null;
SerializedProperty colorMode;
SerializedProperty topLeft;
SerializedProperty topRight;
SerializedProperty bottomLeft;
SerializedProperty bottomRight;
if (m_FontColorGradientPresetProp.objectReferenceValue == null)
{
colorMode = m_ColorModeProp;
topLeft = m_FontColorGradientProp.FindPropertyRelative("topLeft");
topRight = m_FontColorGradientProp.FindPropertyRelative("topRight");
bottomLeft = m_FontColorGradientProp.FindPropertyRelative("bottomLeft");
bottomRight = m_FontColorGradientProp.FindPropertyRelative("bottomRight");
}
else
{
obj = new SerializedObject(m_FontColorGradientPresetProp.objectReferenceValue);
colorMode = obj.FindProperty("colorMode");
topLeft = obj.FindProperty("topLeft");
topRight = obj.FindProperty("topRight");
bottomLeft = obj.FindProperty("bottomLeft");
bottomRight = obj.FindProperty("bottomRight");
}
EditorGUILayout.PropertyField(colorMode, k_ColorModeLabel);
var rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2));
EditorGUI.PrefixLabel(rect, k_CorenerColorsLabel);
rect.x += EditorGUIUtility.labelWidth;
rect.width = rect.width - EditorGUIUtility.labelWidth;
switch ((ColorMode)colorMode.enumValueIndex)
{
case ColorMode.Single:
TMP_EditorUtility.DrawColorProperty(rect, topLeft);
topRight.colorValue = topLeft.colorValue;
bottomLeft.colorValue = topLeft.colorValue;
bottomRight.colorValue = topLeft.colorValue;
break;
case ColorMode.HorizontalGradient:
rect.width /= 2f;
TMP_EditorUtility.DrawColorProperty(rect, topLeft);
rect.x += rect.width;
TMP_EditorUtility.DrawColorProperty(rect, topRight);
bottomLeft.colorValue = topLeft.colorValue;
bottomRight.colorValue = topRight.colorValue;
break;
case ColorMode.VerticalGradient:
TMP_EditorUtility.DrawColorProperty(rect, topLeft);
rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2));
rect.x += EditorGUIUtility.labelWidth;
TMP_EditorUtility.DrawColorProperty(rect, bottomLeft);
topRight.colorValue = topLeft.colorValue;
bottomRight.colorValue = bottomLeft.colorValue;
break;
case ColorMode.FourCornersGradient:
rect.width /= 2f;
TMP_EditorUtility.DrawColorProperty(rect, topLeft);
rect.x += rect.width;
TMP_EditorUtility.DrawColorProperty(rect, topRight);
rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2));
rect.x += EditorGUIUtility.labelWidth;
rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2f;
TMP_EditorUtility.DrawColorProperty(rect, bottomLeft);
rect.x += rect.width;
TMP_EditorUtility.DrawColorProperty(rect, bottomRight);
break;
}
if (EditorGUI.EndChangeCheck())
{
m_HavePropertiesChanged = true;
if (obj != null)
{
obj.ApplyModifiedProperties();
TMPro_EventManager.ON_COLOR_GRAIDENT_PROPERTY_CHANGED(m_FontColorGradientPresetProp.objectReferenceValue as TMP_ColorGradient);
}
}
EditorGUI.indentLevel -= 1;
}
EditorGUILayout.PropertyField(m_OverrideHtmlColorProp, k_OverrideTagsLabel);
EditorGUILayout.Space();
}
void DrawSpacing()
{
// CHARACTER, LINE & PARAGRAPH SPACING
EditorGUI.BeginChangeCheck();
Rect rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight);
EditorGUI.PrefixLabel(rect, k_SpacingOptionsLabel);
int oldIndent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
rect.x += EditorGUIUtility.labelWidth;
rect.width = (rect.width - EditorGUIUtility.labelWidth - 3f) / 2f;
EditorGUIUtility.labelWidth = Mathf.Min(rect.width * 0.55f, 80f);
EditorGUI.PropertyField(rect, m_CharacterSpacingProp, k_CharacterSpacingLabel);
rect.x += rect.width + 3f;
EditorGUI.PropertyField(rect, m_WordSpacingProp, k_WordSpacingLabel);
rect = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight);
EditorGUIUtility.labelWidth = 0;
rect.x += EditorGUIUtility.labelWidth;
rect.width = (rect.width - EditorGUIUtility.labelWidth -3f) / 2f;
EditorGUIUtility.labelWidth = Mathf.Min(rect.width * 0.55f, 80f);
EditorGUI.PropertyField(rect, m_LineSpacingProp, k_LineSpacingLabel);
rect.x += rect.width + 3f;
EditorGUI.PropertyField(rect, m_ParagraphSpacingProp, k_ParagraphSpacingLabel);
EditorGUIUtility.labelWidth = 0;
EditorGUI.indentLevel = oldIndent;
if (EditorGUI.EndChangeCheck())
{
m_HavePropertiesChanged = true;
}
}
void DrawAlignment()
{
// TEXT ALIGNMENT
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_TextAlignmentProp, k_AlignmentLabel);
// WRAPPING RATIOS shown if Justified mode is selected.
if (((_HorizontalAlignmentOptions)m_TextAlignmentProp.intValue & _HorizontalAlignmentOptions.Justified) == _HorizontalAlignmentOptions.Justified || ((_HorizontalAlignmentOptions)m_TextAlignmentProp.intValue & _HorizontalAlignmentOptions.Flush) == _HorizontalAlignmentOptions.Flush)
DrawPropertySlider(k_WrapMixLabel, m_WordWrappingRatiosProp);
if (EditorGUI.EndChangeCheck())
m_HavePropertiesChanged = true;
EditorGUILayout.Space();
}
void DrawWrappingOverflow()
{
// TEXT WRAPPING
EditorGUI.BeginChangeCheck();
int wrapSelection = EditorGUILayout.Popup(k_WrappingLabel, m_EnableWordWrappingProp.boolValue ? 1 : 0, k_WrappingOptions);
if (EditorGUI.EndChangeCheck())
{
m_EnableWordWrappingProp.boolValue = wrapSelection == 1;
m_HavePropertiesChanged = true;
m_TextComponent.m_isInputParsingRequired = true;
}
// TEXT OVERFLOW
EditorGUI.BeginChangeCheck();
// Cache Reference to Linked Text Component
TMP_Text oldLinkedComponent = m_LinkedTextComponentProp.objectReferenceValue as TMP_Text;
if ((TextOverflowModes)m_TextOverflowModeProp.enumValueIndex == TextOverflowModes.Linked)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(m_TextOverflowModeProp, k_OverflowLabel);
EditorGUILayout.PropertyField(m_LinkedTextComponentProp, GUIContent.none);
EditorGUILayout.EndHorizontal();
if (GUI.changed)
{
TMP_Text linkedComponent = m_LinkedTextComponentProp.objectReferenceValue as TMP_Text;
if (linkedComponent)
m_TextComponent.linkedTextComponent = linkedComponent;
}
}
else if ((TextOverflowModes)m_TextOverflowModeProp.enumValueIndex == TextOverflowModes.Page)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(m_TextOverflowModeProp, k_OverflowLabel);
EditorGUILayout.PropertyField(m_PageToDisplayProp, GUIContent.none);
EditorGUILayout.EndHorizontal();
if (oldLinkedComponent)
m_TextComponent.linkedTextComponent = null;
}
else
{
EditorGUILayout.PropertyField(m_TextOverflowModeProp, k_OverflowLabel);
if (oldLinkedComponent)
m_TextComponent.linkedTextComponent = null;
}
if (EditorGUI.EndChangeCheck())
{
m_HavePropertiesChanged = true;
m_TextComponent.m_isInputParsingRequired = true;
}
EditorGUILayout.Space();
}
protected abstract void DrawExtraSettings();
protected void DrawMargins()
{
EditorGUI.BeginChangeCheck();
DrawMarginProperty(m_MarginProp, k_MarginsLabel);
if (EditorGUI.EndChangeCheck())
{
m_HavePropertiesChanged = true;
}
EditorGUILayout.Space();
}
protected void DrawGeometrySorting()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_GeometrySortingOrderProp, k_GeometrySortingLabel);
if (EditorGUI.EndChangeCheck())
m_HavePropertiesChanged = true;
EditorGUILayout.Space();
}
protected void DrawRichText()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_IsRichTextProp, k_RichTextLabel);
if (EditorGUI.EndChangeCheck())
m_HavePropertiesChanged = true;
}
protected void DrawParsing()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_EnableEscapeCharacterParsingProp, k_EscapeCharactersLabel);
EditorGUILayout.PropertyField(m_UseMaxVisibleDescenderProp, k_VisibleDescenderLabel);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_SpriteAssetProp, k_SpriteAssetLabel, true);
if (EditorGUI.EndChangeCheck())
m_HavePropertiesChanged = true;
EditorGUILayout.Space();
}
protected void DrawTextureMapping()
{
// TEXTURE MAPPING OPTIONS
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_HorizontalMappingProp, k_HorizontalMappingLabel);
EditorGUILayout.PropertyField(m_VerticalMappingProp, k_VerticalMappingLabel);
if (EditorGUI.EndChangeCheck())
{
m_HavePropertiesChanged = true;
}
// UV OPTIONS
if (m_HorizontalMappingProp.enumValueIndex > 0)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_UvLineOffsetProp, k_LineOffsetLabel, GUILayout.MinWidth(70f));
if (EditorGUI.EndChangeCheck())
{
m_HavePropertiesChanged = true;
}
}
EditorGUILayout.Space();
}
protected void DrawKerning()
{
// KERNING
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_EnableKerningProp, k_KerningLabel);
if (EditorGUI.EndChangeCheck())
{
m_HavePropertiesChanged = true;
}
}
protected void DrawPadding()
{
// EXTRA PADDING
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_EnableExtraPaddingProp, k_PaddingLabel);
if (EditorGUI.EndChangeCheck())
{
m_HavePropertiesChanged = true;
m_CheckPaddingRequiredProp.boolValue = true;
}
}
/// <summary>
/// Method to retrieve the material presets that match the currently selected font asset.
/// </summary>
protected GUIContent[] GetMaterialPresets()
{
TMP_FontAsset fontAsset = m_FontAssetProp.objectReferenceValue as TMP_FontAsset;
if (fontAsset == null) return null;
m_MaterialPresets = TMP_EditorUtility.FindMaterialReferences(fontAsset);
m_MaterialPresetNames = new GUIContent[m_MaterialPresets.Length];
for (int i = 0; i < m_MaterialPresetNames.Length; i++)
{
m_MaterialPresetNames[i] = new GUIContent(m_MaterialPresets[i].name);
if (m_TargetMaterial.GetInstanceID() == m_MaterialPresets[i].GetInstanceID())
m_MaterialPresetSelectionIndex = i;
}
m_IsPresetListDirty = false;
return m_MaterialPresetNames;
}
// DRAW MARGIN PROPERTY
protected void DrawMarginProperty(SerializedProperty property, GUIContent label)
{
Rect rect = EditorGUILayout.GetControlRect(false, 2 * 18);
EditorGUI.BeginProperty(rect, label, property);
Rect pos0 = new Rect(rect.x + 15, rect.y + 2, rect.width - 15, 18);
float width = rect.width + 3;
pos0.width = EditorGUIUtility.labelWidth;
GUI.Label(pos0, label);
var vec = property.vector4Value;
float widthB = width - EditorGUIUtility.labelWidth;
float fieldWidth = widthB / 4;
pos0.width = Mathf.Max(fieldWidth - 5, 45f);
// Labels
pos0.x = EditorGUIUtility.labelWidth + 15;
GUI.Label(pos0, k_LeftLabel);
pos0.x += fieldWidth;
GUI.Label(pos0, k_TopLabel);
pos0.x += fieldWidth;
GUI.Label(pos0, k_RightLabel);
pos0.x += fieldWidth;
GUI.Label(pos0, k_BottomLabel);
pos0.y += 18;
pos0.x = EditorGUIUtility.labelWidth;
vec.x = EditorGUI.FloatField(pos0, GUIContent.none, vec.x);
pos0.x += fieldWidth;
vec.y = EditorGUI.FloatField(pos0, GUIContent.none, vec.y);
pos0.x += fieldWidth;
vec.z = EditorGUI.FloatField(pos0, GUIContent.none, vec.z);
pos0.x += fieldWidth;
vec.w = EditorGUI.FloatField(pos0, GUIContent.none, vec.w);
property.vector4Value = vec;
EditorGUI.EndProperty();
}
protected void DrawPropertySlider(GUIContent label, SerializedProperty property)
{
Rect rect = EditorGUILayout.GetControlRect(false, 17);
GUIContent content = label ?? GUIContent.none;
EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, rect.height), property, 0.0f, 1.0f, content);
}
protected abstract bool IsMixSelectionTypes();
// Special Handling of Undo / Redo Events.
protected abstract void OnUndoRedo();
}
} | 0 | 0.935098 | 1 | 0.935098 | game-dev | MEDIA | 0.602118 | game-dev | 0.540132 | 1 | 0.540132 |
cloudhu/ChineseChessVR | 12,195 | Assets/VRTK/Editor/VRTK_SDKManagerEditor.cs | namespace VRTK
{
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System;
using System.Linq;
[CustomEditor(typeof(VRTK_SDKManager))]
public class VRTK_SDKManagerEditor : Editor
{
private SDK_BaseHeadset previousHeadsetSDK;
private SDK_BaseController previousControllerSDK;
private SDK_BaseBoundaries previousBoundariesSDK;
private VRTK_SDKManager.SupportedSDKs quicklySelectedSDK = VRTK_SDKManager.SupportedSDKs.None;
public override void OnInspectorGUI()
{
serializedObject.Update();
//Get actual inspector
VRTK_SDKManager sdkManager = (VRTK_SDKManager)target;
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.PropertyField(serializedObject.FindProperty("persistOnLoad"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("autoManageScriptDefines"));
sdkManager.systemSDK = (VRTK_SDKManager.SupportedSDKs)EditorGUILayout.EnumPopup(VRTK_EditorUtilities.BuildGUIContent<VRTK_SDKManager>("systemSDK"), sdkManager.systemSDK);
sdkManager.boundariesSDK = (VRTK_SDKManager.SupportedSDKs)EditorGUILayout.EnumPopup(VRTK_EditorUtilities.BuildGUIContent<VRTK_SDKManager>("boundariesSDK"), sdkManager.boundariesSDK);
sdkManager.headsetSDK = (VRTK_SDKManager.SupportedSDKs)EditorGUILayout.EnumPopup(VRTK_EditorUtilities.BuildGUIContent<VRTK_SDKManager>("headsetSDK"), sdkManager.headsetSDK);
sdkManager.controllerSDK = (VRTK_SDKManager.SupportedSDKs)EditorGUILayout.EnumPopup(VRTK_EditorUtilities.BuildGUIContent<VRTK_SDKManager>("controllerSDK"), sdkManager.controllerSDK);
EditorGUILayout.Space();
quicklySelectedSDK = (VRTK_SDKManager.SupportedSDKs)EditorGUILayout.EnumPopup(new GUIContent("Quick select SDK", "Quickly select one of the SDKs into all slots."), quicklySelectedSDK);
if (quicklySelectedSDK != VRTK_SDKManager.SupportedSDKs.None)
{
QuickSelectSDK(quicklySelectedSDK);
quicklySelectedSDK = VRTK_SDKManager.SupportedSDKs.None;
}
CheckSDKUsage(sdkManager);
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.PropertyField(serializedObject.FindProperty("actualBoundaries"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("actualHeadset"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("actualLeftController"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("actualRightController"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("modelAliasLeftController"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("modelAliasRightController"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("scriptAliasLeftController"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("scriptAliasRightController"));
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.Space();
if (GUILayout.Button("Auto Populate Linked Objects"))
{
AutoPopulate(sdkManager);
}
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
serializedObject.ApplyModifiedProperties();
}
private void QuickSelectSDK(VRTK_SDKManager.SupportedSDKs sdk)
{
VRTK_SDKManager sdkManager = (VRTK_SDKManager)target;
sdkManager.systemSDK = sdk;
sdkManager.boundariesSDK = sdk;
sdkManager.headsetSDK = sdk;
sdkManager.controllerSDK = sdk;
}
private SDK_BaseHeadset GetHeadsetSDK(VRTK_SDKManager sdkManager)
{
return sdkManager.GetHeadsetSDK();
}
private SDK_BaseController GetControllerSDK(VRTK_SDKManager sdkManager)
{
return sdkManager.GetControllerSDK();
}
private SDK_BaseBoundaries GetBoundariesSDK(VRTK_SDKManager sdkManager)
{
return sdkManager.GetBoundariesSDK();
}
private void AutoPopulate(VRTK_SDKManager sdkManager)
{
var boundariesSDK = GetBoundariesSDK(sdkManager);
var headsetSDK = GetHeadsetSDK(sdkManager);
var controllerSDK = GetControllerSDK(sdkManager);
var forceSaveScene = false;
if (boundariesSDK && (!sdkManager.actualBoundaries || !previousBoundariesSDK || boundariesSDK.GetType() != previousBoundariesSDK.GetType()))
{
var playareaTransform = boundariesSDK.GetPlayArea();
sdkManager.actualBoundaries = (playareaTransform ? playareaTransform.gameObject : null);
previousBoundariesSDK = boundariesSDK;
forceSaveScene = true;
}
if (headsetSDK && (!sdkManager.actualHeadset || !previousHeadsetSDK || headsetSDK.GetType() != previousHeadsetSDK.GetType()))
{
var headsetTransform = headsetSDK.GetHeadset();
sdkManager.actualHeadset = (headsetTransform ? headsetTransform.gameObject : null);
previousHeadsetSDK = headsetSDK;
forceSaveScene = true;
}
var setPreviousControllerSDK = false;
if (controllerSDK && (!sdkManager.actualLeftController || !previousControllerSDK || controllerSDK.GetType() != previousControllerSDK.GetType()))
{
var controllerLeft = controllerSDK.GetControllerLeftHand(true);
sdkManager.actualLeftController = (controllerLeft ? controllerLeft : null);
setPreviousControllerSDK = true;
}
if (controllerSDK && (!sdkManager.actualRightController || !previousControllerSDK || controllerSDK.GetType() != previousControllerSDK.GetType()))
{
var controllerRight = controllerSDK.GetControllerRightHand(true);
sdkManager.actualRightController = (controllerRight ? controllerRight : null);
setPreviousControllerSDK = true;
}
if (controllerSDK && (!sdkManager.modelAliasLeftController || !previousControllerSDK || controllerSDK.GetType() != previousControllerSDK.GetType()))
{
var controllerLeft = controllerSDK.GetControllerModel(SDK_BaseController.ControllerHand.Left);
sdkManager.modelAliasLeftController = (controllerLeft ? controllerLeft : null);
setPreviousControllerSDK = true;
}
if (controllerSDK && (!sdkManager.modelAliasRightController || !previousControllerSDK || controllerSDK.GetType() != previousControllerSDK.GetType()))
{
var controllerRight = controllerSDK.GetControllerModel(SDK_BaseController.ControllerHand.Right);
sdkManager.modelAliasRightController = (controllerRight ? controllerRight : null);
setPreviousControllerSDK = true;
}
if (setPreviousControllerSDK)
{
previousControllerSDK = controllerSDK;
forceSaveScene = true;
}
if (forceSaveScene)
{
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEngine.SceneManagement.SceneManager.GetActiveScene());
}
}
private void CheckSDKUsage(VRTK_SDKManager sdkManager)
{
ProcessSDK(sdkManager, VRTK_SDKManager.SupportedSDKs.SteamVR);
ProcessSDK(sdkManager, VRTK_SDKManager.SupportedSDKs.OculusVR);
ProcessSDK(sdkManager, VRTK_SDKManager.SupportedSDKs.Simulator);
}
private void ProcessSDK(VRTK_SDKManager sdkManager, VRTK_SDKManager.SupportedSDKs supportedSDK)
{
var system = sdkManager.systemSDK;
var headset = sdkManager.headsetSDK;
var controller = sdkManager.controllerSDK;
var boundaries = sdkManager.boundariesSDK;
var sdkDetails = sdkManager.sdkDetails[supportedSDK];
var defineSymbol = sdkDetails.defineSymbol;
var prettyName = sdkDetails.prettyName;
var checkType = sdkDetails.checkType;
var message = "SDK has been selected but is not currently installed.";
if ((!CheckSDKInstalled(prettyName + message, checkType, false) || (system != supportedSDK && headset != supportedSDK && controller != supportedSDK && boundaries != supportedSDK)) && sdkManager.autoManageScriptDefines)
{
RemoveScriptingDefineSymbol(defineSymbol);
}
if (system == supportedSDK || headset == supportedSDK || controller == supportedSDK || boundaries == supportedSDK)
{
if (CheckSDKInstalled(prettyName + message, checkType, true) && sdkManager.autoManageScriptDefines)
{
AddScriptingDefineSymbol(defineSymbol);
}
}
if (sdkManager.autoManageScriptDefines)
{
CheckAvatarSupport(supportedSDK);
}
}
private void CheckAvatarSupport(VRTK_SDKManager.SupportedSDKs sdk)
{
switch (sdk)
{
case VRTK_SDKManager.SupportedSDKs.OculusVR:
var defineSymbol = "VRTK_SDK_OCULUSVR_AVATAR";
if (TypeExists("OvrAvatar"))
{
AddScriptingDefineSymbol(defineSymbol);
}
else
{
RemoveScriptingDefineSymbol(defineSymbol);
}
break;
}
}
private bool CheckSDKInstalled(string message, string checkType, bool showMessage)
{
if (!TypeExists(checkType))
{
if (showMessage)
{
EditorGUILayout.HelpBox(message, MessageType.Warning);
}
return false;
}
return true;
}
private void AddScriptingDefineSymbol(string define)
{
if (define == "")
{
return;
}
string scriptingDefineSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone);
List<string> definesList = new List<string>(scriptingDefineSymbols.Split(';'));
if (!definesList.Contains(define))
{
definesList.Add(define);
Debug.Log("Scripting Define Symbol Added To [Project Settings->Player]: " + define);
}
PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone, string.Join(";", definesList.ToArray()));
}
private void RemoveScriptingDefineSymbol(string define)
{
if (define == "")
{
return;
}
string scriptingDefineSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone);
List<string> definesList = new List<string>(scriptingDefineSymbols.Split(';'));
if (definesList.Contains(define))
{
definesList.Remove(define);
Debug.Log("Scripting Define Symbol Removed from [Project Settings->Player]: " + define);
}
PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone, string.Join(";", definesList.ToArray()));
}
private bool TypeExists(string className)
{
var foundType = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.Name == className
select type).FirstOrDefault();
return foundType != null;
}
}
} | 0 | 0.88958 | 1 | 0.88958 | game-dev | MEDIA | 0.238474 | game-dev | 0.812853 | 1 | 0.812853 |
Cirrus-Minor/witchblast | 3,400 | src/RockMissileEntity.cpp | #include "RockMissileEntity.h"
#include "PlayerEntity.h"
#include "sfml_game/SpriteEntity.h"
#include "sfml_game/ImageManager.h"
#include "sfml_game/SoundManager.h"
#include "Constants.h"
#include "WitchBlastGame.h"
RockMissileEntity::RockMissileEntity(float x, float y, int rockType)
: EnemyEntity (ImageManager::getInstance().getImage(IMAGE_CYCLOP), x, y)
{
Vector2D targetPos = game().getPlayerPosition();
imagesProLine = 20;
collisionDirection = -1;
enemyType = EnemyTypeRockMissile;
movingStyle = movFlying;
bloodColor = BloodNone; // stones don't bleed
hasCollided = false;
age = 0.0f;
this->rockType = rockType;
if (rockType == 0)
{
creatureSpeed = 500.0f;
hp = 12;
meleeDamages = 5;
frame = 18;
}
else
{
creatureSpeed = 450.0f;
hp = 24;
meleeDamages = 8;
frame = 38;
}
setVelocity(Vector2D(x, y).vectorNearlyTo(targetPos, creatureSpeed, 0.4f));
canExplode = false;
if (y < TILE_HEIGHT) this->y = TILE_HEIGHT;
if (!testEntityInMap()) isDying = true;
resistance[ResistancePoison] = ResistanceImmune;
}
void RockMissileEntity::animate(float delay)
{
EnemyEntity::animate(delay);
if (x < -60 || x > 1050 || y < - 50 || y > 800) isDying = true;
}
void RockMissileEntity::calculateBB()
{
int w;
if (rockType == 0) w = 20;
else w = 24;
boundingBox.left = (int)x - w / 2;
boundingBox.width = w;
boundingBox.top = (int)y - w / 2;
boundingBox.height = w;
}
void RockMissileEntity::collideWall()
{
if (rockType == 1 && !hasCollided)
{
hasCollided = true;
if (collisionDirection == DIRECTION_RIGHT || collisionDirection == DIRECTION_LEFT) velocity.x = -velocity.x;
else velocity.y = -velocity.y;
}
else
{
dying();
}
}
void RockMissileEntity::collideMapRight()
{
collisionDirection = DIRECTION_RIGHT;
collideWall();
}
void RockMissileEntity::collideMapLeft()
{
collisionDirection = DIRECTION_LEFT;
collideWall();
}
void RockMissileEntity::collideMapTop()
{
collisionDirection = DIRECTION_TOP;
collideWall();
}
void RockMissileEntity::collideMapBottom()
{
collisionDirection = DIRECTION_BOTTOM;
collideWall();
}
void RockMissileEntity::collideWithEnemy(EnemyEntity* entity)
{
}
void RockMissileEntity::dying()
{
isDying = true;
game().addKilledEnemy(enemyType, hurtingType);
SoundManager::getInstance().playSound(
rockType == 0 ? SOUND_ROCK_IMPACT_LIGHT : SOUND_ROCK_IMPACT_MEDIUM);
game().makeShake(0.1f);
for (int i = 0; i < 4; i++)
{
displayEntityStruct& de = game().getCurrentMapEntity()->generateBlood(x, y, BloodRock);
if ((collisionDirection == DIRECTION_LEFT) && (de.velocity.x < 0.0f))
de.velocity.x *= -0.25f;
else if ((collisionDirection == DIRECTION_RIGHT) && (de.velocity.x > 0.0f))
de.velocity.x *= -0.25f;
else if ((collisionDirection == DIRECTION_TOP) && (de.velocity.y < 0.0f))
de.velocity.y *= -0.25f;
else if ((collisionDirection == DIRECTION_BOTTOM) && (de.velocity.y > 0.0f))
de.velocity.y *= -0.25f;
}
}
void RockMissileEntity::inflictsRepulsionTo(BaseCreatureEntity* targetEntity)
{
PlayerEntity* playerEntity = dynamic_cast<PlayerEntity*>(targetEntity);
if (playerEntity != NULL && !playerEntity->isDead())
{
Vector2D repulsionVector = Vector2D(0, 0).vectorTo(getVelocity(), 600.0f );
targetEntity->giveRepulsion(true, repulsionVector, 0.5f);
}
}
| 0 | 0.956553 | 1 | 0.956553 | game-dev | MEDIA | 0.990597 | game-dev | 0.986325 | 1 | 0.986325 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.