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
PacktPublishing/Mastering-Cpp-Game-Development
2,045
Chapter05/Include/bullet/BulletInverseDynamics/IDConfig.hpp
///@file Configuration for Inverse Dynamics Library, /// such as choice of linear algebra library and underlying scalar type #ifndef IDCONFIG_HPP_ #define IDCONFIG_HPP_ // If we have a custom configuration, compile without using other parts of bullet. #ifdef BT_CUSTOM_INVERSE_DYNAMICS_CONFIG_H #define BT_ID_WO_BULLET #define BT_ID_POW(a,b) std::pow(a,b) #define BT_ID_SNPRINTF snprintf #define BT_ID_PI M_PI #define BT_ID_USE_DOUBLE_PRECISION #else #define BT_ID_POW(a,b) btPow(a,b) #define BT_ID_PI SIMD_PI #ifdef _WIN32 #define BT_ID_SNPRINTF _snprintf #else #define BT_ID_SNPRINTF snprintf #endif // #endif // error messages #include "IDErrorMessages.hpp" #ifdef BT_CUSTOM_INVERSE_DYNAMICS_CONFIG_H #define INVDYN_INCLUDE_HELPER_2(x) #x #define INVDYN_INCLUDE_HELPER(x) INVDYN_INCLUDE_HELPER_2(x) #include INVDYN_INCLUDE_HELPER(BT_CUSTOM_INVERSE_DYNAMICS_CONFIG_H) #ifndef btInverseDynamics #error "custom inverse dynamics config, but no custom namespace defined" #endif #define BT_ID_MAX(a,b) std::max(a,b) #define BT_ID_MIN(a,b) std::min(a,b) #else #define btInverseDynamics btInverseDynamicsBullet3 // Use default configuration with bullet's types // Use the same scalar type as rest of bullet library #include "LinearMath/btScalar.h" typedef btScalar idScalar; #include "LinearMath/btMinMax.h" #define BT_ID_MAX(a,b) btMax(a,b) #define BT_ID_MIN(a,b) btMin(a,b) #ifdef BT_USE_DOUBLE_PRECISION #define BT_ID_USE_DOUBLE_PRECISION #endif // use bullet types for arrays and array indices #include "Bullet3Common/b3AlignedObjectArray.h" // this is to make it work with C++2003, otherwise we could do this: // template <typename T> // using idArray = b3AlignedObjectArray<T>; template <typename T> struct idArray { typedef b3AlignedObjectArray<T> type; }; typedef int idArrayIdx; #define ID_DECLARE_ALIGNED_ALLOCATOR B3_DECLARE_ALIGNED_ALLOCATOR // use bullet's allocator functions #define idMalloc btAllocFunc #define idFree btFreeFunc #define ID_LINEAR_MATH_USE_BULLET #include "details/IDLinearMathInterface.hpp" #endif #endif
0
0.905281
1
0.905281
game-dev
MEDIA
0.292238
game-dev
0.551902
1
0.551902
chocoteam/choco-solver
15,229
solver/src/main/java/org/chocosolver/solver/constraints/nary/binPacking/PropBinPacking.java
/* * This file is part of choco-solver, http://choco-solver.org/ * * Copyright (c) 2025, IMT Atlantique. All rights reserved. * * Licensed under the BSD 4-clause license. * * See LICENSE file in the project root for full license information. */ package org.chocosolver.solver.constraints.nary.binPacking; import org.chocosolver.memory.IStateInt; import org.chocosolver.solver.constraints.Propagator; import org.chocosolver.solver.constraints.PropagatorPriority; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.solver.variables.IntVar; import org.chocosolver.solver.variables.delta.IIntDeltaMonitor; import org.chocosolver.solver.variables.events.IntEventType; import org.chocosolver.solver.variables.events.PropagatorEventType; import org.chocosolver.util.ESat; import org.chocosolver.util.objects.setDataStructures.ISet; import org.chocosolver.util.objects.setDataStructures.ISetIterator; import org.chocosolver.util.objects.setDataStructures.SetFactory; import org.chocosolver.util.objects.setDataStructures.SetType; import org.chocosolver.util.procedure.UnaryIntProcedure; import org.chocosolver.util.tools.ArrayUtils; import java.util.BitSet; import java.util.Comparator; import java.util.stream.IntStream; /** * Propagator for a Bin Packing constraint * This propagator is an implementation of filtering rules introduced in the following paper : * Shaw, P. (2004). A Constraint for Bin Packing. In M. Wallace (Ed.), Principles and Practice of Constraint Programming – CP 2004 (pp. 648–662). Springer Berlin Heidelberg. * * @author Arthur Godet <arth.godet@gmail.com>, Jean-Guillaume Fages */ public class PropBinPacking extends Propagator<IntVar> { private final IntVar[] itemBin; protected int[] itemSize; protected IntVar[] binLoad; protected final int offset; private final int nbItems; private final int nbAvailableBins; protected IIntDeltaMonitor[] monitors; protected ISet[] P; protected ISet[] R; protected IStateInt[] sumR; private final IStateInt[] sumP; private final BitSet binsToProcess; // NoSum parameters and Java variables private final boolean useNoSumFiltering; private int sumA; private int sumB; private int sumC; private int k; private int kPrime; private final int[] indexSortedBySize; private final int[] X; private int xSize; @SuppressWarnings("Convert2Diamond") private final UnaryIntProcedure<Integer> procedure = new UnaryIntProcedure<Integer>() { int item; @Override public UnaryIntProcedure<Integer> set(Integer itemIdx) { item = itemIdx; return this; } @Override public void execute(int bin) throws ContradictionException { bin -= offset; if (bin >= 0 && bin < nbAvailableBins && P[bin].contains(item)) { P[bin].remove(item); binLoad[bin].updateUpperBound(sumP[bin].add(-itemSize[item]), PropBinPacking.this); } } }; /** * Propagator for a Bin Packing constraint * * @param itemBin bin of every item (possibly with offset) * @param itemSize size of every item * @param binLoad total load of every bin * @param offset index offset: binOfItem[i] = k means item i is in bin k-offset */ public PropBinPacking(IntVar[] itemBin, int[] itemSize, IntVar[] binLoad, int offset) { this(itemBin, itemSize, binLoad, offset, true); } /** * Propagator for a Bin Packing constraint * * @param itemBin bin of every item (possibly with offset) * @param itemSize size of every item * @param binLoad total load of every bin * @param offset index offset: binOfItem[i] = k means item i is in bin k-offset * @param useNoSumFiltering indicates whether to use NoSum filterings or not (should be true) */ public PropBinPacking(IntVar[] itemBin, int[] itemSize, IntVar[] binLoad, int offset, boolean useNoSumFiltering) { super(ArrayUtils.append(itemBin, binLoad), PropagatorPriority.LINEAR, true); this.itemBin = itemBin; this.itemSize = itemSize; this.binLoad = binLoad; this.offset = offset; this.useNoSumFiltering = useNoSumFiltering; nbItems = itemBin.length; nbAvailableBins = binLoad.length; monitors = new IIntDeltaMonitor[nbItems]; for(int i=0; i<nbItems; i++){ monitors[i] = itemBin[i].monitorDelta(this); } P = new ISet[nbAvailableBins]; R = new ISet[nbAvailableBins]; sumR = new IStateInt[nbAvailableBins]; sumP = new IStateInt[nbAvailableBins]; for(int j = 0; j<nbAvailableBins; j++) { P[j] = SetFactory.makeStoredSet(SetType.BITSET, 0, itemBin[0].getModel()); R[j] = SetFactory.makeStoredSet(SetType.BITSET, 0, itemBin[0].getModel()); sumR[j] = itemBin[0].getModel().getEnvironment().makeInt(0); sumP[j] = itemBin[0].getModel().getEnvironment().makeInt(0); } binsToProcess = new BitSet(nbAvailableBins); // NoSum init X = new int[itemSize.length]; indexSortedBySize = IntStream.range(0, itemSize.length) .boxed() .sorted(Comparator.comparingInt(i -> -itemSize[i])) .mapToInt(i -> i) .toArray(); } @Override public int getPropagationConditions(int vIdx) { if(vIdx < nbItems) { return IntEventType.all(); } else { return IntEventType.boundAndInst(); } } //////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////// FILTERING ALGORITHMS ////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// private void removeItemFromBin(int binIdx, int itemIdx) throws ContradictionException { if(P[binIdx].contains(itemIdx)) { P[binIdx].remove(itemIdx); binLoad[binIdx].updateUpperBound(sumP[binIdx].add(-itemSize[itemIdx]), this); binsToProcess.set(binIdx); if(itemBin[itemIdx].isInstantiated()) { updateRAfterInstantiation(itemBin[itemIdx].getValue() - offset, itemIdx); } } } protected void updateRAfterInstantiation(int binIdx, int itemIdx) throws ContradictionException { if(R[binIdx].add(itemIdx)) { binLoad[binIdx].updateLowerBound(sumR[binIdx].add(itemSize[itemIdx]), this); binsToProcess.set(binIdx); for(int k = 0; k<nbAvailableBins; k++) { if(k != binIdx && P[k].remove(itemIdx)) { binLoad[k].updateUpperBound(sumP[k].add(-itemSize[itemIdx]), this); binsToProcess.set(k); } } } } private boolean singleItemEliminationAndCommitment(int j) throws ContradictionException { boolean hasFiltered = false; ISetIterator iter = P[j].iterator(); while(iter.hasNext()) { int i = iter.nextInt(); if(!itemBin[i].contains(j + offset)) { removeItemFromBin(j, i); } else if(!R[j].contains(i)) { if(sumP[j].get() - itemSize[i] < binLoad[j].getLB()) { hasFiltered |= itemBin[i].instantiateTo(j+offset, this); updateRAfterInstantiation(j, i); } else { if(sumR[j].get() + itemSize[i] > binLoad[j].getUB() && itemBin[i].removeValue(j+offset, this)) { hasFiltered = true; removeItemFromBin(j, i); } } } } return hasFiltered; } private void processBin(int j) throws ContradictionException { binsToProcess.clear(j); boolean hasFiltered; do { hasFiltered = singleItemEliminationAndCommitment(j); if(useNoSumFiltering) { hasFiltered |= noSumFiltering(j); } } while(hasFiltered); } //////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////// NO_SUM METHODS ///////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// private void fillXArrayWithCj(int j, int idxToRemove) { xSize = 0; for(int i = 0; i < nbItems; i++) { if(indexSortedBySize[i] != idxToRemove && P[j].contains(indexSortedBySize[i]) && !R[j].contains(indexSortedBySize[i]) ) { X[xSize++] = indexSortedBySize[i]; } } } private void noSumInit() { sumA = 0; sumB = 0; sumC = 0; k = 0; kPrime = 0; } private boolean noSumComputings(int alpha, int beta) { while(kPrime < xSize && sumC + itemSize[X[xSize-1-kPrime]] < alpha) { sumC += itemSize[X[xSize-1-kPrime]]; kPrime++; } if(kPrime < xSize) { sumB = itemSize[X[xSize-1-kPrime]]; } while(k<xSize && sumA < alpha && sumB <= beta) { sumA += itemSize[X[k]]; k++; if(sumA < alpha) { kPrime--; sumB += itemSize[X[xSize-1-kPrime]]; sumC -= itemSize[X[xSize-1-kPrime]]; while(sumA + sumC >= alpha) { kPrime--; sumC -= itemSize[X[xSize-1-kPrime]]; sumB += itemSize[X[xSize-1-kPrime]] - itemSize[X[xSize-1-kPrime-k-1]]; } } } return sumA < alpha; } private boolean noSum(int j, int alpha, int beta) { return noSum(j, alpha, beta, -1); } private boolean noSum(int j, int alpha, int beta, int idxToRemove) { if(alpha <= 0 || beta >= sumP[j].get()-sumR[j].get()) { return false; } noSumInit(); fillXArrayWithCj(j, idxToRemove); return noSumComputings(alpha, beta); } private boolean noSumFiltering(int j) throws ContradictionException { boolean hasFiltered = false; // Pruning Rule if(noSum(j, binLoad[j].getLB()-sumR[j].get(), binLoad[j].getUB()-sumR[j].get())) { fails(); } // Tightening Bounds on Bin Load int lbVal = binLoad[j].getLB()-sumR[j].get(); if(noSum(j, lbVal, lbVal)) { hasFiltered = true; binLoad[j].updateLowerBound(sumR[j].get() + sumB, this); } int ubVal = binLoad[j].getUB()-sumR[j].get(); if(noSum(j, ubVal, ubVal)) { binLoad[j].updateUpperBound(sumR[j].get() + sumA + sumC, this); } // Elimination and Commitment of Items ISetIterator iter = P[j].iterator(); while(iter.hasNext()) { int i = iter.nextInt(); if(!R[j].contains(i)) { int lbVal2 = binLoad[j].getLB()-sumR[j].get()-itemSize[i]; int ubVal2 = binLoad[j].getUB()-sumR[j].get()-itemSize[i]; if(noSum(j, lbVal2, ubVal2, i)) { if(itemBin[i].removeValue(j+offset, this)) { hasFiltered = true; removeItemFromBin(j, i); } } lbVal2 += itemSize[i]; ubVal2 += itemSize[i]; if(noSum(j, lbVal2, ubVal2, i)) { hasFiltered |= itemBin[i].instantiateTo(j+offset, this); updateRAfterInstantiation(j, i); } } } return hasFiltered; } //////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////// PROPAGATION /////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// @Override public void propagate(int idxVarInProp, int mask) throws ContradictionException { if(idxVarInProp < nbItems) { monitors[idxVarInProp].forEachRemVal(procedure.set(idxVarInProp)); if(itemBin[idxVarInProp].isInstantiated()) { int j = itemBin[idxVarInProp].getValue() - offset; updateRAfterInstantiation(j, idxVarInProp); binsToProcess.set(j); } } else { binsToProcess.set(idxVarInProp - nbItems); } forcePropagate(PropagatorEventType.CUSTOM_PROPAGATION); } private void initializeBinsDataStructure() { for(int j = 0; j<nbAvailableBins; j++) { R[j].clear(); P[j].clear(); sumR[j].set(0); int pj = 0; for (int i = 0; i < nbItems; i++) { if (itemBin[i].contains(j + offset)) { P[j].add(i); pj += itemSize[i]; } } sumP[j].set(pj); } } @Override public void propagate(int evtmask) throws ContradictionException { if(PropagatorEventType.isFullPropagation(evtmask)) { initializeBinsDataStructure(); for(int i = 0; i<itemBin.length; i++) { // Pack All itemBin[i].updateBounds(offset, nbAvailableBins+offset-1, this); if(itemBin[i].isInstantiated()) { int j = itemBin[i].getValue() - offset; updateRAfterInstantiation(j, i); } else { for(int j = 0; j<nbAvailableBins; j++) { if(!itemBin[i].contains(j + offset)) { removeItemFromBin(j, i); } } } } binsToProcess.set(0, nbAvailableBins); for(int i=0; i<nbItems; i++){ monitors[i].startMonitoring(); } } while(!binsToProcess.isEmpty()) { processBin(binsToProcess.nextSetBit(0)); } } @Override public ESat isEntailed() { for(int i=0; i<nbItems; i++){ if(itemBin[i].isInstantiated()){ int val = itemBin[i].getValue(); if(val<offset || val>=nbAvailableBins+offset){ return ESat.FALSE; } } } for(int b = 0; b<nbAvailableBins; b++) { int min = 0; int max = 0; for(int i = 0; i<nbItems; i++) { if(itemBin[i].contains(b+offset)) { max += itemSize[i]; if(itemBin[i].isInstantiated()) { min += itemSize[i]; } } } if( min > binLoad[b].getUB() || max < binLoad[b].getLB()) { return ESat.FALSE; } } if(isCompletelyInstantiated()) { return ESat.TRUE; } return ESat.UNDEFINED; } }
0
0.864739
1
0.864739
game-dev
MEDIA
0.256603
game-dev
0.991356
1
0.991356
glKarin/com.n0n3m4.diii4a
10,678
Q3E/src/main/jni/jk/codeJK2/game/g_object.cpp
/* =========================================================================== Copyright (C) 2000 - 2013, Raven Software, Inc. Copyright (C) 2001 - 2013, Activision, Inc. Copyright (C) 2013 - 2015, OpenJK contributors This file is part of the OpenJK source code. OpenJK is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. =========================================================================== */ #include "g_headers.h" #include "g_local.h" #include "g_functions.h" extern void G_MoverTouchPushTriggers( gentity_t *ent, vec3_t oldOrg ); void G_StopObjectMoving( gentity_t *object ); /* ================ G_BounceMissile ================ */ void G_BounceObject( gentity_t *ent, trace_t *trace ) { vec3_t velocity; float dot; int hitTime; // reflect the velocity on the trace plane hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction; EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity ); dot = DotProduct( velocity, trace->plane.normal ); float bounceFactor = 60/ent->mass; if ( bounceFactor > 1.0f ) { bounceFactor = 1.0f; } VectorMA( velocity, -2*dot*bounceFactor, trace->plane.normal, ent->s.pos.trDelta ); //FIXME: customized or material-based impact/bounce sounds if ( ent->s.eFlags & EF_BOUNCE_HALF ) { VectorScale( ent->s.pos.trDelta, 0.5, ent->s.pos.trDelta ); // check for stop if ( ((trace->plane.normal[2] > 0.7&&g_gravity->value>0) || (trace->plane.normal[2]<-0.7&&g_gravity->value<0)) && ((ent->s.pos.trDelta[2]<40&&g_gravity->value>0)||(ent->s.pos.trDelta[2]>-40&&g_gravity->value<0)) ) //this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 { //G_SetOrigin( ent, trace->endpos ); //ent->nextthink = level.time + 500; ent->s.apos.trType = TR_STATIONARY; VectorCopy( ent->currentAngles, ent->s.apos.trBase ); VectorCopy( trace->endpos, ent->currentOrigin ); VectorCopy( trace->endpos, ent->s.pos.trBase ); ent->s.pos.trTime = level.time; return; } } // NEW--It would seem that we want to set our trBase to the trace endpos // and set the trTime to the actual time of impact.... // FIXME: Should we still consider adding the normal though?? VectorCopy( trace->endpos, ent->currentOrigin ); ent->s.pos.trTime = hitTime; VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); VectorCopy( trace->plane.normal, ent->pos1 );//??? } /* ================ G_RunObject TODO: When transition to 0 grav, push away from surface you were resting on TODO: When free-floating in air, apply some friction to your trDelta (based on mass?) ================ */ extern void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf ); extern void pitch_roll_for_slope( gentity_t *forwhom, vec3_t pass_slope ); void G_RunObject( gentity_t *ent ) { vec3_t origin, oldOrg; trace_t tr; gentity_t *traceEnt = NULL; //FIXME: floaters need to stop floating up after a while, even if gravity stays negative? if ( ent->s.pos.trType == TR_STATIONARY )//g_gravity->value <= 0 && { ent->s.pos.trType = TR_GRAVITY; VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); ent->s.pos.trTime = level.previousTime;//?necc? if ( !g_gravity->value ) { ent->s.pos.trDelta[2] += 100; } } ent->nextthink = level.time + FRAMETIME; VectorCopy( ent->currentOrigin, oldOrg ); // get current position EvaluateTrajectory( &ent->s.pos, level.time, origin ); //Get current angles? EvaluateTrajectory( &ent->s.apos, level.time, ent->currentAngles ); if ( VectorCompare( ent->currentOrigin, origin ) ) {//error - didn't move at all! return; } // trace a line from the previous position to the current position, // ignoring interactions with the missile owner gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ent->owner ? ent->owner->s.number : ent->s.number, ent->clipmask, G2_NOCOLLIDE, 0 ); if ( !tr.startsolid && !tr.allsolid && tr.fraction ) { VectorCopy( tr.endpos, ent->currentOrigin ); gi.linkentity( ent ); } else //if ( tr.startsolid ) { tr.fraction = 0; } G_MoverTouchPushTriggers( ent, oldOrg ); /* if ( !(ent->s.eFlags & EF_TELEPORT_BIT) && !(ent->svFlags & SVF_NO_TELEPORT) ) { G_MoverTouchTeleportTriggers( ent, oldOrg ); if ( ent->s.eFlags & EF_TELEPORT_BIT ) {//was teleported return; } } else { ent->s.eFlags &= ~EF_TELEPORT_BIT; } */ if ( tr.fraction == 1 ) { if ( g_gravity->value <= 0 ) { if ( ent->s.apos.trType == TR_STATIONARY ) { VectorCopy( ent->currentAngles, ent->s.apos.trBase ); ent->s.apos.trType = TR_LINEAR; ent->s.apos.trDelta[1] = Q_flrand( -300, 300 ); ent->s.apos.trDelta[0] = Q_flrand( -10, 10 ); ent->s.apos.trDelta[2] = Q_flrand( -10, 10 ); ent->s.apos.trTime = level.time; } } //friction in zero-G if ( !g_gravity->value ) { float friction = 0.975f; /*friction -= ent->mass/1000.0f; if ( friction < 0.1 ) { friction = 0.1f; } */ VectorScale( ent->s.pos.trDelta, friction, ent->s.pos.trDelta ); VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); ent->s.pos.trTime = level.time; } return; } //hit something //Do impact damage traceEnt = &g_entities[tr.entityNum]; if ( tr.fraction || (traceEnt && traceEnt->takedamage) ) { if ( !VectorCompare( ent->currentOrigin, oldOrg ) ) {//moved and impacted if ( (traceEnt && traceEnt->takedamage) ) {//hurt someone G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectHurt.wav" ) ); } G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectHit.wav" ) ); } DoImpact( ent, traceEnt, (qboolean)(!(tr.surfaceFlags & SURF_NODAMAGE)) ); } if ( !ent || (ent->takedamage&&ent->health <= 0) ) {//been destroyed by impact //chunks? G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectBreak.wav" ) ); return; } //do impact physics if ( ent->s.pos.trType == TR_GRAVITY )//tr.fraction < 1.0 && {//FIXME: only do this if no trDelta if ( g_gravity->value <= 0 || tr.plane.normal[2] < 0.7 ) { if ( ent->s.eFlags&(EF_BOUNCE|EF_BOUNCE_HALF) ) { if ( tr.fraction <= 0.0f ) { VectorCopy( tr.endpos, ent->currentOrigin ); VectorCopy( tr.endpos, ent->s.pos.trBase ); VectorClear( ent->s.pos.trDelta ); ent->s.pos.trTime = level.time; } else { G_BounceObject( ent, &tr ); } } else {//slide down? //FIXME: slide off the slope } } else { ent->s.apos.trType = TR_STATIONARY; pitch_roll_for_slope( ent, tr.plane.normal ); //ent->currentAngles[0] = 0;//FIXME: match to slope //ent->currentAngles[2] = 0;//FIXME: match to slope VectorCopy( ent->currentAngles, ent->s.apos.trBase ); //okay, we hit the floor, might as well stop or prediction will //make us go through the floor! //FIXME: this means we can't fall if something is pulled out from under us... G_StopObjectMoving( ent ); } } else { ent->s.apos.trType = TR_STATIONARY; pitch_roll_for_slope( ent, tr.plane.normal ); //ent->currentAngles[0] = 0;//FIXME: match to slope //ent->currentAngles[2] = 0;//FIXME: match to slope VectorCopy( ent->currentAngles, ent->s.apos.trBase ); } //call touch func GEntity_TouchFunc( ent, &g_entities[tr.entityNum], &tr ); } void G_StopObjectMoving( gentity_t *object ) { object->s.pos.trType = TR_STATIONARY; VectorCopy( object->currentOrigin, object->s.origin ); VectorCopy( object->currentOrigin, object->s.pos.trBase ); VectorClear( object->s.pos.trDelta ); /* //Stop spinning VectorClear( self->s.apos.trDelta ); vectoangles(trace->plane.normal, self->s.angles); VectorCopy(self->s.angles, self->currentAngles ); VectorCopy(self->s.angles, self->s.apos.trBase); */ } void G_StartObjectMoving( gentity_t *object, vec3_t dir, float speed, trType_t trType ) { VectorNormalize (dir); //object->s.eType = ET_GENERAL; object->s.pos.trType = trType; VectorCopy( object->currentOrigin, object->s.pos.trBase ); VectorScale(dir, speed, object->s.pos.trDelta ); object->s.pos.trTime = level.time; /* //FIXME: incorporate spin? vectoangles(dir, object->s.angles); VectorCopy(object->s.angles, object->s.apos.trBase); VectorSet(object->s.apos.trDelta, 300, 0, 0 ); object->s.apos.trTime = level.time; */ //FIXME: make these objects go through G_RunObject automatically, like missiles do if ( object->e_ThinkFunc == thinkF_NULL ) { object->nextthink = level.time + FRAMETIME; object->e_ThinkFunc = thinkF_G_RunObject; } else {//You're responsible for calling RunObject } } gentity_t *G_CreateObject ( gentity_t *owner, vec3_t origin, vec3_t angles, int modelIndex, int frame, trType_t trType ) { gentity_t *object; object = G_Spawn(); if ( object == NULL ) { return NULL; } object->classname = "object";//? object->nextthink = level.time + FRAMETIME; object->e_ThinkFunc = thinkF_G_RunObject; object->s.eType = ET_GENERAL; object->s.eFlags |= EF_AUTO_SIZE;//CG_Ents will create the mins & max itself based on model bounds object->s.modelindex = modelIndex; //FIXME: allow to set a targetname/script_targetname and animation info? object->s.frame = object->startFrame = object->endFrame = frame; object->owner = owner; //object->damage = 100; //object->splashDamage = 200; //object->splashRadius = 200; //object->methodOfDeath = MOD_EXPLOSIVE; //object->splashMethodOfDeath = MOD_EXPLOSIVE_SPLASH; object->clipmask = MASK_SOLID;//? //object->e_TouchFunc = touchF_charge_stick; //Give it SOME size for now VectorSet( object->mins, -4, -4, -4 ); VectorSet( object->maxs, 4, 4, 4 ); //Origin G_SetOrigin( object, origin ); object->s.pos.trType = trType; VectorCopy( origin, object->s.pos.trBase ); //Velocity VectorClear( object->s.pos.trDelta ); object->s.pos.trTime = level.time; //VectorScale( dir, 300, object->s.pos.trDelta ); //object->s.pos.trTime = level.time; //Angles VectorCopy( angles, object->s.angles ); VectorCopy( object->s.angles, object->s.apos.trBase ); //Angular Velocity VectorClear( object->s.apos.trDelta ); object->s.apos.trTime = level.time; //VectorSet( object->s.apos.trDelta, 300, 0, 0 ); //object->s.apos.trTime = level.time; gi.linkentity( object ); return object; }
0
0.563668
1
0.563668
game-dev
MEDIA
0.917698
game-dev
0.958086
1
0.958086
Roirtur/EmpireOfLionel
1,176
eol/src/main/java/eol/jfx/buildings/BuildingFactory.java
package eol.jfx.buildings; public class BuildingFactory { private static BuildingFactory instance; private BuildingFactory() { // private constructor to prevent instantiation } public static BuildingFactory getInstance() { if (instance == null) { instance = new BuildingFactory(); } return instance; } public static Building createBuilding(BuildingType type, int x, int y) { switch (type) { case APARTMENT: return new Apartment(x, y); case CEMENTPLANT: return new CementPlant(x, y); case FARM: return new Farm(x, y); case HOUSE: return new House(x, y); case LUMBERMILL: return new LumberMill(x, y); case QUARY: return new Quary(x, y); case STEELMILL: return new SteelMill(x, y); case TOOLFACTORY: return new ToolFactory(x, y); case WOODENCABIN: return new WoodenCabin(x, y); default: return null; } } }
0
0.598872
1
0.598872
game-dev
MEDIA
0.484462
game-dev
0.684129
1
0.684129
magmafoundation/Magma-Neo
1,413
patches/net/minecraft/nbt/CompoundTag.java.patch
--- a/net/minecraft/nbt/CompoundTag.java +++ b/net/minecraft/nbt/CompoundTag.java @@ -46,13 +_,19 @@ return compoundtag; } + private static byte readNamedTagType(DataInput p_302338_, NbtAccounter p_302362_) throws IOException { + p_302362_.accountBytes(2); + return p_302338_.readByte(); + } + private static CompoundTag loadCompound(DataInput p_302338_, NbtAccounter p_302362_) throws IOException { p_302362_.accountBytes(48L); Map<String, Tag> map = Maps.newHashMap(); byte b0; - while ((b0 = p_302338_.readByte()) != 0) { - String s = readString(p_302338_, p_302362_); + while((b0 = readNamedTagType(p_302338_, p_302362_)) != 0) { + String s = p_302362_.readUTF(p_302338_.readUTF()); + p_302362_.accountBytes(4); //Forge: 4 extra bytes for the object allocation. Tag tag = CompoundTag.readNamedTagData(TagTypes.getType(b0), s, p_302338_, p_302362_); if (map.put(s, tag) == null) { p_302362_.accountBytes(36L); @@ -211,6 +_,7 @@ @Nullable public Tag put(String p_128366_, Tag p_128367_) { + if (p_128367_ == null) throw new IllegalArgumentException("Invalid null NBT value with key " + p_128366_); return this.tags.put(p_128366_, p_128367_); }
0
0.674682
1
0.674682
game-dev
MEDIA
0.935135
game-dev
0.613278
1
0.613278
anael-seghezzi/Maratis-4
1,653
3rdparty/bullet/BulletCollision/CollisionDispatch/btCollisionConfiguration.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_COLLISION_CONFIGURATION #define BT_COLLISION_CONFIGURATION struct btCollisionAlgorithmCreateFunc; class btPoolAllocator; ///btCollisionConfiguration allows to configure Bullet collision detection ///stack allocator size, default collision algorithms and persistent manifold pool size ///@todo: describe the meaning class btCollisionConfiguration { public: virtual ~btCollisionConfiguration() { } ///memory pools virtual btPoolAllocator* getPersistentManifoldPool() = 0; virtual btPoolAllocator* getCollisionAlgorithmPool() = 0; virtual btCollisionAlgorithmCreateFunc* getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1) =0; }; #endif //BT_COLLISION_CONFIGURATION
0
0.758916
1
0.758916
game-dev
MEDIA
0.997821
game-dev
0.547107
1
0.547107
OvercastNetwork/ProjectAres
12,803
PGM/src/main/java/tc/oc/pgm/spawns/SpawnMatchModule.java
package tc.oc.pgm.spawns; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.logging.Level; import javax.annotation.Nullable; import javax.inject.Inject; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import org.bukkit.entity.Entity; import org.bukkit.event.EventException; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerInitialSpawnEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.jdom2.Element; import tc.oc.commons.bukkit.event.CoarsePlayerMoveEvent; import tc.oc.commons.core.random.RandomUtils; import tc.oc.commons.core.util.ThrowingConsumer; import tc.oc.pgm.events.CompetitorRemoveEvent; import tc.oc.pgm.events.ListenerScope; import tc.oc.pgm.events.MatchBeginEvent; import tc.oc.pgm.events.MatchEndEvent; import tc.oc.pgm.events.MatchPlayerDeathEvent; import tc.oc.pgm.events.ObserverInteractEvent; import tc.oc.pgm.events.PlayerChangePartyEvent; import tc.oc.pgm.filters.Filter; import tc.oc.pgm.filters.query.IQuery; import tc.oc.pgm.kits.Kit; import tc.oc.pgm.match.Competitor; import tc.oc.pgm.match.Match; import tc.oc.pgm.match.MatchModule; import tc.oc.pgm.match.MatchPlayer; import tc.oc.pgm.match.MatchScope; import tc.oc.pgm.match.Repeatable; import tc.oc.pgm.spawns.states.Joining; import tc.oc.pgm.spawns.states.Observing; import tc.oc.pgm.spawns.states.State; import tc.oc.pgm.xml.InvalidXMLException; import static tc.oc.commons.core.exception.LambdaExceptionUtils.rethrowConsumer; import static tc.oc.commons.core.util.MapUtils.ifPresent; @ListenerScope(MatchScope.LOADED) public class SpawnMatchModule extends MatchModule implements Listener { private final SpawnModule module; private final Map<MatchPlayer, State> states = new HashMap<>(); private final ListMultimap<MatchPlayer, State> transitions = ArrayListMultimap.create(); private final Set<MatchPlayer> processing = new HashSet<>(); private final Map<Competitor, Spawn> uniqueSpawns = new HashMap<>(); private final Set<Spawn> failedSpawns = new HashSet<>(); @Inject private ObserverToolFactory observerToolFactory; public SpawnMatchModule(Match match, SpawnModule module) { super(match); this.module = module; } public RespawnOptions getRespawnOptions(IQuery query) { return module.respawnOptions.stream().filter(respawnOption -> respawnOption.filter.query(query).equals(Filter.QueryResponse.ALLOW)) .findFirst().orElseThrow(() -> new IllegalStateException("No respawn option could be used")); } public Spawn getDefaultSpawn() { return module.defaultSpawn; } public List<Spawn> getSpawns() { return module.spawns; } public List<Kit> getPlayerKits() { return module.playerKits; } public ObserverToolFactory getObserverToolFactory() { return observerToolFactory; } /** * Return all {@link Spawn}s that the given player is currently allowed to spawn at */ public List<Spawn> getSpawns(MatchPlayer player) { List<Spawn> result = Lists.newArrayList(); for(Spawn spawn : this.getSpawns()) { if(spawn.allows(player)) { result.add(spawn); } } return result; } /** * Return a randomly chosen {@link Spawn} that the given player is currently allowed * to spawn at, or null if none are available. If a team is given, assume the player * will have switched to that team by the time they spawn. */ public @Nullable Spawn chooseSpawn(MatchPlayer player) { Competitor competitor = player.getCompetitor(); if(player.isObserving()) { return getDefaultSpawn(); } else if(competitor != null && uniqueSpawns.containsKey(competitor)) { return uniqueSpawns.get(competitor); } else { List<Spawn> potential = getSpawns(player); potential.removeAll(uniqueSpawns.values()); if(!potential.isEmpty()) { Spawn spawn = RandomUtils.element(match.getRandom(), potential); if(spawn.attributes().exclusive) uniqueSpawns.put(competitor, spawn); return spawn; } else { return null; } } } @Repeatable(scope = MatchScope.LOADED) public void tick() { // Copy states so they can transition without concurrent modification ImmutableMap.copyOf(states).forEach((player, state) -> { state.tick(); processQueuedTransitions(player); }); } public void reportFailedSpawn(Spawn spawn, MatchPlayer player) { if(failedSpawns.add(spawn)) { Element elSpawn = getMatch().getModuleContext().features().definitionNode(spawn); InvalidXMLException ex = new InvalidXMLException("Failed to generate spawn location for " + player.getName(), elSpawn); getMatch().getMap().getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } private void leaveState(MatchPlayer player) { final State state = states.get(player); if(state != null) { logger.fine(player.getName() + " leave " + state); state.leaveState(); states.remove(player); } } private void enterState(MatchPlayer player, State state) { logger.fine(player.getName() + " enter " + state); states.put(player, state); state.enterState(); } private void changeState(MatchPlayer player, @Nullable State state) { leaveState(player); if(state != null) { enterState(player, state); } } private boolean hasQueuedTransitions(MatchPlayer player) { return transitions.containsKey(player); } private void processQueuedTransitions(MatchPlayer player) { // Prevent nested processing of the same player if(processing.add(player)) { try { final List<State> queue = transitions.get(player); while(!queue.isEmpty()) { changeState(player, queue.remove(0)); } } finally { processing.remove(player); } } } public void transition(MatchPlayer player, @Nullable State newState) { logger.fine(player.getName() + " queue " + newState); transitions.put(player, newState); } private <X extends Throwable> void withState(@Nullable MatchPlayer player, ThrowingConsumer<State, X> consumer) throws X { if(player == null) return; ifPresent(states, player, rethrowConsumer(consumer::acceptThrows)); } private void withState(@Nullable Entity bukkit, BiConsumer<MatchPlayer, State> consumer) { final MatchPlayer player = match.getPlayer(bukkit); withState(player, state -> consumer.accept(player, state)); } private void dispatchEvent(@Nullable MatchPlayer player, Consumer<State> consumer) { withState(player, state -> { consumer.accept(state); processQueuedTransitions(player); }); } private void dispatchEvent(@Nullable Entity bukkit, BiConsumer<MatchPlayer, State> consumer) { withState(bukkit, (player, state) -> { consumer.accept(player, state); processQueuedTransitions(player); }); } // Events delegated to States @EventHandler(priority = EventPriority.MONITOR) public void onPartyChange(final PlayerChangePartyEvent event) throws EventException { final MatchPlayer player = event.getPlayer(); if(event.getOldParty() == null) { // Join match event.yield(); if(event.getNewParty().isParticipating()) { enterState(player, new Joining(player)); } else { enterState(player, new Observing(player, true, true)); } } else if(event.getNewParty() == null) { // Leave match leaveState(player); } else { // Party change during match withState(player, state -> { state.onEvent(event); if(hasQueuedTransitions(player)) { // If the party change caused a state transition, leave the old // state before the change, and enter the new state afterward. // The potential danger here is that the player has no spawn state // during the party change, while other events are firing. The // danger is minimized by listening at MONITOR priority. leaveState(player); event.yield(); processQueuedTransitions(player); } }); } } /** Must run before {@link tc.oc.pgm.tracker.trackers.DeathTracker#onPlayerDeath} */ @EventHandler(priority = EventPriority.LOW) public void onVanillaDeath(final PlayerDeathEvent event) { dispatchEvent(event.getEntity(), (player, state) -> state.onEvent(event)); } @EventHandler(priority = EventPriority.HIGH) public void onDeath(final MatchPlayerDeathEvent event) { dispatchEvent(event.getVictim(), state -> state.onEvent(event)); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onInventoryClick(final InventoryClickEvent event) { dispatchEvent(event.getWhoClicked(), (player, state) -> state.onEvent(event)); } // Listen on HIGH so the picker can handle this first @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onObserverInteract(final ObserverInteractEvent event) { dispatchEvent(event.getPlayer(), state -> state.onEvent(event)); } @EventHandler public void matchBegin(final MatchBeginEvent event) { // Copy states so they can transition without concurrent modification ImmutableMap.copyOf(states).forEach((player, state) -> { state.onEvent(event); processQueuedTransitions(player); }); } @EventHandler public void matchEnd(final MatchEndEvent event) { // Copy states so they can transition without concurrent modification ImmutableMap.copyOf(states).forEach((player, state) -> { // This event can be fired from inside a party change, so some players may have no party if(player.hasParty()) { state.onEvent(event); processQueuedTransitions(player); } }); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void playerMove(final CoarsePlayerMoveEvent event) { dispatchEvent(event.getPlayer(), (player, state) -> state.onEvent(event)); } // Events handled for other reasons @EventHandler(priority = EventPriority.MONITOR) public void onInitialSpawn(final PlayerInitialSpawnEvent event) { // Make all joining players spawn in this match's world event.setSpawnLocation(match.getWorld().getSpawnLocation()); } @EventHandler(priority = EventPriority.LOW) public void playerJoin(final PlayerJoinEvent event) { // Add the player to the match if they spawn in this world if(match.getWorld().equals(event.getPlayer().getLocation().getWorld())) { event.getPlayer().setGliding(true); // Fixes client desync if player joins server while gliding match.addPlayer(event.getPlayer()); } } @EventHandler(priority = EventPriority.MONITOR) public void playerQuit(final PlayerQuitEvent event) { match.removePlayer(event.getPlayer()); } @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onCompetitorRemove(CompetitorRemoveEvent event) { // If a competitor is no longer valid, free up its provider Competitor competitor = event.getCompetitor(); if(uniqueSpawns.containsKey(competitor)) { Spawn spawn = uniqueSpawns.get(competitor); // Do not change if persistence is enabled if(!spawn.attributes().persistent) { uniqueSpawns.remove(competitor); } } } }
0
0.934414
1
0.934414
game-dev
MEDIA
0.806871
game-dev
0.955203
1
0.955203
danielah05/UndertaleDecomp
3,230
objects/obj_base_writer/Alarm_0.gml
if (stringpos >= string_length(originalstring)) return; var advance = 1 if (global.typer == 111) advance += 1 if (txtsound == snd_mtt1) advance += 2 else if (txtsound == snd_tem) advance += 1 var dosound = 0 var delay = textspeed while (stringpos < string_length(originalstring) && advance > 0) { stringpos++ var ch = string_char_at(originalstring, stringpos) if (ch == "^") { stringpos++ ch = string_char_at(originalstring, stringpos) // Daniela: fixes a cutscene softlock if (ch != "0" && ch != "") { var n = real(ch) delay = (n * 10) advance = 1 } } else if (ch == "\\") { stringpos++ ch = string_char_at(originalstring, stringpos) if (ch == "S") { stringpos++ var sfxtype = string_char_at(originalstring, stringpos) if (sfxtype == "+") sound_enable = snd_sparkle1 else if (sfxtype == "-") sound_enable = 0 else { var sfx = noone if (sfxtype == "p") sfx = snd_phone if (sfx != noone) snd_play(sfx) } } else if (ch == "z") { stringpos++ advance-- if sound_enable dosound = snd_sparkle1 } else if (ch == "E" || ch == "F" || ch == "M" || ch == "T" || ch == "*") stringpos++ } else if (ch != "/" && ch != "%" && ch != "&") { advance-- if sound_enable dosound = snd_sparkle1 } } alarm[0] = delay if dosound { if (txtsound == snd_mtt1) { snd_stop(snd_mtt1) snd_stop(snd_mtt2) snd_stop(snd_mtt3) snd_stop(snd_mtt4) snd_stop(snd_mtt5) snd_stop(snd_mtt6) snd_stop(snd_mtt7) snd_stop(snd_mtt8) snd_stop(snd_mtt9) var rnsound = floor(random(9)) switch rnsound { case 0: snd_play(snd_mtt1) break case 1: snd_play(snd_mtt2) break case 2: snd_play(snd_mtt3) break case 3: snd_play(snd_mtt4) break case 4: snd_play(snd_mtt5) break case 5: snd_play(snd_mtt6) break case 6: snd_play(snd_mtt7) break case 7: snd_play(snd_mtt8) break case 8: snd_play(snd_mtt9) break } } else if (txtsound == snd_wngdng1) { snd_stop(snd_wngdng1) snd_stop(snd_wngdng2) snd_stop(snd_wngdng3) snd_stop(snd_wngdng4) snd_stop(snd_wngdng5) snd_stop(snd_wngdng6) snd_stop(snd_wngdng7) rnsound = floor(random(7)) switch rnsound { case 0: snd_play(snd_wngdng1) break case 1: snd_play(snd_wngdng2) break case 2: snd_play(snd_wngdng3) break case 3: snd_play(snd_wngdng4) break case 4: snd_play(snd_wngdng5) break case 5: snd_play(snd_wngdng6) break case 6: snd_play(snd_wngdng7) break } } else if (txtsound == snd_tem) { snd_stop(snd_tem) snd_stop(snd_tem2) snd_stop(snd_tem3) snd_stop(snd_tem4) snd_stop(snd_tem5) snd_stop(snd_tem6) rnsound = floor(random(6)) switch rnsound { case 0: snd_play(snd_tem) break case 1: snd_play(snd_tem2) break case 2: snd_play(snd_tem3) break case 3: snd_play(snd_tem4) break case 4: snd_play(snd_tem5) break case 5: snd_play(snd_tem6) break } } else { ch = string_char_at(originalstring, stringpos) if (ch != " " && ch != " ") { snd_stop(txtsound) snd_play(txtsound) } } }
0
0.518737
1
0.518737
game-dev
MEDIA
0.6342
game-dev,audio-video-media
0.95444
1
0.95444
a1studmuffin/Cataclysm-DDA-Android
10,571
src/enums.h
#pragma once #ifndef ENUMS_H #define ENUMS_H #include <climits> #include <cassert> #include <ostream> #include "json.h" // (de)serialization for points #ifndef sgn #define sgn(x) (((x) < 0) ? -1 : (((x)>0) ? 1 : 0)) #endif // By default unordered_map doesn't have a hash for tuple or pairs, so we need to include some. // This is taken almost directly from the boost library code. // Function has to live in the std namespace // so that it is picked up by argument-dependent name lookup (ADL). namespace std{ namespace { // Code from boost // Reciprocal of the golden ratio helps spread entropy // and handles duplicates. // See Mike Seymour in magic-numbers-in-boosthash-combine: // http://stackoverflow.com/questions/4948780 template <class T> inline void hash_combine(std::size_t& seed, T const& v) { seed ^= hash<T>()(v) + 0x9e3779b9 + (seed<<6) + (seed>>2); } // Recursive template code derived from Matthieu M. template <class Tuple, size_t Index = std::tuple_size<Tuple>::value - 1> struct HashValueImpl { static void apply(size_t& seed, Tuple const& tuple) { HashValueImpl<Tuple, Index-1>::apply(seed, tuple); hash_combine(seed, get<Index>(tuple)); } }; template <class Tuple> struct HashValueImpl<Tuple,0> { static void apply(size_t& seed, Tuple const& tuple) { hash_combine(seed, get<0>(tuple)); } }; } template <typename ... TT> struct hash<std::tuple<TT...>> { size_t operator()(std::tuple<TT...> const& tt) const { size_t seed = 0; HashValueImpl<std::tuple<TT...> >::apply(seed, tt); return seed; } }; template <class A, class B> struct hash<std::pair<A, B>> { std::size_t operator() (const std::pair<A, B>& v) const { std::size_t seed = 0; hash_combine(seed, v.first); hash_combine(seed, v.second); return seed; } }; } //Used for autopickup and safemode rules enum rule_state : int { RULE_NONE, RULE_WHITELISTED, RULE_BLACKLISTED }; enum visibility_type { VIS_HIDDEN, VIS_CLEAR, VIS_LIT, VIS_BOOMER, VIS_DARK, VIS_BOOMER_DARK }; enum special_game_id { SGAME_NULL = 0, SGAME_TUTORIAL, SGAME_DEFENSE, NUM_SPECIAL_GAMES }; enum art_effect_passive : int { AEP_NULL = 0, // Good AEP_STR_UP, // Strength + 4 AEP_DEX_UP, // Dexterity + 4 AEP_PER_UP, // Perception + 4 AEP_INT_UP, // Intelligence + 4 AEP_ALL_UP, // All stats + 2 AEP_SPEED_UP, // +20 speed AEP_PBLUE, // Reduces radiation AEP_SNAKES, // Summons friendly snakes when you're hit AEP_INVISIBLE, // Makes you invisible AEP_CLAIRVOYANCE, // See through walls AEP_SUPER_CLAIRVOYANCE, // See through walls to a great distance AEP_STEALTH, // Your steps are quieted AEP_EXTINGUISH, // May extinguish nearby flames AEP_GLOW, // Four-tile light source AEP_PSYSHIELD, // Protection from stare attacks AEP_RESIST_ELECTRICITY, // Protection from electricity AEP_CARRY_MORE, // Increases carrying capacity by 200 AEP_SAP_LIFE, // Killing non-zombie monsters may heal you // Splits good from bad AEP_SPLIT, // Bad AEP_HUNGER, // Increases hunger AEP_THIRST, // Increases thirst AEP_SMOKE, // Emits smoke occasionally AEP_EVIL, // Addiction to the power AEP_SCHIZO, // Mimicks schizophrenia AEP_RADIOACTIVE, // Increases your radiation AEP_MUTAGENIC, // Mutates you slowly AEP_ATTENTION, // Draws netherworld attention slowly AEP_STR_DOWN, // Strength - 3 AEP_DEX_DOWN, // Dex - 3 AEP_PER_DOWN, // Per - 3 AEP_INT_DOWN, // Int - 3 AEP_ALL_DOWN, // All stats - 2 AEP_SPEED_DOWN, // -20 speed AEP_FORCE_TELEPORT, // Occasionally force a teleport AEP_MOVEMENT_NOISE, // Makes noise when you move AEP_BAD_WEATHER, // More likely to experience bad weather AEP_SICK, // Decreases health over time NUM_AEPS }; enum artifact_natural_property { ARTPROP_NULL, ARTPROP_WRIGGLING, // ARTPROP_GLOWING, // ARTPROP_HUMMING, // ARTPROP_MOVING, // ARTPROP_WHISPERING, // ARTPROP_BREATHING, // ARTPROP_DEAD, // ARTPROP_ITCHY, // ARTPROP_GLITTERING, // ARTPROP_ELECTRIC, // ARTPROP_SLIMY, // ARTPROP_ENGRAVED, // ARTPROP_CRACKLING, // ARTPROP_WARM, // ARTPROP_RATTLING, // ARTPROP_SCALED, ARTPROP_FRACTAL, ARTPROP_MAX }; enum phase_id : int { PNULL, SOLID, LIQUID, GAS, PLASMA }; // Return the class an in-world object uses to interact with the world. // ex; if ( player.grab_type == OBJECT_VEHICLE ) { ... // or; if ( baseactor_just_shot_at.object_type() == OBJECT_NPC ) { ... enum object_type { OBJECT_NONE, // Nothing, invalid. OBJECT_ITEM, // item.h OBJECT_ACTOR, // potential virtual base class, get_object_type() would return one of the types below OBJECT_PLAYER, // player.h, npc.h OBJECT_NPC, // nph.h OBJECT_MONSTER, // monster.h OBJECT_VEHICLE, // vehicle.h OBJECT_TRAP, // trap.h OBJECT_FIELD, // field.h; field_entry OBJECT_TERRAIN, // Not a real object OBJECT_FURNITURE, // Not a real object NUM_OBJECTS, }; struct point : public JsonSerializer, public JsonDeserializer { int x; int y; point() : x(0), y(0) {} point(int X, int Y) : x (X), y (Y) {} point(point &&) = default; point(const point &) = default; point &operator=(point &&) = default; point &operator=(const point &) = default; ~point() override {} using JsonSerializer::serialize; void serialize(JsonOut &jsout) const override { jsout.start_array(); jsout.write(x); jsout.write(y); jsout.end_array(); } using JsonDeserializer::deserialize; void deserialize(JsonIn &jsin) override { JsonArray ja = jsin.get_array(); x = ja.get_int(0); y = ja.get_int(1); } point operator+(const point &rhs) const { return point( x + rhs.x, y + rhs.y ); } point &operator+=(const point &rhs) { x += rhs.x; y += rhs.y; return *this; } point operator-(const point &rhs) const { return point( x - rhs.x, y - rhs.y ); } point &operator-=(const point &rhs) { x -= rhs.x; y -= rhs.y; return *this; } }; // Make point hashable so it can be used as an unordered_set or unordered_map key, // or a component of one. namespace std { template <> struct hash<point> { std::size_t operator()(const point& k) const { // Circular shift y by half its width so hash(5,6) != hash(6,5). return std::hash<int>()(k.x) ^ std::hash<int>()( (k.y << 16) | (k.y >> 16) ); } }; } inline bool operator<(const point &a, const point &b) { return a.x < b.x || (a.x == b.x && a.y < b.y); } inline bool operator==(const point &a, const point &b) { return a.x == b.x && a.y == b.y; } inline bool operator!=(const point &a, const point &b) { return !(a == b); } struct tripoint : public JsonSerializer, public JsonDeserializer { int x; int y; int z; tripoint() : x(0), y(0), z(0) {} tripoint(int X, int Y, int Z) : x (X), y (Y), z (Z) {} tripoint(tripoint &&) = default; tripoint(const tripoint &) = default; tripoint &operator=(tripoint &&) = default; tripoint &operator=(const tripoint &) = default; explicit tripoint(const point &p, int Z) : x (p.x), y (p.y), z (Z) {} ~tripoint() override {} using JsonSerializer::serialize; void serialize(JsonOut &jsout) const override { jsout.start_array(); jsout.write(x); jsout.write(y); jsout.write(z); jsout.end_array(); } using JsonDeserializer::deserialize; void deserialize(JsonIn &jsin) override { JsonArray ja = jsin.get_array(); x = ja.get_int(0); y = ja.get_int(1); z = ja.get_int(2); } tripoint operator+(const tripoint &rhs) const { return tripoint( x + rhs.x, y + rhs.y, z + rhs.z ); } tripoint operator-(const tripoint &rhs) const { return tripoint( x - rhs.x, y - rhs.y, z - rhs.z ); } tripoint &operator+=(const tripoint &rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } tripoint operator-() const { return tripoint( -x, -y, -z ); } /*** some point operators and functions ***/ tripoint operator+(const point &rhs) const { return tripoint(x + rhs.x, y + rhs.y, z); } tripoint operator-(const point &rhs) const { return tripoint(x - rhs.x, y - rhs.y, z); } tripoint &operator+=(const point &rhs) { x += rhs.x; y += rhs.y; return *this; } tripoint &operator-=(const point &rhs) { x -= rhs.x; y -= rhs.y; return *this; } tripoint &operator-=( const tripoint &rhs ) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; } }; inline std::ostream &operator<<( std::ostream &os, const tripoint &pos ) { return os << pos.x << "," << pos.y << "," << pos.z; } // Make tripoint hashable so it can be used as an unordered_set or unordered_map key, // or a component of one. namespace std { template <> struct hash<tripoint> { std::size_t operator()(const tripoint& k) const { // Circular shift y and z so hash(5,6,7) != hash(7,6,5). return std::hash<int>()(k.x) ^ std::hash<int>()( (k.y << 10) | (k.y >> 10) ) ^ std::hash<int>()( (k.z << 20) | (k.z >> 20) ); } }; } inline bool operator==(const tripoint &a, const tripoint &b) { return a.x == b.x && a.y == b.y && a.z == b.z; } inline bool operator!=(const tripoint &a, const tripoint &b) { return !(a == b); } inline bool operator<(const tripoint &a, const tripoint &b) { if (a.x != b.x) { return a.x < b.x; } if (a.y != b.y) { return a.y < b.y; } if (a.z != b.z) { return a.z < b.z; } return false; } static const tripoint tripoint_min { INT_MIN, INT_MIN, INT_MIN }; static const tripoint tripoint_zero { 0, 0, 0 }; #endif
0
0.941427
1
0.941427
game-dev
MEDIA
0.786578
game-dev
0.944666
1
0.944666
chai3d/chai3d
4,851
modules/Bullet/externals/bullet/src/BulletCollision/Gimpact/gim_contact.h
#ifndef GIM_CONTACT_H_INCLUDED #define GIM_CONTACT_H_INCLUDED /*! \file gim_contact.h \author Francisco Leon Najera */ /* ----------------------------------------------------------------------------- This source file is part of GIMPACT Library. For the latest info, see http://gimpact.sourceforge.net/ Copyright (c) 2006 Francisco Leon Najera. C.C. 80087371. email: projectileman@yahoo.com This library is free software; you can redistribute it and/or modify it under the terms of EITHER: (1) The GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The text of the GNU Lesser General Public License is included with this library in the file GIMPACT-LICENSE-LGPL.TXT. (2) The BSD-style license that is included with this library in the file GIMPACT-LICENSE-BSD.TXT. (3) The zlib/libpng license that is included with this library in the file GIMPACT-LICENSE-ZLIB.TXT. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files GIMPACT-LICENSE-LGPL.TXT, GIMPACT-LICENSE-ZLIB.TXT and GIMPACT-LICENSE-BSD.TXT for more details. ----------------------------------------------------------------------------- */ #include "gim_geometry.h" #include "gim_radixsort.h" #include "gim_array.h" /** Configuration var for applying interpolation of contact normals */ #define NORMAL_CONTACT_AVERAGE 1 #define CONTACT_DIFF_EPSILON 0.00001f /// Structure for collision results ///Functions for managing and sorting contacts resulting from a collision query. ///Contact lists must be create by calling \ref GIM_CREATE_CONTACT_LIST ///After querys, contact lists must be destroy by calling \ref GIM_DYNARRAY_DESTROY ///Contacts can be merge for avoid duplicate results by calling \ref gim_merge_contacts class GIM_CONTACT { public: btVector3 m_point; btVector3 m_normal; GREAL m_depth;//Positive value indicates interpenetration GREAL m_distance;//Padding not for use GUINT m_feature1;//Face number GUINT m_feature2;//Face number public: GIM_CONTACT() { } GIM_CONTACT(const GIM_CONTACT & contact): m_point(contact.m_point), m_normal(contact.m_normal), m_depth(contact.m_depth), m_feature1(contact.m_feature1), m_feature2(contact.m_feature2) { m_point = contact.m_point; m_normal = contact.m_normal; m_depth = contact.m_depth; m_feature1 = contact.m_feature1; m_feature2 = contact.m_feature2; } GIM_CONTACT(const btVector3 &point,const btVector3 & normal, GREAL depth, GUINT feature1, GUINT feature2): m_point(point), m_normal(normal), m_depth(depth), m_feature1(feature1), m_feature2(feature2) { } //! Calcs key for coord classification SIMD_FORCE_INLINE GUINT calc_key_contact() const { GINT _coords[] = { (GINT)(m_point[0]*1000.0f+1.0f), (GINT)(m_point[1]*1333.0f), (GINT)(m_point[2]*2133.0f+3.0f)}; GUINT _hash=0; GUINT *_uitmp = (GUINT *)(&_coords[0]); _hash = *_uitmp; _uitmp++; _hash += (*_uitmp)<<4; _uitmp++; _hash += (*_uitmp)<<8; return _hash; } SIMD_FORCE_INLINE void interpolate_normals( btVector3 * normals,GUINT normal_count) { btVector3 vec_sum(m_normal); for(GUINT i=0;i<normal_count;i++) { vec_sum += normals[i]; } GREAL vec_sum_len = vec_sum.length2(); if(vec_sum_len <CONTACT_DIFF_EPSILON) return; GIM_INV_SQRT(vec_sum_len,vec_sum_len); // 1/sqrt(vec_sum_len) m_normal = vec_sum*vec_sum_len; } }; class gim_contact_array:public gim_array<GIM_CONTACT> { public: gim_contact_array():gim_array<GIM_CONTACT>(64) { } SIMD_FORCE_INLINE void push_contact(const btVector3 &point,const btVector3 & normal, GREAL depth, GUINT feature1, GUINT feature2) { push_back_mem(); GIM_CONTACT & newele = back(); newele.m_point = point; newele.m_normal = normal; newele.m_depth = depth; newele.m_feature1 = feature1; newele.m_feature2 = feature2; } SIMD_FORCE_INLINE void push_triangle_contacts( const GIM_TRIANGLE_CONTACT_DATA & tricontact, GUINT feature1,GUINT feature2) { for(GUINT i = 0;i<tricontact.m_point_count ;i++ ) { push_back_mem(); GIM_CONTACT & newele = back(); newele.m_point = tricontact.m_points[i]; newele.m_normal = tricontact.m_separating_normal; newele.m_depth = tricontact.m_penetration_depth; newele.m_feature1 = feature1; newele.m_feature2 = feature2; } } void merge_contacts(const gim_contact_array & contacts, bool normal_contact_average = true); void merge_contacts_unique(const gim_contact_array & contacts); }; #endif // GIM_CONTACT_H_INCLUDED
0
0.686789
1
0.686789
game-dev
MEDIA
0.507275
game-dev,scientific-computing
0.626996
1
0.626996
puyoai/puyoai
1,638
src/core/rensa_tracker.h
#ifndef CORE_RENSA_TRACKER_H_ #define CORE_RENSA_TRACKER_H_ #include "base/unit.h" #include "core/field_bits.h" // RensaTracker tracks how rensa is vanished. // For example, a puyo is vanished in what-th chain, coefficient of each chain, etc. // You can pass a RensaTracker to CoreField::simulate() to track the rensa. // You can also define your own RensaTracker, and pass it to CoreField::simulate(). // // RensaTracker must define several interface. CoreField::simulate() has several hook points // that calls the corresponding Tracker methods. If you'd like to add a new hook point, // you need to define a hook point in CoreField. // // Here, we define only RensaNonTracker. The other implementations are located on core/rensa_tracker/. // ---------------------------------------------------------------------- template<typename TrackResult> class RensaTracker; // ---------------------------------------------------------------------- // RensaTracker<Unit> is a tracker that does not track anything. template<> class RensaTracker<Unit> { public: void trackCoef(int /*nthChain*/, int /*numErasedPuyo*/, int /*longBonusCoef*/, int /*colorBonusCoef*/) {} void trackVanish(int /*nthChain*/, const FieldBits& /*vanishedPuyoBits*/, const FieldBits& /*vanishedOjamaPuyoBits*/) {} void trackDrop(FieldBits /*blender*/, FieldBits /*leftOnes*/, FieldBits /*rightOnes*/) {} #ifdef __BMI2__ void trackDropBMI2(std::uint64_t /*oldLowBits*/, std::uint64_t /*oldHighBits*/, std::uint64_t /*newLowBits*/, std::uint64_t /*newHighBits*/) {} #endif }; typedef RensaTracker<Unit> RensaNonTracker; #endif // CORE_RENSA_TRACKER_H_
0
0.936186
1
0.936186
game-dev
MEDIA
0.265458
game-dev
0.532327
1
0.532327
utilForever/RosettaStone
2,499
Sources/Rosetta/PlayMode/Models/Hero.cpp
// Copyright (c) 2017-2024 Chris Ohk // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Rosetta/PlayMode/Games/Game.hpp> #include <Rosetta/PlayMode/Models/Hero.hpp> #include <Rosetta/PlayMode/Models/Player.hpp> #include <Rosetta/PlayMode/Zones/GraveyardZone.hpp> #include <utility> namespace RosettaStone::PlayMode { Hero::Hero(Player* _player, Card* _card, std::map<GameTag, int> tags, int id) : Character(_player, _card, std::move(tags), id) { // Do nothing } Hero::~Hero() { delete weapon; } int Hero::GetAttack() const { return HasWeapon() ? Character::GetAttack() + weapon->GetAttack() : Character::GetAttack(); } int Hero::GetArmor() const { return GetGameTag(GameTag::ARMOR); } void Hero::SetArmor(int armor) { SetGameTag(GameTag::ARMOR, armor); } int Hero::GetHeroPowerDamage() const { return GetGameTag(GameTag::HEROPOWER_DAMAGE); } void Hero::AddWeapon(Weapon& _weapon) { RemoveWeapon(); weapon = &_weapon; weapon->orderOfPlay = game->GetNextOOP(); weapon->SetZoneType(ZoneType::PLAY); weapon->SetZonePosition(0); if (weapon->GetGameTag(GameTag::WINDFURY) == 1 && IsExhausted() && GetNumAttacksThisTurn() == 1) { SetExhausted(false); } game->triggerManager.OnEquipWeaponTrigger(weapon); for (int i = static_cast<int>(weaponAuras.size()) - 1; i >= 0; --i) { weaponAuras[i]->NotifyEntityAdded(weapon); } } void Hero::RemoveWeapon() { if (!HasWeapon()) { return; } if (weapon->HasDeathrattle()) { weapon->ActivateTask(PowerType::DEATHRATTLE); } game->ProcessTasks(); game->triggerManager.OnDeathTrigger(weapon); for (int i = static_cast<int>(weaponAuras.size()) - 1; i >= 0; --i) { weaponAuras[i]->NotifyEntityRemoved(weapon); } player->GetGraveyardZone()->Add(weapon); weapon = nullptr; } bool Hero::HasWeapon() const { return weapon != nullptr; } void Hero::GainArmor(int amount) { SetArmor(GetArmor() + amount); } bool Hero::HasLifesteal() const { if (HasWeapon()) { return weapon->HasLifesteal(); } return false; } bool Hero::HasHonorableKill() const { if (HasWeapon()) { return weapon->HasHonorableKill(); } return false; } } // namespace RosettaStone::PlayMode
0
0.969913
1
0.969913
game-dev
MEDIA
0.996656
game-dev
0.930339
1
0.930339
collinsmith/riiablo
6,646
core/src/main/java/com/riiablo/entity/Direction.java
package com.riiablo.entity; import com.badlogic.gdx.math.MathUtils; import org.apache.commons.lang3.ArrayUtils; @Deprecated public class Direction { private Direction() {} public static final int SOUTH = 0; public static final int WEST = 1; public static final int NORTH = 2; public static final int EAST = 3; public static final int DOWN = 4; public static final int LEFT = 5; public static final int UP = 6; public static final int RIGHT = 7; static final float RADIANS_4[] = { MathUtils.atan2(-2, -4), MathUtils.atan2(-2, 4), MathUtils.atan2( 2, 4), MathUtils.atan2( 2, -4), }; static final int DIRS_4M[] = {0, 3, 2, 1}; static final float RADIANS_4M[] = { -MathUtils.PI / 2, 0, MathUtils.PI / 2, MathUtils.PI }; static final float RADIANS_8[] = { RADIANS_4[0], MathUtils.atan2(-4, 0), RADIANS_4[1], MathUtils.atan2( 0, 8), RADIANS_4[2], MathUtils.atan2( 4, 0), RADIANS_4[3], MathUtils.atan2( 0, -8), }; static final int DIRS_8M[] = {5, 0, 4, 3, 7, 2, 6, 1}; static final float RADIANS_8M[]; static { RADIANS_8M = new float[8]; float min = -RADIANS_8[7]; for (int i = 0; i < 8; i++) { RADIANS_8M[i] = (min + RADIANS_8[i]) / 2; min = RADIANS_8[i]; } } static final float RADIANS_16[] = { MathUtils.atan2(-1, -6), RADIANS_8[0], MathUtils.atan2(-3, -2), RADIANS_8[1], MathUtils.atan2(-3, 2), RADIANS_8[2], MathUtils.atan2(-1, 6), RADIANS_8[3], MathUtils.atan2(1, 6), RADIANS_8[4], MathUtils.atan2(3, 2), RADIANS_8[5], MathUtils.atan2(3, -2), RADIANS_8[6], MathUtils.atan2(1, -6), RADIANS_8[7], }; static final int DIRS_16M[] = {5, 9, 0, 8, 4, 15, 3, 14, 7, 13, 2, 12, 6, 11, 1, 10}; static final float RADIANS_16M[]; static { RADIANS_16M = new float[16]; float min = -RADIANS_16[15]; for (int i = 0; i < 16; i++) { RADIANS_16M[i] = (min + RADIANS_16[i]) / 2; min = RADIANS_16[i]; } } static final float RADIANS_32[] = { MathUtils.atan2(-0.5f, -7), RADIANS_16[0], MathUtils.atan2(-1.5f, -5), RADIANS_16[1], MathUtils.atan2(-2.5f, -3), RADIANS_16[2], MathUtils.atan2(-3.5f, -1), RADIANS_16[3], MathUtils.atan2(-3.5f, 1), RADIANS_16[4], MathUtils.atan2(-2.5f, 3), RADIANS_16[5], MathUtils.atan2(-1.5f, 5), RADIANS_16[6], MathUtils.atan2(-0.5f, 7), RADIANS_16[7], MathUtils.atan2(0.5f, 7), RADIANS_16[8], MathUtils.atan2(1.5f, 5), RADIANS_16[9], MathUtils.atan2(2.5f, 3), RADIANS_16[10], MathUtils.atan2(3.5f, 1), RADIANS_16[11], MathUtils.atan2(3.5f, -1), RADIANS_16[12], MathUtils.atan2(2.5f, -3), RADIANS_16[13], MathUtils.atan2(1.5f, -5), RADIANS_16[14], MathUtils.atan2(0.5f, -7), RADIANS_16[15], }; static final int DIRS_32M[] = {5, 19, 9, 18, 0, 17, 8, 16, 4, 31, 15, 30, 3, 29, 14, 28, 7, 27, 13, 26, 2, 25, 12, 24, 6, 23, 11, 22, 1, 21, 10, 20}; static final float RADIANS_32M[]; static { RADIANS_32M = new float[32]; float min = -RADIANS_32[31]; for (int i = 0; i < 32; i++) { RADIANS_32M[i] = (min + RADIANS_32[i]) / 2; min = RADIANS_32[i]; } } public static int radiansToDirection(float radians, int directions) { switch (directions) { case 1: return 0; case 4: return radiansToDirection4(radians); case 8: return radiansToDirection8(radians); case 16: return radiansToDirection16(radians); case 32: return radiansToDirection32(radians); default: return 0; } } @Deprecated static int _radiansToDirection4(float radians) { for (int i = 0; i < 4; i++) { if (radians < RADIANS_4M[i]) { return DIRS_4M[i]; } } return DIRS_4M[0]; } static int radiansToDirection4(float radians) { int index = (radians < RADIANS_4M[1]) ? 0 : 2; index |= (radians < RADIANS_4M[index]) ? 0 : 1; return DIRS_4M[index]; } @Deprecated static int _radiansToDirection8(float radians) { for (int i = 0; i < 8; i++) { if (radians < RADIANS_8M[i]) { return DIRS_8M[i]; } } return DIRS_8M[0]; } static int radiansToDirection8(float radians) { if (radians >= RADIANS_8M[7]) return DIRS_8M[0]; int index = (radians < RADIANS_8M[3]) ? 0 : 4; index |= (radians < RADIANS_8M[index|1]) ? 0 : 2; index |= (radians < RADIANS_8M[index ]) ? 0 : 1; return DIRS_8M[index]; } @Deprecated static int _radiansToDirection16(float radians) { for (int i = 0; i < 16; i++) { if (radians < RADIANS_16M[i]) { return DIRS_16M[i]; } } return DIRS_16M[0]; } static int radiansToDirection16(float radians) { if (radians >= RADIANS_16M[15]) return DIRS_16M[0]; int index = (radians < RADIANS_16M[7]) ? 0 : 8; index |= (radians < RADIANS_16M[index|3]) ? 0 : 4; index |= (radians < RADIANS_16M[index|1]) ? 0 : 2; index |= (radians < RADIANS_16M[index ]) ? 0 : 1; return DIRS_16M[index]; } @Deprecated static int _radiansToDirection32(float radians) { for (int i = 0; i < 32; i++) { if (radians < RADIANS_32M[i]) { return DIRS_32M[i]; } } return DIRS_32M[0]; } static int radiansToDirection32(float radians) { if (radians >= RADIANS_32M[31]) return DIRS_32M[0]; int index = (radians < RADIANS_32M[15]) ? 0 : 16; index |= (radians < RADIANS_32M[index|7]) ? 0 : 8; index |= (radians < RADIANS_32M[index|3]) ? 0 : 4; index |= (radians < RADIANS_32M[index|1]) ? 0 : 2; index |= (radians < RADIANS_32M[index ]) ? 0 : 1; return DIRS_32M[index]; } public static float snapToDirection(float radians, int directions) { switch (directions) { case 1: return RADIANS_4[0]; case 4: return _snapToDirection(radians, directions, DIRS_4M, RADIANS_4); case 8: return _snapToDirection(radians, directions, DIRS_8M, RADIANS_8); case 16: return _snapToDirection(radians, directions, DIRS_16M, RADIANS_16); case 32: return _snapToDirection(radians, directions, DIRS_32M, RADIANS_32); default: return RADIANS_4[0]; } } private static float _snapToDirection(float radians, int dirs, int[] dirsm, float[] rads) { int dir = radiansToDirection(radians, dirs); int index = ArrayUtils.indexOf(dirsm, dir); if (--index < 0) index = dirs - 1; return rads[index]; } }
0
0.749578
1
0.749578
game-dev
MEDIA
0.335363
game-dev
0.976876
1
0.976876
fredakilla/GPlayEngine
6,946
thirdparty/bullet/src/Bullet3OpenCL/BroadphaseCollision/kernels/gridBroadphaseKernels.h
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project static const char* gridBroadphaseCL= \ "int getPosHash(int4 gridPos, __global float4* pParams)\n" "{\n" " int4 gridDim = *((__global int4*)(pParams + 1));\n" " gridPos.x &= gridDim.x - 1;\n" " gridPos.y &= gridDim.y - 1;\n" " gridPos.z &= gridDim.z - 1;\n" " int hash = gridPos.z * gridDim.y * gridDim.x + gridPos.y * gridDim.x + gridPos.x;\n" " return hash;\n" "} \n" "int4 getGridPos(float4 worldPos, __global float4* pParams)\n" "{\n" " int4 gridPos;\n" " int4 gridDim = *((__global int4*)(pParams + 1));\n" " gridPos.x = (int)floor(worldPos.x * pParams[0].x) & (gridDim.x - 1);\n" " gridPos.y = (int)floor(worldPos.y * pParams[0].y) & (gridDim.y - 1);\n" " gridPos.z = (int)floor(worldPos.z * pParams[0].z) & (gridDim.z - 1);\n" " return gridPos;\n" "}\n" "// calculate grid hash value for each body using its AABB\n" "__kernel void kCalcHashAABB(int numObjects, __global float4* allpAABB, __global const int* smallAabbMapping, __global int2* pHash, __global float4* pParams )\n" "{\n" " int index = get_global_id(0);\n" " if(index >= numObjects)\n" " {\n" " return;\n" " }\n" " float4 bbMin = allpAABB[smallAabbMapping[index]*2];\n" " float4 bbMax = allpAABB[smallAabbMapping[index]*2 + 1];\n" " float4 pos;\n" " pos.x = (bbMin.x + bbMax.x) * 0.5f;\n" " pos.y = (bbMin.y + bbMax.y) * 0.5f;\n" " pos.z = (bbMin.z + bbMax.z) * 0.5f;\n" " pos.w = 0.f;\n" " // get address in grid\n" " int4 gridPos = getGridPos(pos, pParams);\n" " int gridHash = getPosHash(gridPos, pParams);\n" " // store grid hash and body index\n" " int2 hashVal;\n" " hashVal.x = gridHash;\n" " hashVal.y = index;\n" " pHash[index] = hashVal;\n" "}\n" "__kernel void kClearCellStart( int numCells, \n" " __global int* pCellStart )\n" "{\n" " int index = get_global_id(0);\n" " if(index >= numCells)\n" " {\n" " return;\n" " }\n" " pCellStart[index] = -1;\n" "}\n" "__kernel void kFindCellStart(int numObjects, __global int2* pHash, __global int* cellStart )\n" "{\n" " __local int sharedHash[513];\n" " int index = get_global_id(0);\n" " int2 sortedData;\n" " if(index < numObjects)\n" " {\n" " sortedData = pHash[index];\n" " // Load hash data into shared memory so that we can look \n" " // at neighboring body's hash value without loading\n" " // two hash values per thread\n" " sharedHash[get_local_id(0) + 1] = sortedData.x;\n" " if((index > 0) && (get_local_id(0) == 0))\n" " {\n" " // first thread in block must load neighbor body hash\n" " sharedHash[0] = pHash[index-1].x;\n" " }\n" " }\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" " if(index < numObjects)\n" " {\n" " if((index == 0) || (sortedData.x != sharedHash[get_local_id(0)]))\n" " {\n" " cellStart[sortedData.x] = index;\n" " }\n" " }\n" "}\n" "int testAABBOverlap(float4 min0, float4 max0, float4 min1, float4 max1)\n" "{\n" " return (min0.x <= max1.x)&& (min1.x <= max0.x) && \n" " (min0.y <= max1.y)&& (min1.y <= max0.y) && \n" " (min0.z <= max1.z)&& (min1.z <= max0.z); \n" "}\n" "//search for AABB 'index' against other AABBs' in this cell\n" "void findPairsInCell( int numObjects,\n" " int4 gridPos,\n" " int index,\n" " __global int2* pHash,\n" " __global int* pCellStart,\n" " __global float4* allpAABB, \n" " __global const int* smallAabbMapping,\n" " __global float4* pParams,\n" " volatile __global int* pairCount,\n" " __global int4* pPairBuff2,\n" " int maxPairs\n" " )\n" "{\n" " int4 pGridDim = *((__global int4*)(pParams + 1));\n" " int maxBodiesPerCell = pGridDim.w;\n" " int gridHash = getPosHash(gridPos, pParams);\n" " // get start of bucket for this cell\n" " int bucketStart = pCellStart[gridHash];\n" " if (bucketStart == -1)\n" " {\n" " return; // cell empty\n" " }\n" " // iterate over bodies in this cell\n" " int2 sortedData = pHash[index];\n" " int unsorted_indx = sortedData.y;\n" " float4 min0 = allpAABB[smallAabbMapping[unsorted_indx]*2 + 0]; \n" " float4 max0 = allpAABB[smallAabbMapping[unsorted_indx]*2 + 1];\n" " int handleIndex = as_int(min0.w);\n" " \n" " int bucketEnd = bucketStart + maxBodiesPerCell;\n" " bucketEnd = (bucketEnd > numObjects) ? numObjects : bucketEnd;\n" " for(int index2 = bucketStart; index2 < bucketEnd; index2++) \n" " {\n" " int2 cellData = pHash[index2];\n" " if (cellData.x != gridHash)\n" " {\n" " break; // no longer in same bucket\n" " }\n" " int unsorted_indx2 = cellData.y;\n" " //if (unsorted_indx2 < unsorted_indx) // check not colliding with self\n" " if (unsorted_indx2 != unsorted_indx) // check not colliding with self\n" " { \n" " float4 min1 = allpAABB[smallAabbMapping[unsorted_indx2]*2 + 0];\n" " float4 max1 = allpAABB[smallAabbMapping[unsorted_indx2]*2 + 1];\n" " if(testAABBOverlap(min0, max0, min1, max1))\n" " {\n" " if (pairCount)\n" " {\n" " int handleIndex2 = as_int(min1.w);\n" " if (handleIndex<handleIndex2)\n" " {\n" " int curPair = atomic_add(pairCount,1);\n" " if (curPair<maxPairs)\n" " {\n" " int4 newpair;\n" " newpair.x = handleIndex;\n" " newpair.y = handleIndex2;\n" " newpair.z = -1;\n" " newpair.w = -1;\n" " pPairBuff2[curPair] = newpair;\n" " }\n" " }\n" " \n" " }\n" " }\n" " }\n" " }\n" "}\n" "__kernel void kFindOverlappingPairs( int numObjects,\n" " __global float4* allpAABB, \n" " __global const int* smallAabbMapping,\n" " __global int2* pHash, \n" " __global int* pCellStart, \n" " __global float4* pParams ,\n" " volatile __global int* pairCount,\n" " __global int4* pPairBuff2,\n" " int maxPairs\n" " )\n" "{\n" " int index = get_global_id(0);\n" " if(index >= numObjects)\n" " {\n" " return;\n" " }\n" " int2 sortedData = pHash[index];\n" " int unsorted_indx = sortedData.y;\n" " float4 bbMin = allpAABB[smallAabbMapping[unsorted_indx]*2 + 0];\n" " float4 bbMax = allpAABB[smallAabbMapping[unsorted_indx]*2 + 1];\n" " float4 pos;\n" " pos.x = (bbMin.x + bbMax.x) * 0.5f;\n" " pos.y = (bbMin.y + bbMax.y) * 0.5f;\n" " pos.z = (bbMin.z + bbMax.z) * 0.5f;\n" " // get address in grid\n" " int4 gridPosA = getGridPos(pos, pParams);\n" " int4 gridPosB; \n" " // examine only neighbouring cells\n" " for(int z=-1; z<=1; z++) \n" " {\n" " gridPosB.z = gridPosA.z + z;\n" " for(int y=-1; y<=1; y++) \n" " {\n" " gridPosB.y = gridPosA.y + y;\n" " for(int x=-1; x<=1; x++) \n" " {\n" " gridPosB.x = gridPosA.x + x;\n" " findPairsInCell(numObjects, gridPosB, index, pHash, pCellStart, allpAABB,smallAabbMapping, pParams, pairCount,pPairBuff2, maxPairs);\n" " }\n" " }\n" " }\n" "}\n" ;
0
0.649002
1
0.649002
game-dev
MEDIA
0.520142
game-dev
0.806246
1
0.806246
Mormert/jle
2,558
engine/cUITransformUpdater.cpp
/********************************************************************************************* * * * , . , . ,--. * * | | | | | o * * | ,-. |- -- | ,-: ,-: ,-: ,-. ,-| |- ;-. ,-: . ;-. ,-. * * | |-' | | | | | | | | |-' | | | | | | | | | | |-' * * -' `-' `-' `--' `-` `-| `-| `-' `-' `--' ' ' `-| ' ' ' `-' * * * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Jet-Lagged Engine (jle) is licenced under GNU General Public License v3.0. * * The licence can be found here: https://github.com/Mormert/jle/blob/master/LICENSE * * Copyright (c) 2020-2024 Johan Lind. All rights reserved. * * * *********************************************************************************************/ /* #include "cUITransformUpdater.h" #include "jleGameEngine.h" JLE_EXTERN_TEMPLATE_CEREAL_CPP(cUITransformUpdater) cUITransformUpdater::cUITransformUpdater(jleObject *owner, jleScene *scene) : jleComponent(owner, scene) {} cUITransformUpdater::~cUITransformUpdater() {} void cUITransformUpdater::start() { jleObject *parent = _attachedToObject; do { if (auto &&c = parent->getComponent<cCamera>()) { _camera = c; break; } parent = parent->parent(); } while (parent); } void cUITransformUpdater::update(float dt) { // TODO: dont do this in update, rely on callback functions instead // since the UI gets dirty every frame now... const auto framebuffer = ((jleGameEngine *)(gCore))->mainScreenFramebuffer; getTransform().setLocalPosition({_x, _y, 0.f}); if (_top) { getTransform().setLocalPosition({_x, _y, 0.f}); } else if (_bottom) { getTransform().setLocalPosition({_x, framebuffer->height() + _y, 0.f}); } if (_left) { getTransform().setLocalPosition({_x, _y, 0.f}); } else if (_right) { getTransform().setLocalPosition({framebuffer->width() + _x, _y, 0.f}); } } */
0
0.858029
1
0.858029
game-dev
MEDIA
0.516965
game-dev,graphics-rendering
0.672131
1
0.672131
tswow/tswow
5,833
tswow-core/Private/TSInstance.cpp
#include "TSMap.h" #if TRINITY #include "AreaBoundary.h" #endif #include "Map.h" #include "InstanceScript.h" #include "ScriptedCreature.h" #include "TSGUID.h" TSInstance::TSInstance(Map* map, InstanceScript* script) : TSMap(map), m_script(script) {} bool TSInstance::IsNull() { return m_script == nullptr || map == nullptr; } void TSInstance::RemoveFromMap(TSPlayer player, bool deleteFromWorld) { map->RemovePlayerFromMap(player.player, deleteFromWorld); } void TSInstance::SaveInstanceToDB() { m_script->SaveToDB(); } bool TSInstance::IsEncounterInProgress() { return m_script->IsEncounterInProgress(); } TSGUID TSInstance::GetObjectGUID(uint32 type) { return TSGUID(m_script->GetObjectGuid(type)); } void TSInstance::DoUseDoorOrButton(TSGUID guid, uint32 withRestoreTime, bool useAlternativeState) { return m_script->DoUseDoorOrButton(guid.asGUID(), withRestoreTime, useAlternativeState); } void TSInstance::DoCloseDoorOrButton(TSGUID guid) { #if TRINITY m_script->DoCloseDoorOrButton(guid.asGUID()); #endif } void TSInstance::DoRespawnGameObject(TSGUID guid, uint32 seconds) { #if TRINITY m_script->DoRespawnGameObject(guid.asGUID(), Seconds(seconds)); #endif } void TSInstance::DoUpdateWorldState(uint32 worldStateId, uint32 worldStateValue) { m_script->DoUpdateWorldState(worldStateId, worldStateValue); } void TSInstance::DoSendNotify(std::string const& message) { m_script->DoSendNotifyToInstance(message.c_str()); } void TSInstance::DoUpdateAchievementCriteria(uint32 type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, TSUnit unit = TSUnit(nullptr)) { m_script->DoUpdateAchievementCriteria(AchievementCriteriaTypes(type), miscValue1, miscValue2, unit.unit); } void TSInstance::DoStartTimedAchievement(uint32 type, uint32 entry) { m_script->DoStartTimedAchievement(AchievementCriteriaTimedTypes(type), entry); } void TSInstance::DoStopTimedAchievement(uint32 type, uint32 entry) { m_script->DoStopTimedAchievement(AchievementCriteriaTimedTypes(type), entry); } void TSInstance::DoRemoveAurasDueToSpellOnPlayers(uint32 spell, bool includePets, bool includeControlled) { #if TRINITY m_script->DoRemoveAurasDueToSpellOnPlayers(spell, includePets, includeControlled); #endif } void TSInstance::DoCastSpellOnPlayers(uint32 spell, bool includePets, bool includeControlled) { #if TRINITY m_script->DoCastSpellOnPlayers(spell, includePets, includeControlled); #endif } void TSInstance::SetBossState(uint32 id, uint32 encounterState) { m_script->SetBossState(id, EncounterState(encounterState)); } TSNumber<uint32> TSInstance::GetBossState(uint32 id) { return m_script->GetBossState(id); } void TSInstance::MarkAreaTriggerDone(uint32 id) { m_script->MarkAreaTriggerDone(id); } void TSInstance::ResetAreaTriggerDone(uint32 id) { m_script->ResetAreaTriggerDone(id); } void TSInstance::BindAllPlayers() { #if TRINITY m_script->instance->PermBindAllPlayers(); #endif } bool TSInstance::HasPermBoundPlayers() { #if TRINITY return m_script->instance->HasPermBoundPlayers(); #endif } TSNumber<uint32> TSInstance::GetMaxPlayers() { #if TRINITY return m_script->instance->GetMaxPlayers(); #endif } TSNumber<uint32> TSInstance::GetMaxResetDelay() { #if TRINITY return m_script->instance->GetMaxResetDelay(); #endif } TSNumber<uint32> TSInstance::GetTeamIDInInstance() { #if TRINITY return m_script->instance->GetTeamIdInInstance(); #endif } TSNumber<uint32> TSInstance::GetFactionInInstance() { #if TRINITY return m_script->instance->GetTeamInInstance(); #endif } TSNumber<uint32> TSInstance::GetEncounterCount() { return m_script->GetEncounterCount(); } TSBossInfo TSInstance::GetBossInfo(uint32 id) { return TSBossInfo(&m_script->bosses[id]); } TSGUIDSet::TSGUIDSet(std::set<ObjectGuid>* set) : m_set(set) {} bool TSGUIDSet::Contains(uint64 value) { return m_set->find(ObjectGuid(value)) == m_set->end(); } void TSGUIDSet::Add(uint64 value) { m_set->insert(ObjectGuid(value)); } void TSGUIDSet::Remove(uint64 value) { m_set->erase(ObjectGuid(value)); } TSBossInfo::TSBossInfo(BossInfo* info) : m_info(info) {} TSNumber<uint32> TSBossInfo::GetBossState() { return m_info->state; } TSGUIDSet TSBossInfo::GetMinionGUIDs() { #if TRINITY return TSGUIDSet(&m_info->minion); #endif } TSGUIDSet TSBossInfo::GetDoorsClosedDuringEncounter() { #if TRINITY return TSGUIDSet(&m_info->door[DoorType::DOOR_TYPE_ROOM]); #endif } TSGUIDSet TSBossInfo::GetDoorsOpenDuringEncounter() { #if TRINITY return TSGUIDSet(&m_info->door[DoorType::DOOR_TYPE_SPAWN_HOLE]); #endif } TSGUIDSet TSBossInfo::GetDoorsOpenAfterEncounter() { #if TRINITY return TSGUIDSet(&m_info->door[DoorType::DOOR_TYPE_PASSAGE]); #endif } bool TSBossInfo::IsWithinBoundary(float x, float y, float z) { #if TRINITY for (auto part : m_info->boundary) { if (!part->IsWithinBoundary(Position(x, y, z))) return false; } #endif return true; } bool TSBossInfo::IsWithinBoundary(TSWorldObject obj) { #if TRINITY for (auto part : m_info->boundary) { if (!part->IsWithinBoundary(obj.obj)) { return false; } } #endif return true; } TSNumber<uint32> TSInstance::GetInstanceData(uint32 id) { return m_script->GetData(id); } void TSInstance::SetInstanceData(uint32 id, uint32 data) { m_script->SetData(id, data); } TSNumber<uint64> TSInstance::GetInstanceData64(uint32 id) { return m_script->GetData64(id); } void TSInstance::SetInstanceData64(uint32 id, uint64 data) { m_script->SetData64(id, data); } TSGUID TSInstance::GetInstanceGUIDData(uint32 id) { return TSGUID(m_script->GetGuidData(id)); } void TSInstance::SetInstanceGUIDData(uint32 id, TSGUID data) { m_script->SetGuidData(id, data->asGUID()); }
0
0.750697
1
0.750697
game-dev
MEDIA
0.934791
game-dev
0.923291
1
0.923291
parkchamchi/DepthViewer
3,010
DEPTH/Assets/Plugins/SimpleFileBrowser/Scripts/FileBrowserMovement.cs
using UnityEngine; using UnityEngine.EventSystems; namespace SimpleFileBrowser { public class FileBrowserMovement : MonoBehaviour { #region Variables #pragma warning disable 0649 private FileBrowser fileBrowser; private RectTransform canvasTR; private Camera canvasCam; [SerializeField] private RectTransform window; [SerializeField] private RecycledListView listView; #pragma warning restore 0649 private Vector2 initialTouchPos = Vector2.zero; private Vector2 initialAnchoredPos, initialSizeDelta; #endregion #region Initialization Functions public void Initialize( FileBrowser fileBrowser ) { this.fileBrowser = fileBrowser; canvasTR = fileBrowser.GetComponent<RectTransform>(); } #endregion #region Pointer Events public void OnDragStarted( BaseEventData data ) { PointerEventData pointer = (PointerEventData) data; canvasCam = pointer.pressEventCamera; RectTransformUtility.ScreenPointToLocalPointInRectangle( window, pointer.pressPosition, canvasCam, out initialTouchPos ); } public void OnDrag( BaseEventData data ) { PointerEventData pointer = (PointerEventData) data; Vector2 touchPos; RectTransformUtility.ScreenPointToLocalPointInRectangle( window, pointer.position, canvasCam, out touchPos ); window.anchoredPosition += touchPos - initialTouchPos; } public void OnEndDrag( BaseEventData data ) { fileBrowser.EnsureWindowIsWithinBounds(); } public void OnResizeStarted( BaseEventData data ) { PointerEventData pointer = (PointerEventData) data; canvasCam = pointer.pressEventCamera; initialAnchoredPos = window.anchoredPosition; initialSizeDelta = window.sizeDelta; RectTransformUtility.ScreenPointToLocalPointInRectangle( canvasTR, pointer.pressPosition, canvasCam, out initialTouchPos ); } public void OnResize( BaseEventData data ) { PointerEventData pointer = (PointerEventData) data; Vector2 touchPos; RectTransformUtility.ScreenPointToLocalPointInRectangle( canvasTR, pointer.position, canvasCam, out touchPos ); Vector2 delta = touchPos - initialTouchPos; Vector2 newSize = initialSizeDelta + new Vector2( delta.x, -delta.y ); Vector2 canvasSize = canvasTR.sizeDelta; if( newSize.x < fileBrowser.minWidth ) newSize.x = fileBrowser.minWidth; if( newSize.y < fileBrowser.minHeight ) newSize.y = fileBrowser.minHeight; if( newSize.x > canvasSize.x ) newSize.x = canvasSize.x; if( newSize.y > canvasSize.y ) newSize.y = canvasSize.y; newSize.x = (int) newSize.x; newSize.y = (int) newSize.y; delta = newSize - initialSizeDelta; window.anchoredPosition = initialAnchoredPos + new Vector2( delta.x * 0.5f, delta.y * -0.5f ); if( window.sizeDelta != newSize ) { window.sizeDelta = newSize; fileBrowser.OnWindowDimensionsChanged( newSize ); } listView.OnViewportDimensionsChanged(); } public void OnEndResize( BaseEventData data ) { fileBrowser.EnsureWindowIsWithinBounds(); } #endregion } }
0
0.941495
1
0.941495
game-dev
MEDIA
0.429896
game-dev
0.949165
1
0.949165
chocolate-doom/chocolate-doom
8,139
src/strife/r_defs.h
// // Copyright(C) 1993-1996 Id Software, Inc. // Copyright(C) 2005-2014 Simon Howard // // 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. // // DESCRIPTION: // Refresh/rendering module, shared data struct definitions. // #ifndef __R_DEFS__ #define __R_DEFS__ // Screenwidth. #include "doomdef.h" // Some more or less basic data types // we depend on. #include "m_fixed.h" // We rely on the thinker data struct // to handle sound origins in sectors. #include "d_think.h" // SECTORS do store MObjs anyway. #include "p_mobj.h" #include "i_video.h" #include "v_patch.h" // Silhouette, needed for clipping Segs (mainly) // and sprites representing things. #define SIL_NONE 0 #define SIL_BOTTOM 1 #define SIL_TOP 2 #define SIL_BOTH 3 #define MAXDRAWSEGS 256 // // INTERNAL MAP TYPES // used by play and refresh // // // Your plain vanilla vertex. // Note: transformed values not buffered locally, // like some DOOM-alikes ("wt", "WebView") did. // typedef struct { fixed_t x; fixed_t y; } vertex_t; // Forward of LineDefs, for Sectors. struct line_s; // Each sector has a degenmobj_t in its center // for sound origin purposes. // I suppose this does not handle sound from // moving objects (doppler), because // position is prolly just buffered, not // updated. typedef struct { thinker_t thinker; // not used for anything fixed_t x; fixed_t y; fixed_t z; } degenmobj_t; // // The SECTORS record, at runtime. // Stores things/mobjs. // typedef struct { fixed_t floorheight; fixed_t ceilingheight; short floorpic; short ceilingpic; short lightlevel; short special; short tag; // 0 = untraversed, 1,2 = sndlines -1 int soundtraversed; // thing that made a sound (or null) mobj_t* soundtarget; // mapblock bounding box for height changes int blockbox[4]; // origin for any sounds played by the sector degenmobj_t soundorg; // if == validcount, already checked int validcount; // list of mobjs in sector mobj_t* thinglist; // thinker_t for reversable actions void* specialdata; int linecount; struct line_s** lines; // [linecount] size } sector_t; // // The SideDef. // typedef struct { // add this to the calculated texture column fixed_t textureoffset; // add this to the calculated texture top fixed_t rowoffset; // Texture indices. // We do not maintain names here. short toptexture; short bottomtexture; short midtexture; // Sector the SideDef is facing. sector_t* sector; } side_t; // // Move clipping aid for LineDefs. // typedef enum { ST_HORIZONTAL, ST_VERTICAL, ST_POSITIVE, ST_NEGATIVE } slopetype_t; typedef struct line_s { // Vertices, from v1 to v2. vertex_t* v1; vertex_t* v2; // Precalculated v2 - v1 for side checking. fixed_t dx; fixed_t dy; // Animation related. short flags; short special; short tag; // Visual appearance: SideDefs. // sidenum[1] will be -1 if one sided short sidenum[2]; // Neat. Another bounding box, for the extent // of the LineDef. fixed_t bbox[4]; // To aid move clipping. slopetype_t slopetype; // Front and back sector. // Note: redundant? Can be retrieved from SideDefs. sector_t* frontsector; sector_t* backsector; // if == validcount, already checked int validcount; // thinker_t for reversable actions void* specialdata; } line_t; // // A SubSector. // References a Sector. // Basically, this is a list of LineSegs, // indicating the visible walls that define // (all or some) sides of a convex BSP leaf. // typedef struct subsector_s { sector_t* sector; short numlines; short firstline; } subsector_t; // // The LineSeg. // typedef struct { vertex_t* v1; vertex_t* v2; fixed_t offset; angle_t angle; side_t* sidedef; line_t* linedef; // Sector references. // Could be retrieved from linedef, too. // backsector is NULL for one sided lines sector_t* frontsector; sector_t* backsector; } seg_t; // // BSP node. // typedef struct { // Partition line. fixed_t x; fixed_t y; fixed_t dx; fixed_t dy; // Bounding box for each child. fixed_t bbox[2][4]; // If NF_SUBSECTOR its a subsector. unsigned short children[2]; } node_t; // PC direct to screen pointers //B UNUSED - keep till detailshift in r_draw.c resolved //extern byte* destview; //extern byte* destscreen; // // OTHER TYPES // // This could be wider for >8 bit display. // Indeed, true color support is posibble // precalculating 24bpp lightmap/colormap LUT. // from darkening PLAYPAL to all black. // Could even us emore than 32 levels. typedef byte lighttable_t; // // ? // typedef struct drawseg_s { seg_t* curline; int x1; int x2; fixed_t scale1; fixed_t scale2; fixed_t scalestep; // 0=none, 1=bottom, 2=top, 3=both int silhouette; // do not clip sprites above this fixed_t bsilheight; // do not clip sprites below this fixed_t tsilheight; // Pointers to lists for sprite clipping, // all three adjusted so [x1] is first value. short* sprtopclip; short* sprbottomclip; short* maskedtexturecol; } drawseg_t; // A vissprite_t is a thing // that will be drawn during a refresh. // I.e. a sprite object that is partly visible. typedef struct vissprite_s { // Doubly linked list. struct vissprite_s* prev; struct vissprite_s* next; int x1; int x2; // for line side calculation fixed_t gx; fixed_t gy; // global bottom / top for silhouette clipping fixed_t gz; fixed_t gzt; // horizontal position of x1 fixed_t startfrac; fixed_t scale; // negative if flipped fixed_t xiscale; fixed_t texturemid; int patch; // for color translation and shadow draw, // maxbright frames as well lighttable_t* colormap; int mobjflags; } vissprite_t; // // Sprites are patches with a special naming convention // so they can be recognized by R_InitSprites. // The base name is NNNNFx or NNNNFxFx, with // x indicating the rotation, x = 0, 1-7. // The sprite and frame specified by a thing_t // is range checked at run time. // A sprite is a patch_t that is assumed to represent // a three dimensional object and may have multiple // rotations pre drawn. // Horizontal flipping is used to save space, // thus NNNNF2F5 defines a mirrored patch. // Some sprites will only have one picture used // for all views: NNNNF0 // typedef struct { // If false use 0 for any position. // Note: as eight entries are available, // we might as well insert the same name eight times. boolean rotate; // Lump to use for view angles 0-7. short lump[8]; // Flip bit (1 = flip) to use for view angles 0-7. byte flip[8]; } spriteframe_t; // // A sprite definition: // a number of animation frames. // typedef struct { int numframes; spriteframe_t* spriteframes; } spritedef_t; // // Now what is a visplane, anyway? // typedef struct { fixed_t height; int picnum; int lightlevel; int minx; int maxx; // leave pads for [minx-1]/[maxx+1] byte pad1; // Here lies the rub for all // dynamic resize/change of resolution. byte top[SCREENWIDTH]; byte pad2; byte pad3; // See above. byte bottom[SCREENWIDTH]; byte pad4; } visplane_t; #endif
0
0.874044
1
0.874044
game-dev
MEDIA
0.690543
game-dev,graphics-rendering
0.596483
1
0.596483
ScRichard/GOTHAJ_RECODE_UNRELEASED
1,483
net/minecraft/block/BlockBreakable.java
package net.minecraft.block; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; public class BlockBreakable extends Block { private boolean ignoreSimilarity; protected BlockBreakable(Material materialIn, boolean ignoreSimilarityIn) { this(materialIn, ignoreSimilarityIn, materialIn.getMaterialMapColor()); } protected BlockBreakable(Material p_i46393_1_, boolean p_i46393_2_, MapColor p_i46393_3_) { super(p_i46393_1_, p_i46393_3_); this.ignoreSimilarity = p_i46393_2_; } public boolean isOpaqueCube() { return false; } public boolean shouldSideBeRendered(IBlockAccess worldIn, BlockPos pos, EnumFacing side) { IBlockState iblockstate = worldIn.getBlockState(pos); Block block = iblockstate.getBlock(); if (this == Blocks.glass || this == Blocks.stained_glass) { if (worldIn.getBlockState(pos.offset(side.getOpposite())) != iblockstate) { return true; } if (block == this) { return false; } } return !this.ignoreSimilarity && block == this ? false : super.shouldSideBeRendered(worldIn, pos, side); } }
0
0.638317
1
0.638317
game-dev
MEDIA
0.986994
game-dev
0.785069
1
0.785069
Goob-Station/Goob-Station-MRP
1,365
Content.Server/Movement/StressTestMovementSystem.cs
using System.Numerics; using Content.Server.Movement.Components; namespace Content.Server.Movement; public sealed class StressTestMovementSystem : EntitySystem { [Dependency] private readonly SharedTransformSystem _transform = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<StressTestMovementComponent, ComponentStartup>(OnStressStartup); } private void OnStressStartup(EntityUid uid, StressTestMovementComponent component, ComponentStartup args) { component.Origin = _transform.GetWorldPosition(uid); } public override void Update(float frameTime) { base.Update(frameTime); var query = EntityQueryEnumerator<StressTestMovementComponent, TransformComponent>(); while (query.MoveNext(out var uid, out var stressTest, out var transform)) { if (!transform.ParentUid.IsValid()) continue; stressTest.Progress += frameTime; if (stressTest.Progress > 1) { stressTest.Progress -= 1; } var x = MathF.Sin(stressTest.Progress * MathHelper.TwoPi); var y = MathF.Cos(stressTest.Progress * MathHelper.TwoPi); _transform.SetWorldPosition(transform, stressTest.Origin + new Vector2(x, y) * 5); } } }
0
0.786624
1
0.786624
game-dev
MEDIA
0.722608
game-dev,testing-qa
0.897808
1
0.897808
mariofv/LittleOrionEngine
5,891
Libraries/include/bullet3/BulletDynamics/Featherstone/btMultiBodyGearConstraint.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 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. */ ///This file was written by Erwin Coumans #include "btMultiBodyGearConstraint.h" #include "btMultiBody.h" #include "btMultiBodyLinkCollider.h" #include "BulletCollision/CollisionDispatch/btCollisionObject.h" btMultiBodyGearConstraint::btMultiBodyGearConstraint(btMultiBody* bodyA, int linkA, btMultiBody* bodyB, int linkB, const btVector3& pivotInA, const btVector3& pivotInB, const btMatrix3x3& frameInA, const btMatrix3x3& frameInB) : btMultiBodyConstraint(bodyA, bodyB, linkA, linkB, 1, false), m_gearRatio(1), m_gearAuxLink(-1), m_erp(0), m_relativePositionTarget(0) { } void btMultiBodyGearConstraint::finalizeMultiDof() { allocateJacobiansMultiDof(); m_numDofsFinalized = m_jacSizeBoth; } btMultiBodyGearConstraint::~btMultiBodyGearConstraint() { } int btMultiBodyGearConstraint::getIslandIdA() const { if (m_bodyA) { if (m_linkA < 0) { btMultiBodyLinkCollider* col = m_bodyA->getBaseCollider(); if (col) return col->getIslandTag(); } else { if (m_bodyA->getLink(m_linkA).m_collider) return m_bodyA->getLink(m_linkA).m_collider->getIslandTag(); } } return -1; } int btMultiBodyGearConstraint::getIslandIdB() const { if (m_bodyB) { if (m_linkB < 0) { btMultiBodyLinkCollider* col = m_bodyB->getBaseCollider(); if (col) return col->getIslandTag(); } else { if (m_bodyB->getLink(m_linkB).m_collider) return m_bodyB->getLink(m_linkB).m_collider->getIslandTag(); } } return -1; } void btMultiBodyGearConstraint::createConstraintRows(btMultiBodyConstraintArray& constraintRows, btMultiBodyJacobianData& data, const btContactSolverInfo& infoGlobal) { // only positions need to be updated -- data.m_jacobians and force // directions were set in the ctor and never change. if (m_numDofsFinalized != m_jacSizeBoth) { finalizeMultiDof(); } //don't crash if (m_numDofsFinalized != m_jacSizeBoth) return; if (m_maxAppliedImpulse == 0.f) return; // note: we rely on the fact that data.m_jacobians are // always initialized to zero by the Constraint ctor int linkDoF = 0; unsigned int offsetA = 6 + (m_bodyA->getLink(m_linkA).m_dofOffset + linkDoF); unsigned int offsetB = 6 + (m_bodyB->getLink(m_linkB).m_dofOffset + linkDoF); // row 0: the lower bound jacobianA(0)[offsetA] = 1; jacobianB(0)[offsetB] = m_gearRatio; btScalar posError = 0; const btVector3 dummy(0, 0, 0); btScalar kp = 1; btScalar kd = 1; int numRows = getNumRows(); for (int row = 0; row < numRows; row++) { btMultiBodySolverConstraint& constraintRow = constraintRows.expandNonInitializing(); int dof = 0; btScalar currentPosition = m_bodyA->getJointPosMultiDof(m_linkA)[dof]; btScalar currentVelocity = m_bodyA->getJointVelMultiDof(m_linkA)[dof]; btScalar auxVel = 0; if (m_gearAuxLink >= 0) { auxVel = m_bodyA->getJointVelMultiDof(m_gearAuxLink)[dof]; } currentVelocity += auxVel; if (m_erp != 0) { btScalar currentPositionA = m_bodyA->getJointPosMultiDof(m_linkA)[dof]; if (m_gearAuxLink >= 0) { currentPositionA -= m_bodyA->getJointPosMultiDof(m_gearAuxLink)[dof]; } btScalar currentPositionB = m_gearRatio * m_bodyA->getJointPosMultiDof(m_linkB)[dof]; btScalar diff = currentPositionB + currentPositionA; btScalar desiredPositionDiff = this->m_relativePositionTarget; posError = -m_erp * (desiredPositionDiff - diff); } btScalar desiredRelativeVelocity = auxVel; fillMultiBodyConstraint(constraintRow, data, jacobianA(row), jacobianB(row), dummy, dummy, dummy, dummy, posError, infoGlobal, -m_maxAppliedImpulse, m_maxAppliedImpulse, false, 1, false, desiredRelativeVelocity); constraintRow.m_orgConstraint = this; constraintRow.m_orgDofIndex = row; { //expect either prismatic or revolute joint type for now btAssert((m_bodyA->getLink(m_linkA).m_jointType == btMultibodyLink::eRevolute) || (m_bodyA->getLink(m_linkA).m_jointType == btMultibodyLink::ePrismatic)); switch (m_bodyA->getLink(m_linkA).m_jointType) { case btMultibodyLink::eRevolute: { constraintRow.m_contactNormal1.setZero(); constraintRow.m_contactNormal2.setZero(); btVector3 revoluteAxisInWorld = quatRotate(m_bodyA->getLink(m_linkA).m_cachedWorldTransform.getRotation(), m_bodyA->getLink(m_linkA).m_axes[0].m_topVec); constraintRow.m_relpos1CrossNormal = revoluteAxisInWorld; constraintRow.m_relpos2CrossNormal = -revoluteAxisInWorld; break; } case btMultibodyLink::ePrismatic: { btVector3 prismaticAxisInWorld = quatRotate(m_bodyA->getLink(m_linkA).m_cachedWorldTransform.getRotation(), m_bodyA->getLink(m_linkA).m_axes[0].m_bottomVec); constraintRow.m_contactNormal1 = prismaticAxisInWorld; constraintRow.m_contactNormal2 = -prismaticAxisInWorld; constraintRow.m_relpos1CrossNormal.setZero(); constraintRow.m_relpos2CrossNormal.setZero(); break; } default: { btAssert(0); } }; } } }
0
0.97159
1
0.97159
game-dev
MEDIA
0.969498
game-dev
0.997084
1
0.997084
mastercomfig/tf2-patches-old
76,143
src/game/client/replay/vgui/replayperformanceeditor.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #if defined( REPLAY_ENABLED ) #include "replayperformanceeditor.h" #include "replay/replay.h" #include "replay/ireplayperformanceeditor.h" #include "replay/ireplayperformancecontroller.h" #include "replay/performance.h" #include "ienginevgui.h" #include "iclientmode.h" #include "vgui_controls/ImagePanel.h" #include "vgui_controls/TextImage.h" #include "vgui_controls/Slider.h" #include "vgui_controls/Menu.h" #include "vgui/ILocalize.h" #include "vgui/IImage.h" #include "c_team.h" #include "vgui_avatarimage.h" #include "vgui/ISurface.h" #include "vgui/IInput.h" #include "replay/replaycamera.h" #include "replay/ireplaymanager.h" #include "replay/iclientreplaycontext.h" #include "confirm_dialog.h" #include "replayperformancesavedlg.h" #include "replay/irecordingsessionmanager.h" #include "achievementmgr.h" #include "c_playerresource.h" #include "replay/gamedefs.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> extern CAchievementMgr g_AchievementMgrTF; //----------------------------------------------------------------------------- using namespace vgui; //----------------------------------------------------------------------------- extern IReplayPerformanceController *g_pReplayPerformanceController; //----------------------------------------------------------------------------- // Hack-y global bool to communicate when we are rewinding for map load screens. // Order of operations issues preclude the use of engine->IsPlayingDemo(). bool g_bIsReplayRewinding = false; //----------------------------------------------------------------------------- // TODO: Make these archive? Right now, the tips are reset every time the game starts ConVar replay_perftip_count_enter( "replay_perftip_count_enter", "0", FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_HIDDEN, "", true, 0, false, 0 ); ConVar replay_perftip_count_exit( "replay_perftip_count_exit", "0", FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_HIDDEN, "", true, 0, false, 0 ); ConVar replay_perftip_count_freecam_enter( "replay_perftip_count_freecam_enter", "0", FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_HIDDEN, "", true, 0, false, 0 ); ConVar replay_perftip_count_freecam_exit( "replay_perftip_count_freecam_exit", "0", FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_HIDDEN, "", true, 0, false, 0 ); ConVar replay_perftip_count_freecam_exit2( "replay_perftip_count_freecam_exit2", "0", FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_HIDDEN, "", true, 0, false, 0 ); ConVar replay_editor_fov_mousewheel_multiplier( "replay_editor_fov_mousewheel_multiplier", "5", FCVAR_ARCHIVE | FCVAR_CLIENTDLL | FCVAR_DONTRECORD, "The multiplier on mousewheel input for adjusting camera FOV in the replay editor." ); ConVar replay_editor_fov_mousewheel_invert( "replay_editor_fov_mousewheel_invert", "0", FCVAR_ARCHIVE | FCVAR_CLIENTDLL | FCVAR_DONTRECORD, "Invert FOV zoom/unzoom on mousewheel in the replay editor." ); ConVar replay_replayeditor_rewindmsgcounter( "replay_replayeditor_rewindmsgcounter", "0", FCVAR_ARCHIVE | FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_HIDDEN, "" ); //----------------------------------------------------------------------------- #define MAX_TIP_DISPLAYS 1 //----------------------------------------------------------------------------- #define TIMESCALE_MIN 0.01f #define TIMESCALE_MAX 3.0f //----------------------------------------------------------------------------- #define SLIDER_RANGE_MAX 10000.0f //----------------------------------------------------------------------------- #define REPLAY_SOUND_DIALOG_POPUP "replay\\replaydialog_warn.wav" //----------------------------------------------------------------------------- static const char *gs_pCamNames[ NCAMS ] = { "free", "third", "first", "timescale", }; static const char *gs_pBaseComponentNames[ NCAMS ] = { "replay/replay_camera_%s%s", "replay/replay_camera_%s%s", "replay/replay_camera_%s%s", "replay/replay_%s%s", }; //----------------------------------------------------------------------------- void PlayDemo() { engine->ClientCmd_Unrestricted( "demo_resume" ); } void PauseDemo() { engine->ClientCmd_Unrestricted( "demo_pause" ); } //----------------------------------------------------------------------------- inline float SCurve( float t ) { t = clamp( t, 0.0f, 1.0f ); return t * t * (3 - 2*t); } inline float CubicEaseIn( float t ) { t = clamp( t, 0.0f, 1.0f ); return t * t * t; } inline float LerpScale( float flIn, float flInMin, float flInMax, float flOutMin, float flOutMax ) { float flDenom = flInMax - flInMin; if ( flDenom == 0.0f ) return 0.0f; float t = clamp( ( flIn - flInMin ) / flDenom, 0.0f, 1.0f ); return Lerp( t, flOutMin, flOutMax ); } //----------------------------------------------------------------------------- void HighlightTipWords( Label *pLabel ) { // Setup coloring - get # of words that should be highlighted wchar_t *pwNumWords = g_pVGuiLocalize->Find( "#Replay_PerfTip_Highlight_NumWords" ); if ( !pwNumWords ) return; // Get the current label text wchar_t wszLabelText[512]; pLabel->GetText( wszLabelText, sizeof( wszLabelText ) ); pLabel->GetTextImage()->ClearColorChangeStream(); pLabel->GetTextImage()->AddColorChange( pLabel->GetFgColor(), 0 ); int nNumWords = _wtoi( pwNumWords ); for ( int i = 0; i < nNumWords; ++i ) { char szWordFindStr[64]; V_snprintf( szWordFindStr, sizeof( szWordFindStr ), "#Replay_PerfTip_Highlight_Word%i", i ); wchar_t *pwWord = g_pVGuiLocalize->Find( szWordFindStr ); if ( !pwWord ) continue; const int nWordLen = wcslen( pwWord ); // Find any instance of the word in the label text and highlight it in red const wchar_t *p = wszLabelText; do { const wchar_t *pInst = wcsstr( p, pwWord ); if ( !pInst ) break; // Highlight the text int nStartPos = pInst - wszLabelText; int nEndPos = nStartPos + nWordLen; // If start pos is non-zero, clear color changes bool bChangeColor = true; if ( nStartPos == 0 ) { pLabel->GetTextImage()->ClearColorChangeStream(); } else if ( iswalpha( wszLabelText[ nStartPos - 1 ] ) ) { // If this is not the beginning of the string, check the previous character. If it's // not whitespace, etc, we found an instance of a keyword within another word. Skip. bChangeColor = false; } if ( bChangeColor ) { pLabel->GetTextImage()->AddColorChange( Color(200,80,60,255), nStartPos ); pLabel->GetTextImage()->AddColorChange( pLabel->GetFgColor(), nEndPos ); } p = pInst + nWordLen; } while ( 1 ); } } //----------------------------------------------------------------------------- class CSavingDialog : public CGenericWaitingDialog { DECLARE_CLASS_SIMPLE( CSavingDialog, CGenericWaitingDialog ); public: CSavingDialog( CReplayPerformanceEditorPanel *pEditorPanel ) : CGenericWaitingDialog( pEditorPanel ) { m_pEditorPanel = pEditorPanel; } virtual void OnTick() { BaseClass::OnTick(); if ( !g_pReplayPerformanceController ) return; // Update async save if ( g_pReplayPerformanceController->IsSaving() ) { g_pReplayPerformanceController->SaveThink(); } else { if ( m_pEditorPanel.Get() ) { m_pEditorPanel->OnSaveComplete(); } Close(); } } private: CConfirmDialog *m_pLoginDialog; vgui::DHANDLE< CReplayPerformanceEditorPanel > m_pEditorPanel; }; //----------------------------------------------------------------------------- class CReplayTipLabel : public Label { DECLARE_CLASS_SIMPLE( CReplayTipLabel, Label ); public: CReplayTipLabel( Panel *pParent, const char *pName, const char *pText ) : BaseClass( pParent, pName, pText ) { } virtual void ApplySchemeSettings( IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); HighlightTipWords( this ); } }; DECLARE_BUILD_FACTORY_DEFAULT_TEXT( CReplayTipLabel, Label ); //----------------------------------------------------------------------------- class CPerformanceTip : public EditablePanel { DECLARE_CLASS_SIMPLE( CPerformanceTip, EditablePanel ); public: static DHANDLE< CPerformanceTip > s_pTip; static CPerformanceTip *CreateInstance( const char *pText ) { if ( s_pTip ) { s_pTip->SetVisible( false ); s_pTip->MarkForDeletion(); s_pTip = NULL; } s_pTip = SETUP_PANEL( new CPerformanceTip( pText ) ); return s_pTip; } CPerformanceTip( const char *pText ) : BaseClass( g_pClientMode->GetViewport(), "Tip" ), m_flBornTime( gpGlobals->realtime ), m_flAge( 0.0f ), m_flShowDuration( 15.0f ) { m_pTextLabel = new CReplayTipLabel( this, "TextLabel", pText ); } virtual void OnThink() { // Delete the panel if life exceeded const float flEndTime = m_flBornTime + m_flShowDuration; if ( gpGlobals->realtime >= flEndTime ) { SetVisible( false ); MarkForDeletion(); s_pTip = NULL; return; } SetVisible( true ); const float flFadeDuration = .4f; float flAlpha; // Fade out? if ( gpGlobals->realtime >= flEndTime - flFadeDuration ) { flAlpha = LerpScale( gpGlobals->realtime, flEndTime - flFadeDuration, flEndTime, 1.0f, 0.0f ); } // Fade in? else if ( gpGlobals->realtime <= m_flBornTime + flFadeDuration ) { flAlpha = LerpScale( gpGlobals->realtime, m_flBornTime, m_flBornTime + flFadeDuration, 0.0f, 1.0f ); } // Otherwise, we must be in between fade in/fade out else { flAlpha = 1.0f; } SetAlpha( 255 * SCurve( flAlpha ) ); } virtual void ApplySchemeSettings( IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); LoadControlSettings( "resource/ui/replayperformanceeditor/tip.res", "GAME" ); // Center relative to parent const int nScreenW = ScreenWidth(); const int nScreenH = ScreenHeight(); int aContentSize[2]; m_pTextLabel->GetContentSize( aContentSize[0], aContentSize[1] ); const int nLabelHeight = aContentSize[1]; SetBounds( 0, 3 * nScreenH / 4 - nLabelHeight / 2, nScreenW, nLabelHeight + 2 * m_nTopBottomMargin ); m_pTextLabel->SetBounds( m_nLeftRightMarginWidth, m_nTopBottomMargin, nScreenW - 2 * m_nLeftRightMarginWidth, nLabelHeight ); } static void Cleanup() { if ( s_pTip ) { s_pTip->MarkForDeletion(); s_pTip = NULL; } } CPanelAnimationVarAliasType( int, m_nLeftRightMarginWidth, "left_right_margin", "0", "proportional_xpos" ); CPanelAnimationVarAliasType( int, m_nTopBottomMargin , "top_bottom_margin", "0", "proportional_ypos" ); CReplayTipLabel *m_pTextLabel; float m_flBornTime; float m_flAge; float m_flShowDuration; }; DHANDLE< CPerformanceTip > CPerformanceTip::s_pTip; // Display the performance tip if we haven't already displayed it nMaxTimesToDisplay times or more inline void DisplayPerformanceTip( const char *pText, ConVar* pCountCv = NULL, int nMaxTimesToDisplay = -1 ) { // Already displayed too many times? Get out. if ( pCountCv && nMaxTimesToDisplay >= 0 ) { int nCount = pCountCv->GetInt(); if ( nCount >= nMaxTimesToDisplay ) return; // Incremement count cvar pCountCv->SetValue( nCount + 1 ); } // Display the tip CPerformanceTip::CreateInstance( pText ); } //----------------------------------------------------------------------------- inline float GetPlaybackTime() { CReplay *pPlayingReplay = g_pReplayManager->GetPlayingReplay(); return gpGlobals->curtime - TICKS_TO_TIME( pPlayingReplay->m_nSpawnTick ); } //----------------------------------------------------------------------------- class CPlayerCell : public CExImageButton { DECLARE_CLASS_SIMPLE( CPlayerCell, CExImageButton ); public: CPlayerCell( Panel *pParent, const char *pName, int *pCurTargetPlayerIndex ) : CExImageButton( pParent, pName, "" ), m_iPlayerIndex( -1 ), m_pCurTargetPlayerIndex( pCurTargetPlayerIndex ) { } virtual void ApplySchemeSettings( IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); GetImage()->SetImage( "" ); SetFont( pScheme->GetFont( "ReplaySmall" ) ); SetContentAlignment( Label::a_center ); } MESSAGE_FUNC( DoClick, "PressButton" ) { ReplayCamera()->SetPrimaryTarget( m_iPlayerIndex ); *m_pCurTargetPlayerIndex = m_iPlayerIndex; float flCurTime = GetPlaybackTime(); extern IReplayPerformanceController *g_pReplayPerformanceController; g_pReplayPerformanceController->AddEvent_Camera_ChangePlayer( flCurTime, m_iPlayerIndex ); } int m_iPlayerIndex; int *m_pCurTargetPlayerIndex; // Allow the button to write current target in outer class when pressed }; //----------------------------------------------------------------------------- /* class CReplayEditorSlider : public Slider { DECLARE_CLASS_SIMPLE( CReplayEditorSlider, Slider ); public: CReplayEditorSlider( Panel *pParent, const char *pName ) : Slider( pParent, pName ) { } virtual void SetDefault( float flDefault ) { m_flDefault = flDefault; } ON_MESSAGE( Reset, OnReset ) { SetValue( } private: float m_flDefault; }; */ //----------------------------------------------------------------------------- class CCameraOptionsPanel : public EditablePanel { DECLARE_CLASS_SIMPLE( CCameraOptionsPanel, EditablePanel ); public: CCameraOptionsPanel( Panel *pParent, const char *pName, const char *pTitle ) : EditablePanel( pParent, pName ), m_bControlsAdded( false ) { m_pTitleLabel = new CExLabel( this, "TitleLabel", pTitle ); AddControlToLayout( m_pTitleLabel ); } ~CCameraOptionsPanel() { m_lstSliderInfos.PurgeAndDeleteElements(); } void AddControlToLayout( Panel *pControl ) { if ( pControl ) { m_lstControls.AddToTail( pControl ); pControl->SetMouseInputEnabled( true ); } } // NOTE: Default value is assumed to be stored in flOut void AddSliderToLayout( int nId, Slider *pSlider, const char *pLabelText, float flMinValue, float flMaxValue, float &flOut ) { SliderInfo_t *pNewSliderInfo = new SliderInfo_t; pNewSliderInfo->m_nId = nId; pNewSliderInfo->m_pSlider = pSlider; pNewSliderInfo->m_flRange[ 0 ] = flMinValue; pNewSliderInfo->m_flRange[ 1 ] = flMaxValue; pNewSliderInfo->m_flDefault = flOut; pNewSliderInfo->m_pValueOut = &flOut; m_lstSliderInfos.AddToTail( pNewSliderInfo ); AddControlToLayout( new EditablePanel( this, "Buffer" ) ); AddControlToLayout( NewLabel( pLabelText ) ); AddControlToLayout( NewSetDefaultButton( nId ) ); AddControlToLayout( pSlider ); pSlider->AddActionSignalTarget( this ); } void ResetSlider( int nId ) { const SliderInfo_t *pSliderInfo = FindSliderInfoFromId( nId ); if ( !pSliderInfo ) return; SetValue( pSliderInfo, pSliderInfo->m_flDefault ); } void SetValue( int nId, float flValue ) { const SliderInfo_t *pSliderInfo = FindSliderInfoFromId( nId ); if ( !pSliderInfo ) return; SetValue( pSliderInfo, flValue ); } virtual void ApplySchemeSettings( IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); // Setup border SetBorder( pScheme->GetBorder( "ButtonBorder" ) ); HFont hFont = pScheme->GetFont( "ReplayBrowserSmallest", true ); m_pTitleLabel->SetFont( hFont ); m_pTitleLabel->SizeToContents(); m_pTitleLabel->SetTall( YRES( 20 ) ); m_pTitleLabel->SetColorStr( "235 235 235 255" ); if ( !m_bControlsAdded ) { const char *pResFile = GetResFile(); if ( pResFile ) { LoadControlSettings( pResFile, "GAME" ); } AddControls(); m_bControlsAdded = true; } FOR_EACH_LL( m_lstSliderInfos, it ) { SliderInfo_t *pInfo = m_lstSliderInfos[ it ]; Slider *pSlider = pInfo->m_pSlider; pSlider->SetRange( 0, SLIDER_RANGE_MAX ); pSlider->SetNumTicks( 10 ); float flDenom = fabs( pInfo->m_flRange[1] - pInfo->m_flRange[0] ); pSlider->SetValue( SLIDER_RANGE_MAX * fabs( pInfo->m_flDefault - pInfo->m_flRange[0] ) / flDenom ); } } virtual void PerformLayout() { BaseClass::PerformLayout(); int nWidth = XRES( 140 ); int nMargins[2] = { (int)XRES( 5 ), (int)YRES( 5 ) }; int nVBuf = YRES( 0 ); int nLastY = -1; int nY = nMargins[1]; Panel *pPrevPanel = NULL; int nLastCtrlHeight = 0; FOR_EACH_LL( m_lstControls, i ) { Panel *pPanel = m_lstControls[ i ]; if ( !pPanel->IsVisible() ) continue; int aPos[2]; pPanel->GetPos( aPos[0], aPos[1] ); if ( pPrevPanel && aPos[1] >= 0 ) { nY += pPrevPanel->GetTall() + nVBuf; } // Gross hack to see if the control is a default button if ( dynamic_cast< CExButton * >( pPanel ) ) { pPanel->SetWide( XRES( 36 ) ); pPanel->SetPos( pPrevPanel ? ( GetWide() - nMargins[0] - pPanel->GetWide() ) : 0, nLastY ); } else { pPanel->SetWide( nWidth - 2 * nMargins[0] ); pPanel->SetPos( nMargins[0], nY ); } nLastY = nY; pPrevPanel = pPanel; nLastCtrlHeight = MAX( nLastCtrlHeight, pPanel->GetTall() ); } SetSize( nWidth, nY + nLastCtrlHeight + 2 * YRES( 3 ) ); } virtual void OnCommand( const char *pCommand ) { if ( !V_strnicmp( pCommand, "reset_", 6 ) ) { const int nSliderInfoId = atoi( pCommand + 6 ); ResetSlider( nSliderInfoId ); } else { BaseClass::OnCommand( pCommand ); } } Label *NewLabel( const char *pText ) { Label *pLabel = new Label( this, "Label", pText ); pLabel->SetTall( YRES( 9 ) ); pLabel->SetPos( -1, 0 ); // Use default x and accumulated y // Set font IScheme *pScheme = vgui::scheme()->GetIScheme( GetScheme() ); HFont hFont = pScheme->GetFont( "DefaultVerySmall", true ); pLabel->SetFont( hFont ); return pLabel; } CExButton *NewSetDefaultButton( int nSliderInfoId ) { CExButton *pButton = new CExButton( this, "DefaultButton", "#Replay_SetDefaultSetting" ); pButton->SetTall( YRES( 11 ) ); pButton->SetPos( XRES( 30 ), -1 ); // Set y to -1 so it will stay on the same line pButton->SetContentAlignment( Label::a_center ); CFmtStr fmtResetCommand( "reset_%i", nSliderInfoId ); pButton->SetCommand( fmtResetCommand.Access() ); pButton->AddActionSignalTarget( this ); // Set font IScheme *pScheme = vgui::scheme()->GetIScheme( GetScheme() ); HFont hFont = pScheme->GetFont( "DefaultVerySmall", true ); pButton->SetFont( hFont ); return pButton; } protected: MESSAGE_FUNC_PARAMS( OnSliderMoved, "SliderMoved", pParams ) { Panel *pSlider = (Panel *)pParams->GetPtr( "panel" ); float flPercent = pParams->GetInt( "position" ) / SLIDER_RANGE_MAX; FOR_EACH_LL( m_lstSliderInfos, it ) { SliderInfo_t *pInfo = m_lstSliderInfos[ it ]; if ( pSlider == pInfo->m_pSlider ) { *pInfo->m_pValueOut = Lerp( flPercent, pInfo->m_flRange[0], pInfo->m_flRange[1] ); } } } virtual const char *GetResFile() { return NULL; } virtual void AddControls() { } struct SliderInfo_t { Slider *m_pSlider; float m_flRange[2]; float m_flDefault; int m_nId; float *m_pValueOut; }; const SliderInfo_t *FindSliderInfoFromId( int nId ) { FOR_EACH_LL( m_lstSliderInfos, it ) { SliderInfo_t *pInfo = m_lstSliderInfos[ it ]; if ( pInfo->m_nId == nId ) return pInfo; } AssertMsg( 0, "Should always find a slider here." ); return NULL; } void SetValue( const SliderInfo_t *pSliderInfo, float flValue ) { if ( !pSliderInfo ) { AssertMsg( 0, "This should not happen." ); return; } // Calculate the range const float flRange = fabs( pSliderInfo->m_flRange[1] - pSliderInfo->m_flRange[0] ); AssertMsg( flRange > 0, "Bad slider range!" ); // Calculate the percentile based on the specified value and the range. const float flPercent = fabs( flValue - pSliderInfo->m_flRange[0] ) / flRange; pSliderInfo->m_pSlider->SetValue( flPercent * SLIDER_RANGE_MAX, true ); } CUtlLinkedList< Panel * > m_lstControls; CUtlLinkedList< SliderInfo_t *, int > m_lstSliderInfos; CExLabel *m_pTitleLabel; bool m_bControlsAdded; }; //----------------------------------------------------------------------------- class CTimeScaleOptionsPanel : public CCameraOptionsPanel { DECLARE_CLASS_SIMPLE( CTimeScaleOptionsPanel, CCameraOptionsPanel ); public: CTimeScaleOptionsPanel( Panel *pParent, float *pTimeScaleProxy ) : BaseClass( pParent, "TimeScaleSettings", "#Replay_TimeScale" ), m_pTimeScaleSlider( NULL ), m_pTimeScaleProxy( pTimeScaleProxy ) { } virtual const char *GetResFile() { return "resource/ui/replayperformanceeditor/settings_timescale.res"; } virtual void AddControls() { m_pTimeScaleSlider = dynamic_cast< Slider * >( FindChildByName( "TimeScaleSlider" ) ); AddSliderToLayout( SLIDER_TIMESCALE, m_pTimeScaleSlider, "#Replay_Scale", TIMESCALE_MIN, TIMESCALE_MAX, *m_pTimeScaleProxy ); } enum FreeCamSliders_t { SLIDER_TIMESCALE, }; Slider *m_pTimeScaleSlider; float *m_pTimeScaleProxy; }; //----------------------------------------------------------------------------- class CCameraOptionsPanel_Free : public CCameraOptionsPanel { DECLARE_CLASS_SIMPLE( CCameraOptionsPanel_Free, CCameraOptionsPanel ); public: CCameraOptionsPanel_Free( Panel *pParent ) : BaseClass( pParent, "FreeCameraSettings", "#Replay_FreeCam" ), m_pAccelSlider( NULL ), m_pSpeedSlider( NULL ), m_pFovSlider( NULL ), m_pRotFilterSlider( NULL ), m_pShakeSpeedSlider( NULL ), m_pShakeAmountSlider( NULL ) { } virtual const char *GetResFile() { return "resource/ui/replayperformanceeditor/camsettings_free.res"; } virtual void AddControls() { m_pAccelSlider = dynamic_cast< Slider * >( FindChildByName( "AccelSlider" ) ); m_pSpeedSlider = dynamic_cast< Slider * >( FindChildByName( "SpeedSlider" ) ); m_pFovSlider = dynamic_cast< Slider * >( FindChildByName( "FovSlider" ) ); m_pRotFilterSlider = dynamic_cast< Slider * >( FindChildByName( "RotFilterSlider" ) ); m_pShakeSpeedSlider = dynamic_cast< Slider * >( FindChildByName( "ShakeSpeedSlider" ) ); m_pShakeAmountSlider = dynamic_cast< Slider * >( FindChildByName( "ShakeAmountSlider" ) ); m_pShakeDirSlider = dynamic_cast< Slider * >( FindChildByName( "ShakeDirSlider" ) ); AddSliderToLayout( SLIDER_ACCEL, m_pAccelSlider, "#Replay_Accel", FREE_CAM_ACCEL_MIN, FREE_CAM_ACCEL_MAX, ReplayCamera()->m_flRoamingAccel ); AddSliderToLayout( SLIDER_SPEED, m_pSpeedSlider, "#Replay_Speed", FREE_CAM_SPEED_MIN, FREE_CAM_SPEED_MAX, ReplayCamera()->m_flRoamingSpeed ); AddSliderToLayout( SLIDER_FOV, m_pFovSlider, "#Replay_Fov", FREE_CAM_FOV_MIN, FREE_CAM_FOV_MAX, ReplayCamera()->m_flRoamingFov[1] ); AddSliderToLayout( SLIDER_ROTFILTER, m_pRotFilterSlider, "#Replay_RotFilter", FREE_CAM_ROT_FILTER_MIN, FREE_CAM_ROT_FILTER_MAX, ReplayCamera()->m_flRoamingRotFilterFactor ); AddSliderToLayout( SLIDER_SHAKE_SPEED, m_pShakeSpeedSlider, "#Replay_ShakeSpeed", FREE_CAM_SHAKE_SPEED_MIN, FREE_CAM_SHAKE_SPEED_MAX, ReplayCamera()->m_flRoamingShakeSpeed ); AddSliderToLayout( SLIDER_SHAKE_AMOUNT, m_pShakeAmountSlider, "#Replay_ShakeAmount", FREE_CAM_SHAKE_AMOUNT_MIN, FREE_CAM_SHAKE_AMOUNT_MAX, ReplayCamera()->m_flRoamingShakeAmount ); AddSliderToLayout( SLIDER_SHAKE_DIR, m_pShakeDirSlider, "#Replay_ShakeDir", FREE_CAM_SHAKE_DIR_MIN, FREE_CAM_SHAKE_DIR_MAX, ReplayCamera()->m_flRoamingShakeDir ); } enum FreeCamSliders_t { SLIDER_ACCEL, SLIDER_SPEED, SLIDER_FOV, SLIDER_ROTFILTER, SLIDER_SHAKE_SPEED, SLIDER_SHAKE_AMOUNT, SLIDER_SHAKE_DIR, }; Slider *m_pAccelSlider; Slider *m_pSpeedSlider; Slider *m_pFovSlider; Slider *m_pRotFilterSlider; Slider *m_pShakeSpeedSlider; Slider *m_pShakeAmountSlider; Slider *m_pShakeDirSlider; }; //----------------------------------------------------------------------------- class CReplayButton : public CExImageButton { DECLARE_CLASS_SIMPLE( CReplayButton, CExImageButton ); public: CReplayButton( Panel *pParent, const char *pName, const char *pText ) : BaseClass( pParent, pName, pText ), m_pTipText( NULL ) { } virtual void ApplySettings( KeyValues *pInResourceData ) { BaseClass::ApplySettings( pInResourceData ); const char *pTipName = pInResourceData->GetString( "tipname" ); if ( pTipName && pTipName[0] ) { const wchar_t *pTipText = g_pVGuiLocalize->Find( pTipName ); if ( pTipText && pTipText[0] ) { const int nTipLength = V_wcslen( pTipText ); m_pTipText = new wchar_t[ nTipLength + 1 ]; V_wcsncpy( m_pTipText, pTipText, sizeof(wchar_t) * ( nTipLength + 1 ) ); m_pTipText[ nTipLength ] = L'\0'; } } } virtual void OnCursorEntered() { BaseClass::OnCursorEntered(); CReplayPerformanceEditorPanel *pEditor = ReplayUI_GetPerformanceEditor(); if ( pEditor && m_pTipText ) { pEditor->SetButtonTip( m_pTipText, this ); pEditor->ShowButtonTip( true ); } } virtual void OnCursorExited() { BaseClass::OnCursorExited(); CReplayPerformanceEditorPanel *pEditor = ReplayUI_GetPerformanceEditor(); if ( pEditor && m_pTipText ) { pEditor->ShowButtonTip( false ); } } private: wchar_t *m_pTipText; }; DECLARE_BUILD_FACTORY_DEFAULT_TEXT( CReplayButton, CExImageButton ); //----------------------------------------------------------------------------- #define MAX_FF_RAMP_TIME 8.0f // The amount of time until we ramp to max scale value. class CReplayEditorFastForwardButton : public CReplayButton { DECLARE_CLASS_SIMPLE( CReplayEditorFastForwardButton, CReplayButton ); public: CReplayEditorFastForwardButton( Panel *pParent, const char *pName, const char *pText ) : BaseClass( pParent, pName, pText ), m_flPressTime( 0.0f ) { m_pHostTimescale = cvar->FindVar( "host_timescale" ); AssertMsg( m_pHostTimescale, "host_timescale lookup failed!" ); ivgui()->AddTickSignal( GetVPanel(), 10 ); } ~CReplayEditorFastForwardButton() { ivgui()->RemoveTickSignal( GetVPanel() ); // Avoid a non-1.0 host_timescale after replay edit, which can happen if // the user is still holding downt he FF button at the end of the replay. if ( m_pHostTimescale ) { m_pHostTimescale->SetValue( 1.0f ); } // Resume demo playback so that any demo played later won't start paused. PlayDemo(); } virtual void OnMousePressed( MouseCode code ) { m_flPressTime = gpGlobals->realtime; PlayDemo(); BaseClass::OnMousePressed( code ); } virtual void OnMouseReleased( MouseCode code ) { m_flPressTime = 0.0f; PauseDemo(); BaseClass::OnMouseReleased( code ); } void OnTick() { float flScale; if ( m_flPressTime == 0.0f ) { flScale = 1.0f; } else { const float flElapsed = clamp( gpGlobals->realtime - m_flPressTime, 0.0f, MAX_FF_RAMP_TIME ); const float t = CubicEaseIn( flElapsed / MAX_FF_RAMP_TIME ); // If a shift key is down... if ( input()->IsKeyDown( KEY_LSHIFT ) || input()->IsKeyDown( KEY_RSHIFT ) ) { // ...slow down host_timescale. flScale = .1f + .4f * t; } // If alt key down... else if ( input()->IsKeyDown( KEY_LALT ) || input()->IsKeyDown( KEY_RALT ) ) { // ...FF very quickly, ramp from 5 to 10. flScale = 5.0f + 5.0f * t; } else { // Otherwise, start at 1.5 and ramp upwards over time. flScale = 1.5f + 3.5f * t; } } // Set host_timescale. if ( m_pHostTimescale ) { m_pHostTimescale->SetValue( flScale ); } } private: float m_flPressTime; ConVar *m_pHostTimescale; }; DECLARE_BUILD_FACTORY_DEFAULT_TEXT( CReplayEditorFastForwardButton, CExImageButton ); //----------------------------------------------------------------------------- class CRecLightPanel : public EditablePanel { DECLARE_CLASS_SIMPLE( CRecLightPanel, vgui::EditablePanel ); public: CRecLightPanel( Panel *pParent ) : EditablePanel( pParent, "RecLightPanel" ), m_flPlayPauseTime( 0.0f ), m_bPaused( false ), m_bPerforming( false ) { m_pRecLights[ 0 ] = NULL; m_pRecLights[ 1 ] = NULL; m_pPlayPause[ 0 ] = NULL; m_pPlayPause[ 1 ] = NULL; } virtual void ApplySchemeSettings( IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); LoadControlSettings( "resource/ui/replayperformanceeditor/reclight.res", "GAME" ); m_pRecLights[ 0 ] = dynamic_cast< ImagePanel * >( FindChildByName( "RecLightOffImg" ) ); m_pRecLights[ 1 ] = dynamic_cast< ImagePanel * >( FindChildByName( "RecLightOnImg" ) ); m_pPlayPause[ 0 ] = dynamic_cast< ImagePanel * >( FindChildByName( "PlayImg" ) ); m_pPlayPause[ 1 ] = dynamic_cast< ImagePanel * >( FindChildByName( "PauseImg" ) ); m_pCameraFringe = dynamic_cast< ImagePanel *>( FindChildByName( "CameraFringe" ) ); m_pCameraCrosshair = dynamic_cast< ImagePanel *>( FindChildByName( "CameraCrosshair" ) ); } virtual void PerformLayout() { BaseClass::PerformLayout(); SetVisible( m_bPerforming ); const int nScreenWidth = ScreenWidth(); const int nRecLightW = m_pRecLights[ 0 ]->GetWide(); int nXPos = nScreenWidth - nRecLightW + XRES( 6 ); int nYPos = -YRES( 8 ); m_pRecLights[ 0 ]->SetPos( nXPos, nYPos ); m_pRecLights[ 1 ]->SetPos( nXPos, nYPos ); const int nWidth = GetWide(); const int nHeight = GetTall(); // Setup camera fringe height if ( m_pCameraFringe ) { m_pCameraFringe->SetSize( nWidth, nHeight ); m_pCameraFringe->InstallMouseHandler( this ); } // Setup camera cross hair height if ( m_pCameraCrosshair ) { int aImageSize[2]; IImage *pImage = m_pCameraCrosshair->GetImage(); pImage->GetSize( aImageSize[0], aImageSize[1] ); aImageSize[0] = m_pCameraCrosshair->GetWide(); aImageSize[1] = m_pCameraCrosshair->GetTall(); const int nStartY = YRES( 13 ); m_pCameraCrosshair->SetBounds( nStartY + ( nWidth - aImageSize[0] ) / 2, nStartY + ( nHeight - aImageSize[1] ) / 2, aImageSize[0] - 2 * nStartY, aImageSize[1] - 2 * nStartY ); m_pCameraCrosshair->InstallMouseHandler( this ); } } void UpdateBackgroundVisibility() { m_pCameraCrosshair->SetVisible( m_bPaused ); m_pCameraFringe->SetVisible( m_bPaused ); } virtual void OnThink() { const float flTime = gpGlobals->realtime; bool bPauseAnimating = m_flPlayPauseTime > 0.0f && flTime >= m_flPlayPauseTime && flTime < ( m_flPlayPauseTime + m_flAnimTime ); // Setup light visibility int nOnOff = fmod( flTime * 2.0f, 2.0f ); bool bOnLightVisible = (bool)nOnOff; bool bRecording = g_pReplayPerformanceController->IsRecording(); m_pRecLights[ 0 ]->SetVisible( m_bPaused || ( bRecording && !bOnLightVisible ) ); m_pRecLights[ 1 ]->SetVisible( bRecording && ( !m_bPaused && bOnLightVisible ) ); // Deal with fringe and crosshair vis UpdateBackgroundVisibility(); int iPlayPauseActive = (int)m_bPaused; // Animate the pause icon if ( bPauseAnimating ) { const float t = clamp( ( flTime - m_flPlayPauseTime ) / m_flAnimTime, 0.0f, 1.0f ); const float s = SCurve( t ); const int nSize = (int)Lerp( s, 60.0f, 60.0f * m_nAnimScale ); int aCrossHairPos[2]; m_pCameraCrosshair->GetPos( aCrossHairPos[0], aCrossHairPos[1] ); const int nScreenXCenter = aCrossHairPos[0] + m_pCameraCrosshair->GetWide() / 2; const int nScreenYCenter = aCrossHairPos[1] + m_pCameraCrosshair->GetTall() / 2; m_pPlayPause[ iPlayPauseActive ]->SetBounds( nScreenXCenter - nSize / 2, nScreenYCenter - nSize / 2, nSize, nSize ); m_pPlayPause[ iPlayPauseActive ]->SetAlpha( (int)( MIN( 0.5f, 1.0f - s ) * 255) ); } m_pPlayPause[ iPlayPauseActive ]->SetVisible( bPauseAnimating ); m_pPlayPause[ !iPlayPauseActive ]->SetVisible( false ); } void UpdatePauseState( bool bPaused ) { if ( bPaused == m_bPaused ) return; m_bPaused = bPaused; m_flPlayPauseTime = gpGlobals->realtime; } void SetPerforming( bool bPerforming ) { if ( bPerforming == m_bPerforming ) return; m_bPerforming = bPerforming; InvalidateLayout( true, false ); } float m_flPlayPauseTime; bool m_bPaused; bool m_bPerforming; ImagePanel *m_pPlayPause[2]; // 0=play, 1=pause ImagePanel *m_pRecLights[2]; // 0=off, 1=on ImagePanel *m_pCameraFringe; ImagePanel *m_pCameraCrosshair; CPanelAnimationVar( int, m_nAnimScale, "anim_scale", "4" ); CPanelAnimationVar( float, m_flAnimTime, "anim_time", "1.5" ); }; //----------------------------------------------------------------------------- CReplayPerformanceEditorPanel::CReplayPerformanceEditorPanel( Panel *parent, ReplayHandle_t hReplay ) : EditablePanel( parent, "ReplayPerformanceEditor" ), m_hReplay( hReplay ), m_flLastTime( -1 ), m_nRedBlueLabelRightX( 0 ), m_nBottomPanelStartY( 0 ), m_nBottomPanelHeight( 0 ), m_nLastRoundedTime( -1 ), m_flSpaceDownStart( 0.0f ), m_flOldFps( -1.0f ), m_flLastTimeSpaceBarPressed( 0.0f ), m_flActiveTimeInEditor( 0.0f ), m_flTimeScaleProxy( 1.0f ), m_iCameraSelection( CAM_FIRST ), m_bMousePressed( false ), m_bMouseDown( false ), m_nMouseClickedOverCameraSettingsPanel( CAM_INVALID ), m_bShownAtLeastOnce( false ), m_bAchievementAwarded( false ), m_pImageList( NULL ), m_pCurTimeLabel( NULL ), m_pTotalTimeLabel( NULL ), m_pPlayerNameLabel( NULL ), m_pMouseTargetPanel( NULL ), m_pSlowMoButton( NULL ), m_pRecLightPanel( NULL ), m_pPlayerCellData( NULL ), m_pBottom( NULL ), m_pMenuButton( NULL ), m_pMenu( NULL ), m_pPlayerCellsPanel( NULL ), m_pButtonTip( NULL ), m_pSavingDlg( NULL ) { V_memset( m_pCameraButtons, 0, sizeof( m_pCameraButtons ) ); V_memset( m_pCtrlButtons, 0, sizeof( m_pCtrlButtons ) ); V_memset( m_pCameraOptionsPanels, NULL, sizeof( m_pCameraOptionsPanels ) ); m_pCameraOptionsPanels[ CAM_FREE ] = new CCameraOptionsPanel_Free( this ); m_pCameraOptionsPanels[ COMPONENT_TIMESCALE ] = new CTimeScaleOptionsPanel( this, &m_flTimeScaleProxy ); m_nRedBlueSigns[0] = -1; m_nRedBlueSigns[1] = 1; m_iCurPlayerTarget = -1; m_bCurrentTargetNeedsVisibilityUpdate = false; m_pImageList = new ImageList( false ); SetParent( g_pClientMode->GetViewport() ); HScheme hScheme = scheme()->LoadSchemeFromFileEx( enginevgui->GetPanel( PANEL_CLIENTDLL ), "resource/ClientScheme.res", "ClientScheme" ); SetScheme( hScheme ); ivgui()->AddTickSignal( GetVPanel(), 16 ); // Roughly 60hz MakePopup( true ); SetMouseInputEnabled( true ); // Create bottom m_pBottom = new EditablePanel( this, "BottomPanel" ); // Add player cells m_pPlayerCellsPanel = new EditablePanel( m_pBottom, "PlayerCellsPanel" ); for ( int i = 0; i < 2; ++i ) { for ( int j = 0; j <= MAX_PLAYERS; ++j ) { m_pPlayerCells[i][j] = new CPlayerCell( m_pPlayerCellsPanel, "PlayerCell", &m_iCurPlayerTarget ); m_pPlayerCells[i][j]->SetVisible( false ); AddPanelKeyboardInputDisableList( m_pPlayerCells[i][j] ); } } // Create rec light panel m_pRecLightPanel = SETUP_PANEL( new CRecLightPanel( g_pClientMode->GetViewport() ) ); // Display "enter performance mode" tip DisplayPerformanceTip( "#Replay_PerfTip_EnterPerfMode", &replay_perftip_count_enter, MAX_TIP_DISPLAYS ); // Create menu m_pMenu = new Menu( this, "Menu" ); m_aMenuItemIds[ MENU_SAVE ] = m_pMenu->AddMenuItem( "#Replay_Save", "menu_save", this ); m_aMenuItemIds[ MENU_SAVEAS ] = m_pMenu->AddMenuItem( "#Replay_SaveAs", "menu_saveas", this ); m_pMenu->AddSeparator(); m_aMenuItemIds[ MENU_EXIT ] = m_pMenu->AddMenuItem( "#Replay_Exit", "menu_exit", this ); m_pMenu->EnableUseMenuManager( false ); // The menu manager doesn't play nice with the menu button } CReplayPerformanceEditorPanel::~CReplayPerformanceEditorPanel() { m_pRecLightPanel->MarkForDeletion(); m_pRecLightPanel = NULL; m_pButtonTip->MarkForDeletion(); m_pButtonTip = NULL; g_bIsReplayRewinding = false; surface()->PlaySound( "replay\\performanceeditorclosed.wav" ); CPerformanceTip::Cleanup(); ClearPlayerCellData(); } void CReplayPerformanceEditorPanel::ClearPlayerCellData() { if ( m_pPlayerCellData ) { m_pPlayerCellData->deleteThis(); m_pPlayerCellData = NULL; } } void CReplayPerformanceEditorPanel::AddPanelKeyboardInputDisableList( Panel *pPanel ) { m_lstDisableKeyboardInputPanels.AddToTail( pPanel ); } void CReplayPerformanceEditorPanel::ApplySchemeSettings( IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); LoadControlSettings( "resource/ui/replayperformanceeditor/main.res", "GAME" ); m_lstDisableKeyboardInputPanels.RemoveAll(); int nParentWidth = GetParent()->GetWide(); int nParentHeight = GetParent()->GetTall(); // Set size of this panel SetSize( nParentWidth, nParentHeight ); // Layout bottom if ( m_pBottom ) { m_nBottomPanelHeight = m_pBottom->GetTall(); // Get from .res m_nBottomPanelStartY = nParentHeight - m_nBottomPanelHeight; m_pBottom->SetBounds( 0, m_nBottomPanelStartY, nParentWidth, m_nBottomPanelHeight ); } // Layout rec light panel - don't overlap bottom panel m_pRecLightPanel->SetBounds( 0, 0, ScreenWidth(), m_nBottomPanelStartY ); // Setup camera buttons const int nNumCameraButtons = NCAMS; const char *pCameraButtonNames[nNumCameraButtons] = { "CameraFree", "CameraThird", "CameraFirst", "TimeScaleButton" }; int nCurButtonX = nParentWidth - m_nRightMarginWidth; int nLeftmostCameraButtonX = 0; for ( int i = 0; i < nNumCameraButtons; ++i ) { m_pCameraButtons[i] = dynamic_cast< CExImageButton * >( FindChildByName( pCameraButtonNames[ i ] ) ); if ( m_pCameraButtons[i] ) { CExImageButton *pCurButton = m_pCameraButtons[ i ]; if ( !pCurButton ) continue; nCurButtonX -= pCurButton->GetWide(); int nX, nY; pCurButton->GetPos( nX, nY ); pCurButton->SetPos( nCurButtonX, nY ); pCurButton->SetParent( m_pBottom ); pCurButton->AddActionSignalTarget( this ); #if !defined( TF_CLIENT_DLL ) pCurButton->SetPaintBorderEnabled( false ); #endif AddPanelKeyboardInputDisableList( pCurButton ); } } nLeftmostCameraButtonX = nCurButtonX; static const char *s_pControlButtonNames[NUM_CTRLBUTTONS] = { "InButton", "GotoBeginningButton", "RewindButton", "PlayButton", "FastForwardButton", "GotoEndButton", "OutButton" }; for ( int i = 0; i < NUM_CTRLBUTTONS; ++i ) { CExImageButton *pCurButton = dynamic_cast< CExImageButton * >( FindChildByName( s_pControlButtonNames[ i ] ) ); Assert( pCurButton ); if ( !pCurButton ) continue; pCurButton->SetParent( m_pBottom ); pCurButton->AddActionSignalTarget( this ); AddPanelKeyboardInputDisableList( pCurButton ); #if !defined( TF_CLIENT_DLL ) pCurButton->SetPaintBorderEnabled( false ); #endif m_pCtrlButtons[ i ] = pCurButton; } // If the performance in tick is set, highlight the in point button { CReplayPerformance *pSavedPerformance = GetSavedPerformance(); m_pCtrlButtons[ CTRLBUTTON_IN ]->SetSelected( pSavedPerformance && pSavedPerformance->HasInTick() ); m_pCtrlButtons[ CTRLBUTTON_OUT ]->SetSelected( pSavedPerformance && pSavedPerformance->HasOutTick() ); } // Select first-person camera by default. UpdateCameraSelectionPosition( CAM_FIRST ); // Position time label m_pCurTimeLabel = dynamic_cast< CExLabel * >( FindChildByName( "CurTimeLabel" ) ); m_pTotalTimeLabel = dynamic_cast< CExLabel * >( FindChildByName( "TotalTimeLabel" ) ); m_pCurTimeLabel->SetParent( m_pBottom ); m_pTotalTimeLabel->SetParent( m_pBottom ); // Get player name label m_pPlayerNameLabel = dynamic_cast< CExLabel * >( FindChildByName( "PlayerNameLabel" ) ); // Get mouse target panel m_pMouseTargetPanel = dynamic_cast< EditablePanel * >( FindChildByName( "MouseTargetPanel" ) ); for ( int i = 0; i < 2; ++i ) { for ( int j = 0; j <= MAX_PLAYERS; ++j ) { m_pPlayerCells[i][j]->SetMouseInputEnabled( true ); } } // Get menu button m_pMenuButton = dynamic_cast< CExImageButton * >( FindChildByName( "MenuButton" ) ); AddPanelKeyboardInputDisableList( m_pMenuButton ); m_pMenuButton->SetMouseInputEnabled( true ); #if !defined( TF_CLIENT_DLL ) m_pMenuButton->SetPaintBorderEnabled( false ); #endif // Get button tip m_pButtonTip = dynamic_cast< CReplayTipLabel * >( FindChildByName( "ButtonTip" ) ); m_pButtonTip->SetParent( g_pClientMode->GetViewport() ); } static void Replay_GotoTick( bool bConfirmed, void *pContext ) { if ( bConfirmed ) { int nGotoTick = (int)pContext; CFmtStr fmtCmd( "demo_gototick %i\ndemo_pause\n", nGotoTick ); engine->ClientCmd_Unrestricted( fmtCmd.Access() ); } } void CReplayPerformanceEditorPanel::OnSliderMoved( KeyValues *pParams ) { } void CReplayPerformanceEditorPanel::OnInGameMouseWheelEvent( int nDelta ) { HandleMouseWheel( nDelta ); } void CReplayPerformanceEditorPanel::HandleMouseWheel( int nDelta ) { if ( ReplayCamera()->GetMode() == OBS_MODE_ROAMING ) { // Invert mousewheel input if necessary if ( replay_editor_fov_mousewheel_invert.GetBool() ) { nDelta *= -1; } float &flFov = ReplayCamera()->m_flRoamingFov[1]; flFov = clamp( flFov - nDelta * replay_editor_fov_mousewheel_multiplier.GetFloat(), FREE_CAM_FOV_MIN, FREE_CAM_FOV_MAX ); // Update FOV slider in free camera settings CCameraOptionsPanel_Free *pFreeCamOptions = static_cast< CCameraOptionsPanel_Free * >( m_pCameraOptionsPanels[ CAM_FREE ] ); pFreeCamOptions->m_pFovSlider->SetValue( flFov - FREE_CAM_FOV_MIN, false ); } } void CReplayPerformanceEditorPanel::ApplySettings( KeyValues *pInResourceData ) { BaseClass::ApplySettings( pInResourceData ); ClearPlayerCellData(); KeyValues *pPlayerCellData = pInResourceData->FindKey( "PlayerCell" ); if ( pPlayerCellData ) { m_pPlayerCellData = new KeyValues( "PlayerCell" ); pPlayerCellData->CopySubkeys( m_pPlayerCellData ); } } CameraMode_t CReplayPerformanceEditorPanel::IsMouseOverActiveCameraOptionsPanel( int nMouseX, int nMouseY ) { // In one of the camera options panels? for ( int i = 0; i < NCAMS; ++i ) { CCameraOptionsPanel *pCurPanel = m_pCameraOptionsPanels[ i ]; if ( pCurPanel && pCurPanel->IsVisible() && pCurPanel->IsWithin( nMouseX, nMouseY ) ) return (CameraMode_t)i; } return CAM_INVALID; } void CReplayPerformanceEditorPanel::OnMouseWheeled( int nDelta ) { HandleMouseWheel( nDelta ); } void CReplayPerformanceEditorPanel::OnTick() { BaseClass::OnTick(); // engine->Con_NPrintf( 0, "timescale: %f", g_pReplayPerformanceController->GetPlaybackTimeScale() ); C_ReplayCamera *pCamera = ReplayCamera(); if ( !pCamera ) return; // Calc elapsed time float flElapsed = gpGlobals->realtime - m_flLastTime; m_flLastTime = gpGlobals->realtime; // If this is the first time we're running and camera is valid, get primary target if ( m_iCurPlayerTarget < 0 ) { m_iCurPlayerTarget = pCamera->GetPrimaryTargetIndex(); } // NOTE: Third-person is not "controllable" yet int nCameraMode = pCamera->GetMode(); bool bInAControllableCameraMode = nCameraMode == OBS_MODE_ROAMING || nCameraMode == OBS_MODE_CHASE; // Get mouse cursor pos int nMouseX, nMouseY; input()->GetCursorPos( nMouseX, nMouseY ); // Toggle in and out of camera control if appropriate // Mouse pressed? bool bMouseDown = input()->IsMouseDown( MOUSE_LEFT ); m_bMousePressed = bMouseDown && !m_bMouseDown; m_bMouseDown = bMouseDown; // Reset this flag if mouse is no longer down if ( !m_bMouseDown ) { m_nMouseClickedOverCameraSettingsPanel = CAM_INVALID; } bool bNoDialogsUp = TFModalStack()->IsEmpty(); bool bMouseCursorOverPerfEditor = nMouseY >= m_nBottomPanelStartY; bool bMouseOverMenuButton = m_pMenuButton->IsWithin( nMouseX, nMouseY ); bool bMouseOverMenu = m_pMenu->IsWithin( nMouseX, nMouseY ); bool bRecording = g_pReplayPerformanceController->IsRecording(); if ( IsVisible() && m_bMousePressed ) { CameraMode_t nActiveOptionsPanel = IsMouseOverActiveCameraOptionsPanel( nMouseX, nMouseY ); if ( nActiveOptionsPanel != CAM_INVALID ) { m_nMouseClickedOverCameraSettingsPanel = nActiveOptionsPanel; } else if ( m_pMenu->IsVisible() && !m_pMenu->IsWithin( nMouseX, nMouseY ) ) { ToggleMenu(); } else if ( bInAControllableCameraMode && !bMouseCursorOverPerfEditor && !bMouseOverMenuButton && !bMouseOverMenu && bNoDialogsUp ) { if ( bRecording ) { bool bMouseInputEnabled = IsMouseInputEnabled(); // Already in a controllable camera mode? if ( bMouseInputEnabled ) { DisplayPerformanceTip( "#Replay_PerfTip_ExitFreeCam", &replay_perftip_count_freecam_exit, MAX_TIP_DISPLAYS ); surface()->PlaySound( "replay\\cameracontrolmodeentered.wav" ); } else { DisplayPerformanceTip( "#Replay_PerfTip_EnterFreeCam", &replay_perftip_count_freecam_enter, MAX_TIP_DISPLAYS ); surface()->PlaySound( "replay\\cameracontrolmodeexited.wav" ); } SetMouseInputEnabled( !bMouseInputEnabled ); } else { // Play an error sound surface()->PlaySound( "replay\\cameracontrolerror.wav" ); } } } // Show panel if space key bar is down bool bSpaceDown = bNoDialogsUp && !enginevgui->IsGameUIVisible() && input()->IsKeyDown( KEY_SPACE ); m_bSpacePressed = bSpaceDown && !m_bSpaceDown; m_bSpaceDown = bSpaceDown; // Modify visibility? bool bShow = IsVisible(); if ( m_bSpacePressed ) { bShow = !IsVisible(); } // Set visibility? if ( IsVisible() != bShow ) { ShowPanel( bShow ); m_bShownAtLeastOnce = true; // For achievements: Achievements_OnSpaceBarPressed(); } // Factor in host_timescale. float flScaledElapsed = flElapsed; ConVarRef host_timescale( "host_timescale" ); if ( host_timescale.GetFloat() > 0 ) { flScaledElapsed *= host_timescale.GetFloat(); } // Do FOV smoothing ReplayCamera()->SmoothFov( flScaledElapsed ); // Don't do any more processing if not needed if ( !m_bShownAtLeastOnce ) return; // Update time text if necessary UpdateTimeLabels(); // Make all player cells invisible int nTeamCounts[2] = {0,0}; int nCurTeam = 0; for ( int i = 0; i < 2; ++i ) for ( int j = 0; j <= MAX_PLAYERS; ++j ) { m_pPlayerCells[i][j]->SetVisible( false ); } int iMouseOverPlayerIndex = -1; CPlayerCell *pMouseOverCell = NULL; // Update player cells bool bLayoutPlayerCells = true; // TODO: only layout when necessary C_ReplayGame_PlayerResource_t *pGamePlayerResource = dynamic_cast< C_ReplayGame_PlayerResource_t * >( g_PR ); for ( int iPlayer = 1; iPlayer <= MAX_PLAYERS; ++iPlayer ) { IGameResources *pGR = GameResources(); if ( !pGR || !pGR->IsConnected( iPlayer ) ) continue; // Which team? int iTeam = pGR->GetTeam( iPlayer ); switch ( iTeam ) { case REPLAY_TEAM_TEAM0: ++nTeamCounts[0]; nCurTeam = 0; break; case REPLAY_TEAM_TEAM1: ++nTeamCounts[1]; nCurTeam = 1; break; default: nCurTeam = -1; break; } if ( nCurTeam < 0 ) continue; #if !defined( CSTRIKE_DLL ) int iPlayerClass = pGamePlayerResource->GetPlayerClass( iPlayer ); if ( iPlayerClass == REPLAY_CLASS_UNDEFINED ) continue; #endif int nCurTeamCount = nTeamCounts[ nCurTeam ]; CPlayerCell* pCell = m_pPlayerCells[ nCurTeam ][ nCurTeamCount-1 ]; // Cache the player index pCell->m_iPlayerIndex = iPlayer; // Make visible pCell->SetVisible( true ); // Show leaderboard icon #if defined( TF_CLIENT_DLL ) char szClassImg[64]; extern const char *g_aPlayerClassNames_NonLocalized[ REPLAY_NUM_CLASSES ]; char const *pClassName = iPlayerClass == TF_CLASS_DEMOMAN ? "demo" : g_aPlayerClassNames_NonLocalized[ iPlayerClass ]; V_snprintf( szClassImg, sizeof( szClassImg ), "../HUD/leaderboard_class_%s", pClassName ); // Show dead icon instead? if ( !pGamePlayerResource->IsAlive( iPlayer ) ) { V_strcat( szClassImg, "_d", sizeof( szClassImg ) ); } IImage *pImage = scheme()->GetImage( szClassImg, true ); if ( pImage ) { pImage->SetSize( 32, 32 ); pCell->GetImage()->SetImage( pImage ); } #elif defined( CSTRIKE_DLL ) // TODO - create and use class icons char szText[16]; V_snprintf( szText, sizeof( szText ), "%i", nTeamCounts[ nCurTeam ] ); pCell->SetText( szText ); #endif // Display player name if mouse is over the current cell if ( pCell->IsWithin( nMouseX, nMouseY ) ) { iMouseOverPlayerIndex = iPlayer; pMouseOverCell = pCell; } } // Check to see if we're hovering over a camera-mode, and if so, display its options panel if it has one if ( bRecording ) { for ( int i = 0; i < NCAMS; ++i ) { CCameraOptionsPanel *pCurOptionsPanel = m_pCameraOptionsPanels[ i ]; if ( !pCurOptionsPanel ) continue; bool bMouseOverButton = m_pCameraButtons[ i ]->IsWithin( nMouseX, nMouseY ); bool bMouseOverOptionsPanel = pCurOptionsPanel->IsWithin( nMouseX, nMouseY ); bool bInCameraModeThatMouseIsOver = ReplayCamera()->GetMode() == GetCameraModeFromButtonIndex( (CameraMode_t)i ); bool bDontCareAboutCameraMode = i == COMPONENT_TIMESCALE; bool bActivate = ( i == m_nMouseClickedOverCameraSettingsPanel ) || ( ( ( bInCameraModeThatMouseIsOver || bDontCareAboutCameraMode ) && bMouseOverButton ) || ( bMouseOverOptionsPanel && pCurOptionsPanel->IsVisible() ) ); pCurOptionsPanel->SetVisible( bActivate ); } } if ( bLayoutPlayerCells ) { LayoutPlayerCells(); } // Setup player name label and temporary camera view if ( m_pPlayerNameLabel && pGamePlayerResource && pMouseOverCell ) { m_pPlayerNameLabel->SetText( pGamePlayerResource->GetPlayerName( iMouseOverPlayerIndex ) ); m_pPlayerNameLabel->SizeToContents(); int nCellPos[2]; pMouseOverCell->GetPos( nCellPos[0], nCellPos[1] ); int nLabelX = MAX( nCellPos[0], m_nRedBlueLabelRightX ); int nLabelY = m_nBottomPanelStartY + ( m_nBottomPanelHeight - m_pPlayerNameLabel->GetTall() ) / 2; m_pPlayerNameLabel->SetPos( nLabelX, nLabelY ); m_pPlayerNameLabel->SetVisible( true ); // Setup camera pCamera->SetPrimaryTarget( iMouseOverPlayerIndex ); } else { m_pPlayerNameLabel->SetVisible( false ); // Set camera to last valid target Assert( m_iCurPlayerTarget >= 0 ); pCamera->SetPrimaryTarget( m_iCurPlayerTarget ); } // If user clicked, assume it was the selected cell and set primary target in camera if ( iMouseOverPlayerIndex >= 0 ) { pCamera->SetPrimaryTarget( iMouseOverPlayerIndex ); } else { pCamera->SetPrimaryTarget( m_iCurPlayerTarget ); } // fixes a case where the replay would be paused and the player would cycle cameras but the // target's visibility wouldn't be updated until the replay was unpaused (they would be invisible) if ( m_bCurrentTargetNeedsVisibilityUpdate ) { C_BaseEntity *pTarget = ClientEntityList().GetEnt( pCamera->GetPrimaryTargetIndex() ); if ( pTarget ) { pTarget->UpdateVisibility(); } m_bCurrentTargetNeedsVisibilityUpdate = false; } // If in free-cam mode, add set view event if we're not paused if ( bInAControllableCameraMode && m_bShownAtLeastOnce && bRecording ) { AddSetViewEvent(); AddTimeScaleEvent( m_flTimeScaleProxy ); } // Set paused state in rec light const bool bPaused = IsPaused(); m_pRecLightPanel->UpdatePauseState( bPaused ); Achievements_Think( flElapsed ); } void CReplayPerformanceEditorPanel::Achievements_OnSpaceBarPressed() { m_flLastTimeSpaceBarPressed = gpGlobals->realtime; } void CReplayPerformanceEditorPanel::Achievements_Think( float flElapsed ) { // engine->Con_NPrintf( 10, "total time: %f", m_flActiveTimeInEditor ); // engine->Con_NPrintf( 11, "last time space bar pressed: %f", m_flLastTimeSpaceBarPressed ); // Already awarded one this editing session? if ( m_bAchievementAwarded ) return; // Too much idle time since last activity? if ( gpGlobals->realtime - m_flLastTimeSpaceBarPressed > 60.0f ) { m_flActiveTimeInEditor = 0.0f; return; } // Accumulate active time m_flActiveTimeInEditor += flElapsed; // Award now if three-minutes of non-idle time has passed const float flMinutes = 60.0f * 3.0f; if ( m_flActiveTimeInEditor < flMinutes ) return; Achievements_Grant(); } void CReplayPerformanceEditorPanel::Achievements_Grant() { #if defined( TF_CLIENT_DLL ) g_AchievementMgrTF.AwardAchievement( ACHIEVEMENT_TF_REPLAY_EDIT_TIME ); #endif // Awarded m_bAchievementAwarded = true; } bool CReplayPerformanceEditorPanel::IsPaused() { return IsVisible(); } CReplayPerformance *CReplayPerformanceEditorPanel::GetPerformance() const { return g_pReplayPerformanceController->GetPerformance(); } CReplayPerformance *CReplayPerformanceEditorPanel::GetSavedPerformance() const { return g_pReplayPerformanceController->GetSavedPerformance(); } int CReplayPerformanceEditorPanel::GetCameraModeFromButtonIndex( CameraMode_t iCamera ) { switch ( iCamera ) { case CAM_FREE: return OBS_MODE_ROAMING; case CAM_THIRD: return OBS_MODE_CHASE; case CAM_FIRST: return OBS_MODE_IN_EYE; } return CAM_INVALID; } void CReplayPerformanceEditorPanel::UpdateTimeLabels() { CReplay *pPlayingReplay = g_pReplayManager->GetPlayingReplay(); if ( !pPlayingReplay || !m_pCurTimeLabel || !m_pTotalTimeLabel ) return; float flCurTime, flTotalTime; g_pClientReplayContext->GetPlaybackTimes( flCurTime, flTotalTime, pPlayingReplay, GetPerformance() ); int nCurRoundedTime = (int)flCurTime; // Essentially floor'd if ( nCurRoundedTime == m_nLastRoundedTime ) return; m_nLastRoundedTime = nCurRoundedTime; // Set current time text char szTimeText[64]; V_snprintf( szTimeText, sizeof( szTimeText ), "%s", CReplayTime::FormatTimeString( nCurRoundedTime ) ); m_pCurTimeLabel->SetText( szTimeText ); // Set total time text V_snprintf( szTimeText, sizeof( szTimeText ), "%s", CReplayTime::FormatTimeString( (int)flTotalTime ) ); m_pTotalTimeLabel->SetText( szTimeText ); // Center between left-most camera button and play/pause button m_pCurTimeLabel->SizeToContents(); m_pTotalTimeLabel->SizeToContents(); } void CReplayPerformanceEditorPanel::UpdateCameraSelectionPosition( CameraMode_t nCameraMode ) { Assert( nCameraMode >= 0 && nCameraMode < NCAMS ); m_iCameraSelection = nCameraMode; UpdateCameraButtonImages(); } void CReplayPerformanceEditorPanel::UpdateFreeCamSettings( const SetViewParams_t &params ) { CCameraOptionsPanel_Free *pSettingsPanel = dynamic_cast< CCameraOptionsPanel_Free * >( m_pCameraOptionsPanels[ CAM_FREE ] ); if ( !pSettingsPanel ) return; pSettingsPanel->SetValue( CCameraOptionsPanel_Free::SLIDER_ACCEL, params.m_flAccel ); pSettingsPanel->SetValue( CCameraOptionsPanel_Free::SLIDER_SPEED, params.m_flSpeed ); pSettingsPanel->SetValue( CCameraOptionsPanel_Free::SLIDER_FOV, params.m_flFov ); pSettingsPanel->SetValue( CCameraOptionsPanel_Free::SLIDER_ROTFILTER, params.m_flRotationFilter ); } void CReplayPerformanceEditorPanel::UpdateTimeScale( float flScale ) { CTimeScaleOptionsPanel *pSettingsPanel = dynamic_cast< CTimeScaleOptionsPanel * >( m_pCameraOptionsPanels[ COMPONENT_TIMESCALE ] ); if ( !pSettingsPanel ) return; pSettingsPanel->SetValue( CTimeScaleOptionsPanel::SLIDER_TIMESCALE, flScale ); } void CReplayPerformanceEditorPanel::LayoutPlayerCells() { int nPanelHeight = m_pPlayerCellsPanel->GetTall(); int nCellBuffer = XRES(1); for ( int i = 0; i < 2; ++i ) { int nCurX = m_nRedBlueLabelRightX; for ( int j = 0; j <= MAX_PLAYERS; ++j ) { CPlayerCell *pCurCell = m_pPlayerCells[i][j]; if ( !pCurCell->IsVisible() ) continue; // Apply cached settings from .res file if ( m_pPlayerCellData ) { pCurCell->ApplySettings( m_pPlayerCellData ); } const int nY = nPanelHeight/2 + m_nRedBlueSigns[i] * nPanelHeight/4 - pCurCell->GetTall()/2; pCurCell->SetPos( nCurX, nY ); nCurX += pCurCell->GetWide() + nCellBuffer; } } } void CReplayPerformanceEditorPanel::PerformLayout() { int w = ScreenWidth(), h = ScreenHeight(); SetBounds(0,0,w,h); // Layout camera options panels for ( int i = 0; i < NCAMS; ++i ) { CCameraOptionsPanel *pCurOptionsPanel = m_pCameraOptionsPanels[ i ]; if ( !pCurOptionsPanel ) continue; CExImageButton *pCurCameraButton = m_pCameraButtons[ i ]; if ( !pCurCameraButton ) continue; // Get camera button position int aCameraButtonPos[2]; int aBottomPos[2]; pCurCameraButton->GetPos( aCameraButtonPos[ 0 ], aCameraButtonPos[ 1 ] ); m_pBottom->GetPos( aBottomPos[ 0 ], aBottomPos[ 1 ] ); // Layout the panel now - it should set its own size, which we need to know to position it properly pCurOptionsPanel->InvalidateLayout( true, true ); // Position it pCurOptionsPanel->SetPos( aBottomPos[ 0 ] + aCameraButtonPos[ 0 ] + pCurCameraButton->GetWide() - pCurOptionsPanel->GetWide() - XRES( 3 ), aBottomPos[ 1 ] + aCameraButtonPos[ 1 ] - pCurOptionsPanel->GetTall() ); } // Setup menu position relative to menu button int aMenuButtonPos[2]; m_pMenuButton->GetPos( aMenuButtonPos[0], aMenuButtonPos[1] ); m_pMenu->SetPos( aMenuButtonPos[0], aMenuButtonPos[1] + m_pMenuButton->GetTall() ); // Set player cell panel to be the size of half the bottom panel int aBottomSize[2]; m_pBottom->GetSize( aBottomSize[0], aBottomSize[1] ); m_pPlayerCellsPanel->SetBounds( 0, 0, aBottomSize[0] / 2, m_pPlayerCellsPanel->GetTall() ); CExLabel *pRedBlueLabels[2] = { dynamic_cast< CExLabel * >( m_pPlayerCellsPanel->FindChildByName( "RedLabel" ) ), dynamic_cast< CExLabel * >( m_pPlayerCellsPanel->FindChildByName( "BlueLabel" ) ) }; int nMargins[2] = { (int)XRES( 5 ), (int)YRES( 2 ) }; for ( int i = 0; i < 2; ++i ) { pRedBlueLabels[i]->SizeToContents(); const int nY = m_pPlayerCellsPanel->GetTall()/2 + m_nRedBlueSigns[i] * m_pPlayerCellsPanel->GetTall()/4 - pRedBlueLabels[i]->GetTall()/2; pRedBlueLabels[i]->SetPos( nMargins[0], nY ); m_nRedBlueLabelRightX = MAX( m_nRedBlueLabelRightX, nMargins[0] + pRedBlueLabels[i]->GetWide() + nMargins[0] ); } // Position player cells LayoutPlayerCells(); BaseClass::PerformLayout(); } bool CReplayPerformanceEditorPanel::OnStateChangeRequested( const char *pEventStr ) { // If we're already recording, allow the change. if ( g_pReplayPerformanceController->IsRecording() ) return true; // If we aren't recording and there is no forthcoming data in the playback stream, allow the change. if ( !g_pReplayPerformanceController->IsPlaybackDataLeft() ) return true; // Otherwise, record the event string and show a dialog asking the user if they're sure they want to nuke. V_strncpy( m_szSuspendedEvent, pEventStr, sizeof( m_szSuspendedEvent ) ); ShowConfirmDialog( "#Replay_Warning", "#Replay_NukePerformanceChanges", "#GameUI_Confirm", "#GameUI_CancelBold", OnConfirmDestroyChanges, this, this, REPLAY_SOUND_DIALOG_POPUP ); return false; } void CReplayPerformanceEditorPanel::SetButtonTip( wchar_t *pTipText, Panel *pContextPanel ) { // Set the text m_pButtonTip->SetText( pTipText ); m_pButtonTip->InvalidateLayout( true, true ); // Center relative to context panel int aPos[2]; ipanel()->GetAbsPos( pContextPanel->GetVPanel(), aPos[0], aPos[1] ); const int nX = clamp( aPos[0] - m_pButtonTip->GetWide() / 2, 0, ScreenWidth() - m_pButtonTip->GetWide() - (int) XRES( 40 ) ); const int nY = m_nBottomPanelStartY - m_pButtonTip->GetTall() - (int) YRES( 2 ); m_pButtonTip->SetPos( nX, nY ); } void CReplayPerformanceEditorPanel::ShowButtonTip( bool bShow ) { m_pButtonTip->SetVisible( bShow ); } void CReplayPerformanceEditorPanel::ShowSavingDialog() { Assert( !m_pSavingDlg ); m_pSavingDlg = new CSavingDialog( ReplayUI_GetPerformanceEditor() ); ShowWaitingDialog( m_pSavingDlg, "#Replay_Saving", true, false, -1 ); } void CReplayPerformanceEditorPanel::ShowPanel( bool bShow ) { if ( bShow == IsVisible() ) return; if ( bShow ) { // We are now performing. m_pRecLightPanel->SetPerforming( true ); // Disable keyboard input on all panels added to the list FOR_EACH_LL( m_lstDisableKeyboardInputPanels, it ) { m_lstDisableKeyboardInputPanels[ it ]->SetKeyBoardInputEnabled( false ); } DisplayPerformanceTip( "#Replay_PerfTip_ExitPerfMode", &replay_perftip_count_exit, MAX_TIP_DISPLAYS ); // Fire a message the game DLL can intercept (for achievements, etc). IGameEvent *event = gameeventmanager->CreateEvent( "entered_performance_mode" ); if ( event ) { gameeventmanager->FireEventClientSide( event ); } // Play a sound surface()->PlaySound( "replay\\enterperformancemode.wav" ); } else { // Display a tip DisplayPerformanceTip( "#Replay_PerfTip_EnterPerfMode", &replay_perftip_count_enter, MAX_TIP_DISPLAYS ); // Play a sound surface()->PlaySound( "replay\\exitperformancemode.wav" ); } // Show mouse cursor SetMouseInputEnabled( bShow ); SetVisible( bShow ); MakePopup( bShow ); // Avoid waiting for next OnThink() to hide background images m_pRecLightPanel->UpdatePauseState( bShow ); m_pRecLightPanel->UpdateBackgroundVisibility(); // Play or pause if ( bShow ) { PauseDemo(); } else { PlayDemo(); } // Keep controller informed about pause state so that it can throw away unimportant events during pause if it's recording. g_pReplayPerformanceController->NotifyPauseState( bShow ); } bool CReplayPerformanceEditorPanel::OnEndOfReplayReached() { if ( m_bShownAtLeastOnce ) { ShowPanel( true ); DisplayPerformanceTip( "#Replay_PerfTip_EndOfReplayReached" ); // Don't end demo playback yet. return true; } // Let the demo player end demo playback return false; } void CReplayPerformanceEditorPanel::AddSetViewEvent() { if ( !g_pReplayManager->GetPlayingReplay() ) return; if ( !g_pReplayPerformanceController ) return; Vector pos; QAngle angles; float fov; ReplayCamera()->GetCachedView( pos, angles, fov ); SetViewParams_t params; params.m_flTime = GetPlaybackTime(); params.m_flFov = fov; params.m_pOrigin = &pos; params.m_pAngles = &angles; params.m_flAccel = ReplayCamera()->m_flRoamingAccel; params.m_flSpeed = ReplayCamera()->m_flRoamingSpeed; params.m_flRotationFilter = ReplayCamera()->m_flRoamingRotFilterFactor; g_pReplayPerformanceController->AddEvent_Camera_SetView( params ); } // Input should be in [0,1] void CReplayPerformanceEditorPanel::AddTimeScaleEvent( float flTimeScale ) { if ( !g_pReplayManager->GetPlayingReplay() ) return; if ( !g_pReplayPerformanceController ) return; g_pReplayPerformanceController->AddEvent_TimeScale( GetPlaybackTime(), flTimeScale ); } void CReplayPerformanceEditorPanel::UpdateCameraButtonImages( bool bForceUnselected/*=false*/ ) { CReplayPerformance *pPerformance = GetPerformance(); for ( int i = 0; i < NCAMS; ++i ) { CFmtStr fmtFile( gs_pBaseComponentNames[i], gs_pCamNames[i], ( !bForceUnselected && ( !pPerformance || g_pReplayPerformanceController->IsRecording() ) && i == m_iCameraSelection ) ? "_selected" : "" ); if ( m_pCameraButtons[ i ] ) { m_pCameraButtons[ i ]->SetSubImage( fmtFile.Access() ); } } } void CReplayPerformanceEditorPanel::EnsureRecording( bool bShouldSnip ) { // Not recording? if ( !g_pReplayPerformanceController->IsRecording() ) { // Start recording - snip if needed. g_pReplayPerformanceController->StartRecording( GetReplay(), bShouldSnip ); } } void CReplayPerformanceEditorPanel::ToggleMenu() { if ( !m_pMenu ) return; // Show/hide const bool bShow = !m_pMenu->IsVisible(); m_pMenu->SetVisible( bShow ); } void CReplayPerformanceEditorPanel::SaveAs( const wchar_t *pTitle ) { if ( !g_pReplayPerformanceController->SaveAsAsync( pTitle ) ) { DisplaySavedTip( false ); } ShowSavingDialog(); } /*static*/ void CReplayPerformanceEditorPanel::OnConfirmSaveAs( bool bShouldSave, wchar_t *pTitle, void *pContext ) { // NOTE: Assumes that overwriting has already been confirmed by the user. if ( !bShouldSave ) return; CReplayPerformanceEditorPanel *pThis = (CReplayPerformanceEditorPanel *)pContext; pThis->SaveAs( pTitle ); surface()->PlaySound( "replay\\saved_take.wav" ); } void CReplayPerformanceEditorPanel::ShowRewindConfirmMessage() { ShowMessageBox( "#Replay_RewindWarningTitle", "#Replay_RewindWarningMsg", "#GameUI_OK", OnConfirmRewind, NULL, (void *)this ); surface()->PlaySound( "replay\\replaydialog_warn.wav" ); } /*static*/ void CReplayPerformanceEditorPanel::OnConfirmRewind( bool bConfirmed, void *pContext ) { if ( bConfirmed ) { if ( pContext ) { CReplayPerformanceEditorPanel *pEditor = (CReplayPerformanceEditorPanel *)pContext; pEditor->OnCommand( "goto_back" ); } } } void CReplayPerformanceEditorPanel::OnMenuCommand_Save( bool bExitEditorWhenDone/*=false*/ ) { // If this is the first time we're saving this performance, do a save-as. if ( !g_pReplayPerformanceController->HasSavedPerformance() ) { OnMenuCommand_SaveAs( bExitEditorWhenDone ); return; } // Regular save if ( !g_pReplayPerformanceController->SaveAsync() ) { DisplaySavedTip( false ); } // Show saving dialog ShowSavingDialog(); // Exit editor? if ( bExitEditorWhenDone ) { OnMenuCommand_Exit(); } } void CReplayPerformanceEditorPanel::OnMenuCommand_SaveAs( bool bExitEditorWhenDone/*=false*/ ) { ReplayUI_ShowPerformanceSaveDlg( OnConfirmSaveAs, this, GetReplay(), bExitEditorWhenDone ); } void CReplayPerformanceEditorPanel::DisplaySavedTip( bool bSucceess ) { DisplayPerformanceTip( bSucceess ? "#Replay_PerfTip_Saved" : "#Replay_PerfTip_SaveFailed" ); } void CReplayPerformanceEditorPanel::OnSaveComplete() { DisplaySavedTip( g_pReplayPerformanceController->GetLastSaveStatus() ); m_pSavingDlg = NULL; } void CReplayPerformanceEditorPanel::HandleUiToggle() { if ( !TFModalStack()->IsEmpty() ) return; PauseDemo(); Exit_ShowDialogs(); } void CReplayPerformanceEditorPanel::Exit() { engine->ClientCmd_Unrestricted( "disconnect" ); } void CReplayPerformanceEditorPanel::Exit_ShowDialogs() { if ( g_pReplayPerformanceController->IsDirty() ) { ShowConfirmDialog( "#Replay_DiscardTitle", "#Replay_DiscardChanges", "#Replay_Discard", "#Replay_Cancel", OnConfirmDiscard, NULL, this, REPLAY_SOUND_DIALOG_POPUP ); } else { ShowConfirmDialog( "#Replay_ExitEditorTitle", "#Replay_BackToReplays", "#GameUI_Confirm", "#Replay_Cancel", OnConfirmExit, NULL, this, REPLAY_SOUND_DIALOG_POPUP ); } } void CReplayPerformanceEditorPanel::OnMenuCommand_Exit() { Exit_ShowDialogs(); } void CReplayPerformanceEditorPanel::OnCommand( const char *command ) { float flCurTime = GetPlaybackTime(); g_bIsReplayRewinding = false; if ( !V_stricmp( command, "toggle_menu" ) ) { ToggleMenu(); } else if ( !V_strnicmp( command, "menu_", 5 ) ) { const char *pMenuCommand = command + 5; if ( !V_stricmp( pMenuCommand, "save" ) ) { OnMenuCommand_Save(); } else if ( !V_stricmp( pMenuCommand, "saveas" ) ) { OnMenuCommand_SaveAs(); } else if ( !V_stricmp( pMenuCommand, "exit" ) ) { OnMenuCommand_Exit(); } } else if ( !V_stricmp( command, "close" ) ) { ShowPanel( false ); MarkForDeletion(); return; } else if ( !V_stricmp( command, "play" ) ) { ShowPanel( false ); return; } else if ( !V_stricmp( command, "pause" ) ) { ShowPanel( true ); return; } else if ( !V_strnicmp( command, "timescale_", 10 ) ) { const char *pTimeScaleCmd = command + 10; if ( !V_stricmp( pTimeScaleCmd, "showpanel" ) ) { // If we're playing back, pop up a dialog asking if the user is sure they want to nuke the // rest of whatever is playing back. if ( !OnStateChangeRequested( command ) ) return; EnsureRecording(); } } else if ( !V_strnicmp( command, "settick_", 8 ) ) { const char *pSetType = command + 8; const int nCurTick = engine->GetDemoPlaybackTick(); if ( !V_stricmp( pSetType, "in" ) ) { SetOrRemoveInTick( nCurTick, true ); } else if ( !V_stricmp( pSetType, "out" ) ) { SetOrRemoveOutTick( nCurTick, true ); } // Save the replay CReplay *pReplay = GetReplay(); if ( pReplay ) { g_pReplayManager->FlagReplayForFlush( pReplay, true ); } return; } else if ( !V_strnicmp( command, "goto_", 5 ) ) { const char *pGotoType = command + 5; CReplay *pReplay = GetReplay(); if ( pReplay ) { const CReplayPerformance *pScratchPerformance = g_pReplayPerformanceController->GetPerformance(); const CReplayPerformance *pSavedPerformance = g_pReplayPerformanceController->GetSavedPerformance(); const CReplayPerformance *pPerformance = pScratchPerformance ? pScratchPerformance : pSavedPerformance; const int nCurTick = engine->GetDemoPlaybackTick(); // If in or out ticks are set in the performance, use those for the 'full' rewind/fast-forward const int nStartTick = MAX( 0, ( pPerformance && pPerformance->HasInTick() ) ? pPerformance->m_nTickIn : pReplay->m_nSpawnTick ); const int nEndTick = MAX( // The MAX() here will keep us from going back in time if we're already past the "end" tick nCurTick, ( ( pPerformance && pPerformance->HasOutTick() ) ? pPerformance->m_nTickOut : ( nStartTick + TIME_TO_TICKS( pReplay->m_flLength ) ) ) - TIME_TO_TICKS( 0.1f ) ); int nGotoTick = 0; bool bGoingBack = false; if ( !V_stricmp( pGotoType, "start" ) ) { bGoingBack = true; nGotoTick = nStartTick; } else if ( !V_stricmp( pGotoType, "back" ) ) { // If this is the first time rewinding, display a message if ( !replay_replayeditor_rewindmsgcounter.GetBool() ) { replay_replayeditor_rewindmsgcounter.SetValue( 1 ); ShowRewindConfirmMessage(); return; } bGoingBack = true; nGotoTick = nCurTick - TIME_TO_TICKS( 10.0f ); } else if ( !V_stricmp( pGotoType, "end" ) ) { nGotoTick = nEndTick; // Don't go back in time } // Clamp it nGotoTick = clamp( nGotoTick, nStartTick, nEndTick ); // If going back... if ( bGoingBack ) { // ...and notify the recorder that we're skipping, which we only need to do if we're going backwards g_pReplayPerformanceController->NotifyRewinding(); g_bIsReplayRewinding = true; } // Go to the given tick and pause CFmtStr fmtCmd( "demo_gototick %i\ndemo_pause\n", nGotoTick ); engine->ClientCmd_Unrestricted( fmtCmd.Access() ); } return; } else if ( !V_strnicmp( command, "setcamera_", 10 ) ) { const char *pCamType = command + 10; int nEntIndex = ReplayCamera()->GetPrimaryTargetIndex(); // If we're playing back, pop up a dialog asking if the user is sure they want to nuke the // rest of whatever is playing back. if ( !OnStateChangeRequested( command ) ) return; EnsureRecording(); if ( !V_stricmp( pCamType, "first" ) ) { ReplayCamera()->SetMode( OBS_MODE_IN_EYE ); UpdateCameraSelectionPosition( CAM_FIRST ); m_bCurrentTargetNeedsVisibilityUpdate = true; g_pReplayPerformanceController->AddEvent_Camera_Change_FirstPerson( flCurTime, nEntIndex ); } else if ( !V_stricmp( pCamType, "third" ) ) { ReplayCamera()->SetMode( OBS_MODE_CHASE ); UpdateCameraSelectionPosition( CAM_THIRD ); m_bCurrentTargetNeedsVisibilityUpdate = true; g_pReplayPerformanceController->AddEvent_Camera_Change_ThirdPerson( flCurTime, nEntIndex ); AddSetViewEvent(); } else if ( !V_stricmp( pCamType, "free" ) ) { ReplayCamera()->SetMode( OBS_MODE_ROAMING ); UpdateCameraSelectionPosition( CAM_FREE ); m_bCurrentTargetNeedsVisibilityUpdate = true; g_pReplayPerformanceController->AddEvent_Camera_Change_Free( flCurTime ); AddSetViewEvent(); DisplayPerformanceTip( "#Replay_PerfTip_EnterFreeCam", &replay_perftip_count_freecam_enter, MAX_TIP_DISPLAYS ); } return; } else { engine->ClientCmd( const_cast<char *>( command ) ); return; } BaseClass::OnCommand( command ); } void CReplayPerformanceEditorPanel::OnConfirmDestroyChanges( bool bConfirmed, void *pContext ) { AssertMsg( pContext, "Should have a context! Fix me!" ); if ( pContext && bConfirmed ) { CReplayPerformanceEditorPanel *pEditorPanel = (CReplayPerformanceEditorPanel *)pContext; if ( bConfirmed ) { CReplay *pReplay = pEditorPanel->GetReplay(); g_pReplayPerformanceController->StartRecording( pReplay, true ); // Reissue the command. pEditorPanel->OnCommand( pEditorPanel->m_szSuspendedEvent ); // Play a sound surface()->PlaySound( "replay\\snip.wav" ); } // Clear suspended event pEditorPanel->m_szSuspendedEvent[ 0 ] = '\0'; // Make sure mouse is free pEditorPanel->SetMouseInputEnabled( true ); DisplayPerformanceTip( "#Replay_PerfTip_Snip" ); } } /*static*/ void CReplayPerformanceEditorPanel::OnConfirmDiscard( bool bConfirmed, void *pContext ) { CReplayPerformanceEditorPanel *pEditor = (CReplayPerformanceEditorPanel *)pContext; if ( bConfirmed ) { pEditor->Exit(); } else { if ( !pEditor->IsVisible() ) { PlayDemo(); } } } /*static*/ void CReplayPerformanceEditorPanel::OnConfirmExit( bool bConfirmed, void *pContext ) { CReplayPerformanceEditorPanel *pEditor = (CReplayPerformanceEditorPanel *)pContext; if ( bConfirmed ) { pEditor->Exit(); } else { if ( !pEditor->IsVisible() ) { PlayDemo(); } } } void CReplayPerformanceEditorPanel::SetOrRemoveInTick( int nTick, bool bRemoveIfSet ) { SetOrRemoveTick( nTick, true, bRemoveIfSet ); } void CReplayPerformanceEditorPanel::SetOrRemoveOutTick( int nTick, bool bRemoveIfSet ) { SetOrRemoveTick( nTick, false, bRemoveIfSet ); } void CReplayPerformanceEditorPanel::SetOrRemoveTick( int nTick, bool bUseInTick, bool bRemoveIfSet ) { CReplayPerformance *pPerformance = GetPerformance(); AssertMsg( pPerformance, "Performance should always be valid by this point." ); ControlButtons_t iButton; int *pResultTick; const char *pSetTickKey; const char *pUnsetTickKey; if ( bUseInTick ) { pResultTick = &pPerformance->m_nTickIn; iButton = CTRLBUTTON_IN; pSetTickKey = "#Replay_PerfTip_InPointSet"; pUnsetTickKey = "#Replay_PerfTip_InPointRemoved"; } else { pResultTick = &pPerformance->m_nTickOut; iButton = CTRLBUTTON_OUT; pSetTickKey = "#Replay_PerfTip_OutPointSet"; pUnsetTickKey = "#Replay_PerfTip_OutPointRemoved"; } // Tick explicitly being removed? Caller passing in -1? const bool bRemoving = nTick < 0; // If tick already exists and we want to remove, remove it bool bSetting; if ( ( *pResultTick >= 0 && bRemoveIfSet ) || bRemoving ) { *pResultTick = -1; bSetting = false; } else { *pResultTick = nTick; bSetting = true; } // Display the appropriate tip DisplayPerformanceTip( bSetting ? pSetTickKey : pUnsetTickKey ); // Select/unselect button CExImageButton *pButton = m_pCtrlButtons[ iButton ]; pButton->SetSelected( bSetting ); pButton->InvalidateLayout( true, true ); // Without this, buttons don't update immediately // Mark the performance as dirty g_pReplayPerformanceController->NotifyDirty(); } CReplay *CReplayPerformanceEditorPanel::GetReplay() { return g_pReplayManager->GetReplay( m_hReplay ); } void CReplayPerformanceEditorPanel::OnRewindComplete() { // Get rid of any "selected" icon - this will happen as soon as we actually start playing back // events, but if we aren't playing back events yet we need to explicitly tell the icons not // to display their "selected" versions. UpdateCameraButtonImages( true ); } //----------------------------------------------------------------------------- static DHANDLE<CReplayPerformanceEditorPanel> g_ReplayPerformanceEditorPanel; //----------------------------------------------------------------------------- CReplayPerformanceEditorPanel *ReplayUI_InitPerformanceEditor( ReplayHandle_t hReplay ) { if ( !g_ReplayPerformanceEditorPanel.Get() ) { g_ReplayPerformanceEditorPanel = SETUP_PANEL( new CReplayPerformanceEditorPanel( NULL, hReplay ) ); g_ReplayPerformanceEditorPanel->InvalidateLayout( false, true ); } // Notify recorder of editor g_pReplayPerformanceController->SetEditor( g_ReplayPerformanceEditorPanel.Get() ); return g_ReplayPerformanceEditorPanel; } void ReplayUI_ClosePerformanceEditor() { if ( g_ReplayPerformanceEditorPanel ) { g_ReplayPerformanceEditorPanel->MarkForDeletion(); g_ReplayPerformanceEditorPanel = NULL; } } CReplayPerformanceEditorPanel *ReplayUI_GetPerformanceEditor() { return g_ReplayPerformanceEditorPanel; } #if _DEBUG CON_COMMAND_F( replay_showperfeditor, "Show performance editor", FCVAR_CLIENTDLL ) { ReplayUI_ClosePerformanceEditor(); ReplayUI_InitPerformanceEditor( REPLAY_HANDLE_INVALID ); } CON_COMMAND_F( replay_tiptest, "", FCVAR_CLIENTDLL ) { DisplayPerformanceTip( "#Replay_PerfTip_EnterFreeCam" ); } #endif #endif
0
0.969378
1
0.969378
game-dev
MEDIA
0.535934
game-dev,desktop-app
0.904713
1
0.904713
OpenCubicChunks/CubicChunks
6,860
src/main/java/io/github/opencubicchunks/cubicchunks/core/visibility/CuboidalCubeSelector.java
/* * This file is part of Cubic Chunks Mod, licensed under the MIT License (MIT). * * Copyright (c) 2015-2021 OpenCubicChunks * Copyright (c) 2015-2021 contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.github.opencubicchunks.cubicchunks.core.visibility; import io.github.opencubicchunks.cubicchunks.api.util.CubePos; import mcp.MethodsReturnNonnullByDefault; import net.minecraft.util.math.ChunkPos; import java.util.Set; import java.util.function.Consumer; import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class CuboidalCubeSelector extends CubeSelector { @Override public void forAllVisibleFrom(CubePos cubePos, int horizontalViewDistance, int verticalViewDistance, Consumer<CubePos> consumer) { int cubeX = cubePos.getX(); int cubeY = cubePos.getY(); int cubeZ = cubePos.getZ(); for (int x = cubeX - horizontalViewDistance; x <= cubeX + horizontalViewDistance; x++) { for (int y = cubeY - verticalViewDistance; y <= cubeY + verticalViewDistance; y++) { for (int z = cubeZ - horizontalViewDistance; z <= cubeZ + horizontalViewDistance; z++) { consumer.accept(new CubePos(x, y, z)); } } } } @Override public void findChanged(CubePos oldPos, CubePos newPos, int horizontalViewDistance, int verticalViewDistance, Set<CubePos> cubesToRemove, Set<CubePos> cubesToLoad, Set<ChunkPos> columnsToRemove, Set<ChunkPos> columnsToLoad) { int oldX = oldPos.getX(); int oldY = oldPos.getY(); int oldZ = oldPos.getZ(); int newX = newPos.getX(); int newY = newPos.getY(); int newZ = newPos.getZ(); int dx = newX - oldX; int dy = newY - oldY; int dz = newZ - oldZ; for (int currentX = newX - horizontalViewDistance; currentX <= newX + horizontalViewDistance; ++currentX) { for (int currentZ = newZ - horizontalViewDistance; currentZ <= newZ + horizontalViewDistance; ++currentZ) { //first handle columns //is current position outside of the old render distance square? if (!this.isPointWithinCubeVolume(oldX, 0, oldZ, currentX, 0, currentZ, horizontalViewDistance, verticalViewDistance)) { columnsToLoad.add(new ChunkPos(currentX, currentZ)); } //if we moved the current point to where it would be previously, //would it be outside of current render distance square? if (!this.isPointWithinCubeVolume(newX, 0, newZ, currentX - dx, 0, currentZ - dz, horizontalViewDistance, verticalViewDistance)) { columnsToRemove.add(new ChunkPos(currentX - dx, currentZ - dz)); } for (int currentY = newY - verticalViewDistance; currentY <= newY + verticalViewDistance; ++currentY) { //now handle cubes, the same way if (!this.isPointWithinCubeVolume(oldX, oldY, oldZ, currentX, currentY, currentZ, horizontalViewDistance, verticalViewDistance)) { cubesToLoad.add(new CubePos(currentX, currentY, currentZ)); } if (!this.isPointWithinCubeVolume(newX, newY, newZ, currentX - dx, currentY - dy, currentZ - dz, horizontalViewDistance, verticalViewDistance)) { cubesToRemove.add(new CubePos(currentX - dx, currentY - dy, currentZ - dz)); } } } } assert cubesToLoad.stream().allMatch(pos -> !cubesToRemove.contains(pos)) : "cubesToRemove contains element from cubesToLoad!"; assert columnsToLoad.stream().allMatch(pos -> !columnsToRemove.contains(pos)) : "columnsToRemove contains element from columnsToLoad!"; } @Override public void findAllUnloadedOnViewDistanceDecrease(CubePos playerPos, int oldHorizontalViewDistance, int newHorizontalViewDistance, int oldVerticalViewDistance, int newVerticalViewDistance, Set<CubePos> cubesToUnload, Set<ChunkPos> columnsToUnload) { int playerCubeX = playerPos.getX(); int playerCubeY = playerPos.getY(); int playerCubeZ = playerPos.getZ(); for (int cubeX = playerCubeX - oldHorizontalViewDistance; cubeX <= playerCubeX + oldHorizontalViewDistance; cubeX++) { for (int cubeZ = playerCubeZ - oldHorizontalViewDistance; cubeZ <= playerCubeZ + oldHorizontalViewDistance; cubeZ++) { if (!isPointWithinCubeVolume(playerCubeX, 0, playerCubeZ, cubeX, 0, cubeZ, newHorizontalViewDistance, newVerticalViewDistance)) { columnsToUnload.add(new ChunkPos(cubeX, cubeZ)); } for (int cubeY = playerCubeY - oldVerticalViewDistance; cubeY <= playerCubeY + oldVerticalViewDistance; cubeY++) { if (!isPointWithinCubeVolume(playerCubeX, playerCubeY, playerCubeZ, cubeX, cubeY, cubeZ, newHorizontalViewDistance, newVerticalViewDistance)) { cubesToUnload.add(new CubePos(cubeX, cubeY, cubeZ)); } } } } } private boolean isPointWithinCubeVolume(int cubeX, int cubeY, int cubeZ, int pointX, int pointY, int pointZ, int horizontal, int vertical) { int dx = cubeX - pointX; int dy = cubeY - pointY; int dz = cubeZ - pointZ; return dx >= -horizontal && dx <= horizontal && dy >= -vertical && dy <= vertical && dz >= -horizontal && dz <= horizontal; } }
0
0.872209
1
0.872209
game-dev
MEDIA
0.768684
game-dev
0.994806
1
0.994806
PGMDev/PGM
7,561
core/src/main/java/tc/oc/pgm/flag/LegacyFlagBeamMatchModule.java
package tc.oc.pgm.flag; import static java.util.stream.IntStream.range; import static tc.oc.pgm.util.nms.Packets.ENTITIES; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.inventory.ItemStack; import tc.oc.pgm.api.PGM; import tc.oc.pgm.api.match.Match; import tc.oc.pgm.api.match.MatchModule; import tc.oc.pgm.api.match.MatchScope; import tc.oc.pgm.api.match.factory.MatchModuleFactory; import tc.oc.pgm.api.module.exception.ModuleLoadException; import tc.oc.pgm.api.player.MatchPlayer; import tc.oc.pgm.events.ListenerScope; import tc.oc.pgm.events.PlayerJoinMatchEvent; import tc.oc.pgm.events.PlayerLeaveMatchEvent; import tc.oc.pgm.flag.event.FlagStateChangeEvent; import tc.oc.pgm.flag.state.Carried; import tc.oc.pgm.flag.state.Spawned; import tc.oc.pgm.util.inventory.ItemBuilder; import tc.oc.pgm.util.material.Materials; import tc.oc.pgm.util.nms.packets.FakeEntity; @ListenerScope(MatchScope.LOADED) public class LegacyFlagBeamMatchModule implements MatchModule, Listener { public static class Factory implements MatchModuleFactory<LegacyFlagBeamMatchModule> { @Override public Collection<Class<? extends MatchModule>> getSoftDependencies() { return ImmutableList.of(FlagMatchModule.class); // Only needs to load if Flags are loaded } @Override public LegacyFlagBeamMatchModule createMatchModule(Match match) throws ModuleLoadException { return new LegacyFlagBeamMatchModule(match); } } private static final int UPDATE_DELAY = 0; private static final int UPDATE_FREQUENCY = 50; private final Match match; private final Map<Flag, Beam> beams; public LegacyFlagBeamMatchModule(Match match) { this.match = match; this.beams = new HashMap<>(); FlagMatchModule module = match.needModule(FlagMatchModule.class); module.getFlags().forEach(f -> beams.put(f, new Beam(f))); } private Stream<Beam> beams() { return beams.values().stream(); } @Override public void enable() { match .getExecutor(MatchScope.RUNNING) .scheduleAtFixedRate( () -> beams.values().forEach(Beam::update), UPDATE_DELAY, UPDATE_FREQUENCY, TimeUnit.MILLISECONDS); } @Override public void unload() { beams.values().forEach(Beam::hide); beams.clear(); } private void showLater(MatchPlayer player) { match .getExecutor(MatchScope.LOADED) .schedule(() -> beams().forEach(b -> b.show(player)), 50, TimeUnit.MILLISECONDS); } @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onPlayerChangedWorld(PlayerChangedWorldEvent event) { MatchPlayer player = match.getPlayer(event.getPlayer()); if (player == null) return; if (event.getPlayer().getWorld() == match.getWorld()) showLater(player); else beams().forEach(beam -> beam.hide(player)); } @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onPlayerJoin(PlayerJoinMatchEvent event) { showLater(event.getPlayer()); } @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onPlayerLeaveMatch(PlayerLeaveMatchEvent event) { beams().forEach(beam -> beam.hide(event.getPlayer())); } @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onFlagStateChange(FlagStateChangeEvent event) { Beam beam = beams.get(event.getFlag()); boolean wasSpawned = event.getOldState() instanceof Spawned, isSpawned = event.getNewState() instanceof Spawned; if (wasSpawned && !isSpawned) beam.hide(); else if (!wasSpawned && isSpawned) beam.show(); // Hide beam for carrier if (event.getNewState() instanceof Carried) beam.hide(((Carried) event.getNewState()).getCarrier()); // Show beam to old carrier if (event.getOldState() instanceof Carried) beam.show(((Carried) event.getOldState()).getCarrier()); } class Beam { private final Flag flag; private final FakeEntity base, legacyBase; private final List<FakeEntity> segments; private final Set<MatchPlayer> viewers = new HashSet<>(); Beam(Flag flag) { this.flag = flag; ItemStack wool = new ItemBuilder().material(Materials.WOOL).color(flag.getDyeColor()).build(); this.base = ENTITIES.fakeArmorStand(wool); this.legacyBase = ENTITIES.fakeWitherSkull(); this.segments = range( 0, 64) // ~100 blocks is the height which the particles appear to be reasonably // visible (similar amount to amount closest to the flag), we limit this to 64 blocks // to reduce load on the client .mapToObj(i -> ENTITIES.fakeArmorStand(wool)) .collect(Collectors.toList()); } Optional<MatchPlayer> carrier() { return flag.getState() instanceof Carried ? Optional.of(((Carried) flag.getState()).getCarrier()) : Optional.empty(); } Optional<Location> location() { return flag.getLocation(); } Location toBaseLocation(Location loc) { loc = loc.clone().add(0, 2.75, 0); if (loc.getY() < -64) loc.setY(-64); loc.setPitch(0f); loc.setYaw(0f); return loc; } private FakeEntity base(MatchPlayer player) { return player.isLegacy() ? legacyBase : base; } public void show() { match.getPlayers().forEach(this::show); } public void show(MatchPlayer player) { if (!flag.getDefinition().showBeam()) return; if (!player.isLegacy() && !PGM.get().getConfiguration().useLegacyFlagBeams()) return; if (!(flag.getState() instanceof Spawned)) return; if (carrier().map(player::equals).orElse(false) || !viewers.add(player)) return; Player bukkit = player.getBukkit(); spawn(bukkit, base(player)); segments.forEach(segment -> spawn(bukkit, segment)); for (int i = 1; i < segments.size(); i++) { segments.get(i - 1).ride(segments.get(i).entityId()).send(bukkit); } base(player).ride(segments.getFirst().entityId()).send(bukkit); update(player); } private void spawn(Player player, FakeEntity entity) { location().ifPresent(l -> entity.spawn(toBaseLocation(l)).send(player)); } public void update() { viewers.forEach(this::update); } public void update(MatchPlayer player) { carrier() .map(MatchPlayer::getLocation) .or(this::location) .map(this::toBaseLocation) .ifPresent(loc -> base(player).teleport(loc).send(player.getBukkit())); } public void hide() { ImmutableSet.copyOf(viewers).forEach(this::hide); viewers.clear(); } private void hide(MatchPlayer player) { if (!viewers.remove(player)) return; Player bukkit = player.getBukkit(); for (int i = segments.size() - 1; i >= 0; i--) { segments.get(i).destroy().send(bukkit); } base(player).destroy().send(bukkit); } } }
0
0.819854
1
0.819854
game-dev
MEDIA
0.941459
game-dev
0.891848
1
0.891848
gawric/Unity-Client-for-L2J
6,426
l2-unity/Assets/Scripts/Audio/AmbientSoundEmitter.cs
using FMODUnity; using System.Collections; using System.Collections.Generic; using UnityEngine; public class AmbientSoundEmitter : EventHandler { private FMOD.Studio.EventDescription _eventDescription; private FMOD.Studio.EventInstance _instance; [SerializeField] private EventReference _eventReference; [SerializeField] private EmitterGameEvent _playEvent = EmitterGameEvent.None; [SerializeField] private EmitterGameEvent _stopEvent = EmitterGameEvent.None; [SerializeField] private AmbientSoundType _ambientSoundType; [SerializeField] private bool _allowFadeout = true; [SerializeField] private bool _overrideAttenuation = false; [SerializeField] private float _loopDelaySeconds = 1; [SerializeField] private float _playChancePercent = 100; [SerializeField] private float _soundPitch = 0; [SerializeField] private bool _loop = true; [SerializeField] private float _overrideMinDistance = -1.0f; [SerializeField] private float _overrideMaxDistance = -1.0f; [SerializeField] private float _clipLengthSeconds = 0; [SerializeField] private bool _isSound3D = true; public EventReference EventReference { set { _eventReference = value; } } public EmitterGameEvent PlayEvent { set { _playEvent = value; } } public EmitterGameEvent StopEvent { set { _stopEvent = value; } } public AmbientSoundType AmbientSoundType { set { _ambientSoundType = value; } } public bool AllowFadeout { set { _allowFadeout = value; } } public bool OverrideAttenuation { set { _overrideAttenuation = value; } } public float LoopDelaySeconds { set { _loopDelaySeconds = value; } } public float PlayChancePercent { set { _playChancePercent = value; } } public float SoundPitch { set { _soundPitch = value; } } public bool Loop { set { _loop = value; } } public float OverrideMinDistance { set { _overrideMinDistance = value; } } public float OverrideMaxDistance { set { _overrideMaxDistance = value; } } private void Awake() { if(!_eventDescription.isValid()) { Lookup(); } int lengthMs = 0; _eventDescription.getLength(out lengthMs); _clipLengthSeconds = lengthMs / 1000f; _clipLengthSeconds = _clipLengthSeconds / _soundPitch; _eventDescription.is3D(out _isSound3D); } private float MaxDistance { get { if(_overrideAttenuation) { return _overrideMaxDistance; } if(!_eventDescription.isValid()) { Lookup(); } float minDistance, maxDistance; _eventDescription.getMinMaxDistance(out minDistance, out maxDistance); return maxDistance; } } private void Lookup() { _eventDescription = RuntimeManager.GetEventDescription(_eventReference); } public void Play() { if(_eventReference.IsNull) { return; } if(!_eventDescription.isValid()) { Lookup(); } if (_loop) { StopCoroutine(StartPlayLoop()); StartCoroutine(StartPlayLoop()); return; } if (_isSound3D && ShouldStop()) { Stop(); } else if (ShouldPlayEvent()) { PlayInstance(); } } IEnumerator StartPlayLoop() { while(true) { if (_isSound3D && ShouldStop()) { Stop(); yield break; } if(ShouldPlayEvent()) { PlayInstance(); } yield return new WaitForSeconds(_clipLengthSeconds * 0.99f); // 1% for error margin if (_loopDelaySeconds > 0) { yield return new WaitForSeconds(_loopDelaySeconds); } } } private bool ShouldPlayEvent() { if(_ambientSoundType == AmbientSoundType.AST1_Day && WorldClock.Instance.IsNightTime()) { return false; } if(_ambientSoundType == AmbientSoundType.AST1_Night && !WorldClock.Instance.IsNightTime()) { return false; } if(Random.Range(1, 100) <= _playChancePercent) { return true; } return false; } private bool ShouldStop() { if(ThirdPersonListener.Instance.Player == null) { return true; } float distance = Vector3.Distance(transform.position, ThirdPersonListener.Instance.Player.transform.position); return distance > MaxDistance; } private void PlayInstance() { if (!_instance.isValid()) { _instance.clearHandle(); } // Let previous oneshot instances play out if (_instance.isValid()) { _instance.release(); _instance.clearHandle(); } bool is3D; _eventDescription.is3D(out is3D); if(!_instance.isValid()) { _eventDescription.createInstance(out _instance); // Only want to update if we need to set 3D attributes if(is3D) { _instance.set3DAttributes(RuntimeUtils.To3DAttributes(gameObject)); } } if(is3D && _overrideAttenuation) { _instance.setProperty(FMOD.Studio.EVENT_PROPERTY.MINIMUM_DISTANCE, _overrideMinDistance); _instance.setProperty(FMOD.Studio.EVENT_PROPERTY.MAXIMUM_DISTANCE, _overrideMaxDistance); } _instance.setPitch(_soundPitch); _instance.start(); } public void Stop() { StopCoroutine(StartPlayLoop()); StopInstance(); } private void StopInstance() { if(_instance.isValid()) { _instance.stop(_allowFadeout ? FMOD.Studio.STOP_MODE.ALLOWFADEOUT : FMOD.Studio.STOP_MODE.IMMEDIATE); _instance.release(); if(!_allowFadeout) { _instance.clearHandle(); } } } public bool IsPlaying() { if(_instance.isValid()) { FMOD.Studio.PLAYBACK_STATE playbackState; _instance.getPlaybackState(out playbackState); return (playbackState != FMOD.Studio.PLAYBACK_STATE.STOPPED); } return false; } protected override void HandleGameEvent(EmitterGameEvent gameEvent) { if(_playEvent == gameEvent) { Play(); } if(_stopEvent == gameEvent) { Stop(); } } }
0
0.851912
1
0.851912
game-dev
MEDIA
0.926621
game-dev
0.913711
1
0.913711
pqtriick/LabySK
1,394
src/main/java/de/pqtriick/labysk/elements/effects/discord/AddEndTimeRPCEff.java
package de.pqtriick.labysk.elements.effects.discord; import ch.njol.skript.Skript; import ch.njol.skript.lang.Effect; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser; import ch.njol.util.Kleenean; import de.pqtriick.labysk.laby.laby4.discord.LabyRPCManager; import org.bukkit.entity.Player; import org.bukkit.event.Event; import javax.annotation.Nullable; public class AddEndTimeRPCEff extends Effect { private Expression<Player> player; private Expression<String> title; private Expression<Integer> endTime; static { Skript.registerEffect(AddEndTimeRPCEff.class, "create Discord RPC named %string% with end time of %integer% minutes for %player%"); } @Override protected void execute(Event event) { Player p = player.getSingle(event); String t = title.getSingle(event); Integer e = endTime.getSingle(event); LabyRPCManager.addPresenceEndTime(p, t, e); } @Override public String toString(@Nullable Event event, boolean b) { return null; } @Override public boolean init(Expression<?>[] expressions, int i, Kleenean kleenean, SkriptParser.ParseResult parseResult) { title = (Expression<String>) expressions[0]; endTime = (Expression<Integer>) expressions[1]; player = (Expression<Player>) expressions[2]; return true; } }
0
0.824389
1
0.824389
game-dev
MEDIA
0.734416
game-dev
0.914097
1
0.914097
deltanedas/routorio-old
2,764
scripts/units/router-chainer.js
/* Copyright (c) deltanedas 2024 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 <https://www.gnu.org/licenses/>. */ /* Factory for routorio's units */ const UnitPlan = UnitFactory.UnitPlan; const routorio = global.routorio; const chainer = extend(UnitFactory, "router-chainer", { init() { // TODO: Use reconstructor for sexy -> chain -> reverout? // TODO: balance unit costs in respect to dagger -> crawler -> azimuth chainer.plans = Seq.with( new UnitPlan(routorio["sexy-router"], 60 * 5, ItemStack.with(Items.silicon, 5, Items.copper, 6)), new UnitPlan(routorio.routerpede, 60 * 20, ItemStack.with(Items.silicon, 30, Items.graphite, 80)), new UnitPlan(routorio.reverout, 60 * 30, ItemStack.with(Items.silicon, 120, Items.titanium, 70, Items.graphite, 160))); this.super$init(); }, load() { this.super$load(); this.topRegion = this.outRegion = Core.atlas.find("clear"); this.region = Core.atlas.find(this.name + "-base"); this.router = Core.atlas.find("router"); this.surge = Core.atlas.find("routorio-surge-router"); this.laser = Core.atlas.find("laser"); this.laserEnd = Core.atlas.find("laser-end"); } }); chainer.buildType = () => extend(UnitFactory.UnitFactoryBuild, chainer, { draw() { const dx = this.x, dy = this.y; Draw.rect(chainer.region, dx, dy); Draw.z(Layer.turret); this.rot = Mathf.lerp(this.rot, Math.min(this.efficiency, 1) * this.timeScale, 0.02); const rot = Time.time * this.rot; const chaining = this.efficiency > 0; this.dist = Mathf.lerp(this.dist, this.plan ? this.plan.type.size / 40 : 4 * this.rot + 8, 0.04); for (var i = 0; i < 8; i++) { var angle = rot + 360 * i / 8; var x = dx + Angles.trnsx(angle, this.dist); var y = dy + Angles.trnsy(angle, this.dist); if (chaining) { Drawf.laser(chainer.laser, chainer.laserEnd, // imaginary = hide laser x, y, dx, dy, Math.sqrt(Math.sin(angle / 50) / 5)); // Surge routers face the center when at max dist Draw.rect(chainer.surge, x, y, angle); //Mathf.slerp(0, angle,this.dist / 24)); } else { Draw.rect(chainer.router, x, y); } } }, // Routers start by folding out dist: 0, rot: 0 }); module.exports = chainer;
0
0.914871
1
0.914871
game-dev
MEDIA
0.492326
game-dev
0.960514
1
0.960514
dimitriv/Ziria
12,555
csrc/buf.h
/* Copyright (c) Microsoft Corporation 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ #pragma once #include "types.h" #include "params.h" #include "utils.h" #include "bit.h" typedef enum __GetStatus { GS_SUCCESS, GS_EOF } GetStatus; typedef struct _BufContextBlock { // Bit buffers BitArrPtr bit_input_buffer; unsigned int bit_input_entries; unsigned int bit_input_idx; unsigned int bit_input_repetitions; unsigned int bit_input_dummy_samples; unsigned int bit_max_dummy_samples; int bit_fst; unsigned char * bit_output_buffer; unsigned int bit_output_entries; unsigned int bit_output_idx; FILE *bit_output_file; // Byte buffer /* A buffer of elements, each element of size chunk_size */ void *chunk_input_buffer; size_t chunk_size; unsigned int chunk_input_entries; unsigned int chunk_input_idx; unsigned int chunk_input_repetitions; unsigned int chunk_input_dummy_samples; unsigned int chunk_max_dummy_samples; int chunk_fst; void * chunk_output_buffer; unsigned int chunk_output_entries; unsigned int chunk_output_idx; FILE *chunk_output_file; // Int8 buffers int8 *num8_input_buffer; unsigned int num8_input_entries; unsigned int num8_input_idx; unsigned int num8_input_repeats; unsigned int num8_input_dummy_samples; unsigned int num8_max_dummy_samples; int num8_fst; int8 *num8_output_buffer; unsigned int num8_output_entries; unsigned int num8_output_idx; FILE *num8_output_file; // Int16 buffers int16 *num16_input_buffer; unsigned int num16_input_entries; unsigned int num16_input_idx; unsigned int num16_input_repeats; unsigned int num16_input_dummy_samples; unsigned int num16_max_dummy_samples; int num16_fst; int16 *num16_output_buffer; unsigned int num16_output_entries; unsigned int num16_output_idx; FILE *num16_output_file; // Int32 buffers int32 *num_input_buffer; unsigned int num_input_entries; unsigned int num_input_idx; unsigned int num_input_repeats; unsigned int num_input_dummy_samples; unsigned int num_max_dummy_samples; int num_fst; int32 *num_output_buffer; unsigned int num_output_entries; unsigned int num_output_idx; FILE *num_output_file; // All buffers - callback functions for TY_MEM // These functions are called to replenish buffers, if needed, when they are empty. void(*buf_input_callback) (); void(*buf_output_callback) (); // Buffers for memory input and output // This essentially points to the same location as <type>_input/output_buffer // but it is type-agnostic void *mem_input_buf, *mem_output_buf; unsigned long mem_input_buf_size, mem_output_buf_size; // General statistics unsigned long total_in, total_out; // Total number of data inputs read/written size_t size_in, size_out; // Size of input and output data type (in bits) #ifdef SORA_PLATFORM thread_info *ti; #endif } BufContextBlock; // Defined in buf_bit.c void resetBufCtxBlock(BufContextBlock *blk); void initBufCtxBlock(BufContextBlock *blk); unsigned int parse_dbg_bit(char *dbg_buf, BitArrPtr target); void init_getbit(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); GetStatus buf_getbit(BlinkParams *params, BufContextBlock *blk, Bit *x); GetStatus buf_getarrbit(BlinkParams *params, BufContextBlock *blk, BitArrPtr x, unsigned int vlen); void init_putbit(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); void buf_putbit(BlinkParams *params, BufContextBlock *blk, Bit x); void buf_putarrbit(BlinkParams *params, BufContextBlock *blk, BitArrPtr x, unsigned int vlen); void flush_putbit(BlinkParams *params, BufContextBlock *blk); void reset_putbit(BlinkParams *params, BufContextBlock *blk); void init_getchunk(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); GetStatus buf_getchunk(BlinkParams *params, BufContextBlock *blk, void *x); GetStatus buf_getarrchunk(BlinkParams *params, BufContextBlock *blk, void *x, unsigned int vlen); void init_putchunk(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); void buf_putchunk(BlinkParams *params, BufContextBlock *blk, void *x); void buf_putarrchunk(BlinkParams *params, BufContextBlock *blk, void *x, unsigned int vlen); void flush_putchunk(BlinkParams *params, BufContextBlock *blk); void reset_putchunk(BlinkParams *params, BufContextBlock *blk); void init_getint32(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); GetStatus buf_getint32(BlinkParams *params, BufContextBlock *blk, int32 *x); GetStatus buf_getarrint32(BlinkParams *params, BufContextBlock *blk, int32 *x, unsigned int vlen); void init_putint32(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); void buf_putint32(BlinkParams *params, BufContextBlock *blk, int32 x); void buf_putarrint32(BlinkParams *params, BufContextBlock *blk, int32 * x, unsigned int vlen); void flush_putint32(BlinkParams *params, BufContextBlock *blk); void reset_putint32(BlinkParams *params, BufContextBlock *blk); void init_getuint32(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); GetStatus buf_getuint32(BlinkParams *params, BufContextBlock *blk, uint32 *x); GetStatus buf_getarruint32(BlinkParams *params, BufContextBlock *blk, uint32 *x, unsigned int vlen); void init_putuint32(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); void buf_putuint32(BlinkParams *params, BufContextBlock *blk, uint32 x); void buf_putarruint32(BlinkParams *params, BufContextBlock *blk, uint32 * x, unsigned int vlen); void flush_putuint32(BlinkParams *params, BufContextBlock *blk); void reset_putuint32(BlinkParams *params, BufContextBlock *blk); void init_getcomplex32(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); GetStatus buf_getcomplex32(BlinkParams *params, BufContextBlock *blk, struct complex32 *x); GetStatus buf_getarrcomplex32(BlinkParams *params, BufContextBlock *blk, struct complex32 * x, unsigned int vlen); void init_putcomplex32(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); void buf_putcomplex32(BlinkParams *params, BufContextBlock *blk, struct complex32 x); void buf_putarrcomplex32(BlinkParams *params, BufContextBlock *blk, struct complex32 *x, unsigned int vlen); void flush_putcomplex32(BlinkParams *params, BufContextBlock *blk); void reset_putcomplex32(BlinkParams *params, BufContextBlock *blk); unsigned int parse_dbg_int16(char *dbg_buf, int16 *target); void init_getint16(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); GetStatus buf_getint16(BlinkParams *params, BufContextBlock *blk, int16 *x); GetStatus buf_getarrint16(BlinkParams *params, BufContextBlock *blk, int16 *x, unsigned int vlen); void init_putint16(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); void buf_putint16(BlinkParams *params, BufContextBlock *blk, int16 x); void buf_putarrint16(BlinkParams *params, BufContextBlock *blk, int16 * x, unsigned int vlen); void flush_putint16(BlinkParams *params, BufContextBlock *blk); void reset_putint16(BlinkParams *params, BufContextBlock *blk); unsigned int parse_dbg_uint16(char *dbg_buf, uint16 *target); void init_getuint16(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); GetStatus buf_getuint16(BlinkParams *params, BufContextBlock *blk, uint16 *x); GetStatus buf_getarruint16(BlinkParams *params, BufContextBlock *blk, uint16 *x, unsigned int vlen); void init_putuint16(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); void buf_putuint16(BlinkParams *params, BufContextBlock *blk, uint16 x); void buf_putarruint16(BlinkParams *params, BufContextBlock *blk, uint16 * x, unsigned int vlen); void flush_putuint16(BlinkParams *params, BufContextBlock *blk); void reset_putuint16(BlinkParams *params, BufContextBlock *blk); void init_getcomplex16(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); GetStatus buf_getcomplex16(BlinkParams *params, BufContextBlock *blk, struct complex16 *x); GetStatus buf_getarrcomplex16(BlinkParams *params, BufContextBlock *blk, struct complex16 * x, unsigned int vlen); void init_putcomplex16(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); void buf_putcomplex16(BlinkParams *params, BufContextBlock *blk, struct complex16 x); void buf_putarrcomplex16(BlinkParams *params, BufContextBlock *blk, struct complex16 *x, unsigned int vlen); void flush_putcomplex16(BlinkParams *params, BufContextBlock *blk); void reset_putcomplex16(BlinkParams *params, BufContextBlock *blk); void init_getint8(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); GetStatus buf_getint8(BlinkParams *params, BufContextBlock *blk, int8 *x); GetStatus buf_getarrint8(BlinkParams *params, BufContextBlock *blk, int8 *x, unsigned int vlen); void init_putint8(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); void buf_putint8(BlinkParams *params, BufContextBlock *blk, int8 x); void buf_putarrint8(BlinkParams *params, BufContextBlock *blk, int8 * x, unsigned int vlen); void flush_putint8(BlinkParams *params, BufContextBlock *blk); void reset_putint8(BlinkParams *params, BufContextBlock *blk); void init_getuint8(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); GetStatus buf_getuint8(BlinkParams *params, BufContextBlock *blk, uint8 *x); GetStatus buf_getarruint8(BlinkParams *params, BufContextBlock *blk, uint8 *x, unsigned int vlen); void init_putuint8(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); void buf_putuint8(BlinkParams *params, BufContextBlock *blk, uint8 x); void buf_putarruint8(BlinkParams *params, BufContextBlock *blk, uint8 * x, unsigned int vlen); void flush_putuint8(BlinkParams *params, BufContextBlock *blk); void reset_putuint8(BlinkParams *params, BufContextBlock *blk); void init_getcomplex8(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); GetStatus buf_getcomplex8(BlinkParams *params, BufContextBlock *blk, struct complex8 *x); GetStatus buf_getarrcomplex8(BlinkParams *params, BufContextBlock *blk, struct complex8 * x, unsigned int vlen); void init_putcomplex8(BlinkParams *params, BufContextBlock *blk, HeapContextBlock *hblk, size_t unit_size); void buf_putcomplex8(BlinkParams *params, BufContextBlock *blk, struct complex8 x); void buf_putarrcomplex8(BlinkParams *params, BufContextBlock *blk, struct complex8 *x, unsigned int vlen); void flush_putcomplex8(BlinkParams *params, BufContextBlock *blk); void reset_putcomplex8(BlinkParams *params, BufContextBlock *blk); #ifdef SORA_PLATFORM FINL void write_time_stamp(BlinkParams *params) { if (params->latencySampling > 0) { if (params->measurementInfo.nSamples % params->latencySampling == 0) { ULONGLONG time = SoraGetCPUTimestamp(&(params->measurementInfo.tsinfo)); ULONGLONG diff = time - (params->measurementInfo.lastWrite); // Skip the first difference (the first two samples) as this one is usually an outlier if (params->measurementInfo.lastWrite > 0 && params->measurementInfo.nSamples / params->latencySampling > 1) { if (params->measurementInfo.aDiffPtr < params->latencyCDFSize) { params->measurementInfo.aDiff[params->measurementInfo.aDiffPtr] = diff; params->measurementInfo.aDiffPtr++; } if (diff < params->measurementInfo.minDiff) { params->measurementInfo.minDiff = diff; } if (diff > params->measurementInfo.maxDiff) { params->measurementInfo.maxDiff = diff; } } params->measurementInfo.lastWrite = time; } params->measurementInfo.nSamples++; } } #else #define write_time_stamp(x) #endif
0
0.837837
1
0.837837
game-dev
MEDIA
0.174148
game-dev
0.738879
1
0.738879
sniperHW/Survive
13,382
gameserver/battlebag.lua
local Cjson = require "cjson" local Name2idx = require "common.name2idx" local NetCmd = require "netcmd.netcmd" --local Db = require "common.db" --local MsgHandler = require "netcmd.msghandler" local bag = {} function bag:new() local o = {} setmetatable(o, self) self.__index = self return o end function bag:Init(ply,battlebag) --for k,v in pairs(battlebag) do -- print(v.id,v.count) --end self.bag = {} for k,v in pairs(battlebag) do self.bag[v[1] - 4] = {id=v[2],count=v[3],tmpcount = 0} end for i=1,6 do if not self.bag[i] then self.bag[i] = {id=0,count=0,tmpcount = 0} end end self.owner = ply self.flag = {} return self end function bag:AddItem(id,count) local pos for i=1,6 do if self.bag[i].id == id then pos = i break end if not pos and self.bag[i].id == 0 then pos = i end end if not pos then return false end local item = self.bag[pos] if item.id == 0 then item.id = id end --print("bag:AddItem",pos) if item.count + item.tmpcount >= 5 then return false end if item.count + item.tmpcount + count > 5 then local c = 5 - item.tmpcount - item.count item.tmpcount = item.tmpcount + c else item.tmpcount = item.tmpcount + count end self.flag[pos] = true --print("bag:AddItem Success") return true end function bag:RemItem(id,count) local pos for i=1,6 do if self.bag[i].id == id then pos = i end end if pos then local item = self.bag[pos] if item.count + item.tmpcount < count then return false end if item.tmpcount < count then count = count - item.tmpcount item.tmpcount = 0 item.count = item.count - count else item.tmpcount = item.tmpcount - count end if item.tmpcount + item.count == 0 then item.id = 0 end self.flag[pos] = true return true end return false end function bag:NotifyUpdate() local wpk = CPacket.NewWPacket(512) wpk:Write_uint16(NetCmd.CMD_SC_BAGUPDATE) local wpos = wpk:Get_write_pos() wpk:Write_uint8(0) local c = 0 for k,v in pairs(self.flag) do self.flag[k] = nil wpk:Write_uint8(k+4) local item = self.bag[k] wpk:Write_uint16(item.id) wpk:Write_uint16(item.count + item.tmpcount) c = c + 1 end wpk:Rewrite_uint8(wpos,c) self.owner:Send2Client(wpk) end function bag:on_entermap(wpk) wpk:Write_uint8(6) for i = 1,6 do local item = self.bag[i] wpk:Write_uint8(i+4) --print("bag:on_entermap",i+4,item.id) wpk:Write_uint16(item.id) wpk:Write_uint16(item.count + item.tmpcount) end end return { New = function () return bag:new() end, } --[[ function bag:GetItemId(pos) if self.bag[pos] then return self.bag[pos].id else return nil end end function bag:GetBagItem(pos) return self.bag[pos] end function bag:SetBagItem(pos,item) if pos > 0 and pos <= self.bag.size then self.bag[pos] = item self.flag[pos] = true end end function bag:GetItemCount(pos) if self.bag[pos] then return self.bag[pos].count else return nil end end function bag:GetItemAttr(pos,idxs) if self.bag[pos] then if idxs then return self.bag[pos]:GetAttr(idxs) else return self.bag[pos].attr end else return nil end end function bag:SetItemAttr(pos,idxs,vals) if self.bag[pos] then self.bag[pos]:SetAttr(idxs,vals) self.flag[pos] = true end end local function find_battle_item_pos(self,id) if not id then for i=5,10 do if not self.bag[i] then return i end end return nil else local firstempty = nil for i=5,10 do if self.bag[i] then if self.bag[i].id == id then return i end elseif not firstempty then firstempty = i end end return firstempty end end local function findbagpos(self,id) if not id then for i=11,self.bag.size do if not self.bag[i] then return i end end return nil else local firstempty = nil for i=11,self.bag.size do if self.bag[i] then if self.bag[i].id == id then return i end elseif not firstempty then firstempty = i end end return firstempty end end --向背包新增加一个物品 function bag:AddItem(id,count,attr) if attr then local pos = findbagpos(self) if pos then self.bag[pos] = Item.New(id,count,attr) self.flag[pos] = true return true else return false end else local pos = findbagpos(self,id) if pos then if not self.bag[pos] then self.bag[pos] = Item.New(id,count,attr) else if self.bag[pos].count + count > 65535 then self.bag[pos].count = 65535 else self.bag[pos].count = self.bag[pos].count + count end end self.flag[pos] = true return true else return false end end end function bag:AddItems(items) local bagpos = {} for i = 1,#items do local item = items[i] local tb = TableItem[item[1] ] if not tb then return false end if tb["Item_Type"] < 5 then item.isEquip = true end local fitpos for j=11,self.bag.size do if item.isEquip then if not self.bag[j] and not bagpos[j] then fitpos = j break end else if not self.bag[j] and not fitpos then fitpos = j elseif self.bag[j] and self.bag[j].id == item[1] then fitpos = j break end end end if not fitpos then return false end if not bagpos[fitpos] then bagpos[fitpos] = {} end table.insert(bagpos[fitpos],item) end for k,v in pairs(bagpos) do local items = v for k1,v1 in pairs(items) do if v1.isEquip then self.bag[k] = Item.New(v1[1],v1[2],v1[3]) else local count = v1[2] if not self.bag[k] then self.bag[k] = Item.New(v1[1],v1[2]) else if self.bag[k].count + count > 65535 then self.bag[k].count = 65535 else self.bag[k].count = self.bag[k].count + count end end end end self.flag[k] = true end return true end local fashion = 1 local weapon = 2 local belt = 3 local cloth = 4 function bag:LoadBattleItem(pos) if pos >= 11 and pos < self.bag.size then local item = self.bag[pos] if not item then return false end local tb = TableItem[item.id] if not tb then return false end local tag = tb["Tag"] if tag ~= 0 then return false end local maxcount = 5 local battlepos = find_battle_item_pos(self,item.id) local battle_item = self.bag[battlepos] if not battle_item then if item.count <= maxcount then battle_item = item item = nil else battle_item = Item.New(item.id,maxcount) item.count = item.count - maxcount end self:SetBagItem(pos,item) self:SetBagItem(battlepos,battle_item) else local count = maxcount - battle_item.count if count == 0 then return false end if item.count <= count then battle_item.count = battle_item.count + item.count item = nil else battle_item.count = battle_item.count + count item.count = item.count - count end self:SetBagItem(pos,item) self:SetBagItem(battlepos,battle_item) end return true end return false end function bag:UnLoadBattleItem(pos) if pos >= 5 and pos <= 10 then local battle_item = self.bag[pos] if not battle_item then return false end local bagpos = findbagpos(self,battle_item.id) if not bagpos then return false end local item = self.bag[bagpos] if not item then item = battle_item battle_item = nil self:SetBagItem(bagpos,item) self:SetBagItem(pos,battle_item) else item.count = item.count + battle_item.count if item.count > 65535 then item.count = 65535 end battle_item = nil self:SetBagItem(bagpos,item) self:SetBagItem(pos,battle_item) end return true end return false end function bag:Swap(pos1,pos2) if pos1 < 1 or pos1 > self.bag.size then return false end if pos2 < 1 or pos2 > self.bag.size then return false end if pos1 <= 10 and pos2 <= 10 then return false end local item1 = self.bag[pos1] local item2 = self.bag[pos2] if not item1 and not item2 then return false end local type1 local type2 if item1 then local tb1 = TableItem[item1.id] if not tb1 then return false end type1 = tb1["Item_Type"] if not type1 then return false end if pos2 <= cloth then if type1 ~= pos2 then return false end if tb1["Use_level"] > self.owner.attr:Get("level") then return false end elseif pos2 <= 10 then local InBattle = tb1["Tag"] == 0 if not InBattle then return false end end end if item1 and type1 > cloth and item2 and item1.id == item2.id then --merge if item1.count + item2.count > 65535 then item2.count = 65535 else item2.count = item1.count + item2.count end self.bag[pos1] = nil self.flag[pos1] = true self.flag[pos2] = true return true end --ok swap self.bag[pos2] = item1 self.bag[pos1] = item2 self.flag[pos1] = true self.flag[pos2] = true --print("bag:Swap",pos1,pos2,self.bag[pos1],self.bag[pos2]) if pos1 >= weapon and pos1 <= cloth or pos2 >= weapon and pos2 <= cloth then --print("recalattr") return true,"recalattr" else return true end end --根据位置或id移除一定数量的物品 function bag:RemItem(pos,id,count) if id then for i=0,self.bag.size do if self.bag[i] and self.bag[i].id == id then pos = i end end end local item = self.bag[pos] if item and item.count >= count then item.count = item.count - count if item.count == 0 then self.bag[pos] = nil end self.flag[pos] = true return true else return false end end function bag:FetchBattleItem() --print("FetchBattleItem") local battleitem = {} for i=5,10 do local item = self.bag[i] if item then --print(i,item.id,item.count) table.insert(battleitem,{i,item.id,item.count}) end end return battleitem end function bag:OnBegPly(wpk) --先打包battle相关 wpk:Write_uint8(self.bag.size) local wpos = wpk:Get_write_pos() wpk:Write_uint8(0) local c = 0 for k,v in pairs(self.bag) do if k ~= "size" then wpk:Write_uint8(k) v:Pack(wpk) c = c + 1 end end wpk:Rewrite_uint8(wpos,c) end function bag:DbStr() local b = {size = self.bag.size} for i=1,b.size do local item = self.bag[i] if item then local attr = item.attr if attr then b[i] = {id=item.id,count=item.count,attr = attr} else b[i] = {id=item.id,count=item.count} end end end return Cjson.encode(b) end function bag:Save() local cmd = "hmset chaid:" .. self.owner.chaid .. " bag " .. self:DbStr() Db.CommandAsync(cmd) end function bag:NotifyUpdate() local wpk = CPacket.NewWPacket(512) wpk:Write_uint16(NetCmd.CMD_GC_BAGUPDATE) local wpos = wpk:Get_write_pos() wpk:Write_uint8(0) local c = 0 for k,v in pairs(self.flag) do self.flag[k] = nil wpk:Write_uint8(k) local item = self.bag[k] if item then item:Pack(wpk) else Item.PackEmpty(wpk) end c = c + 1 end wpk:Rewrite_uint8(wpos,c) self.owner:Send2Client(wpk) end function bag:PeekInfo(wpk,beg_index,end_index) if end_index > beg_index or end_index > self.bag.size or beg_index < 0 then return false end local size = end_index - beg_index wpk:Write_uint8(size) for i = beg_index,end_index do wpk:Write_uint8(i) local item = self.bag[i] if item then item:Pack(wpk) else Item.PackEmpty(wpk) end end return true end MsgHandler.RegHandler(NetCmd.CMD_CG_USEITEM,function (sock,rpk) local groupsession = rpk:Reverse_read_uint16() local ply = GetPlayerBySessionId(groupsession) if ply and ply.bag then end end) MsgHandler.RegHandler(NetCmd.CMD_CG_REMITEM,function (sock,rpk) local groupsession = rpk:Reverse_read_uint16() local ply = GetPlayerBySessionId(groupsession) if ply and ply.bag then local pos1 = rpk:Read_uint8() if ply.bag:RemItem(pos1,nil,65535) then ply.bag:NotifyUpdate() ply.bag:Save() end end end) MsgHandler.RegHandler(NetCmd.CMD_CG_LOADBATTLEITEM,function (sock,rpk) print("CMD_CG_LOADBATTLEITEM") local groupsession = rpk:Reverse_read_uint16() local ply = GetPlayerBySessionId(groupsession) if ply and ply.bag then local pos = rpk:Read_uint8() if ply.bag:LoadBattleItem(pos) then ply.bag:NotifyUpdate() ply.bag:Save() end end end) MsgHandler.RegHandler(NetCmd.CMD_CG_UNLOADBATTLEITEM,function (sock,rpk) print("CMD_CG_UNLOADBATTLEITEM") local groupsession = rpk:Reverse_read_uint16() local ply = GetPlayerBySessionId(groupsession) if ply and ply.bag then local pos = rpk:Read_uint8() if ply.bag:UnLoadBattleItem(pos) then ply.bag:NotifyUpdate() ply.bag:Save() end end end) MsgHandler.RegHandler(NetCmd.CMD_CG_SWAP,function (sock,rpk) print("CMD_CG_SWAP") local groupsession = rpk:Reverse_read_uint16() local ply = GetPlayerBySessionId(groupsession) if ply and ply.bag then local pos1 = rpk:Read_uint8() local pos2 = rpk:Read_uint8() local ret,action = ply.bag:Swap(pos1,pos2) if ret then ply.bag:NotifyUpdate() ply.bag:Save() if action == "recalattr" then ply:CalAttr(true) end end end end) MsgHandler.RegHandler(NetCmd.CMD_CG_SINGLE_USE_ITEM,function (sock,rpk) print("CMD_CG_SINGLE_USE_ITEM") local groupsession = rpk:Reverse_read_uint16() local ply = GetPlayerBySessionId(groupsession) if ply and ply.bag then local pos = rpk:Read_uint8() if ply.bag:RemItem(pos,nil,1) then ply.bag:NotifyUpdate() ply.bag:Save() end end end) local function newRes(ply,param) return ply.bag:AddItems(param) end return { New = function () return bag:new() end, NewRes = newRes, fashion = fashion, weapon = weapon, belt = belt, cloth = cloth, } ]]--
0
0.864433
1
0.864433
game-dev
MEDIA
0.828914
game-dev
0.978794
1
0.978794
DeltaV-Station/Delta-v
4,002
Content.Server/_DV/Salvage/Systems/ShelterCapsuleSystem.cs
using Content.Server.Fluids.EntitySystems; using Content.Server.Procedural; using Content.Shared.Administration.Logs; using Content.Shared.Chemistry.Components; using Content.Shared.Database; using Content.Shared._DV.Salvage.Components; using Content.Shared._DV.Salvage.Systems; using Content.Shared.Maps; using Content.Shared.Physics; using Robust.Shared.Map.Components; using Robust.Shared.Maths; using Robust.Shared.Physics; using Robust.Shared.Prototypes; using System.Numerics; namespace Content.Server._DV.Salvage.Systems; public sealed class ShelterCapsuleSystem : SharedShelterCapsuleSystem { [Dependency] private readonly DungeonSystem _dungeon = default!; [Dependency] private readonly EntityLookupSystem _lookup = default!; [Dependency] private readonly IPrototypeManager _proto = default!; [Dependency] private readonly ISharedAdminLogManager _adminLogger = default!; [Dependency] private readonly SharedMapSystem _map = default!; [Dependency] private readonly SmokeSystem _smoke = default!; public static readonly EntProtoId SmokePrototype = "Smoke"; private EntityQuery<FixturesComponent> _fixturesQuery; private HashSet<EntityUid> _entities = new(); public override void Initialize() { base.Initialize(); _fixturesQuery = GetEntityQuery<FixturesComponent>(); } protected override LocId? TrySpawnRoom(Entity<ShelterCapsuleComponent> ent) { var xform = Transform(ent); if (xform.GridUid is not {} gridUid || !TryComp<MapGridComponent>(gridUid, out var grid)) return "shelter-capsule-error-space"; var center = _map.LocalToTile(gridUid, grid, xform.Coordinates); var room = _proto.Index(ent.Comp.Room); var origin = center - room.Size / 2; // check that every tile it needs isn't blocked var mask = (int) CollisionGroup.MobMask; if (IsAreaBlocked(gridUid, center, room.Size, mask)) return "shelter-capsule-error-obstructed"; // check that it isn't on space or SpawnRoom will crash for (int y = 0; y < room.Size.Y; y++) { for (int x = 0; x < room.Size.X; x++) { var pos = origin + new Vector2i(x, y); var tile = _map.GetTileRef((gridUid, grid), pos); if (tile.Tile.IsEmpty) return "shelter-capsule-error-space"; } } var user = ent.Comp.User; _adminLogger.Add(LogType.Action, LogImpact.High, $"{ToPrettyString(user):user} expanded {ToPrettyString(ent):capsule} at {center} on {ToPrettyString(gridUid):grid}"); _dungeon.SpawnRoom(gridUid, grid, origin, room, new Random(), null, clearExisting: true); // already checked for mobs and structures here var smoke = Spawn(SmokePrototype, xform.Coordinates); var spreadAmount = (int) room.Size.Length * 2; _smoke.StartSmoke(smoke, new Solution(), 3f, spreadAmount); QueueDel(ent); return null; } private bool IsAreaBlocked(EntityUid grid, Vector2i center, Vector2i size, int mask) { // This is scaled to 95 % so it doesn't encompass walls on other tiles. var aabb = Box2.CenteredAround(center, size * 0.95f); _entities.Clear(); _lookup.GetLocalEntitiesIntersecting(grid, aabb, _entities, LookupFlags.Dynamic | LookupFlags.Static); foreach (var uid in _entities) { // don't care about non-physical entities if (!_fixturesQuery.TryComp(uid, out var fixtures)) continue; foreach (var fixture in fixtures.Fixtures.Values) { if (!fixture.Hard) continue; if ((fixture.CollisionLayer & mask) != 0) return true; } } return false; // no entities colliding with the mask found } }
0
0.942676
1
0.942676
game-dev
MEDIA
0.920081
game-dev
0.948364
1
0.948364
Griizz/Fortnite-Hack
1,216
SDK/FN_TooltipDurabilityMeter_parameters.hpp
#pragma once // Fortnite SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function TooltipDurabilityMeter.TooltipDurabilityMeter_C.Draw struct UTooltipDurabilityMeter_C_Draw_Params { float Normalized; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) struct FFortDisplayAttribute Display_Attribute; // (CPF_Parm) }; // Function TooltipDurabilityMeter.TooltipDurabilityMeter_C.Construct struct UTooltipDurabilityMeter_C_Construct_Params { }; // Function TooltipDurabilityMeter.TooltipDurabilityMeter_C.ExecuteUbergraph_TooltipDurabilityMeter struct UTooltipDurabilityMeter_C_ExecuteUbergraph_TooltipDurabilityMeter_Params { int EntryPoint; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
0
0.566727
1
0.566727
game-dev
MEDIA
0.844477
game-dev
0.569665
1
0.569665
magefree/mage
4,336
Mage.Sets/src/mage/cards/r/RalMonsoonMage.java
package mage.cards.r; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.dynamicvalue.common.InstantAndSorceryCastThisTurn; import mage.constants.Pronoun; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.common.SpellCastControllerTriggeredAbility; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.DamageControllerEffect; import mage.abilities.effects.common.ExileAndReturnSourceEffect; import mage.abilities.effects.common.cost.SpellsCostReductionControllerEffect; import mage.abilities.keyword.TransformAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.filter.FilterCard; import mage.filter.StaticFilters; import mage.filter.common.FilterInstantOrSorceryCard; import mage.game.Game; import mage.game.events.GameEvent; import mage.players.Player; import java.util.UUID; /** * @author Susucr */ public final class RalMonsoonMage extends CardImpl { private static final FilterCard filter = new FilterInstantOrSorceryCard("Instant and sorcery spells"); public RalMonsoonMage(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{R}"); this.supertype.add(SuperType.LEGENDARY); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.WIZARD); this.power = new MageInt(1); this.toughness = new MageInt(3); this.secondSideCardClazz = RalLeylineProdigy.class; // Instant and sorcery spells you cast cost {1} less to cast. this.addAbility(new SimpleStaticAbility(new SpellsCostReductionControllerEffect(filter, 1))); // Whenever you cast an instant or sorcery spell during your turn, flip a coin. If you lose the flip, Ral, Monsoon Mage deals 1 damage to you. If you win the flip, you may exile Ral. If you do, return him to the battlefield transformed under his owner control. this.addAbility(new TransformAbility()); this.addAbility(new RalMonsoonMageTriggeredAbility() .addHint(InstantAndSorceryCastThisTurn.YOU.getHint())); } private RalMonsoonMage(final RalMonsoonMage card) { super(card); } @Override public RalMonsoonMage copy() { return new RalMonsoonMage(this); } } class RalMonsoonMageTriggeredAbility extends SpellCastControllerTriggeredAbility { RalMonsoonMageTriggeredAbility() { super(new RalMonsoonMageEffect(), StaticFilters.FILTER_SPELL_AN_INSTANT_OR_SORCERY, false); setTriggerPhrase("Whenever you cast an instant or sorcery spell during your turn, "); } private RalMonsoonMageTriggeredAbility(final RalMonsoonMageTriggeredAbility ability) { super(ability); } @Override public RalMonsoonMageTriggeredAbility copy() { return new RalMonsoonMageTriggeredAbility(this); } @Override public boolean checkTrigger(GameEvent event, Game game) { return game.getActivePlayerId().equals(getControllerId()) && super.checkTrigger(event, game); } } class RalMonsoonMageEffect extends OneShotEffect { RalMonsoonMageEffect() { super(Outcome.Benefit); staticText = "flip a coin. If you lose the flip, {this} deals 1 damage to you. " + "If you win the flip, you may exile {this}. If you do, return him to the battlefield transformed under his owner's control"; } private RalMonsoonMageEffect(final RalMonsoonMageEffect effect) { super(effect); } @Override public RalMonsoonMageEffect copy() { return new RalMonsoonMageEffect(this); } @Override public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getControllerId()); if (player == null) { return false; } boolean wonFlip = player.flipCoin(source, game, true); if (wonFlip) { if (player.chooseUse(outcome, "Exile {this} and return transformed?", source, game)) { new ExileAndReturnSourceEffect(PutCards.BATTLEFIELD_TRANSFORMED, Pronoun.HE) .apply(game, source); } } else { new DamageControllerEffect(1) .apply(game, source); } return true; } }
0
0.981165
1
0.981165
game-dev
MEDIA
0.990709
game-dev
0.999386
1
0.999386
NASA-NJU/Pyrrha-NS3
2,114
src/core/model/simulation-singleton.h
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #ifndef SIMULATION_SINGLETON_H #define SIMULATION_SINGLETON_H namespace ns3 { /** * This singleton class template ensures that the type * for which we want a singleton has a lifetime bounded * by the simulation lifetime. That it, the underlying * type will be automatically deleted upon a users' call * to Simulator::Destroy. */ template <typename T> class SimulationSingleton { public: /** * \returns the instance underlying this singleton. * * This instance will be automatically deleted when the * user calls ns3::Simulator::Destroy. */ static T *Get (void); private: static T **GetObject (void); static void DeleteObject (void); }; } // namespace ns3 #include "simulator.h" namespace ns3 { template <typename T> T * SimulationSingleton<T>::Get (void) { T ** ppobject = GetObject (); return *ppobject; } template <typename T> T ** SimulationSingleton<T>::GetObject (void) { static T *pobject = 0; if (pobject == 0) { pobject = new T (); Simulator::ScheduleDestroy (&SimulationSingleton<T>::DeleteObject); } return &pobject; } template <typename T> void SimulationSingleton<T>::DeleteObject (void) { T **ppobject = GetObject (); delete (*ppobject); *ppobject = 0; } } // namespace ns3 #endif /* SIMULATION_SINGLETON_H */
0
0.886622
1
0.886622
game-dev
MEDIA
0.144832
game-dev
0.723645
1
0.723645
FMXExpress/Firemonkey
5,860
Embarcadero/Berlin/Object Pascal/TestBed/Tests/DumpShell.pas
//--------------------------------------------------------------------------- // This software is Copyright (c) 2015 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit DumpShell; interface uses Test; type TDumpShell = class(TTest) protected public constructor Create; class function CreateTest: TTest; static; end; implementation uses System.Math, Box2D.Common, Box2D.Collision, Box2D.Dynamics, DebugDraw; constructor TDumpShell.Create; var g: b2Vec2; bodies: array [0..2] of b2BodyWrapper; bd: b2BodyDef; fd: b2FixtureDef; shape: b2PolygonShapeWrapper; vs: array [0..7] of b2Vec2; begin inherited Create; //Source code dump of Box2D scene: issue304-minimal-case.rube // // Created by R.U.B.E 1.3.0 // Using Box2D version 2.3.0 // Wed April 3 2013 04:33:28 // // This code is originally intended for use in the Box2D testbed, // but you can easily use it in other applications by providing // a b2World for use as the 'm_world' variable in the code below. g := b2Vec2.Create(0.000000000000000e+00, -1.000000000000000e+01); m_world.SetGravity(g); //b2Body** bodies = (b2Body** )b2Alloc(3 * sizeof(b2Body* )); //b2Joint** joints = (b2Joint** )b2Alloc(0 * sizeof(b2Joint* )); bd := b2BodyDef.Create; bd.&type := b2BodyType(0); bd.position.&Set(2.587699890136719e-02, 5.515012264251709e+00); bd.angle := 0.000000000000000e+00; bd.linearVelocity.&Set(0.000000000000000e+00, 0.000000000000000e+00); bd.angularVelocity := 0.000000000000000e+00; bd.linearDamping := 0.000000000000000e+00; bd.angularDamping := 0.000000000000000e+00; bd.allowSleep := True;//bool(4); bd.awake := True;//bool(2); bd.fixedRotation := False;//bool(0); bd.bullet := False;//bool(0); bd.active := True;//bool(32); bd.gravityScale := 1.000000000000000e+00; bodies[0] := m_world.CreateBody(@bd); fd := b2FixtureDef.Create; fd.friction := 2.000000029802322e-01; fd.restitution := 0.000000000000000e+00; fd.density := 1.000000000000000e+00; fd.isSensor := False;//bool(0); fd.filter.categoryBits := uint16(1); fd.filter.maskBits := uint16(65535); fd.filter.groupIndex := int16(0); shape := b2PolygonShapeWrapper.Create; vs[0].&Set(7.733039855957031e-01, -1.497260034084320e-01); vs[1].&Set(-4.487270116806030e-01, 1.138330027461052e-01); vs[2].&Set(-1.880589962005615e+00, -1.365900039672852e-01); vs[3].&Set(3.972740173339844e-01, -3.897832870483398e+00); shape.&Set(@vs[0], 4); fd.shape := shape; bodies[0].CreateFixture(@fd); shape.Destroy; bd := b2BodyDef.Create; bd.&type := b2BodyType(2); bd.position.&Set(-3.122138977050781e-02, 7.535382270812988e+00); bd.angle := -1.313644275069237e-02; bd.linearVelocity.&Set(8.230687379837036e-01, 7.775862514972687e-02); bd.angularVelocity := 3.705333173274994e-02; bd.linearDamping := 0.000000000000000e+00; bd.angularDamping := 0.000000000000000e+00; bd.allowSleep := True;//bool(4); bd.awake := True;//bool(2); bd.fixedRotation := False;//bool(0); bd.bullet := False;//bool(0); bd.active := True;//bool(32); bd.gravityScale := 1.000000000000000e+00; bodies[1] := m_world.CreateBody(@bd); fd := b2FixtureDef.Create; fd.friction := 5.000000000000000e-01; fd.restitution := 0.000000000000000e+00; fd.density := 5.000000000000000e+00; fd.isSensor := False;//bool(0); fd.filter.categoryBits := uint16(1); fd.filter.maskBits := uint16(65535); fd.filter.groupIndex := int16(0); shape := b2PolygonShapeWrapper.Create; vs[0].&Set(3.473900079727173e+00, -2.009889930486679e-01); vs[1].&Set(3.457079887390137e+00, 3.694039955735207e-02); vs[2].&Set(-3.116359949111938e+00, 2.348500071093440e-03); vs[3].&Set(-3.109960079193115e+00, -3.581250011920929e-01); vs[4].&Set(-2.590820074081421e+00, -5.472509860992432e-01); vs[5].&Set(2.819370031356812e+00, -5.402340292930603e-01); shape.&Set(@vs[0], 6); fd.shape := shape; bodies[1].CreateFixture(@fd); shape.Destroy; // bd := b2BodyDef.Create; bd.&type := b2BodyType(2); bd.position.&Set(-7.438077926635742e-01, 6.626811981201172e+00); bd.angle := -1.884713363647461e+01; bd.linearVelocity.&Set(1.785794943571091e-01, 3.799796104431152e-07); bd.angularVelocity := -5.908820639888290e-06; bd.linearDamping := 0.000000000000000e+00; bd.angularDamping := 0.000000000000000e+00; bd.allowSleep := True;//bool(4); bd.awake := True;//bool(2); bd.fixedRotation := False;//bool(0); bd.bullet := False;//bool(0); bd.active := True;//bool(32); bd.gravityScale := 1.000000000000000e+00; bodies[2] := m_world.CreateBody(@bd); fd := b2FixtureDef.Create; fd.friction := 9.499999880790710e-01; fd.restitution := 0.000000000000000e+00; fd.density := 1.000000000000000e+01; fd.isSensor := False;//bool(0); fd.filter.categoryBits := uint16(1); fd.filter.maskBits := uint16(65535); fd.filter.groupIndex := int16(-3); shape := b2PolygonShapeWrapper.Create; vs[0].&Set(1.639146506786346e-01, 4.428443685173988e-02); vs[1].&Set(-1.639146655797958e-01, 4.428443685173988e-02); vs[2].&Set(-1.639146655797958e-01, -4.428443312644958e-02); vs[3].&Set(1.639146357774734e-01, -4.428444057703018e-02); shape.&Set(@vs[0], 4); fd.shape := shape; bodies[2].CreateFixture(@fd); shape.Destroy; end; class function TDumpShell.CreateTest: TTest; begin Result := TDumpShell.Create; end; initialization RegisterTest(TestEntry.Create('DumpShell', @TDumpShell.CreateTest)); end.
0
0.86218
1
0.86218
game-dev
MEDIA
0.584451
game-dev
0.867528
1
0.867528
WoWUIDev/Ace3
8,070
AceGUI-3.0/widgets/AceGUIWidget-Slider.lua
--[[----------------------------------------------------------------------------- Slider Widget Graphical Slider, like, for Range values. -------------------------------------------------------------------------------]] local Type, Version = "Slider", 23 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local min, max, floor = math.min, math.max, math.floor local tonumber, pairs = tonumber, pairs -- WoW APIs local PlaySound = PlaySound local CreateFrame, UIParent = CreateFrame, UIParent --[[----------------------------------------------------------------------------- Support functions -------------------------------------------------------------------------------]] local function UpdateText(self) local value = self.value or 0 if self.ispercent then self.editbox:SetText(("%s%%"):format(floor(value * 1000 + 0.5) / 10)) else self.editbox:SetText(floor(value * 100 + 0.5) / 100) end end local function UpdateLabels(self) local min_value, max_value = (self.min or 0), (self.max or 100) if self.ispercent then self.lowtext:SetFormattedText("%s%%", (min_value * 100)) self.hightext:SetFormattedText("%s%%", (max_value * 100)) else self.lowtext:SetText(min_value) self.hightext:SetText(max_value) end end --[[----------------------------------------------------------------------------- Scripts -------------------------------------------------------------------------------]] local function Control_OnEnter(frame) frame.obj:Fire("OnEnter") end local function Control_OnLeave(frame) frame.obj:Fire("OnLeave") end local function Frame_OnMouseDown(frame) frame.obj.slider:EnableMouseWheel(true) AceGUI:ClearFocus() end local function Slider_OnValueChanged(frame, newvalue) local self = frame.obj if not frame.setup then if self.step and self.step > 0 then local min_value = self.min or 0 newvalue = floor((newvalue - min_value) / self.step + 0.5) * self.step + min_value end if newvalue ~= self.value and not self.disabled then self.value = newvalue self:Fire("OnValueChanged", newvalue) end if self.value then UpdateText(self) end end end local function Slider_OnMouseUp(frame) local self = frame.obj self:Fire("OnMouseUp", self.value) end local function Slider_OnMouseWheel(frame, v) local self = frame.obj if not self.disabled then local value = self.value if v > 0 then value = min(value + (self.step or 1), self.max) else value = max(value - (self.step or 1), self.min) end self.slider:SetValue(value) end end local function EditBox_OnEscapePressed(frame) frame:ClearFocus() end local function EditBox_OnEnterPressed(frame) local self = frame.obj local value = frame:GetText() if self.ispercent then value = value:gsub('%%', '') value = tonumber(value) / 100 else value = tonumber(value) end if value then PlaySound(856) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON self.slider:SetValue(value) self:Fire("OnMouseUp", value) end end local function EditBox_OnEnter(frame) frame:SetBackdropBorderColor(0.5, 0.5, 0.5, 1) end local function EditBox_OnLeave(frame) frame:SetBackdropBorderColor(0.3, 0.3, 0.3, 0.8) end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetWidth(200) self:SetHeight(44) self:SetDisabled(false) self:SetIsPercent(nil) self:SetSliderValues(0,100,1) self:SetValue(0) self.slider:EnableMouseWheel(false) end, -- ["OnRelease"] = nil, ["SetDisabled"] = function(self, disabled) self.disabled = disabled if disabled then self.slider:EnableMouse(false) self.label:SetTextColor(.5, .5, .5) self.hightext:SetTextColor(.5, .5, .5) self.lowtext:SetTextColor(.5, .5, .5) --self.valuetext:SetTextColor(.5, .5, .5) self.editbox:SetTextColor(.5, .5, .5) self.editbox:EnableMouse(false) self.editbox:ClearFocus() else self.slider:EnableMouse(true) self.label:SetTextColor(1, .82, 0) self.hightext:SetTextColor(1, 1, 1) self.lowtext:SetTextColor(1, 1, 1) --self.valuetext:SetTextColor(1, 1, 1) self.editbox:SetTextColor(1, 1, 1) self.editbox:EnableMouse(true) end end, ["SetValue"] = function(self, value) self.slider.setup = true self.slider:SetValue(value) self.value = value UpdateText(self) self.slider.setup = nil end, ["GetValue"] = function(self) return self.value end, ["SetLabel"] = function(self, text) self.label:SetText(text) end, ["SetSliderValues"] = function(self, min_value, max_value, step) local frame = self.slider frame.setup = true self.min = min_value self.max = max_value self.step = step frame:SetMinMaxValues(min_value or 0,max_value or 100) UpdateLabels(self) frame:SetValueStep(step or 1) if self.value then frame:SetValue(self.value) end frame.setup = nil end, ["SetIsPercent"] = function(self, value) self.ispercent = value UpdateLabels(self) UpdateText(self) end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local SliderBackdrop = { bgFile = "Interface\\Buttons\\UI-SliderBar-Background", edgeFile = "Interface\\Buttons\\UI-SliderBar-Border", tile = true, tileSize = 8, edgeSize = 8, insets = { left = 3, right = 3, top = 6, bottom = 6 } } local ManualBackdrop = { bgFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeFile = "Interface\\ChatFrame\\ChatFrameBackground", tile = true, edgeSize = 1, tileSize = 5, } local function Constructor() local frame = CreateFrame("Frame", nil, UIParent) frame:EnableMouse(true) frame:SetScript("OnMouseDown", Frame_OnMouseDown) local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal") label:SetPoint("TOPLEFT") label:SetPoint("TOPRIGHT") label:SetJustifyH("CENTER") label:SetHeight(15) local slider = CreateFrame("Slider", nil, frame, "BackdropTemplate") slider:SetOrientation("HORIZONTAL") slider:SetHeight(15) slider:SetHitRectInsets(0, 0, -10, 0) slider:SetBackdrop(SliderBackdrop) slider:SetThumbTexture("Interface\\Buttons\\UI-SliderBar-Button-Horizontal") slider:SetPoint("TOP", label, "BOTTOM") slider:SetPoint("LEFT", 3, 0) slider:SetPoint("RIGHT", -3, 0) slider:SetValue(0) slider:SetScript("OnValueChanged",Slider_OnValueChanged) slider:SetScript("OnEnter", Control_OnEnter) slider:SetScript("OnLeave", Control_OnLeave) slider:SetScript("OnMouseUp", Slider_OnMouseUp) slider:SetScript("OnMouseWheel", Slider_OnMouseWheel) local lowtext = slider:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall") lowtext:SetPoint("TOPLEFT", slider, "BOTTOMLEFT", 2, 3) local hightext = slider:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall") hightext:SetPoint("TOPRIGHT", slider, "BOTTOMRIGHT", -2, 3) local editbox = CreateFrame("EditBox", nil, frame, "BackdropTemplate") editbox:SetAutoFocus(false) editbox:SetFontObject(GameFontHighlightSmall) editbox:SetPoint("TOP", slider, "BOTTOM") editbox:SetHeight(14) editbox:SetWidth(70) editbox:SetJustifyH("CENTER") editbox:EnableMouse(true) editbox:SetBackdrop(ManualBackdrop) editbox:SetBackdropColor(0, 0, 0, 0.5) editbox:SetBackdropBorderColor(0.3, 0.3, 0.30, 0.80) editbox:SetScript("OnEnter", EditBox_OnEnter) editbox:SetScript("OnLeave", EditBox_OnLeave) editbox:SetScript("OnEnterPressed", EditBox_OnEnterPressed) editbox:SetScript("OnEscapePressed", EditBox_OnEscapePressed) local widget = { label = label, slider = slider, lowtext = lowtext, hightext = hightext, editbox = editbox, alignoffset = 25, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end slider.obj, editbox.obj = widget, widget return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type,Constructor,Version)
0
0.944985
1
0.944985
game-dev
MEDIA
0.861563
game-dev
0.932936
1
0.932936
onnx/onnx-mlir
17,679
src/Accelerators/NNPA/Dialect/ZLow/ZLowOps.cpp
/* * SPDX-License-Identifier: Apache-2.0 */ //===------------------ ZLowOps.cpp - ONNX Operations ---------------------===// // // Copyright 2019-2020 The IBM Research Authors. // // ============================================================================= // // This file defines the ZLow operations in the MLIR operation set. // //===----------------------------------------------------------------------===// #include "mlir/Dialect/Shape/IR/Shape.h" #include "mlir/Dialect/Traits.h" #include "mlir/IR/Block.h" #include "mlir/IR/Builders.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/IR/IntegerSet.h" #include "mlir/IR/Matchers.h" #include "mlir/IR/OpImplementation.h" #include "mlir/IR/PatternMatch.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "src/Accelerators/NNPA/Dialect/ZLow/ZLowOps.hpp" using namespace mlir; namespace onnx_mlir { namespace zlow { //===----------------------------------------------------------------------===// // ZLowDialect //===----------------------------------------------------------------------===// void ZLowDialect::initialize() { addOperations< #define GET_OP_LIST #include "src/Accelerators/NNPA/Dialect/ZLow/ZLowOps.cpp.inc" >(); } void ZLowAddOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getYMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowSubOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getYMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowMulOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getYMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowDivOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getYMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowMinOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getYMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowMaxOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getYMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowLogOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowExpOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowReluOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowTanhOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowSigmoidOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowSoftmaxOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getWorkAreaMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowMatMulOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getYMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getBiasMutable(), SideEffects::DefaultResource::get()); } void ZLowLSTMOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getHnOutputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Write::get(), &getCfOutputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getH0Mutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getC0Mutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputWeightsMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputBiasMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getHiddenWeightsMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getHiddenBiasMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getWorkAreaMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowGRUOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getHnOutputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getH0Mutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputWeightsMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputBiasMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getHiddenWeightsMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getHiddenBiasMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getWorkAreaMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowStickOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); } void ZLowStickForLSTMOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getFGateMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getIGateMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getCGateMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getOGateMutable(), SideEffects::DefaultResource::get()); } void ZLowStickForGRUOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getZGateMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getRGateMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getHGateMutable(), SideEffects::DefaultResource::get()); } void ZLowUnstickOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getXMutable(), SideEffects::DefaultResource::get()); } void ZLowConv2DOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputKernelMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputBiasMutable(), SideEffects::DefaultResource::get()); } void ZLowAvgPool2DOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowMaxPool2DOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowMeanReduce2DOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } void ZLowBatchNormOp::getEffects( SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> &effects) { effects.emplace_back(MemoryEffects::Write::get(), &getOutputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getInputMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getAMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getBMutable(), SideEffects::DefaultResource::get()); effects.emplace_back(MemoryEffects::Read::get(), &getShapeMutable(), SideEffects::DefaultResource::get()); } //===----------------------------------------------------------------------===// // ZLowOps methods //===----------------------------------------------------------------------===// LogicalResult ZLowQuantizedStickOp::verify() { ZLowQuantizedStickOp::Adaptor operandAdaptor(*this); Value recScale = operandAdaptor.getRecScale(); Value offset = operandAdaptor.getOffset(); Value output = operandAdaptor.getOut(); auto outputType = llvm::dyn_cast<MemRefType>(output.getType()); if (!outputType) return failure(); // Verify quantized type. StringRef quantizedType = getQType(); if (!(quantizedType.equals_insensitive("dlfloat16") || quantizedType.equals_insensitive("int8") || quantizedType.equals_insensitive("weights"))) return emitOpError("q_type must be one of dlfloat16, int8, and weights"); // Verify element type of the output. // TODO: should we have a more stricted contraint, e.g. signed integer? Type elementType = outputType.getElementType(); if (quantizedType.equals_insensitive("dfloat16") && !elementType.isF16()) return emitOpError("q_type and element type mismatched"); if (quantizedType.equals_insensitive("int8") && !elementType.isInteger(8)) return emitOpError("q_type and element type mismatched"); if (quantizedType.equals_insensitive("weights") && !elementType.isInteger(8)) return emitOpError("q_type and element type mismatched"); // Verify recScale and offset. if (auto ty = llvm::dyn_cast<MemRefType>(recScale.getType())) { if (!ty.getElementType().isF32()) return emitOpError("recScale must be f32"); } if (auto ty = llvm::dyn_cast<MemRefType>(offset.getType())) { if (!ty.getElementType().isF32()) return emitOpError("offset must be f32"); } return success(); } } // namespace zlow } // namespace onnx_mlir //===----------------------------------------------------------------------===// // TableGen'd op method definitions //===----------------------------------------------------------------------===// #define GET_OP_CLASSES #include "src/Accelerators/NNPA/Dialect/ZLow/ZLowOps.cpp.inc" #include "src/Accelerators/NNPA/Dialect/ZLow/ZLowDialect.cpp.inc"
0
0.693545
1
0.693545
game-dev
MEDIA
0.401857
game-dev
0.671477
1
0.671477
ghostinthecamera/IGCS-GITC
4,418
Cameras/Resident Evil 7/InjectableGenericCameraSystem/ActionData.cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////// // Part of Injectable Generic Camera System // Copyright(c) 2019, Frans Bouma // All rights reserved. // https://github.com/FransBouma/InjectableGenericCameraSystem // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met : // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and / or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ActionData.h" #include "Globals.h" #include "Utils.h" using namespace std; namespace IGCS { ActionData::~ActionData() {} // altCtrlOptional is only effective for actions which don't have alt/ctrl as a required key. Actions which do have one or more of these // keys as required, will ignore altCtrlOptional and always test for these keys. bool ActionData::isActive(bool altCtrlOptional) { if (!_available) { return false; } // Handle based on input source if (_inputSource == InputSource::Keyboard) { bool toReturn = (Utils::keyDown(_keyCode)) && (_shiftRequired == Utils::shiftPressed()); if ((_altRequired || _ctrlRequired) || !altCtrlOptional) { toReturn = toReturn && (Utils::altPressed() == _altRequired) && (Utils::ctrlPressed() == _ctrlRequired); } return toReturn; } else if (_inputSource == InputSource::Gamepad) { // For gamepad, the _keyCode corresponds to a button code defined in Gamepad::button_t auto& gamepad = Globals::instance().gamePad(); if (!gamepad.isConnected()) { return false; } // Check if the main button is pressed bool mainButtonPressed = gamepad.isButtonPressed(static_cast<Gamepad::button_t>(_keyCode)); if (!mainButtonPressed) { return false; } // Check modifiers bool rbPressed = gamepad.isButtonPressed(Gamepad::button_t::RB); bool lbPressed = gamepad.isButtonPressed(Gamepad::button_t::LB); // ALWAYS do exact modifier matching for gamepad inputs // This ensures bindings with no modifiers won't activate when modifiers are pressed return (rbPressed == _altRequired) && (lbPressed == _ctrlRequired); } return false; } void ActionData::setKeyCode(int newKeyCode) { // if we have a keycode set and this is a different one, we will reset alt/ctrl/shift key requirements as it's a different key altogether. if (_keyCode > 0 && newKeyCode > 0 && newKeyCode != _keyCode) { clear(); } _keyCode = newKeyCode; } void ActionData::clear() { _altRequired = false; _ctrlRequired = false; _shiftRequired = false; _keyCode = 0; } void ActionData::update(int newKeyCode, bool altRequired, bool ctrlRequired, bool shiftRequired, bool isGamepad) { if (isGamepad) { _keyCode = newKeyCode; } else { _keyCode = static_cast<uint8_t>(newKeyCode); } _altRequired = altRequired; _ctrlRequired = ctrlRequired; _shiftRequired = shiftRequired; } }
0
0.822305
1
0.822305
game-dev
MEDIA
0.876003
game-dev
0.592142
1
0.592142
chrisj951/MiyooFlipPortMaster
2,946
App/PortMaster/.portmaster/PortMaster/exlibs/sdl2/keyboard.py
from ctypes import Structure, c_int, c_char_p from ctypes import POINTER as _P from .dll import _bind, SDLFunc, AttributeDict from .stdinc import Uint8, Uint16, Uint32, SDL_bool from .keycode import SDL_Keycode, SDL_Keymod from .scancode import SDL_Scancode from .rect import SDL_Rect from .video import SDL_Window __all__ = [ # Structs "SDL_Keysym", ] # Struct definitions class SDL_Keysym(Structure): _fields_ = [ ("scancode", SDL_Scancode), ("sym", SDL_Keycode), ("mod", Uint16), ("unused", Uint32), ] # Raw ctypes function definitions _funcdefs = [ SDLFunc("SDL_GetKeyboardFocus", None, _P(SDL_Window)), SDLFunc("SDL_GetKeyboardState", [_P(c_int)], _P(Uint8)), SDLFunc("SDL_ResetKeyboard", None, None, added='2.24.0'), SDLFunc("SDL_GetModState", None, SDL_Keymod), SDLFunc("SDL_SetModState", [SDL_Keymod]), SDLFunc("SDL_GetKeyFromScancode", [SDL_Scancode], SDL_Keycode), SDLFunc("SDL_GetScancodeFromKey", [SDL_Keycode], SDL_Scancode), SDLFunc("SDL_GetScancodeName", [SDL_Scancode], c_char_p), SDLFunc("SDL_GetScancodeFromName", [c_char_p], SDL_Scancode), SDLFunc("SDL_GetKeyName", [SDL_Keycode], c_char_p), SDLFunc("SDL_GetKeyFromName", [c_char_p], SDL_Keycode), SDLFunc("SDL_StartTextInput"), SDLFunc("SDL_IsTextInputActive", None, SDL_bool), SDLFunc("SDL_StopTextInput"), SDLFunc("SDL_ClearComposition", added='2.0.22'), SDLFunc("SDL_IsTextInputShown", None, SDL_bool, added='2.0.22'), SDLFunc("SDL_SetTextInputRect", [_P(SDL_Rect)]), SDLFunc("SDL_HasScreenKeyboardSupport", None, SDL_bool), SDLFunc("SDL_IsScreenKeyboardShown", [_P(SDL_Window)], SDL_bool), ] _ctypes = AttributeDict() for f in _funcdefs: _ctypes[f.name] = _bind(f.name, f.args, f.returns, f.added) __all__.append(f.name) # Add all bound functions to module namespace # Aliases for ctypes bindings SDL_GetKeyboardFocus = _ctypes["SDL_GetKeyboardFocus"] SDL_GetKeyboardState = _ctypes["SDL_GetKeyboardState"] SDL_ResetKeyboard = _ctypes["SDL_ResetKeyboard"] SDL_GetModState = _ctypes["SDL_GetModState"] SDL_SetModState = _ctypes["SDL_SetModState"] SDL_GetKeyFromScancode = _ctypes["SDL_GetKeyFromScancode"] SDL_GetScancodeFromKey = _ctypes["SDL_GetScancodeFromKey"] SDL_GetScancodeName = _ctypes["SDL_GetScancodeName"] SDL_GetScancodeFromName = _ctypes["SDL_GetScancodeFromName"] SDL_GetKeyName = _ctypes["SDL_GetKeyName"] SDL_GetKeyFromName = _ctypes["SDL_GetKeyFromName"] SDL_StartTextInput = _ctypes["SDL_StartTextInput"] SDL_IsTextInputActive = _ctypes["SDL_IsTextInputActive"] SDL_StopTextInput = _ctypes["SDL_StopTextInput"] SDL_ClearComposition = _ctypes["SDL_ClearComposition"] SDL_IsTextInputShown = _ctypes["SDL_IsTextInputShown"] SDL_SetTextInputRect = _ctypes["SDL_SetTextInputRect"] SDL_HasScreenKeyboardSupport = _ctypes["SDL_HasScreenKeyboardSupport"] SDL_IsScreenKeyboardShown = _ctypes["SDL_IsScreenKeyboardShown"]
0
0.865729
1
0.865729
game-dev
MEDIA
0.876216
game-dev
0.660777
1
0.660777
Azurency/CQUI_Community-Edition
58,587
Integrations/BTS/UI/tradesupport.lua
include("civ6common") local BACKDROP_DARKER_OFFSET = -85 local BACKDROP_DARKER_OPACITY = 238 local BACKDROP_BRIGHTER_OFFSET = 90 local BACKDROP_BRIGHTER_OPACITY = 250 local Game = Game local Players = Players local Events = Events local ipairs = ipairs local pairs = pairs local L_Lookup = Locale.Lookup -- =========================================================================== -- Local Constants -- =========================================================================== SORT_BY_ID = { FOOD = 1, PRODUCTION = 2, GOLD = 3, SCIENCE = 4, CULTURE = 5, FAITH = 6, TURNS_TO_COMPLETE = 7, ORIGIN_NAME = 8, DESTINATION_NAME = 9 } SORT_ASCENDING = 1; SORT_DESCENDING = 2; -- Yield constants FOOD_INDEX = GameInfo.Yields["YIELD_FOOD"].Index; PRODUCTION_INDEX = GameInfo.Yields["YIELD_PRODUCTION"].Index; GOLD_INDEX = GameInfo.Yields["YIELD_GOLD"].Index; SCIENCE_INDEX = GameInfo.Yields["YIELD_SCIENCE"].Index; CULTURE_INDEX = GameInfo.Yields["YIELD_CULTURE"].Index; FAITH_INDEX = GameInfo.Yields["YIELD_FAITH"].Index; START_INDEX = FOOD_INDEX; END_INDEX = FAITH_INDEX; -- Build lookup table for icons ICON_LOOKUP = {} ICON_LOOKUP[FOOD_INDEX] = "[ICON_Food]" ICON_LOOKUP[PRODUCTION_INDEX] = "[ICON_Production]" ICON_LOOKUP[GOLD_INDEX] = "[ICON_Gold]" ICON_LOOKUP[SCIENCE_INDEX] = "[ICON_Science]" ICON_LOOKUP[CULTURE_INDEX] = "[ICON_Culture]" ICON_LOOKUP[FAITH_INDEX] = "[ICON_Faith]" -- Build lookup table for score functions ScoreFunctionByID = {} ScoreFunctionByID[SORT_BY_ID.FOOD] = function(a) return GetYieldForOriginCity(FOOD_INDEX, a, true) end ScoreFunctionByID[SORT_BY_ID.PRODUCTION] = function(a) return GetYieldForOriginCity(PRODUCTION_INDEX, a, true) end ScoreFunctionByID[SORT_BY_ID.GOLD] = function(a) return GetYieldForOriginCity(GOLD_INDEX, a, true) end ScoreFunctionByID[SORT_BY_ID.SCIENCE] = function(a) return GetYieldForOriginCity(SCIENCE_INDEX, a, true) end ScoreFunctionByID[SORT_BY_ID.CULTURE] = function(a) return GetYieldForOriginCity(CULTURE_INDEX, a, true) end ScoreFunctionByID[SORT_BY_ID.FAITH] = function(a) return GetYieldForOriginCity(FAITH_INDEX, a, true) end ScoreFunctionByID[SORT_BY_ID.TURNS_TO_COMPLETE] = function(a) return GetTurnsToComplete(a, true) end ScoreFunctionByID[SORT_BY_ID.ORIGIN_NAME] = function(a) return GetOriginCityName(a) end ScoreFunctionByID[SORT_BY_ID.DESTINATION_NAME] = function(a) return GetDestinationCityName(a) end -- =========================================================================== -- Variables -- =========================================================================== local m_LocalPlayerRunningRoutes :table = {}; -- Tracks local players active routes (turns remaining) local m_TradersAutomatedSettings :table = {}; -- Tracks traders, and if they are automated local m_Cache :table = {}; -- Cache for all route info -- local debug_func_calls:number = 0; -- local debug_total_calls:number = 0; -- =========================================================================== -- Trader Route tracker - Tracks active routes, turns remaining -- =========================================================================== function GetLocalPlayerRunningRoutes() CheckConsistencyWithMyRunningRoutes(m_LocalPlayerRunningRoutes); return m_LocalPlayerRunningRoutes; end function GetLastRouteForTrader( traderID:number ) -- @Astog NOTE: As of Summer 2017 patch, base game added code to get this info -- Commenting my modded code -- LoadTraderAutomatedInfo(); -- if m_TradersAutomatedSettings[traderID] ~= nil then -- return m_TradersAutomatedSettings[traderID].LastRouteInfo; -- end local pTrader = Players[Game.GetLocalPlayer()]:GetUnits():FindID(traderID) local trade:table = pTrader:GetTrade(); local prevOriginComponentID:table = trade:GetLastOriginTradeCityComponentID(); local prevDestComponentID:table = trade:GetLastDestinationTradeCityComponentID(); -- Make sure the entries are valid. Return nil if not if pTrader ~= nil and prevOriginComponentID.player ~= nil and prevOriginComponentID.player ~= -1 and prevOriginComponentID.id ~= nil and prevOriginComponentID.id ~= -1 and prevDestComponentID.player ~= nil and prevDestComponentID.player ~= -1 and prevDestComponentID.id ~= nil and prevDestComponentID.id ~= -1 then local routeInfo = { OriginCityPlayer = prevOriginComponentID.player, OriginCityID = prevOriginComponentID.id, DestinationCityPlayer = prevDestComponentID.player, DestinationCityID = prevDestComponentID.id }; return routeInfo end return nil end -- Adds the route turns remaining to the table, if it does not exist already function AddRouteWithTurnsRemaining( routeInfo:table, routesTable:table) -- print("Adding route: " .. GetTradeRouteString(routeInfo)); local routeIndex = findIndex(routesTable, routeInfo, CheckRouteEquality); if routeIndex == -1 then local tradePathLength, tripsToDestination, turnsToCompleteRoute = GetRouteInfo(routeInfo); -- Build entry local routeEntry:table = { OriginCityPlayer = routeInfo.OriginCityPlayer; OriginCityID = routeInfo.OriginCityID; DestinationCityPlayer = routeInfo.DestinationCityPlayer; DestinationCityID = routeInfo.DestinationCityID; TraderUnitID = routeInfo.TraderUnitID; TurnsRemaining = turnsToCompleteRoute; }; -- Append entry table.insert(routesTable, routeEntry); SaveRunningRoutesInfo(); else print_debug("AddRouteWithTurnsRemaining: Route already exists in table."); end end -- Decrements routes present. Removes those that completed function UpdateRoutesWithTurnsRemaining( routesTable:table ) for i=1, #routesTable do if routesTable[i].TurnsRemaining ~= nil then routesTable[i].TurnsRemaining = routesTable[i].TurnsRemaining - 1; print_debug("Updated route " .. GetTradeRouteString(routesTable[i]) .. " with turns remaining " .. routesTable[i].TurnsRemaining) end end SaveRunningRoutesInfo(); end -- Checks if routes running in game and the routesTable are consistent with each other function CheckConsistencyWithMyRunningRoutes( routesTable:table ) -- Build currently running routes local routesCurrentlyRunning:table = {}; local localPlayerCities:table = Players[Game.GetLocalPlayer()]:GetCities(); for _, city in localPlayerCities:Members() do local outgoingRoutes = city:GetTrade():GetOutgoingRoutes(); for _, routeInfo in ipairs(outgoingRoutes) do table.insert(routesCurrentlyRunning, routeInfo); end end -- Add all routes in routesCurrentlyRunning table that are not in routesTable for _, route in ipairs(routesCurrentlyRunning) do local routeIndex = findIndex(routesTable, route, CheckRouteEquality); -- Is the route not present? if routeIndex == -1 then -- Add it to the list print_debug(GetTradeRouteString(route) .. " was not present. Adding it to the table."); AddRouteWithTurnsRemaining(route, routesTable, true); end end -- Remove all routes in routesTable, that are not in routesCurrentlyRunning. -- Manually control the indices, so that you can iterate over the table while deleting items within it local i = 1; while i <= table.count(routesTable) do local routeIndex = findIndex( routesCurrentlyRunning, routesTable[i], CheckRouteEquality ); -- Is the route not present? if routeIndex == -1 then print_debug("Route " .. GetTradeRouteString(routesTable[i]) .. " is no longer running. Removing it."); table.remove(routesTable, i) else i = i + 1 end end SaveRunningRoutesInfo(); end function SaveRunningRoutesInfo() -- Dump active routes info -- print("Saving running routes info in PlayerConfig database") local dataDump = DataDumper(m_LocalPlayerRunningRoutes, "localPlayerRunningRoutes"); -- print(dataDump); PlayerConfigurations[Game.GetLocalPlayer()]:SetValue("BTS_LocalPlayerRunningRotues", dataDump); end function LoadRunningRoutesInfo() local localPlayerID = Game.GetLocalPlayer(); if(PlayerConfigurations[localPlayerID]:GetValue("BTS_LocalPlayerRunningRotues") ~= nil) then -- print("Retrieving previous routes PlayerConfig database") local dataDump = PlayerConfigurations[localPlayerID]:GetValue("BTS_LocalPlayerRunningRotues"); -- print(dataDump); loadstring(dataDump)(); m_LocalPlayerRunningRoutes = localPlayerRunningRoutes; else print_debug("No running route data was found, on load.") end -- Check for consistency CheckConsistencyWithMyRunningRoutes(m_LocalPlayerRunningRoutes); end -- --------------------------------------------------------------------------- -- Game event hookups (Local to this file) -- --------------------------------------------------------------------------- local function TradeSupportTracker_OnUnitOperationStarted(ownerID:number, unitID:number, operationID:number) if ownerID == Game.GetLocalPlayer() and operationID == UnitOperationTypes.MAKE_TRADE_ROUTE then -- Unit was just started a trade route. Find the route, and update the tables local localPlayerCities:table = Players[ownerID]:GetCities(); for _, city in localPlayerCities:Members() do local outgoingRoutes = city:GetTrade():GetOutgoingRoutes(); for _, route in ipairs(outgoingRoutes) do if route.TraderUnitID == unitID then -- Add it to the local players runnning routes print_debug("Route just started. Adding Route: " .. GetTradeRouteString(route)); AddRouteWithTurnsRemaining( route, m_LocalPlayerRunningRoutes ); return end end end end end -- Removes trader from currently running routes, when it completes local function TradeSupportTracker_OnUnitOperationsCleared(ownerID:number, unitID:number, operationID:number) if ownerID == Game.GetLocalPlayer() then local pPlayer:table = Players[ownerID]; local pUnit:table = pPlayer:GetUnits():FindID(unitID); if pUnit ~= nil then local unitInfo:table = GameInfo.Units[pUnit:GetUnitType()]; if unitInfo ~= nil and unitInfo.MakeTradeRoute then LoadTraderAutomatedInfo(); -- Remove entry from local players running routes for _, route in ipairs(m_LocalPlayerRunningRoutes) do if route.TraderUnitID == unitID then if m_TradersAutomatedSettings[unitID] == nil then print_debug("Couldn't find trader automated info. Creating one.") m_TradersAutomatedSettings[unitID] = { IsAutomated=false }; end -- Add it to the last route info for trader -- @Astog NOTE: As of Summer 2017 patch, this got added in vanilla code, hence commenting this modded code -- m_TradersAutomatedSettings[unitID].LastRouteInfo = route; -- SaveTraderAutomatedInfo(); print_debug("Removing route " .. GetTradeRouteString(route) .. " from currently running, since it completed."); -- Remove route from currrently running routes RemoveRouteFromTable(route, m_LocalPlayerRunningRoutes, false); SaveRunningRoutesInfo() return end end end end end end local function TradeSupportTracker_OnPlayerTurnActivated( playerID:number, isFirstTime:boolean ) if playerID == Game.GetLocalPlayer() and isFirstTime then UpdateRoutesWithTurnsRemaining(m_LocalPlayerRunningRoutes); end end -- =========================================================================== -- Trader Route Automater - Auto renew, last route -- =========================================================================== function AutomateTrader(traderID:number, isAutomated:boolean, sortSettings:table) LoadTraderAutomatedInfo(); if m_TradersAutomatedSettings[traderID] == nil then m_TradersAutomatedSettings[traderID] = {} end m_TradersAutomatedSettings[traderID].IsAutomated = isAutomated if sortSettings ~= nil and table.count(sortSettings) > 0 then print_debug("Automate trader " .. traderID .. " with top route.") m_TradersAutomatedSettings[traderID].SortSettings = sortSettings else print_debug("Automate trader " .. traderID) end SaveTraderAutomatedInfo(); end function CancelAutomatedTrader(traderID:number) print_debug("Cancelling automation for trader " .. traderID); LoadTraderAutomatedInfo(); if m_TradersAutomatedSettings[traderID] ~= nil then m_TradersAutomatedSettings[traderID].IsAutomated = false; m_TradersAutomatedSettings[traderID].SortSettings = nil; SaveTraderAutomatedInfo(); else print("Error: Could not find automated trader info"); end end function FindTopRoute(originPlayerID:number, originCityID:number, sortSettings:table) local tradeManager:table = Game.GetTradeManager(); local tradeRoutes:table = {}; local players:table = Game.GetPlayers{ Alive=true }; -- Build list of trade routes for _, player in ipairs(players) do local playerID = player:GetID() if CanPossiblyTradeWithPlayer(originPlayerID, playerID) then for _, city in player:GetCities():Members() do local cityID = city:GetID() -- Can we start a trade route with this city? if tradeManager:CanStartRoute(originPlayerID, originCityID, playerID, cityID) then local routeInfo = { OriginCityPlayer = originPlayerID, OriginCityID = originCityID, DestinationCityPlayer = playerID, DestinationCityID = cityID }; tradeRoutes[#tradeRoutes + 1] = routeInfo; end end end end -- Get the top route based on the settings saved when the route was begun. NOTE - Will have cache misses here. return GetTopRouteFromSortSettings( tradeRoutes, sortSettings); end function RenewTradeRoutes() local renewedRoute:boolean = false; -- Load the automated settings, (so that changes from TradeOverview.lua reach here) LoadTraderAutomatedInfo(); local pPlayerUnits:table = Players[Game.GetLocalPlayer()]:GetUnits(); for _, pUnit in pPlayerUnits:Members() do local unitInfo:table = GameInfo.Units[pUnit:GetUnitType()]; local unitID:number = pUnit:GetID(); -- Check if it is a free trader if unitInfo.MakeTradeRoute == true and (not pUnit:HasPendingOperations()) then if m_TradersAutomatedSettings[unitID] ~= nil and m_TradersAutomatedSettings[unitID].IsAutomated then local tradeManager:table = Game.GetTradeManager(); local originCity:table = Cities.GetCityInPlot(pUnit:GetX(), pUnit:GetY()); local originPlayerID = originCity:GetOwner() local originCityID = originCity:GetID() local destinationPlayerID:number; local destinationCityID:number; if m_TradersAutomatedSettings[unitID].SortSettings ~= nil and table.count(m_TradersAutomatedSettings[unitID].SortSettings) > 0 then print_debug("Picking from top sort entry"); -- Get destination based on the top entry local topRoute = FindTopRoute(originPlayerID, originCityID, m_TradersAutomatedSettings[unitID].SortSettings) destinationPlayerID = topRoute.DestinationCityPlayer destinationCityID = topRoute.DestinationCityID else print_debug("Picking last route"); local lastRouteInfo = GetLastRouteForTrader(unitID) if lastRouteInfo ~= nil then destinationPlayerID = lastRouteInfo.DestinationCityPlayer destinationCityID = lastRouteInfo.DestinationCityID end end if tradeManager:CanStartRoute(originPlayerID, originCityID, destinationPlayerID, destinationCityID) then local destinationPlayer = Players[destinationPlayerID] local destinationCity = destinationPlayer:GetCities():FindID(destinationCityID) local operationParams = {}; operationParams[UnitOperationTypes.PARAM_X0] = destinationCity:GetX(); operationParams[UnitOperationTypes.PARAM_Y0] = destinationCity:GetY(); operationParams[UnitOperationTypes.PARAM_X1] = originCity:GetX(); operationParams[UnitOperationTypes.PARAM_Y1] = originCity:GetY(); if (UnitManager.CanStartOperation(pUnit, UnitOperationTypes.MAKE_TRADE_ROUTE, nil, operationParams)) then print_debug("Trader " .. unitID .. " renewed its trade route to " .. L_Lookup(destinationCity:GetName())); -- TODO: Send notification for renewing routes UnitManager.RequestOperation(pUnit, UnitOperationTypes.MAKE_TRADE_ROUTE, operationParams); renewedRoute = true else print("ERROR : Could not start a route"); end else print("ERROR : Could not renew a route. Missing route info, or the destination is no longer a valid trade route destination."); end end end end -- Play sound, if a route was renewed. -- Done here to ensure the sound was only played once, if multiple traders were automated if renewedRoute then UI.PlaySound("START_TRADE_ROUTE"); SaveTraderAutomatedInfo() end end function IsTraderAutomated(traderID:number) LoadTraderAutomatedInfo(); if m_TradersAutomatedSettings[traderID] ~= nil then return m_TradersAutomatedSettings[traderID].IsAutomated; end return false; end function SaveTraderAutomatedInfo() -- Dump active routes info local localPlayerID = Game.GetLocalPlayer(); -- print("Saving Trader Automated info in PlayerConfig database") local dataDump = DataDumper(m_TradersAutomatedSettings, "traderAutomatedSettings"); -- print(dataDump); PlayerConfigurations[localPlayerID]:SetValue("BTS_TraderAutomatedSettings", dataDump); end function LoadTraderAutomatedInfo() local localPlayerID = Game.GetLocalPlayer(); if(PlayerConfigurations[localPlayerID]:GetValue("BTS_TraderAutomatedSettings") ~= nil) then -- print("Retrieving trader automated settings from PlayerConfig database") local dataDump = PlayerConfigurations[localPlayerID]:GetValue("BTS_TraderAutomatedSettings"); -- print(dataDump); loadstring(dataDump)(); m_TradersAutomatedSettings = traderAutomatedSettings; else print("ERROR : No running route data was found, on load.") end end -- --------------------------------------------------------------------------- -- Game event hookups (Local to this file) -- --------------------------------------------------------------------------- local function TradeSupportAutomater_OnPlayerTurnActivated( playerID:number, isFirstTime:boolean ) if playerID == Game.GetLocalPlayer() and isFirstTime then RenewTradeRoutes(); end end -- =========================================================================== -- Cache Functions -- =========================================================================== function CacheRoutesInfo(tRoutes) if m_Cache.TurnBuilt ~= nil and m_Cache.TurnBuilt >= Game.GetCurrentGameTurn() then print_debug("OPT: Cache table already upto date") return false else print_debug("Caching routes") -- for i, routeInfo in ipairs(tRoutes) do for i=1, #tRoutes do CacheRoute(tRoutes[i]) CachePlayer(tRoutes[i].DestinationCityPlayer) end m_Cache.TurnBuilt = Game.GetCurrentGameTurn() return true end end function CacheRoute(routeInfo) local key:string = GetRouteKey(routeInfo); -- print("Key for " .. GetTradeRouteString(routeInfo) .. " is " .. key) m_Cache[key] = {} ------------------------------------------------- -- Yields ------------------------------------------------- m_Cache[key].Yields = {} local netOriginYield:number = 0 local netDestinationYield:number = 0 for yieldIndex = START_INDEX, END_INDEX do local originYield = GetYieldForOriginCity(yieldIndex, routeInfo) local destinationYield = GetYieldForDestinationCity(yieldIndex, routeInfo) m_Cache[key].Yields[yieldIndex] = { Origin = originYield, Destination = destinationYield } netOriginYield = netOriginYield + originYield netDestinationYield = netDestinationYield + destinationYield end ------------------------------------------------- -- Net Yields ------------------------------------------------- m_Cache[key].NetOriginYield = netOriginYield m_Cache[key].NetDestinationYield = netDestinationYield ------------------------------------------------- -- Trading Post ------------------------------------------------- m_Cache[key].HasTradingPost = GetRouteHasTradingPost(routeInfo) ------------------------------------------------- -- Advanced Info - Length, trips, turns ------------------------------------------------- local tradePathLength, tripsToDestination, turnsToCompleteRoute = GetAdvancedRouteInfo(routeInfo); m_Cache[key].TurnsToCompleteRoute = turnsToCompleteRoute; m_Cache[key].TripsToDestination = tripsToDestination; m_Cache[key].TradePathLength = tradePathLength; ------------------------------------------------- -- Turn Built ------------------------------------------------- m_Cache[key].TurnBuilt = Game.GetCurrentGameTurn() -- print("KEY == " .. key) -- dump(m_Cache[key]) end function CachePlayer(playerID) -- Make entry if none exists if m_Cache.Players == nil then m_Cache.Players = {} end if m_Cache.Players[playerID] == nil then m_Cache.Players[playerID] = {} ------------------------------------------------- -- Active Route ------------------------------------------------- m_Cache.Players[playerID].HasActiveRoute = GetHasActiveRoute(playerID); ------------------------------------------------- -- Visibility Index ------------------------------------------------- m_Cache.Players[playerID].VisibilityIndex = GetVisibilityIndex(playerID); ------------------------------------------------- -- Icons, colors ------------------------------------------------- local textureOffsetX, textureOffsetY, textureSheet, tooltip = GetPlayerIconInfo(playerID) local backColor, frontColor, darkerBackColor, brighterBackColor = GetPlayerColorInfo(playerID) m_Cache.Players[playerID].Icon = { textureOffsetX, textureOffsetY, textureSheet, tooltip } m_Cache.Players[playerID].Colors = { backColor, frontColor, darkerBackColor, brighterBackColor } ------------------------------------------------- m_Cache.Players[playerID].TurnBuilt = Game.GetCurrentGameTurn() end end function CacheEmpty() -- If cache has entry TurnBuilt then the cache is built if m_Cache.TurnBuilt ~= nil then print_debug("CACHE Emptying") m_Cache = {} end end function GetRouteKey(routeInfo) return routeInfo.OriginCityPlayer .. "_" .. routeInfo.OriginCityID .. "_" .. routeInfo.DestinationCityPlayer .. "_" .. routeInfo.DestinationCityID; end function CacheKeyToRouteInfo(cacheKey) -- print("key: " .. cacheKey) local ids = Split(cacheKey, "_", 4) -- At max 4 entries should only exist local routeInfo = { OriginCityPlayer = tonumber(ids[1]), OriginCityID = tonumber(ids[2]), DestinationCityPlayer = tonumber(ids[3]), DestinationCityID = tonumber(ids[4]) } -- dump(routeInfo) return routeInfo end -- --------------------------------------------------------------------------- -- Cache lookups -- --------------------------------------------------------------------------- function Cached_GetYieldForOriginCity(yieldIndex:number, routeCacheKey:string) local cacheEntry = m_Cache[routeCacheKey] if cacheEntry ~= nil then -- print("CACHE HIT for " .. routeCacheKey) return cacheEntry.Yields[yieldIndex].Origin else print_debug("CACHE MISS for " .. routeCacheKey) CacheRoute(CacheKeyToRouteInfo(routeCacheKey)); return m_Cache[routeCacheKey].Yields[yieldIndex].Origin end end function Cached_GetYieldForDestinationCity(yieldIndex:number, routeCacheKey:string) local cacheEntry = m_Cache[routeCacheKey] if cacheEntry ~= nil then -- print("CACHE HIT for " .. routeCacheKey) return cacheEntry.Yields[yieldIndex].Destination else print_debug("CACHE MISS for " .. routeCacheKey) CacheRoute(CacheKeyToRouteInfo(routeCacheKey)); return m_Cache[routeCacheKey].Yields[yieldIndex].Destination end end function Cached_GetTurnsToComplete(routeCacheKey:string) if m_Cache[routeCacheKey] ~= nil then -- print("CACHE HIT for " .. routeCacheKey) return m_Cache[routeCacheKey].TurnsToCompleteRoute else print_debug("CACHE MISS for " .. routeCacheKey) CacheRoute(CacheKeyToRouteInfo(routeCacheKey)); return m_Cache[routeCacheKey].TurnsToCompleteRoute end end -- =========================================================================== -- Trade Route Sorter -- =========================================================================== -- This requires sort settings table passed. function SortTradeRoutes( tradeRoutes:table, sortSettings:table) if table.count(sortSettings) > 0 then -- Score all routes based on sort settings, sort them local routeScores = ScoreRoutes(tradeRoutes, sortSettings) table.sort(routeScores, function(a, b) return ScoreComp(a, b, sortSettings) end ) -- Build new table based on these sorted scores local routes = {} for i, scoreInfo in ipairs(routeScores) do routes[i] = tradeRoutes[scoreInfo.id] end return routes end -- No sort settings, return original array return tradeRoutes -- print("Total func calls: " .. debug_func_calls) -- debug_total_calls = debug_total_calls + debug_func_calls -- print("Total calls: " .. debug_total_calls) -- debug_func_calls = 0; end function GetTopRouteFromSortSettings( tradeRoutes:table, sortSettings:table ) if sortSettings ~= nil and table.count(sortSettings) > 0 then local routeScores = ScoreRoutes(tradeRoutes, sortSettings) local minScoreInfo = GetMinEntry(routeScores, function(a, b) return ScoreComp(a, b, sortSettings) end ) return tradeRoutes[minScoreInfo.id] end -- if no sort settings, return top entry return tradeRoutes[1]; end -- --------------------------------------------------------------------------- -- Score Route functions -- --------------------------------------------------------------------------- function ScoreRoutes( tradeRoutes:table, sortSettings:table ) local scores = {} for index=1, #tradeRoutes do scores[index] = { id = index, score = ScoreRoute(tradeRoutes[index], sortSettings)} end return scores end function ScoreRoute( routeInfo:table, sortSettings:table ) local score = {} for _, sortSetting in ipairs(sortSettings) do local scoreFunction = ScoreFunctionByID[sortSetting.SortByID]; local val = scoreFunction(routeInfo) -- Change the sign, if in descending order. EX: (-)5 < (-)2 if sortSetting.SortOrder == SORT_DESCENDING then -- Handle if val is string if type(val) == "string" then val = invert_string(val) else val = val * -1 end end score[#score + 1] = val end -- Add final score, ie net yield score[#score + 1] = GetNetYieldForOriginCity(routeInfo, true) return score end function ScoreComp( scoreInfo1, scoreInfo2, sortSettings ) local score1 = scoreInfo1.score local score2 = scoreInfo2.score if #score1 ~= #score2 then print("ERROR : scores unequal in length") return false end -- Last score is the net yield, it will not have a matching sortSetting for i=1, #score1-1 do if score1[i] < score2[i] then return true elseif score1[i] > score2[i] then return false end end return score1[#score1] > score2[#score1] -- Descending order of net yield end -- --------------------------------------------------------------------------- -- Sort Entries functions -- --------------------------------------------------------------------------- function InsertSortEntry( sortByID:number, sortOrder:number, sortSettings:table ) local sortEntry = { SortByID = sortByID, SortOrder = sortOrder }; -- Only insert if it does not exist local sortEntryIndex = findIndex (sortSettings, sortEntry, CompareSortEntries); if sortEntryIndex == -1 then -- print("Inserting " .. sortEntry.SortByID); table.insert(sortSettings, sortEntry); else -- If it exists, just update the sort oder -- print("Index: " .. sortEntryIndex); sortSettings[sortEntryIndex].SortOrder = sortOrder; end end function RemoveSortEntry( sortByID:number, sortSettings:table ) local sortEntry = { SortByID = sortByID, SortOrder = sortOrder }; -- Only delete if it exists local sortEntryIndex:number = findIndex(sortSettings, sortEntry, CompareSortEntries); if (sortEntryIndex > 0) then table.remove(sortSettings, sortEntryIndex); end end -- Checks for the same ID, not the same order function CompareSortEntries( sortEntry1:table, sortEntry2:table) if sortEntry1.SortByID == sortEntry2.SortByID then return true; end return false; end -- =========================================================================== -- Getter functions -- =========================================================================== -- Get idle Trade Units by Player ID function GetIdleTradeUnits( playerID:number ) local idleTradeUnits:table = {}; -- Loop through the Players units local localPlayerUnits:table = Players[playerID]:GetUnits(); for i,unit in localPlayerUnits:Members() do -- Find any trade units local unitInfo:table = GameInfo.Units[unit:GetUnitType()]; if unitInfo.MakeTradeRoute then local doestradeUnitHasRoute:boolean = false; -- Determine if those trade units are busy by checking outgoing routes from the players cities local localPlayerCities:table = Players[playerID]:GetCities(); for _, city in localPlayerCities:Members() do local routes = city:GetTrade():GetOutgoingRoutes(); for _, route in ipairs(routes) do if route.TraderUnitID == unit:GetID() then doestradeUnitHasRoute = true; end end end -- If this trade unit isn't attached to an outgoing route then they are idle if not doestradeUnitHasRoute then table.insert(idleTradeUnits, unit); end end end return idleTradeUnits; end -- Returns a string of the route in format "[ORIGIN_CITY_NAME]-[DESTINATION_CITY_NAME]" function GetTradeRouteString( routeInfo:table ) local originCityName:string = "[NOT_FOUND]"; local destinationCityName:string = "[NOT_FOUND]"; local originPlayer:table = Players[routeInfo.OriginCityPlayer]; if originPlayer ~= nil then local originCity:table = originPlayer:GetCities():FindID(routeInfo.OriginCityID); if originCity ~= nil then originCityName = L_Lookup(originCity:GetName()); else print("Error : CITY", routeInfo.OriginCityID, "NOT FOUND") end else print("Error : PLAYER", routeInfo.OriginCityPlayer, "NOT FOUND") end local destinationPlayer:table = Players[routeInfo.DestinationCityPlayer]; if destinationPlayer ~= nil then local destinationCity:table = destinationPlayer:GetCities():FindID(routeInfo.DestinationCityID); if destinationCity ~= nil then destinationCityName = L_Lookup(destinationCity:GetName()); else print("Error : CITY", routeInfo.DestinationCityID, "NOT FOUND") end else print("Error : PLAYER", routeInfo.DestinationCityPlayer, "NOT FOUND") end return originCityName .. "-" .. destinationCityName; end function GetTradeRouteYieldString( routeInfo:table ) local returnString:string = ""; local originPlayer:table = Players[routeInfo.OriginCityPlayer]; local originCity:table = originPlayer:GetCities():FindID(routeInfo.OriginCityID); local destinationPlayer:table = Players[routeInfo.DestinationCityPlayer]; local destinationCity:table = destinationPlayer:GetCities():FindID(routeInfo.DestinationCityID); for yieldIndex = START_INDEX, END_INDEX do local originCityYieldValue = GetYieldForOriginCity(yieldIndex, routeInfo, true); -- Skip if yield is not more than 0 if originCityYieldValue > 0 then local iconString, text = FormatYieldText(yieldIndex, originCityYieldValue); if (yieldIndex == FOOD_INDEX) then returnString = returnString .. text .. iconString .. " "; elseif (yieldIndex == PRODUCTION_INDEX) then returnString = returnString .. text .. iconString .. " "; elseif (yieldIndex == GOLD_INDEX) then returnString = returnString .. text .. iconString .. " "; elseif (yieldIndex == SCIENCE_INDEX) then returnString = returnString .. text .. iconString .. " "; elseif (yieldIndex == CULTURE_INDEX) then returnString = returnString .. text .. iconString .. " "; elseif (yieldIndex == FAITH_INDEX) then returnString = returnString .. text .. iconString; end end end return returnString; end -- Returns length of trade path, number of trips to destination, turns to complete route function GetAdvancedRouteInfo(routeInfo) local eSpeed = GameConfiguration.GetGameSpeedType(); if GameInfo.GameSpeeds[eSpeed] ~= nil then local iSpeedCostMultiplier = GameInfo.GameSpeeds[eSpeed].CostMultiplier; local tradeManager = Game.GetTradeManager(); local pathPlots = tradeManager:GetTradeRoutePath(routeInfo.OriginCityPlayer, routeInfo.OriginCityID, routeInfo.DestinationCityPlayer, routeInfo.DestinationCityID); local tradePathLength:number = table.count(pathPlots) - 1; local multiplierConstant:number = 0.1; local tripsToDestination = 1 + math.floor(iSpeedCostMultiplier/tradePathLength * multiplierConstant); --print("Error: Playing on an unrecognized speed. Defaulting to standard for route turns calculation"); local turnsToCompleteRoute = (tradePathLength * 2 * tripsToDestination); return tradePathLength, tripsToDestination, turnsToCompleteRoute; else print_debug("Speed type index " .. eSpeed); print("Error: Could not find game speed type. Defaulting to first entry in table"); local iSpeedCostMultiplier = GameInfo.GameSpeeds[1].CostMultiplier; local tradeManager = Game.GetTradeManager(); local pathPlots = tradeManager:GetTradeRoutePath(routeInfo.OriginCityPlayer, routeInfo.OriginCityID, routeInfo.DestinationCityPlayer, routeInfo.DestinationCityID); local tradePathLength:number = table.count(pathPlots) - 1; local multiplierConstant:number = 0.1; local tripsToDestination = 1 + math.floor(iSpeedCostMultiplier/tradePathLength * multiplierConstant); local turnsToCompleteRoute = (tradePathLength * 2 * tripsToDestination); return tradePathLength, tripsToDestination, turnsToCompleteRoute; end end -- --------------------------------------------------------------------------- -- Trade Route Getters -- --------------------------------------------------------------------------- function GetOriginCityName( routeInfo:table ) -- TODO - Maybe implement cache for this? local pPlayer = Players[routeInfo.OriginCityPlayer] local pCity = pPlayer:GetCities():FindID(routeInfo.OriginCityID) return L_Lookup(pCity:GetName()) -- How does lua compare localized text? end function GetDestinationCityName( routeInfo:table ) -- TODO - Maybe implement cache for this? local pPlayer = Players[routeInfo.DestinationCityPlayer] local pCity = pPlayer:GetCities():FindID(routeInfo.DestinationCityID) return L_Lookup(pCity:GetName()) -- How does lua compare localized text? end -- Returns yield for the origin city function GetYieldForOriginCity( yieldIndex:number, routeInfo:table, checkCache) if checkCache then local key:string = GetRouteKey(routeInfo) return Cached_GetYieldForOriginCity(yieldIndex, key) else local tradeManager = Game.GetTradeManager(); -- From route local yieldValue = tradeManager:CalculateOriginYieldFromPotentialRoute(routeInfo.OriginCityPlayer, routeInfo.OriginCityID, routeInfo.DestinationCityPlayer, routeInfo.DestinationCityID, yieldIndex); -- From path only if yield is gold. Trading posts add only gold. if yieldIndex == GameInfo.Yields["YIELD_GOLD"].Index then yieldValue = yieldValue + tradeManager:CalculateOriginYieldFromPath(routeInfo.OriginCityPlayer, routeInfo.OriginCityID, routeInfo.DestinationCityPlayer, routeInfo.DestinationCityID, yieldIndex); end -- From modifiers local resourceID = -1; yieldValue = yieldValue + tradeManager:CalculateOriginYieldFromModifiers(routeInfo.OriginCityPlayer, routeInfo.OriginCityID, routeInfo.DestinationCityPlayer, routeInfo.DestinationCityID, yieldIndex, resourceID); return yieldValue; end end -- Returns yield for the destination city function GetYieldForDestinationCity( yieldIndex:number, routeInfo:table, checkCache ) if checkCache then local key:string = GetRouteKey(routeInfo) return Cached_GetYieldForDestinationCity(yieldIndex, key) else local tradeManager = Game.GetTradeManager(); -- From route local yieldValue = tradeManager:CalculateDestinationYieldFromPotentialRoute(routeInfo.OriginCityPlayer, routeInfo.OriginCityID, routeInfo.DestinationCityPlayer, routeInfo.DestinationCityID, yieldIndex); -- From path yieldValue = yieldValue + tradeManager:CalculateDestinationYieldFromPath(routeInfo.OriginCityPlayer, routeInfo.OriginCityID, routeInfo.DestinationCityPlayer, routeInfo.DestinationCityID, yieldIndex); -- From modifiers local resourceID = -1; yieldValue = yieldValue + tradeManager:CalculateDestinationYieldFromModifiers(routeInfo.OriginCityPlayer, routeInfo.OriginCityID, routeInfo.DestinationCityPlayer, routeInfo.DestinationCityID, yieldIndex, resourceID); return yieldValue; end end function GetNetYieldForOriginCity( routeInfo, checkCache ) if checkCache then local key:string = GetRouteKey(routeInfo) if m_Cache[key] ~= nil then -- print("CACHE HIT for " .. GetTradeRouteString(routeInfo)) return m_Cache[key].NetOriginYield else print_debug("CACHE MISS for " .. GetTradeRouteString(routeInfo)) CacheRoute(routeInfo); return m_Cache[key].NetOriginYield end else local netYield:number = 0 for iI = START_INDEX, END_INDEX do -- Dont check cache here netYield = netYield + GetYieldForOriginCity(iI, routeInfo) end return netYield end end function GetNetYieldForDestinationCity( routeInfo, checkCache ) if checkCache then local key:string = GetRouteKey(routeInfo) if m_Cache[key] ~= nil then -- print("CACHE HIT for " .. GetTradeRouteString(routeInfo)) return m_Cache[key].NetDestinationYield else print_debug("CACHE MISS for " .. GetTradeRouteString(routeInfo)) CacheRoute(routeInfo); return m_Cache[key].NetDestinationYield end else local netYield:number = 0 for iI = START_INDEX, END_INDEX do -- Dont check cache here netYield = netYield + GetYieldForDestinationCity(iI, routeInfo) end return netYield end end function GetTurnsToComplete(routeInfo, checkCache) if checkCache then local key = GetRouteKey(routeInfo) if m_Cache[key] ~= nil then -- print("CACHE HIT for " .. GetTradeRouteString(routeInfo)) return m_Cache[key].TurnsToCompleteRoute else print_debug("CACHE MISS for " .. GetTradeRouteString(routeInfo)) CacheRoute(routeInfo); return m_Cache[key].TurnsToCompleteRoute end else local tradePathLength, tripsToDestination, turnsToCompleteRoute = GetAdvancedRouteInfo(routeInfo); return turnsToCompleteRoute end end function GetRouteInfo(routeInfo, checkCache) if checkCache then local key = GetRouteKey(routeInfo) if m_Cache[key] ~= nil then -- print("CACHE HIT for " .. GetTradeRouteString(routeInfo)) return m_Cache[key].TradePathLength, m_Cache[key].TripsToDestination, m_Cache[key].TurnsToCompleteRoute else print_debug("CACHE MISS for " .. GetTradeRouteString(routeInfo)) CacheRoute(routeInfo) return m_Cache[key].TradePathLength, m_Cache[key].TripsToDestination, m_Cache[key].TurnsToCompleteRoute end else return GetAdvancedRouteInfo(routeInfo) end end function GetRouteHasTradingPost(routeInfo, checkCache) if checkCache then local key = GetRouteKey(routeInfo) if m_Cache[key] ~= nil then -- print("CACHE HIT for " .. GetTradeRouteString(routeInfo)) return m_Cache[key].HasTradingPost else print_debug("CACHE MISS for " .. GetTradeRouteString(routeInfo)) CacheRoute(routeInfo) return m_Cache[key].HasTradingPost end else local destinationPlayer:table = Players[routeInfo.DestinationCityPlayer]; local destinationCity:table = destinationPlayer:GetCities():FindID(routeInfo.DestinationCityID); return destinationCity:GetTrade():HasActiveTradingPost(routeInfo.OriginCityPlayer) end end function GetHasActiveRoute(playerID, checkCache) if checkCache then if m_Cache.Players ~= nil and m_Cache.Players[playerID] ~= nil then -- print("CACHE HIT for player " .. playerID) return m_Cache.Players[playerID].HasActiveRoute else print_debug("CACHE MISS for player " .. playerID) CachePlayer(playerID) return m_Cache.Players[playerID].HasActiveRoute end else local pPlayer:table = Players[playerID]; local playerCities:table = pPlayer:GetCities(); for _, city in playerCities:Members() do if city:GetTrade():HasActiveTradingPost(Game.GetLocalPlayer()) then return true end end return false end end function GetVisibilityIndex(playerID, checkCache) if checkCache then if m_Cache.Players ~= nil and m_Cache.Players[playerID] ~= nil then -- print("CACHE HIT for player " .. playerID) return m_Cache.Players[playerID].VisibilityIndex else print_debug("CACHE MISS for player " .. playerID) CachePlayer(playerID) return m_Cache.Players[playerID].VisibilityIndex end else return Players[Game.GetLocalPlayer()]:GetDiplomacy():GetVisibilityOn(playerID); end end function GetPlayerIconInfo(playerID, checkCache) if checkCache then if m_Cache.Players ~= nil and m_Cache.Players[playerID] ~= nil then -- print("CACHE HIT for player " .. playerID) return unpack(m_Cache.Players[playerID].Icon) else print_debug("CACHE MISS for player " .. playerID) CachePlayer(playerID) return unpack(m_Cache.Players[playerID].Icon) end else local pPlayer = Players[playerID]; local playerConfig:table = PlayerConfigurations[playerID]; local playerInfluence:table = pPlayer:GetInfluence(); local playerIconString:string; if playerConfig ~= nil then if not playerInfluence:CanReceiveInfluence() then -- Civilizations playerIconString = "ICON_" .. playerConfig:GetCivilizationTypeName(); else -- City States local leader:string = playerConfig:GetLeaderTypeName(); local leaderInfo:table = GameInfo.Leaders[leader]; if (leader == "LEADER_MINOR_CIV_SCIENTIFIC" or leaderInfo.InheritFrom == "LEADER_MINOR_CIV_SCIENTIFIC") then playerIconString = "ICON_CITYSTATE_SCIENCE"; elseif (leader == "LEADER_MINOR_CIV_RELIGIOUS" or leaderInfo.InheritFrom == "LEADER_MINOR_CIV_RELIGIOUS") then playerIconString = "ICON_CITYSTATE_FAITH"; elseif (leader == "LEADER_MINOR_CIV_TRADE" or leaderInfo.InheritFrom == "LEADER_MINOR_CIV_TRADE") then playerIconString = "ICON_CITYSTATE_TRADE"; elseif (leader == "LEADER_MINOR_CIV_CULTURAL" or leaderInfo.InheritFrom == "LEADER_MINOR_CIV_CULTURAL") then playerIconString = "ICON_CITYSTATE_CULTURE"; elseif (leader == "LEADER_MINOR_CIV_MILITARISTIC" or leaderInfo.InheritFrom == "LEADER_MINOR_CIV_MILITARISTIC") then playerIconString = "ICON_CITYSTATE_MILITARISTIC"; elseif (leader == "LEADER_MINOR_CIV_INDUSTRIAL" or leaderInfo.InheritFrom == "LEADER_MINOR_CIV_INDUSTRIAL") then playerIconString = "ICON_CITYSTATE_INDUSTRIAL"; end end local playerDescription:string = playerConfig:GetCivilizationDescription(); local textureOffsetX, textureOffsetY, textureSheet = IconManager:FindIconAtlas(playerIconString, 30) return textureOffsetX, textureOffsetY, textureSheet, playerDescription; end end end function GetPlayerColorInfo(playerID, checkCache) if checkCache then if m_Cache.Players ~= nil and m_Cache.Players[playerID] ~= nil then -- print("CACHE HIT for player " .. playerID) return unpack(m_Cache.Players[playerID].Colors) else print_debug("CACHE MISS for player " .. playerID) CachePlayer(playerID) return unpack(m_Cache.Players[playerID].Colors) end else local backColor, frontColor = UI.GetPlayerColors(playerID) local darkerBackColor = DarkenLightenColor(backColor, BACKDROP_DARKER_OFFSET, BACKDROP_DARKER_OPACITY); local brighterBackColor = DarkenLightenColor(backColor, BACKDROP_BRIGHTER_OFFSET, BACKDROP_BRIGHTER_OPACITY); return backColor, frontColor, darkerBackColor, brighterBackColor end end -- =========================================================================== -- General Helper functions -- =========================================================================== -- Simple check to seeif player1 and player2 can possibly have a trade route. function CanPossiblyTradeWithPlayer(player1, player2) if player1 == player2 then return true; end local pPlayer1 = Players[player1]; local pPlayer1Diplomacy = pPlayer1:GetDiplomacy(); local pPlayer2 = Players[player2] if pPlayer2:IsAlive() and pPlayer1Diplomacy:HasMet(player2) then if not pPlayer1Diplomacy:IsAtWarWith(player2) then return true; end end return false; end function IsRoutePossible(originCityPlayerID, originCityID, destinationCityPlayerID, destinationCityID) local tradeManager:table = Game.GetTradeManager(); return tradeManager:CanStartRoute(originCityPlayerID, originCityID, destinationCityPlayerID, destinationCityID); end function FormatYieldText(yieldIndex, yieldAmount) if yieldAmount == 0 then return "", "" end local iconString:string = ICON_LOOKUP[yieldIndex] local text:string; if yieldAmount > 0 then text = "+"; else text = "-"; end text = text .. yieldAmount; return iconString, text; end -- Finds and removes routeToDelete from routeTable function RemoveRouteFromTable( routeToDelete:table , routeTable:table, isGrouped:boolean ) -- If grouping by something, go one level deeper if isGrouped then print_debug("Routes grouped") local targetIndex:number = -1; local targetGroupIndex:number = -1; for i, groupedRoutes in ipairs(routeTable) do for j, route in ipairs(groupedRoutes) do if CheckRouteEquality( route, routeToDelete ) then targetIndex = j; targetGroupIndex = i; break end end end -- Remove route if targetIndex ~= -1 and targetGroupIndex ~= -1 then print_debug("REMOVING ROUTE") table.remove(routeTable[targetGroupIndex], targetIndex); -- If that group is empty, remove that group if table.count(routeTable[targetGroupIndex]) <= 0 then table.remove(routeTable, targetGroupIndex); end else print("Error : COULD NOT FIND ROUTE") end else print_debug("Routes not grouped") -- Find and remove route local targetIndex:number = findIndex(routeTable, routeToDelete, CheckRouteEquality) if targetIndex ~= -1 then print_debug("REMOVING ROUTE") table.remove(routeTable, targetIndex); else print("Error : COULD NOT FIND ROUTE") end end end -- Checks if the two routes are the same (does not compare traderUnit) function CheckRouteEquality ( tradeRoute1:table, tradeRoute2:table ) if ( tradeRoute1.OriginCityPlayer == tradeRoute2.OriginCityPlayer and tradeRoute1.OriginCityID == tradeRoute2.OriginCityID and tradeRoute1.DestinationCityPlayer == tradeRoute2.DestinationCityPlayer and tradeRoute1.DestinationCityID == tradeRoute2.DestinationCityID ) then return true; end return false; end function IsCityState( player:table ) local playerInfluence:table = player:GetInfluence(); if playerInfluence:CanReceiveInfluence() then return true end return false end -- Checks if the player is a city state, with "Send a trade route" quest function IsCityStateWithTradeQuest( player:table ) local questsManager:table = Game.GetQuestsManager(); local localPlayer = Game.GetLocalPlayer() if (questsManager ~= nil and localPlayer ~= nil) then local tradeRouteQuestInfo:table = GameInfo.Quests["QUEST_SEND_TRADE_ROUTE"]; if (tradeRouteQuestInfo ~= nil) then if (questsManager:HasActiveQuestFromPlayer(localPlayer, player:GetID(), tradeRouteQuestInfo.Index)) then return true end end end return false end -- Checks if the player is a civ, other than the local player function IsOtherCiv( player:table ) if player:GetID() ~= Game.GetLocalPlayer() then return true end return false end -- =========================================================================== -- Helper Utility functions -- =========================================================================== -- Converts 'A' -> 'Z' || 'Z' -> 'A' function invert_string(s:string) s = s:upper() print_debug("org: " .. s) local newS:string = "" for i=1, s:len() do newS = newS .. string.char(invert_char_code(s:byte(i))) end print_debug("inv: " .. newS) return newS end function invert_char_code(code:number) local delta = string.byte("Z", 1) - code return delta + string.byte("A", 1) end function table_nnill_count(T:table) local count = 0 for k in pairs(T) do if T[k] ~= nil then count = count + 1 end end return count end function findIndex(T, searchItem, compareFunc) for index, item in ipairs(T) do if compareFunc(item, searchItem) then return index; end end return -1; end function GetMinEntry(searchTable, compareFunc) local minIndex = 1 for index=1, #searchTable do if not compareFunc(searchTable[minIndex], searchTable[index]) then minIndex = index; end end return searchTable[minIndex], minIndex end -- ========== START OF DataDumper.lua ================= --[[ DataDumper.lua Copyright (c) 2007 Olivetti-Engineering SA 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. ]] function dump(...) print(DataDumper(...), "\n---") end local dumplua_closure = [[ local closures = {} local function closure(t) closures[#closures+1] = t t[1] = assert(loadstring(t[1])) return t[1] end for _,t in pairs(closures) do for i = 2,#t do debug.setupvalue(t[1], i-1, t[i]) end end ]] local lua_reserved_keywords = { 'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' } local function keys(t) local res = {} local oktypes = { stringstring = true, numbernumber = true } local function cmpfct(a,b) if oktypes[type(a)..type(b)] then return a < b else return type(a) < type(b) end end for k in pairs(t) do res[#res+1] = k end table.sort(res, cmpfct) return res end local c_functions = {} for _,lib in pairs{'_G', 'string', 'table', 'math', 'io', 'os', 'coroutine', 'package', 'debug'} do local t = {} lib = lib .. "." if lib == "_G." then lib = "" end for k,v in pairs(t) do if type(v) == 'function' and not pcall(string.dump, v) then c_functions[v] = lib..k end end end function DataDumper(value, varname, fastmode, ident) local defined, dumplua = {} -- Local variables for speed optimization local string_format, type, string_dump, string_rep = string.format, type, string.dump, string.rep local tostring, pairs, table_concat = tostring, pairs, table.concat local keycache, strvalcache, out, closure_cnt = {}, {}, {}, 0 setmetatable(strvalcache, {__index = function(t,value) local res = string_format('%q', value) t[value] = res return res end}) local fcts = { string = function(value) return strvalcache[value] end, number = function(value) return value end, boolean = function(value) return tostring(value) end, ['nil'] = function(value) return 'nil' end, ['function'] = function(value) return string_format("loadstring(%q)", string_dump(value)) end, userdata = function() error("Cannot dump userdata") end, thread = function() error("Cannot dump threads") end, } local function test_defined(value, path) if defined[value] then if path:match("^getmetatable.*%)$") then out[#out+1] = string_format("s%s, %s)\n", path:sub(2,-2), defined[value]) else out[#out+1] = path .. " = " .. defined[value] .. "\n" end return true end defined[value] = path end local function make_key(t, key) local s if type(key) == 'string' and key:match('^[_%a][_%w]*$') then s = key .. "=" else s = "[" .. dumplua(key, 0) .. "]=" end t[key] = s return s end for _,k in ipairs(lua_reserved_keywords) do keycache[k] = '["'..k..'"] = ' end if fastmode then fcts.table = function (value) -- Table value local numidx = 1 out[#out+1] = "{" for key,val in pairs(value) do if key == numidx then numidx = numidx + 1 else out[#out+1] = keycache[key] end local str = dumplua(val) out[#out+1] = str.."," end if string.sub(out[#out], -1) == "," then out[#out] = string.sub(out[#out], 1, -2); end out[#out+1] = "}" return "" end else fcts.table = function (value, ident, path) if test_defined(value, path) then return "nil" end -- Table value local sep, str, numidx, totallen = " ", {}, 1, 0 local meta, metastr = getmetatable(value) if meta then ident = ident + 1 metastr = dumplua(meta, ident, "getmetatable("..path..")") totallen = totallen + #metastr + 16 end for _,key in pairs(keys(value)) do local val = value[key] local s = "" local subpath = path or "" if key == numidx then subpath = subpath .. "[" .. numidx .. "]" numidx = numidx + 1 else s = keycache[key] if not s:match "^%[" then subpath = subpath .. "." end subpath = subpath .. s:gsub("%s*=%s*$","") end s = s .. dumplua(val, ident+1, subpath) str[#str+1] = s totallen = totallen + #s + 2 end if totallen > 80 then sep = "\n" .. string_rep(" ", ident+1) end str = "{"..sep..table_concat(str, ","..sep).." "..sep:sub(1,-3).."}" if meta then sep = sep:sub(1,-3) return "setmetatable("..sep..str..","..sep..metastr..sep:sub(1,-3)..")" end return str end fcts['function'] = function (value, ident, path) if test_defined(value, path) then return "nil" end if c_functions[value] then return c_functions[value] elseif debug == nil or debug.getupvalue(value, 1) == nil then return string_format("loadstring(%q)", string_dump(value)) end closure_cnt = closure_cnt + 1 local res = {string.dump(value)} for i = 1,math.huge do local name, v = debug.getupvalue(value,i) if name == nil then break end res[i+1] = v end return "closure " .. dumplua(res, ident, "closures["..closure_cnt.."]") end end function dumplua(value, ident, path) return fcts[type(value)](value, ident, path) end if varname == nil then varname = "" elseif varname:match("^[%a_][%w_]*$") then varname = varname .. " = " end if fastmode then setmetatable(keycache, {__index = make_key }) out[1] = varname table.insert(out,dumplua(value, 0)) return table.concat(out) else setmetatable(keycache, {__index = make_key }) local items = {} for i=1,10 do items[i] = '' end items[3] = dumplua(value, ident or 0, "t") if closure_cnt > 0 then items[1], items[6] = dumplua_closure:match("(.*\n)\n(.*)") out[#out+1] = "" end if #out > 0 then items[2], items[4] = "local t = ", "\n" items[5] = table.concat(out) items[7] = varname .. "t" else items[2] = varname end return table.concat(items) end end -- ========== END OF DataDumper.lua ================= -- =========================================================================== -- Event handlers -- =========================================================================== function TradeSupportTracker_Initialize() print("Initializing BTS Trade Support Tracker"); -- Load Previous Routes LoadRunningRoutesInfo(); Events.UnitOperationStarted.Add( TradeSupportTracker_OnUnitOperationStarted ); Events.UnitOperationsCleared.Add( TradeSupportTracker_OnUnitOperationsCleared ); Events.PlayerTurnActivated.Add( TradeSupportTracker_OnPlayerTurnActivated ); end function TradeSupportAutomater_Initialize() print("Initializing BTS Trade Support Automater"); -- Load previous automated settings LoadTraderAutomatedInfo(); Events.PlayerTurnActivated.Add( TradeSupportAutomater_OnPlayerTurnActivated ); end
0
0.856126
1
0.856126
game-dev
MEDIA
0.744829
game-dev
0.940634
1
0.940634
OpenAngelArena/oaa
1,357
game/scripts/vscripts/abilities/boss/temple_guardian/temple_guardian_rage_hammer_smash.lua
LinkLuaModifier("modifier_temple_guardian_hammer_smash_thinker", "abilities/boss/temple_guardian/modifier_temple_guardian_hammer_smash_thinker.lua", LUA_MODIFIER_MOTION_NONE) temple_guardian_rage_hammer_smash = class(AbilityBaseClass) function temple_guardian_rage_hammer_smash:ProcsMagicStick() return false end function temple_guardian_rage_hammer_smash:OnAbilityPhaseStart() if IsServer() then local caster = self:GetCaster() local delay = self:GetCastPoint() caster:AddNewModifier(caster, self, "modifier_anti_stun_oaa", {duration = delay + 0.03}) caster:EmitSound("TempleGuardian.PreAttack") end return true end function temple_guardian_rage_hammer_smash:GetPlaybackRateOverride() return 0.6090 -- was 0.5500 -- Playbackrate ratio should be kept inversely proportional to RageHammerSmash base_swing_speed end function temple_guardian_rage_hammer_smash:OnSpellStart() local caster = self:GetCaster() local flSpeed = self:GetSpecialValueFor( "base_swing_speed" ) local vToTarget = self:GetCursorPosition() - caster:GetOrigin() vToTarget = vToTarget:Normalized() local vTarget = caster:GetOrigin() + vToTarget * self:GetCastRange( caster:GetOrigin(), nil ) CreateModifierThinker( caster, self, "modifier_temple_guardian_hammer_smash_thinker", { duration = flSpeed }, vTarget, caster:GetTeamNumber(), false ) end
0
0.802601
1
0.802601
game-dev
MEDIA
0.989198
game-dev
0.952475
1
0.952475
KoshakMineDEV/Lumi
2,770
src/main/java/cn/nukkit/level/generator/populator/impl/PopulatorUnderwaterFloor.java
package cn.nukkit.level.generator.populator.impl; import cn.nukkit.block.BlockID; import cn.nukkit.level.ChunkManager; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.generator.OldNormal; import cn.nukkit.level.generator.populator.helper.PopulatorHelpers; import cn.nukkit.level.generator.populator.type.PopulatorCount; import cn.nukkit.math.NukkitRandom; import java.util.List; public class PopulatorUnderwaterFloor extends PopulatorCount { private final double probability; private final int block; private final int radiusMin; private final int radiusMax; private final int radiusY; private final List<Integer> replaceBlocks; public PopulatorUnderwaterFloor(double probability, int block, int radiusMin, int radiusMax, int radiusY, List<Integer> replaceBlocks) { this.probability = probability; this.block = block; this.radiusMin = radiusMin; this.radiusMax = radiusMax; this.radiusY = radiusY; this.replaceBlocks = replaceBlocks; } @Override public void populateCount(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random, FullChunk chunk) { if (random.nextDouble() >= probability) { return; } int sourceX = (chunkX << 4) + random.nextBoundedInt(16); int sourceZ = (chunkZ << 4) + random.nextBoundedInt(16); int sourceY = getHighestWorkableBlock(level, sourceX, sourceZ, chunk) - 1; if (sourceY < radiusY) { return; } if (level.getBlockIdAt(sourceX, sourceY + 1, sourceZ) != BlockID.STILL_WATER) { return; } int radius = random.nextRange(radiusMin, radiusMax); for (int x = sourceX - radius; x <= sourceX + radius; x++) { for (int z = sourceZ - radius; z <= sourceZ + radius; z++) { if ((x - sourceX) * (x - sourceX) + (z - sourceZ) * (z - sourceZ) <= radius * radius) { for (int y = sourceY - radiusY; y <= sourceY + radiusY; y++) { for (int replaceBlockState : replaceBlocks) { if (level.getBlockIdAt(x, y, z) == replaceBlockState) { level.setBlockAt(x, y, z, block, 0); } } } } } } } @Override protected int getHighestWorkableBlock(ChunkManager level, int x, int z, FullChunk chunk) { int y; x &= 0xF; z &= 0xF; for (y = OldNormal.seaHeight - 1; y >= 0; --y) { if (!PopulatorHelpers.isNonOceanSolid(chunk.getBlockId(x, y, z))) { break; } } return y == 0 ? -1 : ++y; } }
0
0.854954
1
0.854954
game-dev
MEDIA
0.880449
game-dev
0.900966
1
0.900966
Lexxie9952/fcw.org-server
21,139
freeciv/freeciv/data/classic/techs.ruleset
; Modifying this file: ; You should not modify this file except to make bugfixes or ; for other "maintenance". If you want to make custom changes, ; you should create a new datadir subdirectory and copy this file ; into that directory, and then modify that copy. Then use the ; command "rulesetdir <mysubdir>" in the server to have freeciv ; use your new customized file. [datafile] description="Classic technology data for Freeciv (as Civ2, minus a few)" options="+Freeciv-ruleset-Devel-2017.Jan.02 web-compatible" format_version=20 [control] ; Names for custom tech flags. There can be up to 8 of these. ; name = rule name; In some circumstances user may see this ; as part of some sentences, so try to make it descriptive ; and sensible. ; helptxt = displayed in the help for advances with this flag (optional) ;flags = ; { "name", "helptxt" ; } ; /* <-- avoid gettext warnings ; ; Tech classes: ; ; First one is the default one. ; If there is none, tech classes feature is disabled ; ; name = translatable name as seen by user ; rule_name = (optional) internal name for savegames, rulesets ; etc; if not present, "name" is used for this ; purpose too. Since the name used in savegames must ; not change, if you want to rename an item after a ; ruleset has been released, you should set ; "rule_name" to the original value of "name". ; cost_pct = how much techs of the class cost compared ; to normal. Default is 100%. ; ; */ <-- avoid gettext warnings ;[techclass_default] ;name = ; /* <-- avoid gettext warnings ; ; Below: The individual advances, one per section. ; The number can be variable, up to 250. ; ; The actual tag used (the * in [advance_*]) does not matter, except ; it must be unique within this file, and it may be used in debug ; output when reading this file. ; ; Notes: ; ; name = translatable name as seen by user ; rule_name = (optional) internal name for savegames, rulesets etc; if ; not present, "name" is used for this purpose too. Since ; the name used in savegames must not change, if you want ; to rename an item after a ruleset has been released, you ; should set "rule_name" to the original value of "name". ; class = tech class this tech belongs to, if they have been defined. ; Default is first one defined above. ; req1, req2 = advances required before researching this one ; root_req = tech required before acquiring this tech, by any means. ; All techs with any direct or indirect dependency on this ; one will *also* have this root_req, as well as their own ; and any others they inherit. ; Giving "None" explicitly here prevents a tech from ; inheriting root_reqs in this way, and stops root_req ; inheritance through that tech. ; Specifying a tech's root_req as itself means that the tech ; can only be acquired by special means (nation's init_techs, ; scripting, etc). ; research_reqs = requirements before researching this one. Can have non ; tech requirements because it is a requirement vector. ; See doc/README.effects to learn more about requirement ; vectors. ; Requireing a tech here in stead of in req1, req2 or ; root_req is not supported yet. ; Requirements that may become fulfilled during the game ; when they weren't at the start of the game is not ; supported yet. ; flags = special flag strings ; graphic = icon for technology ; graphic_alt = alternate icon ; helptext = optional help text string (set units ruleset for examples) ; bonus_message = text seen when a player is the first to discover ; an bonus tech. Must contain '%s' to mark place of the tech ; gained. ; cost = if tech_cost_style is set to "Classic+" or "Experimental+", ; this field is read for information on how much a tech ; costs. ; ; Special values for req1 and req2 are "None" (first section below) ; and "Never" (never available). If only one tech is required, ; it should be listed as req1. ; ; As well as custom flags defined above, the following flag strings are ; possible: ; ; "Bonus_Tech" = player gets extra tech if reached first ; "Bridge" = "Settler" unit types can build roads with ; "RequiresBridge" flag over roads with ; "PreventsOtherRoads" flag (rivers) ; "Build_Airborne" = from now on can build air units (for use by AI) ; "Claim_Ocean" = Player claims ocean tiles even if they are not ; adjacent to border source ; "Claim_Ocean_Limited" = Oceanic border sources claim ocean tiles even if ; they are not adjacent to border source ; ; */ <-- avoid gettext warnings [advance_advanced_flight] name = _("Advanced Flight") req1 = "Radio" req2 = "Machine Tools" flags = "" graphic = "a.advanced_flight" graphic_alt = "-" [advance_alphabet] name = _("Alphabet") req1 = "None" req2 = "None" flags = "" graphic = "a.alphabet" graphic_alt = "-" [advance_amphibious_warfare] name = _("Amphibious Warfare") req1 = "Navigation" req2 = "Tactics" flags = "" graphic = "a.amphibious_warfare" graphic_alt = "-" [advance_astronomy] name = _("Astronomy") req1 = "Mysticism" req2 = "Mathematics" flags = "" graphic = "a.astronomy" graphic_alt = "-" [advance_atomic_theory] name = _("Atomic Theory") req1 = "Theory of Gravity" req2 = "Physics" flags = "" graphic = "a.atomic_theory" graphic_alt = "-" [advance_automobile] name = _("Automobile") req1 = "Combustion" req2 = "Steel" graphic = "a.automobile" graphic_alt = "-" helptext = _("Obsoletes Leonardos Workshop. +25% population pollution.") [advance_banking] name = _("Banking") req1 = "Trade" req2 = "The Republic" flags = "" graphic = "a.banking" graphic_alt = "-" [advance_bridge_building] name = _("Bridge Building") req1 = "Iron Working" req2 = "Construction" flags = "Bridge" graphic = "a.bridge_building" graphic_alt = "-" helptext = _("Allows roads to be built on river tiles.") [advance_bronze_working] name = _("Bronze Working") req1 = "None" req2 = "None" flags = "" graphic = "a.bronze_working" graphic_alt = "-" [advance_ceremonial_burial] name = _("Ceremonial Burial") req1 = "None" req2 = "None" flags = "" graphic = "a.ceremonial_burial" graphic_alt = "-" [advance_chemistry] name = _("Chemistry") req1 = "University" req2 = "Medicine" flags = "" graphic = "a.chemistry" graphic_alt = "-" [advance_chivalry] name = _("Chivalry") req1 = "Feudalism" req2 = "Horseback Riding" flags = "" graphic = "a.chivalry" graphic_alt = "-" helptext = _("Obsoletes Horsemen, Chariots.") [advance_code_of_laws] name = _("Code of Laws") req1 = "Alphabet" req2 = "None" flags = "" graphic = "a.code_of_laws" graphic_alt = "-" [advance_combined_arms] name = _("Combined Arms") req1 = "Mobile Warfare" req2 = "Advanced Flight" flags = "" graphic = "a.combined_arms" graphic_alt = "-" [advance_combustion] name = _("Combustion") req1 = "Refining" req2 = "Explosives" flags = "" graphic = "a.combustion" graphic_alt = "-" [advance_communism] name = _("Communism") req1 = "Philosophy" req2 = "Industrialization" flags = "" graphic = "a.communism" graphic_alt = "-" helptext = _("-1 Effect for Cathedral, Michelangelos Chapel.") [advance_computers] name = _("Computers") req1 = "Mass Production" req2 = "Miniaturization" flags = "" graphic = "a.computers" graphic_alt = "-" [advance_conscription] name = _("Conscription") req1 = "Democracy" req2 = "Metallurgy" flags = "" graphic = "a.conscription" graphic_alt = "-" helptext = _("Obsoletes Musketeers.") [advance_construction] name = _("Construction") req1 = "Masonry" req2 = "Currency" flags = "" graphic = "a.construction" graphic_alt = "-" helptext = _("Allows Fortresses, Oil Wells.") [advance_currency] name = _("Currency") req1 = "Bronze Working" req2 = "None" flags = "" graphic = "a.currency" graphic_alt = "-" [advance_democracy] name = _("Democracy") req1 = "Banking" req2 = "Invention" flags = "" graphic = "a.democracy" graphic_alt = "-" [advance_economics] name = _("Economics") req1 = "Banking" req2 = "University" flags = "" graphic = "a.economics" graphic_alt = "-" [advance_electricity] name = _("Electricity") req1 = "Metallurgy" req2 = "Magnetism" flags = "" graphic = "a.electricity" graphic_alt = "-" helptext = _("Obsoletes Ironclad. +1 Effect for Colosseums.") [advance_electronics] name = _("Electronics") req1 = "The Corporation" req2 = "Electricity" flags = "" graphic = "a.electronics" graphic_alt = "-" [advance_engineering] name = _("Engineering") req1 = "The Wheel" req2 = "Construction" flags = "" graphic = "a.engineering" graphic_alt = "-" [advance_environmentalism] name = _("Environmentalism") req1 = "Recycling" req2 = "Space Flight" flags = "" graphic = "a.environmentalism" graphic_alt = "-" [advance_espionage] name = _("Espionage") req1 = "Communism" req2 = "Democracy" flags = "" graphic = "a.espionage" graphic_alt = "-" helptext = _("Obsoletes Diplomat.") [advance_explosives] name = _("Explosives") req1 = "Gunpowder" req2 = "Chemistry" flags = "" graphic = "a.explosives" graphic_alt = "-" helptext = _("Obsoletes Workers.") [advance_feudalism] name = _("Feudalism") req1 = "Warrior Code" req2 = "Monarchy" flags = "" graphic = "a.feudalism" graphic_alt = "-" [advance_flight] name = _("Flight") req1 = "Combustion" req2 = "Theory of Gravity" flags = "Build_Airborne" graphic = "a.flight" graphic_alt = "-" helptext = _("Obsoletes Colossus, decreases one-time Traderoute revenue.") [advance_fusion_power] name = _("Fusion Power") req1 = "Nuclear Power" req2 = "Superconductors" flags = "" graphic = "a.fusion_power" graphic_alt = "-" [advance_genetic_engineering] name = _("Genetic Engineering") req1 = "Medicine" req2 = "The Corporation" flags = "" graphic = "a.genetic_engineering" graphic_alt = "-" [advance_guerilla_warfare] name = _("Guerilla Warfare") req1 = "Communism" req2 = "Tactics" flags = "" graphic = "a.guerilla_warfare" graphic_alt = "-" helptext = _("Obsoletes Explorer. Globally unlocks defensive partisans.") [advance_gunpowder] name = _("Gunpowder") req1 = "Invention" req2 = "Iron Working" flags = "" graphic = "a.gunpowder" graphic_alt = "-" helptext = _("Obsoletes Barracks, earlier foot soldiers.") [advance_horseback_riding] name = _("Horseback Riding") req1 = "None" req2 = "None" flags = "" graphic = "a.horseback_riding" graphic_alt = "-" [advance_industrialization] name = _("Industrialization") req1 = "Railroad" req2 = "Banking" graphic = "a.industrialization" graphic_alt = "-" helptext = _("Obsoletes Galleon. Population begins polluting.") [advance_invention] name = _("Invention") req1 = "Engineering" req2 = "Literacy" flags = "" graphic = "a.invention" graphic_alt = "-" helptext = _("+2 Fortress vision.") [advance_iron_working] name = _("Iron Working") req1 = "Bronze Working" req2 = "Warrior Code" flags = "" graphic = "a.iron_working" graphic_alt = "-" [advance_labor_union] name = _("Labor Union") req1 = "Mass Production" req2 = "Guerilla Warfare" flags = "" graphic = "a.labor_union" graphic_alt = "-" [advance_laser] name = _("Laser") req1 = "Mass Production" req2 = "Nuclear Power" flags = "" graphic = "a.laser" graphic_alt = "-" [advance_leadership] name = _("Leadership") req1 = "Chivalry" req2 = "Gunpowder" flags = "" graphic = "a.leadership" graphic_alt = "-" helptext = _("Obsoletes Horsemen, Chariot, Elephant, Knight, Crusader.") [advance_literacy] name = _("Literacy") req1 = "Writing" req2 = "Code of Laws" flags = "" graphic = "a.literacy" graphic_alt = "-" [advance_machine_tools] name = _("Machine Tools") req1 = "Steel" req2 = "Tactics" flags = "" graphic = "a.machine_tools" graphic_alt = "-" helptext = _("Obsoletes Cannon.") [advance_magnetism] name = _("Magnetism") req1 = "Iron Working" req2 = "Physics" flags = "" graphic = "a.magnetism" graphic_alt = "-" helptext = _("Obsoletes Caravel, Lighthouse. +1 Trade route per city.") [advance_map_making] name = _("Map Making") req1 = "Alphabet" req2 = "None" flags = "" graphic = "a.map_making" graphic_alt = "-" [advance_masonry] name = _("Masonry") req1 = "None" req2 = "None" flags = "" graphic = "a.masonry" graphic_alt = "-" [advance_mass_production] name = _("Mass Production") req1 = "Automobile" req2 = "The Corporation" graphic = "a.mass_production" graphic_alt = "-" helptext = _("+25% population pollution.") [advance_mathematics] name = _("Mathematics") req1 = "Alphabet" req2 = "Masonry" flags = "" graphic = "a.mathematics" graphic_alt = "-" [advance_medicine] name = _("Medicine") req1 = "Philosophy" req2 = "Trade" flags = "" graphic = "a.medicine" graphic_alt = "-" [advance_metallurgy] name = _("Metallurgy") req1 = "Gunpowder" req2 = "University" flags = "" graphic = "a.metallurgy" graphic_alt = "-" helptext = _("Obsoletes Catapult, Great Wall.") [advance_miniaturization] name = _("Miniaturization") req1 = "Machine Tools" req2 = "Electronics" flags = "" graphic = "a.miniaturization" graphic_alt = "-" [advance_mobile_warfare] name = _("Mobile Warfare") req1 = "Automobile" req2 = "Tactics" flags = "" graphic = "a.mobile_warfare" graphic_alt = "-" helptext = _("Obsoletes Barracks II, Cavalry, Sun Tzu.") [advance_monarchy] name = _("Monarchy") req1 = "Ceremonial Burial" req2 = "Code of Laws" flags = "" graphic = "a.monarchy" graphic_alt = "-" [advance_monotheism] name = _("Monotheism") req1 = "Philosophy" req2 = "Polytheism" flags = "" graphic = "a.monotheism" graphic_alt = "-" helptext = _("Obsoletes Elephants.") [advance_mysticism] name = _("Mysticism") req1 = "Ceremonial Burial" req2 = "None" flags = "" graphic = "a.mysticism" graphic_alt = "-" helptext = _("Doubles the effect of Temples.") [advance_navigation] name = _("Navigation") req1 = "Seafaring" req2 = "Astronomy" flags = "" graphic = "a.navigation" graphic_alt = "-" helptext = _("Obsoletes Trireme.") [advance_nuclear_fission] name = _("Nuclear Fission") req1 = "Mass Production" req2 = "Atomic Theory" flags = "" graphic = "a.nuclear_fission" graphic_alt = "-" [advance_nuclear_power] name = _("Nuclear Power") req1 = "Nuclear Fission" req2 = "Electronics" flags = "" graphic = "a.nuclear_power" graphic_alt = "-" helptext = _("+1 move for Sea units.") [advance_philosophy] name = _("Philosophy") req1 = "Mysticism" req2 = "Literacy" flags = "Bonus_Tech" bonus_message = _("Great philosophers from all the world join \ your civilization: you learn %s immediately.") graphic = "a.philosophy" graphic_alt = "-" helptext = _("Gives a bonus tech.") [advance_physics] name = _("Physics") req1 = "Literacy" req2 = "Navigation" flags = "" graphic = "a.physics" graphic_alt = "-" [advance_plastics] name = _("Plastics") req1 = "Refining" req2 = "Space Flight" graphic = "a.plastics" graphic_alt = "-" helptext = _("+25% population pollution.") [advance_polytheism] name = _("Polytheism") req1 = "Horseback Riding" req2 = "Ceremonial Burial" flags = "" graphic = "a.polytheism" graphic_alt = "-" [advance_pottery] name = _("Pottery") req1 = "None" req2 = "None" flags = "" graphic = "a.pottery" graphic_alt = "-" [advance_radio] name = _("Radio") req1 = "Flight" req2 = "Electricity" flags = "" graphic = "a.radio" graphic_alt = "-" helptext = _("Allows Airbase, Buoy.") [advance_railroad] name = _("?tech:Railroad") req1 = "Steam Engine" req2 = "Bridge Building" flags = "" graphic = "a.railroad" graphic_alt = "-" helptext = _("Obsoletes Hanging Gardens. Allows Railroads. Less Trade revenue.") [advance_recycling] name = _("Recycling") req1 = "Mass Production" req2 = "Democracy" flags = "" graphic = "a.recycling" graphic_alt = "-" [advance_refining] name = _("Refining") req1 = "Chemistry" req2 = "The Corporation" flags = "" graphic = "a.refining" graphic_alt = "-" helptext = _("Allows Oil Wells on Glaciers.") [advance_refrigeration] name = _("Refrigeration") req1 = "Sanitation" req2 = "Electricity" flags = "" graphic = "a.refrigeration" graphic_alt = "-" helptext = _("Allows Farmland.") [advance_robotics] name = _("Robotics") req1 = "Mobile Warfare" req2 = "Computers" flags = "" graphic = "a.robotics" graphic_alt = "-" helptext = _("Obsoletes Artillery, King Richards Crusade.") [advance_rocketry] name = _("Rocketry") req1 = "Advanced Flight" req2 = "Electronics" flags = "" graphic = "a.rocketry" graphic_alt = "-" helptext = _("Obsoletes Cruiser.") [advance_sanitation] name = _("Sanitation") req1 = "Engineering" req2 = "Medicine" flags = "" graphic = "a.sanitation" graphic_alt = "-" [advance_seafaring] name = _("Seafaring") req1 = "Pottery" req2 = "Map Making" flags = "" graphic = "a.seafaring" graphic_alt = "-" [advance_space_flight] name = _("Space Flight") req1 = "Computers" req2 = "Rocketry" flags = "" graphic = "a.space_flight" graphic_alt = "-" [advance_stealth] name = _("Stealth") req1 = "Superconductors" req2 = "Advanced Flight" flags = "" graphic = "a.stealth" graphic_alt = "-" helptext = _("Obsoletes Fighter, Bomber.") [advance_steam_engine] name = _("Steam Engine") req1 = "Physics" req2 = "Invention" flags = "" graphic = "a.steam_engine" graphic_alt = "-" helptext = _("Obsoletes Frigate.") [advance_steel] name = _("Steel") req1 = "Electricity" req2 = "Industrialization" flags = "" graphic = "a.steel" graphic_alt = "-" [advance_superconductors] name = _("Superconductors") req1 = "Nuclear Power" req2 = "Laser" flags = "" graphic = "a.superconductors" graphic_alt = "-" [advance_tactics] name = _("Tactics") req1 = "Conscription" req2 = "Leadership" flags = "" graphic = "a.tactics" graphic_alt = "-" helptext = _("Obsoletes Dragoons.") [advance_the_corporation] name = _("The Corporation") req1 = "Economics" req2 = "Industrialization" flags = "" graphic = "a.the_corporation" graphic_alt = "-" helptext = _("Obsoletes Caravan. +1 trade route per city.") [advance_the_republic] name = _("The Republic") req1 = "Code of Laws" req2 = "Literacy" flags = "" graphic = "a.the_republic" graphic_alt = "-" [advance_the_wheel] name = _("The Wheel") req1 = "Horseback Riding" req2 = "None" flags = "" graphic = "a.the_wheel" graphic_alt = "-" [advance_theology] name = _("Theology") req1 = "Feudalism" req2 = "Monotheism" flags = "" graphic = "a.theology" graphic_alt = "-" helptext = _("Obsoletes Oracle. +1 Effect on Cathedral, Michelangelos Chapel.") [advance_theory_of_gravity] name = _("Theory of Gravity") req1 = "Astronomy" req2 = "University" flags = "" graphic = "a.theory_of_gravity" graphic_alt = "-" [advance_trade] name = _("Trade") req1 = "Currency" req2 = "Code of Laws" flags = "" graphic = "a.trade" graphic_alt = "-" [advance_university] name = _("University") req1 = "Mathematics" req2 = "Philosophy" flags = "" graphic = "a.university" graphic_alt = "-" [advance_warrior_code] name = _("Warrior Code") req1 = "None" req2 = "None" flags = "" graphic = "a.warrior_code" graphic_alt = "-" [advance_writing] name = _("Writing") req1 = "Alphabet" req2 = "None" flags = "" graphic = "a.writing" graphic_alt = "-"
0
0.710197
1
0.710197
game-dev
MEDIA
0.971791
game-dev
0.735672
1
0.735672
ReactiveDrop/reactivedrop_public_src
2,786
src/game/server/hl2/ar2_explosion.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "ar2_explosion.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define AR2EXPLOSION_ENTITYNAME "ar2explosion" IMPLEMENT_SERVERCLASS_ST(AR2Explosion, DT_AR2Explosion) SendPropString( SENDINFO( m_szMaterialName ) ), END_SEND_TABLE() LINK_ENTITY_TO_CLASS(ar2explosion, AR2Explosion); //--------------------------------------------------------- // Save/Restore //--------------------------------------------------------- BEGIN_DATADESC( AR2Explosion ) DEFINE_AUTO_ARRAY( m_szMaterialName, FIELD_CHARACTER ), END_DATADESC() AR2Explosion* AR2Explosion::CreateAR2Explosion(const Vector &pos) { CBaseEntity *pEnt = CreateEntityByName(AR2EXPLOSION_ENTITYNAME); if(pEnt) { AR2Explosion *pEffect = dynamic_cast<AR2Explosion*>(pEnt); if(pEffect && pEffect->edict()) { pEffect->SetLocalOrigin( pos ); pEffect->Activate(); return pEffect; } else { UTIL_Remove(pEnt); } } return NULL; } //----------------------------------------------------------------------------- // A lightweight entity for level-designer placed AR2 explosions. //----------------------------------------------------------------------------- class CEnvAR2Explosion : public CPointEntity { public: DECLARE_CLASS( CEnvAR2Explosion, CPointEntity ); void Spawn( void ); // Input handlers void InputExplode( inputdata_t &inputdata ); DECLARE_DATADESC(); private: string_t m_iszMaterialName; }; BEGIN_DATADESC( CEnvAR2Explosion ) DEFINE_INPUTFUNC(FIELD_VOID, "Explode", InputExplode), DEFINE_KEYFIELD(m_iszMaterialName, FIELD_STRING, "material"), END_DATADESC() LINK_ENTITY_TO_CLASS( env_ar2explosion, CEnvAR2Explosion ); //----------------------------------------------------------------------------- // Purpose: So you can see where this function begins and the last one ends. //----------------------------------------------------------------------------- void CEnvAR2Explosion::Spawn( void ) { Precache(); SetSolid( SOLID_NONE ); AddEffects( EF_NODRAW ); SetMoveType( MOVETYPE_NONE ); } //----------------------------------------------------------------------------- // Purpose: Creates the explosion effect. //----------------------------------------------------------------------------- void CEnvAR2Explosion::InputExplode( inputdata_t &inputdata ) { AR2Explosion *pExplosion = AR2Explosion::CreateAR2Explosion(GetAbsOrigin()); if (pExplosion) { pExplosion->SetLifetime( 10 ); if (m_iszMaterialName != NULL_STRING) { pExplosion->SetMaterialName(STRING(m_iszMaterialName)); } } }
0
0.783055
1
0.783055
game-dev
MEDIA
0.92839
game-dev
0.617802
1
0.617802
libretro/libretro-prboom
18,356
src/r_bsp.c
/* Emacs style mode select -*- C++ -*- *----------------------------------------------------------------------------- * * * PrBoom: a Doom port merged with LxDoom and LSDLDoom * based on BOOM, a modified and improved DOOM engine * Copyright (C) 1999 by * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman * Copyright (C) 1999-2000 by * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze * Copyright 2005, 2006 by * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko * * 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. * * DESCRIPTION: * BSP traversal, handling of LineSegs for rendering. * *-----------------------------------------------------------------------------*/ #include "doomstat.h" #include "m_bbox.h" #include "r_main.h" #include "r_segs.h" #include "r_plane.h" #include "r_things.h" #include "r_bsp.h" // cph - sanity checking #include "v_video.h" #include "lprintf.h" seg_t *curline; side_t *sidedef; line_t *linedef; sector_t *frontsector; sector_t *backsector; drawseg_t *ds_p; // killough 4/7/98: indicates doors closed wrt automap bugfix: // cph - replaced by linedef rendering flags - int doorclosed; // killough: New code which removes 2s linedef limit drawseg_t *drawsegs; unsigned maxdrawsegs; // drawseg_t drawsegs[MAXDRAWSEGS]; // old code -- killough // // R_ClearDrawSegs // void R_ClearDrawSegs(void) { ds_p = drawsegs; } // CPhipps - // Instead of clipsegs, let's try using an array with one entry for each column, // indicating whether it's blocked by a solid wall yet or not. uint8_t solidcol[MAX_SCREENWIDTH]; // CPhipps - // R_ClipWallSegment // // Replaces the old R_Clip*WallSegment functions. It draws bits of walls in those // columns which aren't solid, and updates the solidcol[] array appropriately static void R_ClipWallSegment(int first, int last, dbool solid) { uint8_t *p; while (first < last) { if (solidcol[first]) { if (!(p = memchr(solidcol+first, 0, last-first))) return; // All solid first = p - solidcol; } else { int to; if (!(p = memchr(solidcol+first, 1, last-first))) to = last; else to = p - solidcol; R_StoreWallRange(first, to-1); if (solid) memset(solidcol+first,1,to-first); first = to; } } } // // R_ClearClipSegs // void R_ClearClipSegs (void) { memset(solidcol, 0, SCREENWIDTH); } // killough 1/18/98 -- This function is used to fix the automap bug which // showed lines behind closed doors simply because the door had a dropoff. // // cph - converted to R_RecalcLineFlags. This recalculates all the flags for // a line, including closure and texture tiling. static void R_RecalcLineFlags(void) { linedef->r_validcount = gametic; /* First decide if the line is closed, normal, or invisible */ if (!(linedef->flags & ML_TWOSIDED) || backsector->ceilingheight <= frontsector->floorheight || backsector->floorheight >= frontsector->ceilingheight || ( // if door is closed because back is shut: backsector->ceilingheight <= backsector->floorheight // preserve a kind of transparent door/lift special effect: && (backsector->ceilingheight >= frontsector->ceilingheight || curline->sidedef->toptexture) && (backsector->floorheight <= frontsector->floorheight || curline->sidedef->bottomtexture) // properly render skies (consider door "open" if both ceilings are sky): && (backsector->ceilingpic !=skyflatnum || frontsector->ceilingpic!=skyflatnum) ) ) linedef->r_flags = RF_CLOSED; else { // Reject empty lines used for triggers // and special events. // Identical floor and ceiling on both sides, // identical light levels on both sides, // and no middle texture. // CPhipps - recode for speed, not certain if this is portable though if (backsector->ceilingheight != frontsector->ceilingheight || backsector->floorheight != frontsector->floorheight || curline->sidedef->midtexture || memcmp(&backsector->floor_xoffs, &frontsector->floor_xoffs, sizeof(frontsector->floor_xoffs) + sizeof(frontsector->floor_yoffs) + sizeof(frontsector->ceiling_xoffs) + sizeof(frontsector->ceiling_yoffs) + sizeof(frontsector->ceilingpic) + sizeof(frontsector->floorpic) + sizeof(frontsector->lightlevel) + sizeof(frontsector->floorlightsec) + sizeof(frontsector->ceilinglightsec))) { linedef->r_flags = 0; return; } else linedef->r_flags = RF_IGNORE; } /* cph - I'm too lazy to try and work with offsets in this */ if (curline->sidedef->rowoffset) return; /* Now decide on texture tiling */ if (linedef->flags & ML_TWOSIDED) { int c; /* Does top texture need tiling */ if ((c = frontsector->ceilingheight - backsector->ceilingheight) > 0 && (textureheight[texturetranslation[curline->sidedef->toptexture]] > c)) linedef->r_flags |= RF_TOP_TILE; /* Does bottom texture need tiling */ if ((c = frontsector->floorheight - backsector->floorheight) > 0 && (textureheight[texturetranslation[curline->sidedef->bottomtexture]] > c)) linedef->r_flags |= RF_BOT_TILE; } else { int c; /* Does middle texture need tiling */ if ((c = frontsector->ceilingheight - frontsector->floorheight) > 0 && (textureheight[texturetranslation[curline->sidedef->midtexture]] > c)) linedef->r_flags |= RF_MID_TILE; } } // // killough 3/7/98: Hack floor/ceiling heights for deep water etc. // // If player's view height is underneath fake floor, lower the // drawn ceiling to be just under the floor height, and replace // the drawn floor and ceiling textures, and light level, with // the control sector's. // // Similar for ceiling, only reflected. // // killough 4/11/98, 4/13/98: fix bugs, add 'back' parameter // sector_t *R_FakeFlat(sector_t *sec, sector_t *tempsec, int *floorlightlevel, int *ceilinglightlevel, dbool back) { if (floorlightlevel) *floorlightlevel = sec->floorlightsec == -1 ? sec->lightlevel : sectors[sec->floorlightsec].lightlevel; if (ceilinglightlevel) *ceilinglightlevel = sec->ceilinglightsec == -1 ? // killough 4/11/98 sec->lightlevel : sectors[sec->ceilinglightsec].lightlevel; if (sec->heightsec != -1) { const sector_t *s = &sectors[sec->heightsec]; int heightsec = viewplayer->mo->subsector->sector->heightsec; int underwater = heightsec!=-1 && viewz<=sectors[heightsec].floorheight; // Replace sector being drawn, with a copy to be hacked *tempsec = *sec; // Replace floor and ceiling height with other sector's heights. tempsec->floorheight = s->floorheight; tempsec->ceilingheight = s->ceilingheight; // killough 11/98: prevent sudden light changes from non-water sectors: if (underwater && (tempsec-> floorheight = sec->floorheight, tempsec->ceilingheight = s->floorheight-1, !back)) { // head-below-floor hack tempsec->floorpic = s->floorpic; tempsec->floor_xoffs = s->floor_xoffs; tempsec->floor_yoffs = s->floor_yoffs; if (underwater) { if (s->ceilingpic == skyflatnum) { tempsec->floorheight = tempsec->ceilingheight+1; tempsec->ceilingpic = tempsec->floorpic; tempsec->ceiling_xoffs = tempsec->floor_xoffs; tempsec->ceiling_yoffs = tempsec->floor_yoffs; } else { tempsec->ceilingpic = s->ceilingpic; tempsec->ceiling_xoffs = s->ceiling_xoffs; tempsec->ceiling_yoffs = s->ceiling_yoffs; } } tempsec->lightlevel = s->lightlevel; if (floorlightlevel) *floorlightlevel = s->floorlightsec == -1 ? s->lightlevel : sectors[s->floorlightsec].lightlevel; // killough 3/16/98 if (ceilinglightlevel) *ceilinglightlevel = s->ceilinglightsec == -1 ? s->lightlevel : sectors[s->ceilinglightsec].lightlevel; // killough 4/11/98 } else if (heightsec != -1 && viewz >= sectors[heightsec].ceilingheight && sec->ceilingheight > s->ceilingheight) { // Above-ceiling hack tempsec->ceilingheight = s->ceilingheight; tempsec->floorheight = s->ceilingheight + 1; tempsec->floorpic = tempsec->ceilingpic = s->ceilingpic; tempsec->floor_xoffs = tempsec->ceiling_xoffs = s->ceiling_xoffs; tempsec->floor_yoffs = tempsec->ceiling_yoffs = s->ceiling_yoffs; if (s->floorpic != skyflatnum) { tempsec->ceilingheight = sec->ceilingheight; tempsec->floorpic = s->floorpic; tempsec->floor_xoffs = s->floor_xoffs; tempsec->floor_yoffs = s->floor_yoffs; } tempsec->lightlevel = s->lightlevel; if (floorlightlevel) *floorlightlevel = s->floorlightsec == -1 ? s->lightlevel : sectors[s->floorlightsec].lightlevel; // killough 3/16/98 if (ceilinglightlevel) *ceilinglightlevel = s->ceilinglightsec == -1 ? s->lightlevel : sectors[s->ceilinglightsec].lightlevel; // killough 4/11/98 } sec = tempsec; // Use other sector } return sec; } // // R_AddLine // Clips the given segment // and adds any visible pieces to the line list. // static void R_AddLine (seg_t *line) { int x1; int x2; angle_t angle1; angle_t angle2; angle_t span; angle_t tspan; static sector_t tempsec; // killough 3/8/98: ceiling/water hack curline = line; angle1 = R_PointToAngle (line->v1->x, line->v1->y); angle2 = R_PointToAngle (line->v2->x, line->v2->y); // Clip to view edges. span = angle1 - angle2; // Back side, i.e. backface culling if (span >= ANG180) return; // Global angle needed by segcalc. rw_angle1 = angle1; angle1 -= viewangle; angle2 -= viewangle; tspan = angle1 + clipangle; if (tspan > 2*clipangle) { tspan -= 2*clipangle; // Totally off the left edge? if (tspan >= span) return; angle1 = clipangle; } tspan = clipangle - angle2; if (tspan > 2*clipangle) { tspan -= 2*clipangle; // Totally off the left edge? if (tspan >= span) return; angle2 = 0-clipangle; } // The seg is in the view range, // but not necessarily visible. angle1 = (angle1+ANG90)>>ANGLETOFINESHIFT; angle2 = (angle2+ANG90)>>ANGLETOFINESHIFT; // killough 1/31/98: Here is where "slime trails" can SOMETIMES occur: x1 = viewangletox[angle1]; x2 = viewangletox[angle2]; // Does not cross a pixel? if (x1 >= x2) // killough 1/31/98 -- change == to >= for robustness return; backsector = line->backsector; // Single sided line? if (backsector) // killough 3/8/98, 4/4/98: hack for invisible ceilings / deep water backsector = R_FakeFlat(backsector, &tempsec, NULL, NULL, TRUE); /* cph - roll up linedef properties in flags */ if ((linedef = curline->linedef)->r_validcount != gametic) R_RecalcLineFlags(); if (linedef->r_flags & RF_IGNORE) { return; } else R_ClipWallSegment (x1, x2, linedef->r_flags & RF_CLOSED); } // // R_CheckBBox // Checks BSP node/subtree bounding box. // Returns TRUE // if some part of the bbox might be visible. // static const int checkcoord[12][4] = // killough -- static const { {3,0,2,1}, {3,0,2,0}, {3,1,2,0}, {0}, {2,0,2,1}, {0,0,0,0}, {3,1,3,0}, {0}, {2,0,3,1}, {2,1,3,1}, {2,1,3,0} }; // killough 1/28/98: static // CPhipps - const parameter, reformatted static dbool R_CheckBBox(const fixed_t *bspcoord) { angle_t angle1, angle2; { int boxpos; const int* check; // Find the corners of the box // that define the edges from current viewpoint. boxpos = (viewx <= bspcoord[BOXLEFT] ? 0 : viewx < bspcoord[BOXRIGHT ] ? 1 : 2) + (viewy >= bspcoord[BOXTOP ] ? 0 : viewy > bspcoord[BOXBOTTOM] ? 4 : 8); if (boxpos == 5) return TRUE; check = checkcoord[boxpos]; angle1 = R_PointToAngle (bspcoord[check[0]], bspcoord[check[1]]) - viewangle; angle2 = R_PointToAngle (bspcoord[check[2]], bspcoord[check[3]]) - viewangle; } // cph - replaced old code, which was unclear and badly commented // Much more efficient code now if ((signed)angle1 < (signed)angle2) { /* it's "behind" us */ /* Either angle1 or angle2 is behind us, so it doesn't matter if we * change it to the corect sign */ if ((angle1 >= ANG180) && (angle1 < ANG270)) angle1 = INT_MAX; /* which is ANG180-1 */ else angle2 = INT_MIN; } if ((signed)angle2 >= (signed)clipangle) return FALSE; // Both off left edge if ((signed)angle1 <= -(signed)clipangle) return FALSE; // Both off right edge if ((signed)angle1 >= (signed)clipangle) angle1 = clipangle; // Clip at left edge if ((signed)angle2 <= -(signed)clipangle) angle2 = 0-clipangle; // Clip at right edge // Find the first clippost // that touches the source post // (adjacent pixels are touching). angle1 = (angle1+ANG90)>>ANGLETOFINESHIFT; angle2 = (angle2+ANG90)>>ANGLETOFINESHIFT; { int sx1 = viewangletox[angle1]; int sx2 = viewangletox[angle2]; // const cliprange_t *start; // Does not cross a pixel. if (sx1 == sx2) return FALSE; if (!memchr(solidcol+sx1, 0, sx2-sx1)) return FALSE; // All columns it covers are already solidly covered } return TRUE; } // // R_Subsector // Determine floor/ceiling planes. // Add sprites of things in sector. // Draw one or more line segments. // // killough 1/31/98 -- made static, polished static void R_Subsector(int num) { int count; seg_t *line; subsector_t *sub; sector_t tempsec; // killough 3/7/98: deep water hack int floorlightlevel; // killough 3/16/98: set floor lightlevel int ceilinglightlevel; // killough 4/11/98 sub = &subsectors[num]; frontsector = sub->sector; count = sub->numlines; line = &segs[sub->firstline]; // killough 3/8/98, 4/4/98: Deep water / fake ceiling effect frontsector = R_FakeFlat(frontsector, &tempsec, &floorlightlevel, &ceilinglightlevel, FALSE); // killough 4/11/98 // killough 3/7/98: Add (x,y) offsets to flats, add deep water check // killough 3/16/98: add floorlightlevel // killough 10/98: add support for skies transferred from sidedefs floorplane = frontsector->floorheight < viewz || // killough 3/7/98 (frontsector->heightsec != -1 && sectors[frontsector->heightsec].ceilingpic == skyflatnum) ? R_FindPlane(frontsector->floorheight, frontsector->floorpic == skyflatnum && // kilough 10/98 frontsector->sky & PL_SKYFLAT ? frontsector->sky : frontsector->floorpic, floorlightlevel, // killough 3/16/98 frontsector->floor_xoffs, // killough 3/7/98 frontsector->floor_yoffs ) : NULL; ceilingplane = frontsector->ceilingheight > viewz || frontsector->ceilingpic == skyflatnum || (frontsector->heightsec != -1 && sectors[frontsector->heightsec].floorpic == skyflatnum) ? R_FindPlane(frontsector->ceilingheight, // killough 3/8/98 frontsector->ceilingpic == skyflatnum && // kilough 10/98 frontsector->sky & PL_SKYFLAT ? frontsector->sky : frontsector->ceilingpic, ceilinglightlevel, // killough 4/11/98 frontsector->ceiling_xoffs, // killough 3/7/98 frontsector->ceiling_yoffs ) : NULL; // killough 9/18/98: Fix underwater slowdown, by passing real sector // instead of fake one. Improve sprite lighting by basing sprite // lightlevels on floor & ceiling lightlevels in the surrounding area. // // 10/98 killough: // // NOTE: TeamTNT fixed this bug incorrectly, messing up sprite lighting!!! // That is part of the 242 effect!!! If you simply pass sub->sector to // the old code you will not get correct lighting for underwater sprites!!! // Either you must pass the fake sector and handle validcount here, on the // real sector, or you must account for the lighting in some other way, // like passing it as an argument. R_AddSprites(sub, (floorlightlevel+ceilinglightlevel)/2); while (count--) { if (line->miniseg == FALSE) R_AddLine (line); line++; curline = NULL; /* cph 2001/11/18 - must clear curline now we're done with it, so R_ColourMap doesn't try using it for other things */ } } // // RenderBSPNode // Renders all subsectors below a given node, // traversing subtree recursively. // Just call with BSP root. // // killough 5/2/98: reformatted, removed tail recursion void R_RenderBSPNode(int bspnum) { while (!(bspnum & NF_SUBSECTOR)) // Found a subsector? { const node_t *bsp = &nodes[bspnum]; // Decide which side the view point is on. int side = R_PointOnSide(viewx, viewy, bsp); // Recursively divide front space. R_RenderBSPNode(bsp->children[side]); // Possibly divide back space. if (!R_CheckBBox(bsp->bbox[side^1])) return; bspnum = bsp->children[side^1]; } R_Subsector(bspnum == -1 ? 0 : bspnum & ~NF_SUBSECTOR); }
0
0.890653
1
0.890653
game-dev
MEDIA
0.778212
game-dev,graphics-rendering
0.920696
1
0.920696
SDHK/WorldTreeFramework
2,552
Unity/Assets/Scripts/WorldTreeFramework/UnityEnvironment/RunTime/ObjectPool/Pool/GameObjectPool.cs
/**************************************** * 作者:闪电黑客 * 日期:2024/5/14 17:47 * 描述: */ using UnityEngine; namespace WorldTree { /// <summary> /// GameObject对象池 /// </summary> public class GameObjectPool : GenericPool<GameObject>, ChildOf<GameObjectPoolManager> , AsRule<Awake> { /// <summary> /// 预制体 /// </summary> public GameObject prefab { get; set; } /// <summary> /// 游戏对象名称 /// </summary> private string objName; public GameObjectPool() { ObjectType = typeof(GameObject); objName = "GameObject"; NewObject = ObjectNew; DestroyObject = ObjectDestroy; objectOnNew += ObjectOnNew; objectOnGet += ObjectOnGet; objectOnRecycle += ObjectOnRecycle; } /// <summary> /// 设置预制体 /// </summary> public void SetPrefab(GameObject prefab) { if (prefab != null) { this.prefab = prefab; objName = prefab.name; } } public override string ToString() { return "[GameObjectPool] : " + objName; } public override void OnDispose() { base.OnDispose(); } /// <summary> /// 获取对象(设置父节点) /// </summary> public GameObject Get(Transform parent) { GameObject gameObject = DequeueOrNewObject(); gameObject.transform.parent = parent; objectOnGet?.Invoke(gameObject); Preload(); return gameObject; } /// <summary> /// 新建对象 /// </summary> private GameObject ObjectNew(IPool pool) { return (prefab == null) ? new GameObject(objName) : GameObject.Instantiate(prefab); } /// <summary> /// 销毁对象 /// </summary> private void ObjectDestroy(GameObject gameObject) { GameObject.Destroy(gameObject); } /// <summary> /// 对象新建处理 /// </summary> /// <param name="gameObject"></param> private void ObjectOnNew(GameObject gameObject) { } /// <summary> /// 对象获取处理 /// </summary> private void ObjectOnGet(GameObject gameObject) { gameObject.SetActive(true); } /// <summary> /// 对象回收处理 /// </summary> private void ObjectOnRecycle(GameObject gameObject) { gameObject.SetActive(false); } } }
0
0.586004
1
0.586004
game-dev
MEDIA
0.955672
game-dev
0.827689
1
0.827689
games-on-whales/wolf-ui
1,361
src/Misc/InputActions.cs
using Godot; using System; using System.Collections.Generic; using WolfUI; public class ControlCounter { public required int counter; public required Control control; } public partial class InputActions : HBoxContainer { [Export] private Control _cancelContainer = null!; [Export] private Control _backContainer = null!; private static Dictionary<string, ControlCounter> _checkCounter = new Dictionary<string, ControlCounter>(); private static InputActions _singleton = null!; public override void _Ready() { _singleton ??= this; _checkCounter["ui_select"] = new ControlCounter() { counter = 0, control = _backContainer, }; _checkCounter["ui_cancel"] = new ControlCounter() { counter = 0, control = _cancelContainer, }; } public override void _Process(double delta) { foreach (var kv in _checkCounter) { kv.Value.counter--; if (kv.Value.counter == 0) { kv.Value.control.Hide(); } } } public static bool IsActionJustPressed(string action) { _checkCounter[action].counter = 2; _checkCounter[action].control.Visible = true; return Input.IsActionJustPressed(action); } }
0
0.840614
1
0.840614
game-dev
MEDIA
0.68254
game-dev,desktop-app
0.885003
1
0.885003
Frontiers-PackForge/CosmicFrontiers
4,075
overrides/config/embers-common.toml
#Settings for machine/item/misc parameters [parameters] [parameters.mechanical_core] #The maximum distance that mechanical cores can proxy capabilities and upgrades. max_distance = 3 [parameters.emberBore] #The speed modifier of the Ember Bore before upgrades. speedMod = 1.0 #The time in ticks it takes to try one dig attempt. processTime = 200 #The amount of fuel consumed each tick. fuelCost = 3.0 [parameters.reservoir] #How much fluid (in mb) fits into each Caminite Ring on a Reservoir. capacity = 40000 [parameters.mini_boiler] #How much fluid and gas (in mb) fits into a Mini Boiler. capacity = 16000 #How much fluid (in mb) a Mini Boiler boils for each ember used/generated. heat_multiplier = 1.0 #Whether the Mini Boiler can explode when overfilled with gas can_explode = true [parameters.melter] #The time in ticks it takes to process one recipe. processTime = 200 #The ember cost per tick. cost = 1.0 #How much fluid (in mb) fits into a Melter. capacity = 4000 [parameters.geoSeparator] #How much fluid (in mb) fits into a Geologic Seperator. capacity = 1000 [parameters.stamper] #How much fluid (in mb) fits into the Stamp Base. capacity = 1500 [parameters.charger] #How much ember is transferred between item and charger per tick. transfer = 10.0 [parameters.fluidVessel] #How much fluid (in mb) fits into the Fluid Vessel. capacity = 16000 [parameters.ember_injector] #The maximum distance that Ember Injectors can be placed from a crystal seed. max_distance = 1 [parameters.hearth_coil] #The amount of ember consumed per tick. ember_cost = 1.0 #The amount of heat gained per tick when consuming ember. heating_speed = 1.0 #The amount of heat lost per tick when not consuming ember. cooling_speed = 1.0 #The maximum heat value the hearth coil can reach without upgrades. max_heat = 280.0 #The time in ticks it takes to cook 1 item at the highest heat. min_cook_time = 20 #The time in ticks it takes to cook 1 item at the lowest heat. max_cook_time = 300 [parameters.dawnstone_anvil] #The amount of hits required to perform one recipe on a dawnstone anvil. max_hits = 40 [parameters.blazingRay] #Ember used up by each shot. cost = 25.0 #Cooldown in ticks between each shot. cooldown = 10 #Time in ticks to fully charge. charge = 20 #Damage dealt by one shot. damage = 7.0 #Maximum spread. spread = 30.0 #Maximum shot distance. distance = 96.0 [parameters.cinderStaff] #Ember used up by each shot. cost = 25.0 #Cooldown in ticks between each shot. cooldown = 10 #Time in ticks to fully charge. charge = 60 #Damage dealt by one shot. damage = 17.0 #Size of the projectile. size = 17.0 #Area of Effect on impact. aoe = 2.125 #Maximum lifetime in ticks of projectile. lifetime = 160 [parameters.ashen] [parameters.ashen.goggles] #How many inflictor gems can fit in the ashen goggles. gem_slots = 2 [parameters.ashen.cloak] #How many inflictor gems can fit in the ashen cloak. gem_slots = 7 [parameters.ashen.leggings] #How many inflictor gems can fit in the ashen leggings. gem_slots = 5 [parameters.ashen.boots] #How many inflictor gems can fit in the ashen boots. gem_slots = 3 [parameters.shiftingScales] #Syntax is 'damagetype:rate'. Determines which damage types are partially unaffected by the shifting scales augment. damagePasses = ["drown:1.0", "starve:1.0"] #Syntax is 'damagetype:rate'. Specifies a separate damage rate for depleting the scales. damageRates = [] #Miscellaneous settings [misc] #Codex entries need to be completed before the next one unlocks. codexProgression = true #If true, Embers homing projectiles will go for neutral players. everybodyIsEnemy = false #Which domains are preferred for recipes with dynamic outputs. tagPreferences = ["minecraft", "embers"] #Which items are preferred as the result of breaking down a tool on an anvil. itemPreferences = ["minecraft:oak_planks", "minecraft:cobblestone"]
0
0.777214
1
0.777214
game-dev
MEDIA
0.990492
game-dev
0.563003
1
0.563003
rashiph/DecompliedDotNetLibraries
14,456
mscorlib/System/Reflection/Module.cs
namespace System.Reflection { using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; [Serializable, ComVisible(true), ClassInterface(ClassInterfaceType.None), ComDefaultInterface(typeof(_Module)), PermissionSet(SecurityAction.InheritanceDemand, Unrestricted=true)] public abstract class Module : _Module, ISerializable, ICustomAttributeProvider { private const BindingFlags DefaultLookup = (BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); public static readonly TypeFilter FilterTypeName; public static readonly TypeFilter FilterTypeNameIgnoreCase; static Module() { System.Reflection.__Filters filters = new System.Reflection.__Filters(); FilterTypeName = new TypeFilter(filters.FilterTypeName); FilterTypeNameIgnoreCase = new TypeFilter(filters.FilterTypeNameIgnoreCase); } protected Module() { } public override bool Equals(object o) { return base.Equals(o); } public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria) { Type[] types = this.GetTypes(); int num = 0; for (int i = 0; i < types.Length; i++) { if ((filter != null) && !filter(types[i], filterCriteria)) { types[i] = null; } else { num++; } } if (num == types.Length) { return types; } Type[] typeArray2 = new Type[num]; num = 0; for (int j = 0; j < types.Length; j++) { if (types[j] != null) { typeArray2[num++] = types[j]; } } return typeArray2; } public virtual object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public virtual IList<CustomAttributeData> GetCustomAttributesData() { throw new NotImplementedException(); } public FieldInfo GetField(string name) { return this.GetField(name, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); } public virtual FieldInfo GetField(string name, BindingFlags bindingAttr) { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.GetField(name, bindingAttr); } public FieldInfo[] GetFields() { return this.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); } public virtual FieldInfo[] GetFields(BindingFlags bindingFlags) { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.GetFields(bindingFlags); } public override int GetHashCode() { return base.GetHashCode(); } public MethodInfo GetMethod(string name) { if (name == null) { throw new ArgumentNullException("name"); } return this.GetMethodImpl(name, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, CallingConventions.Any, null, null); } public MethodInfo GetMethod(string name, Type[] types) { if (name == null) { throw new ArgumentNullException("name"); } if (types == null) { throw new ArgumentNullException("types"); } for (int i = 0; i < types.Length; i++) { if (types[i] == null) { throw new ArgumentNullException("types"); } } return this.GetMethodImpl(name, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, CallingConventions.Any, types, null); } public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { if (name == null) { throw new ArgumentNullException("name"); } if (types == null) { throw new ArgumentNullException("types"); } for (int i = 0; i < types.Length; i++) { if (types[i] == null) { throw new ArgumentNullException("types"); } } return this.GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers); } protected virtual MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } public MethodInfo[] GetMethods() { return this.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); } public virtual MethodInfo[] GetMethods(BindingFlags bindingFlags) { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.GetMethods(bindingFlags); } internal virtual System.ModuleHandle GetModuleHandle() { return System.ModuleHandle.EmptyHandle; } [SecurityCritical] public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } public virtual void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) { RuntimeModule module = this as RuntimeModule; if (module != null) { module.GetPEKind(out peKind, out machine); } throw new NotImplementedException(); } public virtual X509Certificate GetSignerCertificate() { throw new NotImplementedException(); } [ComVisible(true)] public virtual Type GetType(string className) { return this.GetType(className, false, false); } [ComVisible(true)] public virtual Type GetType(string className, bool ignoreCase) { return this.GetType(className, false, ignoreCase); } [ComVisible(true)] public virtual Type GetType(string className, bool throwOnError, bool ignoreCase) { throw new NotImplementedException(); } public virtual Type[] GetTypes() { throw new NotImplementedException(); } public virtual bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } public virtual bool IsResource() { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.IsResource(); } public static bool operator ==(Module left, Module right) { return (object.ReferenceEquals(left, right) || ((((left != null) && (right != null)) && (!(left is RuntimeModule) && !(right is RuntimeModule))) && left.Equals(right))); } public static bool operator !=(Module left, Module right) { return !(left == right); } public FieldInfo ResolveField(int metadataToken) { return this.ResolveField(metadataToken, null, null); } public virtual FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); } public MemberInfo ResolveMember(int metadataToken) { return this.ResolveMember(metadataToken, null, null); } public virtual MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments); } public MethodBase ResolveMethod(int metadataToken) { return this.ResolveMethod(metadataToken, null, null); } public virtual MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); } public virtual byte[] ResolveSignature(int metadataToken) { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.ResolveSignature(metadataToken); } public virtual string ResolveString(int metadataToken) { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.ResolveString(metadataToken); } public Type ResolveType(int metadataToken) { return this.ResolveType(metadataToken, null, null); } public virtual Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); } void _Module.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _Module.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _Module.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _Module.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } public override string ToString() { return this.ScopeName; } public virtual System.Reflection.Assembly Assembly { get { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.Assembly; } } public virtual string FullyQualifiedName { get { throw new NotImplementedException(); } } public virtual int MDStreamVersion { get { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.MDStreamVersion; } } public virtual int MetadataToken { get { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.MetadataToken; } } public System.ModuleHandle ModuleHandle { get { return this.GetModuleHandle(); } } public virtual Guid ModuleVersionId { get { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.ModuleVersionId; } } public virtual string Name { get { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.Name; } } public virtual string ScopeName { get { RuntimeModule module = this as RuntimeModule; if (module == null) { throw new NotImplementedException(); } return module.ScopeName; } } } }
0
0.945044
1
0.945044
game-dev
MEDIA
0.361276
game-dev
0.961066
1
0.961066
ihm-tswow/Links-Awakening-DX-HD
3,673
InGame/GameObjects/Things/ObjTransition.cs
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ProjectZ.InGame.GameObjects.Base; using ProjectZ.InGame.GameObjects.Base.CObjects; using ProjectZ.InGame.GameObjects.Base.Components; using ProjectZ.InGame.Map; using ProjectZ.InGame.Things; namespace ProjectZ.InGame.GameObjects.Things { class ObjTransition : GameObject { public Color TransitionColor; public float Percentage; public float Brightness; public float WobblePercentage; public bool WobbleTransition; private float _circleSize; public ObjTransition(Map.Map map) : base(map) { SprEditorImage = Resources.SprObjects; EditorIconSource = new Rectangle(240, 16, 16, 16); // should be on top of every other object, // except the player object but only while transitioning AddComponent(DrawComponent.Index, new DrawComponent(Draw, Values.LayerTop, new CPosition(0, 0, 0))); } public void Draw(SpriteBatch spriteBatch) { var gameWidth = Game1.RenderWidth; var gameHeight = Game1.RenderHeight; if (!WobbleTransition) { _circleSize = (1 - Percentage) * (float)Math.Sqrt(gameWidth * gameWidth + gameHeight * gameHeight) / 2; var playerPosition = new Vector2( MapManager.ObjLink.PosX * MapManager.Camera.Scale, (MapManager.ObjLink.PosY - 8 - MapManager.ObjLink.PosZ) * MapManager.Camera.Scale); var centerX = gameWidth / 2.0f - (MapManager.Camera.Location.X - playerPosition.X); var centerY = gameHeight / 2.0f - (MapManager.Camera.Location.Y - playerPosition.Y); Resources.CircleShader.Parameters["softRad"].SetValue(15f); Resources.CircleShader.Parameters["size"].SetValue(_circleSize); Resources.CircleShader.Parameters["centerX"].SetValue(centerX); Resources.CircleShader.Parameters["centerY"].SetValue(centerY); Resources.CircleShader.Parameters["width"].SetValue(gameWidth); Resources.CircleShader.Parameters["height"].SetValue(gameHeight); // draw the circle spriteBatch.Begin(SpriteSortMode.Immediate, null, SamplerState.PointWrap, null, null, Resources.CircleShader, Game1.GetMatrix); spriteBatch.Draw(Resources.SprWhite, new Rectangle(0, 0, gameWidth, gameHeight), TransitionColor); spriteBatch.End(); } else { // draw the wobble transition effect Game1.GameManager.ChangeRenderTarget(); Resources.WobbleEffect.Parameters["width"].SetValue(gameWidth); Resources.WobbleEffect.Parameters["height"].SetValue(gameHeight); Resources.WobbleEffect.Parameters["scale"].SetValue(MapManager.Camera.Scale); Resources.WobbleEffect.Parameters["brightness"].SetValue(Brightness); Resources.WobbleEffect.Parameters["offset"].SetValue(WobblePercentage * 30); Resources.WobbleEffect.Parameters["offsetWidth"].SetValue((0.5f - MathF.Cos(WobblePercentage * 4) / 2) * 3); Resources.WobbleEffect.Parameters["offsetHeight"].SetValue(16); spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointWrap, null, null, Resources.WobbleEffect); spriteBatch.Draw(Game1.GameManager.GetLastRenderTarget(), Vector2.Zero, Color.White); spriteBatch.End(); } } } }
0
0.842957
1
0.842957
game-dev
MEDIA
0.71444
game-dev,graphics-rendering
0.98442
1
0.98442
dbtoaster/dbtoaster-backend
67,746
runtime/tpcc/pardisgen/include/sc/cmmap.hpp
#ifndef CMMAP_H #define CMMAP_H #include <iostream> #include <functional> #include <vector> #include <atomic> #include <type_traits> #include <cassert> #include <string> #include <libcuckoo/cuckoohash_map.hh> #include "serialization.hpp" #include "macro.hpp" #include "types.hpp" #include "types.h" #include "Version.h" #include "Predicate.h" #include "SpinLock.h" std::vector<void*> tempMem; using namespace libcuckoo; #define DEFAULT_CHUNK_SIZE 32 #ifndef DEFAULT_HEAP_SIZE #define DEFAULT_HEAP_SIZE 16 #endif FORCE_INLINE void clearTempMem() { for (auto ptr : tempMem) free(ptr); tempMem.clear(); } #define FuncType const std::function<TransactionReturnStatus (T*)>& template<typename T> class IndexMV { public: int idxId; //SBJ: Check if it can be removed MBase* mmapmv; // virtual bool hashDiffers(const T& x, const T& y) const = 0; virtual T* get(const T* key, Transaction& xact) const = 0; virtual T* getForUpdate(const T* key, OperationReturnStatus& s, Transaction& xact) = 0; virtual OperationReturnStatus add(Version<T>* v) = 0; virtual void removeEntry(T* obj, EntryMV<T>* emv) = 0; virtual void undo(Version<T>* v) = 0; virtual void del(Version<T>* v) = 0; // virtual void delCopy(const T* obj, Index<T>* primary) = 0; virtual OperationReturnStatus foreach(FuncType f, Transaction& xact) = 0; // virtual void foreachCopy(FuncType f) = 0; // virtual void slice(const T* key, FuncType f) = 0; // virtual void sliceCopy(const T* key, FuncType f) = 0; // virtual void update(T* obj) = 0; // // virtual void updateCopy(T* obj, Index<T, V>* primary) = 0; // // virtual void updateCopyDependent(T* obj, T* elem) = 0; // virtual size_t count() const = 0; // virtual void clear() = 0; virtual void prepareSize(size_t arrayS, size_t poolS) = 0; virtual ~IndexMV() { }; }; template <typename T, typename IDX_FN> struct HE_ { size_t operator()(const T* e) const { size_t h = IDX_FN::hash(*e); return h; } bool operator()(const T* e1, const T* e2) const { return IDX_FN::cmp(*e1, *e2) == 0; } }; template<typename T, typename IDX_FN > struct CuckooIndex : public IndexMV<T> { typedef HE_<T, IDX_FN> HE; cuckoohash_map<T*, EntryMV<T>*, HE, HE, std::allocator<std::pair<T, EntryMV<T>*>>> index; std::atomic<EntryMV<T>*> dataHead; CuckooIndex(int s = 0) : index((1 << 25)) { //Constructor argument is ignored dataHead = nullptr; } CuckooIndex(void* ptr, int s = 0) : index(1 << 25) { //Constructor argument is ignored dataHead = nullptr; } FORCE_INLINE bool operator==(CuckooIndex<T, IDX_FN>& that) { auto t1 = index.lock_table(); bool flag = true; Version<T>* v1, *v2; for (auto e1 = t1.cbegin(); e1 != t1.cend(); ++e1) { EntryMV<T>* e2; v1 = e1->second->versionHead; //SBJ: v1 cannot be nullptr if rollback removes EntryMV if all versions are gone if (!v1 || v1->obj.isInvalid) continue; if (!that.index.find(e1->first, e2)) { std::cerr << v1->obj << "is extra in table" << std::endl; flag = false; } else { v2 = e2->versionHead; if (!(v2->obj == v1->obj)) { std::cerr << "Found " << v1->obj << " where it should have been " << v2->obj << std::endl; flag = false; } } } t1.release(); auto t2 = that.index.lock_table(); for (auto e2 = t2.cbegin(); e2 != t2.cend(); ++e2) { EntryMV<T>* e1; v2 = e2->second->versionHead; if (!index.find(e2->first, e1)) { std::cerr << v2->obj << " is missing from table " << std::endl; flag = false; } else { v1 = e1->versionHead; if (!(v1->obj == v2->obj)) { std::cerr << "Found" << v1->obj << " where it should have been " << v2->obj << std::endl; flag = false; } } } return flag; } FORCE_INLINE void getSizeStats(std::ostream & fout) { fout << "{}"; } //SBJ: Only for data result loading . To be removed later FORCE_INLINE void add(T* obj, Transaction& xact) { Version<T>* v = aligned_malloc(Version<T>); new(v) Version<T>(*obj, xact); EntryMV<T>* e = aligned_malloc(EntryMV<T>); new(e) EntryMV<T>(nullptr, *obj, v); v->e = e; index.insert(obj, e); xact.undoBufferHead = v; } FORCE_INLINE OperationReturnStatus add(Version<T>* newv) override { auto idxId = IndexMV<T>::idxId; T* keyC = &newv->obj; EntryMV<T> *emv = (EntryMV<T>*) newv->e; if (index.insert(keyC, emv)) { if (idxId == 0) { EntryMV<T>* dh = dataHead; emv->nxt = dh; while (!dataHead.compare_exchange_weak(dh, emv)) { emv->nxt = dh; } } return OP_SUCCESS; } else { return WW_VALUE; } } //SBJ: what should a multiversion clear be? // void clear() override { // index.clear(); // if (dataHead) { // EntryMV<T>* tmp; // Version<T>* VH, *tmpV; // while (dataHead != nullptr) { // tmp = dataHead; // dataHead = dataHead->nxt; // VH = tmp->versionHead; // free(tmp); // while (VH != nullptr) { // tmpV = VH; // VH = VH->oldV; // free(tmpV); // } // } // } // } // size_t count() const override { // return -1; // } FORCE_INLINE void removeEntry(T* obj, EntryMV<T>* emv) override { EntryMV<T>* nxt = emv->nxt; while (!emv->nxt.compare_exchange_strong(nxt, mark(nxt))); //removing from foreach list //SBJ: TODO: Mark other fields as well??? index.erase(obj); //SBJ: TODO: free the memory for key store in cuckoo } FORCE_INLINE void undo(Version<T>* v) override { //Do nothign } FORCE_INLINE void del(Version<T>* v) override { //Do nothing for primary hash index } // void del(T* obj) override { // // if (idxId == 0) { // EntryMV< *elemPrv = obj->prv, *elemNxt = obj->nxt; // if (elemPrv) // elemPrv->nxt = elemNxt; // else // dataHead = elemNxt; // // if (elemNxt) elemNxt->prv = elemPrv; // // obj->nxt = nullptr; // obj->prv = nullptr; // } // // if (index.erase(obj)) { // count_--; // } else { // throw std::logic_error("Delete failed"); // } // } // void delCopy(const T* obj, Index<T, V>* primary) override { // T* orig = primary->get(obj); // del(orig); // } FORCE_INLINE OperationReturnStatus foreach(FuncType f, Transaction& xact) override { EntryMV<T>* cur = dataHead; ForEachPred<T>* pred = (ForEachPred<T>*) malloc(sizeof(ForEachPred<T>)); new(pred) ForEachPred<T>(xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; while (cur) { //SBJ: TODO check for tombstoned entries and delete them Version<T>* v = cur->getCorrectVersion(xact); auto st = f(&v->obj); if (st != SUCCESS) return OR(st); cur = cur->nxt; } return OP_SUCCESS; } // void foreachCopy(FuncType f) override { // std::vector<T*> entries; // T* cur = dataHead; // while (cur) { // entries.push_back(cur->copy()); // cur = cur->nxt; // } // for (auto it : entries) { // f(it); // free(it); //Not calling destructor // } // } FORCE_INLINE T* get(const T* key, Transaction& xact) const override { EntryMV<T>* result; if (index.find(key, result)) { Version<T>* v = result->getCorrectVersion(xact); if (v->obj.isInvalid) return nullptr; GetPred<T, IDX_FN>* pred = (GetPred<T, IDX_FN>*) malloc(sizeof(GetPred<T, IDX_FN>)); new(pred) GetPred<T, IDX_FN>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; return &v->obj; } else { return nullptr; } } FORCE_INLINE T* getForUpdate(const T* key, OperationReturnStatus& st, Transaction& xact) override { EntryMV<T>* result; if (index.find(key, result)) { Version<T>* resV = result->versionHead; if (!resV->isVisible(&xact)) { if (resV->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(resV->xactid); xact.failedBecauseOf = otherXact; } st = WW_VALUE; return nullptr; } if (resV->obj.isInvalid) { st = NO_KEY; return nullptr; } Version<T> *newv = aligned_malloc(Version<T>); new(newv) Version<T>(resV, xact); if (!result->versionHead.compare_exchange_strong(resV, newv)) { if (resV->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(resV->xactid); xact.failedBecauseOf = otherXact; } st = WW_VALUE; free(newv); return nullptr; } GetPred<T, IDX_FN>* pred = (GetPred<T, IDX_FN>*) malloc(sizeof(GetPred<T, IDX_FN>)); new(pred) GetPred<T, IDX_FN>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; xact.undoBufferHead = newv; st = OP_SUCCESS; return &newv->obj; } else { st = NO_KEY; return nullptr; } } FORCE_INLINE void prepareSize(size_t arrayS, size_t poolS) override { index.reserve(arrayS); } //Assumption : primary key columns don't change. So do nothing FORCE_INLINE OperationReturnStatus update(T* obj) { // Version<T>* v = (Version<T>*) VBase::getVersionFromT((char *) obj); // EntryMV<T>* emv = (EntryMV<T>*) v->e; // EntryMV<T>* res; // if (index.find(obj, res)) { // return res == emv ? OP_SUCCESS : DUPLICATE_KEY; // } else { // if (!index.insert(obj, emv)) // return DUPLICATE_KEY; // } return OP_SUCCESS; } virtual ~CuckooIndex() { } /******************* non-virtual function wrappers ************************/ FORCE_INLINE T* get(const T& key, Transaction& xact) const { return get(&key, xact); } FORCE_INLINE T* getForUpdate(const T& key, OperationReturnStatus& st, Transaction& xact) { return getForUpdate(&key, st, xact); } // FORCE_INLINE T* getCopy(const T* key) const { // T* obj = get(key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // // FORCE_INLINE T* getCopy(const T& key) const { // T* obj = get(&key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // // FORCE_INLINE T* getCopyDependent(const T* key) const { // T* obj = get(key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // // FORCE_INLINE T* getCopyDependent(const T& key) const { // T* obj = get(&key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // FORCE_INLINE void slice(const T& key, FuncType f) { // slice(&key, f); // } // FORCE_INLINE void sliceCopy(const T& key, FuncType f) { // sliceCopy(&key, f); // } // // FORCE_INLINE void sliceCopyDependent(const T* key, FuncType f) { // sliceCopy(key, f); // } // // FORCE_INLINE void sliceCopyDependent(const T& key, FuncType f) { // sliceCopy(&key, f); // } // // FORCE_INLINE void delCopyDependent(const T* obj) { // del(obj); // } }; template <typename T, typename IDX_FN, size_t size> struct ConcurrentArrayIndex : public IndexMV<T> { template<typename A> struct ALIGN CacheAtomic { std::atomic<A> elem; }; typedef CacheAtomic<EntryMV<T>*> AlignedEntry; AlignedEntry array[size]; bool operator==(const ConcurrentArrayIndex<T, IDX_FN, size>& that) { for (size_t i = 0; i < size; ++i) { EntryMV<T>* e1 = array[i].elem; EntryMV<T>* e2 = that.array[i].elem; if ((!e1 && e2) || (e1 && !e2)) { cerr << "Array slots don't match" << endl; if (e1) cerr << e1->versionHead.load()->obj << "is extra"; else cerr << e2->versionHead.load()->obj << "is missing"; return false; } if (!e1) continue; T& t1 = e1->versionHead.load()->obj; T& t2 = e2->versionHead.load()->obj; if (!(t1 == t2)) { cerr << "Found " << t1 << " where it should have been " << t2 << endl; return false; } } return true; } ConcurrentArrayIndex(size_t s) {//ignore memset(array, 0, sizeof(AlignedEntry) * size); } ConcurrentArrayIndex(void* ptr, size_t s) {//ignore memset(array, 0, sizeof(AlignedEntry) * size); } //Data Result loading FORCE_INLINE void add(T* obj, Transaction& xact) { Version<T>* v = aligned_malloc(Version<T>); new(v) Version<T>(*obj, xact); EntryMV<T>* e = aligned_malloc(EntryMV<T>); new(e) EntryMV<T>(nullptr, *obj, v); v->e = e; size_t idx = IDX_FN::hash(v->obj); array[idx].elem = e; xact.undoBufferHead = v; } FORCE_INLINE OperationReturnStatus add(Version<T>* v) override { size_t idx = IDX_FN::hash(v->obj); assert(idx >= 0 && idx < size); EntryMV<T>* emv = (EntryMV<T>*)v->e; EntryMV<T>* temp = nullptr; emv->backptrs[IndexMV<T>::idxId] = array + idx; if (array[idx].elem.compare_exchange_strong(temp, emv)) { return OP_SUCCESS; } else return WW_VALUE; } void removeEntry(T* obj, EntryMV<T>* emv) override { } void undo(Version<T>* v) override { } //Assumption: Primary key columns do not change. So, do nothing FORCE_INLINE OperationReturnStatus update(T* obj) { // Version<T>* v = (Version<T>*) VBase::getVersionFromT((char *) obj); // EntryMV<T>* emv = (EntryMV<T>*) v->e; // EntryMV<T>* res = nullptr; // size_t idx = IDX_FN::hash(*obj); // //SBJ: Backpointer?? // if (!array[idx].elem.compare_exchange_strong(res, emv)) { // return res == emv ? OP_SUCCESS : DUPLICATE_KEY; // } return OP_SUCCESS; } FORCE_INLINE void del(Version<T>* v) override { // size_t idx = IDX_FN::hash(*obj); EntryMV<T>* emv = (EntryMV<T>*)v->e; AlignedEntry* ca = (AlignedEntry*) emv->backptrs[IndexMV<T>::idxId]; auto idx = ca - array; assert(idx >= 0 && idx < size); ca->elem.compare_exchange_strong(emv, nullptr); } FORCE_INLINE OperationReturnStatus foreach(FuncType f, Transaction& xact) override { //Do nothing for now return OP_SUCCESS; } FORCE_INLINE T* get(const T* key, Transaction& xact) const override { return get(*key, xact); } FORCE_INLINE T* get(const T& key, Transaction& xact) const { size_t idx = IDX_FN::hash(key); assert(idx >= 0 && idx < size); EntryMV<T>* e = array[idx].elem.load(); if (!e) return nullptr; Version<T>* v = e->getCorrectVersion(xact); if (!v) return nullptr; else { GetPred<T, IDX_FN>* pred = (GetPred<T, IDX_FN>*) malloc(sizeof(GetPred<T, IDX_FN>)); new(pred) GetPred<T, IDX_FN>(key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; return &v->obj; } } T * getForUpdate(const T* key, OperationReturnStatus& s, Transaction & xact) override { return getForUpdate(*key, s, xact); } T * getForUpdate(const T& key, OperationReturnStatus& s, Transaction & xact) { size_t idx = IDX_FN::hash(key); assert(idx >= 0 && idx < size); EntryMV<T>* e = array[idx].elem; if (!e) { s = NO_KEY; return nullptr; } Version<T>* resV = e->versionHead; if (!resV->isVisible(&xact)) { if (resV->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(resV->xactid); xact.failedBecauseOf = otherXact; } s = WW_VALUE; return nullptr; } Version<T>* newv = aligned_malloc(Version<T>); new (newv) Version<T>(resV, xact); if (!e->versionHead.compare_exchange_strong(resV, newv)) { if (resV->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(resV->xactid); xact.failedBecauseOf = otherXact; } s = WW_VALUE; free(newv); return nullptr; } GetPred<T, IDX_FN>* pred = (GetPred<T, IDX_FN>*) malloc(sizeof(GetPred<T, IDX_FN>)); new(pred) GetPred<T, IDX_FN>(key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; xact.undoBufferHead = newv; s = OP_SUCCESS; return &newv->obj; return &resV->obj; } void prepareSize(size_t arrayS, size_t poolS) override { //do nothing } }; // //template <typename T> //struct TreeNode { // uint8_t height; // EntryMV<T>* emv; // TreeNode *parent, *left, *right; // // TreeNode(EntryMV<T>* e, TreeNode* p) : height(1), emv(e), parent(p), left(nullptr), right(nullptr) { // // } //}; //template<typename T, typename IDX_FN2> //struct _Tree { // typedef TreeNode<T> Node; // Node* root; // SpinLock lock; // // _Tree(EntryMV<T>* e) { // root = malloc(sizeof(Node)); // new (root) Node(e, nullptr); // } // FORCE_INLINE Node* getNext(Node* p) { // Node* cur = p->right; // if(cur) { // while(cur->left) // cur = cur->left; // return cur; // } // } // FORCE_INLINE int bfactor(Node *p) { // return height(p->right) - height(p->left); // } // // FORCE_INLINE uint8_t height(Node *p) { // return p ? p->height : 0; // } // // FORCE_INLINE void fixHeight(Node *p) { // uint8_t hl = height(p->left); // uint8_t hr = height(p->right); // p->height = (hl > hr ? hl : hr) + 1; // // } // // FORCE_INLINE Node* rotateRight(Node* p) { // Node* q = p->left; // p->left = q->right; // q->right = p; // // q->parent = p->parent; // p->parent = q; // if (p->left) // p->left->parent = p; // fixHeight(p); // fixHeight(q); // return q; // } // // FORCE_INLINE Node* rotateLeft(Node *p) { // Node* q = p->right; // p->right = q->left; // q->left = p; // // q->parent = p->parent; // p->parent = q; // if (p->right) // p->right->parent = p; // fixHeight(p); // fixHeight(q); // return q; // } // // FORCE_INLINE Node* balance(Node *p) { // fixHeight(p); // if (bfactor(p) == 2) { // if (bfactor(p->right) < 0) // p->right = rotateRight(p->right); // return rotateLeft(p); // } // if (bfactor(p) == -2) { // if (bfactor(p->left) > 0) // p->left = rotateLeft(p->left); // return rotateRight(p); // } // return p; // } // // FORCE_INLINE insert_BST(T* obj, EntryMV<T>* emv) { // Node* cur = root; // while (cur != nullptr) { // T& curObj = cur ->emv->versionHead.load()->obj; // //assumes that slice columns as well as the ord column are same across all versions of Entry // if (IDX_FN2::cmp(*obj, curObj) < 0) { // if (cur->left == nullptr) { // Node* newnode = (Node*) malloc(sizeof(Node)); // new(newnode) Node(emv, cur); // cur->left = newnode; // // Node* par; // while (true) { // par = cur->parent; // if (par) { // if (par->right == cur) { // cur = balance(cur); // par->right = cur; // } else { // cur = balance(cur); // par->left = cur; // } // } else { // root = balance(root); // return; // } // cur = par; // } // } // cur = cur->left; // } else { // if (cur->right == nullptr) { // Node* newnode = (Node*) malloc(sizeof(Node)); // new(newnode) Node(emv, cur); // cur->right = newnode; // // Node* par; // while (true) { // par = cur->parent; // if (par) { // if (par->right == cur) { // cur = balance(cur); // par->right = cur; // } else { // cur = balance(cur); // par->left = cur; // } // } else { // root = balance(root); // return; // } // cur = par; // } // } // cur = cur->right; // } // // } // } // // FORCE_INLINE void removeBST(T* obj, EntryMV* emv) { // Node* cur = root; // while (cur != nullptr) { // if (cur->emv == emv) { // found it // Node* temp; // if (cur->left && cur->right) { // 2 children case // temp = cur; // cur = cur->left; // while (cur->right) { // cur = cur->right; // } // temp-> emv = cur->emv; // } // // now cur has 0 or 1 child // temp = (cur->left ? cur->left : cur->right); // Node* par = cur->parent; // if (!par) // root = temp; // else if (cur == par->right) // par->right = temp; // else // par->left = temp; // // if (temp) // temp->parent = par; // free(cur); // // if (par) { // cur = par; // while (true) { // par = cur->parent; // if (par) { // if (par->right == cur) { // cur = balance(cur); // par->right = cur; // } else { // cur = balance(cur); // par->left = cur; // } // } else { // root = balance(cur); // return; // } // cur = par; // } // } // return; // } // T& curObj = cur->emv->versionHead.load()->obj; // if (IDX_FN2::cmp(*obj, curObj) < 0) // cur = cur->left; // else // cur = cur->right; // } // } //}; // //template<typename T, typename IDX_FN1, typename IDX_FN2> //struct CuckooTreeIndex : public IndexMV<T> { // typedef _Tree<T, IDX_FN2> Tree; // struct HE { // size_t operator()(const T* e) const { // size_t h = IDX_FN1::hash(*e); // return h; // } // bool operator()(const T* e1, const T* e2) const { // return IDX_FN1::cmp(*e1, *e2) == 0; // } // }; // cuckoohash_map<T*, Tree*, HE, HE, std::allocator<std::pair<T*, Tree*>>> index; // // CuckooTreeIndex(size_t s) : index(1 << 23) { // } // // OperationReturnStatus add(T* key, EntryMV<T>* obj) override { // Tree* newtr = (Tree*) malloc(sizeof(Tree)); // new Tree(obj); // T* keyc = key->copy(); // auto updatefn = [newtr, keyc](Tree* &oldtr) { // free(newtr); // free(keyc); // oldtr->lock.lock(); // oldtr->insert_BST(key, obj); // oldtr->lock.unlock(); // }; // return OP_SUCCESS; // } // // void del(T* obj, EntryMV<T>* emv) override { // Tree* tr; // if (index.find(obj, tr)) { // tr->lock.lock(); // tr->removeBST(obj, emv); // tr->lock.unlock(); // } // } // // OperationReturnStatus foreach(const std::function<TransactionReturnStatus()(T*)>& f, Transaction& xact) override { // return OP_SUCCESS; // } // // void prepareSize(size_t arrayS, size_t poolS) override { // } //}; // //template <typename T, typename IDX_FN1, typename IDX_FN2> //struct CuckooMinTreeIndex : public CuckooTreeIndex<T, IDX_FN1, IDX_FN2> { // typedef CuckooTreeIndex<T, IDX_FN1, IDX_FN2> Super; // typedef _Tree<T, IDX_FN2> Tree; // typedef TreeNode<T> Node; // CuckooMinTreeIndex(size_t s ): Super(s){ // // } // T* get(const T* key, Transaction& xact) const override { // Tree* tree; // if (index.find(key, tree)) { // tree->lock.lock(); // Node* cur = tree->root; // // tree->lock.unlock(); // } else // return NO_KEY; // // } //}; template <typename T, typename IDX_FN2, bool is_max> struct Heap { EntryMV<T>** array; uint arraySize; uint size; typedef EntryMV<T>* HeapElemType; Heap() { arraySize = DEFAULT_HEAP_SIZE; array = new EntryMV<T>*[arraySize]; size = 0; } // // void print() { // for (uint i = 1; i <= size; ++i) { // if ((i & (i - 1)) == 0) // std::cout << std::endl; // std::cout << array[i]->getString(4) << "\t"; // } // std::cout << std::endl; // } FORCE_INLINE EntryMV<T>* get() const { return array[1]; } FORCE_INLINE bool checkIfExists(EntryMV<T>* emv) { for (uint i = 1; i <= size; ++i) { if (array[i] == emv) return true; } return false; } FORCE_INLINE void checkHeap(int idx) { for (uint i = 1; i <= size; ++i) { uint l = 2 * i; uint r = l + 1; EntryMV<T>* x = array[i]; if (is_max) { if (l <= size) { assert(IDX_FN2::cmp(x->key, array[l]->key) == 1); if (r <= size) assert(IDX_FN2::cmp(x->key, array[r]->key) == 1); } } else { if (l <= size) { assert(IDX_FN2::cmp(x->key, array[l]->key) == -1); if (r <= size) assert(IDX_FN2::cmp(x->key, array[r]->key) == -1); } } // assert(x->backPtrs[idx] == n); } } FORCE_INLINE void double_() { uint newsize = arraySize << 1; EntryMV<T>** temp = new EntryMV<T>*[newsize]; mempcpy(temp, array, arraySize * sizeof(EntryMV<T>*)); arraySize = newsize; delete[] array; array = temp; assert(array); } FORCE_INLINE void percolateDown(uint holeInput) { uint hole = holeInput; uint child = hole << 1; EntryMV<T>* tmp = array[hole]; while (child <= size) { if (child != size && IDX_FN2::cmp(array[child + 1]->key, array[child]->key) == (is_max ? 1 : -1)) child++; if (IDX_FN2::cmp(array[child]->key, tmp->key) == (is_max ? 1 : -1)) array[hole] = array[child]; else { array[hole] = tmp; return; } hole = child; child = hole << 1; } array[hole] = tmp; } FORCE_INLINE void add(EntryMV<T>* e) { if (size == arraySize - 1) double_(); size++; uint hole = size; uint h = size >> 1; while (hole > 1 && IDX_FN2::cmp(e->key, array[h]->key) == (is_max ? 1 : -1)) { array[hole] = array[h]; hole = h; h = hole >> 1; } array[hole] = e; } //SBJ: Should only be called for a newer value that would be closer to root //In a max heap, the newer value must be greater //In a min heap, the newer value must be smaller //TOFIX: Not considering equal values FORCE_INLINE void update(EntryMV<T>* old, EntryMV<T>* nw) { assert(IDX_FN2::cmp(nw->key, old->key) == (is_max ? 1 : -1)); uint p = 1; if (array[p] != old) { p++; while (p <= size) { if (array[p] == old) break; p++; } // if (p == size + 1) // throw std::logic_error("Element not found in heap"); } uint hole = p; uint h = p >> 1; while (hole > 1 && IDX_FN2::cmp(nw->key, array[h]->key) == (is_max ? 1 : -1)) { array[hole] = array[h]; hole = h; h = hole >> 1; } array[hole] = nw; } FORCE_INLINE void remove(EntryMV<T>* e) { uint p = 1; if (array[p] != e) { p++; while (p <= size) { if (array[p] == e) break; p++; } // if (p == size + 1) // throw std::logic_error("Element not found in heap"); } while (p != 1) { uint h = p >> 1; array[p] = array[h]; p = h; } array[p] = array[size]; array[size] = nullptr; size--; if (p < size) percolateDown(p); } }; template <typename T, typename IDX_FN2> struct MedianHeap { Heap<T, IDX_FN2, true> left; Heap<T, IDX_FN2, false> right; //invariant : l.size = r.size OR l.size = r.size + 1 FORCE_INLINE void add(EntryMV<T>* obj) { if (left.size == 0) { left.add(obj); return; } assert(left.size > 0); if (IDX_FN2::cmp(obj->key, left.array[1]->key) == 1) { //obj greater than median if (right.size == left.size) { // right side will be unbalanced on adding if (IDX_FN2::cmp(obj->key, right.array[1]->key) == 1) { //obj greater than min of right EntryMV<T>* obj2 = right.array[1]; //add obj to right. move min of right to left right.array[1] = obj; right.percolateDown(1); left.add(obj2); } else { //object is new median left.add(obj); } } else { right.add(obj); } } else { //obj same or less as median if (left.size > right.size) { //left will be unbalanced on adding EntryMV<T>* obj2 = left.array[1]; left.array[1] = obj; left.percolateDown(1); right.add(obj2); } else { left.add(obj); } } } //SBJ: May not find the right element if it is median and there are duplicates of it spread across left and right FORCE_INLINE bool checkIfExists(EntryMV<T>* emv) { return left.checkIfExists(emv) || right.checkIfExists(emv); } FORCE_INLINE void remove(EntryMV<T> *obj) { if (IDX_FN2::cmp(obj->key, left.array[1]->key) == 1) { //obj in right if (left.size > right.size) { EntryMV<T> * obj2 = left.array[1]; left.remove(obj2); right.update(obj, obj2); //we are decreasing value in min-heap, safe to call update } else { right.remove(obj); } } else { //obj in left if (left.size == right.size) { EntryMV<T>* obj2 = right.array[1]; right.remove(obj2); left.update(obj, obj2); //increasing value in max-heap } else { left.remove(obj); } } } FORCE_INLINE EntryMV<T>* get() const { return left.array[1]; } FORCE_INLINE void check(int idx) { left.checkHeap(idx); right.checkHeap(idx); EntryMV<T>* r = right.array[1]; EntryMV<T>* l = left.array[1]; assert(left.size == 0 || right.size == 0 || IDX_FN2::cmp(l->key, r->key) == -1); //can be 0 too, but we want to know if there is such a case assert(left.size == right.size || left.size == right.size + 1); } }; template<typename T, typename IDX_FN1, typename IDX_FN2, typename ST_IDX> struct VersionedAggregator : public IndexMV<T> { typedef HE_<T, IDX_FN1> HE; typedef ST_IDX typeST; typedef EntryMV<T>* EntryType; struct ALIGN VersionedContainer { EntryMV<T>* aggE; Transaction* xact; volatile VersionedContainer* next; VersionedContainer(EntryMV<T>*e, Transaction* xact, volatile VersionedContainer* n) : aggE(e), xact(xact), next(n) { } }; struct ALIGN VersionedSlice { SpinLock lock; volatile VersionedContainer* head; ST_IDX sliceST; VersionedSlice() : lock(), head(nullptr), sliceST() { } FORCE_INLINE OperationReturnStatus add(Version<T>* newv) { EntryMV<T>* e = (EntryMV<T>*)newv->e; lock.lock(); sliceST.add(e); EntryMV<T>* aggE = sliceST.get(); if (head && head->xact != TStoPTR(newv->xactid) && head->xact->commitTS == initCommitTS) { lock.unlock(); return WW_VALUE; } /* This is not correct for median index. For example, if there was ab(c) de * ab(c) xde * aby(c) xde and now if we undo x, we should have ab(y) cde. However, this would still return c * Each modification should create a version in median index */ if (!head || head->aggE != aggE) { if (!head || head->xact != TStoPTR(newv->xactid)) { VersionedContainer* vc = aligned_malloc(VersionedContainer); new(vc) VersionedContainer(aggE, TStoPTR(newv->xactid), head); head = vc; } else { head->aggE = aggE; } } lock.unlock(); return OP_SUCCESS; } FORCE_INLINE OperationReturnStatus del(Version<T>* v) { EntryMV<T>* e = (EntryMV<T>*) v->e; lock.lock(); sliceST.remove(e); EntryMV<T>* aggE = sliceST.get(); if (head->xact != TStoPTR(v->xactid) && head->xact->commitTS == initCommitTS) { lock.unlock(); return WW_VALUE; } if (head->aggE != aggE) { if (head->xact != TStoPTR(v->xactid)) { VersionedContainer* vc = aligned_malloc(VersionedContainer); new(vc) VersionedContainer(aggE, TStoPTR(v->xactid), head); head = vc; } else { head->aggE = aggE; } } lock.unlock(); return OP_SUCCESS; } FORCE_INLINE void undo(Version<T>* v) { EntryMV<T>*e = (EntryMV<T>*)v->e; lock.lock(); if (v->obj.isInvalid) { //deleted version, to undo it, need to re-insert entry into index sliceST.add(e); } else if (v->oldV == nullptr) { //only version, inserted. Need to remove to undo sliceST.remove(e); } else { //assuming that normal updates are only to non-key fields, no impact here lock.unlock(); return; } // EntryMV<T>* e_new = sliceST.get(); //to be removed in final version if (head->xact == TStoPTR(v->xactid)) { head = head->next; } // assert(e_new == (head ? head->aggE : nullptr)); lock.unlock(); } FORCE_INLINE void removeEntry(EntryMV<T>* e) { //Do nothing? } FORCE_INLINE OperationReturnStatus update(Version<T>* v) { EntryMV<T>* emv = (EntryMV<T>*) v->e; lock.lock(); if (sliceST.checkIfExists(emv)) { lock.unlock(); return OP_SUCCESS; } else { return add(v); } } FORCE_INLINE EntryMV<T>* get(Transaction & xact) { volatile VersionedContainer* cur = head; while (cur && cur->xact->commitTS > xact.startTS) { cur = cur->next; } return cur ? cur->aggE : nullptr; } }; cuckoohash_map<T*, VersionedSlice*, HE, HE, std::allocator<std::pair<T*, VersionedSlice*>>> index; VersionedAggregator(size_t s) : index(1 << 23) { } FORCE_INLINE OperationReturnStatus add(Version<T>* newv) override { VersionedSlice * vsnew = aligned_malloc(VersionedSlice); new (vsnew) VersionedSlice(); VersionedContainer* vc = aligned_malloc(VersionedContainer); EntryMV<T>* e = (EntryMV<T>*)newv->e; new(vc) VersionedContainer(e, TStoPTR(newv->xactid), nullptr); e->backptrs[IndexMV<T>::idxId] = vsnew; vsnew->head = vc; vsnew->sliceST.add(e); T* keyc = newv->obj.copy(); index.upsert(keyc, [&](VersionedSlice * vsold) { free(keyc); free(vsnew); free(vc); e->backptrs[IndexMV<T>::idxId] = vsold; vsold->add(newv); }, vsnew); return OP_SUCCESS; } FORCE_INLINE void del(Version<T>* newv) override { EntryMV<T>* emv = (EntryMV<T>*) newv->e; VersionedSlice* vs = (VersionedSlice*) emv->backptrs[IndexMV<T>::idxId]; vs->del(newv); } FORCE_INLINE void removeEntry(T* obj, EntryMV<T>* emv) override { VersionedSlice* vs = (VersionedSlice*) emv->backptrs[IndexMV<T>::idxId]; vs->removeEntry(emv); } FORCE_INLINE void undo(Version<T>* v) override { EntryMV<T>* emv = (EntryMV<T>*) v->e; VersionedSlice* vs = (VersionedSlice*) emv->backptrs[IndexMV<T>::idxId]; vs->undo(v); } OperationReturnStatus foreach(FuncType f, Transaction& xact) override { return OP_SUCCESS; } FORCE_INLINE T* get_(const T* key, Transaction& xact) const { VersionedSlice * vs; if (index.find(key, vs)) { EntryMV<T>* e = vs->get(xact); Version<T>* v = e->getCorrectVersion(xact); if (!v) return nullptr; return &v->obj; } else { return nullptr; } } FORCE_INLINE T* getForUpdate_(const T* key, OperationReturnStatus& st, Transaction& xact) { VersionedSlice* result; if (index.find(key, result)) { EntryMV<T>* resE = result->get(xact); if (!resE) { st = NO_KEY; return nullptr; } Version<T>* resV = resE->versionHead; if (!resV->isVisible(&xact)) { if (resV->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(resV->xactid); xact.failedBecauseOf = otherXact; } st = WW_VALUE; return nullptr; } if (resV->obj.isInvalid) { st = NO_KEY; return nullptr; } Version<T> *newv = aligned_malloc(Version<T>); new(newv) Version<T>(resV, xact); if (!resE->versionHead.compare_exchange_strong(resV, newv)) { if (resV->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(resV->xactid); xact.failedBecauseOf = otherXact; } st = WW_VALUE; free(newv); return nullptr; } xact.undoBufferHead = newv; st = OP_SUCCESS; return &newv->obj; } else { st = NO_KEY; return nullptr; } } FORCE_INLINE OperationReturnStatus update(T* obj) { VersionedSlice* res; Version<T>* v = (Version<T>*)VBase::getVersionFromT((char*) obj); OperationReturnStatus ret; if (index.find(obj, res)) { ret = res->update(v); } else { ret = add(v); } assert(ret == OP_SUCCESS); return ret; } void prepareSize(size_t arrayS, size_t poolS) override { } virtual ~VersionedAggregator() { } }; template<typename T, typename IDX_FN1, typename IDX_FN2> struct MinHeapIndex : public VersionedAggregator<T, IDX_FN1, IDX_FN2, Heap<T, IDX_FN2, false >> { typedef VersionedAggregator<T, IDX_FN1, IDX_FN2, Heap<T, IDX_FN2, false >> Super; MinHeapIndex(size_t s) : Super(s) { } FORCE_INLINE T * get(const T& key, Transaction & xact) const { return get(&key, xact); } FORCE_INLINE T * get(const T* key, Transaction & xact) const override { T* ret = Super::get_(key, xact); if (ret) { // assert(ret->_4.data_); MinSlicePred<T, IDX_FN1, IDX_FN2>* pred = (MinSlicePred<T, IDX_FN1, IDX_FN2>*) malloc(sizeof(MinSlicePred<T, IDX_FN1, IDX_FN2>)); new(pred) MinSlicePred<T, IDX_FN1, IDX_FN2>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); pred->key = *ret; xact.predicateHead = pred; } return ret; } FORCE_INLINE T * getForUpdate(const T& key, OperationReturnStatus& s, Transaction & xact) { return getForUpdate(&key, s, xact); } FORCE_INLINE T * getForUpdate(const T* key, OperationReturnStatus& s, Transaction & xact) { T* ret = Super::getForUpdate_(key, s, xact); if (ret) { // assert(ret->_4.data_); MinSlicePred<T, IDX_FN1, IDX_FN2>* pred = (MinSlicePred<T, IDX_FN1, IDX_FN2>*) malloc(sizeof(MinSlicePred<T, IDX_FN1, IDX_FN2>)); new(pred) MinSlicePred<T, IDX_FN1, IDX_FN2>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); pred->key = *ret; xact.predicateHead = pred; } return ret; } }; template<typename T, typename IDX_FN1, typename IDX_FN2> struct MaxHeapIndex : public VersionedAggregator<T, IDX_FN1, IDX_FN2, Heap<T, IDX_FN2, true >> { typedef VersionedAggregator<T, IDX_FN1, IDX_FN2, Heap<T, IDX_FN2, true >> Super; MaxHeapIndex(size_t s) : Super(s) { } FORCE_INLINE T * get(const T& key, Transaction & xact) const { return get(&key, xact); } FORCE_INLINE T * get(const T* key, Transaction & xact) const override { T* ret = Super::get_(key, xact); if (ret) { MaxSlicePred<T, IDX_FN1, IDX_FN2>* pred = (MaxSlicePred<T, IDX_FN1, IDX_FN2>*) malloc(sizeof(MaxSlicePred<T, IDX_FN1, IDX_FN2>)); new(pred) MaxSlicePred<T, IDX_FN1, IDX_FN2>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); pred->key = *ret; xact.predicateHead = pred; } return ret; } FORCE_INLINE T * getForUpdate(const T& key, OperationReturnStatus& s, Transaction & xact) { return getForUpdate(&key, s, xact); } FORCE_INLINE T * getForUpdate(const T* key, OperationReturnStatus& s, Transaction & xact) { T* ret = Super::getForUpdate_(key, s, xact); if (ret) { MaxSlicePred<T, IDX_FN1, IDX_FN2>* pred = (MaxSlicePred<T, IDX_FN1, IDX_FN2>*) malloc(sizeof(MaxSlicePred<T, IDX_FN1, IDX_FN2>)); new(pred) MaxSlicePred<T, IDX_FN1, IDX_FN2>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); pred->key = *ret; xact.predicateHead = pred; } return ret; } }; template<typename T, typename IDX_FN1, typename IDX_FN2> struct MedHeapIndex : public VersionedAggregator<T, IDX_FN1, IDX_FN2, MedianHeap<T, IDX_FN2>> { typedef VersionedAggregator<T, IDX_FN1, IDX_FN2, MedianHeap<T, IDX_FN2>> Super; MedHeapIndex(size_t s) : Super(s) { } FORCE_INLINE T * get(const T& key, Transaction & xact) const { return get(&key, xact); } FORCE_INLINE T * get(const T* key, Transaction & xact) const override { T* ret = Super::get_(key, xact); if (ret) { SlicePred<T, IDX_FN1>* pred = (SlicePred<T, IDX_FN1>*) malloc(sizeof(SlicePred<T, IDX_FN1>)); new(pred) SlicePred<T, IDX_FN1>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; } return ret; } FORCE_INLINE T * getForUpdate(const T* key, OperationReturnStatus& s, Transaction & xact) { T* ret = Super::getForUpdate_(key, s, xact); if (ret) { SlicePred<T, IDX_FN1>* pred = (SlicePred<T, IDX_FN1>*) malloc(sizeof(SlicePred<T, IDX_FN1>)); new(pred) SlicePred<T, IDX_FN1>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; } return ret; } FORCE_INLINE T * getForUpdate(const T& key, OperationReturnStatus& s, Transaction & xact) { return getForUpdate(&key, s, xact); } }; template<typename T, typename IDX_FN> struct ConcurrentCuckooSecondaryIndex : public IndexMV<T> { typedef HE_<T, IDX_FN> HE; struct ALIGN Container { EntryMV<T>* e; std::atomic<Container *> next; Container(EntryMV<T>* e) : e(e), next(nullptr) { } Container(Container *nxt) : e(nullptr), next(nxt) { } }; cuckoohash_map<T*, Container*, HE, HE, std::allocator<std::pair<T*, Container*>>> index; ConcurrentCuckooSecondaryIndex(size_t size = 100000) : index((1 << 25)) { } // Inserts an entry into the secondary index. //Uses cuckoo hashmap as backend //Inserts the entry if it does not exist already in cuckoo index, otherwise if it exists,updates it //Cuckoo points towards a sentinel to protect against concurrent insertions/deletions FORCE_INLINE OperationReturnStatus add(Version<T>* newv) override { Container *newc = aligned_malloc(Container); EntryMV<T>* obj = (EntryMV<T>*)newv->e; new(newc) Container(obj); obj->backptrs[IndexMV<T>::idxId] = newc; Container *sentinel = aligned_malloc(Container); new(sentinel) Container(newc); T* keyc = newv->obj.copy(); auto updatefn = [newc, sentinel, keyc](Container* &c) { free(sentinel); free(keyc); Container *nxt = c->next; do { newc->next = nxt; } while (!c->next.compare_exchange_weak(nxt, newc)); }; index.upsert(keyc, updatefn, sentinel); return OP_SUCCESS; //SBJ: Mem leak if update happens instead of insert for key->copy } //Marks an entry for removal from concurrent list //Will be actually removed only by a later traversal //Removes other nodes marked for removal during its traversal // Loop focus on cur. prev is before cur, curNext is afterCur. prevNext is node after prev (ideally, cur) // ..... prev -> prevNext (....) cur -> curNext ... // a node is said to be marked for removal if its next pointer is marked. //For example, to see if cur is deleted, we check isMarked(curNext) FORCE_INLINE void removeEntry(T* obj, EntryMV<T>* emv) override { Container *cur = (Container*) emv->backptrs[IndexMV<T>::idxId]; Container* nxt = cur->next; while (!cur->next.compare_exchange_weak(nxt, mark(nxt))); } //Assumption: Primary key columns do not change FORCE_INLINE OperationReturnStatus update(T* obj) { Version<T>* v = (Version<T>*) VBase::getVersionFromT((char *) obj); EntryMV<T>* emv = (EntryMV<T>*) v->e; Container* sentinel; if (index.find(obj, sentinel)) { //slice already exists, need to check if entry is already there Container *cur = sentinel->next, *curNext = cur->next, *old = sentinel, *oldNext = cur; while (isMarked(curNext) || cur->e != emv) { if (!isMarked(curNext)) { if (oldNext != cur) { old->next.compare_exchange_strong(oldNext, cur); } old = cur; cur = curNext; oldNext = curNext; } else { cur = unmark(curNext); } if (!cur) break; curNext = cur->next; } if (!cur) { //emv does not exist in slice Container *newc = aligned_malloc(Container); new(newc) Container(emv); Container *nxt = sentinel->next; do { newc->next = nxt; } while (!sentinel->next.compare_exchange_weak(nxt, newc)); } return OP_SUCCESS; } else { //new slice return add(v); } } void undo(Version<T>* v) override { //Do nothing } FORCE_INLINE void del(Version<T>* v) override { //Do nothing for secondary hash index } FORCE_INLINE OperationReturnStatus slice(const T& key, FuncType f, Transaction& xact) { return slice(&key, f, xact); } FORCE_INLINE OperationReturnStatus slice(const T* key, FuncType f, Transaction& xact) { Container *sentinel; if (index.find(key, sentinel)) { Container *prev = sentinel, *prevNext = sentinel->next, *cur = prevNext, *curNext; //SBJ: TODO: Skip all deleted nodes and remove them do { curNext = cur -> next; while (isMarked(curNext)) { cur = unmark(curNext); if (!cur) break; curNext = cur->next; } if (!cur) break; prev->next.compare_exchange_strong(prevNext, cur); Version<T>* v = cur->e->versionHead; if (!v->isVisible(&xact)) { if (v->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(v->xactid); xact.failedBecauseOf = otherXact; } return WW_VALUE; } if (v && !v->obj.isInvalid) { Version<T> * newV = aligned_malloc(Version<T>); new(newV) Version<T>(v, xact); if (!cur->e->versionHead.compare_exchange_strong(v, newV)) { if (v->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(v->xactid); xact.failedBecauseOf = otherXact; } free(newV); return WW_VALUE; } xact.undoBufferHead = newV; auto st = f(&newV->obj); if (st != SUCCESS) return OR(st); } prev = cur; prevNext = curNext; cur = curNext; } while (cur); SlicePred<T, IDX_FN>* pred = (SlicePred<T, IDX_FN>*) malloc(sizeof(SlicePred<T, IDX_FN>)); new(pred) SlicePred<T, IDX_FN>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; return OP_SUCCESS; } else { return NO_KEY; } } FORCE_INLINE OperationReturnStatus sliceNoUpdate(const T& key, FuncType f, Transaction& xact) { return sliceNoUpdate(&key, f, xact); } FORCE_INLINE OperationReturnStatus sliceNoUpdate(const T* key, FuncType f, Transaction& xact) { Container *sentinel; if (index.find(key, sentinel)) { Container *prev = sentinel, *prevNext = sentinel->next, *cur = prevNext, *curNext; //SBJ: TODO: Skip all deleted nodes and remove them do { curNext = cur -> next; while (isMarked(curNext)) { cur = unmark(curNext); if (!cur) break; curNext = cur->next; } prev->next.compare_exchange_strong(prevNext, cur); if (!cur) break; Version<T>* v = cur->e->getCorrectVersion(xact); if (v && !v->obj.isInvalid) { auto st = f(&v->obj); if (st != SUCCESS) return OR(st); } prev = cur; prevNext = curNext; cur = curNext; } while (cur); SlicePred<T, IDX_FN>* pred = (SlicePred<T, IDX_FN>*) malloc(sizeof(SlicePred<T, IDX_FN>)); new(pred) SlicePred<T, IDX_FN>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; return OP_SUCCESS; } else { return NO_KEY; } } OperationReturnStatus foreach(FuncType f, Transaction& xact) override { return NO_KEY; } T* get(const T* key, Transaction& xact) const override { return nullptr; } T* getForUpdate(const T* key, OperationReturnStatus& st, Transaction& xact) override { st = NO_KEY; return nullptr; } void prepareSize(size_t arrayS, size_t poolS) override { index.reserve(arrayS); } virtual ~ConcurrentCuckooSecondaryIndex() { } void getSizeStats(std::ostream & fout) { fout << "{}"; } /******************* non-virtual function wrappers ************************/ FORCE_INLINE T* get(const T& key, Transaction& xact) const { return get(&key, xact); } }; struct MBase { virtual void removeEntry(void* o, void* emv) = 0; virtual void undo(VBase* v) = 0; }; template<typename T, typename...INDEXES> class MultiHashMapMV : MBase { private: bool *modified; public: IndexMV<T>** index; MultiHashMapMV() { // by defintion index 0 is always unique if (sizeof...(INDEXES) > MAX_IDXES_PER_TBL) { cerr << "The maximum indexes per table is configured to be " << MAX_IDXES_PER_TBL << " which is less than the required indexes" << endl; } index = new IndexMV<T>*[sizeof...(INDEXES)] { new INDEXES(DEFAULT_CHUNK_SIZE)... }; modified = new bool[sizeof...(INDEXES)]; for (size_t i = 0; i<sizeof...(INDEXES); ++i) { index[i]->mmapmv = this; index[i]->idxId = i; modified[i] = false; } } MultiHashMapMV(const size_t* arrayLengths, const size_t* poolSizes) { // by defintion index 0 is always unique if (sizeof...(INDEXES) > MAX_IDXES_PER_TBL) { cerr << "The maximum indexes per table is configured to be " << MAX_IDXES_PER_TBL << " which is less than the required indexes" << endl; } index = new IndexMV<T>*[sizeof...(INDEXES)] { new INDEXES()... }; modified = new bool[sizeof...(INDEXES)]; for (size_t i = 0; i<sizeof...(INDEXES); ++i) { index[i]->mmapmv = this; index[i]->prepareSize(arrayLengths[i], poolSizes[i + 1]); index[i]->idxId = i; modified[i] = false; } } ~MultiHashMapMV() { for (size_t i = 0; i<sizeof...(INDEXES); ++i) delete index[i]; delete[] index; delete[] modified; } FORCE_INLINE T* get(const T& key, const size_t idx, Transaction& xact) const { return index[idx]->get(&key, xact); } FORCE_INLINE T* get(const T* key, const size_t idx, Transaction& xact) const { return index[idx]->get(key, xact); } // FORCE_INLINE T* getCopy(const T& key, const size_t idx = 0) const { // T* obj = index[idx]->get(&key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // FORCE_INLINE T* getCopy(const T* key, const size_t idx = 0) const { // T* obj = index[idx]->get(key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // FORCE_INLINE T* getCopyDependent(const T* key, const size_t idx = 0) const { // T* obj = index[idx]->get(key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // // FORCE_INLINE T* getCopyDependent(const T& key, const size_t idx = 0) const { // T* obj = index[idx]->get(&key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // FORCE_INLINE T* copyIntoPool(const T* e) { // T* copy = (T*) malloc(sizeof(T)); // new(copy) T(*e); // return copy; // } // // FORCE_INLINE T* copyIntoPool(const T& e) { // T* copy = (T*) malloc(sizeof(T)); // new(copy) T(e); // return copy; // } FORCE_INLINE OperationReturnStatus add(T& obj, Transaction& xact) { return add(&obj, xact); } FORCE_INLINE OperationReturnStatus add(T* elem, Transaction& xact) { T* cur = index[0]->get(elem); if (cur == nullptr) { Version<T>* newV = aligned_malloc(Version<T>); new(newV) Version<T>(*cur, xact); newV->xactid = PTRtoTS(xact); EntryMV<T> * newE = aligned_malloc(EntryMV<T>); new(newE) EntryMV<T>(this, *elem, newV); newV->e = newE; auto primarySt = index[0] -> add(newV); if (primarySt == OP_SUCCESS) { for (size_t i = 1; i<sizeof...(INDEXES); ++i) index[i]->add(newV); return OP_SUCCESS; } else { free(newE); free(newV); return WW_VALUE; } xact.undoBufferHead = newV; } else { return WW_VALUE; // cur->~T(); // *cur=std::move(*elem); // for (size_t i = 0; i<sizeof...(INDEXES); ++i) { // if (index[i]->hashDiffers(*cur, *elem)) { // index[i]->del(cur); // modified[i] = true; // } // } // new(cur) T(*elem); // for (size_t i = 0; i<sizeof...(INDEXES); ++i) { // if (modified[i]) { // index[i]->add(cur); // modified[i] = false; // } // } } } FORCE_INLINE OperationReturnStatus insert_nocheck(const T& elem, Transaction& xact) { return insert_nocheck(&elem, xact); } FORCE_INLINE OperationReturnStatus insert_nocheck(const T* elem, Transaction& xact) { Version<T>* newV = aligned_malloc(Version<T>); new(newV) Version<T>(*elem, xact); EntryMV<T>* newE = aligned_malloc(EntryMV<T>); new(newE) EntryMV<T>(this, *elem, newV); newV->e = newE; // newV->obj.e = newE; auto primarySt = index[0] -> add(newV); if (primarySt == OP_SUCCESS) { xact.undoBufferHead = newV; for (size_t i = 1; i<sizeof...(INDEXES); ++i) index[i]->add(newV); return OP_SUCCESS; } else { free(newE); free(newV); return WW_VALUE; } } FORCE_INLINE void removeEntry(void* o, void* e) override { T* obj = (T*) o; EntryMV<T>* emv = (EntryMV<T>*) e; for (uint i = 0; i < sizeof...(INDEXES); ++i) index[i]->removeEntry(obj, emv); } FORCE_INLINE void undo(VBase *v) override { for (uint i = 0; i < sizeof...(INDEXES); ++i) index[i]->undo((Version<T>*)v); } FORCE_INLINE void del(T* elem) { elem->isInvalid = true; Version<T>* v = (Version<T>*)VBase::getVersionFromT((char*) elem); for (uint i = 0; i < sizeof...(INDEXES); ++i) index[i]->del(v); } // FORCE_INLINE void del(T* elem) { // assume that the element is already in the map // for (size_t i = 0; i<sizeof...(INDEXES); ++i) index[i]->del(elem); // pool.del(elem); // } // // FORCE_INLINE void delCopyDependent(T* obj) { // T* elem = index[0]->get(obj); // for (size_t i = 0; i<sizeof...(INDEXES); ++i) index[i]->del(elem); // pool.del(elem); // } // // FORCE_INLINE void delCopy(T* obj) { // T* elem = index[0]->get(obj); // for (size_t i = sizeof...(INDEXES) - 1; i != 0; --i) // index[i]->delCopy(obj, index[0]); // index[0]->delCopy(obj, index[0]); // pool.del(elem); // } FORCE_INLINE OperationReturnStatus foreach(FuncType f, Transaction& xact) { return index[0]->foreach(f, xact); } // FORCE_INLINE void foreachCopy(FuncType f) { // index[0]->foreachCopy(f); // } // // void slice(int idx, const T* key, FuncType f) { // index[idx]->slice(key, f); // } // // void slice(int idx, const T& key, FuncType f) { // index[idx]->slice(&key, f); // } // void sliceCopy(int idx, const T* key, FuncType f) { // index[idx]->sliceCopy(key, f); // } // // void sliceCopy(int idx, const T& key, FuncType f) { // index[idx]->sliceCopy(&key, f); // } // // void sliceCopyDependent(int idx, const T* key, FuncType f) { // index[idx]->sliceCopy(key, f); // } // // void sliceCopyDependent(int idx, const T& key, FuncType f) { // index[idx]->sliceCopy(&key, f); // } // // FORCE_INLINE void update(T* elem) { // if (elem == nullptr) // return; // for (size_t i = 0; i < sizeof...(INDEXES); ++i) { // index[i]->update(elem); // } // } // // FORCE_INLINE void updateCopyDependent(T* obj2) { // if (obj2 == nullptr) // return; // T* elem = index[0]->get(obj2); // T* obj = copyIntoPool(obj2); // for (size_t i = 0; i < sizeof...(INDEXES); ++i) { // index[i]->updateCopyDependent(obj, elem); // } // } // // FORCE_INLINE void updateCopy(T* obj2) { // if (obj2 == nullptr) // return; // // T* obj = copyIntoPool(obj2); // //i >= 0 cant be used with unsigned type // for (size_t i = sizeof...(INDEXES) - 1; i != 0; --i) { // index[i]->updateCopy(obj, index[0]); // } // index[0]->updateCopy(obj, index[0]); // } // FORCE_INLINE size_t count() const { // return index[0]->count(); // } // // FORCE_INLINE void clear() { // for (size_t i = sizeof...(INDEXES) - 1; i != 0; --i) // index[i]->clear(); // index[0]->clear(); // } // template<class Archive> // void serialize(Archive& ar) const { // ar << "\n\t\t"; // dbtoaster::serialize_nvp(ar, "count", count()); // //SBJ: Hack! fix it! Cannot use store.foreach directly , as the last index may not be ListIndex created // auto idx = const_cast<Index<T, V> *> (index[0]); // idx->foreach([&ar] (T * e) { // ar << "\n"; dbtoaster::serialize_nvp_tabbed(ar, "item", *e, "\t\t"); }); // } }; #endif //MMAP_H
0
0.996698
1
0.996698
game-dev
MEDIA
0.415656
game-dev
0.996899
1
0.996899
Jerenaux/phaserquest
7,601
js/client/Player_client.js
/** * Created by Jerome on 25-02-17. */ function Player(x,y,key){ // key is a string indicating the atlas to use as texture Human.call(this,x,y,key); // Send context as first argument!! this.anchor.set(0.25,0.35); this.orientation = 4; // down this.speed = Game.playerSpeed; this.dialoguesMemory = {}; this.maxLife = Game.playerLife; this.life = this.maxLife; this.inFight = false; this.defaultFrames = { // the third value is the frame to come back to at the end of the animation "attack_right": [0,4,9], "right": [5, 8], "idle_right": [9, 10], "attack_up": [11,15,20], "up": [16, 19], "idle_up": [20, 21], "attack_down": [22,26,31], "down": [27, 30], "idle_down": [31, 32], "attack_left": [33,37,42], "left": [38, 41], "idle_left": [42, 43] }; this.addChild(this.weapon = game.add.sprite(0,0,'atlas3')); this.addChild(this.shadow = game.add.sprite(0,5, 'atlas1','shadow')); this.addChild(this.nameHolder = game.add.text(0,-30, '', { font: '14px pixel', fill: "#ffffff", stroke: "#000000", strokeThickness: 2 })); this.events.onKilled.add(function(player){ Game.displayedPlayers.delete(player.id); },this); } Player.prototype = Object.create(Human.prototype); Player.prototype.constructor = Player; Player.prototype.setIsPlayer = function(flag){ // sets the isPlayer flag to true or false to indicate if a sprite is the main player or another player this.isPlayer = flag; if(this.isPlayer) this.nameHolder.addColor("#f4d442",0); }; Player.prototype.setName = function(name) { this.nameHolder.text = name; this.nameHolder.x = Math.floor(16 - (this.nameHolder.width/2)); }; Player.prototype.prepareMovement = function(end,finalOrientation,action,delta,sendToServer){ // Handles the necessary caretaking preliminary to moving the player if(!this.alive) return; if(!end) return; var start = Game.computeTileCoords(this.x,this.y); if (start.x == end.x && start.y == end.y) { if(action.action == 1) this.finishMovement(finalOrientation,action); return; } if(this.isPlayer) Game.manageMoveTarget(end.x,end.y); if(this.tween){ this.stopMovement(false); start = this.adjustStartPosition(start); } if(this.isPlayer && this.inFight && action.action != 3) this.endFight(); Game.easystar.findPath(start.x, start.y, end.x, end.y, this.pathfindingCallback.bind(this,finalOrientation,action,delta,sendToServer)); Game.easystar.calculate(); }; Player.prototype.equipWeapon = function(key){ // key is a string use as a key in Game.itemsInfo to fetch the necessary information about the item to equip // it's also used as part of the frame names to use (e.g. redsword_0, redsword_1, ...) this.weapon.name = key; this.weapon.frameName = key+'_0'; this.weapon.absorbProperties(Game.itemsInfo[key]); this.atk = this.weapon.atk; this.adjustWeapon(); this.setAnimations(this.weapon); if(this.isPlayer){ Game.weaponIcon.frameName = this.weapon.icon+'_0'; Client.setWeapon(key); } return true; }; Player.prototype.adjustWeapon = function(){ this.weapon.position.set(this.weapon.offsets.x, this.weapon.offsets.y); }; Player.prototype.equipArmor = function(key){ // key is a string use as a key in Game.itemsInfo to fetch the necessary information about the item to equip // it's also used as part of the frame names to use (e.g. redsword_0, redsword_1, ...) var armorInfo = Game.itemsInfo[key]; this.def = armorInfo.def; this.armorName = key; this.frameName = key+'_0'; if(this.isPlayer) { Game.armorIcon.frameName = armorInfo.icon+'_0'; Client.setArmor(key); Game.armorIcon.anchor.set(0,0); if(armorInfo.iconAnchor) Game.armorIcon.anchor.set(armorInfo.iconAnchor.x,armorInfo.iconAnchor.y); } var animationFrames = (armorInfo.hasOwnProperty('frames')? armorInfo.frames : null); this.frames = animationFrames; this.setAnimations(this); return true; }; Player.prototype.updateLife = function(){ // Update the life bar to reflect the amout of health of the player if(this.life < 0) this.life = 0; var width = Game.computeLifeBarWidth(); var tweenWidth = game.add.tween(Game.health.getChildAt(0)); // tween for the "body" of the bar var tweenEnd = game.add.tween(Game.health.getChildAt(1)); // tween for the curved tip tweenWidth.to({width: width }, 200,null, false, 200); tweenEnd.to({x: width }, 200,null, false, 200); tweenWidth.start(); tweenEnd.start(); }; Player.prototype.teleport = function(){ var cell = Game.computeTileCoords(this.x,this.y); var door = Game.doors.getFirst(cell.x,cell.y); if(door){ this.position.set(door.to.x, door.to.y); if(this.isPlayer) { if (door.camera && !door.follow) { // if the camera cannot follow the player but has to be fixed at specific coordinates Game.unfollowPlayer(); game.camera.x = door.camera.x; game.camera.y = door.camera.y; } else if(door.follow) { // if the camera can follow, but indoors and within possible bounds Game.followPlayerIndoors(door.min_cx,door.min_cy,door.max_cx,door.max_cy); }else{ Game.followPlayer(); } } var orientationMap = { l: 1, u: 2, r: 3, d: 4 }; return orientationMap[door.orientation]; } return null; }; Player.prototype.fight = function(){ // Sets the player in "fight mode", and start a tween that calls fightAction() regularly in order to display the attack animations if(!this.target) return; this.inFight = true; this.fightTween = game.add.tween(this); this.fightTween.to({}, Phaser.Timer.SECOND, null, false, 0, -1); this.fightTween.onStart.add(function(){this.fightAction();}, this); this.fightTween.onLoop.add(function(){this.fightAction();}, this); this.fightTween.start(); }; Player.prototype.fightAction = function(){ // Checks if the target is on an adjacent cell, and if yes, triggers attack animation if(this.isPlayer) return; // For the main player, attack animations are handled differently, see updateSelf() var direction = Game.adjacent(this,this.target); if(direction > 0){ // Target is on adjacent cell if(this.tween){ this.tween.stop(); this.tween = null; } this.orientation = direction; this.attack(); } }; Player.prototype.die = function(animate){ // animate is a boolean indicating if the death animation should be played (if not, the sprite simply disappears) if(this.tween) this.stopMovement(false); this.endFight(); this.target = null; this.life = 0; if(this.isPlayer) { Game.moveTarget.visible = false; this.updateLife(); setTimeout(Game.displayDeathScroll,Phaser.Timer.SECOND*2); } if(animate && this.inCamera) { this.frameName = 'death_0'; this.animate('death', false); Game.sounds.play('death'); } this.delayedKill(750); }; Player.prototype.respawn = function(){ this.revive(); // method from the Phaser Sprite class this.orientation = game.rnd.between(1,4); if(this.isPlayer) { this.life = this.maxLife; this.updateLife(); } this.idle(true); };
0
0.948154
1
0.948154
game-dev
MEDIA
0.87631
game-dev
0.981946
1
0.981946
joetsoi/OpenMoonstone
3,129
python/combat/logic.py
from collections import UserList from attr import attrib, attrs from .blood import create_knight_blood_stain from .graphics import set_animation from .state import Attack, State from .system import SystemFlag @attrs(slots=True) class Logic: health = attrib(type=int, default=10) weapon_damage = attrib(type=int, default=3) dodged = attrib(type=bool, default=False) knight_counter = { Attack.swing: Attack.block, Attack.back: Attack.block, Attack.chop: Attack.dodge, Attack.thrust: Attack.dodge, } class LogicSystem(UserList): flags = SystemFlag.LOGIC + SystemFlag.COLLISION + SystemFlag.ANIMATIONSTATE def update(self, encounter): recover_after_attack = [] take_damage = [] attackers = [ entity for entity in self.data if (entity.collision.has_hit and entity.state.value == State.attacking) ] for attacker in attackers: defender = attacker.collision.has_hit if defender.state.value == State.attacking: defender_action = Attack[defender.state.animation_name] attacker_action = Attack[attacker.state.animation_name] if defender_action == knight_counter[attacker_action]: if defender_action == Attack.dodge: if not defender.logic.dodged: defender.logic.dodged = True continue else: recover_after_attack.append(attacker) continue take_damage.append(defender) defender.logic.health -= attacker.logic.weapon_damage attacker.collision.has_hit = None for entity in recover_after_attack: set_animation( animation_name="recovery", frame_number=-1, graphics=entity.graphics, movement=entity.movement, state=entity.state, ) entity.state.value = State.busy for entity in take_damage: if defender.logic.health <= 0: set_animation( animation_name="death", frame_number=-1, graphics=entity.graphics, movement=entity.movement, state=entity.state, ) entity.state.value = State.loop_once else: set_animation( animation_name="some", frame_number=-1, graphics=entity.graphics, movement=entity.movement, state=entity.state, ) entity.state.value = State.busy print(f"{entity.logic.health}") blood_stain = create_knight_blood_stain( "some", entity.graphics.palette, entity.movement.facing, entity.movement.position, ) encounter.register_entity(blood_stain)
0
0.899265
1
0.899265
game-dev
MEDIA
0.991332
game-dev
0.977318
1
0.977318
The-Final-Nights/The-Final-Nights
8,458
code/modules/events/_event.dm
//this singleton datum is used by the events controller to dictate how it selects events /datum/round_event_control var/name //The human-readable name of the event var/typepath //The typepath of the event datum /datum/round_event var/weight = 10 //The weight this event has in the random-selection process. //Higher weights are more likely to be picked. //10 is the default weight. 20 is twice more likely; 5 is half as likely as this default. //0 here does NOT disable the event, it just makes it extremely unlikely var/earliest_start = 20 MINUTES //The earliest world.time that an event can start (round-duration in deciseconds) default: 20 mins var/min_players = 0 //The minimum amount of alive, non-AFK human players on server required to start the event. var/occurrences = 0 //How many times this event has occured var/max_occurrences = 20 //The maximum number of times this event can occur (naturally), it can still be forced. //By setting this to 0 you can effectively disable an event. var/holidayID = "" //string which should be in the SSeventss.holidays list if you wish this event to be holiday-specific //anything with a (non-null) holidayID which does not match holiday, cannot run. var/wizardevent = FALSE var/alert_observers = TRUE //should we let the ghosts and admins know this event is firing //should be disabled on events that fire a lot var/list/gamemode_blacklist = list() // Event won't happen in these gamemodes var/list/gamemode_whitelist = list() // Event will happen ONLY in these gamemodes if not empty var/triggering //admin cancellation /datum/round_event_control/New() if(config && !wizardevent) // Magic is unaffected by configs earliest_start = CEILING(earliest_start * CONFIG_GET(number/events_min_time_mul), 1) min_players = CEILING(min_players * CONFIG_GET(number/events_min_players_mul), 1) /datum/round_event_control/wizard wizardevent = TRUE // Checks if the event can be spawned. Used by event controller and "false alarm" event. // Admin-created events override this. /datum/round_event_control/proc/canSpawnEvent(players_amt, gamemode) if(occurrences >= max_occurrences) return FALSE if(earliest_start >= world.time-SSticker.round_start_time) return FALSE if(wizardevent != SSevents.wizardmode) return FALSE if(players_amt < min_players) return FALSE if(gamemode_blacklist.len && (gamemode in gamemode_blacklist)) return FALSE if(gamemode_whitelist.len && !(gamemode in gamemode_whitelist)) return FALSE if(holidayID && (!SSevents.holidays || !SSevents.holidays[holidayID])) return FALSE if(EMERGENCY_ESCAPED_OR_ENDGAMED) return FALSE if(ispath(typepath, /datum/round_event/ghost_role) && !(GLOB.ghost_role_flags & GHOSTROLE_MIDROUND_EVENT)) return FALSE return TRUE /datum/round_event_control/proc/preRunEvent() if(!ispath(typepath, /datum/round_event)) return EVENT_CANT_RUN triggering = TRUE if (alert_observers) message_admins("Random Event triggering in 10 seconds: [name] (<a href='byond://?src=[REF(src)];cancel=1'>CANCEL</a>)") sleep(100) var/gamemode = SSticker.mode.config_tag var/players_amt = get_active_player_count(alive_check = TRUE, afk_check = TRUE, human_check = TRUE) if(!canSpawnEvent(players_amt, gamemode)) message_admins("Second pre-condition check for [name] failed, skipping...") return EVENT_INTERRUPTED if(!triggering) return EVENT_CANCELLED //admin cancelled triggering = FALSE return EVENT_READY /datum/round_event_control/Topic(href, href_list) ..() if(href_list["cancel"]) if(!triggering) to_chat(usr, "<span class='admin'>You are too late to cancel that event</span>") return triggering = FALSE message_admins("[key_name_admin(usr)] cancelled event [name].") log_admin_private("[key_name(usr)] cancelled event [name].") SSblackbox.record_feedback("tally", "event_admin_cancelled", 1, typepath) /datum/round_event_control/proc/runEvent(random = FALSE) var/datum/round_event/E = new typepath() E.current_players = get_active_player_count(alive_check = 1, afk_check = 1, human_check = 1) E.control = src SSblackbox.record_feedback("tally", "event_ran", 1, "[E]") occurrences++ testing("[time2text(world.time, "hh:mm:ss")] [E.type]") if(random) log_game("Random Event triggering: [name] ([typepath])") if (alert_observers) deadchat_broadcast(" has just been[random ? " randomly" : ""] triggered!", "<b>[name]</b>", message_type=DEADCHAT_ANNOUNCEMENT) //STOP ASSUMING IT'S BADMINS! return E //Special admins setup /datum/round_event_control/proc/admin_setup() return /datum/round_event //NOTE: Times are measured in master controller ticks! var/processing = TRUE var/datum/round_event_control/control var/startWhen = 0 //When in the lifetime to call start(). var/announceWhen = 0 //When in the lifetime to call announce(). If you don't want it to announce use announceChance, below. var/announceChance = 100 // Probability of announcing, used in prob(), 0 to 100, default 100. Used in ion storms currently. var/endWhen = 0 //When in the lifetime the event should end. var/activeFor = 0 //How long the event has existed. You don't need to change this. var/current_players = 0 //Amount of of alive, non-AFK human players on server at the time of event start var/fakeable = TRUE //Can be faked by fake news event. //Called first before processing. //Allows you to setup your event, such as randomly //setting the startWhen and or announceWhen variables. //Only called once. //EDIT: if there's anything you want to override within the new() call, it will not be overridden by the time this proc is called. //It will only have been overridden by the time we get to announce() start() tick() or end() (anything but setup basically). //This is really only for setting defaults which can be overridden later when New() finishes. /datum/round_event/proc/setup() return //Called when the tick is equal to the startWhen variable. //Allows you to start before announcing or vice versa. //Only called once. /datum/round_event/proc/start() return //Called after something followable has been spawned by an event //Provides ghosts a follow link to an atom if possible //Only called once. /datum/round_event/proc/announce_to_ghosts(atom/atom_of_interest) if(control.alert_observers) if (atom_of_interest) notify_ghosts("[control.name] has an object of interest: [atom_of_interest]!", source=atom_of_interest, action=NOTIFY_ORBIT, header="Something's Interesting!") return //Called when the tick is equal to the announceWhen variable. //Allows you to announce before starting or vice versa. //Only called once. /datum/round_event/proc/announce(fake) return //Called on or after the tick counter is equal to startWhen. //You can include code related to your event or add your own //time stamped events. //Called more than once. /datum/round_event/proc/tick() return //Called on or after the tick is equal or more than endWhen //You can include code related to the event ending. //Do not place spawn() in here, instead use tick() to check for //the activeFor variable. //For example: if(activeFor == myOwnVariable + 30) doStuff() //Only called once. /datum/round_event/proc/end() return //Do not override this proc, instead use the appropiate procs. //This proc will handle the calls to the appropiate procs. /datum/round_event/process() SHOULD_NOT_OVERRIDE(TRUE) if(!processing) return if(activeFor == startWhen) processing = FALSE start() processing = TRUE if(activeFor == announceWhen && prob(announceChance)) processing = FALSE announce(FALSE) processing = TRUE if(startWhen < activeFor && activeFor < endWhen) processing = FALSE tick() processing = TRUE if(activeFor == endWhen) processing = FALSE end() processing = TRUE // Everything is done, let's clean up. if(activeFor >= endWhen && activeFor >= announceWhen && activeFor >= startWhen) processing = FALSE kill() activeFor++ //Garbage collects the event by removing it from the global events list, //which should be the only place it's referenced. //Called when start(), announce() and end() has all been called. /datum/round_event/proc/kill() SSevents.running -= src //Sets up the event then adds the event to the the list of running events /datum/round_event/New(my_processing = TRUE) setup() processing = my_processing SSevents.running += src return ..()
0
0.938251
1
0.938251
game-dev
MEDIA
0.948699
game-dev
0.967045
1
0.967045
dridri/bcflight
2,823
libluacore/src/LuaInterface.h
#ifndef LUA_INTERFACE_H #define LUA_INTERFACE_H #include "Lua.h" class LuaInterface : public LuaValue { private: template< class C, size_t... S > static C* unpack_vector( const std::vector<LuaValue>& vec, std::index_sequence<S...> ) { return new C(vec[S]...); } template< class C, size_t size > static C* unpack_vector( const std::vector<LuaValue>& vec ) { return unpack_vector<C>( vec, std::make_index_sequence<size>() ); } public: template <class C, size_t nArgs> static void RegisterClass( Lua* lua, const string& name = typeid(LuaInterface).name() ) { lua_State* L = lua->state(); lua_createtable( L, 0, 0 ); lua_pushstring( L, "c-class" ); lua_setfield( L, -2, "type" ); lua_pushstring( L, name.c_str() ); lua_setfield( L, -2, "name" ); lua_pushcclosure( L, []( lua_State* L ) { lua_pushvalue( L, 1 ); lua_setfield( L, -2, "super" ); lua_pushvalue( L, 2 ); lua_setfield( L, -2, "name" ); // Create metatable with __index to access super-Class values lua_getmetatable( L, -1 ); lua_pushvalue( L, 1 ); lua_setfield( L, -2, "__index" ); lua_pop( L, 1 ); lua_pushvalue( L, -1 ); return 1; }, 0 ); lua_setfield( L, -2, "extend" ); // Create metatable lua_createtable( L, 0, 0 ); lua_pushcclosure( L, []( lua_State* L ) { int32_t n = lua_gettop( L ); vector< LuaValue > args; for ( int32_t i = 1; i < n; i++ ) { args.push_back( Lua::value( L, i + 1 ) ); } C** pInstance = reinterpret_cast<C**>( lua_newuserdata( L, sizeof(C*) ) ); lua_pushvalue( L, -1 ); *pInstance = unpack_vector< C, nArgs >( args ); return 1; }, 0 ); lua_setfield( L, -2, "__call" ); lua_setmetatable( L, -2 ); lua_setglobal( L, name.c_str() ); } protected: LuaInterface( Lua* lua, const string& className = typeid(LuaInterface).name() ) : mLua( lua ), mClassName( className ) { PreInit(); CallMember( "init" ); } template< typename ...LuaValues > LuaInterface( Lua* lua, const string& className, LuaValues... values ) : mLua( lua ), mClassName( className ) { PreInit(); CallMember( "init", values... ); } virtual ~LuaInterface() = 0; LuaValue CallMember( const string& funcname, const vector<LuaValue>& args ); template< typename ...LuaValues > LuaValue CallMember( const string& funcname, LuaValues... values ) { return CallMember( funcname, { values... } ); } /* template< typename T > class Shared { public: Shared& operator=( const T& from ) { mValue = from; return *this; } operator T& () { return mValue; } operator const T& () { return mValue; } protected: T mValue; }; */ Lua* mLua; string mClassName; // lua_Integer mInstanceRef; private: void PreInit(); std::map< std::string, LuaValue > mValues; }; #endif // LUA_INTERFACE_H
0
0.914356
1
0.914356
game-dev
MEDIA
0.572549
game-dev
0.771807
1
0.771807
CYRUS-STUDIO/LLVM
2,856
llvm/lib/Target/CSKY/CSKYSubtarget.cpp
//===-- CSKYSubtarget.h - Define Subtarget for the CSKY----------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file declares the CSKY specific subclass of TargetSubtargetInfo. // //===----------------------------------------------------------------------===// #include "CSKYSubtarget.h" #include "llvm/CodeGen/MachineFrameInfo.h" using namespace llvm; #define DEBUG_TYPE "csky-subtarget" #define GET_SUBTARGETINFO_TARGET_DESC #define GET_SUBTARGETINFO_CTOR #include "CSKYGenSubtargetInfo.inc" void CSKYSubtarget::anchor() {} CSKYSubtarget &CSKYSubtarget::initializeSubtargetDependencies( const Triple &TT, StringRef CPUName, StringRef TuneCPUName, StringRef FS) { if (CPUName.empty()) CPUName = "generic"; if (TuneCPUName.empty()) TuneCPUName = CPUName; UseHardFloat = false; UseHardFloatABI = false; HasFPUv2SingleFloat = false; HasFPUv2DoubleFloat = false; HasFPUv3HalfWord = false; HasFPUv3HalfFloat = false; HasFPUv3SingleFloat = false; HasFPUv3DoubleFloat = false; HasFdivdu = false; HasFLOATE1 = false; HasFLOAT1E2 = false; HasFLOAT1E3 = false; HasFLOAT3E4 = false; HasFLOAT7E60 = false; HasExtendLrw = false; HasBTST16 = false; HasTrust = false; HasJAVA = false; HasCache = false; HasNVIC = false; HasDSP = false; HasDSP1E2 = false; HasDSPE60 = false; HasDSPV2 = false; HasDSP_Silan = false; HasDoloop = false; HasHardwareDivide = false; HasHighRegisters = false; HasVDSPV2 = false; HasVDSP2E3 = false; HasVDSP2E60F = false; ReadTPHard = false; HasVDSPV1_128 = false; UseCCRT = false; DumpConstPool = false; EnableInterruptAttribute = false; HasPushPop = false; HasSTM = false; SmartMode = false; EnableStackSize = false; HasE1 = false; HasE2 = false; Has2E3 = false; HasMP = false; Has3E3r1 = false; Has3r1E3r2 = false; Has3r2E3r3 = false; Has3E7 = false; HasMP1E2 = false; Has7E10 = false; Has10E60 = false; ParseSubtargetFeatures(CPUName, TuneCPUName, FS); return *this; } CSKYSubtarget::CSKYSubtarget(const Triple &TT, StringRef CPU, StringRef TuneCPU, StringRef FS, const TargetMachine &TM) : CSKYGenSubtargetInfo(TT, CPU, TuneCPU, FS), FrameLowering(initializeSubtargetDependencies(TT, CPU, TuneCPU, FS)), InstrInfo(*this), RegInfo(), TLInfo(TM, *this) {} bool CSKYSubtarget::useHardFloatABI() const { auto FloatABI = getTargetLowering()->getTargetMachine().Options.FloatABIType; if (FloatABI == FloatABI::Default) return UseHardFloatABI; else return FloatABI == FloatABI::Hard; }
0
0.899476
1
0.899476
game-dev
MEDIA
0.382462
game-dev
0.931858
1
0.931858
frzyc/genshin-optimizer
1,924
libs/gi/formula/src/data/char/KukiShinobu.ts
import type { CharacterKey } from '@genshin-optimizer/gi/consts' import { allStats } from '@genshin-optimizer/gi/stats' import { cmpGE } from '@genshin-optimizer/pando/engine' import { allBoolConditionals, allListConditionals, allNumConditionals, enemyDebuff, own, ownBuff, register, team, teamBuff, } from '../util' import { dataGenToCharInfo, dmg, entriesForChar } from './util' const key: CharacterKey = 'KukiShinobu' const data_gen = allStats.char.data[key] const skillParam_gen = allStats.char.skillParam[key] // TODO: Fill data-mine values here const _dm = { normal: { dmg1: skillParam_gen.auto[0], }, charged: {}, plunging: {}, skill: {}, burst: {}, } as const const info = dataGenToCharInfo(data_gen) const { final: _final, char: { ascension: _ascension, constellation }, } = own // TODO: Conditionals const { _someBoolConditional } = allBoolConditionals(info.key) const { _someListConditional } = allListConditionals(info.key, []) const { _someNumConditional } = allNumConditionals(info.key) const _count = team.common.count export default register( info.key, entriesForChar(info, data_gen), // TODO: Double check these ownBuff.char.burst.add(cmpGE(constellation, 3, 3)), ownBuff.char.skill.add(cmpGE(constellation, 5, 3)), // TODO: // - Add member's own formulas using `ownBuff.<buff target>.add(<buff value>)` ownBuff.premod.atk.add(1), // - Add teambuff formulas using `teamBuff.<buff target>.add(<buff value>) teamBuff.premod.atk.add(1), // - Add enemy debuff using `enemyDebuff.<debuff target>.add(<debuff value>)` enemyDebuff.common.defRed_.add(1), // // <buff value> uses `own.*`, `team.*`, `target.*` (target of team buff), and `enemy.*` // Formulas // TODO: Add dmg/heal/shield formulas using `dmg`, `customDmg`, `shield`, `customShield`, `fixedShield`, or `customHeal` dmg('normal1', info, 'atk', _dm.normal.dmg1, 'normal') )
0
0.710422
1
0.710422
game-dev
MEDIA
0.73105
game-dev
0.934439
1
0.934439
FxMorin/carpet-fixes
1,986
src/main/java/carpetfixes/mixins/coreSystemFixes/ServerWorld_spawnPlatformMixin.java
package carpetfixes.mixins.coreSystemFixes; import carpetfixes.CFSettings; import net.minecraft.block.Blocks; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import static net.minecraft.server.world.ServerWorld.END_SPAWN_POS; /** * When the obsidian platform is generated in the end, it breaks all the blocks above. Instead we remove all end stone * and if the 2 middle blocks are not empty we break a larger area with block drop. */ @Mixin(ServerWorld.class) public class ServerWorld_spawnPlatformMixin { @Inject( method = "createEndSpawnPlatform", at = @At("HEAD"), cancellable = true ) private static void cf$createCustomEndSpawnPlatform(ServerWorld world, CallbackInfo ci) { if (CFSettings.obsidianPlatformDestroysBlocksFix) { BlockPos blockPos = END_SPAWN_POS; int x = blockPos.getX(); int y = blockPos.getY() - 2; int z = blockPos.getZ(); BlockPos.iterate(x - 2, y + 1, z - 2, x + 2, y + 3, z + 2).forEach(pos -> { if (world.getBlockState(pos).isOf(Blocks.END_STONE)) { world.setBlockState(pos, Blocks.AIR.getDefaultState()); } }); BlockPos.iterate(x - 2, y, z - 2, x + 2, y, z + 2).forEach(pos -> world.setBlockState(pos, Blocks.OBSIDIAN.getDefaultState()) ); if (!world.isAir(blockPos) || !world.isAir(blockPos.up())) { //obv would do an entityType check instead BlockPos.iterate(x - 1, y + 1, z - 1, x + 1, y + 2, z + 1).forEach(pos -> { world.breakBlock(pos, true); }); } ci.cancel(); } } }
0
0.847647
1
0.847647
game-dev
MEDIA
0.986474
game-dev
0.880358
1
0.880358
opentibiabr/canary
1,783
data-otservbr-global/scripts/actions/other/special_boxes.lua
local config = { [37457] = { -- supernatural box 37572, 37573, 37574, 37575, 37576, }, [37461] = { -- balloon box 37471, 37472, 37496, 37497, 37498, 37499, 37500, 37501, 37513, 37514, 37515, 37516, 37517, 37518, }, [37462] = { -- special carpet box 37354, 37357, 37358, 37360, 37362, 37364, }, [37463] = { -- luminous box 37543, 37544, 37545, }, [37465] = { -- box full of presents 37562, 37563, 37564, 37565, 37566, 37567, 37568, 37569, 37570, 37571, }, [37466] = { -- embroidered box 37540, 37541, 37542, }, [37467] = { -- carpet box 37366, 37374, 37375, 37376, 37377, 37378, 37379, 37380, 37382, 37390, 37391, 37392, 37393, 37394, 37395, 37396, }, [37468] = { -- special fx box 37448, 37450, 37451, 37452, 37453, 37454, 37455, 37456, 37458, 37459, 37460, }, [37469] = { -- special balloon box 37502, 37503, 37504, 37505, 37506, 37507, 37508, 37509, 37510, 37511, 37512, }, [37614] = { -- box full of decoration 37463, 37466, 37496, 37717, }, } local specialBox = Action() function specialBox.onUse(player, item, fromPosition, itemEx, toPosition) local box = config[item.itemid] if not box or not player then return false end local gift = box[math.random(1, #box)] for index, value in pairs(config) do Item(item.uid):remove(1) if fromPosition.x == CONTAINER_POSITION then player:getPosition():sendMagicEffect(CONST_ME_PRISMATIC_SPARK) player:addItem(gift) else fromPosition:sendMagicEffect(CONST_ME_PRISMATIC_SPARK) fromPosition:getTile():addItem(gift) end return true end end for index, value in pairs(config) do specialBox:id(index) end specialBox:register()
0
0.52611
1
0.52611
game-dev
MEDIA
0.883752
game-dev
0.709489
1
0.709489
reckdave/crazycattle3d-steam-multiplayer
5,504
assets/scripts/player.gd
extends Node3D class_name Player @export var sheep_speed : float = 100.0 var tick_rate : int = 0 #region playerdata var dead : bool = false: set(val): $Controller.freeze = val $Controller/Collision.disabled = val $Controller/sheepmodel.visible = !val $Controller.engine_force = 0.0 $Controller.steering = 0.0 dead = val var infreecam : bool = false: set(val): if (is_multiplayer_authority()): $Controller/Camera.current = !val $FreeCam.current = val if val: Input.mouse_mode = Input.MOUSE_MODE_CAPTURED %FreeCam.global_position = $Controller.global_position + Vector3(0,5,0) %player_display.reparent(%FreeCam,false) else: Input.mouse_mode = Input.MOUSE_MODE_VISIBLE %player_display.reparent($Controller,false) infreecam = val var username : String = "steamuser99": set(val): %player_display.text = val username = val #endregion func _enter_tree() -> void: set_multiplayer_authority(int(str(name))) func _ready() -> void: %player_display.text = MultiplayerHandler.players[int(name)]["username"] multiplayer.peer_disconnected.connect(_on_player_leave) if !(is_multiplayer_authority()):$UI.hide(); $SettingsMenu.hide(); return $Controller/Camera.current = true %player_display.hide() global_position = Vector3(randi_range(-80,80),1,randi_range(-80,80)) func _unhandled_input(event: InputEvent) -> void: if !(is_multiplayer_authority()): return if (infreecam) and event is InputEventMouseMotion: var look_dir = event.relative * 0.01 %FreeCam.rotation.y -= look_dir.x * 1.0 * 1.0 %FreeCam.rotation.x = clamp(%FreeCam.rotation.x - look_dir.y * 1.0 * 1.0, -1.5, 1.5) func _physics_process(delta: float) -> void: if not (is_multiplayer_authority()): set_physics_process(false); return if Input.is_action_just_pressed("debug_die"): die.rpc() if !(dead): $Controller.steering = lerp($Controller.steering, Input.get_axis("left", "right") * 0.4, 5 * delta) $Controller.engine_force = Input.get_axis("back", "forward") * sheep_speed setcarforce.rpc($Controller.engine_force,$Controller.steering) tick_rate += 1 if tick_rate >= 8 : setcardata.rpc($Controller.global_position,$Controller.global_rotation) if Input.is_action_just_pressed("space"): baa_sound.rpc() elif (infreecam) and (dead): var input_dir = Input.get_vector("left","right","forward","back") var forward_dir = %FreeCam.global_transform.basis * Vector3(input_dir.x,0,input_dir.y).normalized() if (Input.is_action_pressed("space")): %FreeCam.global_position.y += 1.0 if (Input.is_action_pressed("control")): %FreeCam.global_position.y -= 1.0 %FreeCam.global_position.x += forward_dir.x * 0.6 %FreeCam.global_position.z += forward_dir.z * 0.6 setfreecamdata.rpc(%FreeCam.global_position) var can_try : bool = false var try_time : float = 1.0 var can_impulse : bool = true func _process(delta: float) -> void: $UI/Control/Remaining.text = "%s left alive." % str(GameHandler.alive_players.size()) #if (Input.is_action_just_pressed("ui_down")): GameHandler.world_node.get_node("Map/DeathBarriar").queue_free() if !(multiplayer.is_server()): return else: try_time -= delta if !(can_try): if (try_time <= 0): can_try = true return var dead_collide = %death_ray.is_colliding() var death_area_collide = $Controller/DeathArea.get_overlapping_bodies().size() var inside_zone = $Controller/ZoneArea.get_overlapping_areas().size() if (%impulse_ray.is_colliding()): if (can_impulse): apply_push.rpc(%impulse_ray.get_collider().get_parent().name,$Controller.linear_velocity) can_impulse = false print("sending") else: can_impulse = true if !(dead): if (dead_collide) or (inside_zone <= 0) or (death_area_collide > 0): die.rpc() # multiplayer calls #@rpc("any_peer","call_local","reliable",0) #func push_collide(body): #if (multiplayer.get_remote_sender_id() != 1): return #body.apply_impulse($Controller.linear_velocity) @rpc("any_peer","call_local","reliable") func apply_push(pid,force): if (multiplayer.get_remote_sender_id() != 1): return var plr = GameHandler.get_player(pid) plr.get_node("Controller").apply_impulse(force * 1.1) @rpc("authority","call_remote","unreliable",0) func setcardata(newpos,newrot): if !(has_node("Controller")): return $Controller.global_position = lerp($Controller.global_position,newpos,0.4) $Controller.global_rotation = newrot @rpc("authority","call_remote","unreliable",0) func setcarforce(newforce,newsteer): if !(has_node("Controller")): return $Controller.engine_force = newforce $Controller.steering = newsteer @rpc("authority","call_remote","unreliable",0) func setfreecamdata(newpos): %FreeCam.global_position = newpos @rpc("authority","call_local","unreliable",0) func baa_sound(): if !(has_node("Controller")): return $Controller/SFX/Baa.play() @rpc("any_peer","call_local","reliable",0) func die(): if (multiplayer.get_remote_sender_id() != 1): return if !(has_node("Controller")): return if !(dead): print("%s HAS DIED" % username) $Controller/VFX/Explosion.play("Explode") $Controller/SFX/Explode.play() $Controller/SFX/Death1.play() sheep_speed = 0.0 infreecam = true dead = true GameHandler.alive_players.erase(int(name)) GameHandler.player_removed.emit(int(name)) # multiplayer connects func _on_player_leave(pid): if pid == int(name): if GameHandler.alive_players.has(pid): GameHandler.alive_players.erase(pid); GameHandler.player_removed.emit(int(name)) queue_free() # MISC
0
0.795829
1
0.795829
game-dev
MEDIA
0.933438
game-dev
0.935572
1
0.935572
ProjectIgnis/CardScripts
3,934
unofficial/c511001777.lua
--CNo.43 魂魄傀儡鬼神カオス・マリオネッター (Anime) --Number C43: High Manipulator of Chaos (Anime) Duel.LoadCardScript("c32446630.lua") local s,id=GetID() function s.initial_effect(c) --xyz summon Xyz.AddProcedure(c,aux.FilterBoolFunctionEx(Card.IsAttribute,ATTRIBUTE_DARK),3,4) c:EnableReviveLimit() --Rank Up Check aux.EnableCheckRankUp(c,nil,nil,56051086) --battle indestructable local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e1:SetValue(aux.NOT(aux.TargetBoolFunction(Card.IsSetCard,SET_NUMBER))) c:RegisterEffect(e1) --indestructable local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e2:SetRange(LOCATION_MZONE) e2:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE) e2:SetTarget(aux.TargetBoolFunction(Card.IsCode,32446631)) e2:SetValue(1) --Negates Battle Damage local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e3:SetRange(LOCATION_MZONE) e3:SetCode(EVENT_PRE_BATTLE_DAMAGE) e3:SetCondition(s.rdcon) e3:SetOperation(s.rdop) --atk local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_FIELD) e4:SetCode(EFFECT_EXTRA_ATTACK) e4:SetRange(LOCATION_MZONE) e4:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE) e4:SetTarget(aux.TargetBoolFunction(Card.IsCode,32446631)) e4:SetValue(s.atkval) --token local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(id,0)) e5:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN) e5:SetType(EFFECT_TYPE_IGNITION) e5:SetRange(LOCATION_MZONE) e5:SetCountLimit(1) e5:SetCondition(s.spcon) e5:SetCost(Cost.DetachFromSelf(1)) e5:SetTarget(s.sptg) e5:SetOperation(s.spop) -- local e6=Effect.CreateEffect(c) e6:SetType(EFFECT_TYPE_SINGLE) e6:SetCode(EFFECT_RANKUP_EFFECT) e6:SetLabelObject(e2) c:RegisterEffect(e6) local e7=e6:Clone() e7:SetLabelObject(e3) c:RegisterEffect(e7) local e8=e6:Clone() e8:SetLabelObject(e4) c:RegisterEffect(e8) local e9=e6:Clone() e9:SetLabelObject(e5) c:RegisterEffect(e9) end s.listed_series={SET_NUMBER} s.listed_names={56051086,32446631} s.xyz_number=43 function s.cfilter(c,lp) return c:IsFaceup() and c:GetAttack()>lp end function s.spcon(e,tp,eg,ep,ev,re,r,rp) return Duel.IsExistingMatchingCard(s.cfilter,tp,0,LOCATION_MZONE,1,nil,Duel.GetLP(1-tp)) end function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsPlayerCanSpecialSummonMonster(tp,32446631,0,TYPES_TOKEN,-2,-2,1,RACE_FIEND,ATTRIBUTE_DARK) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_MZONE) Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,1,tp,LOCATION_MZONE) end function s.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end if not Duel.IsPlayerCanSpecialSummonMonster(tp,32446631,0,TYPES_TOKEN,-2,-2,1,RACE_FIEND,ATTRIBUTE_DARK) then return end local token=Duel.CreateToken(tp,32446631) Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SET_ATTACK) e1:SetValue(Duel.GetLP(1-tp)) e1:SetLabel(RESET_EVENT+RESETS_STANDARD) token:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_SET_DEFENSE) token:RegisterEffect(e2) Duel.SpecialSummonComplete() end function s.rdcon(e,tp,eg,ep,ev,re,r,rp) local a=Duel.GetAttacker() local d=Duel.GetAttackTarget() return (a:IsCode(32446631) or (d and d:IsCode(32446631))) and tp==ep end function s.rdop(e,tp,eg,ep,ev,re,r,rp) Duel.ChangeBattleDamage(tp,0) local c=e:GetHandler() if ev>0 and tp==ep then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetProperty(EFFECT_FLAG_COPY_INHERIT) e1:SetReset(RESET_EVENT+RESETS_STANDARD_DISABLE) e1:SetValue(ev) c:RegisterEffect(e1) end end function s.atkval(e,c) return e:GetHandler():GetOverlayCount()-1 end
0
0.841194
1
0.841194
game-dev
MEDIA
0.990627
game-dev
0.869151
1
0.869151
levinzonr/godot-asset-placer
1,734
addons/asset_placer/ui/asset_collections_window/asset_collections_presenter.gd
extends RefCounted class_name AssetCollectionsPresenter var _repository: AssetCollectionRepository var _assets_repository: AssetsRepository var _new_collection_name: String = "" var _new_collection_color: Color signal show_collections(items: Array[AssetCollection]) signal enable_create_button(enable: bool) signal show_empty_view signal clear_text_field() func _init(): self._repository = AssetCollectionRepository.new() self._repository.collections_changed.connect(_load_collections) self._assets_repository = AssetsRepository.instance func ready(): _load_collections() _update_state_new_collection_state() func set_color(color: Color): _new_collection_color = color _update_state_new_collection_state() func set_name(name: String): _new_collection_name = name _update_state_new_collection_state() func create_collection(): var collection = AssetCollection.new(_new_collection_name, _new_collection_color) _repository.add_collection(collection) clear_text_field.emit() enable_create_button.emit(false) func _update_state_new_collection_state(): var valid_name := !_new_collection_name.is_empty() var valid_color = _new_collection_color != null enable_create_button.emit(valid_color && valid_name) func _load_collections(): var collections := _repository.get_collections() if collections.size() == 0: show_empty_view.emit() else: show_collections.emit(collections) func delete_collection(collection: AssetCollection): _repository.delete_collection(collection.name) for asset in _assets_repository.get_all_assets(): var updated_tags = asset.tags.filter(func(f): return f != collection.name) if updated_tags != asset.tags: asset.tags = updated_tags _assets_repository.update(asset)
0
0.873296
1
0.873296
game-dev
MEDIA
0.84012
game-dev
0.805942
1
0.805942
amethyst/rustrogueliketutorial
3,115
chapter-35-vaults2/src/monster_ai_system.rs
use specs::prelude::*; use super::{Viewshed, Monster, Map, Position, WantsToMelee, RunState, Confusion, particle_system::ParticleBuilder, EntityMoved}; use rltk::{Point}; pub struct MonsterAI {} impl<'a> System<'a> for MonsterAI { #[allow(clippy::type_complexity)] type SystemData = ( WriteExpect<'a, Map>, ReadExpect<'a, Point>, ReadExpect<'a, Entity>, ReadExpect<'a, RunState>, Entities<'a>, WriteStorage<'a, Viewshed>, ReadStorage<'a, Monster>, WriteStorage<'a, Position>, WriteStorage<'a, WantsToMelee>, WriteStorage<'a, Confusion>, WriteExpect<'a, ParticleBuilder>, WriteStorage<'a, EntityMoved>); fn run(&mut self, data : Self::SystemData) { let (mut map, player_pos, player_entity, runstate, entities, mut viewshed, monster, mut position, mut wants_to_melee, mut confused, mut particle_builder, mut entity_moved) = data; if *runstate != RunState::MonsterTurn { return; } for (entity, mut viewshed,_monster,mut pos) in (&entities, &mut viewshed, &monster, &mut position).join() { let mut can_act = true; let is_confused = confused.get_mut(entity); if let Some(i_am_confused) = is_confused { i_am_confused.turns -= 1; if i_am_confused.turns < 1 { confused.remove(entity); } can_act = false; particle_builder.request(pos.x, pos.y, rltk::RGB::named(rltk::MAGENTA), rltk::RGB::named(rltk::BLACK), rltk::to_cp437('?'), 200.0); } if can_act { let distance = rltk::DistanceAlg::Pythagoras.distance2d(Point::new(pos.x, pos.y), *player_pos); if distance < 1.5 { wants_to_melee.insert(entity, WantsToMelee{ target: *player_entity }).expect("Unable to insert attack"); } else if viewshed.visible_tiles.contains(&*player_pos) { // Path to the player let path = rltk::a_star_search( map.xy_idx(pos.x, pos.y), map.xy_idx(player_pos.x, player_pos.y), &*map ); if path.success && path.steps.len()>1 { let mut idx = map.xy_idx(pos.x, pos.y); map.blocked[idx] = false; pos.x = path.steps[1] as i32 % map.width; pos.y = path.steps[1] as i32 / map.width; entity_moved.insert(entity, EntityMoved{}).expect("Unable to insert marker"); idx = map.xy_idx(pos.x, pos.y); map.blocked[idx] = true; viewshed.dirty = true; } } } } } }
0
0.823229
1
0.823229
game-dev
MEDIA
0.958655
game-dev
0.973423
1
0.973423
benjames-171/defold-games
2,126
Urban Climber/menu/menu.gui_script
local data = require "main.data" local ui = require "main.ui" function init(self) self.handpos = 1 self.arrowpos = { gui.get_position(gui.get_node("1")), gui.get_position(gui.get_node("2")), gui.get_position(gui.get_node("3")), } msg.post(".", "acquire_input_focus") self.node = gui.get_node("container") gui.set_position(self.node, vmath.vector3(data.SCR_W/2, (data.SCR_H/2), 0)) gui.set_text(gui.get_node("v"), sys.get_config("project.version")) gui.animate(gui.get_node("logo"), "scale", vmath.vector3(4, 4, 1), gui.EASING_OUTBOUNCE, 1) data.state = data.STATE_MENU end local function startgame(self) msg.post("main:/handler", "show_game") sound.play("main:/sound#music") data.time = 60 data.state = data.STATE_PLAYING end local function show(self) ui.show(self.node) data.state = data.STATE_MENU end function update(self, dt) if data.state == data.STATE_MENU then local pos = vmath.vector3(self.arrowpos[self.handpos].x - 48, self.arrowpos[self.handpos].y - 10, 0) gui.set_position(gui.get_node("arrow"), pos) end end function on_message(self, message_id, message, sender) if message_id == hash("show") then show(self) end end local function controls(self) ui.hide(self.node) msg.post("#controls", "show", {}) end local function credits(self) ui.hide(self.node) msg.post("#credits", "show", {}) end function on_input(self, action_id, action) if data.state == data.STATE_MENU then if action_id == hash("up") and action.pressed then self.handpos = self.handpos - 1 if self.handpos < 1 then self.handpos = 3 end sound.play("main:/sound#pop") elseif action_id == hash("down") and action.pressed then self.handpos = self.handpos + 1 if self.handpos > 3 then self.handpos = 1 end sound.play("main:/sound#pop") elseif action_id == hash("action") and action.pressed then if self.handpos == 1 then startgame(self) elseif self.handpos == 2 then controls(self) elseif self.handpos == 3 then credits(self) end elseif action_id == hash("exit") and action.pressed and not html5 then msg.post("@system:", "exit", {code = 0}) end end end
0
0.605496
1
0.605496
game-dev
MEDIA
0.801193
game-dev,desktop-app
0.895599
1
0.895599
LeroyMackerl/UE5-ApparatusECS-CrowdBattlePlugin
2,607
BattleFrame/Source/BattleFrame/Private/BFSubjectiveActorComponent.cpp
#include "BFSubjectiveActorComponent.h" #include "Traits/Health.h" #include "Traits/GridData.h" #include "Traits/Collider.h" #include "Traits/BindFlowField.h" #include "Traits/Activated.h" #include "Traits/IsSubjective.h" #include "Traits/Slow.h" #include "Traits/TemporalDamage.h" UBFSubjectiveActorComponent::UBFSubjectiveActorComponent() { // Set up basic traits in constructor SetTrait(FHealth()); SetTrait(FCollider()); SetTrait(FBindFlowField()); SetTrait(FStatistics()); // Enable ticking PrimaryComponentTick.bCanEverTick = true; PrimaryComponentTick.bStartWithTickEnabled = true; } void UBFSubjectiveActorComponent::BeginPlay() { Super::BeginPlay(); InitializeSubjectTraits(GetOwner()); } void UBFSubjectiveActorComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); SyncTransformActorToSubject(GetOwner()); } void UBFSubjectiveActorComponent::InitializeSubjectTraits(AActor* OwnerActor) { if (!OwnerActor) return; // Ensure we have these traits if (!HasTrait<FHealth>()) { SetTrait(FHealth()); } if (!HasTrait<FCollider>()) { SetTrait(FCollider()); } SetTrait(FLocated{ OwnerActor->GetActorLocation() }); SetTrait(FDirected{ OwnerActor->GetActorForwardVector().GetSafeNormal2D() }); FVector ActorScale3D = OwnerActor->GetActorScale3D(); float Scale = FMath::Max3(ActorScale3D.X, ActorScale3D.Y, ActorScale3D.Z); SetTrait(FScaled{ Scale, ActorScale3D }); const auto SubjectHandle = GetHandle(); SetTrait(FGridData{ SubjectHandle.CalcHash(), FVector3f(GetTrait<FLocated>().Location), GetTrait<FCollider>().Radius, SubjectHandle }); SetTrait(FTemporalDamaging()); SetTrait(FSlowing()); SetTrait(FIsSubjective()); SetTrait(FActivated()); } void UBFSubjectiveActorComponent::SyncTransformActorToSubject(AActor* OwnerActor) { if (!OwnerActor) return; auto Located = GetTraitPtr<FLocated, EParadigm::Unsafe>(); if (Located) { Located->Location = OwnerActor->GetActorLocation(); } auto Directed = GetTraitPtr<FDirected, EParadigm::Unsafe>(); if (Directed) { Directed->Direction = OwnerActor->GetActorForwardVector().GetSafeNormal2D(); } auto Scaled = GetTraitPtr<FScaled, EParadigm::Unsafe>(); if (Scaled) { FVector ActorScale3D = OwnerActor->GetActorScale3D(); Scaled->Scale = FMath::Max3(ActorScale3D.X, ActorScale3D.Y, ActorScale3D.Z); } }
0
0.888082
1
0.888082
game-dev
MEDIA
0.931263
game-dev
0.925683
1
0.925683
AkiKurisu/Real-Agents
1,028
Packages/com.kurisu.akibt@fe34111aff/Runtime/Core/Model/BehaviorTreeTemplate.cs
using System.Collections.Generic; using UnityEngine; namespace Kurisu.AkiBT { public class BehaviorTreeTemplate { [SerializeReference] private List<SharedVariable> variables; [SerializeReference] private Root root; public List<SharedVariable> Variables => variables; public Root Root => root; public string TemplateName { get; } #if UNITY_EDITOR [SerializeField] private List<GroupBlockData> blockData = new(); public List<GroupBlockData> BlockData => blockData; #endif public BehaviorTreeTemplate(IBehaviorTree behaviorTree) { TemplateName = behaviorTree._Object.name; variables = new List<SharedVariable>(); foreach (var variable in behaviorTree.SharedVariables) { variables.Add(variable.Clone() as SharedVariable); } #if UNITY_EDITOR blockData = behaviorTree.BlockData; #endif root = behaviorTree.Root; } } }
0
0.762898
1
0.762898
game-dev
MEDIA
0.699539
game-dev
0.847843
1
0.847843
OvercastNetwork/SportBukkit
3,879
snapshot/Bukkit/src/main/java/org/bukkit/command/defaults/ClearCommand.java
package org.bukkit.command.defaults; import com.google.common.collect.ImmutableList; import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; import java.util.ArrayList; import java.util.Collections; import java.util.List; @Deprecated public class ClearCommand extends VanillaCommand { private static List<String> materials; static { ArrayList<String> materialList = new ArrayList<String>(); for (Material material : Material.values()) { materialList.add(material.name()); } Collections.sort(materialList); materials = ImmutableList.copyOf(materialList); } public ClearCommand() { super("clear"); this.description = "Clears the player's inventory. Can specify item and data filters too."; this.usageMessage = "/clear <player> [item] [data]"; this.setPermission("bukkit.command.clear"); } @Override public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) return true; Player player = null; if (args.length > 0) { player = Bukkit.getPlayer(args[0]); } else if (sender instanceof Player) { player = (Player) sender; } if (player != null) { int id; if (args.length > 1 && !(args[1].equals("-1"))) { Material material = Material.matchMaterial(args[1]); if (material == null) { sender.sendMessage(ChatColor.RED + "There's no item called " + args[1]); return false; } id = material.getId(); } else { id = -1; } int data = args.length >= 3 ? getInteger(sender, args[2], 0) : -1; int count = player.getInventory().clear(id, data); Command.broadcastCommandMessage(sender, "Cleared the inventory of " + player.getDisplayName() + ", removing " + count + " items"); } else if (args.length == 0) { sender.sendMessage(ChatColor.RED + "Please provide a player!"); } else { sender.sendMessage(ChatColor.RED + "Can't find player " + args[0]); } return true; } @Override public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { Validate.notNull(sender, "Sender cannot be null"); Validate.notNull(args, "Arguments cannot be null"); Validate.notNull(alias, "Alias cannot be null"); if (args.length == 1) { return super.tabComplete(sender, alias, args); } if (args.length == 2) { final String arg = args[1]; final List<String> materials = ClearCommand.materials; List<String> completion = null; final int size = materials.size(); int i = Collections.binarySearch(materials, arg, String.CASE_INSENSITIVE_ORDER); if (i < 0) { // Insertion (start) index i = -1 - i; } for ( ; i < size; i++) { String material = materials.get(i); if (StringUtil.startsWithIgnoreCase(material, arg)) { if (completion == null) { completion = new ArrayList<String>(); } completion.add(material); } else { break; } } if (completion != null) { return completion; } } return ImmutableList.of(); } }
0
0.83088
1
0.83088
game-dev
MEDIA
0.851041
game-dev
0.815116
1
0.815116
gansm/finalcut
3,121
final/menu/fcheckmenuitem.cpp
/*********************************************************************** * fcheckmenuitem.cpp - Widget FCheckMenuItem * * * * This file is part of the FINAL CUT widget toolkit * * * * Copyright 2015-2021 Markus Gans * * * * FINAL CUT 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. * * * * FINAL CUT 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, see * * <http://www.gnu.org/licenses/>. * ***********************************************************************/ #include "final/fc.h" #include "final/menu/fcheckmenuitem.h" #include "final/menu/fmenu.h" namespace finalcut { //---------------------------------------------------------------------- // class FCheckMenuItem //---------------------------------------------------------------------- // constructor and destructor //---------------------------------------------------------------------- FCheckMenuItem::FCheckMenuItem (FWidget* parent) : FMenuItem{parent} { init(); } //---------------------------------------------------------------------- FCheckMenuItem::FCheckMenuItem (FString&& txt, FWidget* parent) : FMenuItem{std::move(txt), parent} { init(); } //---------------------------------------------------------------------- FCheckMenuItem::~FCheckMenuItem() noexcept = default; // destructor // private methods of FCheckMenuItem //---------------------------------------------------------------------- void FCheckMenuItem::init() { setCheckable(); const auto& parent = getParentWidget(); if ( ! parent ) return; if ( isMenu(parent) ) // Parent is menu { auto menu_ptr = static_cast<FMenu*>(parent); menu_ptr->has_checkable_items = true; } } //---------------------------------------------------------------------- void FCheckMenuItem::processToggle() const { emitCallback("toggled"); } //---------------------------------------------------------------------- void FCheckMenuItem::processClicked() { if ( isChecked() ) unsetChecked(); else setChecked(); processToggle(); emitCallback("clicked"); } } // namespace finalcut
0
0.624457
1
0.624457
game-dev
MEDIA
0.516376
game-dev
0.886506
1
0.886506
pknu-wap/OverClean
5,880
Assets/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUtils.cs
// Author: Daniele Giardini - http://www.demigiant.com // Created: 2018/07/13 using System; using System.Reflection; using UnityEngine; using DG.Tweening.Core; using DG.Tweening.Plugins.Core.PathCore; using DG.Tweening.Plugins.Options; #pragma warning disable 1591 namespace DG.Tweening { /// <summary> /// Utility functions that deal with available Modules. /// Modules defines: /// - DOTAUDIO /// - DOTPHYSICS /// - DOTPHYSICS2D /// - DOTSPRITE /// - DOTUI /// Extra defines set and used for implementation of external assets: /// - DOTWEEN_TMP ► TextMesh Pro /// - DOTWEEN_TK2D ► 2D Toolkit /// </summary> public static class DOTweenModuleUtils { static bool _initialized; #region Reflection /// <summary> /// Called via Reflection by DOTweenComponent on Awake /// </summary> #if UNITY_2018_1_OR_NEWER [UnityEngine.Scripting.Preserve] #endif public static void Init() { if (_initialized) return; _initialized = true; DOTweenExternalCommand.SetOrientationOnPath += Physics.SetOrientationOnPath; #if UNITY_EDITOR #if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1 UnityEditor.EditorApplication.playmodeStateChanged += PlaymodeStateChanged; #else UnityEditor.EditorApplication.playModeStateChanged += PlaymodeStateChanged; #endif #endif } #if UNITY_2018_1_OR_NEWER #pragma warning disable [UnityEngine.Scripting.Preserve] // Just used to preserve methods when building, never called static void Preserver() { Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); MethodInfo mi = typeof(MonoBehaviour).GetMethod("Stub"); } #pragma warning restore #endif #endregion #if UNITY_EDITOR // Fires OnApplicationPause in DOTweenComponent even when Editor is paused (otherwise it's only fired at runtime) #if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1 static void PlaymodeStateChanged() #else static void PlaymodeStateChanged(UnityEditor.PlayModeStateChange state) #endif { if (DOTween.instance == null) return; DOTween.instance.OnApplicationPause(UnityEditor.EditorApplication.isPaused); } #endif // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ // ███ INTERNAL CLASSES ████████████████████████████████████████████████████████████████████████████████████████████████ // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ public static class Physics { // Called via DOTweenExternalCommand callback public static void SetOrientationOnPath(PathOptions options, Tween t, Quaternion newRot, Transform trans) { #if true // PHYSICS_MARKER if (options.isRigidbody) ((Rigidbody)t.target).rotation = newRot; else trans.rotation = newRot; #else trans.rotation = newRot; #endif } // Returns FALSE if the DOTween's Physics2D Module is disabled, or if there's no Rigidbody2D attached public static bool HasRigidbody2D(Component target) { #if true // PHYSICS2D_MARKER return target.GetComponent<Rigidbody2D>() != null; #else return false; #endif } #region Called via Reflection // Called via Reflection by DOTweenPathInspector // Returns FALSE if the DOTween's Physics Module is disabled, or if there's no rigidbody attached #if UNITY_2018_1_OR_NEWER [UnityEngine.Scripting.Preserve] #endif public static bool HasRigidbody(Component target) { #if true // PHYSICS_MARKER return target.GetComponent<Rigidbody>() != null; #else return false; #endif } // Called via Reflection by DOTweenPath #if UNITY_2018_1_OR_NEWER [UnityEngine.Scripting.Preserve] #endif public static TweenerCore<Vector3, Path, PathOptions> CreateDOTweenPathTween( MonoBehaviour target, bool tweenRigidbody, bool isLocal, Path path, float duration, PathMode pathMode ){ TweenerCore<Vector3, Path, PathOptions> t = null; bool rBodyFoundAndTweened = false; #if true // PHYSICS_MARKER if (tweenRigidbody) { Rigidbody rBody = target.GetComponent<Rigidbody>(); if (rBody != null) { rBodyFoundAndTweened = true; t = isLocal ? rBody.DOLocalPath(path, duration, pathMode) : rBody.DOPath(path, duration, pathMode); } } #endif #if true // PHYSICS2D_MARKER if (!rBodyFoundAndTweened && tweenRigidbody) { Rigidbody2D rBody2D = target.GetComponent<Rigidbody2D>(); if (rBody2D != null) { rBodyFoundAndTweened = true; t = isLocal ? rBody2D.DOLocalPath(path, duration, pathMode) : rBody2D.DOPath(path, duration, pathMode); } } #endif if (!rBodyFoundAndTweened) { t = isLocal ? target.transform.DOLocalPath(path, duration, pathMode) : target.transform.DOPath(path, duration, pathMode); } return t; } #endregion } } }
0
0.85663
1
0.85663
game-dev
MEDIA
0.969353
game-dev
0.932024
1
0.932024
Chainfire/android-ndk-compression-tools
20,919
bzip2/decompress.c
/*-------------------------------------------------------------*/ /*--- Decompression machinery ---*/ /*--- decompress.c ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #include "bzlib_private.h" /*---------------------------------------------------*/ static void makeMaps_d ( DState* s ) { Int32 i; s->nInUse = 0; for (i = 0; i < 256; i++) if (s->inUse[i]) { s->seqToUnseq[s->nInUse] = i; s->nInUse++; } } /*---------------------------------------------------*/ #define RETURN(rrr) \ { retVal = rrr; goto save_state_and_return; }; #define GET_BITS(lll,vvv,nnn) \ case lll: s->state = lll; \ while (True) { \ if (s->bsLive >= nnn) { \ UInt32 v; \ v = (s->bsBuff >> \ (s->bsLive-nnn)) & ((1 << nnn)-1); \ s->bsLive -= nnn; \ vvv = v; \ break; \ } \ if (s->strm->avail_in == 0) RETURN(BZ_OK); \ s->bsBuff \ = (s->bsBuff << 8) | \ ((UInt32) \ (*((UChar*)(s->strm->next_in)))); \ s->bsLive += 8; \ s->strm->next_in++; \ s->strm->avail_in--; \ s->strm->total_in_lo32++; \ if (s->strm->total_in_lo32 == 0) \ s->strm->total_in_hi32++; \ } #define GET_UCHAR(lll,uuu) \ GET_BITS(lll,uuu,8) #define GET_BIT(lll,uuu) \ GET_BITS(lll,uuu,1) /*---------------------------------------------------*/ #define GET_MTF_VAL(label1,label2,lval) \ { \ if (groupPos == 0) { \ groupNo++; \ if (groupNo >= nSelectors) \ RETURN(BZ_DATA_ERROR); \ groupPos = BZ_G_SIZE; \ gSel = s->selector[groupNo]; \ gMinlen = s->minLens[gSel]; \ gLimit = &(s->limit[gSel][0]); \ gPerm = &(s->perm[gSel][0]); \ gBase = &(s->base[gSel][0]); \ } \ groupPos--; \ zn = gMinlen; \ GET_BITS(label1, zvec, zn); \ while (1) { \ if (zn > 20 /* the longest code */) \ RETURN(BZ_DATA_ERROR); \ if (zvec <= gLimit[zn]) break; \ zn++; \ GET_BIT(label2, zj); \ zvec = (zvec << 1) | zj; \ }; \ if (zvec - gBase[zn] < 0 \ || zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \ RETURN(BZ_DATA_ERROR); \ lval = gPerm[zvec - gBase[zn]]; \ } /*---------------------------------------------------*/ Int32 BZ2_decompress ( DState* s ) { UChar uc; Int32 retVal; Int32 minLen, maxLen; bz_stream* strm = s->strm; /* stuff that needs to be saved/restored */ Int32 i; Int32 j; Int32 t; Int32 alphaSize; Int32 nGroups; Int32 nSelectors; Int32 EOB; Int32 groupNo; Int32 groupPos; Int32 nextSym; Int32 nblockMAX; Int32 nblock; Int32 es; Int32 N; Int32 curr; Int32 zt; Int32 zn; Int32 zvec; Int32 zj; Int32 gSel; Int32 gMinlen; Int32* gLimit; Int32* gBase; Int32* gPerm; if (s->state == BZ_X_MAGIC_1) { /*initialise the save area*/ s->save_i = 0; s->save_j = 0; s->save_t = 0; s->save_alphaSize = 0; s->save_nGroups = 0; s->save_nSelectors = 0; s->save_EOB = 0; s->save_groupNo = 0; s->save_groupPos = 0; s->save_nextSym = 0; s->save_nblockMAX = 0; s->save_nblock = 0; s->save_es = 0; s->save_N = 0; s->save_curr = 0; s->save_zt = 0; s->save_zn = 0; s->save_zvec = 0; s->save_zj = 0; s->save_gSel = 0; s->save_gMinlen = 0; s->save_gLimit = NULL; s->save_gBase = NULL; s->save_gPerm = NULL; } /*restore from the save area*/ i = s->save_i; j = s->save_j; t = s->save_t; alphaSize = s->save_alphaSize; nGroups = s->save_nGroups; nSelectors = s->save_nSelectors; EOB = s->save_EOB; groupNo = s->save_groupNo; groupPos = s->save_groupPos; nextSym = s->save_nextSym; nblockMAX = s->save_nblockMAX; nblock = s->save_nblock; es = s->save_es; N = s->save_N; curr = s->save_curr; zt = s->save_zt; zn = s->save_zn; zvec = s->save_zvec; zj = s->save_zj; gSel = s->save_gSel; gMinlen = s->save_gMinlen; gLimit = s->save_gLimit; gBase = s->save_gBase; gPerm = s->save_gPerm; retVal = BZ_OK; switch (s->state) { GET_UCHAR(BZ_X_MAGIC_1, uc); if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_2, uc); if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_3, uc) if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) if (s->blockSize100k < (BZ_HDR_0 + 1) || s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); s->blockSize100k -= BZ_HDR_0; if (s->smallDecompress) { s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); s->ll4 = BZALLOC( ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) ); if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); } else { s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); if (s->tt == NULL) RETURN(BZ_MEM_ERROR); } GET_UCHAR(BZ_X_BLKHDR_1, uc); if (uc == 0x17) goto endhdr_2; if (uc != 0x31) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_2, uc); if (uc != 0x41) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_3, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_4, uc); if (uc != 0x26) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_5, uc); if (uc != 0x53) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_6, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); s->currBlockNo++; if (s->verbosity >= 2) VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); s->storedBlockCRC = 0; GET_UCHAR(BZ_X_BCRC_1, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_2, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_3, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_4, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); s->origPtr = 0; GET_UCHAR(BZ_X_ORIGPTR_1, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_2, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_3, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); if (s->origPtr < 0) RETURN(BZ_DATA_ERROR); if (s->origPtr > 10 + 100000*s->blockSize100k) RETURN(BZ_DATA_ERROR); /*--- Receive the mapping table ---*/ for (i = 0; i < 16; i++) { GET_BIT(BZ_X_MAPPING_1, uc); if (uc == 1) s->inUse16[i] = True; else s->inUse16[i] = False; } for (i = 0; i < 256; i++) s->inUse[i] = False; for (i = 0; i < 16; i++) if (s->inUse16[i]) for (j = 0; j < 16; j++) { GET_BIT(BZ_X_MAPPING_2, uc); if (uc == 1) s->inUse[i * 16 + j] = True; } makeMaps_d ( s ); if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); alphaSize = s->nInUse+2; /*--- Now the selectors ---*/ GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR); GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); if (nSelectors < 1) RETURN(BZ_DATA_ERROR); for (i = 0; i < nSelectors; i++) { j = 0; while (True) { GET_BIT(BZ_X_SELECTOR_3, uc); if (uc == 0) break; j++; if (j >= nGroups) RETURN(BZ_DATA_ERROR); } s->selectorMtf[i] = j; } /*--- Undo the MTF values for the selectors. ---*/ { UChar pos[BZ_N_GROUPS], tmp, v; for (v = 0; v < nGroups; v++) pos[v] = v; for (i = 0; i < nSelectors; i++) { v = s->selectorMtf[i]; tmp = pos[v]; while (v > 0) { pos[v] = pos[v-1]; v--; } pos[0] = tmp; s->selector[i] = tmp; } } /*--- Now the coding tables ---*/ for (t = 0; t < nGroups; t++) { GET_BITS(BZ_X_CODING_1, curr, 5); for (i = 0; i < alphaSize; i++) { while (True) { if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); GET_BIT(BZ_X_CODING_2, uc); if (uc == 0) break; GET_BIT(BZ_X_CODING_3, uc); if (uc == 0) curr++; else curr--; } s->len[t][i] = curr; } } /*--- Create the Huffman decoding tables ---*/ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; if (s->len[t][i] < minLen) minLen = s->len[t][i]; } BZ2_hbCreateDecodeTables ( &(s->limit[t][0]), &(s->base[t][0]), &(s->perm[t][0]), &(s->len[t][0]), minLen, maxLen, alphaSize ); s->minLens[t] = minLen; } /*--- Now the MTF values ---*/ EOB = s->nInUse+1; nblockMAX = 100000 * s->blockSize100k; groupNo = -1; groupPos = 0; for (i = 0; i <= 255; i++) s->unzftab[i] = 0; /*-- MTF init --*/ { Int32 ii, jj, kk; kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); kk--; } s->mtfbase[ii] = kk + 1; } } /*-- end MTF init --*/ nblock = 0; GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); while (True) { if (nextSym == EOB) break; if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { es = -1; N = 1; do { /* Check that N doesn't get too big, so that es doesn't go negative. The maximum value that can be RUNA/RUNB encoded is equal to the block size (post the initial RLE), viz, 900k, so bounding N at 2 million should guard against overflow without rejecting any legitimate inputs. */ if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR); if (nextSym == BZ_RUNA) es = es + (0+1) * N; else if (nextSym == BZ_RUNB) es = es + (1+1) * N; N = N * 2; GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); } while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); es++; uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; s->unzftab[uc] += es; if (s->smallDecompress) while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->ll16[nblock] = (UInt16)uc; nblock++; es--; } else while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->tt[nblock] = (UInt32)uc; nblock++; es--; }; continue; } else { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); /*-- uc = MTF ( nextSym-1 ) --*/ { Int32 ii, jj, kk, pp, lno, off; UInt32 nn; nn = (UInt32)(nextSym - 1); if (nn < MTFL_SIZE) { /* avoid general-case expense */ pp = s->mtfbase[0]; uc = s->mtfa[pp+nn]; while (nn > 3) { Int32 z = pp+nn; s->mtfa[(z) ] = s->mtfa[(z)-1]; s->mtfa[(z)-1] = s->mtfa[(z)-2]; s->mtfa[(z)-2] = s->mtfa[(z)-3]; s->mtfa[(z)-3] = s->mtfa[(z)-4]; nn -= 4; } while (nn > 0) { s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; }; s->mtfa[pp] = uc; } else { /* general case */ lno = nn / MTFL_SIZE; off = nn % MTFL_SIZE; pp = s->mtfbase[lno] + off; uc = s->mtfa[pp]; while (pp > s->mtfbase[lno]) { s->mtfa[pp] = s->mtfa[pp-1]; pp--; }; s->mtfbase[lno]++; while (lno > 0) { s->mtfbase[lno]--; s->mtfa[s->mtfbase[lno]] = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; lno--; } s->mtfbase[0]--; s->mtfa[s->mtfbase[0]] = uc; if (s->mtfbase[0] == 0) { kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; kk--; } s->mtfbase[ii] = kk + 1; } } } } /*-- end uc = MTF ( nextSym-1 ) --*/ s->unzftab[s->seqToUnseq[uc]]++; if (s->smallDecompress) s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); nblock++; GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); continue; } } /* Now we know what nblock is, we can do a better sanity check on s->origPtr. */ if (s->origPtr < 0 || s->origPtr >= nblock) RETURN(BZ_DATA_ERROR); /*-- Set up cftab to facilitate generation of T^(-1) --*/ /* Check: unzftab entries in range. */ for (i = 0; i <= 255; i++) { if (s->unzftab[i] < 0 || s->unzftab[i] > nblock) RETURN(BZ_DATA_ERROR); } /* Actually generate cftab. */ s->cftab[0] = 0; for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; /* Check: cftab entries in range. */ for (i = 0; i <= 256; i++) { if (s->cftab[i] < 0 || s->cftab[i] > nblock) { /* s->cftab[i] can legitimately be == nblock */ RETURN(BZ_DATA_ERROR); } } /* Check: cftab entries non-descending. */ for (i = 1; i <= 256; i++) { if (s->cftab[i-1] > s->cftab[i]) { RETURN(BZ_DATA_ERROR); } } s->state_out_len = 0; s->state_out_ch = 0; BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); s->state = BZ_X_OUTPUT; if (s->verbosity >= 2) VPrintf0 ( "rt+rld" ); if (s->smallDecompress) { /*-- Make a copy of cftab, used in generation of T --*/ for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; /*-- compute the T vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->ll16[i]); SET_LL(i, s->cftabCopy[uc]); s->cftabCopy[uc]++; } /*-- Compute T^(-1) by pointer reversal on T --*/ i = s->origPtr; j = GET_LL(i); do { Int32 tmp = GET_LL(j); SET_LL(j, i); i = j; j = tmp; } while (i != s->origPtr); s->tPos = s->origPtr; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_SMALL(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_SMALL(s->k0); s->nblock_used++; } } else { /*-- compute the T^(-1) vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->tt[i] & 0xff); s->tt[s->cftab[uc]] |= (i << 8); s->cftab[uc]++; } s->tPos = s->tt[s->origPtr] >> 8; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_FAST(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_FAST(s->k0); s->nblock_used++; } } RETURN(BZ_OK); endhdr_2: GET_UCHAR(BZ_X_ENDHDR_2, uc); if (uc != 0x72) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_3, uc); if (uc != 0x45) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_4, uc); if (uc != 0x38) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_5, uc); if (uc != 0x50) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_6, uc); if (uc != 0x90) RETURN(BZ_DATA_ERROR); s->storedCombinedCRC = 0; GET_UCHAR(BZ_X_CCRC_1, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_2, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_3, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_4, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); s->state = BZ_X_IDLE; RETURN(BZ_STREAM_END); default: AssertH ( False, 4001 ); } AssertH ( False, 4002 ); save_state_and_return: s->save_i = i; s->save_j = j; s->save_t = t; s->save_alphaSize = alphaSize; s->save_nGroups = nGroups; s->save_nSelectors = nSelectors; s->save_EOB = EOB; s->save_groupNo = groupNo; s->save_groupPos = groupPos; s->save_nextSym = nextSym; s->save_nblockMAX = nblockMAX; s->save_nblock = nblock; s->save_es = es; s->save_N = N; s->save_curr = curr; s->save_zt = zt; s->save_zn = zn; s->save_zvec = zvec; s->save_zj = zj; s->save_gSel = gSel; s->save_gMinlen = gMinlen; s->save_gLimit = gLimit; s->save_gBase = gBase; s->save_gPerm = gPerm; return retVal; } /*-------------------------------------------------------------*/ /*--- end decompress.c ---*/ /*-------------------------------------------------------------*/
0
0.99788
1
0.99788
game-dev
MEDIA
0.188514
game-dev
0.999774
1
0.999774
oot-pc-port/oot-pc-port
8,589
asm/non_matchings/overlays/actors/ovl_En_GeldB/func_80A36830.s
glabel func_80A36830 /* 01520 80A36830 27BDFFE0 */ addiu $sp, $sp, 0xFFE0 ## $sp = FFFFFFE0 /* 01524 80A36834 AFB00018 */ sw $s0, 0x0018($sp) /* 01528 80A36838 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000 /* 0152C 80A3683C AFBF001C */ sw $ra, 0x001C($sp) /* 01530 80A36840 AFA50024 */ sw $a1, 0x0024($sp) /* 01534 80A36844 00A02025 */ or $a0, $a1, $zero ## $a0 = 00000000 /* 01538 80A36848 0C28E78B */ jal func_80A39E2C /* 0153C 80A3684C 02002825 */ or $a1, $s0, $zero ## $a1 = 00000000 /* 01540 80A36850 1440006A */ bne $v0, $zero, .L80A369FC /* 01544 80A36854 8FA40024 */ lw $a0, 0x0024($sp) /* 01548 80A36858 02002825 */ or $a1, $s0, $zero ## $a1 = 00000000 /* 0154C 80A3685C 0C28D567 */ jal func_80A3559C /* 01550 80A36860 00003025 */ or $a2, $zero, $zero ## $a2 = 00000000 /* 01554 80A36864 54400066 */ bnel $v0, $zero, .L80A36A00 /* 01558 80A36868 8FBF001C */ lw $ra, 0x001C($sp) /* 0155C 80A3686C 860400B6 */ lh $a0, 0x00B6($s0) ## 000000B6 /* 01560 80A36870 860E008A */ lh $t6, 0x008A($s0) ## 0000008A /* 01564 80A36874 01C41023 */ subu $v0, $t6, $a0 /* 01568 80A36878 00021400 */ sll $v0, $v0, 16 /* 0156C 80A3687C 00021403 */ sra $v0, $v0, 16 /* 01570 80A36880 58400010 */ blezl $v0, .L80A368C4 /* 01574 80A36884 44823000 */ mtc1 $v0, $f6 ## $f6 = 0.00 /* 01578 80A36888 44822000 */ mtc1 $v0, $f4 ## $f4 = 0.00 /* 0157C 80A3688C 3C013E80 */ lui $at, 0x3E80 ## $at = 3E800000 /* 01580 80A36890 44814000 */ mtc1 $at, $f8 ## $f8 = 0.25 /* 01584 80A36894 468021A0 */ cvt.s.w $f6, $f4 /* 01588 80A36898 3C0144FA */ lui $at, 0x44FA ## $at = 44FA0000 /* 0158C 80A3689C 44818000 */ mtc1 $at, $f16 ## $f16 = 2000.00 /* 01590 80A368A0 46083282 */ mul.s $f10, $f6, $f8 /* 01594 80A368A4 46105480 */ add.s $f18, $f10, $f16 /* 01598 80A368A8 4600910D */ trunc.w.s $f4, $f18 /* 0159C 80A368AC 44032000 */ mfc1 $v1, $f4 /* 015A0 80A368B0 00000000 */ nop /* 015A4 80A368B4 00031C00 */ sll $v1, $v1, 16 /* 015A8 80A368B8 1000000E */ beq $zero, $zero, .L80A368F4 /* 015AC 80A368BC 00031C03 */ sra $v1, $v1, 16 /* 015B0 80A368C0 44823000 */ mtc1 $v0, $f6 ## $f6 = 0.00 .L80A368C4: /* 015B4 80A368C4 3C013E80 */ lui $at, 0x3E80 ## $at = 3E800000 /* 015B8 80A368C8 44815000 */ mtc1 $at, $f10 ## $f10 = 0.25 /* 015BC 80A368CC 46803220 */ cvt.s.w $f8, $f6 /* 015C0 80A368D0 3C0144FA */ lui $at, 0x44FA ## $at = 44FA0000 /* 015C4 80A368D4 44819000 */ mtc1 $at, $f18 ## $f18 = 2000.00 /* 015C8 80A368D8 460A4402 */ mul.s $f16, $f8, $f10 /* 015CC 80A368DC 46128101 */ sub.s $f4, $f16, $f18 /* 015D0 80A368E0 4600218D */ trunc.w.s $f6, $f4 /* 015D4 80A368E4 44033000 */ mfc1 $v1, $f6 /* 015D8 80A368E8 00000000 */ nop /* 015DC 80A368EC 00031C00 */ sll $v1, $v1, 16 /* 015E0 80A368F0 00031C03 */ sra $v1, $v1, 16 .L80A368F4: /* 015E4 80A368F4 0083C821 */ addu $t9, $a0, $v1 /* 015E8 80A368F8 A61900B6 */ sh $t9, 0x00B6($s0) ## 000000B6 /* 015EC 80A368FC 860800B6 */ lh $t0, 0x00B6($s0) ## 000000B6 /* 015F0 80A36900 26040188 */ addiu $a0, $s0, 0x0188 ## $a0 = 00000188 /* 015F4 80A36904 1840000F */ blez $v0, .L80A36944 /* 015F8 80A36908 A6080032 */ sh $t0, 0x0032($s0) ## 00000032 /* 015FC 80A3690C 44834000 */ mtc1 $v1, $f8 ## $f8 = 0.00 /* 01600 80A36910 3C013F80 */ lui $at, 0x3F80 ## $at = 3F800000 /* 01604 80A36914 44816000 */ mtc1 $at, $f12 ## $f12 = 1.00 /* 01608 80A36918 468042A0 */ cvt.s.w $f10, $f8 /* 0160C 80A3691C 3C013F00 */ lui $at, 0x3F00 ## $at = 3F000000 /* 01610 80A36920 44818000 */ mtc1 $at, $f16 ## $f16 = 0.50 /* 01614 80A36924 00000000 */ nop /* 01618 80A36928 46105082 */ mul.s $f2, $f10, $f16 /* 0161C 80A3692C 4602603C */ c.lt.s $f12, $f2 /* 01620 80A36930 00000000 */ nop /* 01624 80A36934 45020011 */ bc1fl .L80A3697C /* 01628 80A36938 46001207 */ neg.s $f8, $f2 /* 0162C 80A3693C 1000000E */ beq $zero, $zero, .L80A36978 /* 01630 80A36940 46006086 */ mov.s $f2, $f12 .L80A36944: /* 01634 80A36944 44839000 */ mtc1 $v1, $f18 ## $f18 = 0.00 /* 01638 80A36948 3C01BF80 */ lui $at, 0xBF80 ## $at = BF800000 /* 0163C 80A3694C 44816000 */ mtc1 $at, $f12 ## $f12 = -1.00 /* 01640 80A36950 46809120 */ cvt.s.w $f4, $f18 /* 01644 80A36954 3C013F00 */ lui $at, 0x3F00 ## $at = 3F000000 /* 01648 80A36958 44813000 */ mtc1 $at, $f6 ## $f6 = 0.50 /* 0164C 80A3695C 00000000 */ nop /* 01650 80A36960 46062082 */ mul.s $f2, $f4, $f6 /* 01654 80A36964 460C103C */ c.lt.s $f2, $f12 /* 01658 80A36968 00000000 */ nop /* 0165C 80A3696C 45020003 */ bc1fl .L80A3697C /* 01660 80A36970 46001207 */ neg.s $f8, $f2 /* 01664 80A36974 46006086 */ mov.s $f2, $f12 .L80A36978: /* 01668 80A36978 46001207 */ neg.s $f8, $f2 .L80A3697C: /* 0166C 80A3697C 0C02927F */ jal SkelAnime_FrameUpdateMatrix /* 01670 80A36980 E60801A4 */ swc1 $f8, 0x01A4($s0) ## 000001A4 /* 01674 80A36984 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 01678 80A36988 0C00B821 */ jal func_8002E084 /* 0167C 80A3698C 24051555 */ addiu $a1, $zero, 0x1555 ## $a1 = 00001555 /* 01680 80A36990 50400011 */ beql $v0, $zero, .L80A369D8 /* 01684 80A36994 8FA90024 */ lw $t1, 0x0024($sp) /* 01688 80A36998 0C03F66B */ jal Math_Rand_ZeroOne ## Rand.Next() float /* 0168C 80A3699C 00000000 */ nop /* 01690 80A369A0 3C0180A4 */ lui $at, %hi(D_80A3A230) ## $at = 80A40000 /* 01694 80A369A4 C42AA230 */ lwc1 $f10, %lo(D_80A3A230)($at) /* 01698 80A369A8 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 0169C 80A369AC 4600503C */ c.lt.s $f10, $f0 /* 016A0 80A369B0 00000000 */ nop /* 016A4 80A369B4 45000005 */ bc1f .L80A369CC /* 016A8 80A369B8 00000000 */ nop /* 016AC 80A369BC 0C28DA84 */ jal func_80A36A10 /* 016B0 80A369C0 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 016B4 80A369C4 10000004 */ beq $zero, $zero, .L80A369D8 /* 016B8 80A369C8 8FA90024 */ lw $t1, 0x0024($sp) .L80A369CC: /* 016BC 80A369CC 0C28D82C */ jal func_80A360B0 /* 016C0 80A369D0 8FA50024 */ lw $a1, 0x0024($sp) /* 016C4 80A369D4 8FA90024 */ lw $t1, 0x0024($sp) .L80A369D8: /* 016C8 80A369D8 3C0A0001 */ lui $t2, 0x0001 ## $t2 = 00010000 /* 016CC 80A369DC 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 016D0 80A369E0 01495021 */ addu $t2, $t2, $t1 /* 016D4 80A369E4 8D4A1DE4 */ lw $t2, 0x1DE4($t2) ## 00011DE4 /* 016D8 80A369E8 314B005F */ andi $t3, $t2, 0x005F ## $t3 = 00000000 /* 016DC 80A369EC 55600004 */ bnel $t3, $zero, .L80A36A00 /* 016E0 80A369F0 8FBF001C */ lw $ra, 0x001C($sp) /* 016E4 80A369F4 0C00BE0A */ jal Audio_PlayActorSound2 /* 016E8 80A369F8 240539C6 */ addiu $a1, $zero, 0x39C6 ## $a1 = 000039C6 .L80A369FC: /* 016EC 80A369FC 8FBF001C */ lw $ra, 0x001C($sp) .L80A36A00: /* 016F0 80A36A00 8FB00018 */ lw $s0, 0x0018($sp) /* 016F4 80A36A04 27BD0020 */ addiu $sp, $sp, 0x0020 ## $sp = 00000000 /* 016F8 80A36A08 03E00008 */ jr $ra /* 016FC 80A36A0C 00000000 */ nop
0
0.645859
1
0.645859
game-dev
MEDIA
0.986585
game-dev
0.728267
1
0.728267
ihmcrobotics/ihmc-open-robotics-software
1,400
simulation-construction-set-tools/src/main/java/us/ihmc/simulationConstructionSetTools/joystick/BooleanYoVariableJoystickEventListener.java
package us.ihmc.simulationConstructionSetTools.joystick; import net.java.games.input.Component; import net.java.games.input.Event; import us.ihmc.yoVariables.variable.YoBoolean; import us.ihmc.tools.inputDevices.joystick.JoystickEventListener; public class BooleanYoVariableJoystickEventListener implements JoystickEventListener { private final YoBoolean variable; private final Component component; private final boolean flip; private final boolean toggle; public BooleanYoVariableJoystickEventListener(YoBoolean variable, Component component, boolean toggle) { this(variable, component, toggle, false); } public BooleanYoVariableJoystickEventListener(YoBoolean variable, Component component, boolean toggle, boolean flip) { if (component.isAnalog()) throw new RuntimeException("component is analog; should be digital (i.e. an on/off button)"); this.variable = variable; this.component = component; this.flip = flip; this.toggle=toggle; } @Override public void processEvent(Event event) { if (event.getComponent() == component) { boolean value = event.getValue() == 1.0f; if(toggle) { if(value) variable.set(!variable.getBooleanValue()); } else { variable.set(value ^ flip); } } } }
0
0.800836
1
0.800836
game-dev
MEDIA
0.755758
game-dev
0.892075
1
0.892075
Citadel-Station-13/Citadel-Station-13
3,485
code/modules/mob/login.dm
/** * Run when a client is put in this mob or reconnets to byond and their client was on this mob * * Things it does: * * Adds player to player_list * * sets lastKnownIP * * sets computer_id * * logs the login * * tells the world to update it's status (for player count) * * create mob huds for the mob if needed * * reset next_move to 1 * * parent call * * if the client exists set the perspective to the mob loc * * call on_log on the loc (sigh) * * reload the huds for the mob * * reload all full screen huds attached to this mob * * load any global alternate apperances * * sync the mind datum via sync_mind() * * call any client login callbacks that exist * * grant any actions the mob has to the client * * calls [auto_deadmin_on_login](mob.html#proc/auto_deadmin_on_login) * * send signal COMSIG_MOB_CLIENT_LOGIN * * attaches the ash listener element so clients can hear weather * client can be deleted mid-execution of this proc, chiefly on parent calls, with lag */ /mob/Login() if(!client) return FALSE add_to_player_list() lastKnownIP = client.address computer_id = client.computer_id log_access("Mob Login: [key_name(src)] was assigned to a [type]") world.update_status() client.screen = list() //remove hud items just in case client.images = list() if(!hud_used) create_mob_hud() if(hud_used) hud_used.show_hud(hud_used.hud_version) hud_used.update_ui_style(ui_style2icon(client.prefs.UI_style)) . = ..() if(!client) return FALSE // SEND_SIGNAL(src, COMSIG_MOB_LOGIN) if (key != client.key) key = client.key reset_perspective(loc) if(loc) loc.on_log(TRUE) //readd this mob's HUDs (antag, med, etc) reload_huds() sync_mind() //Reload alternate appearances for(var/v in GLOB.active_alternate_appearances) if(!v) continue var/datum/atom_hud/alternate_appearance/AA = v AA.onNewMob(src) update_client_colour() update_mouse_pointer() if(client) client.view_size?.resetToDefault() if(client.player_details && istype(client.player_details)) if(client.player_details.player_actions.len) for(var/datum/action/A in client.player_details.player_actions) A.Grant(src) for(var/foo in client.player_details.post_login_callbacks) var/datum/callback/CB = foo CB.Invoke() auto_deadmin_on_login() mind?.hide_ckey = client?.prefs?.hide_ckey log_message("Client [key_name(src)] has taken ownership of mob [src]([src.type])", LOG_OWNERSHIP) SEND_SIGNAL(src, COMSIG_MOB_CLIENT_LOGIN, client) client.init_verbs() if(has_field_of_vision && CONFIG_GET(flag/use_field_of_vision)) LoadComponent(/datum/component/field_of_vision, field_of_vision_type) // load rendering reload_rendering() AddElement(/datum/element/weather_listener, /datum/weather/ash_storm, ZTRAIT_ASHSTORM, GLOB.ash_storm_sounds) // optimized area sound effects. Enable during events (compile flag when 😳) // AddElement(/datum/element/weather_listener, /datum/weather/long_rain, ZTRAIT_STATION, GLOB.rain_sounds) /mob/proc/auto_deadmin_on_login() //return true if they're not an admin at the end. if(!client?.holder) return TRUE if(CONFIG_GET(flag/auto_deadmin_players) || (client.prefs?.deadmin & DEADMIN_ALWAYS)) return client.holder.auto_deadmin() if(mind.has_antag_datum(/datum/antagonist) && (CONFIG_GET(flag/auto_deadmin_antagonists) || client.prefs?.deadmin & DEADMIN_ANTAGONIST)) return client.holder.auto_deadmin() if(job) return SSjob.handle_auto_deadmin_roles(client, job)
0
0.983054
1
0.983054
game-dev
MEDIA
0.824528
game-dev
0.993903
1
0.993903
trclassic92/tr-lumberjack
9,933
client/menu.lua
local QBCore = exports['qb-core']:GetCoreObject() -- QBCore Menu Configuration if Config.menu == "qbcore" then RegisterNetEvent('tr-lumberjack:client:depo', function() exports['qb-menu']:openMenu({ { header = Lang.depo1, icon = 'fa-solid fa-truck', params = { event = 'tr-lumberjack:client:deliverytruck', } }, { header = string.format(Lang.depo2, Config.workVanPrice), icon = 'fa-solid fa-car', params = { event = 'tr-lumberjack:client:workvan', } }, { header = Lang.depo3, icon = 'fa-solid fa-shop', params = { event = 'tr-lumberjack:client:contractorshop', } }, { header = Lang.depo4, icon = 'fa-solid fa-car', params = { event = 'tr-lumberjack:client:returnworkvan', } }, { header = Lang.depo5, icon = 'fa-solid fa-car', params = { event = 'tr-lumberjack:client:returndeliverytruck', } }, }) end) RegisterNetEvent('tr-lumberjack:client:trailerInteract', function() exports['qb-menu']:openMenu({ { header = Lang.delivery2, icon = 'fa-solid fa-trailer', params = { event = 'tr-lumberjack:client:loadtrailer', } }, { header = Lang.delivery3, icon = 'fa-solid fa-truck', params = { event = 'tr-lumberjack:client:unloadtrailer', } } }) end) RegisterNetEvent('tr-lumberjack:client:crafting', function() if HasPlayerGotChoppedLogs() then exports['qb-menu']:openMenu({ { header = string.format(Lang.craftingMenu, ChoppedLogs), icon = 'fa-solid fa-tree', }, { header = Lang.craftPlanks, txt = Lang.craftPlanksAmount, icon = 'fa-solid fa-gear', params = { event = 'tr-lumberjack:client:craftinginput', args = { number = 1, } } }, { header = Lang.craftHandles, txt = Lang.craftHandlesAmount, icon = 'fa-solid fa-gear', params = { event = 'tr-lumberjack:client:craftinginput', args = { number = 2, } } }, { header = Lang.craftFirewood, txt = Lang.craftFirewoodAmount, icon = 'fa-solid fa-gear', params = { event = 'tr-lumberjack:client:craftinginput', args = { number = 3, } } }, { header = Lang.craftWoodenToySets, txt = Lang.craftWoodenToySetsAmount, icon = 'fa-solid fa-gear', params = { event = 'tr-lumberjack:client:craftinginput', args = { number = 4, } } } }) end end) local function openSellMenu(itemList, eventPrefix) local menuItems = {} for _, item in pairs(itemList) do local itemCount = exports.ox_inventory:Search('count', item.name) local itemAvailable = itemCount > 0 table.insert(menuItems, { header = string.format(item.header, itemCount), icon = 'fa-solid fa-gear', params = { event = eventPrefix .. ':server:sellitem', isServer = true, args = { number = itemCount, itemType = item.name } }, disabled = not itemAvailable }) end exports['qb-menu']:openMenu(menuItems) end RegisterNetEvent('tr-lumberjack:client:sell1', function() openSellMenu({ {name = 'tr_woodplank', header = Lang.sellPlanks}, {name = 'tr_firewood', header = Lang.sellFirewood} }, 'tr-lumberjack') end) RegisterNetEvent('tr-lumberjack:client:sell2', function() openSellMenu({ {name = 'tr_woodhandles', header = Lang.sellHandles}, {name = 'tr_toyset', header = Lang.sellToy} }, 'tr-lumberjack') end) -- Ox Menu Configuration elseif Config.menu == "ox" then RegisterNetEvent('tr-lumberjack:client:depo', function() lib.registerContext({ id = 'lumberjack_depo', title = Lang.interact1, options = { { title = Lang.depo1, event = 'tr-lumberjack:client:deliverytruck', }, { title = string.format(Lang.depo2, Config.workVanPrice), event = 'tr-lumberjack:client:workvan', }, { title = Lang.depo3, event = 'tr-lumberjack:client:contractorshop', }, { title = Lang.depo4, event = 'tr-lumberjack:client:returnworkvan', }, { title = Lang.depo5, event = 'tr-lumberjack:client:returndeliverytruck', }, } }) lib.showContext('lumberjack_depo') end) RegisterNetEvent('tr-lumberjack:client:trailerInteract', function() lib.registerContext({ id = 'lumber_trailer', title = Lang.interact4, options = { { title = Lang.delivery2, event = 'tr-lumberjack:client:loadtrailer', }, { title = Lang.delivery3, event = 'tr-lumberjack:client:unloadtrailer', }, } }) lib.showContext('lumber_trailer') end) RegisterNetEvent('tr-lumberjack:client:crafting', function() if HasPlayerGotChoppedLogs() then lib.registerContext({ id = 'lumberjack_crafting', title = string.format(Lang.craftingMenu, ChoppedLogs), options = { { title = Lang.craftPlanks, description = Lang.craftPlanksAmount, event = 'tr-lumberjack:client:craftinginput', args = { number = 1, } }, { title = Lang.craftHandles, description = Lang.craftHandlesAmount, event = 'tr-lumberjack:client:craftinginput', args = { number = 2, } }, { title = Lang.craftFirewood, description = Lang.craftFirewoodAmount, event = 'tr-lumberjack:client:craftinginput', args = { number = 3, } }, { title = Lang.craftWoodenToySets, description = Lang.craftWoodenToySetsAmount, event = 'tr-lumberjack:client:craftinginput', args = { number = 4, } }, } }) lib.showContext('lumberjack_crafting') end end) local function openSellMenu(itemList, eventPrefix) local menuItems = {} for _, item in pairs(itemList) do local itemCount = exports.ox_inventory:Search('count', item.name) local itemAvailable = itemCount > 0 table.insert(menuItems, { title = string.format(item.header, itemCount), -- Title with item count serverEvent = eventPrefix .. ':server:sellitem', args = { number = itemCount, itemType = item.name }, disabled = not itemAvailable -- Disable if no items available }) end lib.registerContext({ id = 'sell_menu', title = Lang.interact7, options = menuItems }) lib.showContext('sell_menu') end RegisterNetEvent('tr-lumberjack:client:sell1', function() openSellMenu({ {name = 'tr_woodplank', header = Lang.sellPlanks}, {name = 'tr_firewood', header = Lang.sellFirewood} }, 'tr-lumberjack') end) RegisterNetEvent('tr-lumberjack:client:sell2', function() openSellMenu({ {name = 'tr_woodhandles', header = Lang.sellHandles}, {name = 'tr_toyset', header = Lang.sellToy} }, 'tr-lumberjack') end) end
0
0.896199
1
0.896199
game-dev
MEDIA
0.635958
game-dev
0.90787
1
0.90787
eldexterr/ttyd64
39,054
map/src/trd_09.mscr
% Script File: trd_09.mscr % Decoded from: 0 to 52B0 (trd_09) #define .NpcID:BillBlaster_10 0A #define .NpcID:BillBlaster_11 0B #define .NpcID:BillBlaster_12 0C #define .NpcID:BulletBill_20 14 #define .NpcID:BulletBill_21 15 #define .NpcID:BulletBill_22 16 #define .NpcID:BulletBill_23 17 #define .NpcID:BulletBill_24 18 #define .NpcID:BulletBill_25 19 #define .NpcID:BulletBill_26 1A #define .NpcID:BulletBill_27 1B #define .NpcID:BulletBill_28 1C #define .NpcID:BulletBill_29 1D #define .NpcID:BulletBill_40 28 #define .NpcID:BulletBill_41 29 #define .NpcID:BulletBill_42 2A #define .NpcID:BulletBill_43 2B #define .NpcID:BulletBill_44 2C #new:Function $Function_80240000 { 0: ADDIU SP, SP, FFD8 4: SW S3, 1C (SP) 8: COPY S3, A0 C: SW RA, 24 (SP) 10: SW S4, 20 (SP) 14: SW S2, 18 (SP) 18: SW S1, 14 (SP) 1C: SW S0, 10 (SP) 20: LW S0, C (S3) 24: LW S2, 148 (S3) 28: LW A1, 0 (S0) 2C: JAL ~Func:get_variable 30: ADDIU S0, S0, 4 34: COPY S1, V0 38: LW A1, 0 (S0) 3C: ADDIU S0, S0, 4 40: JAL ~Func:get_variable 44: COPY A0, S3 48: COPY S4, V0 4C: LI V0, FFFF 50: BNE S1, V0, .o5C 54: LW S0, 0 (S0) 58: LH S1, 8 (S2) .o5C 5C: JAL ~Func:get_enemy 60: COPY A0, S1 64: COPY S2, V0 68: BEQ S2, R0, .o84 6C: COPY A0, S3 70: SLL V0, S4, 2 74: ADDU V0, S2, V0 78: LW A2, 6C (V0) 7C: BEQ R0, R0, .o8C 80: COPY A1, S0 .o84 84: COPY A1, S0 88: LI A2, FFFF .o8C 8C: JAL ~Func:set_variable 90: NOP 94: LW RA, 24 (SP) 98: LW S4, 20 (SP) 9C: LW S3, 1C (SP) A0: LW S2, 18 (SP) A4: LW S1, 14 (SP) A8: LW S0, 10 (SP) AC: LI V0, 2 B0: JR RA B4: ADDIU SP, SP, 28 } PADDING: 802400B8 to 802400C0 (000000B8 to 000000C0) 00000000 00000000 #new:Function $Function_802400C0 { 0: ADDIU SP, SP, FFD8 4: LA A0, $???_80245234 C: SW RA, 18 (SP) 10: SW S1, 14 (SP) 14: SW S0, 10 (SP) 18: SDC1 F20, 20 (SP) 1C: LW V1, 0 (A0) 20: LA S1, 8010EFC8 28: SLTI V0, V1, 3 2C: BEQL V0, R0, .o4C 30: LI V0, 3 34: BGTZ V1, .o68 38: ADDIU V0, V1, 1 3C: BEQ V1, R0, .o5C 40: CLEAR V0 44: BEQ R0, R0, .oF8 48: NOP .o4C 4C: BEQ V1, V0, .o70 50: CLEAR V0 54: BEQ R0, R0, .oF8 58: NOP .o5C 5C: LI V0, 1 60: BEQ R0, R0, .oF4 64: SW V0, 0 (A0) .o68 68: BEQ R0, R0, .oF4 6C: SW V0, 0 (A0) .o70 70: LWC1 F0, 28 (S1) 74: LIF F2, 30.0 7C: LA S0, 8010C930 84: SUB.S F0, F0, F2 88: LW A0, 0 (S0) 8C: SWC1 F0, 38 (A0) 90: LWC1 F0, 30 (S1) 94: ADD.S F0, F0, F2 98: JAL ~Func:partner_clear_player_tracking 9C: SWC1 F0, 40 (A0) A0: LWC1 F0, 28 (S1) A4: LWC1 F2, 30 (S1) A8: TRUNC.W.S F4, F0 AC: MFC1 A0, F4 B0: TRUNC.W.S F4, F2 B4: MFC1 A1, F4 B8: JAL ~Func:partner_set_goal_pos BC: NOP C0: JAL 800EF3D4 C4: CLEAR A0 C8: LIF F20, 90.0 D0: LW A0, 0 (S0) D4: MFC1 A1, F20 D8: JAL ~Func:set_npc_yaw DC: NOP E0: LI V0, 2 E4: SWC1 F20, 80 (S1) E8: SWC1 F20, 84 (S1) EC: BEQ R0, R0, .oF8 F0: SW R0, A8 (S1) .oF4 F4: CLEAR V0 .oF8 F8: LW RA, 18 (SP) FC: LW S1, 14 (SP) 100: LW S0, 10 (SP) 104: LDC1 F20, 20 (SP) 108: JR RA 10C: ADDIU SP, SP, 28 } #new:EntryList $EntryList { ~Vec4f:Entry0 % -565.0 60.0 10.0 90.0 ~Vec4f:Entry1 % 1515.0 60.0 0.0 270.0 ~Vec4f:Entry2 % -340.0 0.0 50.0 90.0 } #new:Header $Header { [MainScript] $Script_Main [EntryList] $EntryList [EntryCount] 00000003 [Background] 80200000 [MapTattle] 00190057 } #new:Script $Script_80240240 { 0: If *GB_StoryProgress == .Story:Ch1_KoopaBrosFiringBlasters % FFFFFFB1 10: If *GF_TRD09_Defeated_BillBlasters == .False 20: Call SetMusicTrack ( 00000000 .Song:BulletBillAssault 00000000 00000008 ) 3C: Else 44: Call SetMusicTrack ( 00000000 .Song:KoopaFortress 00000000 00000008 ) 60: EndIf 68: Else 70: Call SetMusicTrack ( 00000000 .Song:KoopaFortress 00000000 00000008 ) 8C: EndIf 94: Call UseDoorSounds ( .DoorSounds:Metal ) A4: Return AC: End } PADDING: 802402F4 to 80240300 (000002F4 to 00000300) 00000000 00000000 00000000 #new:Script $Script_ExitDoubleDoor_80240300 { 0: SetGroup 0000001B C: Call DisablePlayerInput ( .True ) 1C: Set *Var0 ~Entry:Entry0 2C: Set *Var1 ~Collider:tt5 3C: Set *Var2 ~Model:o67 4C: Set *Var3 ~Model:o63 5C: Exec ExitDoubleDoor 68: Wait 17` 74: Call GotoMap ( $ASCII_80245290 00000003 ) % trd_01 88: Wait 100` 94: Return 9C: End } #new:Script $Script_ExitDoubleDoor_802403A4 { 0: SetGroup 0000001B C: Call DisablePlayerInput ( .True ) 1C: Set *Var0 ~Entry:Entry1 2C: Set *Var1 ~Collider:tt4 3C: Set *Var2 ~Model:o60 4C: Set *Var3 ~Model:o65 5C: Exec ExitDoubleDoor 68: Wait 17` 74: Call GotoMap ( $ASCII_80245298 00000000 ) % trd_10 88: Wait 100` 94: Return 9C: End } #new:Script $Script_80240448 { 0: Bind $Script_ExitDoubleDoor_80240300 .Trigger:WallPressA ~Collider:tt5 00000001 00000000 1C: Bind $Script_ExitDoubleDoor_802403A4 .Trigger:WallPressA ~Collider:tt4 00000001 00000000 38: Return 40: End } #new:Script $Script_EnterDoubleDoor_80240490 { 0: Call GetLoadType ( *Var1 ) 10: If *Var1 == 00000001 20: Exec EnterSavePoint 2C: Exec $Script_80240448 38: Return 40: EndIf 48: SetGroup 00000000 54: SuspendAll 00000001 60: Exec $Script_80240448 6C: Call GetEntryID ( *Var0 ) 7C: Switch *Var0 88: Case == ~Entry:Entry0 94: Set *Var2 ~Model:o67 A4: Set *Var3 ~Model:o63 B4: ExecWait EnterDoubleDoor C0: Case == ~Entry:Entry1 CC: Set *Var2 ~Model:o60 DC: Set *Var3 ~Model:o65 EC: ExecWait EnterDoubleDoor F8: EndSwitch 100: ResumeAll 00000001 10C: Return 114: End } #new:Script_Main $Script_Main { 0: Set *GB_WorldLocation .Location:KoopaBrosFortress 10: Call SetSpriteShading ( .Shading:None ) 20: Call SetCamPerspective ( .Cam:Default 00000003 25` 16` 4096` ) 40: Call SetCamBGColor ( .Cam:Default 0` 0` 0` ) 5C: Call SetCamEnabled ( .Cam:Default .True ) 70: Call GetDemoState ( *Var0 ) 80: If *Var0 != 00000000 90: Call MakeNpcs ( .True $NpcGroupList_80244E0C ) A4: ExecWait $Script_MakeEntities B0: ExecWait $Script_80245238 BC: Return C4: EndIf CC: If *GB_StoryProgress <= .Story:Ch1_DefeatedKoopaBros % FFFFFFB2 DC: Call MakeNpcs ( .True $NpcGroupList_80244330 ) F0: EndIf F8: If *GF_TRD09_Defeated_BillBlasters == .True 108: Call ModifyColliderFlags ( 00000000 ~Collider:o85 7FFFFE00 ) 120: EndIf 128: ExecWait $Script_MakeEntities 134: Exec $Script_80240240 140: Exec $Script_EnterDoubleDoor_80240490 14C: Wait 1` 158: Return 160: End } PADDING: 80240714 to 80240720 (00000714 to 00000720) 00000000 00000000 00000000 #new:Script $Script_80240720 { 0: Set *GF_TRD09_BombedRock .True 10: Return 18: End } #new:Script $Script_MakeEntities { 0: If *GF_TRD09_BombedRock == .False 10: Call MakeEntity ( .Entity:BombableRock2 ~Vec4d:Entity80240750 80000000 ) 34: Call AssignScript ( $Script_80240720 ) 44: EndIf 4C: Call MakeEntity ( .Entity:HealingBlock ~Vec4d:Entity8024078C 80000000 ) 70: Call MakeEntity ( .Entity:SavePoint ~Vec4d:Entity802407B0 80000000 ) 94: Call MakeEntity ( .Entity:YellowBlock ~Vec4d:Entity802407D4 .Item:MapleSyrup 80000000 ) BC: Call AssignBlockFlag ( *GF_TRD09_ItemBlock_MapleSyrup ) CC: Return D4: End } PADDING: 8024081C to 80240820 (0000081C to 00000820) 00000000 #new:Script $Script_80240820 { 0: Call SetSelfEnemyFlagBits ( 00200000 00000001 ) 14: Return 1C: End } % Origin: HEURISTIC #new:Script $Script_80240844 { 0: Label 0 C: SetF *Var0 *Fixed[400.0] 1C: Set *Var1 00000001 2C: Call GetNpcYaw ( .Npc:Self *Var2 ) 40: Set *Var3 0000000A 50: Set *VarA 002E0001 60: Set *VarB 002E0001 70: ExecWait 800936C0 7C: Call SetNpcAnimation ( .Npc:Self 002E0002 ) 90: Wait 15` 9C: Call GetNpcPos ( .Npc:Self *Var0 *Var1 *Var2 ) B8: Call GetNpcYaw ( .Npc:Self *Var3 ) CC: Call AddVectorPolar ( *Var0 *Var2 *Fixed[20.0] *Var3 ) E8: Add *Var1 0000000C F8: Call SetNpcAnimation ( .Npc:Self 002E0001 ) 10C: Call GetSelfNpcID ( *Var0 ) 11C: Add *Var0 00000001 12C: Call SetNpcVar ( *Var0 00000000 00000001 ) 144: Label 1 150: Call GetSelfNpcID ( *Var0 ) 160: Add *Var0 00000001 170: Call GetNpcVar ( *Var0 00000000 *Var1 ) 188: If *Var1 == 00000000 198: Wait 1` 1A4: Goto 1 1B0: EndIf 1B8: Call RandInt ( 0000001E *Var0 ) 1CC: Add *Var0 0000001E 1DC: Wait *Var0 1E8: Goto 0 1F4: Return 1FC: End } #new:Script $Script_80240A48 { 0: Call SetBattleMusic ( .Song:SpecialBattle ) 10: Call GetOwnerEncounterTrigger ( *Var0 ) 20: Switch *Var0 2C: Case == .EncounterTrigger:None % 1 38: CaseOR == .EncounterTrigger:Jump % 2 44: CaseOR == .EncounterTrigger:Hammer % 4 50: CaseOR == .EncounterTrigger:Partner % 6 5C: Set *Var0 002E0003 6C: ExecWait 800936DC 78: Case == .EncounterTrigger:Spin % 3 84: Thread 8C: Call 800458CC ( *Var0 ) 9C: If *Var0 == 00000000 AC: Set *VarA 00000000 BC: Loop 0000001E C8: Add *VarA 00000028 D8: Call SetNpcRotation ( .Npc:Self 00000000 *VarA 00000000 ) F4: Wait 1` 100: EndLoop 108: EndIf 110: EndThread 118: EndCaseGroup 120: EndSwitch 128: Return 130: End } % Origin: HEURISTIC #new:Script $Script_80240B80 { 0: Call GetBattleOutcome ( *Var0 ) 10: Switch *Var0 1C: Case == .Outcome:PlayerWon % 0 28: Call DoNpcDefeat ( ) 34: Case == .Outcome:PlayerFled % 2 40: Case == .Outcome:EnemyFled % 3 4C: Call SetEnemyFlagBits ( .Npc:Self 00000010 00000001 ) 64: Call RemoveNpc ( .Npc:Self ) 74: EndSwitch 7C: Return 84: End } #new:Script $Script_80240C0C { 0: Return 8: End } #new:Unknown $???_80240C1C { 00000002 00000000 00000001 00000000 } % Origin: HEURISTIC #new:Script $Script_80240C2C { 0: Call SetNpcRotation ( .Npc:Self 00000000 00000000 00000000 ) 1C: Call GetBattleOutcome ( *Var0 ) 2C: Switch *Var0 38: Case == .Outcome:PlayerWon % 0 44: Call DoNpcDefeat ( ) 50: Call SetNpcPos ( .Npc:Self 0` -1000` 0` ) 6C: Case == .Outcome:PlayerFled % 2 78: Case == .Outcome:EnemyFled % 3 84: Call SetNpcPos ( .Npc:Self 0` -1000` 0` ) A0: EndSwitch A8: Return B0: End } MISSING: 80240CE4 to 80240D3C (00000CE4 to 00000D3C) 002E0001 001A0020 80240820 00000000 80240844 80240A48 00000000 80240B80 00000000 00000000 000A0000 002D0001 000E001F 80240C0C 00000000 80240C1C 80077F70 00000000 80240C2C 00000000 00000000 00050000 #new:Script $Script_80240D3C { 0: If *GB_StoryProgress >= .Story:Ch1_KoopaBrosFiringBlasters % FFFFFFB1 10: Call RemoveNpc ( .Npc:Self ) 20: EndIf 28: Return 30: End } #new:Script $Script_NpcAI_80240D74 { 0: Label 0 C: Call GetPlayerPos ( *Var0 *Var1 *Var2 ) 24: Wait 1` 30: If *Var0 < FFFFFE8E 40: Goto 0 4C: EndIf 54: Call DisablePlayerInput ( .True ) 64: Wait 20` 70: Call FadeOutMusic ( 00000000 000007D0 ) 84: Call UseSettingsFrom ( .Cam:Default 1300` 0` 0` ) A0: Call SetPanTarget ( .Cam:Default 1490` 0` 0` ) BC: Call SetCamPosB ( .Cam:Default 1466` *Fixed[41.6] ) D4: Call SetCamSpeed ( .Cam:Default *Fixed[1.5] ) E8: Call PanToTarget ( .Cam:Default 00000000 00000001 ) 100: Call WaitForCam ( .Cam:Default *Fixed[1.0] ) 114: Wait 20` 120: Call SetCamPosB ( .Cam:Default 1466` *Fixed[41.6] ) 138: Call SetPanTarget ( .Cam:Default 1490` 60` 0` ) 154: Call SetCamDistance ( .Cam:Default 300` ) 168: Call SetCamPitch ( .Cam:Default 25` -9` ) 180: Call SetCamSpeed ( .Cam:Default *Fixed[5.0] ) 194: Call PanToTarget ( .Cam:Default 00000000 00000001 ) 1AC: Wait 20` 1B8: Call PlaySound ( 000001C3 ) 1C8: Call SetMusicTrack ( 00000000 .Song:KoopaBrosTheme 00000000 00000008 ) 1E4: Call MakeLerp ( 00000000 0000006E 0000000A .Easing:CosInOut ) 200: Label 2 20C: Call UpdateLerp ( ) 218: Call RotateModel ( ~Model:o60 *Var0 00000000 FFFFFFFF 00000000 ) 238: Call RotateModel ( ~Model:o65 *Var0 00000000 00000001 00000000 ) 258: Wait 1` 264: If *Var1 == 00000001 274: Goto 2 280: EndIf 288: Call SetNpcVar ( 00000047 00000000 00000001 ) 2A0: Call SetNpcVar ( 00000048 00000000 00000001 ) 2B8: Call SetNpcVar ( 00000049 00000000 00000001 ) 2D0: Wait 60` 2DC: Call SetNpcAnimation ( .Npc:Self 00660103 ) 2F0: Call SetNpcSpeed ( .Npc:Self *Fixed[3.0] ) 304: Call SetNpcJumpscale ( .Npc:Self *Fixed[0.8] ) 318: Call NpcMoveTo ( .Npc:Self 1490` 0` 0` ) 334: Wait 10` 340: Call SpeakToPlayer ( .Npc:Self 0066011B 0066011B 00000000 000C00F2 ) % Well, well, well! Mario! I wouldn't have bet you'd ... 360: Call UseSettingsFrom ( .Cam:Default 1300` 0` 0` ) 37C: Call SetCamPosB ( .Cam:Default 1466` *Fixed[41.6] ) 394: Call SetPanTarget ( .Cam:Default 1250` 0` 0` ) 3B0: Call SetCamSpeed ( .Cam:Default *Fixed[1.0] ) 3C4: Call PanToTarget ( .Cam:Default 00000000 00000001 ) 3DC: Call SetNpcAnimation ( .Npc:Self 00660112 ) 3F0: Call NpcJump0 ( .Npc:Self 1440` 30` 0` 20` ) 410: Call NpcJump0 ( .Npc:Self 1380` 0` 0` 20` ) 430: Call SetNpcAnimation ( .Npc:Self 00660103 ) 444: Call NpcMoveTo ( .Npc:Self 1360` 0` 0` ) 460: Wait 20` 46C: Call SetNpcAnimation ( .Npc:Self 00660104 ) 480: Call SpeakToPlayer ( .Npc:Self 0066011B 0066011B 00000000 000C00F3 ) % Yeah, boys!! Open fire! 4A0: Call SetNpcVar ( 00000047 00000000 00000002 ) 4B8: Call SetNpcVar ( 00000048 00000000 00000002 ) 4D0: Call SetNpcVar ( 00000049 00000000 00000002 ) 4E8: Call SetSelfVar ( 00000000 00000001 ) 4FC: Call SetMusicTrack ( 00000000 .Song:BulletBillAssault 00000000 00000008 ) 518: Wait 60` 524: Call UseSettingsFrom ( .Cam:Default 1300` 0` 0` ) 540: Call PanToTarget ( .Cam:Default 00000000 00000000 ) 558: Call SetCamSpeed ( .Cam:Default *Fixed[1.5] ) 56C: Call WaitForCam ( .Cam:Default *Fixed[1.0] ) 580: Call SetCamSpeed ( .Cam:Default *Fixed[1.0] ) 594: Set *GB_StoryProgress .Story:Ch1_KoopaBrosFiringBlasters 5A4: Call DisablePlayerInput ( .False ) 5B4: Call RotateModel ( ~Model:o60 00000000 00000000 FFFFFFFF 00000000 ) 5D4: Call RotateModel ( ~Model:o65 00000000 00000000 00000001 00000000 ) 5F4: Call RemoveNpc ( .Npc:Self ) 604: Return 60C: End } % Origin: HEURISTIC #new:Script $Script_80241388 { 0: If *GB_StoryProgress >= .Story:Ch1_KoopaBrosFiringBlasters % FFFFFFB1 10: Call RemoveNpc ( .Npc:Self ) 20: EndIf 28: Return 30: End } % Origin: HEURISTIC #new:Script $Script_802413C0 { 0: If *GB_StoryProgress >= .Story:Ch1_KoopaBrosFiringBlasters % FFFFFFB1 10: Call RemoveNpc ( .Npc:Self ) 20: EndIf 28: Return 30: End } % Origin: HEURISTIC #new:Script $Script_802413F8 { 0: If *GB_StoryProgress >= .Story:Ch1_KoopaBrosFiringBlasters % FFFFFFB1 10: Call RemoveNpc ( .Npc:Self ) 20: EndIf 28: Return 30: End } % Origin: HEURISTIC #new:Script $Script_80241430 { 0: Call SetSelfVar ( 00000000 00000000 ) 14: Label A 20: Call GetSelfVar ( 00000000 *Var0 ) 34: If *Var0 == 00000000 44: Wait 1` 50: Goto A 5C: EndIf 64: Call SetNpcAnimation ( .Npc:Self 00660003 ) 78: Call SetNpcSpeed ( .Npc:Self *Fixed[3.0] ) 8C: Call SetNpcJumpscale ( .Npc:Self *Fixed[0.8] ) A0: Call NpcMoveTo ( .Npc:Self 1520` 20` 0` ) BC: Call SetNpcAnimation ( .Npc:Self 00660012 ) D0: Call NpcJump0 ( .Npc:Self 1470` 30` 30` 20` ) F0: Call NpcJump0 ( .Npc:Self 1410` 0` 40` 20` ) 110: Call SetNpcAnimation ( .Npc:Self 00660003 ) 124: Call NpcMoveTo ( .Npc:Self 1330` 50` 0` ) 140: Call SetNpcAnimation ( .Npc:Self 00660001 ) 154: Label 14 160: Call GetSelfVar ( 00000000 *Var0 ) 174: If *Var0 == 00000001 184: Wait 1` 190: Goto 14 19C: EndIf 1A4: Call SetNpcAnimation ( .Npc:Self 0066001B ) 1B8: Wait 100` 1C4: Call RemoveNpc ( .Npc:Self ) 1D4: Return 1DC: End } % Origin: HEURISTIC #new:Script $Script_80241614 { 0: Call SetSelfVar ( 00000000 00000000 ) 14: Label A 20: Call GetSelfVar ( 00000000 *Var0 ) 34: If *Var0 == 00000000 44: Wait 1` 50: Goto A 5C: EndIf 64: Call SetNpcAnimation ( .Npc:Self 00660203 ) 78: Call SetNpcSpeed ( .Npc:Self *Fixed[3.0] ) 8C: Call SetNpcJumpscale ( .Npc:Self *Fixed[0.8] ) A0: Call NpcMoveTo ( .Npc:Self 1505` 5` 0` ) BC: Call SetNpcAnimation ( .Npc:Self 00660212 ) D0: Call NpcJump0 ( .Npc:Self 1455` 30` 5` 20` ) F0: Call NpcJump0 ( .Npc:Self 1395` 0` 5` 20` ) 110: Call SetNpcAnimation ( .Npc:Self 00660203 ) 124: Call NpcMoveTo ( .Npc:Self 1315` 5` 0` ) 140: Call SetNpcAnimation ( .Npc:Self 00660201 ) 154: Label 14 160: Call GetSelfVar ( 00000000 *Var0 ) 174: If *Var0 == 00000001 184: Wait 1` 190: Goto 14 19C: EndIf 1A4: Call SetNpcAnimation ( .Npc:Self 0066021B ) 1B8: Wait 100` 1C4: Call RemoveNpc ( .Npc:Self ) 1D4: Return 1DC: End } % Origin: HEURISTIC #new:Script $Script_802417F8 { 0: Call SetSelfVar ( 00000000 00000000 ) 14: Label A 20: Call GetSelfVar ( 00000000 *Var0 ) 34: If *Var0 == 00000000 44: Wait 1` 50: Goto A 5C: EndIf 64: Call SetNpcAnimation ( .Npc:Self 00660303 ) 78: Call SetNpcSpeed ( .Npc:Self *Fixed[3.0] ) 8C: Call SetNpcJumpscale ( .Npc:Self *Fixed[0.8] ) A0: Call NpcMoveTo ( .Npc:Self 1490` -10` 0` ) BC: Call SetNpcAnimation ( .Npc:Self 00660312 ) D0: Call NpcJump0 ( .Npc:Self 1440` 30` -20` 20` ) F0: Call NpcJump0 ( .Npc:Self 1380` 0` -30` 20` ) 110: Call SetNpcAnimation ( .Npc:Self 00660303 ) 124: Call NpcMoveTo ( .Npc:Self 1300` -40` 0` ) 140: Call SetNpcAnimation ( .Npc:Self 00660301 ) 154: Label 14 160: Call GetSelfVar ( 00000000 *Var0 ) 174: If *Var0 == 00000001 184: Wait 1` 190: Goto 14 19C: EndIf 1A4: Call SetNpcAnimation ( .Npc:Self 0066031B ) 1B8: Wait 100` 1C4: Call RemoveNpc ( .Npc:Self ) 1D4: Return 1DC: End } #new:Script $Script_NpcAI_802419DC { 0: If *GB_StoryProgress < .Story:Ch1_KoopaBrosFiringBlasters % FFFFFFB1 10: Label 64 1C: Call GetNpcVar ( 00000046 00000000 *Var0 ) 34: If *Var0 == 00000000 44: Wait 1` 50: Goto 64 5C: EndIf 64: EndIf 6C: Label 0 78: Set *VarA 00000014 88: Loop 0000000A 94: Call $Function_80240000 ( *VarA 00000000 *Var0 ) AC: If *Var0 == 00000000 BC: Call GetSelfNpcID ( *Var0 ) CC: Call SetNpcVar ( *VarA 00000000 *Var0 ) E4: Call SetNpcAnimation ( .Npc:Self 002E0002 ) F8: Wait 15` 104: Call SetNpcAnimation ( .Npc:Self 002E0001 ) 118: Call RandInt ( 00000064 *Var0 ) 12C: Add *Var0 0000003C 13C: Wait *Var0 148: EndIf 150: Add *VarA 00000001 160: EndLoop 168: Wait 1` 174: Goto 0 180: Return 188: End } #new:Script $Script_NpcAI_80241B6C { 0: Call SetSelfEnemyFlagBits ( 00200000 00000001 ) 14: Label 1 20: Call SetSelfVar ( 00000000 00000000 ) 34: Call EnableNpcShadow ( .Npc:Self .False ) 48: Call 80045580 ( 00000000 ) 58: Call SetNpcFlagBits ( .Npc:Self 00000002 .True ) 70: Call SetNpcPos ( .Npc:Self 0` -1000` 0` ) 8C: Label 2 98: Call GetSelfVar ( 00000000 *Var0 ) AC: If *Var0 == 00000000 BC: Wait 1` C8: Goto 2 D4: EndIf DC: Wait 15` E8: Call SetNpcAnimation ( .Npc:Self 002D0004 ) FC: Call EnableNpcShadow ( .Npc:Self .True ) 110: Call SetNpcFlagBits ( .Npc:Self 00000002 .False ) 128: Call 80045580 ( 00000001 ) 138: Call GetNpcPos ( *Var0 *Var1 *Var2 *Var3 ) 154: Call GetNpcYaw ( *Var0 *Var4 ) 168: Call AddVectorPolar ( *Var1 *Var3 *Fixed[14.0] *Var4 ) 184: Add *Var2 0000000B 194: Call SetNpcPos ( .Npc:Self *Var1 *Var2 *Var3 ) 1B0: Call InterpNpcYaw ( .Npc:Self *Var4 0` ) 1C8: Call 80045838 ( FFFFFFFF 00000328 00200000 ) 1E0: Set *VarA *Var1 1F0: Sub *VarA 0000000A 200: Set *VarB *Var2 210: Add *VarB 00000005 220: Set *VarC *Var3 230: Add *VarC 00000003 240: Call PlayEffect ( ~FX:Steam:Ring *VarA *VarB *VarC 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 ) 284: Call SetNpcSpeed ( .Npc:Self *Fixed[6.0] ) 298: Switch *Var0 2A4: Case == 0000000A 2B0: Call NpcMoveTo ( .Npc:Self -437` *Var3 0` ) 2CC: Case == 0000000B 2D8: Call NpcMoveTo ( .Npc:Self -460` *Var3 0` ) 2F4: Case == 0000000C 300: Call NpcMoveTo ( .Npc:Self -450` *Var3 0` ) 31C: EndSwitch 324: Call 80045838 ( FFFFFFFF B0000018 00000000 ) 33C: Call SetNpcAnimation ( .Npc:Self 002D0005 ) 350: Call GetNpcPos ( .Npc:Self *Var0 *Var1 *Var2 ) 36C: Add *Var1 00000005 37C: Add *Var2 00000001 38C: Call PlayEffect ( ~FX:SmokeBurst:Black *Var0 *Var1 *Var2 *Fixed[0.05] 00000014 00000000 00000000 00000000 00000000 00000000 00000000 00000000 ) 3D0: Add *Var2 00000001 3E0: Call PlayEffect ( ~FX:RingBlast:Red *Var0 *Var1 *Var2 *Fixed[1.2] 00000019 00000000 00000000 00000000 00000000 00000000 00000000 00000000 ) 424: Wait 3` 430: Goto 1 43C: Return 444: End } #new:Script $Script_80241FB8 { 0: Call SetNpcRotation ( .Npc:Self 00000000 00000000 00000000 ) 1C: Call GetBattleOutcome ( *Var0 ) 2C: Switch *Var0 38: Case == .Outcome:PlayerWon % 0 44: Thread 4C: Wait 20` 58: Call SetNpcFlagBits ( .Npc:Self 00000002 .True ) 70: Call SetNpcPos ( .Npc:Self 0` -1000` 0` ) 8C: Call BindNpcAI ( .Npc:Self $Script_NpcAI_80241B6C ) A0: EndThread A8: Call DoNpcDefeat ( ) B4: Case == .Outcome:PlayerFled % 2 C0: Call 80045900 ( 00000000 ) D0: EndSwitch D8: Return E0: End } #new:NpcSettings $NpcSettings_802420A0 { 00660102 00220018 $Script_80240D3C 00000000 $Script_NpcAI_80240D74 00000000 00000000 00000000 00000700 00000000 00630000 } #new:Unknown $???_802420CC { 00660002 00220018 $Script_80241388 00000000 $Script_80241430 00000000 00000000 00000000 00000700 00000000 00630000 } #new:Unknown $???_802420F8 { 00660202 00220018 $Script_802413C0 00000000 $Script_80241614 00000000 00000000 00000000 00000700 00000000 00630000 } #new:Unknown $???_80242124 { 00660302 00220018 $Script_802413F8 00000000 $Script_802417F8 00000000 00000000 00000000 00000700 00000000 00630000 } #new:NpcSettings $NpcSettings_80242150 { 002E0001 001A0020 $Script_80240820 00000000 $Script_NpcAI_802419DC $Script_80240A48 00000000 00000000 00000000 00000000 000A0000 } #new:NpcSettings $NpcSettings_8024217C { 002D0001 000E001F $Script_80240C0C 00000000 $Script_NpcAI_80241B6C 80077F70 00000000 $Script_80241FB8 00000000 00000000 00050000 } #new:Script $Script_Defeat_802421A8 { 0: Call ModifyColliderFlags ( 00000000 ~Collider:o85 7FFFFE00 ) 18: Set *GF_TRD09_Defeated_BillBlasters .True 28: Call DoNpcDefeat ( ) 34: Return 3C: End } #new:Script $Script_Init_802421EC { 0: If *GF_TRD09_Defeated_BillBlasters == .False 10: Call BindNpcDefeat ( .Npc:Self $Script_Defeat_802421A8 ) 24: Else 2C: Call RemoveEncounter ( .Npc:Self ) 3C: EndIf 44: Return 4C: End } #new:NpcGroup $NpcGroup_80242240 { .NpcID:NPC_BillBlaster_10 $NpcSettings_80242150 ~Vec3f:NPC_BillBlaster_10 % 1260 0 -40 00242D00 $Script_Init_802421EC 00000000 00000000 0000010E ~NoDrops ~Movement:NPC_BillBlaster_10 ~AnimationTable:NPC_BillBlaster_10 % .Sprite:BillBlaster 00000000 00000000 00000000 00000000 % no tattle string % % $NpcGroup_80242240[1F0] .NpcID:NPC_BillBlaster_12 $NpcSettings_80242150 ~Vec3f:NPC_BillBlaster_12 % 1275 0 5 00242D00 00000000 00000000 00000000 0000010E ~NoItems ~HP:Standard:2 ~FP:Standard:2 ~CoinBonus:1:1 ~Movement:NPC_BillBlaster_12 ~AnimationTable:NPC_BillBlaster_12 % .Sprite:BillBlaster 00000000 00000000 00000000 00000000 % no tattle string % % $NpcGroup_80242240[3E0] .NpcID:NPC_BillBlaster_11 $NpcSettings_80242150 ~Vec3f:NPC_BillBlaster_11 % 1290 0 50 00242D00 00000000 00000000 00000000 0000010E ~NoDrops ~Movement:NPC_BillBlaster_11 ~AnimationTable:NPC_BillBlaster_11 % .Sprite:BillBlaster 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80242810 { .NpcID:NPC_BulletBill_20 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_20 % 0 -1000 0 00080D04 00000000 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_20 ~AnimationTable:NPC_BulletBill_20 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80242A00 { .NpcID:NPC_BulletBill_21 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_21 % 0 -1000 0 00080D04 00000000 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_21 ~AnimationTable:NPC_BulletBill_21 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80242BF0 { .NpcID:NPC_BulletBill_22 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_22 % 0 -1000 0 00080D04 00000000 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_22 ~AnimationTable:NPC_BulletBill_22 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80242DE0 { .NpcID:NPC_BulletBill_23 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_23 % 0 -1000 0 00080D04 00000000 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_23 ~AnimationTable:NPC_BulletBill_23 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80242FD0 { .NpcID:NPC_BulletBill_24 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_24 % 0 -1000 0 00080D04 00000000 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_24 ~AnimationTable:NPC_BulletBill_24 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_802431C0 { .NpcID:NPC_BulletBill_25 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_25 % 0 -1000 0 00080D04 00000000 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_25 ~AnimationTable:NPC_BulletBill_25 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_802433B0 { .NpcID:NPC_BulletBill_26 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_26 % 0 -1000 0 00080D04 00000000 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_26 ~AnimationTable:NPC_BulletBill_26 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_802435A0 { .NpcID:NPC_BulletBill_27 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_27 % 0 -1000 0 00080D04 00000000 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_27 ~AnimationTable:NPC_BulletBill_27 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80243790 { .NpcID:NPC_BulletBill_28 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_28 % 0 -1000 0 00080D04 00000000 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_28 ~AnimationTable:NPC_BulletBill_28 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80243980 { .NpcID:NPC_BulletBill_29 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_29 % 0 -1000 0 00080D04 00000000 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_29 ~AnimationTable:NPC_BulletBill_29 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80243B70 { 00000046 $NpcSettings_802420A0 ~Vec3f:NPC_80243B70 % 1590 60 0 00000001 00000000 00000001 00000000 0000010E ~NoDrops~Movement:NPC_80243B70 ~AnimationTable:NPC_80243B70 % 00000000 00000000 00000000 00000000 00000000 % no tattle string % % $NpcGroup_80243B70[1F0] 00000047 $???_80242124 ~Vec3f:NPC_80243D60 % 1590 60 -10 00000001 00000000 00000001 00000000 0000010E ~NoDrops~Movement:NPC_80243D60 ~AnimationTable:NPC_80243D60 % 00000000 00000000 00000000 00000000 00000000 % no tattle string % % $NpcGroup_80243B70[3E0] 00000048 $???_802420F8 ~Vec3f:NPC_80243F50 % 1605 60 5 00000001 00000000 00000001 00000000 0000010E ~NoDrops~Movement:NPC_80243F50 ~AnimationTable:NPC_80243F50 % 00000000 00000000 00000000 00000000 00000000 % no tattle string % % $NpcGroup_80243B70[5D0] 00000049 $???_802420CC ~Vec3f:NPC_80244140 % 1620 60 20 00000001 00000000 00000001 00000000 0000010E ~NoDrops~Movement:NPC_80244140 ~AnimationTable:NPC_80244140 % 00000000 00000000 00000000 00000000 00000000 % no tattle string } MISSING: 80244058 to 80244330 (00004058 to 00004330) 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000049 802420CC 44CA8000 42700000 41A00000 00000001 00000000 00000001 00000000 0000010E 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 #new:NpcGroupList $NpcGroupList_80244330 { 00000003 $NpcGroup_80242240 06170007 00000001 $NpcGroup_80242810 061A0007 00000001 $NpcGroup_80242A00 061A0007 00000001 $NpcGroup_80242BF0 061A0007 00000001 $NpcGroup_80242DE0 061A0007 00000001 $NpcGroup_80242FD0 061A0007 00000001 $NpcGroup_802431C0 061A0007 00000001 $NpcGroup_802433B0 061A0007 00000001 $NpcGroup_802435A0 061A0007 00000001 $NpcGroup_80243790 061A0007 00000001 $NpcGroup_80243980 061A0007 00000004 $NpcGroup_80243B70 00000000 00000000 00000000 00000000 } #new:Script $Script_Idle_802443CC { 0: Call GetNpcPos ( .Npc:Self *Var1 *Var2 *Var3 ) 1C: Call SetNpcSpeed ( .Npc:Self *Fixed[6.0] ) 30: Call NpcMoveTo ( .Npc:Self -460` *Var3 0` ) 4C: Return 54: End } #new:Script $Script_Init_80244428 { 0: Call BindNpcIdle ( .Npc:Self $Script_Idle_802443CC ) 14: Call 80045580 ( 00000001 ) 24: Return 2C: End } #new:NpcGroup $NpcGroup_8024445C { .NpcID:NPC_BulletBill_40 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_40 % -100 11 50 00080D04 $Script_Init_80244428 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_40 ~AnimationTable:NPC_BulletBill_40 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_8024464C { .NpcID:NPC_BulletBill_41 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_41 % -150 11 5 00080D04 $Script_Init_80244428 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_41 ~AnimationTable:NPC_BulletBill_41 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_8024483C { .NpcID:NPC_BulletBill_42 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_42 % 120 11 50 00080D04 $Script_Init_80244428 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_42 ~AnimationTable:NPC_BulletBill_42 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80244A2C { .NpcID:NPC_BulletBill_43 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_43 % 330 11 5 00080D04 $Script_Init_80244428 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_43 ~AnimationTable:NPC_BulletBill_43 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80244C1C { .NpcID:NPC_BulletBill_44 $NpcSettings_8024217C ~Vec3f:NPC_BulletBill_44 % 380 11 -40 00080D04 $Script_Init_80244428 00000001 00000000 0000010E ~Items:3:Mushroom:A ~HP:Standard:2 ~FP:Standard:2 ~NoCoinBonus ~Movement:NPC_BulletBill_44 ~AnimationTable:NPC_BulletBill_44 % .Sprite:BulletBill 00000000 00000000 00000000 00000000 % no tattle string } #new:NpcGroupList $NpcGroupList_80244E0C { 00000001 $NpcGroup_8024445C 061A0007 00000001 $NpcGroup_8024464C 061A0007 00000001 $NpcGroup_8024483C 061A0007 00000001 $NpcGroup_80244A2C 061A0007 00000001 $NpcGroup_80244C1C 061A0007 00000000 00000000 00000000 } PADDING: 80244E54 to 80244E60 (00004E54 to 00004E60) 00000000 00000000 00000000 #new:Script $Script_80244E60 { 0: Wait 5` C: Call DemoJoystickXY ( 0000004E 00000000 ) 20: Wait 11` 2C: Call DemoJoystickXY ( 0000004F 00000001 ) 40: Call DemoSetButtons ( ~Flags:Buttons:A ) 50: Wait 7` 5C: Call DemoSetButtons ( ~Flags:Buttons:0 ) 6C: Wait 34` 78: Call DemoSetButtons ( ~Flags:Buttons:A ) 88: Wait 4` 94: Call DemoSetButtons ( ~Flags:Buttons:0 ) A4: Wait 9` B0: Call DemoJoystickXY ( 0000004E 00000001 ) C4: Wait 1` D0: Call DemoJoystickXY ( 0000004C 00000006 ) E4: Wait 1` F0: Call DemoJoystickXY ( 00000047 0000001F ) 104: Wait 1` 110: Call DemoJoystickXY ( 00000042 00000033 ) 124: Wait 1` 130: Call DemoJoystickXY ( 0000003F 0000003C ) 144: Wait 1` 150: Call DemoJoystickXY ( 0000003F 0000003D ) 164: Wait 7` 170: Call DemoJoystickXY ( 00000040 0000003D ) 184: Wait 1` 190: Call DemoJoystickXY ( 00000041 0000003B ) 1A4: Wait 1` 1B0: Call DemoJoystickXY ( 00000041 00000038 ) 1C4: Wait 1` 1D0: Call DemoJoystickXY ( 00000043 0000002D ) 1E4: Wait 1` 1F0: Call DemoJoystickXY ( 00000047 0000001C ) 204: Wait 1` 210: Call DemoJoystickXY ( 0000004B 0000000E ) 224: Wait 1` 230: Call DemoJoystickXY ( 0000004D 00000006 ) 244: Wait 1` 250: Call DemoJoystickXY ( 0000004E 00000002 ) 264: Wait 13` 270: Call DemoJoystickXY ( 0000004E 00000003 ) 284: Call DemoSetButtons ( ~Flags:Buttons:A ) 294: Wait 9` 2A0: Call DemoSetButtons ( ~Flags:Buttons:0 ) 2B0: If *GF_DemoSceneDone == .True 2C0: Return 2C8: EndIf 2D0: Set *GF_DemoSceneDone .True 2E0: Call GotoMapSpecial ( $ASCII_802452A0 00000002 00000002 ) % trd_09 2F8: Wait 123` 304: Return 30C: End } #new:Script $Script_80245174 { 0: Wait 10` C: Loop 18: Call GetDemoState ( *Var0 ) 28: If *Var0 == 00000002 38: BreakLoop 40: EndIf 48: Wait 1` 54: EndLoop 5C: If *GF_DemoSceneDone == .True 6C: Return 74: EndIf 7C: Set *GF_DemoSceneDone .True 8C: Call GotoMapSpecial ( $ASCII_802452A0 00000002 00000003 ) % trd_09 A4: Wait 113` B0: Return B8: End } #new:Unknown $???_80245234 { 00000000 } #new:Script $Script_80245238 { 0: Call $Function_802400C0 ( ) C: Call SetNpcYaw ( .Npc:Partner 90` ) 20: Set *GF_DemoSceneDone .False 30: Exec $Script_80245174 3C: Exec $Script_80244E60 48: Return 50: End } #new:ASCII $ASCII_80245290 { "trd_01" } #new:ASCII $ASCII_80245298 { "trd_10" } #new:ASCII $ASCII_802452A0 { "trd_09" } PADDING: 802452A8 to 802452B0 (000052A8 to 000052B0) 00000000 00000000
0
0.823415
1
0.823415
game-dev
MEDIA
0.817222
game-dev
0.792254
1
0.792254
AppliedEnergistics/GuideME
5,507
src/main/java/guideme/navigation/NavigationTree.java
package guideme.navigation; import guideme.compiler.ParsedGuidePage; import guideme.internal.util.NavigationUtil; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import net.minecraft.resources.ResourceLocation; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NavigationTree { private static final Logger LOG = LoggerFactory.getLogger(NavigationTree.class); private final Map<ResourceLocation, NavigationNode> nodeIndex; private final List<NavigationNode> rootNodes; public NavigationTree(Map<ResourceLocation, NavigationNode> nodeIndex, List<NavigationNode> rootNodes) { this.nodeIndex = nodeIndex; this.rootNodes = rootNodes; } public NavigationTree() { this.nodeIndex = Map.of(); this.rootNodes = List.of(); } public List<NavigationNode> getRootNodes() { return rootNodes; } @Nullable public NavigationNode getNodeById(ResourceLocation pageId) { return nodeIndex.get(pageId); } public static NavigationTree build(Collection<ParsedGuidePage> pages) { var pagesWithChildren = new HashMap<ResourceLocation, Pair<ParsedGuidePage, List<ParsedGuidePage>>>(); // First pass, build a map of pages and their children for (var page : pages) { var navigationEntry = page.getFrontmatter().navigationEntry(); if (navigationEntry == null) { continue; } // Create an entry for this page to collect any children it might have pagesWithChildren.compute( page.getId(), (resourceLocation, previousPair) -> { return previousPair != null ? Pair.of(page, previousPair.getRight()) : Pair.of(page, new ArrayList<>()); }); // Add this page to the collected children of the parent page (if any) var parentId = navigationEntry.parent(); if (parentId != null) { pagesWithChildren.compute( parentId, (resourceLocation, prevPage) -> { if (prevPage != null) { prevPage.getRight().add(page); return prevPage; } else { var children = new ArrayList<ParsedGuidePage>(); children.add(page); return Pair.of(null, children); } }); } } var nodeIndex = new HashMap<ResourceLocation, NavigationNode>(pages.size()); var rootNodes = new ArrayList<NavigationNode>(); for (var entry : pagesWithChildren.entrySet()) { createNode(nodeIndex, rootNodes, pagesWithChildren, entry.getKey(), entry.getValue(), new HashSet<>()); } // Sort root nodes rootNodes.sort(NODE_COMPARATOR); return new NavigationTree(Map.copyOf(nodeIndex), List.copyOf(rootNodes)); } @Nullable private static NavigationNode createNode(Map<ResourceLocation, NavigationNode> nodeIndex, List<NavigationNode> rootNodes, Map<ResourceLocation, Pair<ParsedGuidePage, List<ParsedGuidePage>>> pagesWithChildren, ResourceLocation pageId, Pair<ParsedGuidePage, List<ParsedGuidePage>> entry, Set<ResourceLocation> parents) { if (!parents.add(pageId)) { LOG.error("Detected a cycle in the navigation tree parent-child relationship for page {}", pageId); return null; } var page = entry.getKey(); var children = entry.getRight(); if (page == null) { // These children had a parent that doesn't exist LOG.error("Pages {} had unknown navigation parent {}", children, pageId); return null; } var navigationEntry = Objects.requireNonNull(page.getFrontmatter().navigationEntry(), "navigation frontmatter"); // Construct the icon if set var icon = NavigationUtil.createNavigationIcon(page); var childNodes = new ArrayList<NavigationNode>(children.size()); for (var childPage : children) { var childPageEntry = pagesWithChildren.get(childPage.getId()); var childNode = createNode(nodeIndex, rootNodes, pagesWithChildren, childPage.getId(), childPageEntry, parents); if (childNode != null) { childNodes.add(childNode); } } childNodes.sort(NODE_COMPARATOR); var node = new NavigationNode( page.getId(), navigationEntry.title(), icon, childNodes, navigationEntry.position(), true); nodeIndex.put(page.getId(), node); if (navigationEntry.parent() == null) { rootNodes.add(node); } return node; } private static final Comparator<NavigationNode> NODE_COMPARATOR = Comparator.comparingInt(NavigationNode::position) .thenComparing(NavigationNode::title); }
0
0.884326
1
0.884326
game-dev
MEDIA
0.465121
game-dev
0.982312
1
0.982312
LangYa466/MCPLite-all-source
6,835
src/main/java/client/module/modules/world/AutoContainer.java
/* * Decompiled with CFR 0.151. */ package client.module.modules.world; import client.Client; import client.event.events.PacketReceiveSyncEvent; import client.module.Module; import client.module.ModuleType; import client.module.Settings; import client.module.modules.combat.KillAura; import client.module.modules.misc.Gapple; import client.module.modules.misc.ItemManager; import client.module.modules.world.Scaffold; import client.utils.BlockUtils; import client.utils.ClientUtils; import client.utils.MSTimer; import client.utils.rotation.RotationPriority; import client.utils.rotation.RotationSetter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import net.minecraft.block.BlockBrewingStand; import net.minecraft.block.BlockChest; import net.minecraft.block.BlockFurnace; import net.minecraft.client.gui.inventory.GuiChest; import net.minecraft.network.play.server.S45PacketTitle; import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import org.lwjgl.util.vector.Vector2f; public class AutoContainer extends Module { @Settings(maxValue=5.0) private int range = 5; @Settings(maxValue=1000.0) private int delay = 500; @Settings private boolean autoCancel = true; private BlockPos theChest; private List<BlockPos> hasOpened = new ArrayList<BlockPos>(); private MSTimer msTimer = new MSTimer(); public AutoContainer() { super("AutoContainer", 0, false, ModuleType.WORLD); } @Override public void onTick() { if (ClientUtils.nullCheck()) { return; } KillAura killAura = (KillAura)Client.moduleManager.moduleMap.get(KillAura.class); Scaffold scaffold = (Scaffold)Client.moduleManager.moduleMap.get(Scaffold.class); ItemManager itemManager = (ItemManager)Client.moduleManager.moduleMap.get(ItemManager.class); Gapple gapple = (Gapple)Client.moduleManager.moduleMap.get(Gapple.class); if (killAura.target != null && this.autoCancel || scaffold.getState() && this.autoCancel || gapple.getState() && this.autoCancel) { this.msTimer.reset(); return; } if (!this.msTimer.hasPassed(this.delay)) { return; } Vec3 eyesPos = AutoContainer.mc.thePlayer.getPositionEyes(1.0f); this.theChest = BlockUtils.searchBlocks(this.range + 1).keySet().stream().filter(e -> { if (!(BlockUtils.getBlock(e) instanceof BlockChest) && !(BlockUtils.getBlock(e) instanceof BlockBrewingStand)) { if (!(BlockUtils.getBlock(e) instanceof BlockFurnace)) return false; } if (this.hasOpened.contains(e)) return false; double d = (double)e.getX() + 0.5; double d2 = BlockUtils.getBlock(e) instanceof BlockBrewingStand ? (double)e.getY() : (double)e.getY() + 0.5; if (!(AutoContainer.mc.thePlayer.getDistance(d, d2, (double)e.getZ() + 0.5) < (double)this.range)) return false; return true; }).filter(e -> AutoContainer.mc.theWorld.rayTraceBlocks(eyesPos, new Vec3((double)e.getX() + 0.5, BlockUtils.getBlock(e) instanceof BlockBrewingStand ? (double)e.getY() : (double)e.getY() + 0.5, (double)e.getZ() + 0.5), false, true, false) != null).min(Comparator.comparingDouble(e -> AutoContainer.mc.thePlayer.getDistance((double)e.getX() + 0.5, BlockUtils.getBlock(e) instanceof BlockBrewingStand ? (double)e.getY() : (double)e.getY() + 0.5, (double)e.getZ() + 0.5))).orElse(null); if (this.theChest != null && itemManager.openScreen == null && itemManager.screenContainer == null) { Vec3 hitVec = new Vec3((double)this.theChest.getX() + 0.5, (double)this.theChest.getY() + 0.5, (double)this.theChest.getZ() + 0.5); if (BlockUtils.getBlock(this.theChest) instanceof BlockBrewingStand) { hitVec = new Vec3((double)this.theChest.getX() + 0.5, this.theChest.getY(), (double)this.theChest.getZ() + 0.5); } double diffX = hitVec.xCoord - eyesPos.xCoord; double diffY = hitVec.yCoord - eyesPos.yCoord; double diffZ = hitVec.zCoord - eyesPos.zCoord; double diffXZ = Math.sqrt(diffX * diffX + diffZ * diffZ); Vector2f rotation = new Vector2f(MathHelper.wrapAngleTo180_float((float)(Math.toDegrees(MathHelper.atan2(diffZ, diffX)) - 90.0)), MathHelper.wrapAngleTo180_float((float)(-Math.toDegrees(MathHelper.atan2(diffY, diffXZ))))); RotationSetter.setRotation(rotation, 0, RotationPriority.LOW); } } @Override public void onUpdate() { BlockPos blockPos; KillAura killAura = (KillAura)Client.moduleManager.moduleMap.get(KillAura.class); Scaffold scaffold = (Scaffold)Client.moduleManager.moduleMap.get(Scaffold.class); Gapple gapple = (Gapple)Client.moduleManager.moduleMap.get(Gapple.class); if (killAura.target != null && this.autoCancel || scaffold.getState() && this.autoCancel || gapple.getState() && this.autoCancel) { this.msTimer.reset(); return; } if (!this.msTimer.hasPassed(this.delay)) { return; } ItemManager itemManager = (ItemManager)Client.moduleManager.moduleMap.get(ItemManager.class); BlockPos blockPos2 = blockPos = AutoContainer.mc.objectMouseOver.getBlockPos() != null ? AutoContainer.mc.objectMouseOver.getBlockPos() : null; if (!(AutoContainer.mc.currentScreen instanceof GuiChest) && blockPos != null && this.theChest != null && blockPos.getY() == this.theChest.getY() && blockPos.getZ() == this.theChest.getZ() && blockPos.getX() == this.theChest.getX() && (!itemManager.getState() || itemManager.screenContainer == null && itemManager.openScreen == null) && AutoContainer.mc.playerController.onPlayerRightClick(AutoContainer.mc.thePlayer, AutoContainer.mc.theWorld, AutoContainer.mc.thePlayer.getHeldItem(), AutoContainer.mc.objectMouseOver.getBlockPos(), AutoContainer.mc.objectMouseOver.sideHit, AutoContainer.mc.objectMouseOver.hitVec)) { this.msTimer.reset(); AutoContainer.mc.thePlayer.swingItem(); this.hasOpened.add(this.theChest); } } @Override public void onDisable() { this.hasOpened.clear(); } @Override public void onWorldLoad() { this.hasOpened.clear(); } @Override public void onPacketReceiveSync(PacketReceiveSyncEvent event) { String s; S45PacketTitle wrapper; if (event.getPacket() instanceof S45PacketTitle && (wrapper = (S45PacketTitle)event.getPacket()).getType() == S45PacketTitle.Type.TITLE && (s = wrapper.getMessage().getFormattedText()).contains("\u6218\u6597\u5f00\u59cb...")) { this.hasOpened.clear(); } } }
0
0.929776
1
0.929776
game-dev
MEDIA
0.898526
game-dev
0.92521
1
0.92521
LavaGang/MelonLoader
6,608
Dependencies/Il2CppAssemblyGenerator/Core.cs
using System.IO; using System.Net.Http; using MelonLoader.Il2CppAssemblyGenerator.Packages; using MelonLoader.Il2CppAssemblyGenerator.Packages.Models; using MelonLoader.Modules; using MelonLoader.Utils; namespace MelonLoader.Il2CppAssemblyGenerator { internal class Core : MelonModule { internal static string BasePath = null; internal static string GameAssemblyPath = null; internal static string ManagedPath = null; internal static HttpClient webClient = null; internal static ExecutablePackage cpp2il = null; internal static Cpp2IL_StrippedCodeRegSupport cpp2il_scrs = null; internal static Packages.Il2CppInterop il2cppinterop = null; internal static UnityDependencies unitydependencies = null; internal static DeobfuscationMap deobfuscationMap = null; internal static DeobfuscationRegex deobfuscationRegex = null; internal static bool AssemblyGenerationNeeded = false; internal static MelonLogger.Instance Logger; public override void OnInitialize() { Logger = LoggerInstance; webClient = new(); webClient.DefaultRequestHeaders.Add("User-Agent", $"{BuildInfo.Name} v{BuildInfo.Version}"); AssemblyGenerationNeeded = LoaderConfig.Current.UnityEngine.ForceRegeneration; string gameAssemblyName = "GameAssembly"; if (MelonUtils.IsUnix) gameAssemblyName += ".so"; if (MelonUtils.IsWindows) gameAssemblyName += ".dll"; if (MelonUtils.IsMac) gameAssemblyName += ".dylib"; #if OSX GameAssemblyPath = Path.Combine(MelonEnvironment.GameExecutablePath, "Contents", "Frameworks", gameAssemblyName); #else GameAssemblyPath = Path.Combine(MelonEnvironment.GameRootDirectory, gameAssemblyName); #endif ManagedPath = MelonEnvironment.MelonManagedDirectory; BasePath = MelonEnvironment.Il2CppAssemblyGeneratorDirectory; } private static int Run() { Config.Initialize(); if (!LoaderConfig.Current.UnityEngine.ForceOfflineGeneration) RemoteAPI.Contact(); Cpp2IL cpp2IL_netcore = new Cpp2IL(); if (MelonUtils.IsWindows && (cpp2IL_netcore.VersionSem < Cpp2IL.NetCoreMinVersion)) cpp2il = new Cpp2IL_NetFramework(); else cpp2il = cpp2IL_netcore; cpp2il_scrs = new Cpp2IL_StrippedCodeRegSupport(cpp2il); il2cppinterop = new Packages.Il2CppInterop(); unitydependencies = new UnityDependencies(); deobfuscationMap = new DeobfuscationMap(); deobfuscationRegex = new DeobfuscationRegex(); Logger.Msg($"Using Cpp2IL Version: {(string.IsNullOrEmpty(cpp2il.Version) ? "null" : cpp2il.Version)}"); Logger.Msg($"Using Il2CppInterop Version = {(string.IsNullOrEmpty(il2cppinterop.Version) ? "null" : il2cppinterop.Version)}"); Logger.Msg($"Using Unity Dependencies Version = {(string.IsNullOrEmpty(unitydependencies.Version) ? "null" : unitydependencies.Version)}"); Logger.Msg($"Using Deobfuscation Regex = {(string.IsNullOrEmpty(deobfuscationRegex.Regex) ? "null" : deobfuscationRegex.Regex)}"); if (!cpp2il.Setup() || !cpp2il_scrs.Setup() || !il2cppinterop.Setup() || !unitydependencies.Setup() || !deobfuscationMap.Setup()) return 1; deobfuscationRegex.Setup(); string CurrentGameAssemblyHash; Logger.Msg("Checking GameAssembly..."); MelonDebug.Msg($"Last GameAssembly Hash: {Config.Values.GameAssemblyHash}"); MelonDebug.Msg($"Current GameAssembly Hash: {CurrentGameAssemblyHash = MelonUtils.ComputeSimpleSHA512Hash(GameAssemblyPath)}"); if (string.IsNullOrEmpty(Config.Values.GameAssemblyHash) || !Config.Values.GameAssemblyHash.Equals(CurrentGameAssemblyHash)) AssemblyGenerationNeeded = true; if (!AssemblyGenerationNeeded) { Logger.Msg("Assembly is up to date. No Generation Needed."); return 0; } Logger.Msg("Assembly Generation Needed!"); cpp2il.Cleanup(); il2cppinterop.Cleanup(); if (!cpp2il.Execute()) { cpp2il.Cleanup(); return 1; } if (!il2cppinterop.Execute()) { cpp2il.Cleanup(); il2cppinterop.Cleanup(); return 1; } OldFiles_Cleanup(); OldFiles_LAM(); cpp2il.Cleanup(); il2cppinterop.Cleanup(); Logger.Msg("Assembly Generation Successful!"); deobfuscationRegex.Save(); Config.Values.GameAssemblyHash = CurrentGameAssemblyHash; Config.Save(); return 0; } private static void OldFiles_Cleanup() { if (Config.Values.OldFiles.Count <= 0) return; for (int i = 0; i < Config.Values.OldFiles.Count; i++) { string filename = Config.Values.OldFiles[i]; string filepath = Path.Combine(MelonEnvironment.Il2CppAssembliesDirectory, filename); if (File.Exists(filepath)) { Logger.Msg("Deleting " + filename); File.Delete(filepath); } } Config.Values.OldFiles.Clear(); } private static void OldFiles_LAM() { string[] filepathtbl = Directory.GetFiles(il2cppinterop.OutputFolder); string il2CppAssembliesDirectory = MelonEnvironment.Il2CppAssembliesDirectory; for (int i = 0; i < filepathtbl.Length; i++) { string filepath = filepathtbl[i]; string filename = Path.GetFileName(filepath); Logger.Msg("Moving " + filename); Config.Values.OldFiles.Add(filename); string newfilepath = Path.Combine(il2CppAssembliesDirectory, filename); if (File.Exists(newfilepath)) File.Delete(newfilepath); Directory.CreateDirectory(il2CppAssembliesDirectory); File.Move(filepath, newfilepath); } Config.Save(); } } }
0
0.863903
1
0.863903
game-dev
MEDIA
0.892194
game-dev
0.91407
1
0.91407
angband/angband
121,515
src/gen-cave.c
/** * \file gen-cave.c * \brief Generation of dungeon levels * * Copyright (c) 1997 Ben Harrison, James E. Wilson, Robert A. Koeneke * Copyright (c) 2013 Erik Osheim, Nick McConnell * * This work is free software; you can redistribute it and/or modify it * under the terms of either: * * a) the GNU General Public License as published by the Free Software * Foundation, version 2, or * * b) the "Angband licence": * This software may be copied and distributed for educational, research, * and not for profit purposes provided that this copyright and statement * are included in all such copies. Other copyrights may also apply. * * In this file, we use the SQUARE_WALL flags to the info field in * cave->squares. Those are usually only applied and tested on granite, but * some (SQUARE_WALL_INNER) is applied and tested on permanent walls. * SQUARE_WALL_SOLID indicates the wall should not be tunnelled; * SQUARE_WALL_INNER marks an inward-facing wall of a room; SQUARE_WALL_OUTER * marks an outer wall of a room. * * We use SQUARE_WALL_SOLID to prevent multiple corridors from piercing a wall * in two adjacent locations, which would be messy, and SQUARE_WALL_OUTER * to indicate which walls surround rooms, and may thus be pierced by corridors * entering or leaving the room. * * Note that a tunnel which attempts to leave a room near the edge of the * dungeon in a direction toward that edge will cause "silly" wall piercings, * but will have no permanently incorrect effects, as long as the tunnel can * eventually exit from another side. And note that the wall may not come back * into the room by the hole it left through, so it must bend to the left or * right and then optionally re-enter the room (at least 2 grids away). This is * not a problem since every room that is large enough to block the passage of * tunnels is also large enough to allow the tunnel to pierce the room itself * several times. * * Note that no two corridors may enter a room through adjacent grids, they * must either share an entryway or else use entryways at least two grids * apart. This prevents large (or "silly") doorways. * * Traditionally, to create rooms in the dungeon, it was divided up into * "blocks" of 11x11 grids each, and all rooms were required to occupy a * rectangular group of blocks. As long as each room type reserved a * sufficient number of blocks, the room building routines would not need to * check bounds. Note that in classic generation most of the normal rooms * actually only use 23x11 grids, and so reserve 33x11 grids. * * Note that a lot of the original motivation for the block system was the * fact that there was only one size of map available, 22x66 grids, and the * dungeon level was divided up into nine of these in three rows of three. * Now that the map can be resized and enlarged, and dungeon levels themselves * can be different sizes, much of this original motivation has gone. Blocks * can still be used, but different cave profiles can set their own block * sizes. The classic generation method still uses the traditional blocks; the * main motivation for using blocks now is for the aesthetic effect of placing * rooms on a grid. */ #include "angband.h" #include "cave.h" #include "datafile.h" #include "game-event.h" #include "game-world.h" #include "generate.h" #include "init.h" #include "mon-group.h" #include "mon-make.h" #include "mon-spell.h" #include "mon-util.h" #include "player-util.h" #include "store.h" #include "trap.h" #include "z-queue.h" #include "z-type.h" /** * Check whether a square has one of the tunnelling helper flags * \param c is the current chunk * \param grid is the coordinates of the point to check * \param flag is the relevant flag */ static bool square_is_granite_with_flag(struct chunk *c, struct loc grid, int flag) { if (square(c, grid)->feat != FEAT_GRANITE) return false; if (!sqinfo_has(square(c, grid)->info, flag)) return false; return true; } /** * Places a streamer of rock through dungeon. * * \param c is the current chunk * \param feat is the base feature (FEAT_MAGMA or FEAT_QUARTZ) * \param chance is the number of regular features per one gold * * Note that their are actually six different terrain features used to * represent streamers. Three each of magma and quartz, one for basic vein, one * with hidden gold, and one with known gold. The hidden gold types are * currently unused. */ static void build_streamer(struct chunk *c, int feat, int chance) { /* Choose starting point */ struct loc grid = rand_loc(loc(c->width / 2, c->height / 2), 15, 10); /* Choose a random direction */ int dir = ddd[randint0(8)]; /* Place streamer into dungeon */ while (true) { int i; struct loc change; /* One grid per density */ for (i = 0; i < dun->profile->str.den; i++) { int d = dun->profile->str.rng; /* Pick a nearby grid */ find_nearby_grid(c, &change, grid, d, d); /* Only convert walls */ if (square_isrock(c, change)) { /* Turn the rock into the vein type */ square_set_feat(c, change, feat); /* Sometimes add known treasure */ if (one_in_(chance)) square_upgrade_mineral(c, change); } } /* Advance the streamer */ grid = loc_sum(grid, ddgrid[dir]); /* Stop at dungeon edge */ if (!square_in_bounds(c, grid)) break; } } /** * Reset entrance data for rooms in global dun. * \param c Is the chunk holding the rooms. */ static void reset_entrance_data(const struct chunk *c) { int i; for (i = 0; i < z_info->level_room_max; ++i) { dun->ent_n[i] = 0; } if (dun->ent2room) { for (i = 0; dun->ent2room[i]; ++i) { mem_free(dun->ent2room[i]); } mem_free(dun->ent2room); } /* Add a trailing NULL so the deallocation knows when to stop. */ dun->ent2room = mem_alloc((c->height + 1) * sizeof(*dun->ent2room)); for (i = 0; i < c->height; ++i) { int j; dun->ent2room[i] = mem_alloc(c->width * sizeof(*dun->ent2room[i])); for (j = 0; j < c->width; ++j) { dun->ent2room[i][j] = -1; } } dun->ent2room[c->height] = NULL; } /** * Randomly choose a room entrance and return its coordinates. * \param c Is the chunk to use. * \param ridx Is the 0-based index for the room. * \param tgt If not NULL, the choice of entrance will either be *tgt if *tgt * is an entrance for the room, ridx, or can be biased to be closer to *tgt * when *tgt is not an entrance for the room, ridx. * \param bias Sets the amount of bias if tgt is not NULL and *tgt is not an * entrance for the room, ridx. A larger value increases the amount of bias. * A value of zero will give no bias. Must be non-negative. * \param exc Is an array of grids whose adjacent neighbors (but not the grid * itself) should be excluded from selection. May be NULL if nexc is not * positive. * \param nexc Is the number of grids to use from exc. * \return The returned value is an entrance for the room or (0, 0) if * no entrance is available. An entrance, x, satisfies these requirements: * 1) x is the same as dun->ent[ridx][k] for some k between 0 and * dun->ent_n[ridx - 1]. * 2) square_is_marked_granite(c, x, SQUARE_WALL_OUTER) is true. * 3) For all m between zero and nexc - 1, ABS(x.x - exc[m].x) > 1 or * ABS(x.y - exc[m].y) > 1 or (x.x == exc[m].x and x.y == exc[m].y). */ static struct loc choose_random_entrance(struct chunk *c, int ridx, const struct loc *tgt, int bias, const struct loc *exc, int nexc) { assert(ridx >= 0 && ridx < dun->cent_n); if (dun->ent_n[ridx] > 0) { int nchoice = 0; int *accum = mem_alloc((dun->ent_n[ridx] + 1) * sizeof(*accum)); int i; accum[0] = 0; for (i = 0; i < dun->ent_n[ridx]; ++i) { bool included = square_is_granite_with_flag(c, dun->ent[ridx][i], SQUARE_WALL_OUTER); if (included) { int j = 0; while (1) { struct loc diff; if (j >= nexc) { break; } diff = loc_diff(dun->ent[ridx][i], exc[j]); if (ABS(diff.x) <= 1 && ABS(diff.y) <= 1 && (diff.x != 0 || diff.y != 0)) { included = false; break; } ++j; } } if (included) { if (tgt) { int d, biased; assert(bias >= 0); d = distance(dun->ent[ridx][i], *tgt); if (d == 0) { /* * There's an exact match. Use * it. */ mem_free(accum); return dun->ent[ridx][i]; } biased = MAX(1, bias - d); /* * Squaring here is just a guess without * any specific reason to back it. */ accum[i + 1] = accum[i] + biased * biased; } else { accum[i + 1] = accum[i] + 1; } ++nchoice; } else { accum[i + 1] = accum[i]; } } if (nchoice > 0) { int chosen = randint0(accum[dun->ent_n[ridx]]); int low = 0, high = dun->ent_n[ridx]; /* Locate the selection by binary search. */ while (1) { int mid; if (low == high - 1) { assert(accum[low] <= chosen && accum[high] > chosen); mem_free(accum); return dun->ent[ridx][low]; } mid = (low + high) / 2; if (accum[mid] <= chosen) { low = mid; } else { high = mid; } } } mem_free(accum); } /* There's no satisfactory marked entrances. */ return loc(0, 0); } /** * Help build_tunnel(): pierce an outer wall and prevent nearby piercings. * \param c Is the chunk to use. * \param grid Is the location to pierce. */ static void pierce_outer_wall(struct chunk *c, struct loc grid) { struct loc adj; /* Save the wall location */ if (dun->wall_n < z_info->wall_pierce_max) { dun->wall[dun->wall_n] = grid; dun->wall_n++; } /* Forbid re-entry near this piercing */ for (adj.y = grid.y - 1; adj.y <= grid.y + 1; adj.y++) { for (adj.x = grid.x - 1; adj.x <= grid.x + 1; adj.x++) { if (adj.x != 0 && adj.y != 0 && square_in_bounds(c, adj) && square_is_granite_with_flag(c, adj, SQUARE_WALL_OUTER)) { set_marked_granite(c, adj, SQUARE_WALL_SOLID); } } } } /** * Help build_tunnel(): handle bookkeeping, mainly if there's a diagonal step, * for the first step after piercing a wall. * \param c Is the chunk to use. * \param grid At entry, *grid is the location at which the wall was pierced. * At exit, *grid is the starting point for the next iteration of tunnel * building. * \param dir At entry, *dir is the chosen direction for the first step after * the wall piercing. At exit, *dir is the direction for the next iteration of * tunnel building. * \param door_flag At entry, *door_flag is the current setting for whether a * door can be added. At exit, *door_flag is the setting for whether a door * can be added in the next iteration of tunnel building. * \param bend_intvl At entry, *bend_intvl is the current setting for the number * of tunnel iterations to wait before applying a bend. At exit, *bend_intvl * is what that intverval should be for the next iteration of tunnel building. */ static void handle_post_wall_step(struct chunk *c, struct loc *grid, struct loc *dir, bool *door_flag, int *bend_intvl) { if (dir->x != 0 && dir->y != 0) { /* * Take a diagonal step upon leaving the wall. Proceed to that. */ *grid = loc_sum(*grid, *dir); assert(!square_is_granite_with_flag(c, *grid, SQUARE_WALL_OUTER) && !square_is_granite_with_flag(c, *grid, SQUARE_WALL_SOLID) && !square_is_granite_with_flag(c, *grid, SQUARE_WALL_INNER) && !square_isperm(c, *grid)); if (!square_isroom(c, *grid) && square_isgranite(c, *grid)) { /* Save the tunnel location */ if (dun->tunn_n < z_info->tunn_grid_max) { dun->tunn[dun->tunn_n] = *grid; dun->tunn_n++; } /* Allow door in next grid */ *door_flag = false; } /* * Having pierced the wall and taken a step, can forget about * what was set to suppress bends in the past. */ *bend_intvl = 0; /* * Now choose a cardinal direction, one that is +/-45 degrees * from what was used for the diagonal step, for the next step * since the tunnel iterations want a cardinal direction. */ if (randint0(32768) < 16384) { dir->x = 0; } else { dir->y = 0; } } else { /* * Take a cardinal step upon leaving the wall. Most of the * passed in state is fine, but temporarily suppress bends so * the step will be handled as is by the next iteration of * tunnel building. */ *bend_intvl = 1; } } /** * Help build_tunnel(): choose a direction that is approximately normal to a * room's wall. * \param c Is the chunk to use. * \param grid Is a location on the wall. * \param inner If true, return a direction that points to the interior of the * room. Otherwise, return a direction pointing to the exterior. * \return The returned value is the chosen direction. It may be loc(0, 0) * if no feasible direction could be found. */ static struct loc find_normal_to_wall(struct chunk *c, struct loc grid, bool inner) { int n = 0, ncardinal = 0, i; struct loc choices[8]; assert(square_is_granite_with_flag(c, grid, SQUARE_WALL_OUTER) || square_is_granite_with_flag(c, grid, SQUARE_WALL_SOLID)); /* Relies on the cardinal directions being first in ddgrid_ddd. */ for (i = 0; i < 8; ++i) { struct loc chk = loc_sum(grid, ddgrid_ddd[i]); if (square_in_bounds(c, chk) && !square_isperm(c, chk) && (square_isroom(c, chk) == inner) && !square_is_granite_with_flag(c, chk, SQUARE_WALL_OUTER) && !square_is_granite_with_flag(c, chk, SQUARE_WALL_SOLID) && !square_is_granite_with_flag(c, chk, SQUARE_WALL_INNER)) { choices[n] = ddgrid_ddd[i]; ++n; if (i < 4) { ++ncardinal; } } } /* Prefer a cardinal direction if available. */ if (n > 1 && ncardinal > 0) { n = ncardinal; } return (n == 0) ? loc(0, 0) : choices[randint0(n)]; } /** * Help build_tunnel(): test if a wall-piercing location can have a door. * Don't want a door that's only adjacent to terrain that is either * 1) not passable and not rubble * 2) a door (treat a shop like a door) * on either the side facing outside the room or the side facing the room. * \param c Is the chunk to use. * \param grid Is the location of the wall piercing. */ static bool allows_wall_piercing_door(struct chunk *c, struct loc grid) { struct loc chk; int n_outside_good = 0; int n_inside_good = 0; for (chk.y = grid.y - 1; chk.y <= grid.y + 1; ++chk.y) { for (chk.x = grid.x - 1; chk.x <= grid.x + 1; ++chk.x) { if ((chk.y == 0 && chk.x == 0) || !square_in_bounds(c, chk)) continue; if ((square_ispassable(c, chk) || square_isrubble(c, chk)) && !square_isdoor(c, chk) && !square_isshop(c, chk)) { if (square_isroom(c, chk)) { ++n_inside_good; } else { ++n_outside_good; } } } } return n_outside_good > 0 && n_inside_good > 0; } /** * Constructs a tunnel between two points * * \param c is the current chunk * \param grid1 is the location of the first point * \param grid2 is the location of the second point * * This function must be called BEFORE any streamers are created, since we use * granite with the special SQUARE_WALL flags to keep track of legal places for * corridors to pierce rooms. * * Locations to excavate are queued and applied afterward. The wall piercings * are also queued but the outer wall grids adjacent to the piercing are marked * right away to prevent adjacent piercings. That makes testing where to * pierce easier (look at grid flags rather than search through the queued * piercings). * * The solid wall check prevents silly door placement and excessively wide * room entrances. */ static void build_tunnel(struct chunk *c, struct loc grid1, struct loc grid2) { int i; int dstart = ABS(grid1.x - grid2.x) + ABS(grid1.y - grid2.y); int main_loop_count = 0; struct loc start = grid1, tmp_grid, offset; /* Used to prevent random bends for a while. */ int bend_intvl = 0; /* * Used to prevent excessive door creation along overlapping corridors. */ bool door_flag = false; bool preemptive = false; /* Reset the arrays */ dun->tunn_n = 0; dun->wall_n = 0; /* Start out in the correct direction */ correct_dir(&offset, grid1, grid2); /* Keep going until done (or bored) */ while (!loc_eq(grid1, grid2)) { /* Mega-Hack -- Paranoia -- prevent infinite loops */ if (main_loop_count++ > 2000) break; /* Allow bends in the tunnel */ if (bend_intvl == 0) { if (randint0(100) < dun->profile->tun.chg) { /* Get the correct direction */ correct_dir(&offset, grid1, grid2); /* Random direction */ if (randint0(100) < dun->profile->tun.rnd) rand_dir(&offset); } } else { assert(bend_intvl > 0); --bend_intvl; } /* Get the next location */ tmp_grid = loc_sum(grid1, offset); while (!square_in_bounds(c, tmp_grid)) { /* Get the correct direction */ correct_dir(&offset, grid1, grid2); /* Random direction */ if (randint0(100) < dun->profile->tun.rnd) rand_dir(&offset); /* Get the next location */ tmp_grid = loc_sum(grid1, offset); } /* Avoid obstacles */ if ((square_isperm(c, tmp_grid) && !sqinfo_has(square(c, tmp_grid)->info, SQUARE_WALL_INNER)) || square_is_granite_with_flag(c, tmp_grid, SQUARE_WALL_SOLID)) { continue; } /* Pierce "outer" walls of rooms */ if (square_is_granite_with_flag(c, tmp_grid, SQUARE_WALL_OUTER)) { int iroom; struct loc nxtdir = loc_diff(grid2, tmp_grid); /* If it's the goal, accept and pierce the wall. */ if (nxtdir.x == 0 && nxtdir.y == 0) { grid1 = tmp_grid; pierce_outer_wall(c, grid1); continue; } /* * If it's adjacent to the goal and that is also an * outer wall, then can't pierce without making the * goal unreachable. */ if (ABS(nxtdir.x) <= 1 && ABS(nxtdir.y) <= 1 && square_is_granite_with_flag(c, grid2, SQUARE_WALL_OUTER)) { continue; } /* See if it is a marked entrance. */ iroom = dun->ent2room[tmp_grid.y][tmp_grid.x]; if (iroom != -1) { /* It is. */ assert(iroom >= 0 && iroom < dun->cent_n); if (square_isroom(c, grid1)) { /* * The tunnel is coming from inside the * room. See if there's somewhere on * the outside to go. */ nxtdir = find_normal_to_wall(c, tmp_grid, false); if (nxtdir.x == 0 && nxtdir.y == 0) { /* There isn't. */ continue; } /* * There is. Accept the grid and pierce * the wall. */ grid1 = tmp_grid; pierce_outer_wall(c, grid1); } else { /* * The tunnel is coming from outside the * room. Choose an entrance (perhaps * the same as the one just entered) to * use as the exit. Crudely adjust how * biased the entrance selection is * based on how often random steps are * taken while tunneling. The rationale * for a maximum bias of 80 is similar * to that in * do_traditional_tunneling(). */ int bias = 80 - ((80 * MIN(MAX(0, dun->profile->tun.chg), 100) * MIN(MAX(0, dun->profile->tun.rnd), 100)) / 10000); int ntry = 0, mtry = 20; struct loc exc[2] = { tmp_grid, grid2 }; struct loc chk = loc(0, 0); while (1) { if (ntry >= mtry) { /* * Didn't find a usable * exit. */ break; } chk = choose_random_entrance( c, iroom, &grid2, bias, exc, 2); if (chk.x == 0 && chk.y == 0) { /* No exits at all. */ ntry = mtry; break; } nxtdir = find_normal_to_wall( c, chk, false); if (nxtdir.x != 0 || nxtdir.y != 0) { /* * Found a usable exit. */ break; } ++ntry; /* Also make it less biased. */ bias = (bias * 8) / 10; } if (ntry >= mtry) { /* No usable exit was found. */ continue; } /* * Pierce the wall at the original * entrance. */ pierce_outer_wall(c, tmp_grid); /* * And at the exit which is also the * continuation point for the rest of * the tunnel. */ pierce_outer_wall(c, chk); grid1 = chk; } offset = nxtdir; handle_post_wall_step(c, &grid1, &offset, &door_flag, &bend_intvl); continue; } /* Is there a feasible location after the wall? */ nxtdir = find_normal_to_wall(c, tmp_grid, !square_isroom(c, grid1)); if (nxtdir.x == 0 && nxtdir.y == 0) { /* There's no feasible location. */ continue; } /* Accept the location and pierce the wall. */ grid1 = tmp_grid; pierce_outer_wall(c, grid1); offset = nxtdir; handle_post_wall_step(c, &grid1, &offset, &door_flag, &bend_intvl); } else if (square_isroom(c, tmp_grid)) { /* Travel quickly through rooms */ /* Accept the location */ grid1 = tmp_grid; } else if (square_isgranite(c, tmp_grid)) { /* Tunnel through all other walls */ /* Accept this location */ grid1 = tmp_grid; /* Save the tunnel location */ if (dun->tunn_n < z_info->tunn_grid_max) { dun->tunn[dun->tunn_n] = grid1; dun->tunn_n++; } /* Allow door in next grid */ door_flag = false; } else { /* Handle corridor intersections or overlaps */ assert(square_in_bounds_fully(c, tmp_grid)); /* Accept the location */ grid1 = tmp_grid; /* Collect legal door locations */ if (!door_flag) { /* Save the door location */ if (dun->door_n < z_info->level_door_max) { dun->door[dun->door_n] = grid1; dun->door_n++; } /* No door in next grid */ door_flag = true; } /* Allow pre-emptive tunnel termination */ if (randint0(100) >= dun->profile->tun.con) { /* Offset between grid1 and start */ tmp_grid = loc_diff(grid1, start); /* Terminate the tunnel if too far vertically or horizontally */ if ((ABS(tmp_grid.x) > 10) || (ABS(tmp_grid.y) > 10)) { preemptive = true; break; } } } } /* Turn the tunnel into corridor */ for (i = 0; i < dun->tunn_n; i++) { /* Clear previous contents, add a floor */ square_set_feat(c, dun->tunn[i], FEAT_FLOOR); } /* Apply the piercings that we found */ for (i = 0; i < dun->wall_n; i++) { /* Convert to floor grid */ square_set_feat(c, dun->wall[i], FEAT_FLOOR); /* Place a random door */ if (randint0(100) < dun->profile->tun.pen && allows_wall_piercing_door(c, dun->wall[i])) place_random_door(c, dun->wall[i]); } event_signal_tunnel(EVENT_GEN_TUNNEL_FINISHED, main_loop_count, dun->wall_n, dun->tunn_n, dstart, ABS(grid1.x - grid2.x) + ABS(grid1.y - grid2.y), preemptive); } /** * Count the number of corridor grids adjacent to the given grid. * * This routine currently only counts actual "empty floor" grids which are not * in rooms. * \param c is the current chunk * \param grid is the coordinates of the grid of interest * * TODO: count stairs, open doors, closed doors? */ static int next_to_corr(struct chunk *c, struct loc grid) { int i, k = 0; assert(square_in_bounds(c, grid)); /* Scan adjacent grids */ for (i = 0; i < 4; i++) { /* Extract the location */ struct loc grid1 = loc_sum(grid, ddgrid_ddd[i]); /* Count only floors which aren't part of rooms */ if (square_isfloor(c, grid1) && !square_isroom(c, grid1)) k++; } /* Return the number of corridors */ return k; } /** * Returns whether a doorway can be built in a space. * \param c is the current chunk * \param grid is the coordinates of the point to check * * To have a doorway, a space must be adjacent to at least two corridors and be * between two walls. */ static bool possible_doorway(struct chunk *c, struct loc grid) { assert(square_in_bounds(c, grid)); if (next_to_corr(c, grid) < 2) return false; else if (square_isstrongwall(c, next_grid(grid, DIR_N)) && square_isstrongwall(c, next_grid(grid, DIR_S))) return true; else if (square_isstrongwall(c, next_grid(grid, DIR_W)) && square_isstrongwall(c, next_grid(grid, DIR_E))) return true; else return false; } /** * Places door or trap at a position if at least 2 walls found * \param c is the current chunk * \param grid is the location to potentially place the door or trap */ static void try_door(struct chunk *c, struct loc grid) { assert(square_in_bounds(c, grid)); if (square_isstrongwall(c, grid)) return; if (square_isroom(c, grid)) return; if (square_isplayertrap(c, grid)) return; if (square_isdoor(c, grid)) return; if (randint0(100) < dun->profile->tun.jct && possible_doorway(c, grid)) place_random_door(c, grid); else if (randint0(500) < dun->profile->tun.jct && possible_doorway(c, grid)) place_trap(c, grid, -1, c->depth); } /** * Connect the rooms with tunnels in the traditional fashion. * \param c Is the chunk to use. */ static void do_traditional_tunneling(struct chunk *c) { int *scrambled = mem_alloc(dun->cent_n * sizeof(*scrambled)); int i; struct loc grid; /* * Scramble the order in which the rooms will be connected. Use * indirect indexing so dun->ent2room can be left as it is. */ for (i = 0; i < dun->cent_n; ++i) { scrambled[i] = i; } for (i = 0; i < dun->cent_n; ++i) { int pick1 = randint0(dun->cent_n); int pick2 = randint0(dun->cent_n); int tmp = scrambled[pick1]; scrambled[pick1] = scrambled[pick2]; scrambled[pick2] = tmp; } /* Start with no tunnel doors. */ dun->door_n = 0; /* * Link the rooms in the scrambled order with the first connecting to * the last. The bias argument for choose_random_entrance() was * somewhat arbitrarily chosen: i.e. if the room is more than a * typical screen width away, don't particularly care which entrance is * selected. */ grid = choose_random_entrance(c, scrambled[dun->cent_n - 1], NULL, 80, NULL, 0); if (grid.x == 0 && grid.y == 0) { /* Use the room's center. */ grid = dun->cent[scrambled[dun->cent_n - 1]]; } for (i = 0; i < dun->cent_n; ++i) { struct loc next_grid = choose_random_entrance(c, scrambled[i], &grid, 80, NULL, 0); if (next_grid.x == 0 && next_grid.y == 0) { next_grid = dun->cent[scrambled[i]]; } build_tunnel(c, next_grid, grid); /* Remember the "previous" room. */ grid = next_grid; } mem_free(scrambled); /* Place intersection doors. */ for (i = 0; i < dun->door_n; ++i) { /* Try placing doors. */ try_door(c, next_grid(dun->door[i], DIR_W)); try_door(c, next_grid(dun->door[i], DIR_E)); try_door(c, next_grid(dun->door[i], DIR_N)); try_door(c, next_grid(dun->door[i], DIR_S)); } } /** * Build the staircase rooms for a persistent level. */ static void build_staircase_rooms(struct chunk *c, const char *label) { int num_rooms = dun->profile->n_room_profiles; struct room_profile profile; struct connector *join; int i; for (i = 0; i < num_rooms; i++) { profile = dun->profile->room_profiles[i]; if (streq(profile.name, "staircase room")) { break; } } assert(i < num_rooms); for (join = dun->join; join; join = join->next) { dun->curr_join = join; if (!room_build(c, (join->grid.y - 1) / dun->block_hgt, (join->grid.x - 1) / dun->block_wid, profile, true)) { dump_level_simple(NULL, format("%s: Failed to Build " "Staircase Room at Row=%d Column=%d in a " "Cave with %d Rows and %d Columns", label, join->grid.y, join->grid.x, c->height, c->width), c); quit("Failed to place stairs"); } ++dun->nstair_room; } } /** * Add stairs to a level, taking into account the special treatment needed * for persistent levels. */ static void handle_level_stairs(struct chunk *c, bool persistent, bool quest, int down_count, int up_count) { /* * For persistent levels, require that the stairs be at least four * grids apart (two for surrounding walls; two for a buffer between * the walls; the buffer space could be one - shared by the * staircases - but the reservations in the room map don't allow for * that) so the staircase rooms in the connecting level won't overlap. * For both the persistent and non-persistent case, also require that * the stairs be at least 1/4th of the level's diameter (PowerDiver's * suggestion) apart to prevent them from all appearing in certain * rooms. */ int minsep = MAX(MIN(c->width, c->height) / 4, (persistent) ? 4 : 0); if (!persistent || !chunk_find_adjacent(c->depth, false)) { alloc_stairs(c, FEAT_MORE, down_count, minsep, false, dun->one_off_below, quest); } if (!persistent || !chunk_find_adjacent(c->depth, true)) { alloc_stairs(c, FEAT_LESS, up_count, minsep, false, dun->one_off_above, quest); } } /** * Locate two consecutive columns that do not contain any connections to other * levels. * \param join Is the linked list of connection information. * \param colpref Is the column for the center of the search range. If there * are multiple possible results, prefer the one closest to colpref. * \param range The search includes the columns from colpref - range to * colpref + range, inclusive. range must be non-negative. * \param rowmin Ignore any connection whose row coordinate is less than rowmin. * \param rowmax Ignore any connection whose row coordinate is greater than * rowmax. * \return Return the column index of the first column in the pair or, if * two consecutive columns without connections could not be found, -1. */ static int find_joinfree_vertical_seam(const struct connector *join, int colpref, int range, int rowmin, int rowmax) { int metric = range + 1; int result = -1; int i; /* Remember which columns in the range had a connector. */ bool *disallowed; assert(range >= 0); disallowed = mem_zalloc((range + range + 1) * sizeof(*disallowed)); /* * Scan the connections and record the columns that can't be in a * seam. */ for (; join; join = join->next) { if (ABS(join->grid.x - colpref) <= range && join->grid.y >= rowmin && join->grid.y <= rowmax) { disallowed[range + join->grid.x - colpref] = true; } } /* * Find the pair of adjacent columns that are allowed and are closest * to colpref. */ i = 0; while (i < range + range) { if (!disallowed[i]) { if (!disallowed[i + 1]) { if (metric > ABS(i - range)) { metric = ABS(i - range); result = colpref + i - range; } ++i; } else { i += 2; } } else { ++i; } } mem_free(disallowed); return result; } /** * Generate a new linked list of connections based on a geometric transform, * via gen-chunk.c's symmetry_transform(), and clipping of another list of * connections. * \param join Is the source linked list of connections. * \param nrow Is the number of rows for the chunk that'll contain the * transformed connections. * \param ncol Is the number of columns for the chunk that'll contain the * transformed connections. * \param y0 Is the translation in y (rows) applied after the rotations and * reflection that places the nrow by ncol chunk into the coordinate system * for the untransformed connections. * \param x0 Is the translation in x (columns) applied after the rotations and * reflection that places the nrow by ncol chunk into the coordinate system * for the untransformed connections. * \param rotate Is the number of 90 clockwise rotations to apply to nrow by * ncol chunk to get it into the coordinate system for the untransformed * coordinates. * \param reflect Is whether a horizontal reflection (after applying the * rotations) is necessary to get the nrow by ncol chunk into the coordinate * system for the untransformed coordinates. * \return Returns a dynamically allocated linked list (each element will have * to be released by mem_free) of the transformed connection coordinates or * NULL if the list is empty. */ static struct connector *transform_join_list(const struct connector *join, int nrow, int ncol, int y0, int x0, int rotate, bool reflect) { /* * The transformation specified by the arguments is that to map the * chunk to the untransformed coordinates of the connections. Invert * that to get the transformation to apply to the connections. Mimic * the logic symmetry_transform(). */ struct connector *result = NULL; struct connector **next_link = &result; int ntcol, ntrow, i; /* * Get the dimensions of the chunk after the forward (chunk to * untransformed connection coordinates) transform. */ ntrow = nrow; ntcol = ncol; for (i = 0; i < rotate % 4; ++i) { int temp = ntrow; ntrow = ntcol; ntcol = temp; } for (; join; join = join->next) { /* Undo the translation. */ struct loc g = loc(join->grid.x - x0, join->grid.y - y0); int rheight = nrow, rwidth = ncol; /* Only keep the ones that are in bounds for the chunk. */ if (g.y < 0 || g.y >= nrow || g.x < 0 || g.x >= ncol) continue; /* Undo the reflection. */ if (reflect) { g.x = ncol - 1 - g.x; } /* Undo the rotations. */ for (i = 0; i < rotate % 4; ++i) { int temp = g.y; g.y = rwidth - 1 - g.x; g.x = temp; temp = rwidth; rwidth = rheight; rheight = temp; } *next_link = mem_zalloc(sizeof(**next_link)); (*next_link)->grid = g; (*next_link)->feat = join->feat; next_link = &((*next_link)->next); } return result; } /** * Generate a new dungeon level. * \param p is the player * \param min_height is the minimum expected height, in grids, for the level. * \param min_width is the minimum expected width, in grids, for the level. * \param p_error will be dereferenced and set to a the address of a constant * string describing the failure when the returned chunk is NULL. * \return a pointer to the generated chunk * This level builder ignores the minimum height and width. */ struct chunk *classic_gen(struct player *p, int min_height, int min_width, const char **p_error) { int i, j, k; int by, bx = 0, tby, tbx, key, rarity, built; int num_rooms, size_percent; int dun_unusual = dun->profile->dun_unusual; bool **blocks_tried; struct chunk *c; /* This code currently does nothing - see comments below */ i = randint1(10) + p->depth / 24; if (dun->quest) size_percent = 100; else if (i < 2) size_percent = 75; else if (i < 3) size_percent = 80; else if (i < 4) size_percent = 85; else if (i < 5) size_percent = 90; else if (i < 6) size_percent = 95; else size_percent = 100; /* scale the various generation variables */ num_rooms = (dun->profile->dun_rooms * size_percent) / 100; dun->block_hgt = dun->profile->block_size; dun->block_wid = dun->profile->block_size; c = cave_new(z_info->dungeon_hgt, z_info->dungeon_wid); c->depth = p->depth; ROOM_LOG("height=%d width=%d nrooms=%d", c->height, c->width, num_rooms); /* Fill cave area with basic granite */ fill_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_GRANITE, SQUARE_NONE); /* Actual maximum number of rooms on this level */ dun->row_blocks = c->height / dun->block_hgt; dun->col_blocks = c->width / dun->block_wid; /* Initialize the room table */ dun->room_map = mem_zalloc(dun->row_blocks * sizeof(bool*)); for (i = 0; i < dun->row_blocks; i++) dun->room_map[i] = mem_zalloc(dun->col_blocks * sizeof(bool)); /* Initialize the block table */ blocks_tried = mem_zalloc(dun->row_blocks * sizeof(bool*)); for (i = 0; i < dun->row_blocks; i++) blocks_tried[i] = mem_zalloc(dun->col_blocks * sizeof(bool)); /* No rooms yet, pits or otherwise. */ dun->pit_num = 0; dun->cent_n = 0; reset_entrance_data(c); /* Build the special staircase rooms */ if (dun->persist) { build_staircase_rooms(c, "Classic Generation"); } /* Build some rooms. Note that the theoretical maximum number of rooms * in this profile is currently 36, so built never reaches num_rooms, * and room generation is always terminated by having tried all blocks */ built = 0; while(built < num_rooms) { /* Count the room blocks we haven't tried yet. */ j = 0; tby = 0; tbx = 0; for(by = 0; by < dun->row_blocks; by++) { for(bx = 0; bx < dun->col_blocks; bx++) { if (blocks_tried[by][bx]) continue; j++; if (one_in_(j)) { tby = by; tbx = bx; } } } bx = tbx; by = tby; /* If we've tried all blocks we're done. */ if (j == 0) break; if (blocks_tried[by][bx]) quit_fmt("generation: inconsistent blocks"); /* Mark that we are trying this block. */ blocks_tried[by][bx] = true; /* Roll for random key (to be compared against a profile's cutoff) */ key = randint0(100); /* We generate a rarity number to figure out how exotic to make * the room. This number has a (50+depth/2)/DUN_UNUSUAL chance * of being > 0, a (50+depth/2)^2/DUN_UNUSUAL^2 chance of * being > 1, up to MAX_RARITY. */ i = 0; rarity = 0; while (i == rarity && i < dun->profile->max_rarity) { if (randint0(dun_unusual) < 50 + c->depth / 2) rarity++; i++; } /* Once we have a key and a rarity, we iterate through out list of * room profiles looking for a match (whose cutoff > key and whose * rarity > this rarity). We try building the room, and if it works * then we are done with this iteration. We keep going until we find * a room that we can build successfully or we exhaust the profiles. */ for (i = 0; i < dun->profile->n_room_profiles; i++) { struct room_profile profile = dun->profile->room_profiles[i]; if (profile.rarity > rarity) continue; if (profile.cutoff <= key) continue; if (room_build(c, by, bx, profile, false)) { built++; break; } } } for (i = 0; i < dun->row_blocks; i++){ mem_free(blocks_tried[i]); mem_free(dun->room_map[i]); } mem_free(blocks_tried); mem_free(dun->room_map); /* Generate permanent walls around the edge of the generated area */ draw_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_PERM, SQUARE_NONE, true); /* Connect all the rooms together */ do_traditional_tunneling(c); ensure_connectedness(c, true); /* Add some magma streamers */ for (i = 0; i < dun->profile->str.mag; i++) build_streamer(c, FEAT_MAGMA, dun->profile->str.mc); /* Add some quartz streamers */ for (i = 0; i < dun->profile->str.qua; i++) build_streamer(c, FEAT_QUARTZ, dun->profile->str.qc); /* Place 3 or 4 down stairs and 1 or 2 up stairs near some walls */ handle_level_stairs(c, dun->persist, dun->quest, rand_range(3, 4), rand_range(1, 2)); /* General amount of rubble, traps and monsters */ k = MAX(MIN(c->depth / 3, 10), 2); /* Put some rubble in corridors */ alloc_objects(c, SET_CORR, TYP_RUBBLE, randint1(k), c->depth, 0); /* Place some traps in the dungeon, reduce frequency by factor of 5 */ alloc_objects(c, SET_CORR, TYP_TRAP, randint1(k)/5, c->depth, 0); /* Determine the character location */ if (!new_player_spot(c, p)) { uncreate_artifacts(c); wipe_mon_list(c, p); cave_free(c); *p_error = "could not place player"; return NULL; } /* Pick a base number of monsters */ i = z_info->level_monster_min + randint1(8) + k; /* Put some monsters in the dungeon */ for (; i > 0; i--) { pick_and_place_distant_monster(c, p->grid, 0, true, c->depth); } /* Put some objects in rooms */ alloc_objects(c, SET_ROOM, TYP_OBJECT, Rand_normal(z_info->room_item_av, 3), c->depth, ORIGIN_FLOOR); /* Put some objects/gold in the dungeon */ alloc_objects(c, SET_BOTH, TYP_OBJECT, Rand_normal(z_info->both_item_av, 3), c->depth, ORIGIN_FLOOR); alloc_objects(c, SET_BOTH, TYP_GOLD, Rand_normal(z_info->both_gold_av, 3), c->depth, ORIGIN_FLOOR); return c; } /* ------------------ LABYRINTH ---------------- */ /** * Given an adjoining wall (a wall which separates two labyrinth cells) * set a and b to point to the cell indices which are separated. Used by * labyrinth_gen(). * \param i is the wall index * \param w is the width of the labyrinth * \param a are the two cell indices * \param b are the two cell indices */ static void lab_get_adjoin(int i, int w, int *a, int *b) { struct loc grid; i_to_grid(i, w, &grid); if (grid.x % 2 == 0) { *a = grid_to_i(next_grid(grid, DIR_N), w); *b = grid_to_i(next_grid(grid, DIR_S), w); } else { *a = grid_to_i(next_grid(grid, DIR_W), w); *b = grid_to_i(next_grid(grid, DIR_E), w); } } /** * Return whether a grid is in a tunnel. * * \param c is the current chunk * \param grid is the location * * For our purposes a tunnel is a horizontal or vertical path, not an * intersection. Thus, we want the squares on either side to walls in one * case (e.g. up/down) and open in the other case (e.g. left/right). We don't * want a square that represents an intersection point. Treat doors the same * as open floors in the tests since doors may replace a floor but not a wall. * * The high-level idea is that these are squares which can't be avoided (by * walking diagonally around them). */ static bool lab_is_tunnel(struct chunk *c, struct loc grid) { bool west = square_ispassable(c, next_grid(grid, DIR_W)) || square_iscloseddoor(c, next_grid(grid, DIR_W)); bool east = square_ispassable(c, next_grid(grid, DIR_E)) || square_iscloseddoor(c, next_grid(grid, DIR_E)); bool north = square_ispassable(c, next_grid(grid, DIR_N)) || square_iscloseddoor(c, next_grid(grid, DIR_N)); bool south = square_ispassable(c, next_grid(grid, DIR_S)) || square_iscloseddoor(c, next_grid(grid, DIR_S)); return north == south && west == east && north != west; } /** * Build a labyrinth chunk of a given height and width * * \param depth is the native depth * \param h are the dimensions of the chunk * \param w are the dimensions of the chunk * \param lit is whether the labyrinth is lit * \param soft is true if we use regular walls, false if permanent walls * \return a pointer to the generated chunk */ static struct chunk *labyrinth_chunk(int depth, int h, int w, bool lit, bool soft) { int i, j, k; struct loc grid; int *find_state; /* This is the number of squares in the labyrinth */ int n = h * w; /* NOTE: 'sets' and 'walls' are too large... we only need to use about * 1/4 as much memory. However, in that case, the addressing math * becomes a lot more complicated, so let's just stick with this * because it's easier to read. */ /* 'sets' tracks connectedness; if sets[i] == sets[j] then cells i and j * are connected to each other in the maze. */ int *sets; /* 'walls' is a list of wall coordinates which we will randomize */ int *walls; /* The labyrinth chunk */ struct chunk *c = cave_new(h + 2, w + 2); c->depth = depth; /* allocate our arrays */ sets = mem_zalloc(n * sizeof(int)); walls = mem_zalloc(n * sizeof(int)); /* Bound with perma-rock */ draw_rectangle(c, 0, 0, h + 1, w + 1, FEAT_PERM, SQUARE_NONE, true); /* Fill the labyrinth area with rock */ if (soft) fill_rectangle(c, 1, 1, h, w, FEAT_GRANITE, SQUARE_WALL_SOLID); else fill_rectangle(c, 1, 1, h, w, FEAT_PERM, SQUARE_NONE); /* Initialize each wall. */ for (i = 0; i < n; i++) { walls[i] = i; sets[i] = -1; } /* Cut out a grid of 1x1 rooms which we will call "cells" */ for (grid.y = 0; grid.y < h; grid.y += 2) { for (grid.x = 0; grid.x < w; grid.x += 2) { int k_local = grid_to_i(grid, w); struct loc diag = next_grid(grid, DIR_SE); sets[k_local] = k_local; square_set_feat(c, diag, FEAT_FLOOR); if (lit) sqinfo_on(square(c, diag)->info, SQUARE_GLOW); } } /* Shuffle the walls, using Knuth's shuffle. */ shuffle(walls, n); /* For each adjoining wall, look at the cells it divides. If they aren't * in the same set, remove the wall and join their sets. * * This is a randomized version of Kruskal's algorithm. */ for (i = 0; i < n; i++) { int a, b; j = walls[i]; /* If this cell isn't an adjoining wall, skip it */ i_to_grid(j, w, &grid); if ((grid.x < 1 && grid.y < 1) || (grid.x > w - 2 && grid.y > h - 2)) continue; if (grid.x % 2 == grid.y % 2) continue; /* Figure out which cells are separated by this wall */ lab_get_adjoin(j, w, &a, &b); /* If the cells aren't connected, kill the wall and join the sets */ if (sets[a] != sets[b]) { int sa = sets[a]; int sb = sets[b]; square_set_feat(c, next_grid(grid, DIR_SE), FEAT_FLOOR); if (lit) { sqinfo_on(square(c, next_grid(grid, DIR_SE))->info, SQUARE_GLOW); } for (k = 0; k < n; k++) { if (sets[k] == sb) sets[k] = sa; } } } /* Deallocate our lists */ mem_free(sets); mem_free(walls); /* Generate a door for every 100 squares in the labyrinth */ find_state = cave_find_init(loc(1, 1), loc(c->width - 2, c->height - 2)); i = n / 100; while (i > 0 && cave_find_get_grid(&grid, find_state)) { if (square_isempty(c, grid) && lab_is_tunnel(c, grid)) { place_closed_door(c, grid); --i; } } mem_free(find_state); /* Unlit labyrinths will have some good items */ if (!lit) alloc_objects(c, SET_BOTH, TYP_GOOD, Rand_normal(3, 2), c->depth, ORIGIN_LABYRINTH); /* Hard (non-diggable) labyrinths will have some great items */ if (!soft) alloc_objects(c, SET_BOTH, TYP_GREAT, Rand_normal(2, 1), c->depth, ORIGIN_LABYRINTH); return c; } /** * Build a labyrinth level. * \param p is the player * \param min_height is the minimum expected height, in grids, for the level. * \param min_width is the minimum expected width, in grids, for the level. * \param p_error will be dereferenced and set to a the address of a constant * string describing the failure when the returned chunk is NULL. * \return a pointer to the generated chunk */ struct chunk *labyrinth_gen(struct player *p, int min_height, int min_width, const char **p_error) { int i, k; struct chunk *c; struct loc grid; /* Size of the actual labyrinth part must be odd. */ /* NOTE: these are not the actual dungeon size, but rather the size of * the area we're generating a labyrinth in (which doesn't count the * enclosing outer walls. */ int h = 15 + randint0(p->depth / 10) * 2; int w = 51 + randint0(p->depth / 10) * 2; /* Most labyrinths are lit */ bool lit = randint0(p->depth) < 25 || randint0(2) < 1; /* Many labyrinths are known */ bool known = lit && randint0(p->depth) < 25; /* Most labyrinths have soft (diggable) walls */ bool soft = randint0(p->depth) < 35 || randint0(3) < 2; /* No persistent levels of this type for now */ if (dun->persist) { *p_error = "no labyrinth levels in persistent dungeons"; return NULL; } /* Enforce minimum dimensions */ h = MAX(h, min_height); w = MAX(w, min_width); /* Generate the actual labyrinth */ c = labyrinth_chunk(p->depth, h, w, lit, soft); if (!c) { *p_error = "labyrinth chunk could not be created"; return NULL; } /* Determine the character location */ if (!new_player_spot(c, p)) { uncreate_artifacts(c); cave_free(c); *p_error = "could not place player"; return NULL; } /* Generate a single set of stairs up if necessary. */ if (!cave_find(c, &grid, square_isupstairs)) alloc_stairs(c, FEAT_LESS, 1, 0, false, NULL, dun->quest); /* Generate a single set of stairs down if necessary. */ if (!cave_find(c, &grid, square_isdownstairs)) alloc_stairs(c, FEAT_MORE, 1, 0, false, NULL, dun->quest); /* General some rubble, traps and monsters */ k = MAX(MIN(c->depth / 3, 10), 2); /* Scale number of monsters items by labyrinth size */ k = (3 * k * (h * w)) / (z_info->dungeon_hgt * z_info->dungeon_wid); /* Put some rubble in corridors */ alloc_objects(c, SET_BOTH, TYP_RUBBLE, randint1(k), c->depth, 0); /* Place some traps in the dungeon */ alloc_objects(c, SET_CORR, TYP_TRAP, randint1(k), c->depth, 0); /* Put some monsters in the dungeon */ for (i = z_info->level_monster_min + randint1(8) + k; i > 0; i--) { pick_and_place_distant_monster(c, p->grid, 0, true, c->depth); } /* Put some objects/gold in the dungeon */ alloc_objects(c, SET_BOTH, TYP_OBJECT, Rand_normal(k * 6, 2), c->depth, ORIGIN_LABYRINTH); alloc_objects(c, SET_BOTH, TYP_GOLD, Rand_normal(k * 3, 2), c->depth, ORIGIN_LABYRINTH); alloc_objects(c, SET_BOTH, TYP_GOOD, randint1(2), c->depth, ORIGIN_LABYRINTH); /* Notify if we want the player to see the maze layout */ if (known) { p->upkeep->light_level = true; } return c; } /* ---------------- CAVERNS ---------------------- */ /** * Initialize the dungeon array, with a random percentage of squares open. * \param c is the current chunk * \param density is the percentage of floors we are aiming for * \param join Is a linked list of the connection information to adjacent * levels; the cavern will build in stairs at those locations. May be NULL * to not build in stairs during cavern generation. */ static void init_cavern(struct chunk *c, int density, const struct connector *join) { int h = c->height; int w = c->width; int size = h * w; int count = (size * density) / 100; /* Fill the entire chunk with rock */ fill_rectangle(c, 0, 0, h - 1, w - 1, FEAT_GRANITE, SQUARE_WALL_SOLID); /* * Add in the desired stairs. Surround each staircase with three * floors, preferentially pointing to the center of the level, so the * staircase will remain in place during applications of * mutate_cavern(). Make three of the other squares adjacent to * the stairs permanent rock so they'll remain as walls during * applications of mutate_cavern(). */ while (join) { if (join->grid.y > 0 && join->grid.y < h - 1 && join->grid.x > 0 && join->grid.x < w - 1 && !square_isstairs(c, join->grid)) { int bcrit = randint0(h) + ((join->grid.y > h / 2) ? -10 : 10); int rcrit = randint0(w) + ((join->grid.x > w / 2) ? -10 : 10); int offy = (bcrit > join->grid.y) ? 1 : -1; int offx = (rcrit > join->grid.x) ? 1 : -1; struct loc adj; if (!square_isfloor(c, join->grid)) { --count; } square_set_feat(c, join->grid, join->feat); adj = loc(join->grid.x + offx, join->grid.y + offy); if (!square_isstairs(c, adj) && !square_isfloor(c, adj)) { --count; square_set_feat(c, adj, FEAT_FLOOR); } adj = loc(join->grid.x, join->grid.y + offy); if (!square_isstairs(c, adj) && !square_isfloor(c, adj)) { --count; square_set_feat(c, adj, FEAT_FLOOR); } adj = loc(join->grid.x + offx, join->grid.y); if (!square_isstairs(c, adj) && !square_isfloor(c, adj)) { --count; square_set_feat(c, adj, FEAT_FLOOR); } adj = loc(join->grid.x - offx, join->grid.y - offy); if (square_isrock(c, adj)) { square_set_feat(c, adj, FEAT_PERM); } adj = loc(join->grid.x, join->grid.y - offy); if (square_isrock(c, adj)) { square_set_feat(c, adj, FEAT_PERM); } adj = loc(join->grid.x - offx, join->grid.y); if (square_isrock(c, adj)) { square_set_feat(c, adj, FEAT_PERM); } } join = join->next; } while (count > 0) { struct loc grid = loc(randint1(w - 2), randint1(h - 2)); if (square_isrock(c, grid)) { square_set_feat(c, grid, FEAT_FLOOR); count--; } } } /** * Run a single pass of the cellular automata rules (4,5) on the dungeon. * \param c is the chunk being mutated */ static void mutate_cavern(struct chunk *c) { struct loc grid; int h = c->height; int w = c->width; int *temp = mem_zalloc(h * w * sizeof(int)); for (grid.y = 1; grid.y < h - 1; grid.y++) { for (grid.x = 1; grid.x < w - 1; grid.x++) { int count = 8 - count_neighbors(NULL, c, grid, square_ispassable, false); if (square_isstairs(c, grid) || square_isperm(c, grid)) { temp[grid_to_i(grid, w)] = square(c, grid)->feat; } else if (count > 5) { temp[grid_to_i(grid, w)] = FEAT_GRANITE; } else if (count < 4) { temp[grid_to_i(grid, w)] = FEAT_FLOOR; } else { temp[grid_to_i(grid, w)] = square(c, grid)->feat; } } } for (grid.y = 1; grid.y < h - 1; grid.y++) { for (grid.x = 1; grid.x < w - 1; grid.x++) { if (temp[grid_to_i(grid, w)] == FEAT_GRANITE) set_marked_granite(c, grid, SQUARE_WALL_SOLID); else square_set_feat(c, grid, temp[grid_to_i(grid, w)]); } } mem_free(temp); } /** * Fill an int[] with a single value. * \param data is the array * \param value is what it's being filled with * \param size is the array length */ static void array_filler(int data[], int value, int size) { int i; for (i = 0; i < size; i++) data[i] = value; } /** * Determine if we need to worry about coloring a point, or can ignore it. * \param c is the current chunk * \param colors is the array of current point colors * \param grid is the coordinates of the point of interest */ static int ignore_point(struct chunk *c, int colors[], struct loc grid) { int n = grid_to_i(grid, c->width); if (!square_in_bounds(c, grid)) return true; if (colors[n]) return true; if (square_ispassable(c, grid)) return false; if (square_isdoor(c, grid)) return false; return true; } /** * Color a particular point, and all adjacent points. * \param c is the current chunk * \param colors is the array of current point colors * \param counts is the array of current color counts * \param stairs If not NULL, stairs is an array with the same number of * elements as counts. At exit, stairs[i] will indicate whether the region * with color i includes a staircase. * \param grid is the location * \param color is the color we are coloring * \param diagonal controls whether we can progress diagonally */ static void build_color_point(struct chunk *c, int colors[], int counts[], bool *stairs, struct loc grid, int color, bool diagonal) { int h = c->height; int w = c->width; int size = h * w; struct queue *queue = q_new(size); int *added = mem_zalloc(size * sizeof(int)); array_filler(added, 0, size); q_push_int(queue, grid_to_i(grid, w)); counts[color] = 0; while (q_len(queue) > 0) { int i; struct loc grid1; int n1 = q_pop_int(queue); i_to_grid(n1, w, &grid1); if (ignore_point(c, colors, grid1)) continue; colors[n1] = color; counts[color]++; if (stairs && square_isstairs(c, grid1)) stairs[color] = true; for (i = 0; i < (diagonal ? 8 : 4); i++) { struct loc grid2 = loc_sum(grid1, ddgrid_ddd[i]); int n2 = grid_to_i(grid2, w); if (ignore_point(c, colors, grid2)) continue; if (added[n2]) continue; q_push_int(queue, n2); added[n2] = 1; } } mem_free(added); q_free(queue); } /** * Create a color for each "NESW contiguous" region of the dungeon. * \param c is the current chunk * \param colors is the array of current point colors * \param counts is the array of current color counts * \param stairs If not NULL, stairs is an array with the same number of * elements as counts. At exit, stairs[i] will indicate whether the region * with color i includes a staircase. * \param diagonal controls whether we can progress diagonally */ static void build_colors(struct chunk *c, int colors[], int counts[], bool *stairs, bool diagonal) { int y, x; int h = c->height; int w = c->width; int color = 1; for (y = 0; y < h; y++) { for (x = 0; x < w; x++) { if (ignore_point(c, colors, loc(x, y))) continue; build_color_point(c, colors, counts, stairs, loc(x, y), color, diagonal); color++; } } } /** * Find and delete all small (<9 square) open regions. * \param c is the current chunk * \param colors is the array of current point colors * \param counts is the array of current color counts * \param stairs If not NULL, stairs is an array with the same number of * elements as counts and stairs[i] will indicate whether the region with * color i includes a staircase. Regions with staircases will not be deleted. */ static void clear_small_regions(struct chunk *c, int colors[], int counts[], bool *stairs) { int i, y, x; int h = c->height; int w = c->width; int size = h * w; int *deleted = mem_zalloc(size * sizeof(int)); array_filler(deleted, 0, size); for (i = 0; i < size; i++) { if (counts[i] < 9 && (!stairs || !stairs[i])) { deleted[i] = 1; counts[i] = 0; } } for (y = 1; y < c->height - 1; y++) { for (x = 1; x < c->width - 1; x++) { struct loc grid = loc(x, y); i = grid_to_i(grid, w); if (!deleted[colors[i]]) continue; colors[i] = 0; set_marked_granite(c, grid, SQUARE_WALL_SOLID); } } mem_free(deleted); } /** * Return the number of colors which have active cells. * \param counts is the array of current color counts * \param size is the total area */ static int count_colors(int counts[], int size) { int i; int num = 0; for (i = 0; i < size; i++) if (counts[i] > 0) num++; return num; } /** * Return the first color which has one or more active cells. * \param counts is the array of current color counts * \param size is the total area */ static int first_color(int counts[], int size) { int i; for (i = 0; i < size; i++) if (counts[i] > 0) return i; return -1; } /** * Find all cells of 'fromcolor' and repaint them to 'tocolor'. * \param colors is the array of current point colors * \param counts is the array of current color counts * \param from is the color to change * \param to is the color to change to * \param size is the total area */ static void fix_colors(int colors[], int counts[], int from, int to, int size) { int i; for (i = 0; i < size; i++) if (colors[i] == from) colors[i] = to; counts[to] += counts[from]; counts[from] = 0; } /** * Create a tunnel connecting a region to one of its nearest neighbors. * Set new_color = -1 for any neighbour, the required color for a specific one * \param c is the current chunk * \param colors is the array of current point colors * \param counts is the array of current color counts * \param color is the color of the region we want to connect * \param new_color is the color of the region we want to connect to (if used) * \param allow_vault_disconnect If true, vaults can be included in path * planning which can leave regions disconnected. */ static void join_region(struct chunk *c, int colors[], int counts[], int color, int new_color, bool allow_vault_disconnect) { int i; int h = c->height; int w = c->width; int size = h * w; /* Allocate a processing queue */ struct queue *queue = q_new(size); /* Allocate an array to keep track of handled squares, and which square * we reached them from. */ int *previous = mem_zalloc(size * sizeof(int)); array_filler(previous, -1, size); /* Push all squares of the given color onto the queue */ for (i = 0; i < size; i++) { if (colors[i] == color) { q_push_int(queue, i); previous[i] = i; } } /* Process all squares into the queue */ while (q_len(queue) > 0) { /* Get the current square and its color */ int n1 = q_pop_int(queue); int color2 = colors[n1]; /* If we're not looking for a specific color, any new one will do */ if ((new_color == -1) && color2 && (color2 != color)) new_color = color2; /* See if we've reached a square with a new color */ if (color2 == new_color) { /* Step backward through the path, turning stone to tunnel */ while (colors[n1] != color) { struct loc grid; i_to_grid(n1, w, &grid); if (colors[n1] > 0) { --counts[colors[n1]]; } ++counts[color]; colors[n1] = color; /* Don't break permanent walls or vaults. Also * don't override terrain that already allows * passage. */ if (!square_isperm(c, grid) && !square_isvault(c, grid) && !(square_ispassable(c, grid) || square_isdoor(c, grid))) { square_set_feat(c, grid, FEAT_FLOOR); } n1 = previous[n1]; } /* Update the color mapping to combine the two colors */ fix_colors(colors, counts, color2, color, size); /* We're done now */ break; } /* If we haven't reached a new color, add all the unprocessed adjacent * squares to our queue. */ for (i = 0; i < 4; i++) { int n2; struct loc grid; i_to_grid(n1, w, &grid); /* Move to the adjacent square */ grid = loc_sum(grid, ddgrid_ddd[i]); /* Make sure we stay inside the boundaries */ if (!square_in_bounds(c, grid)) continue; /* If the cell hasn't already been processed and we're * willing to include it, add it to the queue */ n2 = grid_to_i(grid, w); if (previous[n2] >= 0) continue; if (square_isperm(c, grid)) continue; if (square_isvault(c, grid) && !allow_vault_disconnect) continue; q_push_int(queue, n2); previous[n2] = n1; } } /* Free the memory we've allocated */ q_free(queue); mem_free(previous); } /** * Start connecting regions, stopping when the cave is entirely connected. * \param c is the current chunk * \param colors is the array of current point colors * \param counts is the array of current color counts * \param allow_vault_disconnect will, if true, allows vaults to be included in * path planning which can leave regions disconnected */ static void join_regions(struct chunk *c, int colors[], int counts[], bool allow_vault_disconnect) { int h = c->height; int w = c->width; int size = h * w; int num = count_colors(counts, size); /* While we have multiple colors (i.e. disconnected regions), join one * of the regions to another one. */ while (num > 1) { int color = first_color(counts, size); join_region(c, colors, counts, color, -1, allow_vault_disconnect); num--; } } /** * Make sure that all the regions of the dungeon are connected. * \param c is the current chunk * \param allow_vault_disconnect will, if true, allows vaults to be included in * path planning which can leave regions disconnected * * This function colors each connected region of the dungeon, then uses that * information to join them into one conected region. */ void ensure_connectedness(struct chunk *c, bool allow_vault_disconnect) { int size = c->height * c->width; int *colors = mem_zalloc(size * sizeof(int)); int *counts = mem_zalloc(size * sizeof(int)); build_colors(c, colors, counts, NULL, true); join_regions(c, colors, counts, allow_vault_disconnect); mem_free(colors); mem_free(counts); } #define MAX_CAVERN_TRIES 10 /** * The cavern generator's main function. * \param depth the chunk's native depth * \param h the chunk's dimensions * \param w the chunk's dimensions * \param join Is a linked list of the connection information to adjacent * levels; the cavern will build in stairs at those locations. May be NULL * to not build in stairs during cavern generation. * \return a pointer to the generated chunk */ static struct chunk *cavern_chunk(int depth, int h, int w, const struct connector *join) { int i; int size = h * w; int limit = size / 13; int density = rand_range(25, 40); int times = rand_range(3, 6); int *colors = mem_zalloc(size * sizeof(int)); int *counts = mem_zalloc(size * sizeof(int)); bool *stairs = (join) ? mem_zalloc(size * sizeof(*stairs)) : NULL; int tries; struct chunk *c = cave_new(h, w); c->depth = depth; ROOM_LOG("cavern h=%d w=%d size=%d density=%d times=%d", h, w, size, density, times); /* Start trying to build caverns */ for (tries = 0; tries < MAX_CAVERN_TRIES; tries++) { /* Build a random cavern and mutate it a number of times */ init_cavern(c, density, join); for (i = 0; i < times; i++) mutate_cavern(c); /* If there are enough open squares then we're done */ if (c->feat_count[FEAT_FLOOR] >= limit) { ROOM_LOG("cavern ok (%d vs %d)", c->feat_count[FEAT_FLOOR], limit); break; } ROOM_LOG("cavern failed--try again (%d vs %d)", c->feat_count[FEAT_FLOOR], limit); } /* If we couldn't make a big enough cavern then fail */ if (tries == MAX_CAVERN_TRIES) { mem_free(colors); mem_free(counts); mem_free(stairs); cave_free(c); return NULL; } build_colors(c, colors, counts, stairs, false); clear_small_regions(c, colors, counts, stairs); join_regions(c, colors, counts, true); /* Convert the permanent rock walls near stairs back to granite. */ while (join) { for (i = 0; i < 8; ++i) { struct loc adj = loc_sum(join->grid, ddgrid_ddd[i]); if (square_in_bounds(c, adj) && square_isperm(c, adj)) { set_marked_granite(c, adj, SQUARE_WALL_SOLID); } } join = join->next; } mem_free(colors); mem_free(counts); mem_free(stairs); return c; } /** * Make a cavern level. * \param p is the player * \param min_height is the minimum expected height, in grids, for the level. * \param min_width is the minimum expected width, in grids, for the level. * \param p_error will be dereferenced and set to a the address of a constant * string describing the failure when the returned chunk is NULL. * \return a pointer to the generated chunk */ struct chunk *cavern_gen(struct player *p, int min_height, int min_width, const char **p_error) { int i, k; int h = rand_range(z_info->dungeon_hgt / 2, (z_info->dungeon_hgt * 3) / 4); int w = rand_range(z_info->dungeon_wid / 2, (z_info->dungeon_wid * 3) / 4); struct chunk *c; /* Enforce minimum dimensions */ h = MAX(h, min_height); w = MAX(w, min_width); /* Try to build the cavern, fail gracefully */ c = cavern_chunk(p->depth, h, w, dun->join); if (!c) { *p_error = "cavern chunk could not be created"; return NULL; } /* Surround the level with perma-rock */ draw_rectangle(c, 0, 0, h - 1, w - 1, FEAT_PERM, SQUARE_NONE, true); /* Place 1-3 down stairs and 1-2 up stairs near some walls */ handle_level_stairs(c, dun->persist, dun->quest, rand_range(1, 3), rand_range(1, 2)); /* General some rubble, traps and monsters */ k = MAX(MIN(c->depth / 3, 10), 2); /* Scale number of monsters items by cavern size */ k = MAX((4 * k * (h * w)) / (z_info->dungeon_hgt * z_info->dungeon_wid), 6); /* Put some rubble in corridors */ alloc_objects(c, SET_BOTH, TYP_RUBBLE, randint1(k), c->depth, 0); /* Place some traps in the dungeon, */ alloc_objects(c, SET_CORR, TYP_TRAP, randint1(k), c->depth, 0); /* Determine the character location */ if (!new_player_spot(c, p)) { cave_free(c); *p_error = "could not place player"; return NULL; } /* Put some monsters in the dungeon */ for (i = randint1(8) + k; i > 0; i--) { pick_and_place_distant_monster(c, p->grid, 0, true, c->depth); } /* Put some objects/gold in the dungeon */ alloc_objects(c, SET_BOTH, TYP_OBJECT, Rand_normal(k, 2), c->depth + 5, ORIGIN_CAVERN); alloc_objects(c, SET_BOTH, TYP_GOLD, Rand_normal(k / 2, 2), c->depth, ORIGIN_CAVERN); alloc_objects(c, SET_BOTH, TYP_GOOD, randint0(k / 4), c->depth, ORIGIN_CAVERN); return c; } /* ------------------ TOWN ---------------- */ /** * Get the bounds of a town lot. * @param xroads - the location of the town crossroads * @param lot - the lot location, indexed from the nw corner * @param lot_wid - lot width for the town * @param lot_hgt - lot height for the town * @param west - a pointer to put the minimum x coord of the lot * @param north - a pointer to put the minimum y coord of the lot * @param east - a pointer to put the maximum x coord of the lot * @param south - a pointer to put the maximum y coord of the lot */ static void get_lot_bounds(struct loc xroads, struct loc lot, int lot_wid, int lot_hgt, int *west, int *north, int *east, int *south) { // 0 is the road. no lots. if (lot.x == 0 || lot.y == 0) { *east = 0; *west = 0; *north = 0; *south = 0; return; } if (lot.x < 0) { *west = MAX(2, xroads.x - 1 + (lot.x) * lot_wid); *east = MIN(z_info->town_wid - 3, xroads.x - 2 + (lot.x + 1) * lot_wid); } else { *west = MAX(2, xroads.x + 2 + (lot.x - 1) * lot_wid); *east = MIN(z_info->town_wid - 3, xroads.x + 1 + (lot.x) * lot_wid); } if (lot.y < 0) { *north = MAX(2, xroads.y + (lot.y) * lot_hgt); *south = MIN(z_info->town_hgt - 3, xroads.y - 1 + (lot.y + 1) * lot_hgt); } else { *north = MAX(2, xroads.y + 2 + (lot.y - 1) * lot_hgt); *south = MIN(z_info->town_hgt - 3, xroads.y + 1 + (lot.y) * lot_hgt); } } static bool lot_is_clear(struct chunk *c, struct loc xroads, struct loc lot, int lot_wid, int lot_hgt) { struct loc nw_corner, se_corner, probe; get_lot_bounds(xroads, lot, lot_wid, lot_hgt, &nw_corner.x, &nw_corner.y, &se_corner.x, &se_corner.y); if (se_corner.x - nw_corner.x < lot_wid - 1 || se_corner.y - nw_corner.y < lot_hgt - 1) { return false; } for (probe.x = nw_corner.x; probe.x <= se_corner.x; probe.x++) { for (probe.y = nw_corner.y; probe.y <= se_corner.y; probe.y++) { if (!square_isfloor(c, probe)) { return false; } } } return true; } static bool lot_has_shop(struct chunk *c, struct loc xroads, struct loc lot, int lot_wid, int lot_hgt) { struct loc nw_corner, se_corner, probe; get_lot_bounds(xroads, lot, lot_wid, lot_hgt, &nw_corner.x, &nw_corner.y, &se_corner.x, &se_corner.y); for (probe.x = nw_corner.x; probe.x <= se_corner.x; probe.x++) { for (probe.y = nw_corner.y; probe.y <= se_corner.y; probe.y++) { if (feat_is_shop(square(c, probe)->feat)) { return true; } } } return false; } /** * Builds a store at a given pseudo-location * \param c is the current chunk * \param n is which shop it is * \param xroads is the location of the town crossroads * \param lot the upper left corner of this store in the town layout * \param lot_wid is the width, in grids, for the store * \param lot_hgt is the height, in grids, for the store */ static void build_store(struct chunk *c, int n, struct loc xroads, struct loc lot, int lot_wid, int lot_hgt) { int feat; struct loc door; int lot_w, lot_n, lot_e, lot_s; int build_w, build_n, build_e, build_s; get_lot_bounds(xroads, lot, lot_wid, lot_hgt, &lot_w, &lot_n, &lot_e, &lot_s); if (lot.x < -1 || lot.x > 1) { /* on the east west street */ if (lot.y == -1) { /* north side of street */ door.y = MAX(lot_n + 1, lot_s - randint0(2)); build_s = door.y; build_n = door.y - 2; } else { /* south side */ door.y = MIN(lot_s - 1, lot_n + randint0(2)); build_n = door.y; build_s = door.y + 2; } door.x = rand_range(lot_w + 1, lot_e - 2); build_w = rand_range(MAX(lot_w, door.x - 2), door.x); if (!square_isfloor(c, loc(build_w - 1, door.y))) { build_w++; door.x = MAX(door.x, build_w); } build_e = rand_range(build_w + 2, MIN(door.x + 2, lot_e)); if (build_e - build_w > 1 && !square_isfloor(c, loc(build_e + 1, door.y))) { build_e--; door.x = MIN(door.x, build_e); } } else if (lot.y < -1 || lot.y > 1) { /* on the north - south street */ if (lot.x == -1) { /* west side of street */ door.x = MAX(lot_w + 1, lot_e - randint0(2) - randint0(2)); build_e = door.x; build_w = door.x - 2; } else { /* east side */ door.x = MIN(lot_e - 1, lot_w + randint0(2) + randint0(2)); build_w = door.x; build_e = door.x + 2; } door.y = rand_range(lot_n, lot_s - 1); build_n = rand_range(MAX(lot_n, door.y - 2), door.y); if (!square_isfloor(c, loc(door.x, build_n - 1))) { build_n++; door.y = MAX(door.y, build_n); } build_s = rand_range(MAX(build_n + 1, door.y), MIN(lot_s, door.y + 2)); if (build_s - build_n > 1 && !square_isfloor(c, loc(door.x, build_s + 1))) { build_s--; door.y = MIN(door.y, build_s); } } else { /* corner store */ if (lot.x < 0) { /* west side */ door.x = lot_e - 1 - randint0(2); build_e = MIN(lot_e, door.x + randint0(2)); build_w = rand_range(MAX(lot_w, door.x - 2), build_e - 2); } else { /* east side */ door.x = lot_w + 1 + randint0(2); build_w = MAX(lot_w, door.x - randint0(2)); build_e = rand_range(build_w + 2, MIN(lot_e, door.x + 2)); } if (lot.y < 0) { /* north side */ door.y = lot_s - randint0(2); if (build_e == door.x || build_w == door.x) { build_s = door.y + randint0(2); } else { /* Avoid encapsulating door */ build_s = door.y; } build_n = MAX(lot_n, door.y - 2); if (build_s - build_n > 1 && !square_isfloor(c, loc(door.x, build_n - 1))) { build_n++; door.y = MAX(build_n, door.y); } } else { /* south side */ door.y = lot_n + randint0(2); if (build_e == door.x || build_w == door.x) { build_n = door.y - randint0(2); } else { /* Avoid encapsulating door */ build_n = door.y; } build_s = MIN(lot_s, door.y + 2); if (build_s - build_n > 1 && !square_isfloor(c, loc(door.x, build_s + 1))) { build_s--; door.y = MIN(build_s, door.y); } } // Avoid placing buildings without space between them if (lot.x < 0 && build_e - build_w > 1 && !square_isfloor(c, loc(build_w - 1, door.y))) { build_w++; door.x = MAX(door.x, build_w); } else if (lot.x > 0 && build_e - build_w > 1 && !square_isfloor(c, loc(build_e + 1, door.y))) { build_e--; door.x = MIN(door.x, build_e); } } build_w = MAX(build_w, lot_w); build_e = MIN(build_e, lot_e); build_n = MAX(build_n, lot_n); build_s = MIN(build_s, lot_s); /* Build an invulnerable rectangular building */ fill_rectangle(c, build_n, build_w, build_s, build_e, FEAT_PERM, SQUARE_NONE); /* Clear previous contents, add a store door */ for (feat = 0; feat < FEAT_MAX; feat++) if (feat_is_shop(feat) && (f_info[feat].shopnum == n + 1)) square_set_feat(c, door, feat); } static void build_ruin(struct chunk *c, struct loc xroads, struct loc lot, int lot_wid, int lot_hgt) { int lot_west, lot_north, lot_east, lot_south; int wid, hgt; get_lot_bounds(xroads, lot, lot_wid, lot_hgt, &lot_west, &lot_north, &lot_east, &lot_south); if (lot_east - lot_west < 1 || lot_south - lot_north < 1) return; /* make a building */ wid = rand_range(1, lot_wid - 2); hgt = rand_range(1, lot_hgt - 2); int offset_x = rand_range(1, lot_wid - 1 - wid); int offset_y = rand_range(1, lot_hgt - 1 - hgt); int west = lot_west + offset_x; int north = lot_north + offset_y; int south = lot_south - (lot_hgt - (hgt + offset_y)); int east = lot_east - (lot_wid - (wid + offset_x)); fill_rectangle(c, north, west, south, east, FEAT_GRANITE, SQUARE_NONE); int x, y; /* and then destroy it and spew rubble everywhere */ for (x = lot_west; x <= lot_east; x++) { for (y = lot_north; y <= lot_south; y++) { if (x >= west && x <= east && y >= north && y <= south) { if (!randint0(4)) { square_set_feat(c, loc(x,y), FEAT_RUBBLE); } } else if (!randint0(3) && square_isfloor(c, loc(x,y)) && /* Avoid placing rubble next to a store */ (x > lot_west || x == 2 || !square_isperm(c, loc(x-1, y))) && (x < lot_east || x == z_info->town_wid-2 || !square_isperm(c, loc(x+1, y))) && (y > lot_north || y == 2 || !square_isperm(c, loc(x, y-1))) && (y < lot_south || y == z_info-> town_hgt-2 || !square_isperm(c, loc(x, y+1)))) { square_set_feat(c, loc(x,y), FEAT_PASS_RUBBLE); } } } } /** * Generate the town for the first time, and place the player * \param c is the current chunk * \param p is the player */ static void town_gen_layout(struct chunk *c, struct player *p) { int n, x, y; struct loc grid, pgrid, xroads; int num_lava = 3 + randint0(3); int ruins_percent = 80; int max_attempts = 100; int num_attempts = 0; bool success = false; int max_store_y = 0; int min_store_x = z_info->town_wid; int max_store_x = 0; /* divide the town into lots */ uint16_t lot_hgt = 4, lot_wid = 6; /* Create walls */ draw_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_PERM, SQUARE_NONE, true); while (!success) { /* Initialize to ROCK for build_streamer precondition */ for (grid.y = 1; grid.y < c->height - 1; grid.y++) for (grid.x = 1; grid.x < c->width - 1; grid.x++) { square_set_feat(c, grid, FEAT_GRANITE); } /* Make some lava streamers */ for (n = 0; n < 3 + num_lava; n++) build_streamer(c, FEAT_LAVA, 0); /* Make a town-sized starburst room. */ (void) generate_starburst_room(c, 0, 0, c->height - 1, c->width - 1, false, FEAT_FLOOR, false); /* Turn off room illumination flag */ for (grid.y = 1; grid.y < c->height - 1; grid.y++) { for (grid.x = 1; grid.x < c->width - 1; grid.x++) { sqinfo_off(square(c, grid)->info, SQUARE_ROOM); } } /* Stairs along north wall */ pgrid.x = rand_spread(z_info->town_wid / 2, z_info->town_wid / 6); pgrid.y = 1; while (!square_isfloor(c, pgrid) && (pgrid.y < z_info->town_hgt / 4)) { pgrid.y++; } if (pgrid.y >= z_info->town_hgt / 4) continue; /* no lava next to stairs */ for (x = pgrid.x - 1; x <= pgrid.x + 1; x++) { for (y = pgrid.y - 1; y <= pgrid.y + 1; y++) { if (square_isfiery(c, loc(x, y))) { square_set_feat(c, loc(x, y), FEAT_GRANITE); } } } xroads.x = pgrid.x; xroads.y = z_info->town_hgt / 2 - randint0(z_info->town_hgt / 4) + randint0(z_info->town_hgt / 8); int lot_min_x = -1 * xroads.x / lot_wid; int lot_max_x = (z_info->town_wid - xroads.x) / lot_wid; int lot_min_y = -1 * xroads.y / lot_hgt; int lot_max_y = (z_info->town_hgt - xroads.y) / lot_hgt; /* place stores along the streets */ num_attempts = 0; for (n = 0; n < z_info->store_max; n++) { struct loc store_lot; bool found_spot = false; while (!found_spot && num_attempts < max_attempts) { num_attempts++; if (randint0(2)) { /* east-west street */ store_lot.x = rand_range(lot_min_x, lot_max_x); store_lot.y = randint0(2) ? 1 : -1; } else { /* north-south street */ store_lot.x = randint0(2) ? 1 : -1; store_lot.y = rand_range(lot_min_y, lot_max_y); } if (store_lot.y == 0 || store_lot.x == 0) continue; found_spot = lot_is_clear(c, xroads, store_lot, lot_wid, lot_hgt); } if (num_attempts >= max_attempts) break; max_store_y = MAX(max_store_y, xroads.y + lot_hgt * store_lot.y); min_store_x = MIN(min_store_x, xroads.x + lot_wid * store_lot.x); max_store_x = MAX(max_store_x, xroads.x + lot_wid * store_lot.x); build_store(c, n, xroads, store_lot, lot_wid, lot_hgt); } if (num_attempts >= max_attempts) continue; /* place ruins */ for (x = lot_min_x; x <= lot_max_x; x++) { if (x == 0) continue; /* 0 is the street */ for (y = lot_min_y; y <= lot_max_y; y++) { if (y == 0) continue; if (randint0(100) > ruins_percent) continue; if (one_in_(2) && !lot_has_shop(c, xroads, loc(x, y), lot_wid, lot_hgt)) { build_ruin(c, xroads, loc(x, y), lot_wid, lot_hgt); } } } success = true; } /* clear the street */ square_set_feat(c, loc(pgrid.x, pgrid.y + 1), FEAT_FLOOR); fill_rectangle(c, pgrid.y + 2, pgrid.x - 1, max_store_y, pgrid.x + 1, FEAT_FLOOR, SQUARE_NONE); fill_rectangle(c, xroads.y, min_store_x, xroads.y + 1, max_store_x, FEAT_FLOOR, SQUARE_NONE); /* Clear previous contents, add down stairs */ square_set_feat(c, pgrid, FEAT_MORE); /* Place the player */ player_place(c, p, pgrid); } /** * Town logic flow for generation of new town. * \param p is the player * \param min_height is the minimum expected height, in grids, for the level. * \param min_width is the minimum expected width, in grids, for the level. * \param p_error will be dereferenced and set to a the address of a constant * string describing the failure when the returned chunk is NULL. * \return a pointer to the generated chunk * We start with a fully wiped cave of normal floors. This function does NOT do * anything about the owners of the stores, nor the contents thereof. It only * handles the physical layout. This level builder ignores the minimum height * and width. */ struct chunk *town_gen(struct player *p, int min_height, int min_width, const char **p_error) { int i; struct loc grid; int residents = is_daytime() ? z_info->town_monsters_day : z_info->town_monsters_night; struct chunk *c_new, *c_old = chunk_find_name("Town"); /* Make a new chunk */ c_new = cave_new(z_info->town_hgt, z_info->town_wid); /* First time */ if (!c_old) { c_new->depth = p->depth; /* Build stuff */ town_gen_layout(c_new, p); } else { /* Copy from the chunk list, remove the old one */ c_new->depth = c_old->depth; if (!chunk_copy(c_new, p, c_old, 0, 0, 0, 0)) quit_fmt("chunk_copy() level bounds failed!"); chunk_list_remove("Town"); cave_free(c_old); /* Find the stairs (lame) */ for (grid.y = 0; grid.y < c_new->height; grid.y++) { bool found = false; for (grid.x = 0; grid.x < c_new->width; grid.x++) { if (square_feat(c_new, grid)->fidx == FEAT_MORE) { found = true; break; } } if (found) break; } /* Place the player */ player_place(c_new, p, grid); } /* Apply illumination */ cave_illuminate(c_new, is_daytime()); /* Make some residents */ for (i = 0; i < residents; i++) { pick_and_place_distant_monster(c_new, p->grid, 3, true, c_new->depth); } return c_new; } /* ------------------ MODIFIED ---------------- */ /** * The main modified generation algorithm * \param p is the player, in case generation fails and the partially created * level needs to be cleaned up * \param depth is the chunk's native depth * \param height are the chunk's dimensions * \param width are the chunk's dimensions * \param persistent If true, handle the connections for persistent levels. * \return a pointer to the generated chunk */ static struct chunk *modified_chunk(struct player *p, int depth, int height, int width, bool persistent) { int i; int by = 0, bx = 0, key, rarity; int num_floors; int num_rooms = dun->profile->n_room_profiles; int dun_unusual = dun->profile->dun_unusual; int n_attempt; /* Make the cave */ struct chunk *c = cave_new(height, width); c->depth = depth; /* Set the intended number of floor grids based on cave floor area */ num_floors = c->height * c->width / 7; ROOM_LOG("height=%d width=%d nfloors=%d", c->height, c->width,num_floors); /* Fill cave area with basic granite */ fill_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_GRANITE, SQUARE_NONE); /* Generate permanent walls around the generated area (temporarily!) */ draw_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_PERM, SQUARE_NONE, true); /* Actual maximum number of blocks on this level */ dun->row_blocks = c->height / dun->block_hgt; dun->col_blocks = c->width / dun->block_wid; /* Initialize the room table */ dun->room_map = mem_zalloc(dun->row_blocks * sizeof(bool*)); for (i = 0; i < dun->row_blocks; i++) dun->room_map[i] = mem_zalloc(dun->col_blocks * sizeof(bool)); /* No rooms yet, pits or otherwise. */ dun->pit_num = 0; dun->cent_n = 0; reset_entrance_data(c); /* Build the special staircase rooms */ if (persistent) { build_staircase_rooms(c, "Modified Generation"); } /* * Build rooms until we have enough floor grids and at least two rooms * or we appear to be stuck and can't match those criteria. */ n_attempt = 0; while (1) { if (c->feat_count[FEAT_FLOOR] >= num_floors && dun->cent_n >= 2) { break; } /* * At an average of roughly 22 successful rooms per level * (and a standard deviation of 4.5 or so for that) and a * room failure rate that's less than .5 failures per success * (4.2.x profile doesn't use full allocation for rarity two * rooms - only up to 60; and the last type tried in that * rarity has a failure rate per successful rooms of all types * of around .024). 500 attempts is a generous cutoff for * saying no further progress is likely. */ if (n_attempt > 500) { uncreate_artifacts(c); wipe_mon_list(c, p); cave_free(c); return NULL; } ++n_attempt; /* Roll for random key (to be compared against a profile's cutoff) */ key = randint0(100); /* We generate a rarity number to figure out how exotic to make * the room. This number has a (50+depth/2)/DUN_UNUSUAL chance * of being > 0, a (50+depth/2)^2/DUN_UNUSUAL^2 chance of * being > 1, up to MAX_RARITY. */ i = 0; rarity = 0; while (i == rarity && i < dun->profile->max_rarity) { if (randint0(dun_unusual) < 50 + c->depth / 2) rarity++; i++; } /* Once we have a key and a rarity, we iterate through out list of * room profiles looking for a match (whose cutoff > key and whose * rarity > this rarity). We try building the room, and if it works * then we are done with this iteration. We keep going until we find * a room that we can build successfully or we exhaust the profiles. */ for (i = 0; i < num_rooms; i++) { struct room_profile profile = dun->profile->room_profiles[i]; if (profile.rarity > rarity) continue; if (profile.cutoff <= key) continue; if (room_build(c, by, bx, profile, true)) break; } } for (i = 0; i < dun->row_blocks; i++) mem_free(dun->room_map[i]); mem_free(dun->room_map); /* Connect all the rooms together */ do_traditional_tunneling(c); ensure_connectedness(c, true); /* Turn the outer permanent walls back to granite */ draw_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_GRANITE, SQUARE_NONE, true); return c; } /** * Generate a new dungeon level. * \param p is the player * \param min_height is the minimum expected height, in grids, for the level. * \param min_width is the minimum expected width, in grids, for the level. * \param p_error will be dereferenced and set to a the address of a constant * string describing the failure when the returned chunk is NULL. * \return a pointer to the generated chunk * * This is sample code to illustrate some of the new dungeon generation * methods; I think it actually produces quite nice levels. New stuff: * * - different sized levels * - independence from block size: the block size can be set to any number * from 1 (no blocks) to about 15; beyond that it struggles to generate * enough floor space * - the find_space function, called from the room builder functions, allows * the room to find space for itself rather than the generation algorithm * allocating it; this helps because the room knows better what size it is * - a count is now kept of grids of the various terrains, allowing dungeon * generation to terminate when enough floor is generated * - there are three new room types - huge rooms, rooms of chambers * and interesting rooms - as well as many new vaults * - there is the ability to place specific monsters and objects in vaults and * interesting rooms, as well as to make general monster restrictions in * areas or the whole dungeon */ struct chunk *modified_gen(struct player *p, int min_height, int min_width, const char **p_error) { int i, k; int size_percent, y_size, x_size; struct chunk *c; /* Scale the level */ i = randint1(10) + p->depth / 24; if (dun->quest) size_percent = 100; else if (i < 2) size_percent = 75; else if (i < 3) size_percent = 80; else if (i < 4) size_percent = 85; else if (i < 5) size_percent = 90; else if (i < 6) size_percent = 95; else size_percent = 100; y_size = z_info->dungeon_hgt * (size_percent - 5 + randint0(10)) / 100; x_size = z_info->dungeon_wid * (size_percent - 5 + randint0(10)) / 100; /* Enforce dimension limits */ y_size = MIN(MAX(y_size, min_height), z_info->dungeon_hgt); x_size = MIN(MAX(x_size, min_width), z_info->dungeon_wid); /* Set the block height and width */ dun->block_hgt = dun->profile->block_size; dun->block_wid = dun->profile->block_size; c = modified_chunk(p, p->depth, MIN(z_info->dungeon_hgt, y_size), MIN(z_info->dungeon_wid, x_size), dun->persist); if (!c) { *p_error = "modified chunk could not be created"; return NULL; } /* Generate permanent walls around the edge of the generated area */ draw_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_PERM, SQUARE_NONE, true); /* Add some magma streamers */ for (i = 0; i < dun->profile->str.mag; i++) build_streamer(c, FEAT_MAGMA, dun->profile->str.mc); /* Add some quartz streamers */ for (i = 0; i < dun->profile->str.qua; i++) build_streamer(c, FEAT_QUARTZ, dun->profile->str.qc); /* Place 3 or 4 down stairs and 1 or 2 up stairs near some walls */ handle_level_stairs(c, dun->persist, dun->quest, rand_range(3, 4), rand_range(1, 2)); /* General amount of rubble, traps and monsters */ k = MAX(MIN(c->depth / 3, 10), 2); /* Put some rubble in corridors */ alloc_objects(c, SET_CORR, TYP_RUBBLE, randint1(k), c->depth, 0); /* Place some traps in the dungeon, reduce frequency by factor of 5 */ alloc_objects(c, SET_CORR, TYP_TRAP, randint1(k)/5, c->depth, 0); /* Determine the character location */ if (!new_player_spot(c, p)) { uncreate_artifacts(c); wipe_mon_list(c, p); cave_free(c); *p_error = "could not place player"; return NULL; } /* Pick a base number of monsters */ i = z_info->level_monster_min + randint1(8) + k; /* Remove all monster restrictions. */ mon_restrict(NULL, c->depth, c->depth, true); /* Put some monsters in the dungeon */ for (; i > 0; i--) { pick_and_place_distant_monster(c, p->grid, 0, true, c->depth); } /* Put some objects in rooms */ alloc_objects(c, SET_ROOM, TYP_OBJECT, Rand_normal(z_info->room_item_av, 3), c->depth, ORIGIN_FLOOR); /* Put some objects/gold in the dungeon */ alloc_objects(c, SET_BOTH, TYP_OBJECT, Rand_normal(z_info->both_item_av, 3), c->depth, ORIGIN_FLOOR); alloc_objects(c, SET_BOTH, TYP_GOLD, Rand_normal(z_info->both_gold_av, 3), c->depth, ORIGIN_FLOOR); return c; } /* ------------------ MORIA ---------------- */ /** * The main moria generation algorithm * \param p is the player, in case generation fails and the partially created * level needs to be cleaned up * \param depth is the chunk's native depth * \param height are the chunk's dimensions * \param width are the chunk's dimensions * \param persistent If true, handle the connections for persistent levels. * \return a pointer to the generated chunk */ static struct chunk *moria_chunk(struct player *p, int depth, int height, int width, bool persistent) { int i; int by = 0, bx = 0, key, rarity; int num_floors; int num_rooms = dun->profile->n_room_profiles; int dun_unusual = dun->profile->dun_unusual; int n_attempt; /* Make the cave */ struct chunk *c = cave_new(height, width); c->depth = depth; /* Set the intended number of floor grids based on cave floor area */ num_floors = c->height * c->width / 7; ROOM_LOG("height=%d width=%d nfloors=%d", c->height, c->width,num_floors); /* Fill cave area with basic granite */ fill_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_GRANITE, SQUARE_NONE); /* Generate permanent walls around the generated area (temporarily!) */ draw_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_PERM, SQUARE_NONE, true); /* Actual maximum number of blocks on this level */ dun->row_blocks = c->height / dun->block_hgt; dun->col_blocks = c->width / dun->block_wid; /* Initialize the room table */ dun->room_map = mem_zalloc(dun->row_blocks * sizeof(bool*)); for (i = 0; i < dun->row_blocks; i++) dun->room_map[i] = mem_zalloc(dun->col_blocks * sizeof(bool)); /* No rooms yet, pits or otherwise. */ dun->pit_num = 0; dun->cent_n = 0; reset_entrance_data(c); /* Build the special staircase rooms */ if (persistent) { build_staircase_rooms(c, "Moria Generation"); } /* * Build rooms until we have enough floor grids and at least two rooms * (the latter is to make it easier to satisfy the constraints for * player placement) or we appear to be stuck and can't match those * criteria. */ n_attempt = 0; while (1) { if (c->feat_count[FEAT_FLOOR] >= num_floors && dun->cent_n >= 2) { break; } /* * At an average of around 10 successful rooms per level * (and a standard deviation of 3.1 or so for that) and a * a room failure rate that's less than .5 failures per success * (4.2.x profile doesn't specify any rarity 1 rooms; the * moria rooms at rarity zero have around .49 failures per * successful room of any type), 500 attempts is a generous * cutoff for saying no further progress is likely. */ if (n_attempt > 500) { uncreate_artifacts(c); wipe_mon_list(c, p); cave_free(c); return NULL; } ++n_attempt; /* Roll for random key (to be compared against a profile's cutoff) */ key = randint0(100); /* We generate a rarity number to figure out how exotic to make * the room. This number has a (50+depth/2)/DUN_UNUSUAL chance * of being > 0, a (50+depth/2)^2/DUN_UNUSUAL^2 chance of * being > 1, up to MAX_RARITY. */ i = 0; rarity = 0; while (i == rarity && i < dun->profile->max_rarity) { if (randint0(dun_unusual) < 50 + c->depth / 2) rarity++; i++; } /* Once we have a key and a rarity, we iterate through out list of * room profiles looking for a match (whose cutoff > key and whose * rarity > this rarity). We try building the room, and if it works * then we are done with this iteration. We keep going until we find * a room that we can build successfully or we exhaust the profiles. */ for (i = 0; i < num_rooms; i++) { struct room_profile profile = dun->profile->room_profiles[i]; if (profile.rarity > rarity) continue; if (profile.cutoff <= key) continue; if (room_build(c, by, bx, profile, true)) break; } } for (i = 0; i < dun->row_blocks; i++) mem_free(dun->room_map[i]); mem_free(dun->room_map); /* Connect all the rooms together */ do_traditional_tunneling(c); ensure_connectedness(c, true); /* Turn the outer permanent walls back to granite */ draw_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_GRANITE, SQUARE_NONE, true); return c; } /** * Generate an Oangband-style moria level. * \param p is the player * \param min_height is the minimum expected height, in grids, for the level. * \param min_width is the minimum expected width, in grids, for the level. * \param p_error will be dereferenced and set to a the address of a constant * string describing the failure when the returned chunk is NULL. * \return a pointer to the generated chunk * * Most rooms on these levels are large, ragged-edged and roughly oval-shaped. * * Monsters are mostly "Moria dwellers" - orcs, ogres, trolls and giants. * * Apart from the room and monster changes, generation is similar to modified * levels. A good way of selecting these instead of modified (similar to * labyrinth levels are selected) would be * if ((c->depth >= 10) && (c->depth < 40) && one_in_(40)) */ struct chunk *moria_gen(struct player *p, int min_height, int min_width, const char **p_error) { int i, k; int size_percent, y_size, x_size; struct chunk *c; /* Scale the level */ i = randint1(10) + p->depth / 24; if (dun->quest) size_percent = 100; else if (i < 2) size_percent = 75; else if (i < 3) size_percent = 80; else if (i < 4) size_percent = 85; else if (i < 5) size_percent = 90; else if (i < 6) size_percent = 95; else size_percent = 100; y_size = z_info->dungeon_hgt * (size_percent - 5 + randint0(10)) / 100; x_size = z_info->dungeon_wid * (size_percent - 5 + randint0(10)) / 100; /* Enforce dimension limits */ y_size = MIN(MAX(y_size, min_height), z_info->dungeon_hgt); x_size = MIN(MAX(x_size, min_width), z_info->dungeon_wid); /* Set the block height and width */ dun->block_hgt = dun->profile->block_size; dun->block_wid = dun->profile->block_size; c = moria_chunk(p, p->depth, MIN(z_info->dungeon_hgt, y_size), MIN(z_info->dungeon_wid, x_size), dun->persist); if (!c) { *p_error = "moria chunk could not be created"; return NULL; } /* Generate permanent walls around the edge of the generated area */ draw_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_PERM, SQUARE_NONE, true); /* Add some magma streamers */ for (i = 0; i < dun->profile->str.mag; i++) build_streamer(c, FEAT_MAGMA, dun->profile->str.mc); /* Add some quartz streamers */ for (i = 0; i < dun->profile->str.qua; i++) build_streamer(c, FEAT_QUARTZ, dun->profile->str.qc); /* Place 3 or 4 down stairs and 1 or 2 up stairs near some walls */ handle_level_stairs(c, dun->persist, dun->quest, rand_range(3, 4), rand_range(1, 2)); /* General amount of rubble, traps and monsters */ k = MAX(MIN(c->depth / 3, 10), 2); /* Put some rubble in corridors */ alloc_objects(c, SET_CORR, TYP_RUBBLE, randint1(k), c->depth, 0); /* Place some traps in the dungeon, reduce frequency by factor of 5 */ alloc_objects(c, SET_CORR, TYP_TRAP, randint1(k)/5, c->depth, 0); /* Determine the character location */ if (!new_player_spot(c, p)) { uncreate_artifacts(c); wipe_mon_list(c, p); cave_free(c); *p_error = "could not place player"; return NULL; } /* Pick a base number of monsters */ i = z_info->level_monster_min + randint1(8) + k; /* Moria levels have a high proportion of cave dwellers. */ mon_restrict("Moria dwellers", c->depth, c->depth, true); /* Put some monsters in the dungeon */ for (; i > 0; i--) { pick_and_place_distant_monster(c, p->grid, 0, true, c->depth); } /* Remove our restrictions. */ (void) mon_restrict(NULL, c->depth, c->depth, false); /* Put some objects in rooms */ alloc_objects(c, SET_ROOM, TYP_OBJECT, Rand_normal(z_info->room_item_av, 3), c->depth, ORIGIN_FLOOR); /* Put some objects/gold in the dungeon */ alloc_objects(c, SET_BOTH, TYP_OBJECT, Rand_normal(z_info->both_item_av, 3), c->depth, ORIGIN_FLOOR); alloc_objects(c, SET_BOTH, TYP_GOLD, Rand_normal(z_info->both_gold_av, 3), c->depth, ORIGIN_FLOOR); return c; } /* ------------------ HARD CENTRE ---------------- */ /** * Make a chunk consisting only of a greater vault * \param p is the player * \return a pointer to the generated chunk */ static struct chunk *vault_chunk(struct player *p) { const char *vname = (one_in_(2)) ? "Greater vault (new)" : "Greater vault"; struct vault *v = random_vault(p->depth, vname); struct chunk *c; bool built; /* Make the chunk */ c = cave_new(v->hgt, v->wid); c->depth = p->depth; /* Fill with granite; the vault will override for the grids it sets. */ fill_rectangle(c, 0, 0, v->hgt - 1, v->wid - 1, FEAT_GRANITE, SQUARE_NONE); /* Build the vault in it */ dun->cent_n = 0; reset_entrance_data(c); event_signal_string(EVENT_GEN_ROOM_START, vname); built = build_vault(c, loc(v->wid / 2, v->hgt / 2), v); event_signal_flag(EVENT_GEN_ROOM_END, built); if (!built) { uncreate_artifacts(c); cave_free(c); c = NULL; } return c; } /** * Make sure that all the caverns surrounding the centre are connected. * \param c is the entire current chunk (containing the caverns) * \param floor is an array of sample floor grids, one from each cavern in the * order left, upper, lower, right */ static void connect_caverns(struct chunk *c, struct loc floor[]) { int i; int size = c->height * c->width; int *colors = mem_zalloc(size * sizeof(int)); int *counts = mem_zalloc(size * sizeof(int)); int color_of_floor[4]; /* Color the regions, find which cavern is which color */ build_colors(c, colors, counts, NULL, true); for (i = 0; i < 4; i++) { int spot = grid_to_i(floor[i], c->width); color_of_floor[i] = colors[spot]; } /* Join left and upper, right and lower */ join_region(c, colors, counts, color_of_floor[0], color_of_floor[1], false); join_region(c, colors, counts, color_of_floor[2], color_of_floor[3], false); /* Join the two big caverns */ for (i = 1; i < 3; i++) { int spot = grid_to_i(floor[i], c->width); color_of_floor[i] = colors[spot]; } join_region(c, colors, counts, color_of_floor[1], color_of_floor[2], false); mem_free(colors); mem_free(counts); } /** * Generate a hard centre level - a greater vault surrounded by caverns * \param p is the player * \param min_height is the minimum expected height, in grids, for the level. * \param min_width is the minimum expected width, in grids, for the level. * \param p_error will be dereferenced and set to a the address of a constant * string describing the failure when the returned chunk is NULL. * \return a pointer to the generated chunk * This level builder ignores the minimum height and width. */ struct chunk *hard_centre_gen(struct player *p, int min_height, int min_width, const char **p_error) { /* Make a vault for the centre */ struct chunk *centre = vault_chunk(p); int rotate = 0; /* Dimensions for the surrounding caverns */ int centre_cavern_ypos; int centre_cavern_hgt, centre_cavern_wid; int upper_cavern_hgt, lower_cavern_hgt; struct chunk *upper_cavern; struct chunk *lower_cavern; int lower_cavern_ypos; int left_cavern_wid, right_cavern_wid; struct chunk *left_cavern; struct chunk *right_cavern; struct chunk *c; int i, k, cavern_area; struct loc grid; struct loc floor[4]; /* No persistent levels of this type for now */ if (dun->persist) { uncreate_artifacts(centre); wipe_mon_list(centre, p); cave_free(centre); *p_error = "no hard centre levels in persistent dungeons"; return NULL; } /* * Carve out entrances to the vault. Only use one if there aren't * explicitly marked entrances since those vaults typically have empty * space about them and the extra entrances aren't useful. */ k = 1 + ((dun->ent_n[0] > 0) ? randint1(3) : 0); dun->wall_n = 0; for (i = 0; i < k; ++i) { if (dun->ent_n[0] == 0) { /* * There's no explicitly marked entrances. Look for a * square marked SQUARE_WALL_OUTER. */ if (!cave_find(centre, &grid, square_iswall_outer)) { if (i == 0) { uncreate_artifacts(centre); wipe_mon_list(centre, p); cave_free(centre); *p_error = "no SQUARE_WALL_OUTER grid for an entrance to the centre vault"; return NULL; } break; } } else { grid = choose_random_entrance(centre, 0, NULL, 0, dun->wall, i); if (loc_eq(grid, loc(0, 0))) { if (i == 0) { uncreate_artifacts(centre); wipe_mon_list(centre, p); cave_free(centre); *p_error = "random selection of entrance to the centre vault failed"; return NULL; } break; } } /* * Store position in dun->wall and mark neighbors as invalid * entrances. */ pierce_outer_wall(centre, grid); /* Convert it to a floor. */ square_set_feat(centre, grid, FEAT_FLOOR); } /* Measure the vault, rotate to make it wider than it is high */ if (centre->height > centre->width) { rotate = 1; centre_cavern_ypos = (z_info->dungeon_hgt - centre->width) / 2; centre_cavern_hgt = centre->width; centre_cavern_wid = centre->height; } else { centre_cavern_ypos = (z_info->dungeon_hgt - centre->height) / 2; centre_cavern_hgt = centre->height; centre_cavern_wid = centre->width; } upper_cavern_hgt = centre_cavern_ypos; lower_cavern_hgt = z_info->dungeon_hgt - upper_cavern_hgt - centre_cavern_hgt; lower_cavern_ypos = centre_cavern_ypos + centre_cavern_hgt; /* Make the caverns */ upper_cavern = cavern_chunk(p->depth, upper_cavern_hgt, centre_cavern_wid, NULL); lower_cavern = cavern_chunk(p->depth, lower_cavern_hgt, centre_cavern_wid, NULL); left_cavern_wid = (z_info->dungeon_wid - centre_cavern_wid) / 2; right_cavern_wid = z_info->dungeon_wid - left_cavern_wid - centre_cavern_wid; left_cavern = cavern_chunk(p->depth, z_info->dungeon_hgt, left_cavern_wid, NULL); right_cavern = cavern_chunk(p->depth, z_info->dungeon_hgt, right_cavern_wid, NULL); /* Return on failure */ if (!upper_cavern || !lower_cavern || !left_cavern || !right_cavern) { if (right_cavern) { uncreate_artifacts(right_cavern); cave_free(right_cavern); } if (left_cavern) { uncreate_artifacts(left_cavern); cave_free(left_cavern); } if (lower_cavern) { uncreate_artifacts(lower_cavern); cave_free(lower_cavern); } if (upper_cavern) { uncreate_artifacts(upper_cavern); cave_free(upper_cavern); } uncreate_artifacts(centre); wipe_mon_list(centre, p); cave_free(centre); *p_error = "could not create one or more of the surrounding caverns"; return NULL; } /* Make a cave to copy them into, and find a floor square in each cavern */ c = cave_new(z_info->dungeon_hgt, z_info->dungeon_wid); c->depth = p->depth; /* Left */ chunk_copy(c, p, left_cavern, 0, 0, 0, false); find_empty_range(c, &grid, loc(0, 0), loc(left_cavern_wid - 1, z_info->dungeon_hgt - 1)); floor[0] = grid; /* Upper */ chunk_copy(c, p, upper_cavern, 0, left_cavern_wid, 0, false); find_empty_range(c, &grid, loc(left_cavern_wid, 0), loc(left_cavern_wid + centre_cavern_wid - 1, upper_cavern_hgt - 1)); floor[1] = grid; /* Centre */ chunk_copy(c, p, centre, centre_cavern_ypos, left_cavern_wid, rotate, false); /* Lower */ chunk_copy(c, p, lower_cavern, lower_cavern_ypos, left_cavern_wid, 0, false); find_empty_range(c, &grid, loc(left_cavern_wid, lower_cavern_ypos), loc(left_cavern_wid + centre_cavern_wid - 1, z_info->dungeon_hgt - 1)); floor[3] = grid; /* Right */ chunk_copy(c, p, right_cavern, 0, left_cavern_wid + centre_cavern_wid, 0, false); find_empty_range(c, &grid, loc(left_cavern_wid + centre_cavern_wid, 0), loc(z_info->dungeon_wid - 1, z_info->dungeon_hgt - 1)); floor[2] = grid; /* Encase in perma-rock */ draw_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_PERM, SQUARE_NONE, true); /* Connect up all the caverns */ connect_caverns(c, floor); /* Connect to the centre entrances. */ ensure_connectedness(c, false); /* Free all the chunks */ cave_free(left_cavern); cave_free(upper_cavern); cave_free(centre); cave_free(lower_cavern); cave_free(right_cavern); cavern_area = (left_cavern_wid + right_cavern_wid) * z_info->dungeon_hgt + centre_cavern_wid * (upper_cavern_hgt + lower_cavern_hgt); /* Place 2-3 down stairs near some walls */ alloc_stairs(c, FEAT_MORE, rand_range(1, 3), 0, false, NULL, dun->quest); /* Place 1-2 up stairs near some walls */ alloc_stairs(c, FEAT_LESS, rand_range(1, 2), 0, false, NULL, dun->quest); /* Generate some rubble, traps and monsters */ k = MAX(MIN(c->depth / 3, 10), 2); /* Scale number by total cavern size - caverns are fairly sparse */ k = (k * cavern_area) / (z_info->dungeon_hgt * z_info->dungeon_wid); /* Put some rubble in corridors */ alloc_objects(c, SET_BOTH, TYP_RUBBLE, randint1(k), c->depth, 0); /* Place some traps in the dungeon */ alloc_objects(c, SET_CORR, TYP_TRAP, randint1(k), c->depth, 0); /* Determine the character location */ if (!new_player_spot(c, p)) { uncreate_artifacts(c); wipe_mon_list(c, p); cave_free(c); *p_error = "could not place player"; return NULL; } /* Put some monsters in the dungeon */ for (i = randint1(8) + k; i > 0; i--) { pick_and_place_distant_monster(c, p->grid, 0, true, c->depth); } /* Put some objects/gold in the dungeon */ alloc_objects(c, SET_BOTH, TYP_OBJECT, Rand_normal(k, 2), c->depth + 5, ORIGIN_CAVERN); alloc_objects(c, SET_BOTH, TYP_GOLD, Rand_normal(k / 2, 2), c->depth, ORIGIN_CAVERN); alloc_objects(c, SET_BOTH, TYP_GOOD, randint0(k / 4), c->depth, ORIGIN_CAVERN); return c; } /* ------------------ LAIR ---------------- */ /** * Generate a lair level - a regular cave generated with the modified * algorithm, connected to a cavern with themed monsters * \param p is the player * \param min_height is the minimum expected height, in grids, for the level. * \param min_width is the minimum expected width, in grids, for the level. * \param p_error will be dereferenced and set to a the address of a constant * string describing the failure when the returned chunk is NULL. * \return a pointer to the generated chunk */ struct chunk *lair_gen(struct player *p, int min_height, int min_width, const char **p_error) { int i, k; int size_percent, y_size, x_size; int left_width, normal_width, lair_width; int normal_offset, lair_offset; struct chunk *c; struct chunk *normal; struct chunk *lair; struct connector *cached_join; /* Scale the level */ i = randint1(10) + p->depth / 24; if (dun->quest) size_percent = 100; else if (i < 2) size_percent = 75; else if (i < 3) size_percent = 80; else if (i < 4) size_percent = 85; else if (i < 5) size_percent = 90; else if (i < 6) size_percent = 95; else size_percent = 100; y_size = z_info->dungeon_hgt * (size_percent - 5 + randint0(10)) / 100; x_size = z_info->dungeon_wid * (size_percent - 5 + randint0(10)) / 100; /* Enforce dimension limits */ y_size = MIN(MAX(y_size, min_height), z_info->dungeon_hgt); x_size = MIN(MAX(x_size, min_width), z_info->dungeon_wid); /* Set the block height and width */ dun->block_hgt = dun->profile->block_size; dun->block_wid = dun->profile->block_size; cached_join = dun->join; dun->join = NULL; if (dun->persist) { left_width = 1 + find_joinfree_vertical_seam(cached_join, x_size / 2, MIN(5, x_size / 20), 0, y_size - 1); if (left_width < 4 || x_size - left_width < 4) return NULL; } else { assert(cached_join == NULL); left_width = x_size / 2; } if (one_in_(2)) { /* Place the normal part on the left. */ normal_width = left_width; normal_offset = 0; lair_width = x_size - left_width; lair_offset = left_width; } else { /* Place the lair part on the left. */ normal_width = x_size - left_width; normal_offset = left_width; lair_width = left_width; lair_offset = 0; } /* * The transformation applied here should match that for chunk_copy() * below. */ dun->join = transform_join_list(cached_join, y_size, normal_width, 0, normal_offset, 0, false); normal = modified_chunk(p, p->depth, y_size, normal_width, dun->persist); /* Done with the transformed connector information. */ cave_connectors_free(dun->join); dun->join = cached_join; if (!normal) { *p_error = "modified chunk could not be created"; return NULL; } /* * The transformation applied here should match that for chunk_copy() * below. */ dun->join = transform_join_list(cached_join, y_size, lair_width, 0, lair_offset, 0, false); lair = cavern_chunk(p->depth, y_size, lair_width, dun->join); /* Done with the transformed connector information. */ cave_connectors_free(dun->join); dun->join = cached_join; if (!lair) { uncreate_artifacts(normal); wipe_mon_list(normal, p); cave_free(normal); *p_error = "cavern chunk could not be created"; return NULL; } /* General amount of rubble, traps and monsters */ k = MAX(MIN(p->depth / 3, 10), 2) / 2; /* Put the character in the normal half */ if (!new_player_spot(normal, p)) { uncreate_artifacts(lair); cave_free(lair); uncreate_artifacts(normal); wipe_mon_list(normal, p); cave_free(normal); *p_error = "could not place player"; return NULL; } /* Pick a smallish number of monsters for the normal half */ i = randint1(4) + k; /* Put some monsters in the dungeon */ for (; i > 0; i--) { pick_and_place_distant_monster(normal, p->grid, 0, true, normal->depth); } /* Add some magma streamers */ for (i = 0; i < dun->profile->str.mag; i++) build_streamer(normal, FEAT_MAGMA, dun->profile->str.mc); /* Add some quartz streamers */ for (i = 0; i < dun->profile->str.qua; i++) build_streamer(normal, FEAT_QUARTZ, dun->profile->str.qc); /* Pick a larger number of monsters for the lair */ i = (z_info->level_monster_min + randint1(20) + k); /* Find appropriate monsters */ while (true) { /* Choose a pit profile */ set_pit_type(lair->depth, 0); /* Set monster generation restrictions */ if (mon_restrict(dun->pit_type->name, lair->depth, lair->depth, true)) break; } ROOM_LOG("Monster lair - %s", dun->pit_type->name); /* Place lair monsters */ spread_monsters(lair, dun->pit_type->name, lair->depth, i, lair->height / 2, lair->width / 2, lair->height / 2, lair->width / 2, ORIGIN_CAVERN); /* Remove our restrictions. */ (void) mon_restrict(NULL, lair->depth, lair->depth, false); /* Make the level */ c = cave_new(y_size, x_size); c->depth = p->depth; chunk_copy(c, p, normal, 0, normal_offset, 0, false); chunk_copy(c, p, lair, 0, lair_offset, 0, false); /* Free the chunks */ cave_free(normal); cave_free(lair); /* Generate permanent walls around the edge of the generated area */ draw_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_PERM, SQUARE_NONE, true); /* Connect */ ensure_connectedness(c, true); /* Place 3 or 4 down stairs and 1 or 2 up stairs near some walls */ handle_level_stairs(c, dun->persist, dun->quest, rand_range(3, 4), rand_range(1, 2)); /* Put some rubble in corridors */ alloc_objects(c, SET_CORR, TYP_RUBBLE, randint1(k), c->depth, 0); /* Place some traps in the dungeon, reduce frequency by factor of 5 */ alloc_objects(c, SET_CORR, TYP_TRAP, randint1(k)/5, c->depth, 0); /* Put some objects in rooms */ alloc_objects(c, SET_ROOM, TYP_OBJECT, Rand_normal(z_info->room_item_av, 3), c->depth, ORIGIN_FLOOR); /* Put some objects/gold in the dungeon */ alloc_objects(c, SET_BOTH, TYP_OBJECT, Rand_normal(z_info->both_item_av, 3), c->depth, ORIGIN_FLOOR); alloc_objects(c, SET_BOTH, TYP_GOLD, Rand_normal(z_info->both_gold_av, 3), c->depth, ORIGIN_FLOOR); return c; } /* ------------------ GAUNTLET ---------------- */ /** * Generate a gauntlet level - two separate caverns with an unmappable labyrinth * between them, and no teleport and only upstairs from the side where the * player starts. * * \param p is the player * \param min_height is the minimum expected height, in grids, for the level. * \param min_width is the minimum expected width, in grids, for the level. * \param p_error will be dereferenced and set to a the address of a constant * string describing the failure when the returned chunk is NULL. * \return a pointer to the generated chunk * This level builder ignores the minimum height and width. */ struct chunk *gauntlet_gen(struct player *p, int min_height, int min_width, const char **p_error) { int i, k; struct chunk *c; struct chunk *left; struct chunk *gauntlet; struct chunk *right; struct chunk *arrival; int gauntlet_hgt = 2 * randint1(5) + 3; int gauntlet_wid = 2 * randint1(10) + 19; int y_size = z_info->dungeon_hgt - randint0(25 - gauntlet_hgt); /* * labyrinth_gen() generates something that's two grids wider than * the argument passed, thus the extra "- 2" below. */ int x_size = (z_info->dungeon_wid - gauntlet_wid - 2) / 2 - randint0(45 - gauntlet_wid); struct loc p_loc_in_r, p_loc_in_l; int line1, line2; /* No persistent levels of this type for now */ if (dun->persist) { *p_error = "no gauntlet levels in persistent dungeons"; return NULL; } gauntlet = labyrinth_chunk(p->depth, gauntlet_hgt, gauntlet_wid, false, false); if (!gauntlet) { *p_error = "labyrinth chunk could not be generated"; return NULL; } left = cavern_chunk(p->depth, y_size, x_size, NULL); if (!left) { uncreate_artifacts(gauntlet); cave_free(gauntlet); *p_error = "left cavern chunk could not be generated"; return NULL; } right = cavern_chunk(p->depth, y_size, x_size, NULL); if (!right) { uncreate_artifacts(gauntlet); cave_free(gauntlet); uncreate_artifacts(left); cave_free(left); *p_error = "right cavern chunk could not be generated"; return NULL; } /* Record lines between chunks */ line1 = left->width; line2 = line1 + gauntlet->width; /* Set the movement and mapping restrictions */ generate_mark(left, 0, 0, left->height - 1, left->width - 1, SQUARE_NO_TELEPORT); generate_mark(gauntlet, 0, 0, gauntlet->height - 1, gauntlet->width - 1, SQUARE_NO_MAP); generate_mark(gauntlet, 0, 0, gauntlet->height - 1, gauntlet->width - 1, SQUARE_NO_TELEPORT); /* Place down stairs in the right cavern */ alloc_stairs(right, FEAT_MORE, rand_range(2, 3), 0, false, NULL, dun->quest); /* Place up stairs in the left cavern */ alloc_stairs(left, FEAT_LESS, rand_range(1, 3), 0, false, NULL, dun->quest); /* * Open the ends of the gauntlet. Make sure the opening is * horizontally adjacent to a non-permanent wall for interoperability * with ensure_connectedness(). */ i = 0; while (1) { struct loc grid = loc(0, randint1(gauntlet->height - 2)); if (i >= 20) { uncreate_artifacts(gauntlet); cave_free(gauntlet); uncreate_artifacts(left); cave_free(left); uncreate_artifacts(right); cave_free(right); *p_error = "could not open entrance to the labyrinth"; return NULL; } if (!square_isperm(gauntlet, loc_sum(grid, loc(1, 0)))) { square_set_feat(gauntlet, grid, FEAT_GRANITE); break; } ++i; } i = 0; while (1) { struct loc grid = loc(gauntlet->width - 1, randint1(gauntlet->height - 2)); if (i >= 20) { uncreate_artifacts(gauntlet); cave_free(gauntlet); uncreate_artifacts(left); cave_free(left); uncreate_artifacts(right); cave_free(right); *p_error = "could not open entrance to the labyrinth"; return NULL; } if (!square_isperm(gauntlet, loc_sum(grid, loc(-1, 0)))) { square_set_feat(gauntlet, grid, FEAT_GRANITE); break; } ++i; } /* General amount of rubble, traps and monsters */ k = MAX(MIN(p->depth / 3, 10), 2) / 2; /* Put the character in the arrival cavern */ arrival = (p->upkeep->create_down_stair) ? right : left; if (!new_player_spot(arrival, p)) { uncreate_artifacts(gauntlet); cave_free(gauntlet); uncreate_artifacts(left); cave_free(left); uncreate_artifacts(right); cave_free(right); *p_error = "could not place player"; return NULL; } /* * Account for the player's location relative to the right and left * chunks for use in pick_and_place_distant_monster(). The * transformations here have to match what the calls to chunk_copy() * below do. */ if (arrival == right) { p_loc_in_r = p->grid; p_loc_in_l.x = line2 + p->grid.x; p_loc_in_l.y = p->grid.y; } else { p_loc_in_l = p->grid; p_loc_in_r.x = p->grid.x - line2; p_loc_in_r.y = p->grid.y; } /* Pick some monsters for the left cavern */ i = z_info->level_monster_min + randint1(4) + k; /* Place the monsters */ for (; i > 0; i--) { pick_and_place_distant_monster(left, p_loc_in_l, 0, true, left->depth); } /* Pick some of monsters for the right cavern */ i = z_info->level_monster_min + randint1(4) + k; /* Place the monsters */ for (; i > 0; i--) { pick_and_place_distant_monster(right, p_loc_in_r, 0, true, right->depth); } /* Pick a larger number of monsters for the gauntlet */ i = (z_info->level_monster_min + randint1(6) + k); /* Find appropriate monsters */ while (true) { /* Choose a pit profile */ set_pit_type(gauntlet->depth, 0); /* Set monster generation restrictions */ if (mon_restrict(dun->pit_type->name, gauntlet->depth, gauntlet->depth, true)) break; } ROOM_LOG("Gauntlet - %s", dun->pit_type->name); /* Place labyrinth monsters */ spread_monsters(gauntlet, dun->pit_type->name, gauntlet->depth, i, gauntlet->height / 2, gauntlet->width / 2, gauntlet->height / 2, gauntlet->width / 2, ORIGIN_LABYRINTH); /* Remove our restrictions. */ (void) mon_restrict(NULL, gauntlet->depth, gauntlet->depth, false); /* Make the level */ c = cave_new(y_size, left->width + gauntlet->width + right->width); c->depth = p->depth; /* Fill cave area with basic granite */ fill_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_GRANITE, SQUARE_NONE); /* Fill the area between the caverns with permanent rock */ fill_rectangle(c, 0, line1, c->height - 1, line2 - 1, FEAT_PERM, SQUARE_NONE); /* Copy in the pieces */ chunk_copy(c, p, left, 0, 0, 0, false); chunk_copy(c, p, gauntlet, (y_size - gauntlet->height) / 2, line1, 0, false); chunk_copy(c, p, right, 0, line2, 0, false); /* Free the chunks */ cave_free(left); cave_free(gauntlet); cave_free(right); /* Generate permanent walls around the edge of the generated area */ draw_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_PERM, SQUARE_NONE, true); /* Connect */ ensure_connectedness(c, true); /* Put some rubble in corridors */ alloc_objects(c, SET_CORR, TYP_RUBBLE, randint1(k), c->depth, 0); /* Place some traps in the dungeon */ alloc_objects(c, SET_CORR, TYP_TRAP, randint1(k), c->depth, 0); /* Put some objects in rooms */ alloc_objects(c, SET_ROOM, TYP_OBJECT, Rand_normal(z_info->room_item_av, 3), c->depth, ORIGIN_FLOOR); /* Put some objects/gold in the dungeon */ alloc_objects(c, SET_BOTH, TYP_OBJECT, Rand_normal(z_info->both_item_av, 3), c->depth, ORIGIN_FLOOR); alloc_objects(c, SET_BOTH, TYP_GOLD, Rand_normal(z_info->both_gold_av, 3), c->depth, ORIGIN_FLOOR); return c; } /* ------------------ ARENA ---------------- */ /** * Generate an arena level - an open single combat arena. * * \param p is the player * \param min_height is the minimum expected height, in grids, for the level * \param min_width is the minimum expected width, in grids, for the level * \return a pointer to the generated chunk */ struct chunk *arena_gen(struct player *p, int min_height, int min_width) { struct chunk *c; struct monster *mon = p->upkeep->health_who; c = cave_new(min_height, min_width); c->depth = p->depth; c->name = string_make("arena"); /* Fill cave area with floors */ fill_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_FLOOR, SQUARE_NONE); /* Bound with perma-rock */ draw_rectangle(c, 0, 0, c->height - 1, c->width - 1, FEAT_PERM, SQUARE_NONE, true); /* Place the player */ player_place(c, p, loc(1, c->height - 2)); /* Place the monster */ memcpy(&c->monsters[mon->midx], mon, sizeof(*mon)); mon = &c->monsters[mon->midx]; mon->grid = loc(c->width - 2, 1); square_set_mon(c, mon->grid, mon->midx); c->mon_max = mon->midx + 1; c->mon_cnt = 1; update_mon(mon, c, true); p->upkeep->health_who = mon; /* Ignore its held objects */ mon->held_obj = NULL; /* Give it a group */ monster_group_start(c, mon, 0); return c; }
0
0.974646
1
0.974646
game-dev
MEDIA
0.95028
game-dev
0.941429
1
0.941429
CrypticMonkey33/ArchipelagoExplorersOfSky
3,714
worlds/clique/__init__.py
from typing import List, Dict, Any from BaseClasses import Region, Tutorial from worlds.AutoWorld import WebWorld, World from .Items import CliqueItem, item_data_table, item_table from .Locations import CliqueLocation, location_data_table, location_table, locked_locations from .Options import CliqueOptions from .Regions import region_data_table from .Rules import get_button_rule class CliqueWebWorld(WebWorld): theme = "partyTime" setup_en = Tutorial( tutorial_name="Start Guide", description="A guide to playing Clique.", language="English", file_name="guide_en.md", link="guide/en", authors=["Phar"] ) setup_de = Tutorial( tutorial_name="Anleitung zum Anfangen", description="Eine Anleitung um Clique zu spielen.", language="Deutsch", file_name="guide_de.md", link="guide/de", authors=["Held_der_Zeit"] ) tutorials = [setup_en, setup_de] class CliqueWorld(World): """The greatest game of all time.""" game = "Clique" web = CliqueWebWorld() options: CliqueOptions options_dataclass = CliqueOptions location_name_to_id = location_table item_name_to_id = item_table def create_item(self, name: str) -> CliqueItem: return CliqueItem(name, item_data_table[name].type, item_data_table[name].code, self.player) def create_items(self) -> None: item_pool: List[CliqueItem] = [] for name, item in item_data_table.items(): if item.code and item.can_create(self): item_pool.append(self.create_item(name)) self.multiworld.itempool += item_pool def create_regions(self) -> None: # Create regions. for region_name in region_data_table.keys(): region = Region(region_name, self.player, self.multiworld) self.multiworld.regions.append(region) # Create locations. for region_name, region_data in region_data_table.items(): region = self.get_region(region_name) region.add_locations({ location_name: location_data.address for location_name, location_data in location_data_table.items() if location_data.region == region_name and location_data.can_create(self) }, CliqueLocation) region.add_exits(region_data_table[region_name].connecting_regions) # Place locked locations. for location_name, location_data in locked_locations.items(): # Ignore locations we never created. if not location_data.can_create(self): continue locked_item = self.create_item(location_data_table[location_name].locked_item) self.get_location(location_name).place_locked_item(locked_item) # Set priority location for the Big Red Button! self.options.priority_locations.value.add("The Big Red Button") def get_filler_item_name(self) -> str: return "A Cool Filler Item (No Satisfaction Guaranteed)" def set_rules(self) -> None: button_rule = get_button_rule(self) self.get_location("The Big Red Button").access_rule = button_rule self.get_location("In the Player's Mind").access_rule = button_rule # Do not allow button activations on buttons. self.get_location("The Big Red Button").item_rule = lambda item: item.name != "Button Activation" # Completion condition. self.multiworld.completion_condition[self.player] = lambda state: state.has("The Urge to Push", self.player) def fill_slot_data(self) -> Dict[str, Any]: return { "color": self.options.color.current_key }
0
0.795141
1
0.795141
game-dev
MEDIA
0.49454
game-dev
0.962391
1
0.962391
seppukudevelopment/seppuku
1,451
src/main/java/me/rigamortis/seppuku/impl/module/misc/FakePlayerModule.java
package me.rigamortis.seppuku.impl.module.misc; import com.mojang.authlib.GameProfile; import me.rigamortis.seppuku.api.module.Module; import me.rigamortis.seppuku.api.value.Value; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityOtherPlayerMP; /** * @author Seth * @author noil */ public final class FakePlayerModule extends Module { public final Value<String> username = new Value<String>("Username", new String[]{"name", "uname", "u"}, "The username of the fake player", "Notch"); private final Minecraft mc = Minecraft.getMinecraft(); private EntityOtherPlayerMP entity; public FakePlayerModule() { super("FakePlayer", new String[]{"FakeP", "FPlayer"}, "Adds a fake player to your game", "NONE", -1, Module.ModuleType.MISC); } @Override public void onEnable() { super.onEnable(); if (mc.player != null && mc.world != null) { entity = new EntityOtherPlayerMP(mc.world, new GameProfile(mc.player.getUniqueID(), username.getValue())); entity.copyLocationAndAnglesFrom(mc.player); entity.inventory.copyInventory(mc.player.inventory); mc.world.addEntityToWorld(6942069, entity); } } @Override public void onDisable() { super.onDisable(); if (mc.world != null) { if (entity != null) { mc.world.removeEntity(entity); } } } }
0
0.787173
1
0.787173
game-dev
MEDIA
0.92276
game-dev
0.691635
1
0.691635
bibendovsky/ltjs
2,357
game/objectdll/objectshared/door.h
// ----------------------------------------------------------------------- // // // MODULE : DOOR.h // // PURPOSE : A Door object // // CREATED : 8/5/97 5:07:00 PM // // (c) 1997-2001 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __DOOR_H__ #define __DOOR_H__ // // Includes... // #include "activeworldmodel.h" // // Defines... // // Assign these to the equivelant AactiveWorldModel states... #define DOORSTATE_CLOSED AWM_STATE_OFF #define DOORSTATE_CLOSING AWM_STATE_POWEROFF #define DOORSTATE_OPEN AWM_STATE_ON #define DOORSTATE_OPENING AWM_STATE_POWERON LINKTO_MODULE( Door ); // // Structs... // class Door : public ActiveWorldModel { public: // Methods... Door(); virtual ~Door(); LTBOOL IsLockedForCharacter( HOBJECT hChar ) const; uint8 GetState() const { return m_nCurState; } LTBOOL IsAITriggerable() const { return ( m_dwPropFlags & AWM_PROP_AIACTIVATE ); } LTFLOAT GetYaw() const { return m_fYaw; } void SetAIUser(HOBJECT hAIUser) { m_hAIUser = hAIUser; } HOBJECT GetAIUser() const { return m_hAIUser; } HOBJECT GetDoorLink() const { return m_hDoorLink; } protected: // Members... HSTRING m_hstrDoorLink; // Name of other door we are linked to for synched motion LTObjRef m_hDoorLink; // Door Object that we are linked to LTObjRef m_hAIUser; // Handle to AI currently using the door. LTBOOL IsLocked() const { return ( m_dwPropFlags & AWM_PROP_LOCKED ); } protected: // Methods... // Engine message handlers... virtual uint32 OnAllObjectsCreated( ); virtual bool OnTrigger( HOBJECT hSender, const CParsedMsg &cMsg ); virtual void HandleTriggerMsg( ); virtual void HandleLock(LTBOOL bLock); virtual void OnSave( ILTMessage_Write *pMsg, uint32 dwSaveFlags ); virtual void OnLoad( ILTMessage_Read *pMsg, uint32 dwSaveFlags ); virtual void ReadProps( ObjectCreateStruct *pOCS ); // State methods... virtual void SetPowerOn( ); virtual void SetPowerOff( ); // Activation... virtual void Activate( HOBJECT hObj ); private: // Methods... // Trigger handlers... void HandelLinkTriggerMsg( LTBOOL bTriggerLink ); void TriggerLink( HOBJECT hActivateObj ); void TriggerClose( ); void PlayDoorKnobAni( char* pAniName ); }; #endif // __DOOR_H__
0
0.96329
1
0.96329
game-dev
MEDIA
0.899612
game-dev
0.714246
1
0.714246
SuperNewRoles/SuperNewRoles
6,715
SuperNewRoles/Roles/Ability/SafecrackerAbility.cs
using System; using System.Collections.Generic; using System.Linq; using AmongUs.GameOptions; using HarmonyLib; using SuperNewRoles.Events; using SuperNewRoles.Events.PCEvents; using SuperNewRoles.Modules; using SuperNewRoles.Modules.Events.Bases; using SuperNewRoles.Roles.Ability.CustomButton; using SuperNewRoles.Roles.Neutral; using UnityEngine; namespace SuperNewRoles.Roles.Ability; public class SafecrackerAbility : AbilityBase { public float KillGuardTaskRate { get; } public int MaxKillGuardCount { get; } public float ExiledGuardTaskRate { get; } public int MaxExiledGuardCount { get; } public float UseVentTaskRate { get; } public float UseSaboTaskRate { get; } public float ImpostorLightTaskRate { get; } public float CheckImpostorTaskRate { get; } public bool ChangeTaskPrefab { get; } private int _allTaskCount; private int _killGuardCount; private int _exiledGuardCount; private Dictionary<CheckTasks, bool> _unlockedAbilities; private EventListener<TryKillEventData> _onTryKillListener; private EventListener<ExileEventData> _exileListener; private EventListener<TaskCompleteEventData> _taskCompleteListener; private TaskOptionData _task; public enum CheckTasks { KillGuard, ExiledGuard, UseVent, UseSabo, ImpostorLight, CheckImpostor } public SafecrackerAbility( float killGuardTaskRate, int maxKillGuardCount, float exiledGuardTaskRate, int maxExiledGuardCount, float useVentTaskRate, float useSaboTaskRate, float impostorLightTaskRate, float checkImpostorTaskRate, bool changeTaskPrefab, TaskOptionData task) { KillGuardTaskRate = killGuardTaskRate; MaxKillGuardCount = maxKillGuardCount; ExiledGuardTaskRate = exiledGuardTaskRate; MaxExiledGuardCount = maxExiledGuardCount; UseVentTaskRate = useVentTaskRate; UseSaboTaskRate = useSaboTaskRate; ImpostorLightTaskRate = impostorLightTaskRate; CheckImpostorTaskRate = checkImpostorTaskRate; ChangeTaskPrefab = changeTaskPrefab; _unlockedAbilities = new(); _killGuardCount = 0; _exiledGuardCount = 0; _task = task; } public override void AttachToAlls() { base.AttachToAlls(); _allTaskCount = _task.Total; _unlockedAbilities.Clear(); _killGuardCount = 0; _exiledGuardCount = 0; _onTryKillListener = TryKillEvent.Instance.AddListener(OnTryKill); _exileListener = ExileEvent.Instance.AddListener(OnExile); _taskCompleteListener = TaskCompleteEvent.Instance.AddListener(OnTaskComplete); Player.AttachAbility(new CustomTaskAbility(() => (true, false, null), _task), new AbilityParentAbility(this)); Player.AttachAbility(new CustomTaskTypeAbility(TaskTypes.UnlockSafe, ChangeTaskPrefab, MapNames.Airship), new AbilityParentAbility(this)); } public override void DetachToAlls() { base.DetachToAlls(); TryKillEvent.Instance.RemoveListener(_onTryKillListener); ExileEvent.Instance.RemoveListener(_exileListener); TaskCompleteEvent.Instance.RemoveListener(_taskCompleteListener); } private int GetTotalTaskCount() { return Player?.Data?.Tasks?.Count ?? 0; } private int GetCompletedTaskCount() { return ModHelpers.TaskCompletedData(Player.Player.Data).completed; } private bool CheckTaskProgress(CheckTasks taskType, float requiredRate) { if (requiredRate <= 0f) return false; if (_unlockedAbilities.TryGetValue(taskType, out var unlocked) && unlocked) return true; var requiredTasks = Mathf.CeilToInt(_allTaskCount * (requiredRate / 100f)); if (GetCompletedTaskCount() < requiredTasks) return false; _unlockedAbilities[taskType] = true; return true; } public bool CanKillGuard() => CheckTaskProgress(CheckTasks.KillGuard, KillGuardTaskRate) && _killGuardCount < MaxKillGuardCount; public bool CanExiledGuard() => CheckTaskProgress(CheckTasks.ExiledGuard, ExiledGuardTaskRate) && _exiledGuardCount < MaxExiledGuardCount; public bool CanUseVent() => CheckTaskProgress(CheckTasks.UseVent, UseVentTaskRate); public bool CanUseSabo() => CheckTaskProgress(CheckTasks.UseSabo, UseSaboTaskRate); public bool HasImpostorLight() => CheckTaskProgress(CheckTasks.ImpostorLight, ImpostorLightTaskRate); public bool CanCheckImpostor() => CheckTaskProgress(CheckTasks.CheckImpostor, CheckImpostorTaskRate); private void OnTaskComplete(TaskCompleteEventData data) { if (data.player != Player) return; CheckAllAbilities(); // すべてのタスクが完了したかチェック if (GetCompletedTaskCount() >= _allTaskCount) { // Safecrackerの勝利(ただし生存している場合のみ) if (AmongUsClient.Instance.AmHost && !Player.Data.IsDead) { EndGamer.RpcEndGameWithWinner(Patches.CustomGameOverReason.SafecrackerWin, WinType.SingleNeutral, [Player], Safecracker.Instance.RoleColor, "Safecracker", "WinText"); } } } // todo private void OnTryKill(TryKillEventData data) { if (data.RefTarget != Player) return; if (CanKillGuard()) { data.RefSuccess = false; _killGuardCount++; if (data.Killer.AmOwner) ExPlayerControl.LocalPlayer.ResetKillCooldown(); if (Player.AmOwner) { // TODO: Add translation key HudManager.Instance.ShowPopUp(ModTranslation.GetString("SafecrackerKillGuardActivated")); } } } private void OnExile(ExileEventData data) { if (data.exiled != Player) return; if (CanExiledGuard()) { Player.Player.Revive(); _exiledGuardCount++; if (Player.AmOwner) { HudManager.Instance.ShowPopUp(ModTranslation.GetString("SafecrackerExiledGuardActivated")); } } } private void CheckAllAbilities() { CanKillGuard(); CanExiledGuard(); if (CanUseVent() && !Player.HasAbility<CustomVentAbility>()) { Player.AttachAbility(new CustomVentAbility(() => true), new AbilityParentAbility(this)); } if (CanUseSabo() && !Player.HasAbility<CustomSaboAbility>()) { Player.AttachAbility(new CustomSaboAbility(() => true), new AbilityParentAbility(this)); } HasImpostorLight(); CanCheckImpostor(); } }
0
0.95044
1
0.95044
game-dev
MEDIA
0.814448
game-dev
0.988958
1
0.988958
petiaccja/Inline-Engine
4,397
Engine/GuiEngine/ControlStateTracker.cpp
#include "ControlStateTracker.hpp" namespace inl::gui { ControlStateTracker::ControlStateTracker(Control* target) : m_target{ target } { target->OnEnterArea += Delegate<void(Control*)>{ &ControlStateTracker::OnMouseEnter, this }; target->OnLeaveArea += Delegate<void(Control*)>{ &ControlStateTracker::OnMouseLeave, this }; target->OnGainFocus += Delegate<void(Control*)>{ &ControlStateTracker::OnGainFocus, this }; target->OnLoseFocus += Delegate<void(Control*)>{ &ControlStateTracker::OnLoseFocus, this }; target->OnMouseDown += Delegate<void(Control*, Vec2, eMouseButton)>{ &ControlStateTracker::OnMouseDown, this }; target->OnMouseUp += Delegate<void(Control*, Vec2, eMouseButton)>{ &ControlStateTracker::OnMouseUp, this }; target->OnDragBegin += Delegate<void(Control*, Vec2)>{ &ControlStateTracker::OnDragBegin, this }; target->OnDragEnd += Delegate<void(Control*, Vec2, Control*)>{ &ControlStateTracker::OnDragEnd, this }; } ControlStateTracker::~ControlStateTracker() { m_target->OnEnterArea -= Delegate<void(Control*)>{ &ControlStateTracker::OnMouseEnter, this }; m_target->OnLeaveArea -= Delegate<void(Control*)>{ &ControlStateTracker::OnMouseLeave, this }; m_target->OnGainFocus -= Delegate<void(Control*)>{ &ControlStateTracker::OnGainFocus, this }; m_target->OnLoseFocus -= Delegate<void(Control*)>{ &ControlStateTracker::OnLoseFocus, this }; m_target->OnMouseDown -= Delegate<void(Control*, Vec2, eMouseButton)>{ &ControlStateTracker::OnMouseDown, this }; m_target->OnMouseUp -= Delegate<void(Control*, Vec2, eMouseButton)>{ &ControlStateTracker::OnMouseUp, this }; m_target->OnDragBegin -= Delegate<void(Control*, Vec2)>{ &ControlStateTracker::OnDragBegin, this }; m_target->OnDragEnd -= Delegate<void(Control*, Vec2, Control*)>{ &ControlStateTracker::OnDragEnd, this }; } void ControlStateTracker::OnMouseEnter(Control* arg) { if (arg != m_target) { return; } m_hovered = true; switch (m_state) { case eControlState::NORMAL: m_state = eControlState::HOVERED; break; default: return; } } void ControlStateTracker::OnMouseLeave(Control* arg) { if (arg != m_target) { return; } m_hovered = false; switch (m_state) { case eControlState::NORMAL: //[[fallthrough]] case eControlState::HOVERED: m_state = eControlState::NORMAL; break; default: return; } } void ControlStateTracker::OnGainFocus(Control* arg) { if (arg != m_target) { return; } m_focused = true; switch (m_state) { case eControlState::NORMAL: case eControlState::HOVERED: m_state = eControlState::FOCUSED; break; default: return; } } void ControlStateTracker::OnLoseFocus(Control* arg) { if (arg != m_target) { return; } m_focused = false; switch (m_state) { case eControlState::NORMAL: case eControlState::HOVERED: case eControlState::FOCUSED: m_state = m_hovered ? eControlState::HOVERED : eControlState::NORMAL; break; default: return; } } void ControlStateTracker::OnMouseDown(Control* arg, Vec2, eMouseButton) { if (arg != m_target) { return; } m_held = true; switch (m_state) { case eControlState::NORMAL: case eControlState::HOVERED: case eControlState::FOCUSED: m_state = eControlState::HELD; break; default: return; } } void ControlStateTracker::OnMouseUp(Control* arg, Vec2, eMouseButton) { if (arg != m_target) { return; } m_held = false; switch (m_state) { case eControlState::NORMAL: case eControlState::HOVERED: case eControlState::FOCUSED: case eControlState::HELD: m_state = m_focused ? eControlState::FOCUSED : (m_hovered ? eControlState::HOVERED : eControlState::NORMAL); break; default: return; } } void ControlStateTracker::OnDragBegin(Control* arg, Vec2) { if (arg != m_target) { return; } switch (m_state) { case eControlState::NORMAL: case eControlState::HOVERED: case eControlState::FOCUSED: case eControlState::HELD: m_state = eControlState::DRAGGED; break; default: return; } } void ControlStateTracker::OnDragEnd(Control* arg, Vec2, Control* dragTarget) { if (arg != m_target) { return; } if (dragTarget != m_target) { m_held = false; } m_state = m_held ? eControlState::HELD : (m_focused ? eControlState::FOCUSED : (m_hovered ? eControlState::HOVERED : eControlState::NORMAL)); } eControlState ControlStateTracker::Get() const { return m_state; } } // namespace inl::gui
0
0.981414
1
0.981414
game-dev
MEDIA
0.728173
game-dev
0.913639
1
0.913639
shiptest-ss13/Shiptest
3,428
code/datums/looping_sounds/_looping_sound.dm
/* output_atoms (list of atoms) The destination(s) for the sounds mid_sounds (list or soundfile) Since this can be either a list or a single soundfile you can have random sounds. May contain further lists but must contain a soundfile at the end. mid_length (num) The length to wait between playing mid_sounds start_sound (soundfile) Played before starting the mid_sounds loop start_length (num) How long to wait before starting the main loop after playing start_sound end_sound (soundfile) The sound played after the main loop has concluded chance (num) Chance per loop to play a mid_sound volume (num) Sound output volume max_loops (num) The max amount of loops to run for. direct (bool) If true plays directly to provided atoms instead of from them */ /datum/looping_sound var/list/atom/output_atoms var/mid_sounds var/mid_length ///Override for volume of start sound var/start_volume var/start_sound var/start_length ///Override for volume of end sound var/end_volume var/end_sound var/chance var/volume = 100 var/vary = FALSE var/max_loops var/direct var/extra_range = 0 var/falloff_exponent var/timerid var/falloff_distance /// Common cache of the mid sounds lists var/static/mid_sounds_cache = list() /datum/looping_sound/New(list/_output_atoms=list(), start_immediately=FALSE, _direct=FALSE) if(!mid_sounds) WARNING("A looping sound datum was created without sounds to play.") return /// Common cache handling if(islist(mid_sounds)) if(!mid_sounds_cache[type]) mid_sounds_cache[type] = mid_sounds mid_sounds = mid_sounds_cache[type] output_atoms = _output_atoms direct = _direct if(start_immediately) start() /datum/looping_sound/Destroy() stop() output_atoms = null return ..() /datum/looping_sound/proc/start(atom/add_thing) if(add_thing) output_atoms |= add_thing if(timerid) return on_start() /datum/looping_sound/proc/stop(atom/remove_thing) if(remove_thing) output_atoms -= remove_thing if(!timerid) return on_stop() deltimer(timerid, SSsound_loops) timerid = null /datum/looping_sound/proc/sound_loop(starttime) if(max_loops && world.time >= starttime + mid_length * max_loops) stop() return if(!chance || prob(chance)) play(get_sound(starttime)) if(!timerid) timerid = addtimer(CALLBACK(src, PROC_REF(sound_loop), world.time), mid_length, TIMER_CLIENT_TIME | TIMER_STOPPABLE | TIMER_LOOP, SSsound_loops) /datum/looping_sound/proc/play(soundfile, volume_override) var/list/atoms_cache = output_atoms var/sound/S = sound(soundfile) if(direct) S.channel = SSsounds.random_available_channel() S.volume = volume_override || volume //Use volume as fallback if theres no override for(var/i in 1 to atoms_cache.len) var/atom/thing = atoms_cache[i] if(direct) SEND_SOUND(thing, S) else playsound(thing, S, volume, vary, extra_range, falloff_exponent = falloff_exponent, falloff_distance = falloff_distance) /datum/looping_sound/proc/get_sound(starttime, _mid_sounds) . = _mid_sounds || mid_sounds while(!isfile(.) && !isnull(.)) . = pick_weight(.) /datum/looping_sound/proc/on_start() var/start_wait = 0 if(start_sound) play(start_sound, start_volume) start_wait = start_length addtimer(CALLBACK(src, PROC_REF(sound_loop)), start_wait, TIMER_CLIENT_TIME, SSsound_loops) /datum/looping_sound/proc/on_stop() if(end_sound) play(end_sound, end_volume)
0
0.796274
1
0.796274
game-dev
MEDIA
0.687793
game-dev,audio-video-media
0.969572
1
0.969572
fuse-open/fuselibs
1,252
Source/Fuse.Text/Implementation/SinglyLinkedList.uno
using Uno.Collections; namespace Fuse.Text { class SinglyLinkedList<T> : IEnumerable<T> { public T Value { get; private set; } public SinglyLinkedList<T> Next; public SinglyLinkedList(T value, SinglyLinkedList<T> next = null) { Value = value; Next = next; } public IEnumerator<T> GetEnumerator() { return new Enumerator(this); } public static SinglyLinkedList<T> FromEnumerable(IEnumerable<T> xs) { var before = new SinglyLinkedList<T>(default(T), null); var head = before; foreach (var x in xs) { head.Next = new SinglyLinkedList<T>(x, null); head = head.Next; } return before.Next; } class Enumerator : IEnumerator<T> { SinglyLinkedList<T> _beforeHead; SinglyLinkedList<T> _current; public Enumerator(SinglyLinkedList<T> list) { _beforeHead = new SinglyLinkedList<T>(default(T), list); Reset(); } public T Current { get { return _current.Value; } } public void Reset() { _current = _beforeHead; } public bool MoveNext() { if (_current != null) { _current = _current.Next; return _current != null; } return false; } public void Dispose() { // Nothing to do } } } }
0
0.80396
1
0.80396
game-dev
MEDIA
0.279328
game-dev
0.953334
1
0.953334
OpenCoreMMO/OpenCoreMMO
2,171
src/ApplicationServer/NeoServer.Server.Events/Creature/CreatureAddedOnMapEventHandler.cs
using NeoServer.Domain.Common.Contracts.Creatures; using NeoServer.Domain.Common.Contracts.World; using NeoServer.Domain.Common.Creatures; using NeoServer.Domain.Common.Helpers; using NeoServer.Networking.Packets.Outgoing.Creature; using NeoServer.Networking.Packets.Outgoing.Effect; using NeoServer.Networking.Packets.Outgoing.Item; using NeoServer.Server.Common.Contracts; using NeoServer.Server.Common.Contracts.Network; namespace NeoServer.Server.Events.Creature; public class CreatureAddedOnMapEventHandler : IEventHandler { private readonly IGameServer game; public CreatureAddedOnMapEventHandler(IGameServer game) { this.game = game; } public void Execute(IWalkableCreature creature, ICylinder cylinder) { if (Guard.AnyNull(cylinder, cylinder.TileSpectators, creature)) return; var tile = cylinder.ToTile; if (tile.IsNull()) return; foreach (var cylinderSpectator in cylinder.TileSpectators) { var spectator = cylinderSpectator.Spectator; if (spectator is not IPlayer spectatorPlayer) continue; if (Equals(creature, spectator)) continue; if (!spectator.CanSee(creature.Location)) continue; if (!game.CreatureManager.GetPlayerConnection(spectator.CreatureId, out var connection)) continue; SendPacketsToSpectator(game, spectatorPlayer, creature, connection, cylinderSpectator.ToStackPosition == byte.MaxValue ? cylinderSpectator.FromStackPosition : cylinderSpectator.ToStackPosition); connection.Send(); } } private static void SendPacketsToSpectator(IGameServer game, IPlayer playerToSend, IWalkableCreature creatureAdded, IConnection connection, byte stackPosition) { connection.OutgoingPackets.Enqueue(new AddAtStackPositionPacket(game.Map, creatureAdded, stackPosition, playerToSend)); connection.OutgoingPackets.Enqueue(new AddCreaturePacket(playerToSend, creatureAdded)); connection.OutgoingPackets.Enqueue(new MagicEffectPacket(creatureAdded.Location, EffectT.BubbleBlue)); } }
0
0.942663
1
0.942663
game-dev
MEDIA
0.73931
game-dev
0.696252
1
0.696252
uniVocity/univocity-parsers
3,487
src/main/java/com/univocity/parsers/tsv/TsvFormat.java
/******************************************************************************* * Copyright 2014 Univocity Software Pty Ltd * * 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.univocity.parsers.tsv; import com.univocity.parsers.common.*; import java.util.*; /** * The TSV format configuration, for tab-separated inputs. It offers the options in the default configuration in {@link Format}, as well as * the {@link #escapeChar} character for escaping \t, \n, \r and \ in TSV values. * * Delimiters are defined as tab characters '\t' * * @see com.univocity.parsers.common.Format * * @author Univocity Software Pty Ltd - <a href="mailto:parsers@univocity.com">parsers@univocity.com</a> * */ public class TsvFormat extends Format { private char escapeChar = '\\'; private char escapedTabChar = 't'; /** * Defines the character used for escaping special characters in TSV inputs: \t, \n, \r and \ . Defaults to '\\' * @param escapeChar the escape character */ public void setEscapeChar(char escapeChar) { this.escapeChar = escapeChar; } /** * Returns the character used for escaping special characters in TSV inputs: \t, \n, \r and \ * * @return the escape character. */ public char getEscapeChar() { return escapeChar; } /** * Returns the character that should be used to represent an escaped tab, i.e. the character before the defined * {@link #getEscapeChar()}. For example, if {@link #getEscapeChar()} == '\\' and {@link #getEscapedTabChar() == 'X'}, * the sequence {@code '\X'} will identify a tab. * * Defaults to {@code 't'}. * * @return the character following the {@link #getEscapeChar()} that represents an escaped tab. */ public char getEscapedTabChar() { return escapedTabChar; } /** * Defines the character that should be used to represent an escaped tab, i.e. the character before the defined * {@link #getEscapeChar()}. For example, if {@link #getEscapeChar()} == '\\' and {@link #getEscapedTabChar() == 'X'}, * the sequence {@code '\X'} will identify a tab. * * Defaults to {@code 't'}. * * @param escapedTabChar the character following the {@link #getEscapeChar()} that represents an escaped tab. */ public void setEscapedTabChar(char escapedTabChar) { this.escapedTabChar = escapedTabChar; } /** * Identifies whether or not a given character is used for escaping special characters in TSV (\t, \n, \r and \). * @param ch the character to be verified * @return true if the given character is escape character, false otherwise */ public boolean isEscapeChar(char ch) { return this.escapeChar == ch; } @Override protected TreeMap<String, Object> getConfiguration() { TreeMap<String, Object> out = new TreeMap<String, Object>(); out.put("Escape character", escapeChar); return out; } @Override public final TsvFormat clone() { return (TsvFormat) super.clone(); } }
0
0.826447
1
0.826447
game-dev
MEDIA
0.474397
game-dev
0.767317
1
0.767317
Isol4tion/HexTech-nightly
34,755
src/main/java/me/hextech/mod/modules/impl/client/HUD_ssNtBhEveKlCmIccBvAN.java
package me.hextech.mod.modules.impl.client; import me.hextech.HexTech; import me.hextech.api.utils.entity.InventoryUtil; import me.hextech.api.utils.math.MathUtil; import me.hextech.api.utils.math.Timer; import me.hextech.api.utils.render.ColorUtil; import me.hextech.mod.modules.Module_eSdgMXWuzcxgQVaJFmKZ; import me.hextech.mod.modules.impl.setting.ComboBreaks; import me.hextech.mod.modules.settings.impl.*; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.ChatScreen; import net.minecraft.entity.effect.StatusEffect; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.entity.effect.StatusEffectUtil; import net.minecraft.entity.effect.StatusEffects; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Items; import net.minecraft.util.Formatting; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; public class HUD_ssNtBhEveKlCmIccBvAN extends Module_eSdgMXWuzcxgQVaJFmKZ { public static HUD_ssNtBhEveKlCmIccBvAN INSTANCE; private final EnumSetting<Page> page = this.add(new EnumSetting<Page>("Page", Page.GLOBAL)); public final BooleanSetting armor = this.add(new BooleanSetting("Armor", true, v -> this.page.getValue() == Page.GLOBAL)); public final SliderSetting lagTime = this.add(new SliderSetting("LagTime", 1000, 0, 2000, v -> this.page.getValue() == Page.GLOBAL)); public final BooleanSetting lowerCase = this.add(new BooleanSetting("LowerCase", false, v -> this.page.getValue() == Page.GLOBAL)); private final BooleanSetting grayColors = this.add(new BooleanSetting("Gray", true, v -> this.page.getValue() == Page.GLOBAL)); private final BooleanSetting renderingUp = this.add(new BooleanSetting("RenderingUp", true, v -> this.page.getValue() == Page.GLOBAL)); private final BooleanSetting watermark = this.add(new BooleanSetting("Watermark", true, v -> this.page.getValue() == Page.ELEMENTS).setParent()); public final SliderSetting offset = this.add(new SliderSetting("Offset", 8.0, 0.0, 100.0, -1.0, v -> this.watermark.isOpen() && this.page.getValue() == Page.ELEMENTS)); public final StringSetting watermarkString = this.add(new StringSetting("Text", "\u029c\u1d07\u04fc\u1d1b\u1d07\u1d04\u029c", v -> this.watermark.isOpen() && this.page.getValue() == Page.ELEMENTS)); private final BooleanSetting watermarkShort = this.add(new BooleanSetting("Shorten", false, v -> this.watermark.isOpen() && this.page.getValue() == Page.ELEMENTS)); private final BooleanSetting watermarkVerColor = this.add(new BooleanSetting("VerColor", true, v -> this.watermark.isOpen() && this.page.getValue() == Page.ELEMENTS)); private final SliderSetting waterMarkY = this.add(new SliderSetting("Height", 2, 2, 12, v -> this.page.getValue() == Page.ELEMENTS && this.watermark.isOpen())); private final BooleanSetting idWatermark = this.add(new BooleanSetting("IdWatermark", true, v -> this.page.getValue() == Page.ELEMENTS)); private final BooleanSetting textRadar = this.add(new BooleanSetting("TextRadar", false, v -> this.page.getValue() == Page.ELEMENTS).setParent()); private final SliderSetting updatedelay = this.add(new SliderSetting("UpdateDelay", 5, 0, 1000, v -> this.page.getValue() == Page.ELEMENTS && this.textRadar.isOpen())); private final BooleanSetting health = this.add(new BooleanSetting("Health", false, v -> this.page.getValue() == Page.ELEMENTS && this.textRadar.isOpen())); private final BooleanSetting coords = this.add(new BooleanSetting("Position(XYZ)", false, v -> this.page.getValue() == Page.ELEMENTS)); private final BooleanSetting direction = this.add(new BooleanSetting("Direction", false, v -> this.page.getValue() == Page.ELEMENTS)); private final BooleanSetting lag = this.add(new BooleanSetting("LagNotifier", false, v -> this.page.getValue() == Page.ELEMENTS)); private final BooleanSetting greeter = this.add(new BooleanSetting("Welcomer", false, v -> this.page.getValue() == Page.ELEMENTS).setParent()); private final EnumSetting<GreeterMod> greeterMode = this.add(new EnumSetting<GreeterMod>("Mode", GreeterMod.PLAYER, v -> this.page.getValue() == Page.ELEMENTS && this.greeter.isOpen())); private final BooleanSetting greeterNameColor = this.add(new BooleanSetting("NameColor", true, v -> this.greeter.isOpen() && this.greeterMode.getValue() == GreeterMod.PLAYER && this.page.getValue() == Page.ELEMENTS)); private final StringSetting greeterText = this.add(new StringSetting("WelcomerText", "i sniff coke and smoke dope i got 2 habbits", v -> this.greeter.isOpen() && this.greeterMode.getValue() == GreeterMod.CUSTOM && this.page.getValue() == Page.ELEMENTS)); private final BooleanSetting potions = this.add(new BooleanSetting("Potions", false, v -> this.page.getValue() == Page.ELEMENTS).setParent()); private final BooleanSetting potionColor = this.add(new BooleanSetting("PotionColor", false, v -> this.page.getValue() == Page.ELEMENTS && this.potions.isOpen())); private final BooleanSetting pvphud = this.add(new BooleanSetting("PVPHud", false, v -> this.page.getValue() == Page.ELEMENTS).setParent()); public final SliderSetting pvphudoffset = this.add(new SliderSetting("PVPHUDOffset", 8.0, 0.0, 100.0, -1.0, v -> this.page.getValue() == Page.ELEMENTS && this.pvphud.isOpen())); private final BooleanSetting totemtext = this.add(new BooleanSetting("TotemText", false, v -> this.page.getValue() == Page.ELEMENTS && this.pvphud.isOpen())); private final BooleanSetting potiontext = this.add(new BooleanSetting("PotionText", false, v -> this.page.getValue() == Page.ELEMENTS && this.pvphud.isOpen())); private final BooleanSetting crtstalText = this.add(new BooleanSetting("CrystalText", false, v -> this.page.getValue() == Page.ELEMENTS && this.pvphud.isOpen())); private final BooleanSetting attacktext = this.add(new BooleanSetting("ComboBreaksText", false, v -> this.page.getValue() == Page.ELEMENTS && this.pvphud.isOpen())); private final BooleanSetting ping = this.add(new BooleanSetting("Ping", false, v -> this.page.getValue() == Page.ELEMENTS)); private final BooleanSetting speed = this.add(new BooleanSetting("Speed", false, v -> this.page.getValue() == Page.ELEMENTS)); private final BooleanSetting tps = this.add(new BooleanSetting("TPS", false, v -> this.page.getValue() == Page.ELEMENTS)); private final BooleanSetting fps = this.add(new BooleanSetting("FPS", false, v -> this.page.getValue() == Page.ELEMENTS)); private final BooleanSetting time = this.add(new BooleanSetting("Time", false, v -> this.page.getValue() == Page.ELEMENTS)); private final EnumSetting colorMode = this.add(new EnumSetting<ColorMode>("ColorMode", ColorMode.Pulse, v -> this.page.getValue() == Page.Color)); private final SliderSetting rainbowSpeed = this.add(new SliderSetting("RainbowSpeed", 200, 1, 400, v -> (this.colorMode.getValue() == ColorMode.Rainbow || this.colorMode.getValue() == ColorMode.PulseRainbow) && this.page.getValue() == Page.Color)); private final SliderSetting saturation = this.add(new SliderSetting("Saturation", 130.0, 1.0, 255.0, v -> (this.colorMode.getValue() == ColorMode.Rainbow || this.colorMode.getValue() == ColorMode.PulseRainbow) && this.page.getValue() == Page.Color)); private final SliderSetting pulseSpeed = this.add(new SliderSetting("PulseSpeed", 100, 1, 400, v -> (this.colorMode.getValue() == ColorMode.Pulse || this.colorMode.getValue() == ColorMode.PulseRainbow) && this.page.getValue() == Page.Color)); private final SliderSetting rainbowDelay = this.add(new SliderSetting("Delay", 350, 0, 600, v -> this.colorMode.getValue() == ColorMode.Rainbow && this.page.getValue() == Page.Color)); private final ColorSetting color = this.add(new ColorSetting("Color", new Color(255, 255, 255, 255), v -> this.colorMode.getValue() != ColorMode.Rainbow && this.page.getValue() == Page.Color)); private final ColorSetting Acolor = this.add(new ColorSetting("AttackColor", new Color(255, 255, 255, 255), v -> this.colorMode.getValue() != ColorMode.Rainbow && this.page.getValue() == Page.Color)); private final ColorSetting Dcolor = this.add(new ColorSetting("DefendColor", new Color(255, 255, 255, 255), v -> this.colorMode.getValue() != ColorMode.Rainbow && this.page.getValue() == Page.Color)); private final BooleanSetting sync = this.add(new BooleanSetting("Sync", false, v -> this.page.getValue() == Page.Color)); private final BooleanSetting debug = this.add(new BooleanSetting("DebugInfo", false, v -> this.page.getValue() == Page.Dev)); private final Timer timer = new Timer(); int progress = 0; int pulseProgress = 0; private Map<String, Integer> players = new HashMap<String, Integer>(); private int counter = 20; public HUD_ssNtBhEveKlCmIccBvAN() { super("HUD", "HUD elements drawn on your screen", Category.Client); INSTANCE = this; } public static float round2(double value) { BigDecimal bd = new BigDecimal(value); bd = bd.setScale(1, RoundingMode.HALF_UP); return bd.floatValue(); } @Override public void onUpdate() { if (this.timer.passed(this.updatedelay.getValue())) { this.players = this.getTextRadarMap(); this.timer.reset(); } this.progress -= this.rainbowSpeed.getValueInt(); this.pulseProgress -= this.pulseSpeed.getValueInt(); } @Override public void onRender2D(final DrawContext drawContext, final float tickDelta) { if (nullCheck()) { return; } this.counter = 20; final int width = HUD_ssNtBhEveKlCmIccBvAN.mc.getWindow().getScaledWidth(); final int height = HUD_ssNtBhEveKlCmIccBvAN.mc.getWindow().getScaledHeight(); if (this.armor.getValue()) { HexTech.GUI.armorHud.draw(drawContext, tickDelta, null); } if (this.pvphud.getValue()) { this.drawpvphud(drawContext, this.pvphudoffset.getValueInt()); } if (this.textRadar.getValue()) { this.drawTextRadar(drawContext, this.watermark.getValue() ? ((int) (this.waterMarkY.getValue() + 2.0)) : 2); } if (this.watermark.getValue()) { final String nameString = this.watermarkString.getValue(); final String verColor = this.watermarkVerColor.getValue() ? "§f" : ""; final String verString = verColor + (this.watermarkShort.getValue() ? "" : "Nightly"); drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, (this.lowerCase.getValue() ? nameString.toLowerCase() : nameString) + verString, 2, this.waterMarkY.getValueInt(), this.getColor(this.counter)); ++this.counter; } if (this.idWatermark.getValue()) { final String nameString = "\u029c\u1d07\u04fc\u1d1b\u1d07\u1d04\u029c "; final String domainString = "8"; final float offset = HUD_ssNtBhEveKlCmIccBvAN.mc.getWindow().getScaledHeight() / 2.0f - 30.0f; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, nameString + domainString, 2, (int) offset, this.getColor(this.counter)); ++this.counter; } final String grayString = this.grayColors.getValue() ? "§7" : ""; int i = (HUD_ssNtBhEveKlCmIccBvAN.mc.currentScreen instanceof ChatScreen && this.renderingUp.getValue()) ? 13 : (this.renderingUp.getValue() ? -2 : 0); if (this.renderingUp.getValue()) { if (this.potions.getValue()) { final List<StatusEffectInstance> effects = new ArrayList<StatusEffectInstance>(HUD_ssNtBhEveKlCmIccBvAN.mc.player.getStatusEffects()); for (final StatusEffectInstance potionEffect : effects) { final String str = this.getColoredPotionString(potionEffect); i += 10; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? str.toLowerCase() : str, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str)) - 2, height - 2 - i, this.potionColor.getValue() ? potionEffect.getEffectType().getColor() : this.getColor(this.counter)); ++this.counter; } } if (this.speed.getValue()) { final String str2 = grayString + "\u901f\u5ea6 §f" + HexTech.SPEED.getSpeedKpH() + " \u5343\u7c73/\u65f6"; i += 10; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? str2.toLowerCase() : str2, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str2.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str2)) - 2, height - 2 - i, this.getColor(this.counter)); ++this.counter; } if (this.time.getValue()) { final String str2 = grayString + "\u65f6\u95f4 §f" + new SimpleDateFormat("h:mm a").format(new Date()); i += 10; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? str2.toLowerCase() : str2, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str2.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str2)) - 2, height - 2 - i, this.getColor(this.counter)); ++this.counter; } if (this.tps.getValue()) { final String str2 = grayString + "\u670d\u52a1\u5668\u7a33\u5b9a\u6027 §f" + HexTech.SERVER.getTPS(); i += 10; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? str2.toLowerCase() : str2, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str2.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str2)) - 2, height - 2 - i, this.getColor(this.counter)); ++this.counter; } final String fpsText = grayString + "\u5e27\u6570 §f" + HexTech.FPS.getFps(); final String str3 = grayString + "\u5ef6\u8fdf §f" + HexTech.SERVER.getPing(); if (HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str3) > HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(fpsText)) { if (this.ping.getValue()) { i += 10; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? str3.toLowerCase() : str3, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str3.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str3)) - 2, height - 2 - i, this.getColor(this.counter)); ++this.counter; } if (this.fps.getValue()) { i += 10; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? fpsText.toLowerCase() : fpsText, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(fpsText.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(fpsText)) - 2, height - 2 - i, this.getColor(this.counter)); } } else { if (this.fps.getValue()) { i += 10; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? fpsText.toLowerCase() : fpsText, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(fpsText.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(fpsText)) - 2, height - 2 - i, this.getColor(this.counter)); ++this.counter; } if (this.ping.getValue()) { i += 10; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? str3.toLowerCase() : str3, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str3.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str3)) - 2, height - 2 - i, this.getColor(this.counter)); } } } else { if (this.potions.getValue()) { final List<StatusEffectInstance> effects = new ArrayList<StatusEffectInstance>(HUD_ssNtBhEveKlCmIccBvAN.mc.player.getStatusEffects()); for (final StatusEffectInstance potionEffect : effects) { final String str = this.getColoredPotionString(potionEffect); drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? str.toLowerCase() : str, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str)) - 2, 2 + i++ * 10, this.potionColor.getValue() ? potionEffect.getEffectType().getColor() : this.getColor(this.counter)); ++this.counter; } } if (this.speed.getValue()) { final String str2 = grayString + "\u901f\u5ea6 §f" + HexTech.SPEED.getSpeedKpH() + " \u5343\u7c73/\u65f6"; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? str2.toLowerCase() : str2, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str2.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str2)) - 2, 2 + i++ * 10, this.getColor(this.counter)); ++this.counter; } if (this.time.getValue()) { final String str2 = grayString + "\u65f6\u95f4 §f" + new SimpleDateFormat("h:mm a").format(new Date()); drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? str2.toLowerCase() : str2, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str2.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str2)) - 2, 2 + i++ * 10, this.getColor(this.counter)); ++this.counter; } if (this.tps.getValue()) { final String str2 = grayString + "\u670d\u52a1\u5668\u7a33\u5b9a\u6027 §f" + HexTech.SERVER.getTPS(); drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? str2.toLowerCase() : str2, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str2.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str2)) - 2, 2 + i++ * 10, this.getColor(this.counter)); ++this.counter; } final String fpsText = grayString + "\u5e27\u6570 §f" + HexTech.FPS.getFps(); final String str3 = grayString + "\u5ef6\u8fdf §f" + HexTech.SERVER.getPing(); if (HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str3) > HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(fpsText)) { if (this.ping.getValue()) { drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? str3.toLowerCase() : str3, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str3.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str3)) - 2, 2 + i++ * 10, this.getColor(this.counter)); ++this.counter; } if (this.fps.getValue()) { drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? fpsText.toLowerCase() : fpsText, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(fpsText.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(fpsText)) - 2, 2 + i++ * 10, this.getColor(this.counter)); } } else { if (this.fps.getValue()) { drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? fpsText.toLowerCase() : fpsText, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(fpsText.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(fpsText)) - 2, 2 + i++ * 10, this.getColor(this.counter)); ++this.counter; } if (this.ping.getValue()) { drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, this.lowerCase.getValue() ? str3.toLowerCase() : str3, width - (this.lowerCase.getValue() ? HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str3.toLowerCase()) : HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(str3)) - 2, 2 + i++ * 10, this.getColor(this.counter)); } } } final boolean inHell = HUD_ssNtBhEveKlCmIccBvAN.mc.world.getRegistryKey().equals(World.NETHER); final int posX = (int) HUD_ssNtBhEveKlCmIccBvAN.mc.player.getX(); final int posY = (int) HUD_ssNtBhEveKlCmIccBvAN.mc.player.getY(); final int posZ = (int) HUD_ssNtBhEveKlCmIccBvAN.mc.player.getZ(); final float nether = inHell ? 8.0f : 0.125f; final int hposX = (int) (HUD_ssNtBhEveKlCmIccBvAN.mc.player.getX() * nether); final int hposZ = (int) (HUD_ssNtBhEveKlCmIccBvAN.mc.player.getZ() * nether); final int yawPitch = (int) MathHelper.wrapDegrees(HUD_ssNtBhEveKlCmIccBvAN.mc.player.getYaw()); final int p = this.coords.getValue() ? 0 : 11; i = ((HUD_ssNtBhEveKlCmIccBvAN.mc.currentScreen instanceof ChatScreen) ? 14 : 0); String coordinates = (this.lowerCase.getValue() ? "XYZ: ".toLowerCase() : "XYZ: ") + "§f" + (inHell ? (posX + ", " + posY + ", " + posZ + " §7[§f" + hposX + ", " + hposZ + "§7]§f") : (posX + ", " + posY + ", " + posZ + "§7 [§f" + hposX + ", " + hposZ + "§7]")); final String yaw = this.direction.getValue() ? ((this.lowerCase.getValue() ? "Yaw: ".toLowerCase() : "Yaw: ") + "§f" + yawPitch) : ""; final String coords = this.coords.getValue() ? coordinates : ""; i += 10; ++this.counter; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, yaw, 2, height - i - 22 + p, this.getColor(this.counter)); ++this.counter; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, coords, 2, height - i, this.getColor(this.counter)); ++this.counter; if (this.greeter.getValue()) { this.drawWelcomer(drawContext); } if (this.lag.getValue()) { this.drawLagOMeter(drawContext); } } private void drawWelcomer(DrawContext drawContext) { Object text; int width = mc.getWindow().getScaledWidth(); String nameColor = this.greeterNameColor.getValue() ? String.valueOf(Formatting.WHITE) : ""; Object object = text = this.lowerCase.getValue() ? "Welcome, ".toLowerCase() : "Welcome, "; if (this.greeterMode.getValue() == GreeterMod.PLAYER) { if (this.greeter.getValue()) { text = text + nameColor + mc.getSession().getUsername(); } drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, text + "\u00a70 :')", (int) ((float) width / 2.0f - (float) HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth((String) text) / 2.0f + 2.0f), 2, this.getColor(this.counter)); ++this.counter; } else { String lel = this.greeterText.getValue(); if (this.greeter.getValue()) { lel = this.greeterText.getValue(); } drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, lel, (int) ((float) width / 2.0f - (float) HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(lel) / 2.0f + 2.0f), 2, this.getColor(this.counter)); ++this.counter; } } private void drawpvphud(DrawContext drawContext, int yOffset) { double x = (double) mc.getWindow().getWidth() / 4.0; double y = (double) mc.getWindow().getHeight() / 4.0 + (double) yOffset; Objects.requireNonNull(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer); int textHeight = 9 + 1; String t1 = "Totem " + Formatting.YELLOW + InventoryUtil.getItemCount(Items.TOTEM_OF_UNDYING); String t2 = "Potion " + Formatting.GRAY + InventoryUtil.getPotCount(StatusEffects.RESISTANCE); String t3 = "Crystal " + Formatting.WHITE + InventoryUtil.getItemCount(Items.END_CRYSTAL); String A1 = "\u00a74[\u64cd\u63a7\u529b] | \u00a78\u538b\u5236"; String D1 = "\u00a73[\u538b\u5236] | \u00a78\u64cd\u63a7\u529b"; String t4 = "\u9759\u6001\u540c\u6b65"; ArrayList<StatusEffectInstance> effects = new ArrayList(HUD_ssNtBhEveKlCmIccBvAN.mc.player.getStatusEffects()); if (this.totemtext.getValue()) { drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, t1, (int) (x - (double) (HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(t1) / 2)), (int) y, this.getColor(this.counter)); ++this.counter; y += textHeight; } if (this.potiontext.getValue()) { drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, t2, (int) (x - (double) (HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(t2) / 2)), (int) y, this.getColor(this.counter)); ++this.counter; y += textHeight; } if (this.crtstalText.getValue()) { drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, t3, (int) (x - (double) (HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(t3) / 2)), (int) y, this.getColor(this.counter)); ++this.counter; y += textHeight; } if (this.attacktext.getValue()) { if (ComboBreaks.INSTANCE.isOn()) { drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, A1, (int) (x - (double) (HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(A1) / 2)), (int) y, this.getColorComboA(this.counter)); } if (ComboBreaks.INSTANCE.isOff()) { drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, D1, (int) (x - (double) (HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(D1) / 2)), (int) y, this.getColorComboD(this.counter)); } ++this.counter; y += textHeight; } for (StatusEffectInstance potionEffect : effects) { if (potionEffect.getEffectType() != StatusEffects.RESISTANCE || potionEffect.getAmplifier() + 1 <= 1) continue; String str = this.getColoredPotionTimeString(potionEffect); String t31 = "PotionTime " + Formatting.WHITE + str; if (!this.potiontext.getValue()) continue; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, t31, (int) (x - (double) (HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(t31) / 2)), (int) y, this.getColor(this.counter)); ++this.counter; y += textHeight; } } private void drawLagOMeter(DrawContext drawContext) { int width = mc.getWindow().getScaledWidth(); if (HexTech.SERVER.isServerNotResponding()) { String text = "\u00a74" + (this.lowerCase.getValue() ? "Server is lagging for ".toLowerCase() : "Server is lagging for ") + MathUtil.round((float) HexTech.SERVER.serverRespondingTime() / 1000.0f, 1) + "s."; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, text, (int) ((float) width / 2.0f - (float) HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer.getWidth(text) / 2.0f + 2.0f), 20, this.getColor(this.counter)); ++this.counter; } } private void drawTextRadar(DrawContext drawContext, int yOffset) { if (!this.players.isEmpty()) { Objects.requireNonNull(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer); int y = 9 + 7 + yOffset; for (Map.Entry<String, Integer> player : this.players.entrySet()) { String text = player.getKey() + " "; Objects.requireNonNull(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer); int textHeight = 9 + 1; drawContext.drawTextWithShadow(HUD_ssNtBhEveKlCmIccBvAN.mc.textRenderer, text, 2, y, this.getColor(this.counter)); ++this.counter; y += textHeight; } } } private Map<String, Integer> getTextRadarMap() { Map<String, Integer> retval = new HashMap<String, Integer>(); DecimalFormat dfDistance = new DecimalFormat("#.#"); dfDistance.setRoundingMode(RoundingMode.CEILING); StringBuilder distanceSB = new StringBuilder(); for (PlayerEntity player : HUD_ssNtBhEveKlCmIccBvAN.mc.world.getPlayers()) { if (player.isInvisible() || player.getName().equals(HUD_ssNtBhEveKlCmIccBvAN.mc.player.getName())) continue; int distanceInt = (int) HUD_ssNtBhEveKlCmIccBvAN.mc.player.distanceTo(player); String distance = dfDistance.format(distanceInt); if (distanceInt >= 25) { distanceSB.append(Formatting.GREEN); } else if (distanceInt > 10) { distanceSB.append(Formatting.YELLOW); } else { distanceSB.append(Formatting.RED); } distanceSB.append(distance); retval.put((this.health.getValue() ? String.valueOf(this.getHealthColor(player)) + HUD_ssNtBhEveKlCmIccBvAN.round2(player.getAbsorptionAmount() + player.getHealth()) + " " : "") + (HexTech.FRIEND.isFriend(player) ? Formatting.AQUA : Formatting.RESET) + player.getName().getString() + " " + Formatting.WHITE + "[" + Formatting.RESET + distanceSB + "m" + Formatting.WHITE + "] " + Formatting.GREEN, (int) HUD_ssNtBhEveKlCmIccBvAN.mc.player.distanceTo(player)); distanceSB.setLength(0); } if (!retval.isEmpty()) { retval = MathUtil.sortByValue(retval, false); } return retval; } private Formatting getHealthColor(@NotNull PlayerEntity entity) { int health = (int) ((float) ((int) entity.getHealth()) + entity.getAbsorptionAmount()); if (health <= 15 && health > 7) { return Formatting.YELLOW; } if (health > 15) { return Formatting.GREEN; } return Formatting.RED; } private String getColoredPotionString(StatusEffectInstance effect) { StatusEffect potion = effect.getEffectType(); return potion.getName().getString() + " " + (effect.getAmplifier() + 1) + " \u00a7f" + StatusEffectUtil.getDurationText(effect, 1.0f, HUD_ssNtBhEveKlCmIccBvAN.mc.world.getTickManager().getTickRate()).getString(); } private String getColoredPotionTimeString(StatusEffectInstance effect) { return StatusEffectUtil.getDurationText(effect, 1.0f, HUD_ssNtBhEveKlCmIccBvAN.mc.world.getTickManager().getTickRate()).getString(); } private int getColor(int counter) { if (this.colorMode.getValue() != ColorMode.Custom) { return this.rainbow(counter).getRGB(); } if (this.sync.getValue()) { return ClickGui_ABoiivByuLsVqarYqfYv.INSTANCE.color.getValue().getRGB(); } return this.color.getValue().getRGB(); } private int getColorComboA(int counter) { if (this.colorMode.getValue() != ColorMode.Custom) { return this.rainbow(counter).getRGB(); } return this.Acolor.getValue().getRGB(); } private int getColorComboD(int counter) { if (this.colorMode.getValue() != ColorMode.Custom) { return this.rainbow(counter).getRGB(); } return this.Dcolor.getValue().getRGB(); } private Color rainbow(int delay) { double rainbowState = Math.ceil(((double) this.progress + (double) delay * this.rainbowDelay.getValue()) / 20.0); if (this.colorMode.getValue() == ColorMode.Pulse) { if (this.sync.getValue()) { return this.pulseColor(ClickGui_ABoiivByuLsVqarYqfYv.INSTANCE.color.getValue(), delay); } return this.pulseColor(this.color.getValue(), delay); } if (this.colorMode.getValue() == ColorMode.Rainbow) { return Color.getHSBColor((float) (rainbowState % 360.0 / 360.0), this.saturation.getValueFloat() / 255.0f, 1.0f); } return this.pulseColor(Color.getHSBColor((float) (rainbowState % 360.0 / 360.0), this.saturation.getValueFloat() / 255.0f, 1.0f), delay); } private Color pulseColor(Color color, int index) { float[] hsb = new float[3]; Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), hsb); float brightness = Math.abs(((float) ((long) this.pulseProgress % 2000L) / Float.intBitsToFloat(Float.floatToIntBits(0.0013786979f) ^ 0x7ECEB56D) + (float) index / 14.0f * Float.intBitsToFloat(Float.floatToIntBits(0.09192204f) ^ 0x7DBC419F)) % Float.intBitsToFloat(Float.floatToIntBits(0.7858098f) ^ 0x7F492AD5) - Float.intBitsToFloat(Float.floatToIntBits(6.46708f) ^ 0x7F4EF252)); brightness = Float.intBitsToFloat(Float.floatToIntBits(18.996923f) ^ 0x7E97F9B3) + Float.intBitsToFloat(Float.floatToIntBits(2.7958195f) ^ 0x7F32EEB5) * brightness; hsb[2] = brightness % Float.intBitsToFloat(Float.floatToIntBits(0.8992331f) ^ 0x7F663424); return ColorUtil.injectAlpha(new Color(Color.HSBtoRGB(hsb[0], hsb[1], hsb[2])), color.getAlpha()); } /* * Exception performing whole class analysis ignored. */ public enum GreeterMod { PLAYER, CUSTOM } /* * Exception performing whole class analysis ignored. */ public enum ColorMode { Custom, Pulse, Rainbow, PulseRainbow } /* * Exception performing whole class analysis ignored. */ public enum Page { ELEMENTS, GLOBAL, Color, Dev } }
0
0.952226
1
0.952226
game-dev
MEDIA
0.746422
game-dev
0.971074
1
0.971074
manuelbua/uracer-kotd
2,659
uracer-desktop/src/com/bitfire/uracer/game/logic/helpers/PlayerGameTasks.java
package com.bitfire.uracer.game.logic.helpers; import com.bitfire.uracer.URacer; import com.bitfire.uracer.configuration.UserProfile; import com.bitfire.uracer.game.logic.gametasks.GameTasksManager; import com.bitfire.uracer.game.logic.gametasks.hud.elements.HudLapInfo; import com.bitfire.uracer.game.logic.gametasks.hud.elements.HudPlayer; import com.bitfire.uracer.game.logic.gametasks.hud.elements.HudPlayerStatic; import com.bitfire.uracer.game.logic.gametasks.sounds.effects.PlayerDriftSoundEffect; import com.bitfire.uracer.game.logic.gametasks.sounds.effects.PlayerEngineSoundEffect; import com.bitfire.uracer.game.logic.gametasks.sounds.effects.PlayerImpactSoundEffect; import com.bitfire.uracer.game.logic.gametasks.sounds.effects.PlayerTensiveMusic; import com.bitfire.uracer.game.logic.gametasks.trackeffects.effects.PlayerSkidMarks; import com.bitfire.uracer.game.logic.gametasks.trackeffects.effects.PlayerSmokeTrails; import com.bitfire.uracer.game.logic.replaying.LapManager; /** Manages the creation and destruction of the player-bound game tasks. */ public final class PlayerGameTasks { private final UserProfile userProfile; private final GameTasksManager manager; /** keeps track of the concrete player tasks (note that they are all publicly accessible for performance reasons) */ public HudPlayer hudPlayer = null; public HudPlayerStatic hudPlayerStatic = null; public HudLapInfo hudLapInfo = null; public PlayerGameTasks (UserProfile userProfile, GameTasksManager gameTaskManager) { this.userProfile = userProfile; manager = gameTaskManager; } public void dispose () { destroyTasks(); } public void createTasks (LapManager lapManager, TrackProgressData progressData) { // sounds manager.sound.add(new PlayerDriftSoundEffect()); manager.sound.add(new PlayerImpactSoundEffect()); manager.sound.add(new PlayerEngineSoundEffect(progressData)); manager.sound.add(new PlayerTensiveMusic(progressData)); // track effects int maxSkidMarks = URacer.Game.isDesktop() ? 150 : 100; float maxLife = URacer.Game.isDesktop() ? 5 : 3; manager.effects.addBeforeCars(new PlayerSkidMarks(maxSkidMarks, maxLife)); manager.effects.addAfterCars(new PlayerSmokeTrails()); // hud hudPlayer = new HudPlayer(userProfile); hudPlayerStatic = new HudPlayerStatic(userProfile); hudLapInfo = new HudLapInfo(lapManager); manager.hud.addBeforePostProcessing(hudPlayer); manager.hud.addAfterPostProcessing(hudLapInfo); manager.hud.addAfterPostProcessing(hudPlayerStatic); } public void destroyTasks () { manager.sound.disposeTasks(); manager.effects.disposeTasks(); manager.hud.disposeTasks(); } }
0
0.551654
1
0.551654
game-dev
MEDIA
0.660745
game-dev
0.901685
1
0.901685
retroroyale/ClashRoyale
2,966
src/ClashRoyale/Database/Cache/DuoBattles.cs
using System.Collections.Generic; using System.Linq; using ClashRoyale.Logic; using ClashRoyale.Logic.Battle; using ClashRoyale.Protocol.Messages.Server; namespace ClashRoyale.Database.Cache { public class DuoBattles : Dictionary<long, LogicBattle> { private readonly List<Player> _duoPlayerQueue = new List<Player>(); private long _seed = 1; /// <summary> /// Get 3 players from the duo queue and remove them /// </summary> public List<Player> Dequeue { get { lock (_duoPlayerQueue) { if (_duoPlayerQueue.Count < 3) return null; var players = new List<Player>(); for (var i = 0; i < 3; i++) { var player = _duoPlayerQueue[0]; _duoPlayerQueue.RemoveAt(0); players.Add(player); } return players; } } } /// <summary> /// Adds a player to the queue and sends the estimated time /// </summary> /// <param name="player"></param> public async void Enqueue(Player player) { var players = Resources.Players; var playerCount = players.Count; lock (_duoPlayerQueue) { if (_duoPlayerQueue.Contains(player)) return; _duoPlayerQueue.Add(player); } // TODO SEND INFO TO PLAYERS IN QUEUE if (playerCount > 100) return; // Notify other players foreach (var p in players.Values.ToList()) if (p.Device.IsConnected && p.Home.Id != player.Home.Id) await new PvpMatchmakeNotificationMessage(p.Device).SendAsync(); } /// <summary> /// Remove a player from queue and returns true wether he has been removed /// </summary> /// <param name="player"></param> /// <returns></returns> public bool Cancel(Player player) { lock (_duoPlayerQueue) { if (!_duoPlayerQueue.Contains(player)) return false; _duoPlayerQueue.Remove(player); return true; } } /// <summary> /// Adds a battle to the list /// </summary> /// <param name="battle"></param> public void Add(LogicBattle battle) { battle.BattleId = _seed++; if (!ContainsKey(battle.BattleId)) Add(battle.BattleId, battle); } /// <summary> /// Remove a battle with the id /// </summary> /// <param name="id"></param> public new void Remove(long id) { if (ContainsKey(id)) base.Remove(id); } } }
0
0.661345
1
0.661345
game-dev
MEDIA
0.542584
game-dev
0.854682
1
0.854682
mangosthree/server
25,429
src/game/WorldHandlers/QuestHandler.cpp
/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2025 MaNGOS <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 * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ #include "Common.h" #include "Log.h" #include "WorldPacket.h" #include "WorldSession.h" #include "Opcodes.h" #include "World.h" #include "ObjectMgr.h" #include "Player.h" #include "GossipDef.h" #include "QuestDef.h" #include "ObjectAccessor.h" #include "ScriptMgr.h" #include "Group.h" #ifdef ENABLE_ELUNA #include "LuaEngine.h" #endif /* ENABLE_ELUNA */ void WorldSession::HandleQuestgiverStatusQueryOpcode(WorldPacket& recv_data) { ObjectGuid guid; recv_data >> guid; uint32 dialogStatus = DIALOG_STATUS_NONE; Object* questgiver = _player->GetObjectByTypeMask(guid, TYPEMASK_CREATURE_OR_GAMEOBJECT); if (!questgiver) { DETAIL_LOG("Error in CMSG_QUESTGIVER_STATUS_QUERY, called for not found questgiver %s", guid.GetString().c_str()); return; } DEBUG_LOG("WORLD: Received opcode CMSG_QUESTGIVER_STATUS_QUERY - for %s to %s", _player->GetGuidStr().c_str(), guid.GetString().c_str()); switch (questgiver->GetTypeId()) { case TYPEID_UNIT: { Creature* cr_questgiver = (Creature*)questgiver; if (!cr_questgiver->IsHostileTo(_player)) // not show quest status to enemies { dialogStatus = sScriptMgr.GetDialogStatus(_player, cr_questgiver); if (dialogStatus > DIALOG_STATUS_REWARD_REP) { dialogStatus = getDialogStatus(_player, cr_questgiver, DIALOG_STATUS_NONE); } } break; } case TYPEID_GAMEOBJECT: { GameObject* go_questgiver = (GameObject*)questgiver; dialogStatus = sScriptMgr.GetDialogStatus(_player, go_questgiver); if (dialogStatus > DIALOG_STATUS_REWARD_REP) { dialogStatus = getDialogStatus(_player, go_questgiver, DIALOG_STATUS_NONE); } break; } default: sLog.outError("QuestGiver called for unexpected type %u", questgiver->GetTypeId()); break; } // inform client about status of quest _player->PlayerTalkClass->SendQuestGiverStatus(dialogStatus, guid); } void WorldSession::HandleQuestgiverHelloOpcode(WorldPacket& recv_data) { ObjectGuid guid; recv_data >> guid; DEBUG_LOG("WORLD: Received opcode CMSG_QUESTGIVER_HELLO - for %s to %s", _player->GetGuidStr().c_str(), guid.GetString().c_str()); Creature* pCreature = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_NONE); if (!pCreature) { DEBUG_LOG("WORLD: HandleQuestgiverHelloOpcode - for %s to %s not found or you can't interact with him.", _player->GetGuidStr().c_str(), guid.GetString().c_str()); return; } // Stop the npc if moving pCreature->StopMoving(); if (sScriptMgr.OnGossipHello(_player, pCreature)) { return; } _player->PrepareGossipMenu(pCreature, pCreature->GetCreatureInfo()->GossipMenuId); _player->SendPreparedGossip(pCreature); } void WorldSession::HandleQuestgiverAcceptQuestOpcode(WorldPacket& recv_data) { ObjectGuid guid; uint32 quest; uint32 unk1; recv_data >> guid >> quest >> unk1; if (!CanInteractWithQuestGiver(guid, "CMSG_QUESTGIVER_ACCEPT_QUEST")) { return; } DEBUG_LOG("WORLD: Received opcode CMSG_QUESTGIVER_ACCEPT_QUEST - for %s to %s, quest = %u, unk1 = %u", _player->GetGuidStr().c_str(), guid.GetString().c_str(), quest, unk1); Object* pObject = _player->GetObjectByTypeMask(guid, TYPEMASK_CREATURE_GAMEOBJECT_PLAYER_OR_ITEM); // no or incorrect quest giver (player himself is questgiver for SPELL_EFFECT_QUEST_OFFER) if (!pObject || (pObject->GetTypeId() != TYPEID_PLAYER && !pObject->HasQuest(quest)) || (pObject->GetTypeId() == TYPEID_PLAYER && pObject != _player && !((Player*)pObject)->CanShareQuest(quest)) ) { _player->PlayerTalkClass->CloseGossip(); _player->ClearDividerGuid(); return; } Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest); if (qInfo) { // prevent cheating if (!GetPlayer()->CanTakeQuest(qInfo, true)) { _player->PlayerTalkClass->CloseGossip(); _player->ClearDividerGuid(); return; } if (Player* pPlayer = sObjectAccessor.FindPlayer(_player->GetDividerGuid())) { pPlayer->SendPushToPartyResponse(_player, QUEST_PARTY_MSG_ACCEPT_QUEST); _player->ClearDividerGuid(); } if (_player->CanAddQuest(qInfo, true)) { _player->AddQuest(qInfo, pObject); // pObject (if it item) can be destroyed at call if (qInfo->HasQuestFlag(QUEST_FLAGS_PARTY_ACCEPT)) { if (Group* pGroup = _player->GetGroup()) { for (GroupReference* itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* pPlayer = itr->getSource(); if (!pPlayer || pPlayer == _player) // not self { continue; } if (pPlayer->CanTakeQuest(qInfo, true)) { pPlayer->SetDividerGuid(_player->GetObjectGuid()); // need confirmation that any gossip window will close pPlayer->PlayerTalkClass->CloseGossip(); _player->SendQuestConfirmAccept(qInfo, pPlayer); } } } } if (_player->CanCompleteQuest(quest)) { _player->CompleteQuest(quest); } _player->GetAchievementMgr().StartTimedAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, quest); _player->PlayerTalkClass->CloseGossip(); if (qInfo->GetSrcSpell() > 0) { _player->CastSpell(_player, qInfo->GetSrcSpell(), true); } return; } } _player->PlayerTalkClass->CloseGossip(); } void WorldSession::HandleQuestgiverQueryQuestOpcode(WorldPacket& recv_data) { ObjectGuid guid; uint32 quest; uint8 unk1; recv_data >> guid >> quest >> unk1; DEBUG_LOG("WORLD: Received opcode CMSG_QUESTGIVER_QUERY_QUEST - for %s to %s, quest = %u, unk1 = %u", _player->GetGuidStr().c_str(), guid.GetString().c_str(), quest, unk1); // Verify that the guid is valid and is a questgiver or involved in the requested quest Object* pObject = _player->GetObjectByTypeMask(guid, TYPEMASK_CREATURE_GAMEOBJECT_OR_ITEM); if (!pObject || (!pObject->HasQuest(quest) && !pObject->HasInvolvedQuest(quest))) { _player->PlayerTalkClass->CloseGossip(); return; } if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest)) { _player->PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, pObject->GetObjectGuid(), true); } } void WorldSession::HandleQuestQueryOpcode(WorldPacket& recv_data) { uint32 quest; recv_data >> quest; DEBUG_LOG("WORLD: Received opcode CMSG_QUEST_QUERY quest = %u", quest); Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest); if (pQuest) { _player->PlayerTalkClass->SendQuestQueryResponse(pQuest); } } void WorldSession::HandleQuestgiverChooseRewardOpcode(WorldPacket& recv_data) { uint32 quest, reward; ObjectGuid guid; recv_data >> guid >> quest >> reward; if (reward >= QUEST_REWARD_CHOICES_COUNT) { sLog.outError("Error in CMSG_QUESTGIVER_CHOOSE_REWARD - %s tried to get invalid reward (%u) (probably packet hacking)", _player->GetGuidStr().c_str(), reward); return; } if (!CanInteractWithQuestGiver(guid, "CMSG_QUESTGIVER_CHOOSE_REWARD")) { return; } DEBUG_LOG("WORLD: Received opcode CMSG_QUESTGIVER_CHOOSE_REWARD - for %s to %s, quest = %u, reward = %u", _player->GetGuidStr().c_str(), guid.GetString().c_str(), quest, reward); Object* pObject = _player->GetObjectByTypeMask(guid, TYPEMASK_CREATURE_OR_GAMEOBJECT); if (!pObject) { return; } if (!pObject->HasInvolvedQuest(quest)) { return; } Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest); if (pQuest) { if (_player->CanRewardQuest(pQuest, reward, true)) { _player->RewardQuest(pQuest, reward, pObject, false); // Send next quest if (Quest const* nextquest = _player->GetNextQuest(guid, pQuest)) { _player->PlayerTalkClass->SendQuestGiverQuestDetails(nextquest, guid, true); } } else { _player->PlayerTalkClass->SendQuestGiverOfferReward(pQuest, guid, true); } } } void WorldSession::HandleQuestgiverRequestRewardOpcode(WorldPacket& recv_data) { uint32 quest; ObjectGuid guid; recv_data >> guid >> quest; if (!CanInteractWithQuestGiver(guid, "CMSG_QUESTGIVER_REQUEST_REWARD")) { return; } DEBUG_LOG("WORLD: Received opcode CMSG_QUESTGIVER_REQUEST_REWARD - for %s to %s, quest = %u", _player->GetGuidStr().c_str(), guid.GetString().c_str(), quest); Object* pObject = _player->GetObjectByTypeMask(guid, TYPEMASK_CREATURE_OR_GAMEOBJECT); if (!pObject || !pObject->HasInvolvedQuest(quest)) { return; } if (_player->CanCompleteQuest(quest)) { _player->CompleteQuest(quest); } if (_player->GetQuestStatus(quest) != QUEST_STATUS_COMPLETE) { return; } if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest)) { _player->PlayerTalkClass->SendQuestGiverOfferReward(pQuest, guid, true); } } void WorldSession::HandleQuestgiverCancel(WorldPacket& /*recv_data*/) { DEBUG_LOG("WORLD: Received opcode CMSG_QUESTGIVER_CANCEL"); _player->PlayerTalkClass->CloseGossip(); } void WorldSession::HandleQuestLogSwapQuest(WorldPacket& recv_data) { uint8 slot1, slot2; recv_data >> slot1 >> slot2; if (slot1 == slot2 || slot1 >= MAX_QUEST_LOG_SIZE || slot2 >= MAX_QUEST_LOG_SIZE) { return; } DEBUG_LOG("WORLD: Received opcode CMSG_QUESTLOG_SWAP_QUEST slot 1 = %u, slot 2 = %u", slot1, slot2); GetPlayer()->SwapQuestSlot(slot1, slot2); } void WorldSession::HandleQuestLogRemoveQuest(WorldPacket& recv_data) { uint8 slot; recv_data >> slot; DEBUG_LOG("WORLD: Received opcode CMSG_QUESTLOG_REMOVE_QUEST slot = %u", slot); if (slot < MAX_QUEST_LOG_SIZE) { if (uint32 quest = _player->GetQuestSlotQuestId(slot)) { if (!_player->TakeQuestSourceItem(quest, true)) { return; // can't un-equip some items, reject quest cancel } if (const Quest* pQuest = sObjectMgr.GetQuestTemplate(quest)) { if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED)) { _player->RemoveTimedQuest(quest); } for (int i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i) { if (pQuest->ReqSourceId[i]) { ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(pQuest->ReqSourceId[i]); if (iProto && iProto->Bonding == BIND_QUEST_ITEM) { _player->DestroyItemCount(pQuest->ReqSourceId[i], pQuest->ReqSourceCount[i], true, false, true); } } } } _player->SetQuestStatus(quest, QUEST_STATUS_NONE); if (sWorld.getConfig(CONFIG_BOOL_ENABLE_QUEST_TRACKER)) // check if Quest Tracker is enabled { DEBUG_LOG("QUEST TRACKER: Quest Abandoned."); static SqlStatementID CHAR_UPD_QUEST_TRACK_ABANDON_TIME; // prepare Quest Tracker datas SqlStatement stmt = CharacterDatabase.CreateStatement(CHAR_UPD_QUEST_TRACK_ABANDON_TIME, "UPDATE `quest_tracker` SET `quest_abandon_time` = NOW() WHERE `id` = ? AND `character_guid` = ? ORDER BY `quest_accept_time` DESC LIMIT 1"); stmt.addUInt32(quest); stmt.addUInt32(_player->GetGUIDLow()); // add to Quest Tracker stmt.Execute(); } // Used by Eluna #ifdef ENABLE_ELUNA if (Eluna* e = _player->GetEluna()) { e->OnQuestAbandon(_player, quest); } #endif /* ENABLE_ELUNA */ } _player->SetQuestSlot(slot, 0); _player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED, 1); } } void WorldSession::HandleQuestConfirmAccept(WorldPacket& recv_data) { uint32 quest; recv_data >> quest; DEBUG_LOG("WORLD: Received opcode CMSG_QUEST_CONFIRM_ACCEPT quest = %u", quest); if (const Quest* pQuest = sObjectMgr.GetQuestTemplate(quest)) { if (!pQuest->HasQuestFlag(QUEST_FLAGS_PARTY_ACCEPT)) { return; } Player* pOriginalPlayer = sObjectAccessor.FindPlayer(_player->GetDividerGuid()); if (!pOriginalPlayer) { return; } if (pQuest->IsAllowedInRaid()) { if (!_player->IsInSameRaidWith(pOriginalPlayer)) { return; } } else { if (!_player->IsInSameGroupWith(pOriginalPlayer)) { return; } } if (_player->CanAddQuest(pQuest, true)) { _player->AddQuest(pQuest, NULL); // NULL, this prevent DB script from duplicate running } _player->ClearDividerGuid(); } } void WorldSession::HandleQuestgiverCompleteQuest(WorldPacket& recv_data) { uint32 quest; ObjectGuid guid; uint8 unk; recv_data >> guid >> quest >> unk; if (!CanInteractWithQuestGiver(guid, "CMSG_QUESTGIVER_COMPLETE_QUEST")) { return; } // All ok, continue DEBUG_LOG("WORLD: Received opcode CMSG_QUESTGIVER_COMPLETE_QUEST - for %s to %s, quest = %u, unk = %u", _player->GetGuidStr().c_str(), guid.GetString().c_str(), quest, unk); if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest)) { if (_player->GetQuestStatus(quest) != QUEST_STATUS_COMPLETE) { if (pQuest->IsRepeatable()) { _player->PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, _player->CanCompleteRepeatableQuest(pQuest), false); } else { _player->PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, _player->CanRewardQuest(pQuest, false), false); } } else { if (pQuest->GetReqItemsCount() || pQuest->GetReqCurrencyCount()) // some items or currency required { _player->PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, _player->CanRewardQuest(pQuest, false), false); } else // no items required { _player->PlayerTalkClass->SendQuestGiverOfferReward(pQuest, guid, true); } } } } void WorldSession::HandleQuestgiverQuestAutoLaunch(WorldPacket& /*recvPacket*/) { DEBUG_LOG("WORLD: Received opcode CMSG_QUESTGIVER_QUEST_AUTOLAUNCH"); } void WorldSession::HandlePushQuestToParty(WorldPacket& recvPacket) { uint32 questId; recvPacket >> questId; DEBUG_LOG("WORLD: Received opcode CMSG_PUSHQUESTTOPARTY quest = %u", questId); if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(questId)) { if (Group* pGroup = _player->GetGroup()) { for (GroupReference* itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* pPlayer = itr->getSource(); if (!pPlayer || pPlayer == _player) // skip self { continue; } _player->SendPushToPartyResponse(pPlayer, QUEST_PARTY_MSG_SHARING_QUEST); if (!pPlayer->SatisfyQuestStatus(pQuest, false)) { _player->SendPushToPartyResponse(pPlayer, QUEST_PARTY_MSG_HAVE_QUEST); continue; } if (pPlayer->GetQuestStatus(questId) == QUEST_STATUS_COMPLETE) { _player->SendPushToPartyResponse(pPlayer, QUEST_PARTY_MSG_FINISH_QUEST); continue; } if (!pPlayer->CanTakeQuest(pQuest, false)) { _player->SendPushToPartyResponse(pPlayer, QUEST_PARTY_MSG_CANT_TAKE_QUEST); continue; } if (!pPlayer->SatisfyQuestLog(false)) { _player->SendPushToPartyResponse(pPlayer, QUEST_PARTY_MSG_LOG_FULL); continue; } if (pPlayer->GetDividerGuid()) { _player->SendPushToPartyResponse(pPlayer, QUEST_PARTY_MSG_BUSY); continue; } pPlayer->PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, _player->GetObjectGuid(), true); pPlayer->SetDividerGuid(_player->GetObjectGuid()); } } } } void WorldSession::HandleQuestPushResult(WorldPacket& recvPacket) { ObjectGuid guid; uint32 quest; uint8 msg; recvPacket >> guid >> quest >> msg; DEBUG_LOG("WORLD: Received opcode MSG_QUEST_PUSH_RESULT"); if (Player* pPlayer = sObjectAccessor.FindPlayer(_player->GetDividerGuid())) { WorldPacket data(MSG_QUEST_PUSH_RESULT, (8 + 1)); data << ObjectGuid(guid); data << uint8(msg); // valid values: 0-8 pPlayer->GetSession()->SendPacket(&data); _player->ClearDividerGuid(); } } /** * What - if any - kind of exclamation mark or question-mark should a quest-giver display for a player * @param pPlayer - for whom * @param questgiver - from whom * @param defstatus - initial set status (usually it will be called with DIALOG_STATUS_NONE) - must not be DIALOG_STATUS_UNDEFINED */ uint32 WorldSession::getDialogStatus(Player* pPlayer, Object* questgiver, uint32 defstatus) { MANGOS_ASSERT(defstatus != DIALOG_STATUS_UNDEFINED); uint32 dialogStatus = defstatus; QuestRelationsMapBounds rbounds; // QuestRelations (quest-giver) QuestRelationsMapBounds irbounds; // InvolvedRelations (quest-finisher) switch (questgiver->GetTypeId()) { case TYPEID_UNIT: { rbounds = sObjectMgr.GetCreatureQuestRelationsMapBounds(questgiver->GetEntry()); irbounds = sObjectMgr.GetCreatureQuestInvolvedRelationsMapBounds(questgiver->GetEntry()); break; } case TYPEID_GAMEOBJECT: { rbounds = sObjectMgr.GetGOQuestRelationsMapBounds(questgiver->GetEntry()); irbounds = sObjectMgr.GetGOQuestInvolvedRelationsMapBounds(questgiver->GetEntry()); break; } default: // it's impossible, but check ^) sLog.outError("Warning: GetDialogStatus called for unexpected type %u", questgiver->GetTypeId()); return DIALOG_STATUS_NONE; } // Check markings for quest-finisher for (QuestRelationsMap::const_iterator itr = irbounds.first; itr != irbounds.second; ++itr) { uint32 dialogStatusNew = DIALOG_STATUS_NONE; uint32 quest_id = itr->second; Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest || !pQuest->IsActive()) { continue; } QuestStatus status = pPlayer->GetQuestStatus(quest_id); if (status == QUEST_STATUS_COMPLETE && !pPlayer->GetQuestRewardStatus(quest_id)) { dialogStatusNew = pQuest->IsRepeatable() ? DIALOG_STATUS_REWARD_REP : DIALOG_STATUS_REWARD; } else if (pQuest->IsAutoComplete() && pPlayer->CanTakeQuest(pQuest, false)) { dialogStatusNew = pQuest->IsRepeatable() ? DIALOG_STATUS_AVAILABLE_REP : DIALOG_STATUS_AVAILABLE; } else if (status == QUEST_STATUS_INCOMPLETE) { dialogStatusNew = DIALOG_STATUS_INCOMPLETE; } if (dialogStatusNew > dialogStatus) { dialogStatus = dialogStatusNew; } } // check markings for quest-giver for (QuestRelationsMap::const_iterator itr = rbounds.first; itr != rbounds.second; ++itr) { uint32 dialogStatusNew = DIALOG_STATUS_NONE; uint32 quest_id = itr->second; Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest || !pQuest->IsActive()) { continue; } QuestStatus status = pPlayer->GetQuestStatus(quest_id); if (status == QUEST_STATUS_NONE) // For all other cases the mark is handled either at some place else, or with involved-relations already { if (pPlayer->CanSeeStartQuest(pQuest)) { if (pPlayer->SatisfyQuestLevel(pQuest, false)) { int32 lowLevelDiff = sWorld.getConfig(CONFIG_INT32_QUEST_LOW_LEVEL_HIDE_DIFF); if (pQuest->IsAutoComplete() || (pQuest->IsRepeatable() && pPlayer->getQuestStatusMap()[quest_id].m_rewarded)) { dialogStatusNew = DIALOG_STATUS_REWARD_REP; } else if (lowLevelDiff < 0 || pPlayer->getLevel() <= pPlayer->GetQuestLevelForPlayer(pQuest) + uint32(lowLevelDiff)) { if (pQuest->HasQuestFlag(QUEST_FLAGS_DAILY) || pQuest->HasQuestFlag(QUEST_FLAGS_WEEKLY)) { dialogStatusNew = DIALOG_STATUS_AVAILABLE_REP; } else { dialogStatusNew = DIALOG_STATUS_AVAILABLE; } } else // player level much higher then quest-level { dialogStatusNew = DIALOG_STATUS_LOW_LEVEL_AVAILABLE; } } else { dialogStatusNew = DIALOG_STATUS_UNAVAILABLE; } } } if (dialogStatusNew > dialogStatus) { dialogStatus = dialogStatusNew; } } return dialogStatus; } void WorldSession::HandleQuestgiverStatusMultipleQuery(WorldPacket& /*recvPacket*/) { DEBUG_LOG("WORLD: Received opcode CMSG_QUESTGIVER_STATUS_MULTIPLE_QUERY"); _player->SendQuestGiverStatusMultiple(); } bool WorldSession::CanInteractWithQuestGiver(ObjectGuid guid, char const* descr) { if (guid.IsCreatureOrVehicle()) { Creature* pCreature = _player->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_QUESTGIVER); if (!pCreature) { DEBUG_LOG("WORLD: %s - %s cannot interact with %s.", descr, _player->GetGuidStr().c_str(), guid.GetString().c_str()); return false; } } else if (guid.IsGameObject()) { GameObject* pGo = _player->GetGameObjectIfCanInteractWith(guid, GAMEOBJECT_TYPE_QUESTGIVER); if (!pGo) { DEBUG_LOG("WORLD: %s - %s cannot interact with %s.", descr, _player->GetGuidStr().c_str(), guid.GetString().c_str()); return false; } } else if (!_player->IsAlive()) { DEBUG_LOG("WORLD: %s - %s is dead, requested guid was %s", descr, _player->GetGuidStr().c_str(), guid.GetString().c_str()); return false; } return true; }
0
0.932502
1
0.932502
game-dev
MEDIA
0.935111
game-dev
0.926879
1
0.926879
andr3wmac/Torque6
2,778
lib/bullet/BulletCollision/Gimpact/btCompoundFromGimpact.h
#ifndef BT_COMPOUND_FROM_GIMPACT #define BT_COMPOUND_FROM_GIMPACT #include "BulletCollision/CollisionShapes/btCompoundShape.h" #include "btGImpactShape.h" #include "BulletCollision/NarrowPhaseCollision/btRaycastCallback.h" struct MyCallback : public btTriangleRaycastCallback { int m_ignorePart; int m_ignoreTriangleIndex; MyCallback(const btVector3& from, const btVector3& to, int ignorePart, int ignoreTriangleIndex) :btTriangleRaycastCallback(from,to), m_ignorePart(ignorePart), m_ignoreTriangleIndex(ignoreTriangleIndex) { } virtual btScalar reportHit(const btVector3& hitNormalLocal, btScalar hitFraction, int partId, int triangleIndex) { if (partId!=m_ignorePart || triangleIndex!=m_ignoreTriangleIndex) { if (hitFraction < m_hitFraction) return hitFraction; } return m_hitFraction; } }; struct MyInternalTriangleIndexCallback :public btInternalTriangleIndexCallback { const btGImpactMeshShape* m_gimpactShape; btCompoundShape* m_colShape; btScalar m_depth; MyInternalTriangleIndexCallback (btCompoundShape* colShape, const btGImpactMeshShape* meshShape, btScalar depth) :m_colShape(colShape), m_gimpactShape(meshShape), m_depth(depth) { } virtual void internalProcessTriangleIndex(btVector3* triangle,int partId,int triangleIndex) { btVector3 scale = m_gimpactShape->getLocalScaling(); btVector3 v0=triangle[0]*scale; btVector3 v1=triangle[1]*scale; btVector3 v2=triangle[2]*scale; btVector3 centroid = (v0+v1+v2)/3; btVector3 normal = (v1-v0).cross(v2-v0); normal.normalize(); btVector3 rayFrom = centroid; btVector3 rayTo = centroid-normal*m_depth; MyCallback cb(rayFrom,rayTo,partId,triangleIndex); m_gimpactShape->processAllTrianglesRay(&cb,rayFrom, rayTo); if (cb.m_hitFraction<1) { rayTo.setInterpolate3(cb.m_from,cb.m_to,cb.m_hitFraction); //rayTo = cb.m_from; //rayTo = rayTo.lerp(cb.m_to,cb.m_hitFraction); //gDebugDraw.drawLine(tr(centroid),tr(centroid+normal),btVector3(1,0,0)); } btBU_Simplex1to4* tet = new btBU_Simplex1to4(v0,v1,v2,rayTo); btTransform ident; ident.setIdentity(); m_colShape->addChildShape(ident,tet); } }; btCompoundShape* btCreateCompoundFromGimpactShape(const btGImpactMeshShape* gimpactMesh, btScalar depth) { btCompoundShape* colShape = new btCompoundShape(); btTransform tr; tr.setIdentity(); MyInternalTriangleIndexCallback cb(colShape,gimpactMesh, depth); btVector3 aabbMin,aabbMax; gimpactMesh->getAabb(tr,aabbMin,aabbMax); gimpactMesh->getMeshInterface()->InternalProcessAllTriangles(&cb,aabbMin,aabbMax); return colShape; } #endif //BT_COMPOUND_FROM_GIMPACT
0
0.918802
1
0.918802
game-dev
MEDIA
0.910706
game-dev
0.989601
1
0.989601
vlad250906/Create-UfoPort
7,476
modules/create/src/main/java/com/simibubi/create/foundation/placement/IPlacementHelper.java
package com.simibubi.create.foundation.placement; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import com.simibubi.create.CreateClient; import com.simibubi.create.foundation.utility.Iterate; import com.simibubi.create.foundation.utility.Pair; import com.simibubi.create.foundation.utility.VecHelper; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Vec3i; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; @MethodsReturnNonnullByDefault public interface IPlacementHelper { /** * used as an identifier in SuperGlueHandler to skip blocks placed by helpers */ BlockState ID = new BlockState(Blocks.AIR, null, null); /** * @return a predicate that gets tested with the items held in the players hands<br> * should return true if this placement helper is active with the given item */ Predicate<ItemStack> getItemPredicate(); /** * @return a predicate that gets tested with the blockstate the player is looking at<br> * should return true if this placement helper is active with the given blockstate */ Predicate<BlockState> getStatePredicate(); /** * * @param player the player that activated the placement helper * @param world the world that the placement helper got activated in * @param state the Blockstate of the Block that the player is looking at or clicked on * @param pos the position of the Block the player is looking at or clicked on * @param ray the exact raytrace result * * @return the PlacementOffset object describing where to place the new block.<br> * Use {@link PlacementOffset#fail} when no new position could be found.<br> * Use {@link PlacementOffset#success(Vec3i)} with the new BlockPos to indicate a success * and call {@link PlacementOffset#withTransform(Function)} if the blocks default state has to be modified before it is placed */ PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos, BlockHitResult ray); //sets the offset's ghost state with the default state of the held block item, this is used in PlacementHelpers and can be ignored in most cases default PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos, BlockHitResult ray, ItemStack heldItem) { PlacementOffset offset = getOffset(player, world, state, pos, ray); if (heldItem.getItem() instanceof BlockItem) { BlockItem blockItem = (BlockItem) heldItem.getItem(); offset = offset.withGhostState(blockItem.getBlock().defaultBlockState()); } return offset; } /** * overwrite this method if your placement helper needs a different rendering than the default ghost state * * @param pos the position of the Block the player is looking at or clicked on * @param state the Blockstate of the Block that the player is looking at or clicked on * @param ray the exact raytrace result * @param offset the PlacementOffset returned by {@link #getOffset(Player, Level, BlockState, BlockPos, BlockHitResult)}<br> * the offset will always be successful if this method is called */ default void renderAt(BlockPos pos, BlockState state, BlockHitResult ray, PlacementOffset offset) { displayGhost(offset); } //RIP static void renderArrow(Vec3 center, Vec3 target, Direction arrowPlane) { renderArrow(center, target, arrowPlane, 1D); } static void renderArrow(Vec3 center, Vec3 target, Direction arrowPlane, double distanceFromCenter) { Vec3 direction = target.subtract(center).normalize(); Vec3 facing = Vec3.atLowerCornerOf(arrowPlane.getNormal()); Vec3 start = center.add(direction); Vec3 offset = direction.scale(distanceFromCenter - 1); Vec3 offsetA = direction.cross(facing).normalize().scale(.25); Vec3 offsetB = facing.cross(direction).normalize().scale(.25); Vec3 endA = center.add(direction.scale(.75)).add(offsetA); Vec3 endB = center.add(direction.scale(.75)).add(offsetB); CreateClient.OUTLINER.showLine("placementArrowA" + center + target, start.add(offset), endA.add(offset)).lineWidth(1 / 16f); CreateClient.OUTLINER.showLine("placementArrowB" + center + target, start.add(offset), endB.add(offset)).lineWidth(1 / 16f); } default void displayGhost(PlacementOffset offset) { if (!offset.hasGhostState()) return; CreateClient.GHOST_BLOCKS.showGhostState(this, offset.getTransform().apply(offset.getGhostState())) .at(offset.getBlockPos()) .breathingAlpha(); } static List<Direction> orderedByDistanceOnlyAxis(BlockPos pos, Vec3 hit, Direction.Axis axis) { return orderedByDistance(pos, hit, dir -> dir.getAxis() == axis); } static List<Direction> orderedByDistanceOnlyAxis(BlockPos pos, Vec3 hit, Direction.Axis axis, Predicate<Direction> includeDirection) { return orderedByDistance(pos, hit, ((Predicate<Direction>) dir -> dir.getAxis() == axis).and(includeDirection)); } static List<Direction> orderedByDistanceExceptAxis(BlockPos pos, Vec3 hit, Direction.Axis axis) { return orderedByDistance(pos, hit, dir -> dir.getAxis() != axis); } static List<Direction> orderedByDistanceExceptAxis(BlockPos pos, Vec3 hit, Direction.Axis axis, Predicate<Direction> includeDirection) { return orderedByDistance(pos, hit, ((Predicate<Direction>) dir -> dir.getAxis() != axis).and(includeDirection)); } static List<Direction> orderedByDistanceExceptAxis(BlockPos pos, Vec3 hit, Direction.Axis first, Direction.Axis second) { return orderedByDistanceExceptAxis(pos, hit, first, d -> d.getAxis() != second); } static List<Direction> orderedByDistanceExceptAxis(BlockPos pos, Vec3 hit, Direction.Axis first, Direction.Axis second, Predicate<Direction> includeDirection) { return orderedByDistanceExceptAxis(pos, hit, first, ((Predicate<Direction>) d -> d.getAxis() != second).and(includeDirection)); } static List<Direction> orderedByDistance(BlockPos pos, Vec3 hit) { return orderedByDistance(pos, hit, _$ -> true); } static List<Direction> orderedByDistance(BlockPos pos, Vec3 hit, Predicate<Direction> includeDirection) { Vec3 centerToHit = hit.subtract(VecHelper.getCenterOf(pos)); return Arrays.stream(Iterate.directions) .filter(includeDirection) .map(dir -> Pair.of(dir, Vec3.atLowerCornerOf(dir.getNormal()).distanceTo(centerToHit))) .sorted(Comparator.comparingDouble(Pair::getSecond)) .map(Pair::getFirst) .collect(Collectors.toList()); } static List<Direction> orderedByDistance(BlockPos pos, Vec3 hit, Collection<Direction> directions) { Vec3 centerToHit = hit.subtract(VecHelper.getCenterOf(pos)); return directions.stream() .map(dir -> Pair.of(dir, Vec3.atLowerCornerOf(dir.getNormal()).distanceTo(centerToHit))) .sorted(Comparator.comparingDouble(Pair::getSecond)) .map(Pair::getFirst) .toList(); } default boolean matchesItem(ItemStack item) { return getItemPredicate().test(item); } default boolean matchesState(BlockState state) { return getStatePredicate().test(state); } }
0
0.930789
1
0.930789
game-dev
MEDIA
0.813944
game-dev
0.980362
1
0.980362
DataRealms/CCOSS
23,612
System/Reader.h
#ifndef _RTEREADER_ #define _RTEREADER_ ////////////////////////////////////////////////////////////////////////////////////////// // File: Reader.h ////////////////////////////////////////////////////////////////////////////////////////// // Description: Header file for the Reader class. // Project: Retro Terrain Engine // Author(s): Daniel Tabar // data@datarealms.com // http://www.datarealms.com ////////////////////////////////////////////////////////////////////////////////////////// // Inclusions of header files #include <istream> #include <fstream> #include <string> #include <list> #include "Writer.h" namespace RTE { // Not necessary anymore since enforce *.rte in dirnames if not packaged. //const char g_ReadPackageExtension[8] = ".rte"; class Attachable; class MOSRotating; ////////////////////////////////////////////////////////////////////////////////////////// // Class: Reader ////////////////////////////////////////////////////////////////////////////////////////// // Description: Reads RTE objects from std::istreams. // Parent(s): None. // Class history: 01/20/2002 Reader created. class Reader { ////////////////////////////////////////////////////////////////////////////////////////// // Public member variable, method and friend function declarations public: ////////////////////////////////////////////////////////////////////////////////////////// // Constructor: Reader ////////////////////////////////////////////////////////////////////////////////////////// // Description: Constructor method used to instantiate a Reader object in system // memory. Create() should be called before using the object. // Arguments: None. Reader() { Clear(); } ////////////////////////////////////////////////////////////////////////////////////////// // Constructor: Reader ////////////////////////////////////////////////////////////////////////////////////////// // Description: Constructor method used to instantiate a Reader object in system // memory. Create() should be called before using the object. // Whether object defintions read here overwrite existing ones with the // same names. // A function pointer to a function that will be called and sent a string // with information about the progress of this Reader's reading. // Whether it's ok for the file to not be there, ie we're only trying to // open, and if it's not there, then fail silently. // Arguments: Path to the file to open for reading. Reader(const char *filename, bool overwrites = false, void (*fpProgressCallback)(std::string, bool) = 0, bool failOK = false) { Clear(); Create(filename, overwrites, fpProgressCallback, failOK); } ////////////////////////////////////////////////////////////////////////////////////////// // Destructor: ~Reader ////////////////////////////////////////////////////////////////////////////////////////// // Description: Destructor method used to clean up a Reader object before deletion // from system memory. // Arguments: None. virtual ~Reader() { Destroy(true); } ////////////////////////////////////////////////////////////////////////////////////////// // Virtual method: Create ////////////////////////////////////////////////////////////////////////////////////////// // Description: Makes the Reader object ready for use. // Arguments: The filename of the file to open and read from. If the file isn't found // directly on disk, the first directory in the path will be used to try // open a package of that name. If that doesn't work, and error code will // be returned. // Whether object defintions read here overwrite existing ones with the // same names. // A function pointer to a function that will be called and sent a string // with information about the progress of this Reader's reading. // Return value: An error return value signaling sucess or any particular failure. // Anything below 0 is an error signal. virtual int Create(const char *filename, bool overwrites = false, void (*fpProgressCallback)(std::string, bool) = 0, bool failOK = false); ////////////////////////////////////////////////////////////////////////////////////////// // Virtual method: Reset ////////////////////////////////////////////////////////////////////////////////////////// // Description: Resets the entire Reader, including its inherited members, to their // default settings or values. // Arguments: None. // Return value: None. virtual void Reset() { Clear(); /*Serializable::Reset();*/ } ////////////////////////////////////////////////////////////////////////////////////////// // Virtual method: Destroy ////////////////////////////////////////////////////////////////////////////////////////// // Description: Destroys and resets (through Clear()) the Reader object. // Arguments: Whether to only destroy the members defined in this derived class, or // to destroy all inherited members also. // Return value: None. virtual void Destroy(bool notInherited = false); ////////////////////////////////////////////////////////////////////////////////////////// // Operators: Elemental types stream extractions ////////////////////////////////////////////////////////////////////////////////////////// // Description: Stream extraction operator overloads for all the elemental types // Arguments: A reference to the variable that will be filled by the extracted data. // Return value: A Reader reference for further use in an expression. virtual Reader & operator>>(bool &var) { Eat(); *m_pStream >> var; return *this; } virtual Reader & operator>>(char &var) { Eat(); *m_pStream >> var; return *this; } virtual Reader & operator>>(unsigned char &var) { Eat(); int temp; *m_pStream >> temp; var = temp; return *this; } virtual Reader & operator>>(short &var) { Eat(); *m_pStream >> var; return *this; } virtual Reader & operator>>(unsigned short &var) { Eat(); *m_pStream >> var; return *this; } virtual Reader & operator>>(int &var) { Eat(); *m_pStream >> var; return *this; } virtual Reader & operator>>(unsigned int &var) { Eat(); *m_pStream >> var; return *this; } virtual Reader & operator>>(long &var) { Eat(); *m_pStream >> var; return *this; } virtual Reader & operator>>(unsigned long &var) { Eat(); *m_pStream >> var; return *this; } virtual Reader & operator>>(float &var) { Eat(); *m_pStream >> var; return *this; } virtual Reader & operator>>(double &var) { Eat(); *m_pStream >> var; return *this; } virtual Reader & operator>>(char * var) { Eat(); *m_pStream >> var; return *this; } ////////////////////////////////////////////////////////////////////////////////////////// // Operators: std::string extraction ////////////////////////////////////////////////////////////////////////////////////////// // Description: Stream extraction operator overloads for std::string. // Arguments: A reference to the variable that will be filled by the extracted data. // Return value: A Reader reference for further use in an expression. virtual Reader & operator>>(std::string &var); ////////////////////////////////////////////////////////////////////////////////////////// // Virtual method: GetClassName ////////////////////////////////////////////////////////////////////////////////////////// // Description: Gets the class name of this Reader. // Arguments: None. // Return value: A string with the friendly-formatted type name of this Reader. virtual const std::string & GetClassName() const { return ClassName; } ////////////////////////////////////////////////////////////////////////////////////////// // Virtual method: GetReadModuleName ////////////////////////////////////////////////////////////////////////////////////////// // Description: Gets the name of Data Module this reader is reading from. // Arguments: None. // Return value: A string with the friendly-formatted type name of this Reader. virtual const std::string & GetReadModuleName() const { return m_DataModuleName; } ////////////////////////////////////////////////////////////////////////////////////////// // Virtual method: GetReadModuleID ////////////////////////////////////////////////////////////////////////////////////////// // Description: Gets the ID of Data Module this reader is reading from. // Arguments: None. // Return value: A string with the friendly-formatted type name of this Reader. virtual int GetReadModuleID() const; ////////////////////////////////////////////////////////////////////////////////////////// // Method: GetStream ////////////////////////////////////////////////////////////////////////////////////////// // Description: Gets a pointer to the istream of this reader. // Arguments: None. // Return value: A pointer to the istream object fo this reader. std::istream * GetStream() { return m_pStream; } ////////////////////////////////////////////////////////////////////////////////////////// // Method: IsOK ////////////////////////////////////////////////////////////////////////////////////////// // Description: Shows whether this is still OK to read from. If file isn't present, // etc, this will return false. // Arguments: None. // Return value: Whether this Reader's stream is OK or not. bool IsOK() { return m_pStream && m_pStream->good(); } ////////////////////////////////////////////////////////////////////////////////////////// // Method: GetCurrentFilePath ////////////////////////////////////////////////////////////////////////////////////////// // Description: Gets the path of the current file this reader is reading from. // Arguments: None. // Return value: A string with the path, relative from the working directory. std::string GetCurrentFilePath() const { return m_FilePath; } ////////////////////////////////////////////////////////////////////////////////////////// // Method: GetCurrentFileLine ////////////////////////////////////////////////////////////////////////////////////////// // Description: Gets the line of the current file line this reader is reading from. // Arguments: None. // Return value: The line number that will be read from next. int GetCurrentFileLine() const { return m_CurrentLine; } ////////////////////////////////////////////////////////////////////////////////////////// // Method: GetCurrentFileLine ////////////////////////////////////////////////////////////////////////////////////////// // Description: Gets the line of the current file line this reader is reading from. // Arguments: None. // Return value: The line number that will be read from next. std::string GetCurrentFileLineString() const { char str[128]; sprintf(str, "%d", m_CurrentLine); return str; } ////////////////////////////////////////////////////////////////////////////////////////// // Method: GetPresetOverwriting ////////////////////////////////////////////////////////////////////////////////////////// // Description: Shows whether objects read from this will be overwritng any existing // ones with the same names. // Arguments: None. // Return value: Whether this overwrites or not. bool GetPresetOverwriting() { return m_OverwriteExisting; } ////////////////////////////////////////////////////////////////////////////////////////// // Method: SetPresetOverwriting ////////////////////////////////////////////////////////////////////////////////////////// // Description: Sets whether objects read from this will be overwritng any existing // ones with the same names. // Arguments: Whether this should overwrite existing definitions or not. // Return value: None. void SetPresetOverwriting(bool overwrites = true) { m_OverwriteExisting = overwrites; } /* ////////////////////////////////////////////////////////////////////////////////////////// // Method: SetMass ////////////////////////////////////////////////////////////////////////////////////////// // Description: Sets the mass of this Reader. // Arguments: A float specifying the new mass value in Kilograms (kg). // Return value: None. void SetMass(const float newMass) { m_Mass = newMass; } */ ////////////////////////////////////////////////////////////////////////////////////////// // Method: Eat ////////////////////////////////////////////////////////////////////////////////////////// // Description: Eats all whitespace and newlines and comment lines (which start with // '//') so that the next thing to be read will be actual data. // Arguments: None. // Return value: Whether there is more data to read from the filestreams after this eat. bool Eat(); ////////////////////////////////////////////////////////////////////////////////////////// // Method: ReadLine ////////////////////////////////////////////////////////////////////////////////////////// // Description: Reads the rest of the line from the context object Reader's stream // current location. // Arguments: The c-string that will be filled out with the line. // An int specifying the max size of the c-string. // Return value: None. void ReadLine(char *locString, int size); ////////////////////////////////////////////////////////////////////////////////////////// // Method: ReadLine ////////////////////////////////////////////////////////////////////////////////////////// // Description: Reads the rest of the line from the context object Reader's stream // current location. // Arguments: None. // Return value: The std::string that will hold the line's contents. std::string ReadLine(); ////////////////////////////////////////////////////////////////////////////////////////// // Method: ReadTo ////////////////////////////////////////////////////////////////////////////////////////// // Description: Reads from teh current position up to a specific character or eof. // Arguments: Which character to stop reading at. // Whether to also eat the terminator when it is encountered, or to leave // it in the stream. // Return value: The std::string that will hold what has been read up till, but not // including the terminator char. std::string ReadTo(char terminator, bool eatTerminator = false); ////////////////////////////////////////////////////////////////////////////////////////// // Method: NextProperty ////////////////////////////////////////////////////////////////////////////////////////// // Description: Lines up the reader with the next property of the current object. // Arguments: None. // Return value: Whether there are any more properties to be read by the current object. bool NextProperty(); ////////////////////////////////////////////////////////////////////////////////////////// // Method: ReadPropName ////////////////////////////////////////////////////////////////////////////////////////// // Description: Reads the next property name from the context object Reader's stream // after eating all whitespace including newlines up till the first // newline char. Basically gets anything between the last newline before // text to the next "=" after that. // Arguments: None. // Return value: The whitespace-trimmed std::string that will hold the next property's // name. std::string ReadPropName(); ////////////////////////////////////////////////////////////////////////////////////////// // Method: ReadPropValue ////////////////////////////////////////////////////////////////////////////////////////// // Description: Reads the next property value from the context object Reader's stream // after eating all whitespace including newlines up till the first // newline char. Basically gets anything after the last "=" and up to // the next newline after that. // Arguments: None. // Return value: The whitespace-trimmed std::string that will hold the next property // value. std::string ReadPropValue(); ////////////////////////////////////////////////////////////////////////////////////////// // Method: TrimString ////////////////////////////////////////////////////////////////////////////////////////// // Description: Takes out whitespace from the beginning and the end of a string. // Arguments: None. // Return value: The string that was passed in, sans whitespace in the front and end. std::string TrimString(std::string &stringToTrim); ////////////////////////////////////////////////////////////////////////////////////////// // Method: ReportError ////////////////////////////////////////////////////////////////////////////////////////// // Description: Makes an error message box pop up for the user that tells them // something went wrong with the reading, and where. // Arguments: The message describing what's wrong. // Return value: None. void ReportError(std::string errorDesc); ////////////////////////////////////////////////////////////////////////////////////////// // Method: SetSkipIncludes ////////////////////////////////////////////////////////////////////////////////////////// // Description: Set whether this reader should skip included files. // Arguments: To make reader skip included files pass true, pass false otherwise. // Return value: None. void SetSkipIncludes(bool skip) { m_SkipIncludes = skip; }; ////////////////////////////////////////////////////////////////////////////////////////// // Method: GetSkipIncludes ////////////////////////////////////////////////////////////////////////////////////////// // Description: Returns true if reader was told to skip InlcudeFile statements // Arguments: None. // Return value: Returns whether reader was told to skip inlcuded files. bool GetSkipIncludes() const { return m_SkipIncludes; }; ////////////////////////////////////////////////////////////////////////////////////////// // Protected member variable and method declarations protected: struct StreamInfo { StreamInfo(std::ifstream *pStream, std::string filePath, int currentLine, int prevIndent): m_pStream(pStream), m_FilePath(filePath), m_CurrentLine(currentLine), m_PreviousIndent(prevIndent) { ; } // Owned by the reader, so not deleted by this std::ifstream *m_pStream; std::string m_FilePath; int m_CurrentLine; int m_PreviousIndent; }; ////////////////////////////////////////////////////////////////////////////////////////// // Method: StartIncludeFile ////////////////////////////////////////////////////////////////////////////////////////// // Description: When ReadPropName encounters the property name "IncludeFile", it will // automatically call this function to get started reading on that file. // This will create a new stream to the include file. // Arguments: None. // Return value: Whether the include file was found and opened ok or not. bool StartIncludeFile(); ////////////////////////////////////////////////////////////////////////////////////////// // Method: EndIncludeFile ////////////////////////////////////////////////////////////////////////////////////////// // Description: This should be called when eof is detected in an included file stream. // It will destroy the current stream pop the top stream off the stream // stack to resume reading from it instead. // Arguments: None. // Return value: Wheteher there were any stream on the stack to resume. bool EndIncludeFile(); // Member variables static const std::string ClassName; // Currently used stream, is not on the StreamStack until a new stream is opned std::ifstream *m_pStream; // Currently used stream's filepath std::string m_FilePath; // The line number the stream is on int m_CurrentLine; // Stack of stream and filepath pairs, each one representing a file opened to read from within another std::list<StreamInfo> m_StreamStack; // zip::izipfile *m_Package; // Count of tabs encountered on the last line Eat() ate. int m_PreviousIndent; // Difference in indentation from the last line to the current line int m_IndentDifference; // When NextProperty() has returned false, indicating that there were no more properties to read on that object, // this is incremented until it matches -m_IndentDifference, and then NextProperty will start returning true again int m_ObjectEndings; /* Couldn't figure out how to determine a new object started as opposed to a one-line property // Shows wheter we just started reading a new property/object, and should have a positive indentdiff on the first line // If it's 0 or negative, it means the new object to be read didn't ahve any properties defined at all bool m_NewObject; */ // All streams have been depleted bool m_EndOfStreams; // Funciton pointer to report our reading progress to, by calling it and passing a descriptive string to it. void (*m_fpReportProgress)(std::string, bool); // String containing the proper amount of tabs for the report std::string m_ReportTabs; // Only the name of the currently read file, excluding the path std::string m_FileName; // The current name of the data module being read from, including the .rte extension std::string m_DataModuleName; // The current ID of the data module being read from int m_DataModuleID; // Whether object instances read from this should overwrite any already existing ones with the same names bool m_OverwriteExisting; // Indicates wether reader should skip inlcuded files bool m_SkipIncludes; ////////////////////////////////////////////////////////////////////////////////////////// // Private member variable and method declarations private: ////////////////////////////////////////////////////////////////////////////////////////// // Method: Clear ////////////////////////////////////////////////////////////////////////////////////////// // Description: Clears all the member variables of this Reader, effectively // resetting the members of this abstraction level only. // Arguments: None. // Return value: None. void Clear(); // Disallow the use of some implicit methods. Reader(const Reader &reference); Reader & operator=(const Reader &rhs); }; } // namespace RTE #endif // File
0
0.716626
1
0.716626
game-dev
MEDIA
0.149178
game-dev
0.734398
1
0.734398
elsong823/HalfSLG
2,428
S7/HalfSLG/Assets/HalfSLG/Scripts/UIView/SO_UIViewConfig.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace ELGame { #if UNITY_EDITOR using UnityEditor; [CanEditMultipleObjects] [CustomEditor(typeof(SO_UIViewConfig))] public class SO_UIViewConfigEditor : Editor { public override void OnInspectorGUI() { //常规显示 base.OnInspectorGUI(); serializedObject.Update(); if (GUI.changed) { //修正唯一按钮 var pUnique = serializedObject.FindProperty("unique"); var pCacheScheme = serializedObject.FindProperty("cacheScheme"); //如果选择的是常驻内存,则必须勾选唯一 if (pCacheScheme.enumValueIndex == 2 && pUnique.boolValue == false) { //提醒一下 EditorUtility.DisplayDialog("Warning", "Cache scheme view must be UNIQUE !", "OK"); pUnique.boolValue = true; } serializedObject.ApplyModifiedProperties(); } } } #endif //添加后需要在初始化时注册 public enum UIViewName { None, Debug, Main, //主界面 BattleFieldPlayerActOption, //玩家操作选择栏 BattleFieldUnitInfo, //显示战斗单位信息 } //添加后需要在初始化时注册 public enum UIViewLayer { None, Background, Base, Popup, Top, Debug, } public enum UIViewCacheScheme { AutoRemove, //自动移除 TempCache, //关闭后进入临时缓冲池 Cache, //关闭后常驻内存 } [CreateAssetMenu(menuName = "ScriptableObject/UI view config")] public class SO_UIViewConfig : ScriptableObject { public bool unique = true; //是否唯一打开 public UIViewName viewName; //界面名称 public UIViewLayer viewLayer; //所在层 public UIViewCacheScheme cacheScheme; //缓存策略 public string assetName; //资源的名称 public bool coverScreen; //是否遮挡了整个屏幕 public bool alwaysUpdate; //被遮挡后是否需要更新 public bool bgTriggerClose; //点击了背景是否关闭界面 public string BundleName { get { return string.Format("prefabs/uiview/{0}", assetName); } } } }
0
0.50514
1
0.50514
game-dev
MEDIA
0.529454
game-dev,mobile
0.712372
1
0.712372
jinglikeblue/Zero
1,034
Assets/Zero/Scripts/Monos/Data/FloatBindingData.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Zero { public class FloatBindingData : BaseBinding { [Serializable] public struct BindingVO { public string key; public float[] list; } [Header("数据引用")] public BindingVO[] list; /// <summary> /// 找到Key对应的资源 /// </summary> /// <param name="key"></param> /// <returns></returns> public float[] Find(string key) { foreach (var vo in list) { if (vo.key == key) { return vo.list; } } return null; } public static float[] Find(GameObject go, string key) { var data = go.GetComponent<FloatBindingData>(); if (null == data) { return null; } return data.Find(key); } } }
0
0.781934
1
0.781934
game-dev
MEDIA
0.643157
game-dev
0.808541
1
0.808541
LandSandBoat/server
1,087
scripts/zones/Riverne-Site_B01/Zone.lua
----------------------------------- -- Zone: Riverne-Site_B01 ----------------------------------- ---@type TZone local zoneObject = {} zoneObject.onInitialize = function(zone) end zoneObject.onConquestUpdate = function(zone, updatetype, influence, owner, ranking, isConquestAlliance) xi.conquest.onConquestUpdate(zone, updatetype, influence, owner, ranking, isConquestAlliance) end zoneObject.onZoneIn = function(player, prevZone) local cs = -1 if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then player:setPos(729.749, -20.319, 407.153, 90) end return cs end zoneObject.afterZoneIn = function(player) -- ZONE WIDE LEVEL RESTRICTION if xi.settings.main.ENABLE_COP_ZONE_CAP == 1 then player:addStatusEffect(xi.effect.LEVEL_RESTRICTION, 50, 0, 0) end end zoneObject.onTriggerAreaEnter = function(player, triggerArea) end zoneObject.onEventUpdate = function(player, csid, option, npc) end zoneObject.onEventFinish = function(player, csid, option, npc) end return zoneObject
0
0.93159
1
0.93159
game-dev
MEDIA
0.9607
game-dev
0.842131
1
0.842131
ProjectIgnis/CardScripts
1,689
unofficial/c511000951.lua
--Regreatful Tuning local s,id=GetID() function s.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetCode(EVENT_BATTLE_DAMAGE) e1:SetCondition(s.condition) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) end function s.condition(e,tp,eg,ep,ev,re,r,rp) return eg:GetFirst():IsControler(1-tp) and ep==tp and Duel.GetAttackTarget()==nil end function s.filter(c,e,tp) return c:IsType(TYPE_SYNCHRO) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:GetControler()==tp and s.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(s.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,s.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function s.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)~=0 then local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetCode(EVENT_PHASE+PHASE_BATTLE) e2:SetOperation(s.desop) e2:SetReset(RESET_EVENT+RESETS_STANDARD) tc:RegisterEffect(e2) end end function s.desop(e,tp,eg,ep,ev,re,r,rp) if e:GetHandler():GetAttackedCount()>0 then Duel.Destroy(e:GetHandler(),REASON_EFFECT) end end
0
0.920547
1
0.920547
game-dev
MEDIA
0.99284
game-dev
0.897701
1
0.897701
luna-rs/luna
3,528
src/main/kotlin/world/player/item/banking/regularBank/openBank.kts
package world.player.item.banking.regularBank import api.predef.* import io.luna.game.event.impl.ServerStateChangedEvent.ServerLaunchEvent import io.luna.game.model.mob.Player /** * Load all banking NPC dialogues and bank object actions. */ on(ServerLaunchEvent::class) { // Load all banking npcs and make them initialize dialogues. Banking.loadBankingNpcs() for (id in Banking.bankingNpcs) { npc1(id) { openDialogue(plr, id) } } // Load all banking objects, make them open the bank. Banking.loadBankingObjects() for (id in Banking.bankingObjects) { // Add listeners for "Use" object1(id) { val npc = plr.updateNpcs.stream().filter { Banking.bankingNpcs.contains(it.id) } .filter { it.position.isWithinDistance(gameObject.position, 1) }.findFirst() if (npc.isPresent) { openDialogue(plr, npc.get().id) } else { // Use default banker if no NPC is nearby. openDialogue(plr, Banking.DEFAULT_BANKER) } } // Add listeners for "Use-quickly" if (objectDef(id).actions.contains("Use-quickly")) { object2(id) { plr.bank.open() } } } } /** * Opens the NPC main banker dialogue. */ fun openDialogue(plr: Player, id: Int) { plr.newDialogue() .npc(id, "Good day, how may I help you?") .options("I'd like to access my bank account, please.", { accessAccountDialogue(it) }, "What is this place?", { areaInfoDialogue(it, id) }, "Didn't you used to be called the bank of Varrock?", { oldNameInfoDialogue(it, id) }).open() } /** * Opens the sub-dialogue for accessing the bank. */ fun accessAccountDialogue(plr: Player) { plr.newDialogue() .player("I'd like to access my bank account, please.") .then { plr.bank.open() } .open() } /** * Opens the sub-dialogue for learning about the area. */ fun areaInfoDialogue(plr: Player, id: Int) { plr.newDialogue() .player("What is this place?") .npc(id, "This is a branch of the bank of Runescape. We have", "branches in many towns.") .options("And what do you do?", { plr.newDialogue() .player("And what do you do?") .npc(id, "We will look after your items and money for you.", "Leave your valuables with us if you want to keep them", "safe.").open() }, "Didn't you used to be called the bank of Varrock?", { plr.newDialogue() .player("Didn't you used to be called the bank of Varrock?") .npc(id, "Yes we did, but people kept on coming into our", "branches outside of Varrock and telling us that our", "signs were wrong. They acted as if we didn't know", "what town we were in or something.").open() }).open() } /** * Opens the sub-dialogue for learning about the previous name. */ fun oldNameInfoDialogue(plr: Player, id: Int) { plr.newDialogue() .player("Didn't you used to be called the bank of Varrock?") .npc(id, "Yes we did, but people kept on coming into our", "branches outside of Varrock and telling us that our", "signs were wrong. They acted as if we didn't know", "what town we were in or something.") .open() }
0
0.606345
1
0.606345
game-dev
MEDIA
0.723635
game-dev
0.572461
1
0.572461
Fluorohydride/ygopro-scripts
2,504
c71541986.lua
--エクシーズ・ディメンション・スプラッシュ function c71541986.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(71541986,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetCode(EVENT_REMOVE) e1:SetCondition(c71541986.spcon) e1:SetTarget(c71541986.sptg) e1:SetOperation(c71541986.spop) c:RegisterEffect(e1) end function c71541986.spcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsPreviousLocation(LOCATION_ONFIELD) and c:IsPreviousPosition(POS_FACEDOWN) end function c71541986.spfilter(c,e,tp) return c:IsAttribute(ATTRIBUTE_WATER) and c:IsLevel(8) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c71541986.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return not Duel.IsPlayerAffectedByEffect(tp,59822133) and Duel.GetLocationCount(tp,LOCATION_MZONE)>1 and Duel.IsExistingMatchingCard(c71541986.spfilter,tp,LOCATION_DECK,0,2,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK) end function c71541986.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.IsPlayerAffectedByEffect(tp,59822133) then return end if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 then return end local g=Duel.GetMatchingGroup(c71541986.spfilter,tp,LOCATION_DECK,0,nil,e,tp) if g:GetCount()<2 then return end local c=e:GetHandler() Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg=g:Select(tp,2,2,nil) local tc=sg:GetFirst() while tc do Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_ATTACK_ANNOUNCE) e1:SetReset(RESET_EVENT+RESETS_STANDARD) tc:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_DISABLE) e2:SetReset(RESET_EVENT+RESETS_STANDARD) tc:RegisterEffect(e2) local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_DISABLE_EFFECT) e3:SetValue(RESET_TURN_SET) e3:SetReset(RESET_EVENT+RESETS_STANDARD) tc:RegisterEffect(e3) local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e4:SetRange(LOCATION_MZONE) e4:SetCode(EFFECT_UNRELEASABLE_SUM) e4:SetValue(1) e4:SetReset(RESET_EVENT+RESETS_STANDARD) tc:RegisterEffect(e4) local e5=e4:Clone() e5:SetCode(EFFECT_UNRELEASABLE_NONSUM) tc:RegisterEffect(e5) tc=sg:GetNext() end Duel.SpecialSummonComplete() end
0
0.87696
1
0.87696
game-dev
MEDIA
0.984081
game-dev
0.939892
1
0.939892