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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
interkosmos/micropolis | 8,804 | src/sim/s_eval.c | /* s_eval.c
*
* Micropolis, Unix Version. This game was released for the Unix platform
* in or about 1990 and has been modified for inclusion in the One Laptop
* Per Child program. Copyright (C) 1989 - 2007 Electronic Arts Inc. If
* you need assistance with this program, you may contact:
* http://wiki.laptop.org/go/Micropolis or email micropolis@laptop.org.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details. You should have received a
* copy of the GNU General Public License along with this program. If
* not, see <http://www.gnu.org/licenses/>.
*
* ADDITIONAL TERMS per GNU GPL Section 7
*
* No trademark or publicity rights are granted. This license does NOT
* give you any right, title or interest in the trademark SimCity or any
* other Electronic Arts trademark. You may not distribute any
* modification of this program using the trademark SimCity or claim any
* affliation or association with Electronic Arts Inc. or its employees.
*
* Any propagation or conveyance of this program must include this
* copyright notice and these terms.
*
* If you convey this program (or any modifications of it) and assume
* contractual liability for the program to recipients of it, you agree
* to indemnify Electronic Arts for any liability that those contractual
* assumptions impose on Electronic Arts.
*
* You may not misrepresent the origins of this program; modified
* versions of the program must be marked as such and not identified as
* the original program.
*
* This disclaimer supplements the one included in the General Public
* License. TO THE FULLEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW, THIS
* PROGRAM IS PROVIDED TO YOU "AS IS," WITH ALL FAULTS, WITHOUT WARRANTY
* OF ANY KIND, AND YOUR USE IS AT YOUR SOLE RISK. THE ENTIRE RISK OF
* SATISFACTORY QUALITY AND PERFORMANCE RESIDES WITH YOU. ELECTRONIC ARTS
* DISCLAIMS ANY AND ALL EXPRESS, IMPLIED OR STATUTORY WARRANTIES,
* INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY, SATISFACTORY QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT OF THIRD PARTY
* RIGHTS, AND WARRANTIES (IF ANY) ARISING FROM A COURSE OF DEALING,
* USAGE, OR TRADE PRACTICE. ELECTRONIC ARTS DOES NOT WARRANT AGAINST
* INTERFERENCE WITH YOUR ENJOYMENT OF THE PROGRAM; THAT THE PROGRAM WILL
* MEET YOUR REQUIREMENTS; THAT OPERATION OF THE PROGRAM WILL BE
* UNINTERRUPTED OR ERROR-FREE, OR THAT THE PROGRAM WILL BE COMPATIBLE
* WITH THIRD PARTY SOFTWARE OR THAT ANY ERRORS IN THE PROGRAM WILL BE
* CORRECTED. NO ORAL OR WRITTEN ADVICE PROVIDED BY ELECTRONIC ARTS OR
* ANY AUTHORIZED REPRESENTATIVE SHALL CREATE A WARRANTY. SOME
* JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF OR LIMITATIONS ON IMPLIED
* WARRANTIES OR THE LIMITATIONS ON THE APPLICABLE STATUTORY RIGHTS OF A
* CONSUMER, SO SOME OR ALL OF THE ABOVE EXCLUSIONS AND LIMITATIONS MAY
* NOT APPLY TO YOU.
*/
#include "sim.h"
/* City Evaluation */
short EvalValid;
short CityYes, CityNo;
short ProblemTable[PROBNUM];
short ProblemTaken[PROBNUM];
short ProblemVotes[PROBNUM]; /* these are the votes for each */
short ProblemOrder[4]; /* sorted index to above */
QUAD CityPop, deltaCityPop;
QUAD CityAssValue;
short CityClass; /* 0..5 */
short CityScore, deltaCityScore, AverageCityScore;
short TrafficAverage;
/* comefrom: SpecialInit Simulate */
CityEvaluation(void)
{
EvalValid = 0;
if (TotalPop) {
GetAssValue();
DoPopNum();
DoProblems();
GetScore();
DoVotes();
ChangeEval();
} else {
EvalInit();
ChangeEval();
}
EvalValid = 1;
}
/* comefrom: CityEvaluation SetCommonInits */
EvalInit(void)
{
register short x, z;
z = 0;
CityYes = z;
CityNo = z;
CityPop = z;
deltaCityPop = z;
CityAssValue = z;
CityClass = z;
CityScore = 500;
deltaCityScore = z;
EvalValid = 1;
for (x = 0; x < PROBNUM; x++)
ProblemVotes[x] = z;
for (x = 0; x < 4; x++)
ProblemOrder[x] = z;
}
/* comefrom: CityEvaluation */
GetAssValue(void)
{
QUAD z;
z = RoadTotal * 5;
z += RailTotal * 10;
z += PolicePop * 1000;
z += FireStPop * 1000;
z += HospPop * 400;
z += StadiumPop * 3000;
z += PortPop * 5000;
z += APortPop * 10000;
z += CoalPop * 3000;
z += NuclearPop * 6000;
CityAssValue = z * 1000;
}
/* comefrom: CityEvaluation */
DoPopNum(void)
{
QUAD OldCityPop;
OldCityPop = CityPop;
CityPop = ((ResPop) + (ComPop * 8L) + (IndPop *8L)) * 20L;
if (OldCityPop == -1) {
OldCityPop = CityPop;
}
deltaCityPop = CityPop - OldCityPop;
CityClass = 0; /* village */
if (CityPop > 2000) CityClass++; /* town */
if (CityPop > 10000) CityClass++; /* city */
if (CityPop > 50000) CityClass++; /* capital */
if (CityPop > 100000) CityClass++; /* metropolis */
if (CityPop > 500000) CityClass++; /* megalopolis */
}
/* comefrom: CityEvaluation */
DoProblems(void)
{
register short x, z;
short ThisProb, Max;
for (z = 0; z < PROBNUM; z++)
ProblemTable[z] = 0;
ProblemTable[0] = CrimeAverage; /* Crime */
ProblemTable[1] = PolluteAverage; /* Pollution */
ProblemTable[2] = LVAverage * .7; /* Housing */
ProblemTable[3] = CityTax * 10; /* Taxes */
ProblemTable[4] = AverageTrf(); /* Traffic */
ProblemTable[5] = GetUnemployment(); /* Unemployment */
ProblemTable[6] = GetFire(); /* Fire */
VoteProblems();
for (z = 0; z < PROBNUM; z++)
ProblemTaken[z] = 0;
for (z = 0; z < 4; z++) {
Max = 0;
for (x = 0; x < 7; x++) {
if ((ProblemVotes[x] > Max) && (!ProblemTaken[x])) {
ThisProb = x;
Max = ProblemVotes[x];
}
}
if (Max) {
ProblemTaken[ThisProb] = 1;
ProblemOrder[z] = ThisProb;
}
else {
ProblemOrder[z] = 7;
ProblemTable[7] = 0;
}
}
}
/* comefrom: DoProblems */
VoteProblems(void)
{
register x, z, count;
for (z = 0; z < PROBNUM; z++)
ProblemVotes[z] = 0;
x = 0;
z = 0;
count = 0;
while ((z < 100) && (count < 600)) {
if (Rand(300) < ProblemTable[x]) {
ProblemVotes[x]++;
z++;
}
x++;
if (x > PROBNUM) x = 0;
count++;
}
}
/* comefrom: DoProblems */
AverageTrf(void)
{
QUAD TrfTotal;
register short x, y, count;
TrfTotal = 0;
count = 1;
for (x=0; x < HWLDX; x++)
for (y=0; y < HWLDY; y++)
if (LandValueMem[x][y]) {
TrfTotal += TrfDensity[x][y];
count++;
}
TrafficAverage = (TrfTotal / count) * 2.4;
return(TrafficAverage);
}
/* comefrom: DoProblems */
GetUnemployment(void)
{
float r;
short b;
b = (ComPop + IndPop) << 3;
if (b)
r = ((float)ResPop) / b;
else
return(0);
b = (r - 1) * 255;
if (b > 255)
b = 255;
return (b);
}
/* comefrom: DoProblems GetScore */
GetFire(void)
{
short z;
z = FirePop * 5;
if (z > 255)
return(255);
else
return(z);
}
/* comefrom: CityEvaluation */
GetScore(void)
{
register x, z;
short OldCityScore;
float SM, TM;
OldCityScore = CityScore;
x = 0;
for (z = 0; z < 7; z++)
x += ProblemTable[z]; /* add 7 probs */
x = x / 3; /* 7 + 2 average */
if (x > 256) x = 256;
z = (256 - x) * 4;
if (z > 1000) z = 1000;
if (z < 0 ) z = 0;
if (ResCap) z = z * .85;
if (ComCap) z = z * .85;
if (IndCap) z = z * .85;
if (RoadEffect < 32) z = z - (32 - RoadEffect);
if (PoliceEffect < 1000) z = z * (.9 + (PoliceEffect / 10000.1));
if (FireEffect < 1000) z = z * (.9 + (FireEffect / 10000.1));
if (RValve < -1000) z = z * .85;
if (CValve < -1000) z = z * .85;
if (IValve < -1000) z = z * .85;
SM = 1.0;
if ((CityPop == 0) || (deltaCityPop == 0))
SM = 1.0;
else if (deltaCityPop == CityPop)
SM = 1.0;
else if (deltaCityPop > 0)
SM = ((float)deltaCityPop/CityPop) + 1.0;
else if (deltaCityPop < 0)
SM = .95 + ((float) deltaCityPop/(CityPop - deltaCityPop));
z = z * SM;
z = z - GetFire(); /* dec score for fires */
z = z - (CityTax);
TM = unPwrdZCnt + PwrdZCnt; /* dec score for unpowered zones */
if (TM) SM = PwrdZCnt / TM;
else SM = 1.0;
z = z * SM;
if (z > 1000) z = 1000;
if (z < 0 ) z = 0;
CityScore = (CityScore + z) / 2;
deltaCityScore = CityScore - OldCityScore;
}
/* comefrom: CityEvaluation */
DoVotes(void)
{
register z;
CityYes = 0;
CityNo = 0;
for (z = 0; z < 100; z++) {
if (Rand(1000) < CityScore)
CityYes++;
else
CityNo++;
}
}
| 0 | 0.732716 | 1 | 0.732716 | game-dev | MEDIA | 0.782834 | game-dev | 0.939047 | 1 | 0.939047 |
LordOfDragons/dragengine | 4,654 | src/deigde/editors/gameDefinition/src/gamedef/objectClass/forceField/gdeOCForceField.cpp | /*
* MIT License
*
* Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gdeOCForceField.h"
#include <dragengine/common/exceptions.h>
// Class gdeOCForceField
//////////////////////////
// Constructor, destructor
////////////////////////////
gdeOCForceField::gdeOCForceField() :
pRadius( 1.0f ),
pExponent( 1.0f ),
pFieldType( deForceField::eftRadial ),
pApplicationType( deForceField::eatDirect ),
pForce( 1.0f ),
pFluctuationDirection( 0.0f ),
pFluctuationForce( 0.0f ),
pEnabled( true ){
}
gdeOCForceField::gdeOCForceField( const gdeOCForceField &field ) :
pPosition( field.pPosition ),
pRotation( field.pRotation ),
pBoneName( field.pBoneName ),
pInfluenceArea( field.pInfluenceArea ),
pRadius( field.pRadius ),
pExponent( field.pExponent ),
pFieldType( field.pFieldType ),
pApplicationType( field.pApplicationType ),
pDirection( field.pDirection ),
pForce( field.pForce ),
pFluctuationDirection( field.pFluctuationDirection ),
pFluctuationForce( field.pFluctuationForce ),
pShape( field.pShape ),
pEnabled( field.pEnabled )
{
int i;
for( i=0; i<=epAttachRotation; i++ ){
pPropertyNames[ i ] = field.pPropertyNames[ i ];
}
for( i=etEnabled; i<=etEnabled; i++ ){
pTriggerNames[ i ] = field.pTriggerNames[ i ];
}
}
gdeOCForceField::~gdeOCForceField(){
}
// Management
///////////////
void gdeOCForceField::SetPosition( const decVector &position ){
pPosition = position;
}
void gdeOCForceField::SetRotation( const decVector &orientation ){
pRotation = orientation;
}
void gdeOCForceField::SetBoneName( const char *boneName ){
pBoneName = boneName;
}
void gdeOCForceField::SetInfluenceArea( const decShapeList &area ){
pInfluenceArea = area;
}
void gdeOCForceField::SetRadius( float radius ){
pRadius = decMath::max( radius, 0.0f );
}
void gdeOCForceField::SetExponent( float exponent ){
pExponent = decMath::max( exponent, 0.0f );
}
void gdeOCForceField::SetFieldType( deForceField::eFieldTypes type ){
pFieldType = type;
}
void gdeOCForceField::SetApplicationType( deForceField::eApplicationTypes type ){
pApplicationType = type;
}
void gdeOCForceField::SetDirection( const decVector &direction ){
pDirection = direction;
}
void gdeOCForceField::SetForce( float force ){
pForce = force;
}
void gdeOCForceField::SetFluctuationDirection( float fluctuation ){
pFluctuationDirection = fluctuation;
}
void gdeOCForceField::SetFluctuationForce( float fluctuation ){
pFluctuationForce = fluctuation;
}
void gdeOCForceField::SetShape( const decShapeList &shape ){
pShape = shape;
}
void gdeOCForceField::SetEnabled( bool enabled ){
pEnabled = enabled;
}
bool gdeOCForceField::IsPropertySet( eProperties property ) const{
return ! pPropertyNames[ property ].IsEmpty();
}
const decString &gdeOCForceField::GetPropertyName( eProperties property ) const{
return pPropertyNames[ property ];
}
void gdeOCForceField::SetPropertyName( eProperties property, const char *name ){
pPropertyNames[ property ] = name;
}
bool gdeOCForceField::HasPropertyWithName( const char *name ) const{
int i;
for( i=0; i<=epAttachRotation; i++ ){
if( pPropertyNames[ i ] == name ){
return true;
}
}
return false;
}
bool gdeOCForceField::IsTriggerSet( eTriggers trigger ) const{
return ! pTriggerNames[ trigger ].IsEmpty();
}
const decString &gdeOCForceField::GetTriggerName( eTriggers trigger ) const{
return pTriggerNames[ trigger ];
}
void gdeOCForceField::SetTriggerName( eTriggers trigger, const char *name ){
pTriggerNames[ trigger ] = name;
}
| 0 | 0.969805 | 1 | 0.969805 | game-dev | MEDIA | 0.837651 | game-dev | 0.988088 | 1 | 0.988088 |
fynv/Three.V8 | 6,834 | game/RubiksCube.js | class RubiksCube
{
constructor()
{
this.reset();
}
reset()
{
this.map = Array.from(Array(6*9).keys());
this.dirs = Array(6*9).fill(0);
}
clone(input)
{
this.map = [...input.map];
this.dirs = [...input.dirs];
return this;
}
multiply(input)
{
let map_old = [...this.map];
let dirs_old = [...this.dirs];
for (let i = 0; i < 6 * 9; i++)
{
let j = input.map[i];
let ddir = input.dirs[i];
this.map[i] = map_old[j];
this.dirs[i] = (dirs_old[j] + ddir) % 4;
}
return this;
}
divide(input)
{
let map_old = [...this.map];
let dirs_old = [...this.dirs];
for (let i = 0; i < 6 * 9; i++)
{
let j = input.map[i];
let ddir = input.dirs[i];
this.map[j] = map_old[i];
this.dirs[j] = (dirs_old[i] + 4 - ddir) % 4;
}
return this;
}
static s_Initialize()
{
this.s_cube_o = new RubiksCube();
let text = fileLoader.loadTextFile("bases.json");
let base_data = JSON.parse(text);
this.s_bases = new Array(18);
for (let i =0; i<18; i++)
{
this.s_bases[i] = new RubiksCube();
this.s_bases[i].map = base_data[i].map;
this.s_bases[i].dirs = base_data[i].dirs;
}
this.s_RCW = new RubiksCube();
this.s_RCW.multiply(this.s_bases[0]);
this.s_RCCW = new RubiksCube();
this.s_RCCW.multiply(this.s_bases[5]);
this.s_R2CW = new RubiksCube();
this.s_R2CW.multiply(this.s_bases[0]);
this.s_R2CW.multiply(this.s_bases[1]);
this.s_R2CCW = new RubiksCube();
this.s_R2CCW.multiply(this.s_bases[5]);
this.s_R2CCW.multiply(this.s_bases[4]);
this.s_LCW = new RubiksCube();
this.s_LCW.multiply(this.s_bases[3]);
this.s_LCCW = new RubiksCube();
this.s_LCCW.multiply(this.s_bases[2]);
this.s_L2CW = new RubiksCube();
this.s_L2CW.multiply(this.s_bases[3]);
this.s_L2CW.multiply(this.s_bases[4]);
this.s_L2CCW = new RubiksCube();
this.s_L2CCW.multiply(this.s_bases[2]);
this.s_L2CCW.multiply(this.s_bases[1]);
this.s_UCW = new RubiksCube();
this.s_UCW.multiply(this.s_bases[6]);
this.s_UCCW = new RubiksCube();
this.s_UCCW.multiply(this.s_bases[11]);
this.s_U2CW = new RubiksCube();
this.s_U2CW.multiply(this.s_bases[6]);
this.s_U2CW.multiply(this.s_bases[7]);
this.s_U2CCW = new RubiksCube();
this.s_U2CCW.multiply(this.s_bases[11]);
this.s_U2CCW.multiply(this.s_bases[10]);
this.s_DCW = new RubiksCube();
this.s_DCW.multiply(this.s_bases[9]);
this.s_DCCW = new RubiksCube();
this.s_DCCW.multiply(this.s_bases[8]);
this.s_D2CW = new RubiksCube();
this.s_D2CW.multiply(this.s_bases[9]);
this.s_D2CW.multiply(this.s_bases[10]);
this.s_D2CCW = new RubiksCube();
this.s_D2CCW.multiply(this.s_bases[8]);
this.s_D2CCW.multiply(this.s_bases[7]);
this.s_FCW = new RubiksCube();
this.s_FCW.multiply(this.s_bases[12]);
this.s_FCCW = new RubiksCube();
this.s_FCCW.multiply(this.s_bases[17]);
this.s_F2CW = new RubiksCube();
this.s_F2CW.multiply(this.s_bases[12]);
this.s_F2CW.multiply(this.s_bases[13]);
this.s_F2CCW = new RubiksCube();
this.s_F2CCW.multiply(this.s_bases[17]);
this.s_F2CCW.multiply(this.s_bases[16]);
this.s_BCW = new RubiksCube();
this.s_BCW.multiply(this.s_bases[15]);
this.s_BCCW = new RubiksCube();
this.s_BCCW.multiply(this.s_bases[14]);
this.s_B2CW = new RubiksCube();
this.s_B2CW.multiply(this.s_bases[15]);
this.s_B2CW.multiply(this.s_bases[16]);
this.s_B2CCW = new RubiksCube();
this.s_B2CCW.multiply(this.s_bases[14]);
this.s_B2CCW.multiply(this.s_bases[13]);
this.s_op_map = {};
this.s_op_map['R'] = [ this.s_RCW, this.s_RCCW ]; this.s_op_map['r'] = [ this.s_R2CW, this.s_R2CCW ];
this.s_op_map['L'] = [ this.s_LCW, this.s_LCCW ]; this.s_op_map['l'] = [ this.s_L2CW, this.s_L2CCW ];
this.s_op_map['U'] = [ this.s_UCW, this.s_UCCW ]; this.s_op_map['u'] = [ this.s_U2CW, this.s_U2CCW ];
this.s_op_map['D'] = [ this.s_DCW, this.s_DCCW ]; this.s_op_map['d'] = [ this.s_D2CW, this.s_D2CCW ];
this.s_op_map['F'] = [ this.s_FCW, this.s_FCCW ]; this.s_op_map['f'] = [ this.s_F2CW, this.s_F2CCW ];
this.s_op_map['B'] = [ this.s_BCW, this.s_BCCW ]; this.s_op_map['b'] = [ this.s_B2CW, this.s_B2CCW ];
}
static parse_seq(seq)
{
let operations = [];
let notes = [];
let groups = [];
let group_id = 0;
let in_group = false;
for (let i = 0; i < seq.length; i++)
{
let c = seq[i];
let op = null;
let note = "";
if (this.s_op_map.hasOwnProperty(c))
{
if (i < seq.length - 1 && (seq[i + 1] == '\'' || seq[i + 1] == '`'))
{
op = this.s_op_map[c][1];
note = c + "\'";
}
else
{
op = this.s_op_map[c][0];
note = c;
}
let count = 1;
if (i < seq.length - 1 && seq[i + 1] == '2')
{
count = 2;
i++;
}
if (!in_group) group_id++;
for (let j = 0; j < count; j++)
{
operations.push(op);
notes.push(note);
groups.push(group_id);
}
}
else if (c == '(')
{
in_group = true;
group_id++;
}
else if (c == ')')
{
in_group = false;
}
}
return {
operations,
notes,
groups
};
}
exec_seq(seq)
{
let res = RubiksCube.parse_seq(seq);
for (let op of res.operations)
{
this.multiply(op);
}
}
}
export { RubiksCube };
| 0 | 0.871296 | 1 | 0.871296 | game-dev | MEDIA | 0.209718 | game-dev | 0.863489 | 1 | 0.863489 |
ryzom/ryzomcore | 3,439 | ryzom/common/src/game_share/body.h | // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef RY_BODY_H
#define RY_BODY_H
#include "nel/misc/types_nl.h"
//
#include "slot_equipment.h"
namespace BODY
{
/** Side of body
*/
enum TSide
{
Right = 0,
Left
};
/**
* describe the different body types, according to the considered entity
*/
enum TBodyType
{
Homin = 0,
Quadruped,
LandKitin,
FlyingKitin,
Fish,
Bird,
Plant,
NbBodyTypes,
UnknownBodyType = NbBodyTypes,
};
/**
* Following enum describe the body parts according to considered entity (body) type
* MUST be always in this order (regarding slot)
*
* HEAD
* CHEST
* ARMS
* HANDS
* LEGS
* FEET
* NbBodySlotParts = 6
*/
enum TBodyPart
{
BeginHomin = 0,
HHead = BeginHomin,
HChest,
HArms,
HHands,
HLegs,
HFeet,
EndHomin = HFeet,
BeginQuadruped,
QHead = BeginQuadruped,
QBody,
QFrontPaws,
QFrontHooves,
QRearPaws,
QRearHooves,
EndHomins = QRearHooves,
BeginLandKitin,
LKHead = BeginLandKitin,
LKBody,
LKFrontPaws1,
LKFrontPaws2,
LKRearPaws1,
LKRearPaws2,
EndLandKitin = LKRearPaws2,
BeginFlyingKitin,
FKHead = BeginFlyingKitin,
FKBody,
FKPaws1,
FKPaws2,
FKWings1,
FKWings2,
EndFlyingKitin = FKWings2,
BeginFish,
FHead = BeginFish,
FBody,
FFrontFins1,
FFrontFins2,
FRearFins1,
FRearFins2,
EndFish = FRearFins2,
BeginBird,
BHead = BeginBird,
BBody,
BFeet1,
BFeet2,
BWings1,
BWings2,
EndBird = BWings2,
BeginPlant,
PUpperTrunk = BeginPlant,
PTrunk,
PLeaves1,
PLeaves2,
PLowerTrunk,
PVisibleRoots,
EndPlant = PVisibleRoots,
NbBodyParts,
UnknownBodyPart = NbBodyParts,
};
/**
* get the localisation type from the input string
* \param str the input string
* \return the TBodyType associated to this string
*/
TBodyType toBodyType(const std::string &str);
/// convert a body type to a string
const std::string & toString(TBodyType type);
/**
* get the body part from the input string
* \param str the input string
* \return the TBodyPart associated to this string
*/
TBodyPart toBodyPart(const std::string &str);
/// convert a localisation to a string
const std::string & toString(TBodyPart part);
/// convert a body part to a slot type
SLOT_EQUIPMENT::TSlotEquipment toSlotEquipement(TBodyPart part);
/// get a body part from a body type and a slot type
TBodyPart getBodyPart( TBodyType type, SLOT_EQUIPMENT::TSlotEquipment slot);
// from any body part, gives the matching body part for homins, or UnknownBodyPart
TBodyPart getMatchingHominBodyPart(TBodyPart src);
}; // BODY
#endif // RY_BODY_H
/* End of body.h */
| 0 | 0.881717 | 1 | 0.881717 | game-dev | MEDIA | 0.685858 | game-dev | 0.682242 | 1 | 0.682242 |
emileb/OpenGames | 24,914 | opengames/src/main/jni/OpenJK/code/game/AI_Howler.cpp | /*
This file is part of Jedi Academy.
Jedi Academy 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.
Jedi Academy 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 Jedi Academy. If not, see <http://www.gnu.org/licenses/>.
*/
// Copyright 2001-2013 Raven Software
#include "b_local.h"
#include "../cgame/cg_camera.h"
// These define the working combat range for these suckers
#define MIN_DISTANCE 54
#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE )
#define MAX_DISTANCE 128
#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE )
#define LSTATE_CLEAR 0
#define LSTATE_WAITING 1
#define LSTATE_FLEE 2
#define LSTATE_BERZERK 3
#define HOWLER_RETREAT_DIST 300.0f
#define HOWLER_PANIC_HEALTH 10
extern void G_UcmdMoveForDir( gentity_t *self, usercmd_t *cmd, vec3_t dir );
extern void G_GetBoltPosition( gentity_t *self, int boltIndex, vec3_t pos, int modelIndex = 0 );
extern int PM_AnimLength( int index, animNumber_t anim );
extern qboolean NAV_DirSafe( gentity_t *self, vec3_t dir, float dist );
extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock );
extern float NPC_EntRangeFromBolt( gentity_t *targEnt, int boltIndex );
extern int NPC_GetEntsNearBolt( gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg );
extern qboolean PM_InKnockDown( playerState_t *ps );
extern qboolean PM_HasAnimation( gentity_t *ent, int animation );
static void Howler_Attack( float enemyDist, qboolean howl = qfalse );
/*
-------------------------
NPC_Howler_Precache
-------------------------
*/
void NPC_Howler_Precache( void )
{
int i;
//G_SoundIndex( "sound/chars/howler/howl.mp3" );
G_EffectIndex( "howler/sonic" );
G_SoundIndex( "sound/chars/howler/howl.mp3" );
for ( i = 1; i < 3; i++ )
{
G_SoundIndex( va( "sound/chars/howler/idle_hiss%d.mp3", i ) );
}
for ( i = 1; i < 6; i++ )
{
G_SoundIndex( va( "sound/chars/howler/howl_talk%d.mp3", i ) );
G_SoundIndex( va( "sound/chars/howler/howl_yell%d.mp3", i ) );
}
}
void Howler_ClearTimers( gentity_t *self )
{
//clear all my timers
TIMER_Set( self, "flee", -level.time );
TIMER_Set( self, "retreating", -level.time );
TIMER_Set( self, "standing", -level.time );
TIMER_Set( self, "walking", -level.time );
TIMER_Set( self, "running", -level.time );
TIMER_Set( self, "aggressionDecay", -level.time );
TIMER_Set( self, "speaking", -level.time );
}
static qboolean NPC_Howler_Move( int randomJumpChance = 0 )
{
if ( !TIMER_Done( NPC, "standing" ) )
{//standing around
return qfalse;
}
if ( NPC->client->ps.groundEntityNum == ENTITYNUM_NONE )
{//in air, don't do anything
return qfalse;
}
if ( (!NPC->enemy&&TIMER_Done( NPC, "running" )) || !TIMER_Done( NPC, "walking" ) )
{
ucmd.buttons |= BUTTON_WALKING;
}
if ( (!randomJumpChance||Q_irand( 0, randomJumpChance ))
&& NPC_MoveToGoal( qtrue ) )
{
if ( VectorCompare( NPC->client->ps.moveDir, vec3_origin )
|| !NPC->client->ps.speed )
{//uh.... wtf? Got there?
if ( NPCInfo->goalEntity )
{
NPC_FaceEntity( NPCInfo->goalEntity, qfalse );
}
else
{
NPC_UpdateAngles( qfalse, qtrue );
}
return qtrue;
}
//TEMP: don't want to strafe
VectorClear( NPC->client->ps.moveDir );
ucmd.rightmove = 0.0f;
// Com_Printf( "Howler moving %d\n",ucmd.forwardmove );
//if backing up, go slow...
if ( ucmd.forwardmove < 0.0f )
{
ucmd.buttons |= BUTTON_WALKING;
//if ( NPC->client->ps.speed > NPCInfo->stats.walkSpeed )
{//don't walk faster than I'm allowed to
NPC->client->ps.speed = NPCInfo->stats.walkSpeed;
}
}
else
{
if ( (ucmd.buttons&BUTTON_WALKING) )
{
NPC->client->ps.speed = NPCInfo->stats.walkSpeed;
}
else
{
NPC->client->ps.speed = NPCInfo->stats.runSpeed;
}
}
NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw = NPCInfo->lastPathAngles[YAW];
NPC_UpdateAngles( qfalse, qtrue );
}
else if ( NPCInfo->goalEntity )
{//couldn't get where we wanted to go, try to jump there
NPC_FaceEntity( NPCInfo->goalEntity, qfalse );
NPC_TryJump( NPCInfo->goalEntity, 400.0f, -256.0f );
}
return qtrue;
}
/*
-------------------------
Howler_Idle
-------------------------
*/
static void Howler_Idle( void )
{
}
/*
-------------------------
Howler_Patrol
-------------------------
*/
static void Howler_Patrol( void )
{
NPCInfo->localState = LSTATE_CLEAR;
//If we have somewhere to go, then do that
if ( UpdateGoal() )
{
NPC_Howler_Move( 100 );
}
vec3_t dif;
VectorSubtract( g_entities[0].currentOrigin, NPC->currentOrigin, dif );
if ( VectorLengthSquared( dif ) < 256 * 256 )
{
G_SetEnemy( NPC, &g_entities[0] );
}
if ( NPC_CheckEnemyExt( qtrue ) == qfalse )
{
Howler_Idle();
return;
}
Howler_Attack( 0.0f, qtrue );
}
/*
-------------------------
Howler_Move
-------------------------
*/
static qboolean Howler_Move( qboolean visible )
{
if ( NPCInfo->localState != LSTATE_WAITING )
{
NPCInfo->goalEntity = NPC->enemy;
NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range
return NPC_Howler_Move( 30 );
}
return qfalse;
}
//---------------------------------------------------------
static void Howler_TryDamage( int damage, qboolean tongue, qboolean knockdown )
{
vec3_t start, end, dir;
trace_t tr;
if ( tongue )
{
G_GetBoltPosition( NPC, NPC->genericBolt1, start );
G_GetBoltPosition( NPC, NPC->genericBolt2, end );
VectorSubtract( end, start, dir );
float dist = VectorNormalize( dir );
VectorMA( start, dist+16, dir, end );
}
else
{
VectorCopy( NPC->currentOrigin, start );
AngleVectors( NPC->currentAngles, dir, NULL, NULL );
VectorMA( start, MIN_DISTANCE*2, dir, end );
}
#ifndef FINAL_BUILD
if ( d_saberCombat->integer > 1 )
{
G_DebugLine(start, end, 1000, 0x000000ff, qtrue);
}
#endif
// Should probably trace from the mouth, but, ah well.
gi.trace( &tr, start, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 );
if ( tr.entityNum < ENTITYNUM_WORLD )
{//hit *something*
gentity_t *victim = &g_entities[tr.entityNum];
if ( !victim->client
|| victim->client->NPC_class != CLASS_HOWLER )
{//not another howler
if ( knockdown && victim->client )
{//only do damage if victim isn't knocked down. If he isn't, knock him down
if ( PM_InKnockDown( &victim->client->ps ) )
{
return;
}
}
//FIXME: some sort of damage effect (claws and tongue are cutting you... blood?)
G_Damage( victim, NPC, NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE );
if ( knockdown && victim->health > 0 )
{//victim still alive
G_Knockdown( victim, NPC, NPC->client->ps.velocity, 500, qfalse );
}
}
}
}
static void Howler_Howl( void )
{
gentity_t *radiusEnts[ 128 ];
int numEnts;
const float radius = (NPC->spawnflags&1)?256:128;
const float halfRadSquared = ((radius/2)*(radius/2));
const float radiusSquared = (radius*radius);
float distSq;
int i;
vec3_t boltOrg;
AddSoundEvent( NPC, NPC->currentOrigin, 512, AEL_DANGER, qfalse, qtrue );
numEnts = NPC_GetEntsNearBolt( radiusEnts, radius, NPC->handLBolt, boltOrg );
for ( i = 0; i < numEnts; i++ )
{
if ( !radiusEnts[i]->inuse )
{
continue;
}
if ( radiusEnts[i] == NPC )
{//Skip the rancor ent
continue;
}
if ( radiusEnts[i]->client == NULL )
{//must be a client
continue;
}
if ( radiusEnts[i]->client->NPC_class == CLASS_HOWLER )
{//other howlers immune
continue;
}
distSq = DistanceSquared( radiusEnts[i]->currentOrigin, boltOrg );
if ( distSq <= radiusSquared )
{
if ( distSq < halfRadSquared )
{//close enough to do damage, too
if ( Q_irand( 0, g_spskill->integer ) )
{//does no damage on easy, does 1 point every other frame on medium, more often on hard
G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, NPC->currentOrigin, 1, DAMAGE_NO_KNOCKBACK, MOD_IMPACT );
}
}
if ( radiusEnts[i]->health > 0
&& radiusEnts[i]->client
&& radiusEnts[i]->client->NPC_class != CLASS_RANCOR
&& radiusEnts[i]->client->NPC_class != CLASS_ATST
&& !PM_InKnockDown( &radiusEnts[i]->client->ps ) )
{
if ( PM_HasAnimation( radiusEnts[i], BOTH_SONICPAIN_START ) )
{
if ( radiusEnts[i]->client->ps.torsoAnim != BOTH_SONICPAIN_START
&& radiusEnts[i]->client->ps.torsoAnim != BOTH_SONICPAIN_HOLD )
{
NPC_SetAnim( radiusEnts[i], SETANIM_LEGS, BOTH_SONICPAIN_START, SETANIM_FLAG_NORMAL );
NPC_SetAnim( radiusEnts[i], SETANIM_TORSO, BOTH_SONICPAIN_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );
radiusEnts[i]->client->ps.torsoAnimTimer += 100;
radiusEnts[i]->client->ps.weaponTime = radiusEnts[i]->client->ps.torsoAnimTimer;
}
else if ( radiusEnts[i]->client->ps.torsoAnimTimer <= 100 )
{//at the end of the sonic pain start or hold anim
NPC_SetAnim( radiusEnts[i], SETANIM_LEGS, BOTH_SONICPAIN_HOLD, SETANIM_FLAG_NORMAL );
NPC_SetAnim( radiusEnts[i], SETANIM_TORSO, BOTH_SONICPAIN_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );
radiusEnts[i]->client->ps.torsoAnimTimer += 100;
radiusEnts[i]->client->ps.weaponTime = radiusEnts[i]->client->ps.torsoAnimTimer;
}
}
/*
else if ( distSq < halfRadSquared
&& radiusEnts[i]->client->ps.groundEntityNum != ENTITYNUM_NONE
&& !Q_irand( 0, 10 ) )//FIXME: base on skill
{//within range
G_Knockdown( radiusEnts[i], NPC, vec3_origin, 500, qfalse );
}
*/
}
}
}
float playerDist = NPC_EntRangeFromBolt( player, NPC->genericBolt1 );
if ( playerDist < 256.0f )
{
CGCam_Shake( 1.0f*playerDist/128.0f, 200 );
}
}
//------------------------------
static void Howler_Attack( float enemyDist, qboolean howl )
{
int dmg = (NPCInfo->localState==LSTATE_BERZERK)?5:2;
if ( !TIMER_Exists( NPC, "attacking" ))
{
int attackAnim = BOTH_GESTURE1;
// Going to do an attack
if ( NPC->enemy && NPC->enemy->client && PM_InKnockDown( &NPC->enemy->client->ps )
&& enemyDist <= MIN_DISTANCE )
{
attackAnim = BOTH_ATTACK2;
}
else if ( !Q_irand( 0, 4 ) || howl )
{//howl attack
//G_SoundOnEnt( NPC, CHAN_VOICE, "sound/chars/howler/howl.mp3" );
}
else if ( enemyDist > MIN_DISTANCE && Q_irand( 0, 1 ) )
{//lunge attack
//jump foward
vec3_t fwd, yawAng = {0, NPC->client->ps.viewangles[YAW], 0};
AngleVectors( yawAng, fwd, NULL, NULL );
VectorScale( fwd, (enemyDist*3.0f), NPC->client->ps.velocity );
NPC->client->ps.velocity[2] = 200;
NPC->client->ps.groundEntityNum = ENTITYNUM_NONE;
attackAnim = BOTH_ATTACK1;
}
else
{//tongue attack
attackAnim = BOTH_ATTACK2;
}
NPC_SetAnim( NPC, SETANIM_BOTH, attackAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART );
if ( NPCInfo->localState == LSTATE_BERZERK )
{//attack again right away
TIMER_Set( NPC, "attacking", NPC->client->ps.legsAnimTimer );
}
else
{
TIMER_Set( NPC, "attacking", NPC->client->ps.legsAnimTimer + Q_irand( 0, 1500 ) );//FIXME: base on skill
TIMER_Set( NPC, "standing", -level.time );
TIMER_Set( NPC, "walking", -level.time );
TIMER_Set( NPC, "running", NPC->client->ps.legsAnimTimer + 5000 );
}
TIMER_Set( NPC, "attack_dmg", 200 ); // level two damage
}
// Need to do delayed damage since the attack animations encapsulate multiple mini-attacks
switch ( NPC->client->ps.legsAnim )
{
case BOTH_ATTACK1:
case BOTH_MELEE1:
if ( NPC->client->ps.legsAnimTimer > 650//more than 13 frames left
&& PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t)NPC->client->ps.legsAnim ) - NPC->client->ps.legsAnimTimer >= 800 )//at least 16 frames into anim
{
Howler_TryDamage( dmg, qfalse, qfalse );
}
break;
case BOTH_ATTACK2:
case BOTH_MELEE2:
if ( NPC->client->ps.legsAnimTimer > 350//more than 7 frames left
&& PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t)NPC->client->ps.legsAnim ) - NPC->client->ps.legsAnimTimer >= 550 )//at least 11 frames into anim
{
Howler_TryDamage( dmg, qtrue, qfalse );
}
break;
case BOTH_GESTURE1:
{
if ( NPC->client->ps.legsAnimTimer > 1800//more than 36 frames left
&& PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t)NPC->client->ps.legsAnim ) - NPC->client->ps.legsAnimTimer >= 950 )//at least 19 frames into anim
{
Howler_Howl();
if ( !NPC->count )
{
G_PlayEffect( G_EffectIndex( "howler/sonic" ), NPC->playerModel, NPC->genericBolt1, NPC->s.number, NPC->currentOrigin, 4750, qtrue );
G_SoundOnEnt( NPC, CHAN_VOICE, "sound/chars/howler/howl.mp3" );
NPC->count = 1;
}
}
}
break;
default:
//anims seem to get reset after a load, so just stop attacking and it will restart as needed.
TIMER_Remove( NPC, "attacking" );
break;
}
// Just using this to remove the attacking flag at the right time
TIMER_Done2( NPC, "attacking", qtrue );
}
//----------------------------------
static void Howler_Combat( void )
{
qboolean faced = qfalse;
float distance;
qboolean advance = qfalse;
if ( NPC->client->ps.groundEntityNum == ENTITYNUM_NONE )
{//not on the ground
if ( NPC->client->ps.legsAnim == BOTH_JUMP1
|| NPC->client->ps.legsAnim == BOTH_INAIR1 )
{//flying through the air with the greatest of ease, etc
Howler_TryDamage( 10, qfalse, qfalse );
}
}
else
{//not in air, see if we should attack or advance
// If we cannot see our target or we have somewhere to go, then do that
if ( !NPC_ClearLOS( NPC->enemy ) )//|| UpdateGoal( ))
{
NPCInfo->goalEntity = NPC->enemy;
NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range
if ( NPCInfo->localState == LSTATE_BERZERK )
{
NPC_Howler_Move( 3 );
}
else
{
NPC_Howler_Move( 10 );
}
NPC_UpdateAngles( qfalse, qtrue );
return;
}
distance = DistanceHorizontal( NPC->currentOrigin, NPC->enemy->currentOrigin );
if ( NPC->enemy && NPC->enemy->client && PM_InKnockDown( &NPC->enemy->client->ps ) )
{//get really close to knocked down enemies
advance = (qboolean)( distance > MIN_DISTANCE ? qtrue : qfalse );
}
else
{
advance = (qboolean)( distance > MAX_DISTANCE ? qtrue : qfalse );//MIN_DISTANCE
}
if (( advance || NPCInfo->localState == LSTATE_WAITING ) && TIMER_Done( NPC, "attacking" )) // waiting monsters can't attack
{
if ( TIMER_Done2( NPC, "takingPain", qtrue ))
{
NPCInfo->localState = LSTATE_CLEAR;
}
else if ( TIMER_Done( NPC, "standing" ) )
{
faced = Howler_Move( 1 );
}
}
else
{
Howler_Attack( distance );
}
}
if ( !faced )
{
if ( //TIMER_Done( NPC, "standing" ) //not just standing there
//!advance //not moving
TIMER_Done( NPC, "attacking" ) )// not attacking
{//not standing around
// Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb
NPC_FaceEnemy( qtrue );
}
else
{
NPC_UpdateAngles( qfalse, qtrue );
}
}
}
/*
-------------------------
NPC_Howler_Pain
-------------------------
*/
void NPC_Howler_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc )
{
if ( !self || !self->NPC )
{
return;
}
if ( self->NPC->localState != LSTATE_BERZERK )//damage >= 10 )
{
self->NPC->stats.aggression += damage;
self->NPC->localState = LSTATE_WAITING;
TIMER_Remove( self, "attacking" );
VectorCopy( self->NPC->lastPathAngles, self->s.angles );
//if ( self->client->ps.legsAnim == BOTH_GESTURE1 )
{
G_StopEffect( G_EffectIndex( "howler/sonic" ), self->playerModel, self->genericBolt1, self->s.number );
}
NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD );
TIMER_Set( self, "takingPain", self->client->ps.legsAnimTimer );//2900 );
if ( self->health > HOWLER_PANIC_HEALTH )
{//still have some health left
if ( Q_irand( 0, self->max_health ) > self->health )//FIXME: or check damage?
{//back off!
TIMER_Set( self, "standing", -level.time );
TIMER_Set( self, "running", -level.time );
TIMER_Set( self, "walking", -level.time );
TIMER_Set( self, "retreating", Q_irand( 1000, 5000 ) );
}
else
{//go after him!
TIMER_Set( self, "standing", -level.time );
TIMER_Set( self, "running", self->client->ps.legsAnimTimer+Q_irand(3000,6000) );
TIMER_Set( self, "walking", -level.time );
TIMER_Set( self, "retreating", -level.time );
}
}
else if ( self->NPC )
{//panic!
if ( Q_irand( 0, 1 ) )
{//berzerk
self->NPC->localState = LSTATE_BERZERK;
}
else
{//flee
self->NPC->localState = LSTATE_FLEE;
TIMER_Set( self, "flee", Q_irand( 10000, 30000 ) );
}
}
}
}
/*
-------------------------
NPC_BSHowler_Default
-------------------------
*/
void NPC_BSHowler_Default( void )
{
if ( NPC->client->ps.legsAnim != BOTH_GESTURE1 )
{
NPC->count = 0;
}
//FIXME: if in jump, do damage in front and maybe knock them down?
if ( !TIMER_Done( NPC, "attacking" ) )
{
if ( NPC->enemy )
{
//NPC_FaceEnemy( qfalse );
Howler_Attack( Distance( NPC->enemy->currentOrigin, NPC->currentOrigin ) );
}
else
{
//NPC_UpdateAngles( qfalse, qtrue );
Howler_Attack( 0.0f );
}
NPC_UpdateAngles( qfalse, qtrue );
return;
}
if ( NPC->enemy )
{
if ( NPCInfo->stats.aggression > 0 )
{
if ( TIMER_Done( NPC, "aggressionDecay" ) )
{
NPCInfo->stats.aggression--;
TIMER_Set( NPC, "aggressionDecay", 500 );
}
}
if ( !TIMER_Done( NPC, "flee" )
&& NPC_BSFlee() ) //this can clear ENEMY
{//successfully trying to run away
return;
}
if ( NPC->enemy == NULL)
{
NPC_UpdateAngles( qfalse, qtrue );
return;
}
if ( NPCInfo->localState == LSTATE_FLEE )
{//we were fleeing, now done (either timer ran out or we cannot flee anymore
if ( NPC_ClearLOS( NPC->enemy ) )
{//if enemy is still around, go berzerk
NPCInfo->localState = LSTATE_BERZERK;
}
else
{//otherwise, lick our wounds?
NPCInfo->localState = LSTATE_CLEAR;
TIMER_Set( NPC, "standing", Q_irand( 3000, 10000 ) );
}
}
else if ( NPCInfo->localState == LSTATE_BERZERK )
{//go nuts!
}
else if ( NPCInfo->stats.aggression >= Q_irand( 75, 125 ) )
{//that's it, go nuts!
NPCInfo->localState = LSTATE_BERZERK;
}
else if ( !TIMER_Done( NPC, "retreating" ) )
{//trying to back off
NPC_FaceEnemy( qtrue );
if ( NPC->client->ps.speed > NPCInfo->stats.walkSpeed )
{
NPC->client->ps.speed = NPCInfo->stats.walkSpeed;
}
ucmd.buttons |= BUTTON_WALKING;
if ( Distance( NPC->enemy->currentOrigin, NPC->currentOrigin ) < HOWLER_RETREAT_DIST )
{//enemy is close
vec3_t moveDir;
AngleVectors( NPC->currentAngles, moveDir, NULL, NULL );
VectorScale( moveDir, -1, moveDir );
if ( !NAV_DirSafe( NPC, moveDir, 8 ) )
{//enemy is backing me up against a wall or ledge! Start to get really mad!
NPCInfo->stats.aggression += 2;
}
else
{//back off
ucmd.forwardmove = -127;
}
//enemy won't leave me alone, get mad...
NPCInfo->stats.aggression++;
}
return;
}
else if ( TIMER_Done( NPC, "standing" ) )
{//not standing around
if ( !(NPCInfo->last_ucmd.forwardmove)
&& !(NPCInfo->last_ucmd.rightmove) )
{//stood last frame
if ( TIMER_Done( NPC, "walking" )
&& TIMER_Done( NPC, "running" ) )
{//not walking or running
if ( Q_irand( 0, 2 ) )
{//run for a while
TIMER_Set( NPC, "walking", Q_irand( 4000, 8000 ) );
}
else
{//walk for a bit
TIMER_Set( NPC, "running", Q_irand( 2500, 5000 ) );
}
}
}
else if ( (NPCInfo->last_ucmd.buttons&BUTTON_WALKING) )
{//walked last frame
if ( TIMER_Done( NPC, "walking" ) )
{//just finished walking
if ( Q_irand( 0, 5 ) || DistanceSquared( NPC->enemy->currentOrigin, NPC->currentOrigin ) < MAX_DISTANCE_SQR )
{//run for a while
TIMER_Set( NPC, "running", Q_irand( 4000, 20000 ) );
}
else
{//stand for a bit
TIMER_Set( NPC, "standing", Q_irand( 2000, 6000 ) );
}
}
}
else
{//ran last frame
if ( TIMER_Done( NPC, "running" ) )
{//just finished running
if ( Q_irand( 0, 8 ) || DistanceSquared( NPC->enemy->currentOrigin, NPC->currentOrigin ) < MAX_DISTANCE_SQR )
{//walk for a while
TIMER_Set( NPC, "walking", Q_irand( 3000, 10000 ) );
}
else
{//stand for a bit
TIMER_Set( NPC, "standing", Q_irand( 2000, 6000 ) );
}
}
}
}
if ( NPC_ValidEnemy( NPC->enemy ) == qfalse )
{
TIMER_Remove( NPC, "lookForNewEnemy" );//make them look again right now
if ( !NPC->enemy->inuse || level.time - NPC->enemy->s.time > Q_irand( 10000, 15000 ) )
{//it's been a while since the enemy died, or enemy is completely gone, get bored with him
NPC->enemy = NULL;
Howler_Patrol();
NPC_UpdateAngles( qtrue, qtrue );
return;
}
}
if ( TIMER_Done( NPC, "lookForNewEnemy" ) )
{
gentity_t *sav_enemy = NPC->enemy;//FIXME: what about NPC->lastEnemy?
NPC->enemy = NULL;
gentity_t *newEnemy = NPC_CheckEnemy( NPCInfo->confusionTime < level.time, qfalse, qfalse );
NPC->enemy = sav_enemy;
if ( newEnemy && newEnemy != sav_enemy )
{//picked up a new enemy!
NPC->lastEnemy = NPC->enemy;
G_SetEnemy( NPC, newEnemy );
if ( NPC->enemy != NPC->lastEnemy )
{//clear this so that we only sniff the player the first time we pick them up
NPC->useDebounceTime = 0;
}
//hold this one for at least 5-15 seconds
TIMER_Set( NPC, "lookForNewEnemy", Q_irand( 5000, 15000 ) );
}
else
{//look again in 2-5 secs
TIMER_Set( NPC, "lookForNewEnemy", Q_irand( 2000, 5000 ) );
}
}
Howler_Combat();
if ( TIMER_Done( NPC, "speaking" ) )
{
if ( !TIMER_Done( NPC, "standing" )
|| !TIMER_Done( NPC, "retreating" ))
{
G_SoundOnEnt( NPC, CHAN_VOICE, va( "sound/chars/howler/idle_hiss%d.mp3", Q_irand( 1, 2 ) ) );
}
else if ( !TIMER_Done( NPC, "walking" )
|| NPCInfo->localState == LSTATE_FLEE )
{
G_SoundOnEnt( NPC, CHAN_VOICE, va( "sound/chars/howler/howl_talk%d.mp3", Q_irand( 1, 5 ) ) );
}
else
{
G_SoundOnEnt( NPC, CHAN_VOICE, va( "sound/chars/howler/howl_yell%d.mp3", Q_irand( 1, 5 ) ) );
}
if ( NPCInfo->localState == LSTATE_BERZERK
|| NPCInfo->localState == LSTATE_FLEE )
{
TIMER_Set( NPC, "speaking", Q_irand( 1000, 4000 ) );
}
else
{
TIMER_Set( NPC, "speaking", Q_irand( 3000, 8000 ) );
}
}
return;
}
else
{
if ( TIMER_Done( NPC, "speaking" ) )
{
if ( !Q_irand( 0, 3 ) )
{
G_SoundOnEnt( NPC, CHAN_VOICE, va( "sound/chars/howler/idle_hiss%d.mp3", Q_irand( 1, 2 ) ) );
}
else
{
G_SoundOnEnt( NPC, CHAN_VOICE, va( "sound/chars/howler/howl_talk%d.mp3", Q_irand( 1, 5 ) ) );
}
TIMER_Set( NPC, "speaking", Q_irand( 4000, 12000 ) );
}
if ( NPCInfo->stats.aggression > 0 )
{
if ( TIMER_Done( NPC, "aggressionDecay" ) )
{
NPCInfo->stats.aggression--;
TIMER_Set( NPC, "aggressionDecay", 200 );
}
}
if ( TIMER_Done( NPC, "standing" ) )
{//not standing around
if ( !(NPCInfo->last_ucmd.forwardmove)
&& !(NPCInfo->last_ucmd.rightmove) )
{//stood last frame
if ( TIMER_Done( NPC, "walking" )
&& TIMER_Done( NPC, "running" ) )
{//not walking or running
if ( NPCInfo->goalEntity )
{//have somewhere to go
if ( Q_irand( 0, 2 ) )
{//walk for a while
TIMER_Set( NPC, "walking", Q_irand( 3000, 10000 ) );
}
else
{//run for a bit
TIMER_Set( NPC, "running", Q_irand( 2500, 5000 ) );
}
}
}
}
else if ( (NPCInfo->last_ucmd.buttons&BUTTON_WALKING) )
{//walked last frame
if ( TIMER_Done( NPC, "walking" ) )
{//just finished walking
if ( Q_irand( 0, 3 ) )
{//run for a while
TIMER_Set( NPC, "running", Q_irand( 3000, 6000 ) );
}
else
{//stand for a bit
TIMER_Set( NPC, "standing", Q_irand( 2500, 5000 ) );
}
}
}
else
{//ran last frame
if ( TIMER_Done( NPC, "running" ) )
{//just finished running
if ( Q_irand( 0, 2 ) )
{//walk for a while
TIMER_Set( NPC, "walking", Q_irand( 6000, 15000 ) );
}
else
{//stand for a bit
TIMER_Set( NPC, "standing", Q_irand( 4000, 6000 ) );
}
}
}
}
if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES )
{
Howler_Patrol();
}
else
{
Howler_Idle();
}
}
NPC_UpdateAngles( qfalse, qtrue );
}
| 0 | 0.979763 | 1 | 0.979763 | game-dev | MEDIA | 0.989449 | game-dev | 0.983912 | 1 | 0.983912 |
kessiler/muOnline-season6 | 3,007 | gameServer/gameServer/KanturuMaya.cpp | // KanturuMaya.cpp: implementation of the CKanturuMaya class.
// GS-CS 1.00.90 JPN - finished
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "KanturuMaya.h"
#include "TMonsterSkillManager.h"
#include "LogProc.h"
#include "KanturuUtil.h"
static CKanturuUtil KANTURU_UTIL;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CKanturuMaya::CKanturuMaya()
{
this->Init();
}
CKanturuMaya::~CKanturuMaya()
{
return;
}
void CKanturuMaya::Init()
{
this->m_iMayaObjIndex = -1;
this->m_iMayaSkillTime = 0;
this->m_iIceStormCount = 0;
}
void CKanturuMaya::KanturuMayaAct_IceStorm(int iSkillUsingRate)
{
if ( (rand()%10000) > iSkillUsingRate )
return;
if ( this->m_iMayaObjIndex < 0 || this->m_iMayaObjIndex > OBJMAX ) // #errot change to OBJMAX-1
return;
for ( int iCount=OBJ_STARTUSERINDEX;iCount < OBJMAX;iCount++)
{
if ( gObj[iCount].Type == OBJ_USER &&
gObjIsConnected(iCount) &&
gObj[iCount].MapNumber == MAP_INDEX_KANTURU_BOSS )
{
KANTURU_UTIL.NotifyKanturuWideAreaAttack(this->m_iMayaObjIndex, iCount, 0);
TMonsterSkillManager::UseMonsterSkill(this->m_iMayaObjIndex, iCount, 31,-1,NULL);
this->m_iIceStormCount++;
}
}
LogAddTD("[ KANTURU ][ IceStorm ] Skill Using(%d) : Index(%d) %s",
this->m_iIceStormCount, this->m_iMayaObjIndex, gObj[this->m_iMayaObjIndex].Name);
}
//Season 4.5 identical
void CKanturuMaya::KanturuMayaAct_Hands()
{
int TickCount = GetTickCount() - this->m_iMayaSkillTime;
if ( TickCount < 20000 )
return;
this->m_iMayaSkillTime = GetTickCount();
if ( this->m_iMayaObjIndex < 0 || this->m_iMayaObjIndex > OBJMAX ) // #errot change to OBJMAX-1
return;
for ( int iCount=OBJ_STARTUSERINDEX;iCount < OBJMAX;iCount++)
{
if ( gObj[iCount].Type == OBJ_USER &&
gObjIsConnected(iCount) &&
gObj[iCount].MapNumber == MAP_INDEX_KANTURU_BOSS )
{
KANTURU_UTIL.NotifyKanturuWideAreaAttack(this->m_iMayaObjIndex, iCount, 1);
TMonsterSkillManager::UseMonsterSkill(this->m_iMayaObjIndex, iCount, 1,-1,NULL);
//#if(_GSCS==0)
if (gObj[iCount].pInventory[10].m_Type == ITEMGET(13,38) &&
gObj[iCount].pInventory[10].m_Durability != 0.0f )
{
continue;
}
if ( gObj[iCount].pInventory[11].m_Type == ITEMGET(13,38) &&
gObj[iCount].pInventory[11].m_Durability != 0.0f )
{
continue;
}
if ( gObj[iCount].MapNumber == MAP_INDEX_KANTURU_BOSS )
{
LPOBJ lpMayaHandObj = &gObj[this->m_iMayaObjIndex];
gObj[iCount].Life = 0;
gObjLifeCheck(&gObj[iCount], lpMayaHandObj, gObj[iCount].Life, 0, 0, 0, 0, 0);
LogAddTD("[ KANTURU ][ BrokenShower ] [%s][%s] User Dying cause NOT wearing MoonStone Pandent",
gObj[iCount].AccountID, gObj[iCount].Name);
}
//#endif
}
}
LogAddTD("[ KANTURU ][ BrokenShower ] Skill Using : Index(%d) %s",
this->m_iMayaObjIndex, gObj[this->m_iMayaObjIndex].Name);
} | 0 | 0.814694 | 1 | 0.814694 | game-dev | MEDIA | 0.827375 | game-dev | 0.976798 | 1 | 0.976798 |
JohnBaracuda/com.baracuda.runtime-monitoring | 8,182 | Runtime/Scripts/Core/Systems/MonitoringDisplay.cs | // Copyright (c) 2022 Jonathan Lang
using System;
using System.Text.RegularExpressions;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Baracuda.Monitoring.Systems
{
internal sealed class MonitoringDisplay : IMonitoringUI
{
#region Data
// State
private string _activeFilter;
private MonitoringUI _current;
#endregion
#region Setup
#if !DISABLE_MONITORING
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
#endif
private static void Initialize()
{
if (!(Monitor.UI is MonitoringDisplay uiManager))
{
return;
}
if (uiManager.GetCurrent<MonitoringUI>() != null)
{
return;
}
if (Monitor.Settings.MonitoringUIOverride != null)
{
var instance = Object.Instantiate(Monitor.Settings.MonitoringUIOverride);
Object.DontDestroyOnLoad(instance.gameObject);
}
else
{
var gameObject = new GameObject("Monitoring UI");
gameObject.AddComponent<MonitoringUIFallback>();
gameObject.hideFlags = Monitor.Settings.ShowRuntimeMonitoringObject
? HideFlags.None
: HideFlags.HideInHierarchy;
Object.DontDestroyOnLoad(gameObject);
}
}
#endregion
#region Visiblity
/// <summary>
/// Get or set the visibility of the current monitoring UI.
/// </summary>
public bool Visible
{
get => _current && _current.Visible;
set
{
if (!_current || _current.Visible == value)
{
return;
}
_current.Visible = value;
VisibleStateChanged?.Invoke(value);
}
}
public event Action<bool> VisibleStateChanged;
#endregion
#region Current
/// <summary>
/// Get the current monitoring UI instance
/// </summary>
public TMonitoringUI GetCurrent<TMonitoringUI>() where TMonitoringUI : MonitoringUI
{
return _current as TMonitoringUI;
}
public void SetActiveMonitoringUI(MonitoringUI monitoringUI)
{
if (monitoringUI == _current)
{
return;
}
if (_current != null)
{
if (Monitor.Settings.AllowMultipleUIInstances)
{
_current.gameObject.SetActive(false);
}
else
{
Object.Destroy(_current.gameObject);
}
}
_current = monitoringUI;
VisibleStateChanged?.Invoke(Visible);
}
#endregion
#region Filtering
private static readonly Regex onlyLetter =
new Regex(@"[^a-zA-Z0-9<>_]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public void ApplyFilter(string filterString)
{
_activeFilter = filterString;
Monitor.MonitoringUpdateEvents.ValidationUpdateEnabled = false;
var settings = Monitor.Settings;
var and = settings.FilterAppendSymbol;
var not = settings.FilterNegateSymbol.ToString();
var absolute = settings.FilterAbsoluteSymbol.ToString();
var tag = settings.FilterTagsSymbol.ToString();
var list = Monitor.Registry.GetMonitorHandles();
var filters = filterString.Split(and);
for (var i = 0; i < list.Count; i++)
{
var unit = list[i];
var unitEnabled = false;
for (var filterIndex = 0; filterIndex < filters.Length; filterIndex++)
{
var filter = filters[filterIndex];
var filterOnlyLetters = onlyLetter.Replace(filter, string.Empty);
var filterNoSpace = filter.Replace(" ", string.Empty);
unitEnabled = filterNoSpace.StartsWith(not);
if (filterNoSpace.StartsWith(absolute))
{
var absoluteFilter = filterNoSpace.Substring(1);
if (unit.Name.StartsWith(absoluteFilter))
{
unitEnabled = true;
}
goto End;
}
if (filterNoSpace.StartsWith(tag))
{
var tagFilter = filterNoSpace.Substring(1);
var customTags = unit.Profile.CustomTags;
if (string.IsNullOrWhiteSpace(tagFilter))
{
goto End;
}
for (var tagIndex = 0; tagIndex < customTags.Length; tagIndex++)
{
var customTag = customTags[tagIndex];
if (customTag.IndexOf(filterOnlyLetters, settings.FilterComparison) < 0)
{
continue;
}
unitEnabled = true;
goto End;
}
goto End;
}
if (unit.Name.IndexOf(filterOnlyLetters, settings.FilterComparison) >= 0)
{
unitEnabled = !filterNoSpace.StartsWith(not);
goto End;
}
if (unit.DisplayName.IndexOf(filterOnlyLetters, settings.FilterComparison) >= 0)
{
unitEnabled = !filterNoSpace.StartsWith(not);
goto End;
}
// Filter with tags.
var tags = unit.Profile.Tags;
for (var tagIndex = 0; tagIndex < tags.Length; tagIndex++)
{
if (tags[tagIndex].Replace(" ", string.Empty)
.IndexOf(filterOnlyLetters, settings.FilterComparison) < 0)
{
continue;
}
unitEnabled = !filterNoSpace.StartsWith(not);
goto End;
}
}
End:
unit.Enabled = unitEnabled;
}
}
public void ResetFilter()
{
if (string.IsNullOrWhiteSpace(_activeFilter))
{
return;
}
_activeFilter = null;
Monitor.MonitoringUpdateEvents.ValidationUpdateEnabled = true;
var units = Monitor.Registry.GetMonitorHandles();
for (var i = 0; i < units.Count; i++)
{
var unit = units[i];
unit.Enabled = unit.Profile.DefaultEnabled;
}
}
#endregion
#region Oboslete
[Obsolete]
public bool IsVisible()
{
return Visible;
}
[Obsolete]
public void Show()
{
Visible = true;
}
[Obsolete]
public void Hide()
{
Visible = false;
}
[Obsolete]
public bool ToggleDisplay()
{
Visible = !Visible;
return Visible;
}
[Obsolete]
public MonitoringUIController GetActiveUIController()
{
return _current as MonitoringUIController;
}
[Obsolete]
public TUIController GetActiveUIController<TUIController>() where TUIController : MonitoringUIController
{
return _current as TUIController;
}
[Obsolete]
public void CreateMonitoringUI()
{
}
#endregion
}
} | 0 | 0.872512 | 1 | 0.872512 | game-dev | MEDIA | 0.932152 | game-dev | 0.917656 | 1 | 0.917656 |
Gallasko/ColumbaEngine | 17,246 | import/SDL2_net-2.2.0/Xcode/macOS/SDL2.framework/Versions/A/Headers/SDL_thread.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_thread_h_
#define SDL_thread_h_
/**
* \file SDL_thread.h
*
* Header for the SDL thread management routines.
*/
#include <SDL2/SDL_stdinc.h>
#include <SDL2/SDL_error.h>
/* Thread synchronization primitives */
#include <SDL2/SDL_atomic.h>
#include <SDL2/SDL_mutex.h>
#if defined(__WIN32__)
#include <process.h> /* _beginthreadex() and _endthreadex() */
#endif
#if defined(__OS2__) /* for _beginthread() and _endthread() */
#ifndef __EMX__
#include <process.h>
#else
#include <stdlib.h>
#endif
#endif
#include <SDL2/begin_code.h>
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* The SDL thread structure, defined in SDL_thread.c */
struct SDL_Thread;
typedef struct SDL_Thread SDL_Thread;
/* The SDL thread ID */
typedef unsigned long SDL_threadID;
/* Thread local storage ID, 0 is the invalid ID */
typedef unsigned int SDL_TLSID;
/**
* The SDL thread priority.
*
* SDL will make system changes as necessary in order to apply the thread priority.
* Code which attempts to control thread state related to priority should be aware
* that calling SDL_SetThreadPriority may alter such state.
* SDL_HINT_THREAD_PRIORITY_POLICY can be used to control aspects of this behavior.
*
* \note On many systems you require special privileges to set high or time critical priority.
*/
typedef enum {
SDL_THREAD_PRIORITY_LOW,
SDL_THREAD_PRIORITY_NORMAL,
SDL_THREAD_PRIORITY_HIGH,
SDL_THREAD_PRIORITY_TIME_CRITICAL
} SDL_ThreadPriority;
/**
* The function passed to SDL_CreateThread().
*
* \param data what was passed as `data` to SDL_CreateThread()
* \returns a value that can be reported through SDL_WaitThread().
*/
typedef int (SDLCALL * SDL_ThreadFunction) (void *data);
#if defined(__WIN32__)
/**
* \file SDL_thread.h
*
* We compile SDL into a DLL. This means, that it's the DLL which
* creates a new thread for the calling process with the SDL_CreateThread()
* API. There is a problem with this, that only the RTL of the SDL2.DLL will
* be initialized for those threads, and not the RTL of the calling
* application!
*
* To solve this, we make a little hack here.
*
* We'll always use the caller's _beginthread() and _endthread() APIs to
* start a new thread. This way, if it's the SDL2.DLL which uses this API,
* then the RTL of SDL2.DLL will be used to create the new thread, and if it's
* the application, then the RTL of the application will be used.
*
* So, in short:
* Always use the _beginthread() and _endthread() of the calling runtime
* library!
*/
#define SDL_PASSED_BEGINTHREAD_ENDTHREAD
typedef uintptr_t (__cdecl * pfnSDL_CurrentBeginThread)
(void *, unsigned, unsigned (__stdcall *func)(void *),
void * /*arg*/, unsigned, unsigned * /* threadID */);
typedef void (__cdecl * pfnSDL_CurrentEndThread) (unsigned code);
#ifndef SDL_beginthread
#define SDL_beginthread _beginthreadex
#endif
#ifndef SDL_endthread
#define SDL_endthread _endthreadex
#endif
extern DECLSPEC SDL_Thread *SDLCALL
SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data,
pfnSDL_CurrentBeginThread pfnBeginThread,
pfnSDL_CurrentEndThread pfnEndThread);
extern DECLSPEC SDL_Thread *SDLCALL
SDL_CreateThreadWithStackSize(int (SDLCALL * fn) (void *),
const char *name, const size_t stacksize, void *data,
pfnSDL_CurrentBeginThread pfnBeginThread,
pfnSDL_CurrentEndThread pfnEndThread);
#if defined(SDL_CreateThread) && SDL_DYNAMIC_API
#undef SDL_CreateThread
#define SDL_CreateThread(fn, name, data) SDL_CreateThread_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread)
#undef SDL_CreateThreadWithStackSize
#define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize_REAL(fn, name, stacksize, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread)
#else
#define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread)
#define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize(fn, name, data, (pfnSDL_CurrentBeginThread)_beginthreadex, (pfnSDL_CurrentEndThread)SDL_endthread)
#endif
#elif defined(__OS2__)
/*
* just like the windows case above: We compile SDL2
* into a dll with Watcom's runtime statically linked.
*/
#define SDL_PASSED_BEGINTHREAD_ENDTHREAD
typedef int (*pfnSDL_CurrentBeginThread)(void (*func)(void *), void *, unsigned, void * /*arg*/);
typedef void (*pfnSDL_CurrentEndThread)(void);
#ifndef SDL_beginthread
#define SDL_beginthread _beginthread
#endif
#ifndef SDL_endthread
#define SDL_endthread _endthread
#endif
extern DECLSPEC SDL_Thread *SDLCALL
SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data,
pfnSDL_CurrentBeginThread pfnBeginThread,
pfnSDL_CurrentEndThread pfnEndThread);
extern DECLSPEC SDL_Thread *SDLCALL
SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, const size_t stacksize, void *data,
pfnSDL_CurrentBeginThread pfnBeginThread,
pfnSDL_CurrentEndThread pfnEndThread);
#if defined(SDL_CreateThread) && SDL_DYNAMIC_API
#undef SDL_CreateThread
#define SDL_CreateThread(fn, name, data) SDL_CreateThread_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread)
#undef SDL_CreateThreadWithStackSize
#define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread)
#else
#define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread)
#define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize(fn, name, stacksize, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread)
#endif
#else
/**
* Create a new thread with a default stack size.
*
* This is equivalent to calling:
*
* ```c
* SDL_CreateThreadWithStackSize(fn, name, 0, data);
* ```
*
* \param fn the SDL_ThreadFunction function to call in the new thread
* \param name the name of the thread
* \param data a pointer that is passed to `fn`
* \returns an opaque pointer to the new thread object on success, NULL if the
* new thread could not be created; call SDL_GetError() for more
* information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_CreateThreadWithStackSize
* \sa SDL_WaitThread
*/
extern DECLSPEC SDL_Thread *SDLCALL
SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data);
/**
* Create a new thread with a specific stack size.
*
* SDL makes an attempt to report `name` to the system, so that debuggers can
* display it. Not all platforms support this.
*
* Thread naming is a little complicated: Most systems have very small limits
* for the string length (Haiku has 32 bytes, Linux currently has 16, Visual
* C++ 6.0 has _nine_!), and possibly other arbitrary rules. You'll have to
* see what happens with your system's debugger. The name should be UTF-8 (but
* using the naming limits of C identifiers is a better bet). There are no
* requirements for thread naming conventions, so long as the string is
* null-terminated UTF-8, but these guidelines are helpful in choosing a name:
*
* https://stackoverflow.com/questions/149932/naming-conventions-for-threads
*
* If a system imposes requirements, SDL will try to munge the string for it
* (truncate, etc), but the original string contents will be available from
* SDL_GetThreadName().
*
* The size (in bytes) of the new stack can be specified. Zero means "use the
* system default" which might be wildly different between platforms. x86
* Linux generally defaults to eight megabytes, an embedded device might be a
* few kilobytes instead. You generally need to specify a stack that is a
* multiple of the system's page size (in many cases, this is 4 kilobytes, but
* check your system documentation).
*
* In SDL 2.1, stack size will be folded into the original SDL_CreateThread
* function, but for backwards compatibility, this is currently a separate
* function.
*
* \param fn the SDL_ThreadFunction function to call in the new thread
* \param name the name of the thread
* \param stacksize the size, in bytes, to allocate for the new thread stack.
* \param data a pointer that is passed to `fn`
* \returns an opaque pointer to the new thread object on success, NULL if the
* new thread could not be created; call SDL_GetError() for more
* information.
*
* \since This function is available since SDL 2.0.9.
*
* \sa SDL_WaitThread
*/
extern DECLSPEC SDL_Thread *SDLCALL
SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, const size_t stacksize, void *data);
#endif
/**
* Get the thread name as it was specified in SDL_CreateThread().
*
* This is internal memory, not to be freed by the caller, and remains valid
* until the specified thread is cleaned up by SDL_WaitThread().
*
* \param thread the thread to query
* \returns a pointer to a UTF-8 string that names the specified thread, or
* NULL if it doesn't have a name.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_CreateThread
*/
extern DECLSPEC const char *SDLCALL SDL_GetThreadName(SDL_Thread *thread);
/**
* Get the thread identifier for the current thread.
*
* This thread identifier is as reported by the underlying operating system.
* If SDL is running on a platform that does not support threads the return
* value will always be zero.
*
* This function also returns a valid thread ID when called from the main
* thread.
*
* \returns the ID of the current thread.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetThreadID
*/
extern DECLSPEC SDL_threadID SDLCALL SDL_ThreadID(void);
/**
* Get the thread identifier for the specified thread.
*
* This thread identifier is as reported by the underlying operating system.
* If SDL is running on a platform that does not support threads the return
* value will always be zero.
*
* \param thread the thread to query
* \returns the ID of the specified thread, or the ID of the current thread if
* `thread` is NULL.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_ThreadID
*/
extern DECLSPEC SDL_threadID SDLCALL SDL_GetThreadID(SDL_Thread * thread);
/**
* Set the priority for the current thread.
*
* Note that some platforms will not let you alter the priority (or at least,
* promote the thread to a higher priority) at all, and some require you to be
* an administrator account. Be prepared for this to fail.
*
* \param priority the SDL_ThreadPriority to set
* \returns 0 on success or a negative error code on failure; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*/
extern DECLSPEC int SDLCALL SDL_SetThreadPriority(SDL_ThreadPriority priority);
/**
* Wait for a thread to finish.
*
* Threads that haven't been detached will remain (as a "zombie") until this
* function cleans them up. Not doing so is a resource leak.
*
* Once a thread has been cleaned up through this function, the SDL_Thread
* that references it becomes invalid and should not be referenced again. As
* such, only one thread may call SDL_WaitThread() on another.
*
* The return code for the thread function is placed in the area pointed to by
* `status`, if `status` is not NULL.
*
* You may not wait on a thread that has been used in a call to
* SDL_DetachThread(). Use either that function or this one, but not both, or
* behavior is undefined.
*
* It is safe to pass a NULL thread to this function; it is a no-op.
*
* Note that the thread pointer is freed by this function and is not valid
* afterward.
*
* \param thread the SDL_Thread pointer that was returned from the
* SDL_CreateThread() call that started this thread
* \param status pointer to an integer that will receive the value returned
* from the thread function by its 'return', or NULL to not
* receive such value back.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_CreateThread
* \sa SDL_DetachThread
*/
extern DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread * thread, int *status);
/**
* Let a thread clean up on exit without intervention.
*
* A thread may be "detached" to signify that it should not remain until
* another thread has called SDL_WaitThread() on it. Detaching a thread is
* useful for long-running threads that nothing needs to synchronize with or
* further manage. When a detached thread is done, it simply goes away.
*
* There is no way to recover the return code of a detached thread. If you
* need this, don't detach the thread and instead use SDL_WaitThread().
*
* Once a thread is detached, you should usually assume the SDL_Thread isn't
* safe to reference again, as it will become invalid immediately upon the
* detached thread's exit, instead of remaining until someone has called
* SDL_WaitThread() to finally clean it up. As such, don't detach the same
* thread more than once.
*
* If a thread has already exited when passed to SDL_DetachThread(), it will
* stop waiting for a call to SDL_WaitThread() and clean up immediately. It is
* not safe to detach a thread that might be used with SDL_WaitThread().
*
* You may not call SDL_WaitThread() on a thread that has been detached. Use
* either that function or this one, but not both, or behavior is undefined.
*
* It is safe to pass NULL to this function; it is a no-op.
*
* \param thread the SDL_Thread pointer that was returned from the
* SDL_CreateThread() call that started this thread
*
* \since This function is available since SDL 2.0.2.
*
* \sa SDL_CreateThread
* \sa SDL_WaitThread
*/
extern DECLSPEC void SDLCALL SDL_DetachThread(SDL_Thread * thread);
/**
* Create a piece of thread-local storage.
*
* This creates an identifier that is globally visible to all threads but
* refers to data that is thread-specific.
*
* \returns the newly created thread local storage identifier or 0 on error.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_TLSGet
* \sa SDL_TLSSet
*/
extern DECLSPEC SDL_TLSID SDLCALL SDL_TLSCreate(void);
/**
* Get the current thread's value associated with a thread local storage ID.
*
* \param id the thread local storage ID
* \returns the value associated with the ID for the current thread or NULL if
* no value has been set; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_TLSCreate
* \sa SDL_TLSSet
*/
extern DECLSPEC void * SDLCALL SDL_TLSGet(SDL_TLSID id);
/**
* Set the current thread's value associated with a thread local storage ID.
*
* The function prototype for `destructor` is:
*
* ```c
* void destructor(void *value)
* ```
*
* where its parameter `value` is what was passed as `value` to SDL_TLSSet().
*
* \param id the thread local storage ID
* \param value the value to associate with the ID for the current thread
* \param destructor a function called when the thread exits, to free the
* value
* \returns 0 on success or a negative error code on failure; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_TLSCreate
* \sa SDL_TLSGet
*/
extern DECLSPEC int SDLCALL SDL_TLSSet(SDL_TLSID id, const void *value, void (SDLCALL *destructor)(void*));
/**
* Cleanup all TLS data for this thread.
*
* \since This function is available since SDL 2.0.16.
*/
extern DECLSPEC void SDLCALL SDL_TLSCleanup(void);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include <SDL2/close_code.h>
#endif /* SDL_thread_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.928474 | 1 | 0.928474 | game-dev | MEDIA | 0.337338 | game-dev | 0.584475 | 1 | 0.584475 |
b1inkie/dst-api | 2,239 | scripts_619045/brains/spiderqueenbrain.lua | require "behaviours/wander"
require "behaviours/chaseandattack"
require "behaviours/follow"
require "behaviours/doaction"
require "behaviours/minperiod"
local BrainCommon = require("brains/braincommon")
local SpiderQueenBrain = Class(Brain, function(self, inst)
Brain._ctor(self, inst)
end)
function SpiderQueenBrain:CanSpawnChild()
return self.inst:GetTimeAlive() > 5
and not self.inst.sg:HasStateTag("busy")
and self.inst.components.incrementalproducer and self.inst.components.incrementalproducer:CanProduce()
end
local BLOCKER_TAGS = {'blocker'}
local SPIDERDEN_TAGS = {"spiderden"}
local SPIDERQUEEN_TAGS = {"spiderqueen"}
function SpiderQueenBrain:CanPlantNest()
if self.inst:GetTimeAlive() > TUNING.SPIDERQUEEN_MINWANDERTIME then
local pt = Vector3(self.inst.Transform:GetWorldPosition())
local ents = TheSim:FindEntities(pt.x,pt.y,pt.z, 4, BLOCKER_TAGS)
local min_spacing = 3
for k, v in pairs(ents) do
if v ~= self.inst and v.entity:IsValid() and v.entity:IsVisible() then
if distsq( Vector3(v.Transform:GetWorldPosition()), pt) < min_spacing*min_spacing then
return false
end
end
end
local den = GetClosestInstWithTag(SPIDERDEN_TAGS, self.inst, TUNING.SPIDERQUEEN_MINDENSPACING)
local queen = GetClosestInstWithTag(SPIDERQUEEN_TAGS, self.inst, TUNING.SPIDERQUEEN_MINDENSPACING)
if den or queen then
return false
end
return true
end
return false
end
local MIN_FOLLOW = 10
local MAX_FOLLOW = 20
local MED_FOLLOW = 15
function SpiderQueenBrain:OnStart()
local root = PriorityNode(
{
BrainCommon.PanicTrigger(self.inst),
IfNode(function() return self:CanPlantNest() end, "can plant nest",
ActionNode(function() self.inst.sg:GoToState("makenest") end)),
IfNode(function() return self:CanSpawnChild() end, "needs follower",
ActionNode(function() self.inst.sg:GoToState("poop_pre") return SUCCESS end, "make child" )),
--SPIDERQUEEN_MINDENSPACING
ChaseAndAttack(self.inst, 60, 40, nil, nil, nil, TUNING.WINONA_CATAPULT_MAX_RANGE + TUNING.MAX_WALKABLE_PLATFORM_RADIUS + TUNING.WINONA_CATAPULT_KEEP_TARGET_BUFFER + 1),
Wander(self.inst),
}, 2)
self.bt = BT(self.inst, root)
end
return SpiderQueenBrain | 0 | 0.850362 | 1 | 0.850362 | game-dev | MEDIA | 0.853644 | game-dev | 0.933734 | 1 | 0.933734 |
Fundynamic/RealBot | 22,608 | dependencies/hlsdk-old/multiplayer/ricochet/cl_dll/inputw32.cpp | /***
*
* Copyright (c) 1999, 2000 Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
// inputw32.cpp-- windows 95/98/nt mouse and joystick code
#include "hud.h"
#include "cl_util.h"
#include "camera.h"
#include "kbutton.h"
#include "cvardef.h"
#include "usercmd.h"
#include "const.h"
#include "camera.h"
#include "in_defs.h"
#include "../engine/keydefs.h"
#include "view.h"
#include "windows.h"
#include "vgui_TeamFortressViewport.h"
#define MOUSE_BUTTON_COUNT 5
// Set this to 1 to show mouse cursor. Experimental
int g_iVisibleMouse = 0;
extern "C"
{
void DLLEXPORT IN_ActivateMouse( void );
void DLLEXPORT IN_DeactivateMouse( void );
void DLLEXPORT IN_MouseEvent (int mstate);
void DLLEXPORT IN_Accumulate (void);
void DLLEXPORT IN_ClearStates (void);
}
extern cl_enginefunc_t gEngfuncs;
extern int iMouseInUse;
extern kbutton_t in_strafe;
extern kbutton_t in_mlook;
extern kbutton_t in_speed;
extern kbutton_t in_jlook;
extern cvar_t *m_pitch;
extern cvar_t *m_yaw;
extern cvar_t *m_forward;
extern cvar_t *m_side;
extern cvar_t *lookstrafe;
extern cvar_t *lookspring;
extern cvar_t *cl_pitchdown;
extern cvar_t *cl_pitchup;
extern cvar_t *cl_yawspeed;
extern cvar_t *cl_sidespeed;
extern cvar_t *cl_forwardspeed;
extern cvar_t *cl_pitchspeed;
extern cvar_t *cl_movespeedkey;
// mouse variables
cvar_t *m_filter;
cvar_t *sensitivity;
int mouse_buttons;
int mouse_oldbuttonstate;
POINT current_pos;
int mouse_x, mouse_y, old_mouse_x, old_mouse_y, mx_accum, my_accum;
static int restore_spi;
static int originalmouseparms[3], newmouseparms[3] = {0, 0, 1};
static int mouseactive;
int mouseinitialized;
static int mouseparmsvalid;
static int mouseshowtoggle = 1;
// joystick defines and variables
// where should defines be moved?
#define JOY_ABSOLUTE_AXIS 0x00000000 // control like a joystick
#define JOY_RELATIVE_AXIS 0x00000010 // control like a mouse, spinner, trackball
#define JOY_MAX_AXES 6 // X, Y, Z, R, U, V
#define JOY_AXIS_X 0
#define JOY_AXIS_Y 1
#define JOY_AXIS_Z 2
#define JOY_AXIS_R 3
#define JOY_AXIS_U 4
#define JOY_AXIS_V 5
enum _ControlList
{
AxisNada = 0,
AxisForward,
AxisLook,
AxisSide,
AxisTurn
};
DWORD dwAxisFlags[JOY_MAX_AXES] =
{
JOY_RETURNX,
JOY_RETURNY,
JOY_RETURNZ,
JOY_RETURNR,
JOY_RETURNU,
JOY_RETURNV
};
DWORD dwAxisMap[ JOY_MAX_AXES ];
DWORD dwControlMap[ JOY_MAX_AXES ];
PDWORD pdwRawValue[ JOY_MAX_AXES ];
// none of these cvars are saved over a session
// this means that advanced controller configuration needs to be executed
// each time. this avoids any problems with getting back to a default usage
// or when changing from one controller to another. this way at least something
// works.
cvar_t *in_joystick;
cvar_t *joy_name;
cvar_t *joy_advanced;
cvar_t *joy_advaxisx;
cvar_t *joy_advaxisy;
cvar_t *joy_advaxisz;
cvar_t *joy_advaxisr;
cvar_t *joy_advaxisu;
cvar_t *joy_advaxisv;
cvar_t *joy_forwardthreshold;
cvar_t *joy_sidethreshold;
cvar_t *joy_pitchthreshold;
cvar_t *joy_yawthreshold;
cvar_t *joy_forwardsensitivity;
cvar_t *joy_sidesensitivity;
cvar_t *joy_pitchsensitivity;
cvar_t *joy_yawsensitivity;
cvar_t *joy_wwhack1;
cvar_t *joy_wwhack2;
int joy_avail, joy_advancedinit, joy_haspov;
DWORD joy_oldbuttonstate, joy_oldpovstate;
int joy_id;
DWORD joy_flags;
DWORD joy_numbuttons;
static JOYINFOEX ji;
/*
===========
Force_CenterView_f
===========
*/
void Force_CenterView_f (void)
{
vec3_t viewangles;
if (!iMouseInUse)
{
gEngfuncs.GetViewAngles( (float *)viewangles );
viewangles[PITCH] = 0;
gEngfuncs.SetViewAngles( (float *)viewangles );
}
}
/*
===========
IN_ActivateMouse
===========
*/
void DLLEXPORT IN_ActivateMouse (void)
{
if (mouseinitialized)
{
if (mouseparmsvalid)
restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0);
mouseactive = 1;
}
}
/*
===========
IN_DeactivateMouse
===========
*/
void DLLEXPORT IN_DeactivateMouse (void)
{
if (mouseinitialized)
{
if (restore_spi)
SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0);
mouseactive = 0;
}
}
/*
===========
IN_StartupMouse
===========
*/
void IN_StartupMouse (void)
{
if ( gEngfuncs.CheckParm ("-nomouse", NULL ) )
return;
mouseinitialized = 1;
mouseparmsvalid = SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0);
if (mouseparmsvalid)
{
if ( gEngfuncs.CheckParm ("-noforcemspd", NULL ) )
newmouseparms[2] = originalmouseparms[2];
if ( gEngfuncs.CheckParm ("-noforcemaccel", NULL ) )
{
newmouseparms[0] = originalmouseparms[0];
newmouseparms[1] = originalmouseparms[1];
}
if ( gEngfuncs.CheckParm ("-noforcemparms", NULL ) )
{
newmouseparms[0] = originalmouseparms[0];
newmouseparms[1] = originalmouseparms[1];
newmouseparms[2] = originalmouseparms[2];
}
}
mouse_buttons = MOUSE_BUTTON_COUNT;
}
/*
===========
IN_Shutdown
===========
*/
void IN_Shutdown (void)
{
IN_DeactivateMouse ();
}
/*
===========
IN_GetMousePos
Ask for mouse position from engine
===========
*/
void IN_GetMousePos( int *mx, int *my )
{
gEngfuncs.GetMousePosition( mx, my );
}
/*
===========
IN_ResetMouse
FIXME: Call through to engine?
===========
*/
void IN_ResetMouse( void )
{
SetCursorPos ( gEngfuncs.GetWindowCenterX(), gEngfuncs.GetWindowCenterY() );
}
/*
===========
IN_MouseEvent
===========
*/
void DLLEXPORT IN_MouseEvent (int mstate)
{
int i;
if ( iMouseInUse || g_iVisibleMouse )
return;
// perform button actions
for (i=0 ; i<mouse_buttons ; i++)
{
if ( (mstate & (1<<i)) &&
!(mouse_oldbuttonstate & (1<<i)) )
{
gEngfuncs.Key_Event (K_MOUSE1 + i, 1);
}
if ( !(mstate & (1<<i)) &&
(mouse_oldbuttonstate & (1<<i)) )
{
gEngfuncs.Key_Event (K_MOUSE1 + i, 0);
}
}
mouse_oldbuttonstate = mstate;
}
bool bCanMoveMouse ( void );
/*
===========
IN_MouseMove
===========
*/
void IN_MouseMove ( float frametime, usercmd_t *cmd)
{
int mx, my;
vec3_t viewangles;
gEngfuncs.GetViewAngles( (float *)viewangles );
// Ricochet: Don't let them move the mouse when they're in spectator mode
int iSpectator = !bCanMoveMouse();
//jjb - this disbles normal mouse control if the user is trying to
// move the camera
if ( !iMouseInUse && !g_iVisibleMouse && !iSpectator )
{
GetCursorPos (¤t_pos);
mx = current_pos.x - gEngfuncs.GetWindowCenterX() + mx_accum;
my = current_pos.y - gEngfuncs.GetWindowCenterY() + my_accum;
mx_accum = 0;
my_accum = 0;
if (m_filter->value)
{
mouse_x = (mx + old_mouse_x) * 0.5;
mouse_y = (my + old_mouse_y) * 0.5;
}
else
{
mouse_x = mx;
mouse_y = my;
}
old_mouse_x = mx;
old_mouse_y = my;
if ( gHUD.GetSensitivity() != 0 )
{
mouse_x *= gHUD.GetSensitivity();
mouse_y *= gHUD.GetSensitivity();
}
else
{
mouse_x *= sensitivity->value;
mouse_y *= sensitivity->value;
}
// add mouse X/Y movement to cmd
if ( (in_strafe.state & 1) || (lookstrafe->value && (in_mlook.state & 1) ))
cmd->sidemove += m_side->value * mouse_x;
else
viewangles[YAW] -= m_yaw->value * mouse_x;
if ( in_mlook.state & 1)
{
V_StopPitchDrift ();
}
if ( (in_mlook.state & 1) && !(in_strafe.state & 1))
{
viewangles[PITCH] += m_pitch->value * mouse_y;
if (viewangles[PITCH] > cl_pitchdown->value)
viewangles[PITCH] = cl_pitchdown->value;
if (viewangles[PITCH] < -cl_pitchup->value)
viewangles[PITCH] = -cl_pitchup->value;
}
else
{
if ((in_strafe.state & 1) && gEngfuncs.IsNoClipping() )
{
cmd->upmove -= m_forward->value * mouse_y;
}
else
{
cmd->forwardmove -= m_forward->value * mouse_y;
}
}
// if the mouse has moved, force it to the center, so there's room to move
if ( mx || my )
{
IN_ResetMouse();
}
}
gEngfuncs.SetViewAngles( (float *)viewangles );
/*
//#define TRACE_TEST
#if defined( TRACE_TEST )
{
int mx, my;
void V_Move( int mx, int my );
IN_GetMousePos( &mx, &my );
V_Move( mx, my );
}
#endif
*/
}
/*
===========
IN_Accumulate
===========
*/
void DLLEXPORT IN_Accumulate (void)
{
//only accumulate mouse if we are not moving the camera with the mouse
if ( !iMouseInUse && !g_iVisibleMouse )
{
if (mouseactive)
{
GetCursorPos (¤t_pos);
mx_accum += current_pos.x - gEngfuncs.GetWindowCenterX();
my_accum += current_pos.y - gEngfuncs.GetWindowCenterY();
// force the mouse to the center, so there's room to move
IN_ResetMouse();
}
}
}
/*
===================
IN_ClearStates
===================
*/
void DLLEXPORT IN_ClearStates (void)
{
if ( !mouseactive )
return;
mx_accum = 0;
my_accum = 0;
mouse_oldbuttonstate = 0;
}
/*
===============
IN_StartupJoystick
===============
*/
void IN_StartupJoystick (void)
{
int numdevs;
JOYCAPS jc;
MMRESULT mmr;
// assume no joystick
joy_avail = 0;
// abort startup if user requests no joystick
if ( gEngfuncs.CheckParm ("-nojoy", NULL ) )
return;
// verify joystick driver is present
if ((numdevs = joyGetNumDevs ()) == 0)
{
gEngfuncs.Con_DPrintf ("joystick not found -- driver not present\n\n");
return;
}
// cycle through the joystick ids for the first valid one
for (joy_id=0 ; joy_id<numdevs ; joy_id++)
{
memset (&ji, 0, sizeof(ji));
ji.dwSize = sizeof(ji);
ji.dwFlags = JOY_RETURNCENTERED;
if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR)
break;
}
// abort startup if we didn't find a valid joystick
if (mmr != JOYERR_NOERROR)
{
gEngfuncs.Con_DPrintf ("joystick not found -- no valid joysticks (%x)\n\n", mmr);
return;
}
// get the capabilities of the selected joystick
// abort startup if command fails
memset (&jc, 0, sizeof(jc));
if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR)
{
gEngfuncs.Con_DPrintf ("joystick not found -- invalid joystick capabilities (%x)\n\n", mmr);
return;
}
// save the joystick's number of buttons and POV status
joy_numbuttons = jc.wNumButtons;
joy_haspov = jc.wCaps & JOYCAPS_HASPOV;
// old button and POV states default to no buttons pressed
joy_oldbuttonstate = joy_oldpovstate = 0;
// mark the joystick as available and advanced initialization not completed
// this is needed as cvars are not available during initialization
gEngfuncs.Con_Printf ("joystick found\n\n", mmr);
joy_avail = 1;
joy_advancedinit = 0;
}
/*
===========
RawValuePointer
===========
*/
PDWORD RawValuePointer (int axis)
{
switch (axis)
{
case JOY_AXIS_X:
return &ji.dwXpos;
case JOY_AXIS_Y:
return &ji.dwYpos;
case JOY_AXIS_Z:
return &ji.dwZpos;
case JOY_AXIS_R:
return &ji.dwRpos;
case JOY_AXIS_U:
return &ji.dwUpos;
case JOY_AXIS_V:
return &ji.dwVpos;
}
// FIX: need to do some kind of error
return &ji.dwXpos;
}
/*
===========
Joy_AdvancedUpdate_f
===========
*/
void Joy_AdvancedUpdate_f (void)
{
// called once by IN_ReadJoystick and by user whenever an update is needed
// cvars are now available
int i;
DWORD dwTemp;
// initialize all the maps
for (i = 0; i < JOY_MAX_AXES; i++)
{
dwAxisMap[i] = AxisNada;
dwControlMap[i] = JOY_ABSOLUTE_AXIS;
pdwRawValue[i] = RawValuePointer(i);
}
if( joy_advanced->value == 0.0)
{
// default joystick initialization
// 2 axes only with joystick control
dwAxisMap[JOY_AXIS_X] = AxisTurn;
// dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS;
dwAxisMap[JOY_AXIS_Y] = AxisForward;
// dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS;
}
else
{
if ( strcmp ( joy_name->string, "joystick") != 0 )
{
// notify user of advanced controller
gEngfuncs.Con_Printf ("\n%s configured\n\n", joy_name->string);
}
// advanced initialization here
// data supplied by user via joy_axisn cvars
dwTemp = (DWORD) joy_advaxisx->value;
dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f;
dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS;
dwTemp = (DWORD) joy_advaxisy->value;
dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f;
dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS;
dwTemp = (DWORD) joy_advaxisz->value;
dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f;
dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS;
dwTemp = (DWORD) joy_advaxisr->value;
dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f;
dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS;
dwTemp = (DWORD) joy_advaxisu->value;
dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f;
dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS;
dwTemp = (DWORD) joy_advaxisv->value;
dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f;
dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS;
}
// compute the axes to collect from DirectInput
joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV;
for (i = 0; i < JOY_MAX_AXES; i++)
{
if (dwAxisMap[i] != AxisNada)
{
joy_flags |= dwAxisFlags[i];
}
}
}
/*
===========
IN_Commands
===========
*/
void IN_Commands (void)
{
int i, key_index;
DWORD buttonstate, povstate;
if (!joy_avail)
{
return;
}
// loop through the joystick buttons
// key a joystick event or auxillary event for higher number buttons for each state change
buttonstate = ji.dwButtons;
for (i=0 ; i < (int)joy_numbuttons ; i++)
{
if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) )
{
key_index = (i < 4) ? K_JOY1 : K_AUX1;
gEngfuncs.Key_Event (key_index + i, 1);
}
if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) )
{
key_index = (i < 4) ? K_JOY1 : K_AUX1;
gEngfuncs.Key_Event (key_index + i, 0);
}
}
joy_oldbuttonstate = buttonstate;
if (joy_haspov)
{
// convert POV information into 4 bits of state information
// this avoids any potential problems related to moving from one
// direction to another without going through the center position
povstate = 0;
if(ji.dwPOV != JOY_POVCENTERED)
{
if (ji.dwPOV == JOY_POVFORWARD)
povstate |= 0x01;
if (ji.dwPOV == JOY_POVRIGHT)
povstate |= 0x02;
if (ji.dwPOV == JOY_POVBACKWARD)
povstate |= 0x04;
if (ji.dwPOV == JOY_POVLEFT)
povstate |= 0x08;
}
// determine which bits have changed and key an auxillary event for each change
for (i=0 ; i < 4 ; i++)
{
if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) )
{
gEngfuncs.Key_Event (K_AUX29 + i, 1);
}
if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) )
{
gEngfuncs.Key_Event (K_AUX29 + i, 0);
}
}
joy_oldpovstate = povstate;
}
}
/*
===============
IN_ReadJoystick
===============
*/
int IN_ReadJoystick (void)
{
memset (&ji, 0, sizeof(ji));
ji.dwSize = sizeof(ji);
ji.dwFlags = joy_flags;
if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR)
{
// this is a hack -- there is a bug in the Logitech WingMan Warrior DirectInput Driver
// rather than having 32768 be the zero point, they have the zero point at 32668
// go figure -- anyway, now we get the full resolution out of the device
if (joy_wwhack1->value != 0.0)
{
ji.dwUpos += 100;
}
return 1;
}
else
{
// read error occurred
// turning off the joystick seems too harsh for 1 read error,\
// but what should be done?
// Con_Printf ("IN_ReadJoystick: no response\n");
// joy_avail = 0;
return 0;
}
}
/*
===========
IN_JoyMove
===========
*/
void IN_JoyMove ( float frametime, usercmd_t *cmd )
{
float speed, aspeed;
float fAxisValue, fTemp;
int i;
vec3_t viewangles;
gEngfuncs.GetViewAngles( (float *)viewangles );
// complete initialization if first time in
// this is needed as cvars are not available at initialization time
if( joy_advancedinit != 1 )
{
Joy_AdvancedUpdate_f();
joy_advancedinit = 1;
}
// verify joystick is available and that the user wants to use it
if (!joy_avail || !in_joystick->value)
{
return;
}
// collect the joystick data, if possible
if (IN_ReadJoystick () != 1)
{
return;
}
if (in_speed.state & 1)
speed = cl_movespeedkey->value;
else
speed = 1;
aspeed = speed * frametime;
// loop through the axes
for (i = 0; i < JOY_MAX_AXES; i++)
{
// get the floating point zero-centered, potentially-inverted data for the current axis
fAxisValue = (float) *pdwRawValue[i];
// move centerpoint to zero
fAxisValue -= 32768.0;
if (joy_wwhack2->value != 0.0)
{
if (dwAxisMap[i] == AxisTurn)
{
// this is a special formula for the Logitech WingMan Warrior
// y=ax^b; where a = 300 and b = 1.3
// also x values are in increments of 800 (so this is factored out)
// then bounds check result to level out excessively high spin rates
fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3);
if (fTemp > 14000.0)
fTemp = 14000.0;
// restore direction information
fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp;
}
}
// convert range from -32768..32767 to -1..1
fAxisValue /= 32768.0;
switch (dwAxisMap[i])
{
case AxisForward:
if ((joy_advanced->value == 0.0) && (in_jlook.state & 1))
{
// user wants forward control to become look control
if (fabs(fAxisValue) > joy_pitchthreshold->value)
{
// if mouse invert is on, invert the joystick pitch value
// only absolute control support here (joy_advanced is 0)
if (m_pitch->value < 0.0)
{
viewangles[PITCH] -= (fAxisValue * joy_pitchsensitivity->value) * aspeed * cl_pitchspeed->value;
}
else
{
viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity->value) * aspeed * cl_pitchspeed->value;
}
V_StopPitchDrift();
}
else
{
// no pitch movement
// disable pitch return-to-center unless requested by user
// *** this code can be removed when the lookspring bug is fixed
// *** the bug always has the lookspring feature on
if(lookspring->value == 0.0)
{
V_StopPitchDrift();
}
}
}
else
{
// user wants forward control to be forward control
if (fabs(fAxisValue) > joy_forwardthreshold->value)
{
cmd->forwardmove += (fAxisValue * joy_forwardsensitivity->value) * speed * cl_forwardspeed->value;
}
}
break;
case AxisSide:
if (fabs(fAxisValue) > joy_sidethreshold->value)
{
cmd->sidemove += (fAxisValue * joy_sidesensitivity->value) * speed * cl_sidespeed->value;
}
break;
case AxisTurn:
if ((in_strafe.state & 1) || (lookstrafe->value && (in_jlook.state & 1)))
{
// user wants turn control to become side control
if (fabs(fAxisValue) > joy_sidethreshold->value)
{
cmd->sidemove -= (fAxisValue * joy_sidesensitivity->value) * speed * cl_sidespeed->value;
}
}
else
{
// user wants turn control to be turn control
if (fabs(fAxisValue) > joy_yawthreshold->value)
{
if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
{
viewangles[YAW] += (fAxisValue * joy_yawsensitivity->value) * aspeed * cl_yawspeed->value;
}
else
{
viewangles[YAW] += (fAxisValue * joy_yawsensitivity->value) * speed * 180.0;
}
}
}
break;
case AxisLook:
if (in_jlook.state & 1)
{
if (fabs(fAxisValue) > joy_pitchthreshold->value)
{
// pitch movement detected and pitch movement desired by user
if(dwControlMap[i] == JOY_ABSOLUTE_AXIS)
{
viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity->value) * aspeed * cl_pitchspeed->value;
}
else
{
viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity->value) * speed * 180.0;
}
V_StopPitchDrift();
}
else
{
// no pitch movement
// disable pitch return-to-center unless requested by user
// *** this code can be removed when the lookspring bug is fixed
// *** the bug always has the lookspring feature on
if( lookspring->value == 0.0 )
{
V_StopPitchDrift();
}
}
}
break;
default:
break;
}
}
// bounds check pitch
if (viewangles[PITCH] > cl_pitchdown->value)
viewangles[PITCH] = cl_pitchdown->value;
if (viewangles[PITCH] < -cl_pitchup->value)
viewangles[PITCH] = -cl_pitchup->value;
gEngfuncs.SetViewAngles( (float *)viewangles );
}
/*
===========
IN_Move
===========
*/
void IN_Move ( float frametime, usercmd_t *cmd)
{
if ( !iMouseInUse && mouseactive )
{
IN_MouseMove ( frametime, cmd);
}
IN_JoyMove ( frametime, cmd);
}
/*
===========
IN_Init
===========
*/
void IN_Init (void)
{
m_filter = gEngfuncs.pfnRegisterVariable ( "m_filter","0", FCVAR_ARCHIVE );
sensitivity = gEngfuncs.pfnRegisterVariable ( "sensitivity","3", FCVAR_ARCHIVE ); // user mouse sensitivity setting.
in_joystick = gEngfuncs.pfnRegisterVariable ( "joystick","0", FCVAR_ARCHIVE );
joy_name = gEngfuncs.pfnRegisterVariable ( "joyname", "joystick", 0 );
joy_advanced = gEngfuncs.pfnRegisterVariable ( "joyadvanced", "0", 0 );
joy_advaxisx = gEngfuncs.pfnRegisterVariable ( "joyadvaxisx", "0", 0 );
joy_advaxisy = gEngfuncs.pfnRegisterVariable ( "joyadvaxisy", "0", 0 );
joy_advaxisz = gEngfuncs.pfnRegisterVariable ( "joyadvaxisz", "0", 0 );
joy_advaxisr = gEngfuncs.pfnRegisterVariable ( "joyadvaxisr", "0", 0 );
joy_advaxisu = gEngfuncs.pfnRegisterVariable ( "joyadvaxisu", "0", 0 );
joy_advaxisv = gEngfuncs.pfnRegisterVariable ( "joyadvaxisv", "0", 0 );
joy_forwardthreshold = gEngfuncs.pfnRegisterVariable ( "joyforwardthreshold", "0.15", 0 );
joy_sidethreshold = gEngfuncs.pfnRegisterVariable ( "joysidethreshold", "0.15", 0 );
joy_pitchthreshold = gEngfuncs.pfnRegisterVariable ( "joypitchthreshold", "0.15", 0 );
joy_yawthreshold = gEngfuncs.pfnRegisterVariable ( "joyyawthreshold", "0.15", 0 );
joy_forwardsensitivity = gEngfuncs.pfnRegisterVariable ( "joyforwardsensitivity", "-1.0", 0 );
joy_sidesensitivity = gEngfuncs.pfnRegisterVariable ( "joysidesensitivity", "-1.0", 0 );
joy_pitchsensitivity = gEngfuncs.pfnRegisterVariable ( "joypitchsensitivity", "1.0", 0 );
joy_yawsensitivity = gEngfuncs.pfnRegisterVariable ( "joyyawsensitivity", "-1.0", 0 );
joy_wwhack1 = gEngfuncs.pfnRegisterVariable ( "joywwhack1", "0.0", 0 );
joy_wwhack2 = gEngfuncs.pfnRegisterVariable ( "joywwhack2", "0.0", 0 );
gEngfuncs.pfnAddCommand ("force_centerview", Force_CenterView_f);
gEngfuncs.pfnAddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f);
IN_StartupMouse ();
IN_StartupJoystick ();
}
| 0 | 0.911913 | 1 | 0.911913 | game-dev | MEDIA | 0.456991 | game-dev | 0.904911 | 1 | 0.904911 |
SimonGaufreteau/ZygorGuidesViewer | 20,126 | Libs/AceGUI-3.0/widgets/AceGUIWidget-TreeGroup.lua | local AceGUI = LibStub('AceGUI-3.0')
-- Recycling functions
local new, del
do
local pool = setmetatable({}, { __mode = 'k' })
function new()
local t = next(pool)
if t then
pool[t] = nil
return t
else
return {}
end
end
function del(t)
for k in pairs(t) do
t[k] = nil
end
pool[t] = true
end
end
--------------
-- TreeView --
--------------
do
local Type = 'TreeGroup'
local Version = 20
local DEFAULT_TREE_WIDTH = 175
local DEFAULT_TREE_SIZABLE = true
local PaneBackdrop = {
bgFile = 'Interface\\ChatFrame\\ChatFrameBackground',
edgeFile = 'Interface\\Tooltips\\UI-Tooltip-Border',
tile = true,
tileSize = 16,
edgeSize = 16,
insets = { left = 3, right = 3, top = 5, bottom = 3 },
}
local DraggerBackdrop = {
bgFile = 'Interface\\Tooltips\\UI-Tooltip-Background',
edgeFile = nil,
tile = true,
tileSize = 16,
edgeSize = 0,
insets = { left = 3, right = 3, top = 7, bottom = 7 },
}
local function OnAcquire(self)
self:SetTreeWidth(DEFAULT_TREE_WIDTH, DEFAULT_TREE_SIZABLE)
self:EnableButtonTooltips(true)
end
local function OnRelease(self)
self.frame:ClearAllPoints()
self.frame:Hide()
self.status = nil
for k, v in pairs(self.localstatus) do
if k == 'groups' then
for k2 in pairs(v) do
v[k2] = nil
end
else
self.localstatus[k] = nil
end
end
self.localstatus.scrollvalue = 0
self.localstatus.treewidth = DEFAULT_TREE_WIDTH
self.localstatus.treesizable = DEFAULT_TREE_SIZABLE
end
local function GetButtonParents(line)
local parent = line.parent
if parent and parent.value then
return parent.value, GetButtonParents(parent)
end
end
local function GetButtonUniqueValue(line)
local parent = line.parent
if parent and parent.value then
return GetButtonUniqueValue(parent) .. '\001' .. line.value
else
return line.value
end
end
local function ButtonOnClick(this)
local self = this.obj
self:Fire('OnClick', this.uniquevalue, this.selected)
if not this.selected then
self:SetSelected(this.uniquevalue)
this.selected = true
this:LockHighlight()
self:RefreshTree()
end
AceGUI:ClearFocus()
end
local function ExpandOnClick(this)
local button = this.button
local self = button.obj
local status = (self.status or self.localstatus).groups
status[button.uniquevalue] = not status[button.uniquevalue]
self:RefreshTree()
end
local function ButtonOnDoubleClick(button)
local self = button.obj
local status = self.status or self.localstatus
local status = (self.status or self.localstatus).groups
status[button.uniquevalue] = not status[button.uniquevalue]
self:RefreshTree()
end
local function EnableButtonTooltips(self, enable)
self.enabletooltips = enable
end
local function Button_OnEnter(this)
local self = this.obj
self:Fire('OnButtonEnter', this.uniquevalue, this)
if self.enabletooltips then
GameTooltip:SetOwner(this, 'ANCHOR_NONE')
GameTooltip:SetPoint('LEFT', this, 'RIGHT')
GameTooltip:SetText(this.text:GetText() or '', 1, 0.82, 0, 1)
GameTooltip:Show()
end
end
local function Button_OnLeave(this)
local self = this.obj
self:Fire('OnButtonLeave', this.uniquevalue, this)
if self.enabletooltips then
GameTooltip:Hide()
end
end
local buttoncount = 1
local function CreateButton(self)
local button = CreateFrame(
'Button',
('AceGUI30TreeButton%d'):format(buttoncount),
self.treeframe,
'OptionsListButtonTemplate'
)
buttoncount = buttoncount + 1
button.obj = self
local icon = button:CreateTexture(nil, 'OVERLAY')
icon:SetWidth(14)
icon:SetHeight(14)
button.icon = icon
button:SetScript('OnClick', ButtonOnClick)
button:SetScript('OnDoubleClick', ButtonOnDoubleClick)
button:SetScript('OnEnter', Button_OnEnter)
button:SetScript('OnLeave', Button_OnLeave)
button.toggle.button = button
button.toggle:SetScript('OnClick', ExpandOnClick)
return button
end
local function UpdateButton(button, treeline, selected, canExpand, isExpanded)
local self = button.obj
local toggle = button.toggle
local frame = self.frame
local text = treeline.text or ''
local icon = treeline.icon
local level = treeline.level
local value = treeline.value
local uniquevalue = treeline.uniquevalue
local disabled = treeline.disabled
button.treeline = treeline
button.value = value
button.uniquevalue = uniquevalue
if selected then
button:LockHighlight()
button.selected = true
else
button:UnlockHighlight()
button.selected = false
end
local normalTexture = button:GetNormalTexture()
local line = button.line
button.level = level
if level == 1 then
button:SetNormalFontObject('GameFontNormal')
button:SetHighlightFontObject('GameFontHighlight')
button.text:SetPoint('LEFT', (icon and 16 or 0) + 8, 2)
else
button:SetNormalFontObject('GameFontHighlightSmall')
button:SetHighlightFontObject('GameFontHighlightSmall')
button.text:SetPoint('LEFT', (icon and 16 or 0) + 8 * level, 2)
end
if disabled then
button:EnableMouse(false)
button.text:SetText('|cff808080' .. text .. FONT_COLOR_CODE_CLOSE)
else
button.text:SetText(text)
button:EnableMouse(true)
end
if icon then
button.icon:SetTexture(icon)
button.icon:SetPoint('LEFT', button, 'LEFT', 8 * level, (level == 1) and 0 or 1)
else
button.icon:SetTexture(nil)
end
if canExpand then
if not isExpanded then
toggle:SetNormalTexture('Interface\\Buttons\\UI-PlusButton-UP')
toggle:SetPushedTexture('Interface\\Buttons\\UI-PlusButton-DOWN')
else
toggle:SetNormalTexture('Interface\\Buttons\\UI-MinusButton-UP')
toggle:SetPushedTexture('Interface\\Buttons\\UI-MinusButton-DOWN')
end
toggle:Show()
else
toggle:Hide()
end
end
local function OnScrollValueChanged(this, value)
if this.obj.noupdate then
return
end
local self = this.obj
local status = self.status or self.localstatus
status.scrollvalue = value
self:RefreshTree()
AceGUI:ClearFocus()
end
-- called to set an external table to store status in
local function SetStatusTable(self, status)
assert(type(status) == 'table')
self.status = status
if not status.groups then
status.groups = {}
end
if not status.scrollvalue then
status.scrollvalue = 0
end
if not status.treewidth then
status.treewidth = DEFAULT_TREE_WIDTH
end
if not status.treesizable then
status.treesizable = DEFAULT_TREE_SIZABLE
end
self:SetTreeWidth(status.treewidth, status.treesizable)
self:RefreshTree()
end
--sets the tree to be displayed
--[[
example tree
Alpha
Bravo
-Charlie
-Delta
-Echo
Foxtrot
tree = {
{
value = "A",
text = "Alpha"
},
{
value = "B",
text = "Bravo",
children = {
{
value = "C",
text = "Charlie"
},
{
value = "D",
text = "Delta"
children = {
{
value = "E",
text = "Echo"
}
}
}
}
},
{
value = "F",
text = "Foxtrot"
},
}
]]
local function SetTree(self, tree, filter)
self.filter = filter
if tree then
assert(type(tree) == 'table')
end
self.tree = tree
self:RefreshTree()
end
local function ShouldDisplayLevel(tree)
local result = false
for k, v in ipairs(tree) do
if v.children == nil and v.visible ~= false then
result = true
elseif v.children then
result = result or ShouldDisplayLevel(v.children)
end
if result then
return result
end
end
return false
end
local function addLine(self, v, tree, level, parent)
local line = new()
line.value = v.value
line.text = v.text
line.icon = v.icon
line.disabled = v.disabled
line.tree = tree
line.level = level
line.parent = parent
line.visible = v.visible
line.uniquevalue = GetButtonUniqueValue(line)
if v.children then
line.hasChildren = true
else
line.hasChildren = nil
end
self.lines[#self.lines + 1] = line
return line
end
local function BuildLevel(self, tree, level, parent)
local groups = (self.status or self.localstatus).groups
local hasChildren = self.hasChildren
for i, v in ipairs(tree) do
if v.children then
if not self.filter or ShouldDisplayLevel(v.children) then
local line = addLine(self, v, tree, level, parent)
if groups[line.uniquevalue] then
self:BuildLevel(v.children, level + 1, line)
end
end
elseif v.visible ~= false or not self.filter then
addLine(self, v, tree, level, parent)
end
end
end
--fire an update after one frame to catch the treeframes height
local function FirstFrameUpdate(this)
local self = this.obj
this:SetScript('OnUpdate', nil)
self:RefreshTree()
end
local function ResizeUpdate(this)
this.obj:RefreshTree()
end
local function RefreshTree(self)
local buttons = self.buttons
local lines = self.lines
for i, v in ipairs(buttons) do
v:Hide()
end
while lines[1] do
local t = tremove(lines)
for k in pairs(t) do
t[k] = nil
end
del(t)
end
if not self.tree then
return
end
--Build the list of visible entries from the tree and status tables
local status = self.status or self.localstatus
local groupstatus = status.groups
local tree = self.tree
local treeframe = self.treeframe
self:BuildLevel(tree, 1)
local numlines = #lines
local maxlines = (math.floor(((self.treeframe:GetHeight() or 0) - 20) / 18))
local first, last
if numlines <= maxlines then
--the whole tree fits in the frame
status.scrollvalue = 0
self:ShowScroll(false)
first, last = 1, numlines
else
self:ShowScroll(true)
--scrolling will be needed
self.noupdate = true
self.scrollbar:SetMinMaxValues(0, numlines - maxlines)
--check if we are scrolled down too far
if numlines - status.scrollvalue < maxlines then
status.scrollvalue = numlines - maxlines
self.scrollbar:SetValue(status.scrollvalue)
end
self.noupdate = nil
first, last = status.scrollvalue + 1, status.scrollvalue + maxlines
end
local buttonnum = 1
for i = first, last do
local line = lines[i]
local button = buttons[buttonnum]
if not button then
button = self:CreateButton()
buttons[buttonnum] = button
button:SetParent(treeframe)
button:SetFrameLevel(treeframe:GetFrameLevel() + 1)
button:ClearAllPoints()
if i == 1 then
if self.showscroll then
button:SetPoint('TOPRIGHT', self.treeframe, 'TOPRIGHT', -22, -10)
button:SetPoint('TOPLEFT', self.treeframe, 'TOPLEFT', 0, -10)
else
button:SetPoint('TOPRIGHT', self.treeframe, 'TOPRIGHT', 0, -10)
button:SetPoint('TOPLEFT', self.treeframe, 'TOPLEFT', 0, -10)
end
else
button:SetPoint('TOPRIGHT', buttons[buttonnum - 1], 'BOTTOMRIGHT', 0, 0)
button:SetPoint('TOPLEFT', buttons[buttonnum - 1], 'BOTTOMLEFT', 0, 0)
end
end
UpdateButton(
button,
line,
status.selected == line.uniquevalue,
line.hasChildren,
groupstatus[line.uniquevalue]
)
button:Show()
buttonnum = buttonnum + 1
end
end
local function SetSelected(self, value)
local status = self.status or self.localstatus
if status.selected ~= value then
status.selected = value
self:Fire('OnGroupSelected', value)
end
end
local function BuildUniqueValue(...)
local n = select('#', ...)
if n == 1 then
return ...
else
return (...) .. '\001' .. BuildUniqueValue(select(2, ...))
end
end
local function Select(self, uniquevalue, ...)
self.filter = false
local status = self.status or self.localstatus
local groups = status.groups
for i = 1, select('#', ...) do
groups[BuildUniqueValue(select(i, ...))] = true
end
status.selected = uniquevalue
self:RefreshTree()
self:Fire('OnGroupSelected', uniquevalue)
end
local function SelectByPath(self, ...)
self:Select(BuildUniqueValue(...), ...)
end
--Selects a tree node by UniqueValue
local function SelectByValue(self, uniquevalue)
self:Select(uniquevalue, string.split('\001', uniquevalue))
end
local function ShowScroll(self, show)
self.showscroll = show
if show then
self.scrollbar:Show()
if self.buttons[1] then
self.buttons[1]:SetPoint('TOPRIGHT', self.treeframe, 'TOPRIGHT', -22, -10)
end
else
self.scrollbar:Hide()
if self.buttons[1] then
self.buttons[1]:SetPoint('TOPRIGHT', self.treeframe, 'TOPRIGHT', 0, -10)
end
end
end
local function OnWidthSet(self, width)
local content = self.content
local treeframe = self.treeframe
local status = self.status or self.localstatus
local contentwidth = width - status.treewidth - 20
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
local maxtreewidth = math.min(400, width - 50)
if maxtreewidth > 100 and status.treewidth > maxtreewidth then
self:SetTreeWidth(maxtreewidth, status.treesizable)
end
treeframe:SetMaxResize(maxtreewidth, 1600)
end
local function OnHeightSet(self, height)
local content = self.content
local contentheight = height - 20
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end
local function TreeOnMouseWheel(this, delta)
local self = this.obj
if self.showscroll then
local scrollbar = self.scrollbar
local min, max = scrollbar:GetMinMaxValues()
local value = scrollbar:GetValue()
local newvalue = math.min(max, math.max(min, value - delta))
if value ~= newvalue then
scrollbar:SetValue(newvalue)
end
end
end
local function SetTreeWidth(self, treewidth, resizable)
if not resizable then
if type(treewidth) == 'number' then
resizable = false
elseif type(treewidth) == 'boolean' then
resizable = treewidth
treewidth = DEFAULT_TREE_WIDTH
else
resizable = false
treewidth = DEFAULT_TREE_WIDTH
end
end
self.treeframe:SetWidth(treewidth)
self.dragger:EnableMouse(resizable)
local status = self.status or self.localstatus
status.treewidth = treewidth
status.treesizable = resizable
end
local function draggerLeave(this)
this:SetBackdropColor(1, 1, 1, 0)
end
local function draggerEnter(this)
this:SetBackdropColor(1, 1, 1, 0.8)
end
local function draggerDown(this)
local treeframe = this:GetParent()
treeframe:StartSizing('RIGHT')
end
local function draggerUp(this)
local treeframe = this:GetParent()
local self = treeframe.obj
local frame = treeframe:GetParent()
treeframe:StopMovingOrSizing()
--treeframe:SetScript("OnUpdate", nil)
treeframe:SetUserPlaced(false)
--Without this :GetHeight will get stuck on the current height, causing the tree contents to not resize
treeframe:SetHeight(0)
treeframe:SetPoint('TOPLEFT', frame, 'TOPLEFT', 0, 0)
treeframe:SetPoint('BOTTOMLEFT', frame, 'BOTTOMLEFT', 0, 0)
treeframe.obj:Fire('OnTreeResize', treeframe:GetWidth())
local status = self.status or self.localstatus
status.treewidth = treeframe:GetWidth()
end
local function LayoutFinished(self, width, height)
if self.noAutoHeight then
return
end
self:SetHeight((height or 0) + 20)
end
local createdcount = 0
local function Constructor()
local frame = CreateFrame('Frame', nil, UIParent)
local self = {}
self.type = Type
self.lines = {}
self.levels = {}
self.buttons = {}
self.hasChildren = {}
self.localstatus = {}
self.localstatus.groups = {}
self.filter = false
local treeframe = CreateFrame('Frame', nil, frame)
treeframe.obj = self
treeframe:SetPoint('TOPLEFT', frame, 'TOPLEFT', 0, 0)
treeframe:SetPoint('BOTTOMLEFT', frame, 'BOTTOMLEFT', 0, 0)
treeframe:SetWidth(DEFAULT_TREE_WIDTH)
treeframe:SetScript('OnUpdate', FirstFrameUpdate)
treeframe:SetScript('OnSizeChanged', ResizeUpdate)
treeframe:EnableMouseWheel(true)
treeframe:SetScript('OnMouseWheel', TreeOnMouseWheel)
treeframe:SetBackdrop(PaneBackdrop)
treeframe:SetBackdropColor(0.1, 0.1, 0.1, 0.5)
treeframe:SetBackdropBorderColor(0.4, 0.4, 0.4)
treeframe:SetResizable(true)
treeframe:SetMinResize(100, 1)
treeframe:SetMaxResize(400, 1600)
local dragger = CreateFrame('Frame', nil, treeframe)
dragger:SetWidth(8)
dragger:SetPoint('TOP', treeframe, 'TOPRIGHT')
dragger:SetPoint('BOTTOM', treeframe, 'BOTTOMRIGHT')
dragger:SetBackdrop(DraggerBackdrop)
dragger:SetBackdropColor(1, 1, 1, 0)
dragger:SetScript('OnMouseDown', draggerDown)
dragger:SetScript('OnMouseUp', draggerUp)
dragger:SetScript('OnEnter', draggerEnter)
dragger:SetScript('OnLeave', draggerLeave)
self.dragger = dragger
self.treeframe = treeframe
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.SetTree = SetTree
self.SetTreeWidth = SetTreeWidth
self.RefreshTree = RefreshTree
self.SetStatusTable = SetStatusTable
self.BuildLevel = BuildLevel
self.CreateButton = CreateButton
self.SetSelected = SetSelected
self.ShowScroll = ShowScroll
self.SetStatusTable = SetStatusTable
self.Select = Select
self.SelectByValue = SelectByValue
self.SelectByPath = SelectByPath
self.OnWidthSet = OnWidthSet
self.OnHeightSet = OnHeightSet
self.EnableButtonTooltips = EnableButtonTooltips
self.Filter = Filter
self.LayoutFinished = LayoutFinished
self.frame = frame
frame.obj = self
createdcount = createdcount + 1
local scrollbar = CreateFrame(
'Slider',
('AceConfigDialogTreeGroup%dScrollBar'):format(createdcount),
treeframe,
'UIPanelScrollBarTemplate'
)
self.scrollbar = scrollbar
local scrollbg = scrollbar:CreateTexture(nil, 'BACKGROUND')
scrollbg:SetAllPoints(scrollbar)
scrollbg:SetTexture(0, 0, 0, 0.4)
scrollbar.obj = self
self.noupdate = true
scrollbar:SetPoint('TOPRIGHT', treeframe, 'TOPRIGHT', -10, -26)
scrollbar:SetPoint('BOTTOMRIGHT', treeframe, 'BOTTOMRIGHT', -10, 26)
scrollbar:SetScript('OnValueChanged', OnScrollValueChanged)
scrollbar:SetMinMaxValues(0, 0)
self.localstatus.scrollvalue = 0
scrollbar:SetValueStep(1)
scrollbar:SetValue(0)
scrollbar:SetWidth(16)
self.noupdate = nil
local border = CreateFrame('Frame', nil, frame)
self.border = border
border:SetPoint('TOPLEFT', treeframe, 'TOPRIGHT', 0, 0)
border:SetPoint('BOTTOMRIGHT', frame, 'BOTTOMRIGHT', 0, 0)
border:SetBackdrop(PaneBackdrop)
border:SetBackdropColor(0.1, 0.1, 0.1, 0.5)
border:SetBackdropBorderColor(0.4, 0.4, 0.4)
--Container Support
local content = CreateFrame('Frame', nil, border)
self.content = content
content.obj = self
content:SetPoint('TOPLEFT', border, 'TOPLEFT', 10, -10)
content:SetPoint('BOTTOMRIGHT', border, 'BOTTOMRIGHT', -10, 10)
AceGUI:RegisterAsContainer(self)
--AceGUI:RegisterAsWidget(self)
return self
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
end
| 0 | 0.969438 | 1 | 0.969438 | game-dev | MEDIA | 0.756868 | game-dev,desktop-app | 0.962613 | 1 | 0.962613 |
tukkek/javelin | 8,163 | javelin/controller/db/Preferences.java | package javelin.controller.db;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.MissingResourceException;
import java.util.Properties;
import javelin.controller.Weather;
import javelin.controller.action.ActionDescription;
import javelin.controller.ai.ThreadManager;
import javelin.model.item.Item;
import javelin.model.unit.Combatant;
import javelin.model.unit.Squad;
import javelin.model.world.Season;
import javelin.model.world.World;
import javelin.model.world.WorldActor;
import javelin.model.world.location.town.Town;
import javelin.model.world.location.unique.Haxor;
import javelin.view.KeysScreen;
import javelin.view.frame.keys.BattleKeysScreen;
import javelin.view.frame.keys.PreferencesScreen;
import javelin.view.frame.keys.WorldKeysScreen;
import javelin.view.screen.WorldScreen;
import tyrant.mikera.tyrant.TextZone;
/**
* Used to read the file "preferences.properties". See the file
* "preferences.properties" for more details on standard options and this link
* for development options:
*
* https://github.com/tukkek/javelin/wiki/Development-options
*
* @see PreferencesScreen
* @author alex
*/
public class Preferences {
/** Configuration file key for {@link #MONITORPERFORMANCE}. */
public static final String KEYCHECKPERFORMANCE = "ai.checkperformance";
/** Configuration file key for {@link #MAXTHREADS}. */
public static final String KEYMAXTHREADS = "ai.maxthreads";
static final String FILE = "preferences.properties";
static Properties PROPERTIES = new Properties();
public static boolean AICACHEENABLED;
public static Integer MAXTEMPERATURE;
public static int MAXMILISECONDSTHINKING;
public static int MAXTHREADS;
public static boolean MONITORPERFORMANCE;
public static int MESSAGEWAIT;
public static String TEXTCOLOR;
public static boolean BACKUP;
public static int SAVEINTERVAL;
public static boolean DEBUGDISABLECOMBAT;
public static boolean DEBUGESHOWMAP;
public static Integer DEBUGSXP;
public static Integer DEBUGSGOLD;
public static Integer DEBUGRUBIES;
public static Integer DEBUGLABOR;
public static boolean DEBUGCLEARGARRISON;
public static String DEBUGFOE;
public static String DEBUGPERIOD;
public static String DEBUGMAPTYPE;
public static Integer DEBUGMINIMUMFOES;
public static String DEBUGWEATHER;
public static String DEBUGSEASON;
public static boolean DEBUGUNLOCKTEMPLES;
/**
* TODO make this take a {@link String} from the properties file.
*/
public static Item DEBUGSTARTINGITEM = null;
static {
load();
}
static void load() {
try {
PROPERTIES.clear();
PROPERTIES.load(new FileReader(FILE));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static String getString(String key) {
try {
return PROPERTIES.getProperty(key);
} catch (MissingResourceException e) {
return null;
}
}
static Integer getInteger(String key, Integer fallback) {
String value = getString(key);
/* Don't inline. */
if (value == null) {
return fallback;
}
return Integer.parseInt(value);
}
/**
* @return the entire text of the properties file.
*/
public static String getfile() {
try {
String s = "";
BufferedReader reader = new BufferedReader(new FileReader(FILE));
String line = reader.readLine();
while (line != null) {
s += line + "\n";
line = reader.readLine();
}
reader.close();
return s;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* TODO would be better to have an option #setpreference(String key,String
* value) that would read the file, replace a line with the given key and
* save it in the proper order instead of forever appending to the file. It
* could be used in a few places this is being used instead.
*
* @param content
* Overwrite the properties file with this content and reloads
* all options.
*/
public static void savefile(String content) {
try {
write(content, FILE);
load();
init();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param content
* Write content...
* @param f
* to this file.
* @throws IOException
*/
public static void write(String content, String f) throws IOException {
FileWriter writer = new FileWriter(f);
writer.write(content);
writer.close();
}
/**
* Initializes or reloads all preferences.
*/
public static void init() {
AICACHEENABLED = getString("ai.cache").equals("true");
MAXTEMPERATURE = getInteger("ai.maxtemperature", 0);
MAXMILISECONDSTHINKING =
Math.round(1000 * getFloat("ai.maxsecondsthinking"));
int cpus = Runtime.getRuntime().availableProcessors();
MAXTHREADS = Preferences.getInteger(KEYMAXTHREADS, cpus);
if (MAXTHREADS > cpus) {
MAXTHREADS = cpus;
}
MONITORPERFORMANCE =
Preferences.getString(KEYCHECKPERFORMANCE).equals("true");
if (MONITORPERFORMANCE) {
if (ThreadManager.performance == Integer.MIN_VALUE) {
ThreadManager.performance = 0;
}
} else {
ThreadManager.performance = Integer.MIN_VALUE;
}
BACKUP = getString("fs.backup").equals("true");
SAVEINTERVAL = getInteger("fs.saveinterval", 9);
MESSAGEWAIT = Math.round(1000 * getFloat("ui.messagedelay"));
TEXTCOLOR = getString("ui.textcolor").toUpperCase();
try {
TextZone.fontcolor = (Color) Color.class
.getField(Preferences.TEXTCOLOR).get(null);
} catch (Exception e) {
TextZone.fontcolor = Color.BLACK;
}
initkeys("keys.world", new WorldKeysScreen());
initkeys("keys.battle", new BattleKeysScreen());
readdebug();
}
private static void initkeys(String propertyname,
KeysScreen worldKeyScreen) {
String keys = getString(propertyname);
if (keys == null) {
return;
}
ArrayList<ActionDescription> actions = worldKeyScreen.getactions();
for (int i = 0; i < keys.length(); i++) {
actions.get(i).setMainKey(Character.toString(keys.charAt(i)));
}
}
static void readdebug() {
DEBUGDISABLECOMBAT = getString("cheat.combat") != null
&& getString("cheat.combat").equals("false");
DEBUGESHOWMAP = javelin.controller.db.Preferences
.getString("cheat.world") != null;
DEBUGSXP =
javelin.controller.db.Preferences.getInteger("cheat.xp", null);
DEBUGSGOLD = javelin.controller.db.Preferences.getInteger("cheat.gold",
null);
DEBUGRUBIES = javelin.controller.db.Preferences
.getInteger("cheat.rubies", null);
DEBUGLABOR = javelin.controller.db.Preferences.getInteger("cheat.labor",
null);
DEBUGCLEARGARRISON = javelin.controller.db.Preferences
.getString("cheat.garrison") != null;
DEBUGFOE = getString("cheat.monster");
DEBUGPERIOD = getString("cheat.period");
DEBUGMAPTYPE = getString("cheat.map");
DEBUGMINIMUMFOES = getInteger("cheat.foes", null);
DEBUGWEATHER = getString("cheat.weather");
DEBUGSEASON = getString("cheat.season");
DEBUGUNLOCKTEMPLES = getString("cheat.temples") != null;
initdebug();
}
static void initdebug() {
if (DEBUGESHOWMAP) {
for (int x = 0; x < World.MAPDIMENSION; x++) {
for (int y = 0; y < World.MAPDIMENSION; y++) {
WorldScreen.setVisible(x, y);
}
}
}
for (WorldActor a : Squad.getall(Squad.class)) {
initsquaddebug((Squad) a);
}
if (DEBUGRUBIES != null && Haxor.singleton != null) {
Haxor.singleton.rubies = DEBUGRUBIES;
}
if (DEBUGLABOR != null) {
for (WorldActor a : Town.getall(Town.class)) {
Town t = (Town) a;
if (!t.ishostile()) {
t.labor = DEBUGLABOR;
}
}
}
if (DEBUGWEATHER != null) {
DEBUGWEATHER = DEBUGWEATHER.toLowerCase();
Weather.read(0); // tests cheat.weather value
}
if (DEBUGSEASON != null) {
Season.current = Season.valueOf(DEBUGSEASON.toUpperCase());
}
}
static void initsquaddebug(Squad s) {
if (DEBUGSGOLD != null) {
s.gold = DEBUGSGOLD;
}
if (DEBUGSXP != null) {
for (Combatant c : s.members) {
c.xp = new BigDecimal(DEBUGSXP / 100f);
}
}
}
private static float getFloat(String key) {
return Float.parseFloat(getString(key));
}
}
| 0 | 0.778202 | 1 | 0.778202 | game-dev | MEDIA | 0.726519 | game-dev | 0.965131 | 1 | 0.965131 |
Team-Immersive-Intelligence/ImmersiveIntelligence | 23,442 | src/main/java/pl/pabilo8/immersiveintelligence/common/entity/EntityHans.java | package pl.pabilo8.immersiveintelligence.common.entity;
import blusunrize.immersiveengineering.common.IEContent;
import blusunrize.immersiveengineering.common.util.ChatUtils;
import blusunrize.immersiveengineering.common.util.Utils;
import net.minecraft.entity.*;
import net.minecraft.entity.ai.*;
import net.minecraft.entity.ai.EntityAITasks.EntityAITaskEntry;
import net.minecraft.entity.monster.EntityIronGolem;
import net.minecraft.entity.monster.IMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagInt;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.pathfinding.PathNavigate;
import net.minecraft.util.*;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.event.HoverEvent;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.Constants.NBT;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandlerItem;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;
import pl.pabilo8.immersiveintelligence.common.IIContent;
import pl.pabilo8.immersiveintelligence.common.entity.ammo.component.EntityGasCloud;
import pl.pabilo8.immersiveintelligence.common.entity.hans.HansAnimations;
import pl.pabilo8.immersiveintelligence.common.entity.hans.HansAnimations.*;
import pl.pabilo8.immersiveintelligence.common.entity.hans.HansPathNavigate;
import pl.pabilo8.immersiveintelligence.common.entity.hans.HansUtils;
import pl.pabilo8.immersiveintelligence.common.entity.hans.tasks.*;
import pl.pabilo8.immersiveintelligence.common.entity.hans.tasks.hand_weapon.AIHansHandWeapon;
import pl.pabilo8.immersiveintelligence.common.entity.hans.tasks.idle.AIHansKazachok;
import pl.pabilo8.immersiveintelligence.common.entity.hans.tasks.idle.AIHansSalute;
import pl.pabilo8.immersiveintelligence.common.entity.hans.tasks.idle.AIHansTimedLookAtEntity;
import pl.pabilo8.immersiveintelligence.common.entity.vehicle.towable.gun.EntityFieldHowitzer;
import pl.pabilo8.immersiveintelligence.common.item.armor.ItemIILightEngineerHelmet;
import pl.pabilo8.immersiveintelligence.common.util.IIColor;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
/**
* @author Pabilo8 (pabilo@iiteam.net)
* @since 11.01.2021
*/
public class EntityHans extends EntityCreature implements INpc
{
/**
* A dangerously close distance, most {@link AIHansHandWeapon} tasks will resort to {@link EntityAIAttackMelee}
*/
public static final float MELEE_DISTANCE = 1.25f;
private static final IIColor[] EYE_COLORS = new IIColor[]{
IIColor.fromPackedRGB(0x597179),//cyan
IIColor.fromPackedRGB(0x536579),//toned blue
IIColor.fromPackedRGB(0x486479),//blue 2
IIColor.fromPackedRGB(0x3F795B),//green
IIColor.fromPackedRGB(0x3B7959),//green/blue
IIColor.fromPackedRGB(0x54795B),//toned green
IIColor.fromPackedRGB(0x414832),//khaki
IIColor.fromPackedRGB(0x3D4827),//olive
IIColor.fromPackedRGB(0x9D7956),//amber
IIColor.fromPackedRGB(0x434139),//brown
IIColor.fromPackedRGB(0x484739),//light brown
IIColor.fromPackedRGB(0x2F2E28),//dark brown
};
private static final DataParameter<String> DATA_MARKER_LEG_ANIMATION = EntityDataManager.createKey(EntityHans.class, DataSerializers.STRING);
private static final DataParameter<String> DATA_MARKER_ARM_ANIMATION = EntityDataManager.createKey(EntityHans.class, DataSerializers.STRING);
private static final DataParameter<Integer> DATA_MARKER_EYE_COLOR = EntityDataManager.createKey(EntityHans.class, DataSerializers.VARINT);
private static final DataParameter<NBTTagCompound> DATA_MARKER_SPEECH = EntityDataManager.createKey(EntityHans.class, DataSerializers.COMPOUND_TAG);
public static boolean INFINITE_AMMO = false;
public final NonNullList<ItemStack> mainInventory = NonNullList.withSize(27, ItemStack.EMPTY);
private final net.minecraftforge.items.IItemHandlerModifiable handHandler = new net.minecraftforge.items.wrapper.EntityHandsInvWrapper(this);
private final net.minecraftforge.items.IItemHandlerModifiable armorHandler = new net.minecraftforge.items.wrapper.EntityArmorInvWrapper(this);
private final net.minecraftforge.items.IItemHandlerModifiable invHandler = new ItemStackHandler(this.mainInventory);
private final net.minecraftforge.items.IItemHandler joinedHandler = new net.minecraftforge.items.wrapper.CombinedInvWrapper(armorHandler, handHandler, invHandler);
public HansLegAnimation prevLegAnimation = HansLegAnimation.STANDING;
public HansLegAnimation legAnimation = HansLegAnimation.STANDING;
public int legAnimationTimer = 0;
public HansArmAnimation prevArmAnimation = HansArmAnimation.NORMAL;
public HansArmAnimation armAnimation = HansArmAnimation.NORMAL;
public int armAnimationTimer = 8;
public EyeEmotions eyeEmotion = HansAnimations.EyeEmotions.NEUTRAL;
public MouthEmotions mouthEmotion = HansAnimations.MouthEmotions.NEUTRAL;
public MouthShapes mouthShape = HansAnimations.MouthShapes.CLOSED;
public ArrayList<Tuple<Integer, MouthShapes>> mouthShapeQueue = new ArrayList<>();
public int speechProgress = 0;
public IIColor eyeColor;
/**
* Whether this Hans is a head of a Squad
*/
public boolean commander = false;
public boolean enemyContact = false;
public boolean hasAmmo = true;
private EntityAIBase vehicleTask = null;
private AIHansHandWeapon weaponTask = null;
private AIHansOpenDoor doorTask = null;
public EntityHans(World worldIn)
{
super(worldIn);
this.enablePersistence();
setSneaking(false);
this.dataManager.register(DATA_MARKER_LEG_ANIMATION, legAnimation.name().toLowerCase());
this.dataManager.register(DATA_MARKER_ARM_ANIMATION, armAnimation.name().toLowerCase());
this.dataManager.register(DATA_MARKER_EYE_COLOR, (eyeColor = EYE_COLORS[rand.nextInt(EYE_COLORS.length)]).getPackedRGB());
this.dataManager.register(DATA_MARKER_SPEECH, new NBTTagCompound());
setHealth(20);
}
@Override
protected PathNavigate createNavigator(World worldIn)
{
return new HansPathNavigate(this, world);
}
@Override
protected void entityInit()
{
super.entityInit();
}
@Override
public void onUpdate()
{
super.onUpdate();
tasks.taskEntries.removeIf(entry -> entry.action instanceof AIHansBase&&((AIHansBase)entry.action).shouldBeRemoved());
if(world.isRemote)
{
if(dataManager.isDirty())
{
eyeColor = IIColor.fromPackedRGB(dataManager.get(DATA_MARKER_EYE_COLOR));
legAnimation = getLegAnimationFromString(dataManager.get(DATA_MARKER_LEG_ANIMATION));
armAnimation = getArmAnimationFromString(dataManager.get(DATA_MARKER_ARM_ANIMATION));
NBTTagCompound speech = dataManager.get(DATA_MARKER_SPEECH);
if(mouthShapeQueue.size()==0)
{
NBTTagList durations = speech.getTagList("durations", NBT.TAG_INT);
NBTTagList shapes = speech.getTagList("shapes", NBT.TAG_STRING);
for(int i = 0; i < durations.tagCount(); i++)
{
NBTTagString s = (NBTTagString)shapes.get(i);
NBTTagInt d = (NBTTagInt)durations.get(i);
mouthShapeQueue.add(new Tuple<>(d.getInt(), MouthShapes.v(s.getString())));
}
dataManager.set(DATA_MARKER_SPEECH, new NBTTagCompound());
}
}
handleSpeech();
if(this.getAttackTarget()!=null)
{
eyeEmotion = EyeEmotions.FROWNING;
mouthEmotion = MouthEmotions.ANGRY;
}
else
{
mouthEmotion = MouthEmotions.ANGRY;
if(legAnimation==HansLegAnimation.KAZACHOK)
mouthEmotion = MouthEmotions.HAPPY;
float hp = getHealth()/getMaxHealth();
if(hp > 0.75||legAnimation==HansLegAnimation.KAZACHOK)
eyeEmotion = EyeEmotions.HAPPY;
else if(hp > 0.5)
eyeEmotion = EyeEmotions.NEUTRAL;
else
eyeEmotion = EyeEmotions.FROWNING;
}
}
else
{
dataManager.set(DATA_MARKER_EYE_COLOR, eyeColor.getPackedRGB());
//check if enemies are around
if(ticksExisted%25==0)
enemyContact = world.getEntitiesWithinAABB(Entity.class,
new AxisAlignedBB(posX, posY, posZ, posX, posY, posZ).grow(14), this::isValidTarget)
.stream().findAny().isPresent();
//idle + combat animations
HansLegAnimation currentLeg = legAnimation;
HansArmAnimation currentArm = armAnimation;
legAnimation = isInWater()?HansLegAnimation.SWIMMING: HansLegAnimation.STANDING;
armAnimation = HansArmAnimation.NORMAL;
for(EntityAITaskEntry entry : tasks.taskEntries)
{
if(entry.action instanceof AIHansBase)
((AIHansBase)entry.action).setRequiredAnimation();
}
if(currentLeg!=legAnimation)
{
this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(getWalkSpeed());
dataManager.set(DATA_MARKER_LEG_ANIMATION, legAnimation.name().toLowerCase());
}
//dataManager.set(DATA_MARKER_ARM_ANIMATION, HansArmAnimation.NORMAL.name().toLowerCase());
if(currentArm!=armAnimation)
dataManager.set(DATA_MARKER_ARM_ANIMATION, armAnimation.name().toLowerCase());
}
//update held item
getHeldItemMainhand().getItem().onUpdate(getHeldItemMainhand(), world, this, 0, true);
if(prevLegAnimation!=legAnimation)
{
if(legAnimationTimer > 0)
legAnimationTimer--;
else
{
legAnimationTimer = 8;
prevLegAnimation = legAnimation;
setSize(legAnimation.aabbWidth, legAnimation.aabbHeight);
}
}
if(prevArmAnimation!=armAnimation)
{
if(armAnimationTimer > 0)
armAnimationTimer--;
else
{
armAnimationTimer = 8;
prevArmAnimation = armAnimation;
}
}
}
private void handleSpeech()
{
if(mouthShapeQueue.size() > 0)
{
if(speechProgress++ >= mouthShapeQueue.get(0).getFirst())
{
this.mouthShape = mouthShapeQueue.get(0).getSecond();
this.mouthShapeQueue.remove(0);
this.speechProgress = 0;
}
}
else
{
this.mouthShape = MouthShapes.CLOSED;
this.speechProgress = 0;
}
}
private double getWalkSpeed()
{
return 0.25D*legAnimation.walkSpeedModifier;
}
private HansLegAnimation getLegAnimationFromString(String s)
{
return Arrays.stream(HansLegAnimation.values())
.filter(anim -> s.equalsIgnoreCase(anim.name()))
.findFirst().orElse(HansLegAnimation.STANDING);
}
private HansArmAnimation getArmAnimationFromString(String s)
{
return Arrays.stream(HansArmAnimation.values())
.filter(anim -> s.equalsIgnoreCase(anim.name()))
.findFirst().orElse(HansArmAnimation.NORMAL);
}
@Nonnull
@Override
public HansPathNavigate getNavigator()
{
return ((HansPathNavigate)super.getNavigator());
}
@Override
protected void initEntityAI()
{
super.initEntityAI();
//Attack mobs and enemies focused on the Hans first
this.targetTasks.addTask(1, new EntityAINearestAttackableTarget<EntityLiving>(this, EntityLiving.class, 1, true, false,
input -> input.isEntityAlive()&&(input instanceof IMob||input.getAttackTarget()==this))
{
@Override
protected AxisAlignedBB getTargetableArea(double targetDistance)
{
return this.taskOwner.getEntityBoundingBox().grow(targetDistance, targetDistance*0.66f, targetDistance);
}
}
);
//Attack entities with different team, stay neutral on default
this.targetTasks.addTask(2, new EntityAINearestAttackableTarget<EntityLivingBase>(this, EntityLivingBase.class, 1, true, false,
input -> input!=null&&isValidTarget(input))
{
@Override
protected AxisAlignedBB getTargetableArea(double targetDistance)
{
return this.taskOwner.getEntityBoundingBox().grow(targetDistance, targetDistance*0.66f, targetDistance);
}
}
);
//Call other hanses for help when attacked
this.targetTasks.addTask(2, new AIHansAlertOthers(this, true));
this.tasks.addTask(2, new AIHansHolsterWeapon(this));
updateWeaponTasks();
this.tasks.addTask(5, new EntityAIAvoidEntity<>(this, EntityGasCloud.class, 8.0F, 0.6f, 0.7f));
//this.tasks.addTask(6, new AIHansIdle(this));
//this.tasks.addTask(7, new EntityAIWatchClosest(this, EntityLiving.class, 6.0F));
// TODO: 04.02.2022 swimming anim
this.tasks.addTask(0, new EntityAISwimming(this));
this.tasks.addTask(0, new AIHansClimbLadder(this));
this.tasks.addTask(0, doorTask = new AIHansOpenDoor(this, true));
//this.tasks.addTask(4, new EntityAIAvoidEntity<>(this, EntityLivingBase.class, avEntity-> this.hasAmmunition()&&avEntity!=null&&avEntity.getRevengeTarget()==this, 8.0F, 0.6D, 0.6D));
}
public double getSprintSpeed()
{
return getWalkSpeed()*1.25f;
}
public void updateWeaponTasks()
{
if(weaponTask!=null)
this.tasks.removeTask(weaponTask);
this.weaponTask = HansUtils.getHandWeaponTask(this);
if(weaponTask!=null)
this.tasks.addTask(3, weaponTask);
this.tasks.addTask(4, new EntityAIAttackMelee(this, 1.125f, true));
}
@Override
public boolean startRiding(@Nonnull Entity entity)
{
if(super.startRiding(entity))
{
if(entity instanceof EntityMachinegun)
tasks.addTask(0, vehicleTask = new AIHansMachinegun(this));
else if(entity instanceof EntityMortar)
tasks.addTask(0, vehicleTask = new AIHansMortar(this));
else if(entity.getLowestRidingEntity() instanceof EntityFieldHowitzer)
tasks.addTask(0, vehicleTask = new AIHansHowitzer(this));
return true;
}
return false;
}
public boolean markCrewman(@Nonnull Entity entity)
{
if(vehicleTask!=null)
return false;
tasks.addTask(0, new AIHansCrewman(this, entity));
return true;
}
@Override
public void dismountEntity(@Nonnull Entity entity)
{
super.dismountEntity(entity);
if(vehicleTask!=null)
tasks.removeTask(vehicleTask);
}
@Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing)
{
if(capability==CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)
return true;
return super.hasCapability(capability, facing);
}
@Nullable
@Override
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing)
{
if(capability==CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)
{
if(facing==null) return (T)invHandler;
else if(facing.getAxis().isVertical()) return (T)handHandler;
else if(facing.getAxis().isHorizontal()) return (T)armorHandler;
}
return super.getCapability(capability, facing);
}
@Override
public void readEntityFromNBT(@Nonnull NBTTagCompound compound)
{
super.readEntityFromNBT(compound);
readInventory(compound.getTagList("npc_inventory", 10));
//hey, Mojang guys, do you know you can make a field accessible instead of doubling it for each extending class?
//seriously, you consider yourself real programmers?
if(compound.hasKey("HandItems"))
{
NBTTagList handInventory = compound.getTagList("HandItems", 10);
setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(((NBTTagCompound)handInventory.get(0))));
setItemStackToSlot(EntityEquipmentSlot.OFFHAND, new ItemStack((NBTTagCompound)handInventory.get(1)));
}
this.legAnimation = getLegAnimationFromString(compound.getString("leg_animation"));
this.armAnimation = getArmAnimationFromString(compound.getString("arm_animation"));
this.eyeColor = IIColor.fromPackedRGB(compound.getInteger("eye_color"));
this.commander = compound.getBoolean("commander");
updateWeaponTasks();
}
@Override
public void writeEntityToNBT(@Nonnull NBTTagCompound compound)
{
super.writeEntityToNBT(compound);
compound.setTag("npc_inventory", Utils.writeInventory(mainInventory));
compound.setString("leg_animation", legAnimation.name().toLowerCase());
compound.setString("arm_animation", armAnimation.name().toLowerCase());
compound.setInteger("eye_color", eyeColor.getPackedRGB());
compound.setBoolean("commander", commander);
}
private void readInventory(NBTTagList npc_inventory)
{
int max = npc_inventory.tagCount();
for(int i = 0; i < max; i++)
{
NBTTagCompound itemTag = npc_inventory.getCompoundTagAt(i);
int slot = itemTag.getByte("Slot")&255;
if(slot < this.mainInventory.size())
this.mainInventory.set(slot, new ItemStack(itemTag));
}
}
@Override
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.25f);
this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(20f);
this.getEntityAttribute(SharedMonsterAttributes.FOLLOW_RANGE).setBaseValue(52f);
}
public boolean attackEntityAsMob(Entity entityIn)
{
this.world.setEntityState(this, (byte)4);
boolean flag = entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), (float)(1+this.rand.nextInt(2)));
if(flag)
this.applyEnchantments(this, entityIn);
this.playSound(SoundEvents.ENTITY_PLAYER_ATTACK_STRONG, 1.0F, 1.0F);
return flag;
}
@Override
protected boolean processInteract(EntityPlayer player, @Nonnull EnumHand hand)
{
return !player.isSpectator()&&hand==EnumHand.MAIN_HAND&&player.getPositionVector().distanceTo(this.getPositionVector()) <= 1d;
}
@Nonnull
@Override
public EnumActionResult applyPlayerInteraction(EntityPlayer player, @Nonnull Vec3d vec, @Nonnull EnumHand hand)
{
if(player.isSpectator()||hand==EnumHand.OFF_HAND)
return EnumActionResult.FAIL;
if(!world.isRemote)
{
this.prevRotationYaw = this.rotationYawHead;
this.rotationYaw = this.rotationYawHead;
ItemStack heldItem = player.getHeldItem(hand);
if(heldItem.isEmpty())
{
tasks.addTask(2, new AIHansSalute(this, player));
greetPlayer(player);
}
else if(tasks.taskEntries.stream().noneMatch(entry -> entry.action instanceof AIHansKazachok)&&Utils.isFluidRelatedItemStack(heldItem))
{
IFluidHandlerItem capability = heldItem.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null);
if(capability!=null)
{
FluidStack drain = capability.drain(new FluidStack(IEContent.fluidEthanol, 1000), false); // TODO: 08.12.2021 make an actual fix
if(drain!=null)
{
tasks.addTask(2, new AIHansTimedLookAtEntity(this, player, 60, 1f));
tasks.addTask(2, new AIHansKazachok(this, drain.amount/1000f));
}
}
}
else if(IIContent.itemSubmachinegun.isAmmo(heldItem, getActiveItemStack()))
{
int i = 0;
while(i < mainInventory.size()&&!heldItem.isEmpty())
{
heldItem = invHandler.insertItem(i, heldItem.copy(), false);
i++;
}
if(heldItem.isEmpty())
sendPlayerMessage(player, "Danke für diese neue Patronen. Meine Maschinenpistole war sehr hungrig!");
else
sendPlayerMessage(player, "Danke für diese neue Patronen, aber habe ich sie genug.");
tasks.addTask(2, new AIHansSalute(this, player));
}
player.setHeldItem(EnumHand.MAIN_HAND, heldItem);
player.swingArm(hand);
}
else
{
if(mouthShapeQueue.size() > 0)
return EnumActionResult.PASS;
}
return EnumActionResult.PASS;
}
private void greetPlayer(EntityPlayer player)
{
sendPlayerMessage(player,
String.format("Guten %1$s, %2$s!",
HansUtils.getGermanTimeName(world.getWorldTime()),
player.getName()
));
//Uses Rhubarb, the voice to lip shapes thingy, if you want to see how it works, check out their github
//Disabled for now, might see service Soon™
// TODO: 28.12.2021 decide on how speech will be performed (server or client)
this.mouthShapeQueue.clear();
this.speechProgress = 0;
HansAnimations.putMouthShape(this, 'X', 0.00, 0.35);
HansAnimations.putMouthShape(this, 'F', 0.35, 0.63);
HansAnimations.putMouthShape(this, 'B', 0.63, 0.70);
HansAnimations.putMouthShape(this, 'C', 0.70, 0.84);
HansAnimations.putMouthShape(this, 'B', 0.84, 0.98);
HansAnimations.putMouthShape(this, 'X', 0.98, 1.27);
HansAnimations.putMouthShape(this, 'B', 1.27, 1.34);
HansAnimations.putMouthShape(this, 'A', 1.34, 1.40);
HansAnimations.putMouthShape(this, 'C', 1.40, 1.45);
HansAnimations.putMouthShape(this, 'B', 1.45, 0.63);
HansAnimations.putMouthShape(this, 'E', 1.56, 0.63);
HansAnimations.putMouthShape(this, 'A', 1.63, 1.72);
HansAnimations.putMouthShape(this, 'E', 1.72, 1.84);
HansAnimations.putMouthShape(this, 'D', 1.84, 2.12);
HansAnimations.putMouthShape(this, 'C', 2.12, 2.19);
HansAnimations.putMouthShape(this, 'B', 2.19, 2.40);
HansAnimations.putMouthShape(this, 'X', 2.40, 2.97);
HansAnimations.putMouthShape(this, 'A', 2.97, 3.10);
dataManager.set(DATA_MARKER_SPEECH, createServerSpeechTagCompound());
}
@Nonnull
private NBTTagCompound createServerSpeechTagCompound()
{
NBTTagCompound tag = new NBTTagCompound();
NBTTagList durations = new NBTTagList();
NBTTagList shapes = new NBTTagList();
for(Tuple<Integer, MouthShapes> element : mouthShapeQueue)
{
durations.appendTag(new NBTTagInt(element.getFirst()));
shapes.appendTag(new NBTTagString(element.getSecond().name()));
}
tag.setTag("durations", durations);
tag.setTag("shapes", shapes);
this.mouthShapeQueue.clear();
return tag;
}
@Override
public HoverEvent getHoverEvent()
{
return super.getHoverEvent();
}
public boolean isValidTarget(Entity entity)
{
return entity instanceof IMob||((entity instanceof EntityPlayer||entity instanceof EntityHans||entity instanceof EntityEmplacementWeapon||entity instanceof EntityIronGolem)&&entity.getTeam()!=this.getTeam());
}
public void sendPlayerMessage(EntityPlayer player, String text)
{
ItemStack helmet = getItemStackFromSlot(EntityEquipmentSlot.HEAD);
if(helmet.getItem() instanceof ItemIILightEngineerHelmet&&IIContent.itemLightEngineerHelmet.getUpgrades(helmet).hasKey("gasmask"))
ChatUtils.sendServerNoSpamMessages(player, new TextComponentTranslation("chat.type.text", this.getDisplayName(), net.minecraftforge.common.ForgeHooks.newChatWithLinks("*Hans Gasmask Noises*")));
else
ChatUtils.sendServerNoSpamMessages(player, new TextComponentTranslation("chat.type.text", this.getDisplayName(), net.minecraftforge.common.ForgeHooks.newChatWithLinks(text)));
}
protected SoundEvent getHurtSound(@Nonnull DamageSource damageSourceIn)
{
if(damageSourceIn==DamageSource.ON_FIRE)
{
return SoundEvents.ENTITY_PLAYER_HURT_ON_FIRE;
}
else
{
return damageSourceIn==DamageSource.DROWN?SoundEvents.ENTITY_PLAYER_HURT_DROWN: SoundEvents.ENTITY_PLAYER_HURT;
}
}
protected SoundEvent getDeathSound()
{
return SoundEvents.ENTITY_PLAYER_DEATH;
}
@Nonnull
protected SoundEvent getSwimSound()
{
return SoundEvents.ENTITY_PLAYER_SWIM;
}
@Nonnull
protected SoundEvent getSplashSound()
{
return SoundEvents.ENTITY_PLAYER_SPLASH;
}
@Nonnull
protected SoundEvent getFallSound(int heightIn)
{
return heightIn > 4?SoundEvents.ENTITY_PLAYER_BIG_FALL: SoundEvents.ENTITY_PLAYER_SMALL_FALL;
}
public HansLegAnimation getLegAnimation()
{
return legAnimation==HansLegAnimation.STANDING&&isSneaking()?HansLegAnimation.SNEAKING: legAnimation;
}
public AIHansOpenDoor getDoorTask()
{
return doorTask;
}
}
| 0 | 0.895815 | 1 | 0.895815 | game-dev | MEDIA | 0.988292 | game-dev | 0.952383 | 1 | 0.952383 |
blurite/rsprot | 19,154 | protocol/osrs-233/osrs-233-model/src/main/kotlin/net/rsprot/protocol/game/outgoing/info/npcinfo/NpcAvatar.kt | package net.rsprot.protocol.game.outgoing.info.npcinfo
import net.rsprot.buffer.bitbuffer.UnsafeLongBackedBitBuf
import net.rsprot.protocol.game.outgoing.info.AvatarPriority
import net.rsprot.protocol.game.outgoing.info.npcinfo.util.NpcCellOpcodes
import net.rsprot.protocol.game.outgoing.info.util.Avatar
import net.rsprot.protocol.internal.RSProtFlags
import net.rsprot.protocol.internal.checkCommunicationThread
import net.rsprot.protocol.internal.game.outgoing.info.CoordGrid
import net.rsprot.protocol.internal.game.outgoing.info.npcinfo.NpcAvatarDetails
import net.rsprot.protocol.internal.game.outgoing.info.util.ZoneIndexStorage
/**
* The npc avatar class represents an NPC as shown by the client.
* This class contains all the properties necessary to put a NPC into high resolution.
*
* Npc direction table:
* ```
* | Id | Client Angle | Direction |
* |:--:|:------------:|:----------:|
* | 0 | 768 | North-West |
* | 1 | 1024 | North |
* | 2 | 1280 | North-East |
* | 3 | 512 | West |
* | 4 | 1536 | East |
* | 5 | 256 | South-West |
* | 6 | 0 | South |
* | 7 | 1792 | South-East |
* ```
*
* @param index the index of the npc in the world
* @param id the id of the npc in the world, limited to range of 0..16383
* @param level the height level of the npc
* @param x the absolute x coordinate of the npc
* @param z the absolute z coordinate of the npc
* @param spawnCycle the game cycle on which the npc spawned into the world;
* for static NPCs, this would always be zero. This is only used by the C++ clients.
* @param direction the direction that the npc will face on spawn (see table above)
* @param priority the priority that the avatar will have. The default is [AvatarPriority.NORMAL].
* If the priority is set to [AvatarPriority.LOW], the NPC will only render if there are enough
* slots leftover for the low priority group. As an example, if the low priority cap is set to 50 elements
* and there are already 50 other low priority avatars rendering to a player, this avatar will simply
* not render at all, even if there are slots leftover in the [AvatarPriority.NORMAL] group.
* For [AvatarPriority.NORMAL], both groups are accessible, although they will prefer the normal group.
* Low priority group will be used if normal group has no more free slots leftover.
* The priorities are especially useful to limit how many pets a player can see at a time. It is very common
* for servers to give everyone pets. During high population events, it is very easy to hit the 149 pet
* threshold in a local area, which could result in important NPCs, such as shopkeepers and whatnot
* from not rendering. Limiting the low priority count ensures that those arguably more important NPCs will
* still be able to render with hundreds of pets around.
* @param specific if true, the NPC will only render to players that have explicitly marked this
* NPC's index as specific-visible, anyone else will be unable to see it. If it's false, anyone can
* see the NPC regardless.
* @property extendedInfo the extended info, commonly referred to as "masks", will track everything relevant
* inside itself. Setting properties such as a spotanim would be done through this.
* The [extendedInfo] is also responsible for caching the non-temporary blocks,
* such as appearance and move speed.
* @property zoneIndexStorage the storage tracking all the allocated game NPCs based on the zones.
*/
public class NpcAvatar internal constructor(
index: Int,
id: Int,
level: Int,
x: Int,
z: Int,
spawnCycle: Int = 0,
direction: Int = 0,
priority: AvatarPriority = AvatarPriority.NORMAL,
specific: Boolean,
allocateCycle: Int,
public val extendedInfo: NpcAvatarExtendedInfo,
internal val zoneIndexStorage: ZoneIndexStorage,
) : Avatar {
/**
* Npc avatar details class wraps all the client properties of a NPC in its own
* data structure.
*/
internal val details: NpcAvatarDetails =
NpcAvatarDetails(
index,
id,
level,
x,
z,
spawnCycle,
direction,
priority.bitcode,
specific,
allocateCycle,
)
private val tracker: NpcAvatarTracker = NpcAvatarTracker()
/**
* The high resolution movement buffer, used to avoid re-calculating the movement information
* for each observer of a given NPC, in cases where there are multiple. It is additionally
* more efficient to just do a single bulk pBits() call, than to call it multiple times, which
* this accomplishes.
*/
internal var highResMovementBuffer: UnsafeLongBackedBitBuf? = null
/**
* Adds an observer to this avatar by incrementing the observer count.
* Note that it is necessary for servers to de-register npc info when the player is logging off,
* or the protocol will run into issues on multiple levels.
*/
internal fun addObserver(index: Int) {
tracker.add(index)
}
/**
* Removes an observer from this avatar by decrementing the observer count.
* This function must be called when a player logs off for each NPC they were observing.
*/
internal fun removeObserver(index: Int) {
// If the allocation cycle is the same as current cycle count,
// a "hotswap" has occurred.
// This means that a npc was deallocated and another allocated the same index
// in the same cycle.
// Due to the new one being allocated, the observer count is already reset
// to zero, and we cannot decrement the observer count further - it would go negative.
if (details.allocateCycle == NpcInfoProtocol.cycleCount) {
return
}
tracker.remove(index)
}
/**
* Resets the observer count.
*/
internal fun resetObservers() {
tracker.reset()
}
/**
* Updates the spawn direction of the NPC.
*
* Table of possible direction values:
* ```
* | Id | Direction | Angle |
* |:--:|:----------:|:-----:|
* | 0 | North-West | 768 |
* | 1 | North | 1024 |
* | 2 | North-East | 1280 |
* | 3 | West | 512 |
* | 4 | East | 1536 |
* | 5 | South-West | 256 |
* | 6 | South | 0 |
* | 7 | South-East | 1792 |
* ```
*
* @param direction the direction for the NPC to face.
*/
@Deprecated(
message = "Deprecated. Use setDirection(direction) for consistency.",
replaceWith = ReplaceWith("setDirection(direction)"),
)
public fun updateDirection(direction: Int) {
setDirection(direction)
}
/**
* Updates the spawn direction of the NPC.
*
* Table of possible direction values:
* ```
* | Id | Direction | Angle |
* |:--:|:----------:|:-----:|
* | 0 | North-West | 768 |
* | 1 | North | 1024 |
* | 2 | North-East | 1280 |
* | 3 | West | 512 |
* | 4 | East | 1536 |
* | 5 | South-West | 256 |
* | 6 | South | 0 |
* | 7 | South-East | 1792 |
* ```
*
* @param direction the direction for the NPC to face.
*/
public fun setDirection(direction: Int) {
checkCommunicationThread()
require(direction in 0..7) {
"Direction must be a value in range of 0..7. " +
"See the table in documentation. Value: $direction"
}
this.details.updateDirection(direction)
}
/**
* Sets the id of the avatar - any new observers of this NPC will receive the new id.
* This should be used in tandem with the transformation extended info block.
* @param id the id of the npc to set to - any new observers will see that id instead.
*/
public fun setId(id: Int) {
checkCommunicationThread()
require(id in 0..RSProtFlags.npcAvatarMaxId) {
"Id must be a value in range of 0..${RSProtFlags.npcAvatarMaxId}. Value: $id"
}
this.details.id = id
if (id > 16383) {
extendedInfo.setTransmogrification(id)
}
}
/**
* A helper function to teleport the NPC to a new coordinate.
* This will furthermore mark the movement type as teleport, meaning no matter what other
* coordinate changes are applied, as teleport has the highest priority, teleportation
* will be how it is rendered on the client's end.
* @param level the new height level of the NPC
* @param x the new absolute x coordinate of the NPC
* @param z the new absolute z coordinate of the NPC
* @param jump whether to "jump" the NPC to the new coordinate, or to treat it as a
* regular walk/run type movement. While this should __almost__ always be true, there are
* certain NPCs, such as Sarachnis in OldSchool, that utilize teleporting without jumping.
* This effectively makes the NPC appear as it is walking towards the destination. If the
* NPC falls visually behind, the client will begin increasing its movement speed, to a
* maximum of run speed, until it has caught up visually.
*/
public fun teleport(
level: Int,
x: Int,
z: Int,
jump: Boolean,
) {
checkCommunicationThread()
val nextCoord = CoordGrid(level, x, z)
zoneIndexStorage.move(details.index, details.currentCoord, nextCoord)
details.currentCoord = nextCoord
details.movementType = details.movementType or (if (jump) NpcAvatarDetails.TELEJUMP else NpcAvatarDetails.TELE)
}
/**
* Marks the NPC as moved with the crawl movement type.
* If more than one crawl/walks are sent in one cycle, it will instead be treated as run.
* If more than two crawl/walks are sent in one cycle, it will be treated as a teleport.
* @param deltaX the x coordinate delta that the NPC moved.
* @param deltaZ the z coordinate delta that the npc moved.
* @throws ArrayIndexOutOfBoundsException if either of the deltas is not in range of -1..1,
* or both are 0s.
*/
@Throws(ArrayIndexOutOfBoundsException::class)
public fun crawl(
deltaX: Int,
deltaZ: Int,
) {
checkCommunicationThread()
singleStepMovement(
deltaX,
deltaZ,
NpcAvatarDetails.CRAWL,
)
}
/**
* Marks the NPC as moved with the walk movement type.
* If more than one crawl/walks are sent in one cycle, it will instead be treated as run.
* If more than two crawl/walks are sent in one cycle, it will be treated as a teleport.
* @param deltaX the x coordinate delta that the NPC moved.
* @param deltaZ the z coordinate delta that the npc moved.
* @throws ArrayIndexOutOfBoundsException if either of the deltas is not in range of -1..1,
* or both are 0s.
*/
@Throws(ArrayIndexOutOfBoundsException::class)
public fun walk(
deltaX: Int,
deltaZ: Int,
) {
checkCommunicationThread()
singleStepMovement(
deltaX,
deltaZ,
NpcAvatarDetails.WALK,
)
}
/**
* Determines the movement opcode for the NPC, adjusting the NPC's underlying coordinate afterwards,
* and defines the movement speed based on previous movements in this cycle, as well as the
* [flag] requested by the movement.
* @param deltaX the x coordinate delta that the NPC moved.
* @param deltaZ the z coordinate delta that the npc moved.
* @param flag the movement speed flag, used to determine what movement speeds have been used
* in one cycle, given it is possible to move a NPC more than one in one cycle, should the
* server request it.
* @throws ArrayIndexOutOfBoundsException if either of the deltas is not in range of -1..1,
* or both are 0s.
*/
@Throws(ArrayIndexOutOfBoundsException::class)
private fun singleStepMovement(
deltaX: Int,
deltaZ: Int,
flag: Int,
) {
val opcode = NpcCellOpcodes.singleCellMovementOpcode(deltaX, deltaZ)
val (level, x, z) = details.currentCoord
val nextCoord = CoordGrid(level, x + deltaX, z + deltaZ)
zoneIndexStorage.move(details.index, details.currentCoord, nextCoord)
details.currentCoord = nextCoord
when (++details.stepCount) {
1 -> {
details.firstStep = opcode
details.movementType = details.movementType or flag
}
2 -> {
details.secondStep = opcode
details.movementType = details.movementType or NpcAvatarDetails.RUN
}
else -> {
details.movementType = details.movementType or NpcAvatarDetails.TELE
}
}
}
/**
* Prepares the bitcodes of a NPC given the assumption it has at least one player observing it,
* and the NPC is not teleporting (or tele-jumping), as both of those cause it to be treated as
* remove + re-add client-side, meaning no normal block is used.
* While it is possible to additionally make NPC removal as part of this function,
* because part of the responsibility is at the NPC info protocol level (coordinate checks,
* state checks), it is not possible to fully cover it, so best to leave that for the protocol
* to handle.
*/
internal fun prepareBitcodes() {
val movementType = details.movementType
// If teleporting, or if there are no observers, there's no need to compute this
if (movementType and (NpcAvatarDetails.TELE or NpcAvatarDetails.TELEJUMP) != 0 || !tracker.hasObservers()) {
return
}
val buffer = UnsafeLongBackedBitBuf()
this.highResMovementBuffer = buffer
val extendedInfo = this.extendedInfo.flags != 0
if (movementType and NpcAvatarDetails.RUN != 0) {
pRun(buffer, extendedInfo)
} else if (movementType and NpcAvatarDetails.WALK != 0) {
pWalk(buffer, extendedInfo)
} else if (movementType and NpcAvatarDetails.CRAWL != 0) {
pCrawl(buffer, extendedInfo)
} else if (extendedInfo) {
pExtendedInfo(buffer)
} else {
pNoUpdate(buffer)
}
}
/**
* Informs the client that there will be no movement or extended info update for this NPC.
* @param buffer the pre-computed buffer into which to write the bitcodes.
*/
private fun pNoUpdate(buffer: UnsafeLongBackedBitBuf) {
buffer.pBits(1, 0)
}
/**
* Informs the client that there is no movement occurring for this NPC, but it does have
* extended info blocks encoded.
* @param buffer the pre-computed buffer into which to write the bitcodes.
*/
private fun pExtendedInfo(buffer: UnsafeLongBackedBitBuf) {
buffer.pBits(1, 1)
buffer.pBits(2, 0)
}
/**
* Informs the client that there is a crawl-speed movement occurring for this NPC.
* @param buffer the pre-computed buffer into which to write the bitcodes.
* @param extendedInfo whether this NPC additionally has extended info updates coming.
*/
private fun pCrawl(
buffer: UnsafeLongBackedBitBuf,
extendedInfo: Boolean,
) {
buffer.pBits(1, 1)
buffer.pBits(2, 2)
buffer.pBits(1, 0)
buffer.pBits(3, details.firstStep)
buffer.pBits(1, if (extendedInfo) 1 else 0)
}
/**
* Informs the client that there is a walk-speed movement occurring for this NPC.
* @param buffer the pre-computed buffer into which to write the bitcodes.
* @param extendedInfo whether this NPC additionally has extended info updates coming.
*/
private fun pWalk(
buffer: UnsafeLongBackedBitBuf,
extendedInfo: Boolean,
) {
buffer.pBits(1, 1)
buffer.pBits(2, 1)
buffer.pBits(3, details.firstStep)
buffer.pBits(1, if (extendedInfo) 1 else 0)
}
/**
* Informs the client that there is a run-speed movement occurring for this NPC.
* @param buffer the pre-computed buffer into which to write the bitcodes.
* @param extendedInfo whether this NPC additionally has extended info updates coming.
*/
private fun pRun(
buffer: UnsafeLongBackedBitBuf,
extendedInfo: Boolean,
) {
buffer.pBits(1, 1)
buffer.pBits(2, 2)
buffer.pBits(1, 1)
buffer.pBits(3, details.firstStep)
buffer.pBits(3, details.secondStep)
buffer.pBits(1, if (extendedInfo) 1 else 0)
}
/**
* The current height level of this avatar.
*/
public fun level(): Int = details.currentCoord.level
/**
* The current absolute x coordinate of this avatar.
*/
public fun x(): Int = details.currentCoord.x
/**
* The current absolute z coordinate of this avatar.
*/
public fun z(): Int = details.currentCoord.z
/**
* Sets this avatar inaccessible, meaning no player can observe this NPC,
* but they are still in the world. This is how NPCs in the 'dead' state
* will be handled.
* @param inaccessible whether the npc is inaccessible to all players (not rendered)
*/
public fun setInaccessible(inaccessible: Boolean) {
checkCommunicationThread()
details.inaccessible = inaccessible
}
/**
* Checks whether a npc is actively observed by at least one player.
* @return true if the NPC has at least one player currently observing it via
* NPC info, false otherwise.
*/
public fun isActive(): Boolean = tracker.hasObservers()
/**
* Checks the number of players that are currently observing this NPC avatar.
* @return the number of players that are observing this avatar.
*/
public fun getObserverCount(): Int = tracker.getObserverCount()
/**
* Gets a set of all the indexes of the players that are observing this NPC.
*
* It is important to note that the collection is re-used across cycles.
* If the collection is intended to be stored for long-term usage, it should be
* copied to a new data set, or re-called each cycle. Trying to access the iterator
* across game cycles will result in a [ConcurrentModificationException].
*
* @return a set of all the player indices observing this NPC.
*/
public fun getObservingPlayerIndices(): Set<Int> = tracker.getCachedSet()
override fun postUpdate() {
details.stepCount = 0
details.firstStep = -1
details.secondStep = -1
details.movementType = 0
extendedInfo.postUpdate()
}
override fun toString(): String =
"NpcAvatar(" +
"extendedInfo=$extendedInfo, " +
"details=$details, " +
"tracker=$tracker, " +
"highResMovementBuffer=$highResMovementBuffer" +
")"
}
| 0 | 0.777428 | 1 | 0.777428 | game-dev | MEDIA | 0.887624 | game-dev | 0.603194 | 1 | 0.603194 |
Deadrik/TFC2 | 3,767 | src/Common/com/bioxx/tfc2/items/itemblocks/ItemStair.java | package com.bioxx.tfc2.items.itemblocks;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import com.bioxx.tfc2.Core;
import com.bioxx.tfc2.TFCBlocks;
import com.bioxx.tfc2.api.interfaces.INeedOffset;
public class ItemStair extends ItemTerraBlock
{
public ItemStair(Block b)
{
super(b);
}
@Override
public void addInformation(ItemStack is, EntityPlayer player, List arraylist, boolean flag)
{
super.addInformation(is, player, arraylist, flag);
if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsAcacia))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.acacia"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsAsh))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.ash"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsAspen))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.aspen"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsBirch))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.birch"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsChestnut))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.chestnut"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsDouglasFir))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.douglas_fir"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsHickory))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.hickory"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsMaple))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.maple"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsOak))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.oak"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsPine))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.pine"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsSequoia))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.sequoia"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsSpruce))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.spruce"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsSycamore))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.sycamore"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsWhiteCedar))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.white_cedar"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsWillow))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.willow"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsKapok))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.kapok"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsRosewood))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.rosewood"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsBlackwood))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.blackwood"));
else if (is.getItem() == Item.getItemFromBlock(TFCBlocks.StairsPalm))
arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global.palm"));
else
arraylist.add(TextFormatting.DARK_RED + Core.translate("global.unknown"));
}
@Override
public int getMetadata(int i)
{
if(block instanceof INeedOffset)
return((INeedOffset)block).convertMetaToBlock(i);
return i;
}
}
| 0 | 0.800054 | 1 | 0.800054 | game-dev | MEDIA | 0.99015 | game-dev | 0.872476 | 1 | 0.872476 |
TauCetiStation/TauCetiClassic | 9,527 | code/game/objects/items/weapons/RSF.dm | /*
CONTAINS:
RSF
*/
/obj/item/weapon/rsf
name = "Rapid-Service-Fabricator"
desc = "A device used to rapidly deploy service items."
icon = 'icons/obj/tools.dmi'
icon_state = "rcd"
opacity = 0
density = FALSE
anchored = FALSE
var/matter = 0
var/mode = 1
w_class = SIZE_SMALL
/obj/item/weapon/rsf/atom_init()
. = ..()
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
/obj/item/weapon/rsf/attackby(obj/item/I, mob/user, params)
if(istype(I, /obj/item/weapon/rcd_ammo))
if(matter + 10 > 30)
to_chat(user, "The RSF cant hold any more matter.")
return
qdel(I)
matter += 10
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
else
return ..()
/obj/item/weapon/rsf/attack_self(mob/user)
playsound(src, 'sound/effects/pop.ogg', VOL_EFFECTS_MASTER, null, FALSE)
if (mode == 1)
mode = 2
to_chat(user, "Changed dispensing mode to 'Drinking Glass'")
return
if (mode == 2)
mode = 3
to_chat(user, "Changed dispensing mode to 'Paper'")
return
if (mode == 3)
mode = 4
to_chat(user, "Changed dispensing mode to 'Pen'")
return
if (mode == 4)
mode = 5
to_chat(user, "Changed dispensing mode to 'Dice Pack'")
return
if (mode == 5)
mode = 6
to_chat(user, "Changed dispensing mode to 'Cigarette'")
return
if (mode == 6)
mode = 1
to_chat(user, "Changed dispensing mode to 'Dosh'")
return
// Change mode
/obj/item/weapon/rsf/afterattack(atom/target, mob/user, proximity, params)
if(!proximity) return
if (!(istype(target, /obj/structure/table) || isfloorturf(target)))
return
if (istype(target, /obj/structure/table) && mode == 1)
if (istype(target, /obj/structure/table) && matter >= 1)
to_chat(user, "Dispensing Dosh...")
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
new /obj/item/weapon/spacecash/c10( target.loc )
if (isrobot(user))
var/mob/living/silicon/robot/engy = user
engy.cell.charge -= 200 //once money becomes useful, I guess changing this to a high amount, like 500 units a kick, till then, enjoy dosh!
else
matter--
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
return
else if (isfloorturf(target) && mode == 1)
if (isfloorturf(target) && matter >= 1)
to_chat(user, "Dispensing Dosh...")
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
new /obj/item/weapon/spacecash/c10( target )
if (isrobot(user))
var/mob/living/silicon/robot/engy = user
engy.cell.charge -= 200 //once money becomes useful, I guess changing this to a high amount, like 500 units a kick, till then, enjoy dosh!
else
matter--
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
return
else if (istype(target, /obj/structure/table) && mode == 2)
if (istype(target, /obj/structure/table) && matter >= 1)
to_chat(user, "Dispensing Drinking Glass...")
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
new /obj/item/weapon/reagent_containers/food/drinks/drinkingglass( target.loc )
if (isrobot(user))
var/mob/living/silicon/robot/engy = user
engy.cell.charge -= 50
else
matter--
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
return
else if (isfloorturf(target) && mode == 2)
if (isfloorturf(target) && matter >= 1)
to_chat(user, "Dispensing Drinking Glass...")
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
new /obj/item/weapon/reagent_containers/food/drinks/drinkingglass( target )
if (isrobot(user))
var/mob/living/silicon/robot/engy = user
engy.cell.charge -= 50
else
matter--
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
return
else if (istype(target, /obj/structure/table) && mode == 3)
if (istype(target, /obj/structure/table) && matter >= 1)
to_chat(user, "Dispensing Paper Sheet...")
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
new /obj/item/weapon/paper( target.loc )
if (isrobot(user))
var/mob/living/silicon/robot/engy = user
engy.cell.charge -= 10
else
matter--
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
return
else if (isfloorturf(target) && mode == 3)
if (isfloorturf(target) && matter >= 1)
to_chat(user, "Dispensing Paper Sheet...")
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
new /obj/item/weapon/paper( target )
if (isrobot(user))
var/mob/living/silicon/robot/engy = user
engy.cell.charge -= 10
else
matter--
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
return
else if (istype(target, /obj/structure/table) && mode == 4)
if (istype(target, /obj/structure/table) && matter >= 1)
to_chat(user, "Dispensing Pen...")
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
new /obj/item/weapon/pen( target.loc )
if (isrobot(user))
var/mob/living/silicon/robot/engy = user
engy.cell.charge -= 50
else
matter--
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
return
else if (isfloorturf(target) && mode == 4)
if (isfloorturf(target) && matter >= 1)
to_chat(user, "Dispensing Pen...")
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
new /obj/item/weapon/pen( target )
if (isrobot(user))
var/mob/living/silicon/robot/engy = user
engy.cell.charge -= 50
else
matter--
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
return
else if (istype(target, /obj/structure/table) && mode == 5)
if (istype(target, /obj/structure/table) && matter >= 1)
to_chat(user, "Dispensing Dice Pack...")
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
new /obj/item/weapon/storage/pill_bottle/dice( target.loc )
if (isrobot(user))
var/mob/living/silicon/robot/engy = user
engy.cell.charge -= 200
else
matter--
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
return
else if (isfloorturf(target) && mode == 5)
if (isfloorturf(target) && matter >= 1)
to_chat(user, "Dispensing Dice Pack...")
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
new /obj/item/weapon/storage/pill_bottle/dice( target )
if (isrobot(user))
var/mob/living/silicon/robot/engy = user
engy.cell.charge -= 200
else
matter--
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
return
else if (istype(target, /obj/structure/table) && mode == 6)
if (istype(target, /obj/structure/table) && matter >= 1)
to_chat(user, "Dispensing Cigarette...")
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
new /obj/item/clothing/mask/cigarette( target.loc )
if (isrobot(user))
var/mob/living/silicon/robot/engy = user
engy.cell.charge -= 10
else
matter--
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
return
else if (isfloorturf(target) && mode == 6)
if (isfloorturf(target) && matter >= 1)
to_chat(user, "Dispensing Cigarette...")
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
new /obj/item/clothing/mask/cigarette( target )
if (isrobot(user))
var/mob/living/silicon/robot/engy = user
engy.cell.charge -= 10
else
matter--
to_chat(user, "The RSF now holds [matter]/30 fabrication-units.")
desc = "A RSF. It currently holds [matter]/30 fabrication-units."
return
/obj/item/weapon/rsf/cookiesynth
name = "Cookie Synthesizer"
desc = "A device used to rapidly deploy cookies."
icon = 'icons/obj/food.dmi'
icon_state = "COOKIE!!!"
matter = 30
var/poisoned = 0
/obj/item/weapon/rsf/cookiesynth/attack_self(mob/living/silicon/robot/user)
playsound(src, 'sound/effects/pop.ogg', VOL_EFFECTS_MASTER, null, FALSE)
poisoned = !poisoned
if(poisoned && user.emagged)
to_chat(user, "<span class='warning'>Cookie Synthesizer hacked.</span>")
else
to_chat(user, "<span class='notice'>Cookie Synthesizer operating normally.</span>")
/obj/item/weapon/rsf/cookiesynth/afterattack(atom/target, mob/living/silicon/robot/user, proximity, params)
if(matter < 1 || !proximity || user.cell.charge < 100 || !user.cell || !istype(target, /obj/structure/table))
return
if(poisoned && user.emagged)
to_chat(user, "Dispensing Bad Cookie...")
new /obj/item/weapon/reagent_containers/food/snacks/cookie/toxin_cookie(target.loc)
else
to_chat(user, "Dispensing Cookie...")
new /obj/item/weapon/reagent_containers/food/snacks/cookie(target.loc)
playsound(src, 'sound/machines/click.ogg', VOL_EFFECTS_MASTER, 10)
user.cell.use(100)
| 0 | 0.809322 | 1 | 0.809322 | game-dev | MEDIA | 0.99431 | game-dev | 0.539497 | 1 | 0.539497 |
Javad-Ak/Space-Dance | 2,994 | src/main.c | // "SPACE DANCE" Game is a project at AUT - CE | Date : Jan - 2024 | Developer : Mohammad Javad Akbari 40231005
#define SDL_MAIN_HANDLED
#include "menu.h"
#include "gameLoop.h"
#include "essentials.h"
SDL_Rect ScreenRect = {0, 0, WIDTH, HEIGHT};
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
Mix_Music* backgroundMusic = NULL;
int isMenuActive = FALSE, isGameActive = FALSE, LastTick;
int init();
void ShutDown();
// main gameloop implementation
int main() {
atexit(ShutDown);
isMenuActive = init();
// main loop to run the game
setupMenu();
while (isMenuActive) {
RenderMenu();
processMenu();
// GameLoop and frame rate controller
while (isMenuActive && isGameActive) {
renderGame();
processGame();
updateGame();
int wait = FRAME_TIME - (SDL_GetTicks() - LastTick);
if (wait > 0 && wait <= FRAME_TIME) SDL_Delay(wait);
LastTick = SDL_GetTicks();
}
}
return 0;
}
// Initialize SDL, sound and window
int init() {
TTF_Init();
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
fprintf(stderr, "window error");
return FALSE;
}
if (SDL_Init(SDL_INIT_EVENTS) != 0) {
fprintf(stderr, "window error");
return FALSE;
}
if (SDL_Init(SDL_INIT_TIMER) != 0) {
fprintf(stderr, "window error");
return FALSE;
}
if (SDL_Init(SDL_INIT_AUDIO) < 0) {
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
return FALSE;
}
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) {
printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError());
return FALSE;
}
window = SDL_CreateWindow(
"Space Dance",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
WIDTH,
HEIGHT,
SDL_WINDOW_SHOWN
);
if (window == NULL) {
fprintf(stderr, "window error");
return FALSE;
}
renderer = SDL_CreateRenderer(window, -1, 0);
if (renderer == NULL) {
fprintf(stderr, "render error");
return FALSE;
}
backgroundMusic = Mix_LoadMUS(MUSIC_P);
if (backgroundMusic == NULL) {
printf("Failed to load background music! SDL_mixer Error: %s\n", Mix_GetError());
return FALSE;
}
// Play the music indefinitely (-1 means loop)
Mix_PlayMusic(backgroundMusic, -1);
return TRUE;
}
// Destroy game window
void ShutDown() {
if (tmpMSGT != NULL) SDL_DestroyTexture(tmpMSGT);
if (tmpMSGS != NULL) SDL_FreeSurface(tmpMSGS);
if (GameBGT != NULL) SDL_DestroyTexture(GameBGT);
if (GameBGS != NULL) SDL_FreeSurface(GameBGS);
if (renderer != NULL) SDL_DestroyRenderer(renderer);
if (window != NULL) SDL_DestroyWindow(window);
TTF_CloseFont(mFont);
TTF_Quit();
Mix_FreeMusic(backgroundMusic);
Mix_CloseAudio();
SDL_Quit();
}
| 0 | 0.751118 | 1 | 0.751118 | game-dev | MEDIA | 0.614135 | game-dev | 0.91589 | 1 | 0.91589 |
xiaoye97/VTS_XYPlugin | 3,992 | VTS_XYPluginUI/Assets/Plugins/Demigiant/DOTweenPro/DOTweenProShortcuts.cs | // Author: Daniele Giardini - http://www.demigiant.com
// Created: 2018/07/13
using System;
using DG.Tweening.Core;
using DG.Tweening.Plugins;
using UnityEngine;
#pragma warning disable 1591
namespace DG.Tweening
{
public static class DOTweenProShortcuts
{
static DOTweenProShortcuts()
{
// Create stub instances of custom plugins, in order to allow IL2CPP to understand they must be included in the build
#pragma warning disable 219
SpiralPlugin stub = new SpiralPlugin();
#pragma warning restore 219
}
#region Shortcuts
#region Transform
/// <summary>Tweens a Transform's localPosition in a spiral shape.
/// Also stores the transform as the tween's target so it can be used for filtered operations</summary>
/// <param name="duration">The duration of the tween</param>
/// <param name="axis">The axis around which the spiral will rotate</param>
/// <param name="mode">The type of spiral movement</param>
/// <param name="speed">Speed of the rotations</param>
/// <param name="frequency">Frequency of the rotation. Lower values lead to wider spirals</param>
/// <param name="depth">Indicates how much the tween should move along the spiral's axis</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Tweener DOSpiral(
this Transform target, float duration, Vector3? axis = null, SpiralMode mode = SpiralMode.Expand,
float speed = 1, float frequency = 10, float depth = 0, bool snapping = false
) {
if (Mathf.Approximately(speed, 0)) speed = 1;
if (axis == null || axis == Vector3.zero) axis = Vector3.forward;
TweenerCore<Vector3, Vector3, SpiralOptions> t = DOTween.To(SpiralPlugin.Get(), () => target.localPosition, x => target.localPosition = x, (Vector3)axis, duration)
.SetTarget(target);
t.plugOptions.mode = mode;
t.plugOptions.speed = speed;
t.plugOptions.frequency = frequency;
t.plugOptions.depth = depth;
t.plugOptions.snapping = snapping;
return t;
}
#endregion
#if true // PHYSICS_MARKER
#region Rigidbody
/// <summary>Tweens a Rigidbody's position in a spiral shape.
/// Also stores the transform as the tween's target so it can be used for filtered operations</summary>
/// <param name="duration">The duration of the tween</param>
/// <param name="axis">The axis around which the spiral will rotate</param>
/// <param name="mode">The type of spiral movement</param>
/// <param name="speed">Speed of the rotations</param>
/// <param name="frequency">Frequency of the rotation. Lower values lead to wider spirals</param>
/// <param name="depth">Indicates how much the tween should move along the spiral's axis</param>
/// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param>
public static Tweener DOSpiral(
this Rigidbody target, float duration, Vector3? axis = null, SpiralMode mode = SpiralMode.Expand,
float speed = 1, float frequency = 10, float depth = 0, bool snapping = false
) {
if (Mathf.Approximately(speed, 0)) speed = 1;
if (axis == null || axis == Vector3.zero) axis = Vector3.forward;
TweenerCore<Vector3, Vector3, SpiralOptions> t = DOTween.To(SpiralPlugin.Get(), () => target.position, target.MovePosition, (Vector3)axis, duration)
.SetTarget(target);
t.plugOptions.mode = mode;
t.plugOptions.speed = speed;
t.plugOptions.frequency = frequency;
t.plugOptions.depth = depth;
t.plugOptions.snapping = snapping;
return t;
}
#endregion
#endif
#endregion
}
}
| 0 | 0.898917 | 1 | 0.898917 | game-dev | MEDIA | 0.822574 | game-dev | 0.852027 | 1 | 0.852027 |
utilForever/RosettaStone | 1,138 | Sources/Rosetta/PlayMode/Tasks/SimpleTasks/DestroyTask.cpp | // This code is based on Sabberstone project.
// Copyright (c) 2017-2021 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2017-2024 Chris Ohk
#include <Rosetta/PlayMode/Games/Game.hpp>
#include <Rosetta/PlayMode/Tasks/SimpleTasks/DestroyTask.hpp>
#include <Rosetta/PlayMode/Tasks/SimpleTasks/IncludeTask.hpp>
namespace RosettaStone::PlayMode::SimpleTasks
{
DestroyTask::DestroyTask(EntityType entityType, bool forceDeathPhase)
: ITask(entityType), m_forceDeathPhase(forceDeathPhase)
{
// Do nothing
}
TaskStatus DestroyTask::Impl(Player* player)
{
const auto playables =
IncludeTask::GetEntities(m_entityType, player, m_source, m_target);
for (auto& playable : playables)
{
playable->Destroy();
}
if (m_forceDeathPhase)
{
player->game->ProcessDestroyAndUpdateAura();
}
return TaskStatus::COMPLETE;
}
std::unique_ptr<ITask> DestroyTask::CloneImpl()
{
return std::make_unique<DestroyTask>(m_entityType, m_forceDeathPhase);
}
} // namespace RosettaStone::PlayMode::SimpleTasks
| 0 | 0.792072 | 1 | 0.792072 | game-dev | MEDIA | 0.933254 | game-dev | 0.800213 | 1 | 0.800213 |
CyberGrandChallenge/samples | 14,160 | cqe-challenges/CROMU_00005/src/service.c | /*
Author: James Nuttall (james@cromulence.co)
Copyright (c) 2014 Cromulence LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <libcgc.h>
#include "stdlib.h"
#include "mymath.h"
#include "service.h"
/*
This CB emulates a chess board. The board is an 8x8 array; the pieces are unique chars saved within the array.
User takes turns between white and black side, moving pieces according to chess rules (mostly).
The pieces do not 'take' each other, they will only switch positions.
Pawns do not take diagonally, they only move forward one step at a time.
As in chess, pieces can not jump over each other; the knight is the only exception to this rule.
To exploit:
If a white knight makes it to 7,8 and then tries to display the board (the '9' option), it will crash.
As seen in the pov.xml.
*/
// global variables for use by all other functions
char (*ptr_array)[WIDTH][HEIGHT]; // pointer to board array
char current_team = WHITE_TEAM; // white/black
// Returns color of piece (BLACK_PIECE, WHITE_PIECE, or EMPTY)
int getColor(char piece)
{
if (piece <= QUEEN_WHITE && piece >= PAWN_WHITE)
return WHITE_PIECE;
if (piece <= QUEEN_BLACK && piece >= PAWN_BLACK)
return BLACK_PIECE;
return EMPTY;
}
// display contents of board
void displayboard(void)
{
for(int i = HEIGHT - 1; i >= 0; i--)
{
for(int j = 0; j < WIDTH; j++)
{
transmit(0, (char*)&(*ptr_array)[j][i], 1, NULL);
}
printf("\n");
}
}
// place all the pieces on the board
void initboard()
{
// all the empty squares get a '.'
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
(*ptr_array)[i][j] = EMPTY;
}
}
// putting WHITE pieces in position
(*ptr_array)[0][0] = ROOK_WHITE;
(*ptr_array)[1][0] = KNIGHT_WHITE;
(*ptr_array)[2][0] = BISHOP_WHITE;
(*ptr_array)[3][0] = QUEEN_WHITE;
(*ptr_array)[4][0] = KING_WHITE;
(*ptr_array)[5][0] = BISHOP_WHITE;
(*ptr_array)[6][0] = KNIGHT_WHITE;
(*ptr_array)[7][0] = ROOK_WHITE;
(*ptr_array)[0][1] = PAWN_WHITE;
(*ptr_array)[1][1] = PAWN_WHITE;
(*ptr_array)[2][1] = PAWN_WHITE;
(*ptr_array)[3][1] = PAWN_WHITE;
(*ptr_array)[4][1] = PAWN_WHITE;
(*ptr_array)[5][1] = PAWN_WHITE;
(*ptr_array)[6][1] = PAWN_WHITE;
(*ptr_array)[7][1] = PAWN_WHITE;
// putting BLACK pieces in position
(*ptr_array)[0][6] = PAWN_BLACK;
(*ptr_array)[1][6] = PAWN_BLACK;
(*ptr_array)[2][6] = PAWN_BLACK;
(*ptr_array)[3][6] = PAWN_BLACK;
(*ptr_array)[4][6] = PAWN_BLACK;
(*ptr_array)[5][6] = PAWN_BLACK;
(*ptr_array)[6][6] = PAWN_BLACK;
(*ptr_array)[7][6] = PAWN_BLACK;
(*ptr_array)[0][7] = ROOK_BLACK;
(*ptr_array)[1][7] = KNIGHT_BLACK;
(*ptr_array)[2][7] = BISHOP_BLACK;
(*ptr_array)[3][7] = QUEEN_BLACK;
(*ptr_array)[4][7] = KING_BLACK;
(*ptr_array)[5][7] = BISHOP_BLACK;
(*ptr_array)[6][7] = KNIGHT_BLACK;
(*ptr_array)[7][7] = ROOK_BLACK;
}
// returns the piece at the given location
char getPiece(Location loc)
{
return (*ptr_array)[loc.x][loc.y];
}
// Checks for a collision
// returns COLLISION or NO_COLLISION
int checkNoCollision(Move move)
{
Location src = move.src;
Location dst = move.dst;
int squares[WIDTH][2]; // squares between src and dst
int square_cnt = 0;
char piece = getPiece(move.src);
// pieces cannot pass through each other (except KNIGHT)
if (piece == KNIGHT_WHITE || piece == KNIGHT_BLACK)
{
// make sure the knight isn't landing on a piece of its own color
if (getColor(piece) != getColor(getPiece(dst)))
return NO_COLLISION;
else
{
return COLLISION;
}
}
// if piece is white and the destination is white, collision
if (getColor(piece) == WHITE_PIECE && getColor(getPiece(move.dst)) == WHITE_PIECE )
return COLLISION;
// if piece is black and the destination is black, collision
if (getColor(piece) == BLACK_PIECE && getColor(getPiece(move.dst)) == BLACK_PIECE)
return COLLISION;
// determine squares between src and dst on a FILE
if (move.src.x == move.dst.x)
{
if (move.src.y < move.dst.y)
{
for(int i = move.src.y+1; i <= move.dst.y; i++)
{
squares[square_cnt][0] = move.src.x;
squares[square_cnt++][1] = i;
}
}
else
for(int i = move.src.y-1; i >= move.dst.y; i--)
{
squares[square_cnt][0] = move.src.x;
squares[square_cnt++][1] = i;
}
}
// determine squares between src and dst on a RANK
else if (move.src.y == move.dst.y)
{
if (move.src.x < move.dst.x)
{
for(int i = move.src.x+1; i <= move.dst.x; i++)
{
squares[square_cnt][0] = i;
squares[square_cnt++][1] = move.src.y;
}
}
else
for(int i = move.src.x-1; i >= move.dst.x; i--)
{
squares[square_cnt][0] = i;
squares[square_cnt++][1] = move.src.y;
}
}
else
{
// determine squares between src and dst on a DIAGONAL
int num = abs(move.dst.x - move.src.x);
if (num == abs(move.dst.y - move.src.y))
{
for (int i = 1; i <= num; i++)
{
if (dst.y > src.y && dst.x > src.x)
{
squares[square_cnt][0] = src.x + i;
squares[square_cnt++][1] = src.y + i;
}
else if (dst.y > src.y && dst.x < src.x)
{
squares[square_cnt][0] = src.x - i;
squares[square_cnt++][1] = src.y + i;
}
else if (dst.y < src.y && dst.x > src.x)
{
squares[square_cnt][0] = src.x + i;
squares[square_cnt++][1] = src.y - i;
}
else if (dst.y < src.y && dst.x < src.x)
{
squares[square_cnt][0] = src.x - i;
squares[square_cnt++][1] = src.y - i;
}
}
}
}
int boop = 0; // track how many pieces we go through in transit
// now 'squares' has a list of all squares being passed through
for (int i = 0; i < square_cnt; i++)
{
// if we've already seen a piece in the way and we're still
// trying to move, collision
if (boop >= 1)
return COLLISION;
Location loc = {squares[i][0], squares[i][1]};
char spot = getPiece(loc);
if (spot == EMPTY)
{
continue; // no penalty for empty squares. keep going
}
if (getColor(piece) != getColor(spot))
{
boop++; // we ran into one enemy piece. track that we did, becuase we can't go through 2 or more
}
else
{
return COLLISION;
}
}
return NO_COLLISION;
}
// Attemps to perform the move, pieces are swapped if landed on
// Returns 1 if the move succeded
// Returns 0 if the move was illegal (based on the piece moved and the state of board)
int performMove(Move move)
{
Location src = move.src;
Location dst = move.dst;
int piece = getPiece(src);
if (current_team == WHITE_TEAM)
{
// WHITE's turn
if (getColor(piece) == BLACK_PIECE)
{
return 0; // trying to move a black piece during white's turn
}
}
else
{
// BLACK's turn
if (getColor(piece) == WHITE_PIECE)
{
return 0; // trying to move a white piece during black's turn
}
}
// NOTE: Vulnerability is here
// the knight move check is placed before the bounds check, which is the vulnerability
#ifndef PATCHED
if (piece == KNIGHT_WHITE)
{
if (dst.x == src.x + 2 || dst.x == src.x - 2)
{
if (dst.y == src.y + 1 || dst.y == src.y - 1)
{
if (checkNoCollision(move))
{
swap(move);
return 1;
}
}
}
if (dst.y == src.y + 2 || dst.y == src.y - 2)
{
if (dst.x == src.x + 1 || dst.x == src.x - 1)
{
if (checkNoCollision(move))
{
swap(move);
return 1;
}
}
}
return 0;
}
#endif
// make sure they're moving within the bounds of the board
if (dst.x > WIDTH - 1 || dst.x < 0 || dst.y > HEIGHT - 1 || dst.y < 0)
return 0;
if (piece == EMPTY)
return 0;
if (piece == PAWN_WHITE)
{
if (dst.x == src.x && dst.y == (src.y + 1))
{
if (checkNoCollision(move))
{
swap(move);
return 1;
}
}
else
return 0;
}
if (piece == PAWN_BLACK)
{
if (dst.x == src.x && dst.y == (src.y - 1))
{
if (checkNoCollision(move))
{
swap(move);
return 1;
}
}
else
return 0;
}
// This is where the knight move check should happen (after the bounds check, above)
#ifdef PATCHED
if (piece == KNIGHT_WHITE)
{
if (dst.x == src.x + 2 || dst.x == src.x - 2)
{
if (dst.y == src.y + 1 || dst.y == src.y - 1)
{
if (checkNoCollision(move))
{
swap(move);
return 1;
}
}
}
if (dst.y == src.y + 2 || dst.y == src.y - 2)
{
if (dst.x == src.x + 1 || dst.x == src.x - 1)
{
if (checkNoCollision(move))
{
swap(move);
return 1;
}
}
}
return 0;
}
#endif
if (piece == KNIGHT_BLACK)
{
if (dst.x == src.x + 2 || dst.x == src.x - 2)
{
if (dst.y == src.y + 1 || dst.y == src.y - 1)
{
if (checkNoCollision(move))
{
swap(move);
return 1;
}
}
}
if (dst.y == src.y + 2 || dst.y == src.y - 2)
{
if (dst.x == src.x + 1 || dst.x == src.x - 1)
{
if (checkNoCollision(move))
{
swap(move);
return 1;
}
}
}
return 0;
}
if (piece == BISHOP_WHITE || piece == BISHOP_BLACK)
{
// bishop traveling to the right
int num = abs(dst.x - src.x);
if (num == abs(dst.y - src.y))
{ // good
if (checkNoCollision(move))
{
swap(move);
return 1;
}
}
return 0;
}
if (piece == QUEEN_WHITE || piece == QUEEN_BLACK)
{
int num = abs(dst.x - src.x);
// moving diagonal
if (num == abs(dst.y - src.y))
{ // good
if (checkNoCollision(move))
{
swap(move);
return 1;
}
}
// moving on RANK or FILE
if (dst.x == src.x || dst.y == src.y)
{
if (checkNoCollision(move))
{
swap(move);
return 1;
}
}
return 0;
}
if (piece == KING_WHITE || piece == KING_BLACK)
{
int diffx = dst.x - src.x;
int diffy = dst.y - src.y;
// king can only move 1 square.
if (abs(diffx) > 1 || abs(diffy) > 1)
return 0;
if (checkNoCollision(move))
{
swap(move);
return 1;
}
return 0;
}
if (piece == ROOK_BLACK || piece == ROOK_WHITE)
{
// moving on RANK or FILE
if (dst.x == src.x || dst.y == src.y)
{
if (checkNoCollision(move))
{
swap(move);
return 1;
}
}
return 0;
}
return 0;
}
// swap two array locations
void swap(Move move)
{
char tmp;
tmp = (*ptr_array)[move.dst.x][move.dst.y];
(*ptr_array)[move.dst.x][move.dst.y] = (*ptr_array)[move.src.x][move.src.y];
(*ptr_array)[move.src.x][move.src.y] = tmp;
}
// Verifies input is in correct move format x,y x,y
// return 1 if format is correct
// return 0 otherwise
int verifyFormat(char *buf, int len)
{
buf[len] = '\x00';
// #,# #,#
if (buf[0] >= '0' && buf[0] <= '9')
if (buf[1] == ',')
if (buf[2] >= '0' && buf[2] <= '9')
if (buf[3] == ' ')
if (buf[4] >= '0' && buf[4] <= '9')
if (buf[5] == ',')
if (buf[6] >= '0' && buf[6] <= '9')
return 1;
return 0;
}
// receive input, parse into 'move' structure
// return GOOD_INPUT for good input
// return INVALID_INPUT for bad input
// return DISPLAY_BOARD for request to display board
int parseUserInput(Move *movers)
{
size_t size = 0; // number of bytes user input
char buf[15]; // will hold user input
int num = 0;
Move tmp = {77,77,77,77}; // arbitrary default values. used later to ensure we received values
bzero(buf,15);
int status;
status = receive(STDIN, buf, sizeof(buf) - 1, &size);
if (status != 0)
{
// Error on receive
return INPUT_ERROR;
}
// Discard newline from manual input
if (buf[size-1] == '\n')
{
size--;
}
if (size == 1)
{
if (buf[0] == '9')
{
// display board
return DISPLAY_BOARD;
}
}
else if (size == 3)
{
if (buf[0] == '6' && buf[1] == '6' && buf[2] == '6')
{
return END_GAME;
}
}
else if (size != 7)
{
printf("incorrect input\n");
return INVALID_INPUT;
}
if (!verifyFormat(buf, size))
{
printf("incorrect input\n");
return INVALID_INPUT;
}
for (int i = 0; i < sizeof(buf); i++)
{
if (buf[i] <= '9' && buf[i] >= '0')
{
if (i == 0)
tmp.src.x = atoi(&buf[i]);
else if (i == 2)
tmp.src.y = atoi(&buf[i]);
else if (i == 4)
tmp.dst.x = atoi(&buf[i]);
else if (i == 6)
tmp.dst.y = atoi(&buf[i]);
}
}
if (tmp.src.x != 77 && tmp.src.y != 77 && tmp.dst.x != 77 && tmp.dst.y != 77)
{
movers->src = tmp.src;
movers->dst = tmp.dst;
return GOOD_INPUT;
}
else
{
return INVALID_INPUT;
}
}
int main(void)
{
// function pointer to print chess board
void (*displayer)(); // overwriting the below array will destroy this function pointer
// chess board
char array[WIDTH][HEIGHT];
displayer = displayboard;
ptr_array = &array;
initboard();
displayer();
Move move;
while(1)
{
// print prompt
if (current_team == WHITE_TEAM)
printf(PROMPT_WHITE);
else
printf(PROMPT_BLACK);
// receive: x,y x,y
int ret = parseUserInput(&move);
if (ret == INVALID_INPUT)
{
printf(WARNING);
continue;
}
else if (ret == DISPLAY_BOARD)
{
displayer();
continue;
}
else if (ret == END_GAME)
{
printf("good game\n");
_terminate(0);
}
else if (ret == INPUT_ERROR)
{
_terminate(0);
}
if(performMove(move))
{
// Move suceeded
printf(OK);
// Switch teams
if (current_team == WHITE_TEAM)
current_team = BLACK_TEAM;
else
current_team = WHITE_TEAM;
}
else
{
// Move was illegal
printf(NO);
}
}
return 0;
}
| 0 | 0.940802 | 1 | 0.940802 | game-dev | MEDIA | 0.844261 | game-dev | 0.980423 | 1 | 0.980423 |
magefree/mage | 1,934 | Mage.Sets/src/mage/cards/k/KozileksShrieker.java |
package mage.cards.k;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.continuous.BoostSourceEffect;
import mage.abilities.effects.common.continuous.GainAbilitySourceEffect;
import mage.abilities.keyword.DevoidAbility;
import mage.abilities.keyword.MenaceAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Duration;
import mage.constants.Zone;
/**
*
* @author LevelX2
*/
public final class KozileksShrieker extends CardImpl {
public KozileksShrieker(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{B}");
this.subtype.add(SubType.ELDRAZI);
this.subtype.add(SubType.DRONE);
this.power = new MageInt(3);
this.toughness = new MageInt(2);
// Devoid
this.addAbility(new DevoidAbility(this.color));
// {C}: Kozilek's Shrieker gets +1/+0 and gains menace until end of turn.
Effect effect = new BoostSourceEffect(1, 0, Duration.EndOfTurn);
effect.setText("{this} gets +1/+0");
Ability ability = new SimpleActivatedAbility(effect, new ManaCostsImpl<>("{C}"));
effect = new GainAbilitySourceEffect(new MenaceAbility(), Duration.EndOfTurn);
effect.setText("and gains menace until end of turn. " +
"<i>(It can't be blocked except by two or more creatures. {C} represents colorless mana.)</i>");
ability.addEffect(effect);
this.addAbility(ability);
}
private KozileksShrieker(final KozileksShrieker card) {
super(card);
}
@Override
public KozileksShrieker copy() {
return new KozileksShrieker(this);
}
}
| 0 | 0.91003 | 1 | 0.91003 | game-dev | MEDIA | 0.971109 | game-dev | 0.996057 | 1 | 0.996057 |
OpenRA/OpenRA | 14,190 | OpenRA.Mods.Common/Widgets/Logic/MapGeneratorLogic.cs | #region Copyright & License Information
/*
* Copyright (c) The OpenRA Developers and Contributors
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OpenRA.FileSystem;
using OpenRA.Mods.Common.MapGenerator;
using OpenRA.Mods.Common.Traits;
using OpenRA.Primitives;
using OpenRA.Widgets;
namespace OpenRA.Mods.Common.Widgets.Logic
{
public class MapGeneratorLogic : ChromeLogic
{
[FluentReference]
const string Tileset = "label-mapchooser-random-map-tileset";
[FluentReference]
const string MapSize = "label-mapchooser-random-map-size";
[FluentReference]
const string RandomMap = "label-mapchooser-random-map-title";
[FluentReference]
const string Generating = "label-mapchooser-random-map-generating";
[FluentReference]
const string GenerationFailed = "label-mapchooser-random-map-error";
[FluentReference("players")]
const string Players = "label-player-count";
[FluentReference("author")]
const string CreatedBy = "label-created-by";
[FluentReference]
const string MapSizeSmall = "label-map-size-small";
[FluentReference]
const string MapSizeMedium = "label-map-size-medium";
[FluentReference]
const string MapSizeLarge = "label-map-size-large";
[FluentReference]
const string MapSizeHuge = "label-map-size-huge";
public static readonly IReadOnlyDictionary<string, int2> MapSizes = new Dictionary<string, int2>()
{
{ MapSizeSmall, new int2(48, 60) },
{ MapSizeMedium, new int2(60, 90) },
{ MapSizeLarge, new int2(90, 120) },
{ MapSizeHuge, new int2(120, 160) },
};
readonly ModData modData;
readonly IEditorMapGeneratorInfo generator;
readonly IMapGeneratorSettings settings;
readonly Action<MapGenerationArgs, IReadWritePackage> onGenerate;
readonly GeneratedMapPreviewWidget preview;
readonly ScrollPanelWidget settingsPanel;
readonly Widget checkboxSettingTemplate;
readonly Widget textSettingTemplate;
readonly Widget dropdownSettingTemplate;
readonly Widget tilesetSetting;
readonly Widget sizeSetting;
readonly IReadWritePackage package;
ITerrainInfo selectedTerrain;
string selectedSize;
Size size;
volatile bool generating;
volatile bool failed;
[ObjectCreator.UseCtor]
internal MapGeneratorLogic(Widget widget, ModData modData, MapGenerationArgs initialSettings, Action<MapGenerationArgs, IReadWritePackage> onGenerate)
{
this.modData = modData;
this.onGenerate = onGenerate;
package = new ZipFileLoader.ReadWriteZipFile();
generator = modData.DefaultRules.Actors[SystemActors.EditorWorld].TraitInfos<IEditorMapGeneratorInfo>().First();
settings = generator.GetSettings();
preview = widget.Get<GeneratedMapPreviewWidget>("PREVIEW");
widget.Get("ERROR").IsVisible = () => failed;
var title = new CachedTransform<string, string>(id => FluentProvider.GetMessage(id));
var previewTitleLabel = widget.Get<LabelWidget>("TITLE");
previewTitleLabel.GetText = () => title.Update(generating ? Generating : failed ? GenerationFailed : RandomMap);
var previewDetailsLabel = widget.GetOrNull<LabelWidget>("DETAILS");
if (previewDetailsLabel != null)
{
// The default "Conquest" label is hardcoded in Map.cs
var desc = new CachedTransform<int, string>(p => "Conquest " + FluentProvider.GetMessage(Players, "players", p));
var playersOption = settings.Options.FirstOrDefault(o => o.Id == "Players") as MapGeneratorMultiIntegerChoiceOption;
previewDetailsLabel.GetText = () => desc.Update(playersOption?.Value ?? 0);
previewDetailsLabel.IsVisible = () => !failed;
}
var previewAuthorLabel = widget.GetOrNull<LabelWithTooltipWidget>("AUTHOR");
if (previewAuthorLabel != null)
{
var desc = FluentProvider.GetMessage(CreatedBy, "author", FluentProvider.GetMessage(generator.Name));
previewAuthorLabel.GetText = () => desc;
previewAuthorLabel.IsVisible = () => !failed;
}
var previewSizeLabel = widget.GetOrNull<LabelWidget>("SIZE");
if (previewSizeLabel != null)
{
var desc = new CachedTransform<Size, string>(MapChooserLogic.MapSizeLabel);
previewSizeLabel.IsVisible = () => !failed;
previewSizeLabel.GetText = () => desc.Update(size);
}
settingsPanel = widget.Get<ScrollPanelWidget>("SETTINGS_PANEL");
checkboxSettingTemplate = settingsPanel.Get<Widget>("CHECKBOX_TEMPLATE");
textSettingTemplate = settingsPanel.Get<Widget>("TEXT_TEMPLATE");
dropdownSettingTemplate = settingsPanel.Get<Widget>("DROPDOWN_TEMPLATE");
settingsPanel.Layout = new GridLayout(settingsPanel);
// Tileset and map size are handled outside the generator logic so must be created manually
var validTerrainInfos = generator.Tilesets.Select(t => modData.DefaultTerrainInfo[t]).ToList();
var tilesetLabel = FluentProvider.GetMessage(Tileset);
tilesetSetting = dropdownSettingTemplate.Clone();
tilesetSetting.Get<LabelWidget>("LABEL").GetText = () => tilesetLabel;
var label = new CachedTransform<ITerrainInfo, string>(ti => FluentProvider.GetMessage(ti.Name));
var tilesetDropdown = tilesetSetting.Get<DropDownButtonWidget>("DROPDOWN");
tilesetDropdown.GetText = () => label.Update(selectedTerrain);
tilesetDropdown.OnMouseDown = _ =>
{
ScrollItemWidget SetupItem(ITerrainInfo terrainInfo, ScrollItemWidget template)
{
bool IsSelected() => terrainInfo == selectedTerrain;
void OnClick()
{
selectedTerrain = terrainInfo;
RefreshSettings();
GenerateMap();
}
var item = ScrollItemWidget.Setup(template, IsSelected, OnClick);
var itemLabel = FluentProvider.GetMessage(terrainInfo.Name);
item.Get<LabelWidget>("LABEL").GetText = () => itemLabel;
return item;
}
tilesetDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", validTerrainInfos.Count * 30, validTerrainInfos, SetupItem);
};
var sizeLabel = FluentProvider.GetMessage(MapSize);
sizeSetting = dropdownSettingTemplate.Clone();
sizeSetting.Get<LabelWidget>("LABEL").GetText = () => sizeLabel;
var sizeDropdown = sizeSetting.Get<DropDownButtonWidget>("DROPDOWN");
var sizeDropdownLabel = new CachedTransform<string, string>(s => FluentProvider.GetMessage(s));
sizeDropdown.GetText = () => sizeDropdownLabel.Update(selectedSize);
sizeDropdown.OnMouseDown = _ =>
{
ScrollItemWidget SetupItem(string size, ScrollItemWidget template)
{
bool IsSelected() => size == selectedSize;
void OnClick()
{
selectedSize = size;
RandomizeSize();
GenerateMap();
}
var item = ScrollItemWidget.Setup(template, IsSelected, OnClick);
var label = FluentProvider.GetMessage(size);
item.Get<LabelWidget>("LABEL").GetText = () => label;
return item;
}
sizeDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", MapSizes.Count * 30, MapSizes.Keys, SetupItem);
};
var generateButton = widget.Get<ButtonWidget>("BUTTON_GENERATE");
generateButton.IsDisabled = () => generating;
generateButton.OnClick = () =>
{
settings.Randomize(Game.CosmeticRandom);
RandomizeSize();
GenerateMap();
};
selectedSize = MapSizes.Keys.Skip(1).First();
if (initialSettings != null)
{
selectedTerrain = modData.DefaultTerrainInfo[initialSettings.Tileset];
size = initialSettings.Size;
foreach (var kv in MapSizes)
if (kv.Value.X > size.Width && kv.Value.Y <= size.Width)
selectedSize = kv.Key;
settings.Initialize(initialSettings);
RefreshSettings();
var map = modData.MapCache[initialSettings.Uid];
if (map.Status == MapStatus.Available)
{
preview.Update(map);
onGenerate(initialSettings, null);
}
else
GenerateMap();
}
else
{
selectedTerrain = validTerrainInfos[0];
settings.Randomize(Game.CosmeticRandom);
RandomizeSize();
RefreshSettings();
GenerateMap();
}
}
void RandomizeSize()
{
var sizeRange = MapSizes[selectedSize];
var width = Game.CosmeticRandom.Next(sizeRange.X, sizeRange.Y);
size = new Size(width + 2, width + 2);
}
void RefreshSettings()
{
settingsPanel.RemoveChildren();
tilesetSetting.Bounds = sizeSetting.Bounds = dropdownSettingTemplate.Bounds;
settingsPanel.AddChild(tilesetSetting);
settingsPanel.AddChild(sizeSetting);
var playerCount = settings.PlayerCount;
foreach (var o in settings.Options)
{
if (o.Id == "Seed")
continue;
Widget settingWidget = null;
switch (o)
{
case MapGeneratorBooleanOption bo:
{
settingWidget = checkboxSettingTemplate.Clone();
var checkboxWidget = settingWidget.Get<CheckboxWidget>("CHECKBOX");
var label = FluentProvider.GetMessage(bo.Label);
checkboxWidget.GetText = () => label;
checkboxWidget.IsChecked = () => bo.Value;
checkboxWidget.OnClick = () =>
{
bo.Value ^= true;
GenerateMap();
};
break;
}
case MapGeneratorIntegerOption io:
{
settingWidget = textSettingTemplate.Clone();
var labelWidget = settingWidget.Get<LabelWidget>("LABEL");
var label = FluentProvider.GetMessage(io.Label);
labelWidget.GetText = () => label;
var textFieldWidget = settingWidget.Get<TextFieldWidget>("INPUT");
textFieldWidget.Type = TextFieldType.Integer;
textFieldWidget.Text = FieldSaver.FormatValue(io.Value);
textFieldWidget.OnTextEdited = () =>
{
var valid = int.TryParse(textFieldWidget.Text, out io.Value);
textFieldWidget.IsValid = () => valid;
};
textFieldWidget.OnEscKey = _ => { textFieldWidget.YieldKeyboardFocus(); return true; };
textFieldWidget.OnEnterKey = _ => { textFieldWidget.YieldKeyboardFocus(); return true; };
textFieldWidget.OnLoseFocus = GenerateMap;
break;
}
case MapGeneratorMultiIntegerChoiceOption mio:
{
settingWidget = dropdownSettingTemplate.Clone();
var labelWidget = settingWidget.Get<LabelWidget>("LABEL");
var label = FluentProvider.GetMessage(mio.Label);
labelWidget.GetText = () => label;
var labelCache = new CachedTransform<int, string>(v => FieldSaver.FormatValue(v));
var dropDownWidget = settingWidget.Get<DropDownButtonWidget>("DROPDOWN");
dropDownWidget.GetText = () => labelCache.Update(mio.Value);
dropDownWidget.OnMouseDown = _ =>
{
ScrollItemWidget SetupItem(int choice, ScrollItemWidget template)
{
bool IsSelected() => choice == mio.Value;
void OnClick()
{
mio.Value = choice;
if (o.Id == "Players")
RefreshSettings();
GenerateMap();
}
var item = ScrollItemWidget.Setup(template, IsSelected, OnClick);
var itemLabel = FieldSaver.FormatValue(choice);
item.Get<LabelWidget>("LABEL").GetText = () => itemLabel;
item.GetTooltipText = null;
return item;
}
dropDownWidget.ShowDropDown("LABEL_DROPDOWN_WITH_TOOLTIP_TEMPLATE", mio.Choices.Length * 30, mio.Choices, SetupItem);
};
break;
}
case MapGeneratorMultiChoiceOption mo:
{
var validChoices = mo.ValidChoices(selectedTerrain, playerCount);
if (!validChoices.Contains(mo.Value))
mo.Value = mo.Default?.FirstOrDefault(validChoices.Contains) ?? validChoices.FirstOrDefault();
if (mo.Label != null && validChoices.Count > 0)
{
settingWidget = dropdownSettingTemplate.Clone();
var labelWidget = settingWidget.Get<LabelWidget>("LABEL");
var label = FluentProvider.GetMessage(mo.Label);
labelWidget.GetText = () => label;
var labelCache = new CachedTransform<string, string>(v => FluentProvider.GetMessage(mo.Choices[v].Label + ".label"));
var dropDownWidget = settingWidget.Get<DropDownButtonWidget>("DROPDOWN");
dropDownWidget.GetText = () => labelCache.Update(mo.Value);
dropDownWidget.OnMouseDown = _ =>
{
ScrollItemWidget SetupItem(string choice, ScrollItemWidget template)
{
bool IsSelected() => choice == mo.Value;
void OnClick()
{
mo.Value = choice;
GenerateMap();
}
var item = ScrollItemWidget.Setup(template, IsSelected, OnClick);
var itemLabel = FluentProvider.GetMessage(mo.Choices[choice].Label + ".label");
item.Get<LabelWidget>("LABEL").GetText = () => itemLabel;
if (FluentProvider.TryGetMessage(mo.Choices[choice].Label + ".description", out var desc))
item.GetTooltipText = () => desc;
else
item.GetTooltipText = null;
return item;
}
dropDownWidget.ShowDropDown("LABEL_DROPDOWN_WITH_TOOLTIP_TEMPLATE", validChoices.Count * 30, validChoices, SetupItem);
};
}
break;
}
default:
throw new NotImplementedException($"Unhandled MapGeneratorOption type {o.GetType().Name}");
}
if (settingWidget == null)
continue;
settingWidget.IsVisible = () => true;
settingsPanel.AddChild(settingWidget);
}
}
void GenerateMap()
{
generating = true;
onGenerate(null, null);
failed = false;
preview.Clear();
Task.Run(() =>
{
try
{
var args = settings.Compile(selectedTerrain, size);
var map = generator.Generate(modData, args);
// Map UID and preview image are generated on save
map.Save(package);
args.Uid = map.Uid;
Game.RunAfterTick(() =>
{
preview.Update(map);
onGenerate(args, package);
generating = false;
});
}
catch (MapGenerationException)
{
failed = true;
generating = false;
}
});
}
bool disposed;
protected override void Dispose(bool disposing)
{
if (disposing && !disposed)
{
disposed = true;
package.Dispose();
}
base.Dispose(disposing);
}
}
}
| 0 | 0.932969 | 1 | 0.932969 | game-dev | MEDIA | 0.791968 | game-dev | 0.978236 | 1 | 0.978236 |
mariofv/LittleOrionEngine | 12,478 | Libraries/include/bullet3/Bullet3OpenCL/NarrowphaseCollision/b3OptimizedBvh.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "b3OptimizedBvh.h"
#include "b3StridingMeshInterface.h"
#include "Bullet3Geometry/b3AabbUtil.h"
b3OptimizedBvh::b3OptimizedBvh()
{
}
b3OptimizedBvh::~b3OptimizedBvh()
{
}
void b3OptimizedBvh::build(b3StridingMeshInterface* triangles, bool useQuantizedAabbCompression, const b3Vector3& bvhAabbMin, const b3Vector3& bvhAabbMax)
{
m_useQuantization = useQuantizedAabbCompression;
// NodeArray triangleNodes;
struct NodeTriangleCallback : public b3InternalTriangleIndexCallback
{
NodeArray& m_triangleNodes;
NodeTriangleCallback& operator=(NodeTriangleCallback& other)
{
m_triangleNodes.copyFromArray(other.m_triangleNodes);
return *this;
}
NodeTriangleCallback(NodeArray& triangleNodes)
: m_triangleNodes(triangleNodes)
{
}
virtual void internalProcessTriangleIndex(b3Vector3* triangle, int partId, int triangleIndex)
{
b3OptimizedBvhNode node;
b3Vector3 aabbMin, aabbMax;
aabbMin.setValue(b3Scalar(B3_LARGE_FLOAT), b3Scalar(B3_LARGE_FLOAT), b3Scalar(B3_LARGE_FLOAT));
aabbMax.setValue(b3Scalar(-B3_LARGE_FLOAT), b3Scalar(-B3_LARGE_FLOAT), b3Scalar(-B3_LARGE_FLOAT));
aabbMin.setMin(triangle[0]);
aabbMax.setMax(triangle[0]);
aabbMin.setMin(triangle[1]);
aabbMax.setMax(triangle[1]);
aabbMin.setMin(triangle[2]);
aabbMax.setMax(triangle[2]);
//with quantization?
node.m_aabbMinOrg = aabbMin;
node.m_aabbMaxOrg = aabbMax;
node.m_escapeIndex = -1;
//for child nodes
node.m_subPart = partId;
node.m_triangleIndex = triangleIndex;
m_triangleNodes.push_back(node);
}
};
struct QuantizedNodeTriangleCallback : public b3InternalTriangleIndexCallback
{
QuantizedNodeArray& m_triangleNodes;
const b3QuantizedBvh* m_optimizedTree; // for quantization
QuantizedNodeTriangleCallback& operator=(QuantizedNodeTriangleCallback& other)
{
m_triangleNodes.copyFromArray(other.m_triangleNodes);
m_optimizedTree = other.m_optimizedTree;
return *this;
}
QuantizedNodeTriangleCallback(QuantizedNodeArray& triangleNodes, const b3QuantizedBvh* tree)
: m_triangleNodes(triangleNodes), m_optimizedTree(tree)
{
}
virtual void internalProcessTriangleIndex(b3Vector3* triangle, int partId, int triangleIndex)
{
// The partId and triangle index must fit in the same (positive) integer
b3Assert(partId < (1 << MAX_NUM_PARTS_IN_BITS));
b3Assert(triangleIndex < (1 << (31 - MAX_NUM_PARTS_IN_BITS)));
//negative indices are reserved for escapeIndex
b3Assert(triangleIndex >= 0);
b3QuantizedBvhNode node;
b3Vector3 aabbMin, aabbMax;
aabbMin.setValue(b3Scalar(B3_LARGE_FLOAT), b3Scalar(B3_LARGE_FLOAT), b3Scalar(B3_LARGE_FLOAT));
aabbMax.setValue(b3Scalar(-B3_LARGE_FLOAT), b3Scalar(-B3_LARGE_FLOAT), b3Scalar(-B3_LARGE_FLOAT));
aabbMin.setMin(triangle[0]);
aabbMax.setMax(triangle[0]);
aabbMin.setMin(triangle[1]);
aabbMax.setMax(triangle[1]);
aabbMin.setMin(triangle[2]);
aabbMax.setMax(triangle[2]);
//PCK: add these checks for zero dimensions of aabb
const b3Scalar MIN_AABB_DIMENSION = b3Scalar(0.002);
const b3Scalar MIN_AABB_HALF_DIMENSION = b3Scalar(0.001);
if (aabbMax.getX() - aabbMin.getX() < MIN_AABB_DIMENSION)
{
aabbMax.setX(aabbMax.getX() + MIN_AABB_HALF_DIMENSION);
aabbMin.setX(aabbMin.getX() - MIN_AABB_HALF_DIMENSION);
}
if (aabbMax.getY() - aabbMin.getY() < MIN_AABB_DIMENSION)
{
aabbMax.setY(aabbMax.getY() + MIN_AABB_HALF_DIMENSION);
aabbMin.setY(aabbMin.getY() - MIN_AABB_HALF_DIMENSION);
}
if (aabbMax.getZ() - aabbMin.getZ() < MIN_AABB_DIMENSION)
{
aabbMax.setZ(aabbMax.getZ() + MIN_AABB_HALF_DIMENSION);
aabbMin.setZ(aabbMin.getZ() - MIN_AABB_HALF_DIMENSION);
}
m_optimizedTree->quantize(&node.m_quantizedAabbMin[0], aabbMin, 0);
m_optimizedTree->quantize(&node.m_quantizedAabbMax[0], aabbMax, 1);
node.m_escapeIndexOrTriangleIndex = (partId << (31 - MAX_NUM_PARTS_IN_BITS)) | triangleIndex;
m_triangleNodes.push_back(node);
}
};
int numLeafNodes = 0;
if (m_useQuantization)
{
//initialize quantization values
setQuantizationValues(bvhAabbMin, bvhAabbMax);
QuantizedNodeTriangleCallback callback(m_quantizedLeafNodes, this);
triangles->InternalProcessAllTriangles(&callback, m_bvhAabbMin, m_bvhAabbMax);
//now we have an array of leafnodes in m_leafNodes
numLeafNodes = m_quantizedLeafNodes.size();
m_quantizedContiguousNodes.resize(2 * numLeafNodes);
}
else
{
NodeTriangleCallback callback(m_leafNodes);
b3Vector3 aabbMin = b3MakeVector3(b3Scalar(-B3_LARGE_FLOAT), b3Scalar(-B3_LARGE_FLOAT), b3Scalar(-B3_LARGE_FLOAT));
b3Vector3 aabbMax = b3MakeVector3(b3Scalar(B3_LARGE_FLOAT), b3Scalar(B3_LARGE_FLOAT), b3Scalar(B3_LARGE_FLOAT));
triangles->InternalProcessAllTriangles(&callback, aabbMin, aabbMax);
//now we have an array of leafnodes in m_leafNodes
numLeafNodes = m_leafNodes.size();
m_contiguousNodes.resize(2 * numLeafNodes);
}
m_curNodeIndex = 0;
buildTree(0, numLeafNodes);
///if the entire tree is small then subtree size, we need to create a header info for the tree
if (m_useQuantization && !m_SubtreeHeaders.size())
{
b3BvhSubtreeInfo& subtree = m_SubtreeHeaders.expand();
subtree.setAabbFromQuantizeNode(m_quantizedContiguousNodes[0]);
subtree.m_rootNodeIndex = 0;
subtree.m_subtreeSize = m_quantizedContiguousNodes[0].isLeafNode() ? 1 : m_quantizedContiguousNodes[0].getEscapeIndex();
}
//PCK: update the copy of the size
m_subtreeHeaderCount = m_SubtreeHeaders.size();
//PCK: clear m_quantizedLeafNodes and m_leafNodes, they are temporary
m_quantizedLeafNodes.clear();
m_leafNodes.clear();
}
void b3OptimizedBvh::refit(b3StridingMeshInterface* meshInterface, const b3Vector3& aabbMin, const b3Vector3& aabbMax)
{
if (m_useQuantization)
{
setQuantizationValues(aabbMin, aabbMax);
updateBvhNodes(meshInterface, 0, m_curNodeIndex, 0);
///now update all subtree headers
int i;
for (i = 0; i < m_SubtreeHeaders.size(); i++)
{
b3BvhSubtreeInfo& subtree = m_SubtreeHeaders[i];
subtree.setAabbFromQuantizeNode(m_quantizedContiguousNodes[subtree.m_rootNodeIndex]);
}
}
else
{
}
}
void b3OptimizedBvh::refitPartial(b3StridingMeshInterface* meshInterface, const b3Vector3& aabbMin, const b3Vector3& aabbMax)
{
//incrementally initialize quantization values
b3Assert(m_useQuantization);
b3Assert(aabbMin.getX() > m_bvhAabbMin.getX());
b3Assert(aabbMin.getY() > m_bvhAabbMin.getY());
b3Assert(aabbMin.getZ() > m_bvhAabbMin.getZ());
b3Assert(aabbMax.getX() < m_bvhAabbMax.getX());
b3Assert(aabbMax.getY() < m_bvhAabbMax.getY());
b3Assert(aabbMax.getZ() < m_bvhAabbMax.getZ());
///we should update all quantization values, using updateBvhNodes(meshInterface);
///but we only update chunks that overlap the given aabb
unsigned short quantizedQueryAabbMin[3];
unsigned short quantizedQueryAabbMax[3];
quantize(&quantizedQueryAabbMin[0], aabbMin, 0);
quantize(&quantizedQueryAabbMax[0], aabbMax, 1);
int i;
for (i = 0; i < this->m_SubtreeHeaders.size(); i++)
{
b3BvhSubtreeInfo& subtree = m_SubtreeHeaders[i];
//PCK: unsigned instead of bool
unsigned overlap = b3TestQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin, quantizedQueryAabbMax, subtree.m_quantizedAabbMin, subtree.m_quantizedAabbMax);
if (overlap != 0)
{
updateBvhNodes(meshInterface, subtree.m_rootNodeIndex, subtree.m_rootNodeIndex + subtree.m_subtreeSize, i);
subtree.setAabbFromQuantizeNode(m_quantizedContiguousNodes[subtree.m_rootNodeIndex]);
}
}
}
void b3OptimizedBvh::updateBvhNodes(b3StridingMeshInterface* meshInterface, int firstNode, int endNode, int index)
{
(void)index;
b3Assert(m_useQuantization);
int curNodeSubPart = -1;
//get access info to trianglemesh data
const unsigned char* vertexbase = 0;
int numverts = 0;
PHY_ScalarType type = PHY_INTEGER;
int stride = 0;
const unsigned char* indexbase = 0;
int indexstride = 0;
int numfaces = 0;
PHY_ScalarType indicestype = PHY_INTEGER;
b3Vector3 triangleVerts[3];
b3Vector3 aabbMin, aabbMax;
const b3Vector3& meshScaling = meshInterface->getScaling();
int i;
for (i = endNode - 1; i >= firstNode; i--)
{
b3QuantizedBvhNode& curNode = m_quantizedContiguousNodes[i];
if (curNode.isLeafNode())
{
//recalc aabb from triangle data
int nodeSubPart = curNode.getPartId();
int nodeTriangleIndex = curNode.getTriangleIndex();
if (nodeSubPart != curNodeSubPart)
{
if (curNodeSubPart >= 0)
meshInterface->unLockReadOnlyVertexBase(curNodeSubPart);
meshInterface->getLockedReadOnlyVertexIndexBase(&vertexbase, numverts, type, stride, &indexbase, indexstride, numfaces, indicestype, nodeSubPart);
curNodeSubPart = nodeSubPart;
b3Assert(indicestype == PHY_INTEGER || indicestype == PHY_SHORT);
}
//triangles->getLockedReadOnlyVertexIndexBase(vertexBase,numVerts,
unsigned int* gfxbase = (unsigned int*)(indexbase + nodeTriangleIndex * indexstride);
for (int j = 2; j >= 0; j--)
{
int graphicsindex = indicestype == PHY_SHORT ? ((unsigned short*)gfxbase)[j] : gfxbase[j];
if (type == PHY_FLOAT)
{
float* graphicsbase = (float*)(vertexbase + graphicsindex * stride);
triangleVerts[j] = b3MakeVector3(
graphicsbase[0] * meshScaling.getX(),
graphicsbase[1] * meshScaling.getY(),
graphicsbase[2] * meshScaling.getZ());
}
else
{
double* graphicsbase = (double*)(vertexbase + graphicsindex * stride);
triangleVerts[j] = b3MakeVector3(b3Scalar(graphicsbase[0] * meshScaling.getX()), b3Scalar(graphicsbase[1] * meshScaling.getY()), b3Scalar(graphicsbase[2] * meshScaling.getZ()));
}
}
aabbMin.setValue(b3Scalar(B3_LARGE_FLOAT), b3Scalar(B3_LARGE_FLOAT), b3Scalar(B3_LARGE_FLOAT));
aabbMax.setValue(b3Scalar(-B3_LARGE_FLOAT), b3Scalar(-B3_LARGE_FLOAT), b3Scalar(-B3_LARGE_FLOAT));
aabbMin.setMin(triangleVerts[0]);
aabbMax.setMax(triangleVerts[0]);
aabbMin.setMin(triangleVerts[1]);
aabbMax.setMax(triangleVerts[1]);
aabbMin.setMin(triangleVerts[2]);
aabbMax.setMax(triangleVerts[2]);
quantize(&curNode.m_quantizedAabbMin[0], aabbMin, 0);
quantize(&curNode.m_quantizedAabbMax[0], aabbMax, 1);
}
else
{
//combine aabb from both children
b3QuantizedBvhNode* leftChildNode = &m_quantizedContiguousNodes[i + 1];
b3QuantizedBvhNode* rightChildNode = leftChildNode->isLeafNode() ? &m_quantizedContiguousNodes[i + 2] : &m_quantizedContiguousNodes[i + 1 + leftChildNode->getEscapeIndex()];
{
for (int i = 0; i < 3; i++)
{
curNode.m_quantizedAabbMin[i] = leftChildNode->m_quantizedAabbMin[i];
if (curNode.m_quantizedAabbMin[i] > rightChildNode->m_quantizedAabbMin[i])
curNode.m_quantizedAabbMin[i] = rightChildNode->m_quantizedAabbMin[i];
curNode.m_quantizedAabbMax[i] = leftChildNode->m_quantizedAabbMax[i];
if (curNode.m_quantizedAabbMax[i] < rightChildNode->m_quantizedAabbMax[i])
curNode.m_quantizedAabbMax[i] = rightChildNode->m_quantizedAabbMax[i];
}
}
}
}
if (curNodeSubPart >= 0)
meshInterface->unLockReadOnlyVertexBase(curNodeSubPart);
}
///deSerializeInPlace loads and initializes a BVH from a buffer in memory 'in place'
b3OptimizedBvh* b3OptimizedBvh::deSerializeInPlace(void* i_alignedDataBuffer, unsigned int i_dataBufferSize, bool i_swapEndian)
{
b3QuantizedBvh* bvh = b3QuantizedBvh::deSerializeInPlace(i_alignedDataBuffer, i_dataBufferSize, i_swapEndian);
//we don't add additional data so just do a static upcast
return static_cast<b3OptimizedBvh*>(bvh);
}
| 0 | 0.945922 | 1 | 0.945922 | game-dev | MEDIA | 0.850936 | game-dev | 0.992923 | 1 | 0.992923 |
enjarai/trickster | 2,291 | src/main/java/dev/enjarai/trickster/spell/trick/entity/StoreEntityTrick.java | package dev.enjarai.trickster.spell.trick.entity;
import dev.enjarai.trickster.entity.ModEntities;
import dev.enjarai.trickster.item.component.EntityStorageComponent;
import dev.enjarai.trickster.item.component.ModComponents;
import dev.enjarai.trickster.spell.Pattern;
import dev.enjarai.trickster.spell.SpellContext;
import dev.enjarai.trickster.spell.blunder.*;
import dev.enjarai.trickster.spell.fragment.EntityFragment;
import dev.enjarai.trickster.spell.fragment.FragmentType;
import dev.enjarai.trickster.spell.fragment.VoidFragment;
import dev.enjarai.trickster.spell.trick.Trick;
import dev.enjarai.trickster.spell.type.Signature;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.NbtCompound;
import java.util.Optional;
public class StoreEntityTrick extends Trick<StoreEntityTrick> {
public StoreEntityTrick() {
super(Pattern.of(5, 2, 4, 3, 6, 7, 4), Signature.of(FragmentType.ENTITY, StoreEntityTrick::store, FragmentType.VOID));
}
public VoidFragment store(SpellContext ctx, EntityFragment entity) throws BlunderException {
var target = entity.getEntity(ctx).orElseThrow(() -> new UnknownEntityBlunder(this));
if (target instanceof PlayerEntity)
throw new EntityInvalidBlunder(this);
if (target.getType().isIn(ModEntities.IRREPRESSIBLE))
throw new EntityCannotBeStoredBlunder(this, target);
var player = ctx.source().getPlayer().orElseThrow(() -> new NoPlayerBlunder(this));
var offhand = player.getOffHandStack();
var entityStorage = offhand.get(ModComponents.ENTITY_STORAGE);
if (entityStorage == null)
throw new ItemInvalidBlunder(this);
if (entityStorage.nbt().isEmpty()) {
var dist = player.getPos().distanceTo(target.getPos());
ctx.useMana(this, (float) (2000 + Math.pow(dist, (dist / 5))));
var compound = new NbtCompound();
target.saveSelfNbt(compound);
offhand.set(ModComponents.ENTITY_STORAGE, new EntityStorageComponent(Optional.of(compound)));
target.remove(Entity.RemovalReason.CHANGED_DIMENSION);
} else throw new EntityAlreadyStoredBlunder(this);
return VoidFragment.INSTANCE;
}
}
| 0 | 0.917354 | 1 | 0.917354 | game-dev | MEDIA | 0.964026 | game-dev | 0.965174 | 1 | 0.965174 |
ArcanaMod/Arcana | 3,894 | src/main/java/net/arcanamod/world/Node.java | package net.arcanamod.world;
import net.arcanamod.aspects.handlers.AspectBattery;
import net.arcanamod.aspects.handlers.AspectHandler;
import net.minecraft.dispenser.IPosition;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.vector.Vector3d;
import java.util.UUID;
// implements position for BlockPos constructor convenience
public class Node implements IPosition{
/** The aspects contained in the node. */
AspectHandler aspects;
/** The type of node this is. */
NodeType type;
/** The position of this node. */
double x, y, z;
/** The unique ID of this node. */
UUID nodeUniqueId = MathHelper.getRandomUUID();
/** The time, in ticks, until the node gains some aspects. */
int timeUntilRecharge;
/** Any extra data, used by the node type (e.g. hungry nodes). */
CompoundNBT data = new CompoundNBT();
public Node(AspectHandler aspects, NodeType type, double x, double y, double z, int timeUntilRecharge){
this.aspects = aspects;
this.type = type;
this.x = x;
this.y = y;
this.z = z;
this.timeUntilRecharge = timeUntilRecharge;
}
public Node(AspectHandler aspects, NodeType type, double x, double y, double z, int timeUntilRecharge, CompoundNBT data){
this.aspects = aspects;
this.type = type;
this.x = x;
this.y = y;
this.z = z;
this.timeUntilRecharge = timeUntilRecharge;
this.data = data;
}
public Node(AspectHandler aspects, NodeType type, double x, double y, double z, int timeUntilRecharge, UUID nodeUniqueId, CompoundNBT data){
this.aspects = aspects;
this.type = type;
this.x = x;
this.y = y;
this.z = z;
this.timeUntilRecharge = timeUntilRecharge;
this.nodeUniqueId = nodeUniqueId;
this.data = data;
}
public NodeType type(){
return type;
}
public CompoundNBT serializeNBT(){
CompoundNBT nbt = new CompoundNBT();
nbt.putString("type", NodeType.TYPES.inverse().get(type()).toString());
nbt.put("aspects", aspects.serializeNBT());
nbt.putDouble("x", getX());
nbt.putDouble("y", getY());
nbt.putDouble("z", getZ());
nbt.putUniqueId("nodeUniqueId", nodeUniqueId);
nbt.putInt("timeUntilRecharge", timeUntilRecharge);
nbt.put("data", data);
return nbt;
}
public static Node fromNBT(CompoundNBT nbt){
AspectHandler aspects = new AspectBattery();
aspects.deserializeNBT(nbt.getCompound("aspects"));
NodeType type = NodeType.TYPES.get(new ResourceLocation(nbt.getString("type")));
double x = nbt.getDouble("x"), y = nbt.getDouble("y"), z = nbt.getDouble("z");
int timeUntilRecharge = nbt.getInt("timeUntilRecharge");
CompoundNBT data = nbt.getCompound("data");
return nbt.hasUniqueId("nodeUniqueId") ? new Node(aspects, type, x, y, z, timeUntilRecharge, nbt.getUniqueId("nodeUniqueId"), data) : new Node(aspects, type, x, y, z, timeUntilRecharge, data);
}
public Vector3d getPosition(){
return new Vector3d(x, y, z);
}
public AspectHandler getAspects(){
return aspects;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
public double getZ(){
return z;
}
public int getTimeUntilRecharge(){
return timeUntilRecharge;
}
public void setType(NodeType type){
this.type = type;
}
public void setX(double x){
this.x = x;
}
public void setY(double y){
this.y = y;
}
public void setZ(double z){
this.z = z;
}
public void setTimeUntilRecharge(int timeUntilRecharge){
this.timeUntilRecharge = timeUntilRecharge;
}
public UUID nodeUniqueId(){
return nodeUniqueId;
}
public CompoundNBT getData(){
return data;
}
public String toString(){
return "Node{" +
"aspects=" + aspects +
", type=" + type +
", x=" + x +
", y=" + y +
", z=" + z +
", nodeUniqueId=" + nodeUniqueId +
", timeUntilRecharge=" + timeUntilRecharge +
", data=" + data +
'}';
}
} | 0 | 0.92388 | 1 | 0.92388 | game-dev | MEDIA | 0.716702 | game-dev | 0.82495 | 1 | 0.82495 |
flet-dev/examples | 3,133 | python/tutorials/solitaire/solitaire-fanned-piles/card.py | CARD_WIDTH = 70
CARD_HEIGTH = 100
DROP_PROXIMITY = 30
CARD_OFFSET = 20
import flet as ft
class Card(ft.GestureDetector):
def __init__(self, solitaire, color):
super().__init__()
self.mouse_cursor = ft.MouseCursor.MOVE
self.drag_interval = 5
self.on_pan_start = self.start_drag
self.on_pan_update = self.drag
self.on_pan_end = self.drop
self.left = None
self.top = None
self.solitaire = solitaire
self.slot = None
self.card_offset = CARD_OFFSET
self.color = color
self.content = ft.Container(
bgcolor=self.color, width=CARD_WIDTH, height=CARD_HEIGTH
)
self.draggable_pile = [self]
def move_on_top(self):
"""Brings draggable card pile to the top of the stack"""
# for card in self.get_draggable_pile():
for card in self.draggable_pile:
self.solitaire.controls.remove(card)
self.solitaire.controls.append(card)
self.solitaire.update()
def bounce_back(self):
"""Returns draggable pile to its original position"""
for card in self.draggable_pile:
card.top = card.slot.top + card.slot.pile.index(card) * CARD_OFFSET
card.left = card.slot.left
self.solitaire.update()
def place(self, slot):
"""Place draggable pile to the slot"""
for card in self.draggable_pile:
card.top = slot.top + len(slot.pile) * CARD_OFFSET
card.left = slot.left
# remove card from it's original slot, if it exists
if card.slot is not None:
card.slot.pile.remove(card)
# change card's slot to a new slot
card.slot = slot
# add card to the new slot's pile
slot.pile.append(card)
self.solitaire.update()
def get_draggable_pile(self):
"""returns list of cards that will be dragged together, starting with the current card"""
if self.slot is not None:
self.draggable_pile = self.slot.pile[self.slot.pile.index(self) :]
else: # slot == None when the cards are dealed and need to be place in slot for the first time
self.draggable_pile = [self]
def start_drag(self, e: ft.DragStartEvent):
self.get_draggable_pile()
self.move_on_top()
self.solitaire.update()
def drag(self, e: ft.DragUpdateEvent):
for card in self.draggable_pile:
card.top = (
max(0, self.top + e.delta_y)
+ self.draggable_pile.index(card) * CARD_OFFSET
)
card.left = max(0, self.left + e.delta_x)
self.solitaire.update()
def drop(self, e: ft.DragEndEvent):
for slot in self.solitaire.slots:
if (
abs(self.top - (slot.top + len(slot.pile) * CARD_OFFSET))
< DROP_PROXIMITY
and abs(self.left - slot.left) < DROP_PROXIMITY
):
self.place(slot)
self.solitaire.update()
return
self.bounce_back()
| 0 | 0.834842 | 1 | 0.834842 | game-dev | MEDIA | 0.484688 | game-dev | 0.995404 | 1 | 0.995404 |
rsmod/rsmod | 2,614 | api/inv-plugin/src/main/kotlin/org/rsmod/api/inv/HeldOpScript.kt | package org.rsmod.api.inv
import jakarta.inject.Inject
import org.rsmod.api.config.refs.components
import org.rsmod.api.player.interact.HeldInteractions
import org.rsmod.api.player.output.UpdateInventory.resendSlot
import org.rsmod.api.player.protect.ProtectedAccessLauncher
import org.rsmod.api.player.protect.clearPendingAction
import org.rsmod.api.player.ui.IfOverlayButton
import org.rsmod.api.player.ui.IfOverlayDrag
import org.rsmod.api.player.ui.ifClose
import org.rsmod.api.script.onIfOverlayButton
import org.rsmod.api.script.onIfOverlayDrag
import org.rsmod.events.EventBus
import org.rsmod.game.entity.Player
import org.rsmod.game.interact.HeldOp
import org.rsmod.game.type.interf.IfButtonOp
import org.rsmod.plugin.scripts.PluginScript
import org.rsmod.plugin.scripts.ScriptContext
public class HeldOpScript
@Inject
private constructor(
private val eventBus: EventBus,
private val interactions: HeldInteractions,
private val protectedAccess: ProtectedAccessLauncher,
) : PluginScript() {
override fun ScriptContext.startup() {
onIfOverlayButton(components.inv_items) { opHeldButton() }
onIfOverlayDrag(components.inv_items) { dragHeldButton() }
}
private fun IfOverlayButton.opHeldButton() {
if (op == IfButtonOp.Op10) {
interactions.examine(player, player.inv, comsub)
return
}
val heldOp = op.toHeldOp() ?: throw IllegalStateException("Op not supported: $this")
player.opHeld(comsub, heldOp)
}
private fun Player.opHeld(invSlot: Int, op: HeldOp) {
ifClose(eventBus)
if (isAccessProtected) {
resendSlot(inv, 0)
return
}
protectedAccess.launch(this) {
clearPendingAction()
interactions.interact(this, inv, invSlot, op)
}
}
private fun IfOverlayDrag.dragHeldButton() {
val fromSlot = selectedSlot ?: return
val intoSlot = targetSlot ?: return
player.dragHeld(fromSlot, intoSlot)
}
private fun Player.dragHeld(fromSlot: Int, intoSlot: Int) {
ifClose(eventBus)
if (isAccessProtected) {
resendSlot(inv, 0)
return
}
protectedAccess.launch(this) { invMoveToSlot(inv, inv, fromSlot, intoSlot) }
}
private fun IfButtonOp.toHeldOp(): HeldOp? =
when (this) {
IfButtonOp.Op2 -> HeldOp.Op1
IfButtonOp.Op3 -> HeldOp.Op2
IfButtonOp.Op4 -> HeldOp.Op3
IfButtonOp.Op6 -> HeldOp.Op4
IfButtonOp.Op7 -> HeldOp.Op5
else -> null
}
}
| 0 | 0.849158 | 1 | 0.849158 | game-dev | MEDIA | 0.891824 | game-dev | 0.767431 | 1 | 0.767431 |
fulpstation/fulpstation | 1,515 | code/game/objects/structures/crates_lockers/closets/secure/bar.dm | /obj/structure/closet/secure_closet/bar
name = "booze storage"
req_access = list(ACCESS_BAR)
icon_state = "cabinet"
resistance_flags = FLAMMABLE
max_integrity = 70
open_sound = 'sound/machines/closet/wooden_closet_open.ogg'
close_sound = 'sound/machines/closet/wooden_closet_close.ogg'
open_sound_volume = 25
close_sound_volume = 50
door_anim_time = 0 // no animation
paint_jobs = null
/obj/structure/closet/secure_closet/bar/PopulateContents()
..()
for(var/i in 1 to 10)
new /obj/item/reagent_containers/cup/glass/bottle/beer(src)
new /obj/item/etherealballdeployer(src)
new /obj/item/roulette_wheel_beacon(src)
/obj/structure/closet/secure_closet/bar/all_access
req_access = null
/obj/structure/closet/secure_closet/bar/lavaland_bartender_booze/PopulateContents()
new /obj/item/vending_refill/cigarette(src)
new /obj/item/vending_refill/boozeomat(src)
new /obj/item/storage/backpack/duffelbag(src)
new /obj/item/etherealballdeployer(src)
for(var/i in 1 to 14)
new /obj/item/reagent_containers/cup/glass/bottle/beer/light(src)
for(var/i in 1 to 5)
new /obj/item/reagent_containers/cup/glass/colocup(src)
/obj/structure/closet/secure_closet/bar/lavaland_bartender_clothes
name = "bartender's closet"
/obj/structure/closet/secure_closet/bar/lavaland_bartender_clothes/PopulateContents()
new /obj/item/clothing/neck/beads(src)
new /obj/item/clothing/glasses/sunglasses/reagent(src)
new /obj/item/clothing/suit/costume/hawaiian(src)
new /obj/item/clothing/shoes/sandal/beach(src)
| 0 | 0.640232 | 1 | 0.640232 | game-dev | MEDIA | 0.18954 | game-dev | 0.649603 | 1 | 0.649603 |
Dimbreath/ArknightsData | 2,451 | ja-JP/gamedata/[uc]lua/entry.lua | require "GlobalConfig";
EntryTable = {}
if CS.Torappu.VersionCompat.CUR_FUNC_VER ~= GlobalConfig.CUR_FUNC_VER then
print("The version of lua not compatible with current c#!",
CS.Torappu.VersionCompat.CUR_FUNC_VER, GlobalConfig.CUR_FUNC_VER);
EntryTable.Init = function()
end
EntryTable.Dispose = function()
CS.Torappu.Lua.LuaEntry.Init = nil;
CS.Torappu.Lua.LuaEntry.Dispose = nil;
print("Disposed");
end
CS.Torappu.Lua.LuaEntry.Init = EntryTable.Init;
CS.Torappu.Lua.LuaEntry.Dispose = EntryTable.Dispose;
return;
end
require "Base/BaseModule"
require "Feature/FeatureModule"
local eutil = CS.Torappu.Lua.Util
local function CleanLuaPreVersions()
end
local function Preprocess()
local ok, error = xpcall(CleanLuaPreVersions, debug.traceback);
if not ok then
eutil.LogHotfixError(error);
end
end
local function InitFeature()
CS.Torappu.Lua.LuaUIContext.SetDialogMgr(DlgMgr);
ModelMgr.Init();
DlgMgr.Init(
{
layoutDir = "UI/",
canvasPath = "UI/Main/LuaUIRoot",
});
TimerModel.me:BindSwitcher(Event.CreateStatic(function(open)
CS.Torappu.Lua.LuaEntry.driveUpdate = open;
end));
end
local function InitBattle()
if BattleMgr.me == nil then
error('InitBattle() must be invoked after DlgMgr.Init()')
end
require "Battle/BattleModule"
end
local function DisposeFeature()
DlgMgr.Clear();
ModelMgr.Dispose();
CS.Torappu.Lua.LuaUIContext.SetDialogMgr(nil);
end
EntryTable.Init = function ()
print("Init");
Preprocess();
local fixes = require ("Hotfixes/DefinedFix");
HotfixProcesser.Do(fixes);
local ok, error = xpcall(InitFeature, debug.traceback);
if not ok then
eutil.LogError("[InitFeature]" .. error);
end
local ok, error = xpcall(InitBattle, debug.traceback);
if not ok then
eutil.LogError("[InitBattle]" .. error);
end
end
EntryTable.Dispose = function ()
HotfixProcesser.Dispose();
local ok, error = xpcall(DisposeFeature, debug.traceback);
if not ok then
eutil.LogError("[DisposeFeature]" .. error);
end
CS.Torappu.Lua.LuaEntry.Init = nil;
CS.Torappu.Lua.LuaEntry.Update = nil;
CS.Torappu.Lua.LuaEntry.Dispose = nil;
print("Disposed");
end
EntryTable.Update = function(deltaTime)
TimerModel.me:Update(deltaTime);
end
CS.Torappu.Lua.LuaEntry.Init = EntryTable.Init;
CS.Torappu.Lua.LuaEntry.Update = EntryTable.Update;
CS.Torappu.Lua.LuaEntry.Dispose = EntryTable.Dispose; | 0 | 0.88706 | 1 | 0.88706 | game-dev | MEDIA | 0.857112 | game-dev | 0.894292 | 1 | 0.894292 |
oiuv/mud | 5,796 | kungfu/skill/tie-zhang.c | #include <ansi.h>
inherit SKILL;
mapping *action = ({
([ "action": "$N右掌一拂而起,施出「推窗望月」自侧面连消带打,登时将$n力道带斜",
"force" : 187,
"attack" : 45,
"dodge" : 33,
"parry" : 32,
"damage" : 38,
"lvl" : 0,
"skill_name" : "推窗望月",
"damage_type": "瘀伤"
]),
([ "action": "$N施出「分水擒龙」,左掌陡然沿着伸长的右臂一削而出,斩向$n的$l",
"force" : 212,
"attack" : 53,
"dodge" : 34,
"parry" : 45,
"damage" : 43,
"lvl" : 20,
"skill_name" : "推窗望月",
"damage_type": "瘀伤"
]),
([ "action": "$N一招「白云幻舞」,双臂如旋风一般一阵狂舞,刮起一阵旋转的气浪",
"force" : 224,
"attack" : 67,
"dodge" : 45,
"parry" : 53,
"damage" : 51,
"lvl" : 40,
"skill_name" : "推窗望月",
"damage_type": "瘀伤"
]),
([ "action": "$N陡然一招「掌内乾坤」,侧过身来,右臂自左肋下翻出,直拍向$n而去",
"force" : 251,
"attack" : 91,
"dodge" : 61,
"parry" : 63,
"damage" : 68,
"lvl" : 80,
"skill_name" : "掌内乾坤",
"damage_type": "瘀伤"
]),
([ "action": "$N一招「落日赶月」,伸掌一拍一收,顿时一股阴柔无比的力道向$n迸去",
"force" : 297,
"attack" : 93,
"dodge" : 81,
"parry" : 87,
"damage" : 76,
"lvl" : 120,
"skill_name" : "落日赶月",
"damage_type": "瘀伤"
]),
([ "action": "$N身行暴起,一式「蛰雷为动」,双掌横横向$n切出,呜呜呼啸之声狂作",
"force" : 310,
"attack" : 91,
"dodge" : 67,
"parry" : 71,
"damage" : 73,
"lvl" : 160,
"skill_name" : "蛰雷为动",
"damage_type": "瘀伤"
]),
([ "action": "$N一招「天罗地网」,左掌大圈而出,右掌小圈而发,两股力道同时击向$n",
"force" : 324,
"attack" : 102,
"dodge" : 71,
"parry" : 68,
"damage" : 85,
"lvl" : 200,
"skill_name" : "天罗地网",
"damage_type": "瘀伤"
]),
([ "action": "$N施一招「五指幻山」,单掌有如推门,另一掌却是迅疾无比的一推即收",
"force" : 330,
"attack" : 112,
"dodge" : 55,
"parry" : 73,
"damage" : 92,
"lvl" : 220,
"skill_name" : "五指幻山",
"damage_type": "瘀伤"
]),
([ "action": "$N突然大吼一声,一招「铁掌神威」,身行疾飞而起,再猛向$n直扑而下",
"force" : 321,
"attack" : 123,
"dodge" : 73,
"parry" : 72,
"damage" : 95,
"lvl" : 240,
"skill_name" : "铁掌神威",
"damage_type": "瘀伤"
]),
([ "action": "$N凝神静气,使出极招"RED" 铁掌之极意 "NOR"",
"force" : (int)this_player()->query_skill("force", 1)/2 + random((int)this_player()->query_skill("force", 1)),
"attack" : (int)this_player()->query_skill("strike", 1)/4 + random((int)this_player()->query_skill("strike", 1)/2),
"dodge" : (int)this_player()->query_skill("dodge", 1)/6 + random((int)this_player()->query_skill("force", 1)/3),
"parry" : (int)this_player()->query_skill("parry", 1)/6 + random((int)this_player()->query_skill("parry", 1)/3),
"damage" : (int)this_player()->query_skill("force", 1)/4 + random((int)this_player()->query_skill("strike", 1)/2),
"lvl" : 300,
"skill_name" : "极意",
"damage_type": "瘀伤"
]),
});
int valid_enable(string usage)
{
return usage == "strike" || usage == "parry";
}
int valid_learn(object me)
{
if (me->query_temp("weapon") || me->query_temp("secondary_weapon"))
return notify_fail("练铁掌掌法必须空手。\n");
if (me->query("str") < 32)
return notify_fail("你的先天臂力孱弱,难以修炼铁掌掌法。\n");
if (me->query("con") < 32)
return notify_fail("你的先天根骨孱弱,难以修炼铁掌掌法。\n");
if ((int)me->query("max_neili") < 2000)
return notify_fail("你的内力修为太弱,难以修炼铁掌掌法。\n");
if ((int)me->query_skill("force") < 230)
return notify_fail("你的内功火候不足,难以修炼铁掌掌法。\n");
if ((int)me->query_skill("strike", 1) < 150)
return notify_fail("你的基本掌法火候不够,难以修炼铁掌掌法。\n");
if ((int)me->query_skill("strike", 1) < (int)me->query_skill("tie-zhang", 1))
return notify_fail("你的基本掌法水平有限,无法领会更高深的铁掌掌法。\n");
return 1;
}
string query_skill_name(int level)
{
int i;
for (i = sizeof(action) - 1; i >= 0; i--)
if (level >= action[i]["lvl"])
return action[i]["skill_name"];
}
mapping query_action(object me, object weapon)
{
int i, level;
level = (int) me->query_skill("tie-zhang", 1);
for (i = sizeof(action); i > 0; i--)
if (level > action[i-1]["lvl"])
return action[NewRandom(i, 50, level)];
}
int practice_skill(object me)
{
int cost;
if (me->query_temp("weapon") || me->query_temp("secondary_weapon"))
return notify_fail("练铁掌掌法必须空手。\n");
if ((int)me->query("qi") < 150)
return notify_fail("你的体力太低了。\n");
cost = me->query_skill("tie-zhang", 1) / 5 + 80;
if ((int)me->query("neili") < cost)
return notify_fail("你的内力不够练铁掌掌法。\n");
me->receive_damage("qi", 120);
me->add("neili", -cost);
return 1;
}
mixed hit_ob(object me, object victim, int damage_bonus)
{
int lvl;
lvl = me->query_skill("tie-zhang", 1);
if (damage_bonus < 150 || lvl < 150)
return 0;
if (damage_bonus / 6 > victim->query_con()
&& random(2) == 1)
{
victim->receive_wound("qi", (damage_bonus - 95) / 3, me);
return random(2) ? HIR "只听$n" HIR "前胸「咔嚓」一声脆响,竟像是"
"肋骨断折的声音。\n" NOR:
HIR "$n" HIR "一声惨叫,胸前「咔嚓咔嚓」几声脆"
"响,口中鲜血狂喷。\n" NOR;
}
}
string perform_action_file(string action)
{
return __DIR__"tie-zhang/" + action;
}
| 0 | 0.875801 | 1 | 0.875801 | game-dev | MEDIA | 0.961979 | game-dev | 0.688691 | 1 | 0.688691 |
revoframework/Revo | 9,399 | Revo.Testing/Infrastructure/EventSourcedEntityTestingHelpers.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentAssertions;
using Revo.Domain.Entities.EventSourcing;
using Revo.Domain.Events;
using Revo.Infrastructure.Repositories;
namespace Revo.Testing.Infrastructure
{
public static class EventSourcedEntityTestingHelpers
{
public static void AssertEvents<T>(this T aggregate, Action<T> action,
Action<T> stateAssertion, bool loadEventsOnly, params DomainAggregateEvent[] expectedEvents)
where T : EventSourcedAggregateRoot
{
DoAssertEvents(aggregate, action, stateAssertion, loadEventsOnly,
expectedEvents
.Select<DomainAggregateEvent, Func<(DomainAggregateEvent ev,
Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)>>(x =>
{
return () => (ev: x, eventAssertion: null);
}).ToArray(), false);
}
public static void AssertEvents<T>(this T aggregate, Action<T> action,
Action<T> stateAssertion, bool loadEventsOnly,
params (DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)[]
expectedEvents)
where T : EventSourcedAggregateRoot
{
DoAssertEvents(aggregate, action, stateAssertion, loadEventsOnly,
expectedEvents
.Select<(DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion),
Func<(DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)>>(
x =>
{
return () => x;
}).ToArray(), false);
}
public static void AssertEvents<T>(this T aggregate, Action<T> action,
Action<T> stateAssertion, bool loadEventsOnly,
params Func<(DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)>[]
expectedEvents)
where T : EventSourcedAggregateRoot
{
DoAssertEvents(aggregate, action, stateAssertion, loadEventsOnly, expectedEvents, false);
}
public static void AssertAllEvents<T>(this T aggregate, Action<T> action,
Action<T> stateAssertion, bool loadEventsOnly, params DomainAggregateEvent[] expectedEvents)
where T : EventSourcedAggregateRoot
{
DoAssertEvents(aggregate, action, stateAssertion, loadEventsOnly,
expectedEvents
.Select<DomainAggregateEvent, Func<(DomainAggregateEvent ev,
Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)>>(x =>
{
return () => (ev: x, eventAssertion: null);
}).ToArray(), true);
}
public static void AssertAllEvents<T>(this T aggregate, Action<T> action,
Action<T> stateAssertion, bool loadEventsOnly,
params (DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)[]
expectedEvents)
where T : EventSourcedAggregateRoot
{
DoAssertEvents(aggregate, action, stateAssertion, loadEventsOnly,
expectedEvents
.Select<(DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion),
Func<(DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)>>(
x =>
{
return () => x;
}).ToArray(), true);
}
public static void AssertAllEvents<T>(this T aggregate, Action<T> action,
Action<T> stateAssertion, bool loadEventsOnly,
params Func<(DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)>[]
expectedEvents)
where T : EventSourcedAggregateRoot
{
DoAssertEvents(aggregate, action, stateAssertion, loadEventsOnly, expectedEvents, true);
}
public static void AssertConstructorEvents<T>(this T aggregate,
Action<T> stateAssertion, bool loadEventsOnly, params DomainAggregateEvent[] expectedEvents)
where T : EventSourcedAggregateRoot
{
AssertConstructorEvents(aggregate, stateAssertion, loadEventsOnly,
expectedEvents
.Select<DomainAggregateEvent, Func<(DomainAggregateEvent ev,
Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)>>(x =>
{
return () => (ev: x, eventAssertion: null);
}).ToArray());
}
public static void AssertConstructorEvents<T>(this T aggregate,
Action<T> stateAssertion, bool loadEventsOnly,
params (DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)[]
expectedEvents)
where T : EventSourcedAggregateRoot
{
AssertConstructorEvents(aggregate, stateAssertion, loadEventsOnly,
expectedEvents
.Select<(DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion),
Func<(DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)>>(
x =>
{
return () => x;
}).ToArray());
}
public static void AssertConstructorEvents<T>(this T aggregate,
Action<T> stateAssertion, bool loadEventsOnly,
params Func<(DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)>[]
expectedEvents)
where T : EventSourcedAggregateRoot
{
T sut;
if (loadEventsOnly)
{
IEntityFactory entityFactory = new EntityFactory();
sut = (T) entityFactory.ConstructEntity(aggregate.GetType(), aggregate.Id);
}
else
{
sut = aggregate;
}
DoAssertEvents(sut, _ => { }, stateAssertion, loadEventsOnly, expectedEvents, true);
}
private static void DoAssertEvents<T>(this T aggregate, Action<T> action,
Action<T> stateAssertion, bool loadEventsOnly,
Func<(DomainAggregateEvent ev, Action<DomainAggregateEvent, DomainAggregateEvent> eventAssertion)>[] expectedEvents,
bool assertAllEvents)
where T : EventSourcedAggregateRoot
{
if (!loadEventsOnly)
{
List<DomainAggregateEvent> newEvents;
List<DomainAggregateEvent> originalEvents = aggregate.UncommittedEvents.ToList();
action(aggregate);
if (assertAllEvents)
{
newEvents = aggregate.UncommittedEvents.ToList();
}
else
{
newEvents = aggregate.UncommittedEvents.Except(originalEvents).ToList();
}
newEvents.Should().HaveSameCount(expectedEvents);
for (int i = 0; i < newEvents.Count; i++)
{
var expectedEvent = expectedEvents[i]();
newEvents[i].Should().BeAssignableTo(expectedEvent.ev.GetType());
if (expectedEvent.eventAssertion == null)
{
//quick fix for cases when there are no comparable properties, which causes ShouldBeEquivalentTo to fail
var excludedProps = new[]
{
//nameof(DomainAggregateEvent.Id),
nameof(DomainAggregateEvent.AggregateId),
//nameof(DomainAggregateEvent.AggregateClassId),
};
if (expectedEvent.ev.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Count(x => !excludedProps.Contains(x.Name)) > 0)
{
newEvents[i].Should().BeEquivalentTo(expectedEvent.ev,
config => config
//.IncludingAllRuntimeProperties()
.RespectingRuntimeTypes()
//.Excluding(x => x.Id)
.Excluding(x => x.AggregateId)
/*.Excluding(x => x.AggregateClassId)*/);
}
}
else
{
expectedEvent.eventAssertion(expectedEvent.ev, newEvents[i]);
}
}
}
else
{
aggregate.ReplayEvents(expectedEvents.Select(x => x().ev));
}
stateAssertion(aggregate);
}
}
}
| 0 | 0.686612 | 1 | 0.686612 | game-dev | MEDIA | 0.46117 | game-dev | 0.704 | 1 | 0.704 |
ImLegiitXD/Ambient | 5,433 | src/main/java/net/minecraft/inventory/InventoryBasic.java | package net.minecraft.inventory;
import com.google.common.collect.Lists;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;
public class InventoryBasic implements IInventory {
private String inventoryTitle;
private final int slotsCount;
private final ItemStack[] inventoryContents;
private List<IInvBasic> changeListeners;
private boolean hasCustomName;
public InventoryBasic(String title, boolean customName, int slotCount) {
this.inventoryTitle = title;
this.hasCustomName = customName;
this.slotsCount = slotCount;
this.inventoryContents = new ItemStack[slotCount];
}
public InventoryBasic(IChatComponent title, int slotCount) {
this(title.getUnformattedText(), true, slotCount);
}
public void addInventoryChangeListener(IInvBasic listener) {
if (this.changeListeners == null) {
this.changeListeners = Lists.newArrayList();
}
this.changeListeners.add(listener);
}
public void removeInventoryChangeListener(IInvBasic listener) {
this.changeListeners.remove(listener);
}
public ItemStack getStackInSlot(int index) {
return index >= 0 && index < this.inventoryContents.length ? this.inventoryContents[index] : null;
}
public ItemStack decrStackSize(int index, int count) {
if (this.inventoryContents[index] != null) {
if (this.inventoryContents[index].stackSize <= count) {
ItemStack itemstack1 = this.inventoryContents[index];
this.inventoryContents[index] = null;
this.markDirty();
return itemstack1;
} else {
ItemStack itemstack = this.inventoryContents[index].splitStack(count);
if (this.inventoryContents[index].stackSize == 0) {
this.inventoryContents[index] = null;
}
this.markDirty();
return itemstack;
}
} else {
return null;
}
}
public ItemStack func_174894_a(ItemStack stack) {
ItemStack itemstack = stack.copy();
for (int i = 0; i < this.slotsCount; ++i) {
ItemStack itemstack1 = this.getStackInSlot(i);
if (itemstack1 == null) {
this.setInventorySlotContents(i, itemstack);
this.markDirty();
return null;
}
if (ItemStack.areItemsEqual(itemstack1, itemstack)) {
int j = Math.min(this.getInventoryStackLimit(), itemstack1.getMaxStackSize());
int k = Math.min(itemstack.stackSize, j - itemstack1.stackSize);
if (k > 0) {
itemstack1.stackSize += k;
itemstack.stackSize -= k;
if (itemstack.stackSize <= 0) {
this.markDirty();
return null;
}
}
}
}
if (itemstack.stackSize != stack.stackSize) {
this.markDirty();
}
return itemstack;
}
public ItemStack removeStackFromSlot(int index) {
if (this.inventoryContents[index] != null) {
ItemStack itemstack = this.inventoryContents[index];
this.inventoryContents[index] = null;
return itemstack;
} else {
return null;
}
}
public void setInventorySlotContents(int index, ItemStack stack) {
this.inventoryContents[index] = stack;
if (stack != null && stack.stackSize > this.getInventoryStackLimit()) {
stack.stackSize = this.getInventoryStackLimit();
}
this.markDirty();
}
public int getSizeInventory() {
return this.slotsCount;
}
public String getName() {
return this.inventoryTitle;
}
public boolean hasCustomName() {
return this.hasCustomName;
}
public void setCustomName(String inventoryTitleIn) {
this.hasCustomName = true;
this.inventoryTitle = inventoryTitleIn;
}
public IChatComponent getDisplayName() {
return this.hasCustomName() ? new ChatComponentText(this.getName()) : new ChatComponentTranslation(this.getName(), new Object[0]);
}
public int getInventoryStackLimit() {
return 64;
}
public void markDirty() {
if (this.changeListeners != null) {
for (IInvBasic changeListener : this.changeListeners) {
changeListener.onInventoryChanged(this);
}
}
}
public boolean isUseableByPlayer(EntityPlayer player) {
return true;
}
public void openInventory(EntityPlayer player) {
}
public void closeInventory(EntityPlayer player) {
}
public boolean isItemValidForSlot(int index, ItemStack stack) {
return true;
}
public int getField(int id) {
return 0;
}
public void setField(int id, int value) {
}
public int getFieldCount() {
return 0;
}
public void clear() {
for (int i = 0; i < this.inventoryContents.length; ++i) {
this.inventoryContents[i] = null;
}
}
}
| 0 | 0.928434 | 1 | 0.928434 | game-dev | MEDIA | 0.991778 | game-dev | 0.923731 | 1 | 0.923731 |
Pugstorm/CoreKeeperModSDK | 2,651 | Packages/com.unity.entities/DocCodeSamples.Tests/EnableableComponentExample.cs | using Unity.Entities;
using Unity.Collections;
namespace Doc.CodeSamples.Tests
{
public struct Health : IComponentData, IEnableableComponent
{
public float Value;
}
public struct Translation : IComponentData, IEnableableComponent
{
}
#region enableable-example
public partial struct EnableableComponentSystem : ISystem
{
public void OnUpdate(ref SystemState system)
{
Entity e = system.EntityManager.CreateEntity(typeof(Health));
ComponentLookup<Health> healthLookup = system.GetComponentLookup<Health>();
// true
bool b = healthLookup.IsComponentEnabled(e);
// disable the Health component of the entity
healthLookup.SetComponentEnabled(e, false);
// though disabled, the component can still be read and modified
Health h = healthLookup[e];
}
}
#endregion
#region enableable-health-example
public partial struct EnableableHealthSystem : ISystem
{
public void OnUpdate(ref SystemState system)
{
Entity e1 = system.EntityManager.CreateEntity(typeof(Health), typeof(Translation));
Entity e2 = system.EntityManager.CreateEntity(typeof(Health), typeof(Translation));
// true (components begin life enabled)
bool b = system.EntityManager.IsComponentEnabled<Health>(e1);
// disable the Health component on the first entity
system.EntityManager.SetComponentEnabled<Health>(e1, false);
EntityQuery query = new EntityQueryBuilder(Allocator.Temp).WithAll<Health, Translation>().Build(ref system);
// the returned array does not include the first entity
var entities = query.ToEntityArray(Allocator.Temp);
// the returned array does not include the Health of the first entity
var healths = query.ToComponentDataArray<Health>(Allocator.Temp);
// the returned array does not include the Translation of the first entity
var translations = query.ToComponentDataArray<Translation>(Allocator.Temp);
// This query matches components whether they're enabled or disabled
var queryIgnoreEnableable = new EntityQueryBuilder(Allocator.Temp).WithAll<Health, Translation>().WithOptions(EntityQueryOptions.IgnoreComponentEnabledState).Build(ref system);
// the returned array includes the Translations of both entities
var translationsAll = queryIgnoreEnableable.ToComponentDataArray<Translation>(Allocator.Temp);
}
}
#endregion
}
| 0 | 0.590398 | 1 | 0.590398 | game-dev | MEDIA | 0.929741 | game-dev | 0.666052 | 1 | 0.666052 |
space-wizards/space-station-14 | 5,312 | Content.Client/Instruments/UI/ChannelsMenu.xaml.cs | using Content.Shared.Instruments;
using Robust.Client.AutoGenerated;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using Robust.Client.UserInterface.XAML;
using Robust.Shared.Audio.Midi;
using Robust.Shared.Utility;
namespace Content.Client.Instruments.UI;
[GenerateTypedNameReferences]
public sealed partial class ChannelsMenu : DefaultWindow
{
[Dependency] private readonly IEntityManager _entityManager = null!;
private readonly InstrumentBoundUserInterface _owner;
public ChannelsMenu(InstrumentBoundUserInterface owner) : base()
{
RobustXamlLoader.Load(this);
IoCManager.InjectDependencies(this);
_owner = owner;
ChannelList.OnItemSelected += OnItemSelected;
ChannelList.OnItemDeselected += OnItemDeselected;
AllButton.OnPressed += OnAllPressed;
ClearButton.OnPressed += OnClearPressed;
DisplayTrackNames.OnPressed += OnDisplayTrackNamesPressed;
}
protected override void EnteredTree()
{
base.EnteredTree();
_owner.Instruments.OnChannelsUpdated += UpdateChannelList;
}
private void OnDisplayTrackNamesPressed(BaseButton.ButtonEventArgs obj)
{
DisplayTrackNames.SetClickPressed(!DisplayTrackNames.Pressed);
Populate();
}
private void UpdateChannelList()
{
Populate(); // This is kind of in-efficent because we don't filter for which instrument updated its channels, but idc
}
protected override void ExitedTree()
{
base.ExitedTree();
_owner.Instruments.OnChannelsUpdated -= UpdateChannelList;
}
private void OnItemSelected(ItemList.ItemListSelectedEventArgs args)
{
_owner.Instruments.SetFilteredChannel(_owner.Owner, (int)ChannelList[args.ItemIndex].Metadata!, false);
}
private void OnItemDeselected(ItemList.ItemListDeselectedEventArgs args)
{
_owner.Instruments.SetFilteredChannel(_owner.Owner, (int)ChannelList[args.ItemIndex].Metadata!, true);
}
private void OnAllPressed(BaseButton.ButtonEventArgs obj)
{
foreach (var item in ChannelList)
{
// TODO: Make this efficient jfc
item.Selected = true;
}
}
private void OnClearPressed(BaseButton.ButtonEventArgs obj)
{
foreach (var item in ChannelList)
{
// TODO: Make this efficient jfc
item.Selected = false;
}
}
/// <summary>
/// Walks up the tree of instrument masters to find the truest master of them all.
/// </summary>
private ActiveInstrumentComponent ResolveActiveInstrument(InstrumentComponent? comp)
{
comp ??= _entityManager.GetComponent<InstrumentComponent>(_owner.Owner);
var instrument = new Entity<InstrumentComponent>(_owner.Owner, comp);
while (true)
{
if (instrument.Comp.Master == null)
break;
instrument = new Entity<InstrumentComponent>((EntityUid)instrument.Comp.Master,
_entityManager.GetComponent<InstrumentComponent>((EntityUid)instrument.Comp.Master));
}
return _entityManager.GetComponent<ActiveInstrumentComponent>(instrument.Owner);
}
public void Populate()
{
ChannelList.Clear();
var instrument = _entityManager.GetComponent<InstrumentComponent>(_owner.Owner);
var activeInstrument = ResolveActiveInstrument(instrument);
for (int i = 0; i < RobustMidiEvent.MaxChannels; i++)
{
var label = _owner.Loc.GetString("instrument-component-channel-name",
("number", i));
if (activeInstrument != null
&& activeInstrument.Tracks.TryGetValue(i, out var resolvedMidiChannel)
&& resolvedMidiChannel != null)
{
if (DisplayTrackNames.Pressed)
{
label = resolvedMidiChannel switch
{
{ TrackName: not null, InstrumentName: not null } =>
Loc.GetString("instruments-component-channels-multi",
("channel", i),
("name", resolvedMidiChannel.TrackName),
("other", resolvedMidiChannel.InstrumentName)),
{ TrackName: not null } =>
Loc.GetString("instruments-component-channels-single",
("channel", i),
("name", resolvedMidiChannel.TrackName)),
_ => label,
};
}
else
{
label = resolvedMidiChannel switch
{
{ ProgramName: not null } =>
Loc.GetString("instruments-component-channels-single",
("channel", i),
("name", resolvedMidiChannel.ProgramName)),
_ => label,
};
}
}
var item = ChannelList.AddItem(label, null, true, i);
item.Selected = !instrument?.FilteredChannels[i] ?? false;
}
}
}
| 0 | 0.943642 | 1 | 0.943642 | game-dev | MEDIA | 0.69219 | game-dev | 0.925221 | 1 | 0.925221 |
AionGermany/aion-germany | 3,038 | AL-Game/src/com/aionemu/gameserver/spawnengine/StaticObjectSpawnManager.java | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.spawnengine;
import com.aionemu.gameserver.controllers.StaticObjectController;
import com.aionemu.gameserver.dataholders.DataManager;
import com.aionemu.gameserver.model.gameobjects.StaticObject;
import com.aionemu.gameserver.model.gameobjects.VisibleObject;
import com.aionemu.gameserver.model.templates.VisibleObjectTemplate;
import com.aionemu.gameserver.model.templates.spawns.SpawnGroup2;
import com.aionemu.gameserver.model.templates.spawns.SpawnTemplate;
import com.aionemu.gameserver.utils.idfactory.IDFactory;
import com.aionemu.gameserver.world.World;
import com.aionemu.gameserver.world.knownlist.PlayerAwareKnownList;
/**
* @author ATracer
*/
public class StaticObjectSpawnManager {
/**
* @param spawnGroup
* @param instanceIndex
*/
public static void spawnTemplate(SpawnGroup2 spawn, int instanceIndex) {
VisibleObjectTemplate objectTemplate = DataManager.ITEM_DATA.getItemTemplate(spawn.getNpcId());
if (objectTemplate == null) {
return;
}
if (spawn.hasPool()) {
spawn.resetTemplates(instanceIndex);
for (int i = 0; i < spawn.getPool(); i++) {
SpawnTemplate template = spawn.getRndTemplate(instanceIndex);
int objectId = IDFactory.getInstance().nextId();
StaticObject staticObject = new StaticObject(objectId, new StaticObjectController(), template, objectTemplate);
staticObject.setKnownlist(new PlayerAwareKnownList(staticObject));
bringIntoWorld(staticObject, template, instanceIndex);
}
}
else {
for (SpawnTemplate template : spawn.getSpawnTemplates()) {
int objectId = IDFactory.getInstance().nextId();
StaticObject staticObject = new StaticObject(objectId, new StaticObjectController(), template, objectTemplate);
staticObject.setKnownlist(new PlayerAwareKnownList(staticObject));
bringIntoWorld(staticObject, template, instanceIndex);
}
}
}
/**
* @param visibleObject
* @param spawn
* @param instanceIndex
*/
private static void bringIntoWorld(VisibleObject visibleObject, SpawnTemplate spawn, int instanceIndex) {
World world = World.getInstance();
world.storeObject(visibleObject);
world.setPosition(visibleObject, spawn.getWorldId(), instanceIndex, spawn.getX(), spawn.getY(), spawn.getZ(), spawn.getHeading());
world.spawn(visibleObject);
}
}
| 0 | 0.671483 | 1 | 0.671483 | game-dev | MEDIA | 0.986002 | game-dev | 0.596187 | 1 | 0.596187 |
DamiTheHuman/quill-framework | 1,720 | Assets/Resources/Regular Stage/Player/Data/SpriteEffectsData.cs | using UnityEngine;
[System.Serializable]
public class SpriteEffectsData
{
[HideInInspector, SerializeField]
protected string name;
[SerializeField]
protected Animator animator;
[SerializeField]
protected SpriteEffectToggle tag;
[SerializeField]
protected GameObject prefab;
[SerializeField]
protected Vector2 relativeSpawnPosition;
/// <summary>
/// Set the name of the pool data
/// </summary>
public string SetName(string name) => this.name = name;
/// <summary>
/// Get the tag of the pool data items
/// </summary>
public SpriteEffectToggle GetTag() => this.tag;
/// <summary>
/// Set the tag of the pool data items
/// </summary>
public void SetTag(SpriteEffectToggle tag) => this.tag = tag;
/// <summary>
/// Get the prefab to be cloned of the prefab
/// </summary>
public GameObject GetPrefab() => this.prefab;
/// <summary>
/// Set the prefab
/// </summary>
public void SetPrefab(GameObject prefab) => this.prefab = prefab;
/// <summary>
/// Get the relative spawn Position
/// </summary>
public Vector2 GetRelativeSpawnPosition() => this.relativeSpawnPosition;
/// <summary>
/// Set the relative spawn Position
/// </summary>
public void SetRelativeSpawnPosition(Vector2 relativeSpawnPosition) => this.relativeSpawnPosition = relativeSpawnPosition;
/// <summary>
/// Get the sprite effects Animator
/// </summary>
public Animator GetSpriteEffectAnimator() => this.animator;
/// <summary>
/// Set the sprite effects Animator
/// </summary>
public Animator SetAnimator(Animator animator) => this.animator = animator;
}
| 0 | 0.516527 | 1 | 0.516527 | game-dev | MEDIA | 0.983281 | game-dev | 0.630233 | 1 | 0.630233 |
cping/RipplePower | 32,856 | eclipse/jcoinlibs/src/org/ripple/bouncycastle/pqc/math/linearalgebra/GF2nONBElement.java | package org.ripple.bouncycastle.pqc.math.linearalgebra;
import java.math.BigInteger;
import java.util.Random;
/**
* This class implements an element of the finite field <i>GF(2<sup>n </sup>)</i>.
* It is represented in an optimal normal basis representation and holds the
* pointer <tt>mField</tt> to its corresponding field.
*
* @see GF2nField
* @see GF2nElement
*/
public class GF2nONBElement
extends GF2nElement
{
// /////////////////////////////////////////////////////////////////////
// member variables
// /////////////////////////////////////////////////////////////////////
private static final long[] mBitmask = new long[]{0x0000000000000001L,
0x0000000000000002L, 0x0000000000000004L, 0x0000000000000008L,
0x0000000000000010L, 0x0000000000000020L, 0x0000000000000040L,
0x0000000000000080L, 0x0000000000000100L, 0x0000000000000200L,
0x0000000000000400L, 0x0000000000000800L, 0x0000000000001000L,
0x0000000000002000L, 0x0000000000004000L, 0x0000000000008000L,
0x0000000000010000L, 0x0000000000020000L, 0x0000000000040000L,
0x0000000000080000L, 0x0000000000100000L, 0x0000000000200000L,
0x0000000000400000L, 0x0000000000800000L, 0x0000000001000000L,
0x0000000002000000L, 0x0000000004000000L, 0x0000000008000000L,
0x0000000010000000L, 0x0000000020000000L, 0x0000000040000000L,
0x0000000080000000L, 0x0000000100000000L, 0x0000000200000000L,
0x0000000400000000L, 0x0000000800000000L, 0x0000001000000000L,
0x0000002000000000L, 0x0000004000000000L, 0x0000008000000000L,
0x0000010000000000L, 0x0000020000000000L, 0x0000040000000000L,
0x0000080000000000L, 0x0000100000000000L, 0x0000200000000000L,
0x0000400000000000L, 0x0000800000000000L, 0x0001000000000000L,
0x0002000000000000L, 0x0004000000000000L, 0x0008000000000000L,
0x0010000000000000L, 0x0020000000000000L, 0x0040000000000000L,
0x0080000000000000L, 0x0100000000000000L, 0x0200000000000000L,
0x0400000000000000L, 0x0800000000000000L, 0x1000000000000000L,
0x2000000000000000L, 0x4000000000000000L, 0x8000000000000000L};
private static final long[] mMaxmask = new long[]{0x0000000000000001L,
0x0000000000000003L, 0x0000000000000007L, 0x000000000000000FL,
0x000000000000001FL, 0x000000000000003FL, 0x000000000000007FL,
0x00000000000000FFL, 0x00000000000001FFL, 0x00000000000003FFL,
0x00000000000007FFL, 0x0000000000000FFFL, 0x0000000000001FFFL,
0x0000000000003FFFL, 0x0000000000007FFFL, 0x000000000000FFFFL,
0x000000000001FFFFL, 0x000000000003FFFFL, 0x000000000007FFFFL,
0x00000000000FFFFFL, 0x00000000001FFFFFL, 0x00000000003FFFFFL,
0x00000000007FFFFFL, 0x0000000000FFFFFFL, 0x0000000001FFFFFFL,
0x0000000003FFFFFFL, 0x0000000007FFFFFFL, 0x000000000FFFFFFFL,
0x000000001FFFFFFFL, 0x000000003FFFFFFFL, 0x000000007FFFFFFFL,
0x00000000FFFFFFFFL, 0x00000001FFFFFFFFL, 0x00000003FFFFFFFFL,
0x00000007FFFFFFFFL, 0x0000000FFFFFFFFFL, 0x0000001FFFFFFFFFL,
0x0000003FFFFFFFFFL, 0x0000007FFFFFFFFFL, 0x000000FFFFFFFFFFL,
0x000001FFFFFFFFFFL, 0x000003FFFFFFFFFFL, 0x000007FFFFFFFFFFL,
0x00000FFFFFFFFFFFL, 0x00001FFFFFFFFFFFL, 0x00003FFFFFFFFFFFL,
0x00007FFFFFFFFFFFL, 0x0000FFFFFFFFFFFFL, 0x0001FFFFFFFFFFFFL,
0x0003FFFFFFFFFFFFL, 0x0007FFFFFFFFFFFFL, 0x000FFFFFFFFFFFFFL,
0x001FFFFFFFFFFFFFL, 0x003FFFFFFFFFFFFFL, 0x007FFFFFFFFFFFFFL,
0x00FFFFFFFFFFFFFFL, 0x01FFFFFFFFFFFFFFL, 0x03FFFFFFFFFFFFFFL,
0x07FFFFFFFFFFFFFFL, 0x0FFFFFFFFFFFFFFFL, 0x1FFFFFFFFFFFFFFFL,
0x3FFFFFFFFFFFFFFFL, 0x7FFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL};
// mIBy64[j * 16 + i] = (j * 16 + i)/64
// i =
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//
private static final int[] mIBY64 = new int[]{
// j =
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 5
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 8
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 9
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 10
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 11
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 12
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 13
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 14
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 15
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // 16
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // 17
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // 18
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // 19
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, // 20
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, // 21
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, // 22
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 // 23
};
private static final int MAXLONG = 64;
/**
* holds the lenght of the polynomial with 64 bit sized fields.
*/
private int mLength;
/**
* holds the value of mDeg % MAXLONG.
*/
private int mBit;
/**
* holds this element in ONB representation.
*/
private long[] mPol;
// /////////////////////////////////////////////////////////////////////
// constructors
// /////////////////////////////////////////////////////////////////////
/**
* Construct a random element over the field <tt>gf2n</tt>, using the
* specified source of randomness.
*
* @param gf2n the field
* @param rand the source of randomness
*/
public GF2nONBElement(GF2nONBField gf2n, Random rand)
{
mField = gf2n;
mDegree = mField.getDegree();
mLength = gf2n.getONBLength();
mBit = gf2n.getONBBit();
mPol = new long[mLength];
if (mLength > 1)
{
for (int j = 0; j < mLength - 1; j++)
{
mPol[j] = rand.nextLong();
}
long last = rand.nextLong();
mPol[mLength - 1] = last >>> (MAXLONG - mBit);
}
else
{
mPol[0] = rand.nextLong();
mPol[0] = mPol[0] >>> (MAXLONG - mBit);
}
}
/**
* Construct a new GF2nONBElement from its encoding.
*
* @param gf2n the field
* @param e the encoded element
*/
public GF2nONBElement(GF2nONBField gf2n, byte[] e)
{
mField = gf2n;
mDegree = mField.getDegree();
mLength = gf2n.getONBLength();
mBit = gf2n.getONBBit();
mPol = new long[mLength];
assign(e);
}
/**
* Construct the element of the field <tt>gf2n</tt> with the specified
* value <tt>val</tt>.
*
* @param gf2n the field
* @param val the value represented by a BigInteger
*/
public GF2nONBElement(GF2nONBField gf2n, BigInteger val)
{
mField = gf2n;
mDegree = mField.getDegree();
mLength = gf2n.getONBLength();
mBit = gf2n.getONBBit();
mPol = new long[mLength];
assign(val);
}
/**
* Construct the element of the field <tt>gf2n</tt> with the specified
* value <tt>val</tt>.
*
* @param gf2n the field
* @param val the value in ONB representation
*/
private GF2nONBElement(GF2nONBField gf2n, long[] val)
{
mField = gf2n;
mDegree = mField.getDegree();
mLength = gf2n.getONBLength();
mBit = gf2n.getONBBit();
mPol = val;
}
// /////////////////////////////////////////////////////////////////////
// pseudo-constructors
// /////////////////////////////////////////////////////////////////////
/**
* Copy constructor.
*
* @param gf2n the field
*/
public GF2nONBElement(GF2nONBElement gf2n)
{
mField = gf2n.mField;
mDegree = mField.getDegree();
mLength = ((GF2nONBField)mField).getONBLength();
mBit = ((GF2nONBField)mField).getONBBit();
mPol = new long[mLength];
assign(gf2n.getElement());
}
/**
* Create a new GF2nONBElement by cloning this GF2nPolynomialElement.
*
* @return a copy of this element
*/
public Object clone()
{
return new GF2nONBElement(this);
}
/**
* Create the zero element.
*
* @param gf2n the finite field
* @return the zero element in the given finite field
*/
public static GF2nONBElement ZERO(GF2nONBField gf2n)
{
long[] polynomial = new long[gf2n.getONBLength()];
return new GF2nONBElement(gf2n, polynomial);
}
/**
* Create the one element.
*
* @param gf2n the finite field
* @return the one element in the given finite field
*/
public static GF2nONBElement ONE(GF2nONBField gf2n)
{
int mLength = gf2n.getONBLength();
long[] polynomial = new long[mLength];
// fill mDegree coefficients with one's
for (int i = 0; i < mLength - 1; i++)
{
polynomial[i] = 0xffffffffffffffffL;
}
polynomial[mLength - 1] = mMaxmask[gf2n.getONBBit() - 1];
return new GF2nONBElement(gf2n, polynomial);
}
// /////////////////////////////////////////////////////////////////////
// assignments
// /////////////////////////////////////////////////////////////////////
/**
* assigns to this element the zero element
*/
void assignZero()
{
mPol = new long[mLength];
}
/**
* assigns to this element the one element
*/
void assignOne()
{
// fill mDegree coefficients with one's
for (int i = 0; i < mLength - 1; i++)
{
mPol[i] = 0xffffffffffffffffL;
}
mPol[mLength - 1] = mMaxmask[mBit - 1];
}
/**
* assigns to this element the value <tt>val</tt>.
*
* @param val the value represented by a BigInteger
*/
private void assign(BigInteger val)
{
assign(val.toByteArray());
}
/**
* assigns to this element the value <tt>val</tt>.
*
* @param val the value in ONB representation
*/
private void assign(long[] val)
{
System.arraycopy(val, 0, mPol, 0, mLength);
}
/**
* assigns to this element the value <tt>val</tt>. First: inverting the
* order of val into reversed[]. That means: reversed[0] = val[length - 1],
* ..., reversed[reversed.length - 1] = val[0]. Second: mPol[0] = sum{i = 0,
* ... 7} (val[i]<<(i*8)) .... mPol[1] = sum{i = 8, ... 15} (val[i]<<(i*8))
*
* @param val the value in ONB representation
*/
private void assign(byte[] val)
{
int j;
mPol = new long[mLength];
for (j = 0; j < val.length; j++)
{
mPol[j >>> 3] |= (val[val.length - 1 - j] & 0x00000000000000ffL) << ((j & 0x07) << 3);
}
}
// /////////////////////////////////////////////////////////////////
// comparison
// /////////////////////////////////////////////////////////////////
/**
* Checks whether this element is zero.
*
* @return <tt>true</tt> if <tt>this</tt> is the zero element
*/
public boolean isZero()
{
boolean result = true;
for (int i = 0; i < mLength && result; i++)
{
result = result && ((mPol[i] & 0xFFFFFFFFFFFFFFFFL) == 0);
}
return result;
}
/**
* Checks whether this element is one.
*
* @return <tt>true</tt> if <tt>this</tt> is the one element
*/
public boolean isOne()
{
boolean result = true;
for (int i = 0; i < mLength - 1 && result; i++)
{
result = result
&& ((mPol[i] & 0xFFFFFFFFFFFFFFFFL) == 0xFFFFFFFFFFFFFFFFL);
}
if (result)
{
result = result
&& ((mPol[mLength - 1] & mMaxmask[mBit - 1]) == mMaxmask[mBit - 1]);
}
return result;
}
/**
* Compare this element with another object.
*
* @param other the other object
* @return <tt>true</tt> if the two objects are equal, <tt>false</tt>
* otherwise
*/
public boolean equals(Object other)
{
if (other == null || !(other instanceof GF2nONBElement))
{
return false;
}
GF2nONBElement otherElem = (GF2nONBElement)other;
for (int i = 0; i < mLength; i++)
{
if (mPol[i] != otherElem.mPol[i])
{
return false;
}
}
return true;
}
/**
* @return the hash code of this element
*/
public int hashCode()
{
return mPol.hashCode();
}
// /////////////////////////////////////////////////////////////////////
// access
// /////////////////////////////////////////////////////////////////////
/**
* Returns whether the highest bit of the bit representation is set
*
* @return true, if the highest bit of mPol is set, false, otherwise
*/
public boolean testRightmostBit()
{
// due to the reverse bit order (compared to 1363) this method returns
// the value of the leftmost bit
return (mPol[mLength - 1] & mBitmask[mBit - 1]) != 0L;
}
/**
* Checks whether the indexed bit of the bit representation is set. Warning:
* GF2nONBElement currently stores its bits in reverse order (compared to
* 1363) !!!
*
* @param index the index of the bit to test
* @return <tt>true</tt> if the indexed bit of mPol is set, <tt>false</tt>
* otherwise.
*/
boolean testBit(int index)
{
if (index < 0 || index > mDegree)
{
return false;
}
long test = mPol[index >>> 6] & mBitmask[index & 0x3f];
return test != 0x0L;
}
/**
* @return this element in its ONB representation
*/
private long[] getElement()
{
long[] result = new long[mPol.length];
System.arraycopy(mPol, 0, result, 0, mPol.length);
return result;
}
/**
* Returns the ONB representation of this element. The Bit-Order is
* exchanged (according to 1363)!
*
* @return this element in its representation and reverse bit-order
*/
private long[] getElementReverseOrder()
{
long[] result = new long[mPol.length];
for (int i = 0; i < mDegree; i++)
{
if (testBit(mDegree - i - 1))
{
result[i >>> 6] |= mBitmask[i & 0x3f];
}
}
return result;
}
/**
* Reverses the bit-order in this element(according to 1363). This is a
* hack!
*/
void reverseOrder()
{
mPol = getElementReverseOrder();
}
// /////////////////////////////////////////////////////////////////////
// arithmetic
// /////////////////////////////////////////////////////////////////////
/**
* Compute the sum of this element and <tt>addend</tt>.
*
* @param addend the addend
* @return <tt>this + other</tt> (newly created)
* @throws DifferentFieldsException if the elements are of different fields.
*/
public GFElement add(GFElement addend)
throws RuntimeException
{
GF2nONBElement result = new GF2nONBElement(this);
result.addToThis(addend);
return result;
}
/**
* Compute <tt>this + addend</tt> (overwrite <tt>this</tt>).
*
* @param addend the addend
* @throws DifferentFieldsException if the elements are of different fields.
*/
public void addToThis(GFElement addend)
throws RuntimeException
{
if (!(addend instanceof GF2nONBElement))
{
throw new RuntimeException();
}
if (!mField.equals(((GF2nONBElement)addend).mField))
{
throw new RuntimeException();
}
for (int i = 0; i < mLength; i++)
{
mPol[i] ^= ((GF2nONBElement)addend).mPol[i];
}
}
/**
* returns <tt>this</tt> element + 1.
*
* @return <tt>this</tt> + 1
*/
public GF2nElement increase()
{
GF2nONBElement result = new GF2nONBElement(this);
result.increaseThis();
return result;
}
/**
* increases <tt>this</tt> element.
*/
public void increaseThis()
{
addToThis(ONE((GF2nONBField)mField));
}
/**
* Compute the product of this element and <tt>factor</tt>.
*
* @param factor the factor
* @return <tt>this * factor</tt> (newly created)
* @throws DifferentFieldsException if the elements are of different fields.
*/
public GFElement multiply(GFElement factor)
throws RuntimeException
{
GF2nONBElement result = new GF2nONBElement(this);
result.multiplyThisBy(factor);
return result;
}
/**
* Compute <tt>this * factor</tt> (overwrite <tt>this</tt>).
*
* @param factor the factor
* @throws DifferentFieldsException if the elements are of different fields.
*/
public void multiplyThisBy(GFElement factor)
throws RuntimeException
{
if (!(factor instanceof GF2nONBElement))
{
throw new RuntimeException("The elements have different"
+ " representation: not yet" + " implemented");
}
if (!mField.equals(((GF2nONBElement)factor).mField))
{
throw new RuntimeException();
}
if (equals(factor))
{
squareThis();
}
else
{
long[] a = mPol;
long[] b = ((GF2nONBElement)factor).mPol;
long[] c = new long[mLength];
int[][] m = ((GF2nONBField)mField).mMult;
int degf, degb, s, fielda, fieldb, bita, bitb;
degf = mLength - 1;
degb = mBit - 1;
s = 0;
long TWOTOMAXLONGM1 = mBitmask[MAXLONG - 1];
long TWOTODEGB = mBitmask[degb];
boolean old, now;
// the product c of a and b (a*b = c) is calculated in mDegree
// cicles
// in every cicle one coefficient of c is calculated and stored
// k indicates the coefficient
//
for (int k = 0; k < mDegree; k++)
{
s = 0;
for (int i = 0; i < mDegree; i++)
{
// fielda = i / MAXLONG
//
fielda = mIBY64[i];
// bita = i % MAXLONG
//
bita = i & (MAXLONG - 1);
// fieldb = m[i][0] / MAXLONG
//
fieldb = mIBY64[m[i][0]];
// bitb = m[i][0] % MAXLONG
//
bitb = m[i][0] & (MAXLONG - 1);
if ((a[fielda] & mBitmask[bita]) != 0)
{
if ((b[fieldb] & mBitmask[bitb]) != 0)
{
s ^= 1;
}
if (m[i][1] != -1)
{
// fieldb = m[i][1] / MAXLONG
//
fieldb = mIBY64[m[i][1]];
// bitb = m[i][1] % MAXLONG
//
bitb = m[i][1] & (MAXLONG - 1);
if ((b[fieldb] & mBitmask[bitb]) != 0)
{
s ^= 1;
}
}
}
}
fielda = mIBY64[k];
bita = k & (MAXLONG - 1);
if (s != 0)
{
c[fielda] ^= mBitmask[bita];
}
// Circular shift of x and y one bit to the right,
// respectively.
if (mLength > 1)
{
// Shift x.
//
old = (a[degf] & 1) == 1;
for (int i = degf - 1; i >= 0; i--)
{
now = (a[i] & 1) != 0;
a[i] = a[i] >>> 1;
if (old)
{
a[i] ^= TWOTOMAXLONGM1;
}
old = now;
}
a[degf] = a[degf] >>> 1;
if (old)
{
a[degf] ^= TWOTODEGB;
}
// Shift y.
//
old = (b[degf] & 1) == 1;
for (int i = degf - 1; i >= 0; i--)
{
now = (b[i] & 1) != 0;
b[i] = b[i] >>> 1;
if (old)
{
b[i] ^= TWOTOMAXLONGM1;
}
old = now;
}
b[degf] = b[degf] >>> 1;
if (old)
{
b[degf] ^= TWOTODEGB;
}
}
else
{
old = (a[0] & 1) == 1;
a[0] = a[0] >>> 1;
if (old)
{
a[0] ^= TWOTODEGB;
}
old = (b[0] & 1) == 1;
b[0] = b[0] >>> 1;
if (old)
{
b[0] ^= TWOTODEGB;
}
}
}
assign(c);
}
}
/**
* returns <tt>this</tt> element to the power of 2.
*
* @return <tt>this</tt><sup>2</sup>
*/
public GF2nElement square()
{
GF2nONBElement result = new GF2nONBElement(this);
result.squareThis();
return result;
}
/**
* squares <tt>this</tt> element.
*/
public void squareThis()
{
long[] pol = getElement();
int f = mLength - 1;
int b = mBit - 1;
// Shift the coefficients one bit to the left.
//
long TWOTOMAXLONGM1 = mBitmask[MAXLONG - 1];
boolean old, now;
old = (pol[f] & mBitmask[b]) != 0;
for (int i = 0; i < f; i++)
{
now = (pol[i] & TWOTOMAXLONGM1) != 0;
pol[i] = pol[i] << 1;
if (old)
{
pol[i] ^= 1;
}
old = now;
}
now = (pol[f] & mBitmask[b]) != 0;
pol[f] = pol[f] << 1;
if (old)
{
pol[f] ^= 1;
}
// Set the bit with index mDegree to zero.
//
if (now)
{
pol[f] ^= mBitmask[b + 1];
}
assign(pol);
}
/**
* Compute the multiplicative inverse of this element.
*
* @return <tt>this<sup>-1</sup></tt> (newly created)
* @throws ArithmeticException if <tt>this</tt> is the zero element.
*/
public GFElement invert()
throws ArithmeticException
{
GF2nONBElement result = new GF2nONBElement(this);
result.invertThis();
return result;
}
/**
* Multiplicatively invert of this element (overwrite <tt>this</tt>).
*
* @throws ArithmeticException if <tt>this</tt> is the zero element.
*/
public void invertThis()
throws ArithmeticException
{
if (isZero())
{
throw new ArithmeticException();
}
int r = 31; // mDegree kann nur 31 Bits lang sein!!!
// Bitlaenge von mDegree:
for (boolean found = false; !found && r >= 0; r--)
{
if (((mDegree - 1) & mBitmask[r]) != 0)
{
found = true;
}
}
r++;
GF2nElement m = ZERO((GF2nONBField)mField);
GF2nElement n = new GF2nONBElement(this);
int k = 1;
for (int i = r - 1; i >= 0; i--)
{
m = (GF2nElement)n.clone();
for (int j = 1; j <= k; j++)
{
m.squareThis();
}
n.multiplyThisBy(m);
k <<= 1;
if (((mDegree - 1) & mBitmask[i]) != 0)
{
n.squareThis();
n.multiplyThisBy(this);
k++;
}
}
n.squareThis();
}
/**
* returns the root of<tt>this</tt> element.
*
* @return <tt>this</tt><sup>1/2</sup>
*/
public GF2nElement squareRoot()
{
GF2nONBElement result = new GF2nONBElement(this);
result.squareRootThis();
return result;
}
/**
* square roots <tt>this</tt> element.
*/
public void squareRootThis()
{
long[] pol = getElement();
int f = mLength - 1;
int b = mBit - 1;
// Shift the coefficients one bit to the right.
//
long TWOTOMAXLONGM1 = mBitmask[MAXLONG - 1];
boolean old, now;
old = (pol[0] & 1) != 0;
for (int i = f; i >= 0; i--)
{
now = (pol[i] & 1) != 0;
pol[i] = pol[i] >>> 1;
if (old)
{
if (i == f)
{
pol[i] ^= mBitmask[b];
}
else
{
pol[i] ^= TWOTOMAXLONGM1;
}
}
old = now;
}
assign(pol);
}
/**
* Returns the trace of this element.
*
* @return the trace of this element
*/
public int trace()
{
// trace = sum of coefficients
//
int result = 0;
int max = mLength - 1;
for (int i = 0; i < max; i++)
{
for (int j = 0; j < MAXLONG; j++)
{
if ((mPol[i] & mBitmask[j]) != 0)
{
result ^= 1;
}
}
}
int b = mBit;
for (int j = 0; j < b; j++)
{
if ((mPol[max] & mBitmask[j]) != 0)
{
result ^= 1;
}
}
return result;
}
/**
* Solves a quadratic equation.<br>
* Let z<sup>2</sup> + z = <tt>this</tt>. Then this method returns z.
*
* @return z with z<sup>2</sup> + z = <tt>this</tt>
* @throws NoSolutionException if z<sup>2</sup> + z = <tt>this</tt> does not have a
* solution
*/
public GF2nElement solveQuadraticEquation()
throws RuntimeException
{
if (trace() == 1)
{
throw new RuntimeException();
}
long TWOTOMAXLONGM1 = mBitmask[MAXLONG - 1];
long ZERO = 0L;
long ONE = 1L;
long[] p = new long[mLength];
long z = 0L;
int j = 1;
for (int i = 0; i < mLength - 1; i++)
{
for (j = 1; j < MAXLONG; j++)
{
//
if (!((((mBitmask[j] & mPol[i]) != ZERO) && ((z & mBitmask[j - 1]) != ZERO)) || (((mPol[i] & mBitmask[j]) == ZERO) && ((z & mBitmask[j - 1]) == ZERO))))
{
z ^= mBitmask[j];
}
}
p[i] = z;
if (((TWOTOMAXLONGM1 & z) != ZERO && (ONE & mPol[i + 1]) == ONE)
|| ((TWOTOMAXLONGM1 & z) == ZERO && (ONE & mPol[i + 1]) == ZERO))
{
z = ZERO;
}
else
{
z = ONE;
}
}
int b = mDegree & (MAXLONG - 1);
long LASTLONG = mPol[mLength - 1];
for (j = 1; j < b; j++)
{
if (!((((mBitmask[j] & LASTLONG) != ZERO) && ((mBitmask[j - 1] & z) != ZERO)) || (((mBitmask[j] & LASTLONG) == ZERO) && ((mBitmask[j - 1] & z) == ZERO))))
{
z ^= mBitmask[j];
}
}
p[mLength - 1] = z;
return new GF2nONBElement((GF2nONBField)mField, p);
}
// /////////////////////////////////////////////////////////////////
// conversion
// /////////////////////////////////////////////////////////////////
/**
* Returns a String representation of this element.
*
* @return String representation of this element with the specified radix
*/
public String toString()
{
return toString(16);
}
/**
* Returns a String representation of this element. <tt>radix</tt>
* specifies the radix of the String representation.<br>
* NOTE: ONLY <tt>radix = 2</tt> or <tt>radix = 16</tt> IS IMPLEMENTED
*
* @param radix specifies the radix of the String representation
* @return String representation of this element with the specified radix
*/
public String toString(int radix)
{
String s = "";
long[] a = getElement();
int b = mBit;
if (radix == 2)
{
for (int j = b - 1; j >= 0; j--)
{
if ((a[a.length - 1] & ((long)1 << j)) == 0)
{
s += "0";
}
else
{
s += "1";
}
}
for (int i = a.length - 2; i >= 0; i--)
{
for (int j = MAXLONG - 1; j >= 0; j--)
{
if ((a[i] & mBitmask[j]) == 0)
{
s += "0";
}
else
{
s += "1";
}
}
}
}
else if (radix == 16)
{
final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
for (int i = a.length - 1; i >= 0; i--)
{
s += HEX_CHARS[(int)(a[i] >>> 60) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 56) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 52) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 48) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 44) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 40) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 36) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 32) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 28) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 24) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 20) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 16) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 12) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 8) & 0x0f];
s += HEX_CHARS[(int)(a[i] >>> 4) & 0x0f];
s += HEX_CHARS[(int)(a[i]) & 0x0f];
s += " ";
}
}
return s;
}
/**
* Returns this element as FlexiBigInt. The conversion is <a href =
* "http://grouper.ieee.org/groups/1363/">P1363</a>-conform.
*
* @return this element as BigInteger
*/
public BigInteger toFlexiBigInt()
{
/** @todo this method does not reverse the bit-order as it should!!! */
return new BigInteger(1, toByteArray());
}
/**
* Returns this element as byte array. The conversion is <a href =
* "http://grouper.ieee.org/groups/1363/">P1363</a>-conform.
*
* @return this element as byte array
*/
public byte[] toByteArray()
{
/** @todo this method does not reverse the bit-order as it should!!! */
int k = ((mDegree - 1) >> 3) + 1;
byte[] result = new byte[k];
int i;
for (i = 0; i < k; i++)
{
result[k - i - 1] = (byte)((mPol[i >>> 3] & (0x00000000000000ffL << ((i & 0x07) << 3))) >>> ((i & 0x07) << 3));
}
return result;
}
}
| 0 | 0.792355 | 1 | 0.792355 | game-dev | MEDIA | 0.222807 | game-dev | 0.830327 | 1 | 0.830327 |
SHNecro/ShanghaiJAR | 5,795 | ShanghaiEXE/Chip/EXSprayGun.cs | using NSAttack;
using NSBattle;
using NSBattle.Character;
using NSShanghaiEXE.InputOutput;
using NSShanghaiEXE.InputOutput.Audio;
using NSShanghaiEXE.InputOutput.Rendering;
using NSGame;
using Common.Vectors;
using System.Drawing;
namespace NSChip
{
internal class EXSprayGun : ChipBase
{
private const int start = 5;
private const int speed = 3;
public EXSprayGun(IAudioEngine s)
: base(s)
{
this.rockOnPoint = new Point(-2, 0);
this.number = 277;
this.name = NSGame.ShanghaiEXE.Translate("Chip.EXSprayGunName");
this.element = ChipBase.ELEMENT.poison;
this.power = 600;
this.subpower = 5;
this._break = false;
this.powerprint = true;
this.code[0] = ChipFolder.CODE.none;
this.code[1] = ChipFolder.CODE.none;
this.code[2] = ChipFolder.CODE.none;
this.code[3] = ChipFolder.CODE.none;
var information = NSGame.ShanghaiEXE.Translate("Chip.EXSprayGunDesc");
this.information[0] = information[0];
this.information[1] = information[1];
this.information[2] = information[2];
this.Init();
}
public override void Action(CharacterBase character, SceneBattle battle)
{
if (character.animationpoint.X != 5 || character.waittime == 0)
{
this.sound.PlaySE(SoundEffect.switchon);
character.animationpoint = new Point(5, 0);
}
bool gas = false;
if (character.waittime % 2 == 0)
{
gas = true;
this.sound.PlaySE(SoundEffect.lance);
}
battle.attacks.Add(new PoisonGas(this.sound, battle, character.position.X + 2 * this.UnionRebirth(character.union), character.position.Y - 1, character.union, this.subpower, gas, this.element));
battle.attacks.Add(new PoisonGas(this.sound, battle, character.position.X + 2 * this.UnionRebirth(character.union), character.position.Y, character.union, this.subpower, gas, this.element));
battle.attacks.Add(new PoisonGas(this.sound, battle, character.position.X + 2 * this.UnionRebirth(character.union), character.position.Y + 1, character.union, this.subpower, gas, this.element));
battle.attacks.Add(new PoisonGas(this.sound, battle, character.position.X + 3 * this.UnionRebirth(character.union), character.position.Y - 1, character.union, this.subpower, gas, this.element));
battle.attacks.Add(new PoisonGas(this.sound, battle, character.position.X + 3 * this.UnionRebirth(character.union), character.position.Y, character.union, this.subpower, gas, this.element));
battle.attacks.Add(new PoisonGas(this.sound, battle, character.position.X + 3 * this.UnionRebirth(character.union), character.position.Y + 1, character.union, this.subpower, gas, this.element));
++this.frame;
if (this.frame < this.power / this.subpower && (!Input.IsUp(Button._A) || !(character is Player)))
return;
this.frame = 0;
base.Action(character, battle);
}
public override void GraphicsRender(
IRenderer dg,
Vector2 p,
int c,
bool printgraphics,
bool printstatus)
{
if (!printgraphics)
return;
switch (c % 2)
{
case 0:
this._rect = new Rectangle(848, 320, 74, 79);
dg.DrawImage(dg, "menuwindows", this._rect, true, p - new Vector2(9, 16), Color.White);
this._rect = new Rectangle(56 * 6, 48 * 0, 56, 48);
dg.DrawImage(dg, "pagraphic1", this._rect, true, p, Color.White);
return;
case 1:
string[] strArray =
{
ShanghaiEXE.Translate("Chip.ProgramAdvanceEXSprayGunCombo1Line1"),
ShanghaiEXE.Translate("Chip.ProgramAdvanceEXSprayGunCombo1Line2"),
ShanghaiEXE.Translate("Chip.ProgramAdvanceEXSprayGunCombo1Line3")
};
for (int index = 0; index < strArray.Length; ++index)
{
this._position = new Vector2(p.X - 12f, p.Y - 8f + index * 16);
this.TextRender(dg, strArray[index], false, this._position, false, Color.LightBlue);
}
return;
}
}
public override void IconRender(
IRenderer dg,
Vector2 p,
bool select,
bool custom,
int c,
bool noicon)
{
if (!noicon)
{
int num = 0;
if (select)
num = 1;
this._rect = new Rectangle(624, 80 + num * 96, 16, 16);
dg.DrawImage(dg, "chipicon", this._rect, true, p, Color.White);
}
base.IconRender(dg, p, select, custom, 0, noicon);
}
public override void Render(IRenderer dg, CharacterBase character)
{
if (character.waittime < 0)
return;
this._rect = new Rectangle(8 * character.Wide, character.Height, character.Wide, character.Height);
this._position = new Vector2(character.positionDirect.X + Shake.X, character.positionDirect.Y + Shake.Y);
if (character.waittime % 2 == 1)
this._rect.X += character.Wide;
dg.DrawImage(dg, "weapons", this._rect, false, this._position, character.union == Panel.COLOR.blue, Color.White);
}
}
}
| 0 | 0.92169 | 1 | 0.92169 | game-dev | MEDIA | 0.982891 | game-dev | 0.91934 | 1 | 0.91934 |
ProjectIgnis/CardScripts | 3,885 | official/c38606913.lua | --方界縁起
--Cubic Causality
--scripted by Naim
local s,id=GetID()
function s.initial_effect(c)
--counters
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_COUNTER)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,id)
e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER|TIMING_END_PHASE)
e1:SetTarget(s.target)
e1:SetOperation(s.operation)
c:RegisterEffect(e1)
--damage
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_DISABLE)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetRange(LOCATION_GRAVE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetHintTiming(0,TIMING_BATTLE_START)
e2:SetCountLimit(1,{id,1})
e2:SetCost(Cost.SelfBanish)
e2:SetTarget(s.damtg)
e2:SetOperation(s.damact)
c:RegisterEffect(e2)
end
s.counter_place_list={0x1038}
s.listed_series={SET_CUBIC}
function s.cfilter(c)
return c:IsFaceup() and c:IsSetCard(SET_CUBIC)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.cfilter,tp,LOCATION_MZONE,0,1,nil)
and Duel.IsExistingMatchingCard(Card.IsFaceup,tp,0,LOCATION_MZONE,1,nil) end
end
function s.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local ct=Duel.GetMatchingGroupCount(s.cfilter,tp,LOCATION_MZONE,0,nil)
local g=Duel.GetMatchingGroup(Card.IsFaceup,tp,0,LOCATION_MZONE,nil)
if ct>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local sg=g:Select(tp,1,ct,nil)
local ac=sg:GetFirst()
for ac in aux.Next(sg) do
ac:AddCounter(0x1038,1)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_ATTACK)
e1:SetCondition(s.condition)
e1:SetReset(RESET_EVENT|RESETS_STANDARD)
ac:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_DISABLE)
ac:RegisterEffect(e2)
end
end
end
function s.condition(e)
return e:GetHandler():GetCounter(0x1038)>0
end
function s.tgfilter(c)
return c:IsFaceup() and c:IsSetCard(SET_CUBIC)
end
function s.damtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsControler(tp) and s.tgfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(s.tgfilter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,s.tgfilter,tp,LOCATION_MZONE,0,1,1,nil)
end
function s.damact(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e1:SetCode(EVENT_LEAVE_FIELD_P)
e1:SetOperation(s.shchk)
e1:SetLabelObject(tc)
e1:SetReset(RESET_PHASE|PHASE_END)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,2))
e2:SetCategory(CATEGORY_DAMAGE)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_BATTLE_DESTROYING)
e2:SetCondition(s.shcon)
e2:SetOperation(s.damop)
e2:SetLabelObject(tc)
e2:SetReset(RESET_PHASE|PHASE_END)
Duel.RegisterEffect(e2,tp)
tc:RegisterFlagEffect(id,RESET_EVENT|RESETS_STANDARD_PHASE_END&~(RESET_LEAVE|RESET_TOGRAVE),0,1)
tc:CreateEffectRelation(e1)
end
end
function s.shchk(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
if not tc or not tc:IsRelateToEffect(e) then return end
local bt=tc:GetBattleTarget()
for tc in aux.Next(eg) do
if bt==tc and tc:GetCounter(0x1038) > 0 then
tc:RegisterFlagEffect(id+2,RESET_CHAIN,0,1)
end
end
end
function s.shcon(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
local bt=tc:GetBattleTarget()
return tc and tc:GetFlagEffect(id)~=0 and bt and bt:GetFlagEffect(id+2) ~= 0
end
function s.damop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
local bt=tc:GetBattleTarget()
local atk=bt:GetBaseAttack()
Duel.Damage(1-tp,atk,REASON_EFFECT)
end | 0 | 0.96906 | 1 | 0.96906 | game-dev | MEDIA | 0.980481 | game-dev | 0.975747 | 1 | 0.975747 |
The-Legion-Preservation-Project/LegionCore-7.3.5 | 19,508 | src/server/scripts/Northrend/zone_storm_peaks.cpp | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; 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 "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedGossip.h"
#include "ScriptedEscortAI.h"
#include "SpellScript.h"
#include "SpellAuraEffects.h"
#include "Vehicle.h"
#include "CombatAI.h"
#include "Player.h"
#include "WorldSession.h"
/*######
## npc_frostborn_scout
######*/
#define GOSSIP_ITEM1 "Are you okay? I've come to take you back to Frosthold if you can stand."
#define GOSSIP_ITEM2 "I'm sorry that I didn't get here sooner. What happened?"
#define GOSSIP_ITEM3 "I'll go get some help. Hang in there."
enum eFrostbornScout
{
QUEST_MISSING_SCOUTS = 12864
};
class npc_frostborn_scout : public CreatureScript
{
public:
npc_frostborn_scout() : CreatureScript("npc_frostborn_scout") { }
bool OnGossipHello(Player* player, Creature* creature) override
{
if (player->GetQuestStatus(QUEST_MISSING_SCOUTS) == QUEST_STATUS_INCOMPLETE)
{
player->ADD_GOSSIP_ITEM(GossipOptionNpc::None, GOSSIP_ITEM1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
player->PlayerTalkClass->SendGossipMenu(13611, creature->GetGUID());
}
return true;
}
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override
{
player->PlayerTalkClass->ClearMenus();
switch (action)
{
case GOSSIP_ACTION_INFO_DEF+1:
player->ADD_GOSSIP_ITEM(GossipOptionNpc::None, GOSSIP_ITEM2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
player->PlayerTalkClass->SendGossipMenu(13612, creature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+2:
player->ADD_GOSSIP_ITEM(GossipOptionNpc::None, GOSSIP_ITEM3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3);
player->PlayerTalkClass->SendGossipMenu(13613, creature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+3:
player->PlayerTalkClass->SendGossipMenu(13614, creature->GetGUID());
player->AreaExploredOrEventHappens(QUEST_MISSING_SCOUTS);
break;
}
return true;
}
};
/////////////////////
///npc_injured_goblin
/////////////////////
enum eInjuredGoblin
{
QUEST_BITTER_DEPARTURE = 12832,
SAY_QUEST_ACCEPT = -1800042,
SAY_END_WP_REACHED = -1800043
};
#define GOSSIP_ITEM_1 "I am ready, lets get you out of here"
class npc_injured_goblin : public CreatureScript
{
public:
npc_injured_goblin() : CreatureScript("npc_injured_goblin") { }
struct npc_injured_goblinAI : public npc_escortAI
{
npc_injured_goblinAI(Creature* creature) : npc_escortAI(creature) { }
void WaypointReached(uint32 waypointId) override
{
Player* player = GetPlayerForEscort();
if (!player)
return;
switch (waypointId)
{
case 26:
DoScriptText(SAY_END_WP_REACHED, me, player);
break;
case 27:
player->GroupEventHappens(QUEST_BITTER_DEPARTURE, me);
break;
}
}
void EnterCombat(Unit* /*who*/) override {}
void Reset() override {}
void JustDied(Unit* /*killer*/) override
{
Player* player = GetPlayerForEscort();
if (HasEscortState(STATE_ESCORT_ESCORTING) && player)
player->FailQuest(QUEST_BITTER_DEPARTURE);
}
void UpdateAI(uint32 uiDiff) override
{
npc_escortAI::UpdateAI(uiDiff);
if (!UpdateVictim())
return;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_injured_goblinAI(creature);
}
bool OnGossipHello(Player* player, Creature* creature) override
{
if (creature->isQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
if (player->GetQuestStatus(QUEST_BITTER_DEPARTURE) == QUEST_STATUS_INCOMPLETE)
{
player->ADD_GOSSIP_ITEM(GossipOptionNpc::None, GOSSIP_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
player->PlayerTalkClass->SendGossipMenu(9999999, creature->GetGUID());
}
else
player->SEND_GOSSIP_MENU(999999, creature->GetGUID());
return true;
}
bool OnQuestAccept(Player* /*player*/, Creature* creature, Quest const* quest) override
{
if (quest->GetQuestId() == QUEST_BITTER_DEPARTURE)
DoScriptText(SAY_QUEST_ACCEPT, creature);
return false;
}
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override
{
player->PlayerTalkClass->ClearMenus();
npc_escortAI* pEscortAI = CAST_AI(npc_injured_goblin::npc_injured_goblinAI, creature->AI());
if (action == GOSSIP_ACTION_INFO_DEF+1)
{
pEscortAI->Start(true, true, player->GetGUID());
creature->setFaction(113);
}
return true;
}
};
/*######
## npc_roxi_ramrocket
######*/
#define SPELL_MECHANO_HOG 60866
#define SPELL_MEKGINEERS_CHOPPER 60867
class npc_roxi_ramrocket : public CreatureScript
{
public:
npc_roxi_ramrocket() : CreatureScript("npc_roxi_ramrocket") { }
bool OnGossipHello(Player* player, Creature* creature) override
{
//Quest Menu
if (creature->isQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
//Trainer Menu
if ( creature->isTrainer() )
player->ADD_GOSSIP_ITEM(GossipOptionNpc::Trainer, GOSSIP_TEXT_TRAIN, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRAIN);
//Vendor Menu
if ( creature->isVendor() )
if (player->HasSpell(SPELL_MECHANO_HOG) || player->HasSpell(SPELL_MEKGINEERS_CHOPPER))
player->ADD_GOSSIP_ITEM(GossipOptionNpc::Vendor, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE);
player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override
{
player->PlayerTalkClass->ClearMenus();
switch (action)
{
case GOSSIP_ACTION_TRAIN:
player->GetSession()->SendTrainerList(creature->GetGUID());
break;
case GOSSIP_ACTION_TRADE:
player->GetSession()->SendListInventory(creature->GetGUID());
break;
}
return true;
}
};
/*######
## npc_brunnhildar_prisoner
######*/
enum brunhildar {
NPC_QUEST_GIVER = 29592,
SPELL_ICE_PRISON = 54894,
SPELL_KILL_CREDIT_PRISONER = 55144,
SPELL_KILL_CREDIT_DRAKE = 55143,
SPELL_SUMMON_LIBERATED = 55073,
SPELL_ICE_LANCE = 55046
};
class npc_brunnhildar_prisoner : public CreatureScript
{
public:
npc_brunnhildar_prisoner() : CreatureScript("npc_brunnhildar_prisoner") { }
struct npc_brunnhildar_prisonerAI : public ScriptedAI
{
npc_brunnhildar_prisonerAI(Creature* creature) : ScriptedAI(creature) {}
ObjectGuid drakeGUID;
uint16 enter_timer;
bool hasEmptySeats;
void Reset() override
{
me->CastSpell(me, SPELL_ICE_PRISON, true);
enter_timer = 0;
drakeGUID.Clear();
hasEmptySeats = false;
}
void UpdateAI(uint32 diff) override
{
//TODO: not good script
if (!drakeGUID)
return;
Creature* drake = Unit::GetCreature(*me, drakeGUID);
if (!drake)
{
drakeGUID.Clear();
return;
}
// drake unsummoned, passengers dropped
if (!me->IsOnVehicle(drake) && !hasEmptySeats)
me->DespawnOrUnsummon(3000);
if (enter_timer <= 0)
return;
if (enter_timer < diff)
{
enter_timer = 0;
if (hasEmptySeats)
me->JumpTo(drake, 25.0f);
else
Reset();
}
else
enter_timer -= diff;
}
void MoveInLineOfSight(Unit* who) override
{
if (!who || !drakeGUID)
return;
Creature* drake = Unit::GetCreature(*me, drakeGUID);
if (!drake)
{
drakeGUID.Clear();
return;
}
if (!me->IsOnVehicle(drake) && !me->HasAura(SPELL_ICE_PRISON))
{
if (who->IsVehicle() && me->IsWithinDist(who, 25.0f, true) && who->ToCreature() && who->ToCreature()->GetEntry() == 29709)
{
SeatMap::const_iterator _Seat = who->GetVehicleKit()->GetNextEmptySeat(0, true);
uint8 seat = _Seat->first;
if (seat <= 0)
return;
me->EnterVehicle(who, seat);
hasEmptySeats = false;
}
}
if (who->ToCreature() && me->IsOnVehicle(drake))
{
if (who->ToCreature()->GetEntry() == NPC_QUEST_GIVER && me->IsWithinDist(who, 15.0f, false))
{
Unit* rider = drake->GetVehicleKit()->GetPassenger(0);
if (!rider)
return;
rider->CastSpell(rider, SPELL_KILL_CREDIT_PRISONER, true);
me->ExitVehicle();
me->CastSpell(me, SPELL_SUMMON_LIBERATED, true);
me->DespawnOrUnsummon(500);
// drake is empty now, deliver credit for drake and despawn him
if (drake->GetVehicleKit()->HasEmptySeat(1) &&
drake->GetVehicleKit()->HasEmptySeat(2) &&
drake->GetVehicleKit()->HasEmptySeat(3))
{
// not working rider->CastSpell(rider, SPELL_KILL_CREDIT_DRAKE, true);
if (rider->ToPlayer())
rider->ToPlayer()->KilledMonsterCredit(29709, ObjectGuid::Empty);
drake->DespawnOrUnsummon(0);
}
}
}
}
void SpellHit(Unit* hitter, const SpellInfo* spell) override
{
if (!hitter || !spell)
return;
if (spell->Id != SPELL_ICE_LANCE)
return;
me->RemoveAura(SPELL_ICE_PRISON);
enter_timer = 500;
if (hitter->IsVehicle())
drakeGUID = hitter->GetGUID();
else
return;
SeatMap::const_iterator _Seat = hitter->GetVehicleKit()->GetNextEmptySeat(0, true);
if (_Seat != hitter->GetVehicleKit()->Seats.end())
hasEmptySeats = true;
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_brunnhildar_prisonerAI(creature);
}
};
/*######
## npc_freed_protodrake
######*/
enum FreedProtoDrake
{
AREA_VALLEY_OF_ANCIENT_WINTERS = 4437,
TEXT_EMOTE = 0
};
const Position FreedDrakeWaypoints[5] =
{
{ 7332.343f, -2359.76f, 814.363f, 0.f},
{ 7154.399f, -2206.755f, 821.177f, 0.f},
{ 7118.382f, -2067.392f, 822.963f, 0.f},
{ 7047.499f, -1853.361f, 849.67f, 0.f},
{ 7059.121f, -1730.347f, 825.019f, 0.f},
};
class npc_freed_protodrake : public CreatureScript
{
public:
npc_freed_protodrake() : CreatureScript("npc_freed_protodrake") { }
struct npc_freed_protodrakeAI : public VehicleAI
{
npc_freed_protodrakeAI(Creature* creature) : VehicleAI(creature) {}
bool autoMove;
bool wpstart;
uint16 CheckTimer;
void Reset() override
{
autoMove = false;
wpstart = false;
CheckTimer = 5000;
}
void MovementInform(uint32 type, uint32 id) override
{
if (type != POINT_MOTION_TYPE)
return;
switch (id)
{
case 0:
case 1:
case 2:
case 3:
me->AddDelayedEvent(100, [this, id] {
me->GetMotionMaster()->MovePoint(id + 1, FreedDrakeWaypoints[id + 1]);
});
break;
case 4:
{
auto unit = me->GetVehicleKit()->GetPassenger(0);
if (unit && unit->GetTypeId() == TYPEID_PLAYER)
{
for (uint8 i = 1; i < 4; ++i)
if (Unit* prisoner = me->GetVehicleKit()->GetPassenger(i))
{
if (prisoner->GetTypeId() != TYPEID_UNIT)
return;
prisoner->CastSpell(unit, SPELL_KILL_CREDIT_PRISONER, true);
prisoner->CastSpell(prisoner, SPELL_SUMMON_LIBERATED, true);
prisoner->ExitVehicle();
}
me->CastSpell(me, SPELL_KILL_CREDIT_DRAKE, true);
unit->ExitVehicle();
}
break;
}
}
}
void UpdateAI(uint32 diff) override
{
if (!autoMove)
{
if (CheckTimer < diff)
{
CheckTimer = 3000;
if (me->GetAreaId() == AREA_VALLEY_OF_ANCIENT_WINTERS)
{
Talk(TEXT_EMOTE, me->GetVehicleKit()->GetPassenger(0)->GetGUID());
autoMove = true;
if (!wpstart && autoMove)
{
wpstart = true;
me->GetMotionMaster()->MovePoint(0, FreedDrakeWaypoints[0]);
}
}
}
else
CheckTimer -= diff;
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_freed_protodrakeAI(creature);
}
};
class npc_icefang : public CreatureScript
{
public:
npc_icefang() : CreatureScript("npc_icefang") { }
struct npc_icefangAI : public npc_escortAI
{
npc_icefangAI(Creature* creature) : npc_escortAI(creature) {}
void AttackStart(Unit* /*who*/) override {}
void EnterCombat(Unit* /*who*/) override {}
void EnterEvadeMode() override {}
void PassengerBoarded(Unit* who, int8 /*seatId*/, bool apply) override
{
if (who->GetTypeId() == TYPEID_PLAYER)
{
if (apply)
Start(false, true, who->GetGUID());
}
}
void WaypointReached(uint32 /*waypointId*/) override
{
}
void JustDied(Unit* /*killer*/) override
{
}
void OnCharmed(bool /*apply*/) override
{
}
void UpdateAI(uint32 diff) override
{
npc_escortAI::UpdateAI(diff);
if (!UpdateVictim())
return;
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_icefangAI (creature);
}
};
class npc_hyldsmeet_protodrake : public CreatureScript
{
enum NPCs
{
NPC_HYLDSMEET_DRAKERIDER = 29694
};
public:
npc_hyldsmeet_protodrake() : CreatureScript("npc_hyldsmeet_protodrake") { }
class npc_hyldsmeet_protodrakeAI : public CreatureAI
{
public:
npc_hyldsmeet_protodrakeAI(Creature* creature) : CreatureAI(creature), _accessoryRespawnTimer(0), _vehicleKit(creature->GetVehicleKit()) {}
void PassengerBoarded(Unit* who, int8 /*seat*/, bool apply) override
{
if (apply)
return;
if (who->GetEntry() == NPC_HYLDSMEET_DRAKERIDER)
_accessoryRespawnTimer = 5 * MINUTE * IN_MILLISECONDS;
}
void UpdateAI(uint32 diff) override
{
//! We need to manually reinstall accessories because the vehicle itself is friendly to players,
//! so EnterEvadeMode is never triggered. The accessory on the other hand is hostile and killable.
if (_accessoryRespawnTimer && _accessoryRespawnTimer <= diff && _vehicleKit)
{
_vehicleKit->InstallAllAccessories(true);
_accessoryRespawnTimer = 0;
}
else
_accessoryRespawnTimer -= diff;
}
private:
uint32 _accessoryRespawnTimer;
Vehicle* _vehicleKit;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_hyldsmeet_protodrakeAI (creature);
}
};
enum CloseRift
{
SPELL_DESPAWN_RIFT = 61665
};
class spell_close_rift : public SpellScriptLoader
{
public:
spell_close_rift() : SpellScriptLoader("spell_close_rift") { }
class spell_close_rift_AuraScript : public AuraScript
{
PrepareAuraScript(spell_close_rift_AuraScript);
bool Load() override
{
_counter = 0;
return true;
}
bool Validate(SpellInfo const* /*spell*/) override
{
return sSpellMgr->GetSpellInfo(SPELL_DESPAWN_RIFT);
}
void HandlePeriodic(AuraEffect const* /*aurEff*/)
{
if (++_counter == 5)
GetTarget()->CastSpell((Unit*)NULL, SPELL_DESPAWN_RIFT, true);
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_close_rift_AuraScript::HandlePeriodic, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL);
}
private:
uint8 _counter;
};
AuraScript* GetAuraScript() const override
{
return new spell_close_rift_AuraScript();
}
};
void AddSC_storm_peaks()
{
new npc_frostborn_scout();
//new npc_injured_goblin();
new npc_roxi_ramrocket();
new npc_brunnhildar_prisoner();
new npc_freed_protodrake();
new npc_icefang();
new npc_hyldsmeet_protodrake();
new spell_close_rift();
}
| 0 | 0.983638 | 1 | 0.983638 | game-dev | MEDIA | 0.970738 | game-dev | 0.992757 | 1 | 0.992757 |
2gis/Winium.Desktop | 2,113 | src/Winium.Desktop.Driver/CommandExecutorDispatchTable.cs | namespace Winium.Desktop.Driver
{
#region using
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Winium.Desktop.Driver.CommandExecutors;
using Winium.StoreApps.Common;
#endregion
internal class CommandExecutorDispatchTable
{
#region Fields
private Dictionary<string, Type> commandExecutorsRepository;
#endregion
#region Constructors and Destructors
public CommandExecutorDispatchTable()
{
this.ConstructDispatcherTable();
}
#endregion
#region Public Methods and Operators
public CommandExecutorBase GetExecutor(string commandName)
{
Type executorType;
if (this.commandExecutorsRepository.TryGetValue(commandName, out executorType))
{
}
else
{
executorType = typeof(NotImplementedExecutor);
}
return (CommandExecutorBase)Activator.CreateInstance(executorType);
}
#endregion
#region Methods
private void ConstructDispatcherTable()
{
this.commandExecutorsRepository = new Dictionary<string, Type>();
// TODO: bad const
const string ExecutorsNamespace = "Winium.Desktop.Driver.CommandExecutors";
var q =
(from t in Assembly.GetExecutingAssembly().GetTypes()
where t.IsClass && t.Namespace == ExecutorsNamespace
select t).ToArray();
var fields = typeof(DriverCommand).GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (var field in fields)
{
var localField = field;
var executor = q.FirstOrDefault(x => x.Name.Equals(localField.Name + "Executor"));
if (executor != null)
{
this.commandExecutorsRepository.Add(localField.GetValue(null).ToString(), executor);
}
}
}
#endregion
}
}
| 0 | 0.907166 | 1 | 0.907166 | game-dev | MEDIA | 0.211302 | game-dev | 0.906964 | 1 | 0.906964 |
Petrolpark-Mods/Destroy | 2,009 | src/main/java/com/petrolpark/destroy/core/chemistry/vat/IVatHeaterBlock.java | package com.petrolpark.destroy.core.chemistry.vat;
import com.petrolpark.destroy.config.DestroyAllConfigs;
import com.simibubi.create.content.processing.burner.BlazeBurnerBlock;
import com.simibubi.create.content.processing.burner.BlazeBurnerBlock.HeatLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
/**
* Interface for Blocks which can heat or cool a {@link Vat}.
*/
public interface IVatHeaterBlock {
/**
* Get the power (in watts) the given Block State supplies or withdraws from a {@link Vat}.
* @param level
* @param blockState
* @param blockPos
* @param face The face of the Block State touching the Vat
* @return Positive value for heaters, negative value for coolers
*/
float getHeatingPower(Level level, BlockState blockState, BlockPos blockPos, Direction face);
public static float getHeatingPower(Level level, BlockPos blockPos, Direction face) {
BlockState state = level.getBlockState(blockPos);
if (state.isAir()) return 0f;
// IVatHeaters
if (state.getBlock() instanceof IVatHeaterBlock heater) {
return heater.getHeatingPower(level, state, blockPos, face);
};
// Blaze Burners, Coolers, etc.
if (state.hasProperty(BlazeBurnerBlock.HEAT_LEVEL) && face == Direction.UP) {
HeatLevel heatLevel = state.getValue(BlazeBurnerBlock.HEAT_LEVEL);
if (heatLevel == HeatLevel.KINDLED) {
return DestroyAllConfigs.SERVER.blocks.blazeBurnerHeatingPower.getF();
} else if (heatLevel == HeatLevel.SEETHING) {
return DestroyAllConfigs.SERVER.blocks.blazeBurnerSuperHeatingPower.getF();
} else if ("FROSTING".equals(heatLevel.name())) {
return DestroyAllConfigs.SERVER.blocks.coolerHeatingPower.getF();
};
};
return 0f;
};
};
| 0 | 0.652192 | 1 | 0.652192 | game-dev | MEDIA | 0.980437 | game-dev | 0.685985 | 1 | 0.685985 |
JiuTian-VL/Optimus-1 | 5,746 | minerl/minerl/Malmo/Minecraft/src/main/java/com/microsoft/Malmo/Utils/SeedHelper.java | // --------------------------------------------------------------------------------------------------
// Copyright (c) 2016 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// --------------------------------------------------------------------------------------------------
package com.microsoft.Malmo.Utils;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import com.microsoft.Malmo.MalmoMod;
import com.microsoft.Malmo.MalmoMod.IMalmoMessageListener;
import com.microsoft.Malmo.MalmoMod.MalmoMessageType;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent;
@Mod.EventBusSubscriber
public class SeedHelper implements IMalmoMessageListener
{
private static ArrayDeque<Long> seeds = new ArrayDeque<Long>();
private static Long currentSeed;
private static HashMap<String, Random> specificSeedGenerators = new HashMap<String, Random>();
private static int numRandoms = 0;
public static Integer mapSeed;
// The pseudo-random number that is shared across all players
private static long worldSeed = new Random().nextLong();
public static SeedHelper instance = new SeedHelper();
public SeedHelper() {
MalmoMod.MalmoMessageHandler.registerForMessage(this, MalmoMessageType.SERVER_COMMON_SEED);
}
/** Initialize seeding. */
static public void update(Configuration configs)
{
String sSeed = configs.get(MalmoMod.SEED_CONFIGS, "seed", "NONE").getString();
if(!sSeed.isEmpty() && sSeed != "NONE" ){
sSeed = sSeed.replaceAll("\\s+","");
String[] sSeedList = sSeed.split(",");
for(int i = 0; i < sSeedList.length; i++){
try{
long seed = Long.parseLong(sSeedList[i]);
seeds.push(seed);
} catch(NumberFormatException e){
System.out.println("[ERROR] Seed specified was " + sSeedList[i] + ". Expected a long (integer).");
}
}
}
}
static public Random getRandom(){
numRandoms +=1;
return getRandom("");
}
static synchronized public Random getRandom(String key){
Random gen = specificSeedGenerators.get(key);
if(gen == null && currentSeed != null){
gen = new Random(currentSeed);
specificSeedGenerators.put(key, gen);
} else if(currentSeed == null){
gen = new Random();
}
Long seed_inst = (gen.nextLong());
return new Random(seed_inst);
}
@SubscribeEvent
public static void onWorldCreate(WorldEvent.Load loadEvent){
loadEvent.getWorld().rand = getRandom(loadEvent.getWorld().toString());
}
@SubscribeEvent
public static void onPlayerLogin(PlayerLoggedInEvent event) {
MalmoMod.network.sendTo(
new MalmoMod.MalmoMessage(MalmoMessageType.SERVER_COMMON_SEED, 0,
Collections.singletonMap("commonSeed", String.valueOf(worldSeed))),
(EntityPlayerMP) event.player);
}
public static void forceUpdateMinecraftRandoms(){
Item.itemRand = getRandom("item");
}
/**
* Advances the seed manager to the next seed.
*/
static public boolean advanceNextSeed(Long nextSeed){
numRandoms = 0;
specificSeedGenerators = new HashMap<String, Random>();
if(seeds.size() > 0){
currentSeed = seeds.pop();
forceUpdateMinecraftRandoms();
if(nextSeed != null){
System.out.println("[LOGTOPY] Tried to set seed for environment, but overriden by initial seed list.");
return false;
}
}
else{
if(nextSeed != null){
currentSeed = nextSeed;
forceUpdateMinecraftRandoms();
}
else{
currentSeed = null;
forceUpdateMinecraftRandoms();
}
}
return true;
}
@Override
public void onMessage(MalmoMessageType messageType, Map<String, String> data) {
if (messageType == MalmoMessageType.SERVER_COMMON_SEED) {
worldSeed = Long.valueOf(data.get("commonSeed"));
}
}
public static long getWorldSeed() {
return worldSeed;
}
} | 0 | 0.858174 | 1 | 0.858174 | game-dev | MEDIA | 0.949497 | game-dev | 0.970554 | 1 | 0.970554 |
long-war-2/lwotc | 10,434 | LongWarOfTheChosen/Src/LW_Overhaul/Classes/UIResistanceManagement_ListItem.uc | //---------------------------------------------------------------------------------------
// FILE: UIResistanceManagement_ListItem
// AUTHOR: tracktwo / Pavonis Interactive
// PURPOSE: List Item (one row) for UIResistanceManagement
//---------------------------------------------------------------------------------------
class UIResistanceManagement_ListItem extends UIPanel
config(LW_UI);
var config int LIST_ITEM_FONT_SIZE_MK, ADVISER_ICON_OFFSET_MK, ADVISER_ICON_SIZE_MK, ICON_OFFSET_MK, ICON_SIZE_MK;
var config int LIST_ITEM_FONT_SIZE_CTRL, ADVISER_ICON_OFFSET_CTRL, ADVISER_ICON_SIZE_CTRL, ICON_OFFSET_CTRL, ICON_SIZE_CTRL;
var StateObjectReference OutpostRef;
var UIScrollingText RegionLabel;
var UIText RebelCount, RegionStatusLabel, AdviserLabel, IncomeLabel;
var UIButton ButtonBG;
var UIList List;
simulated function UIResistanceManagement_ListItem InitListItem(StateObjectReference Ref)
{
OutpostRef = Ref;
InitPanel();
BuildItem();
UpdateData();
return self;
}
simulated function BuildItem()
{
local int AdviserIconOffset, BorderPadding;
local UIResistanceManagement_LW ParentScreen;
ParentScreen = UIResistanceManagement_LW(Screen);
List = ParentScreen.List;
Width = List.Width;
BorderPadding = 10;
// KDM : Background button which highlights when focused.
// The style is now always set to eUIButtonStyle_NONE else hot links, little button icons, will appear when using a controller.
ButtonBG = Spawn(class'UIButton', self);
ButtonBG.bIsNavigable = false;
ButtonBG.InitButton(, , , eUIButtonStyle_NONE);
ButtonBG.SetResizeToText(false);
ButtonBG.SetPosition(0, 0);
ButtonBG.SetSize(Width, Height - 4);
// KDM : Region name
RegionLabel = Spawn(class'UIScrollingText', self);
RegionLabel.InitScrollingText(, , ParentScreen.RegionHeaderButton.Width - BorderPadding * 2,
ParentScreen.RegionHeaderButton.X + BorderPadding, 7, true);
// KDM : Advent strength and vigilance
RegionStatusLabel = Spawn(class'UIText', self);
RegionStatusLabel.InitText(, , true);
RegionStatusLabel.SetPosition(ParentScreen.RegionStatusButton.X + BorderPadding, 7);
RegionStatusLabel.SetSize(ParentScreen.RegionStatusButton.Width - BorderPadding * 2, Height);
// KDM : Rebel number and rebels per job header
RebelCount = Spawn(class'UIText', self);
RebelCount.InitText(, , true);
RebelCount.SetPosition(ParentScreen.RebelCountHeaderButton.X + BorderPadding, 7);
RebelCount.SetSize(ParentScreen.RebelCountHeaderButton.Width - BorderPadding * 2, Height);
// KDM : Haven adviser
if (`ISCONTROLLERACTIVE)
{
AdviserIconOffset = ADVISER_ICON_OFFSET_CTRL;
}
else
{
AdviserIconOffset = ADVISER_ICON_OFFSET_MK;
}
AdviserLabel = Spawn(class'UIText', self);
AdviserLabel.InitText(, , true);
AdviserLabel.SetPosition(ParentScreen.AdviserHeaderButton.X + BorderPadding, 7 - AdviserIconOffset);
AdviserLabel.SetSize(ParentScreen.AdviserHeaderButton.Width - BorderPadding * 2, Height);
// KDM : Haven income
IncomeLabel = Spawn(class'UIText', self);
IncomeLabel.InitText(, , true);
IncomeLabel.SetPosition(ParentScreen.IncomeHeaderButton.X + BorderPadding, 7);
IncomeLabel.SetSize(ParentScreen.IncomeHeaderButton.Width - BorderPadding * 2, Height);
}
simulated function UpdateData(bool Focused = false)
{
local int TheAdviserIconSize, TheIconOffset, TheIconSize, TheListItemFontSize;
local String strRegion, strCount, strStatus, strJobDetail, strAdviser, strMoolah;
local StateObjectReference LiaisonRef;
local XComGameState_LWOutpost Outpost;
local XComGameState_Unit Liaison;
local XComGameState_WorldRegion Region;
local XComGameState_WorldRegion_LWStrategyAI RegionalAI;
local XGParamTag ParamTag;
if (`ISCONTROLLERACTIVE)
{
TheAdviserIconSize = ADVISER_ICON_SIZE_CTRL;
TheIconOffset = ICON_OFFSET_CTRL;
TheIconSize = ICON_SIZE_CTRL;
TheListItemFontSize = LIST_ITEM_FONT_SIZE_CTRL;
}
else
{
TheAdviserIconSize = ADVISER_ICON_SIZE_MK;
TheIconOffset = ICON_OFFSET_MK;
TheIconSize = ICON_SIZE_MK;
TheListItemFontSize = LIST_ITEM_FONT_SIZE_MK;
}
ParamTag = XGParamTag(`XEXPANDCONTEXT.FindTag("XGParam"));
Outpost = XComGameState_LWOutpost(`XCOMHISTORY.GetGameStateForObjectID(OutpostRef.ObjectID));
Region = XComGameState_WorldRegion(`XCOMHISTORY.GetGameStateForObjectID(Outpost.Region.ObjectID));
RegionalAI = class'XComGameState_WorldRegion_LWStrategyAI'.static.GetRegionalAI(Region);
// KDM : Region name
// It also displays icons if it : [1] is the starting region [2] has a relay built [3] has been liberated to some extent.
if (Region.IsStartingRegion())
{
strRegion = class'UIUtilities_Text'.static.InjectImage("img:///UILibrary_StrategyImages.X2StrategyMap.MissionIcon_ResHQ", TheIconSize, TheIconSize, TheIconOffset);
}
else
{
if (Region.ResistanceLevel >= eResLevel_Outpost)
{
strRegion = class'UIUtilities_Text'.static.InjectImage("img:///UILibrary_StrategyImages.X2StrategyMap.MissionIcon_Outpost", TheIconSize, TheIconSize, TheIconOffset);
}
else
{
strRegion = "";
}
}
strRegion $= " " $ Region.GetDisplayName() $ " ";
if (!RegionalAI.bLiberated)
{
if (RegionalAI.LiberateStage1Complete)
{
strRegion $= class'UIUtilities_LW'.default.m_strBullet;
}
if (RegionalAI.LiberateStage2Complete)
{
strRegion $= class'UIUtilities_LW'.default.m_strBullet;
}
}
RegionLabel.SetHTMLText(class'UIUtilities_Text'.static.GetColoredText(strRegion, Focused ? -1 : eUIState_Normal, TheListItemFontSize));
// KDM : Advent strength and vigilance; dislays liberated status if liberated
if (RegionalAI.bLiberated)
{
strStatus = class'UIResistanceManagement_LW'.default.m_strLiberated;
}
else
{
ParamTag.IntValue0 = RegionalAI.LocalAlertLevel;
ParamTag.IntValue1 = RegionalAI.LocalVigilanceLevel;
strStatus = `XEXPAND.ExpandString(class'UIResistanceManagement_LW'.default.m_strResistanceManagementLevels);
}
RegionStatusLabel.SetCenteredText(class'UIUtilities_Text'.static.GetColoredText(strStatus, Focused ? -1: eUIState_Normal, TheListItemFontSize));
// KDM : Number of rebels in the haven and number of rebels on : [1] supply [2] intel [3] recruit [4] hiding.
strCount = class'UIUtilities_Text'.static.GetColoredText(string(Outpost.GetRebelCount()),
Focused ? -1 : eUIState_Normal, TheListItemFontSize);
strCount $= class'UIUtilities_Text'.static.InjectImage("img:///UILibrary_StrategyImages.X2StrategyMap.MissionIcon_Resistance", TheIconSize, TheIconSize, TheIconOffset);
strCount $= " ";
ParamTag = XGParamTag(`XEXPANDCONTEXT.FindTag("XGParam"));
ParamTag.IntValue0 = Outpost.GetNumRebelsOnJob('Resupply');
ParamTag.IntValue1 = Outpost.GetNumRebelsOnJob('Intel');
ParamTag.IntValue2 = Outpost.GetNumRebelsOnJob('Recruit');
strJobDetail = `XEXPAND.ExpandString(class'UIStrategyMapItem_Region_LW'.default.m_strStaffingPinText);
ParamTag.IntValue0 = Outpost.GetNumRebelsOnJob('Hiding');
strJobDetail = strJobDetail @ `XEXPAND.ExpandString(class'UIStrategyMapItem_Region_LW'.default.m_strStaffingPinTextMore);
strCount $= class'UIUtilities_Text'.static.GetColoredText(strJobDetail, Focused ? -1: eUIState_Normal, TheListItemFontSize);
if (Outpost.GetResistanceMecCount() > 0)
{
strCount $= " ";
strCount $= class'UIUtilities_Text'.static.GetColoredText(string(Outpost.GetResistanceMecCount()), Focused ? -1 : eUIState_Normal, TheListItemFontSize);
strCount $= class'UIUtilities_Text'.static.InjectImage("img:///UILibrary_LWOTC.Resistance_Mec_icon", TheIconSize, TheIconSize, TheIconOffset);
}
RebelCount.SetCenteredText(strCount);
// KDM : Haven adviser icon, if a haven adviser exists
if (OutPost.HasLiaisonOfKind('Soldier'))
{
LiaisonRef = OutPost.GetLiaison();
Liaison = XComGameState_Unit(`XCOMHISTORY.GetGameStateForObjectID(LiaisonRef.ObjectID));
strAdviser = class'UIUtilities_Text'.static.InjectImage(Liaison.GetSoldierClassTemplate().IconImage, TheAdviserIconSize, TheAdviserIconSize, 0);
strAdviser $= class'UIUtilities_Text'.static.InjectImage(class'UIUtilities_Image'.static.GetRankIcon(Liaison.GetRank(), Liaison.GetSoldierClassTemplateName()), TheAdviserIconSize, TheAdviserIconSize, 0);
}
if (OutPost.HasLiaisonOfKind('Engineer'))
{
strAdviser = class'UIUtilities_Text'.static.InjectImage(class'UIUtilities_Image'.const.EventQueue_Engineer, TheAdviserIconSize, TheAdviserIconSize, 9);
}
if (OutPost.HasLiaisonOfKind('Scientist'))
{
strAdviser = class'UIUtilities_Text'.static.InjectImage(class'UIUtilities_Image'.const.EventQueue_Science, TheAdviserIconSize, TheAdviserIconSize, 9);
}
if (strAdviser != "")
{
// KDM : IMPORTANT : If you have a string which only contains an injected image, and then center it, the image is doubled.
// Get around this apparent bug by placing empty spaces on each side of the injected image.
AdviserLabel.SetCenteredText (class'UIUtilities_Text'.static.GetColoredText(" " $ strAdviser $ " ", Focused ? -1: eUIState_Normal, TheListItemFontSize));
}
// KDM : Real and projected haven income
ParamTag.IntValue0 = int(Outpost.GetIncomePoolForJob('Resupply'));
ParamTag.IntValue1 = int(Outpost.GetProjectedMonthlyIncomeForJob('Resupply'));
strMoolah = `XEXPAND.ExpandString(class'UIStrategyMapItem_Region_LW'.default.m_strMonthlyRegionalIncome);
IncomeLabel.SetCenteredText(class'UIUtilities_Text'.static.GetColoredText(strMoolah, Focused ? -1: eUIState_Normal, TheListItemFontSize));
}
simulated function OnReceiveFocus()
{
super.OnReceiveFocus();
ButtonBG.MC.FunctionVoid("mouseIn");
UpdateData(true);
}
simulated function OnLoseFocus()
{
super.OnLoseFocus();
ButtonBG.MC.FunctionVoid("mouseOut");
UpdateData();
}
simulated function bool OnUnrealCommand(int cmd, int arg)
{
local bool bHandled;
local int index;
if (!CheckInputIsReleaseOrDirectionRepeat(cmd, arg))
{
return false;
}
bHandled = true;
switch (cmd)
{
// KDM : X button opens the corresponding haven screen.
case class'UIUtilities_Input'.const.FXS_BUTTON_X:
case class'UIUtilities_Input'.const.FXS_KEY_ENTER:
case class'UIUtilities_Input'.const.FXS_KEY_SPACEBAR:
index = List.GetItemIndex(self);
UIResistanceManagement_LW(Screen).OnRegionSelectedCallback(List, index);
break;
default:
bHandled = false;
break;
}
if (bHandled)
{
return true;
}
// KDM : If the input has not been handled, allow it to continue on its way
return super.OnUnrealCommand(cmd, arg);
}
defaultproperties
{
Height = 52;
bProcessesMouseEvents = true;
bIsNavigable = true;
}
| 0 | 0.910729 | 1 | 0.910729 | game-dev | MEDIA | 0.827565 | game-dev | 0.952734 | 1 | 0.952734 |
shavitush/bhoptimer | 15,077 | addons/sourcemod/scripting/include/shavit/zones.inc | /*
* shavit's Timer - zones.inc file
* by: shavit,
*
* This file is part of shavit's Timer (https://github.com/shavitush/bhoptimer)
*
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, 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/>.
*
*/
#if defined _shavit_zones_included
#endinput
#endif
#define _shavit_zones_included
#define MAX_ZONES 128
#define MAX_STAGES 69
enum
{
Zone_Start, // starts timer
Zone_End, // stops timer
Zone_Respawn, // respawns the player
Zone_Stop, // stops the player's timer
Zone_Slay, // slays (kills) players which come to this zone
Zone_Freestyle, // ignores style physics when at this zone. e.g. WASD when SWing
Zone_CustomSpeedLimit, // overwrites velocity limit in the zone
Zone_Teleport, // teleports to a defined point
Zone_CustomSpawn, // spawn position for a track. not a physical zone.
Zone_Easybhop, // forces easybhop whether if the player is in non-easy styles or if the server has different settings
Zone_Slide, // allows players to slide, in order to fix parts like the 5th stage of bhop_arcane
Zone_Airaccelerate, // custom sv_airaccelerate inside this,
Zone_Stage, // shows time when entering zone
Zone_NoTimerGravity, // prevents the timer from setting gravity while inside this zone
Zone_Gravity, // lets you set a specific gravity while inside this zone
Zone_Speedmod, // creates a player_speedmod
Zone_NoJump, // blocks the player from jumping while inside the zone
Zone_Autobhop, // forces autobhop for the player
ZONETYPES_SIZE
};
enum
{
ZF_ForceRender = (1 << 0),
ZF_Hammerid = (1 << 1), // used by ZoneForm_{trigger_{multiple, teleport}, func_[rot_]button} sometimes
ZF_Solid = (1 << 2), // forces the zone to physically block people...
ZF_Origin = (1 << 4), // sTarget is the entity's origin formatted as "%X %X %X"
};
// Zone Display type
enum
{
ZoneDisplay_Default,
ZoneDisplay_Flat,
ZoneDisplay_Box,
ZoneDisplay_None,
ZoneDisplay_Size
};
// Zone Color, maybe we just let the user decide what color they actually want..? maybe store rgba as hex string but that would be mega long for each track
enum
{
ZoneColor_Default,
ZoneColor_White,
ZoneColor_Red,
ZoneColor_Orange,
ZoneColor_Yellow,
ZoneColor_Green,
ZoneColor_Cyan,
ZoneColor_Blue,
ZoneColor_Purple,
ZoneColor_Pink,
ZoneColor_Size
};
enum
{
ZoneWidth_Default,
ZoneWidth_UltraThin,
ZoneWidth_Thin,
ZoneWidth_Normal,
ZoneWidth_Thick,
ZoneWidth_Size
};
enum
{
ZoneForm_Box,
ZoneForm_trigger_multiple,
ZoneForm_trigger_teleport,
ZoneForm_func_button,
ZoneForm_AreasAndClusters,
};
enum struct zone_cache_t
{
int iType; // The type of zone. Zone_Start, Zone_End, etc...
int iTrack; // 0 - main, 1 - bonus1 etc
int iEntity; // Filled by Shavit_GetZone() if applicable.
int iDatabaseID; // Can be the database ID (> 0) for "sql" sources. Non-sql sources can fill this with whatever.
int iFlags; // The ZF_* flags.
int iData; // Depends on the zone. Zone_Stage stores the stage number in this for example.
float fCorner1[3]; // the hull mins. (or unused if ZoneForm_AreasAndClusters) // TODO, maybe reuse for cluster & areas?
float fCorner2[3]; // the hull maxs. (or unused if ZoneForm_AreasAndClusters)
float fDestination[3]; // Used by Zone_CustomSpawn, Zone_Teleport, and Zone_Stage.
int iForm; // ZoneForm_*
char sSource[16]; // "sql", "autobutton", "autozone", "sourcejump", "http", etc...
char sTarget[64]; // either the hammerid or the targetname
}
stock void GetZoneName(int client, int zoneType, char[] output, int size)
{
static char sTranslationStrings[ZONETYPES_SIZE][] = {
"Zone_Start",
"Zone_End",
"Zone_Respawn",
"Zone_Stop",
"Zone_Slay",
"Zone_Freestyle",
"Zone_CustomSpeedLimit",
"Zone_Teleport",
"Zone_CustomSpawn",
"Zone_Easybhop",
"Zone_Slide",
"Zone_Airaccelerate",
"Zone_Stage",
"Zone_NoTimerGravity",
"Zone_Gravity",
"Zone_Speedmod",
"Zone_NoJump",
"Zone_Autobhop",
};
if (zoneType < 0 || zoneType >= ZONETYPES_SIZE)
FormatEx(output, size, "%T", "Zone_Unknown", client);
else
FormatEx(output, size, "%T", sTranslationStrings[zoneType], client);
}
// Please follow something like this:
// mod_zone_start
// mod_zone_end
// mod_zone_checkpoint_X
// mod_zone_bonus_X_start
// mod_zone_bonus_X_end
// mod_zone_bonus_X_checkpoint_X
//
// climb_startbutton
// climb_endbutton
// climb_bonusX_startbutton
// climb_bonusX_endbutton
//
// climb_startzone
// climb_endzone
// climb_bonusX_startzone
// climb_bonusX_endzone
stock bool Shavit_ParseZoneTargetname(const char[] targetname, bool button, int& type, int& track, int& stage, const char[] mapname_for_log="")
{
track = Track_Main;
type = -1;
stage = 0;
if (strncmp(targetname, "climb_", 6) != 0
&& (button || strncmp(targetname, "mod_zone_", 9) != 0))
{
return false;
}
if (StrContains(targetname, "start") != -1)
{
type = Zone_Start;
}
else if (StrContains(targetname, "end") != -1)
{
type = Zone_End;
}
int bonus = StrContains(targetname, "bonus");
if (bonus != -1)
{
track = Track_Bonus;
bonus += 5; // skip past "bonus"
if (targetname[bonus] == '_') bonus += 1;
if ('1' <= targetname[bonus] <= '9')
{
track = StringToInt(targetname[bonus]);
if (track < Track_Bonus || track > Track_Bonus_Last)
{
if (mapname_for_log[0]) LogError("invalid track in prebuilt map zone (%s) on %s", targetname, mapname_for_log);
return false;
}
}
}
int checkpoint = StrContains(targetname, "checkpoint");
if (checkpoint != -1)
{
if (button)
{
if (mapname_for_log[0]) LogError("invalid button (%s) (has checkpoint) on %s", targetname, mapname_for_log);
return false;
}
if (type != -1)
{
if (mapname_for_log[0]) LogError("invalid type (start/end + checkpoint) in prebuilt map zone (%s) on %s", targetname, mapname_for_log);
return false; // end/start & checkpoint...
}
type = Zone_Stage;
checkpoint += 10; // skip past "checkpoint"
if (targetname[checkpoint] == '_') checkpoint += 1;
if ('1' <= targetname[checkpoint] <= '9')
{
stage = StringToInt(targetname[checkpoint]);
if (stage <= 0 || stage > MAX_STAGES)
{
if (mapname_for_log[0]) LogError("invalid stage number in prebuilt map zone (%s) on %s", targetname, mapname_for_log);
return false;
}
}
}
if (type == -1)
{
if (mapname_for_log[0]) LogError("invalid zone type in prebuilt map zone (%s) on %s", targetname, mapname_for_log);
return false;
}
return true;
}
/**
* Called when a player enters a zone.
*
* @param client Client index.
* @param type Zone type.
* @param track Zone track.
* @param id Zone ID.
* @param entity Zone trigger entity index.
* @param data Zone data if any.
* @noreturn
*/
forward void Shavit_OnEnterZone(int client, int type, int track, int id, int entity, int data);
/**
* Called when a player leaves a zone.
*
* @param client Client index.
* @param type Zone type.
* @param track Zone track.
* @param id Zone ID.
* @param entity Zone trigger entity index.
* @param data Zone data if any.
* @noreturn
*/
forward void Shavit_OnLeaveZone(int client, int type, int track, int id, int entity, int data);
/**
*
*/
forward void Shavit_LoadZonesHere();
/**
* Called when a player leaves a zone.
*
* @param client Client index.
* @param stageNumber Stage number.
* @param message The stage time message that will be printed.
* @param maxlen The buffer size of message.
* @return Plugin_Handled to block the timer from printing msg to the client. Plugin_Continue to let the timer print msg.
*/
forward Action Shavit_OnStageMessage(int client, int stageNumber, char[] message, int maxlen);
/**
* Checks if a mapzone exists.
*
* @param type Mapzone type.
* @param track Mapzone track, -1 to ignore track.
* @return Boolean value.
*/
native bool Shavit_ZoneExists(int type, int track);
/**
* Checks if a player is inside a mapzone.
*
* @param client Client index.
* @param type Mapzone type.
* @param track Mapzone track, -1 to ignore track.
* @return Boolean value.
*/
native bool Shavit_InsideZone(int client, int type, int track);
/**
* Gets the specified zone's data.
*
* @param zoneid ID of the zone we query the data of.
* @return Zone data. 0 if none is specified.
*/
native int Shavit_GetZoneData(int zoneid);
/**
* Gets the specified zone's flags.
*
* @param zoneid ID of the zone we query the flags of.
* @return Zone flags. 0 if none is specified.
*/
native int Shavit_GetZoneFlags(int zoneid);
/**
* Deletes all map zones for the specified map.
* Plugin will refresh if map is currently on.
*
* @param map Map name.
* @noreturn
*/
native void Shavit_Zones_DeleteMap(const char[] map);
/**
* Checks if a player is inside a mapzone.
*
* @param client Client index.
* @param type Mapzone type.
* @param track Mapzone track, -1 to ignore track.
* @param zoneid Reference to variable that will hold the zone's ID.
* @return Boolean value.
*/
native bool Shavit_InsideZoneGetID(int client, int type, int track, int &zoneid);
/**
* Checks if a player is in the process of creating a mapzone.
*
* @param client Client index.
* @return Boolean value.
*/
native bool Shavit_IsClientCreatingZone(int client);
/**
* Retrieve the highest stage number for a given track.
*
* @param track Track number.
* @return Highest stage number...
*/
native int Shavit_GetHighestStage(int track);
/**
* Retrieve the client's current stage number.
*
* @param client Client index.
* @return The client's current stage number.
*/
native int Shavit_GetClientLastStage(int client);
/**
* Returns the zone index for the entity if available.
*
* @param entity Client index.
* @return -1 if not a zone entity. >=0 for a zone index.
*/
native int Shavit_GetZoneID(int entity);
/**
* Returns the zone track.
*
* @param zoneid Zone index.
* @return Zone track.
*/
native int Shavit_GetZoneTrack(int zoneid);
/**
* Returns the zone type.
*
* @param zoneid Zone index.
* @return Zone type.
*/
native int Shavit_GetZoneType(int zoneid);
/**
* Sets the player's current location as their spawn location for the specified track.
*
* @param client Client index.
* @param track Timer track.
* @param anglesonly Whether to save angles only.
* @noreturn
*/
native void Shavit_SetStart(int client, int track, bool anglesonly);
/**
* Deletes the player's current set start position for the specified track.
*
* @param client Client index.
* @param track Timer track.
* @noreturn
*/
native void Shavit_DeleteSetStart(int client, int track);
/**
* Removes all zones from memory and then reloads zones from the database & any plugins.
* @noreturn
*/
native void Shavit_ReloadZones();
/**
* Removes all zones from memory and unhooks any zones and kills any created entities.
* @noreturn
*/
native void Shavit_UnloadZones();
/**
* Returns the number of zones that are currently loaded in memory.
*
* @return The number of zones currently loaded in memory.
*/
native int Shavit_GetZoneCount();
/**
* Retrieves the zone_cache_t for a zone.
*
* @param index The zone index. 0 through Shavit_GetZoneCount()-1.
* @param zonecache The zone_cache_t struct that is retrieved from the zone.
* @param size sizeof(zone_cache_t) to make sure the caller has a matching struct version.
*
* @noreturn
*/
native void Shavit_GetZone(int index, any[] zonecache, int size = sizeof(zone_cache_t));
/**
* Adds a zone to memory. (Does NOT insert into DB).
*
* @param zonecache The zone_cache_t struct that is used to create or hook a zone.
* @param size sizeof(zone_cache_t) to make sure the caller has a matching struct version.
*
* @return The zone index on success (index for a particular zone can change). <0 on failure.
*/
native int Shavit_AddZone(any[] zonecache, int size = sizeof(zone_cache_t));
/**
* Removes a zone from memory. (Does NOT delete from DB).
* WARNING: If there are zones after `index`, then they will be moved down in memory to fill this slot after removal.
* This unhooks the zone's entity too.
*
* @param index The zone's index.
*
* @noreturn
*/
native void Shavit_RemoveZone(int index);
public SharedPlugin __pl_shavit_zones =
{
name = "shavit-zones",
file = "shavit-zones.smx",
#if defined REQUIRE_PLUGIN
required = 1
#else
required = 0
#endif
};
#if !defined REQUIRE_PLUGIN
public void __pl_shavit_zones_SetNTVOptional()
{
MarkNativeAsOptional("Shavit_GetZoneData");
MarkNativeAsOptional("Shavit_GetZoneFlags");
MarkNativeAsOptional("Shavit_GetHighestStage");
MarkNativeAsOptional("Shavit_InsideZone");
MarkNativeAsOptional("Shavit_InsideZoneGetID");
MarkNativeAsOptional("Shavit_IsClientCreatingZone");
MarkNativeAsOptional("Shavit_ZoneExists");
MarkNativeAsOptional("Shavit_Zones_DeleteMap");
MarkNativeAsOptional("Shavit_SetStart");
MarkNativeAsOptional("Shavit_DeleteSetStart");
MarkNativeAsOptional("Shavit_GetClientLastStage");
MarkNativeAsOptional("Shavit_GetZoneTrack");
MarkNativeAsOptional("Shavit_GetZoneType");
MarkNativeAsOptional("Shavit_GetZoneID");
MarkNativeAsOptional("Shavit_ReloadZones");
MarkNativeAsOptional("Shavit_UnloadZones");
MarkNativeAsOptional("Shavit_GetZoneCount");
MarkNativeAsOptional("Shavit_GetZone");
MarkNativeAsOptional("Shavit_AddZone");
MarkNativeAsOptional("Shavit_RemoveZone");
}
#endif
| 0 | 0.873276 | 1 | 0.873276 | game-dev | MEDIA | 0.874891 | game-dev | 0.683599 | 1 | 0.683599 |
MicrosoftDocs/playfab-docs | 2,241 | playfab-docs/multiplayer/networking/reference/classes/PartyManager/methods/partymanager_getlocalusers.md | ---
author: jdeweyMSFT
title: "PartyManager::GetLocalUsers"
description: Gets an array containing all local users created by [CreateLocalUser()](partymanager_createlocaluser.md) or [CreateLocalUserWithEntityType()](partymanager_createlocaluserwithentitytype.md).
ms.author: jdewey
ms.topic: reference
ms.service: azure-playfab
ms.date: 11/08/2019
---
# PartyManager::GetLocalUsers
Gets an array containing all local users created by [CreateLocalUser()](partymanager_createlocaluser.md) or [CreateLocalUserWithEntityType()](partymanager_createlocaluserwithentitytype.md).
## Syntax
```cpp
PartyError GetLocalUsers(
uint32_t* userCount,
PartyLocalUserArray* localUsers
)
```
### Parameters
**`userCount`** uint32_t*
*output*
The output number of local users provided in `localUsers`.
**`localUsers`** [PartyLocalUserArray*](../../../typedefs.md)
*library-allocated output array of size `*userCount`*
A library-allocated output array containing the local users.
### Return value
PartyError
```c_partyErrorSuccess``` if the call succeeded or an error code otherwise. The human-readable form of the error code can be retrieved via [GetErrorMessage()](partymanager_geterrormessage.md).
## Remarks
Once a [PartyDestroyLocalUserCompletedStateChange](../../../structs/partydestroylocalusercompletedstatechange.md) has been provided by [PartyManager::StartProcessingStateChanges()](partymanager_startprocessingstatechanges.md), the local user will no longer be present in the array returned by this method. <br /><br /> The memory for the returned array is invalidated whenever the title calls PartyManager::StartProcessingStateChanges(), or when CreateLocalUser() or CreateLocalUserWithEntityType() returns success.
## Requirements
**Header:** Party.h
## See also
[PartyManager](../partymanager.md)
[PartyManager::CreateLocalUser](partymanager_createlocaluser.md)
[PartyManager::CreateLocalUserWithEntityType](partymanager_createlocaluserwithentitytype.md)
[PartyManager::DestroyLocalUser](partymanager_destroylocaluser.md)
[PartyDestroyLocalUserCompletedStateChange](../../../structs/partydestroylocalusercompletedstatechange.md)
| 0 | 0.662003 | 1 | 0.662003 | game-dev | MEDIA | 0.283545 | game-dev | 0.787652 | 1 | 0.787652 |
lantus/chocolate-doom-nx | 48,802 | src/heretic/g_game.c | //
// Copyright(C) 1993-1996 Id Software, Inc.
// Copyright(C) 1993-2008 Raven Software
// 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.
//
// G_game.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "doomdef.h"
#include "doomkeys.h"
#include "deh_str.h"
#include "i_input.h"
#include "i_timer.h"
#include "i_system.h"
#include "m_argv.h"
#include "m_controls.h"
#include "m_misc.h"
#include "m_random.h"
#include "p_local.h"
#include "s_sound.h"
#include "v_video.h"
// Macros
#define AM_STARTKEY 9
// Functions
boolean G_CheckDemoStatus(void);
void G_ReadDemoTiccmd(ticcmd_t * cmd);
void G_WriteDemoTiccmd(ticcmd_t * cmd);
void G_PlayerReborn(int player);
void G_DoReborn(int playernum);
void G_DoLoadLevel(void);
void G_DoNewGame(void);
void G_DoPlayDemo(void);
void G_DoCompleted(void);
void G_DoVictory(void);
void G_DoWorldDone(void);
void G_DoSaveGame(void);
void D_PageTicker(void);
void D_AdvanceDemo(void);
struct
{
int type; // mobjtype_t
int speed[2];
} MonsterMissileInfo[] = {
{ MT_IMPBALL, { 10, 20 } },
{ MT_MUMMYFX1, { 9, 18 } },
{ MT_KNIGHTAXE, { 9, 18 } },
{ MT_REDAXE, { 9, 18 } },
{ MT_BEASTBALL, { 12, 20 } },
{ MT_WIZFX1, { 18, 24 } },
{ MT_SNAKEPRO_A, { 14, 20 } },
{ MT_SNAKEPRO_B, { 14, 20 } },
{ MT_HEADFX1, { 13, 20 } },
{ MT_HEADFX3, { 10, 18 } },
{ MT_MNTRFX1, { 20, 26 } },
{ MT_MNTRFX2, { 14, 20 } },
{ MT_SRCRFX1, { 20, 28 } },
{ MT_SOR2FX1, { 20, 28 } },
{ -1, { -1, -1 } } // Terminator
};
gameaction_t gameaction;
gamestate_t gamestate;
skill_t gameskill;
boolean respawnmonsters;
int gameepisode;
int gamemap;
int prevmap;
boolean paused;
boolean sendpause; // send a pause event next tic
boolean sendsave; // send a save event next tic
boolean usergame; // ok to save / end game
boolean timingdemo; // if true, exit with report on completion
int starttime; // for comparative timing purposes
boolean viewactive;
boolean deathmatch; // only if started as net death
boolean netgame; // only true if packets are broadcast
boolean playeringame[MAXPLAYERS];
player_t players[MAXPLAYERS];
int consoleplayer; // player taking events and displaying
int displayplayer; // view being displayed
int levelstarttic; // gametic at level start
int totalkills, totalitems, totalsecret; // for intermission
int mouseSensitivity;
char demoname[32];
boolean demorecording;
boolean longtics; // specify high resolution turning in demos
boolean lowres_turn;
boolean shortticfix; // calculate lowres turning like doom
boolean demoplayback;
boolean demoextend;
byte *demobuffer, *demo_p, *demoend;
boolean singledemo; // quit after playing a demo from cmdline
boolean precache = true; // if true, load all graphics at start
// TODO: Heretic uses 16-bit shorts for consistency?
byte consistancy[MAXPLAYERS][BACKUPTICS];
char *savegamedir;
boolean testcontrols = false;
int testcontrols_mousespeed;
//
// controls (have defaults)
//
#define MAXPLMOVE 0x32
fixed_t forwardmove[2] = { 0x19, 0x32 };
fixed_t sidemove[2] = { 0x18, 0x28 };
fixed_t angleturn[3] = { 640, 1280, 320 }; // + slow turn
static int *weapon_keys[] =
{
&key_weapon1,
&key_weapon2,
&key_weapon3,
&key_weapon4,
&key_weapon5,
&key_weapon6,
&key_weapon7
};
// Set to -1 or +1 to switch to the previous or next weapon.
static int next_weapon = 0;
// Used for prev/next weapon keys.
static const struct
{
weapontype_t weapon;
weapontype_t weapon_num;
} weapon_order_table[] = {
{ wp_staff, wp_staff },
{ wp_gauntlets, wp_staff },
{ wp_goldwand, wp_goldwand },
{ wp_crossbow, wp_crossbow },
{ wp_blaster, wp_blaster },
{ wp_skullrod, wp_skullrod },
{ wp_phoenixrod, wp_phoenixrod },
{ wp_mace, wp_mace },
{ wp_beak, wp_beak },
};
#define SLOWTURNTICS 6
#define NUMKEYS 256
boolean gamekeydown[NUMKEYS];
int turnheld; // for accelerative turning
int lookheld;
boolean mousearray[MAX_MOUSE_BUTTONS + 1];
boolean *mousebuttons = &mousearray[1];
// allow [-1]
int mousex, mousey; // mouse values are used once
int dclicktime, dclickstate, dclicks;
int dclicktime2, dclickstate2, dclicks2;
#define MAX_JOY_BUTTONS 20
int joyxmove, joyymove; // joystick values are repeated
int joystrafemove;
int joylook;
boolean joyarray[MAX_JOY_BUTTONS + 1];
boolean *joybuttons = &joyarray[1]; // allow [-1]
int savegameslot;
char savedescription[32];
int vanilla_demo_limit = 1;
int inventoryTics;
// haleyjd: removed WATCOMC
//=============================================================================
// Not used - ripped out for Heretic
/*
int G_CmdChecksum(ticcmd_t *cmd)
{
int i;
int sum;
sum = 0;
for(i = 0; i < sizeof(*cmd)/4-1; i++)
{
sum += ((int *)cmd)[i];
}
return(sum);
}
*/
static boolean WeaponSelectable(weapontype_t weapon)
{
if (weapon == wp_beak)
{
return false;
}
return players[consoleplayer].weaponowned[weapon];
}
static int G_NextWeapon(int direction)
{
weapontype_t weapon;
int start_i, i;
// Find index in the table.
if (players[consoleplayer].pendingweapon == wp_nochange)
{
weapon = players[consoleplayer].readyweapon;
}
else
{
weapon = players[consoleplayer].pendingweapon;
}
for (i=0; i<arrlen(weapon_order_table); ++i)
{
if (weapon_order_table[i].weapon == weapon)
{
break;
}
}
// Switch weapon. Don't loop forever.
start_i = i;
do
{
i += direction;
i = (i + arrlen(weapon_order_table)) % arrlen(weapon_order_table);
} while (i != start_i && !WeaponSelectable(weapon_order_table[i].weapon));
return weapon_order_table[i].weapon_num;
}
/*
====================
=
= G_BuildTiccmd
=
= Builds a ticcmd from all of the available inputs or reads it from the
= demo buffer.
= If recording a demo, write it out
====================
*/
extern boolean inventory;
extern int curpos;
extern int inv_ptr;
boolean usearti = true;
void G_BuildTiccmd(ticcmd_t *cmd, int maketic)
{
int i;
boolean strafe, bstrafe;
int speed, tspeed, lspeed;
int forward, side;
int look, arti;
int flyheight;
extern boolean noartiskip;
// haleyjd: removed externdriver crap
memset(cmd, 0, sizeof(*cmd));
//cmd->consistancy =
// consistancy[consoleplayer][(maketic*ticdup)%BACKUPTICS];
cmd->consistancy = consistancy[consoleplayer][maketic % BACKUPTICS];
//printf ("cons: %i\n",cmd->consistancy);
strafe = gamekeydown[key_strafe] || mousebuttons[mousebstrafe]
|| joybuttons[joybstrafe];
speed = joybspeed >= MAX_JOY_BUTTONS
|| gamekeydown[key_speed]
|| joybuttons[joybspeed];
// haleyjd: removed externdriver crap
forward = side = look = arti = flyheight = 0;
//
// use two stage accelerative turning on the keyboard and joystick
//
if (joyxmove < 0 || joyxmove > 0
|| gamekeydown[key_right] || gamekeydown[key_left])
turnheld += ticdup;
else
turnheld = 0;
if (turnheld < SLOWTURNTICS)
tspeed = 2; // slow turn
else
tspeed = speed;
if (gamekeydown[key_lookdown] || gamekeydown[key_lookup])
{
lookheld += ticdup;
}
else
{
lookheld = 0;
}
if (lookheld < SLOWTURNTICS)
{
lspeed = 1;
}
else
{
lspeed = 2;
}
//
// let movement keys cancel each other out
//
if (strafe)
{
if (gamekeydown[key_right])
side += sidemove[speed];
if (gamekeydown[key_left])
side -= sidemove[speed];
if (joyxmove > 0)
side += sidemove[speed];
if (joyxmove < 0)
side -= sidemove[speed];
}
else
{
if (gamekeydown[key_right])
cmd->angleturn -= angleturn[tspeed];
if (gamekeydown[key_left])
cmd->angleturn += angleturn[tspeed];
if (joyxmove > 0)
cmd->angleturn -= angleturn[tspeed];
if (joyxmove < 0)
cmd->angleturn += angleturn[tspeed];
}
if (gamekeydown[key_up])
forward += forwardmove[speed];
if (gamekeydown[key_down])
forward -= forwardmove[speed];
if (joyymove < 0)
forward += forwardmove[speed];
if (joyymove > 0)
forward -= forwardmove[speed];
if (gamekeydown[key_straferight] || mousebuttons[mousebstraferight]
|| joybuttons[joybstraferight] || joystrafemove > 0)
side += sidemove[speed];
if (gamekeydown[key_strafeleft] || mousebuttons[mousebstrafeleft]
|| joybuttons[joybstrafeleft] || joystrafemove < 0)
side -= sidemove[speed];
// Look up/down/center keys
if (gamekeydown[key_lookup] || joylook < 0)
{
look = lspeed;
}
if (gamekeydown[key_lookdown] || joylook > 0)
{
look = -lspeed;
}
// haleyjd: removed externdriver crap
if (gamekeydown[key_lookcenter])
{
look = TOCENTER;
}
// haleyjd: removed externdriver crap
// Fly up/down/drop keys
if (gamekeydown[key_flyup])
{
flyheight = 5; // note that the actual flyheight will be twice this
}
if (gamekeydown[key_flydown])
{
flyheight = -5;
}
if (gamekeydown[key_flycenter])
{
flyheight = TOCENTER;
// haleyjd: removed externdriver crap
look = TOCENTER;
}
// Use artifact key
if (gamekeydown[key_useartifact])
{
if (gamekeydown[key_speed] && !noartiskip)
{
if (players[consoleplayer].inventory[inv_ptr].type != arti_none)
{
gamekeydown[key_useartifact] = false;
cmd->arti = 0xff; // skip artifact code
}
}
else
{
if (inventory)
{
players[consoleplayer].readyArtifact =
players[consoleplayer].inventory[inv_ptr].type;
inventory = false;
cmd->arti = 0;
usearti = false;
}
else if (usearti)
{
cmd->arti = players[consoleplayer].inventory[inv_ptr].type;
usearti = false;
}
}
}
if (gamekeydown[127] && !cmd->arti
&& !players[consoleplayer].powers[pw_weaponlevel2])
{
gamekeydown[127] = false;
cmd->arti = arti_tomeofpower;
}
//
// buttons
//
cmd->chatchar = CT_dequeueChatChar();
if (gamekeydown[key_fire] || mousebuttons[mousebfire]
|| joybuttons[joybfire])
cmd->buttons |= BT_ATTACK;
if (gamekeydown[key_use] || joybuttons[joybuse] || mousebuttons[mousebuse])
{
cmd->buttons |= BT_USE;
dclicks = 0; // clear double clicks if hit use button
}
// If the previous or next weapon button is pressed, the
// next_weapon variable is set to change weapons when
// we generate a ticcmd. Choose a new weapon.
// (Can't weapon cycle when the player is a chicken)
if (gamestate == GS_LEVEL
&& players[consoleplayer].chickenTics == 0 && next_weapon != 0)
{
i = G_NextWeapon(next_weapon);
cmd->buttons |= BT_CHANGE;
cmd->buttons |= i << BT_WEAPONSHIFT;
}
else
{
for (i=0; i<arrlen(weapon_keys); ++i)
{
int key = *weapon_keys[i];
if (gamekeydown[key])
{
cmd->buttons |= BT_CHANGE;
cmd->buttons |= i<<BT_WEAPONSHIFT;
break;
}
}
}
next_weapon = 0;
//
// mouse
//
if (mousebuttons[mousebforward])
{
forward += forwardmove[speed];
}
if (mousebuttons[mousebbackward])
{
forward -= forwardmove[speed];
}
// Double click to use can be disabled
if (dclick_use)
{
//
// forward double click
//
if (mousebuttons[mousebforward] != dclickstate && dclicktime > 1)
{
dclickstate = mousebuttons[mousebforward];
if (dclickstate)
dclicks++;
if (dclicks == 2)
{
cmd->buttons |= BT_USE;
dclicks = 0;
}
else
dclicktime = 0;
}
else
{
dclicktime += ticdup;
if (dclicktime > 20)
{
dclicks = 0;
dclickstate = 0;
}
}
//
// strafe double click
//
bstrafe = mousebuttons[mousebstrafe] || joybuttons[joybstrafe];
if (bstrafe != dclickstate2 && dclicktime2 > 1)
{
dclickstate2 = bstrafe;
if (dclickstate2)
dclicks2++;
if (dclicks2 == 2)
{
cmd->buttons |= BT_USE;
dclicks2 = 0;
}
else
dclicktime2 = 0;
}
else
{
dclicktime2 += ticdup;
if (dclicktime2 > 20)
{
dclicks2 = 0;
dclickstate2 = 0;
}
}
}
if (strafe)
{
side += mousex * 2;
}
else
{
cmd->angleturn -= mousex * 0x8;
}
// No mouse movement in previous frame?
if (mousex == 0)
{
testcontrols_mousespeed = 0;
}
forward += mousey;
mousex = mousey = 0;
if (forward > MAXPLMOVE)
forward = MAXPLMOVE;
else if (forward < -MAXPLMOVE)
forward = -MAXPLMOVE;
if (side > MAXPLMOVE)
side = MAXPLMOVE;
else if (side < -MAXPLMOVE)
side = -MAXPLMOVE;
cmd->forwardmove += forward;
cmd->sidemove += side;
if (players[consoleplayer].playerstate == PST_LIVE)
{
if (look < 0)
{
look += 16;
}
cmd->lookfly = look;
}
if (flyheight < 0)
{
flyheight += 16;
}
cmd->lookfly |= flyheight << 4;
//
// special buttons
//
if (sendpause)
{
sendpause = false;
cmd->buttons = BT_SPECIAL | BTS_PAUSE;
}
if (sendsave)
{
sendsave = false;
cmd->buttons =
BT_SPECIAL | BTS_SAVEGAME | (savegameslot << BTS_SAVESHIFT);
}
if (lowres_turn)
{
if (shortticfix)
{
static signed short carry = 0;
signed short desired_angleturn;
desired_angleturn = cmd->angleturn + carry;
// round angleturn to the nearest 256 unit boundary
// for recording demos with single byte values for turn
cmd->angleturn = (desired_angleturn + 128) & 0xff00;
// Carry forward the error from the reduced resolution to the
// next tic, so that successive small movements can accumulate.
carry = desired_angleturn - cmd->angleturn;
}
else
{
// truncate angleturn to the nearest 256 boundary
// for recording demos with single byte values for turn
cmd->angleturn &= 0xff00;
}
}
}
/*
==============
=
= G_DoLoadLevel
=
==============
*/
void G_DoLoadLevel(void)
{
int i;
levelstarttic = gametic; // for time calculation
gamestate = GS_LEVEL;
for (i = 0; i < MAXPLAYERS; i++)
{
if (playeringame[i] && players[i].playerstate == PST_DEAD)
players[i].playerstate = PST_REBORN;
memset(players[i].frags, 0, sizeof(players[i].frags));
}
P_SetupLevel(gameepisode, gamemap, 0, gameskill);
displayplayer = consoleplayer; // view the guy you are playing
gameaction = ga_nothing;
Z_CheckHeap();
//
// clear cmd building stuff
//
memset(gamekeydown, 0, sizeof(gamekeydown));
joyxmove = joyymove = joystrafemove = joylook = 0;
mousex = mousey = 0;
sendpause = sendsave = paused = false;
memset(mousearray, 0, sizeof(mousearray));
memset(joyarray, 0, sizeof(joyarray));
if (testcontrols)
{
P_SetMessage(&players[consoleplayer], "PRESS ESCAPE TO QUIT.", false);
}
}
static void SetJoyButtons(unsigned int buttons_mask)
{
int i;
for (i=0; i<MAX_JOY_BUTTONS; ++i)
{
int button_on = (buttons_mask & (1 << i)) != 0;
// Detect button press:
if (!joybuttons[i] && button_on)
{
// Weapon cycling:
if (i == joybprevweapon)
{
next_weapon = -1;
}
else if (i == joybnextweapon)
{
next_weapon = 1;
}
}
joybuttons[i] = button_on;
}
}
static void SetMouseButtons(unsigned int buttons_mask)
{
int i;
for (i=0; i<MAX_MOUSE_BUTTONS; ++i)
{
unsigned int button_on = (buttons_mask & (1 << i)) != 0;
// Detect button press:
if (!mousebuttons[i] && button_on)
{
if (i == mousebprevweapon)
{
next_weapon = -1;
}
else if (i == mousebnextweapon)
{
next_weapon = 1;
}
}
mousebuttons[i] = button_on;
}
}
/*
===============================================================================
=
= G_Responder
=
= get info needed to make ticcmd_ts for the players
=
===============================================================================
*/
boolean G_Responder(event_t * ev)
{
player_t *plr;
plr = &players[consoleplayer];
if (ev->type == ev_keyup && ev->data1 == key_useartifact)
{ // flag to denote that it's okay to use an artifact
if (!inventory)
{
plr->readyArtifact = plr->inventory[inv_ptr].type;
}
usearti = true;
}
// Check for spy mode player cycle
if (gamestate == GS_LEVEL && ev->type == ev_keydown
&& ev->data1 == KEY_F12 && !deathmatch)
{ // Cycle the display player
do
{
displayplayer++;
if (displayplayer == MAXPLAYERS)
{
displayplayer = 0;
}
}
while (!playeringame[displayplayer]
&& displayplayer != consoleplayer);
return (true);
}
if (gamestate == GS_LEVEL)
{
if (CT_Responder(ev))
{ // Chat ate the event
return (true);
}
if (SB_Responder(ev))
{ // Status bar ate the event
return (true);
}
if (AM_Responder(ev))
{ // Automap ate the event
return (true);
}
}
if (ev->type == ev_mouse)
{
testcontrols_mousespeed = abs(ev->data2);
}
if (ev->type == ev_keydown && ev->data1 == key_prevweapon)
{
next_weapon = -1;
}
else if (ev->type == ev_keydown && ev->data1 == key_nextweapon)
{
next_weapon = 1;
}
switch (ev->type)
{
case ev_keydown:
if (ev->data1 == key_invleft)
{
inventoryTics = 5 * 35;
if (!inventory)
{
inventory = true;
break;
}
inv_ptr--;
if (inv_ptr < 0)
{
inv_ptr = 0;
}
else
{
curpos--;
if (curpos < 0)
{
curpos = 0;
}
}
return (true);
}
if (ev->data1 == key_invright)
{
inventoryTics = 5 * 35;
if (!inventory)
{
inventory = true;
break;
}
inv_ptr++;
if (inv_ptr >= plr->inventorySlotNum)
{
inv_ptr--;
if (inv_ptr < 0)
inv_ptr = 0;
}
else
{
curpos++;
if (curpos > 6)
{
curpos = 6;
}
}
return (true);
}
if (ev->data1 == key_pause && !MenuActive)
{
sendpause = true;
return (true);
}
if (ev->data1 < NUMKEYS)
{
gamekeydown[ev->data1] = true;
}
return (true); // eat key down events
case ev_keyup:
if (ev->data1 < NUMKEYS)
{
gamekeydown[ev->data1] = false;
}
return (false); // always let key up events filter down
case ev_mouse:
SetMouseButtons(ev->data1);
mousex = ev->data2 * (mouseSensitivity + 5) / 10;
mousey = ev->data3 * (mouseSensitivity + 5) / 10;
return (true); // eat events
case ev_joystick:
SetJoyButtons(ev->data1);
joyxmove = ev->data2;
joyymove = ev->data3;
joystrafemove = ev->data4;
joylook = ev->data5;
return (true); // eat events
default:
break;
}
return (false);
}
/*
===============================================================================
=
= G_Ticker
=
===============================================================================
*/
void G_Ticker(void)
{
int i, buf;
ticcmd_t *cmd = NULL;
//
// do player reborns if needed
//
for (i = 0; i < MAXPLAYERS; i++)
if (playeringame[i] && players[i].playerstate == PST_REBORN)
G_DoReborn(i);
//
// do things to change the game state
//
while (gameaction != ga_nothing)
{
switch (gameaction)
{
case ga_loadlevel:
G_DoLoadLevel();
break;
case ga_newgame:
G_DoNewGame();
break;
case ga_loadgame:
G_DoLoadGame();
break;
case ga_savegame:
G_DoSaveGame();
break;
case ga_playdemo:
G_DoPlayDemo();
break;
case ga_screenshot:
V_ScreenShot("HTIC%02i.%s");
gameaction = ga_nothing;
break;
case ga_completed:
G_DoCompleted();
break;
case ga_worlddone:
G_DoWorldDone();
break;
case ga_victory:
F_StartFinale();
break;
default:
break;
}
}
//
// get commands, check consistancy, and build new consistancy check
//
//buf = gametic%BACKUPTICS;
buf = (gametic / ticdup) % BACKUPTICS;
for (i = 0; i < MAXPLAYERS; i++)
if (playeringame[i])
{
cmd = &players[i].cmd;
memcpy(cmd, &netcmds[i], sizeof(ticcmd_t));
if (demoplayback)
G_ReadDemoTiccmd(cmd);
if (demorecording)
G_WriteDemoTiccmd(cmd);
if (netgame && !(gametic % ticdup))
{
if (gametic > BACKUPTICS
&& consistancy[i][buf] != cmd->consistancy)
{
I_Error("consistency failure (%i should be %i)",
cmd->consistancy, consistancy[i][buf]);
}
if (players[i].mo)
consistancy[i][buf] = players[i].mo->x;
else
consistancy[i][buf] = rndindex;
}
}
//
// check for special buttons
//
for (i = 0; i < MAXPLAYERS; i++)
if (playeringame[i])
{
if (players[i].cmd.buttons & BT_SPECIAL)
{
switch (players[i].cmd.buttons & BT_SPECIALMASK)
{
case BTS_PAUSE:
paused ^= 1;
if (paused)
{
S_PauseSound();
}
else
{
S_ResumeSound();
}
break;
case BTS_SAVEGAME:
if (!savedescription[0])
{
if (netgame)
{
M_StringCopy(savedescription,
DEH_String("NET GAME"),
sizeof(savedescription));
}
else
{
M_StringCopy(savedescription,
DEH_String("SAVE GAME"),
sizeof(savedescription));
}
}
savegameslot =
(players[i].cmd.
buttons & BTS_SAVEMASK) >> BTS_SAVESHIFT;
gameaction = ga_savegame;
break;
}
}
}
// turn inventory off after a certain amount of time
if (inventory && !(--inventoryTics))
{
players[consoleplayer].readyArtifact =
players[consoleplayer].inventory[inv_ptr].type;
inventory = false;
cmd->arti = 0;
}
//
// do main actions
//
//
// do main actions
//
switch (gamestate)
{
case GS_LEVEL:
P_Ticker();
SB_Ticker();
AM_Ticker();
CT_Ticker();
break;
case GS_INTERMISSION:
IN_Ticker();
break;
case GS_FINALE:
F_Ticker();
break;
case GS_DEMOSCREEN:
D_PageTicker();
break;
}
}
/*
==============================================================================
PLAYER STRUCTURE FUNCTIONS
also see P_SpawnPlayer in P_Things
==============================================================================
*/
/*
====================
=
= G_InitPlayer
=
= Called at the start
= Called by the game initialization functions
====================
*/
void G_InitPlayer(int player)
{
// clear everything else to defaults
G_PlayerReborn(player);
}
/*
====================
=
= G_PlayerFinishLevel
=
= Can when a player completes a level
====================
*/
extern int playerkeys;
void G_PlayerFinishLevel(int player)
{
player_t *p;
int i;
/* // BIG HACK
inv_ptr = 0;
curpos = 0;
*/
// END HACK
p = &players[player];
for (i = 0; i < p->inventorySlotNum; i++)
{
p->inventory[i].count = 1;
}
p->artifactCount = p->inventorySlotNum;
if (!deathmatch)
{
for (i = 0; i < 16; i++)
{
P_PlayerUseArtifact(p, arti_fly);
}
}
memset(p->powers, 0, sizeof(p->powers));
memset(p->keys, 0, sizeof(p->keys));
playerkeys = 0;
// memset(p->inventory, 0, sizeof(p->inventory));
if (p->chickenTics)
{
p->readyweapon = p->mo->special1.i; // Restore weapon
p->chickenTics = 0;
}
p->messageTics = 0;
p->lookdir = 0;
p->mo->flags &= ~MF_SHADOW; // Remove invisibility
p->extralight = 0; // Remove weapon flashes
p->fixedcolormap = 0; // Remove torch
p->damagecount = 0; // No palette changes
p->bonuscount = 0;
p->rain1 = NULL;
p->rain2 = NULL;
if (p == &players[consoleplayer])
{
SB_state = -1; // refresh the status bar
}
}
/*
====================
=
= G_PlayerReborn
=
= Called after a player dies
= almost everything is cleared and initialized
====================
*/
void G_PlayerReborn(int player)
{
player_t *p;
int i;
int frags[MAXPLAYERS];
int killcount, itemcount, secretcount;
boolean secret;
secret = false;
memcpy(frags, players[player].frags, sizeof(frags));
killcount = players[player].killcount;
itemcount = players[player].itemcount;
secretcount = players[player].secretcount;
p = &players[player];
if (p->didsecret)
{
secret = true;
}
memset(p, 0, sizeof(*p));
memcpy(players[player].frags, frags, sizeof(players[player].frags));
players[player].killcount = killcount;
players[player].itemcount = itemcount;
players[player].secretcount = secretcount;
p->usedown = p->attackdown = true; // don't do anything immediately
p->playerstate = PST_LIVE;
p->health = MAXHEALTH;
p->readyweapon = p->pendingweapon = wp_goldwand;
p->weaponowned[wp_staff] = true;
p->weaponowned[wp_goldwand] = true;
p->messageTics = 0;
p->lookdir = 0;
p->ammo[am_goldwand] = 50;
for (i = 0; i < NUMAMMO; i++)
{
p->maxammo[i] = maxammo[i];
}
if (gamemap == 9 || secret)
{
p->didsecret = true;
}
if (p == &players[consoleplayer])
{
SB_state = -1; // refresh the status bar
inv_ptr = 0; // reset the inventory pointer
curpos = 0;
}
}
/*
====================
=
= G_CheckSpot
=
= Returns false if the player cannot be respawned at the given mapthing_t spot
= because something is occupying it
====================
*/
void P_SpawnPlayer(mapthing_t * mthing);
boolean G_CheckSpot(int playernum, mapthing_t * mthing)
{
fixed_t x, y;
subsector_t *ss;
unsigned an;
mobj_t *mo;
x = mthing->x << FRACBITS;
y = mthing->y << FRACBITS;
players[playernum].mo->flags2 &= ~MF2_PASSMOBJ;
if (!P_CheckPosition(players[playernum].mo, x, y))
{
players[playernum].mo->flags2 |= MF2_PASSMOBJ;
return false;
}
players[playernum].mo->flags2 |= MF2_PASSMOBJ;
// spawn a teleport fog
ss = R_PointInSubsector(x, y);
an = ((unsigned) ANG45 * (mthing->angle / 45)) >> ANGLETOFINESHIFT;
mo = P_SpawnMobj(x + 20 * finecosine[an], y + 20 * finesine[an],
ss->sector->floorheight + TELEFOGHEIGHT, MT_TFOG);
if (players[consoleplayer].viewz != 1)
S_StartSound(mo, sfx_telept); // don't start sound on first frame
return true;
}
/*
====================
=
= G_DeathMatchSpawnPlayer
=
= Spawns a player at one of the random death match spots
= called at level load and each death
====================
*/
void G_DeathMatchSpawnPlayer(int playernum)
{
int i, j;
int selections;
selections = deathmatch_p - deathmatchstarts;
if (selections < 4)
I_Error("Only %i deathmatch spots, 4 required", selections);
for (j = 0; j < 20; j++)
{
i = P_Random() % selections;
if (G_CheckSpot(playernum, &deathmatchstarts[i]))
{
deathmatchstarts[i].type = playernum + 1;
P_SpawnPlayer(&deathmatchstarts[i]);
return;
}
}
// no good spot, so the player will probably get stuck
P_SpawnPlayer(&playerstarts[playernum]);
}
/*
====================
=
= G_DoReborn
=
====================
*/
void G_DoReborn(int playernum)
{
int i;
// quit demo unless -demoextend
if (!demoextend && G_CheckDemoStatus())
return;
if (!netgame)
gameaction = ga_loadlevel; // reload the level from scratch
else
{ // respawn at the start
players[playernum].mo->player = NULL; // dissasociate the corpse
// spawn at random spot if in death match
if (deathmatch)
{
G_DeathMatchSpawnPlayer(playernum);
return;
}
if (G_CheckSpot(playernum, &playerstarts[playernum]))
{
P_SpawnPlayer(&playerstarts[playernum]);
return;
}
// try to spawn at one of the other players spots
for (i = 0; i < MAXPLAYERS; i++)
if (G_CheckSpot(playernum, &playerstarts[i]))
{
playerstarts[i].type = playernum + 1; // fake as other player
P_SpawnPlayer(&playerstarts[i]);
playerstarts[i].type = i + 1; // restore
return;
}
// he's going to be inside something. Too bad.
P_SpawnPlayer(&playerstarts[playernum]);
}
}
void G_ScreenShot(void)
{
gameaction = ga_screenshot;
}
/*
====================
=
= G_DoCompleted
=
====================
*/
boolean secretexit;
void G_ExitLevel(void)
{
secretexit = false;
gameaction = ga_completed;
}
void G_SecretExitLevel(void)
{
secretexit = true;
gameaction = ga_completed;
}
void G_DoCompleted(void)
{
int i;
static int afterSecret[5] = { 7, 5, 5, 5, 4 };
gameaction = ga_nothing;
// quit demo unless -demoextend
if (!demoextend && G_CheckDemoStatus())
{
return;
}
for (i = 0; i < MAXPLAYERS; i++)
{
if (playeringame[i])
{
G_PlayerFinishLevel(i);
}
}
prevmap = gamemap;
if (secretexit == true)
{
gamemap = 9;
}
else if (gamemap == 9)
{ // Finished secret level
gamemap = afterSecret[gameepisode - 1];
}
else if (gamemap == 8)
{
gameaction = ga_victory;
return;
}
else
{
gamemap++;
}
gamestate = GS_INTERMISSION;
IN_Start();
}
//============================================================================
//
// G_WorldDone
//
//============================================================================
void G_WorldDone(void)
{
gameaction = ga_worlddone;
}
//============================================================================
//
// G_DoWorldDone
//
//============================================================================
void G_DoWorldDone(void)
{
gamestate = GS_LEVEL;
G_DoLoadLevel();
gameaction = ga_nothing;
viewactive = true;
}
//---------------------------------------------------------------------------
//
// PROC G_LoadGame
//
// Can be called by the startup code or the menu task.
//
//---------------------------------------------------------------------------
static char *savename = NULL;
void G_LoadGame(char *name)
{
savename = M_StringDuplicate(name);
gameaction = ga_loadgame;
}
//---------------------------------------------------------------------------
//
// PROC G_DoLoadGame
//
// Called by G_Ticker based on gameaction.
//
//---------------------------------------------------------------------------
#define VERSIONSIZE 16
void G_DoLoadGame(void)
{
int i;
int a, b, c;
char savestr[SAVESTRINGSIZE];
char vcheck[VERSIONSIZE], readversion[VERSIONSIZE];
gameaction = ga_nothing;
SV_OpenRead(savename);
free(savename);
savename = NULL;
// Skip the description field
SV_Read(savestr, SAVESTRINGSIZE);
memset(vcheck, 0, sizeof(vcheck));
DEH_snprintf(vcheck, VERSIONSIZE, "version %i", HERETIC_VERSION);
SV_Read(readversion, VERSIONSIZE);
if (strncmp(readversion, vcheck, VERSIONSIZE) != 0)
{ // Bad version
return;
}
gameskill = SV_ReadByte();
gameepisode = SV_ReadByte();
gamemap = SV_ReadByte();
for (i = 0; i < MAXPLAYERS; i++)
{
playeringame[i] = SV_ReadByte();
}
// Load a base level
G_InitNew(gameskill, gameepisode, gamemap);
// Create leveltime
a = SV_ReadByte();
b = SV_ReadByte();
c = SV_ReadByte();
leveltime = (a << 16) + (b << 8) + c;
// De-archive all the modifications
P_UnArchivePlayers();
P_UnArchiveWorld();
P_UnArchiveThinkers();
P_UnArchiveSpecials();
if (SV_ReadByte() != SAVE_GAME_TERMINATOR)
{ // Missing savegame termination marker
I_Error("Bad savegame");
}
}
/*
====================
=
= G_InitNew
=
= Can be called by the startup code or the menu task
= consoleplayer, displayplayer, playeringame[] should be set
====================
*/
skill_t d_skill;
int d_episode;
int d_map;
void G_DeferedInitNew(skill_t skill, int episode, int map)
{
d_skill = skill;
d_episode = episode;
d_map = map;
gameaction = ga_newgame;
}
void G_DoNewGame(void)
{
G_InitNew(d_skill, d_episode, d_map);
gameaction = ga_nothing;
}
void G_InitNew(skill_t skill, int episode, int map)
{
int i;
int speed;
static char *skyLumpNames[5] = {
"SKY1", "SKY2", "SKY3", "SKY1", "SKY3"
};
if (paused)
{
paused = false;
S_ResumeSound();
}
if (skill < sk_baby)
skill = sk_baby;
if (skill > sk_nightmare)
skill = sk_nightmare;
if (episode < 1)
episode = 1;
// Up to 9 episodes for testing
if (episode > 9)
episode = 9;
if (map < 1)
map = 1;
if (map > 9)
map = 9;
M_ClearRandom();
if (respawnparm)
{
respawnmonsters = true;
}
else
{
respawnmonsters = false;
}
// Set monster missile speeds
speed = skill == sk_nightmare;
for (i = 0; MonsterMissileInfo[i].type != -1; i++)
{
mobjinfo[MonsterMissileInfo[i].type].speed
= MonsterMissileInfo[i].speed[speed] << FRACBITS;
}
// Force players to be initialized upon first level load
for (i = 0; i < MAXPLAYERS; i++)
{
players[i].playerstate = PST_REBORN;
players[i].didsecret = false;
}
// Set up a bunch of globals
usergame = true; // will be set false if a demo
paused = false;
demorecording = false;
demoplayback = false;
viewactive = true;
gameepisode = episode;
gamemap = map;
gameskill = skill;
viewactive = true;
BorderNeedRefresh = true;
// Set the sky map
if (episode > 5)
{
skytexture = R_TextureNumForName(DEH_String("SKY1"));
}
else
{
skytexture = R_TextureNumForName(DEH_String(skyLumpNames[episode - 1]));
}
//
// give one null ticcmd_t
//
#if 0
gametic = 0;
maketic = 1;
for (i = 0; i < MAXPLAYERS; i++)
nettics[i] = 1; // one null event for this gametic
memset(localcmds, 0, sizeof(localcmds));
memset(netcmds, 0, sizeof(netcmds));
#endif
G_DoLoadLevel();
}
/*
===============================================================================
DEMO RECORDING
===============================================================================
*/
#define DEMOMARKER 0x80
#define DEMOHEADER_RESPAWN 0x20
#define DEMOHEADER_LONGTICS 0x10
#define DEMOHEADER_NOMONSTERS 0x02
void G_ReadDemoTiccmd(ticcmd_t * cmd)
{
if (*demo_p == DEMOMARKER)
{ // end of demo data stream
G_CheckDemoStatus();
return;
}
cmd->forwardmove = ((signed char) *demo_p++);
cmd->sidemove = ((signed char) *demo_p++);
// If this is a longtics demo, read back in higher resolution
if (longtics)
{
cmd->angleturn = *demo_p++;
cmd->angleturn |= (*demo_p++) << 8;
}
else
{
cmd->angleturn = ((unsigned char) *demo_p++) << 8;
}
cmd->buttons = (unsigned char) *demo_p++;
cmd->lookfly = (unsigned char) *demo_p++;
cmd->arti = (unsigned char) *demo_p++;
}
// Increase the size of the demo buffer to allow unlimited demos
static void IncreaseDemoBuffer(void)
{
int current_length;
byte *new_demobuffer;
byte *new_demop;
int new_length;
// Find the current size
current_length = demoend - demobuffer;
// Generate a new buffer twice the size
new_length = current_length * 2;
new_demobuffer = Z_Malloc(new_length, PU_STATIC, 0);
new_demop = new_demobuffer + (demo_p - demobuffer);
// Copy over the old data
memcpy(new_demobuffer, demobuffer, current_length);
// Free the old buffer and point the demo pointers at the new buffer.
Z_Free(demobuffer);
demobuffer = new_demobuffer;
demo_p = new_demop;
demoend = demobuffer + new_length;
}
void G_WriteDemoTiccmd(ticcmd_t * cmd)
{
byte *demo_start;
if (gamekeydown[key_demo_quit]) // press to end demo recording
G_CheckDemoStatus();
demo_start = demo_p;
*demo_p++ = cmd->forwardmove;
*demo_p++ = cmd->sidemove;
// If this is a longtics demo, record in higher resolution
if (longtics)
{
*demo_p++ = (cmd->angleturn & 0xff);
*demo_p++ = (cmd->angleturn >> 8) & 0xff;
}
else
{
*demo_p++ = cmd->angleturn >> 8;
}
*demo_p++ = cmd->buttons;
*demo_p++ = cmd->lookfly;
*demo_p++ = cmd->arti;
// reset demo pointer back
demo_p = demo_start;
if (demo_p > demoend - 16)
{
if (vanilla_demo_limit)
{
// no more space
G_CheckDemoStatus();
return;
}
else
{
// Vanilla demo limit disabled: unlimited
// demo lengths!
IncreaseDemoBuffer();
}
}
G_ReadDemoTiccmd(cmd); // make SURE it is exactly the same
}
/*
===================
=
= G_RecordDemo
=
===================
*/
void G_RecordDemo(skill_t skill, int numplayers, int episode, int map,
char *name)
{
int i;
int maxsize;
//!
// @category demo
//
// Record or playback a demo with high resolution turning.
//
longtics = D_NonVanillaRecord(M_ParmExists("-longtics"),
"vvHeretic longtics demo");
// If not recording a longtics demo, record in low res
lowres_turn = !longtics;
//!
// @category demo
//
// Smooth out low resolution turning when recording a demo.
//
shortticfix = M_ParmExists("-shortticfix");
G_InitNew(skill, episode, map);
usergame = false;
M_StringCopy(demoname, name, sizeof(demoname));
M_StringConcat(demoname, ".lmp", sizeof(demoname));
maxsize = 0x20000;
//!
// @arg <size>
// @category demo
// @vanilla
//
// Specify the demo buffer size (KiB)
//
i = M_CheckParmWithArgs("-maxdemo", 1);
if (i)
maxsize = atoi(myargv[i + 1]) * 1024;
demobuffer = Z_Malloc(maxsize, PU_STATIC, NULL);
demoend = demobuffer + maxsize;
demo_p = demobuffer;
*demo_p++ = skill;
*demo_p++ = episode;
*demo_p++ = map;
// Write special parameter bits onto player one byte.
// This aligns with vvHeretic demo usage:
// 0x20 = -respawn
// 0x10 = -longtics
// 0x02 = -nomonsters
*demo_p = 1; // assume player one exists
if (D_NonVanillaRecord(respawnparm, "vvHeretic -respawn header flag"))
{
*demo_p |= DEMOHEADER_RESPAWN;
}
if (longtics)
{
*demo_p |= DEMOHEADER_LONGTICS;
}
if (D_NonVanillaRecord(nomonsters, "vvHeretic -nomonsters header flag"))
{
*demo_p |= DEMOHEADER_NOMONSTERS;
}
demo_p++;
for (i = 1; i < MAXPLAYERS; i++)
*demo_p++ = playeringame[i];
demorecording = true;
}
/*
===================
=
= G_PlayDemo
=
===================
*/
static const char *defdemoname;
void G_DeferedPlayDemo(const char *name)
{
defdemoname = name;
gameaction = ga_playdemo;
}
void G_DoPlayDemo(void)
{
skill_t skill;
int i, lumpnum, episode, map;
gameaction = ga_nothing;
lumpnum = W_GetNumForName(defdemoname);
demobuffer = W_CacheLumpNum(lumpnum, PU_STATIC);
demo_p = demobuffer;
skill = *demo_p++;
episode = *demo_p++;
map = *demo_p++;
// vvHeretic allows extra options to be stored in the upper bits of
// the player 1 present byte. However, this is a non-vanilla extension.
if (D_NonVanillaPlayback((*demo_p & DEMOHEADER_LONGTICS) != 0,
lumpnum, "vvHeretic longtics demo"))
{
longtics = true;
}
if (D_NonVanillaPlayback((*demo_p & DEMOHEADER_RESPAWN) != 0,
lumpnum, "vvHeretic -respawn header flag"))
{
respawnparm = true;
}
if (D_NonVanillaPlayback((*demo_p & DEMOHEADER_NOMONSTERS) != 0,
lumpnum, "vvHeretic -nomonsters header flag"))
{
nomonsters = true;
}
for (i = 0; i < MAXPLAYERS; i++)
playeringame[i] = (*demo_p++) != 0;
precache = false; // don't spend a lot of time in loadlevel
G_InitNew(skill, episode, map);
precache = true;
usergame = false;
demoplayback = true;
}
/*
===================
=
= G_TimeDemo
=
===================
*/
void G_TimeDemo(char *name)
{
skill_t skill;
int episode, map, i;
demobuffer = demo_p = W_CacheLumpName(name, PU_STATIC);
skill = *demo_p++;
episode = *demo_p++;
map = *demo_p++;
// Read special parameter bits: see G_RecordDemo() for details.
longtics = (*demo_p & DEMOHEADER_LONGTICS) != 0;
// don't overwrite arguments from the command line
respawnparm |= (*demo_p & DEMOHEADER_RESPAWN) != 0;
nomonsters |= (*demo_p & DEMOHEADER_NOMONSTERS) != 0;
for (i = 0; i < MAXPLAYERS; i++)
{
playeringame[i] = (*demo_p++) != 0;
}
G_InitNew(skill, episode, map);
starttime = I_GetTime();
usergame = false;
demoplayback = true;
timingdemo = true;
singletics = true;
}
/*
===================
=
= G_CheckDemoStatus
=
= Called after a death or level completion to allow demos to be cleaned up
= Returns true if a new demo loop action will take place
===================
*/
boolean G_CheckDemoStatus(void)
{
int endtime, realtics;
if (timingdemo)
{
float fps;
endtime = I_GetTime();
realtics = endtime - starttime;
fps = ((float) gametic * TICRATE) / realtics;
I_Error("timed %i gametics in %i realtics (%f fps)",
gametic, realtics, fps);
}
if (demoplayback)
{
if (singledemo)
I_Quit();
W_ReleaseLumpName(defdemoname);
demoplayback = false;
D_AdvanceDemo();
return true;
}
if (demorecording)
{
*demo_p++ = DEMOMARKER;
M_WriteFile(demoname, demobuffer, demo_p - demobuffer);
Z_Free(demobuffer);
demorecording = false;
I_Error("Demo %s recorded", demoname);
}
return false;
}
/**************************************************************************/
/**************************************************************************/
//==========================================================================
//
// G_SaveGame
//
// Called by the menu task. <description> is a 24 byte text string.
//
//==========================================================================
void G_SaveGame(int slot, char *description)
{
savegameslot = slot;
M_StringCopy(savedescription, description, sizeof(savedescription));
sendsave = true;
}
//==========================================================================
//
// G_DoSaveGame
//
// Called by G_Ticker based on gameaction.
//
//==========================================================================
void G_DoSaveGame(void)
{
int i;
char *filename;
char verString[VERSIONSIZE];
char *description;
filename = SV_Filename(savegameslot);
description = savedescription;
SV_Open(filename);
SV_Write(description, SAVESTRINGSIZE);
memset(verString, 0, sizeof(verString));
DEH_snprintf(verString, VERSIONSIZE, "version %i", HERETIC_VERSION);
SV_Write(verString, VERSIONSIZE);
SV_WriteByte(gameskill);
SV_WriteByte(gameepisode);
SV_WriteByte(gamemap);
for (i = 0; i < MAXPLAYERS; i++)
{
SV_WriteByte(playeringame[i]);
}
SV_WriteByte(leveltime >> 16);
SV_WriteByte(leveltime >> 8);
SV_WriteByte(leveltime);
P_ArchivePlayers();
P_ArchiveWorld();
P_ArchiveThinkers();
P_ArchiveSpecials();
SV_Close(filename);
gameaction = ga_nothing;
savedescription[0] = 0;
P_SetMessage(&players[consoleplayer], DEH_String(TXT_GAMESAVED), true);
free(filename);
}
| 0 | 0.822253 | 1 | 0.822253 | game-dev | MEDIA | 0.994373 | game-dev | 0.553994 | 1 | 0.553994 |
ill-inc/biomes-game | 2,409 | src/server/shared/minigames/spleef/client_script.ts | import type { GardenHoseEventOfKind } from "@/client/events/api";
import type { ClientContextSubset } from "@/client/game/context";
import type { Script } from "@/client/game/scripts/script_controller";
import { cleanEmitterCallback } from "@/client/util/helpers";
import { isReadonlyMinigameInstanceOfStateKind } from "@/server/shared/minigames/type_utils";
import { TagMinigameHitPlayerEvent } from "@/shared/ecs/gen/events";
import type { BiomesId } from "@/shared/ids";
import { fireAndForget } from "@/shared/util/async";
import { ok } from "assert";
export class SpleefClientScript implements Script {
readonly name = "spleefClient";
private cleanUps: Array<() => unknown> = [];
constructor(
private deps: ClientContextSubset<
| "userId"
| "gardenHose"
| "resources"
| "audioManager"
| "table"
| "events"
>,
private minigameId: BiomesId,
private minigameInstanceId: BiomesId
) {
this.cleanUps.push(
cleanEmitterCallback(deps.gardenHose, {
start_collide_entity: (ev) => {
this.onStartCollideEntity(ev);
},
})
);
}
clear() {
for (const cleanup of this.cleanUps) {
cleanup();
}
this.cleanUps = [];
}
tick(_dt: number) {}
private onStartCollideEntity(
ev: GardenHoseEventOfKind<"start_collide_entity">
) {
if (ev.entityId === this.deps.userId) {
return;
}
if (this.minigameInstance.state.instance_state.kind !== "playing_round") {
return;
}
if (
!this.minigameInstance.state.instance_state.alive_round_players.has(
ev.entityId
)
) {
return;
}
if (
this.minigameInstance.state.instance_state.tag_round_state?.it_player !==
this.deps.userId
) {
return;
}
this.taggedHitPlayer(ev.entityId);
}
private taggedHitPlayer(entityId: BiomesId) {
fireAndForget(
this.deps.events.publish(
new TagMinigameHitPlayerEvent({
id: this.deps.userId,
minigame_id: this.minigameId,
minigame_instance_id: this.minigameInstanceId,
hit_player_id: entityId,
})
)
);
}
private get minigameInstance() {
const ret = this.deps.resources.get(
"/ecs/c/minigame_instance",
this.minigameInstanceId
);
ok(isReadonlyMinigameInstanceOfStateKind(ret, "spleef"));
return ret;
}
}
| 0 | 0.918185 | 1 | 0.918185 | game-dev | MEDIA | 0.572417 | game-dev | 0.900308 | 1 | 0.900308 |
Andrettin/Wyrmgus | 3,040 | src/script/effect/random_settlement_center_unit_effect.h | // _________ __ __
// / _____// |_____________ _/ |______ ____ __ __ ______
// \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/
// / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ |
// /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ >
// \/ \/ \//_____/ \/
// ______________________ ______________________
// T H E W A R B E G I N S
// Stratagus - A free fantasy real time strategy game engine
//
// (c) Copyright 2022 by Andrettin
//
// 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; only version 2 of the License.
//
// 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.
#pragma once
#include "player/player.h"
#include "script/effect/scope_effect_base.h"
#include "unit/unit.h"
#include "util/vector_util.h"
#include "util/vector_random_util.h"
namespace wyrmgus {
class random_settlement_center_unit_effect final : public scope_effect_base<CPlayer, CUnit>
{
public:
explicit random_settlement_center_unit_effect(const gsml_operator effect_operator)
: scope_effect_base(effect_operator)
{
}
virtual const std::string &get_class_identifier() const override
{
static const std::string class_identifier = "random_settlement_center_unit";
return class_identifier;
}
virtual void process_gsml_scope(const gsml_data &scope) override
{
const std::string &tag = scope.get_tag();
if (tag == "conditions") {
scope.process(&this->conditions);
} else {
scope_effect_base::process_gsml_scope(scope);
}
}
virtual void do_assignment_effect(CPlayer *player, context &ctx) const override
{
std::vector<CUnit *> potential_units = player->get_town_hall_units();
vector::merge(potential_units, player->get_type_units(settlement_site_unit_type));
std::erase_if(potential_units, [this, &ctx](const CUnit *town_hall) {
return !this->conditions.check(town_hall, ctx);
});
if (potential_units.empty()) {
return;
}
CUnit *unit = vector::get_random(potential_units);
this->do_scope_effect(unit, ctx);
}
virtual std::string get_scope_name() const override
{
return "Random settlement center";
}
virtual std::string get_conditions_string(const size_t indent) const override
{
return this->conditions.get_conditions_string(indent, false);
}
private:
and_condition<CUnit> conditions;
};
}
| 0 | 0.884625 | 1 | 0.884625 | game-dev | MEDIA | 0.45959 | game-dev | 0.915693 | 1 | 0.915693 |
retromcorg/Project-Poseidon | 5,973 | src/main/java/org/bukkit/entity/LivingEntity.java | package org.bukkit.entity;
import org.bukkit.Location;
import org.bukkit.block.Block;
import java.util.HashSet;
import java.util.List;
/**
* Represents a living entity, such as a monster or player
*/
public interface LivingEntity extends Entity {
/**
* Gets the entity's health from 0-20, where 0 is dead and 20 is full
*
* @return Health represented from 0-20
*/
public int getHealth();
/**
* Sets the entity's health from 0-20, where 0 is dead and 20 is full
*
* @param health New health represented from 0-20
*/
public void setHealth(int health);
/**
* Gets the height of the entity's head above its Location
*
* @return Height of the entity's eyes above its Location
*/
public double getEyeHeight();
/**
* Gets the height of the entity's head above its Location
*
* @param boolean If set to true, the effects of sneaking will be ignored
* @return Height of the entity's eyes above its Location
*/
public double getEyeHeight(boolean ignoreSneaking);
/**
* Get a Location detailing the current eye position of the LivingEntity.
*
* @return a Location at the eyes of the LivingEntity.
*/
public Location getEyeLocation();
/**
* Gets all blocks along the player's line of sight
* List iterates from player's position to target inclusive
*
* @param HashSet<Byte> HashSet containing all transparent block IDs. If set to null only air is considered transparent.
* @param int This is the maximum distance to scan. This may be further limited by the server, but never to less than 100 blocks.
* @return List containing all blocks along the player's line of sight
*/
public List<Block> getLineOfSight(HashSet<Byte> transparent, int maxDistance);
/**
* Gets the block that the player has targeted
*
* @param HashSet<Byte> HashSet containing all transparent block IDs. If set to null only air is considered transparent.
* @param int This is the maximum distance to scan. This may be further limited by the server, but never to less than 100 blocks.
* @return Block that the player has targeted
*/
public Block getTargetBlock(HashSet<Byte> transparent, int maxDistance);
/**
* Gets the last two blocks along the player's line of sight.
* The target block will be the last block in the list.
*
* @param HashSet<Byte> HashSet containing all transparent block IDs. If set to null only air is considered transparent.
* @param int This is the maximum distance to scan. This may be further limited by the server, but never to less than 100 blocks
* @return List containing the last 2 blocks along the player's line of sight
*/
public List<Block> getLastTwoTargetBlocks(HashSet<Byte> transparent, int maxDistance);
/**
* Throws an egg from the entity.
*/
public Egg throwEgg();
/**
* Throws a snowball from the entity.
*/
public Snowball throwSnowball();
/**
* Shoots an arrow from the entity.
*
* @return
*/
public Arrow shootArrow();
/**
* Returns whether this entity is inside a vehicle.
*
* @return
*/
public boolean isInsideVehicle();
/**
* Leave the current vehicle. If the entity is currently in a vehicle
* (and is removed from it), true will be returned, otherwise false will
* be returned.
*
* @return
*/
public boolean leaveVehicle();
/**
* Get the vehicle that this player is inside. If there is no vehicle,
* null will be returned.
*
* @return
*/
public Vehicle getVehicle();
/**
* Returns the amount of air that this entity has remaining, in ticks
*
* @return Amount of air remaining
*/
public int getRemainingAir();
/**
* Sets the amount of air that this entity has remaining, in ticks
*
* @param ticks Amount of air remaining
*/
public void setRemainingAir(int ticks);
/**
* Returns the maximum amount of air this entity can have, in ticks
*
* @return Maximum amount of air
*/
public int getMaximumAir();
/**
* Sets the maximum amount of air this entity can have, in ticks
*
* @param ticks Maximum amount of air
*/
public void setMaximumAir(int ticks);
/**
* Deals the given amount of damage to this entity
*
* @param amount Amount of damage to deal
*/
public void damage(int amount);
/**
* Deals the given amount of damage to this entity, from a specified entity
*
* @param amount Amount of damage to deal
* @param source Entity which to attribute this damage from
*/
public void damage(int amount, Entity source);
/**
* Returns the entities current maximum noDamageTicks
* This is the time in ticks the entity will become unable to take
* equal or less damage than the lastDamage
*
* @return noDamageTicks
*/
public int getMaximumNoDamageTicks();
/**
* Sets the entities current maximum noDamageTicks
*
* @param ticks maximumNoDamageTicks
*/
public void setMaximumNoDamageTicks(int ticks);
/**
* Returns the entities lastDamage taken in the current noDamageTicks time.
* Only damage higher than this amount will further damage the entity.
*
* @return lastDamage
*/
public int getLastDamage();
/**
* Sets the entities current maximum noDamageTicks
*
* @param damage last damage
*/
public void setLastDamage(int damage);
/**
* Returns the entities current noDamageTicks
*
* @return noDamageTicks
*/
public int getNoDamageTicks();
/**
* Sets the entities current noDamageTicks
*
* @param ticks NoDamageTicks
*/
public void setNoDamageTicks(int ticks);
}
| 0 | 0.852359 | 1 | 0.852359 | game-dev | MEDIA | 0.93239 | game-dev | 0.743411 | 1 | 0.743411 |
NextAlone/Nagram | 1,323 | TMessagesProj/jni/voip/webrtc/base/time/time_override.cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/time/time_override.h"
namespace base {
namespace subtle {
// static
bool ScopedTimeClockOverrides::overrides_active_ = false;
ScopedTimeClockOverrides::ScopedTimeClockOverrides(
TimeNowFunction time_override,
TimeTicksNowFunction time_ticks_override,
ThreadTicksNowFunction thread_ticks_override) {
DCHECK(!overrides_active_);
overrides_active_ = true;
if (time_override) {
internal::g_time_now_function = time_override;
internal::g_time_now_from_system_time_function = time_override;
}
if (time_ticks_override)
internal::g_time_ticks_now_function = time_ticks_override;
if (thread_ticks_override)
internal::g_thread_ticks_now_function = thread_ticks_override;
}
ScopedTimeClockOverrides::~ScopedTimeClockOverrides() {
internal::g_time_now_function = &TimeNowIgnoringOverride;
internal::g_time_now_from_system_time_function =
&TimeNowFromSystemTimeIgnoringOverride;
internal::g_time_ticks_now_function = &TimeTicksNowIgnoringOverride;
internal::g_thread_ticks_now_function = &ThreadTicksNowIgnoringOverride;
overrides_active_ = false;
}
} // namespace subtle
} // namespace base
| 0 | 0.841479 | 1 | 0.841479 | game-dev | MEDIA | 0.343605 | game-dev | 0.771438 | 1 | 0.771438 |
LittleDuck-LD/EMBrawl-51 | 16,759 | Classes/Logic/LogicStarrDropData.py | from Classes.Files.Classes.Cards import Cards
from Classes.Files.Classes.Pins import Emotes
from Classes.Files.Classes.PlayerThumbnails import PlayerThumbnails
from Classes.Files.Classes.Skins import Skins
from Classes.Files.Classes.Sprays import Sprays
from Classes.Files.Classes.Characters import Characters
import random
items_ids = {
"Coins": {
"OfferID": 1,
"DeliveryID": 7
},
"TokenDoubler": {
"OfferID": 9,
"DeliveryID": 2
},
"Credits": {
"OfferID": 38,
"DeliveryID": 22
},
"ChromaCredits": {
"OfferID": 39,
"DeliveryID": 23
},
"PowerPoints": {
"OfferID": 41,
"DeliveryID": 24
},
"Bling": {
"OfferID": 45,
"DeliveryID": 25
},
"Brawler": {
"OfferID": 3,
"DeliveryID": 1
},
"Skin": {
"OfferID": 4,
"DeliveryID": 9
},
"Pin": {
"OfferID": 19,
"DeliveryID": 11
},
"ProfilePic": {
"OfferID": 25,
"DeliveryID": 11
},
"Spray": {
"OfferID": 35,
"DeliveryID": 11
},
"StarPower": {
"OfferID": 5,
"DeliveryID": 4
},
"Gadget": {
"OfferID": 5,
"DeliveryID": 4
},
}
starrDrop_data = {
"Rare": {
"Rarity_ID": 0,
"DropChance": 50,
"TotalTickets": 215,
"Possibilities": {
"Coins_s": {
"Type": "Coins",
"Tickets": 75,
"Min": 50,
"Max": 70,
"Fallback": []
},
"PowerPoints_s": {
"Type": "PowerPoints",
"Tickets": 85,
"Min": 20,
"Max": 30,
"Fallback": []
},
"Credits_s": {
"Type": "Credits",
"Tickets": 5,
"Min": 20,
"Max": 28,
"Fallback": []
},
"Blings_s": {
"Type": "Bling",
"Tickets": 5,
"Min": 20,
"Max": 28,
"Fallback": []
},
"TokenDoubler_s": {
"Type": "TokenDoubler",
"Tickets": 45,
"Min": 100,
"Max": 150,
"Fallback": ["Credits", 100]
}
}
},
"Super_Rare": {
"Rarity_ID": 1,
"DropChance": 28,
"TotalTickets": 151,
"Possibilities": {
"Coins_m": {
"Type": "Coins",
"Tickets": 45,
"Min": 100,
"Max": 140,
"Fallback": []
},
"PowerPoints_m": {
"Type": "PowerPoints",
"Tickets": 60,
"Min": 50,
"Max": 70,
"Fallback": []
},
"Credits_m": {
"Type": "Credits",
"Tickets": 4,
"Min": 50,
"Max": 60,
"Fallback": []
},
"Blings_m": {
"Type": "Bling",
"Tickets": 5,
"Min": 50,
"Max": 60,
"Fallback": []
},
"TokenDoubler_m": {
"Type": "TokenDoubler",
"Tickets": 37,
"Min": 500,
"Max": 575,
"Fallback": ["Credits", 100]
}
}
},
"Epic": {
"Rarity_ID": 2,
"DropChance": 15,
"TotalTickets": 227,
"Possibilities": {
"Coins_l": {
"Type": "Coins",
"Tickets": 90,
"Min": 200,
"Max": 240,
"Fallback": []
},
"PowerPoints_l": {
"Type": "PowerPoints",
"Tickets": 60,
"Min": 100,
"Max": 130,
"Fallback": []
},
"Brawler_Rare": {
"Type": "Brawler",
"Rarity": "rare",
"Tickets": 7,
"Fallback": ["Credits", 100]
},
"Brawler_SuperRare": {
"Type": "Brawler",
"Rarity": "super_rare",
"Tickets": 3,
"Fallback": ["Credits", 250]
},
"Pin_1-9Gems": {
"Type": "Pin",
"Tickets": 10,
"MinPrice": 1,
"MaxPrice": 9,
"Fallback": ["Credits", 100]
},
"Spray_1-19Gems": {
"Type": "Spray",
"Tickets": 5,
"MinPrice": 1,
"MaxPrice": 19,
"Fallback": ["Credits", 100]
},
"ProfilePic": {
"Type": "ProfilePic",
"Tickets": 7,
"Fallback": ["Credits", 200]
},
"TokenDoubler_l": {
"Type": "TokenDoubler",
"Tickets": 45,
"Min": 1000,
"Max": 1200,
"Fallback": ["Credits", 100]
}
}
},
"Mythic": {
"Rarity_ID": 3,
"DropChance": 5,
"TotalTickets": 135,
"Possibilities": {
"Coins_xl": {
"Type": "Coins",
"Tickets": 25,
"Min": 500,
"Max": 540,
"Fallback": []
},
"PowerPoints_xl": {
"Type": "PowerPoints",
"Tickets": 35,
"Min": 240,
"Max": 280,
"Fallback": []
},
"Brawler_Epic": {
"Type": "Brawler",
"Rarity": "epic",
"Tickets": 7,
"Fallback": ["Credits", 500]
},
"Brawler_Mythic": {
"Type": "Brawler",
"Rarity": "mega_epic",
"Tickets": 2,
"Fallback": ["Credits", 1000]
},
"Skin_1-29Gems": {
"Type": "Skin",
"Tickets": 10,
"MinPrice": 1,
"MaxPrice": 29,
"Fallback": ["Credits", 200]
},
"Skin_30-79Gems": {
"Type": "Skin",
"Tickets": 2,
"MinPrice": 30,
"MaxPrice": 79,
"Fallback": ["Credits", 250]
},
"Pin_1-9Gems": {
"Type": "Pin",
"Tickets": 25,
"MinPrice": 1,
"MaxPrice": 9,
"Fallback": ["Credits", 100]
},
"Pin_10-29Gems": {
"Type": "Pin",
"Tickets": 10,
"MinPrice": 10,
"MaxPrice": 29,
"Fallback": ["Credits", 150]
},
"Spray_1-19Gems": {
"Type": "Spray",
"Tickets": 5,
"MinPrice": 1,
"MaxPrice": 19,
"Fallback": ["Credits", 100]
},
"ProfilePic": {
"Type": "ProfilePic",
"Tickets": 14,
"Fallback": ["Credits", 200]
}
}
},
"Legendary": {
"Rarity_ID": 4,
"DropChance": 2,
"TotalTickets": 116,
"Possibilities": {
"Gadget": {
"Type": "Gadget",
"Tickets": 35,
"Fallback": ["Coins", 1000]
},
"StarPower": {
"Type": "StarPower",
"Tickets": 30,
"Fallback": ["Coins", 1000]
},
"Brawler_Epic": {
"Type": "Brawler",
"Rarity": "epic",
"Tickets": 9,
"Fallback": ["Credits", 500]
},
"Brawler_Mythic": {
"Type": "Brawler",
"Rarity": "mega_epic",
"Tickets": 3,
"Fallback": ["Credits", 1000]
},
"Brawler_Legendary": {
"Type": "Brawler",
"Rarity": "legendary",
"Tickets": 2,
"Fallback": ["Credits", 2000]
},
"Skin_1-29Gems": {
"Type": "Skin",
"Tickets": 10,
"MinPrice": 1,
"MaxPrice": 29,
"Fallback": ["Credits", 200]
},
"Skin_30-79Gems": {
"Type": "Skin",
"Tickets": 6,
"MinPrice": 30,
"MaxPrice": 79,
"Fallback": ["Credits", 250]
},
"Skin_80-149Gems": {
"Type": "Skin",
"Tickets": 4,
"MinPrice": 80,
"MaxPrice": 149,
"Fallback": ["Credits", 300]
},
"Pin_30-39Gems": {
"Type": "Pin",
"Tickets": 12,
"MinPrice": 30,
"MaxPrice": 999,
"Fallback": ["Credits", 200]
},
"Spray_20-29Gems": {
"Type": "Spray",
"Tickets": 5,
"MinPrice": 20,
"MaxPrice": 999,
"Fallback": ["Credits", 150]
}
}
},
}
class LogicStarrDropData():
def __init__(self):
self.starrDrop_data = starrDrop_data
self.items_ids = items_ids
self.starr_drop_encoding_data = []
self.range_price_items = ["Skin", "Pin", "Spray"]
self.skin = Skins()
self.pin = Emotes()
self.spray = Sprays()
self.brawler = Characters()
self.card = Cards()
self.profile_pic = PlayerThumbnails()
self.rare_count = 0
self.super_rare_count = 0
self.epic_count = 0
self.mythic_count = 0
self.legendary_count = 0
def choose_random_starrDrop(self):
random_number = random.randint(1, 100)
cumulative = 0
chosen_drop = None
for box_type in self.starrDrop_data.items():
cumulative += self.starrDrop_data[f"{box_type[0]}"]["DropChance"]
if random_number <= cumulative:
chosen_drop = box_type
break
return chosen_drop[0]
def choose_random_reward(self, chosen_drop):
random_number = random.randint(1, self.starrDrop_data[f"{chosen_drop}"]["TotalTickets"])
cumulative = 0
chosen_reward = None
for item, data in self.starrDrop_data[f"{chosen_drop}"]["Possibilities"].items():
cumulative += data["Tickets"]
if random_number <= cumulative:
chosen_reward = item
break
return chosen_reward
def create_starrDrop_opening(self, drop_count, starrDrop_rarity = None, rarity_set = None):
for i in range(drop_count):
starrDrop = []
if rarity_set is None:
starrDrop_rarity = self.choose_random_starrDrop()
starrDrop_reward = self.choose_random_reward(starrDrop_rarity)
else:
starrDrop_reward = self.choose_random_reward(starrDrop_rarity)
try:
starrDrop_reward_amount = random.randint(self.starrDrop_data[f"{starrDrop_rarity}"]["Possibilities"][f"{starrDrop_reward}"]["Min"],self.starrDrop_data[f"{starrDrop_rarity}"]["Possibilities"][f"{starrDrop_reward}"]["Max"])
except KeyError:
starrDrop_reward_amount = 1
starrDrop_type = self.starrDrop_data[f"{starrDrop_rarity}"]["Possibilities"][f"{starrDrop_reward}"]["Type"]
self.updateCount(self.starrDrop_data[f"{starrDrop_rarity}"]["Rarity_ID"])
starrDrop.append(self.starrDrop_data[f"{starrDrop_rarity}"]["Rarity_ID"])
starrDrop.append(starrDrop_type)
starrDrop.append(starrDrop_reward_amount)
if starrDrop_type in self.range_price_items:
starrDrop.append(self.getRewarditemID(starrDrop_type, min=self.starrDrop_data[f"{starrDrop_rarity}"]["Possibilities"][f"{starrDrop_reward}"]["MinPrice"], max=self.starrDrop_data[f"{starrDrop_rarity}"]["Possibilities"][f"{starrDrop_reward}"]["MaxPrice"]))
elif starrDrop_type == "Brawler":
starrDrop.append(self.getRewarditemID(starrDrop_type, additional=self.starrDrop_data[f"{starrDrop_rarity}"]["Possibilities"][f"{starrDrop_reward}"]["Rarity"]))
elif starrDrop_type == "StarPower":
starrDrop.append(self.getRewarditemID(starrDrop_type, additional=4))
elif starrDrop_type == "Gadget":
starrDrop.append(self.getRewarditemID(starrDrop_type, additional=5))
elif starrDrop_type == "ProfilePic":
starrDrop.append(self.getRewarditemID(starrDrop_type))
self.starr_drop_encoding_data.append(starrDrop)
self.setStarrDropEncodingData(self.starr_drop_encoding_data)
def getDeliveryIdFromOfferType(self, offer_type):
return self.items_ids[f"{offer_type}"]["DeliveryID"]
def getStarrDropEncoding(self):
return self.starr_drop_encoding_data
def setStarrDropEncodingData(self, starr_drop_encoding):
self.starr_drop_encoding_data = starr_drop_encoding
def refreshData(self):
self.starr_drop_encoding_data.pop(0)
self.setStarrDropEncodingData(self.starr_drop_encoding_data)
def getRewarditemID(self, item, min=None, max=None, additional=None):
if item == "Skin":
skin_possibilities = self.skin.getSkinsIDSSpecificPrice(min, max)
skin_awarded = random.randint(0, len(skin_possibilities) -1)
return skin_possibilities[skin_awarded]
elif item == "Pin":
pin_possibilities = self.pin.getPinsIDSSpecificPrice(min, max)
pin_awarded = random.randint(0, len(pin_possibilities) -1)
return pin_possibilities[pin_awarded]
elif item == "Spray":
spray_possibilities = self.spray.getSpraysIDSSpecificPrice(min, max)
spray_awarded = random.randint(0, len(spray_possibilities) -1)
return spray_possibilities[spray_awarded]
elif item == "Brawler":
brawler_possibilities = self.brawler.getBrawlerFromSepcificRarity(additional)
brawler_awarded = random.randint(0, len(brawler_possibilities) -1)
return brawler_possibilities[brawler_awarded]
elif item == "StarPower" or item == "Gadget":
card_possibilities = self.card.getCardsListFromMetaType(additional)
card_awarded = random.randint(0, len(card_possibilities) -1)
return card_possibilities[card_awarded]
elif item == "ProfilePic":
return random.randint(0, self.profile_pic.getThumbnailsCount())
def updateCount(self, rarity_id):
if rarity_id == 0:
self.rare_count +=1
elif rarity_id == 1:
self.super_rare_count += 1
elif rarity_id == 2:
self.epic_count += 1
elif rarity_id == 3:
self.mythic_count += 1
elif rarity_id == 4:
self.legendary_count += 1
def encode(self, ByteStream):
ByteStream.writeVInt(5)
for i in range(5):
ByteStream.writeDataReference(80, i)
ByteStream.writeVInt(-1)
ByteStream.writeVInt(0)
ByteStream.writeVInt(len(self.starr_drop_encoding_data))
for x in range(len(self.starr_drop_encoding_data)):
ByteStream.writeDataReference(80,self.starr_drop_encoding_data[len(self.starr_drop_encoding_data )-x -1][0])
ByteStream.writeVInt(len(self.starr_drop_encoding_data))
for x in range(len(self.starr_drop_encoding_data)):
ByteStream.writeByte(1)
reward_type = self.starr_drop_encoding_data[x][1]
offer_id_type = self.items_ids[reward_type]["OfferID"]
ByteStream.writeVInt(offer_id_type)
ByteStream.writeVInt(self.starr_drop_encoding_data[x][2])
ByteStream.writeDataReference(0, 0)
ByteStream.writeVInt(0)
ByteStream.writeInt(-1788180018)
ByteStream.writeVInt(8) # progression step in battles
ByteStream.writeVInt(0)
ByteStream.writeVInt(73529) # timer until refresh
ByteStream.writeVInt(0) #v51 new count
ByteStream.writeVInt(0) #v51 new count
starrDropOpening = LogicStarrDropData()
| 0 | 0.69794 | 1 | 0.69794 | game-dev | MEDIA | 0.863588 | game-dev | 0.588223 | 1 | 0.588223 |
ForOne-Club/ImproveGame | 1,139 | UI/ModernConfig/FakeCategories/Keybinds.cs | using ImproveGame.Common.Configs;
using ImproveGame.Common.ModSystems;
using ImproveGame.UI.ModernConfig.OptionElements;
namespace ImproveGame.UI.ModernConfig.FakeCategories;
public class Keybinds(string ModName) : Category()
{
public Keybinds() : this("ImproveGame") { }
public override int ItemIconId => ItemID.RainbowCursor;
public string ModName { get; } = ModName;
public override void AddOptions(ConfigOptionsPanel panel)
{
panel.ShouldHideSearchBar = true;
var uiConfig = UIConfigs.Instance;
bool hasKeybind = TryGetKeybindString(KeybindSystem.MasterControlKeybind, out _);
if (!hasKeybind)
panel.AddToOptionsDirect<OptionToggle>(uiConfig, nameof(uiConfig.FckKeybindPopup));
if (Language.ActiveCulture.Name == "zh-Hans")
{
panel.AddToOptionsDirect(new KeybindChineseToggle());
}
foreach (var modKeybind in KeybindLoader.Keybinds)
{
if (modKeybind.Mod.Name == ModName)
{
panel.AddToOptionsDirect(new OptionKeybind(modKeybind.FullName));
}
}
}
} | 0 | 0.751115 | 1 | 0.751115 | game-dev | MEDIA | 0.94246 | game-dev | 0.637556 | 1 | 0.637556 |
racenis/tram-sdk | 5,360 | libraries/bullet/BulletCollision/CollisionShapes/btStridingMeshInterface.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_STRIDING_MESHINTERFACE_H
#define BT_STRIDING_MESHINTERFACE_H
#include "LinearMath/btVector3.h"
#include "btTriangleCallback.h"
#include "btConcaveShape.h"
/// The btStridingMeshInterface is the interface class for high performance generic access to triangle meshes, used in combination with btBvhTriangleMeshShape and some other collision shapes.
/// Using index striding of 3*sizeof(integer) it can use triangle arrays, using index striding of 1*sizeof(integer) it can handle triangle strips.
/// It allows for sharing graphics and collision meshes. Also it provides locking/unlocking of graphics meshes that are in gpu memory.
ATTRIBUTE_ALIGNED16(class)
btStridingMeshInterface
{
protected:
btVector3 m_scaling;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btStridingMeshInterface() : m_scaling(btScalar(1.), btScalar(1.), btScalar(1.))
{
}
virtual ~btStridingMeshInterface();
virtual void InternalProcessAllTriangles(btInternalTriangleIndexCallback * callback, const btVector3& aabbMin, const btVector3& aabbMax) const;
///brute force method to calculate aabb
void calculateAabbBruteForce(btVector3 & aabbMin, btVector3 & aabbMax);
/// get read and write access to a subpart of a triangle mesh
/// this subpart has a continuous array of vertices and indices
/// in this way the mesh can be handled as chunks of memory with striding
/// very similar to OpenGL vertexarray support
/// make a call to unLockVertexBase when the read and write access is finished
virtual void getLockedVertexIndexBase(unsigned char** vertexbase, int& numverts, PHY_ScalarType& type, int& stride, unsigned char** indexbase, int& indexstride, int& numfaces, PHY_ScalarType& indicestype, int subpart = 0) = 0;
virtual void getLockedReadOnlyVertexIndexBase(const unsigned char** vertexbase, int& numverts, PHY_ScalarType& type, int& stride, const unsigned char** indexbase, int& indexstride, int& numfaces, PHY_ScalarType& indicestype, int subpart = 0) const = 0;
/// unLockVertexBase finishes the access to a subpart of the triangle mesh
/// make a call to unLockVertexBase when the read and write access (using getLockedVertexIndexBase) is finished
virtual void unLockVertexBase(int subpart) = 0;
virtual void unLockReadOnlyVertexBase(int subpart) const = 0;
/// getNumSubParts returns the number of separate subparts
/// each subpart has a continuous array of vertices and indices
virtual int getNumSubParts() const = 0;
virtual void preallocateVertices(int numverts) = 0;
virtual void preallocateIndices(int numindices) = 0;
virtual bool hasPremadeAabb() const { return false; }
virtual void setPremadeAabb(const btVector3& aabbMin, const btVector3& aabbMax) const
{
(void)aabbMin;
(void)aabbMax;
}
virtual void getPremadeAabb(btVector3 * aabbMin, btVector3 * aabbMax) const
{
(void)aabbMin;
(void)aabbMax;
}
const btVector3& getScaling() const
{
return m_scaling;
}
void setScaling(const btVector3& scaling)
{
m_scaling = scaling;
}
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const;
};
struct btIntIndexData
{
int m_value;
};
struct btShortIntIndexData
{
short m_value;
char m_pad[2];
};
struct btShortIntIndexTripletData
{
short m_values[3];
char m_pad[2];
};
struct btCharIndexTripletData
{
unsigned char m_values[3];
char m_pad;
};
// clang-format off
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btMeshPartData
{
btVector3FloatData *m_vertices3f;
btVector3DoubleData *m_vertices3d;
btIntIndexData *m_indices32;
btShortIntIndexTripletData *m_3indices16;
btCharIndexTripletData *m_3indices8;
btShortIntIndexData *m_indices16;//backwards compatibility
int m_numTriangles;//length of m_indices = m_numTriangles
int m_numVertices;
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btStridingMeshInterfaceData
{
btMeshPartData *m_meshPartsPtr;
btVector3FloatData m_scaling;
int m_numMeshParts;
char m_padding[4];
};
// clang-format on
SIMD_FORCE_INLINE int btStridingMeshInterface::calculateSerializeBufferSize() const
{
return sizeof(btStridingMeshInterfaceData);
}
#endif //BT_STRIDING_MESHINTERFACE_H
| 0 | 0.984539 | 1 | 0.984539 | game-dev | MEDIA | 0.952356 | game-dev | 0.892929 | 1 | 0.892929 |
spheredev/neosphere | 9,475 | assets/system/scripts/joysticks.js | ///////////////////////////////////////////////////////////
// A simple map engine joystick support script
// To use the following functions you must do:
// EvaluateSystemScript("joysticks.js");
//
// And make sure you do:
// SetUpdateScript("UpdateJoysticks()");
//
// And then to give input to the person called 'player':
// if (GetNumJoysticks() >= 1)
// AttachJoystick(0, "player");
//
// Note: If you do AttachInput("player") this will not work
//
// To give input to the next player, just make sure there's enough joysticks for that person too.
// For example:
//
// if (GetNumJoysticks() >= 2) {
// AttachJoystick(0, "player_one");
// AttachJoystick(1, "player_two");
// }
//
//
// BindJoystickButton(joystick, joystick_button, on_press_script, on_release_script)
// i.e.
// if (GetNumJoysticks() >= 1)
// BindJoystickButton(0, 1, "mode = 'in'", "mode = 'out'")
//
// Will call "mode = 'in'" every time joystick zero pressed button one
// And call "mode = 'out'" when joystick zero lets go of button one
//
// Final Note:
// I don't have a joystick, so don't lock me and others out of your games.
// Also thank you to WIP for testing this
//
// - Flik
///////////////////////////////////////////////////////////
var gPersonJoysticks = new Array();
var gBindedJoysticks = new Array();
///////////////////////////////////////////////////////////
function DoesPersonExist(person)
{
if (IsMapEngineRunning()) {
var person_list = GetPersonList();
for (var i = 0; i < person_list.length; ++i) {
if (person_list[i] == person) {
return true;
}
}
}
return false;
}
///////////////////////////////////////////////////////////
function GetNumJoystickPlayers() {
var num = 0;
for (var i = 0; i < gPersonJoysticks.length; i++) {
if (gPersonJoysticks[i].destroy == false) {
num += 1;
}
}
return num;
}
///////////////////////////////////////////////////////////
function IsJoystickAttached(joystick) {
if (joystick < 0 || joystick >= GetNumJoysticks())
{
Abort("Joystick " + joystick + " does not exist");
}
for (var i = 0; i < gPersonJoysticks.length; i++) {
if (gPersonJoysticks[i].joystick == joystick)
return (gPersonJoysticks[i].destroy == false);
}
return false;
}
///////////////////////////////////////////////////////////
function GetJoystickPerson(joystick) {
if (joystick < 0 || joystick >= GetNumJoysticks())
{
Abort("Joystick " + joystick + " does not exist");
}
for (var i = 0; i < gPersonJoysticks.length; i++) {
if (gPersonJoysticks[i].joystick == joystick)
return gPersonJoysticks[i].name;
}
Abort("Joystick " + joystick + " is not attached");
}
///////////////////////////////////////////////////////////
function BindJoystickButton(joystick, joystick_button, on_press_script, on_release_script) {
if (joystick < 0 || joystick >= GetNumJoysticks())
{
Abort("Joystick " + joystick + " does not exist");
}
if (joystick_button < 0 || joystick_button >= GetNumJoystickButtons(joystick)) {
Abort("Joystick button " + joystick_button + " does not exist");
}
var joystick_index = -1;
var joystick_found = false;
for (var i = 0; i < gBindedJoysticks.length; i++) {
if (gBindedJoysticks[i].joystick == joystick) {
joystick_index = i;
joystick_found = true;
break;
}
}
if (joystick_found == false) {
joystick_index = gBindedJoysticks.length;
var binded_joystick = new Object();
binded_joystick.joystick = joystick;
binded_joystick.buttons = new Array();
gBindedJoysticks.push(binded_joystick);
}
var button_found = false;
for (var k = 0; k < gBindedJoysticks[joystick_index].buttons.length; k++) {
if (gBindedJoysticks[joystick_index].buttons[k].name == joystick_button) {
gBindedJoysticks[joystick_index].buttons[k].on_press = new Function(on_press_script);
gBindedJoysticks[joystick_index].buttons[k].on_release = new Function(on_release_script);
gBindedJoysticks[joystick_index].buttons[k].destroy = false;
button_found = true;
break;
}
}
if (button_found == false) {
var binded_button = new Object();
binded_button.name = joystick_button;
binded_button.on_press = new Function(on_press_script);
binded_button.on_release = new Function(on_release_script);
binded_button.destroy = false;
gBindedJoysticks[joystick_index].buttons.push(binded_button);
}
}
///////////////////////////////////////////////////////////
function UnbindJoystickButton(joystick, joystick_button) {
if (joystick < 0 || joystick >= GetNumJoysticks())
{
Abort("Joystick " + joystick + " does not exist");
}
if (joystick_button < 0 || joystick_button >= GetNumJoystickButtons(joystick)) {
Abort("Joystick button " + joystick_button + " does not exist");
}
for (var i = 0; i < gBindedJoysticks.length; i++) {
if (gBindedJoysticks[i].joystick == joystick) {
joystick_index = i;
break;
}
}
for (var k = 0; k < gBindedJoysticks[joystick_index].buttons.length; k++) {
if (gBindedJoysticks[joystick_index].buttons[k].name == joystick_button) {
gBindedJoysticks[joystick_index].buttons[k].destroy = true;
break;
}
}
}
///////////////////////////////////////////////////////////
function AttachJoystick(joystick, name) {
if (joystick < 0 || joystick >= GetNumJoysticks())
{
Abort("Joystick " + joystick + " does not exist");
}
if (!DoesPersonExist(name)) {
Abort("Person " + name + " does not exist");
}
for (var i = 0; i < gPersonJoysticks.length; i++) {
if (gPersonJoysticks[i].name == name) {
gPersonJoysticks[i].joystick = joystick;
return true;
}
}
gPersonJoysticks[i] = new Object();
gPersonJoysticks[i].name = name;
gPersonJoysticks[i].joystick = joystick;
return true;
}
///////////////////////////////////////////////////////////
function DetachJoystick(joystick, name) {
if (joystick < 0 || joystick >= GetNumJoysticks()) {
Abort("Joystick " + joystick + " does not exist");
}
if (!DoesPersonExist(name)) {
Abort("Person " + name + " does not exist");
}
for (var i = 0; i < gPersonJoysticks.length; i++) {
if (gPersonJoysticks[i].name == name) {
gPersonJoysticks[i].destroy = true;
return true;
}
}
}
///////////////////////////////////////////////////////////
function UpdateJoysticks() {
UpdateBindedJoysticks();
UpdatePersonJoysticks();
for (var i = 0; i < gPersonJoysticks.length; i++) {
if (gPersonJoysticks[i].destroy) {
gPersonJoysticks.splice(i, 1);
i -= 1;
}
}
for (var j = 0; j < gBindedJoysticks.length; j++) {
for (var k = 0; k < gBindedJoysticks[j].buttons.length; k++) {
if (gBindedJoysticks[j].buttons[k].destroy) {
gBindedJoysticks[j].buttons.splice(k, 1);
k -= 1;
}
}
}
}
///////////////////////////////////////////////////////////
function UpdateBindedJoysticks() {
for (var j = 0; j < gBindedJoysticks.length; j++) {
for (var k = 0; k < gBindedJoysticks[j].buttons.length; k++) {
if (gBindedJoysticks[j].buttons[k].destroy)
continue;
if (IsJoystickButtonPressed(gBindedJoysticks[j].joystick, gBindedJoysticks[j].buttons[k].name)) {
if (gBindedJoysticks[j].buttons[k].pressed == false) {
gBindedJoysticks[j].buttons[k].pressed = true;
gBindedJoysticks[j].buttons[k].on_press();
}
}
else {
if (gBindedJoysticks[j].buttons[k].pressed) {
gBindedJoysticks[j].buttons[k].pressed = false;
gBindedJoysticks[j].buttons[k].on_release();
}
}
}
}
}
///////////////////////////////////////////////////////////
function UpdatePersonJoysticks()
{
for (var i = 0; i < gPersonJoysticks.length; i++) {
if (!gPersonJoysticks[i].destroy && gPersonJoysticks[i].joystick >= 0 && gPersonJoysticks[i].joystick < GetNumJoysticks())
{
var dx = GetJoystickAxis(gPersonJoysticks[i].joystick, JOYSTICK_AXIS_X);
var dy = GetJoystickAxis(gPersonJoysticks[i].joystick, JOYSTICK_AXIS_Y);
dx = Math.round(dx * 10) / 10;
dy = Math.round(dy * 10) / 10;
if (dy < 0) QueuePersonCommand(gPersonJoysticks[i].name, COMMAND_MOVE_NORTH, true);
if (dx > 0) QueuePersonCommand(gPersonJoysticks[i].name, COMMAND_MOVE_EAST, true);
if (dy > 0) QueuePersonCommand(gPersonJoysticks[i].name, COMMAND_MOVE_SOUTH, true);
if (dx < 0) QueuePersonCommand(gPersonJoysticks[i].name, COMMAND_MOVE_WEST, true);
// set the direction
var command = -1;
if (dx < 0) {
if (dy < 0) {
command = COMMAND_FACE_NORTHWEST;
} else if (dy > 0) {
command = COMMAND_FACE_SOUTHWEST;
} else {
command = COMMAND_FACE_WEST;
}
} else if (dx > 0) {
if (dy < 0) {
command = COMMAND_FACE_NORTHEAST;
} else if (dy > 0) {
command = COMMAND_FACE_SOUTHEAST;
} else {
command = COMMAND_FACE_EAST;
}
} else {
if (dy < 0) {
command = COMMAND_FACE_NORTH;
} else if (dy > 0) {
command = COMMAND_FACE_SOUTH;
}
}
if (command != -1)
QueuePersonCommand(gPersonJoysticks[i].name, command, false);
}
}
}
///////////////////////////////////////////////////////////
| 0 | 0.618527 | 1 | 0.618527 | game-dev | MEDIA | 0.961492 | game-dev | 0.704853 | 1 | 0.704853 |
tgstation/TerraGov-Marine-Corps | 8,610 | code/modules/clothing/modular_armor/attachments/cape.dm | #define HIGHLIGHT_VARIANTS "highlight_variants"
#define HOOD "hood"
/obj/item/armor_module/armor/cape
name = "\improper 6E Chameleon cape"
desc = "A chromatic cape to improve on the design of the 7E badge, this cape is capable of two colors, for all your fashion needs. It also is equipped with thermal insulators so it will double as a blanket. \n Interact with facepaint to color and change variant. Attaches onto a uniform. Activate it to toggle the hood."
icon_state = "cape"
slot = ATTACHMENT_SLOT_CAPE
attachment_layer = CAPE_LAYER
prefered_slot = SLOT_W_UNIFORM
greyscale_config = /datum/greyscale_config/cape
attach_features_flags = ATTACH_REMOVABLE|ATTACH_SAME_ICON|ATTACH_APPLY_ON_MOB|ATTACH_ACTIVATION|ATTACH_NO_HANDS
attach_delay = 0 SECONDS
detach_delay = 0 SECONDS
secondary_color = TRUE
attachments_by_slot = list(ATTACHMENT_SLOT_CAPE_HIGHLIGHT)
starting_attachments = list(/obj/item/armor_module/armor/cape_highlight)
attachments_allowed = list(
/obj/item/armor_module/armor/cape_highlight,
/obj/item/armor_module/armor/cape_highlight/kama,
)
colorable_allowed = PRESET_COLORS_ALLOWED|ICON_STATE_VARIANTS_ALLOWED
current_variant = "normal"
icon_state_variants = list(
"scarf round" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list("none"),
),
"scarf tied" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list("none"),
),
"scarf" = list(
HOOD = TRUE,
HIGHLIGHT_VARIANTS = list(
"scarf",
"none",
),
),
"striped" = list(
HOOD = TRUE,
HIGHLIGHT_VARIANTS = list("none"),
),
"geist" = list(
HOOD = TRUE,
HIGHLIGHT_VARIANTS = list("none"),
),
"ghille" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list("none"),
),
"ghille (left)" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list("none"),
),
"ghille (right)" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list("none"),
),
"ghille (alt)" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list("none"),
),
"drifter" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list("none"),
),
"normal" = list(
HOOD = TRUE,
HIGHLIGHT_VARIANTS = list(
"normal",
"normal (alt)",
"none",
),
),
"short" = list(
HOOD = TRUE,
HIGHLIGHT_VARIANTS = list(
"short",
"none",
),
),
"short (old)" = list(
HOOD = TRUE,
HIGHLIGHT_VARIANTS = list("none"),
),
"shredded" = list(
HOOD = TRUE,
HIGHLIGHT_VARIANTS = list(
"shredded",
"none",
),
),
"half" = list(
HOOD = TRUE,
HIGHLIGHT_VARIANTS = list(
"half",
"none",
),
),
"full" = list(
HOOD = TRUE,
HIGHLIGHT_VARIANTS = list(
"full",
"none",
),
),
"back" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list(
"back",
"none",
),
),
"cover" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list(
"cover",
"none",
),
),
"cover (alt)" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list(
"cover (alt)",
"none",
),
),
"shoal" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list(
"shoal",
"none",
),
),
"shoal (back)" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list(
"shoal (back)",
"none",
),
),
"shoal (alt)" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list(
"shoal (alt)",
"none",
),
),
"rapier (right)" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list(
"rapier (right)",
"none",
),
),
"rapier (left)" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list(
"rapier (left)",
"none",
),
),
)
///True if the hood is up, false if not.
var/hood = FALSE
/obj/item/armor_module/armor/cape/update_icon_state()
. = ..()
var/obj/item/armor_module/highlight = attachments_by_slot[ATTACHMENT_SLOT_CAPE_HIGHLIGHT]
if(hood)
icon_state = initial(icon_state) + "_[current_variant]_h"
worn_icon_state = initial(worn_icon_state) + "_[current_variant]_h"
else
icon_state = initial(icon_state) + "_[current_variant]"
worn_icon_state = initial(worn_icon_state) + "_[current_variant]"
highlight?.update_icon()
if(parent)
parent.update_clothing_icon()
/obj/item/armor_module/armor/cape/activate(mob/living/user)
. = ..()
hood = !hood
update_icon()
update_greyscale()
user.update_inv_w_uniform()
/obj/item/armor_module/armor/cape/color_item(obj/item/facepaint/paint, mob/user)
var/old_variant = current_variant
. = ..()
if(old_variant == current_variant)
return
if(parent)
UnregisterSignal(parent, COMSIG_ITEM_EQUIPPED)
icon_state_variants[current_variant][HOOD] ? ENABLE_BITFIELD(attach_features_flags, ATTACH_ACTIVATION) : DISABLE_BITFIELD(attach_features_flags, ATTACH_ACTIVATION)
if(CHECK_BITFIELD(attach_features_flags, ATTACH_ACTIVATION) && parent)
RegisterSignal(parent, COMSIG_ITEM_EQUIPPED, PROC_REF(handle_actions))
var/obj/item/armor_module/highlight = attachments_by_slot[ATTACHMENT_SLOT_CAPE_HIGHLIGHT]
if(!icon_state_variants[current_variant][HOOD])
hood = FALSE
highlight?.icon_state = initial(highlight.icon_state) + "_[highlight.current_variant]"
if(ishuman(parent?.loc))
LAZYREMOVE(actions_types, /datum/action/item_action/toggle)
var/datum/action/item_action/toggle/old_action = locate(/datum/action/item_action/toggle) in actions
old_action?.remove_action(user)
actions = null
if(!icon_state_variants[old_variant][HOOD] && icon_state_variants[current_variant][HOOD] && ishuman(parent?.loc))
LAZYADD(actions_types, /datum/action/item_action/toggle)
var/datum/action/item_action/toggle/new_action = new(src)
if(toggle_signal)
new_action.keybinding_signals = list(KEYBINDING_NORMAL = toggle_signal)
new_action.give_action(user)
highlight.current_variant = length(icon_state_variants[current_variant][HIGHLIGHT_VARIANTS]) ? icon_state_variants[current_variant][HIGHLIGHT_VARIANTS][1] : "none"
highlight.icon_state_variants = icon_state_variants[current_variant][HIGHLIGHT_VARIANTS]
ENABLE_BITFIELD(highlight.colorable_allowed, PRESET_COLORS_ALLOWED)
update_icon()
update_greyscale()
highlight.update_icon()
highlight.update_greyscale()
user.update_inv_w_uniform()
/obj/item/armor_module/armor/cape/kama
name = "\improper 6E Chameleon kama"
desc = "A chromatic kama to improve on the design of the 7E badge, this kama is capable of two colors, for all your fashion needs. Hanged from the belt, it serves to flourish the lower extremities. \n Interact with facepaint to color. Attaches onto a uniform."
slot = ATTACHMENT_SLOT_KAMA
attachment_layer = KAMA_LAYER
attach_features_flags = ATTACH_REMOVABLE|ATTACH_SAME_ICON|ATTACH_APPLY_ON_MOB|ATTACH_NO_HANDS
starting_attachments = list(/obj/item/armor_module/armor/cape_highlight/kama)
greyscale_config = /datum/greyscale_config/cape
icon_state_variants = list(
"kama" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list(
"kama",
),
),
"kilt" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list(
"kilt",
),
),
"kilt (alt)" = list(
HOOD = FALSE,
HIGHLIGHT_VARIANTS = list(
"kilt",
),
),
)
current_variant = "kama"
/obj/item/armor_module/armor/cape_highlight
name = "Cape Highlight"
desc = "A cape to improve on the design of the 7E badge, this cape is capable of six colors, for all your fashion needs. This variation of the cape functions more as a scarf. \n Interact with facepaint to color. Attaches onto a uniform. Activate it to toggle the hood."
icon_state = "highlight"
slot = ATTACHMENT_SLOT_CAPE_HIGHLIGHT
attach_features_flags = ATTACH_SAME_ICON|ATTACH_APPLY_ON_MOB|ATTACH_NO_HANDS
colorable_allowed = PRESET_COLORS_ALLOWED|ICON_STATE_VARIANTS_ALLOWED|COLOR_WHEEL_ALLOWED
greyscale_config = /datum/greyscale_config/cape_highlight
secondary_color = TRUE
greyscale_colors = VISOR_PALETTE_GOLD
item_map_variant_flags = NONE
colorable_colors = VISOR_PALETTES_LIST
current_variant = "none"
icon_state_variants = list(
"none",
"normal",
"normal (alt)",
)
/obj/item/armor_module/armor/cape_highlight/update_icon_state()
. = ..()
if(!parent)
return
var/obj/item/armor_module/armor/cape/cape_parent = parent
if(cape_parent.hood)
icon_state = initial(icon_state) + "_[current_variant]_h"
else
icon_state = initial(icon_state) + "_[current_variant]"
/obj/item/armor_module/armor/cape_highlight/handle_color(datum/source, mob/user, list/obj/item/secondaries)
if(current_variant == "none" && (length(icon_state_variants) == 1))
return
return ..()
/obj/item/armor_module/armor/cape_highlight/kama
greyscale_config = /datum/greyscale_config/cape_highlight
colorable_allowed = PRESET_COLORS_ALLOWED
current_variant = "kama"
icon_state_variants = list()
| 0 | 0.646041 | 1 | 0.646041 | game-dev | MEDIA | 0.974347 | game-dev | 0.571611 | 1 | 0.571611 |
FlameskyDexive/ETPlus | 2,757 | Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/HashHelpers.cs | using System;
namespace NativeCollection.UnsafeType
{
public static class HashHelpers
{
public const uint HashCollisionThreshold = 100;
// This is the maximum prime smaller than Array.MaxLength.
public const int MaxPrimeArrayLength = 0x7FFFFFC3;
public const int HashPrime = 101;
private static readonly int[] s_primes = new int[72]
{
3,
7,
11,
17,
23,
29,
37,
47,
59,
71,
89,
107,
131,
163,
197,
239,
293,
353,
431,
521,
631,
761,
919,
1103,
1327,
1597,
1931,
2333,
2801,
3371,
4049,
4861,
5839,
7013,
8419,
10103,
12143,
14591,
17519,
21023,
25229,
30293,
36353,
43627,
52361,
62851,
75431,
90523,
108631,
130363,
156437,
187751,
225307,
270371,
324449,
389357,
467237,
560689,
672827,
807403,
968897,
1162687,
1395263,
1674319,
2009191,
2411033,
2893249,
3471899,
4166287,
4999559,
5999471,
7199369
};
public static bool IsPrime(int candidate)
{
if ((candidate & 1) == 0)
return candidate == 2;
int num = (int) Math.Sqrt((double) candidate);
for (int index = 3; index <= num; index += 2)
{
if (candidate % index == 0)
return false;
}
return true;
}
public static int GetPrime(int min)
{
if (min < 0)
throw new ArgumentException("SR.Arg_HTCapacityOverflow");
foreach (int prime in HashHelpers.s_primes)
{
if (prime >= min)
return prime;
}
for (int candidate = min | 1; candidate < int.MaxValue; candidate += 2)
{
if (HashHelpers.IsPrime(candidate) && (candidate - 1) % 101 != 0)
return candidate;
}
return min;
}
public static int ExpandPrime(int oldSize)
{
int min = 2 * oldSize;
return (uint) min > 2147483587U && 2147483587 > oldSize ? 2147483587 : HashHelpers.GetPrime(min);
}
/// <summary>Returns approximate reciprocal of the divisor: ceil(2**64 / divisor).</summary>
/// <remarks>This should only be used on 64-bit.</remarks>
public static ulong GetFastModMultiplier(uint divisor) =>
ulong.MaxValue / divisor + 1;
}
}
| 0 | 0.89673 | 1 | 0.89673 | game-dev | MEDIA | 0.511666 | game-dev | 0.814062 | 1 | 0.814062 |
DanceManiac/Advanced-X-Ray-Public | 1,929 | SourcesAXR/xrGame/ai/monsters/telekinesis.h | #pragma once
#include "telekinetic_object.h"
#include "../../../xrphysics/PHUpdateObject.h"
class CTelekinesis : public CPHUpdateObject {
protected:
DEFINE_VECTOR(CTelekineticObject*,TELE_OBJECTS,TELE_OBJECTS_IT);
TELE_OBJECTS objects;
xr_vector<CObject*> m_nearest;
bool active;
public:
CTelekinesis ();
virtual ~CTelekinesis ();
// allocates relevant TelekineticObject
//
virtual CTelekineticObject* activate(CPhysicsShellHolder *obj, float strength, float height, u32 max_time_keep, bool rot = true);
//
void deactivate ();
//clear objects (does not call release, but call switch to TS_None)
void clear_deactivate ();
// clear
virtual void clear ();
virtual void clear_notrelevant ();
//
void deactivate (CPhysicsShellHolder *obj);
void remove_object (TELE_OBJECTS_IT it);
void remove_object (CPhysicsShellHolder *obj);
// 'target'
void fire_all (const Fvector &target);
// 'obj' 'target'
void fire (CPhysicsShellHolder *obj, const Fvector &target, float power);
// 'obj' 'target'
void fire_t (CPhysicsShellHolder *obj, const Fvector &target, float time);
//
bool is_active () {return active;}
//
bool is_active_object (CPhysicsShellHolder *obj);
// ( TS_Raise & TS_Keep)
u32 get_objects_count ();
// ()
u32 get_objects_total_count() {return objects.size();}
//
// a copy of the object!
CTelekineticObject get_object_by_index (u32 index) {VERIFY(objects.size() > index); return *objects[index];}
// shedule_Update
void schedule_update ();
// -
void remove_links (CObject *O);
protected:
virtual CTelekineticObject* alloc_tele_object(){return xr_new<CTelekineticObject>();}
private:
//
virtual void PhDataUpdate (float step);
virtual void PhTune (float step);
};
| 0 | 0.88652 | 1 | 0.88652 | game-dev | MEDIA | 0.956988 | game-dev | 0.69947 | 1 | 0.69947 |
AzyrGames/GodotProjectileEngine | 1,544 | addons/godot_projectile_engine/core/projectile_template/base/projectile_behaviors/direction/behaviors/projectile_direction_modify.gd | extends ProjectileBehaviorDirection
class_name ProjectileDirectionModify
@export var direction_modify_value : Vector2 = Vector2.RIGHT
# @export var direction_modify_strenght : float = 0.5
# @export var direction_normalize : bool = true
@export var direction_modify_method: DirectionModifyMethod = DirectionModifyMethod.ROTATION
## Requests required context _values
func _request_behavior_context() -> Array:
return []
func _request_persist_behavior_context() -> Array:
return []
## Processes direction behavior with random walk
func process_behavior(_value: Vector2, _component_context: Dictionary) -> Dictionary:
_direction_behavior_values.clear()
match direction_modify_method:
DirectionModifyMethod.ROTATION:
if direction_normalize:
_direction_behavior_values[
ProjectileEngine.DirectionModify.DIRECTION_ROTATION] = direction_modify_value.normalized().angle()
else:
_direction_behavior_values[
ProjectileEngine.DirectionModify.DIRECTION_ROTATION] = direction_modify_value.angle()
DirectionModifyMethod.ADDITION:
if direction_normalize:
_direction_behavior_values[
ProjectileEngine.DirectionModify.DIRECTION_ADDITION] = (direction_modify_value.normalized())
else:
_direction_behavior_values[
ProjectileEngine.DirectionModify.DIRECTION_ADDITION] = direction_modify_value
DirectionModifyMethod.OVERRIDE:
_direction_behavior_values[
ProjectileEngine.DirectionModify.DIRECTION_OVERWRITE] = direction_modify_value.normalized()
_:
pass
return _direction_behavior_values | 0 | 0.905755 | 1 | 0.905755 | game-dev | MEDIA | 0.538928 | game-dev | 0.723773 | 1 | 0.723773 |
magefree/mage | 2,227 | Mage.Sets/src/mage/cards/i/InvasionOfFiora.java | package mage.cards.i;
import mage.abilities.Ability;
import mage.abilities.Mode;
import mage.abilities.common.EntersBattlefieldTriggeredAbility;
import mage.abilities.common.SiegeAbility;
import mage.abilities.effects.common.DestroyAllEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.cards.m.MarchesaResoluteMonarch;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.SuperType;
import mage.filter.FilterPermanent;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.Predicates;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class InvasionOfFiora extends CardImpl {
private static final FilterPermanent filter = new FilterCreaturePermanent("legendary creatures");
private static final FilterPermanent filter2 = new FilterCreaturePermanent("nonlegendary creatures");
static {
filter.add(SuperType.LEGENDARY.getPredicate());
filter2.add(Predicates.not(SuperType.LEGENDARY.getPredicate()));
}
public InvasionOfFiora(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.BATTLE}, "{4}{B}{B}");
this.subtype.add(SubType.SIEGE);
this.setStartingDefense(4);
this.secondSideCardClazz = mage.cards.m.MarchesaResoluteMonarch.class;
// (As a Siege enters, choose an opponent to protect it. You and others can attack it. When it's defeated, exile it, then cast it transformed.)
this.addAbility(new SiegeAbility());
// When Invasion of Fiora enters the battlefield, choose one or both --
// * Destroy all legendary creatures.
Ability ability = new EntersBattlefieldTriggeredAbility(new DestroyAllEffect(filter));
ability.getModes().setMinModes(1);
ability.getModes().setMaxModes(2);
// * Destroy all nonlegendary creatures.
ability.addMode(new Mode(new DestroyAllEffect(filter2)));
this.addAbility(ability, MarchesaResoluteMonarch.makeWatcher());
}
private InvasionOfFiora(final InvasionOfFiora card) {
super(card);
}
@Override
public InvasionOfFiora copy() {
return new InvasionOfFiora(this);
}
}
| 0 | 0.963611 | 1 | 0.963611 | game-dev | MEDIA | 0.963668 | game-dev | 0.995585 | 1 | 0.995585 |
bates64/papermario-dx | 1,119 | src/world/area_kmr/kmr_00/main.c | #include "kmr_00.h"
EvtScript N(EVS_ExitWalk_kmr_02_1) = EVT_EXIT_WALK(60, kmr_00_ENTRY_0, "kmr_02", kmr_02_ENTRY_1);
EvtScript N(EVS_BindExitTriggers) = {
BindTrigger(Ref(N(EVS_ExitWalk_kmr_02_1)), TRIGGER_FLOOR_ABOVE, COLLIDER_deili1, 1, 0)
Return
End
};
EvtScript N(EVS_Main) = {
Set(GB_WorldLocation, LOCATION_GOOMBA_VILLAGE)
Call(SetSpriteShading, SHADING_NONE)
EVT_SETUP_CAMERA_NO_LEAD(0, 0, 0)
Set(GF_MAP_GoombaVillage, TRUE)
IfLt(GB_StoryProgress, STORY_CH0_MET_INNKEEPER)
Call(MakeNpcs, FALSE, Ref(N(DefaultNPCs)))
Call(ClearDefeatedEnemies)
EndIf
ExecWait(N(EVS_MakeEntities))
Exec(N(EVS_SetupMusic))
Exec(N(EVS_Scene_MarioRevived))
Switch(GB_StoryProgress)
CaseEq(STORY_INTRO)
Call(EnableModel, MODEL_ji_3, FALSE)
Exec(N(EVS_BindExitTriggers))
CaseGe(STORY_CH0_WAKE_UP)
Call(EnableModel, MODEL_ji_1, FALSE)
Call(EnableModel, MODEL_ji_2, FALSE)
Set(LVar0, Ref(N(EVS_BindExitTriggers)))
Exec(EnterWalk)
EndSwitch
Wait(1)
Return
End
};
| 0 | 0.983141 | 1 | 0.983141 | game-dev | MEDIA | 0.882912 | game-dev | 0.983671 | 1 | 0.983671 |
Goob-Station/Goob-Station | 4,365 | Content.Shared/Storage/EntitySystems/StoreOnCollideSystem.cs | // SPDX-FileCopyrightText: 2024 keronshb <54602815+keronshb@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Aviu00 <93730715+Aviu00@users.noreply.github.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Content.Shared.Lock;
using Content.Shared.Projectiles;
using Content.Shared.Storage.Components;
using Content.Shared.Whitelist;
using Robust.Shared.Network;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Events;
using Robust.Shared.Spawners;
using Robust.Shared.Timing;
namespace Content.Shared.Storage.EntitySystems;
internal sealed class StoreOnCollideSystem : EntitySystem
{
[Dependency] private readonly SharedEntityStorageSystem _storage = default!;
[Dependency] private readonly LockSystem _lock = default!;
[Dependency] private readonly EntityWhitelistSystem _whitelist = default!;
[Dependency] private readonly INetManager _netMan = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<StoreOnCollideComponent, StartCollideEvent>(OnCollide);
SubscribeLocalEvent<StoreOnCollideComponent, StorageAfterOpenEvent>(AfterOpen);
// TODO: Add support to stop colliding after throw, wands will need a WandComp
SubscribeLocalEvent<StoreOnCollideComponent, TimedDespawnEvent>(OnTimedDespawn); // Goobstation
SubscribeLocalEvent<StoreOnCollideComponent, LockToggledEvent>(OnLockToggle); // Goobstation
SubscribeLocalEvent<StoreOnCollideComponent, PhysicsSleepEvent>(OnSleep); // Goobstation
}
// Goobstation start
private void OnSleep(Entity<StoreOnCollideComponent> ent, ref PhysicsSleepEvent args)
{
var comp = ent.Comp;
if (comp is { DisableOnSleep: true, Disabled: false })
Disable(ent);
}
private void OnLockToggle(Entity<StoreOnCollideComponent> ent, ref LockToggledEvent args)
{
if (args.Locked)
return;
var comp = ent.Comp;
if (comp is { DisableWhenFirstOpened: true, Disabled: false })
Disable(ent);
}
private void OnTimedDespawn(Entity<StoreOnCollideComponent> ent, ref TimedDespawnEvent args)
{
_storage.OpenStorage(ent);
}
private void Disable(Entity<StoreOnCollideComponent> ent)
{
ent.Comp.Disabled = true;
Dirty(ent);
}
// Goobstation end
// We use Collide instead of Projectile to support different types of interactions
private void OnCollide(Entity<StoreOnCollideComponent> ent, ref StartCollideEvent args)
{
TryStoreTarget(ent, args.OtherEntity);
TryLockStorage(ent);
// Goobstation start
if (!TryComp(ent.Owner, out ProjectileComponent? projectile))
return;
ent.Comp.IgnoredEntity = projectile.Shooter;
projectile.IgnoreShooter = false;
Entity<ProjectileComponent, StoreOnCollideComponent> toDirty = (ent.Owner, projectile, ent.Comp);
Dirty(toDirty);
// Goobstation end
}
private void AfterOpen(Entity<StoreOnCollideComponent> ent, ref StorageAfterOpenEvent args)
{
var comp = ent.Comp;
if (comp is { DisableWhenFirstOpened: true, Disabled: false })
Disable(ent); // Goob edit
}
private void TryStoreTarget(Entity<StoreOnCollideComponent> ent, EntityUid target)
{
var storageEnt = ent.Owner;
var comp = ent.Comp;
if (_netMan.IsClient || _gameTiming.ApplyingState)
return;
if (target == comp.IgnoredEntity) // Goobstation
return;
if (ent.Comp.Disabled || storageEnt == target || Transform(target).Anchored || _storage.IsOpen(storageEnt) || _whitelist.IsWhitelistFail(comp.Whitelist, target))
return;
_storage.Insert(target, storageEnt);
}
private void TryLockStorage(Entity<StoreOnCollideComponent> ent)
{
var storageEnt = ent.Owner;
var comp = ent.Comp;
if (_netMan.IsClient || _gameTiming.ApplyingState)
return;
if (ent.Comp.Disabled)
return;
if (comp.LockOnCollide && !_lock.IsLocked(storageEnt))
_lock.Lock(storageEnt, storageEnt);
}
} | 0 | 0.86771 | 1 | 0.86771 | game-dev | MEDIA | 0.948096 | game-dev | 0.939141 | 1 | 0.939141 |
rm-controls/rm_controllers | 16,447 | rm_shooter_controllers/src/standard.cpp | /*******************************************************************************
* BSD 3-Clause License
*
* Copyright (c) 2021, Qiayuan Liao
* All rights reserved.
*
* 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.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 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.
*******************************************************************************/
//
// Created by huakang on 2021/1/18.
//
#include <rm_common/ros_utilities.h>
#include <string>
#include <pluginlib/class_list_macros.hpp>
#include "rm_shooter_controllers/standard.h"
namespace rm_shooter_controllers
{
bool Controller::init(hardware_interface::RobotHW* robot_hw, ros::NodeHandle& root_nh, ros::NodeHandle& controller_nh)
{
config_ = { .block_effort = getParam(controller_nh, "block_effort", 0.),
.block_speed = getParam(controller_nh, "block_speed", 0.),
.block_duration = getParam(controller_nh, "block_duration", 0.),
.block_overtime = getParam(controller_nh, "block_overtime", 0.),
.anti_block_angle = getParam(controller_nh, "anti_block_angle", 0.),
.anti_block_threshold = getParam(controller_nh, "anti_block_threshold", 0.),
.forward_push_threshold = getParam(controller_nh, "forward_push_threshold", 0.1),
.exit_push_threshold = getParam(controller_nh, "exit_push_threshold", 0.1),
.extra_wheel_speed = getParam(controller_nh, "extra_wheel_speed", 0.),
.wheel_speed_drop_threshold = getParam(controller_nh, "wheel_speed_drop_threshold", 10.),
.wheel_speed_raise_threshold = getParam(controller_nh, "wheel_speed_raise_threshold", 3.1) };
config_rt_buffer.initRT(config_);
push_per_rotation_ = getParam(controller_nh, "push_per_rotation", 0);
push_wheel_speed_threshold_ = getParam(controller_nh, "push_wheel_speed_threshold", 0.);
freq_threshold_ = getParam(controller_nh, "freq_threshold", 20.);
anti_friction_block_duty_cycle_ = getParam(controller_nh, "anti_friction_block_duty_cycle", 0.5);
anti_friction_block_vel_ = getParam(controller_nh, "anti_friction_block_vel", 810.0);
friction_block_effort_ = getParam(controller_nh, "friction_block_effort", 0.2);
friction_block_vel_ = getParam(controller_nh, "friction_block_vel", 1.0);
cmd_subscriber_ = controller_nh.subscribe<rm_msgs::ShootCmd>("command", 1, &Controller::commandCB, this);
local_heat_state_pub_.reset(new realtime_tools::RealtimePublisher<rm_msgs::LocalHeatState>(
controller_nh, "/local_heat_state/shooter_state", 10));
shoot_state_pub_.reset(new realtime_tools::RealtimePublisher<rm_msgs::ShootState>(controller_nh, "state", 10));
// Init dynamic reconfigure
d_srv_ = new dynamic_reconfigure::Server<rm_shooter_controllers::ShooterConfig>(controller_nh);
dynamic_reconfigure::Server<rm_shooter_controllers::ShooterConfig>::CallbackType cb = [this](auto&& PH1, auto&& PH2) {
reconfigCB(std::forward<decltype(PH1)>(PH1), std::forward<decltype(PH2)>(PH2));
};
d_srv_->setCallback(cb);
XmlRpc::XmlRpcValue friction;
double wheel_speed_offset;
double wheel_speed_direction;
effort_joint_interface_ = robot_hw->get<hardware_interface::EffortJointInterface>();
controller_nh.getParam("friction", friction);
for (const auto& its : friction)
{
std::vector<double> wheel_speed_offset_temp;
std::vector<double> wheel_speed_direction_temp;
std::vector<effort_controllers::JointVelocityController*> ctrl_frictions;
for (const auto& it : its.second)
{
ros::NodeHandle nh = ros::NodeHandle(controller_nh, "friction/" + its.first + "/" + it.first);
wheel_speed_offset_temp.push_back(nh.getParam("wheel_speed_offset", wheel_speed_offset) ? wheel_speed_offset : 0.);
wheel_speed_direction_temp.push_back(
nh.getParam("wheel_speed_direction", wheel_speed_direction) ? wheel_speed_direction : 1.);
effort_controllers::JointVelocityController* ctrl_friction = new effort_controllers::JointVelocityController;
if (ctrl_friction->init(effort_joint_interface_, nh))
ctrl_frictions.push_back(ctrl_friction);
else
return false;
}
ctrls_friction_.push_back(ctrl_frictions);
wheel_speed_offsets_.push_back(wheel_speed_offset_temp);
wheel_speed_directions_.push_back(wheel_speed_direction_temp);
}
lp_filter_ = new LowPassFilter(controller_nh);
ros::NodeHandle nh_trigger = ros::NodeHandle(controller_nh, "trigger");
return ctrl_trigger_.init(effort_joint_interface_, nh_trigger);
}
void Controller::starting(const ros::Time& /*time*/)
{
state_ = STOP;
state_changed_ = true;
}
void Controller::update(const ros::Time& time, const ros::Duration& period)
{
cmd_ = *cmd_rt_buffer_.readFromRT();
config_ = *config_rt_buffer.readFromRT();
if (state_ != cmd_.mode)
{
if (state_ != BLOCK)
if ((state_ != PUSH || cmd_.mode != READY) ||
(cmd_.mode == READY &&
(std::fmod(std::abs(ctrl_trigger_.command_struct_.position_ - ctrl_trigger_.getPosition()), 2. * M_PI) <
config_.exit_push_threshold ||
cmd_.hz >= freq_threshold_)))
{
if (state_ == STOP && cmd_.mode == READY)
enter_ready_ = true;
state_ = cmd_.mode;
state_changed_ = true;
}
}
if (state_ != STOP)
setSpeed(cmd_);
switch (state_)
{
case READY:
ready(period);
break;
case PUSH:
push(time, period);
break;
case STOP:
stop(time, period);
break;
case BLOCK:
block(time, period);
break;
}
judgeBulletShoot(time, period);
if (shoot_state_pub_->trylock())
{
shoot_state_pub_->msg_.stamp = time;
shoot_state_pub_->msg_.state = state_;
shoot_state_pub_->unlockAndPublish();
}
for (auto& ctrl_frictions : ctrls_friction_)
{
for (auto& ctrl_friction : ctrl_frictions)
{
ctrl_friction->update(time, period);
}
}
ctrl_trigger_.update(time, period);
}
void Controller::stop(const ros::Time& time, const ros::Duration& period)
{
if (state_changed_)
{ // on enter
state_changed_ = false;
ROS_INFO("[Shooter] Enter STOP");
for (auto& ctrl_frictions : ctrls_friction_)
{
for (auto& ctrl_friction : ctrl_frictions)
{
ctrl_friction->setCommand(0.);
}
}
ctrl_trigger_.setCommand(ctrl_trigger_.joint_.getPosition());
}
}
void Controller::ready(const ros::Duration& period)
{
if (state_changed_)
{ // on enter
state_changed_ = false;
ROS_INFO("[Shooter] Enter READY");
normalize();
}
}
void Controller::push(const ros::Time& time, const ros::Duration& period)
{
if (state_changed_)
{ // on enter
state_changed_ = false;
ROS_INFO("[Shooter] Enter PUSH");
}
bool wheel_speed_ready = true;
for (size_t i = 0; i < ctrls_friction_.size(); i++)
{
for (size_t j = 0; j < ctrls_friction_[i].size(); j++)
{
if (wheel_speed_directions_[i][j] * ctrls_friction_[i][j]->joint_.getVelocity() <
push_wheel_speed_threshold_ * ctrls_friction_[i][j]->command_ ||
wheel_speed_directions_[i][j] * ctrls_friction_[i][j]->joint_.getVelocity() <= M_PI)
wheel_speed_ready = false;
}
}
if ((cmd_.wheel_speed == 0. || wheel_speed_ready) && (time - last_shoot_time_).toSec() >= 1. / cmd_.hz)
{ // Time to shoot!!!
if (cmd_.hz >= freq_threshold_)
{
ctrl_trigger_.setCommand(ctrl_trigger_.command_struct_.position_ -
2. * M_PI / static_cast<double>(push_per_rotation_),
-1 * cmd_.hz * 2. * M_PI / static_cast<double>(push_per_rotation_));
last_shoot_time_ = time;
}
else if (std::fmod(std::abs(ctrl_trigger_.command_struct_.position_ - ctrl_trigger_.getPosition()), 2. * M_PI) <
config_.forward_push_threshold)
{
ctrl_trigger_.setCommand(ctrl_trigger_.command_struct_.position_ -
2. * M_PI / static_cast<double>(push_per_rotation_));
last_shoot_time_ = time;
}
// Check block
if ((ctrl_trigger_.joint_.getEffort() < -config_.block_effort &&
std::abs(ctrl_trigger_.joint_.getVelocity()) < config_.block_speed) ||
((time - last_shoot_time_).toSec() > 1 / cmd_.hz &&
std::abs(ctrl_trigger_.joint_.getVelocity()) < config_.block_speed))
{
if (!maybe_block_)
{
block_time_ = time;
maybe_block_ = true;
}
if ((time - block_time_).toSec() >= config_.block_duration)
{
state_ = BLOCK;
state_changed_ = true;
ROS_INFO("[Shooter] Exit PUSH");
}
}
else
maybe_block_ = false;
}
else
ROS_DEBUG("[Shooter] Wait for friction wheel");
}
void Controller::block(const ros::Time& time, const ros::Duration& period)
{
if (state_changed_)
{ // on enter
state_changed_ = false;
ROS_INFO("[Shooter] Trigger Enter BLOCK");
last_block_time_ = time;
ctrl_trigger_.setCommand(ctrl_trigger_.joint_.getPosition() + config_.anti_block_angle);
}
if (std::abs(ctrl_trigger_.command_struct_.position_ - ctrl_trigger_.joint_.getPosition()) <
config_.anti_block_threshold ||
(time - last_block_time_).toSec() > config_.block_overtime)
{
normalize();
state_ = PUSH;
state_changed_ = true;
ROS_INFO("[Shooter] Trigger Exit BLOCK");
}
}
void Controller::setSpeed(const rm_msgs::ShootCmd& cmd)
{
for (size_t i = 0; i < ctrls_friction_.size(); i++)
{
for (size_t j = 0; j < ctrls_friction_[i].size(); j++)
{
if (wheel_speed_directions_[i][j] * ctrls_friction_[i][j]->joint_.getVelocity() <= friction_block_vel_ &&
abs(ctrls_friction_[i][j]->joint_.getEffort()) >= friction_block_effort_ && cmd.wheel_speed != 0)
friction_wheel_block = true;
else
friction_wheel_block = false;
}
}
if (!friction_wheel_block)
{
if (last_friction_wheel_block)
{
ROS_INFO("[Shooter] Frictions Exit BLOCK");
last_friction_wheel_block = false;
}
for (size_t i = 0; i < ctrls_friction_.size(); i++)
{
for (size_t j = 0; j < ctrls_friction_[i].size(); j++)
{
// Used to distinguish the front and rear friction wheels.
if (j == 0)
ctrls_friction_[i][j]->setCommand(
wheel_speed_directions_[i][j] *
(cmd_.wheel_speed + config_.extra_wheel_speed + cmd_.wheels_speed_offset_back));
if (j == 1)
ctrls_friction_[i][j]->setCommand(
wheel_speed_directions_[i][j] *
(cmd_.wheel_speed + config_.extra_wheel_speed + cmd_.wheels_speed_offset_front));
}
}
}
else
{
ROS_INFO("[Shooter] Frictions Enter BLOCK");
last_friction_wheel_block = true;
double command = (friction_block_count <= static_cast<int>(anti_friction_block_duty_cycle_ * 1000)) ?
anti_friction_block_vel_ :
0.;
for (size_t i = 0; i < ctrls_friction_.size(); i++)
{
for (size_t j = 0; j < ctrls_friction_[i].size(); j++)
{
ctrls_friction_[i][j]->setCommand(command);
}
}
friction_block_count = (friction_block_count + 1) % 1000;
}
}
void Controller::normalize()
{
double push_angle = 2. * M_PI / static_cast<double>(push_per_rotation_);
if (cmd_.hz <= freq_threshold_)
{
ctrl_trigger_.setCommand(
push_angle * std::floor((ctrl_trigger_.joint_.getPosition() + 0.01 + config_.exit_push_threshold) / push_angle));
}
else if (enter_ready_)
{
ctrl_trigger_.setCommand(push_angle * std::floor((ctrl_trigger_.joint_.getPosition() + 0.01) / push_angle));
enter_ready_ = false;
}
else
ctrl_trigger_.setCommand(push_angle * std::floor((ctrl_trigger_.joint_.getPosition() - 0.01) / push_angle));
}
void Controller::judgeBulletShoot(const ros::Time& time, const ros::Duration& period)
{
lp_filter_->input(ctrls_friction_[0][0]->joint_.getVelocity());
double friction_speed = lp_filter_->output();
double friction_change_speed = abs(friction_speed) - last_fricition_speed_;
double friction_change_speed_derivative = friction_change_speed - last_friction_change_speed_;
if (state_ != STOP)
{
if (friction_change_speed_derivative > 0 && has_shoot_)
has_shoot_ = false;
if (friction_change_speed < -config_.wheel_speed_drop_threshold && !has_shoot_ &&
friction_change_speed_derivative < 0)
has_shoot_ = true;
}
last_fricition_speed_ = abs(friction_speed);
last_friction_change_speed_ = friction_change_speed;
if (local_heat_state_pub_->trylock())
{
local_heat_state_pub_->msg_.stamp = time;
local_heat_state_pub_->msg_.has_shoot = has_shoot_;
local_heat_state_pub_->msg_.friction_speed = friction_speed;
local_heat_state_pub_->msg_.friction_change_speed = friction_change_speed;
local_heat_state_pub_->msg_.friction_change_speed_derivative = friction_change_speed_derivative;
local_heat_state_pub_->unlockAndPublish();
}
}
void Controller::reconfigCB(rm_shooter_controllers::ShooterConfig& config, uint32_t /*level*/)
{
ROS_INFO("[Shooter] Dynamic params change");
if (!dynamic_reconfig_initialized_)
{
Config init_config = *config_rt_buffer.readFromNonRT(); // config init use yaml
config.block_effort = init_config.block_effort;
config.block_speed = init_config.block_speed;
config.block_duration = init_config.block_duration;
config.block_overtime = init_config.block_overtime;
config.anti_block_angle = init_config.anti_block_angle;
config.anti_block_threshold = init_config.anti_block_threshold;
config.forward_push_threshold = init_config.forward_push_threshold;
config.exit_push_threshold = init_config.exit_push_threshold;
config.extra_wheel_speed = init_config.extra_wheel_speed;
config.wheel_speed_drop_threshold = init_config.wheel_speed_drop_threshold;
config.wheel_speed_raise_threshold = init_config.wheel_speed_raise_threshold;
dynamic_reconfig_initialized_ = true;
}
Config config_non_rt{ .block_effort = config.block_effort,
.block_speed = config.block_speed,
.block_duration = config.block_duration,
.block_overtime = config.block_overtime,
.anti_block_angle = config.anti_block_angle,
.anti_block_threshold = config.anti_block_threshold,
.forward_push_threshold = config.forward_push_threshold,
.exit_push_threshold = config.exit_push_threshold,
.extra_wheel_speed = config.extra_wheel_speed,
.wheel_speed_drop_threshold = config.wheel_speed_drop_threshold,
.wheel_speed_raise_threshold = config.wheel_speed_raise_threshold };
config_rt_buffer.writeFromNonRT(config_non_rt);
}
} // namespace rm_shooter_controllers
PLUGINLIB_EXPORT_CLASS(rm_shooter_controllers::Controller, controller_interface::ControllerBase)
| 0 | 0.971063 | 1 | 0.971063 | game-dev | MEDIA | 0.36456 | game-dev | 0.875989 | 1 | 0.875989 |
bozimmerman/CoffeeMud | 5,312 | com/planet_ink/coffee_mud/Races/Deva.java | package com.planet_ink.coffee_mud.Races;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2016-2025 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Deva extends StdRace
{
@Override
public String ID()
{
return "Deva";
}
private final static String localizedStaticName = CMLib.lang().L("Deva");
@Override
public String name()
{
return localizedStaticName;
}
private final static String localizedStaticRacialCat = CMLib.lang().L("Celestial");
@Override
public String racialCategory()
{
return localizedStaticRacialCat;
}
@Override
public long forbiddenWornBits()
{
return Wearable.WORN_BACK;
}
private final String[] racialAbilityNames = { "WingFlying" };
private final int[] racialAbilityLevels = { 1 };
private final int[] racialAbilityProficiencies = { 100 };
private final boolean[] racialAbilityQuals = { false };
private final String[] racialAbilityParms = { "" };
@Override
public String[] racialAbilityNames()
{
return racialAbilityNames;
}
@Override
public int[] racialAbilityLevels()
{
return racialAbilityLevels;
}
@Override
public int[] racialAbilityProficiencies()
{
return racialAbilityProficiencies;
}
@Override
public boolean[] racialAbilityQuals()
{
return racialAbilityQuals;
}
@Override
public String[] racialAbilityParms()
{
return racialAbilityParms;
}
// an ey ea he ne ar ha to le fo no gi mo wa ta wi
private static final int[] parts={0 ,2 ,2 ,1 ,1 ,2 ,2 ,1 ,2 ,2 ,1 ,0 ,1 ,1 ,0 ,2 };
@Override
public int[] bodyMask()
{
return parts;
}
protected static Vector<RawMaterial> resources=new Vector<RawMaterial>();
@Override
public void affectCharStats(final MOB affectedMOB, final CharStats affectableStats)
{
super.affectCharStats(affectedMOB, affectableStats);
affectableStats.setStat(CharStats.STAT_SAVE_COLD, affectableStats.getStat(CharStats.STAT_SAVE_COLD)+20);
affectableStats.setStat(CharStats.STAT_SAVE_ELECTRIC, affectableStats.getStat(CharStats.STAT_SAVE_ELECTRIC)+20);
affectableStats.setStat(CharStats.STAT_SAVE_POISON, affectableStats.getStat(CharStats.STAT_SAVE_POISON)+20);
affectableStats.setStat(CharStats.STAT_SAVE_GAS, affectableStats.getStat(CharStats.STAT_SAVE_GAS)+20);
affectableStats.setStat(CharStats.STAT_SAVE_FIRE, affectableStats.getStat(CharStats.STAT_SAVE_FIRE)+10);
}
@Override
public void unaffectCharStats(final MOB affectedMOB, final CharStats affectableStats)
{
super.unaffectCharStats(affectedMOB, affectableStats);
affectableStats.setStat(CharStats.STAT_SAVE_COLD, affectableStats.getStat(CharStats.STAT_SAVE_COLD)-20);
affectableStats.setStat(CharStats.STAT_SAVE_ELECTRIC, affectableStats.getStat(CharStats.STAT_SAVE_ELECTRIC)-20);
affectableStats.setStat(CharStats.STAT_SAVE_POISON, affectableStats.getStat(CharStats.STAT_SAVE_POISON)-20);
affectableStats.setStat(CharStats.STAT_SAVE_GAS, affectableStats.getStat(CharStats.STAT_SAVE_GAS)-20);
affectableStats.setStat(CharStats.STAT_SAVE_FIRE, affectableStats.getStat(CharStats.STAT_SAVE_FIRE)-10);
}
@Override
public int lightestWeight()
{
return 250;
}
@Override
public int shortestMale()
{
return 90;
}
@Override
public int shortestFemale()
{
return 90;
}
@Override
public void affectPhyStats(final Physical affected, final PhyStats affectableStats)
{
super.affectPhyStats(affected,affectableStats);
affectableStats.setSensesMask(affectableStats.sensesMask()|PhyStats.CAN_SEE_DARK|PhyStats.CAN_SEE_EVIL);
}
@Override
public List<RawMaterial> myResources()
{
synchronized(resources)
{
if(resources.size()==0)
{
resources.addElement(makeResource
(L("some @x1 feathers",name().toLowerCase()),RawMaterial.RESOURCE_FEATHERS));
resources.addElement(makeResource
(L("some @x1 blood",name().toLowerCase()),RawMaterial.RESOURCE_BLOOD));
resources.addElement(makeResource
(L("a pile of @x1 bones",name().toLowerCase()),RawMaterial.RESOURCE_BONE));
}
}
return resources;
}
}
| 0 | 0.772527 | 1 | 0.772527 | game-dev | MEDIA | 0.731658 | game-dev | 0.603527 | 1 | 0.603527 |
CardboardPowered/cardboard | 6,890 | src/main/java/io/papermc/paper/datacomponent/item/PaperWrittenBookContent.java | package io.papermc.paper.datacomponent.item;
import com.google.common.base.Preconditions;
import io.papermc.paper.adventure.PaperAdventure;
import io.papermc.paper.text.Filtered;
import io.papermc.paper.util.MCUtil;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List;
import java.util.Optional;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.minecraft.text.RawFilteredPair;
import net.minecraft.util.JsonHelper;
import org.bukkit.craftbukkit.util.Handleable;
import org.jetbrains.annotations.Unmodifiable;
import static io.papermc.paper.adventure.PaperAdventure.asAdventure;
import static io.papermc.paper.adventure.PaperAdventure.asVanilla;
public record PaperWrittenBookContent(
net.minecraft.component.type.WrittenBookContentComponent impl
) implements WrittenBookContent, Handleable<net.minecraft.component.type.WrittenBookContentComponent> {
@Override
public net.minecraft.component.type.WrittenBookContentComponent getHandle() {
return this.impl;
}
@Override
public Filtered<String> title() {
return Filtered.of(this.impl.title().raw(), this.impl.title().filtered().orElse(null));
}
@Override
public String author() {
return this.impl.author();
}
@Override
public int generation() {
return this.impl.generation();
}
@Override
public @Unmodifiable List<Filtered<Component>> pages() {
return MCUtil.transformUnmodifiable(
this.impl.pages(),
page -> Filtered.of(asAdventure(page.raw()), page.filtered().map(PaperAdventure::asAdventure).orElse(null))
);
}
@Override
public boolean resolved() {
return this.impl.resolved();
}
static final class BuilderImpl implements WrittenBookContent.Builder {
private final List<RawFilteredPair<net.minecraft.text.Text>> pages = new ObjectArrayList<>();
private RawFilteredPair<String> title;
private String author;
private int generation = 0;
private boolean resolved = false;
BuilderImpl(final Filtered<String> title, final String author) {
validateTitle(title.raw());
if (title.filtered() != null) {
validateTitle(title.filtered());
}
this.title = new RawFilteredPair<>(title.raw(), Optional.ofNullable(title.filtered()));
this.author = author;
}
private static void validateTitle(final String title) {
Preconditions.checkArgument(
title.length() <= net.minecraft.component.type.WrittenBookContentComponent.MAX_TITLE_LENGTH,
"Title cannot be longer than %s, was %s",
net.minecraft.component.type.WrittenBookContentComponent.MAX_TITLE_LENGTH,
title.length()
);
}
private static void validatePageLength(final Component page) {
final String flagPage = JsonHelper.toSortedString(GsonComponentSerializer.gson().serializeToTree(page));
Preconditions.checkArgument(
flagPage.length() <= net.minecraft.component.type.WrittenBookContentComponent.MAX_SERIALIZED_PAGE_LENGTH,
"Cannot have page length more than %s, had %s",
net.minecraft.component.type.WrittenBookContentComponent.MAX_SERIALIZED_PAGE_LENGTH,
flagPage.length()
);
}
@Override
public WrittenBookContent.Builder title(final String title) {
validateTitle(title);
this.title = RawFilteredPair.of(title);
return this;
}
@Override
public WrittenBookContent.Builder filteredTitle(final Filtered<String> title) {
validateTitle(title.raw());
if (title.filtered() != null) {
validateTitle(title.filtered());
}
this.title = new RawFilteredPair<>(title.raw(), Optional.ofNullable(title.filtered()));
return this;
}
@Override
public WrittenBookContent.Builder author(final String author) {
this.author = author;
return this;
}
@Override
public WrittenBookContent.Builder generation(final int generation) {
Preconditions.checkArgument(
generation >= 0 && generation <= net.minecraft.component.type.WrittenBookContentComponent.MAX_GENERATION,
"generation must be between %s and %s, was %s",
0, net.minecraft.component.type.WrittenBookContentComponent.MAX_GENERATION,
generation
);
this.generation = generation;
return this;
}
@Override
public WrittenBookContent.Builder resolved(final boolean resolved) {
this.resolved = resolved;
return this;
}
@Override
public WrittenBookContent.Builder addPage(final ComponentLike page) {
final Component component = page.asComponent();
validatePageLength(component);
this.pages.add(RawFilteredPair.of(asVanilla(component)));
return this;
}
@Override
public WrittenBookContent.Builder addPages(final List<? extends ComponentLike> pages) {
for (final ComponentLike page : pages) {
final Component component = page.asComponent();
validatePageLength(component);
this.pages.add(RawFilteredPair.of(asVanilla(component)));
}
return this;
}
@Override
public WrittenBookContent.Builder addFilteredPage(final Filtered<? extends ComponentLike> page) {
final Component raw = page.raw().asComponent();
validatePageLength(raw);
Component filtered = null;
if (page.filtered() != null) {
filtered = page.filtered().asComponent();
validatePageLength(filtered);
}
this.pages.add(new RawFilteredPair<>(asVanilla(raw), Optional.ofNullable(filtered).map(PaperAdventure::asVanilla)));
return this;
}
@Override
public WrittenBookContent.Builder addFilteredPages(final List<Filtered<? extends ComponentLike>> pages) {
pages.forEach(this::addFilteredPage);
return this;
}
@Override
public WrittenBookContent build() {
return new PaperWrittenBookContent(new net.minecraft.component.type.WrittenBookContentComponent(
this.title,
this.author,
this.generation,
new ObjectArrayList<>(this.pages),
this.resolved
));
}
}
}
| 0 | 0.86543 | 1 | 0.86543 | game-dev | MEDIA | 0.826752 | game-dev | 0.928044 | 1 | 0.928044 |
ss14Starlight/space-station-14 | 15,837 | Content.IntegrationTests/Tests/VendingMachineRestockTest.cs | #nullable enable
using System.Collections.Generic;
using Content.Server.VendingMachines;
using Content.Server.Wires;
using Content.Shared.Cargo.Prototypes;
using Content.Shared.Damage;
using Content.Shared.Damage.Prototypes;
using Content.Shared.Prototypes;
using Content.Shared.Starlight.Antags.Abductor;
using Content.Shared.Storage.Components;
using Content.Shared.VendingMachines;
using Content.Shared.Wires;
using Robust.Shared.GameObjects;
using Robust.Shared.Map;
using Robust.Shared.Prototypes;
namespace Content.IntegrationTests.Tests
{
[TestFixture]
[TestOf(typeof(VendingMachineRestockComponent))]
[TestOf(typeof(VendingMachineSystem))]
public sealed class VendingMachineRestockTest : EntitySystem
{
private static readonly ProtoId<DamageTypePrototype> TestDamageType = "Blunt";
[TestPrototypes]
private const string Prototypes = @"
- type: entity
name: HumanVendingDummy
id: HumanVendingDummy
components:
- type: Hands
- type: ComplexInteraction
- type: Body
prototype: Human
- type: entity
parent: FoodSnackBase
id: TestRamen
name: TestRamen
- type: vendingMachineInventory
id: TestInventory
startingInventory:
TestRamen: 1
- type: vendingMachineInventory
id: OtherTestInventory
startingInventory:
TestRamen: 3
- type: vendingMachineInventory
id: BigTestInventory
startingInventory:
TestRamen: 4
- type: entity
parent: BaseVendingMachineRestock
id: TestRestockWrong
name: TestRestockWrong
components:
- type: VendingMachineRestock
canRestock:
- OtherTestInventory
- type: entity
parent: BaseVendingMachineRestock
id: TestRestockCorrect
name: TestRestockCorrect
components:
- type: VendingMachineRestock
canRestock:
- TestInventory
- type: entity
parent: BaseVendingMachineRestock
id: TestRestockExplode
name: TestRestockExplode
components:
- type: Damageable
damageContainer: Inorganic
damageModifierSet: Metallic
- type: Destructible
thresholds:
- trigger:
!type:DamageTrigger
damage: 20
behaviors:
- !type:DumpRestockInventory
- !type:DoActsBehavior
acts: [ 'Destruction' ]
- type: VendingMachineRestock
canRestock:
- BigTestInventory
- type: entity
parent: VendingMachine
id: VendingMachineTest
name: Test Ramen
components:
- type: Wires
layoutId: Vending
- type: VendingMachine
pack: TestInventory
- type: Sprite
sprite: error.rsi
";
[Test]
public async Task TestAllRestocksAreAvailableToBuy()
{
await using var pair = await PoolManager.GetServerClient();
var server = pair.Server;
await server.WaitIdleAsync();
var prototypeManager = server.ResolveDependency<IPrototypeManager>();
var compFact = server.ResolveDependency<IComponentFactory>();
await server.WaitAssertion(() =>
{
HashSet<string> restocks = new();
Dictionary<string, List<string>> restockStores = new();
// Collect all the prototypes with restock components.
foreach (var proto in prototypeManager.EnumeratePrototypes<EntityPrototype>())
{
if (proto.Abstract
|| pair.IsTestPrototype(proto)
|| !proto.HasComponent<VendingMachineRestockComponent>())
{
continue;
}
restocks.Add(proto.ID);
}
// Starlight start
foreach (var listing in prototypeManager.EnumeratePrototypes<AbductorListingPrototype>())
{
// Ignore any prototypes that are listed as abductor listings instead
restocks.Remove(listing.ProductEntity);
}
// Starlight end
// Collect all the prototypes with StorageFills referencing those entities.
foreach (var proto in prototypeManager.EnumeratePrototypes<EntityPrototype>())
{
if (!proto.TryGetComponent<StorageFillComponent>(out var storage, compFact))
continue;
List<string> restockStore = new();
foreach (var spawnEntry in storage.Contents)
{
if (spawnEntry.PrototypeId != null && restocks.Contains(spawnEntry.PrototypeId))
restockStore.Add(spawnEntry.PrototypeId);
}
if (restockStore.Count > 0)
restockStores.Add(proto.ID, restockStore);
}
// Iterate through every CargoProduct and make sure each
// prototype with a restock component is referenced in a
// purchaseable entity with a StorageFill.
foreach (var proto in prototypeManager.EnumeratePrototypes<CargoProductPrototype>())
{
if (restockStores.ContainsKey(proto.Product))
{
foreach (var entry in restockStores[proto.Product])
restocks.Remove(entry);
restockStores.Remove(proto.Product);
}
}
Assert.Multiple(() =>
{
Assert.That(restockStores, Has.Count.EqualTo(0),
$"Some entities containing entities with VendingMachineRestock components are unavailable for purchase: \n - {string.Join("\n - ", restockStores.Keys)}");
Assert.That(restocks, Has.Count.EqualTo(0),
$"Some entities with VendingMachineRestock components are unavailable for purchase: \n - {string.Join("\n - ", restocks)}");
});
});
await pair.CleanReturnAsync();
}
[Test]
public async Task TestCompleteRestockProcess()
{
await using var pair = await PoolManager.GetServerClient();
var server = pair.Server;
await server.WaitIdleAsync();
var entityManager = server.ResolveDependency<IEntityManager>();
var entitySystemManager = server.ResolveDependency<IEntitySystemManager>();
var mapSystem = server.System<SharedMapSystem>();
EntityUid packageRight;
EntityUid packageWrong;
EntityUid machine;
EntityUid user;
VendingMachineComponent machineComponent = default!;
VendingMachineRestockComponent restockRightComponent = default!;
VendingMachineRestockComponent restockWrongComponent = default!;
WiresPanelComponent machineWiresPanel = default!;
var testMap = await pair.CreateTestMap();
await server.WaitAssertion(() =>
{
var coordinates = testMap.GridCoords;
// Spawn the entities.
user = entityManager.SpawnEntity("HumanVendingDummy", coordinates);
machine = entityManager.SpawnEntity("VendingMachineTest", coordinates);
packageRight = entityManager.SpawnEntity("TestRestockCorrect", coordinates);
packageWrong = entityManager.SpawnEntity("TestRestockWrong", coordinates);
// Sanity test for components existing.
Assert.Multiple(() =>
{
Assert.That(entityManager.TryGetComponent(machine, out machineComponent!), $"Machine has no {nameof(VendingMachineComponent)}");
Assert.That(entityManager.TryGetComponent(packageRight, out restockRightComponent!), $"Correct package has no {nameof(VendingMachineRestockComponent)}");
Assert.That(entityManager.TryGetComponent(packageWrong, out restockWrongComponent!), $"Wrong package has no {nameof(VendingMachineRestockComponent)}");
Assert.That(entityManager.TryGetComponent(machine, out machineWiresPanel!), $"Machine has no {nameof(WiresPanelComponent)}");
});
var systemMachine = entitySystemManager.GetEntitySystem<VendingMachineSystem>();
// Test that the panel needs to be opened first.
Assert.Multiple(() =>
{
Assert.That(systemMachine.TryAccessMachine(packageRight, restockRightComponent, machineComponent, user, machine), Is.False, "Right package is able to restock without opened access panel");
Assert.That(systemMachine.TryAccessMachine(packageWrong, restockWrongComponent, machineComponent, user, machine), Is.False, "Wrong package is able to restock without opened access panel");
});
var systemWires = entitySystemManager.GetEntitySystem<WiresSystem>();
// Open the panel.
systemWires.TogglePanel(machine, machineWiresPanel, true);
Assert.Multiple(() =>
{
// Test that the right package works for the right machine.
Assert.That(systemMachine.TryAccessMachine(packageRight, restockRightComponent, machineComponent, user, machine), Is.True, "Correct package is unable to restock with access panel opened");
// Test that the wrong package does not work.
Assert.That(systemMachine.TryMatchPackageToMachine(packageWrong, restockWrongComponent, machineComponent, user, machine), Is.False, "Package with invalid canRestock is able to restock machine");
// Test that the right package does work.
Assert.That(systemMachine.TryMatchPackageToMachine(packageRight, restockRightComponent, machineComponent, user, machine), Is.True, "Package with valid canRestock is unable to restock machine");
// Make sure there's something in there to begin with.
Assert.That(systemMachine.GetAvailableInventory(machine, machineComponent), Has.Count.GreaterThan(0),
"Machine inventory is empty before emptying.");
});
// Empty the inventory.
systemMachine.EjectRandom(machine, false, true, machineComponent);
Assert.That(systemMachine.GetAvailableInventory(machine, machineComponent), Has.Count.EqualTo(0),
"Machine inventory is not empty after ejecting.");
// Test that the inventory is actually restocked.
systemMachine.TryRestockInventory(machine, machineComponent);
Assert.That(systemMachine.GetAvailableInventory(machine, machineComponent), Has.Count.GreaterThan(0),
"Machine available inventory count is not greater than zero after restock.");
mapSystem.DeleteMap(testMap.MapId);
});
await pair.CleanReturnAsync();
}
[Test]
public async Task TestRestockBreaksOpen()
{
await using var pair = await PoolManager.GetServerClient();
var server = pair.Server;
await server.WaitIdleAsync();
var prototypeManager = server.ResolveDependency<IPrototypeManager>();
var entityManager = server.ResolveDependency<IEntityManager>();
var entitySystemManager = server.ResolveDependency<IEntitySystemManager>();
var mapSystem = server.System<SharedMapSystem>();
var damageableSystem = entitySystemManager.GetEntitySystem<DamageableSystem>();
var testMap = await pair.CreateTestMap();
EntityUid restock = default;
await server.WaitAssertion(() =>
{
var coordinates = testMap.GridCoords;
var totalStartingRamen = 0;
foreach (var meta in entityManager.EntityQuery<MetaDataComponent>())
if (!meta.Deleted && meta.EntityPrototype?.ID == "TestRamen")
totalStartingRamen++;
Assert.That(totalStartingRamen, Is.EqualTo(0),
"Did not start with zero ramen.");
restock = entityManager.SpawnEntity("TestRestockExplode", coordinates);
var damageSpec = new DamageSpecifier(prototypeManager.Index(TestDamageType), 100);
var damageResult = damageableSystem.TryChangeDamage(restock, damageSpec);
#pragma warning disable NUnit2045
Assert.That(damageResult, Is.Not.Null,
"Received null damageResult when attempting to damage restock box.");
Assert.That((int) damageResult!.GetTotal(), Is.GreaterThan(0),
"Box damage result was not greater than 0.");
#pragma warning restore NUnit2045
});
await server.WaitRunTicks(15);
await server.WaitAssertion(() =>
{
Assert.That(entityManager.Deleted(restock),
"Restock box was not deleted after being damaged.");
var totalRamen = 0;
foreach (var meta in entityManager.EntityQuery<MetaDataComponent>())
if (!meta.Deleted && meta.EntityPrototype?.ID == "TestRamen")
totalRamen++;
Assert.That(totalRamen, Is.EqualTo(2),
"Did not find enough ramen after destroying restock box.");
mapSystem.DeleteMap(testMap.MapId);
});
await pair.CleanReturnAsync();
}
[Test]
public async Task TestRestockInventoryBounds()
{
await using var pair = await PoolManager.GetServerClient();
var server = pair.Server;
await server.WaitIdleAsync();
var mapManager = server.ResolveDependency<IMapManager>();
var entityManager = server.ResolveDependency<IEntityManager>();
var entitySystemManager = server.ResolveDependency<IEntitySystemManager>();
var vendingMachineSystem = entitySystemManager.GetEntitySystem<SharedVendingMachineSystem>();
var testMap = await pair.CreateTestMap();
await server.WaitAssertion(() =>
{
var coordinates = testMap.GridCoords;
var machine = entityManager.SpawnEntity("VendingMachineTest", coordinates);
Assert.That(vendingMachineSystem.GetAvailableInventory(machine), Has.Count.EqualTo(1),
"Machine's available inventory did not contain one entry.");
Assert.That(vendingMachineSystem.GetAvailableInventory(machine)[0].Amount, Is.EqualTo(1),
"Machine's available inventory is not the expected amount.");
vendingMachineSystem.RestockInventoryFromPrototype(machine);
Assert.That(vendingMachineSystem.GetAvailableInventory(machine)[0].Amount, Is.EqualTo(2),
"Machine's available inventory is not double its starting amount after a restock.");
vendingMachineSystem.RestockInventoryFromPrototype(machine);
Assert.That(vendingMachineSystem.GetAvailableInventory(machine)[0].Amount, Is.EqualTo(3),
"Machine's available inventory is not triple its starting amount after two restocks.");
vendingMachineSystem.RestockInventoryFromPrototype(machine);
Assert.That(vendingMachineSystem.GetAvailableInventory(machine)[0].Amount, Is.EqualTo(3),
"Machine's available inventory did not stay the same after a third restock.");
});
await pair.CleanReturnAsync();
}
}
}
#nullable disable
| 0 | 0.923464 | 1 | 0.923464 | game-dev | MEDIA | 0.860779 | game-dev,testing-qa | 0.855621 | 1 | 0.855621 |
Interkarma/daggerfall-unity | 10,167 | Assets/Scripts/Game/UserInterfaceWindows/DaggerfallWitchesCovenPopupWindow.cs | // Project: Daggerfall Unity
// Copyright: Copyright (C) 2009-2023 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Hazelnut
// Contributors:
//
// Notes:
// This is only for witch covens currently, but may be generalised if similarly handled NPCs are found.
using UnityEngine;
using DaggerfallWorkshop.Utility;
using DaggerfallWorkshop.Game.UserInterface;
using DaggerfallWorkshop.Game.Questing;
using DaggerfallConnect.Arena2;
namespace DaggerfallWorkshop.Game.UserInterfaceWindows
{
public class DaggerfallWitchesCovenPopupWindow : DaggerfallQuestPopupWindow
{
#region UI Rects
protected Rect talkButtonRect = new Rect(5, 5, 120, 7);
protected Rect summonButtonRect = new Rect(5, 14, 120, 7);
protected Rect questButtonRect = new Rect(5, 23, 120, 7);
protected Rect exitButtonRect = new Rect(44, 33, 43, 15);
#endregion
#region UI Controls
protected Panel mainPanel = new Panel();
protected Button talkButton = new Button();
protected Button summonButton = new Button();
protected Button questButton = new Button();
protected Button exitButton = new Button();
#endregion
#region Fields
const string baseTextureName = "DAED00I0.IMG"; // Talk / Daedra Summoning / Quest
Texture2D baseTexture;
StaticNPC witchNPC;
bool isCloseWindowDeferred = false;
bool isTalkWindowDeferred = false;
bool isSummonDeferred = false;
bool isGetQuestDeferred = false;
#endregion
#region Constructors
public DaggerfallWitchesCovenPopupWindow(IUserInterfaceManager uiManager, StaticNPC npc)
: base(uiManager)
{
witchNPC = npc;
// Clear background
ParentPanel.BackgroundColor = Color.clear;
}
#endregion
#region Setup Methods
protected override void Setup()
{
// Load all textures
LoadTextures();
// Create interface panel
mainPanel.HorizontalAlignment = HorizontalAlignment.Center;
mainPanel.VerticalAlignment = VerticalAlignment.Middle;
mainPanel.BackgroundTexture = baseTexture;
mainPanel.Position = new Vector2(0, 50);
mainPanel.Size = new Vector2(130, 51);
// Talk button
talkButton = DaggerfallUI.AddButton(talkButtonRect, mainPanel);
talkButton.OnMouseClick += TalkButton_OnMouseClick;
talkButton.Hotkey = DaggerfallShortcut.GetBinding(DaggerfallShortcut.Buttons.WitchesTalk);
talkButton.OnKeyboardEvent += TalkButton_OnKeyboardEvent;
// Summon button
summonButton = DaggerfallUI.AddButton(summonButtonRect, mainPanel);
summonButton.OnMouseClick += SummonButton_OnMouseClick;
summonButton.Hotkey = DaggerfallShortcut.GetBinding(DaggerfallShortcut.Buttons.WitchesDaedraSummon);
summonButton.OnKeyboardEvent += SummonButton_OnKeyboardEvent;
// Quest button
questButton = DaggerfallUI.AddButton(questButtonRect, mainPanel);
questButton.OnMouseClick += QuestButton_OnMouseClick;
questButton.Hotkey = DaggerfallShortcut.GetBinding(DaggerfallShortcut.Buttons.WitchesQuest);
questButton.OnKeyboardEvent += QuestButton_OnKeyboardEvent;
// Exit button
exitButton = DaggerfallUI.AddButton(exitButtonRect, mainPanel);
exitButton.OnMouseClick += ExitButton_OnMouseClick;
exitButton.Hotkey = DaggerfallShortcut.GetBinding(DaggerfallShortcut.Buttons.WitchesExit);
exitButton.OnKeyboardEvent += ExitButton_OnKeyboardEvent;
NativePanel.Components.Add(mainPanel);
}
#endregion
#region Private Methods
void LoadTextures()
{
baseTexture = ImageReader.GetTexture(baseTextureName);
}
#endregion
#region Quest handling
protected override void GetQuest()
{
// Just exit if this NPC already involved in an active quest
// If quest conditions are complete the quest system should pickup ending
if (QuestMachine.Instance.IsLastNPCClickedAnActiveQuestor())
{
CloseWindow();
return;
}
// Get the faction id for affecting reputation on success/failure, and current rep
int factionId = witchNPC.Data.factionID;
int reputation = GameManager.Instance.PlayerEntity.FactionData.GetReputation(factionId);
int level = GameManager.Instance.PlayerEntity.Level; // Not a proper guild so rank = player level
// Select a quest at random from appropriate pool
offeredQuest = GameManager.Instance.QuestListsManager.GetGuildQuest(FactionFile.GuildGroups.Witches, MembershipStatus.Nonmember, factionId, reputation, level);
if (offeredQuest != null)
{
// Log offered quest
Debug.LogFormat("Offering quest {0} from Guild {1} affecting factionId {2}", offeredQuest.QuestName, FactionFile.GuildGroups.Witches, offeredQuest.FactionId);
// Offer the quest to player
DaggerfallMessageBox messageBox = QuestMachine.Instance.CreateMessagePrompt(offeredQuest, (int)QuestMachine.QuestMessages.QuestorOffer);// TODO - need to provide an mcp for macros
if (messageBox != null)
{
messageBox.OnButtonClick += OfferQuest_OnButtonClick;
messageBox.Show();
}
}
else
{
ShowFailGetQuestMessage();
}
}
#endregion
#region Event Handlers
private void TalkButton_OnMouseClick(BaseScreenComponent sender, Vector2 position)
{
DaggerfallUI.Instance.PlayOneShot(SoundClips.ButtonClick);
CloseWindow();
GameManager.Instance.TalkManager.TalkToStaticNPC(witchNPC);
}
void TalkButton_OnKeyboardEvent(BaseScreenComponent sender, Event keyboardEvent)
{
if (keyboardEvent.type == EventType.KeyDown)
{
DaggerfallUI.Instance.PlayOneShot(SoundClips.ButtonClick);
isTalkWindowDeferred = true;
}
else if (keyboardEvent.type == EventType.KeyUp && isTalkWindowDeferred)
{
isTalkWindowDeferred = false;
CloseWindow();
GameManager.Instance.TalkManager.TalkToStaticNPC(witchNPC);
}
}
private void SummonButton_OnMouseClick(BaseScreenComponent sender, Vector2 position)
{
DaggerfallUI.Instance.PlayOneShot(SoundClips.ButtonClick);
DaedraSummoningService(witchNPC.Data.factionID);
}
void SummonButton_OnKeyboardEvent(BaseScreenComponent sender, Event keyboardEvent)
{
if (keyboardEvent.type == EventType.KeyDown)
{
DaggerfallUI.Instance.PlayOneShot(SoundClips.ButtonClick);
isSummonDeferred = true;
}
else if (keyboardEvent.type == EventType.KeyUp && isSummonDeferred)
{
isSummonDeferred = false;
DaedraSummoningService(witchNPC.Data.factionID);
}
}
private void QuestButton_OnMouseClick(BaseScreenComponent sender, Vector2 position)
{
DaggerfallUI.Instance.PlayOneShot(SoundClips.ButtonClick);
GetQuest();
}
void QuestButton_OnKeyboardEvent(BaseScreenComponent sender, Event keyboardEvent)
{
if (keyboardEvent.type == EventType.KeyDown)
{
DaggerfallUI.Instance.PlayOneShot(SoundClips.ButtonClick);
isGetQuestDeferred = true;
}
else if (keyboardEvent.type == EventType.KeyUp && isGetQuestDeferred)
{
isGetQuestDeferred = false;
GetQuest();
}
}
private void ExitButton_OnMouseClick(BaseScreenComponent sender, Vector2 position)
{
DaggerfallUI.Instance.PlayOneShot(SoundClips.ButtonClick);
CloseWindow();
}
protected void ExitButton_OnKeyboardEvent(BaseScreenComponent sender, Event keyboardEvent)
{
if (keyboardEvent.type == EventType.KeyDown)
{
DaggerfallUI.Instance.PlayOneShot(SoundClips.ButtonClick);
isCloseWindowDeferred = true;
}
else if (keyboardEvent.type == EventType.KeyUp && isCloseWindowDeferred)
{
isCloseWindowDeferred = false;
CloseWindow();
}
}
#endregion
#region Macro handling
public override MacroDataSource GetMacroDataSource()
{
return new WitchCovenMacroDataSource(this);
}
/// <summary>
/// MacroDataSource context sensitive methods for guild services window.
/// </summary>
private class WitchCovenMacroDataSource : MacroDataSource
{
private DaggerfallWitchesCovenPopupWindow parent;
public WitchCovenMacroDataSource(DaggerfallWitchesCovenPopupWindow witchCovenWindow)
{
this.parent = witchCovenWindow;
}
public override string Daedra()
{
FactionFile.FactionData factionData;
if (GameManager.Instance.PlayerEntity.FactionData.GetFactionData(parent.daedraToSummon.factionId, out factionData))
return factionData.name;
else
return "%dae[error]";
}
}
#endregion
}
} | 0 | 0.923573 | 1 | 0.923573 | game-dev | MEDIA | 0.955052 | game-dev | 0.849109 | 1 | 0.849109 |
ReactiveDrop/reactivedrop_public_src | 65,313 | src/game/server/hl2/prop_combine_ball.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: combine ball - can be held by the super physcannon and launched
// by the AR2's alt-fire
//
//=============================================================================//
#include "cbase.h"
#include "prop_combine_ball.h"
#include "props.h"
#include "explode.h"
#include "saverestore_utlvector.h"
#include "materialsystem/imaterial.h"
#include "beam_flags.h"
#include "physics_prop_ragdoll.h"
#include "soundent.h"
#include "soundenvelope.h"
#include "te_effect_dispatch.h"
#include "ai_basenpc.h"
#include "npc_bullseye.h"
#include "filters.h"
#include "SpriteTrail.h"
#include "decals.h"
#include "eventqueue.h"
#include "physics_collisionevent.h"
#include "gamestats.h"
#include "asw_shareddefs.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define PROP_COMBINE_BALL_MODEL "models/effects/combineball.mdl"
#define PROP_COMBINE_BALL_SPRITE_TRAIL "sprites/combineball_trail_black_1.vmt"
#define PROP_COMBINE_BALL_LIFETIME 4.0f // Seconds
#define PROP_COMBINE_BALL_HOLD_DISSOLVE_TIME 8.0f
#define SF_COMBINE_BALL_BOUNCING_IN_SPAWNER 0x10000
#define MAX_COMBINEBALL_RADIUS 12
ConVar sk_npc_dmg_combineball( "sk_npc_dmg_combineball", "45", FCVAR_CHEAT );
ConVar sk_combineball_guidefactor( "sk_combineball_guidefactor", "1.0", FCVAR_CHEAT );
ConVar sk_combine_ball_search_radius( "sk_combine_ball_search_radius", "512", FCVAR_CHEAT );
ConVar sk_combineball_seek_angle( "sk_combineball_seek_angle", "15", FCVAR_CHEAT );
ConVar sk_combineball_seek_kill( "sk_combineball_seek_kill", "0", FCVAR_CHEAT );
ConVar rd_combine_ball_first_hit_bonus( "rd_combine_ball_first_hit_bonus", "10", FCVAR_CHEAT );
// For our ring explosion
int s_nExplosionTexture = -1;
//-----------------------------------------------------------------------------
// Context think
//-----------------------------------------------------------------------------
static const char *s_pWhizThinkContext = "WhizThinkContext";
static const char *s_pHoldDissolveContext = "HoldDissolveContext";
static const char *s_pExplodeTimerContext = "ExplodeTimerContext";
static const char *s_pAnimThinkContext = "AnimThinkContext";
static const char *s_pCaptureContext = "CaptureContext";
static const char *s_pRemoveContext = "RemoveContext";
//-----------------------------------------------------------------------------
// Purpose:
// Input : radius -
// Output : CBaseEntity
//-----------------------------------------------------------------------------
CBaseEntity *CreateCombineBall( const Vector &origin, const Vector &velocity, float radius, float mass, float lifetime, CBaseEntity *pOwner, CBaseCombatWeapon *pWeapon )
{
CPropCombineBall *pBall = static_cast<CPropCombineBall*>( CreateEntityByName( "prop_combine_ball" ) );
pBall->SetRadius( radius );
pBall->SetAbsOrigin( origin );
pBall->SetOwnerEntity( pOwner );
pBall->SetOriginalOwner( pOwner );
pBall->SetAbsVelocity( velocity );
pBall->Spawn();
pBall->SetState( CPropCombineBall::STATE_THROWN );
pBall->SetSpeed( velocity.Length() );
pBall->EmitSound( "NPC_CombineBall.Launch" );
PhysSetGameFlags( pBall->VPhysicsGetObject(), FVPHYSICS_WAS_THROWN );
pBall->StartWhizSoundThink();
pBall->SetMass( mass );
pBall->StartLifetime( lifetime );
pBall->SetWeaponLaunched( true );
pBall->m_hWeapon = pWeapon;
return pBall;
}
//-----------------------------------------------------------------------------
// Purpose: Allows game to know if the physics object should kill allies or not
//-----------------------------------------------------------------------------
CBasePlayer *CPropCombineBall::HasPhysicsAttacker( float dt )
{
// Must have an owner
if ( GetOwnerEntity() == NULL )
return NULL;
// Must be a player
if ( GetOwnerEntity()->IsPlayer() == false )
return NULL;
// We don't care about the time passed in
return static_cast<CBasePlayer *>(GetOwnerEntity());
}
//-----------------------------------------------------------------------------
// Purpose: Determines whether a physics object is a combine ball or not
// Input : *pObj - Object to test
// Output : Returns true on success, false on failure.
// Notes : This function cannot identify a combine ball that is held by
// the physcannon because any object held by the physcannon is
// COLLISIONGROUP_DEBRIS.
//-----------------------------------------------------------------------------
bool UTIL_IsCombineBall( CBaseEntity *pEntity )
{
// Must be the correct collision group
if ( pEntity->GetCollisionGroup() != HL2COLLISION_GROUP_COMBINE_BALL )
return false;
//NOTENOTE: This allows ANY combine ball to pass the test
/*
CPropCombineBall *pBall = dynamic_cast<CPropCombineBall *>(pEntity);
if ( pBall && pBall->WasWeaponLaunched() )
return false;
*/
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Determines whether a physics object is an AR2 combine ball or not
// Input : *pEntity -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool UTIL_IsAR2CombineBall( CBaseEntity *pEntity )
{
// Must be the correct collision group
if ( pEntity->GetCollisionGroup() != HL2COLLISION_GROUP_COMBINE_BALL )
return false;
CPropCombineBall *pBall = dynamic_cast<CPropCombineBall *>(pEntity);
if ( pBall && pBall->WasWeaponLaunched() )
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Uses a deeper casting check to determine if pEntity is a combine
// ball. This function exists because the normal (much faster) check
// in UTIL_IsCombineBall() can never identify a combine ball held by
// the physcannon because the physcannon changes the held entity's
// collision group.
// Input : *pEntity - Entity to check
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool UTIL_IsCombineBallDefinite( CBaseEntity *pEntity )
{
CPropCombineBall *pBall = dynamic_cast<CPropCombineBall *>(pEntity);
return pBall != NULL;
}
//-----------------------------------------------------------------------------
//
// Spawns combine balls
//
//-----------------------------------------------------------------------------
#define SF_SPAWNER_START_DISABLED 0x1000
#define SF_SPAWNER_POWER_SUPPLY 0x2000
//-----------------------------------------------------------------------------
// Implementation of CPropCombineBall
//-----------------------------------------------------------------------------
LINK_ENTITY_TO_CLASS( prop_combine_ball, CPropCombineBall );
//-----------------------------------------------------------------------------
// Save/load:
//-----------------------------------------------------------------------------
BEGIN_DATADESC( CPropCombineBall )
DEFINE_FIELD( m_flLastBounceTime, FIELD_TIME ),
DEFINE_FIELD( m_flRadius, FIELD_FLOAT ),
DEFINE_FIELD( m_nState, FIELD_CHARACTER ),
DEFINE_FIELD( m_pGlowTrail, FIELD_CLASSPTR ),
DEFINE_SOUNDPATCH( m_pHoldingSound ),
DEFINE_FIELD( m_bFiredGrabbedOutput, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bEmit, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bHeld, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bLaunched, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bStruckEntity, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bWeaponLaunched, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bForward, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flSpeed, FIELD_FLOAT ),
DEFINE_FIELD( m_flNextDamageTime, FIELD_TIME ),
DEFINE_FIELD( m_flLastCaptureTime, FIELD_TIME ),
DEFINE_FIELD( m_bCaptureInProgress, FIELD_BOOLEAN ),
DEFINE_FIELD( m_nBounceCount, FIELD_INTEGER ),
DEFINE_FIELD( m_nMaxBounces, FIELD_INTEGER ),
DEFINE_FIELD( m_bBounceDie, FIELD_BOOLEAN ),
DEFINE_FIELD( m_hSpawner, FIELD_EHANDLE ),
DEFINE_FIELD( m_hWeapon, FIELD_EHANDLE ),
DEFINE_THINKFUNC( ExplodeThink ),
DEFINE_THINKFUNC( WhizSoundThink ),
DEFINE_THINKFUNC( DieThink ),
DEFINE_THINKFUNC( DissolveThink ),
DEFINE_THINKFUNC( DissolveRampSoundThink ),
DEFINE_THINKFUNC( AnimThink ),
DEFINE_THINKFUNC( CaptureBySpawner ),
DEFINE_INPUTFUNC( FIELD_VOID, "Explode", InputExplode ),
DEFINE_INPUTFUNC( FIELD_VOID, "FadeAndRespawn", InputFadeAndRespawn ),
DEFINE_INPUTFUNC( FIELD_VOID, "Kill", InputKill ),
DEFINE_INPUTFUNC( FIELD_VOID, "Socketed", InputSocketed ),
END_DATADESC()
IMPLEMENT_SERVERCLASS_ST( CPropCombineBall, DT_PropCombineBall )
SendPropBool( SENDINFO( m_bEmit ) ),
SendPropFloat( SENDINFO( m_flRadius ), 0, SPROP_NOSCALE ),
SendPropBool( SENDINFO( m_bHeld ) ),
SendPropBool( SENDINFO( m_bLaunched ) ),
END_SEND_TABLE()
//-----------------------------------------------------------------------------
// Gets at the spawner
//-----------------------------------------------------------------------------
CFuncCombineBallSpawner *CPropCombineBall::GetSpawner()
{
return m_hSpawner;
}
//-----------------------------------------------------------------------------
// Precache
//-----------------------------------------------------------------------------
void CPropCombineBall::Precache( void )
{
//NOTENOTE: We don't call into the base class because it chains multiple
// precaches we don't need to incur
PrecacheModel( PROP_COMBINE_BALL_MODEL );
PrecacheModel( PROP_COMBINE_BALL_SPRITE_TRAIL );
PrecacheEffect( "cball_bounce" );
PrecacheEffect( "cball_explode" );
s_nExplosionTexture = PrecacheModel( "sprites/lgtning.vmt" );
PrecacheScriptSound( "NPC_CombineBall.Launch" );
PrecacheScriptSound( "NPC_CombineBall.KillImpact" );
if ( hl2_episodic.GetBool() )
{
PrecacheScriptSound( "NPC_CombineBall_Episodic.Explosion" );
PrecacheScriptSound( "NPC_CombineBall_Episodic.WhizFlyby" );
PrecacheScriptSound( "NPC_CombineBall_Episodic.Impact" );
}
else
{
PrecacheScriptSound( "NPC_CombineBall.Explosion" );
PrecacheScriptSound( "NPC_CombineBall.WhizFlyby" );
PrecacheScriptSound( "NPC_CombineBall.Impact" );
}
PrecacheScriptSound( "NPC_CombineBall.HoldingInPhysCannon" );
}
//-----------------------------------------------------------------------------
// Spherical vphysics
//-----------------------------------------------------------------------------
bool CPropCombineBall::OverridePropdata()
{
return true;
}
//-----------------------------------------------------------------------------
// Spherical vphysics
//-----------------------------------------------------------------------------
void CPropCombineBall::SetState( int state )
{
if ( m_nState != state )
{
if ( m_nState == STATE_NOT_THROWN )
{
m_flLastCaptureTime = gpGlobals->curtime;
}
m_nState = state;
}
}
bool CPropCombineBall::IsInField() const
{
return (m_nState == STATE_NOT_THROWN);
}
//-----------------------------------------------------------------------------
// Sets the radius
//-----------------------------------------------------------------------------
void CPropCombineBall::SetRadius( float flRadius )
{
m_flRadius = clamp( flRadius, 1, MAX_COMBINEBALL_RADIUS );
}
//-----------------------------------------------------------------------------
// Create vphysics
//-----------------------------------------------------------------------------
bool CPropCombineBall::CreateVPhysics()
{
SetSolid( SOLID_BBOX );
float flSize = m_flRadius;
SetCollisionBounds( Vector(-flSize, -flSize, -flSize), Vector(flSize, flSize, flSize) );
objectparams_t params = g_PhysDefaultObjectParams;
params.pGameData = static_cast<void *>(this);
int nMaterialIndex = physprops->GetSurfaceIndex("metal_bouncy");
IPhysicsObject *pPhysicsObject = physenv->CreateSphereObject( flSize, nMaterialIndex, GetAbsOrigin(), GetAbsAngles(), ¶ms, false );
if ( !pPhysicsObject )
return false;
VPhysicsSetObject( pPhysicsObject );
SetMoveType( MOVETYPE_VPHYSICS );
pPhysicsObject->Wake();
pPhysicsObject->SetMass( 750.0f );
pPhysicsObject->EnableGravity( false );
pPhysicsObject->EnableDrag( false );
float flDamping = 0.0f;
float flAngDamping = 0.5f;
pPhysicsObject->SetDamping( &flDamping, &flAngDamping );
pPhysicsObject->SetInertia( Vector( 1e30, 1e30, 1e30 ) );
#ifndef INFESTED_DLL
if( WasFiredByNPC() )
{
// Don't do impact damage. Just touch them and do your dissolve damage and move on.
PhysSetGameFlags( pPhysicsObject, FVPHYSICS_NO_NPC_IMPACT_DMG );
}
else
#endif
{
PhysSetGameFlags( pPhysicsObject, FVPHYSICS_DMG_DISSOLVE | FVPHYSICS_HEAVY_OBJECT );
}
return true;
}
//-----------------------------------------------------------------------------
// Spawn:
//-----------------------------------------------------------------------------
void CPropCombineBall::Spawn( void )
{
BaseClass::Spawn();
SetModel( PROP_COMBINE_BALL_MODEL );
#ifndef INFESTED_DLL
if( ShouldHitPlayer() )
{
// This allows the combine ball to hit the player.
SetCollisionGroup( HL2COLLISION_GROUP_COMBINE_BALL_NPC );
}
else
#endif
{
SetCollisionGroup( HL2COLLISION_GROUP_COMBINE_BALL );
}
CreateVPhysics();
Vector vecAbsVelocity = GetAbsVelocity();
VPhysicsGetObject()->SetVelocity( &vecAbsVelocity, NULL );
m_nState = STATE_NOT_THROWN;
m_flLastBounceTime = -1.0f;
m_bFiredGrabbedOutput = false;
m_bForward = true;
m_bCaptureInProgress = false;
// No shadow!
AddEffects( EF_NOSHADOW );
// Start up the eye trail
m_pGlowTrail = CSpriteTrail::SpriteTrailCreate( PROP_COMBINE_BALL_SPRITE_TRAIL, GetAbsOrigin(), false );
if ( m_pGlowTrail != NULL )
{
m_pGlowTrail->FollowEntity( this );
m_pGlowTrail->SetTransparency( kRenderTransAdd, 0, 0, 0, 255, kRenderFxNone );
m_pGlowTrail->SetStartWidth( m_flRadius );
m_pGlowTrail->SetEndWidth( 0 );
m_pGlowTrail->SetLifeTime( 0.1f );
m_pGlowTrail->TurnOff();
}
m_bEmit = true;
m_bHeld = false;
m_bLaunched = false;
m_bStruckEntity = false;
m_bWeaponLaunched = false;
m_flNextDamageTime = gpGlobals->curtime;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropCombineBall::StartAnimating( void )
{
// Start our animation cycle. Use the random to avoid everything thinking the same frame
SetContextThink( &CPropCombineBall::AnimThink, gpGlobals->curtime + random->RandomFloat( 0.0f, 0.1f), s_pAnimThinkContext );
int nSequence = LookupSequence( "idle" );
SetCycle( 0 );
m_flAnimTime = gpGlobals->curtime;
ResetSequence( nSequence );
ResetClientsideFrame();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropCombineBall::StopAnimating( void )
{
SetContextThink( NULL, gpGlobals->curtime, s_pAnimThinkContext );
}
//-----------------------------------------------------------------------------
// Put it into the spawner
//-----------------------------------------------------------------------------
void CPropCombineBall::CaptureBySpawner( )
{
m_bCaptureInProgress = true;
m_bFiredGrabbedOutput = false;
// Slow down the ball
Vector vecVelocity;
VPhysicsGetObject()->GetVelocity( &vecVelocity, NULL );
float flSpeed = VectorNormalize( vecVelocity );
if ( flSpeed > 25.0f )
{
vecVelocity *= flSpeed * 0.4f;
VPhysicsGetObject()->SetVelocity( &vecVelocity, NULL );
// Slow it down until we can set its velocity ok
SetContextThink( &CPropCombineBall::CaptureBySpawner, gpGlobals->curtime + 0.01f, s_pCaptureContext );
return;
}
// Ok, we're captured
SetContextThink( NULL, gpGlobals->curtime, s_pCaptureContext );
ReplaceInSpawner( GetSpawner()->GetBallSpeed() );
m_bCaptureInProgress = false;
}
//-----------------------------------------------------------------------------
// Put it into the spawner
//-----------------------------------------------------------------------------
void CPropCombineBall::ReplaceInSpawner( float flSpeed )
{
m_bForward = true;
m_nState = STATE_NOT_THROWN;
// Prevent it from exploding
ClearLifetime( );
// Stop whiz noises
SetContextThink( NULL, gpGlobals->curtime, s_pWhizThinkContext );
// Slam velocity to what the field wants
Vector vecTarget, vecVelocity;
GetSpawner()->GetTargetEndpoint( m_bForward, &vecTarget );
VectorSubtract( vecTarget, GetAbsOrigin(), vecVelocity );
VectorNormalize( vecVelocity );
vecVelocity *= flSpeed;
VPhysicsGetObject()->SetVelocity( &vecVelocity, NULL );
// Set our desired speed to the spawner's speed. This will be
// our speed on our first bounce in the field.
SetSpeed( flSpeed );
}
float CPropCombineBall::LastCaptureTime() const
{
if ( IsInField() || IsBeingCaptured() )
return gpGlobals->curtime;
return m_flLastCaptureTime;
}
//-----------------------------------------------------------------------------
// Purpose: Starts the lifetime countdown on the ball
// Input : flDuration - number of seconds to live before exploding
//-----------------------------------------------------------------------------
void CPropCombineBall::StartLifetime( float flDuration )
{
SetContextThink( &CPropCombineBall::ExplodeThink, gpGlobals->curtime + flDuration, s_pExplodeTimerContext );
}
//-----------------------------------------------------------------------------
// Purpose: Stops the lifetime on the ball from expiring
//-----------------------------------------------------------------------------
void CPropCombineBall::ClearLifetime( void )
{
// Prevent it from exploding
SetContextThink( NULL, gpGlobals->curtime, s_pExplodeTimerContext );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : mass -
//-----------------------------------------------------------------------------
void CPropCombineBall::SetMass( float mass )
{
IPhysicsObject *pObj = VPhysicsGetObject();
if ( pObj != NULL )
{
pObj->SetMass( mass );
pObj->SetInertia( Vector( 500, 500, 500 ) );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CPropCombineBall::ShouldHitPlayer() const
{
#ifndef INFESTED_DLL
if ( GetOwnerEntity() )
{
CAI_BaseNPC *pNPC = GetOwnerEntity()->MyNPCPointer();
if ( pNPC && !pNPC->IsPlayerAlly() )
{
return true;
}
}
#endif
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropCombineBall::InputKill( inputdata_t &inputdata )
{
// tell owner ( if any ) that we're dead.This is mostly for NPCMaker functionality.
CBaseEntity *pOwner = GetOwnerEntity();
if ( pOwner )
{
pOwner->DeathNotice( this );
SetOwnerEntity( NULL );
}
UTIL_Remove( this );
NotifySpawnerOfRemoval();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropCombineBall::InputSocketed( inputdata_t &inputdata )
{
// tell owner ( if any ) that we're dead.This is mostly for NPCMaker functionality.
CBaseEntity *pOwner = GetOwnerEntity();
if ( pOwner )
{
pOwner->DeathNotice( this );
SetOwnerEntity( NULL );
}
#ifdef HL2_DLL
// if our owner is a player, tell them we were socketed
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player *>( pOwner );
if ( pPlayer )
{
pPlayer->CombineBallSocketed( this );
}
#endif
UTIL_Remove( this );
NotifySpawnerOfRemoval();
}
//-----------------------------------------------------------------------------
// Cleanup.
//-----------------------------------------------------------------------------
void CPropCombineBall::UpdateOnRemove()
{
if ( m_pGlowTrail != NULL )
{
UTIL_Remove( m_pGlowTrail );
m_pGlowTrail = NULL;
}
//Sigh... this is the only place where I can get a message after the ball is done dissolving.
if ( hl2_episodic.GetBool() )
{
if ( IsDissolving() )
{
if ( GetSpawner() )
{
GetSpawner()->BallGrabbed( this );
NotifySpawnerOfRemoval();
}
}
}
BaseClass::UpdateOnRemove();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropCombineBall::ExplodeThink( void )
{
DoExplosion();
}
//-----------------------------------------------------------------------------
// Purpose: Tell the respawner to make a new one
//-----------------------------------------------------------------------------
void CPropCombineBall::NotifySpawnerOfRemoval( void )
{
if ( GetSpawner() )
{
GetSpawner()->RespawnBallPostExplosion();
}
}
//-----------------------------------------------------------------------------
// Fade out.
//-----------------------------------------------------------------------------
void CPropCombineBall::DieThink()
{
if ( GetSpawner() )
{
//Let the spawner know we died so it does it's thing
if( hl2_episodic.GetBool() && IsInField() )
{
GetSpawner()->BallGrabbed( this );
}
GetSpawner()->RespawnBall( 0.1 );
}
UTIL_Remove( this );
}
//-----------------------------------------------------------------------------
// Fade out.
//-----------------------------------------------------------------------------
void CPropCombineBall::FadeOut( float flDuration )
{
AddSolidFlags( FSOLID_NOT_SOLID );
// Start up the eye trail
if ( m_pGlowTrail != NULL )
{
m_pGlowTrail->SetBrightness( 0, flDuration );
}
SetThink( &CPropCombineBall::DieThink );
SetNextThink( gpGlobals->curtime + flDuration );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropCombineBall::StartWhizSoundThink( void )
{
SetContextThink( &CPropCombineBall::WhizSoundThink, gpGlobals->curtime + 2.0f * TICK_INTERVAL, s_pWhizThinkContext );
}
//-----------------------------------------------------------------------------
// Danger sounds.
//-----------------------------------------------------------------------------
void CPropCombineBall::WhizSoundThink()
{
Vector vecPosition, vecVelocity;
IPhysicsObject *pPhysicsObject = VPhysicsGetObject();
if ( pPhysicsObject == NULL )
{
//NOTENOTE: We should always have been created at this point
Assert( 0 );
SetContextThink( &CPropCombineBall::WhizSoundThink, gpGlobals->curtime + 2.0f * TICK_INTERVAL, s_pWhizThinkContext );
return;
}
pPhysicsObject->GetPosition( &vecPosition, NULL );
pPhysicsObject->GetVelocity( &vecVelocity, NULL );
bool bFoundAny = false;
for ( int i = 1; i <= gpGlobals->maxClients; i++ )
{
CBasePlayer *pPlayer = UTIL_PlayerByIndex( i );
if ( pPlayer )
{
Vector vecDelta;
VectorSubtract( pPlayer->EarPosition(), vecPosition, vecDelta );
VectorNormalize( vecDelta );
if ( DotProduct( vecDelta, vecVelocity ) > 0.5f )
{
Vector vecEndPoint;
VectorMA( vecPosition, 2.0f * TICK_INTERVAL, vecVelocity, vecEndPoint );
float flDist = CalcDistanceToLineSegment( pPlayer->EarPosition(), vecPosition, vecEndPoint );
if ( flDist < 200.0f )
{
CSingleUserRecipientFilter filter( pPlayer );
EmitSound_t ep;
ep.m_nChannel = CHAN_STATIC;
if ( hl2_episodic.GetBool() )
{
ep.m_pSoundName = "NPC_CombineBall_Episodic.WhizFlyby";
}
else
{
ep.m_pSoundName = "NPC_CombineBall.WhizFlyby";
}
ep.m_flVolume = 1.0f;
ep.m_SoundLevel = SNDLVL_NORM;
EmitSound( filter, entindex(), ep );
bFoundAny = true;
}
}
}
}
if ( bFoundAny )
SetContextThink( &CPropCombineBall::WhizSoundThink, gpGlobals->curtime + 0.5f, s_pWhizThinkContext );
else
SetContextThink( &CPropCombineBall::WhizSoundThink, gpGlobals->curtime + 2.0f * TICK_INTERVAL, s_pWhizThinkContext );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropCombineBall::SetBallAsLaunched( void )
{
// Give the ball a duration
StartLifetime( PROP_COMBINE_BALL_LIFETIME );
m_bHeld = false;
m_bLaunched = true;
SetState( STATE_THROWN );
VPhysicsGetObject()->SetMass( 750.0f );
VPhysicsGetObject()->SetInertia( Vector( 1e30, 1e30, 1e30 ) );
StopLoopingSounds();
EmitSound( "NPC_CombineBall.Launch" );
WhizSoundThink();
}
//-----------------------------------------------------------------------------
// Lighten the mass so it's zippy toget to the gun
//-----------------------------------------------------------------------------
void CPropCombineBall::OnPhysGunPickup( CBasePlayer *pPhysGunUser, PhysGunPickup_t reason )
{
CDefaultPlayerPickupVPhysics::OnPhysGunPickup( pPhysGunUser, reason );
if ( m_nMaxBounces == -1 )
{
m_nMaxBounces = 0;
}
if ( !m_bFiredGrabbedOutput )
{
if ( GetSpawner() )
{
GetSpawner()->BallGrabbed( this );
}
m_bFiredGrabbedOutput = true;
}
if ( m_pGlowTrail )
{
m_pGlowTrail->TurnOff();
m_pGlowTrail->SetRenderColor( 0, 0, 0 );
m_pGlowTrail->SetRenderAlpha( 0 );
}
if ( reason != PUNTED_BY_CANNON )
{
SetState( STATE_HOLDING );
CPASAttenuationFilter filter( GetAbsOrigin(), ATTN_NORM );
filter.MakeReliable();
EmitSound_t ep;
ep.m_nChannel = CHAN_STATIC;
if( hl2_episodic.GetBool() )
{
ep.m_pSoundName = "NPC_CombineBall_Episodic.HoldingInPhysCannon";
}
else
{
ep.m_pSoundName = "NPC_CombineBall.HoldingInPhysCannon";
}
ep.m_flVolume = 1.0f;
ep.m_SoundLevel = SNDLVL_NORM;
// Now we own this ball
SetPlayerLaunched( pPhysGunUser );
CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();
m_pHoldingSound = controller.SoundCreate( filter, entindex(), ep );
controller.Play( m_pHoldingSound, 1.0f, 100 );
// Don't collide with anything we may have to pull the ball through
SetCollisionGroup( COLLISION_GROUP_DEBRIS );
VPhysicsGetObject()->SetMass( 20.0f );
VPhysicsGetObject()->SetInertia( Vector( 100, 100, 100 ) );
// Make it not explode
ClearLifetime( );
m_bHeld = true;
m_bLaunched = false;
//Let the ball know is not being captured by one of those ball fields anymore.
//
m_bCaptureInProgress = false;
SetContextThink( &CPropCombineBall::DissolveRampSoundThink, gpGlobals->curtime + GetBallHoldSoundRampTime(), s_pHoldDissolveContext );
StartAnimating();
}
else
{
Vector vecVelocity;
VPhysicsGetObject()->GetVelocity( &vecVelocity, NULL );
SetSpeed( vecVelocity.Length() );
// Set us as being launched by the player
SetPlayerLaunched( pPhysGunUser );
SetBallAsLaunched();
StopAnimating();
}
}
//-----------------------------------------------------------------------------
// Purpose: Reset the ball to be deadly to NPCs after we've picked it up
//-----------------------------------------------------------------------------
void CPropCombineBall::SetPlayerLaunched( CBasePlayer *pOwner )
{
// Now we own this ball
SetOwnerEntity( pOwner );
SetWeaponLaunched( false );
if( VPhysicsGetObject() )
{
PhysClearGameFlags( VPhysicsGetObject(), FVPHYSICS_NO_NPC_IMPACT_DMG );
PhysSetGameFlags( VPhysicsGetObject(), FVPHYSICS_DMG_DISSOLVE | FVPHYSICS_HEAVY_OBJECT );
}
}
//-----------------------------------------------------------------------------
// Activate death-spin!
//-----------------------------------------------------------------------------
void CPropCombineBall::OnPhysGunDrop( CBasePlayer *pPhysGunUser, PhysGunDrop_t Reason )
{
CDefaultPlayerPickupVPhysics::OnPhysGunDrop( pPhysGunUser, Reason );
SetState( STATE_THROWN );
WhizSoundThink();
m_bHeld = false;
m_bLaunched = true;
// Stop with the dissolving
SetContextThink( NULL, gpGlobals->curtime, s_pHoldDissolveContext );
// We're ready to start colliding again.
SetCollisionGroup( HL2COLLISION_GROUP_COMBINE_BALL );
if ( m_pGlowTrail )
{
m_pGlowTrail->TurnOn();
m_pGlowTrail->SetRenderColor( 255, 255, 255 );
m_pGlowTrail->SetRenderAlpha( 255 );
}
// Set our desired speed to be launched at
SetSpeed( 1500.0f );
SetPlayerLaunched( pPhysGunUser );
if ( Reason != LAUNCHED_BY_CANNON )
{
// Choose a random direction (forward facing)
Vector vecForward;
pPhysGunUser->GetVectors( &vecForward, NULL, NULL );
QAngle shotAng;
VectorAngles( vecForward, shotAng );
// Offset by some small cone
shotAng[PITCH] += random->RandomInt( -55, 55 );
shotAng[YAW] += random->RandomInt( -55, 55 );
AngleVectors( shotAng, &vecForward, NULL, NULL );
vecForward *= GetSpeed();
VPhysicsGetObject()->SetVelocity( &vecForward, &vec3_origin );
}
else
{
// This will have the consequence of making it so that the
// ball is launched directly down the crosshair even if the player is moving.
VPhysicsGetObject()->SetVelocity( &vec3_origin, &vec3_origin );
}
SetBallAsLaunched();
StopAnimating();
}
//------------------------------------------------------------------------------
// Stop looping sounds
//------------------------------------------------------------------------------
void CPropCombineBall::StopLoopingSounds()
{
if ( m_pHoldingSound )
{
CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();
controller.Shutdown( m_pHoldingSound );
controller.SoundDestroy( m_pHoldingSound );
m_pHoldingSound = NULL;
}
}
//------------------------------------------------------------------------------
// Pow!
//------------------------------------------------------------------------------
void CPropCombineBall::DissolveRampSoundThink( )
{
float dt = GetBallHoldDissolveTime() - GetBallHoldSoundRampTime();
if ( m_pHoldingSound )
{
CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();
controller.SoundChangePitch( m_pHoldingSound, 150, dt );
}
SetContextThink( &CPropCombineBall::DissolveThink, gpGlobals->curtime + dt, s_pHoldDissolveContext );
}
//------------------------------------------------------------------------------
// Pow!
//------------------------------------------------------------------------------
void CPropCombineBall::DissolveThink( )
{
DoExplosion();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
float CPropCombineBall::GetBallHoldDissolveTime()
{
float flDissolveTime = PROP_COMBINE_BALL_HOLD_DISSOLVE_TIME;
if( g_pGameRules->IsSkillLevel( 1 ) && hl2_episodic.GetBool() )
{
// Give players more time to handle/aim combine balls on Easy.
flDissolveTime *= 1.5f;
}
return flDissolveTime;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
float CPropCombineBall::GetBallHoldSoundRampTime()
{
return GetBallHoldDissolveTime() - 1.0f;
}
//------------------------------------------------------------------------------
// Pow!
//------------------------------------------------------------------------------
void CPropCombineBall::DoExplosion( )
{
// don't do this twice
if ( GetMoveType() == MOVETYPE_NONE )
return;
if ( PhysIsInCallback() )
{
g_PostSimulationQueue.QueueCall( this, &CPropCombineBall::DoExplosion );
return;
}
// Tell the respawner to make a new one
if ( GetSpawner() )
{
GetSpawner()->RespawnBallPostExplosion();
}
//Shockring
CBroadcastRecipientFilter filter2;
if ( OutOfBounces() == false )
{
if ( hl2_episodic.GetBool() )
{
EmitSound( "NPC_CombineBall_Episodic.Explosion" );
}
else
{
EmitSound( "NPC_CombineBall.Explosion" );
}
UTIL_ScreenShake( GetAbsOrigin(), 20.0f, 150.0, 1.0, 1250.0f, SHAKE_START );
CEffectData data;
data.m_vOrigin = GetAbsOrigin();
DispatchEffect( "cball_explode", data );
te->BeamRingPoint( filter2, 0, GetAbsOrigin(), //origin
m_flRadius, //start radius
1024, //end radius
s_nExplosionTexture, //texture
0, //halo index
0, //start frame
2, //framerate
0.2f, //life
64, //width
0, //spread
0, //amplitude
255, //r
255, //g
225, //b
32, //a
0, //speed
FBEAM_FADEOUT
);
//Shockring
te->BeamRingPoint( filter2, 0, GetAbsOrigin(), //origin
m_flRadius, //start radius
1024, //end radius
s_nExplosionTexture, //texture
0, //halo index
0, //start frame
2, //framerate
0.5f, //life
64, //width
0, //spread
0, //amplitude
255, //r
255, //g
225, //b
64, //a
0, //speed
FBEAM_FADEOUT
);
}
else
{
//Shockring
te->BeamRingPoint( filter2, 0, GetAbsOrigin(), //origin
128, //start radius
384, //end radius
s_nExplosionTexture, //texture
0, //halo index
0, //start frame
2, //framerate
0.25f, //life
48, //width
0, //spread
0, //amplitude
255, //r
255, //g
225, //b
64, //a
0, //speed
FBEAM_FADEOUT
);
}
if( hl2_episodic.GetBool() )
{
CSoundEnt::InsertSound( SOUND_COMBAT | SOUND_CONTEXT_EXPLOSION, WorldSpaceCenter(), 180.0f, 0.25, this );
}
// Turn us off and wait because we need our trails to finish up properly
SetAbsVelocity( vec3_origin );
SetMoveType( MOVETYPE_NONE );
AddSolidFlags( FSOLID_NOT_SOLID );
m_bEmit = false;
#ifdef HL2_DLL
if( !m_bStruckEntity && hl2_episodic.GetBool() && GetOwnerEntity() != NULL )
{
// Notify the player proxy that this combine ball missed so that it can fire an output.
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player *>( GetOwnerEntity() );
if ( pPlayer )
{
pPlayer->MissedAR2AltFire();
}
}
#endif
SetContextThink( &CPropCombineBall::SUB_Remove, gpGlobals->curtime + 0.5f, s_pRemoveContext );
StopLoopingSounds();
}
//-----------------------------------------------------------------------------
// Enable/disable
//-----------------------------------------------------------------------------
void CPropCombineBall::InputExplode( inputdata_t &inputdata )
{
DoExplosion();
}
//-----------------------------------------------------------------------------
// Enable/disable
//-----------------------------------------------------------------------------
void CPropCombineBall::InputFadeAndRespawn( inputdata_t &inputdata )
{
FadeOut( 0.1f );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropCombineBall::CollisionEventToTrace( int index, gamevcollisionevent_t *pEvent, trace_t &tr )
{
UTIL_ClearTrace( tr );
pEvent->pInternalData->GetSurfaceNormal( tr.plane.normal );
pEvent->pInternalData->GetContactPoint( tr.endpos );
tr.plane.dist = DotProduct( tr.plane.normal, tr.endpos );
VectorMA( tr.endpos, -1.0f, pEvent->preVelocity[index], tr.startpos );
tr.m_pEnt = pEvent->pEntities[!index];
tr.fraction = 0.01f; // spoof!
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CPropCombineBall::DissolveEntity( CBaseEntity *pEntity )
{
if( pEntity->IsEFlagSet( EFL_NO_DISSOLVE ) )
return false;
#ifdef HL2MP
if ( pEntity->IsPlayer() )
{
m_bStruckEntity = true;
return false;
}
#endif
if( !pEntity->IsNPC() && !(dynamic_cast<CRagdollProp*>(pEntity)) )
return false;
pEntity->GetBaseAnimating()->Dissolve( "", gpGlobals->curtime, false, ENTITY_DISSOLVE_NORMAL );
// Note that we've struck an entity
m_bStruckEntity = true;
// Force an NPC to not drop their weapon if dissolved
// CBaseCombatCharacter *pBCC = ToBaseCombatCharacter( pEntity );
// if ( pBCC != NULL )
// {
// pEntity->AddSpawnFlags( SF_NPC_NO_WEAPON_DROP );
// }
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropCombineBall::OnHitEntity( CBaseEntity *pHitEntity, float flSpeed, int index, gamevcollisionevent_t *pEvent )
{
// Detonate on the strider + the bone followers in the strider
if ( FClassnameIs( pHitEntity, "npc_strider" ) ||
(pHitEntity->GetOwnerEntity() && FClassnameIs( pHitEntity->GetOwnerEntity(), "npc_strider" )) )
{
DoExplosion();
return;
}
CTakeDamageInfo info( this, GetOwnerEntity(), m_hWeapon, GetAbsVelocity(), GetAbsOrigin(), sk_npc_dmg_combineball.GetFloat(), DMG_DISSOLVE );
bool bIsDissolving = (pHitEntity->GetFlags() & FL_DISSOLVING) != 0;
bool bShouldHit = pHitEntity->PassesDamageFilter( info );
#ifdef HL2_DLL
//One more check
//Combine soldiers are not allowed to hurt their friends with combine balls (they can still shoot and hurt each other with grenades).
CBaseCombatCharacter *pBCC = pHitEntity->MyCombatCharacterPointer();
if ( pBCC )
{
bShouldHit = pBCC->IRelationType( GetOwnerEntity() ) != D_LI;
}
#endif
if ( !bIsDissolving && bShouldHit == true )
{
if ( pHitEntity->PassesDamageFilter( info ) )
{
if( WasFiredByNPC() || m_nMaxBounces == -1 )
{
// Since Combine balls fired by NPCs do a metered dose of damage per impact, we have to ignore touches
// for a little while after we hit someone, or the ball will immediately touch them again and do more
// damage.
if( gpGlobals->curtime >= m_flNextDamageTime )
{
EmitSound( "NPC_CombineBall.KillImpact" );
if ( pHitEntity->IsNPC() && pHitEntity->Classify() != CLASS_PLAYER_ALLY_VITAL && hl2_episodic.GetBool() == true )
{
if ( pHitEntity->Classify() != CLASS_PLAYER_ALLY || ( pHitEntity->Classify() == CLASS_PLAYER_ALLY && m_bStruckEntity == false ) )
{
#ifdef INFESTED_DLL
info.ScaleDamage( rd_combine_ball_first_hit_bonus.GetFloat() );
#else
info.SetDamage( pHitEntity->GetMaxHealth() );
#endif
m_bStruckEntity = true;
}
}
else
{
// Ignore touches briefly.
m_flNextDamageTime = gpGlobals->curtime + 0.1f;
}
pHitEntity->TakeDamage( info );
}
}
else
{
if ( (m_nState == STATE_THROWN) && (pHitEntity->IsNPC() || dynamic_cast<CRagdollProp*>(pHitEntity) ))
{
EmitSound( "NPC_CombineBall.KillImpact" );
}
if ( (m_nState != STATE_HOLDING) )
{
CBasePlayer *pPlayer = ToBasePlayer( GetOwnerEntity() );
if ( pPlayer && UTIL_IsAR2CombineBall( this ) && ToBaseCombatCharacter( pHitEntity ) )
{
gamestats->Event_WeaponHit( pPlayer, false, "weapon_ar2", info );
}
DissolveEntity( pHitEntity );
if ( pHitEntity->ClassMatches( "npc_hunter" ) )
{
DoExplosion();
return;
}
}
}
}
}
Vector vecFinalVelocity;
if ( IsInField() )
{
// Don't deflect when in a spawner field
vecFinalVelocity = pEvent->preVelocity[index];
}
else
{
// Don't slow down when hitting other entities.
vecFinalVelocity = pEvent->postVelocity[index];
VectorNormalize( vecFinalVelocity );
vecFinalVelocity *= GetSpeed();
}
PhysCallbackSetVelocity( pEvent->pObjects[index], vecFinalVelocity );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropCombineBall::DoImpactEffect( const Vector &preVelocity, int index, gamevcollisionevent_t *pEvent )
{
// Do that crazy impact effect!
trace_t tr;
CollisionEventToTrace( index ? 0 : 1, pEvent, tr );
CBaseEntity *pTraceEntity = pEvent->pEntities[index];
UTIL_TraceLine( tr.startpos - preVelocity * 2.0f, tr.startpos + preVelocity * 2.0f, MASK_SOLID, pTraceEntity, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction < 1.0f )
{
// See if we hit the sky
if ( tr.surface.flags & SURF_SKY )
{
DoExplosion();
return;
}
// Send the effect over
CEffectData data;
data.m_flRadius = 16;
data.m_vNormal = tr.plane.normal;
data.m_vOrigin = tr.endpos + tr.plane.normal * 1.0f;
DispatchEffect( "cball_bounce", data );
}
if ( hl2_episodic.GetBool() )
{
EmitSound( "NPC_CombineBall_Episodic.Impact" );
}
else
{
EmitSound( "NPC_CombineBall.Impact" );
}
}
//-----------------------------------------------------------------------------
// Tells whether this combine ball should consider deflecting towards this entity.
//-----------------------------------------------------------------------------
bool CPropCombineBall::IsAttractiveTarget( CBaseEntity *pEntity )
{
if ( !pEntity->IsAlive() )
return false;
if ( pEntity->GetFlags() & EF_NODRAW )
return false;
// Don't guide toward striders
if ( FClassnameIs( pEntity, "npc_strider" ) )
return false;
#ifdef INFESTED_DLL
if ( !pEntity->IsNPC() )
return false;
if ( pEntity->Classify() == CLASS_BULLSEYE )
return false;
if ( GetOwnerEntity() && GetOwnerEntity()->MyCombatCharacterPointer() &&
GetOwnerEntity()->MyCombatCharacterPointer()->IRelationType( pEntity ) == D_LI )
return false;
#else
if( WasFiredByNPC() )
{
// Fired by an NPC
if( !pEntity->IsNPC() && !pEntity->IsPlayer() )
return false;
// Don't seek entities of the same class.
if ( pEntity->m_iClassname == GetOwnerEntity()->m_iClassname )
return false;
}
else
{
#ifndef HL2MP
if ( GetOwnerEntity() )
{
// Things we check if this ball has an owner that's not an NPC.
if( GetOwnerEntity()->IsPlayer() )
{
if( pEntity->Classify() == CLASS_PLAYER ||
pEntity->Classify() == CLASS_PLAYER_ALLY ||
pEntity->Classify() == CLASS_PLAYER_ALLY_VITAL )
{
// Not attracted to other players or allies.
return false;
}
}
}
// The default case.
if ( !pEntity->IsNPC() )
return false;
if( pEntity->Classify() == CLASS_BULLSEYE )
return false;
#else
if ( pEntity->IsPlayer() == false )
return false;
if ( pEntity == GetOwnerEntity() )
return false;
//No tracking teammates in teammode!
if ( g_pGameRules->IsTeamplay() )
{
if ( g_pGameRules->PlayerRelationship( GetOwnerEntity(), pEntity ) == GR_TEAMMATE )
return false;
}
#endif
// We must be able to hit them
trace_t tr;
UTIL_TraceLine( WorldSpaceCenter(), pEntity->BodyTarget( WorldSpaceCenter() ), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction < 1.0f && tr.m_pEnt != pEntity )
return false;
}
#endif
return true;
}
//-----------------------------------------------------------------------------
// Deflects the ball toward enemies in case of a collision
//-----------------------------------------------------------------------------
void CPropCombineBall::DeflectTowardEnemy( float flSpeed, int index, gamevcollisionevent_t *pEvent )
{
// Bounce toward a particular enemy; choose one that's closest to my new velocity.
Vector vecVelDir = pEvent->postVelocity[index];
VectorNormalize( vecVelDir );
CBaseEntity *pBestTarget = NULL;
Vector vecStartPoint;
pEvent->pInternalData->GetContactPoint( vecStartPoint );
float flBestDist = MAX_COORD_FLOAT;
CBaseEntity *list[1024];
Vector vecDelta;
float distance, flDot;
// If we've already hit something, get accurate
bool bSeekKill = m_bStruckEntity && (WasWeaponLaunched() || sk_combineball_seek_kill.GetInt() );
if ( bSeekKill )
{
int nCount = UTIL_EntitiesInSphere( list, 1024, GetAbsOrigin(), sk_combine_ball_search_radius.GetFloat(), FL_NPC | FL_CLIENT );
for ( int i = 0; i < nCount; i++ )
{
if ( !IsAttractiveTarget( list[i] ) )
continue;
VectorSubtract( list[i]->WorldSpaceCenter(), vecStartPoint, vecDelta );
distance = VectorNormalize( vecDelta );
if ( distance < flBestDist )
{
// Check our direction
if ( DotProduct( vecDelta, vecVelDir ) > 0.0f )
{
pBestTarget = list[i];
flBestDist = distance;
}
}
}
}
else
{
float flMaxDot = 0.966f;
if ( !WasWeaponLaunched() )
{
flMaxDot = sk_combineball_seek_angle.GetFloat();
float flGuideFactor = sk_combineball_guidefactor.GetFloat();
for ( int i = m_nBounceCount; --i >= 0; )
{
flMaxDot *= flGuideFactor;
}
flMaxDot = cos( flMaxDot * M_PI / 180.0f );
if ( flMaxDot > 1.0f )
{
flMaxDot = 1.0f;
}
}
// Otherwise only help out a little
Vector extents = Vector(256, 256, 256);
Ray_t ray;
ray.Init( vecStartPoint, vecStartPoint + 2048 * vecVelDir, -extents, extents );
int nCount = UTIL_EntitiesAlongRay( list, 1024, ray, FL_NPC | FL_CLIENT );
for ( int i = 0; i < nCount; i++ )
{
if ( !IsAttractiveTarget( list[i] ) )
continue;
VectorSubtract( list[i]->WorldSpaceCenter(), vecStartPoint, vecDelta );
distance = VectorNormalize( vecDelta );
flDot = DotProduct( vecDelta, vecVelDir );
if ( flDot > flMaxDot )
{
if ( distance < flBestDist )
{
pBestTarget = list[i];
flBestDist = distance;
}
}
}
}
if ( pBestTarget )
{
VectorSubtract( pBestTarget->WorldSpaceCenter(), vecStartPoint, vecDelta );
VectorNormalize( vecDelta );
vecDelta *= GetSpeed();
PhysCallbackSetVelocity( pEvent->pObjects[index], vecDelta );
}
}
//-----------------------------------------------------------------------------
// Bounce inside the spawner:
//-----------------------------------------------------------------------------
void CPropCombineBall::BounceInSpawner( float flSpeed, int index, gamevcollisionevent_t *pEvent )
{
GetSpawner()->RegisterReflection( this, m_bForward );
m_bForward = !m_bForward;
Vector vecTarget;
GetSpawner()->GetTargetEndpoint( m_bForward, &vecTarget );
Vector vecVelocity;
VectorSubtract( vecTarget, GetAbsOrigin(), vecVelocity );
VectorNormalize( vecVelocity );
vecVelocity *= flSpeed;
PhysCallbackSetVelocity( pEvent->pObjects[index], vecVelocity );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CPropCombineBall::IsHittableEntity( CBaseEntity *pHitEntity )
{
if ( pHitEntity->IsWorld() )
return false;
if ( pHitEntity->GetMoveType() == MOVETYPE_PUSH )
{
if( pHitEntity->GetOwnerEntity() && FClassnameIs(pHitEntity->GetOwnerEntity(), "npc_strider") )
{
// The Strider's Bone Followers are MOVETYPE_PUSH, and we want the combine ball to hit these.
return true;
}
// If the entity we hit can take damage, we're good
if ( pHitEntity->m_takedamage == DAMAGE_YES )
return true;
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropCombineBall::VPhysicsCollision( int index, gamevcollisionevent_t *pEvent )
{
Vector preVelocity = pEvent->preVelocity[index];
float flSpeed = VectorNormalize( preVelocity );
if ( m_nMaxBounces == -1 )
{
const surfacedata_t *pHit = physprops->GetSurfaceData( pEvent->surfaceProps[!index] );
if( pHit->game.material != CHAR_TEX_FLESH || !hl2_episodic.GetBool() )
{
CBaseEntity *pHitEntity = pEvent->pEntities[!index];
if ( pHitEntity && IsHittableEntity( pHitEntity ) )
{
OnHitEntity( pHitEntity, flSpeed, index, pEvent );
}
// Remove self without affecting the object that was hit. (Unless it was flesh)
NotifySpawnerOfRemoval();
PhysCallbackRemove( this->NetworkProp() );
// disable dissolve damage so we don't kill off the player when he's the one we hit
PhysClearGameFlags( VPhysicsGetObject(), FVPHYSICS_DMG_DISSOLVE );
return;
}
}
// Prevents impact sounds, effects, etc. when it's in the field
if ( !IsInField() )
{
BaseClass::VPhysicsCollision( index, pEvent );
}
if ( m_nState == STATE_HOLDING )
return;
// If we've collided going faster than our desired, then up our desired
if ( flSpeed > GetSpeed() )
{
SetSpeed( flSpeed );
}
// Make sure we don't slow down
Vector vecFinalVelocity = pEvent->postVelocity[index];
VectorNormalize( vecFinalVelocity );
vecFinalVelocity *= GetSpeed();
PhysCallbackSetVelocity( pEvent->pObjects[index], vecFinalVelocity );
CBaseEntity *pHitEntity = pEvent->pEntities[!index];
if ( pHitEntity && IsHittableEntity( pHitEntity ) )
{
OnHitEntity( pHitEntity, flSpeed, index, pEvent );
return;
}
if ( IsInField() )
{
if ( HasSpawnFlags( SF_COMBINE_BALL_BOUNCING_IN_SPAWNER ) && GetSpawner() )
{
BounceInSpawner( GetSpeed(), index, pEvent );
return;
}
PhysCallbackSetVelocity( pEvent->pObjects[index], vec3_origin );
// Delay the fade out so that we don't change our
// collision rules inside a vphysics callback.
variant_t emptyVariant;
g_EventQueue.AddEvent( this, "FadeAndRespawn", 0.01, NULL, NULL );
return;
}
if ( IsBeingCaptured() )
return;
// Do that crazy impact effect!
DoImpactEffect( preVelocity, index, pEvent );
// Only do the bounce so often
if ( gpGlobals->curtime - m_flLastBounceTime < 0.25f )
return;
// Save off our last bounce time
m_flLastBounceTime = gpGlobals->curtime;
// Reset the sound timer
SetContextThink( &CPropCombineBall::WhizSoundThink, gpGlobals->curtime + 0.01, s_pWhizThinkContext );
// Deflect towards nearby enemies
DeflectTowardEnemy( flSpeed, index, pEvent );
// Once more bounce
++m_nBounceCount;
if ( OutOfBounces() && m_bBounceDie == false )
{
StartLifetime( 0.5 );
//Hack: Stop this from being called by doing this.
m_bBounceDie = true;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPropCombineBall::AnimThink( void )
{
StudioFrameAdvance();
SetContextThink( &CPropCombineBall::AnimThink, gpGlobals->curtime + 0.1f, s_pAnimThinkContext );
}
//-----------------------------------------------------------------------------
//
// Implementation of CPropCombineBall
//
//-----------------------------------------------------------------------------
LINK_ENTITY_TO_CLASS( func_combine_ball_spawner, CFuncCombineBallSpawner );
//-----------------------------------------------------------------------------
// Save/load:
//-----------------------------------------------------------------------------
BEGIN_DATADESC( CFuncCombineBallSpawner )
DEFINE_KEYFIELD( m_nBallCount, FIELD_INTEGER, "ballcount" ),
DEFINE_KEYFIELD( m_flMinSpeed, FIELD_FLOAT, "minspeed" ),
DEFINE_KEYFIELD( m_flMaxSpeed, FIELD_FLOAT, "maxspeed" ),
DEFINE_KEYFIELD( m_flBallRadius, FIELD_FLOAT, "ballradius" ),
DEFINE_KEYFIELD( m_flBallRespawnTime, FIELD_FLOAT, "ballrespawntime" ),
DEFINE_FIELD( m_flRadius, FIELD_FLOAT ),
DEFINE_FIELD( m_nBallsRemainingInField, FIELD_INTEGER ),
DEFINE_FIELD( m_bEnabled, FIELD_BOOLEAN ),
DEFINE_UTLVECTOR( m_BallRespawnTime, FIELD_TIME ),
DEFINE_FIELD( m_flDisableTime, FIELD_TIME ),
DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ),
DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ),
DEFINE_OUTPUT( m_OnBallGrabbed, "OnBallGrabbed" ),
DEFINE_OUTPUT( m_OnBallReinserted, "OnBallReinserted" ),
DEFINE_OUTPUT( m_OnBallHitTopSide, "OnBallHitTopSide" ),
DEFINE_OUTPUT( m_OnBallHitBottomSide, "OnBallHitBottomSide" ),
DEFINE_OUTPUT( m_OnLastBallGrabbed, "OnLastBallGrabbed" ),
DEFINE_OUTPUT( m_OnFirstBallReinserted, "OnFirstBallReinserted" ),
DEFINE_THINKFUNC( BallThink ),
DEFINE_ENTITYFUNC( GrabBallTouch ),
END_DATADESC()
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CFuncCombineBallSpawner::CFuncCombineBallSpawner()
{
m_flBallRespawnTime = 0.0f;
m_flBallRadius = 20.0f;
m_flDisableTime = 0.0f;
m_bShooter = false;
}
//-----------------------------------------------------------------------------
// Spawn a ball
//-----------------------------------------------------------------------------
void CFuncCombineBallSpawner::SpawnBall()
{
CPropCombineBall *pBall = static_cast<CPropCombineBall*>( CreateEntityByName( "prop_combine_ball" ) );
float flRadius = m_flBallRadius;
pBall->SetRadius( flRadius );
Vector vecAbsOrigin;
ChoosePointInBox( &vecAbsOrigin );
Vector zaxis;
MatrixGetColumn( EntityToWorldTransform(), 2, zaxis );
VectorMA( vecAbsOrigin, flRadius, zaxis, vecAbsOrigin );
pBall->SetAbsOrigin( vecAbsOrigin );
pBall->SetSpawner( this );
float flSpeed = random->RandomFloat( m_flMinSpeed, m_flMaxSpeed );
zaxis *= flSpeed;
pBall->SetAbsVelocity( zaxis );
if ( HasSpawnFlags( SF_SPAWNER_POWER_SUPPLY ) )
{
pBall->AddSpawnFlags( SF_COMBINE_BALL_BOUNCING_IN_SPAWNER );
}
pBall->Spawn();
}
void CFuncCombineBallSpawner::Precache()
{
BaseClass::Precache();
UTIL_PrecacheOther( "prop_combine_ball" );
}
//-----------------------------------------------------------------------------
// Spawn
//-----------------------------------------------------------------------------
void CFuncCombineBallSpawner::Spawn()
{
BaseClass::Spawn();
Precache();
AddEffects( EF_NODRAW );
SetModel( STRING( GetModelName() ) );
SetSolid( SOLID_BSP );
AddSolidFlags( FSOLID_NOT_SOLID );
m_nBallsRemainingInField = m_nBallCount;
float flWidth = CollisionProp()->OBBSize().x;
float flHeight = CollisionProp()->OBBSize().y;
m_flRadius = MIN( flWidth, flHeight ) * 0.5f;
if ( m_flRadius <= 0.0f && m_bShooter == false )
{
Warning("Zero dimension func_combine_ball_spawner! Removing...\n");
UTIL_Remove( this );
return;
}
// Compute a respawn time
float flDeltaT = 1.0f;
if ( !( m_flMinSpeed == 0 && m_flMaxSpeed == 0 ) )
{
flDeltaT = (CollisionProp()->OBBSize().z - 2 * m_flBallRadius) / ((m_flMinSpeed + m_flMaxSpeed) * 0.5f);
flDeltaT /= m_nBallCount;
}
m_BallRespawnTime.EnsureCapacity( m_nBallCount );
for ( int i = 0; i < m_nBallCount; ++i )
{
RespawnBall( (float)i * flDeltaT );
}
m_bEnabled = true;
if ( HasSpawnFlags( SF_SPAWNER_START_DISABLED ) )
{
inputdata_t inputData;
InputDisable( inputData );
}
else
{
SetThink( &CFuncCombineBallSpawner::BallThink );
SetNextThink( gpGlobals->curtime + 0.1f );
}
}
//-----------------------------------------------------------------------------
// Enable/disable
//-----------------------------------------------------------------------------
void CFuncCombineBallSpawner::InputEnable( inputdata_t &inputdata )
{
if ( m_bEnabled )
return;
m_bEnabled = true;
m_flDisableTime = 0.0f;
for ( int i = m_BallRespawnTime.Count(); --i >= 0; )
{
m_BallRespawnTime[i] += gpGlobals->curtime;
}
SetThink( &CFuncCombineBallSpawner::BallThink );
SetNextThink( gpGlobals->curtime + 0.1f );
}
void CFuncCombineBallSpawner::InputDisable( inputdata_t &inputdata )
{
if ( !m_bEnabled )
return;
m_flDisableTime = gpGlobals->curtime;
m_bEnabled = false;
for ( int i = m_BallRespawnTime.Count(); --i >= 0; )
{
m_BallRespawnTime[i] -= gpGlobals->curtime;
}
SetThink( NULL );
}
//-----------------------------------------------------------------------------
// Choose a random point inside the cylinder
//-----------------------------------------------------------------------------
void CFuncCombineBallSpawner::ChoosePointInBox( Vector *pVecPoint )
{
float flXBoundary = ( CollisionProp()->OBBSize().x != 0 ) ? m_flBallRadius / CollisionProp()->OBBSize().x : 0.0f;
float flYBoundary = ( CollisionProp()->OBBSize().y != 0 ) ? m_flBallRadius / CollisionProp()->OBBSize().y : 0.0f;
if ( flXBoundary > 0.5f )
{
flXBoundary = 0.5f;
}
if ( flYBoundary > 0.5f )
{
flYBoundary = 0.5f;
}
CollisionProp()->RandomPointInBounds(
Vector( flXBoundary, flYBoundary, 0.0f ), Vector( 1.0f - flXBoundary, 1.0f - flYBoundary, 0.0f ), pVecPoint );
}
//-----------------------------------------------------------------------------
// Choose a random point inside the cylinder
//-----------------------------------------------------------------------------
void CFuncCombineBallSpawner::ChoosePointInCylinder( Vector *pVecPoint )
{
float flXRange = m_flRadius / CollisionProp()->OBBSize().x;
float flYRange = m_flRadius / CollisionProp()->OBBSize().y;
Vector vecEndPoint1, vecEndPoint2;
CollisionProp()->NormalizedToWorldSpace( Vector( 0.5f, 0.5f, 0.0f ), &vecEndPoint1 );
CollisionProp()->NormalizedToWorldSpace( Vector( 0.5f, 0.5f, 1.0f ), &vecEndPoint2 );
// Choose a point inside the cylinder
float flDistSq;
do
{
CollisionProp()->RandomPointInBounds(
Vector( 0.5f - flXRange, 0.5f - flYRange, 0.0f ),
Vector( 0.5f + flXRange, 0.5f + flYRange, 0.0f ),
pVecPoint );
flDistSq = CalcDistanceSqrToLine( *pVecPoint, vecEndPoint1, vecEndPoint2 );
} while ( flDistSq > m_flRadius * m_flRadius );
}
//-----------------------------------------------------------------------------
// Register that a reflection occurred
//-----------------------------------------------------------------------------
void CFuncCombineBallSpawner::RegisterReflection( CPropCombineBall *pBall, bool bForward )
{
if ( bForward )
{
m_OnBallHitTopSide.FireOutput( pBall, this );
}
else
{
m_OnBallHitBottomSide.FireOutput( pBall, this );
}
}
//-----------------------------------------------------------------------------
// Choose a random point on the
//-----------------------------------------------------------------------------
void CFuncCombineBallSpawner::GetTargetEndpoint( bool bForward, Vector *pVecEndPoint )
{
float flZValue = bForward ? 1.0f : 0.0f;
CollisionProp()->RandomPointInBounds(
Vector( 0.0f, 0.0f, flZValue ), Vector( 1.0f, 1.0f, flZValue ), pVecEndPoint );
}
//-----------------------------------------------------------------------------
// Fire ball grabbed output
//-----------------------------------------------------------------------------
void CFuncCombineBallSpawner::BallGrabbed( CBaseEntity *pCombineBall )
{
m_OnBallGrabbed.FireOutput( pCombineBall, this );
--m_nBallsRemainingInField;
if ( m_nBallsRemainingInField == 0 )
{
m_OnLastBallGrabbed.FireOutput( pCombineBall, this );
}
// Wait for another ball to touch this to re-power it up.
if ( HasSpawnFlags( SF_SPAWNER_POWER_SUPPLY ) )
{
AddSolidFlags( FSOLID_TRIGGER );
SetTouch( &CFuncCombineBallSpawner::GrabBallTouch );
}
// Stop the ball thinking in case it was in the middle of being captured (which could re-add incorrectly)
if ( pCombineBall != NULL )
{
pCombineBall->SetContextThink( NULL, gpGlobals->curtime, s_pCaptureContext );
}
}
//-----------------------------------------------------------------------------
// Fire ball grabbed output
//-----------------------------------------------------------------------------
void CFuncCombineBallSpawner::GrabBallTouch( CBaseEntity *pOther )
{
// Safety net for two balls hitting this at once
if ( m_nBallsRemainingInField >= m_nBallCount )
return;
if ( pOther->GetCollisionGroup() != HL2COLLISION_GROUP_COMBINE_BALL )
return;
CPropCombineBall *pBall = dynamic_cast<CPropCombineBall*>( pOther );
Assert( pBall );
// Don't grab AR2 alt-fire
if ( pBall->WasWeaponLaunched() || !pBall->VPhysicsGetObject() )
return;
// Don't grab balls that are already in the field..
if ( pBall->IsInField() )
return;
// Don't grab fading out balls...
if ( !pBall->IsSolid() )
return;
// Don't capture balls that were very recently in the field (breaks punting)
if ( gpGlobals->curtime - pBall->LastCaptureTime() < 0.5f )
return;
// Now we're bouncing in this spawner
pBall->AddSpawnFlags( SF_COMBINE_BALL_BOUNCING_IN_SPAWNER );
// Tell the respawner we're no longer its ball
pBall->NotifySpawnerOfRemoval();
pBall->SetOwnerEntity( NULL );
pBall->SetSpawner( this );
pBall->CaptureBySpawner();
++m_nBallsRemainingInField;
if ( m_nBallsRemainingInField >= m_nBallCount )
{
RemoveSolidFlags( FSOLID_TRIGGER );
SetTouch( NULL );
}
m_OnBallReinserted.FireOutput( pBall, this );
if ( m_nBallsRemainingInField == 1 )
{
m_OnFirstBallReinserted.FireOutput( pBall, this );
}
}
//-----------------------------------------------------------------------------
// Get a speed for the ball to insert
//-----------------------------------------------------------------------------
float CFuncCombineBallSpawner::GetBallSpeed( ) const
{
return random->RandomFloat( m_flMinSpeed, m_flMaxSpeed );
}
//-----------------------------------------------------------------------------
// Balls call this when they've been removed from the spawner
//-----------------------------------------------------------------------------
void CFuncCombineBallSpawner::RespawnBall( float flRespawnTime )
{
// Insert the time in sorted order,
// which by definition means to always insert at the start
m_BallRespawnTime.AddToTail( gpGlobals->curtime + flRespawnTime - m_flDisableTime );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CFuncCombineBallSpawner::RespawnBallPostExplosion( void )
{
if ( m_flBallRespawnTime < 0 )
return;
if ( m_flBallRespawnTime == 0.0f )
{
m_BallRespawnTime.AddToTail( gpGlobals->curtime + 4.0f - m_flDisableTime );
}
else
{
m_BallRespawnTime.AddToTail( gpGlobals->curtime + m_flBallRespawnTime - m_flDisableTime );
}
}
//-----------------------------------------------------------------------------
// Ball think
//-----------------------------------------------------------------------------
void CFuncCombineBallSpawner::BallThink()
{
for ( int i = m_BallRespawnTime.Count(); --i >= 0; )
{
if ( m_BallRespawnTime[i] < gpGlobals->curtime )
{
SpawnBall();
m_BallRespawnTime.FastRemove( i );
}
}
// There are no more to respawn
SetNextThink( gpGlobals->curtime + 0.1f );
}
BEGIN_DATADESC( CPointCombineBallLauncher )
DEFINE_KEYFIELD( m_flConeDegrees, FIELD_FLOAT, "launchconenoise" ),
DEFINE_KEYFIELD( m_iszBullseyeName, FIELD_STRING, "bullseyename" ),
DEFINE_KEYFIELD( m_iBounces, FIELD_INTEGER, "maxballbounces" ),
DEFINE_INPUTFUNC( FIELD_VOID, "LaunchBall", InputLaunchBall ),
END_DATADESC()
#define SF_COMBINE_BALL_LAUNCHER_ATTACH_BULLSEYE 0x00000001
#define SF_COMBINE_BALL_LAUNCHER_COLLIDE_PLAYER 0x00000002
LINK_ENTITY_TO_CLASS( point_combine_ball_launcher, CPointCombineBallLauncher );
CPointCombineBallLauncher::CPointCombineBallLauncher()
{
m_bShooter = true;
m_flConeDegrees = 0.0f;
m_iBounces = 0;
}
void CPointCombineBallLauncher::Spawn( void )
{
m_bShooter = true;
BaseClass::Spawn();
}
void CPointCombineBallLauncher::InputLaunchBall ( inputdata_t &inputdata )
{
SpawnBall();
}
//-----------------------------------------------------------------------------
// Spawn a ball
//-----------------------------------------------------------------------------
void CPointCombineBallLauncher::SpawnBall()
{
CPropCombineBall *pBall = static_cast<CPropCombineBall*>( CreateEntityByName( "prop_combine_ball" ) );
if ( pBall == NULL )
return;
float flRadius = m_flBallRadius;
pBall->SetRadius( flRadius );
Vector vecAbsOrigin = GetAbsOrigin();
Vector zaxis;
pBall->SetAbsOrigin( vecAbsOrigin );
pBall->SetSpawner( this );
float flSpeed = random->RandomFloat( m_flMinSpeed, m_flMaxSpeed );
Vector vDirection;
QAngle qAngle = GetAbsAngles();
qAngle = qAngle + QAngle ( random->RandomFloat( -m_flConeDegrees, m_flConeDegrees ), random->RandomFloat( -m_flConeDegrees, m_flConeDegrees ), 0 );
AngleVectors( qAngle, &vDirection, NULL, NULL );
vDirection *= flSpeed;
pBall->SetAbsVelocity( vDirection );
DispatchSpawn(pBall);
pBall->Activate();
pBall->SetState( CPropCombineBall::STATE_LAUNCHED );
pBall->SetMaxBounces( m_iBounces );
#ifndef INFESTED_DLL
if ( HasSpawnFlags( SF_COMBINE_BALL_LAUNCHER_COLLIDE_PLAYER ) )
{
pBall->SetCollisionGroup( HL2COLLISION_GROUP_COMBINE_BALL_NPC );
}
#endif
if( GetSpawnFlags() & SF_COMBINE_BALL_LAUNCHER_ATTACH_BULLSEYE )
{
CNPC_Bullseye *pBullseye = static_cast<CNPC_Bullseye*>( CreateEntityByName( "npc_bullseye" ) );
if( pBullseye )
{
pBullseye->SetAbsOrigin( pBall->GetAbsOrigin() );
pBullseye->SetAbsAngles( QAngle( 0, 0, 0 ) );
pBullseye->KeyValue( "solid", "6" );
pBullseye->KeyValue( "targetname", STRING(m_iszBullseyeName) );
pBullseye->Spawn();
DispatchSpawn(pBullseye);
pBullseye->Activate();
pBullseye->SetParent(pBall);
pBullseye->SetHealth(10);
}
}
}
// ###################################################################
// > FilterClass
// ###################################################################
class CFilterCombineBall : public CBaseFilter
{
DECLARE_CLASS( CFilterCombineBall, CBaseFilter );
DECLARE_DATADESC();
public:
int m_iBallType;
bool PassesFilterImpl( CBaseEntity *pCaller, CBaseEntity *pEntity )
{
CPropCombineBall *pBall = dynamic_cast<CPropCombineBall*>(pEntity );
if ( pBall )
{
#ifdef HL2_DLL
//Playtest HACK: If we have an NPC owner then we were shot from an AR2.
if ( pBall->GetOwnerEntity() && pBall->GetOwnerEntity()->IsNPC() )
return false;
#endif
return pBall->GetState() == m_iBallType;
}
return false;
}
};
LINK_ENTITY_TO_CLASS( filter_combineball_type, CFilterCombineBall );
BEGIN_DATADESC( CFilterCombineBall )
// Keyfields
DEFINE_KEYFIELD( m_iBallType, FIELD_INTEGER, "balltype" ),
END_DATADESC()
| 0 | 0.977331 | 1 | 0.977331 | game-dev | MEDIA | 0.974077 | game-dev | 0.91782 | 1 | 0.91782 |
dotnet/machinelearning-samples | 204,771 | samples/csharp/end-to-end-apps/Unity-HelloMLNET/HelloMLNET/Library/PackageCache/com.unity.textmeshpro@1.3.0/Scripts/Runtime/TMPro_Private.cs | //#define TMP_PROFILE_ON
//#define TMP_PROFILE_PHASES_ON
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
#pragma warning disable 0414 // Disabled a few warnings related to serialized variables not used in this script but used in the editor.
namespace TMPro
{
public partial class TextMeshPro
{
[SerializeField]
private bool m_hasFontAssetChanged = false; // Used to track when font properties have changed.
float m_previousLossyScaleY = -1; // Used for Tracking lossy scale changes in the transform;
[SerializeField]
private Renderer m_renderer;
private MeshFilter m_meshFilter;
private bool m_isFirstAllocation; // Flag to determine if this is the first allocation of the buffers.
private int m_max_characters = 8; // Determines the initial allocation and size of the character array / buffer.
private int m_max_numberOfLines = 4; // Determines the initial allocation and maximum number of lines of text.
private Bounds m_default_bounds = new Bounds(Vector3.zero, new Vector3(1000, 1000, 0));
[SerializeField]
protected TMP_SubMesh[] m_subTextObjects = new TMP_SubMesh[8];
// MASKING RELATED PROPERTIES
//MaterialPropertyBlock m_maskingPropertyBlock;
//[SerializeField]
private bool m_isMaskingEnabled;
private bool isMaskUpdateRequired;
//private bool m_isMaterialBlockSet;
[SerializeField]
private MaskingTypes m_maskType;
// Matrix used to animated Env Map
private Matrix4x4 m_EnvMapMatrix = new Matrix4x4();
// Text Container / RectTransform Component
private Vector3[] m_RectTransformCorners = new Vector3[4];
[NonSerialized]
private bool m_isRegisteredForEvents;
// DEBUG Variables
//private System.Diagnostics.Stopwatch m_StopWatch;
//private bool isDebugOutputDone;
//private int m_recursiveCount = 0;
private int loopCountA;
//private int loopCountB;
//private int loopCountC;
//private int loopCountD;
//private int loopCountE;
protected override void Awake()
{
//Debug.Log("Awake() called on Object ID " + GetInstanceID());
#if UNITY_EDITOR
// Special handling for TMP Settings and importing Essential Resources
if (TMP_Settings.instance == null)
{
if (m_isWaitingOnResourceLoad == false)
TMPro_EventManager.RESOURCE_LOAD_EVENT.Add(ON_RESOURCES_LOADED);
m_isWaitingOnResourceLoad = true;
return;
}
#endif
// Cache Reference to the Mesh Renderer.
m_renderer = GetComponent<Renderer>();
if (m_renderer == null)
m_renderer = gameObject.AddComponent<Renderer>();
// Make sure we have a CanvasRenderer for compatibility reasons and hide it
if (this.canvasRenderer != null)
this.canvasRenderer.hideFlags = HideFlags.HideInInspector;
else
{
CanvasRenderer canvasRenderer = gameObject.AddComponent<CanvasRenderer>();
canvasRenderer.hideFlags = HideFlags.HideInInspector;
}
// Cache Reference to RectTransform
m_rectTransform = this.rectTransform;
// Cache Reference to the transform;
m_transform = this.transform;
// Cache a reference to the Mesh Filter.
m_meshFilter = GetComponent<MeshFilter>();
if (m_meshFilter == null)
m_meshFilter = gameObject.AddComponent<MeshFilter>();
// Cache a reference to our mesh.
if (m_mesh == null)
{
//Debug.Log("Creating new mesh.");
m_mesh = new Mesh();
m_mesh.hideFlags = HideFlags.HideAndDontSave;
m_meshFilter.mesh = m_mesh;
//m_mesh.bounds = new Bounds(transform.position, new Vector3(1000, 1000, 0));
}
m_meshFilter.hideFlags = HideFlags.HideInInspector;
// Load TMP Settings for new text object instances.
LoadDefaultSettings();
// Load the font asset and assign material to renderer.
LoadFontAsset();
// Load Default TMP StyleSheet
TMP_StyleSheet.LoadDefaultStyleSheet();
// Allocate our initial buffers.
if (m_char_buffer == null)
m_char_buffer = new int[m_max_characters];
m_cached_TextElement = new TMP_Glyph();
m_isFirstAllocation = true;
if (m_textInfo == null)
m_textInfo = new TMP_TextInfo(this);
// Check if we have a font asset assigned. Return if we don't because no one likes to see purple squares on screen.
if (m_fontAsset == null)
{
Debug.LogWarning("Please assign a Font Asset to this " + transform.name + " gameobject.", this);
return;
}
// Check to make sure Sub Text Objects are tracked correctly in the event a Prefab is used.
TMP_SubMesh[] subTextObjects = GetComponentsInChildren<TMP_SubMesh>();
if (subTextObjects.Length > 0)
{
for (int i = 0; i < subTextObjects.Length; i++)
m_subTextObjects[i + 1] = subTextObjects[i];
}
// Set flags to ensure our text is parsed and redrawn.
m_isInputParsingRequired = true;
m_havePropertiesChanged = true;
m_isCalculateSizeRequired = true;
m_isAwake = true;
}
protected override void OnEnable()
{
//Debug.Log("***** OnEnable() called on object ID " + GetInstanceID() + ". *****"); // called. Renderer.MeshFilter ID " + m_renderer.GetComponent<MeshFilter>().sharedMesh.GetInstanceID() + " Mesh ID " + m_mesh.GetInstanceID() + " MeshFilter ID " + m_meshFilter.GetInstanceID()); //has been called. HavePropertiesChanged = " + havePropertiesChanged); // has been called on Object ID:" + gameObject.GetInstanceID());
// Return if Awake() has not been called on the text object.
if (m_isAwake == false)
return;
// Register Callbacks for various events.
if (!m_isRegisteredForEvents)
{
#if UNITY_EDITOR
TMPro_EventManager.MATERIAL_PROPERTY_EVENT.Add(ON_MATERIAL_PROPERTY_CHANGED);
TMPro_EventManager.FONT_PROPERTY_EVENT.Add(ON_FONT_PROPERTY_CHANGED);
TMPro_EventManager.TEXTMESHPRO_PROPERTY_EVENT.Add(ON_TEXTMESHPRO_PROPERTY_CHANGED);
TMPro_EventManager.DRAG_AND_DROP_MATERIAL_EVENT.Add(ON_DRAG_AND_DROP_MATERIAL);
TMPro_EventManager.TEXT_STYLE_PROPERTY_EVENT.Add(ON_TEXT_STYLE_CHANGED);
TMPro_EventManager.COLOR_GRADIENT_PROPERTY_EVENT.Add(ON_COLOR_GRADIENT_CHANGED);
TMPro_EventManager.TMP_SETTINGS_PROPERTY_EVENT.Add(ON_TMP_SETTINGS_CHANGED);
#endif
m_isRegisteredForEvents = true;
}
meshFilter.sharedMesh = mesh;
SetActiveSubMeshes(true);
// Schedule potential text object update (if any of the properties have changed.
ComputeMarginSize();
m_isInputParsingRequired = true;
m_havePropertiesChanged = true;
m_verticesAlreadyDirty = false;
SetVerticesDirty();
}
protected override void OnDisable()
{
//Debug.Log("***** OnDisable() called on object ID " + GetInstanceID() + ". *****"); //+ m_renderer.GetComponent<MeshFilter>().sharedMesh.GetInstanceID() + " Mesh ID " + m_mesh.GetInstanceID() + " MeshFilter ID " + m_meshFilter.GetInstanceID()); //has been called. HavePropertiesChanged = " + havePropertiesChanged); // has been called on Object ID:" + gameObject.GetInstanceID());
// Return if Awake() has not been called on the text object.
if (m_isAwake == false)
return;
TMP_UpdateManager.UnRegisterTextElementForRebuild(this);
m_meshFilter.sharedMesh = null;
SetActiveSubMeshes(false);
}
protected override void OnDestroy()
{
//Debug.Log("***** OnDestroy() called on object ID " + GetInstanceID() + ". *****");
// Destroy the mesh if we have one.
if (m_mesh != null)
{
DestroyImmediate(m_mesh);
}
// Unregister the event this object was listening to
#if UNITY_EDITOR
TMPro_EventManager.MATERIAL_PROPERTY_EVENT.Remove(ON_MATERIAL_PROPERTY_CHANGED);
TMPro_EventManager.FONT_PROPERTY_EVENT.Remove(ON_FONT_PROPERTY_CHANGED);
TMPro_EventManager.TEXTMESHPRO_PROPERTY_EVENT.Remove(ON_TEXTMESHPRO_PROPERTY_CHANGED);
TMPro_EventManager.DRAG_AND_DROP_MATERIAL_EVENT.Remove(ON_DRAG_AND_DROP_MATERIAL);
TMPro_EventManager.TEXT_STYLE_PROPERTY_EVENT.Remove(ON_TEXT_STYLE_CHANGED);
TMPro_EventManager.COLOR_GRADIENT_PROPERTY_EVENT.Remove(ON_COLOR_GRADIENT_CHANGED);
TMPro_EventManager.TMP_SETTINGS_PROPERTY_EVENT.Remove(ON_TMP_SETTINGS_CHANGED);
TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
#endif
m_isRegisteredForEvents = false;
TMP_UpdateManager.UnRegisterTextElementForRebuild(this);
}
#if UNITY_EDITOR
protected override void Reset()
{
//Debug.Log("Reset() has been called." + m_subTextObjects);
// Return if Awake() has not been called on the text object.
if (m_isAwake == false)
return;
if (m_mesh != null)
DestroyImmediate(m_mesh);
Awake();
}
protected override void OnValidate()
{
//Debug.Log("*** TextMeshPro OnValidate() has been called on Object ID:" + gameObject.GetInstanceID());
// Return if Awake() has not been called on the text object.
if (m_isAwake == false)
return;
// Additional Properties could be added to sync up Serialized Properties & Properties.
// Handle Font Asset changes in the inspector
if (m_fontAsset == null || m_hasFontAssetChanged)
{
LoadFontAsset();
m_isCalculateSizeRequired = true;
m_hasFontAssetChanged = false;
}
m_padding = GetPaddingForMaterial();
m_isInputParsingRequired = true;
m_inputSource = TextInputSources.Text;
m_havePropertiesChanged = true;
m_isCalculateSizeRequired = true;
m_isPreferredWidthDirty = true;
m_isPreferredHeightDirty = true;
SetAllDirty();
}
// Event received when TMP resources have been loaded.
void ON_RESOURCES_LOADED()
{
TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
Awake();
OnEnable();
}
// Event received when custom material editor properties are changed.
void ON_MATERIAL_PROPERTY_CHANGED(bool isChanged, Material mat)
{
//Debug.Log("ON_MATERIAL_PROPERTY_CHANGED event received. Targeted Material is: " + mat.name + " m_sharedMaterial: " + m_sharedMaterial.name + " m_renderer.sharedMaterial: " + m_renderer.sharedMaterial);
if (m_renderer.sharedMaterial == null)
{
if (m_fontAsset != null)
{
m_renderer.sharedMaterial = m_fontAsset.material;
Debug.LogWarning("No Material was assigned to " + name + ". " + m_fontAsset.material.name + " was assigned.", this);
}
else
Debug.LogWarning("No Font Asset assigned to " + name + ". Please assign a Font Asset.", this);
}
if (m_fontAsset.atlas.GetInstanceID() != m_renderer.sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
{
m_renderer.sharedMaterial = m_sharedMaterial;
//m_renderer.sharedMaterial = m_fontAsset.material;
Debug.LogWarning("Font Asset Atlas doesn't match the Atlas in the newly assigned material. Select a matching material or a different font asset.", this);
}
if (m_renderer.sharedMaterial != m_sharedMaterial) // || m_renderer.sharedMaterials.Contains(mat))
{
//Debug.Log("ON_MATERIAL_PROPERTY_CHANGED Called on Target ID: " + GetInstanceID() + ". Previous Material:" + m_sharedMaterial + " New Material:" + m_renderer.sharedMaterial); // on Object ID:" + GetInstanceID() + ". m_sharedMaterial: " + m_sharedMaterial.name + " m_renderer.sharedMaterial: " + m_renderer.sharedMaterial.name);
m_sharedMaterial = m_renderer.sharedMaterial;
}
m_padding = GetPaddingForMaterial();
//m_sharedMaterialHashCode = TMP_TextUtilities.GetSimpleHashCode(m_sharedMaterial.name);
UpdateMask();
UpdateEnvMapMatrix();
m_havePropertiesChanged = true;
SetVerticesDirty();
}
// Event received when font asset properties are changed in Font Inspector
void ON_FONT_PROPERTY_CHANGED(bool isChanged, TMP_FontAsset font)
{
if (MaterialReference.Contains(m_materialReferences, font))
{
//Debug.Log("ON_FONT_PROPERTY_CHANGED event received.");
m_isInputParsingRequired = true;
m_havePropertiesChanged = true;
SetMaterialDirty();
SetVerticesDirty();
}
}
// Event received when UNDO / REDO Event alters the properties of the object.
void ON_TEXTMESHPRO_PROPERTY_CHANGED(bool isChanged, TextMeshPro obj)
{
if (obj == this)
{
//Debug.Log("Undo / Redo Event Received by Object ID:" + GetInstanceID());
m_havePropertiesChanged = true;
m_isInputParsingRequired = true;
m_padding = GetPaddingForMaterial();
ComputeMarginSize();
SetVerticesDirty();
}
}
// Event to Track Material Changed resulting from Drag-n-drop.
void ON_DRAG_AND_DROP_MATERIAL(GameObject obj, Material currentMaterial, Material newMaterial)
{
//Debug.Log("Drag-n-Drop Event - Receiving Object ID " + GetInstanceID()); // + ". Target Object ID " + obj.GetInstanceID() + ". New Material is " + mat.name + " with ID " + mat.GetInstanceID() + ". Base Material is " + m_baseMaterial.name + " with ID " + m_baseMaterial.GetInstanceID());
// Check if event applies to this current object
#if UNITY_2018_2_OR_NEWER
if (obj == gameObject || UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(gameObject) == obj)
#else
if (obj == gameObject || UnityEditor.PrefabUtility.GetPrefabParent(gameObject) == obj)
#endif
{
UnityEditor.Undo.RecordObject(this, "Material Assignment");
UnityEditor.Undo.RecordObject(m_renderer, "Material Assignment");
m_sharedMaterial = newMaterial;
m_padding = GetPaddingForMaterial();
m_havePropertiesChanged = true;
SetVerticesDirty();
SetMaterialDirty();
}
}
// Event received when Text Styles are changed.
void ON_TEXT_STYLE_CHANGED(bool isChanged)
{
m_havePropertiesChanged = true;
m_isInputParsingRequired = true;
SetVerticesDirty();
}
/// <summary>
/// Event received when a Color Gradient Preset is modified.
/// </summary>
/// <param name="textObject"></param>
void ON_COLOR_GRADIENT_CHANGED(TMP_ColorGradient gradient)
{
if (m_fontColorGradientPreset != null && gradient.GetInstanceID() == m_fontColorGradientPreset.GetInstanceID())
{
m_havePropertiesChanged = true;
SetVerticesDirty();
}
}
/// <summary>
/// Event received when the TMP Settings are changed.
/// </summary>
void ON_TMP_SETTINGS_CHANGED()
{
m_defaultSpriteAsset = null;
m_havePropertiesChanged = true;
m_isInputParsingRequired = true;
SetAllDirty();
}
#endif
// Function which loads either the default font or a newly assigned font asset. This function also assigned the appropriate material to the renderer.
protected override void LoadFontAsset()
{
//Debug.Log("TextMeshPro LoadFontAsset() has been called."); // Current Font Asset is " + (font != null ? font.name: "Null") );
ShaderUtilities.GetShaderPropertyIDs(); // Initialize & Get shader property IDs.
if (m_fontAsset == null)
{
if (TMP_Settings.defaultFontAsset != null)
m_fontAsset =TMP_Settings.defaultFontAsset;
else
m_fontAsset = Resources.Load<TMP_FontAsset>("Fonts & Materials/LiberationSans SDF");
if (m_fontAsset == null)
{
Debug.LogWarning("The LiberationSans SDF Font Asset was not found. There is no Font Asset assigned to " + gameObject.name + ".", this);
return;
}
if (m_fontAsset.characterDictionary == null)
{
Debug.Log("Dictionary is Null!");
}
m_renderer.sharedMaterial = m_fontAsset.material;
m_sharedMaterial = m_fontAsset.material;
m_sharedMaterial.SetFloat("_CullMode", 0);
m_sharedMaterial.SetFloat(ShaderUtilities.ShaderTag_ZTestMode, 4);
m_renderer.receiveShadows = false;
m_renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; // true;
// Get a Reference to the Shader
}
else
{
if (m_fontAsset.characterDictionary == null)
{
//Debug.Log("Reading Font Definition and Creating Character Dictionary.");
m_fontAsset.ReadFontDefinition();
}
//Debug.Log("Font Asset name:" + font.material.name);
// If font atlas texture doesn't match the assigned material font atlas, switch back to default material specified in the Font Asset.
if (m_renderer.sharedMaterial == null || m_renderer.sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex) == null || m_fontAsset.atlas.GetInstanceID() != m_renderer.sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
{
m_renderer.sharedMaterial = m_fontAsset.material;
m_sharedMaterial = m_fontAsset.material;
}
else
{
m_sharedMaterial = m_renderer.sharedMaterial;
}
//m_sharedMaterial.SetFloat("_CullMode", 0);
m_sharedMaterial.SetFloat(ShaderUtilities.ShaderTag_ZTestMode, 4);
// Check if we are using the SDF Surface Shader
if (m_sharedMaterial.passCount == 1)
{
m_renderer.receiveShadows = false;
m_renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
}
}
m_padding = GetPaddingForMaterial();
//m_alignmentPadding = ShaderUtilities.GetFontExtent(m_sharedMaterial);
m_isMaskingEnabled = ShaderUtilities.IsMaskingEnabled(m_sharedMaterial);
// Find and cache Underline & Ellipsis characters.
GetSpecialCharacters(m_fontAsset);
//m_sharedMaterials.Add(m_sharedMaterial);
//m_sharedMaterialHashCode = TMP_TextUtilities.GetSimpleHashCode(m_sharedMaterial.name);
// Hide Material Editor Component
//m_renderer.sharedMaterial.hideFlags = HideFlags.None;
}
void UpdateEnvMapMatrix()
{
if (!m_sharedMaterial.HasProperty(ShaderUtilities.ID_EnvMap) || m_sharedMaterial.GetTexture(ShaderUtilities.ID_EnvMap) == null)
return;
//Debug.Log("Updating Env Matrix...");
Vector3 rotation = m_sharedMaterial.GetVector(ShaderUtilities.ID_EnvMatrixRotation);
m_EnvMapMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(rotation), Vector3.one);
m_sharedMaterial.SetMatrix(ShaderUtilities.ID_EnvMatrix, m_EnvMapMatrix);
}
//
void SetMask(MaskingTypes maskType)
{
switch(maskType)
{
case MaskingTypes.MaskOff:
m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_HARD);
m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_TEX);
break;
case MaskingTypes.MaskSoft:
m_sharedMaterial.EnableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_HARD);
m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_TEX);
break;
case MaskingTypes.MaskHard:
m_sharedMaterial.EnableKeyword(ShaderUtilities.Keyword_MASK_HARD);
m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_TEX);
break;
//case MaskingTypes.MaskTex:
// m_sharedMaterial.EnableKeyword(ShaderUtilities.Keyword_MASK_TEX);
// m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_HARD);
// m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
// break;
}
}
// Method used to set the masking coordinates
void SetMaskCoordinates(Vector4 coords)
{
m_sharedMaterial.SetVector(ShaderUtilities.ID_ClipRect, coords);
}
// Method used to set the masking coordinates
void SetMaskCoordinates(Vector4 coords, float softX, float softY)
{
m_sharedMaterial.SetVector(ShaderUtilities.ID_ClipRect, coords);
m_sharedMaterial.SetFloat(ShaderUtilities.ID_MaskSoftnessX, softX);
m_sharedMaterial.SetFloat(ShaderUtilities.ID_MaskSoftnessY, softY);
}
// Enable Masking in the Shader
void EnableMasking()
{
if (m_sharedMaterial.HasProperty(ShaderUtilities.ID_ClipRect))
{
m_sharedMaterial.EnableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_HARD);
m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_TEX);
m_isMaskingEnabled = true;
UpdateMask();
}
}
// Enable Masking in the Shader
void DisableMasking()
{
if (m_sharedMaterial.HasProperty(ShaderUtilities.ID_ClipRect))
{
m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_SOFT);
m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_HARD);
m_sharedMaterial.DisableKeyword(ShaderUtilities.Keyword_MASK_TEX);
m_isMaskingEnabled = false;
UpdateMask();
}
}
void UpdateMask()
{
//Debug.Log("UpdateMask() called.");
if (!m_isMaskingEnabled)
{
// Release Masking Material
// Re-assign Base Material
return;
}
if (m_isMaskingEnabled && m_fontMaterial == null)
{
CreateMaterialInstance();
}
/*
if (!m_isMaskingEnabled)
{
//Debug.Log("Masking is not enabled.");
if (m_maskingPropertyBlock != null)
{
m_renderer.SetPropertyBlock(null);
//havePropertiesChanged = true;
}
return;
}
//else
// Debug.Log("Updating Masking...");
*/
// Compute Masking Coordinates & Softness
//float softnessX = Mathf.Min(Mathf.Min(m_textContainer.margins.x, m_textContainer.margins.z), m_sharedMaterial.GetFloat(ShaderUtilities.ID_MaskSoftnessX));
//float softnessY = Mathf.Min(Mathf.Min(m_textContainer.margins.y, m_textContainer.margins.w), m_sharedMaterial.GetFloat(ShaderUtilities.ID_MaskSoftnessY));
//softnessX = softnessX > 0 ? softnessX : 0;
//softnessY = softnessY > 0 ? softnessY : 0;
//float width = (m_textContainer.width - Mathf.Max(m_textContainer.margins.x, 0) - Mathf.Max(m_textContainer.margins.z, 0)) / 2 + softnessX;
//float height = (m_textContainer.height - Mathf.Max(m_textContainer.margins.y, 0) - Mathf.Max(m_textContainer.margins.w, 0)) / 2 + softnessY;
//Vector2 center = new Vector2((0.5f - m_textContainer.pivot.x) * m_textContainer.width + (Mathf.Max(m_textContainer.margins.x, 0) - Mathf.Max(m_textContainer.margins.z, 0)) / 2, (0.5f - m_textContainer.pivot.y) * m_textContainer.height + (- Mathf.Max(m_textContainer.margins.y, 0) + Mathf.Max(m_textContainer.margins.w, 0)) / 2);
//Vector4 mask = new Vector4(center.x, center.y, width, height);
//m_fontMaterial.SetVector(ShaderUtilities.ID_ClipRect, mask);
//m_fontMaterial.SetFloat(ShaderUtilities.ID_MaskSoftnessX, softnessX);
//m_fontMaterial.SetFloat(ShaderUtilities.ID_MaskSoftnessY, softnessY);
/*
if(m_maskingPropertyBlock == null)
{
m_maskingPropertyBlock = new MaterialPropertyBlock();
//m_maskingPropertyBlock.AddFloat(ShaderUtilities.ID_VertexOffsetX, m_sharedMaterial.GetFloat(ShaderUtilities.ID_VertexOffsetX));
//m_maskingPropertyBlock.AddFloat(ShaderUtilities.ID_VertexOffsetY, m_sharedMaterial.GetFloat(ShaderUtilities.ID_VertexOffsetY));
//Debug.Log("Creating new MaterialPropertyBlock.");
}
//Debug.Log("Updating Material Property Block.");
//m_maskingPropertyBlock.Clear();
m_maskingPropertyBlock.AddFloat(ShaderUtilities.ID_MaskID, m_renderer.GetInstanceID());
m_maskingPropertyBlock.AddVector(ShaderUtilities.ID_MaskCoord, mask);
m_maskingPropertyBlock.AddFloat(ShaderUtilities.ID_MaskSoftnessX, softnessX);
m_maskingPropertyBlock.AddFloat(ShaderUtilities.ID_MaskSoftnessY, softnessY);
m_renderer.SetPropertyBlock(m_maskingPropertyBlock);
*/
}
// Function called internally when a new material is assigned via the fontMaterial property.
protected override Material GetMaterial(Material mat)
{
// Check in case Object is disabled. If so, we don't have a valid reference to the Renderer.
// This can occur when the Duplicate Material Context menu is used on an inactive object.
//if (m_renderer == null)
// m_renderer = GetComponent<Renderer>();
// Create Instance Material only if the new material is not the same instance previously used.
if (m_fontMaterial == null || m_fontMaterial.GetInstanceID() != mat.GetInstanceID())
m_fontMaterial = CreateMaterialInstance(mat);
m_sharedMaterial = m_fontMaterial;
m_padding = GetPaddingForMaterial();
SetVerticesDirty();
SetMaterialDirty();
return m_sharedMaterial;
}
/// <summary>
/// Method returning instances of the materials used by the text object.
/// </summary>
/// <returns></returns>
protected override Material[] GetMaterials(Material[] mats)
{
int materialCount = m_textInfo.materialCount;
if (m_fontMaterials == null)
m_fontMaterials = new Material[materialCount];
else if (m_fontMaterials.Length != materialCount)
TMP_TextInfo.Resize(ref m_fontMaterials, materialCount, false);
// Get instances of the materials
for (int i = 0; i < materialCount; i++)
{
if (i == 0)
m_fontMaterials[i] = fontMaterial;
else
m_fontMaterials[i] = m_subTextObjects[i].material;
}
m_fontSharedMaterials = m_fontMaterials;
return m_fontMaterials;
}
// Function called internally when a new shared material is assigned via the fontSharedMaterial property.
protected override void SetSharedMaterial(Material mat)
{
// Check in case Object is disabled. If so, we don't have a valid reference to the Renderer.
// This can occur when the Duplicate Material Context menu is used on an inactive object.
//if (m_renderer == null)
// m_renderer = GetComponent<Renderer>();
m_sharedMaterial = mat;
m_padding = GetPaddingForMaterial();
SetMaterialDirty();
}
/// <summary>
/// Method returning an array containing the materials used by the text object.
/// </summary>
/// <returns></returns>
protected override Material[] GetSharedMaterials()
{
int materialCount = m_textInfo.materialCount;
if (m_fontSharedMaterials == null)
m_fontSharedMaterials = new Material[materialCount];
else if (m_fontSharedMaterials.Length != materialCount)
TMP_TextInfo.Resize(ref m_fontSharedMaterials, materialCount, false);
for (int i = 0; i < materialCount; i++)
{
if (i == 0)
m_fontSharedMaterials[i] = m_sharedMaterial;
else
m_fontSharedMaterials[i] = m_subTextObjects[i].sharedMaterial;
}
return m_fontSharedMaterials;
}
/// <summary>
/// Method used to assign new materials to the text and sub text objects.
/// </summary>
protected override void SetSharedMaterials(Material[] materials)
{
int materialCount = m_textInfo.materialCount;
// Check allocation of the fontSharedMaterials array.
if (m_fontSharedMaterials == null)
m_fontSharedMaterials = new Material[materialCount];
else if (m_fontSharedMaterials.Length != materialCount)
TMP_TextInfo.Resize(ref m_fontSharedMaterials, materialCount, false);
// Only assign as many materials as the text object contains.
for (int i = 0; i < materialCount; i++)
{
Texture mat_MainTex = materials[i].GetTexture(ShaderUtilities.ID_MainTex);
if (i == 0)
{
// Only assign new material if the font atlas textures match.
if ( mat_MainTex == null || mat_MainTex.GetInstanceID() != m_sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
continue;
m_sharedMaterial = m_fontSharedMaterials[i] = materials[i];
m_padding = GetPaddingForMaterial(m_sharedMaterial);
}
else
{
// Only assign new material if the font atlas textures match.
if (mat_MainTex == null || mat_MainTex.GetInstanceID() != m_subTextObjects[i].sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
continue;
// Only assign a new material if none were specified in the text input.
if (m_subTextObjects[i].isDefaultMaterial)
m_subTextObjects[i].sharedMaterial = m_fontSharedMaterials[i] = materials[i];
}
}
}
// This function will create an instance of the Font Material.
protected override void SetOutlineThickness(float thickness)
{
thickness = Mathf.Clamp01(thickness);
m_renderer.material.SetFloat(ShaderUtilities.ID_OutlineWidth, thickness);
if (m_fontMaterial == null)
m_fontMaterial = m_renderer.material;
m_fontMaterial = m_renderer.material;
m_sharedMaterial = m_fontMaterial;
m_padding = GetPaddingForMaterial();
}
// This function will create an instance of the Font Material.
protected override void SetFaceColor(Color32 color)
{
m_renderer.material.SetColor(ShaderUtilities.ID_FaceColor, color);
if (m_fontMaterial == null)
m_fontMaterial = m_renderer.material;
m_sharedMaterial = m_fontMaterial;
}
// This function will create an instance of the Font Material.
protected override void SetOutlineColor(Color32 color)
{
m_renderer.material.SetColor(ShaderUtilities.ID_OutlineColor, color);
if (m_fontMaterial == null)
m_fontMaterial = m_renderer.material;
//Debug.Log("Material ID:" + m_fontMaterial.GetInstanceID());
m_sharedMaterial = m_fontMaterial;
}
// Function used to create an instance of the material
void CreateMaterialInstance()
{
Material mat = new Material(m_sharedMaterial);
mat.shaderKeywords = m_sharedMaterial.shaderKeywords;
//mat.hideFlags = HideFlags.DontSave;
mat.name += " Instance";
//m_uiRenderer.SetMaterial(mat, null);
m_fontMaterial = mat;
}
// Sets the Render Queue and Ztest mode
protected override void SetShaderDepth()
{
if (m_isOverlay)
{
// Changing these properties results in an instance of the material
m_sharedMaterial.SetFloat(ShaderUtilities.ShaderTag_ZTestMode, 0);
//m_renderer.material.SetFloat("_ZTestMode", 8);
m_renderer.material.renderQueue = 4000;
m_sharedMaterial = m_renderer.material;
//Debug.Log("Text set to Overlay mode.");
}
else
{
// Should this use an instanced material?
m_sharedMaterial.SetFloat(ShaderUtilities.ShaderTag_ZTestMode, 4);
m_renderer.material.renderQueue = -1;
m_sharedMaterial = m_renderer.material;
//Debug.Log("Text set to Normal mode.");
}
}
// Sets the Culling mode of the material
protected override void SetCulling()
{
if (m_isCullingEnabled)
{
m_renderer.material.SetFloat("_CullMode", 2);
for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
{
Renderer renderer = m_subTextObjects[i].renderer;
if (renderer != null)
{
renderer.material.SetFloat(ShaderUtilities.ShaderTag_CullMode, 2);
}
}
}
else
{
m_renderer.material.SetFloat("_CullMode", 0);
for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
{
Renderer renderer = m_subTextObjects[i].renderer;
if (renderer != null)
{
renderer.material.SetFloat(ShaderUtilities.ShaderTag_CullMode, 0);
}
}
}
}
// Set Perspective Correction Mode based on whether Camera is Orthographic or Perspective
void SetPerspectiveCorrection()
{
if (m_isOrthographic)
m_sharedMaterial.SetFloat(ShaderUtilities.ID_PerspectiveFilter, 0.0f);
else
m_sharedMaterial.SetFloat(ShaderUtilities.ID_PerspectiveFilter, 0.875f);
}
/// <summary>
/// Get the padding value for the currently assigned material.
/// </summary>
/// <returns></returns>
protected override float GetPaddingForMaterial(Material mat)
{
m_padding = ShaderUtilities.GetPadding(mat, m_enableExtraPadding, m_isUsingBold);
m_isMaskingEnabled = ShaderUtilities.IsMaskingEnabled(m_sharedMaterial);
m_isSDFShader = mat.HasProperty(ShaderUtilities.ID_WeightNormal);
return m_padding;
}
/// <summary>
/// Get the padding value for the currently assigned material.
/// </summary>
/// <returns></returns>
protected override float GetPaddingForMaterial()
{
ShaderUtilities.GetShaderPropertyIDs();
if (m_sharedMaterial == null) return 0;
m_padding = ShaderUtilities.GetPadding(m_sharedMaterial, m_enableExtraPadding, m_isUsingBold);
m_isMaskingEnabled = ShaderUtilities.IsMaskingEnabled(m_sharedMaterial);
m_isSDFShader = m_sharedMaterial.HasProperty(ShaderUtilities.ID_WeightNormal);
return m_padding;
}
// This function parses through the Char[] to determine how many characters will be visible. It then makes sure the arrays are large enough for all those characters.
protected override int SetArraySizes(int[] chars)
{
//Debug.Log("*** SetArraySizes() ***");
int tagEnd = 0;
int spriteCount = 0;
m_totalCharacterCount = 0;
m_isUsingBold = false;
m_isParsingText = false;
tag_NoParsing = false;
m_style = m_fontStyle;
m_fontWeightInternal = (m_style & FontStyles.Bold) == FontStyles.Bold ? 700 : m_fontWeight;
m_fontWeightStack.SetDefault(m_fontWeightInternal);
m_currentFontAsset = m_fontAsset;
m_currentMaterial = m_sharedMaterial;
m_currentMaterialIndex = 0;
m_materialReferenceStack.SetDefault(new MaterialReference(m_currentMaterialIndex, m_currentFontAsset, null, m_currentMaterial, m_padding));
m_materialReferenceIndexLookup.Clear();
MaterialReference.AddMaterialReference(m_currentMaterial, m_currentFontAsset, m_materialReferences, m_materialReferenceIndexLookup);
if (m_textInfo == null) m_textInfo = new TMP_TextInfo();
m_textElementType = TMP_TextElementType.Character;
// Clear Linked Text object if we have one.
if (m_linkedTextComponent != null)
{
m_linkedTextComponent.text = string.Empty;
m_linkedTextComponent.ForceMeshUpdate();
}
// Parsing XML tags in the text
for (int i = 0; i < chars.Length && chars[i] != 0; i++)
{
//Make sure the characterInfo array can hold the next text element.
if (m_textInfo.characterInfo == null || m_totalCharacterCount >= m_textInfo.characterInfo.Length)
TMP_TextInfo.Resize(ref m_textInfo.characterInfo, m_totalCharacterCount + 1, true);
int c = chars[i];
// PARSE XML TAGS
#region PARSE XML TAGS
if (m_isRichText && c == 60) // if Char '<'
{
int prev_MaterialIndex = m_currentMaterialIndex;
// Check if Tag is Valid
if (ValidateHtmlTag(chars, i + 1, out tagEnd))
{
i = tagEnd;
if ((m_style & FontStyles.Bold) == FontStyles.Bold) m_isUsingBold = true;
if (m_textElementType == TMP_TextElementType.Sprite)
{
m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
m_textInfo.characterInfo[m_totalCharacterCount].character = (char)(57344 + m_spriteIndex);
m_textInfo.characterInfo[m_totalCharacterCount].spriteIndex = m_spriteIndex;
m_textInfo.characterInfo[m_totalCharacterCount].fontAsset = m_currentFontAsset;
m_textInfo.characterInfo[m_totalCharacterCount].spriteAsset = m_currentSpriteAsset;
m_textInfo.characterInfo[m_totalCharacterCount].materialReferenceIndex = m_currentMaterialIndex;
m_textInfo.characterInfo[m_totalCharacterCount].elementType = m_textElementType;
// Restore element type and material index to previous values.
m_textElementType = TMP_TextElementType.Character;
m_currentMaterialIndex = prev_MaterialIndex;
spriteCount += 1;
m_totalCharacterCount += 1;
}
continue;
}
}
#endregion
bool isUsingFallback = false;
bool isUsingAlternativeTypeface = false;
TMP_Glyph glyph;
TMP_FontAsset tempFontAsset;
TMP_FontAsset prev_fontAsset = m_currentFontAsset;
Material prev_material = m_currentMaterial;
int prev_materialIndex = m_currentMaterialIndex;
// Handle Font Styles like LowerCase, UpperCase and SmallCaps.
#region Handling of LowerCase, UpperCase and SmallCaps Font Styles
if (m_textElementType == TMP_TextElementType.Character)
{
if ((m_style & FontStyles.UpperCase) == FontStyles.UpperCase)
{
// If this character is lowercase, switch to uppercase.
if (char.IsLower((char)c))
c = char.ToUpper((char)c);
}
else if ((m_style & FontStyles.LowerCase) == FontStyles.LowerCase)
{
// If this character is uppercase, switch to lowercase.
if (char.IsUpper((char)c))
c = char.ToLower((char)c);
}
else if ((m_fontStyle & FontStyles.SmallCaps) == FontStyles.SmallCaps || (m_style & FontStyles.SmallCaps) == FontStyles.SmallCaps)
{
// Only convert lowercase characters to uppercase.
if (char.IsLower((char)c))
c = char.ToUpper((char)c);
}
}
#endregion
// Handling of font weights.
#region HANDLING OF FONT WEIGHT
tempFontAsset = GetFontAssetForWeight(m_fontWeightInternal);
if (tempFontAsset != null)
{
isUsingFallback = true;
isUsingAlternativeTypeface = true;
m_currentFontAsset = tempFontAsset;
//m_currentMaterialIndex = MaterialReference.AddMaterialReference(m_currentMaterial, tempFontAsset, m_materialReferences, m_materialReferenceIndexLookup);
}
#endregion
// Lookup the Glyph data for each character and cache it.
#region LOOKUP GLYPH
tempFontAsset = TMP_FontUtilities.SearchForGlyph(m_currentFontAsset, c, out glyph);
// Search for the glyph in the Sprite Asset assigned to the text object.
if (glyph == null)
{
TMP_SpriteAsset spriteAsset = this.spriteAsset;
if (spriteAsset != null)
{
int spriteIndex = -1;
// Check Default Sprite Asset and its Fallbacks
spriteAsset = TMP_SpriteAsset.SearchForSpriteByUnicode(spriteAsset, c, true, out spriteIndex);
if (spriteIndex != -1)
{
m_textElementType = TMP_TextElementType.Sprite;
m_textInfo.characterInfo[m_totalCharacterCount].elementType = m_textElementType;
m_currentMaterialIndex = MaterialReference.AddMaterialReference(spriteAsset.material, spriteAsset, m_materialReferences, m_materialReferenceIndexLookup);
m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
m_textInfo.characterInfo[m_totalCharacterCount].character = (char)c;
m_textInfo.characterInfo[m_totalCharacterCount].spriteIndex = spriteIndex;
m_textInfo.characterInfo[m_totalCharacterCount].fontAsset = m_currentFontAsset;
m_textInfo.characterInfo[m_totalCharacterCount].spriteAsset = spriteAsset;
m_textInfo.characterInfo[m_totalCharacterCount].materialReferenceIndex = m_currentMaterialIndex;
// Restore element type and material index to previous values.
m_textElementType = TMP_TextElementType.Character;
m_currentMaterialIndex = prev_materialIndex;
spriteCount += 1;
m_totalCharacterCount += 1;
continue;
}
}
}
// Search for the glyph in the list of fallback assigned in the TMP Settings (General Fallbacks).
if (glyph == null)
{
if (TMP_Settings.fallbackFontAssets != null && TMP_Settings.fallbackFontAssets.Count > 0)
tempFontAsset = TMP_FontUtilities.SearchForGlyph(TMP_Settings.fallbackFontAssets, c, out glyph);
}
// Search for the glyph in the Default Font Asset assigned in the TMP Settings file.
if (glyph == null)
{
if (TMP_Settings.defaultFontAsset != null)
tempFontAsset = TMP_FontUtilities.SearchForGlyph(TMP_Settings.defaultFontAsset, c, out glyph);
}
// TODO: Add support for using Sprite Assets like a special Emoji only Sprite Asset when UTF16 or UTF32 glyphs are requested.
// This would kind of mirror native Emoji support.
if (glyph == null)
{
TMP_SpriteAsset spriteAsset = TMP_Settings.defaultSpriteAsset;
if (spriteAsset != null)
{
int spriteIndex = -1;
// Check Default Sprite Asset and its Fallbacks
spriteAsset = TMP_SpriteAsset.SearchForSpriteByUnicode(spriteAsset, c, true, out spriteIndex);
if (spriteIndex != -1)
{
m_textElementType = TMP_TextElementType.Sprite;
m_textInfo.characterInfo[m_totalCharacterCount].elementType = m_textElementType;
m_currentMaterialIndex = MaterialReference.AddMaterialReference(spriteAsset.material, spriteAsset, m_materialReferences, m_materialReferenceIndexLookup);
m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
m_textInfo.characterInfo[m_totalCharacterCount].character = (char)c;
m_textInfo.characterInfo[m_totalCharacterCount].spriteIndex = spriteIndex;
m_textInfo.characterInfo[m_totalCharacterCount].fontAsset = m_currentFontAsset;
m_textInfo.characterInfo[m_totalCharacterCount].spriteAsset = spriteAsset;
m_textInfo.characterInfo[m_totalCharacterCount].materialReferenceIndex = m_currentMaterialIndex;
// Restore element type and material index to previous values.
m_textElementType = TMP_TextElementType.Character;
m_currentMaterialIndex = prev_materialIndex;
spriteCount += 1;
m_totalCharacterCount += 1;
continue;
}
}
}
//Check if Lowercase or Uppercase variant of the character is available.
// Not sure this is necessary anyone as it is very unlikely with recursive search through fallback fonts.
//if (glyph == null)
//{
// if (char.IsLower((char)c))
// {
// if (m_currentFontAsset.characterDictionary.TryGetValue(char.ToUpper((char)c), out glyph))
// c = chars[i] = char.ToUpper((char)c);
// }
// else if (char.IsUpper((char)c))
// {
// if (m_currentFontAsset.characterDictionary.TryGetValue(char.ToLower((char)c), out glyph))
// c = chars[i] = char.ToLower((char)c);
// }
//}
// Replace missing glyph by the Square (9633) glyph or possibly the Space (32) glyph.
if (glyph == null)
{
// Save the original unicode character
int srcGlyph = c;
// Try replacing the missing glyph character by TMP Settings Missing Glyph or Square (9633) character.
c = chars[i] = TMP_Settings.missingGlyphCharacter == 0 ? 9633 : TMP_Settings.missingGlyphCharacter;
// Check for the missing glyph character in the currently assigned font asset.
tempFontAsset = TMP_FontUtilities.SearchForGlyph(m_currentFontAsset, c, out glyph);
if (glyph == null)
{
// Search for the missing glyph character in the TMP Settings Fallback list.
if (TMP_Settings.fallbackFontAssets != null && TMP_Settings.fallbackFontAssets.Count > 0)
tempFontAsset = TMP_FontUtilities.SearchForGlyph(TMP_Settings.fallbackFontAssets, c, out glyph);
}
if (glyph == null)
{
// Search for the missing glyph in the TMP Settings Default Font Asset.
if (TMP_Settings.defaultFontAsset != null)
tempFontAsset = TMP_FontUtilities.SearchForGlyph(TMP_Settings.defaultFontAsset, c, out glyph);
}
if (glyph == null)
{
// Use Space (32) Glyph from the currently assigned font asset.
c = chars[i] = 32;
tempFontAsset = TMP_FontUtilities.SearchForGlyph(m_currentFontAsset, c, out glyph);
if (!TMP_Settings.warningsDisabled) Debug.LogWarning("Character with ASCII value of " + srcGlyph + " was not found in the Font Asset Glyph Table. It was replaced by a space.", this);
}
}
// Determine if the font asset is still the current font asset or a fallback.
if (tempFontAsset != null)
{
if (tempFontAsset.GetInstanceID() != m_currentFontAsset.GetInstanceID())
{
isUsingFallback = true;
isUsingAlternativeTypeface = false;
m_currentFontAsset = tempFontAsset;
}
}
#endregion
m_textInfo.characterInfo[m_totalCharacterCount].elementType = TMP_TextElementType.Character;
m_textInfo.characterInfo[m_totalCharacterCount].textElement = glyph;
m_textInfo.characterInfo[m_totalCharacterCount].isUsingAlternateTypeface = isUsingAlternativeTypeface;
m_textInfo.characterInfo[m_totalCharacterCount].character = (char)c;
m_textInfo.characterInfo[m_totalCharacterCount].fontAsset = m_currentFontAsset;
if (isUsingFallback)
{
// Create Fallback material instance matching current material preset if necessary
if (TMP_Settings.matchMaterialPreset)
m_currentMaterial = TMP_MaterialManager.GetFallbackMaterial(m_currentMaterial, m_currentFontAsset.material);
else
m_currentMaterial = m_currentFontAsset.material;
m_currentMaterialIndex = MaterialReference.AddMaterialReference(m_currentMaterial, m_currentFontAsset, m_materialReferences, m_materialReferenceIndexLookup);
}
if (!char.IsWhiteSpace((char)c) && c != 0x200B)
{
// Limit the mesh of the main text object to 65535 vertices and use sub objects for the overflow.
if (m_materialReferences[m_currentMaterialIndex].referenceCount < 16383)
m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
else
{
m_currentMaterialIndex = MaterialReference.AddMaterialReference(new Material(m_currentMaterial), m_currentFontAsset, m_materialReferences, m_materialReferenceIndexLookup);
m_materialReferences[m_currentMaterialIndex].referenceCount += 1;
}
}
m_textInfo.characterInfo[m_totalCharacterCount].material = m_currentMaterial;
m_textInfo.characterInfo[m_totalCharacterCount].materialReferenceIndex = m_currentMaterialIndex;
m_materialReferences[m_currentMaterialIndex].isFallbackMaterial = isUsingFallback;
// Restore previous font asset and material if fallback font was used.
if (isUsingFallback)
{
m_materialReferences[m_currentMaterialIndex].fallbackMaterial = prev_material;
m_currentFontAsset = prev_fontAsset;
m_currentMaterial = prev_material;
m_currentMaterialIndex = prev_materialIndex;
}
m_totalCharacterCount += 1;
}
// Early return if we are calculating the preferred values.
if (m_isCalculatingPreferredValues)
{
m_isCalculatingPreferredValues = false;
m_isInputParsingRequired = true;
return m_totalCharacterCount;
}
// Save material and sprite count.
m_textInfo.spriteCount = spriteCount;
int materialCount = m_textInfo.materialCount = m_materialReferenceIndexLookup.Count;
// Check if we need to resize the MeshInfo array for handling different materials.
if (materialCount > m_textInfo.meshInfo.Length)
TMP_TextInfo.Resize(ref m_textInfo.meshInfo, materialCount, false);
// Resize SubTextObject array if necessary
if (materialCount > m_subTextObjects.Length)
TMP_TextInfo.Resize(ref m_subTextObjects, Mathf.NextPowerOfTwo(materialCount + 1));
// Resize CharacterInfo[] if allocations are excessive
if (m_textInfo.characterInfo.Length - m_totalCharacterCount > 256)
TMP_TextInfo.Resize(ref m_textInfo.characterInfo, Mathf.Max(m_totalCharacterCount + 1, 256), true);
// Iterate through the material references to set the mesh buffer allocations
for (int i = 0; i < materialCount; i++)
{
// Add new sub text object for each material reference
if (i > 0)
{
if (m_subTextObjects[i] == null)
{
m_subTextObjects[i] = TMP_SubMesh.AddSubTextObject(this, m_materialReferences[i]);
// Not sure this is necessary
m_textInfo.meshInfo[i].vertices = null;
}
//else if (m_subTextObjects[i].gameObject.activeInHierarchy == false)
// m_subTextObjects[i].gameObject.SetActive(true);
// Check if the material has changed.
if (m_subTextObjects[i].sharedMaterial == null || m_subTextObjects[i].sharedMaterial.GetInstanceID() != m_materialReferences[i].material.GetInstanceID())
{
bool isDefaultMaterial = m_materialReferences[i].isDefaultMaterial;
m_subTextObjects[i].isDefaultMaterial = isDefaultMaterial;
// Assign new material if we are not using the default material or if the font asset has changed.
if (!isDefaultMaterial || m_subTextObjects[i].sharedMaterial == null || m_subTextObjects[i].sharedMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() != m_materialReferences[i].material.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
{
m_subTextObjects[i].sharedMaterial = m_materialReferences[i].material;
m_subTextObjects[i].fontAsset = m_materialReferences[i].fontAsset;
m_subTextObjects[i].spriteAsset = m_materialReferences[i].spriteAsset;
}
}
// Check if we need to use a Fallback Material
if (m_materialReferences[i].isFallbackMaterial)
{
m_subTextObjects[i].fallbackMaterial = m_materialReferences[i].material;
m_subTextObjects[i].fallbackSourceMaterial = m_materialReferences[i].fallbackMaterial;
}
}
int referenceCount = m_materialReferences[i].referenceCount;
// Check to make sure our buffers allocations can accommodate the required text elements.
if (m_textInfo.meshInfo[i].vertices == null || m_textInfo.meshInfo[i].vertices.Length < referenceCount * (!m_isVolumetricText ? 4 : 8))
{
if (m_textInfo.meshInfo[i].vertices == null)
{
if (i == 0)
m_textInfo.meshInfo[i] = new TMP_MeshInfo(m_mesh, referenceCount + 1, m_isVolumetricText);
else
m_textInfo.meshInfo[i] = new TMP_MeshInfo(m_subTextObjects[i].mesh, referenceCount + 1, m_isVolumetricText);
}
else
m_textInfo.meshInfo[i].ResizeMeshInfo(referenceCount > 1024 ? referenceCount + 256 : Mathf.NextPowerOfTwo(referenceCount), m_isVolumetricText);
}
else if (m_textInfo.meshInfo[i].vertices.Length - referenceCount * (!m_isVolumetricText ? 4 : 8) > 1024)
{
// Resize vertex buffers if allocations are excessive.
//Debug.Log("Reducing the size of the vertex buffers.");
m_textInfo.meshInfo[i].ResizeMeshInfo(referenceCount > 1024 ? referenceCount + 256 : Mathf.Max(Mathf.NextPowerOfTwo(referenceCount), 256), m_isVolumetricText);
}
}
//TMP_MaterialManager.CleanupFallbackMaterials();
// Clean up unused SubMeshes
for (int i = materialCount; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
{
if (i < m_textInfo.meshInfo.Length)
m_textInfo.meshInfo[i].ClearUnusedVertices(0, true);
//m_subTextObjects[i].gameObject.SetActive(false);
}
return m_totalCharacterCount;
}
// Added to sort handle the potential issue with OnWillRenderObject() not getting called when objects are not visible by camera.
//void OnBecameInvisible()
//{
// if (m_mesh != null)
// m_mesh.bounds = new Bounds(transform.position, new Vector3(1000, 1000, 0));
//}
/// <summary>
/// Update the margin width and height
/// </summary>
public override void ComputeMarginSize()
{
if (this.rectTransform != null)
{
//Debug.Log("*** ComputeMarginSize() *** Current RectTransform's Width is " + m_rectTransform.rect.width + " and Height is " + m_rectTransform.rect.height); // + " and size delta is " + m_rectTransform.sizeDelta);
m_marginWidth = m_rectTransform.rect.width - m_margin.x - m_margin.z;
m_marginHeight = m_rectTransform.rect.height - m_margin.y - m_margin.w;
// Update the corners of the RectTransform
m_RectTransformCorners = GetTextContainerLocalCorners();
}
}
protected override void OnDidApplyAnimationProperties()
{
//Debug.Log("*** OnDidApplyAnimationProperties() ***");
m_havePropertiesChanged = true;
isMaskUpdateRequired = true;
SetVerticesDirty();
}
protected override void OnTransformParentChanged()
{
//Debug.Log("*** OnTransformParentChanged() ***");
SetVerticesDirty();
SetLayoutDirty();
}
protected override void OnRectTransformDimensionsChange()
{
//Debug.Log("*** OnRectTransformDimensionsChange() ***");
ComputeMarginSize();
SetVerticesDirty();
SetLayoutDirty();
}
/// <summary>
/// Unity standard function used to check if the transform or scale of the text object has changed.
/// </summary>
void LateUpdate()
{
// TODO : Review this
if (m_rectTransform.hasChanged)
{
// We need to update the SDF scale or possibly regenerate the text object if lossy scale has changed.
float lossyScaleY = m_rectTransform.lossyScale.y;
if (!m_havePropertiesChanged && lossyScaleY != m_previousLossyScaleY && m_text != string.Empty && m_text != null)
{
UpdateSDFScale(lossyScaleY);
m_previousLossyScaleY = lossyScaleY;
}
}
// Added to handle legacy animation mode.
if (m_isUsingLegacyAnimationComponent)
{
//if (m_havePropertiesChanged)
m_havePropertiesChanged = true;
OnPreRenderObject();
}
}
/// <summary>
/// Function called when the text needs to be updated.
/// </summary>
void OnPreRenderObject()
{
//Debug.Log("*** OnPreRenderObject() ***");
if (!m_isAwake || (this.IsActive() == false && m_ignoreActiveState == false)) return;
// Debug Variables
loopCountA = 0;
//loopCountB = 0;
//loopCountC = 0;
//loopCountD = 0;
//loopCountE = 0;
if (m_havePropertiesChanged || m_isLayoutDirty)
{
//Debug.Log("Properties have changed!"); // Assigned Material is:" + m_sharedMaterial); // New Text is: " + m_text + ".");
if (isMaskUpdateRequired)
{
UpdateMask();
isMaskUpdateRequired = false;
}
// Update mesh padding if necessary.
if (checkPaddingRequired)
UpdateMeshPadding();
// Reparse the text if the input has changed or text was truncated.
if (m_isInputParsingRequired || m_isTextTruncated)
ParseInputText();
// Reset Font min / max used with Auto-sizing
if (m_enableAutoSizing)
m_fontSize = Mathf.Clamp(m_fontSizeBase, m_fontSizeMin, m_fontSizeMax);
m_maxFontSize = m_fontSizeMax;
m_minFontSize = m_fontSizeMin;
m_lineSpacingDelta = 0;
m_charWidthAdjDelta = 0;
//m_recursiveCount = 0;
m_isCharacterWrappingEnabled = false;
m_isTextTruncated = false;
m_havePropertiesChanged = false;
m_isLayoutDirty = false;
m_ignoreActiveState = false;
GenerateTextMesh();
}
}
/// <summary>
/// This is the main function that is responsible for creating / displaying the text.
/// </summary>
protected override void GenerateTextMesh()
{
//Debug.Log("***** GenerateTextMesh() *****"); // ***** Frame: " + Time.frameCount); // + ". Point Size: " + m_fontSize + ". Margins are (W) " + m_marginWidth + " (H) " + m_marginHeight); // ". Iteration Count: " + loopCountA + ". Min: " + m_minFontSize + " Max: " + m_maxFontSize + " Delta: " + (m_maxFontSize - m_minFontSize) + " Font size is " + m_fontSize); //called for Object with ID " + GetInstanceID()); // Assigned Material is " + m_uiRenderer.GetMaterial().name); // IncludeForMasking " + this.m_IncludeForMasking); // and text is " + m_text);
// Early exit if no font asset was assigned. This should not be needed since LiberationSans SDF will be assigned by default.
if (m_fontAsset == null || m_fontAsset.characterDictionary == null)
{
Debug.LogWarning("Can't Generate Mesh! No Font Asset has been assigned to Object ID: " + this.GetInstanceID());
return;
}
// Clear TextInfo
if (m_textInfo != null)
m_textInfo.Clear();
// Early exit if we don't have any Text to generate.
if (m_char_buffer == null || m_char_buffer.Length == 0 || m_char_buffer[0] == (char)0)
{
// Clear mesh and upload changes to the mesh.
ClearMesh(true);
m_preferredWidth = 0;
m_preferredHeight = 0;
// Event indicating the text has been regenerated.
TMPro_EventManager.ON_TEXT_CHANGED(this);
return;
}
m_currentFontAsset = m_fontAsset;
m_currentMaterial = m_sharedMaterial;
m_currentMaterialIndex = 0;
m_materialReferenceStack.SetDefault(new MaterialReference(m_currentMaterialIndex, m_currentFontAsset, null, m_currentMaterial, m_padding));
m_currentSpriteAsset = m_spriteAsset;
// Stop all Sprite Animations
if (m_spriteAnimator != null)
m_spriteAnimator.StopAllAnimations();
// Total character count is computed when the text is parsed.
int totalCharacterCount = m_totalCharacterCount;
// Calculate the scale of the font based on selected font size and sampling point size.
// baseScale is calculated using the font asset assigned to the text object.
float baseScale = m_fontScale = (m_fontSize / m_fontAsset.fontInfo.PointSize * m_fontAsset.fontInfo.Scale * (m_isOrthographic ? 1 : 0.1f));
float currentElementScale = baseScale;
m_fontScaleMultiplier = 1;
m_currentFontSize = m_fontSize;
m_sizeStack.SetDefault(m_currentFontSize);
float fontSizeDelta = 0;
int charCode = 0; // Holds the character code of the currently being processed character.
m_style = m_fontStyle; // Set the default style.
m_fontWeightInternal = (m_style & FontStyles.Bold) == FontStyles.Bold ? 700 : m_fontWeight;
m_fontWeightStack.SetDefault(m_fontWeightInternal);
m_fontStyleStack.Clear();
m_lineJustification = m_textAlignment; // Sets the line justification mode to match editor alignment.
m_lineJustificationStack.SetDefault(m_lineJustification);
float padding = 0;
float style_padding = 0; // Extra padding required to accommodate Bold style.
float bold_xAdvance_multiplier = 1; // Used to increase spacing between character when style is bold.
m_baselineOffset = 0; // Used by subscript characters.
m_baselineOffsetStack.Clear();
// Underline
bool beginUnderline = false;
Vector3 underline_start = Vector3.zero; // Used to track where underline starts & ends.
Vector3 underline_end = Vector3.zero;
// Strike-through
bool beginStrikethrough = false;
Vector3 strikethrough_start = Vector3.zero;
Vector3 strikethrough_end = Vector3.zero;
// Text Highlight
bool beginHighlight = false;
Vector3 highlight_start = Vector3.zero;
Vector3 highlight_end = Vector3.zero;
m_fontColor32 = m_fontColor;
Color32 vertexColor;
m_htmlColor = m_fontColor32;
m_underlineColor = m_htmlColor;
m_strikethroughColor = m_htmlColor;
m_colorStack.SetDefault(m_htmlColor);
m_underlineColorStack.SetDefault(m_htmlColor);
m_strikethroughColorStack.SetDefault(m_htmlColor);
m_highlightColorStack.SetDefault(m_htmlColor);
m_colorGradientPreset = null;
m_colorGradientStack.SetDefault(null);
// Clear the Style stack.
//m_styleStack.Clear();
// Clear the Action stack.
m_actionStack.Clear();
m_isFXMatrixSet = false;
m_lineOffset = 0; // Amount of space between lines (font line spacing + m_linespacing).
m_lineHeight = TMP_Math.FLOAT_UNSET;
float lineGap = m_currentFontAsset.fontInfo.LineHeight - (m_currentFontAsset.fontInfo.Ascender - m_currentFontAsset.fontInfo.Descender);
m_cSpacing = 0; // Amount of space added between characters as a result of the use of the <cspace> tag.
m_monoSpacing = 0;
float lineOffsetDelta = 0;
m_xAdvance = 0; // Used to track the position of each character.
tag_LineIndent = 0; // Used for indentation of text.
tag_Indent = 0;
m_indentStack.SetDefault(0);
tag_NoParsing = false;
//m_isIgnoringAlignment = false;
m_characterCount = 0; // Total characters in the char[]
// Tracking of line information
m_firstCharacterOfLine = 0;
m_lastCharacterOfLine = 0;
m_firstVisibleCharacterOfLine = 0;
m_lastVisibleCharacterOfLine = 0;
m_maxLineAscender = k_LargeNegativeFloat;
m_maxLineDescender = k_LargePositiveFloat;
m_lineNumber = 0;
m_lineVisibleCharacterCount = 0;
bool isStartOfNewLine = true;
m_firstOverflowCharacterIndex = -1;
m_pageNumber = 0;
int pageToDisplay = Mathf.Clamp(m_pageToDisplay - 1, 0, m_textInfo.pageInfo.Length - 1);
int previousPageOverflowChar = 0;
int ellipsisIndex = 0;
Vector4 margins = m_margin;
float marginWidth = m_marginWidth;
float marginHeight = m_marginHeight;
m_marginLeft = 0;
m_marginRight = 0;
m_width = -1;
float width = marginWidth + 0.0001f - m_marginLeft - m_marginRight;
// Need to initialize these Extents structures
m_meshExtents.min = k_LargePositiveVector2;
m_meshExtents.max = k_LargeNegativeVector2;
// Initialize lineInfo
m_textInfo.ClearLineInfo();
// Tracking of the highest Ascender
m_maxCapHeight = 0;
m_maxAscender = 0;
m_maxDescender = 0;
float pageAscender = 0;
float maxVisibleDescender = 0;
bool isMaxVisibleDescenderSet = false;
m_isNewPage = false;
// Initialize struct to track states of word wrapping
bool isFirstWord = true;
m_isNonBreakingSpace = false;
bool ignoreNonBreakingSpace = false;
bool isLastBreakingChar = false;
float linebreakingWidth = 0;
int wrappingIndex = 0;
// Save character and line state before we begin layout.
SaveWordWrappingState(ref m_SavedWordWrapState, -1, -1);
SaveWordWrappingState(ref m_SavedLineState, -1, -1);
loopCountA += 1;
int endTagIndex = 0;
// Parse through Character buffer to read HTML tags and begin creating mesh.
for (int i = 0; i < m_char_buffer.Length && m_char_buffer[i] != 0; i++)
{
charCode = m_char_buffer[i];
// Parse Rich Text Tag
#region Parse Rich Text Tag
if (m_isRichText && charCode == 60) // '<'
{
m_isParsingText = true;
m_textElementType = TMP_TextElementType.Character;
// Check if Tag is valid. If valid, skip to the end of the validated tag.
if (ValidateHtmlTag(m_char_buffer, i + 1, out endTagIndex))
{
i = endTagIndex;
// Continue to next character or handle the sprite element
if (m_textElementType == TMP_TextElementType.Character)
continue;
}
}
else
{
m_textElementType = m_textInfo.characterInfo[m_characterCount].elementType;
m_currentMaterialIndex = m_textInfo.characterInfo[m_characterCount].materialReferenceIndex;
m_currentFontAsset = m_textInfo.characterInfo[m_characterCount].fontAsset;
}
#endregion End Parse Rich Text Tag
int prev_MaterialIndex = m_currentMaterialIndex;
bool isUsingAltTypeface = m_textInfo.characterInfo[m_characterCount].isUsingAlternateTypeface;
m_isParsingText = false;
// When using Linked text, mark character as ignored and skip to next character.
if (m_characterCount < m_firstVisibleCharacter)
{
m_textInfo.characterInfo[m_characterCount].isVisible = false;
m_textInfo.characterInfo[m_characterCount].character = (char)0x200B;
m_characterCount += 1;
continue;
}
// Handle Font Styles like LowerCase, UpperCase and SmallCaps.
#region Handling of LowerCase, UpperCase and SmallCaps Font Styles
float smallCapsMultiplier = 1.0f;
if (m_textElementType == TMP_TextElementType.Character)
{
if ((m_style & FontStyles.UpperCase) == FontStyles.UpperCase)
{
// If this character is lowercase, switch to uppercase.
if (char.IsLower((char)charCode))
charCode = char.ToUpper((char)charCode);
}
else if ((m_style & FontStyles.LowerCase) == FontStyles.LowerCase)
{
// If this character is uppercase, switch to lowercase.
if (char.IsUpper((char)charCode))
charCode = char.ToLower((char)charCode);
}
else if ((m_fontStyle & FontStyles.SmallCaps) == FontStyles.SmallCaps || (m_style & FontStyles.SmallCaps) == FontStyles.SmallCaps)
{
if (char.IsLower((char)charCode))
{
smallCapsMultiplier = 0.8f;
charCode = char.ToUpper((char)charCode);
}
}
}
#endregion
// Look up Character Data from Dictionary and cache it.
#region Look up Character Data
if (m_textElementType == TMP_TextElementType.Sprite)
{
// If a sprite is used as a fallback then get a reference to it and set the color to white.
// TODO : Finish adding support for the ability to use Sprites as Fallbacks.
m_currentSpriteAsset = m_textInfo.characterInfo[m_characterCount].spriteAsset;
m_spriteIndex = m_textInfo.characterInfo[m_characterCount].spriteIndex;
TMP_Sprite sprite = m_currentSpriteAsset.spriteInfoList[m_spriteIndex];
if (sprite == null) continue;
// Sprites are assigned in the E000 Private Area + sprite Index
if (charCode == 60)
charCode = 57344 + m_spriteIndex;
else
m_spriteColor = s_colorWhite;
// The sprite scale calculations are based on the font asset assigned to the text object.
float spriteScale = (m_currentFontSize / m_currentFontAsset.fontInfo.PointSize * m_currentFontAsset.fontInfo.Scale * (m_isOrthographic ? 1 : 0.1f));
currentElementScale = m_currentFontAsset.fontInfo.Ascender / sprite.height * sprite.scale * spriteScale;
m_cached_TextElement = sprite;
m_textInfo.characterInfo[m_characterCount].elementType = TMP_TextElementType.Sprite;
m_textInfo.characterInfo[m_characterCount].scale = spriteScale;
m_textInfo.characterInfo[m_characterCount].spriteAsset = m_currentSpriteAsset;
m_textInfo.characterInfo[m_characterCount].fontAsset = m_currentFontAsset;
m_textInfo.characterInfo[m_characterCount].materialReferenceIndex = m_currentMaterialIndex;
m_currentMaterialIndex = prev_MaterialIndex;
padding = 0;
}
else if (m_textElementType == TMP_TextElementType.Character)
{
m_cached_TextElement = m_textInfo.characterInfo[m_characterCount].textElement;
if (m_cached_TextElement == null) continue;
m_currentFontAsset = m_textInfo.characterInfo[m_characterCount].fontAsset;
m_currentMaterial = m_textInfo.characterInfo[m_characterCount].material;
m_currentMaterialIndex = m_textInfo.characterInfo[m_characterCount].materialReferenceIndex;
// Re-calculate font scale as the font asset may have changed.
m_fontScale = m_currentFontSize * smallCapsMultiplier / m_currentFontAsset.fontInfo.PointSize * m_currentFontAsset.fontInfo.Scale * (m_isOrthographic ? 1 : 0.1f);
currentElementScale = m_fontScale * m_fontScaleMultiplier * m_cached_TextElement.scale;
m_textInfo.characterInfo[m_characterCount].elementType = TMP_TextElementType.Character;
m_textInfo.characterInfo[m_characterCount].scale = currentElementScale;
padding = m_currentMaterialIndex == 0 ? m_padding : m_subTextObjects[m_currentMaterialIndex].padding;
}
#endregion
// Handle Soft Hyphen
#region Handle Soft Hyphen
float old_scale = currentElementScale;
if (charCode == 0xAD)
{
currentElementScale = 0;
}
#endregion
// Store some of the text object's information
m_textInfo.characterInfo[m_characterCount].character = (char)charCode;
m_textInfo.characterInfo[m_characterCount].pointSize = m_currentFontSize;
m_textInfo.characterInfo[m_characterCount].color = m_htmlColor;
m_textInfo.characterInfo[m_characterCount].underlineColor = m_underlineColor;
m_textInfo.characterInfo[m_characterCount].strikethroughColor = m_strikethroughColor;
m_textInfo.characterInfo[m_characterCount].highlightColor = m_highlightColor;
m_textInfo.characterInfo[m_characterCount].style = m_style;
m_textInfo.characterInfo[m_characterCount].index = i;
//m_textInfo.characterInfo[m_characterCount].isIgnoringAlignment = m_isIgnoringAlignment;
// Handle Kerning if Enabled.
#region Handle Kerning
GlyphValueRecord glyphAdjustments = new GlyphValueRecord();
if (m_enableKerning)
{
KerningPair adjustmentPair = null;
if (m_characterCount < totalCharacterCount - 1)
{
uint nextGlyph = m_textInfo.characterInfo[m_characterCount + 1].character;
KerningPairKey keyValue = new KerningPairKey((uint)charCode, nextGlyph);
m_currentFontAsset.kerningDictionary.TryGetValue((int)keyValue.key, out adjustmentPair);
if (adjustmentPair != null)
glyphAdjustments = adjustmentPair.firstGlyphAdjustments;
}
if (m_characterCount >= 1)
{
uint previousGlyph = m_textInfo.characterInfo[m_characterCount - 1].character;
KerningPairKey keyValue = new KerningPairKey(previousGlyph, (uint)charCode);
m_currentFontAsset.kerningDictionary.TryGetValue((int)keyValue.key, out adjustmentPair);
if (adjustmentPair != null)
glyphAdjustments += adjustmentPair.secondGlyphAdjustments;
}
}
#endregion
// Initial Implementation for RTL support.
#region Handle Right-to-Left
if (m_isRightToLeft)
{
m_xAdvance -= ((m_cached_TextElement.xAdvance * bold_xAdvance_multiplier + m_characterSpacing + m_wordSpacing + m_currentFontAsset.normalSpacingOffset) * currentElementScale + m_cSpacing) * (1 - m_charWidthAdjDelta);
if (char.IsWhiteSpace((char)charCode) || charCode == 0x200B)
m_xAdvance -= m_wordSpacing * currentElementScale;
}
#endregion
// Handle Mono Spacing
#region Handle Mono Spacing
float monoAdvance = 0;
if (m_monoSpacing != 0)
{
monoAdvance = (m_monoSpacing / 2 - (m_cached_TextElement.width / 2 + m_cached_TextElement.xOffset) * currentElementScale) * (1 - m_charWidthAdjDelta);
m_xAdvance += monoAdvance;
}
#endregion
// Set Padding based on selected font style
#region Handle Style Padding
if (m_textElementType == TMP_TextElementType.Character && !isUsingAltTypeface && ((m_style & FontStyles.Bold) == FontStyles.Bold || (m_fontStyle & FontStyles.Bold) == FontStyles.Bold)) // Checks for any combination of Bold Style.
{
if (m_currentMaterial.HasProperty(ShaderUtilities.ID_GradientScale))
{
float gradientScale = m_currentMaterial.GetFloat(ShaderUtilities.ID_GradientScale);
style_padding = m_currentFontAsset.boldStyle / 4.0f * gradientScale * m_currentMaterial.GetFloat(ShaderUtilities.ID_ScaleRatio_A);
// Clamp overall padding to Gradient Scale size.
if (style_padding + padding > gradientScale)
padding = gradientScale - style_padding;
}
else
style_padding = 0;
bold_xAdvance_multiplier = 1 + m_currentFontAsset.boldSpacing * 0.01f;
}
else
{
if (m_currentMaterial.HasProperty(ShaderUtilities.ID_GradientScale))
{
float gradientScale = m_currentMaterial.GetFloat(ShaderUtilities.ID_GradientScale);
style_padding = m_currentFontAsset.normalStyle / 4.0f * gradientScale * m_currentMaterial.GetFloat(ShaderUtilities.ID_ScaleRatio_A);
// Clamp overall padding to Gradient Scale size.
if (style_padding + padding > gradientScale)
padding = gradientScale - style_padding;
}
else
style_padding = 0;
bold_xAdvance_multiplier = 1.0f;
}
#endregion Handle Style Padding
// Determine the position of the vertices of the Character or Sprite.
#region Calculate Vertices Position
float fontBaseLineOffset = m_currentFontAsset.fontInfo.Baseline * m_fontScale * m_fontScaleMultiplier * m_currentFontAsset.fontInfo.Scale;
Vector3 top_left;
top_left.x = m_xAdvance + ((m_cached_TextElement.xOffset - padding - style_padding + glyphAdjustments.xPlacement) * currentElementScale * (1 - m_charWidthAdjDelta));
top_left.y = fontBaseLineOffset + (m_cached_TextElement.yOffset + padding + glyphAdjustments.yPlacement) * currentElementScale - m_lineOffset + m_baselineOffset;
top_left.z = 0;
Vector3 bottom_left;
bottom_left.x = top_left.x;
bottom_left.y = top_left.y - ((m_cached_TextElement.height + padding * 2) * currentElementScale);
bottom_left.z = 0;
Vector3 top_right;
top_right.x = bottom_left.x + ((m_cached_TextElement.width + padding * 2 + style_padding * 2) * currentElementScale * (1 - m_charWidthAdjDelta));
top_right.y = top_left.y;
top_right.z = 0;
Vector3 bottom_right;
bottom_right.x = top_right.x;
bottom_right.y = bottom_left.y;
bottom_right.z = 0;
#endregion
// Check if we need to Shear the rectangles for Italic styles
#region Handle Italic & Shearing
if (m_textElementType == TMP_TextElementType.Character && !isUsingAltTypeface && ((m_style & FontStyles.Italic) == FontStyles.Italic || (m_fontStyle & FontStyles.Italic) == FontStyles.Italic))
{
// Shift Top vertices forward by half (Shear Value * height of character) and Bottom vertices back by same amount.
float shear_value = m_currentFontAsset.italicStyle * 0.01f;
Vector3 topShear = new Vector3(shear_value * ((m_cached_TextElement.yOffset + padding + style_padding) * currentElementScale), 0, 0);
Vector3 bottomShear = new Vector3(shear_value * (((m_cached_TextElement.yOffset - m_cached_TextElement.height - padding - style_padding)) * currentElementScale), 0, 0);
top_left = top_left + topShear;
bottom_left = bottom_left + bottomShear;
top_right = top_right + topShear;
bottom_right = bottom_right + bottomShear;
}
#endregion Handle Italics & Shearing
// Handle Character Rotation
#region Handle Character Rotation
if (m_isFXMatrixSet)
{
// Apply scale matrix when simulating Condensed text.
if (m_FXMatrix.m00 != 1)
{
//top_left = m_FXMatrix.MultiplyPoint3x4(top_left);
//bottom_left = m_FXMatrix.MultiplyPoint3x4(bottom_left);
//top_right = m_FXMatrix.MultiplyPoint3x4(top_right);
//bottom_right = m_FXMatrix.MultiplyPoint3x4(bottom_right);
}
Vector3 positionOffset = (top_right + bottom_left) / 2;
top_left = m_FXMatrix.MultiplyPoint3x4(top_left - positionOffset) + positionOffset;
bottom_left = m_FXMatrix.MultiplyPoint3x4(bottom_left - positionOffset) + positionOffset;
top_right = m_FXMatrix.MultiplyPoint3x4(top_right - positionOffset) + positionOffset;
bottom_right = m_FXMatrix.MultiplyPoint3x4(bottom_right - positionOffset) + positionOffset;
}
#endregion
// Store vertex information for the character or sprite.
m_textInfo.characterInfo[m_characterCount].bottomLeft = bottom_left;
m_textInfo.characterInfo[m_characterCount].topLeft = top_left;
m_textInfo.characterInfo[m_characterCount].topRight = top_right;
m_textInfo.characterInfo[m_characterCount].bottomRight = bottom_right;
m_textInfo.characterInfo[m_characterCount].origin = m_xAdvance;
m_textInfo.characterInfo[m_characterCount].baseLine = fontBaseLineOffset - m_lineOffset + m_baselineOffset;
m_textInfo.characterInfo[m_characterCount].aspectRatio = (top_right.x - bottom_left.x) / (top_left.y - bottom_left.y);
// Compute and save text element Ascender and maximum line Ascender.
float elementAscender = m_currentFontAsset.fontInfo.Ascender * (m_textElementType == TMP_TextElementType.Character ? currentElementScale / smallCapsMultiplier : m_textInfo.characterInfo[m_characterCount].scale) + m_baselineOffset;
m_textInfo.characterInfo[m_characterCount].ascender = elementAscender - m_lineOffset;
m_maxLineAscender = elementAscender > m_maxLineAscender ? elementAscender : m_maxLineAscender;
// Compute and save text element Descender and maximum line Descender.
float elementDescender = m_currentFontAsset.fontInfo.Descender * (m_textElementType == TMP_TextElementType.Character ? currentElementScale / smallCapsMultiplier : m_textInfo.characterInfo[m_characterCount].scale) + m_baselineOffset;
float elementDescenderII = m_textInfo.characterInfo[m_characterCount].descender = elementDescender - m_lineOffset;
m_maxLineDescender = elementDescender < m_maxLineDescender ? elementDescender : m_maxLineDescender;
// Adjust maxLineAscender and maxLineDescender if style is superscript or subscript
if ((m_style & FontStyles.Subscript) == FontStyles.Subscript || (m_style & FontStyles.Superscript) == FontStyles.Superscript)
{
float baseAscender = (elementAscender - m_baselineOffset) / m_currentFontAsset.fontInfo.SubSize;
elementAscender = m_maxLineAscender;
m_maxLineAscender = baseAscender > m_maxLineAscender ? baseAscender : m_maxLineAscender;
float baseDescender = (elementDescender - m_baselineOffset) / m_currentFontAsset.fontInfo.SubSize;
elementDescender = m_maxLineDescender;
m_maxLineDescender = baseDescender < m_maxLineDescender ? baseDescender : m_maxLineDescender;
}
if (m_lineNumber == 0 || m_isNewPage)
{
m_maxAscender = m_maxAscender > elementAscender ? m_maxAscender : elementAscender;
m_maxCapHeight = Mathf.Max(m_maxCapHeight, m_currentFontAsset.fontInfo.CapHeight * currentElementScale / smallCapsMultiplier);
}
if (m_lineOffset == 0) pageAscender = pageAscender > elementAscender ? pageAscender : elementAscender;
// Set Characters to not visible by default.
m_textInfo.characterInfo[m_characterCount].isVisible = false;
// Setup Mesh for visible text elements. ie. not a SPACE / LINEFEED / CARRIAGE RETURN.
#region Handle Visible Characters
if (charCode == 9 || charCode == 0xA0 || charCode == 0x2007 || (!char.IsWhiteSpace((char)charCode) && charCode != 0x200B) || m_textElementType == TMP_TextElementType.Sprite)
{
m_textInfo.characterInfo[m_characterCount].isVisible = true;
#region Experimental Margin Shaper
//Vector2 shapedMargins;
//if (marginShaper)
//{
// shapedMargins = m_marginShaper.GetShapedMargins(m_textInfo.characterInfo[m_characterCount].baseLine);
// if (shapedMargins.x < margins.x)
// {
// shapedMargins.x = m_marginLeft;
// }
// else
// {
// shapedMargins.x += m_marginLeft - margins.x;
// }
// if (shapedMargins.y < margins.z)
// {
// shapedMargins.y = m_marginRight;
// }
// else
// {
// shapedMargins.y += m_marginRight - margins.z;
// }
//}
//else
//{
// shapedMargins.x = m_marginLeft;
// shapedMargins.y = m_marginRight;
//}
//width = marginWidth + 0.0001f - shapedMargins.x - shapedMargins.y;
//if (m_width != -1 && m_width < width)
//{
// width = m_width;
//}
//m_textInfo.lineInfo[m_lineNumber].marginLeft = shapedMargins.x;
#endregion
width = m_width != -1 ? Mathf.Min(marginWidth + 0.0001f - m_marginLeft - m_marginRight, m_width) : marginWidth + 0.0001f - m_marginLeft - m_marginRight;
m_textInfo.lineInfo[m_lineNumber].marginLeft = m_marginLeft;
bool isJustifiedOrFlush = ((_HorizontalAlignmentOptions)m_lineJustification & _HorizontalAlignmentOptions.Flush) == _HorizontalAlignmentOptions.Flush || ((_HorizontalAlignmentOptions)m_lineJustification & _HorizontalAlignmentOptions.Justified) == _HorizontalAlignmentOptions.Justified;
// Calculate the line breaking width of the text.
linebreakingWidth = Mathf.Abs(m_xAdvance) + (!m_isRightToLeft ? m_cached_TextElement.xAdvance : 0) * (1 - m_charWidthAdjDelta) * (charCode != 0xAD ? currentElementScale : old_scale);
// Check if Character exceeds the width of the Text Container
#region Handle Line Breaking, Text Auto-Sizing and Horizontal Overflow
if (linebreakingWidth > width * (isJustifiedOrFlush ? 1.05f : 1.0f))
{
ellipsisIndex = m_characterCount - 1; // Last safely rendered character
// Word Wrapping
#region Handle Word Wrapping
if (enableWordWrapping && m_characterCount != m_firstCharacterOfLine)
{
// Check if word wrapping is still possible
#region Line Breaking Check
if (wrappingIndex == m_SavedWordWrapState.previous_WordBreak || isFirstWord)
{
// Word wrapping is no longer possible. Shrink size of text if auto-sizing is enabled.
if (m_enableAutoSizing && m_fontSize > m_fontSizeMin)
{
// Handle Character Width Adjustments
#region Character Width Adjustments
if (m_charWidthAdjDelta < m_charWidthMaxAdj / 100)
{
loopCountA = 0;
m_charWidthAdjDelta += 0.01f;
GenerateTextMesh();
return;
}
#endregion
// Adjust Point Size
m_maxFontSize = m_fontSize;
m_fontSize -= Mathf.Max((m_fontSize - m_minFontSize) / 2, 0.05f);
m_fontSize = (int)(Mathf.Max(m_fontSize, m_fontSizeMin) * 20 + 0.5f) / 20f;
if (loopCountA > 20) return; // Added to debug
GenerateTextMesh();
return;
}
// Word wrapping is no longer possible, now breaking up individual words.
if (m_isCharacterWrappingEnabled == false)
{
if (ignoreNonBreakingSpace == false)
ignoreNonBreakingSpace = true;
else
m_isCharacterWrappingEnabled = true;
}
else
isLastBreakingChar = true;
//m_recursiveCount += 1;
//if (m_recursiveCount > 20)
//{
// Debug.Log("Recursive count exceeded!");
// continue;
//}
}
#endregion
// Restore to previously stored state of last valid (space character or linefeed)
i = RestoreWordWrappingState(ref m_SavedWordWrapState);
wrappingIndex = i; // Used to detect when line length can no longer be reduced.
// Handling for Soft Hyphen
if (m_char_buffer[i] == 0xAD) // && !m_isCharacterWrappingEnabled) // && ellipsisIndex != i && !m_isCharacterWrappingEnabled)
{
m_isTextTruncated = true;
m_char_buffer[i] = 0x2D;
GenerateTextMesh();
return;
}
//Debug.Log("Last Visible Character of line # " + m_lineNumber + " is [" + m_textInfo.characterInfo[m_lastVisibleCharacterOfLine].character + " Character Count: " + m_characterCount + " Last visible: " + m_lastVisibleCharacterOfLine);
// Check if Line Spacing of previous line needs to be adjusted.
if (m_lineNumber > 0 && !TMP_Math.Approximately(m_maxLineAscender, m_startOfLineAscender) && m_lineHeight == TMP_Math.FLOAT_UNSET && !m_isNewPage)
{
//Debug.Log("(Line Break - Adjusting Line Spacing on line #" + m_lineNumber);
float offsetDelta = m_maxLineAscender - m_startOfLineAscender;
AdjustLineOffset(m_firstCharacterOfLine, m_characterCount, offsetDelta);
m_lineOffset += offsetDelta;
m_SavedWordWrapState.lineOffset = m_lineOffset;
m_SavedWordWrapState.previousLineAscender = m_maxLineAscender;
// TODO - Add check for character exceeding vertical bounds
}
m_isNewPage = false;
// Calculate lineAscender & make sure if last character is superscript or subscript that we check that as well.
float lineAscender = m_maxLineAscender - m_lineOffset;
float lineDescender = m_maxLineDescender - m_lineOffset;
// Update maxDescender and maxVisibleDescender
m_maxDescender = m_maxDescender < lineDescender ? m_maxDescender : lineDescender;
if (!isMaxVisibleDescenderSet)
maxVisibleDescender = m_maxDescender;
if (m_useMaxVisibleDescender && (m_characterCount >= m_maxVisibleCharacters || m_lineNumber >= m_maxVisibleLines))
isMaxVisibleDescenderSet = true;
// Track & Store lineInfo for the new line
m_textInfo.lineInfo[m_lineNumber].firstCharacterIndex = m_firstCharacterOfLine;
m_textInfo.lineInfo[m_lineNumber].firstVisibleCharacterIndex = m_firstVisibleCharacterOfLine = m_firstCharacterOfLine > m_firstVisibleCharacterOfLine ? m_firstCharacterOfLine : m_firstVisibleCharacterOfLine;
m_textInfo.lineInfo[m_lineNumber].lastCharacterIndex = m_lastCharacterOfLine = m_characterCount - 1 > 0 ? m_characterCount - 1 : 0;
m_textInfo.lineInfo[m_lineNumber].lastVisibleCharacterIndex = m_lastVisibleCharacterOfLine = m_lastVisibleCharacterOfLine < m_firstVisibleCharacterOfLine ? m_firstVisibleCharacterOfLine : m_lastVisibleCharacterOfLine;
m_textInfo.lineInfo[m_lineNumber].characterCount = m_textInfo.lineInfo[m_lineNumber].lastCharacterIndex - m_textInfo.lineInfo[m_lineNumber].firstCharacterIndex + 1;
m_textInfo.lineInfo[m_lineNumber].visibleCharacterCount = m_lineVisibleCharacterCount;
m_textInfo.lineInfo[m_lineNumber].lineExtents.min = new Vector2(m_textInfo.characterInfo[m_firstVisibleCharacterOfLine].bottomLeft.x, lineDescender);
m_textInfo.lineInfo[m_lineNumber].lineExtents.max = new Vector2(m_textInfo.characterInfo[m_lastVisibleCharacterOfLine].topRight.x, lineAscender);
m_textInfo.lineInfo[m_lineNumber].length = m_textInfo.lineInfo[m_lineNumber].lineExtents.max.x;
m_textInfo.lineInfo[m_lineNumber].width = width;
//m_textInfo.lineInfo[m_lineNumber].alignment = m_lineJustification;
m_textInfo.lineInfo[m_lineNumber].maxAdvance = m_textInfo.characterInfo[m_lastVisibleCharacterOfLine].xAdvance - (m_characterSpacing + m_currentFontAsset.normalSpacingOffset) * currentElementScale - m_cSpacing;
m_textInfo.lineInfo[m_lineNumber].baseline = 0 - m_lineOffset;
m_textInfo.lineInfo[m_lineNumber].ascender = lineAscender;
m_textInfo.lineInfo[m_lineNumber].descender = lineDescender;
m_textInfo.lineInfo[m_lineNumber].lineHeight = lineAscender - lineDescender + lineGap * baseScale;
m_firstCharacterOfLine = m_characterCount; // Store first character of the next line.
m_lineVisibleCharacterCount = 0;
// Store the state of the line before starting on the new line.
SaveWordWrappingState(ref m_SavedLineState, i, m_characterCount - 1);
m_lineNumber += 1;
isStartOfNewLine = true;
isFirstWord = true;
// Check to make sure Array is large enough to hold a new line.
if (m_lineNumber >= m_textInfo.lineInfo.Length)
ResizeLineExtents(m_lineNumber);
// Apply Line Spacing based on scale of the last character of the line.
if (m_lineHeight == TMP_Math.FLOAT_UNSET)
{
float ascender = m_textInfo.characterInfo[m_characterCount].ascender - m_textInfo.characterInfo[m_characterCount].baseLine;
lineOffsetDelta = 0 - m_maxLineDescender + ascender + (lineGap + m_lineSpacing + m_lineSpacingDelta) * baseScale;
m_lineOffset += lineOffsetDelta;
m_startOfLineAscender = ascender;
}
else
m_lineOffset += m_lineHeight + m_lineSpacing * baseScale;
m_maxLineAscender = k_LargeNegativeFloat;
m_maxLineDescender = k_LargePositiveFloat;
m_xAdvance = 0 + tag_Indent;
continue;
}
#endregion End Word Wrapping
// Text Auto-Sizing (text exceeding Width of container.
#region Handle Text Auto-Sizing
if (m_enableAutoSizing && m_fontSize > m_fontSizeMin)
{
// Handle Character Width Adjustments
#region Character Width Adjustments
if (m_charWidthAdjDelta < m_charWidthMaxAdj / 100)
{
loopCountA = 0;
m_charWidthAdjDelta += 0.01f;
GenerateTextMesh();
return;
}
#endregion
// Adjust Point Size
m_maxFontSize = m_fontSize;
m_fontSize -= Mathf.Max((m_fontSize - m_minFontSize) / 2, 0.05f);
m_fontSize = (int)(Mathf.Max(m_fontSize, m_fontSizeMin) * 20 + 0.5f) / 20f;
//m_recursiveCount = 0;
if (loopCountA > 20) return; // Added to debug
GenerateTextMesh();
return;
}
#endregion End Text Auto-Sizing
// Handle Text Overflow
#region Handle Text Overflow
switch (m_overflowMode)
{
case TextOverflowModes.Overflow:
if (m_isMaskingEnabled)
DisableMasking();
break;
case TextOverflowModes.Ellipsis:
if (m_isMaskingEnabled)
DisableMasking();
m_isTextTruncated = true;
if (m_characterCount < 1)
{
m_textInfo.characterInfo[m_characterCount].isVisible = false;
//m_visibleCharacterCount = 0;
break;
}
m_char_buffer[i - 1] = 8230;
m_char_buffer[i] = (char)0;
if (m_cached_Ellipsis_GlyphInfo != null)
{
m_textInfo.characterInfo[ellipsisIndex].character = (char)8230;
m_textInfo.characterInfo[ellipsisIndex].textElement = m_cached_Ellipsis_GlyphInfo;
m_textInfo.characterInfo[ellipsisIndex].fontAsset = m_materialReferences[0].fontAsset;
m_textInfo.characterInfo[ellipsisIndex].material = m_materialReferences[0].material;
m_textInfo.characterInfo[ellipsisIndex].materialReferenceIndex = 0;
}
else
{
Debug.LogWarning("Unable to use Ellipsis character since it wasn't found in the current Font Asset [" + m_fontAsset.name + "]. Consider regenerating this font asset to include the Ellipsis character (u+2026).\nNote: Warnings can be disabled in the TMP Settings file.", this);
}
m_totalCharacterCount = ellipsisIndex + 1;
GenerateTextMesh();
return;
case TextOverflowModes.Masking:
if (!m_isMaskingEnabled)
EnableMasking();
break;
case TextOverflowModes.ScrollRect:
if (!m_isMaskingEnabled)
EnableMasking();
break;
case TextOverflowModes.Truncate:
if (m_isMaskingEnabled)
DisableMasking();
m_textInfo.characterInfo[m_characterCount].isVisible = false;
break;
case TextOverflowModes.Linked:
//m_textInfo.characterInfo[m_characterCount].isVisible = false;
//if (m_linkedTextComponent != null)
//{
// m_linkedTextComponent.text = text;
// m_linkedTextComponent.firstVisibleCharacter = m_characterCount;
// m_linkedTextComponent.ForceMeshUpdate();
//}
break;
}
#endregion End Text Overflow
}
#endregion End Check for Characters Exceeding Width of Text Container
// Special handling of characters that are not ignored at the end of a line.
if (charCode == 9 || charCode == 0xA0 || charCode == 0x2007)
{
m_textInfo.characterInfo[m_characterCount].isVisible = false;
m_lastVisibleCharacterOfLine = m_characterCount;
m_textInfo.lineInfo[m_lineNumber].spaceCount += 1;
m_textInfo.spaceCount += 1;
if (charCode == 0xA0)
m_textInfo.lineInfo[m_lineNumber].controlCharacterCount += 1;
}
else
{
// Determine Vertex Color
if (m_overrideHtmlColors)
vertexColor = m_fontColor32;
else
vertexColor = m_htmlColor;
// Store Character & Sprite Vertex Information
if (m_textElementType == TMP_TextElementType.Character)
{
// Save Character Vertex Data
SaveGlyphVertexInfo(padding, style_padding, vertexColor);
}
else if (m_textElementType == TMP_TextElementType.Sprite)
{
SaveSpriteVertexInfo(vertexColor);
}
}
// Increase visible count for Characters.
if (m_textInfo.characterInfo[m_characterCount].isVisible && charCode != 0xAD)
{
if (isStartOfNewLine) { isStartOfNewLine = false; m_firstVisibleCharacterOfLine = m_characterCount; }
m_lineVisibleCharacterCount += 1;
m_lastVisibleCharacterOfLine = m_characterCount;
}
}
else
{ // This is a Space, Tab, LineFeed or Carriage Return
// Track # of spaces per line which is used for line justification.
if ((charCode == 10 || char.IsSeparator((char)charCode)) && charCode != 0xAD && charCode != 0x200B && charCode != 0x2060)
{
m_textInfo.lineInfo[m_lineNumber].spaceCount += 1;
m_textInfo.spaceCount += 1;
}
}
#endregion Handle Visible Characters
// Check if Line Spacing of previous line needs to be adjusted.
#region Adjust Line Spacing
if (m_lineNumber > 0 && !TMP_Math.Approximately(m_maxLineAscender, m_startOfLineAscender) && m_lineHeight == TMP_Math.FLOAT_UNSET && !m_isNewPage)
{
//Debug.Log("Inline - Adjusting Line Spacing on line #" + m_lineNumber);
//float gap = 0; // Compute gap.
float offsetDelta = m_maxLineAscender - m_startOfLineAscender;
AdjustLineOffset(m_firstCharacterOfLine, m_characterCount, offsetDelta);
elementDescenderII -= offsetDelta;
m_lineOffset += offsetDelta;
m_startOfLineAscender += offsetDelta;
m_SavedWordWrapState.lineOffset = m_lineOffset;
m_SavedWordWrapState.previousLineAscender = m_startOfLineAscender;
}
#endregion
// Store Rectangle positions for each Character.
#region Store Character Data
m_textInfo.characterInfo[m_characterCount].lineNumber = m_lineNumber;
m_textInfo.characterInfo[m_characterCount].pageNumber = m_pageNumber;
if (charCode != 10 && charCode != 13 && charCode != 8230 || m_textInfo.lineInfo[m_lineNumber].characterCount == 1)
m_textInfo.lineInfo[m_lineNumber].alignment = m_lineJustification;
#endregion Store Character Data
// Check if text Exceeds the vertical bounds of the margin area.
#region Check Vertical Bounds & Auto-Sizing
if (m_maxAscender - elementDescenderII > marginHeight + 0.0001f)
{
// Handle Line spacing adjustments
#region Line Spacing Adjustments
if (m_enableAutoSizing && m_lineSpacingDelta > m_lineSpacingMax && m_lineNumber > 0)
{
loopCountA = 0;
m_lineSpacingDelta -= 1;
GenerateTextMesh();
return;
}
#endregion
// Handle Text Auto-sizing resulting from text exceeding vertical bounds.
#region Text Auto-Sizing (Text greater than vertical bounds)
if (m_enableAutoSizing && m_fontSize > m_fontSizeMin)
{
m_maxFontSize = m_fontSize;
m_fontSize -= Mathf.Max((m_fontSize - m_minFontSize) / 2, 0.05f);
m_fontSize = (int)(Mathf.Max(m_fontSize, m_fontSizeMin) * 20 + 0.5f) / 20f;
//m_recursiveCount = 0;
if (loopCountA > 20) return; // Added to debug
GenerateTextMesh();
return;
}
#endregion Text Auto-Sizing
// Set isTextOverflowing and firstOverflowCharacterIndex
if (m_firstOverflowCharacterIndex == -1)
m_firstOverflowCharacterIndex = m_characterCount;
// Handle Text Overflow
#region Text Overflow
switch (m_overflowMode)
{
case TextOverflowModes.Overflow:
if (m_isMaskingEnabled)
DisableMasking();
break;
case TextOverflowModes.Ellipsis:
if (m_isMaskingEnabled)
DisableMasking();
if (m_lineNumber > 0)
{
m_char_buffer[m_textInfo.characterInfo[ellipsisIndex].index] = 8230;
m_char_buffer[m_textInfo.characterInfo[ellipsisIndex].index + 1] = (char)0;
if (m_cached_Ellipsis_GlyphInfo != null)
{
m_textInfo.characterInfo[ellipsisIndex].character = (char)8230;
m_textInfo.characterInfo[ellipsisIndex].textElement = m_cached_Ellipsis_GlyphInfo;
m_textInfo.characterInfo[ellipsisIndex].fontAsset = m_materialReferences[0].fontAsset;
m_textInfo.characterInfo[ellipsisIndex].material = m_materialReferences[0].material;
m_textInfo.characterInfo[ellipsisIndex].materialReferenceIndex = 0;
}
else
{
Debug.LogWarning("Unable to use Ellipsis character since it wasn't found in the current Font Asset [" + m_fontAsset.name + "]. Consider regenerating this font asset to include the Ellipsis character (u+2026).\nNote: Warnings can be disabled in the TMP Settings file.", this);
}
m_totalCharacterCount = ellipsisIndex + 1;
GenerateTextMesh();
m_isTextTruncated = true;
return;
}
else
{
ClearMesh(false);
return;
}
case TextOverflowModes.Masking:
if (!m_isMaskingEnabled)
EnableMasking();
break;
case TextOverflowModes.ScrollRect:
if (!m_isMaskingEnabled)
EnableMasking();
break;
case TextOverflowModes.Truncate:
if (m_isMaskingEnabled)
DisableMasking();
// TODO : Optimize
if (m_lineNumber > 0)
{
m_char_buffer[m_textInfo.characterInfo[ellipsisIndex].index + 1] = (char)0;
m_totalCharacterCount = ellipsisIndex + 1;
GenerateTextMesh();
m_isTextTruncated = true;
return;
}
else
{
ClearMesh(false);
return;
}
case TextOverflowModes.Page:
if (m_isMaskingEnabled)
DisableMasking();
// Ignore Page Break, Linefeed or carriage return
if (charCode == 13 || charCode == 10)
break;
// Return if the first character doesn't fit.
if (i == 0)
{
ClearMesh();
return;
}
else if (previousPageOverflowChar == i)
{
m_char_buffer[i] = 0;
m_isTextTruncated = true;
}
previousPageOverflowChar = i;
// Go back to previous line and re-layout
i = RestoreWordWrappingState(ref m_SavedLineState);
m_isNewPage = true;
m_xAdvance = 0 + tag_Indent;
m_lineOffset = 0;
m_maxAscender = 0;
pageAscender = 0;
m_lineNumber += 1;
m_pageNumber += 1;
continue;
case TextOverflowModes.Linked:
if (m_linkedTextComponent != null)
{
m_linkedTextComponent.text = text;
m_linkedTextComponent.firstVisibleCharacter = m_characterCount;
m_linkedTextComponent.ForceMeshUpdate();
}
// Truncate remaining text
if (m_lineNumber > 0)
{
m_char_buffer[i] = (char)0;
m_totalCharacterCount = m_characterCount;
// TODO : Optimize as we should be able to end the layout phase here without having to do another pass.
GenerateTextMesh();
m_isTextTruncated = true;
return;
}
else
{
ClearMesh(true);
return;
}
}
#endregion End Text Overflow
}
#endregion Check Vertical Bounds
// Handle xAdvance & Tabulation Stops. Tab stops at every 25% of Font Size.
#region XAdvance, Tabulation & Stops
if (charCode == 9)
{
float tabSize = m_currentFontAsset.fontInfo.TabWidth * currentElementScale;
float tabs = Mathf.Ceil(m_xAdvance / tabSize) * tabSize;
m_xAdvance = tabs > m_xAdvance ? tabs : m_xAdvance + tabSize;
}
else if (m_monoSpacing != 0)
{
m_xAdvance += (m_monoSpacing - monoAdvance + ((m_characterSpacing + m_currentFontAsset.normalSpacingOffset) * currentElementScale) + m_cSpacing) * (1 - m_charWidthAdjDelta);
if (char.IsWhiteSpace((char)charCode) || charCode == 0x200B)
m_xAdvance += m_wordSpacing * currentElementScale;
}
else if (!m_isRightToLeft)
{
float scaleFXMultiplier = 1;
if (m_isFXMatrixSet) scaleFXMultiplier = m_FXMatrix.m00;
m_xAdvance += ((m_cached_TextElement.xAdvance * scaleFXMultiplier * bold_xAdvance_multiplier + m_characterSpacing + m_currentFontAsset.normalSpacingOffset + glyphAdjustments.xAdvance) * currentElementScale + m_cSpacing) * (1 - m_charWidthAdjDelta);
if (char.IsWhiteSpace((char)charCode) || charCode == 0x200B)
m_xAdvance += m_wordSpacing * currentElementScale;
}
else
{
m_xAdvance -= glyphAdjustments.xAdvance * currentElementScale;
}
// Store xAdvance information
m_textInfo.characterInfo[m_characterCount].xAdvance = m_xAdvance;
#endregion Tabulation & Stops
// Handle Carriage Return
#region Carriage Return
if (charCode == 13)
{
m_xAdvance = 0 + tag_Indent;
}
#endregion Carriage Return
// Handle Line Spacing Adjustments + Word Wrapping & special case for last line.
#region Check for Line Feed and Last Character
if (charCode == 10 || m_characterCount == totalCharacterCount - 1)
{
// Check if Line Spacing of previous line needs to be adjusted.
if (m_lineNumber > 0 && !TMP_Math.Approximately(m_maxLineAscender, m_startOfLineAscender) && m_lineHeight == TMP_Math.FLOAT_UNSET && !m_isNewPage)
{
//Debug.Log("Line Feed - Adjusting Line Spacing on line #" + m_lineNumber);
float offsetDelta = m_maxLineAscender - m_startOfLineAscender;
AdjustLineOffset(m_firstCharacterOfLine, m_characterCount, offsetDelta);
elementDescenderII -= offsetDelta;
m_lineOffset += offsetDelta;
}
m_isNewPage = false;
// Calculate lineAscender & make sure if last character is superscript or subscript that we check that as well.
float lineAscender = m_maxLineAscender - m_lineOffset;
float lineDescender = m_maxLineDescender - m_lineOffset;
// Update maxDescender and maxVisibleDescender
m_maxDescender = m_maxDescender < lineDescender ? m_maxDescender : lineDescender;
if (!isMaxVisibleDescenderSet)
maxVisibleDescender = m_maxDescender;
if (m_useMaxVisibleDescender && (m_characterCount >= m_maxVisibleCharacters || m_lineNumber >= m_maxVisibleLines))
isMaxVisibleDescenderSet = true;
// Save Line Information
m_textInfo.lineInfo[m_lineNumber].firstCharacterIndex = m_firstCharacterOfLine;
m_textInfo.lineInfo[m_lineNumber].firstVisibleCharacterIndex = m_firstVisibleCharacterOfLine = m_firstCharacterOfLine > m_firstVisibleCharacterOfLine ? m_firstCharacterOfLine : m_firstVisibleCharacterOfLine;
m_textInfo.lineInfo[m_lineNumber].lastCharacterIndex = m_lastCharacterOfLine = m_characterCount;
m_textInfo.lineInfo[m_lineNumber].lastVisibleCharacterIndex = m_lastVisibleCharacterOfLine = m_lastVisibleCharacterOfLine < m_firstVisibleCharacterOfLine ? m_firstVisibleCharacterOfLine : m_lastVisibleCharacterOfLine;
m_textInfo.lineInfo[m_lineNumber].characterCount = m_textInfo.lineInfo[m_lineNumber].lastCharacterIndex - m_textInfo.lineInfo[m_lineNumber].firstCharacterIndex + 1;
m_textInfo.lineInfo[m_lineNumber].visibleCharacterCount = m_lineVisibleCharacterCount;
m_textInfo.lineInfo[m_lineNumber].lineExtents.min = new Vector2(m_textInfo.characterInfo[m_firstVisibleCharacterOfLine].bottomLeft.x, lineDescender);
m_textInfo.lineInfo[m_lineNumber].lineExtents.max = new Vector2(m_textInfo.characterInfo[m_lastVisibleCharacterOfLine].topRight.x, lineAscender);
m_textInfo.lineInfo[m_lineNumber].length = m_textInfo.lineInfo[m_lineNumber].lineExtents.max.x - (padding * currentElementScale);
m_textInfo.lineInfo[m_lineNumber].width = width;
if (m_textInfo.lineInfo[m_lineNumber].characterCount == 1)
m_textInfo.lineInfo[m_lineNumber].alignment = m_lineJustification;
if (m_textInfo.characterInfo[m_lastVisibleCharacterOfLine].isVisible)
m_textInfo.lineInfo[m_lineNumber].maxAdvance = m_textInfo.characterInfo[m_lastVisibleCharacterOfLine].xAdvance - (m_characterSpacing + m_currentFontAsset.normalSpacingOffset) * currentElementScale - m_cSpacing;
else
m_textInfo.lineInfo[m_lineNumber].maxAdvance = m_textInfo.characterInfo[m_lastCharacterOfLine].xAdvance - (m_characterSpacing + m_currentFontAsset.normalSpacingOffset) * currentElementScale - m_cSpacing;
m_textInfo.lineInfo[m_lineNumber].baseline = 0 - m_lineOffset;
m_textInfo.lineInfo[m_lineNumber].ascender = lineAscender;
m_textInfo.lineInfo[m_lineNumber].descender = lineDescender;
m_textInfo.lineInfo[m_lineNumber].lineHeight = lineAscender - lineDescender + lineGap * baseScale;
m_firstCharacterOfLine = m_characterCount + 1;
m_lineVisibleCharacterCount = 0;
// Add new line if not last line or character.
if (charCode == 10)
{
// Store the state of the line before starting on the new line.
SaveWordWrappingState(ref m_SavedLineState, i, m_characterCount);
// Store the state of the last Character before the new line.
SaveWordWrappingState(ref m_SavedWordWrapState, i, m_characterCount);
m_lineNumber += 1;
isStartOfNewLine = true;
ignoreNonBreakingSpace = false;
isFirstWord = true;
// Check to make sure Array is large enough to hold a new line.
if (m_lineNumber >= m_textInfo.lineInfo.Length)
ResizeLineExtents(m_lineNumber);
// Apply Line Spacing
if (m_lineHeight == TMP_Math.FLOAT_UNSET)
{
lineOffsetDelta = 0 - m_maxLineDescender + elementAscender + (lineGap + m_lineSpacing + m_paragraphSpacing + m_lineSpacingDelta) * baseScale;
m_lineOffset += lineOffsetDelta;
}
else
m_lineOffset += m_lineHeight + (m_lineSpacing + m_paragraphSpacing) * baseScale;
m_maxLineAscender = k_LargeNegativeFloat;
m_maxLineDescender = k_LargePositiveFloat;
m_startOfLineAscender = elementAscender;
m_xAdvance = 0 + tag_LineIndent + tag_Indent;
ellipsisIndex = m_characterCount - 1;
m_characterCount += 1;
continue;
}
}
#endregion Check for Linefeed or Last Character
// Store Rectangle positions for each Character.
#region Save CharacterInfo for the current character.
// Determine the bounds of the Mesh.
if (m_textInfo.characterInfo[m_characterCount].isVisible)
{
m_meshExtents.min.x = Mathf.Min(m_meshExtents.min.x, m_textInfo.characterInfo[m_characterCount].bottomLeft.x);
m_meshExtents.min.y = Mathf.Min(m_meshExtents.min.y, m_textInfo.characterInfo[m_characterCount].bottomLeft.y);
m_meshExtents.max.x = Mathf.Max(m_meshExtents.max.x, m_textInfo.characterInfo[m_characterCount].topRight.x);
m_meshExtents.max.y = Mathf.Max(m_meshExtents.max.y, m_textInfo.characterInfo[m_characterCount].topRight.y);
//m_meshExtents.min = new Vector2(Mathf.Min(m_meshExtents.min.x, m_textInfo.characterInfo[m_characterCount].bottomLeft.x), Mathf.Min(m_meshExtents.min.y, m_textInfo.characterInfo[m_characterCount].bottomLeft.y));
//m_meshExtents.max = new Vector2(Mathf.Max(m_meshExtents.max.x, m_textInfo.characterInfo[m_characterCount].topRight.x), Mathf.Max(m_meshExtents.max.y, m_textInfo.characterInfo[m_characterCount].topRight.y));
}
// Save pageInfo Data
if (m_overflowMode == TextOverflowModes.Page && charCode != 13 && charCode != 10) // && m_pageNumber < 16)
{
// Check if we need to increase allocations for the pageInfo array.
if (m_pageNumber + 1 > m_textInfo.pageInfo.Length)
TMP_TextInfo.Resize(ref m_textInfo.pageInfo, m_pageNumber + 1, true);
m_textInfo.pageInfo[m_pageNumber].ascender = pageAscender;
m_textInfo.pageInfo[m_pageNumber].descender = elementDescender < m_textInfo.pageInfo[m_pageNumber].descender ? elementDescender : m_textInfo.pageInfo[m_pageNumber].descender;
if (m_pageNumber == 0 && m_characterCount == 0)
m_textInfo.pageInfo[m_pageNumber].firstCharacterIndex = m_characterCount;
else if (m_characterCount > 0 && m_pageNumber != m_textInfo.characterInfo[m_characterCount - 1].pageNumber)
{
m_textInfo.pageInfo[m_pageNumber - 1].lastCharacterIndex = m_characterCount - 1;
m_textInfo.pageInfo[m_pageNumber].firstCharacterIndex = m_characterCount;
}
else if (m_characterCount == totalCharacterCount - 1)
m_textInfo.pageInfo[m_pageNumber].lastCharacterIndex = m_characterCount;
}
#endregion Saving CharacterInfo
// Save State of Mesh Creation for handling of Word Wrapping
#region Save Word Wrapping State
if (m_enableWordWrapping || m_overflowMode == TextOverflowModes.Truncate || m_overflowMode == TextOverflowModes.Ellipsis)
{
if ((char.IsWhiteSpace((char)charCode) || charCode == 0x200B || charCode == 0x2D || charCode == 0xAD) && (!m_isNonBreakingSpace || ignoreNonBreakingSpace) && charCode != 0xA0 && charCode != 0x2007 && charCode != 0x2011 && charCode != 0x202F && charCode != 0x2060)
{
// We store the state of numerous variables for the most recent Space, LineFeed or Carriage Return to enable them to be restored
// for Word Wrapping.
SaveWordWrappingState(ref m_SavedWordWrapState, i, m_characterCount);
m_isCharacterWrappingEnabled = false;
isFirstWord = false;
}
// Handling for East Asian languages
else if (( charCode > 0x1100 && charCode < 0x11ff || /* Hangul Jamo */
charCode > 0x2E80 && charCode < 0x9FFF || /* CJK */
charCode > 0xA960 && charCode < 0xA97F || /* Hangul Jame Extended-A */
charCode > 0xAC00 && charCode < 0xD7FF || /* Hangul Syllables */
charCode > 0xF900 && charCode < 0xFAFF || /* CJK Compatibility Ideographs */
charCode > 0xFE30 && charCode < 0xFE4F || /* CJK Compatibility Forms */
charCode > 0xFF00 && charCode < 0xFFEF) /* CJK Halfwidth */
&& !m_isNonBreakingSpace)
{
if (isFirstWord || isLastBreakingChar || TMP_Settings.linebreakingRules.leadingCharacters.ContainsKey(charCode) == false &&
(m_characterCount < totalCharacterCount - 1 &&
TMP_Settings.linebreakingRules.followingCharacters.ContainsKey(m_textInfo.characterInfo[m_characterCount + 1].character) == false))
{
SaveWordWrappingState(ref m_SavedWordWrapState, i, m_characterCount);
m_isCharacterWrappingEnabled = false;
isFirstWord = false;
}
}
else if ((isFirstWord || m_isCharacterWrappingEnabled == true || isLastBreakingChar))
SaveWordWrappingState(ref m_SavedWordWrapState, i, m_characterCount);
}
#endregion Save Word Wrapping State
m_characterCount += 1;
}
// Check Auto Sizing and increase font size to fill text container.
#region Check Auto-Sizing (Upper Font Size Bounds)
fontSizeDelta = m_maxFontSize - m_minFontSize;
if (!m_isCharacterWrappingEnabled && m_enableAutoSizing && fontSizeDelta > 0.051f && m_fontSize < m_fontSizeMax)
{
m_minFontSize = m_fontSize;
m_fontSize += Mathf.Max((m_maxFontSize - m_fontSize) / 2, 0.05f);
m_fontSize = (int)(Mathf.Min(m_fontSize, m_fontSizeMax) * 20 + 0.5f) / 20f;
//Debug.Log(m_fontSize);
if (loopCountA > 20) return; // Added to debug
GenerateTextMesh();
return;
}
#endregion End Auto-sizing Check
m_isCharacterWrappingEnabled = false;
//Debug.Log("Iteration Count: " + loopCountA + ". Final Point Size: " + m_fontSize); // + " B: " + loopCountB + " C: " + loopCountC + " D: " + loopCountD);
// If there are no visible characters... no need to continue
if (m_characterCount == 0) // && m_visibleSpriteCount == 0)
{
ClearMesh(true);
// Event indicating the text has been regenerated.
TMPro_EventManager.ON_TEXT_CHANGED(this);
return;
}
// *** PHASE II of Text Generation ***
int last_vert_index = m_materialReferences[0].referenceCount * (!m_isVolumetricText ? 4 : 8);
// Partial clear of the vertices array to mark unused vertices as degenerate.
m_textInfo.meshInfo[0].Clear(false);
// Handle Text Alignment
#region Text Vertical Alignment
Vector3 anchorOffset = Vector3.zero;
Vector3[] corners = m_RectTransformCorners; // GetTextContainerLocalCorners();
// Handle Vertical Text Alignment
switch (m_textAlignment)
{
// Top Vertically
case TextAlignmentOptions.Top:
case TextAlignmentOptions.TopLeft:
case TextAlignmentOptions.TopRight:
case TextAlignmentOptions.TopJustified:
case TextAlignmentOptions.TopFlush:
case TextAlignmentOptions.TopGeoAligned:
if (m_overflowMode != TextOverflowModes.Page)
anchorOffset = corners[1] + new Vector3(0 + margins.x, 0 - m_maxAscender - margins.y, 0);
else
anchorOffset = corners[1] + new Vector3(0 + margins.x, 0 - m_textInfo.pageInfo[pageToDisplay].ascender - margins.y, 0);
break;
// Middle Vertically
case TextAlignmentOptions.Left:
case TextAlignmentOptions.Right:
case TextAlignmentOptions.Center:
case TextAlignmentOptions.Justified:
case TextAlignmentOptions.Flush:
case TextAlignmentOptions.CenterGeoAligned:
if (m_overflowMode != TextOverflowModes.Page)
anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0 - (m_maxAscender + margins.y + maxVisibleDescender - margins.w) / 2, 0);
else
anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0 - (m_textInfo.pageInfo[pageToDisplay].ascender + margins.y + m_textInfo.pageInfo[pageToDisplay].descender - margins.w) / 2, 0);
break;
// Bottom Vertically
case TextAlignmentOptions.Bottom:
case TextAlignmentOptions.BottomLeft:
case TextAlignmentOptions.BottomRight:
case TextAlignmentOptions.BottomJustified:
case TextAlignmentOptions.BottomFlush:
case TextAlignmentOptions.BottomGeoAligned:
if (m_overflowMode != TextOverflowModes.Page)
anchorOffset = corners[0] + new Vector3(0 + margins.x, 0 - maxVisibleDescender + margins.w, 0);
else
anchorOffset = corners[0] + new Vector3(0 + margins.x, 0 - m_textInfo.pageInfo[pageToDisplay].descender + margins.w, 0);
break;
// Baseline Vertically
case TextAlignmentOptions.Baseline:
case TextAlignmentOptions.BaselineLeft:
case TextAlignmentOptions.BaselineRight:
case TextAlignmentOptions.BaselineJustified:
case TextAlignmentOptions.BaselineFlush:
case TextAlignmentOptions.BaselineGeoAligned:
anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0, 0);
break;
// Midline Vertically
case TextAlignmentOptions.MidlineLeft:
case TextAlignmentOptions.Midline:
case TextAlignmentOptions.MidlineRight:
case TextAlignmentOptions.MidlineJustified:
case TextAlignmentOptions.MidlineFlush:
case TextAlignmentOptions.MidlineGeoAligned:
anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0 - (m_meshExtents.max.y + margins.y + m_meshExtents.min.y - margins.w) / 2, 0);
break;
// Capline Vertically
case TextAlignmentOptions.CaplineLeft:
case TextAlignmentOptions.Capline:
case TextAlignmentOptions.CaplineRight:
case TextAlignmentOptions.CaplineJustified:
case TextAlignmentOptions.CaplineFlush:
case TextAlignmentOptions.CaplineGeoAligned:
anchorOffset = (corners[0] + corners[1]) / 2 + new Vector3(0 + margins.x, 0 - (m_maxCapHeight - margins.y - margins.w) / 2, 0);
break;
}
#endregion
// Initialization for Second Pass
Vector3 justificationOffset = Vector3.zero;
Vector3 offset = Vector3.zero;
int vert_index_X4 = 0;
int sprite_index_X4 = 0;
int wordCount = 0;
int lineCount = 0;
int lastLine = 0;
bool isFirstSeperator = false;
bool isStartOfWord = false;
int wordFirstChar = 0;
int wordLastChar = 0;
// Second Pass : Line Justification, UV Mapping, Character & Line Visibility & more.
float lossyScale = m_previousLossyScaleY = this.transform.lossyScale.y;
Color32 underlineColor = Color.white;
Color32 strikethroughColor = Color.white;
Color32 highlightColor = new Color32(255, 255, 0, 64);
float xScale = 0;
float underlineStartScale = 0;
float underlineEndScale = 0;
float underlineMaxScale = 0;
float underlineBaseLine = k_LargePositiveFloat;
int lastPage = 0;
float strikethroughPointSize = 0;
float strikethroughScale = 0;
float strikethroughBaseline = 0;
TMP_CharacterInfo[] characterInfos = m_textInfo.characterInfo;
#region Handle Line Justification & UV Mapping & Character Visibility & More
for (int i = 0; i < m_characterCount; i++)
{
TMP_FontAsset currentFontAsset = characterInfos[i].fontAsset;
char currentCharacter = characterInfos[i].character;
int currentLine = characterInfos[i].lineNumber;
TMP_LineInfo lineInfo = m_textInfo.lineInfo[currentLine];
lineCount = currentLine + 1;
TextAlignmentOptions lineAlignment = lineInfo.alignment;
// Process Line Justification
#region Handle Line Justification
switch (lineAlignment)
{
case TextAlignmentOptions.TopLeft:
case TextAlignmentOptions.Left:
case TextAlignmentOptions.BottomLeft:
case TextAlignmentOptions.BaselineLeft:
case TextAlignmentOptions.MidlineLeft:
case TextAlignmentOptions.CaplineLeft:
if (!m_isRightToLeft)
justificationOffset = new Vector3(0 + lineInfo.marginLeft, 0, 0);
else
justificationOffset = new Vector3(0 - lineInfo.maxAdvance, 0, 0);
break;
case TextAlignmentOptions.Top:
case TextAlignmentOptions.Center:
case TextAlignmentOptions.Bottom:
case TextAlignmentOptions.Baseline:
case TextAlignmentOptions.Midline:
case TextAlignmentOptions.Capline:
justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width / 2 - lineInfo.maxAdvance / 2, 0, 0);
break;
case TextAlignmentOptions.TopGeoAligned:
case TextAlignmentOptions.CenterGeoAligned:
case TextAlignmentOptions.BottomGeoAligned:
case TextAlignmentOptions.BaselineGeoAligned:
case TextAlignmentOptions.MidlineGeoAligned:
case TextAlignmentOptions.CaplineGeoAligned:
justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width / 2 - (lineInfo.lineExtents.min.x + lineInfo.lineExtents.max.x) / 2, 0, 0);
break;
case TextAlignmentOptions.TopRight:
case TextAlignmentOptions.Right:
case TextAlignmentOptions.BottomRight:
case TextAlignmentOptions.BaselineRight:
case TextAlignmentOptions.MidlineRight:
case TextAlignmentOptions.CaplineRight:
if (!m_isRightToLeft)
justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width - lineInfo.maxAdvance, 0, 0);
else
justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width, 0, 0);
break;
case TextAlignmentOptions.TopJustified:
case TextAlignmentOptions.Justified:
case TextAlignmentOptions.BottomJustified:
case TextAlignmentOptions.BaselineJustified:
case TextAlignmentOptions.MidlineJustified:
case TextAlignmentOptions.CaplineJustified:
case TextAlignmentOptions.TopFlush:
case TextAlignmentOptions.Flush:
case TextAlignmentOptions.BottomFlush:
case TextAlignmentOptions.BaselineFlush:
case TextAlignmentOptions.MidlineFlush:
case TextAlignmentOptions.CaplineFlush:
// Skip Zero Width Characters
if (currentCharacter == 0xAD || currentCharacter == 0x200B || currentCharacter == 0x2060) break;
char lastCharOfCurrentLine = characterInfos[lineInfo.lastCharacterIndex].character;
bool isFlush = ((_HorizontalAlignmentOptions)lineAlignment & _HorizontalAlignmentOptions.Flush) == _HorizontalAlignmentOptions.Flush;
// In Justified mode, all lines are justified except the last one.
// In Flush mode, all lines are justified.
if (char.IsControl(lastCharOfCurrentLine) == false && currentLine < m_lineNumber || isFlush || lineInfo.maxAdvance > lineInfo.width)
{
// First character of each line.
if (currentLine != lastLine || i == 0 || i == m_firstVisibleCharacter)
{
if (!m_isRightToLeft)
justificationOffset = new Vector3(lineInfo.marginLeft, 0, 0);
else
justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width, 0, 0);
if (char.IsSeparator(currentCharacter))
isFirstSeperator = true;
else
isFirstSeperator = false;
}
else
{
float gap = !m_isRightToLeft ? lineInfo.width - lineInfo.maxAdvance : lineInfo.width + lineInfo.maxAdvance;
int visibleCount = lineInfo.visibleCharacterCount - 1 + lineInfo.controlCharacterCount;
// Get the number of spaces for each line ignoring the last character if it is not visible (ie. a space or linefeed).
int spaces = (characterInfos[lineInfo.lastCharacterIndex].isVisible ? lineInfo.spaceCount : lineInfo.spaceCount - 1) - lineInfo.controlCharacterCount;
if (isFirstSeperator) { spaces -= 1; visibleCount += 1; }
float ratio = spaces > 0 ? m_wordWrappingRatios : 1;
if (spaces < 1) spaces = 1;
if (currentCharacter != 0xA0 && (currentCharacter == 9 || char.IsSeparator((char)currentCharacter)))
{
if (!m_isRightToLeft)
justificationOffset += new Vector3(gap * (1 - ratio) / spaces, 0, 0);
else
justificationOffset -= new Vector3(gap * (1 - ratio) / spaces, 0, 0);
}
else
{
if (!m_isRightToLeft)
justificationOffset += new Vector3(gap * ratio / visibleCount, 0, 0);
else
justificationOffset -= new Vector3(gap * ratio / visibleCount, 0, 0);
}
}
}
else
{
if (!m_isRightToLeft)
justificationOffset = new Vector3(lineInfo.marginLeft, 0, 0); // Keep last line left justified.
else
justificationOffset = new Vector3(lineInfo.marginLeft + lineInfo.width, 0, 0); // Keep last line right justified.
}
//Debug.Log("Char [" + (char)charCode + "] Code:" + charCode + " Line # " + currentLine + " Offset:" + justificationOffset + " # Spaces:" + lineInfo.spaceCount + " # Characters:" + lineInfo.characterCount);
break;
}
#endregion End Text Justification
offset = anchorOffset + justificationOffset;
// Handle UV2 mapping options and packing of scale information into UV2.
#region Handling of UV2 mapping & Scale packing
bool isCharacterVisible = characterInfos[i].isVisible;
if (isCharacterVisible)
{
TMP_TextElementType elementType = characterInfos[i].elementType;
switch (elementType)
{
// CHARACTERS
case TMP_TextElementType.Character:
Extents lineExtents = lineInfo.lineExtents;
float uvOffset = (m_uvLineOffset * currentLine) % 1; // + m_uvOffset.x;
// Setup UV2 based on Character Mapping Options Selected
#region Handle UV Mapping Options
switch (m_horizontalMapping)
{
case TextureMappingOptions.Character:
characterInfos[i].vertex_BL.uv2.x = 0; //+ m_uvOffset.x;
characterInfos[i].vertex_TL.uv2.x = 0; //+ m_uvOffset.x;
characterInfos[i].vertex_TR.uv2.x = 1; //+ m_uvOffset.x;
characterInfos[i].vertex_BR.uv2.x = 1; //+ m_uvOffset.x;
break;
case TextureMappingOptions.Line:
if (m_textAlignment != TextAlignmentOptions.Justified)
{
characterInfos[i].vertex_BL.uv2.x = (characterInfos[i].vertex_BL.position.x - lineExtents.min.x) / (lineExtents.max.x - lineExtents.min.x) + uvOffset;
characterInfos[i].vertex_TL.uv2.x = (characterInfos[i].vertex_TL.position.x - lineExtents.min.x) / (lineExtents.max.x - lineExtents.min.x) + uvOffset;
characterInfos[i].vertex_TR.uv2.x = (characterInfos[i].vertex_TR.position.x - lineExtents.min.x) / (lineExtents.max.x - lineExtents.min.x) + uvOffset;
characterInfos[i].vertex_BR.uv2.x = (characterInfos[i].vertex_BR.position.x - lineExtents.min.x) / (lineExtents.max.x - lineExtents.min.x) + uvOffset;
break;
}
else // Special Case if Justified is used in Line Mode.
{
characterInfos[i].vertex_BL.uv2.x = (characterInfos[i].vertex_BL.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
characterInfos[i].vertex_TL.uv2.x = (characterInfos[i].vertex_TL.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
characterInfos[i].vertex_TR.uv2.x = (characterInfos[i].vertex_TR.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
characterInfos[i].vertex_BR.uv2.x = (characterInfos[i].vertex_BR.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
break;
}
case TextureMappingOptions.Paragraph:
characterInfos[i].vertex_BL.uv2.x = (characterInfos[i].vertex_BL.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
characterInfos[i].vertex_TL.uv2.x = (characterInfos[i].vertex_TL.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
characterInfos[i].vertex_TR.uv2.x = (characterInfos[i].vertex_TR.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
characterInfos[i].vertex_BR.uv2.x = (characterInfos[i].vertex_BR.position.x + justificationOffset.x - m_meshExtents.min.x) / (m_meshExtents.max.x - m_meshExtents.min.x) + uvOffset;
break;
case TextureMappingOptions.MatchAspect:
switch (m_verticalMapping)
{
case TextureMappingOptions.Character:
characterInfos[i].vertex_BL.uv2.y = 0; //+ m_uvOffset.y;
characterInfos[i].vertex_TL.uv2.y = 1; //+ m_uvOffset.y;
characterInfos[i].vertex_TR.uv2.y = 0; //+ m_uvOffset.y;
characterInfos[i].vertex_BR.uv2.y = 1; //+ m_uvOffset.y;
break;
case TextureMappingOptions.Line:
characterInfos[i].vertex_BL.uv2.y = (characterInfos[i].vertex_BL.position.y - lineExtents.min.y) / (lineExtents.max.y - lineExtents.min.y) + uvOffset;
characterInfos[i].vertex_TL.uv2.y = (characterInfos[i].vertex_TL.position.y - lineExtents.min.y) / (lineExtents.max.y - lineExtents.min.y) + uvOffset;
characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
break;
case TextureMappingOptions.Paragraph:
characterInfos[i].vertex_BL.uv2.y = (characterInfos[i].vertex_BL.position.y - m_meshExtents.min.y) / (m_meshExtents.max.y - m_meshExtents.min.y) + uvOffset;
characterInfos[i].vertex_TL.uv2.y = (characterInfos[i].vertex_TL.position.y - m_meshExtents.min.y) / (m_meshExtents.max.y - m_meshExtents.min.y) + uvOffset;
characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
break;
case TextureMappingOptions.MatchAspect:
Debug.Log("ERROR: Cannot Match both Vertical & Horizontal.");
break;
}
//float xDelta = 1 - (_uv2s[vert_index + 0].y * textMeshCharacterInfo[i].AspectRatio); // Left aligned
float xDelta = (1 - ((characterInfos[i].vertex_BL.uv2.y + characterInfos[i].vertex_TL.uv2.y) * characterInfos[i].aspectRatio)) / 2; // Center of Rectangle
characterInfos[i].vertex_BL.uv2.x = (characterInfos[i].vertex_BL.uv2.y * characterInfos[i].aspectRatio) + xDelta + uvOffset;
characterInfos[i].vertex_TL.uv2.x = characterInfos[i].vertex_BL.uv2.x;
characterInfos[i].vertex_TR.uv2.x = (characterInfos[i].vertex_TL.uv2.y * characterInfos[i].aspectRatio) + xDelta + uvOffset;
characterInfos[i].vertex_BR.uv2.x = characterInfos[i].vertex_TR.uv2.x;
break;
}
switch (m_verticalMapping)
{
case TextureMappingOptions.Character:
characterInfos[i].vertex_BL.uv2.y = 0; //+ m_uvOffset.y;
characterInfos[i].vertex_TL.uv2.y = 1; //+ m_uvOffset.y;
characterInfos[i].vertex_TR.uv2.y = 1; //+ m_uvOffset.y;
characterInfos[i].vertex_BR.uv2.y = 0; //+ m_uvOffset.y;
break;
case TextureMappingOptions.Line:
characterInfos[i].vertex_BL.uv2.y = (characterInfos[i].vertex_BL.position.y - lineInfo.descender) / (lineInfo.ascender - lineInfo.descender); // + m_uvOffset.y;
characterInfos[i].vertex_TL.uv2.y = (characterInfos[i].vertex_TL.position.y - lineInfo.descender) / (lineInfo.ascender - lineInfo.descender); // + m_uvOffset.y;
characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
break;
case TextureMappingOptions.Paragraph:
characterInfos[i].vertex_BL.uv2.y = (characterInfos[i].vertex_BL.position.y - m_meshExtents.min.y) / (m_meshExtents.max.y - m_meshExtents.min.y); // + m_uvOffset.y;
characterInfos[i].vertex_TL.uv2.y = (characterInfos[i].vertex_TL.position.y - m_meshExtents.min.y) / (m_meshExtents.max.y - m_meshExtents.min.y); // + m_uvOffset.y;
characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
break;
case TextureMappingOptions.MatchAspect:
float yDelta = (1 - ((characterInfos[i].vertex_BL.uv2.x + characterInfos[i].vertex_TR.uv2.x) / characterInfos[i].aspectRatio)) / 2; // Center of Rectangle
characterInfos[i].vertex_BL.uv2.y = yDelta + (characterInfos[i].vertex_BL.uv2.x / characterInfos[i].aspectRatio); // + m_uvOffset.y;
characterInfos[i].vertex_TL.uv2.y = yDelta + (characterInfos[i].vertex_TR.uv2.x / characterInfos[i].aspectRatio); // + m_uvOffset.y;
characterInfos[i].vertex_BR.uv2.y = characterInfos[i].vertex_BL.uv2.y;
characterInfos[i].vertex_TR.uv2.y = characterInfos[i].vertex_TL.uv2.y;
break;
}
#endregion
// Pack UV's so that we can pass Xscale needed for Shader to maintain 1:1 ratio.
#region Pack Scale into UV2
xScale = characterInfos[i].scale * lossyScale * (1 - m_charWidthAdjDelta);
if (!characterInfos[i].isUsingAlternateTypeface && (characterInfos[i].style & FontStyles.Bold) == FontStyles.Bold) xScale *= -1;
//int isBold = (m_textInfo.characterInfo[i].style & FontStyles.Bold) == FontStyles.Bold ? 1 : 0;
//Vector2 vertexData = new Vector2(isBold, xScale);
//characterInfos[i].vertex_BL.uv4 = vertexData;
//characterInfos[i].vertex_TL.uv4 = vertexData;
//characterInfos[i].vertex_TR.uv4 = vertexData;
//characterInfos[i].vertex_BR.uv4 = vertexData;
float x0 = characterInfos[i].vertex_BL.uv2.x;
float y0 = characterInfos[i].vertex_BL.uv2.y;
float x1 = characterInfos[i].vertex_TR.uv2.x;
float y1 = characterInfos[i].vertex_TR.uv2.y;
float dx = (int)x0;
float dy = (int)y0;
x0 = x0 - dx;
x1 = x1 - dx;
y0 = y0 - dy;
y1 = y1 - dy;
// Optimization to avoid having a vector2 returned from the Pack UV function.
characterInfos[i].vertex_BL.uv2.x = PackUV(x0, y0); characterInfos[i].vertex_BL.uv2.y = xScale;
characterInfos[i].vertex_TL.uv2.x = PackUV(x0, y1); characterInfos[i].vertex_TL.uv2.y = xScale;
characterInfos[i].vertex_TR.uv2.x = PackUV(x1, y1); characterInfos[i].vertex_TR.uv2.y = xScale;
characterInfos[i].vertex_BR.uv2.x = PackUV(x1, y0); characterInfos[i].vertex_BR.uv2.y = xScale;
#endregion
break;
// SPRITES
case TMP_TextElementType.Sprite:
// Nothing right now
break;
}
// Handle maxVisibleCharacters, maxVisibleLines and Overflow Page Mode.
#region Handle maxVisibleCharacters / maxVisibleLines / Page Mode
if (i < m_maxVisibleCharacters && wordCount < m_maxVisibleWords && currentLine < m_maxVisibleLines && m_overflowMode != TextOverflowModes.Page)
{
characterInfos[i].vertex_BL.position += offset;
characterInfos[i].vertex_TL.position += offset;
characterInfos[i].vertex_TR.position += offset;
characterInfos[i].vertex_BR.position += offset;
}
else if (i < m_maxVisibleCharacters && wordCount < m_maxVisibleWords && currentLine < m_maxVisibleLines && m_overflowMode == TextOverflowModes.Page && characterInfos[i].pageNumber == pageToDisplay)
{
characterInfos[i].vertex_BL.position += offset;
characterInfos[i].vertex_TL.position += offset;
characterInfos[i].vertex_TR.position += offset;
characterInfos[i].vertex_BR.position += offset;
}
else
{
characterInfos[i].vertex_BL.position = Vector3.zero;
characterInfos[i].vertex_TL.position = Vector3.zero;
characterInfos[i].vertex_TR.position = Vector3.zero;
characterInfos[i].vertex_BR.position = Vector3.zero;
characterInfos[i].isVisible = false;
}
#endregion
// Fill Vertex Buffers for the various types of element
if (elementType == TMP_TextElementType.Character)
{
FillCharacterVertexBuffers(i, vert_index_X4, m_isVolumetricText);
}
else if (elementType == TMP_TextElementType.Sprite)
{
FillSpriteVertexBuffers(i, sprite_index_X4);
}
}
#endregion
// Apply Alignment and Justification Offset
m_textInfo.characterInfo[i].bottomLeft += offset;
m_textInfo.characterInfo[i].topLeft += offset;
m_textInfo.characterInfo[i].topRight += offset;
m_textInfo.characterInfo[i].bottomRight += offset;
m_textInfo.characterInfo[i].origin += offset.x;
m_textInfo.characterInfo[i].xAdvance += offset.x;
m_textInfo.characterInfo[i].ascender += offset.y;
m_textInfo.characterInfo[i].descender += offset.y;
m_textInfo.characterInfo[i].baseLine += offset.y;
// Update MeshExtents
if (isCharacterVisible)
{
//m_meshExtents.min = new Vector2(Mathf.Min(m_meshExtents.min.x, m_textInfo.characterInfo[i].bottomLeft.x), Mathf.Min(m_meshExtents.min.y, m_textInfo.characterInfo[i].bottomLeft.y));
//m_meshExtents.max = new Vector2(Mathf.Max(m_meshExtents.max.x, m_textInfo.characterInfo[i].topRight.x), Mathf.Max(m_meshExtents.max.y, m_textInfo.characterInfo[i].topLeft.y));
}
// Need to recompute lineExtent to account for the offset from justification.
#region Adjust lineExtents resulting from alignment offset
if (currentLine != lastLine || i == m_characterCount - 1)
{
// Update the previous line's extents
if (currentLine != lastLine)
{
m_textInfo.lineInfo[lastLine].baseline += offset.y;
m_textInfo.lineInfo[lastLine].ascender += offset.y;
m_textInfo.lineInfo[lastLine].descender += offset.y;
m_textInfo.lineInfo[lastLine].lineExtents.min = new Vector2(m_textInfo.characterInfo[m_textInfo.lineInfo[lastLine].firstCharacterIndex].bottomLeft.x, m_textInfo.lineInfo[lastLine].descender);
m_textInfo.lineInfo[lastLine].lineExtents.max = new Vector2(m_textInfo.characterInfo[m_textInfo.lineInfo[lastLine].lastVisibleCharacterIndex].topRight.x, m_textInfo.lineInfo[lastLine].ascender);
}
// Update the current line's extents
if (i == m_characterCount - 1)
{
m_textInfo.lineInfo[currentLine].baseline += offset.y;
m_textInfo.lineInfo[currentLine].ascender += offset.y;
m_textInfo.lineInfo[currentLine].descender += offset.y;
m_textInfo.lineInfo[currentLine].lineExtents.min = new Vector2(m_textInfo.characterInfo[m_textInfo.lineInfo[currentLine].firstCharacterIndex].bottomLeft.x, m_textInfo.lineInfo[currentLine].descender);
m_textInfo.lineInfo[currentLine].lineExtents.max = new Vector2(m_textInfo.characterInfo[m_textInfo.lineInfo[currentLine].lastVisibleCharacterIndex].topRight.x, m_textInfo.lineInfo[currentLine].ascender);
}
}
#endregion
// Track Word Count per line and for the object
#region Track Word Count
if (char.IsLetterOrDigit(currentCharacter) || currentCharacter == 0x2D || currentCharacter == 0xAD || currentCharacter == 0x2010 || currentCharacter == 0x2011)
{
if (isStartOfWord == false)
{
isStartOfWord = true;
wordFirstChar = i;
}
// If last character is a word
if (isStartOfWord && i == m_characterCount - 1)
{
int size = m_textInfo.wordInfo.Length;
int index = m_textInfo.wordCount;
if (m_textInfo.wordCount + 1 > size)
TMP_TextInfo.Resize(ref m_textInfo.wordInfo, size + 1);
wordLastChar = i;
m_textInfo.wordInfo[index].firstCharacterIndex = wordFirstChar;
m_textInfo.wordInfo[index].lastCharacterIndex = wordLastChar;
m_textInfo.wordInfo[index].characterCount = wordLastChar - wordFirstChar + 1;
m_textInfo.wordInfo[index].textComponent = this;
wordCount += 1;
m_textInfo.wordCount += 1;
m_textInfo.lineInfo[currentLine].wordCount += 1;
}
}
else if (isStartOfWord || i == 0 && (!char.IsPunctuation(currentCharacter) || char.IsWhiteSpace(currentCharacter) || currentCharacter == 0x200B || i == m_characterCount - 1))
{
if (i > 0 && i < characterInfos.Length - 1 && i < m_characterCount && (currentCharacter == 39 || currentCharacter == 8217) && char.IsLetterOrDigit(characterInfos[i - 1].character) && char.IsLetterOrDigit(characterInfos[i + 1].character))
{
}
else
{
wordLastChar = i == m_characterCount - 1 && char.IsLetterOrDigit(currentCharacter) ? i : i - 1;
isStartOfWord = false;
int size = m_textInfo.wordInfo.Length;
int index = m_textInfo.wordCount;
if (m_textInfo.wordCount + 1 > size)
TMP_TextInfo.Resize(ref m_textInfo.wordInfo, size + 1);
m_textInfo.wordInfo[index].firstCharacterIndex = wordFirstChar;
m_textInfo.wordInfo[index].lastCharacterIndex = wordLastChar;
m_textInfo.wordInfo[index].characterCount = wordLastChar - wordFirstChar + 1;
m_textInfo.wordInfo[index].textComponent = this;
wordCount += 1;
m_textInfo.wordCount += 1;
m_textInfo.lineInfo[currentLine].wordCount += 1;
}
}
#endregion
// Setup & Handle Underline
#region Underline
// NOTE: Need to figure out how underline will be handled with multiple fonts and which font will be used for the underline.
bool isUnderline = (m_textInfo.characterInfo[i].style & FontStyles.Underline) == FontStyles.Underline;
if (isUnderline)
{
bool isUnderlineVisible = true;
int currentPage = m_textInfo.characterInfo[i].pageNumber;
if (i > m_maxVisibleCharacters || currentLine > m_maxVisibleLines || (m_overflowMode == TextOverflowModes.Page && currentPage + 1 != m_pageToDisplay))
isUnderlineVisible = false;
// We only use the scale of visible characters.
if (!char.IsWhiteSpace(currentCharacter) && currentCharacter != 0x200B)
{
underlineMaxScale = Mathf.Max(underlineMaxScale, m_textInfo.characterInfo[i].scale);
underlineBaseLine = Mathf.Min(currentPage == lastPage ? underlineBaseLine : k_LargePositiveFloat, m_textInfo.characterInfo[i].baseLine + font.fontInfo.Underline * underlineMaxScale);
lastPage = currentPage; // Need to track pages to ensure we reset baseline for the new pages.
}
if (beginUnderline == false && isUnderlineVisible == true && i <= lineInfo.lastVisibleCharacterIndex && currentCharacter != 10 && currentCharacter != 13)
{
if (i == lineInfo.lastVisibleCharacterIndex && char.IsSeparator(currentCharacter))
{ }
else
{
beginUnderline = true;
underlineStartScale = m_textInfo.characterInfo[i].scale;
if (underlineMaxScale == 0) underlineMaxScale = underlineStartScale;
underline_start = new Vector3(m_textInfo.characterInfo[i].bottomLeft.x, underlineBaseLine, 0);
underlineColor = m_textInfo.characterInfo[i].underlineColor;
}
}
// End Underline if text only contains one character.
if (beginUnderline && m_characterCount == 1)
{
beginUnderline = false;
underline_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, underlineBaseLine, 0);
underlineEndScale = m_textInfo.characterInfo[i].scale;
DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScale, underlineColor);
underlineMaxScale = 0;
underlineBaseLine = k_LargePositiveFloat;
}
else if (beginUnderline && (i == lineInfo.lastCharacterIndex || i >= lineInfo.lastVisibleCharacterIndex))
{
// Terminate underline at previous visible character if space or carriage return.
if (char.IsWhiteSpace(currentCharacter) || currentCharacter == 0x200B)
{
int lastVisibleCharacterIndex = lineInfo.lastVisibleCharacterIndex;
underline_end = new Vector3(m_textInfo.characterInfo[lastVisibleCharacterIndex].topRight.x, underlineBaseLine, 0);
underlineEndScale = m_textInfo.characterInfo[lastVisibleCharacterIndex].scale;
}
else
{ // End underline if last character of the line.
underline_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, underlineBaseLine, 0);
underlineEndScale = m_textInfo.characterInfo[i].scale;
}
beginUnderline = false;
DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScale, underlineColor);
underlineMaxScale = 0;
underlineBaseLine = k_LargePositiveFloat;
}
else if (beginUnderline && !isUnderlineVisible)
{
beginUnderline = false;
underline_end = new Vector3(m_textInfo.characterInfo[i - 1].topRight.x, underlineBaseLine, 0);
underlineEndScale = m_textInfo.characterInfo[i - 1].scale;
DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScale, underlineColor);
underlineMaxScale = 0;
underlineBaseLine = k_LargePositiveFloat;
}
else if (beginUnderline && i < m_characterCount - 1 && !underlineColor.Compare(m_textInfo.characterInfo[i + 1].underlineColor))
{
// End underline if underline color has changed.
beginUnderline = false;
underline_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, underlineBaseLine, 0);
underlineEndScale = m_textInfo.characterInfo[i].scale;
DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScale, underlineColor);
underlineMaxScale = 0;
underlineBaseLine = k_LargePositiveFloat;
}
}
else
{
// End Underline
if (beginUnderline == true)
{
beginUnderline = false;
underline_end = new Vector3(m_textInfo.characterInfo[i - 1].topRight.x, underlineBaseLine, 0);
underlineEndScale = m_textInfo.characterInfo[i - 1].scale;
DrawUnderlineMesh(underline_start, underline_end, ref last_vert_index, underlineStartScale, underlineEndScale, underlineMaxScale, xScale, underlineColor);
underlineMaxScale = 0;
underlineBaseLine = k_LargePositiveFloat;
}
}
#endregion
// Setup & Handle Strikethrough
#region Strikethrough
// NOTE: Need to figure out how underline will be handled with multiple fonts and which font will be used for the underline.
bool isStrikethrough = (m_textInfo.characterInfo[i].style & FontStyles.Strikethrough) == FontStyles.Strikethrough;
float strikethroughOffset = currentFontAsset.fontInfo.strikethrough;
if (isStrikethrough)
{
bool isStrikeThroughVisible = true;
if (i > m_maxVisibleCharacters || currentLine > m_maxVisibleLines || (m_overflowMode == TextOverflowModes.Page && m_textInfo.characterInfo[i].pageNumber + 1 != m_pageToDisplay))
isStrikeThroughVisible = false;
if (beginStrikethrough == false && isStrikeThroughVisible && i <= lineInfo.lastVisibleCharacterIndex && currentCharacter != 10 && currentCharacter != 13)
{
if (i == lineInfo.lastVisibleCharacterIndex && char.IsSeparator(currentCharacter))
{ }
else
{
beginStrikethrough = true;
strikethroughPointSize = m_textInfo.characterInfo[i].pointSize;
strikethroughScale = m_textInfo.characterInfo[i].scale;
strikethrough_start = new Vector3(m_textInfo.characterInfo[i].bottomLeft.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
strikethroughColor = m_textInfo.characterInfo[i].strikethroughColor;
strikethroughBaseline = m_textInfo.characterInfo[i].baseLine;
//Debug.Log("Char [" + currentCharacter + "] Start Strikethrough POS: " + strikethrough_start);
}
}
// End Strikethrough if text only contains one character.
if (beginStrikethrough && m_characterCount == 1)
{
beginStrikethrough = false;
strikethrough_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
}
else if (beginStrikethrough && i == lineInfo.lastCharacterIndex)
{
// Terminate Strikethrough at previous visible character if space or carriage return.
if (char.IsWhiteSpace(currentCharacter) || currentCharacter == 0x200B)
{
int lastVisibleCharacterIndex = lineInfo.lastVisibleCharacterIndex;
strikethrough_end = new Vector3(m_textInfo.characterInfo[lastVisibleCharacterIndex].topRight.x, m_textInfo.characterInfo[lastVisibleCharacterIndex].baseLine + strikethroughOffset * strikethroughScale, 0);
}
else
{
// Terminate Strikethrough at last character of line.
strikethrough_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
}
beginStrikethrough = false;
DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
}
else if (beginStrikethrough && i < m_characterCount && (m_textInfo.characterInfo[i + 1].pointSize != strikethroughPointSize || !TMP_Math.Approximately(m_textInfo.characterInfo[i + 1].baseLine + offset.y, strikethroughBaseline)))
{
// Terminate Strikethrough if scale changes.
beginStrikethrough = false;
int lastVisibleCharacterIndex = lineInfo.lastVisibleCharacterIndex;
if (i > lastVisibleCharacterIndex)
strikethrough_end = new Vector3(m_textInfo.characterInfo[lastVisibleCharacterIndex].topRight.x, m_textInfo.characterInfo[lastVisibleCharacterIndex].baseLine + strikethroughOffset * strikethroughScale, 0);
else
strikethrough_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
//Debug.Log("Char [" + currentCharacter + "] at Index: " + i + " End Strikethrough POS: " + strikethrough_end + " Baseline: " + m_textInfo.characterInfo[i].baseLine.ToString("f3"));
}
else if (beginStrikethrough && i < m_characterCount && currentFontAsset.GetInstanceID() != characterInfos[i + 1].fontAsset.GetInstanceID())
{
// Terminate Strikethrough if font asset changes.
beginStrikethrough = false;
strikethrough_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].baseLine + strikethroughOffset * strikethroughScale, 0);
DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
}
else if (beginStrikethrough && !isStrikeThroughVisible)
{
// Terminate Strikethrough if character is not visible.
beginStrikethrough = false;
strikethrough_end = new Vector3(m_textInfo.characterInfo[i - 1].topRight.x, m_textInfo.characterInfo[i - 1].baseLine + strikethroughOffset * strikethroughScale, 0);
DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
}
}
else
{
// End Strikethrough
if (beginStrikethrough == true)
{
beginStrikethrough = false;
strikethrough_end = new Vector3(m_textInfo.characterInfo[i - 1].topRight.x, m_textInfo.characterInfo[i - 1].baseLine + strikethroughOffset * strikethroughScale, 0);
DrawUnderlineMesh(strikethrough_start, strikethrough_end, ref last_vert_index, strikethroughScale, strikethroughScale, strikethroughScale, xScale, strikethroughColor);
}
}
#endregion
// HANDLE TEXT HIGHLIGHTING
#region Text Highlighting
bool isHighlight = (m_textInfo.characterInfo[i].style & FontStyles.Highlight) == FontStyles.Highlight;
if (isHighlight)
{
bool isHighlightVisible = true;
int currentPage = m_textInfo.characterInfo[i].pageNumber;
if (i > m_maxVisibleCharacters || currentLine > m_maxVisibleLines || (m_overflowMode == TextOverflowModes.Page && currentPage + 1 != m_pageToDisplay))
isHighlightVisible = false;
if (beginHighlight == false && isHighlightVisible == true && i <= lineInfo.lastVisibleCharacterIndex && currentCharacter != 10 && currentCharacter != 13)
{
if (i == lineInfo.lastVisibleCharacterIndex && char.IsSeparator(currentCharacter))
{ }
else
{
beginHighlight = true;
highlight_start = k_LargePositiveVector2;
highlight_end = k_LargeNegativeVector2;
highlightColor = m_textInfo.characterInfo[i].highlightColor;
}
}
if (beginHighlight)
{
Color32 currentHighlightColor = m_textInfo.characterInfo[i].highlightColor;
bool isColorTransition = false;
// Handle Highlight color changes
if (!highlightColor.Compare(currentHighlightColor))
{
// End drawing at the start of new highlight color to prevent a gap between highlight sections.
highlight_end.x = (highlight_end.x + m_textInfo.characterInfo[i].bottomLeft.x) / 2;
highlight_start.y = Mathf.Min(highlight_start.y, m_textInfo.characterInfo[i].descender);
highlight_end.y = Mathf.Max(highlight_end.y, m_textInfo.characterInfo[i].ascender);
DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightColor);
beginHighlight = true;
highlight_start = highlight_end;
highlight_end = new Vector3(m_textInfo.characterInfo[i].topRight.x, m_textInfo.characterInfo[i].descender, 0);
highlightColor = m_textInfo.characterInfo[i].highlightColor;
isColorTransition = true;
}
if (!isColorTransition)
{
// Use the Min / Max Extents of the Highlight area to handle different character sizes and fonts.
highlight_start.x = Mathf.Min(highlight_start.x, m_textInfo.characterInfo[i].bottomLeft.x); // - (1 * m_textInfo.characterInfo[i].scale));
highlight_start.y = Mathf.Min(highlight_start.y, m_textInfo.characterInfo[i].descender); // - (1 * m_textInfo.characterInfo[i].scale));
highlight_end.x = Mathf.Max(highlight_end.x, m_textInfo.characterInfo[i].topRight.x); // + (1 * m_textInfo.characterInfo[i].scale));
highlight_end.y = Mathf.Max(highlight_end.y, m_textInfo.characterInfo[i].ascender); // + (1 * m_textInfo.characterInfo[i].scale));
}
}
// End Highlight if text only contains one character.
if (beginHighlight && m_characterCount == 1)
{
beginHighlight = false;
DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightColor);
}
else if (beginHighlight && (i == lineInfo.lastCharacterIndex || i >= lineInfo.lastVisibleCharacterIndex))
{
beginHighlight = false;
DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightColor);
}
else if (beginHighlight && !isHighlightVisible)
{
beginHighlight = false;
DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightColor);
}
}
else
{
// End Highlight
if (beginHighlight == true)
{
beginHighlight = false;
DrawTextHighlight(highlight_start, highlight_end, ref last_vert_index, highlightColor);
}
}
#endregion
lastLine = currentLine;
}
#endregion
// METRICS ABOUT THE TEXT OBJECT
m_textInfo.characterCount = m_characterCount;
m_textInfo.spriteCount = m_spriteCount;
m_textInfo.lineCount = lineCount;
m_textInfo.wordCount = wordCount != 0 && m_characterCount > 0 ? wordCount : 1;
m_textInfo.pageCount = m_pageNumber + 1;
////Profiler.BeginSample("TMP Generate Text - Phase III");
// Update Mesh Vertex Data
if (m_renderMode == TextRenderFlags.Render && IsActive())
{
// Clear unused vertices
//m_textInfo.meshInfo[0].ClearUnusedVertices();
// Sort the geometry of the text object if needed.
if (m_geometrySortingOrder != VertexSortingOrder.Normal)
m_textInfo.meshInfo[0].SortGeometry(VertexSortingOrder.Reverse);
// Upload Mesh Data
m_mesh.MarkDynamic();
m_mesh.vertices = m_textInfo.meshInfo[0].vertices;
m_mesh.uv = m_textInfo.meshInfo[0].uvs0;
m_mesh.uv2 = m_textInfo.meshInfo[0].uvs2;
//m_mesh.uv4 = m_textInfo.meshInfo[0].uvs4;
m_mesh.colors32 = m_textInfo.meshInfo[0].colors32;
// Compute Bounds for the mesh. Manual computation is more efficient then using Mesh.recalcualteBounds.
m_mesh.RecalculateBounds();
//m_mesh.bounds = new Bounds(new Vector3((m_meshExtents.max.x + m_meshExtents.min.x) / 2, (m_meshExtents.max.y + m_meshExtents.min.y) / 2, 0) + offset, new Vector3(m_meshExtents.max.x - m_meshExtents.min.x, m_meshExtents.max.y - m_meshExtents.min.y, 0));
for (int i = 1; i < m_textInfo.materialCount; i++)
{
// Clear unused vertices
m_textInfo.meshInfo[i].ClearUnusedVertices();
if (m_subTextObjects[i] == null) continue;
// Sort the geometry of the sub-text objects if needed.
if (m_geometrySortingOrder != VertexSortingOrder.Normal)
m_textInfo.meshInfo[i].SortGeometry(VertexSortingOrder.Reverse);
m_subTextObjects[i].mesh.vertices = m_textInfo.meshInfo[i].vertices;
m_subTextObjects[i].mesh.uv = m_textInfo.meshInfo[i].uvs0;
m_subTextObjects[i].mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
//m_subTextObjects[i].mesh.uv4 = m_textInfo.meshInfo[i].uvs4;
m_subTextObjects[i].mesh.colors32 = m_textInfo.meshInfo[i].colors32;
m_subTextObjects[i].mesh.RecalculateBounds();
// Update the collider on the sub text object
//m_subTextObjects[i].UpdateColliders(m_textInfo.meshInfo[i].vertexCount);
}
}
// Event indicating the text has been regenerated.
TMPro_EventManager.ON_TEXT_CHANGED(this);
////Profiler.EndSample();
//Debug.Log("Done Rendering Text.");
}
/// <summary>
/// Method to return the local corners of the Text Container or RectTransform.
/// </summary>
/// <returns></returns>
protected override Vector3[] GetTextContainerLocalCorners()
{
if (m_rectTransform == null) m_rectTransform = this.rectTransform;
m_rectTransform.GetLocalCorners(m_RectTransformCorners);
return m_RectTransformCorners;
}
/// <summary>
/// Method to disable the renderers.
/// </summary>
void SetMeshFilters(bool state)
{
// Parent text object
if (m_meshFilter != null)
{
if (state)
m_meshFilter.sharedMesh = m_mesh;
else
m_meshFilter.sharedMesh = null;
}
for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
{
if (m_subTextObjects[i].meshFilter != null)
{
if (state)
m_subTextObjects[i].meshFilter.sharedMesh = m_subTextObjects[i].mesh;
else
m_subTextObjects[i].meshFilter.sharedMesh = null;
}
}
}
/// <summary>
/// Method to Enable or Disable child SubMesh objects.
/// </summary>
/// <param name="state"></param>
protected override void SetActiveSubMeshes(bool state)
{
for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
{
if (m_subTextObjects[i].enabled != state)
m_subTextObjects[i].enabled = state;
}
}
/// <summary>
/// Destroy Sub Mesh Objects
/// </summary>
protected override void ClearSubMeshObjects()
{
for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
{
Debug.Log("Destroying Sub Text object[" + i + "].");
DestroyImmediate(m_subTextObjects[i]);
}
}
/// <summary>
/// Method returning the compound bounds of the text object and child sub objects.
/// </summary>
/// <returns></returns>
protected override Bounds GetCompoundBounds()
{
Bounds mainBounds = m_mesh.bounds;
Vector3 min = mainBounds.min;
Vector3 max = mainBounds.max;
for (int i = 1; i < m_subTextObjects.Length && m_subTextObjects[i] != null; i++)
{
Bounds subBounds = m_subTextObjects[i].mesh.bounds;
min.x = min.x < subBounds.min.x ? min.x : subBounds.min.x;
min.y = min.y < subBounds.min.y ? min.y : subBounds.min.y;
max.x = max.x > subBounds.max.x ? max.x : subBounds.max.x;
max.y = max.y > subBounds.max.y ? max.y : subBounds.max.y;
}
Vector3 center = (min + max) / 2;
Vector2 size = max - min;
return new Bounds(center, size);
}
/// <summary>
/// Method to Update Scale in UV2
/// </summary>
void UpdateSDFScale(float lossyScale)
{
//Debug.Log("*** UpdateSDFScale() ***");
// Iterate through each of the characters.
for (int i = 0; i < m_textInfo.characterCount; i++)
{
// Only update scale for visible characters.
if (m_textInfo.characterInfo[i].isVisible && m_textInfo.characterInfo[i].elementType == TMP_TextElementType.Character)
{
float scale = lossyScale * m_textInfo.characterInfo[i].scale * (1 - m_charWidthAdjDelta);
if (!m_textInfo.characterInfo[i].isUsingAlternateTypeface && (m_textInfo.characterInfo[i].style & FontStyles.Bold) == FontStyles.Bold) scale *= -1;
int index = m_textInfo.characterInfo[i].materialReferenceIndex;
int vertexIndex = m_textInfo.characterInfo[i].vertexIndex;
m_textInfo.meshInfo[index].uvs2[vertexIndex + 0].y = scale;
m_textInfo.meshInfo[index].uvs2[vertexIndex + 1].y = scale;
m_textInfo.meshInfo[index].uvs2[vertexIndex + 2].y = scale;
m_textInfo.meshInfo[index].uvs2[vertexIndex + 3].y = scale;
}
}
// Push the updated uv2 scale information to the meshes.
for (int i = 0; i < m_textInfo.meshInfo.Length; i++)
{
if (i == 0)
m_mesh.uv2 = m_textInfo.meshInfo[0].uvs2;
else
m_subTextObjects[i].mesh.uv2 = m_textInfo.meshInfo[i].uvs2;
}
}
// Function to offset vertices position to account for line spacing changes.
protected override void AdjustLineOffset(int startIndex, int endIndex, float offset)
{
Vector3 vertexOffset = new Vector3(0, offset, 0);
for (int i = startIndex; i <= endIndex; i++)
{
m_textInfo.characterInfo[i].bottomLeft -= vertexOffset;
m_textInfo.characterInfo[i].topLeft -= vertexOffset;
m_textInfo.characterInfo[i].topRight -= vertexOffset;
m_textInfo.characterInfo[i].bottomRight -= vertexOffset;
m_textInfo.characterInfo[i].ascender -= vertexOffset.y;
m_textInfo.characterInfo[i].baseLine -= vertexOffset.y;
m_textInfo.characterInfo[i].descender -= vertexOffset.y;
if (m_textInfo.characterInfo[i].isVisible)
{
m_textInfo.characterInfo[i].vertex_BL.position -= vertexOffset;
m_textInfo.characterInfo[i].vertex_TL.position -= vertexOffset;
m_textInfo.characterInfo[i].vertex_TR.position -= vertexOffset;
m_textInfo.characterInfo[i].vertex_BR.position -= vertexOffset;
}
}
}
}
} | 0 | 0.9262 | 1 | 0.9262 | game-dev | MEDIA | 0.801774 | game-dev,graphics-rendering | 0.95855 | 1 | 0.95855 |
CoderGamester/mcp-unity | 6,442 | Server~/src/resources/getGameObjectResource.ts | import { Logger } from '../utils/logger.js';
import { ResourceTemplate, McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { ReadResourceResult } from '@modelcontextprotocol/sdk/types.js';
import { McpUnity } from '../unity/mcpUnity.js';
import { Variables } from '@modelcontextprotocol/sdk/shared/uriTemplate.js';
import { McpUnityError, ErrorType } from '../utils/errors.js';
import { resourceName as hierarchyResourceName } from './getScenesHierarchyResource.js';
// Constants for the resource
const resourceName = 'get_gameobject';
const resourceUri = 'unity://gameobject/{idOrName}';
const resourceMimeType = 'application/json';
/**
* Creates and registers the GameObject resource with the MCP server
* This resource provides access to GameObjects in Unity scenes
*
* @param server The MCP server instance to register with
* @param mcpUnity The McpUnity instance to communicate with Unity
* @param logger The logger instance for diagnostic information
*/
export function registerGetGameObjectResource(server: McpServer, mcpUnity: McpUnity, logger: Logger) {
// Create a resource template with the MCP SDK
const resourceTemplate = new ResourceTemplate(
resourceUri,
{
// This list method is commented because is calling getHierarchyResource every second to the MCP client in the current format.
// TODO: Find a new way to implement this so that it doesn't request the list of game objects so often
list: undefined//async () => listGameObjects(mcpUnity, logger, resourceMimeType)
}
);
logger.info(`Registering resource: ${resourceName}`);
// Register this resource with the MCP server
server.resource(
resourceName,
resourceTemplate,
{
description: 'Retrieve a GameObject by instance ID, name, or hierarchical path (e.g., "Parent/Child/MyObject")',
mimeType: resourceMimeType
},
async (uri, variables) => {
try {
return await resourceHandler(mcpUnity, uri, variables, logger);
} catch (error) {
logger.error(`Error handling resource ${resourceName}: ${error}`);
throw error;
}
}
);
}
/**
* Handles requests for GameObject information from Unity
*
* @param mcpUnity The McpUnity instance to communicate with Unity
* @param uri The requested resource URI
* @param variables Variables extracted from the URI template
* @param logger The logger instance for diagnostic information
* @returns A promise that resolves to the GameObject data
* @throws McpUnityError if the request to Unity fails
*/
async function resourceHandler(mcpUnity: McpUnity, uri: URL, variables: Variables, logger: Logger): Promise<ReadResourceResult> {
// Extract and convert the parameter from the template variables
const idOrName = decodeURIComponent(variables["idOrName"] as string);
// Send request to Unity
const response = await mcpUnity.sendRequest({
method: resourceName,
params: {
idOrName: idOrName
}
});
if (!response.success) {
throw new McpUnityError(
ErrorType.RESOURCE_FETCH,
response.message || 'Failed to fetch GameObject from Unity'
);
}
return {
contents: [{
uri: `unity://gameobject/${idOrName}`,
mimeType: resourceMimeType,
text: JSON.stringify(response, null, 2)
}]
};
}
/**
* Get a list of all GameObjects in the scene
* @param mcpUnity The McpUnity instance to communicate with Unity
* @param logger The logger instance
* @param resourceMimeType The MIME type for the resource
* @returns A promise that resolves to a list of GameObject resources
*/
async function listGameObjects(mcpUnity: McpUnity, logger: Logger, resourceMimeType: string) {
const hierarchyResponse = await mcpUnity.sendRequest({
method: hierarchyResourceName,
params: {}
});
if (!hierarchyResponse.success) {
logger.error(`Failed to fetch hierarchy: ${hierarchyResponse.message}`);
throw new Error(hierarchyResponse.message || 'Failed to fetch hierarchy');
}
// Process the hierarchy to create a list of GameObject references
const gameObjects = processHierarchyToGameObjectList(hierarchyResponse.hierarchy || []);
logger.info(`[getGameObjectResource] Fetched hierarchy with ${gameObjects.length} GameObjects ${hierarchyResponse.hierarchy}`);
// Create resources array with both instance ID and path URIs
const resources: Array<{
uri: string;
name: string;
description: string;
mimeType: string;
}> = [];
// Add resources for each GameObject
gameObjects.forEach(obj => {
// Add resource with instance ID URI
resources.push({
uri: `unity://gameobject/${obj.instanceId}`,
name: obj.name,
description: `GameObject with instance ID ${obj.instanceId} at path: ${obj.path}`,
mimeType: resourceMimeType
});
// Add resource with path URI if path exists
if (obj.path) {
resources.push({
uri: `unity://gameobject/${encodeURIComponent(obj.path)}`,
name: obj.name,
description: `GameObject with instance ID ${obj.instanceId} at path: ${obj.path}`,
mimeType: resourceMimeType
});
}
});
return { resources };
}
/**
* Process the hierarchy data to create a list of GameObject references
* @param hierarchyData The hierarchy data from Unity
* @returns An array of GameObject references with their instance IDs and paths
*/
function processHierarchyToGameObjectList(hierarchyData: any): any[] {
const gameObjects: any[] = [];
// Helper function to traverse the hierarchy recursively
function traverseHierarchy(node: any, path: string = ''): void {
if (!node) return;
// Current path is parent path + node name
const currentPath = path ? `${path}/${node.name}` : node.name;
// Add this GameObject to the list
gameObjects.push({
instanceId: node.instanceId,
name: node.name,
path: currentPath,
active: node.active,
uri: `unity://gameobject/${node.instanceId}`
});
// Process children recursively
if (node.children && Array.isArray(node.children)) {
for (const child of node.children) {
traverseHierarchy(child, currentPath);
}
}
}
// Start traversal with each root GameObject
if (Array.isArray(hierarchyData)) {
for (const rootNode of hierarchyData) {
traverseHierarchy(rootNode);
}
}
return gameObjects;
}
| 0 | 0.859088 | 1 | 0.859088 | game-dev | MEDIA | 0.865753 | game-dev | 0.859064 | 1 | 0.859064 |
Pokechu22/WorldDownloader | 12,285 | share/src/main/java/wdl/WDLMessages.java | /*
* This file is part of World Downloader: A mod to make backups of your multiplayer worlds.
* https://www.minecraftforum.net/forums/mapping-and-modding-java-edition/minecraft-mods/2520465-world-downloader-mod-create-backups-of-your-builds
*
* Copyright (c) 2014 nairol, cubic72
* Copyright (c) 2017-2020 Pokechu22, julialy
*
* This project is licensed under the MMPLv2. The full text of the MMPL can be
* found in LICENSE.md, or online at https://github.com/iopleke/MMPLv2/blob/master/LICENSE.md
* For information about this the MMPLv2, see https://stopmodreposts.org/
*
* Do not redistribute (in modified or unmodified form) without prior permission.
*/
package wdl;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.event.HoverEvent;
import net.minecraft.util.text.event.HoverEvent.Action;
import wdl.api.IWDLMessageType;
import wdl.config.CyclableSetting;
import wdl.config.IConfiguration;
import wdl.config.settings.MessageSettings;
/**
* Responsible for displaying messages in chat or the log, depending on whether
* they are enabled.
*/
public class WDLMessages {
private static final Logger LOGGER = LogManager.getLogger();
/**
* Information about an individual message type.
*/
public static class MessageRegistration {
public final String name;
public final IWDLMessageType type;
public final MessageTypeCategory category;
public final CyclableSetting<Boolean> setting;
/**
* Creates a MessageRegistration.
*
* @param name The name to use.
* @param type The type bound to this registration.
* @param category The category.
*/
public MessageRegistration(String name, IWDLMessageType type,
MessageTypeCategory category) {
this.name = name;
this.type = type;
this.category = category;
this.setting = new MessageSettings.MessageTypeSetting(this);
}
@Override
public String toString() {
return "MessageRegistration [name=" + name + ", type=" + type
+ ", category=" + category + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((category == null) ? 0 : category.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MessageRegistration)) {
return false;
}
MessageRegistration other = (MessageRegistration) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (category == null) {
if (other.category != null) {
return false;
}
} else if (!category.equals(other.category)) {
return false;
}
if (type == null) {
if (other.type != null) {
return false;
}
} else if (!type.equals(other.type)) {
return false;
}
return true;
}
}
/**
* List of all registrations, by category.
*/
private static ListMultimap<MessageTypeCategory, MessageRegistration> registrations = LinkedListMultimap.create();
/**
* Gets the {@link MessageRegistration} for the given name.
* @param name The name to look for
* @return The registration
* @throws IllegalArgumentException for unknown names
*/
@Nonnull
public static MessageRegistration getRegistration(String name) {
for (MessageRegistration r : registrations.values()) {
if (r.name.equals(name)) {
return r;
}
}
throw new IllegalArgumentException("Asked for the registration for " + name + ", but there is no registration for that!");
}
/**
* Gets the {@link MessageRegistration} for the given {@link IWDLMessageType}.
* @param type The type to look for
* @return The registration
* @throws IllegalArgumentException for unknown names
*/
@Nonnull
public static MessageRegistration getRegistration(IWDLMessageType type) {
for (MessageRegistration r : registrations.values()) {
if (r.type.equals(type)) {
return r;
}
}
throw new IllegalArgumentException("Asked for the registration for " + type + ", but there is no registration for that!");
}
/**
* Adds registration for another type of message.
*
* @param name The programmatic name.
* @param type The type.
* @param category The category.
*/
public static void registerMessage(String name, IWDLMessageType type,
MessageTypeCategory category) {
registrations.put(category, new MessageRegistration(name, type, category));
}
/**
* Gets all of the MessageTypes
* @return All the types, ordered by the category.
*/
@Nonnull
public static ListMultimap<MessageTypeCategory, MessageRegistration> getRegistrations() {
return ImmutableListMultimap.copyOf(registrations);
}
/**
* Prints the given message into the chat.
*
* @param config Configuration to use to check if a message is enabled
* @param type The type of the message.
* @param message The message to display.
*/
public static void chatMessage(@Nonnull IConfiguration config,
@Nonnull IWDLMessageType type, @Nonnull String message) {
chatMessage(config, type, new TextComponentString(message));
}
/**
* Prints a translated chat message into the chat.
*
* @param config
* Configuration to use to check if a message is enabled
* @param type
* The type of the message.
* @param translationKey
* I18n key that is translated.
* @param args
* The arguments to pass to the {@link TextComponentTranslation}.
* A limited amount of processing is performed: {@link Entity}s
* will be converted properly with a tooltip like the one
* generated by {@link Entity#getDisplayName()}.
*/
public static void chatMessageTranslated(@Nonnull IConfiguration config,
@Nonnull IWDLMessageType type, @Nonnull String translationKey, @Nonnull Object... args) {
List<Throwable> exceptionsToPrint = new ArrayList<>();
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
TextComponentString text = new TextComponentString("null");
text.getStyle().setHoverEvent(new HoverEvent(Action.SHOW_TEXT, new TextComponentString("~~null~~")));
args[i] = text;
} else if (args[i] instanceof Entity) {
Entity e = (Entity)args[i];
args[i] = convertEntityToComponent(e);
} else if (args[i] instanceof Throwable) {
Throwable t = (Throwable) args[i];
args[i] = convertThrowableToComponent(t);
exceptionsToPrint.add(t);
} else if (args[i] instanceof BlockPos) {
// Manually toString BlockPos instances to deal with obfuscation
BlockPos pos = (BlockPos) args[i];
args[i] = String.format("Pos[x=%d, y=%d, z=%d]", pos.getX(), pos.getY(), pos.getZ());
}
}
final ITextComponent component;
if (I18n.hasKey(translationKey)) {
component = new TextComponentTranslation(translationKey, args);
} else {
// Oh boy, no translation text. Manually apply parameters.
String message = translationKey;
component = new TextComponentString(message);
component.appendText("[");
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof ITextComponent) {
component.appendSibling((ITextComponent) args[i]);
} else {
component.appendText(String.valueOf(args[i]));
}
if (i != args.length - 1) {
component.appendText(", ");
}
}
component.appendText("]");
}
chatMessage(config, type, component);
for (int i = 0; i < exceptionsToPrint.size(); i++) {
LOGGER.warn("Exception #" + (i + 1) + ": ", exceptionsToPrint.get(i));
}
}
/**
* Prints the given message into the chat.
*
* @param config Configuration to use to check if a message is enabled
* @param type The type of the message.
* @param message The message to display.
*/
public static void chatMessage(@Nonnull IConfiguration config,
@Nonnull IWDLMessageType type, @Nonnull ITextComponent message) {
boolean enabled;
try {
MessageRegistration registration = getRegistration(type);
enabled = config.getValue(registration.setting);
} catch (Exception ex) {
enabled = false;
LOGGER.error("Failed to check if type was enabled: " + type, ex);
}
// Can't use a TextComponentTranslation here because it doesn't like new lines.
String tooltipText = I18n.format("wdl.messages.tooltip",
type.getDisplayName().getFormattedText()).replace("\\n", "\n");
ITextComponent tooltip = new TextComponentString(tooltipText);
ITextComponent text = new TextComponentString("");
ITextComponent header = new TextComponentString("[WorldDL]");
header.getStyle().setColor(type.getTitleColor());
header.getStyle().setHoverEvent(
new HoverEvent(Action.SHOW_TEXT, tooltip));
// If the message has its own style, it'll use that instead.
// TODO: Better way?
TextComponentString messageFormat = new TextComponentString(" ");
messageFormat.getStyle().setColor(type.getTextColor());
messageFormat.appendSibling(message);
text.appendSibling(header);
text.appendSibling(messageFormat);
if (enabled) {
Minecraft minecraft = Minecraft.getInstance();
// Cross-thread calls to printChatMessage are illegal in 1.13 due to accessing
// the font renderer; add a scheduled task instead.
minecraft.execute(() -> minecraft.ingameGUI.getChatGUI().printChatMessage(text));
} else {
LOGGER.info(text.getString());
}
}
@Nonnull
private static ITextComponent convertEntityToComponent(@Nonnull Entity e) {
ITextComponent wdlName, displayName;
try {
String identifier = EntityUtils.getEntityType(e);
if (identifier == null) {
wdlName = new TextComponentTranslation("wdl.messages.entityData.noKnownName");
} else {
String group = EntityUtils.getEntityGroup(identifier);
String displayIdentifier = EntityUtils.getDisplayType(identifier);
String displayGroup = EntityUtils.getDisplayGroup(group);
wdlName = new TextComponentString(displayIdentifier);
ITextComponent hoverText = new TextComponentString("");
hoverText.appendSibling(new TextComponentTranslation("wdl.messages.entityData.internalName", identifier));
hoverText.appendText("\n");
hoverText.appendSibling(new TextComponentTranslation("wdl.messages.entityData.group", displayGroup, group));
wdlName.getStyle().setHoverEvent(new HoverEvent(Action.SHOW_TEXT, hoverText));
}
} catch (Exception ex) {
LOGGER.warn("[WDL] Exception in entity name!", ex);
wdlName = convertThrowableToComponent(ex);
}
try {
displayName = e.getDisplayName();
} catch (Exception ex) {
LOGGER.warn("[WDL] Exception in entity display name!", ex);
displayName = convertThrowableToComponent(ex);
}
return new TextComponentTranslation("wdl.messages.entityData", wdlName, displayName);
}
@Nonnull
private static ITextComponent convertThrowableToComponent(@Nonnull Throwable t) {
ITextComponent component = new TextComponentString(t.toString());
// https://stackoverflow.com/a/1149721/3991344
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
exceptionAsString = exceptionAsString.replace("\r", "")
.replace("\t", " ");
HoverEvent event = new HoverEvent(Action.SHOW_TEXT,
new TextComponentString(exceptionAsString));
component.getStyle().setHoverEvent(event);
return component;
}
static {
for (WDLMessageTypes type : WDLMessageTypes.values()) {
registerMessage(type.name(), type, type.category);
}
}
}
| 0 | 0.914165 | 1 | 0.914165 | game-dev | MEDIA | 0.737248 | game-dev,web-backend | 0.93118 | 1 | 0.93118 |
Polka37/Krastorio2-spaced-out | 2,436 | prototypes/buildings/warehouse.lua | local hit_effects = require("__base__.prototypes.entity.hit-effects")
local sounds = require("__base__.prototypes.entity.sounds")
if not settings.startup["kr-containers"].value then
return
end
data:extend({
{
type = "recipe",
name = "kr-warehouse",
energy_required = 1,
enabled = false,
ingredients = {
{ type = "item", name = "kr-strongbox", amount = 4 },
{ type = "item", name = "kr-steel-beam", amount = 10 },
},
results = { { type = "item", name = "kr-warehouse", amount = 1 } },
},
{
type = "item",
name = "kr-warehouse",
icon = "__Krastorio2Assets__/icons/entities/warehouse.png",
subgroup = "kr-warehouse",
order = "a[warehouse]",
place_result = "kr-warehouse",
stack_size = 50,
weight = 100*kg,
},
{
type = "container",
name = "kr-warehouse",
icon = "__Krastorio2Assets__/icons/entities/warehouse.png",
flags = { "placeable-player", "player-creation" },
fast_replaceable_group = "container",
minable = { mining_time = 1, result = "kr-warehouse" },
collision_box = { { -2.75, -2.75 }, { 2.75, 2.75 } },
selection_box = { { -3, -3 }, { 3, 3 } },
inventory_size = 500,
max_health = 1500,
surface_conditions = {
{ property = "pressure", min = 0.1, }
},
corpse = "kr-big-random-pipes-remnants",
damaged_trigger_effect = hit_effects.entity(),
resistances = {
{ type = "physical", percent = 50 },
{ type = "fire", percent = 75 },
{ type = "impact", percent = 75 },
},
open_sound = sounds.machine_open,
close_sound = sounds.machine_close,
vehicle_impact_sound = sounds.generic_impact,
picture = {
filename = "__Krastorio2Assets__/buildings/warehouse/warehouse.png",
priority = "extra-high",
width = 512,
height = 512,
frame_count = 6,
line_length = 3,
scale = 0.5,
},
water_reflection = {
pictures = {
filename = "__Krastorio2Assets__/buildings/warehouse/warehouse-reflection.png",
priority = "extra-high",
width = 60,
height = 50,
shift = util.by_pixel(0, 40),
variation_count = 1,
scale = 5,
},
rotate = false,
orientation_to_variation = false,
},
opened_duration = logistic_chest_opened_duration,
circuit_connector = circuit_connector_definitions["chest"],
circuit_wire_max_distance = 20,
},
})
| 0 | 0.804832 | 1 | 0.804832 | game-dev | MEDIA | 0.991218 | game-dev | 0.664013 | 1 | 0.664013 |
spatialos/gdk-for-unity | 1,418 | workers/unity/Packages/io.improbable.gdk.playerlifecycle/Representation/Types/OwningWorkerEntityResolver.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Improbable.Gdk.Core;
using Improbable.Gdk.Core.Representation;
using Unity.Entities;
using UnityEngine;
namespace Improbable.Gdk.PlayerLifecycle.Representation.Types
{
[Serializable]
public class OwningWorkerEntityResolver : IEntityRepresentationResolver
{
public string EntityType => entityType;
public IEnumerable<uint> RequiredComponents => requiredComponents.Append(OwningWorker.ComponentId);
#pragma warning disable 649
[SerializeField] private string entityType;
[SerializeField] private GameObject ownedPrefab;
[SerializeField] private GameObject unownedPrefab;
[SerializeField] private uint[] requiredComponents = { };
#pragma warning restore 649
public GameObject Resolve(SpatialOSEntityInfo entityInfo, EntityManager manager)
{
var owningWorkerId = manager.GetComponentData<OwningWorker.Component>(entityInfo.Entity).WorkerId;
var myWorkerId = manager.World.GetExistingSystem<WorkerSystem>().WorkerId;
return owningWorkerId == myWorkerId
? ownedPrefab
: unownedPrefab;
}
public void DeclareReferencedPrefabs(List<GameObject> referencedPrefabs)
{
referencedPrefabs.Add(ownedPrefab);
referencedPrefabs.Add(unownedPrefab);
}
}
}
| 0 | 0.701764 | 1 | 0.701764 | game-dev | MEDIA | 0.666342 | game-dev | 0.765924 | 1 | 0.765924 |
ModificationStation/StationAPI | 1,302 | station-items-v0/src/main/java/net/modificationstation/stationapi/impl/entity/player/ItemCustomReachImpl.java | package net.modificationstation.stationapi.impl.entity.player;
import net.mine_diver.unsafeevents.listener.EventListener;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.modificationstation.stationapi.api.StationAPI;
import net.modificationstation.stationapi.api.event.entity.player.PlayerEvent;
import net.modificationstation.stationapi.api.item.CustomReachProvider;
import net.modificationstation.stationapi.api.mod.entrypoint.Entrypoint;
import net.modificationstation.stationapi.api.mod.entrypoint.EntrypointManager;
import net.modificationstation.stationapi.api.mod.entrypoint.EventBusPolicy;
import java.lang.invoke.MethodHandles;
@Entrypoint(eventBus = @EventBusPolicy(registerInstance = false))
@EventListener(phase = StationAPI.INTERNAL_PHASE)
public final class ItemCustomReachImpl {
static {
EntrypointManager.registerLookup(MethodHandles.lookup());
}
@EventListener
private static void getReach(PlayerEvent.Reach event) {
ItemStack stack = event.player.getHand();
if (stack != null) {
Item item = stack.getItem();
if (item instanceof CustomReachProvider provider)
event.currentReach = provider.getReach(stack, event.player, event.type, event.currentReach);
}
}
} | 0 | 0.807392 | 1 | 0.807392 | game-dev | MEDIA | 0.888874 | game-dev | 0.502771 | 1 | 0.502771 |
gta-reversed/gta-reversed | 1,150 | source/game_sa/Tasks/TaskTypes/TaskSimpleCarSetPedInAsPassenger.cpp | #include "StdInc.h"
#include "TaskSimpleCarSetPedInAsPassenger.h"
#include "TaskUtilityLineUpPedWithCar.h"
// OG constructor was at 0x646FE0
CTaskSimpleCarSetPedInAsPassenger::CTaskSimpleCarSetPedInAsPassenger(CVehicle* targetVehicle, eTargetDoor nTargetDoor, bool warpingInToCar, CTaskUtilityLineUpPedWithCar* utility) :
m_nTargetDoor{ nTargetDoor },
m_pTargetVehicle{ targetVehicle },
m_pUtility{ utility },
m_bWarpingInToCar{warpingInToCar}
{
CEntity::SafeRegisterRef(m_pTargetVehicle);
}
// For 0x649D90
CTaskSimpleCarSetPedInAsPassenger::CTaskSimpleCarSetPedInAsPassenger(const CTaskSimpleCarSetPedInAsPassenger& o) :
CTaskSimpleCarSetPedInAsPassenger{
o.m_pTargetVehicle,
o.m_nTargetDoor,
o.m_bWarpingInToCar,
o.m_pUtility
}
{
m_nNumGettingInToClear = o.m_nNumGettingInToClear;
}
// 0x647080
CTaskSimpleCarSetPedInAsPassenger::~CTaskSimpleCarSetPedInAsPassenger() {
CEntity::SafeCleanUpRef(m_pTargetVehicle);
}
// 0x64B5D0
bool CTaskSimpleCarSetPedInAsPassenger::ProcessPed(CPed* ped) {
return plugin::CallMethodAndReturn<bool, 0x64B5D0, CTask*, CPed*>(this, ped);
}
| 0 | 0.74691 | 1 | 0.74691 | game-dev | MEDIA | 0.342944 | game-dev | 0.536503 | 1 | 0.536503 |
wenanlee/EFramework | 1,730 | Leopotam/EditorHelpers/Editor/PostSolutionGenerationAttribute.cs | // ----------------------------------------------------------------------------
// The MIT License
// LeopotamGroupLibrary https://github.com/Leopotam/LeopotamGroupLibraryUnity
// Copyright (c) 2012-2019 Leopotam <leopotam@gmail.com>
// ----------------------------------------------------------------------------
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace EFramework.EditorHelpers.UnityEditors {
/// <summary>
/// Post solution generation attribute. Methods with PostSolutionGeneration attribute will be executed after C# project recompile.
/// </summary>
[AttributeUsage (AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class PostSolutionGenerationAttribute : Attribute {
class PostSolutionGenerationProcessor : AssetPostprocessor {
static void OnGeneratedCSProjectFiles () {
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies ()) {
foreach (var type in assembly.GetTypes ()) {
foreach (var method in type.GetMethods (BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) {
var attrs = method.GetCustomAttributes (typeof (PostSolutionGenerationAttribute), false);
if (attrs.Length > 0) {
try {
method.Invoke (null, null);
} catch (Exception ex) {
Debug.LogError (ex);
}
}
}
}
}
}
}
}
} | 0 | 0.858983 | 1 | 0.858983 | game-dev | MEDIA | 0.744667 | game-dev | 0.890207 | 1 | 0.890207 |
LessonStudio/Arduino_BLE_iOS_CPP | 79,654 | iOS_Example/cocos2d/plugin/luabindings/auto/lua_cocos2dx_pluginx_auto.cpp | #include "lua_cocos2dx_pluginx_auto.hpp"
#include "PluginManager.h"
#include "ProtocolAnalytics.h"
#include "ProtocolIAP.h"
#include "ProtocolAds.h"
#include "ProtocolShare.h"
#include "ProtocolSocial.h"
#include "ProtocolUser.h"
#include "AgentManager.h"
#include "FacebookAgent.h"
#include "tolua_fix.h"
#include "LuaBasicConversions.h"
#include "lua_pluginx_basic_conversions.h"
int lua_pluginx_protocols_PluginProtocol_getPluginName(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::PluginProtocol* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.PluginProtocol",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::PluginProtocol*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_PluginProtocol_getPluginName'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_PluginProtocol_getPluginName'", nullptr);
return 0;
}
const char* ret = cobj->getPluginName();
tolua_pushstring(tolua_S,(const char*)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.PluginProtocol:getPluginName",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_PluginProtocol_getPluginName'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_PluginProtocol_getPluginVersion(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::PluginProtocol* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.PluginProtocol",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::PluginProtocol*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_PluginProtocol_getPluginVersion'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_PluginProtocol_getPluginVersion'", nullptr);
return 0;
}
std::string ret = cobj->getPluginVersion();
tolua_pushcppstring(tolua_S,ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.PluginProtocol:getPluginVersion",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_PluginProtocol_getPluginVersion'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_PluginProtocol_getSDKVersion(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::PluginProtocol* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.PluginProtocol",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::PluginProtocol*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_PluginProtocol_getSDKVersion'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_PluginProtocol_getSDKVersion'", nullptr);
return 0;
}
std::string ret = cobj->getSDKVersion();
tolua_pushcppstring(tolua_S,ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.PluginProtocol:getSDKVersion",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_PluginProtocol_getSDKVersion'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_PluginProtocol_setDebugMode(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::PluginProtocol* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.PluginProtocol",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::PluginProtocol*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_PluginProtocol_setDebugMode'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
bool arg0;
ok &= luaval_to_boolean(tolua_S, 2,&arg0, "plugin.PluginProtocol:setDebugMode");
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_PluginProtocol_setDebugMode'", nullptr);
return 0;
}
cobj->setDebugMode(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.PluginProtocol:setDebugMode",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_PluginProtocol_setDebugMode'.",&tolua_err);
#endif
return 0;
}
static int lua_pluginx_protocols_PluginProtocol_finalize(lua_State* tolua_S)
{
printf("luabindings: finalizing LUA object (PluginProtocol)");
return 0;
}
int lua_register_pluginx_protocols_PluginProtocol(lua_State* tolua_S)
{
tolua_usertype(tolua_S,"plugin.PluginProtocol");
tolua_cclass(tolua_S,"PluginProtocol","plugin.PluginProtocol","",nullptr);
tolua_beginmodule(tolua_S,"PluginProtocol");
tolua_function(tolua_S,"getPluginName",lua_pluginx_protocols_PluginProtocol_getPluginName);
tolua_function(tolua_S,"getPluginVersion",lua_pluginx_protocols_PluginProtocol_getPluginVersion);
tolua_function(tolua_S,"getSDKVersion",lua_pluginx_protocols_PluginProtocol_getSDKVersion);
tolua_function(tolua_S,"setDebugMode",lua_pluginx_protocols_PluginProtocol_setDebugMode);
tolua_endmodule(tolua_S);
std::string typeName = typeid(cocos2d::plugin::PluginProtocol).name();
g_luaType[typeName] = "plugin.PluginProtocol";
g_typeCast["PluginProtocol"] = "plugin.PluginProtocol";
return 1;
}
int lua_pluginx_protocols_PluginManager_unloadPlugin(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::PluginManager* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.PluginManager",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::PluginManager*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_PluginManager_unloadPlugin'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
const char* arg0;
std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "plugin.PluginManager:unloadPlugin"); arg0 = arg0_tmp.c_str();
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_PluginManager_unloadPlugin'", nullptr);
return 0;
}
cobj->unloadPlugin(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.PluginManager:unloadPlugin",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_PluginManager_unloadPlugin'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_PluginManager_loadPlugin(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::PluginManager* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.PluginManager",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::PluginManager*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_PluginManager_loadPlugin'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
const char* arg0;
std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "plugin.PluginManager:loadPlugin"); arg0 = arg0_tmp.c_str();
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_PluginManager_loadPlugin'", nullptr);
return 0;
}
cocos2d::plugin::PluginProtocol* ret = cobj->loadPlugin(arg0);
object_to_luaval<cocos2d::plugin::PluginProtocol>(tolua_S, "plugin.PluginProtocol",(cocos2d::plugin::PluginProtocol*)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.PluginManager:loadPlugin",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_PluginManager_loadPlugin'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_PluginManager_end(lua_State* tolua_S)
{
int argc = 0;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertable(tolua_S,1,"plugin.PluginManager",0,&tolua_err)) goto tolua_lerror;
#endif
argc = lua_gettop(tolua_S) - 1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_PluginManager_end'", nullptr);
return 0;
}
cocos2d::plugin::PluginManager::end();
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "plugin.PluginManager:end",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_PluginManager_end'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_PluginManager_getInstance(lua_State* tolua_S)
{
int argc = 0;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertable(tolua_S,1,"plugin.PluginManager",0,&tolua_err)) goto tolua_lerror;
#endif
argc = lua_gettop(tolua_S) - 1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_PluginManager_getInstance'", nullptr);
return 0;
}
cocos2d::plugin::PluginManager* ret = cocos2d::plugin::PluginManager::getInstance();
object_to_luaval<cocos2d::plugin::PluginManager>(tolua_S, "plugin.PluginManager",(cocos2d::plugin::PluginManager*)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "plugin.PluginManager:getInstance",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_PluginManager_getInstance'.",&tolua_err);
#endif
return 0;
}
static int lua_pluginx_protocols_PluginManager_finalize(lua_State* tolua_S)
{
printf("luabindings: finalizing LUA object (PluginManager)");
return 0;
}
int lua_register_pluginx_protocols_PluginManager(lua_State* tolua_S)
{
tolua_usertype(tolua_S,"plugin.PluginManager");
tolua_cclass(tolua_S,"PluginManager","plugin.PluginManager","",nullptr);
tolua_beginmodule(tolua_S,"PluginManager");
tolua_function(tolua_S,"unloadPlugin",lua_pluginx_protocols_PluginManager_unloadPlugin);
tolua_function(tolua_S,"loadPlugin",lua_pluginx_protocols_PluginManager_loadPlugin);
tolua_function(tolua_S,"end", lua_pluginx_protocols_PluginManager_end);
tolua_function(tolua_S,"getInstance", lua_pluginx_protocols_PluginManager_getInstance);
tolua_endmodule(tolua_S);
std::string typeName = typeid(cocos2d::plugin::PluginManager).name();
g_luaType[typeName] = "plugin.PluginManager";
g_typeCast["PluginManager"] = "plugin.PluginManager";
return 1;
}
int lua_pluginx_protocols_ProtocolAnalytics_logTimedEventBegin(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAnalytics* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAnalytics",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAnalytics*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAnalytics_logTimedEventBegin'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
const char* arg0;
std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "plugin.ProtocolAnalytics:logTimedEventBegin"); arg0 = arg0_tmp.c_str();
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAnalytics_logTimedEventBegin'", nullptr);
return 0;
}
cobj->logTimedEventBegin(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAnalytics:logTimedEventBegin",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAnalytics_logTimedEventBegin'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolAnalytics_logError(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAnalytics* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAnalytics",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAnalytics*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAnalytics_logError'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 2)
{
const char* arg0;
const char* arg1;
std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "plugin.ProtocolAnalytics:logError"); arg0 = arg0_tmp.c_str();
std::string arg1_tmp; ok &= luaval_to_std_string(tolua_S, 3, &arg1_tmp, "plugin.ProtocolAnalytics:logError"); arg1 = arg1_tmp.c_str();
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAnalytics_logError'", nullptr);
return 0;
}
cobj->logError(arg0, arg1);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAnalytics:logError",argc, 2);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAnalytics_logError'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolAnalytics_setCaptureUncaughtException(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAnalytics* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAnalytics",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAnalytics*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAnalytics_setCaptureUncaughtException'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
bool arg0;
ok &= luaval_to_boolean(tolua_S, 2,&arg0, "plugin.ProtocolAnalytics:setCaptureUncaughtException");
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAnalytics_setCaptureUncaughtException'", nullptr);
return 0;
}
cobj->setCaptureUncaughtException(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAnalytics:setCaptureUncaughtException",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAnalytics_setCaptureUncaughtException'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolAnalytics_setSessionContinueMillis(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAnalytics* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAnalytics",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAnalytics*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAnalytics_setSessionContinueMillis'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
long arg0;
ok &= luaval_to_long(tolua_S, 2, &arg0, "plugin.ProtocolAnalytics:setSessionContinueMillis");
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAnalytics_setSessionContinueMillis'", nullptr);
return 0;
}
cobj->setSessionContinueMillis(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAnalytics:setSessionContinueMillis",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAnalytics_setSessionContinueMillis'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolAnalytics_logEvent(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAnalytics* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAnalytics",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAnalytics*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAnalytics_logEvent'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
const char* arg0;
std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "plugin.ProtocolAnalytics:logEvent"); arg0 = arg0_tmp.c_str();
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAnalytics_logEvent'", nullptr);
return 0;
}
cobj->logEvent(arg0);
return 0;
}
if (argc == 2)
{
const char* arg0;
std::map<std::basic_string<char>, std::basic_string<char>, std::less<std::basic_string<char> >, std::allocator<std::pair<const std::basic_string<char>, std::basic_string<char> > > >* arg1;
std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "plugin.ProtocolAnalytics:logEvent"); arg0 = arg0_tmp.c_str();
ok &= luaval_to_object<std::map<std::basic_string<char>, std::basic_string<char>, std::less<std::basic_string<char> >, std::allocator<std::pair<const std::basic_string<char>, std::basic_string<char> > > >>(tolua_S, 3, "std::map<std::basic_string<char>, std::basic_string<char>, std::less<std::basic_string<char> >, std::allocator<std::pair<const std::basic_string<char>, std::basic_string<char> > > >*",&arg1);
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAnalytics_logEvent'", nullptr);
return 0;
}
cobj->logEvent(arg0, arg1);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAnalytics:logEvent",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAnalytics_logEvent'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolAnalytics_startSession(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAnalytics* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAnalytics",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAnalytics*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAnalytics_startSession'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
const char* arg0;
std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "plugin.ProtocolAnalytics:startSession"); arg0 = arg0_tmp.c_str();
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAnalytics_startSession'", nullptr);
return 0;
}
cobj->startSession(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAnalytics:startSession",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAnalytics_startSession'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolAnalytics_stopSession(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAnalytics* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAnalytics",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAnalytics*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAnalytics_stopSession'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAnalytics_stopSession'", nullptr);
return 0;
}
cobj->stopSession();
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAnalytics:stopSession",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAnalytics_stopSession'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolAnalytics_logTimedEventEnd(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAnalytics* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAnalytics",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAnalytics*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAnalytics_logTimedEventEnd'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
const char* arg0;
std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "plugin.ProtocolAnalytics:logTimedEventEnd"); arg0 = arg0_tmp.c_str();
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAnalytics_logTimedEventEnd'", nullptr);
return 0;
}
cobj->logTimedEventEnd(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAnalytics:logTimedEventEnd",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAnalytics_logTimedEventEnd'.",&tolua_err);
#endif
return 0;
}
static int lua_pluginx_protocols_ProtocolAnalytics_finalize(lua_State* tolua_S)
{
printf("luabindings: finalizing LUA object (ProtocolAnalytics)");
return 0;
}
int lua_register_pluginx_protocols_ProtocolAnalytics(lua_State* tolua_S)
{
tolua_usertype(tolua_S,"plugin.ProtocolAnalytics");
tolua_cclass(tolua_S,"ProtocolAnalytics","plugin.ProtocolAnalytics","plugin.PluginProtocol",nullptr);
tolua_beginmodule(tolua_S,"ProtocolAnalytics");
tolua_function(tolua_S,"logTimedEventBegin",lua_pluginx_protocols_ProtocolAnalytics_logTimedEventBegin);
tolua_function(tolua_S,"logError",lua_pluginx_protocols_ProtocolAnalytics_logError);
tolua_function(tolua_S,"setCaptureUncaughtException",lua_pluginx_protocols_ProtocolAnalytics_setCaptureUncaughtException);
tolua_function(tolua_S,"setSessionContinueMillis",lua_pluginx_protocols_ProtocolAnalytics_setSessionContinueMillis);
tolua_function(tolua_S,"logEvent",lua_pluginx_protocols_ProtocolAnalytics_logEvent);
tolua_function(tolua_S,"startSession",lua_pluginx_protocols_ProtocolAnalytics_startSession);
tolua_function(tolua_S,"stopSession",lua_pluginx_protocols_ProtocolAnalytics_stopSession);
tolua_function(tolua_S,"logTimedEventEnd",lua_pluginx_protocols_ProtocolAnalytics_logTimedEventEnd);
tolua_endmodule(tolua_S);
std::string typeName = typeid(cocos2d::plugin::ProtocolAnalytics).name();
g_luaType[typeName] = "plugin.ProtocolAnalytics";
g_typeCast["ProtocolAnalytics"] = "plugin.ProtocolAnalytics";
return 1;
}
int lua_pluginx_protocols_ProtocolIAP_onPayResult(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolIAP* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolIAP",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolIAP*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolIAP_onPayResult'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 2)
{
cocos2d::plugin::PayResultCode arg0;
const char* arg1;
ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "plugin.ProtocolIAP:onPayResult");
std::string arg1_tmp; ok &= luaval_to_std_string(tolua_S, 3, &arg1_tmp, "plugin.ProtocolIAP:onPayResult"); arg1 = arg1_tmp.c_str();
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolIAP_onPayResult'", nullptr);
return 0;
}
cobj->onPayResult(arg0, arg1);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolIAP:onPayResult",argc, 2);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolIAP_onPayResult'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolIAP_configDeveloperInfo(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolIAP* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolIAP",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolIAP*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolIAP_configDeveloperInfo'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
cocos2d::plugin::TIAPDeveloperInfo arg0;
ok &= pluginx::luaval_to_TIAPDeveloperInfo(tolua_S, 2, &arg0);
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolIAP_configDeveloperInfo'", nullptr);
return 0;
}
cobj->configDeveloperInfo(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolIAP:configDeveloperInfo",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolIAP_configDeveloperInfo'.",&tolua_err);
#endif
return 0;
}
static int lua_pluginx_protocols_ProtocolIAP_finalize(lua_State* tolua_S)
{
printf("luabindings: finalizing LUA object (ProtocolIAP)");
return 0;
}
int lua_register_pluginx_protocols_ProtocolIAP(lua_State* tolua_S)
{
tolua_usertype(tolua_S,"plugin.ProtocolIAP");
tolua_cclass(tolua_S,"ProtocolIAP","plugin.ProtocolIAP","plugin.PluginProtocol",nullptr);
tolua_beginmodule(tolua_S,"ProtocolIAP");
tolua_function(tolua_S,"onPayResult",lua_pluginx_protocols_ProtocolIAP_onPayResult);
tolua_function(tolua_S,"configDeveloperInfo",lua_pluginx_protocols_ProtocolIAP_configDeveloperInfo);
tolua_endmodule(tolua_S);
std::string typeName = typeid(cocos2d::plugin::ProtocolIAP).name();
g_luaType[typeName] = "plugin.ProtocolIAP";
g_typeCast["ProtocolIAP"] = "plugin.ProtocolIAP";
return 1;
}
int lua_pluginx_protocols_ProtocolAds_showAds(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAds* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAds",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAds*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAds_showAds'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
cocos2d::plugin::TAdsInfo arg0;
ok &= pluginx::luaval_to_TAdsInfo(tolua_S, 2, &arg0);
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAds_showAds'", nullptr);
return 0;
}
cobj->showAds(arg0);
return 0;
}
if (argc == 2)
{
cocos2d::plugin::TAdsInfo arg0;
cocos2d::plugin::ProtocolAds::AdsPos arg1;
ok &= pluginx::luaval_to_TAdsInfo(tolua_S, 2, &arg0);
ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1, "plugin.ProtocolAds:showAds");
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAds_showAds'", nullptr);
return 0;
}
cobj->showAds(arg0, arg1);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAds:showAds",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAds_showAds'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolAds_hideAds(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAds* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAds",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAds*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAds_hideAds'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
cocos2d::plugin::TAdsInfo arg0;
ok &= pluginx::luaval_to_TAdsInfo(tolua_S, 2, &arg0);
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAds_hideAds'", nullptr);
return 0;
}
cobj->hideAds(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAds:hideAds",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAds_hideAds'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolAds_queryPoints(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAds* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAds",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAds*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAds_queryPoints'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAds_queryPoints'", nullptr);
return 0;
}
cobj->queryPoints();
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAds:queryPoints",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAds_queryPoints'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolAds_spendPoints(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAds* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAds",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAds*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAds_spendPoints'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
int arg0;
ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "plugin.ProtocolAds:spendPoints");
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAds_spendPoints'", nullptr);
return 0;
}
cobj->spendPoints(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAds:spendPoints",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAds_spendPoints'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolAds_configDeveloperInfo(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolAds* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolAds",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolAds*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolAds_configDeveloperInfo'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
cocos2d::plugin::TAdsDeveloperInfo arg0;
ok &= pluginx::luaval_to_TAdsDeveloperInfo(tolua_S, 2, &arg0);
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolAds_configDeveloperInfo'", nullptr);
return 0;
}
cobj->configDeveloperInfo(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolAds:configDeveloperInfo",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolAds_configDeveloperInfo'.",&tolua_err);
#endif
return 0;
}
static int lua_pluginx_protocols_ProtocolAds_finalize(lua_State* tolua_S)
{
printf("luabindings: finalizing LUA object (ProtocolAds)");
return 0;
}
int lua_register_pluginx_protocols_ProtocolAds(lua_State* tolua_S)
{
tolua_usertype(tolua_S,"plugin.ProtocolAds");
tolua_cclass(tolua_S,"ProtocolAds","plugin.ProtocolAds","plugin.PluginProtocol",nullptr);
tolua_beginmodule(tolua_S,"ProtocolAds");
tolua_function(tolua_S,"showAds",lua_pluginx_protocols_ProtocolAds_showAds);
tolua_function(tolua_S,"hideAds",lua_pluginx_protocols_ProtocolAds_hideAds);
tolua_function(tolua_S,"queryPoints",lua_pluginx_protocols_ProtocolAds_queryPoints);
tolua_function(tolua_S,"spendPoints",lua_pluginx_protocols_ProtocolAds_spendPoints);
tolua_function(tolua_S,"configDeveloperInfo",lua_pluginx_protocols_ProtocolAds_configDeveloperInfo);
tolua_endmodule(tolua_S);
std::string typeName = typeid(cocos2d::plugin::ProtocolAds).name();
g_luaType[typeName] = "plugin.ProtocolAds";
g_typeCast["ProtocolAds"] = "plugin.ProtocolAds";
return 1;
}
int lua_pluginx_protocols_ProtocolShare_onShareResult(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolShare* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolShare",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolShare*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolShare_onShareResult'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 2)
{
cocos2d::plugin::ShareResultCode arg0;
const char* arg1;
ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "plugin.ProtocolShare:onShareResult");
std::string arg1_tmp; ok &= luaval_to_std_string(tolua_S, 3, &arg1_tmp, "plugin.ProtocolShare:onShareResult"); arg1 = arg1_tmp.c_str();
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolShare_onShareResult'", nullptr);
return 0;
}
cobj->onShareResult(arg0, arg1);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolShare:onShareResult",argc, 2);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolShare_onShareResult'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolShare_configDeveloperInfo(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolShare* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolShare",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolShare*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolShare_configDeveloperInfo'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
cocos2d::plugin::TShareDeveloperInfo arg0;
ok &= pluginx::luaval_to_TShareDeveloperInfo(tolua_S, 2, &arg0);
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolShare_configDeveloperInfo'", nullptr);
return 0;
}
cobj->configDeveloperInfo(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolShare:configDeveloperInfo",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolShare_configDeveloperInfo'.",&tolua_err);
#endif
return 0;
}
static int lua_pluginx_protocols_ProtocolShare_finalize(lua_State* tolua_S)
{
printf("luabindings: finalizing LUA object (ProtocolShare)");
return 0;
}
int lua_register_pluginx_protocols_ProtocolShare(lua_State* tolua_S)
{
tolua_usertype(tolua_S,"plugin.ProtocolShare");
tolua_cclass(tolua_S,"ProtocolShare","plugin.ProtocolShare","plugin.PluginProtocol",nullptr);
tolua_beginmodule(tolua_S,"ProtocolShare");
tolua_function(tolua_S,"onShareResult",lua_pluginx_protocols_ProtocolShare_onShareResult);
tolua_function(tolua_S,"configDeveloperInfo",lua_pluginx_protocols_ProtocolShare_configDeveloperInfo);
tolua_endmodule(tolua_S);
std::string typeName = typeid(cocos2d::plugin::ProtocolShare).name();
g_luaType[typeName] = "plugin.ProtocolShare";
g_typeCast["ProtocolShare"] = "plugin.ProtocolShare";
return 1;
}
int lua_pluginx_protocols_ProtocolSocial_showLeaderboard(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolSocial* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolSocial",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolSocial*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolSocial_showLeaderboard'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
const char* arg0;
std::string arg0_tmp; ok &= luaval_to_std_string(tolua_S, 2, &arg0_tmp, "plugin.ProtocolSocial:showLeaderboard"); arg0 = arg0_tmp.c_str();
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolSocial_showLeaderboard'", nullptr);
return 0;
}
cobj->showLeaderboard(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolSocial:showLeaderboard",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolSocial_showLeaderboard'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolSocial_showAchievements(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolSocial* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolSocial",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolSocial*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolSocial_showAchievements'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolSocial_showAchievements'", nullptr);
return 0;
}
cobj->showAchievements();
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolSocial:showAchievements",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolSocial_showAchievements'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolSocial_configDeveloperInfo(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolSocial* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolSocial",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolSocial*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolSocial_configDeveloperInfo'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
cocos2d::plugin::TSocialDeveloperInfo arg0;
ok &= pluginx::luaval_to_TSocialDeveloperInfo(tolua_S, 2, &arg0);
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolSocial_configDeveloperInfo'", nullptr);
return 0;
}
cobj->configDeveloperInfo(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolSocial:configDeveloperInfo",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolSocial_configDeveloperInfo'.",&tolua_err);
#endif
return 0;
}
static int lua_pluginx_protocols_ProtocolSocial_finalize(lua_State* tolua_S)
{
printf("luabindings: finalizing LUA object (ProtocolSocial)");
return 0;
}
int lua_register_pluginx_protocols_ProtocolSocial(lua_State* tolua_S)
{
tolua_usertype(tolua_S,"plugin.ProtocolSocial");
tolua_cclass(tolua_S,"ProtocolSocial","plugin.ProtocolSocial","plugin.PluginProtocol",nullptr);
tolua_beginmodule(tolua_S,"ProtocolSocial");
tolua_function(tolua_S,"showLeaderboard",lua_pluginx_protocols_ProtocolSocial_showLeaderboard);
tolua_function(tolua_S,"showAchievements",lua_pluginx_protocols_ProtocolSocial_showAchievements);
tolua_function(tolua_S,"configDeveloperInfo",lua_pluginx_protocols_ProtocolSocial_configDeveloperInfo);
tolua_endmodule(tolua_S);
std::string typeName = typeid(cocos2d::plugin::ProtocolSocial).name();
g_luaType[typeName] = "plugin.ProtocolSocial";
g_typeCast["ProtocolSocial"] = "plugin.ProtocolSocial";
return 1;
}
int lua_pluginx_protocols_ProtocolUser_configDeveloperInfo(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolUser* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolUser",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolUser*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolUser_configDeveloperInfo'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 1)
{
cocos2d::plugin::TUserDeveloperInfo arg0;
ok &= pluginx::luaval_to_TUserDeveloperInfo(tolua_S, 2, &arg0);
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolUser_configDeveloperInfo'", nullptr);
return 0;
}
cobj->configDeveloperInfo(arg0);
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolUser:configDeveloperInfo",argc, 1);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolUser_configDeveloperInfo'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolUser_isLoggedIn(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolUser* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolUser",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolUser*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolUser_isLoggedIn'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolUser_isLoggedIn'", nullptr);
return 0;
}
bool ret = cobj->isLoggedIn();
tolua_pushboolean(tolua_S,(bool)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolUser:isLoggedIn",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolUser_isLoggedIn'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolUser_getSessionID(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolUser* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolUser",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolUser*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolUser_getSessionID'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolUser_getSessionID'", nullptr);
return 0;
}
std::string ret = cobj->getSessionID();
tolua_pushcppstring(tolua_S,ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolUser:getSessionID",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolUser_getSessionID'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_ProtocolUser_getAccessToken(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::ProtocolUser* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.ProtocolUser",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::ProtocolUser*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_ProtocolUser_getAccessToken'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_ProtocolUser_getAccessToken'", nullptr);
return 0;
}
std::string ret = cobj->getAccessToken();
tolua_pushcppstring(tolua_S,ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.ProtocolUser:getAccessToken",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_ProtocolUser_getAccessToken'.",&tolua_err);
#endif
return 0;
}
static int lua_pluginx_protocols_ProtocolUser_finalize(lua_State* tolua_S)
{
printf("luabindings: finalizing LUA object (ProtocolUser)");
return 0;
}
int lua_register_pluginx_protocols_ProtocolUser(lua_State* tolua_S)
{
tolua_usertype(tolua_S,"plugin.ProtocolUser");
tolua_cclass(tolua_S,"ProtocolUser","plugin.ProtocolUser","plugin.PluginProtocol",nullptr);
tolua_beginmodule(tolua_S,"ProtocolUser");
tolua_function(tolua_S,"configDeveloperInfo",lua_pluginx_protocols_ProtocolUser_configDeveloperInfo);
tolua_function(tolua_S,"isLoggedIn",lua_pluginx_protocols_ProtocolUser_isLoggedIn);
tolua_function(tolua_S,"getSessionID",lua_pluginx_protocols_ProtocolUser_getSessionID);
tolua_function(tolua_S,"getAccessToken",lua_pluginx_protocols_ProtocolUser_getAccessToken);
tolua_endmodule(tolua_S);
std::string typeName = typeid(cocos2d::plugin::ProtocolUser).name();
g_luaType[typeName] = "plugin.ProtocolUser";
g_typeCast["ProtocolUser"] = "plugin.ProtocolUser";
return 1;
}
int lua_pluginx_protocols_AgentManager_getSocialPlugin(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::AgentManager* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.AgentManager",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::AgentManager*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_AgentManager_getSocialPlugin'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_AgentManager_getSocialPlugin'", nullptr);
return 0;
}
cocos2d::plugin::ProtocolSocial* ret = cobj->getSocialPlugin();
object_to_luaval<cocos2d::plugin::ProtocolSocial>(tolua_S, "plugin.ProtocolSocial",(cocos2d::plugin::ProtocolSocial*)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.AgentManager:getSocialPlugin",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_AgentManager_getSocialPlugin'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_AgentManager_getAdsPlugin(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::AgentManager* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.AgentManager",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::AgentManager*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_AgentManager_getAdsPlugin'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_AgentManager_getAdsPlugin'", nullptr);
return 0;
}
cocos2d::plugin::ProtocolAds* ret = cobj->getAdsPlugin();
object_to_luaval<cocos2d::plugin::ProtocolAds>(tolua_S, "plugin.ProtocolAds",(cocos2d::plugin::ProtocolAds*)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.AgentManager:getAdsPlugin",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_AgentManager_getAdsPlugin'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_AgentManager_purge(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::AgentManager* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.AgentManager",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::AgentManager*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_AgentManager_purge'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_AgentManager_purge'", nullptr);
return 0;
}
cobj->purge();
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.AgentManager:purge",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_AgentManager_purge'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_AgentManager_getUserPlugin(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::AgentManager* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.AgentManager",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::AgentManager*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_AgentManager_getUserPlugin'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_AgentManager_getUserPlugin'", nullptr);
return 0;
}
cocos2d::plugin::ProtocolUser* ret = cobj->getUserPlugin();
object_to_luaval<cocos2d::plugin::ProtocolUser>(tolua_S, "plugin.ProtocolUser",(cocos2d::plugin::ProtocolUser*)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.AgentManager:getUserPlugin",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_AgentManager_getUserPlugin'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_AgentManager_getIAPPlugin(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::AgentManager* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.AgentManager",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::AgentManager*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_AgentManager_getIAPPlugin'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_AgentManager_getIAPPlugin'", nullptr);
return 0;
}
cocos2d::plugin::ProtocolIAP* ret = cobj->getIAPPlugin();
object_to_luaval<cocos2d::plugin::ProtocolIAP>(tolua_S, "plugin.ProtocolIAP",(cocos2d::plugin::ProtocolIAP*)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.AgentManager:getIAPPlugin",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_AgentManager_getIAPPlugin'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_AgentManager_getSharePlugin(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::AgentManager* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.AgentManager",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::AgentManager*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_AgentManager_getSharePlugin'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_AgentManager_getSharePlugin'", nullptr);
return 0;
}
cocos2d::plugin::ProtocolShare* ret = cobj->getSharePlugin();
object_to_luaval<cocos2d::plugin::ProtocolShare>(tolua_S, "plugin.ProtocolShare",(cocos2d::plugin::ProtocolShare*)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.AgentManager:getSharePlugin",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_AgentManager_getSharePlugin'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_AgentManager_getAnalyticsPlugin(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::AgentManager* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.AgentManager",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::AgentManager*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_AgentManager_getAnalyticsPlugin'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_AgentManager_getAnalyticsPlugin'", nullptr);
return 0;
}
cocos2d::plugin::ProtocolAnalytics* ret = cobj->getAnalyticsPlugin();
object_to_luaval<cocos2d::plugin::ProtocolAnalytics>(tolua_S, "plugin.ProtocolAnalytics",(cocos2d::plugin::ProtocolAnalytics*)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.AgentManager:getAnalyticsPlugin",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_AgentManager_getAnalyticsPlugin'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_AgentManager_destroyInstance(lua_State* tolua_S)
{
int argc = 0;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertable(tolua_S,1,"plugin.AgentManager",0,&tolua_err)) goto tolua_lerror;
#endif
argc = lua_gettop(tolua_S) - 1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_AgentManager_destroyInstance'", nullptr);
return 0;
}
cocos2d::plugin::AgentManager::destroyInstance();
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "plugin.AgentManager:destroyInstance",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_AgentManager_destroyInstance'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_AgentManager_getInstance(lua_State* tolua_S)
{
int argc = 0;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertable(tolua_S,1,"plugin.AgentManager",0,&tolua_err)) goto tolua_lerror;
#endif
argc = lua_gettop(tolua_S) - 1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_AgentManager_getInstance'", nullptr);
return 0;
}
cocos2d::plugin::AgentManager* ret = cocos2d::plugin::AgentManager::getInstance();
object_to_luaval<cocos2d::plugin::AgentManager>(tolua_S, "plugin.AgentManager",(cocos2d::plugin::AgentManager*)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "plugin.AgentManager:getInstance",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_AgentManager_getInstance'.",&tolua_err);
#endif
return 0;
}
static int lua_pluginx_protocols_AgentManager_finalize(lua_State* tolua_S)
{
printf("luabindings: finalizing LUA object (AgentManager)");
return 0;
}
int lua_register_pluginx_protocols_AgentManager(lua_State* tolua_S)
{
tolua_usertype(tolua_S,"plugin.AgentManager");
tolua_cclass(tolua_S,"AgentManager","plugin.AgentManager","",nullptr);
tolua_beginmodule(tolua_S,"AgentManager");
tolua_function(tolua_S,"getSocialPlugin",lua_pluginx_protocols_AgentManager_getSocialPlugin);
tolua_function(tolua_S,"getAdsPlugin",lua_pluginx_protocols_AgentManager_getAdsPlugin);
tolua_function(tolua_S,"purge",lua_pluginx_protocols_AgentManager_purge);
tolua_function(tolua_S,"getUserPlugin",lua_pluginx_protocols_AgentManager_getUserPlugin);
tolua_function(tolua_S,"getIAPPlugin",lua_pluginx_protocols_AgentManager_getIAPPlugin);
tolua_function(tolua_S,"getSharePlugin",lua_pluginx_protocols_AgentManager_getSharePlugin);
tolua_function(tolua_S,"getAnalyticsPlugin",lua_pluginx_protocols_AgentManager_getAnalyticsPlugin);
tolua_function(tolua_S,"destroyInstance", lua_pluginx_protocols_AgentManager_destroyInstance);
tolua_function(tolua_S,"getInstance", lua_pluginx_protocols_AgentManager_getInstance);
tolua_endmodule(tolua_S);
std::string typeName = typeid(cocos2d::plugin::AgentManager).name();
g_luaType[typeName] = "plugin.AgentManager";
g_typeCast["AgentManager"] = "plugin.AgentManager";
return 1;
}
int lua_pluginx_protocols_FacebookAgent_activateApp(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::FacebookAgent* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.FacebookAgent",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::FacebookAgent*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_FacebookAgent_activateApp'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_FacebookAgent_activateApp'", nullptr);
return 0;
}
cobj->activateApp();
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.FacebookAgent:activateApp",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_FacebookAgent_activateApp'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_FacebookAgent_getPermissionList(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::FacebookAgent* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.FacebookAgent",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::FacebookAgent*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_FacebookAgent_getPermissionList'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_FacebookAgent_getPermissionList'", nullptr);
return 0;
}
std::string ret = cobj->getPermissionList();
tolua_pushcppstring(tolua_S,ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.FacebookAgent:getPermissionList",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_FacebookAgent_getPermissionList'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_FacebookAgent_getUserID(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::FacebookAgent* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.FacebookAgent",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::FacebookAgent*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_FacebookAgent_getUserID'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_FacebookAgent_getUserID'", nullptr);
return 0;
}
std::string ret = cobj->getUserID();
tolua_pushcppstring(tolua_S,ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.FacebookAgent:getUserID",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_FacebookAgent_getUserID'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_FacebookAgent_logout(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::FacebookAgent* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.FacebookAgent",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::FacebookAgent*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_FacebookAgent_logout'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_FacebookAgent_logout'", nullptr);
return 0;
}
cobj->logout();
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.FacebookAgent:logout",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_FacebookAgent_logout'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_FacebookAgent_getSDKVersion(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::FacebookAgent* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.FacebookAgent",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::FacebookAgent*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_FacebookAgent_getSDKVersion'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_FacebookAgent_getSDKVersion'", nullptr);
return 0;
}
std::string ret = cobj->getSDKVersion();
tolua_pushcppstring(tolua_S,ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.FacebookAgent:getSDKVersion",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_FacebookAgent_getSDKVersion'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_FacebookAgent_isLoggedIn(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::FacebookAgent* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.FacebookAgent",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::FacebookAgent*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_FacebookAgent_isLoggedIn'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_FacebookAgent_isLoggedIn'", nullptr);
return 0;
}
bool ret = cobj->isLoggedIn();
tolua_pushboolean(tolua_S,(bool)ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.FacebookAgent:isLoggedIn",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_FacebookAgent_isLoggedIn'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_FacebookAgent_getAccessToken(lua_State* tolua_S)
{
int argc = 0;
cocos2d::plugin::FacebookAgent* cobj = nullptr;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertype(tolua_S,1,"plugin.FacebookAgent",0,&tolua_err)) goto tolua_lerror;
#endif
cobj = (cocos2d::plugin::FacebookAgent*)tolua_tousertype(tolua_S,1,0);
#if COCOS2D_DEBUG >= 1
if (!cobj)
{
tolua_error(tolua_S,"invalid 'cobj' in function 'lua_pluginx_protocols_FacebookAgent_getAccessToken'", nullptr);
return 0;
}
#endif
argc = lua_gettop(tolua_S)-1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_FacebookAgent_getAccessToken'", nullptr);
return 0;
}
std::string ret = cobj->getAccessToken();
tolua_pushcppstring(tolua_S,ret);
return 1;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "plugin.FacebookAgent:getAccessToken",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_FacebookAgent_getAccessToken'.",&tolua_err);
#endif
return 0;
}
int lua_pluginx_protocols_FacebookAgent_destroyInstance(lua_State* tolua_S)
{
int argc = 0;
bool ok = true;
#if COCOS2D_DEBUG >= 1
tolua_Error tolua_err;
#endif
#if COCOS2D_DEBUG >= 1
if (!tolua_isusertable(tolua_S,1,"plugin.FacebookAgent",0,&tolua_err)) goto tolua_lerror;
#endif
argc = lua_gettop(tolua_S) - 1;
if (argc == 0)
{
if(!ok)
{
tolua_error(tolua_S,"invalid arguments in function 'lua_pluginx_protocols_FacebookAgent_destroyInstance'", nullptr);
return 0;
}
cocos2d::plugin::FacebookAgent::destroyInstance();
return 0;
}
luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "plugin.FacebookAgent:destroyInstance",argc, 0);
return 0;
#if COCOS2D_DEBUG >= 1
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'lua_pluginx_protocols_FacebookAgent_destroyInstance'.",&tolua_err);
#endif
return 0;
}
static int lua_pluginx_protocols_FacebookAgent_finalize(lua_State* tolua_S)
{
printf("luabindings: finalizing LUA object (FacebookAgent)");
return 0;
}
int lua_register_pluginx_protocols_FacebookAgent(lua_State* tolua_S)
{
tolua_usertype(tolua_S,"plugin.FacebookAgent");
tolua_cclass(tolua_S,"FacebookAgent","plugin.FacebookAgent","",nullptr);
tolua_beginmodule(tolua_S,"FacebookAgent");
tolua_function(tolua_S,"activateApp",lua_pluginx_protocols_FacebookAgent_activateApp);
tolua_function(tolua_S,"getPermissionList",lua_pluginx_protocols_FacebookAgent_getPermissionList);
tolua_function(tolua_S,"getUserID",lua_pluginx_protocols_FacebookAgent_getUserID);
tolua_function(tolua_S,"logout",lua_pluginx_protocols_FacebookAgent_logout);
tolua_function(tolua_S,"getSDKVersion",lua_pluginx_protocols_FacebookAgent_getSDKVersion);
tolua_function(tolua_S,"isLoggedIn",lua_pluginx_protocols_FacebookAgent_isLoggedIn);
tolua_function(tolua_S,"getAccessToken",lua_pluginx_protocols_FacebookAgent_getAccessToken);
tolua_function(tolua_S,"destroyInstance", lua_pluginx_protocols_FacebookAgent_destroyInstance);
tolua_endmodule(tolua_S);
std::string typeName = typeid(cocos2d::plugin::FacebookAgent).name();
g_luaType[typeName] = "plugin.FacebookAgent";
g_typeCast["FacebookAgent"] = "plugin.FacebookAgent";
return 1;
}
TOLUA_API int register_all_pluginx_protocols(lua_State* tolua_S)
{
tolua_open(tolua_S);
tolua_module(tolua_S,"plugin",0);
tolua_beginmodule(tolua_S,"plugin");
lua_register_pluginx_protocols_FacebookAgent(tolua_S);
lua_register_pluginx_protocols_PluginProtocol(tolua_S);
lua_register_pluginx_protocols_ProtocolUser(tolua_S);
lua_register_pluginx_protocols_ProtocolShare(tolua_S);
lua_register_pluginx_protocols_ProtocolIAP(tolua_S);
lua_register_pluginx_protocols_AgentManager(tolua_S);
lua_register_pluginx_protocols_ProtocolSocial(tolua_S);
lua_register_pluginx_protocols_ProtocolAnalytics(tolua_S);
lua_register_pluginx_protocols_ProtocolAds(tolua_S);
lua_register_pluginx_protocols_PluginManager(tolua_S);
tolua_endmodule(tolua_S);
return 1;
}
| 0 | 0.797983 | 1 | 0.797983 | game-dev | MEDIA | 0.67668 | game-dev | 0.800171 | 1 | 0.800171 |
OpenMW/openmw | 5,115 | apps/openmw/mwlua/types/armor.cpp | #include "types.hpp"
#include "modelproperty.hpp"
#include <components/esm3/loadarmo.hpp>
#include <components/lua/luastate.hpp>
#include <components/lua/util.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/resource/resourcesystem.hpp>
#include "apps/openmw/mwbase/environment.hpp"
namespace sol
{
template <>
struct is_automagical<ESM::Armor> : std::false_type
{
};
}
namespace
{
// Populates an armor struct from a Lua table.
ESM::Armor tableToArmor(const sol::table& rec)
{
ESM::Armor armor;
if (rec["template"] != sol::nil)
armor = LuaUtil::cast<ESM::Armor>(rec["template"]);
else
armor.blank();
if (rec["name"] != sol::nil)
armor.mName = rec["name"];
if (rec["model"] != sol::nil)
armor.mModel = Misc::ResourceHelpers::meshPathForESM3(rec["model"].get<std::string_view>());
if (rec["icon"] != sol::nil)
armor.mIcon = rec["icon"];
if (rec["enchant"] != sol::nil)
{
std::string_view enchantId = rec["enchant"].get<std::string_view>();
armor.mEnchant = ESM::RefId::deserializeText(enchantId);
}
if (rec["mwscript"] != sol::nil)
{
std::string_view scriptId = rec["mwscript"].get<std::string_view>();
armor.mScript = ESM::RefId::deserializeText(scriptId);
}
if (rec["weight"] != sol::nil)
armor.mData.mWeight = rec["weight"];
if (rec["value"] != sol::nil)
armor.mData.mValue = rec["value"];
if (rec["type"] != sol::nil)
{
int armorType = rec["type"].get<int>();
if (armorType >= 0 && armorType <= ESM::Armor::RBracer)
armor.mData.mType = armorType;
else
throw std::runtime_error("Invalid Armor Type provided: " + std::to_string(armorType));
}
if (rec["health"] != sol::nil)
armor.mData.mHealth = rec["health"];
if (rec["baseArmor"] != sol::nil)
armor.mData.mArmor = rec["baseArmor"];
if (rec["enchantCapacity"] != sol::nil)
armor.mData.mEnchant = std::round(rec["enchantCapacity"].get<float>() * 10);
return armor;
}
}
namespace MWLua
{
void addArmorBindings(sol::table armor, const Context& context)
{
sol::state_view lua = context.sol();
armor["TYPE"] = LuaUtil::makeStrictReadOnly(LuaUtil::tableFromPairs<std::string_view, int>(lua,
{
{ "Helmet", ESM::Armor::Helmet },
{ "Cuirass", ESM::Armor::Cuirass },
{ "LPauldron", ESM::Armor::LPauldron },
{ "RPauldron", ESM::Armor::RPauldron },
{ "Greaves", ESM::Armor::Greaves },
{ "Boots", ESM::Armor::Boots },
{ "LGauntlet", ESM::Armor::LGauntlet },
{ "RGauntlet", ESM::Armor::RGauntlet },
{ "Shield", ESM::Armor::Shield },
{ "LBracer", ESM::Armor::LBracer },
{ "RBracer", ESM::Armor::RBracer },
}));
auto vfs = MWBase::Environment::get().getResourceSystem()->getVFS();
addRecordFunctionBinding<ESM::Armor>(armor, context);
armor["createRecordDraft"] = tableToArmor;
sol::usertype<ESM::Armor> record = lua.new_usertype<ESM::Armor>("ESM3_Armor");
record[sol::meta_function::to_string]
= [](const ESM::Armor& rec) -> std::string { return "ESM3_Armor[" + rec.mId.toDebugString() + "]"; };
record["id"]
= sol::readonly_property([](const ESM::Armor& rec) -> std::string { return rec.mId.serializeText(); });
record["name"] = sol::readonly_property([](const ESM::Armor& rec) -> std::string { return rec.mName; });
addModelProperty(record);
record["icon"] = sol::readonly_property([vfs](const ESM::Armor& rec) -> std::string {
return Misc::ResourceHelpers::correctIconPath(rec.mIcon, vfs);
});
record["enchant"] = sol::readonly_property(
[](const ESM::Armor& rec) -> sol::optional<std::string> { return LuaUtil::serializeRefId(rec.mEnchant); });
record["mwscript"] = sol::readonly_property(
[](const ESM::Armor& rec) -> sol::optional<std::string> { return LuaUtil::serializeRefId(rec.mScript); });
record["weight"] = sol::readonly_property([](const ESM::Armor& rec) -> float { return rec.mData.mWeight; });
record["value"] = sol::readonly_property([](const ESM::Armor& rec) -> int { return rec.mData.mValue; });
record["type"] = sol::readonly_property([](const ESM::Armor& rec) -> int { return rec.mData.mType; });
record["health"] = sol::readonly_property([](const ESM::Armor& rec) -> int { return rec.mData.mHealth; });
record["baseArmor"] = sol::readonly_property([](const ESM::Armor& rec) -> int { return rec.mData.mArmor; });
record["enchantCapacity"]
= sol::readonly_property([](const ESM::Armor& rec) -> float { return rec.mData.mEnchant * 0.1f; });
}
}
| 0 | 0.792553 | 1 | 0.792553 | game-dev | MEDIA | 0.975124 | game-dev | 0.617573 | 1 | 0.617573 |
eduard-permyakov/permafrost-engine | 4,182 | deps/SDL2/test/testautomation_joystick.c | /**
* Joystick test suite
*/
#include "SDL.h"
#include "SDL_test.h"
#include "../src/joystick/usb_ids.h"
/* ================= Test Case Implementation ================== */
/* Test case functions */
/**
* @brief Check virtual joystick creation
*
* @sa SDL_JoystickAttachVirtualEx
*/
static int
TestVirtualJoystick(void *arg)
{
SDL_VirtualJoystickDesc desc;
SDL_Joystick *joystick = NULL;
int device_index;
SDLTest_AssertCheck(SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == 0, "SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER)");
SDL_zero(desc);
desc.version = SDL_VIRTUAL_JOYSTICK_DESC_VERSION;
desc.type = SDL_JOYSTICK_TYPE_GAMECONTROLLER;
desc.naxes = SDL_CONTROLLER_AXIS_MAX;
desc.nbuttons = SDL_CONTROLLER_BUTTON_MAX;
desc.vendor_id = USB_VENDOR_NVIDIA;
desc.product_id = USB_PRODUCT_NVIDIA_SHIELD_CONTROLLER_V104;
desc.name = "Virtual NVIDIA SHIELD Controller";
device_index = SDL_JoystickAttachVirtualEx(&desc);
SDLTest_AssertCheck(device_index >= 0, "SDL_JoystickAttachVirtualEx()");
SDLTest_AssertCheck(SDL_JoystickIsVirtual(device_index), "SDL_JoystickIsVirtual()");
if (device_index >= 0) {
joystick = SDL_JoystickOpen(device_index);
SDLTest_AssertCheck(joystick != NULL, "SDL_JoystickOpen()");
if (joystick) {
SDLTest_AssertCheck(SDL_strcmp(SDL_JoystickName(joystick), desc.name) == 0, "SDL_JoystickName()");
SDLTest_AssertCheck(SDL_JoystickGetVendor(joystick) == desc.vendor_id, "SDL_JoystickGetVendor()");
SDLTest_AssertCheck(SDL_JoystickGetProduct(joystick) == desc.product_id, "SDL_JoystickGetProduct()");
SDLTest_AssertCheck(SDL_JoystickGetProductVersion(joystick) == 0, "SDL_JoystickGetProductVersion()");
SDLTest_AssertCheck(SDL_JoystickGetFirmwareVersion(joystick) == 0, "SDL_JoystickGetFirmwareVersion()");
SDLTest_AssertCheck(SDL_JoystickGetSerial(joystick) == NULL, "SDL_JoystickGetSerial()");
SDLTest_AssertCheck(SDL_JoystickGetType(joystick) == desc.type, "SDL_JoystickGetType()");
SDLTest_AssertCheck(SDL_JoystickNumAxes(joystick) == desc.naxes, "SDL_JoystickNumAxes()");
SDLTest_AssertCheck(SDL_JoystickNumBalls(joystick) == 0, "SDL_JoystickNumBalls()");
SDLTest_AssertCheck(SDL_JoystickNumHats(joystick) == desc.nhats, "SDL_JoystickNumHats()");
SDLTest_AssertCheck(SDL_JoystickNumButtons(joystick) == desc.nbuttons, "SDL_JoystickNumButtons()");
SDLTest_AssertCheck(SDL_JoystickSetVirtualButton(joystick, SDL_CONTROLLER_BUTTON_A, SDL_PRESSED) == 0, "SDL_JoystickSetVirtualButton(SDL_CONTROLLER_BUTTON_A, SDL_PRESSED)");
SDL_JoystickUpdate();
SDLTest_AssertCheck(SDL_JoystickGetButton(joystick, SDL_CONTROLLER_BUTTON_A) == SDL_PRESSED, "SDL_JoystickGetButton(SDL_CONTROLLER_BUTTON_A) == SDL_PRESSED");
SDLTest_AssertCheck(SDL_JoystickSetVirtualButton(joystick, SDL_CONTROLLER_BUTTON_A, SDL_RELEASED) == 0, "SDL_JoystickSetVirtualButton(SDL_CONTROLLER_BUTTON_A, SDL_RELEASED)");
SDL_JoystickUpdate();
SDLTest_AssertCheck(SDL_JoystickGetButton(joystick, SDL_CONTROLLER_BUTTON_A) == SDL_RELEASED, "SDL_JoystickGetButton(SDL_CONTROLLER_BUTTON_A) == SDL_RELEASED");
SDL_JoystickClose(joystick);
}
SDLTest_AssertCheck(SDL_JoystickDetachVirtual(device_index) == 0, "SDL_JoystickDetachVirtual()");
}
SDLTest_AssertCheck(!SDL_JoystickIsVirtual(device_index), "!SDL_JoystickIsVirtual()");
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Joystick routine test cases */
static const SDLTest_TestCaseReference joystickTest1 = {
(SDLTest_TestCaseFp)TestVirtualJoystick, "TestVirtualJoystick", "Test virtual joystick functionality", TEST_ENABLED
};
/* Sequence of Joystick routine test cases */
static const SDLTest_TestCaseReference *joystickTests[] = {
&joystickTest1,
NULL
};
/* Joystick routine test suite (global) */
SDLTest_TestSuiteReference joystickTestSuite = {
"Joystick",
NULL,
joystickTests,
NULL
};
| 0 | 0.716694 | 1 | 0.716694 | game-dev | MEDIA | 0.931848 | game-dev,testing-qa | 0.708205 | 1 | 0.708205 |
superk589/PrincessGuide | 3,380 | PrincessGuide/Quest/Enemy/View/ClanBattleEnemyView.swift | //
// ClanBattleEnemyView.swift
// PrincessGuide
//
// Created by zzk on 12/28/20.
// Copyright © 2020 zzk. All rights reserved.
//
import UIKit
class ClanBattleEnemyView: UIView {
let enemyIcon = IconImageView()
let defLabel = UILabel()
let mdefLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(enemyIcon)
enemyIcon.snp.makeConstraints { (make) in
make.top.left.equalToSuperview()
make.height.width.equalTo(64)
}
addSubview(defLabel)
defLabel.snp.makeConstraints { (make) in
make.top.equalTo(enemyIcon.snp.bottom)
make.left.right.equalToSuperview()
}
defLabel.font = .systemFont(ofSize: 12)
defLabel.textColor = Theme.dynamic.color.body
defLabel.textAlignment = .center
addSubview(mdefLabel)
mdefLabel.snp.makeConstraints { (make) in
make.top.equalTo(defLabel.snp.bottom)
make.left.right.equalToSuperview()
}
mdefLabel.font = .systemFont(ofSize: 12)
mdefLabel.textColor = Theme.dynamic.color.body
mdefLabel.textAlignment = .center
}
func configure(for enemy: Enemy) {
if enemy.unit.visualChangeFlag == 1 {
enemyIcon.shadowUnitID = enemy.unit.prefabId
} else {
enemyIcon.unitID = enemy.unit.prefabId
}
if enemy.isBossPart {
enemyIcon.layer.borderColor = UIColor.red.cgColor
enemyIcon.layer.borderWidth = 2
enemyIcon.layer.cornerRadius = 6
enemyIcon.layer.masksToBounds = true
enemyIcon.layer.borderColor = Theme.dynamic.color.highlightedText.cgColor
} else {
enemyIcon.layer.borderWidth = 0
}
if enemy.parts.count > 0 {
defLabel.text = ""
mdefLabel.text = ""
} else {
defLabel.setText(enemy.base.property.def.roundedString(roundingRule: nil), prependedBySymbolNameed: "shield.fill")
mdefLabel.setText(enemy.base.property.magicDef.roundedString(roundingRule: nil), prependedBySymbolNameed: "sparkles")
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: 64, height: 92)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension UILabel {
func setText(_ text: String, prependedBySymbolNameed symbolSystemName: String, font: UIFont? = nil) {
if #available(iOS 13.0, *) {
if let font = font { self.font = font }
let symbolConfiguration = UIImage.SymbolConfiguration(font: self.font)
let symbolImage = UIImage(systemName: symbolSystemName, withConfiguration: symbolConfiguration)?.withRenderingMode(.alwaysTemplate)
let symbolTextAttachment = NSTextAttachment()
symbolTextAttachment.image = symbolImage
let attributedText = NSMutableAttributedString()
attributedText.append(NSAttributedString(attachment: symbolTextAttachment))
attributedText.append(NSAttributedString(string: " " + text))
self.attributedText = attributedText
} else {
self.text = text // fallback
}
}
}
| 0 | 0.81725 | 1 | 0.81725 | game-dev | MEDIA | 0.558428 | game-dev | 0.908523 | 1 | 0.908523 |
psiroki/gzdoomxxh | 1,633 | wadsrc/static/zscript/ui/menu/doommenus.zs | class GameplayMenu : OptionMenu
{
override void Drawer ()
{
Super.Drawer();
String s = String.Format("dmflags = %d dmflags2 = %d", dmflags, dmflags2);
screen.DrawText (OptionFont(), OptionMenuSettings.mFontColorValue,
(screen.GetWidth() - OptionWidth (s) * CleanXfac_1) / 2, 35 * CleanXfac_1, s,
DTA_CleanNoMove_1, true);
}
}
class CompatibilityMenu : OptionMenu
{
override void Drawer ()
{
Super.Drawer();
String s = String.Format("compatflags = %d compatflags2 = %d", compatflags, compatflags2);
screen.DrawText (OptionFont(), OptionMenuSettings.mFontColorValue,
(screen.GetWidth() - OptionWidth (s) * CleanXfac_1) / 2, 35 * CleanXfac_1, s,
DTA_CleanNoMove_1, true);
}
}
//=============================================================================
//
// Placeholder classes for overhauled video mode menu. Do not use!
// Their sole purpose is to support mods with full copy of embedded MENUDEF
//
//=============================================================================
class OptionMenuItemScreenResolution : OptionMenuItem
{
String mResTexts[3];
int mSelection;
int mHighlight;
int mMaxValid;
enum EValues
{
SRL_INDEX = 0x30000,
SRL_SELECTION = 0x30003,
SRL_HIGHLIGHT = 0x30004,
};
OptionMenuItemScreenResolution Init(String command)
{
return self;
}
override bool Selectable()
{
return false;
}
}
class VideoModeMenu : OptionMenu
{
static bool SetSelectedSize()
{
return false;
}
}
class DoomMenuDelegate : MenuDelegateBase
{
override void PlaySound(Name snd)
{
String s = snd;
S_StartSound (s, CHAN_VOICE, CHANF_UI, snd_menuvolume);
}
}
| 0 | 0.89845 | 1 | 0.89845 | game-dev | MEDIA | 0.85046 | game-dev | 0.829848 | 1 | 0.829848 |
kxtools/kx-vision | 5,166 | src/Core/AppLifecycleManager.h | #pragma once
#include <d3d11.h>
#include <windows.h>
#include "../Game/Camera.h"
#include "../Game/MumbleLinkManager.h"
namespace kx {
/**
* @brief Manages the application lifecycle state machine
*
* This class encapsulates the initialization, runtime, and shutdown logic
* of the KX Vision application. It provides a clean separation between
* the main thread loop and the complex state management.
*
* States:
* - PreInit: Initial state, waiting to start initialization
* - WaitingForImGui: Waiting for ImGui to be initialized by the Present hook
* - WaitingForRenderer: (GW2AL mode) Waiting for GW2AL to provide D3D device
* - WaitingForGame: Waiting for player to be in-game (map loaded)
* - InitializingServices: Initializing AddressManager and game thread hook
* - Running: Normal operation
* - ShuttingDown: Cleanup in progress
*/
class AppLifecycleManager {
public:
/**
* @brief Initialize the application lifecycle manager (DLL mode)
* @return true if initialization successful, false otherwise
*/
bool Initialize();
/**
* @brief Initialize for GW2AL mode (event-driven)
* @return true if initialization successful, false otherwise
*/
bool InitializeForGW2AL();
/**
* @brief Called when the renderer is initialized (GW2AL mode)
*
* This transitions the state machine from WaitingForRenderer to the next state.
*/
void OnRendererInitialized();
/**
* @brief Update the state machine (called every frame)
*/
void Update();
/**
* @brief Begin the shutdown process
*/
void Shutdown();
/**
* @brief Check if shutdown has been requested
* @return true if user requested shutdown (DELETE key or window closed)
*/
bool IsShutdownRequested() const;
/**
* @brief Get current state as string for debugging
*/
const char* GetCurrentStateName() const;
/**
* @brief Get reference to the Camera (for core game state)
* @return Reference to Camera instance
*/
Camera& GetCamera() { return m_camera; }
/**
* @brief Get reference to MumbleLinkManager (for core game state)
* @return Reference to MumbleLinkManager instance
*/
MumbleLinkManager& GetMumbleLinkManager() { return m_mumbleLinkManager; }
/**
* @brief Get const pointer to current MumbleLink data
* @return Pointer to MumbleLinkData, or nullptr if not available
*/
const MumbleLinkData* GetMumbleLinkData() const { return m_mumbleLinkManager.GetData(); }
/**
* @brief Get the D3D11 device (if initialized)
* @return Pointer to ID3D11Device, or nullptr if not available
*/
ID3D11Device* GetDevice() const;
/**
* @brief Check and initialize services if ready (for GW2AL mode)
*
* This is called from OnPresent to check if MumbleLink is connected
* and player is in-game, then initializes services once.
*/
void CheckAndInitializeServices();
/**
* @brief Centralized per-frame tick logic for rendering
*
* This function contains all the shared per-frame logic that needs to
* happen before ImGui rendering in both DLL and GW2AL modes:
* - Update MumbleLink data
* - Update camera
* - Check and initialize services (if not already done)
*
* @param windowHandle The HWND of the game window
* @param displayWidth The width of the display/viewport
* @param displayHeight The height of the display/viewport
* @param context The D3D11 device context (for rendering)
* @param renderTargetView The render target view to render to
*/
void RenderTick(HWND windowHandle, float displayWidth, float displayHeight,
ID3D11DeviceContext* context, ID3D11RenderTargetView* renderTargetView);
private:
/**
* @brief Application lifecycle states
*/
enum class State {
PreInit, // Initial state before any initialization
WaitingForImGui, // Waiting for ImGui to be initialized
WaitingForRenderer, // (GW2AL mode) Waiting for renderer initialization
WaitingForGame, // Waiting for player to enter a map
InitializingServices, // Initializing game services
Running, // Normal operation
ShuttingDown // Cleanup in progress
};
State m_currentState = State::PreInit;
bool m_servicesInitialized = false;
// Core game state (owned by lifecycle manager)
Camera m_camera;
MumbleLinkManager m_mumbleLinkManager;
// State transition handlers
void HandlePreInitState();
void HandleWaitingForImGuiState();
void HandleWaitingForRendererState();
void HandleWaitingForGameState();
void HandleInitializingServicesState();
void HandleRunningState();
void HandleShuttingDownState();
// Helper methods
bool IsImGuiReady() const;
bool IsPlayerInGame() const;
bool InitializeGameServices();
void CleanupServices();
};
// Global instance of AppLifecycleManager (used by both DLL and GW2AL modes)
extern AppLifecycleManager g_App;
} // namespace kx
| 0 | 0.953525 | 1 | 0.953525 | game-dev | MEDIA | 0.58478 | game-dev | 0.674325 | 1 | 0.674325 |
AmazingMonster/conceptrodon | 1,387 | tests/unit/concepts/omennivore/unflowful.test.hpp | // Copyright 2024 Feng Mofan
// SPDX-License-Identifier: Apache-2.0
#ifndef CONCEPTRODON_TESTS_UNIT_OMENNIVORE_UNFLOWFUL_H
#define CONCEPTRODON_TESTS_UNIT_OMENNIVORE_UNFLOWFUL_H
#include "conceptrodon/omennivore/concepts/unflowful.hpp"
#include "conceptrodon/capsule.hpp"
#include "conceptrodon/shuttle.hpp"
#include "conceptrodon/vehicle.hpp"
#include "conceptrodon/carrier.hpp"
#include "conceptrodon/reverie.hpp"
#include "conceptrodon/phantom.hpp"
#include "conceptrodon/forlorn.hpp"
#include "conceptrodon/travail.hpp"
#include "conceptrodon/lullaby.hpp"
#include "conceptrodon/halcyon.hpp"
#include "conceptrodon/pursuit.hpp"
#include "conceptrodon/persist.hpp"
#include "conceptrodon/sunrise.hpp"
#include "conceptrodon/morning.hpp"
namespace Conceptrodon {
namespace Omennivore {
namespace UnitTests {
namespace TestUnflowful {
static_assert(Unflowful<Capsule<>>);
static_assert(Unflowful<Shuttle<>>);
static_assert(Unflowful<Vehicle<>>);
static_assert(Unflowful<Carrier<>>);
static_assert(! Unflowful<Reverie<>>);
static_assert(Unflowful<Phantom<>>);
static_assert(Unflowful<Forlorn<>>);
static_assert(Unflowful<Travail<>>);
static_assert(Unflowful<Lullaby<>>);
static_assert(Unflowful<Halcyon<>>);
static_assert(Unflowful<Pursuit<>>);
static_assert(Unflowful<Persist<>>);
static_assert(Unflowful<Sunrise<>>);
static_assert(Unflowful<Morning<>>);
}}}}
#endif | 0 | 0.516118 | 1 | 0.516118 | game-dev | MEDIA | 0.156115 | game-dev | 0.791999 | 1 | 0.791999 |
Jermesa-Studio/JRS_Vehicle_Physics_Controller | 1,421 | Library/PackageCache/com.unity.timeline@1.6.5/Samples~/Customization/Utilities/Editor/NoFoldOutPropertyDrawer.cs | using UnityEditor;
using UnityEngine;
namespace Timeline.Samples
{
// Custom property drawer that draws all child properties inline
[CustomPropertyDrawer(typeof(NoFoldOutAttribute))]
public class NoFoldOutPropertyDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
if (!property.hasChildren)
return base.GetPropertyHeight(property, label);
property.isExpanded = true;
return EditorGUI.GetPropertyHeight(property, label, true) -
EditorGUI.GetPropertyHeight(property, label, false);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (!property.hasChildren)
base.OnGUI(position, property, label);
else
{
SerializedProperty iter = property.Copy();
property.Next(true);
do
{
float height = EditorGUI.GetPropertyHeight(property, property.hasVisibleChildren);
position.height = height;
EditorGUI.PropertyField(position, property, property.hasVisibleChildren);
position.y = position.y + height;
}
while (property.NextVisible(false));
}
}
}
}
| 0 | 0.755018 | 1 | 0.755018 | game-dev | MEDIA | 0.828633 | game-dev | 0.711184 | 1 | 0.711184 |
TerraForged/TerraForged | 2,483 | src/main/java/com/terraforged/mod/worldgen/noise/continent/river/RiverPieces.java | /*
* MIT License
*
* Copyright (c) 2021 TerraForged
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.terraforged.mod.worldgen.noise.continent.river;
import java.util.Arrays;
public class RiverPieces {
public static final RiverPieces NONE = new RiverPieces();
private static final int INITIAL_SIZE = RiverGenerator.DIRS.length;
private static final int GROW_AMOUNT = 1;
private int riverCount = 0;
private int lakeCount = 0;
private RiverNode[] riverNodes = new RiverNode[INITIAL_SIZE];
private RiverNode[] lakeNodes = new RiverNode[INITIAL_SIZE];
public RiverPieces reset() {
riverCount = 0;
lakeCount = 0;
return this;
}
public int riverCount() {
return riverCount;
}
public int lakeCount() {
return lakeCount;
}
public RiverNode river(int i) {
return riverNodes[i];
}
public RiverNode lake(int i) {
return lakeNodes[i];
}
public void addRiver(RiverNode node) {
riverNodes = ensureCapacity(riverCount, riverNodes);
riverNodes[riverCount++] = node;
}
public void addLake(RiverNode node) {
lakeNodes = ensureCapacity(lakeCount, lakeNodes);
lakeNodes[lakeCount++] = node;
}
private RiverNode[] ensureCapacity(int size, RiverNode[] array) {
if (size < array.length) return array;
return Arrays.copyOf(array, size + GROW_AMOUNT);
}
}
| 0 | 0.500622 | 1 | 0.500622 | game-dev | MEDIA | 0.705634 | game-dev | 0.791591 | 1 | 0.791591 |
amzeratul/halley | 4,014 | src/tools/tools/src/assets/asset_collector.cpp | #include "halley/tools/assets/asset_collector.h"
#include "halley/tools/file/filesystem.h"
#include "halley/bytes/byte_serializer.h"
#include "halley/resources/metadata.h"
#include "halley/support/logger.h"
#include "halley/bytes/compression.h"
#include "halley/utils/algorithm.h"
using namespace Halley;
AssetCollector::AssetCollector(const ImportingAsset& asset, const Path& dstDir, const Vector<Path>& assetsSrc, ProgressReporter reporter)
: asset(asset)
, dstDir(dstDir)
, assetsSrc(assetsSrc)
, reporter(std::move(reporter))
{}
void AssetCollector::output(const String& name, AssetType type, const Bytes& data, std::optional<Metadata> metadata, const String& platform, const Path& primaryInputFile)
{
const String id = name.replaceAll("_", "__").replaceAll("/", "_-_").replaceAll(":", "_c_");
Path filePath = Path(toString(type)) / id;
Path fullPath = Path(platform) / filePath;
if (metadata && metadata->getString("asset_compression", "") == "lz4") {
Compression::LZ4Options options;
options.mode = Compression::LZ4Mode::HC;
outFiles.emplace_back(fullPath, Compression::lz4CompressFile(data.byte_span(), {}, options));
} else if (metadata && metadata->getString("asset_compression", "") == "deflate") {
auto newData = Compression::compress(data);
outFiles.emplace_back(fullPath, newData);
} else {
outFiles.emplace_back(fullPath, data);
}
// Store information about this asset version
AssetResource::PlatformVersion version;
version.filepath = fullPath.string();
if (metadata) {
version.metadata = metadata.value();
}
getAsset(name, type, primaryInputFile).platformVersions[platform] = std::move(version);
}
AssetResource& AssetCollector::getAsset(const String& name, AssetType type, const Path& primaryInputFile)
{
AssetResource* result = nullptr;
for (auto& a: assets) {
if (a.name == name && a.type == type) {
result = &a;
}
}
if (!result) {
assets.emplace_back();
result = &assets.back();
result->name = name;
result->type = type;
result->primaryInputFile = primaryInputFile;
}
return *result;
}
void AssetCollector::output(const String& name, AssetType type, const Path& path, gsl::span<const std::byte> data)
{
Bytes result;
result.resize(data.size());
memcpy(result.data(), data.data(), data.size());
outFiles.emplace_back(path, std::move(result));
AssetResource::PlatformVersion version;
version.filepath = path.getString();
getAsset(name, type).platformVersions[""] = std::move(version);
}
void AssetCollector::output(const String& name, AssetType type, const Path& path)
{
outFiles.emplace_back(path, std::nullopt);
AssetResource::PlatformVersion version;
version.filepath = path.getString();
getAsset(name, type).platformVersions[""] = std::move(version);
}
void AssetCollector::addAdditionalAsset(ImportingAsset&& additionalAsset)
{
additionalAssets.emplace_back(std::move(additionalAsset));
}
bool AssetCollector::reportProgress(float progress, const String& label)
{
return reporter ? reporter(progress, label) : true;
}
const Path& AssetCollector::getDestinationDirectory()
{
return dstDir;
}
Bytes AssetCollector::readAdditionalFile(const Path& filePath)
{
for (const auto& path: assetsSrc) {
Path f = path / filePath;
if (FileSystem::exists(f)) {
if (!std_ex::contains_if(additionalInputs, [&] (const auto& e) { return e.first == f; })) {
additionalInputs.push_back(TimestampedPath(f, FileSystem::getLastWriteTime(f)));
}
return FileSystem::readFile(f);
}
}
throw Exception("Unable to find asset dependency: \"" + filePath.getString() + "\"", HalleyExceptions::Tools);
}
const Vector<AssetResource>& AssetCollector::getAssets() const
{
return assets;
}
Vector<ImportingAsset> AssetCollector::collectAdditionalAssets()
{
return std::move(additionalAssets);
}
Vector<std::pair<Path, std::optional<Bytes>>> AssetCollector::collectOutFiles()
{
return std::move(outFiles);
}
const Vector<TimestampedPath>& AssetCollector::getAdditionalInputs() const
{
return additionalInputs;
}
| 0 | 0.989494 | 1 | 0.989494 | game-dev | MEDIA | 0.849721 | game-dev | 0.970708 | 1 | 0.970708 |
AppliedEnergistics/Applied-Energistics-2 | 1,138 | src/main/java/appeng/api/components/ExportedUpgrades.java | package appeng.api.components;
import java.util.List;
import com.mojang.serialization.Codec;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.world.item.ItemStack;
public record ExportedUpgrades(List<ItemStack> upgrades) {
// Defined using xmap since we previously used a List directly.
// TODO 1.21.1 Use a normal record codec
public static Codec<ExportedUpgrades> CODEC = ItemStack.CODEC.listOf().xmap(ExportedUpgrades::new,
ExportedUpgrades::upgrades);
public static StreamCodec<RegistryFriendlyByteBuf, ExportedUpgrades> STREAM_CODEC = StreamCodec.composite(
ItemStack.LIST_STREAM_CODEC, ExportedUpgrades::upgrades,
ExportedUpgrades::new);
@Override
public boolean equals(Object object) {
if (this == object)
return true;
if (!(object instanceof ExportedUpgrades that))
return false;
return ItemStack.listMatches(upgrades, that.upgrades);
}
@Override
public int hashCode() {
return ItemStack.hashStackList(upgrades);
}
}
| 0 | 0.609585 | 1 | 0.609585 | game-dev | MEDIA | 0.967212 | game-dev | 0.733999 | 1 | 0.733999 |
EricDDK/billiards_cocos2d | 13,761 | Billiards/frameworks/cocos2d-x/external/bullet/BulletDynamics/Dynamics/Bullet-C-API.cpp | /*
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.
*/
/*
Draft high-level generic physics C-API. For low-level access, use the physics SDK native API's.
Work in progress, functionality will be added on demand.
If possible, use the richer Bullet C++ API, by including <src/btBulletDynamicsCommon.h>
*/
#include "bullet/Bullet-C-Api.h"
#include "bullet/btBulletDynamicsCommon.h"
#include "bullet/LinearMath/btAlignedAllocator.h"
#include "bullet/LinearMath/btVector3.h"
#include "bullet/LinearMath/btScalar.h"
#include "bullet/LinearMath/btMatrix3x3.h"
#include "bullet/LinearMath/btTransform.h"
#include "bullet/BulletCollision//NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "bullet/BulletCollision//CollisionShapes/btTriangleShape.h"
#include "bullet/BulletCollision//NarrowPhaseCollision/btGjkPairDetector.h"
#include "bullet/BulletCollision//NarrowPhaseCollision/btPointCollector.h"
#include "bullet/BulletCollision//NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "bullet/BulletCollision//NarrowPhaseCollision/btSubSimplexConvexCast.h"
#include "bullet/BulletCollision//NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
#include "bullet/BulletCollision//NarrowPhaseCollision/btGjkEpa2.h"
#include "bullet/BulletCollision//CollisionShapes/btMinkowskiSumShape.h"
#include "bullet/BulletCollision//NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h"
#include "bullet/BulletCollision//NarrowPhaseCollision/btSimplexSolverInterface.h"
#include "bullet/BulletCollision//NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h"
/*
Create and Delete a Physics SDK
*/
struct btPhysicsSdk
{
// btDispatcher* m_dispatcher;
// btOverlappingPairCache* m_pairCache;
// btConstraintSolver* m_constraintSolver
btVector3 m_worldAabbMin;
btVector3 m_worldAabbMax;
//todo: version, hardware/optimization settings etc?
btPhysicsSdk()
:m_worldAabbMin(-1000,-1000,-1000),
m_worldAabbMax(1000,1000,1000)
{
}
};
plPhysicsSdkHandle plNewBulletSdk()
{
void* mem = btAlignedAlloc(sizeof(btPhysicsSdk),16);
return (plPhysicsSdkHandle)new (mem)btPhysicsSdk;
}
void plDeletePhysicsSdk(plPhysicsSdkHandle physicsSdk)
{
btPhysicsSdk* phys = reinterpret_cast<btPhysicsSdk*>(physicsSdk);
btAlignedFree(phys);
}
/* Dynamics World */
plDynamicsWorldHandle plCreateDynamicsWorld(plPhysicsSdkHandle physicsSdkHandle)
{
btPhysicsSdk* physicsSdk = reinterpret_cast<btPhysicsSdk*>(physicsSdkHandle);
void* mem = btAlignedAlloc(sizeof(btDefaultCollisionConfiguration),16);
btDefaultCollisionConfiguration* collisionConfiguration = new (mem)btDefaultCollisionConfiguration();
mem = btAlignedAlloc(sizeof(btCollisionDispatcher),16);
btDispatcher* dispatcher = new (mem)btCollisionDispatcher(collisionConfiguration);
mem = btAlignedAlloc(sizeof(btAxisSweep3),16);
btBroadphaseInterface* pairCache = new (mem)btAxisSweep3(physicsSdk->m_worldAabbMin,physicsSdk->m_worldAabbMax);
mem = btAlignedAlloc(sizeof(btSequentialImpulseConstraintSolver),16);
btConstraintSolver* constraintSolver = new(mem) btSequentialImpulseConstraintSolver();
mem = btAlignedAlloc(sizeof(btDiscreteDynamicsWorld),16);
return (plDynamicsWorldHandle) new (mem)btDiscreteDynamicsWorld(dispatcher,pairCache,constraintSolver,collisionConfiguration);
}
void plDeleteDynamicsWorld(plDynamicsWorldHandle world)
{
//todo: also clean up the other allocations, axisSweep, pairCache,dispatcher,constraintSolver,collisionConfiguration
btDynamicsWorld* dynamicsWorld = reinterpret_cast< btDynamicsWorld* >(world);
btAlignedFree(dynamicsWorld);
}
void plStepSimulation(plDynamicsWorldHandle world, plReal timeStep)
{
btDynamicsWorld* dynamicsWorld = reinterpret_cast< btDynamicsWorld* >(world);
btAssert(dynamicsWorld);
dynamicsWorld->stepSimulation(timeStep);
}
void plAddRigidBody(plDynamicsWorldHandle world, plRigidBodyHandle object)
{
btDynamicsWorld* dynamicsWorld = reinterpret_cast< btDynamicsWorld* >(world);
btAssert(dynamicsWorld);
btRigidBody* body = reinterpret_cast< btRigidBody* >(object);
btAssert(body);
dynamicsWorld->addRigidBody(body);
}
void plRemoveRigidBody(plDynamicsWorldHandle world, plRigidBodyHandle object)
{
btDynamicsWorld* dynamicsWorld = reinterpret_cast< btDynamicsWorld* >(world);
btAssert(dynamicsWorld);
btRigidBody* body = reinterpret_cast< btRigidBody* >(object);
btAssert(body);
dynamicsWorld->removeRigidBody(body);
}
/* Rigid Body */
plRigidBodyHandle plCreateRigidBody( void* user_data, float mass, plCollisionShapeHandle cshape )
{
btTransform trans;
trans.setIdentity();
btVector3 localInertia(0,0,0);
btCollisionShape* shape = reinterpret_cast<btCollisionShape*>( cshape);
btAssert(shape);
if (mass)
{
shape->calculateLocalInertia(mass,localInertia);
}
void* mem = btAlignedAlloc(sizeof(btRigidBody),16);
btRigidBody::btRigidBodyConstructionInfo rbci(mass, 0,shape,localInertia);
btRigidBody* body = new (mem)btRigidBody(rbci);
body->setWorldTransform(trans);
body->setUserPointer(user_data);
return (plRigidBodyHandle) body;
}
void plDeleteRigidBody(plRigidBodyHandle cbody)
{
btRigidBody* body = reinterpret_cast< btRigidBody* >(cbody);
btAssert(body);
btAlignedFree( body);
}
/* Collision Shape definition */
plCollisionShapeHandle plNewSphereShape(plReal radius)
{
void* mem = btAlignedAlloc(sizeof(btSphereShape),16);
return (plCollisionShapeHandle) new (mem)btSphereShape(radius);
}
plCollisionShapeHandle plNewBoxShape(plReal x, plReal y, plReal z)
{
void* mem = btAlignedAlloc(sizeof(btBoxShape),16);
return (plCollisionShapeHandle) new (mem)btBoxShape(btVector3(x,y,z));
}
plCollisionShapeHandle plNewCapsuleShape(plReal radius, plReal height)
{
//capsule is convex hull of 2 spheres, so use btMultiSphereShape
const int numSpheres = 2;
btVector3 positions[numSpheres] = {btVector3(0,height,0),btVector3(0,-height,0)};
btScalar radi[numSpheres] = {radius,radius};
void* mem = btAlignedAlloc(sizeof(btMultiSphereShape),16);
return (plCollisionShapeHandle) new (mem)btMultiSphereShape(positions,radi,numSpheres);
}
plCollisionShapeHandle plNewConeShape(plReal radius, plReal height)
{
void* mem = btAlignedAlloc(sizeof(btConeShape),16);
return (plCollisionShapeHandle) new (mem)btConeShape(radius,height);
}
plCollisionShapeHandle plNewCylinderShape(plReal radius, plReal height)
{
void* mem = btAlignedAlloc(sizeof(btCylinderShape),16);
return (plCollisionShapeHandle) new (mem)btCylinderShape(btVector3(radius,height,radius));
}
/* Convex Meshes */
plCollisionShapeHandle plNewConvexHullShape()
{
void* mem = btAlignedAlloc(sizeof(btConvexHullShape),16);
return (plCollisionShapeHandle) new (mem)btConvexHullShape();
}
/* Concave static triangle meshes */
plMeshInterfaceHandle plNewMeshInterface()
{
return 0;
}
plCollisionShapeHandle plNewCompoundShape()
{
void* mem = btAlignedAlloc(sizeof(btCompoundShape),16);
return (plCollisionShapeHandle) new (mem)btCompoundShape();
}
void plAddChildShape(plCollisionShapeHandle compoundShapeHandle,plCollisionShapeHandle childShapeHandle, plVector3 childPos,plQuaternion childOrn)
{
btCollisionShape* colShape = reinterpret_cast<btCollisionShape*>(compoundShapeHandle);
btAssert(colShape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE);
btCompoundShape* compoundShape = reinterpret_cast<btCompoundShape*>(colShape);
btCollisionShape* childShape = reinterpret_cast<btCollisionShape*>(childShapeHandle);
btTransform localTrans;
localTrans.setIdentity();
localTrans.setOrigin(btVector3(childPos[0],childPos[1],childPos[2]));
localTrans.setRotation(btQuaternion(childOrn[0],childOrn[1],childOrn[2],childOrn[3]));
compoundShape->addChildShape(localTrans,childShape);
}
void plSetEuler(plReal yaw,plReal pitch,plReal roll, plQuaternion orient)
{
btQuaternion orn;
orn.setEuler(yaw,pitch,roll);
orient[0] = orn.getX();
orient[1] = orn.getY();
orient[2] = orn.getZ();
orient[3] = orn.getW();
}
// extern void plAddTriangle(plMeshInterfaceHandle meshHandle, plVector3 v0,plVector3 v1,plVector3 v2);
// extern plCollisionShapeHandle plNewStaticTriangleMeshShape(plMeshInterfaceHandle);
void plAddVertex(plCollisionShapeHandle cshape, plReal x,plReal y,plReal z)
{
btCollisionShape* colShape = reinterpret_cast<btCollisionShape*>( cshape);
(void)colShape;
btAssert(colShape->getShapeType()==CONVEX_HULL_SHAPE_PROXYTYPE);
btConvexHullShape* convexHullShape = reinterpret_cast<btConvexHullShape*>( cshape);
convexHullShape->addPoint(btVector3(x,y,z));
}
void plDeleteShape(plCollisionShapeHandle cshape)
{
btCollisionShape* shape = reinterpret_cast<btCollisionShape*>( cshape);
btAssert(shape);
btAlignedFree(shape);
}
void plSetScaling(plCollisionShapeHandle cshape, plVector3 cscaling)
{
btCollisionShape* shape = reinterpret_cast<btCollisionShape*>( cshape);
btAssert(shape);
btVector3 scaling(cscaling[0],cscaling[1],cscaling[2]);
shape->setLocalScaling(scaling);
}
void plSetPosition(plRigidBodyHandle object, const plVector3 position)
{
btRigidBody* body = reinterpret_cast< btRigidBody* >(object);
btAssert(body);
btVector3 pos(position[0],position[1],position[2]);
btTransform worldTrans = body->getWorldTransform();
worldTrans.setOrigin(pos);
body->setWorldTransform(worldTrans);
}
void plSetOrientation(plRigidBodyHandle object, const plQuaternion orientation)
{
btRigidBody* body = reinterpret_cast< btRigidBody* >(object);
btAssert(body);
btQuaternion orn(orientation[0],orientation[1],orientation[2],orientation[3]);
btTransform worldTrans = body->getWorldTransform();
worldTrans.setRotation(orn);
body->setWorldTransform(worldTrans);
}
void plSetOpenGLMatrix(plRigidBodyHandle object, plReal* matrix)
{
btRigidBody* body = reinterpret_cast< btRigidBody* >(object);
btAssert(body);
btTransform& worldTrans = body->getWorldTransform();
worldTrans.setFromOpenGLMatrix(matrix);
}
void plGetOpenGLMatrix(plRigidBodyHandle object, plReal* matrix)
{
btRigidBody* body = reinterpret_cast< btRigidBody* >(object);
btAssert(body);
body->getWorldTransform().getOpenGLMatrix(matrix);
}
void plGetPosition(plRigidBodyHandle object,plVector3 position)
{
btRigidBody* body = reinterpret_cast< btRigidBody* >(object);
btAssert(body);
const btVector3& pos = body->getWorldTransform().getOrigin();
position[0] = pos.getX();
position[1] = pos.getY();
position[2] = pos.getZ();
}
void plGetOrientation(plRigidBodyHandle object,plQuaternion orientation)
{
btRigidBody* body = reinterpret_cast< btRigidBody* >(object);
btAssert(body);
const btQuaternion& orn = body->getWorldTransform().getRotation();
orientation[0] = orn.getX();
orientation[1] = orn.getY();
orientation[2] = orn.getZ();
orientation[3] = orn.getW();
}
//plRigidBodyHandle plRayCast(plDynamicsWorldHandle world, const plVector3 rayStart, const plVector3 rayEnd, plVector3 hitpoint, plVector3 normal);
// extern plRigidBodyHandle plObjectCast(plDynamicsWorldHandle world, const plVector3 rayStart, const plVector3 rayEnd, plVector3 hitpoint, plVector3 normal);
double plNearestPoints(float p1[3], float p2[3], float p3[3], float q1[3], float q2[3], float q3[3], float *pa, float *pb, float normal[3])
{
btVector3 vp(p1[0], p1[1], p1[2]);
btTriangleShape trishapeA(vp,
btVector3(p2[0], p2[1], p2[2]),
btVector3(p3[0], p3[1], p3[2]));
trishapeA.setMargin(0.000001f);
btVector3 vq(q1[0], q1[1], q1[2]);
btTriangleShape trishapeB(vq,
btVector3(q2[0], q2[1], q2[2]),
btVector3(q3[0], q3[1], q3[2]));
trishapeB.setMargin(0.000001f);
// btVoronoiSimplexSolver sGjkSimplexSolver;
// btGjkEpaPenetrationDepthSolver penSolverPtr;
static btSimplexSolverInterface sGjkSimplexSolver;
sGjkSimplexSolver.reset();
static btGjkEpaPenetrationDepthSolver Solver0;
static btMinkowskiPenetrationDepthSolver Solver1;
btConvexPenetrationDepthSolver* Solver = NULL;
Solver = &Solver1;
btGjkPairDetector convexConvex(&trishapeA ,&trishapeB,&sGjkSimplexSolver,Solver);
convexConvex.m_catchDegeneracies = 1;
// btGjkPairDetector convexConvex(&trishapeA ,&trishapeB,&sGjkSimplexSolver,0);
btPointCollector gjkOutput;
btGjkPairDetector::ClosestPointInput input;
btTransform tr;
tr.setIdentity();
input.m_transformA = tr;
input.m_transformB = tr;
convexConvex.getClosestPoints(input, gjkOutput, 0);
if (gjkOutput.m_hasResult)
{
pb[0] = pa[0] = gjkOutput.m_pointInWorld[0];
pb[1] = pa[1] = gjkOutput.m_pointInWorld[1];
pb[2] = pa[2] = gjkOutput.m_pointInWorld[2];
pb[0]+= gjkOutput.m_normalOnBInWorld[0] * gjkOutput.m_distance;
pb[1]+= gjkOutput.m_normalOnBInWorld[1] * gjkOutput.m_distance;
pb[2]+= gjkOutput.m_normalOnBInWorld[2] * gjkOutput.m_distance;
normal[0] = gjkOutput.m_normalOnBInWorld[0];
normal[1] = gjkOutput.m_normalOnBInWorld[1];
normal[2] = gjkOutput.m_normalOnBInWorld[2];
return gjkOutput.m_distance;
}
return -1.0f;
}
| 0 | 0.935508 | 1 | 0.935508 | game-dev | MEDIA | 0.988454 | game-dev | 0.920212 | 1 | 0.920212 |
arcemu/arcemu | 7,406 | src/plugins/SpellHandlers/PetAISpells.cpp | #include "Setup.h"
class ArmyOfTheDeadGhoulAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(ArmyOfTheDeadGhoulAI);
ArmyOfTheDeadGhoulAI(Creature* c) : CreatureAIScript(c)
{
_unit->GetAIInterface()->m_canMove = false;
}
void OnLoad()
{
RegisterAIUpdateEvent(200);
if(_unit->IsSummon())
{
Summon* s = TO< Summon* >(_unit);
float parent_bonus = s->GetOwner()->GetDamageDoneMod(SCHOOL_NORMAL) * 0.04f ;
s->SetMinDamage(s->GetMinDamage() + parent_bonus);
s->SetMaxDamage(s->GetMaxDamage() + parent_bonus);
}
}
void AIUpdate()
{
_unit->CastSpell(_unit->GetGUID(), 20480, false);
RemoveAIUpdateEvent();
_unit->GetAIInterface()->m_canMove = true;
}
private:
};
class ShadowFiendAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(ShadowFiendAI);
ShadowFiendAI(Creature* c) : CreatureAIScript(c)
{
}
void OnLoad()
{
if(_unit->IsPet())
{
Pet* s = TO< Pet* >(_unit);
Player* owner = s->GetPetOwner();
float owner_bonus = static_cast< float >(owner->GetDamageDoneMod(SCHOOL_SHADOW) * 0.375f); // 37.5%
s->BaseAttackType = SCHOOL_SHADOW; // Melee hits are supposed to do damage with the shadow school
s->SetBaseAttackTime(MELEE, 1500); // Shadowfiend is supposed to do 10 attacks, sometimes it can be 11
s->SetMinDamage(s->GetMinDamage() + owner_bonus);
s->SetMaxDamage(s->GetMaxDamage() + owner_bonus);
s->BaseDamage[0] += owner_bonus;
s->BaseDamage[1] += owner_bonus;
Unit* uTarget = s->GetMapMgr()->GetUnit(owner->GetTargetGUID());
if((uTarget != NULL) && isAttackable(owner, uTarget))
{
s->GetAIInterface()->AttackReaction(uTarget, 1);
s->GetAIInterface()->setNextTarget(uTarget);
}
}
}
private:
};
class MirrorImageAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(MirrorImageAI);
MirrorImageAI(Creature* c) : CreatureAIScript(c)
{
}
void OnLoad()
{
if(_unit->IsSummon())
{
Summon* s = TO< Summon* >(_unit);
Unit* owner = s->GetOwner();
owner->CastSpell(_unit, 45204, true); // clone me
owner->CastSpell(_unit, 58838, true); // inherit threat list
// Mage mirror image spell
if(_unit->GetCreatedBySpell() == 58833)
{
_unit->SetMaxHealth(2500);
_unit->SetHealth(2500);
_unit->SetMaxPower(POWER_TYPE_MANA, owner->GetMaxPower(POWER_TYPE_MANA));
_unit->SetPower(POWER_TYPE_MANA, owner->GetPower(POWER_TYPE_MANA));
SpellRange* range = NULL;
AI_Spell sp1;
sp1.entryId = 59638;
sp1.spell = dbcSpell.LookupEntryForced(sp1.entryId);
sp1.spellType = STYPE_DAMAGE;
sp1.agent = AGENT_SPELL;
sp1.spelltargetType = TTYPE_SINGLETARGET;
sp1.cooldown = 0;
sp1.cooldowntime = 0;
sp1.Misc2 = 0;
sp1.procCount = 0;
sp1.procChance = 100;
range = dbcSpellRange.LookupEntry(sp1.spell->rangeIndex);
sp1.minrange = GetMinRange(range);
sp1.maxrange = GetMaxRange(range);
_unit->GetAIInterface()->addSpellToList(&sp1);
AI_Spell sp2;
sp2.entryId = 59637;
sp2.spell = dbcSpell.LookupEntryForced(sp2.entryId);
sp2.spellType = STYPE_DAMAGE;
sp2.agent = AGENT_SPELL;
sp2.spelltargetType = TTYPE_SINGLETARGET;
sp2.cooldown = 0;
sp2.cooldowntime = 0;
sp2.Misc2 = 0;
sp2.procCount = 0;
sp2.procChance = 100;
range = dbcSpellRange.LookupEntry(sp2.spell->rangeIndex);
sp2.minrange = GetMinRange(range);
sp2.maxrange = GetMaxRange(range);
_unit->GetAIInterface()->addSpellToList(&sp2);
}
}
}
private:
};
class DancingRuneWeaponAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(DancingRuneWeaponAI);
DancingRuneWeaponAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
}
void OnLoad()
{
_unit->SetDisplayId(_unit->GetProto()->Female_DisplayID);
_unit->SetBaseAttackTime(MELEE, 2000);
if(_unit->IsSummon())
{
Summon* s = TO< Summon* >(_unit);
Unit* owner = s->GetOwner();
if(owner->IsPlayer())
{
Player* pOwner = TO< Player* >(owner);
Item* item = pOwner->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_MAINHAND);
if(item != NULL)
{
for(int s = 0; s < 5; s++)
{
if(item->GetProto()->Spells[s].Id == 0)
continue;
if(item->GetProto()->Spells[s].Trigger == CHANCE_ON_HIT)
procSpell[s] = item->GetProto()->Spells[s].Id;
}
s->SetEquippedItem(MELEE, item->GetEntry());
s->SetBaseAttackTime(MELEE, item->GetProto()->Delay);
}
pOwner->SetPower(POWER_TYPE_RUNIC_POWER, 0);
}
s->SetMinDamage(owner->GetDamageDoneMod(SCHOOL_NORMAL));
s->SetMaxDamage(owner->GetDamageDoneMod(SCHOOL_NORMAL));
}
}
void OnDied(Unit* mKiller) { RemoveAIUpdateEvent(); }
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE));
dpsCycle = 0;
}
void OnCombatStop(Unit* mTarget)
{
RemoveAIUpdateEvent();
dpsCycle = 0;
}
void AIUpdate()
{
Unit* curtarget = _unit->GetAIInterface()->getNextTarget();
if(_unit->GetCurrentSpell() == NULL && curtarget)
{
switch(dpsCycle)
{
case 0:
dpsSpell = 49921; // Plague Strike
break;
case 1:
dpsSpell = 49909; // Icy Touch
break;
case 2:
case 3:
dpsSpell = 55262; // Heart Strike x 2
break;
case 4:
dpsSpell = 51425; // Obliterate
break;
case 5:
dpsSpell = 49895; // Death Coil
break;
case 6:
case 7:
dpsSpell = 51425; // Obliterate x 2
break;
case 8:
case 9:
dpsSpell = 55262; // Heart Strike x 2
break;
case 10:
case 11:
dpsSpell = 49895; // Death Coil x 2
break;
}
dpsCycle++;
if(dpsCycle > 11)
dpsCycle = 0;
SpellEntry* MyNextSpell = dbcSpell.LookupEntryForced(dpsSpell);
if(MyNextSpell != NULL)
_unit->CastSpell(curtarget, MyNextSpell, true);
}
}
void OnHit(Unit* mTarget, float fAmount)
{
for(int p = 0; p < 5; p++)
{
if(procSpell[p] != 0)
{
SpellEntry* mProc = dbcSpell.LookupEntryForced(procSpell[p]);
if(!mProc)
return;
int x = rand() % 100;
uint32 proc = mProc->procChance;
if(proc < 1)
proc = 10; // Got to be fair :P
if((uint32)x <= proc)
{
Unit* Vic = mProc->self_cast_only ? _unit : mTarget;
_unit->CastSpell(Vic, mProc, true);
}
}
}
}
private:
int dpsCycle;
int dpsSpell;
int procSpell[5];
};
class FrostBroodVanquisherAI : public CreatureAIScript{
public:
ADD_CREATURE_FACTORY_FUNCTION( FrostBroodVanquisherAI );
FrostBroodVanquisherAI( Creature *c ) : CreatureAIScript( c ){
}
void OnLoad(){
_unit->SetByte( UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_UNK_2 );
}
void OnLastPassengerLeft( Unit *passenger ){
if( _unit->GetSummonedByGUID() == passenger->GetGUID() )
_unit->Despawn( 1 * 1000, 0 );
}
};
void SetupPetAISpells(ScriptMgr* mgr)
{
mgr->register_creature_script(24207, &ArmyOfTheDeadGhoulAI::Create);
mgr->register_creature_script(19668, &ShadowFiendAI::Create);
mgr->register_creature_script(27893, &DancingRuneWeaponAI::Create);
mgr->register_creature_script(31216, &MirrorImageAI::Create);
mgr->register_creature_script( 28670, &FrostBroodVanquisherAI::Create );
};
| 0 | 0.933958 | 1 | 0.933958 | game-dev | MEDIA | 0.977965 | game-dev | 0.98757 | 1 | 0.98757 |
andr3wmac/Torque6 | 5,407 | lib/bullet/BulletCollision/CollisionShapes/btMultiSphereShape.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#if defined (_WIN32) || defined (__i386__)
#define BT_USE_SSE_IN_API
#endif
#include "btMultiSphereShape.h"
#include "BulletCollision/CollisionShapes/btCollisionMargin.h"
#include "LinearMath/btQuaternion.h"
#include "LinearMath/btSerializer.h"
btMultiSphereShape::btMultiSphereShape (const btVector3* positions,const btScalar* radi,int numSpheres)
:btConvexInternalAabbCachingShape ()
{
m_shapeType = MULTI_SPHERE_SHAPE_PROXYTYPE;
//btScalar startMargin = btScalar(BT_LARGE_FLOAT);
m_localPositionArray.resize(numSpheres);
m_radiArray.resize(numSpheres);
for (int i=0;i<numSpheres;i++)
{
m_localPositionArray[i] = positions[i];
m_radiArray[i] = radi[i];
}
recalcLocalAabb();
}
#ifndef MIN
#define MIN( _a, _b) ((_a) < (_b) ? (_a) : (_b))
#endif
btVector3 btMultiSphereShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const
{
btVector3 supVec(0,0,0);
btScalar maxDot(btScalar(-BT_LARGE_FLOAT));
btVector3 vec = vec0;
btScalar lenSqr = vec.length2();
if (lenSqr < (SIMD_EPSILON*SIMD_EPSILON))
{
vec.setValue(1,0,0);
} else
{
btScalar rlen = btScalar(1.) / btSqrt(lenSqr );
vec *= rlen;
}
btVector3 vtx;
btScalar newDot;
const btVector3* pos = &m_localPositionArray[0];
const btScalar* rad = &m_radiArray[0];
int numSpheres = m_localPositionArray.size();
for( int k = 0; k < numSpheres; k+= 128 )
{
btVector3 temp[128];
int inner_count = MIN( numSpheres - k, 128 );
for( long i = 0; i < inner_count; i++ )
{
temp[i] = (*pos) +vec*m_localScaling*(*rad) - vec * getMargin();
pos++;
rad++;
}
long i = vec.maxDot( temp, inner_count, newDot);
if( newDot > maxDot )
{
maxDot = newDot;
supVec = temp[i];
}
}
return supVec;
}
void btMultiSphereShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
for (int j=0;j<numVectors;j++)
{
btScalar maxDot(btScalar(-BT_LARGE_FLOAT));
const btVector3& vec = vectors[j];
btVector3 vtx;
btScalar newDot;
const btVector3* pos = &m_localPositionArray[0];
const btScalar* rad = &m_radiArray[0];
int numSpheres = m_localPositionArray.size();
for( int k = 0; k < numSpheres; k+= 128 )
{
btVector3 temp[128];
int inner_count = MIN( numSpheres - k, 128 );
for( long i = 0; i < inner_count; i++ )
{
temp[i] = (*pos) +vec*m_localScaling*(*rad) - vec * getMargin();
pos++;
rad++;
}
long i = vec.maxDot( temp, inner_count, newDot);
if( newDot > maxDot )
{
maxDot = newDot;
supportVerticesOut[j] = temp[i];
}
}
}
}
void btMultiSphereShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const
{
//as an approximation, take the inertia of the box that bounds the spheres
btVector3 localAabbMin,localAabbMax;
getCachedLocalAabb(localAabbMin,localAabbMax);
btVector3 halfExtents = (localAabbMax-localAabbMin)*btScalar(0.5);
btScalar lx=btScalar(2.)*(halfExtents.x());
btScalar ly=btScalar(2.)*(halfExtents.y());
btScalar lz=btScalar(2.)*(halfExtents.z());
inertia.setValue(mass/(btScalar(12.0)) * (ly*ly + lz*lz),
mass/(btScalar(12.0)) * (lx*lx + lz*lz),
mass/(btScalar(12.0)) * (lx*lx + ly*ly));
}
///fills the dataBuffer and returns the struct name (and 0 on failure)
const char* btMultiSphereShape::serialize(void* dataBuffer, btSerializer* serializer) const
{
btMultiSphereShapeData* shapeData = (btMultiSphereShapeData*) dataBuffer;
btConvexInternalShape::serialize(&shapeData->m_convexInternalShapeData, serializer);
int numElem = m_localPositionArray.size();
shapeData->m_localPositionArrayPtr = numElem ? (btPositionAndRadius*)serializer->getUniquePointer((void*)&m_localPositionArray[0]): 0;
shapeData->m_localPositionArraySize = numElem;
if (numElem)
{
btChunk* chunk = serializer->allocate(sizeof(btPositionAndRadius),numElem);
btPositionAndRadius* memPtr = (btPositionAndRadius*)chunk->m_oldPtr;
for (int i=0;i<numElem;i++,memPtr++)
{
m_localPositionArray[i].serializeFloat(memPtr->m_pos);
memPtr->m_radius = float(m_radiArray[i]);
}
serializer->finalizeChunk(chunk,"btPositionAndRadius",BT_ARRAY_CODE,(void*)&m_localPositionArray[0]);
}
return "btMultiSphereShapeData";
}
| 0 | 0.94125 | 1 | 0.94125 | game-dev | MEDIA | 0.9311 | game-dev | 0.991667 | 1 | 0.991667 |
CrucibleMC/Crucible | 1,548 | src/main/java/net/minecraft/inventory/ContainerRepairInventory.java | package net.minecraft.inventory;
// CraftBukkit start
import net.minecraft.item.ItemStack;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftHumanEntity;
import org.bukkit.entity.HumanEntity;
import java.util.List;
// CraftBukkit end
public class ContainerRepairInventory extends InventoryBasic // CraftBukkit - public
{
final ContainerRepair repairContainer;
// CraftBukkit start
public List<HumanEntity> transaction = new java.util.ArrayList<HumanEntity>();
public org.bukkit.entity.Player player;
private int maxStack = MAX_STACK;
ContainerRepairInventory(ContainerRepair par1ContainerRepair, String par2Str, boolean par3, int par4) {
super(par2Str, par3, par4);
this.repairContainer = par1ContainerRepair;
this.setMaxStackSize(1); // CraftBukkit
}
public ItemStack[] getContents() {
return this.inventoryContents;
}
public void onOpen(CraftHumanEntity who) {
transaction.add(who);
}
public void onClose(CraftHumanEntity who) {
transaction.remove(who);
}
public List<HumanEntity> getViewers() {
return transaction;
}
public org.bukkit.inventory.InventoryHolder getOwner() {
return this.player;
}
// CraftBukkit end
public void setMaxStackSize(int size) {
maxStack = size;
}
/**
* Called when an the contents of an Inventory change, usually
*/
public void markDirty() {
super.markDirty();
this.repairContainer.onCraftMatrixChanged(this);
}
} | 0 | 0.73006 | 1 | 0.73006 | game-dev | MEDIA | 0.998342 | game-dev | 0.637968 | 1 | 0.637968 |
ProjectSkyfire/SkyFire.406a | 5,859 | src/server/game/Entities/Item/ItemEnchantmentMgr.cpp | /*
* Copyright (C) 2011-2019 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2019 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2019 MaNGOS <https://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <functional>
#include "ItemEnchantmentMgr.h"
#include "DatabaseEnv.h"
#include "Log.h"
#include "ObjectMgr.h"
#include <list>
#include <vector>
#include "Util.h"
struct EnchStoreItem
{
uint32 ench;
float chance;
EnchStoreItem()
: ench(0), chance(0) {}
EnchStoreItem(uint32 _ench, float _chance)
: ench(_ench), chance(_chance) {}
};
typedef std::vector<EnchStoreItem> EnchStoreList;
typedef UNORDERED_MAP<uint32, EnchStoreList> EnchantmentStore;
static EnchantmentStore RandomItemEnch;
void LoadRandomEnchantmentsTable()
{
uint32 oldMSTime = getMSTime();
RandomItemEnch.clear(); // for reload case
QueryResult result = WorldDatabase.Query("SELECT entry, ench, chance FROM item_enchantment_template");
if (result)
{
uint32 count = 0;
do
{
Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
uint32 ench = fields[1].GetUInt32();
float chance = fields[2].GetFloat();
if (chance > 0.000001f && chance <= 100.0f)
RandomItemEnch[entry].push_back(EnchStoreItem(ench, chance));
++count;
} while (result->NextRow());
sLog->outString(">> Loaded %u Item Enchantment definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
else
{
sLog->outErrorDb(">> Loaded 0 Item Enchantment definitions. DB table `item_enchantment_template` is empty.");
sLog->outString();
}
}
uint32 GetItemEnchantMod(int32 entry)
{
if (!entry)
return 0;
if (entry == -1)
return 0;
EnchantmentStore::const_iterator tab = RandomItemEnch.find(entry);
if (tab == RandomItemEnch.end())
{
sLog->outErrorDb("Item RandomProperty / RandomSuffix id #%u used in `item_template` but it does not have records in `item_enchantment_template` table.", entry);
return 0;
}
double dRoll = rand_chance();
float fCount = 0;
for (EnchStoreList::const_iterator ench_iter = tab->second.begin(); ench_iter != tab->second.end(); ++ench_iter)
{
fCount += ench_iter->chance;
if (fCount > dRoll) return ench_iter->ench;
}
//we could get here only if sum of all enchantment chances is lower than 100%
dRoll = (irand(0, (int)floor(fCount * 100) + 1)) / 100;
fCount = 0;
for (EnchStoreList::const_iterator ench_iter = tab->second.begin(); ench_iter != tab->second.end(); ++ench_iter)
{
fCount += ench_iter->chance;
if (fCount > dRoll) return ench_iter->ench;
}
return 0;
}
uint32 GenerateEnchSuffixFactor(uint32 item_id)
{
ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(item_id);
if (!itemProto)
return 0;
if (!itemProto->RandomSuffix)
return 0;
RandomPropertiesPointsEntry const* randomProperty = sRandomPropertiesPointsStore.LookupEntry(itemProto->ItemLevel);
if (!randomProperty)
return 0;
uint32 suffixFactor;
switch (itemProto->InventoryType)
{
// Items of that type don`t have points
case INVTYPE_NON_EQUIP:
case INVTYPE_BAG:
case INVTYPE_TABARD:
case INVTYPE_AMMO:
case INVTYPE_QUIVER:
case INVTYPE_RELIC:
return 0;
// Select point coefficient
case INVTYPE_HEAD:
case INVTYPE_BODY:
case INVTYPE_CHEST:
case INVTYPE_LEGS:
case INVTYPE_2HWEAPON:
case INVTYPE_ROBE:
suffixFactor = 0;
break;
case INVTYPE_SHOULDERS:
case INVTYPE_WAIST:
case INVTYPE_FEET:
case INVTYPE_HANDS:
case INVTYPE_TRINKET:
suffixFactor = 1;
break;
case INVTYPE_NECK:
case INVTYPE_WRISTS:
case INVTYPE_FINGER:
case INVTYPE_SHIELD:
case INVTYPE_CLOAK:
case INVTYPE_HOLDABLE:
suffixFactor = 2;
break;
case INVTYPE_WEAPON:
case INVTYPE_WEAPONMAINHAND:
case INVTYPE_WEAPONOFFHAND:
suffixFactor = 3;
break;
case INVTYPE_RANGED:
case INVTYPE_THROWN:
case INVTYPE_RANGEDRIGHT:
suffixFactor = 4;
break;
default:
return 0;
}
// Select rare/epic modifier
switch (itemProto->Quality)
{
case ITEM_QUALITY_UNCOMMON:
return randomProperty->UncommonPropertiesPoints[suffixFactor];
case ITEM_QUALITY_RARE:
return randomProperty->RarePropertiesPoints[suffixFactor];
case ITEM_QUALITY_EPIC:
return randomProperty->EpicPropertiesPoints[suffixFactor];
case ITEM_QUALITY_LEGENDARY:
case ITEM_QUALITY_ARTIFACT:
return 0; // not have random properties
default:
break;
}
return 0;
}
| 0 | 0.943406 | 1 | 0.943406 | game-dev | MEDIA | 0.84087 | game-dev | 0.991176 | 1 | 0.991176 |
nguyenduong/spritebuilder_cocos2dx | 1,200 | spritebuilder/CCMenuItemLoader.cpp | #include "CCMenuItemLoader.h"
using namespace cocos2d;
#define PROPERTY_BLOCK "block"
#define PROPERTY_ISENABLED "isEnabled"
namespace spritebuilder {
void MenuItemLoader::onHandlePropTypeBlock(Node * pNode, Node * pParent, const char * pPropertyName, BlockData * pBlockData, CCBReader * ccbReader) {
if(strcmp(pPropertyName, PROPERTY_BLOCK) == 0) {
if (NULL != pBlockData) // Add this condition to allow MenuItemImage without target/selector predefined
{
((MenuItem *)pNode)->setCallback( std::bind( pBlockData->mSELMenuHandler, pBlockData->_target, std::placeholders::_1) );
// ((MenuItem *)pNode)->setTarget(pBlockData->_target, pBlockData->mSELMenuHandler);
}
} else {
NodeLoader::onHandlePropTypeBlock(pNode, pParent, pPropertyName, pBlockData, ccbReader);
}
}
void MenuItemLoader::onHandlePropTypeCheck(Node * pNode, Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader) {
if(strcmp(pPropertyName, PROPERTY_ISENABLED) == 0) {
((MenuItem *)pNode)->setEnabled(pCheck);
} else {
NodeLoader::onHandlePropTypeCheck(pNode, pParent, pPropertyName, pCheck, ccbReader);
}
}
} | 0 | 0.925993 | 1 | 0.925993 | game-dev | MEDIA | 0.50479 | game-dev | 0.611521 | 1 | 0.611521 |
MarkGG8181/stripped-1.8.9 | 10,382 | src/main/java/net/minecraft/entity/monster/EntityWitch.java | package net.minecraft.entity.monster;
import java.util.List;
import java.util.UUID;
import net.minecraft.block.material.Material;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.IRangedAttackMob;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIArrowAttack;
import net.minecraft.entity.ai.EntityAIHurtByTarget;
import net.minecraft.entity.ai.EntityAILookIdle;
import net.minecraft.entity.ai.EntityAINearestAttackableTarget;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.ai.EntityAIWander;
import net.minecraft.entity.ai.EntityAIWatchClosest;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityPotion;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.FastUUID;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
public class EntityWitch extends EntityMob implements IRangedAttackMob
{
private static final UUID MODIFIER_UUID = FastUUID.parseUUID("5CD17E52-A79A-43D3-A529-90FDE04B181E");
private static final AttributeModifier MODIFIER = new AttributeModifier(MODIFIER_UUID, "Drinking speed penalty", -0.25D, 0).setSaved(false);
/** List of items a witch should drop on death. */
private static final Item[] witchDrops = new Item[]{Items.glowstone_dust, Items.sugar, Items.redstone, Items.spider_eye, Items.glass_bottle, Items.gunpowder, Items.stick, Items.stick};
/**
* Timer used as interval for a witch's attack, decremented every tick if aggressive and when reaches zero the witch
* will throw a potion at the target entity.
*/
private int witchAttackTimer;
public EntityWitch(World worldIn)
{
super(worldIn);
this.setSize(0.6F, 1.95F);
this.tasks.addTask(1, new EntityAISwimming(this));
this.tasks.addTask(2, new EntityAIArrowAttack(this, 1.0D, 60, 10.0F));
this.tasks.addTask(2, new EntityAIWander(this, 1.0D));
this.tasks.addTask(3, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F));
this.tasks.addTask(3, new EntityAILookIdle(this));
this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, false, new Class[0]));
this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true));
}
protected void entityInit()
{
super.entityInit();
this.getDataWatcher().addObject(21, Byte.valueOf((byte)0));
}
/**
* Returns the sound this mob makes while it's alive.
*/
protected String getLivingSound()
{
return null;
}
/**
* Returns the sound this mob makes when it is hurt.
*/
protected String getHurtSound()
{
return null;
}
/**
* Returns the sound this mob makes on death.
*/
protected String getDeathSound()
{
return null;
}
/**
* Set whether this witch is aggressive at an entity.
*/
public void setAggressive(boolean aggressive)
{
this.getDataWatcher().updateObject(21, Byte.valueOf((byte)(aggressive ? 1 : 0)));
}
/**
* Return whether this witch is aggressive at an entity.
*/
public boolean getAggressive()
{
return this.getDataWatcher().getWatchableObjectByte(21) == 1;
}
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(26.0D);
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D);
}
/**
* Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons
* use this to react to sunlight and start to burn.
*/
public void onLivingUpdate()
{
if (!this.worldObj.isRemote)
{
if (this.getAggressive())
{
if (this.witchAttackTimer-- <= 0)
{
this.setAggressive(false);
ItemStack itemstack = this.getHeldItem();
this.setCurrentItemOrArmor(0, (ItemStack)null);
if (itemstack != null && itemstack.getItem() == Items.potionitem)
{
List<PotionEffect> list = Items.potionitem.getEffects(itemstack);
if (list != null)
{
for (PotionEffect potioneffect : list)
{
this.addPotionEffect(new PotionEffect(potioneffect));
}
}
}
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).removeModifier(MODIFIER);
}
}
else
{
int i = -1;
if (this.rand.nextFloat() < 0.15F && this.isInsideOfMaterial(Material.water) && !this.isPotionActive(Potion.waterBreathing))
{
i = 8237;
}
else if (this.rand.nextFloat() < 0.15F && this.isBurning() && !this.isPotionActive(Potion.fireResistance))
{
i = 16307;
}
else if (this.rand.nextFloat() < 0.05F && this.getHealth() < this.getMaxHealth())
{
i = 16341;
}
else if (this.rand.nextFloat() < 0.25F && this.getAttackTarget() != null && !this.isPotionActive(Potion.moveSpeed) && this.getAttackTarget().getDistanceSqToEntity(this) > 121.0D)
{
i = 16274;
}
else if (this.rand.nextFloat() < 0.25F && this.getAttackTarget() != null && !this.isPotionActive(Potion.moveSpeed) && this.getAttackTarget().getDistanceSqToEntity(this) > 121.0D)
{
i = 16274;
}
if (i > -1)
{
this.setCurrentItemOrArmor(0, new ItemStack(Items.potionitem, 1, i));
this.witchAttackTimer = this.getHeldItem().getMaxItemUseDuration();
this.setAggressive(true);
IAttributeInstance iattributeinstance = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed);
iattributeinstance.removeModifier(MODIFIER);
iattributeinstance.applyModifier(MODIFIER);
}
}
if (this.rand.nextFloat() < 7.5E-4F)
{
this.worldObj.setEntityState(this, (byte)15);
}
}
super.onLivingUpdate();
}
public void handleStatusUpdate(byte id)
{
if (id == 15)
{
for (int i = 0; i < this.rand.nextInt(35) + 10; i++)
{
this.worldObj.spawnParticle(EnumParticleTypes.SPELL_WITCH, this.posX + this.rand.nextGaussian() * 0.12999999523162842D, this.getEntityBoundingBox().maxY + 0.5D + this.rand.nextGaussian() * 0.12999999523162842D, this.posZ + this.rand.nextGaussian() * 0.12999999523162842D, 0.0D, 0.0D, 0.0D, new int[0]);
}
}
else
{
super.handleStatusUpdate(id);
}
}
/**
* Reduces damage, depending on potions
*/
protected float applyPotionDamageCalculations(DamageSource source, float damage)
{
damage = super.applyPotionDamageCalculations(source, damage);
if (source.getEntity() == this)
{
damage = 0.0F;
}
if (source.isMagicDamage())
{
damage = (float)((double)damage * 0.15D);
}
return damage;
}
/**
* Drop 0-2 items of this living's type
*
* @param wasRecentlyHit true if this this entity was recently hit by appropriate entity (generally only if player
* or tameable)
* @param lootingModifier level of enchanment to be applied to this drop
*/
protected void dropFewItems(boolean wasRecentlyHit, int lootingModifier)
{
int i = this.rand.nextInt(3) + 1;
for (int j = 0; j < i; j++)
{
int k = this.rand.nextInt(3);
Item item = witchDrops[this.rand.nextInt(witchDrops.length)];
if (lootingModifier > 0)
{
k += this.rand.nextInt(lootingModifier + 1);
}
for (int l = 0; l < k; l++)
{
this.dropItem(item, 1);
}
}
}
/**
* Attack the specified entity using a ranged attack.
*/
public void attackEntityWithRangedAttack(EntityLivingBase target, float p_82196_2_)
{
if (!this.getAggressive())
{
EntityPotion entitypotion = new EntityPotion(this.worldObj, this, 32732);
double d0 = target.posY + (double)target.getEyeHeight() - 1.100000023841858D;
entitypotion.rotationPitch -= -20.0F;
double d1 = target.posX + target.motionX - this.posX;
double d2 = d0 - this.posY;
double d3 = target.posZ + target.motionZ - this.posZ;
float f = MathHelper.sqrt_double(d1 * d1 + d3 * d3);
if (f >= 8.0F && !target.isPotionActive(Potion.moveSlowdown))
{
entitypotion.setPotionDamage(32698);
}
else if (target.getHealth() >= 8.0F && !target.isPotionActive(Potion.poison))
{
entitypotion.setPotionDamage(32660);
}
else if (f <= 3.0F && !target.isPotionActive(Potion.weakness) && this.rand.nextFloat() < 0.25F)
{
entitypotion.setPotionDamage(32696);
}
entitypotion.setThrowableHeading(d1, d2 + (double)(f * 0.2F), d3, 0.75F, 8.0F);
this.worldObj.spawnEntityInWorld(entitypotion);
}
}
public float getEyeHeight()
{
return 1.62F;
}
}
| 0 | 0.891375 | 1 | 0.891375 | game-dev | MEDIA | 0.998512 | game-dev | 0.978809 | 1 | 0.978809 |
DynamXInc/DynamX | 8,546 | src/main/java/fr/dynamx/common/physics/PhysicsTickHandler.java | package fr.dynamx.common.physics;
import fr.dynamx.api.network.EnumPacketTarget;
import fr.dynamx.api.physics.IPhysicsWorld;
import fr.dynamx.common.DynamXContext;
import fr.dynamx.common.DynamXMain;
import fr.dynamx.common.handlers.TaskScheduler;
import fr.dynamx.common.network.packets.MessageCollisionDebugDraw;
import fr.dynamx.server.command.CmdNetworkConfig;
import fr.dynamx.utils.DynamXLoadingTasks;
import fr.dynamx.utils.debug.DynamXDebugOptions;
import fr.dynamx.utils.debug.Profiler;
import fr.dynamx.utils.optimization.QuaternionPool;
import fr.dynamx.utils.optimization.SubClassPool;
import fr.dynamx.utils.optimization.Vector3fPool;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.HashMap;
import java.util.Map;
public class PhysicsTickHandler {
private static long lastTickTimeMs;
public static final Map<EntityPlayer, Integer> requestedDebugInfo = new HashMap<>();
@SideOnly(Side.CLIENT)
@SubscribeEvent(priority = EventPriority.LOWEST)
public void tickClient(TickEvent.ClientTickEvent event) {
if (event.phase == TickEvent.Phase.START) {
try {
Profiler.get().start(Profiler.Profiles.TICK);
} catch (Exception e) {
e.printStackTrace();
}
}
if (canTickClient(Minecraft.getMinecraft())) {
tickWorldPhysics(event.phase, Minecraft.getMinecraft().world);
}
if (event.phase == TickEvent.Phase.START) {
QuaternionPool.openPool(SubClassPool.TICK_CLIENT);
Vector3fPool.openPool(SubClassPool.TICK_CLIENT);
DynamXLoadingTasks.tick();
} else {
Profiler.get().end(Profiler.Profiles.TICK);
if (Minecraft.getMinecraft().world != null) {
boolean profiling = DynamXDebugOptions.PROFILING.isActive();
if (profiling) {
if (DynamXMain.proxy.getTickTime() % 20 == 0) {
Profiler.get().printData("Client");
}
}
Profiler.setIsProfilingOn(profiling);
Profiler.get().update();
}
if (!Minecraft.getMinecraft().isSingleplayer()) {//If not in solo
TaskScheduler.tick();
}
Vector3fPool.closePool();
QuaternionPool.closePool();
}
}
@SideOnly(Side.CLIENT)
private boolean canTickClient(Minecraft mc) {
return mc.world != null && !mc.isGamePaused() && DynamXMain.proxy.shouldUseBulletSimulation(mc.world) && DynamXContext.getPhysicsWorld(mc.world) != null;
}
@SubscribeEvent
public void tickServer(TickEvent.ServerTickEvent event) {
if (event.phase == TickEvent.Phase.START) {
QuaternionPool.openPool(SubClassPool.TICK_SERVER);
Vector3fPool.openPool(SubClassPool.TICK_SERVER);
try {
Profiler.get().start(Profiler.Profiles.TICK);
} catch (Exception e) {
DynamXMain.log.throwing(e);
}
}
for (WorldServer world : FMLCommonHandler.instance().getMinecraftServerInstance().worlds) {
if (canTickServer(world)) {
tickWorldPhysics(event.phase, world);
}
}
if (event.phase == TickEvent.Phase.START) {
if (FMLCommonHandler.instance().getSide().isServer()) {
DynamXLoadingTasks.tick();
}
} else {
Profiler.get().end(Profiler.Profiles.TICK);
sendClientsDebug();
Profiler.get().update();
TaskScheduler.tick();
Vector3fPool.closePool();
QuaternionPool.closePool();
}
}
private boolean canTickServer(World world) {
return world != null && DynamXMain.proxy.shouldUseBulletSimulation(world) && DynamXContext.getPhysicsWorld(world) != null;
}
private void tickWorldPhysics(TickEvent.Phase phase, World world) {
IPhysicsWorld physicsWorld = DynamXContext.getPhysicsWorld(world);
if (phase == TickEvent.Phase.END) {
physicsWorld.tickEnd();
return;
}
// START phase
QuaternionPool.openPool(SubClassPool.TICK_PHYSICS_WORLD);
Vector3fPool.openPool(SubClassPool.TICK_PHYSICS_WORLD);
physicsWorld.tickStart();
float deltaTimeSecond = getDeltaTimeMilliseconds() * 1.0E-3F;
if (deltaTimeSecond > 0.5f) // game was paused ?
deltaTimeSecond = 0.05f;
Profiler.get().start(Profiler.Profiles.STEP_SIMULATION);
physicsWorld.stepSimulation(deltaTimeSecond);
Profiler.get().end(Profiler.Profiles.STEP_SIMULATION);
if (physicsWorld.getDynamicsWorld() != null) {
physicsWorld.getDynamicsWorld().getJointList().forEach(joint -> {
if ((joint.getBodyA() != null && !physicsWorld.getDynamicsWorld().contains(joint.getBodyA()))
|| (joint.getBodyB() != null && !physicsWorld.getDynamicsWorld().contains(joint.getBodyB()))) {
physicsWorld.removeJoint(joint);
}
});
}
Vector3fPool.closePool();
QuaternionPool.closePool();
}
private void sendClientsDebug() {
boolean profiling;
if (DynamXMain.proxy.getServerWorld().getMinecraftServer().isDedicatedServer()) { //If integrated server, the vars are already shared
profiling = false;
boolean networkDebug = false, wheelData = false;
for (Map.Entry<EntityPlayer, Integer> e : requestedDebugInfo.entrySet()) {
//Don't spam of debug packets
if (DynamXMain.proxy.getServerWorld().getMinecraftServer().getTickCounter() % 10 == 0 && (DynamXDebugOptions.BLOCK_BOXES.matchesNetMask(e.getValue()) || DynamXDebugOptions.SLOPE_BOXES.matchesNetMask(e.getValue()))) {
DynamXContext.getNetwork().sendToClient(new MessageCollisionDebugDraw(DynamXDebugOptions.BLOCK_BOXES.getDataIn(), DynamXDebugOptions.SLOPE_BOXES.getDataIn()), EnumPacketTarget.PLAYER, (EntityPlayerMP) e.getKey());
}
if (DynamXDebugOptions.PROFILING.matchesNetMask(e.getValue())) {
profiling = true;
} else if (DynamXDebugOptions.FULL_NETWORK_DEBUG.matchesNetMask(e.getValue())) {
networkDebug = true;
} else if (DynamXDebugOptions.WHEEL_ADVANCED_DATA.matchesNetMask(e.getValue())) {
wheelData = true;
}
}
if (DynamXMain.proxy.getServerWorld().getMinecraftServer().getTickCounter() % 5 == 0) //requestedDebugInfo is sent all 5 ticks
requestedDebugInfo.clear();
if (networkDebug != DynamXDebugOptions.FULL_NETWORK_DEBUG.isActive()) {
//System.out.println("Setting FULL_NETWORK_DEBUG active : " + networkDebug);
if (networkDebug)
DynamXDebugOptions.FULL_NETWORK_DEBUG.enable();
else
DynamXDebugOptions.FULL_NETWORK_DEBUG.disable();
}
if (wheelData != DynamXDebugOptions.WHEEL_ADVANCED_DATA.isActive()) {
//System.out.println("Setting WHEEL_ADVANCED_DATA active : " + wheelData);
if (wheelData)
DynamXDebugOptions.WHEEL_ADVANCED_DATA.enable();
else
DynamXDebugOptions.WHEEL_ADVANCED_DATA.disable();
}
} else {
profiling = DynamXDebugOptions.PROFILING.isActive();
}
if (profiling) {
if (DynamXMain.proxy.getTickTime() % 20 == 0) {
Profiler.get().printData("Server");
}
}
Profiler.setIsProfilingOn(profiling);
}
private float getDeltaTimeMilliseconds() {
long cur = System.currentTimeMillis();
long dt = cur - lastTickTimeMs;
lastTickTimeMs = cur;
return dt;
}
}
| 0 | 0.904795 | 1 | 0.904795 | game-dev | MEDIA | 0.613766 | game-dev | 0.925367 | 1 | 0.925367 |
holycake/mhsj | 4,637 | d/WUDANG1/LIANTAI.C | // Room: /d/shaolin/donglang2.c
// By Marz 04/01/96
inherit ROOM;
void init();
void close_men();
void force_open(object);
int do_push(string arg);
int do_knock(string arg);
int valid_leave(object, string);
string look_men();
void create()
{
set("short", "十二莲台");
set("long", @LONG
你走在一条宽敞的石廊上,南边是一个高高的牌楼,雕梁画栋很是好看。东边有
一扇门(men),好象是虚掩着。西边是间竹子扎就的屋子,十分的素雅,里面飘
出一阵阵的茶香,有人轻声细语地不知说那些什么,引得女孩子"吃吃"笑出声来。
LONG
);
set("exits", ([
"north" : __DIR__"zijincheng",
"south" : __DIR__"santian",
"west" : __DIR__"temp1",
]));
set("item_desc",([
"men" : (: look_men :),
]));
setup();
}
void init()
{
add_action("do_knock", "knock");
add_action("do_push", "push");
}
int close_men()
{
object room;
if(!( room = find_object(__DIR__"xiuxishi")) )
room = load_object(__DIR__"xiuxishi");
if(objectp(room))
{
delete("exits/west");
message("vision", "门吱吱呀呀地自己合上了。\n", this_object());
room->delete("exits/east");
message("vision", "门吱吱呀呀地自己合上了。\n", room);
}
else message("vision", "ERROR: men not found(close).\n", room);
}
int do_knock(string arg)
{
object room;
if (query("exits/east"))
return notify_fail("大门已经是开着了。\n");
if (!arg || (arg != "door" && arg != "men"))
return notify_fail("你要敲什么?\n");
if(!( room = find_object(__DIR__"xiuxishi")) )
room = load_object(__DIR__"xiuxishi");
if(objectp(room))
{
if ((int)room->query_temp("sleeping_person") > 0)
{
message_vision(
"$N刚轻轻地敲了一下门,就听见里面传出一阵雷鸣般的鼾声,\n"
"显然里面的人睡得跟死猪似的,怎么敲都没用了\n",
this_player());
} else if ((int)room->query_temp("person_inside") > 0)
{
switch( random(2) )
{
case 0:
message_vision(
"$N轻轻地敲了敲门,只听见里面有人很不耐烦地吼到:\n"
"刚躺下就来敲门!我睡着了,听不见!!!\n",
this_player());
break;
case 1:
message_vision(
"$N轻轻地敲了敲门,只听见里面有些响动,\n"
"好象有人在踱来踱去,拿不定主意是否开门。\n",
this_player());
break;
}
} else
{
room->delete_temp("sleeping_person");
message_vision("$N轻轻地敲了敲门:咚、咚、咚...咚、咚、咚...\n",
this_player());
}
}
if(objectp(room))
message("vision",
"外面传来一阵敲门声,你从门缝往外一瞧,是"+this_player()->query("name")+"一脸焦急地站在门外,\n"
"看样子也想进来休息。\n", room);
return 1;
}
int do_push(string arg)
{
object room;
if (query("exits/east"))
return notify_fail("门已经是开着了。\n");
if (!arg || (arg != "door" && arg != "men"))
return notify_fail("你要推什么?\n");
if(!(room = find_object(__DIR__"xiuxishi")))
room = load_object(__DIR__"xiuxishi");
if(objectp(room))
{
if((int)room->query_temp("person_inside")<=0)
{
room->delete_temp("person_inside");
set("exits/east", __DIR__"xiuxishi");
message_vision("$N轻轻地把门推开。\n", this_player());
room->set("exits/west", __FILE__);
// message("vision", "有人从外面把门推开了。\n", room);
remove_call_out("close_men");
call_out("close_men", 10);
} else
{
message_vision("$N想把门推开,却发觉门被人从里面闩上了。\n",
this_player());
}
}
return 1;
}
string look_men()
{
object room;
if (query("exits/east"))
return ("门上挂了个牌子:南柯梦处\n");
if(!( room = find_object(__DIR__"xiuxishi")) )
room = load_object(__DIR__"xiuxishi");
if( objectp(room) )
if( (int)room->query_temp("person_inside") > 0 )
{
return ("门上挂了个牌子:请毋打扰\n");
}
return ("门上挂了个牌子:休息室\n");
}
int valid_leave(object me, string dir)
{
object room;
if(!( room = find_object(__DIR__"xiuxishi")) )
room = load_object(__DIR__"xiuxishi");
if(objectp(room) && dir == "north")
{
room->add_temp("person_inside", 1);
// will open the door if ppl inside stay too long
remove_call_out("force_open");
call_out("force_open", 599, room);
}
return ::valid_leave(me, dir);
}
int force_open(object room)
{
if ( !objectp(room) ) return 0;
if((int)room->query_temp("person_inside")<=0) return 0;
/***
if((int)room->query_temp("sleeping_person")>0)
{
remove_call_out("force_open");
call_out("force_open", 599, room);
return 0;
}
***/
room->delete_temp("person_inside");
set("exits/east", __DIR__"xiuxishi");
room->set("exits/west", __FILE__);
message("vision", "外面突然响起粗重的脚步声,由远而近,到门前停了下来...\n"
"张松溪啪地把门打开,伸个头进来,一脸狐疑:呆大半天了还不出去,搞什么鬼?\n", room);
remove_call_out("close_men");
call_out("close_men", 10);
}
// End of file
| 0 | 0.771589 | 1 | 0.771589 | game-dev | MEDIA | 0.882723 | game-dev,cli-devtools | 0.574563 | 1 | 0.574563 |
SkriptLang/Skript | 12,952 | src/main/java/ch/njol/skript/command/Commands.java | package ch.njol.skript.command;
import ch.njol.skript.ScriptLoader;
import ch.njol.skript.Skript;
import ch.njol.skript.SkriptConfig;
import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.TriggerItem;
import ch.njol.skript.lang.parser.ParserInstance;
import ch.njol.skript.localization.ArgsMessage;
import ch.njol.skript.localization.Message;
import ch.njol.skript.log.RetainingLogHandler;
import ch.njol.skript.log.SkriptLogger;
import ch.njol.skript.util.SkriptColor;
import ch.njol.skript.variables.Variables;
import com.google.common.base.Preconditions;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.ServerCommandEvent;
import org.bukkit.help.HelpMap;
import org.bukkit.help.HelpTopic;
import org.bukkit.plugin.SimplePluginManager;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import org.skriptlang.skript.lang.script.Script;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.regex.Pattern;
//TODO option to disable replacement of <color>s in command arguments?
/**
* @author Peter Güttinger
*/
@SuppressWarnings("deprecation")
public abstract class Commands {
public final static ArgsMessage m_too_many_arguments = new ArgsMessage("commands.too many arguments");
public final static Message m_internal_error = new Message("commands.internal error");
public final static Message m_correct_usage = new Message("commands.correct usage");
/**
* A Converter flag declaring that a Converter cannot be used for parsing command arguments.
*/
public static final int CONVERTER_NO_COMMAND_ARGUMENTS = 8;
private final static Map<String, ScriptCommand> commands = new HashMap<>();
@Nullable
private static SimpleCommandMap commandMap = null;
@Nullable
private static Map<String, Command> cmKnownCommands;
@Nullable
private static Set<String> cmAliases;
static {
init(); // separate method for the annotation
}
public static Set<String> getScriptCommands(){
return commands.keySet();
}
@Nullable
public static SimpleCommandMap getCommandMap(){
return commandMap;
}
@SuppressWarnings({"unchecked", "removal"})
private static void init() {
try {
if (Bukkit.getPluginManager() instanceof SimplePluginManager) {
Field commandMapField = SimplePluginManager.class.getDeclaredField("commandMap");
commandMapField.setAccessible(true);
commandMap = (SimpleCommandMap) commandMapField.get(Bukkit.getPluginManager());
Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true);
cmKnownCommands = (Map<String, Command>) knownCommandsField.get(commandMap);
try {
Field aliasesField = SimpleCommandMap.class.getDeclaredField("aliases");
aliasesField.setAccessible(true);
cmAliases = (Set<String>) aliasesField.get(commandMap);
} catch (NoSuchFieldException ignored) {}
}
} catch (SecurityException e) {
Skript.error("Please disable the security manager");
commandMap = null;
} catch (Exception e) {
Skript.outdatedError(e);
commandMap = null;
}
}
@Nullable
public static List<Argument<?>> currentArguments = null;
@SuppressWarnings("null")
private final static Pattern escape = Pattern.compile("[" + Pattern.quote("(|)<>%\\") + "]");
@SuppressWarnings("null")
private final static Pattern unescape = Pattern.compile("\\\\[" + Pattern.quote("(|)<>%\\") + "]");
public static String escape(String string) {
return "" + escape.matcher(string).replaceAll("\\\\$0");
}
public static String unescape(String string) {
return "" + unescape.matcher(string).replaceAll("$0");
}
private final static Listener commandListener = new Listener() {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
// Spigot will simply report that the command doesn't exist if a player does not have permission to use it.
// This is good security but, well, it's a breaking change for Skript. So we need to check for permissions
// ourselves and handle those messages, for every command.
// parse command, see if it's a skript command
String[] cmd = event.getMessage().substring(1).split("\\s+", 2);
String label = cmd[0].toLowerCase(Locale.ENGLISH);
String arguments = cmd.length == 1 ? "" : "" + cmd[1];
ScriptCommand command = commands.get(label);
// is it a skript command?
if (command != null) {
// if so, check permissions to handle ourselves
if (!command.checkPermissions(event.getPlayer(), label, arguments))
event.setCancelled(true);
// we can also handle case sensitivity here:
if (SkriptConfig.caseInsensitiveCommands.value()) {
cmd[0] = event.getMessage().charAt(0) + label;
event.setMessage(String.join(" ", cmd));
}
}
}
@SuppressWarnings("null")
@EventHandler(priority = EventPriority.HIGHEST)
public void onServerCommand(ServerCommandEvent event) {
if (event.getCommand().isEmpty() || event.isCancelled())
return;
if ((Skript.testing() || SkriptConfig.enableEffectCommands.value()) && event.getCommand().startsWith(SkriptConfig.effectCommandToken.value())) {
if (handleEffectCommand(event.getSender(), event.getCommand()))
event.setCancelled(true);
}
}
};
static boolean handleEffectCommand(CommandSender sender, String command) {
if (!(Skript.testing() || sender instanceof ConsoleCommandSender || sender.hasPermission("skript.effectcommands") || SkriptConfig.allowOpsToUseEffectCommands.value() && sender.isOp()))
return false;
try {
command = "" + command.substring(SkriptConfig.effectCommandToken.value().length()).trim();
RetainingLogHandler log = SkriptLogger.startRetainingLog();
try {
// Call the event on the Bukkit API for addon developers.
EffectCommandEvent effectCommand = new EffectCommandEvent(sender, command);
Bukkit.getPluginManager().callEvent(effectCommand);
command = effectCommand.getCommand();
ParserInstance parserInstance = ParserInstance.get();
parserInstance.setCurrentEvent("effect command", EffectCommandEvent.class);
Effect effect = Effect.parse(command, null);
parserInstance.deleteCurrentEvent();
if (effect != null) {
log.clear(); // ignore warnings and stuff
log.printLog();
if (!effectCommand.isCancelled()) {
sender.sendMessage(ChatColor.GRAY + "executing '" + SkriptColor.replaceColorChar(command) + "'");
if (SkriptConfig.logEffectCommands.value() && !(sender instanceof ConsoleCommandSender))
Skript.info(sender.getName() + " issued effect command: " + SkriptColor.replaceColorChar(command));
TriggerItem.walk(effect, effectCommand);
Variables.removeLocals(effectCommand);
} else {
sender.sendMessage(ChatColor.RED + "your effect command '" + SkriptColor.replaceColorChar(command) + "' was cancelled.");
}
} else {
if (sender == Bukkit.getConsoleSender()) // log as SEVERE instead of INFO like printErrors below
SkriptLogger.LOGGER.severe("Error in: " + SkriptColor.replaceColorChar(command));
else
sender.sendMessage(ChatColor.RED + "Error in: " + ChatColor.GRAY + SkriptColor.replaceColorChar(command));
log.printErrors(sender, "(No specific information is available)");
}
} finally {
log.stop();
}
return true;
} catch (Exception e) {
Skript.exception(e, "Unexpected error while executing effect command '" + SkriptColor.replaceColorChar(command) + "' by '" + sender.getName() + "'");
sender.sendMessage(ChatColor.RED + "An internal error occurred while executing this effect. Please refer to the server log for details.");
return true;
}
}
@Nullable
public static ScriptCommand getScriptCommand(String key) {
return commands.get(key);
}
/**
* @deprecated Use {@link #scriptCommandExists(String)} instead.
*/
@Deprecated(since = "2.8.0", forRemoval = true)
public static boolean skriptCommandExists(String command) {
return scriptCommandExists(command);
}
public static boolean scriptCommandExists(String command) {
ScriptCommand scriptCommand = commands.get(command);
return scriptCommand != null && scriptCommand.getName().equals(command);
}
public static void registerCommand(ScriptCommand command) {
// Validate that there are no duplicates
ScriptCommand existingCommand = commands.get(command.getLabel());
if (existingCommand != null && existingCommand.getLabel().equals(command.getLabel())) {
Script script = existingCommand.getScript();
Skript.error("A command with the name /" + existingCommand.getName() + " is already defined"
+ (script != null ? (" in " + script.getConfig().getFileName()) : "")
);
return;
}
if (commandMap != null) {
assert cmKnownCommands != null;// && cmAliases != null;
command.register(commandMap, cmKnownCommands, cmAliases);
}
commands.put(command.getLabel(), command);
for (String alias : command.getActiveAliases()) {
commands.put(alias.toLowerCase(Locale.ENGLISH), command);
}
command.registerHelp();
}
@Deprecated(since = "2.7.0", forRemoval = true)
public static int unregisterCommands(File script) {
int numCommands = 0;
for (ScriptCommand c : new ArrayList<>(commands.values())) {
if (c.getScript() != null && c.getScript().equals(ScriptLoader.getScript(script))) {
numCommands++;
unregisterCommand(c);
}
}
return numCommands;
}
public static void unregisterCommand(ScriptCommand scriptCommand) {
scriptCommand.unregisterHelp();
if (commandMap != null) {
assert cmKnownCommands != null;// && cmAliases != null;
scriptCommand.unregister(commandMap, cmKnownCommands, cmAliases);
}
commands.values().removeIf(command -> command == scriptCommand);
}
private static boolean registeredListeners = false;
public static void registerListeners() {
if (!registeredListeners) {
Bukkit.getPluginManager().registerEvents(commandListener, Skript.getInstance());
Bukkit.getPluginManager().registerEvents(new Listener() {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
if ((!SkriptConfig.enableEffectCommands.value() && !Skript.testing()) || !event.getMessage().startsWith(SkriptConfig.effectCommandToken.value()))
return;
if (!event.isAsynchronous()) {
if (handleEffectCommand(event.getPlayer(), event.getMessage()))
event.setCancelled(true);
} else {
Future<Boolean> f = Bukkit.getScheduler().callSyncMethod(Skript.getInstance(), () -> handleEffectCommand(event.getPlayer(), event.getMessage()));
try {
while (true) {
try {
if (f.get())
event.setCancelled(true);
break;
} catch (InterruptedException ignored) {
}
}
} catch (ExecutionException e) {
Skript.exception(e);
}
}
}
}, Skript.getInstance());
registeredListeners = true;
}
}
/**
* copied from CraftBukkit (org.bukkit.craftbukkit.help.CommandAliasHelpTopic)
*/
public static final class CommandAliasHelpTopic extends HelpTopic {
private final String aliasFor;
private final HelpMap helpMap;
public CommandAliasHelpTopic(String alias, String aliasFor, HelpMap helpMap) {
this.aliasFor = aliasFor.startsWith("/") ? aliasFor : "/" + aliasFor;
this.helpMap = helpMap;
name = alias.startsWith("/") ? alias : "/" + alias;
Preconditions.checkState(!name.equals(this.aliasFor), "Command " + name + " cannot be alias for itself");
shortText = ChatColor.YELLOW + "Alias for " + ChatColor.WHITE + this.aliasFor;
}
@Override
@NotNull
public String getFullText(CommandSender forWho) {
StringBuilder fullText = new StringBuilder(shortText);
HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor);
if (aliasForTopic != null) {
fullText.append("\n");
fullText.append(aliasForTopic.getFullText(forWho));
}
return "" + fullText;
}
@Override
public boolean canSee(CommandSender commandSender) {
if (amendedPermission != null)
return commandSender.hasPermission(amendedPermission);
HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor);
return aliasForTopic != null && aliasForTopic.canSee(commandSender);
}
}
}
| 0 | 0.946896 | 1 | 0.946896 | game-dev | MEDIA | 0.673751 | game-dev | 0.983085 | 1 | 0.983085 |
DarkstarProject/darkstar | 1,830 | scripts/globals/effects/light_arts.lua | -----------------------------------
--
--
--
-----------------------------------
function onEffectGain(target,effect)
target:recalculateAbilitiesTable()
local bonus = effect:getPower()
local regen = effect:getSubPower()
target:addMod(dsp.mod.WHITE_MAGIC_COST, -bonus)
target:addMod(dsp.mod.WHITE_MAGIC_CAST, -bonus)
target:addMod(dsp.mod.WHITE_MAGIC_RECAST, -bonus)
if not (target:hasStatusEffect(dsp.effect.TABULA_RASA)) then
target:addMod(dsp.mod.WHITE_MAGIC_COST, -10)
target:addMod(dsp.mod.WHITE_MAGIC_CAST, -10)
target:addMod(dsp.mod.WHITE_MAGIC_RECAST, -10)
target:addMod(dsp.mod.BLACK_MAGIC_COST, 20)
target:addMod(dsp.mod.BLACK_MAGIC_CAST, 20)
target:addMod(dsp.mod.BLACK_MAGIC_RECAST, 20)
target:addMod(dsp.mod.LIGHT_ARTS_REGEN, regen)
target:addMod(dsp.mod.REGEN_DURATION, regen*2)
end
target:recalculateSkillsTable()
end
function onEffectTick(target,effect)
end
function onEffectLose(target,effect)
target:recalculateAbilitiesTable()
local bonus = effect:getPower()
local regen = effect:getSubPower()
target:delMod(dsp.mod.WHITE_MAGIC_COST, -bonus)
target:delMod(dsp.mod.WHITE_MAGIC_CAST, -bonus)
target:delMod(dsp.mod.WHITE_MAGIC_RECAST, -bonus)
if not (target:hasStatusEffect(dsp.effect.TABULA_RASA)) then
target:delMod(dsp.mod.WHITE_MAGIC_COST, -10)
target:delMod(dsp.mod.WHITE_MAGIC_CAST, -10)
target:delMod(dsp.mod.WHITE_MAGIC_RECAST, -10)
target:delMod(dsp.mod.BLACK_MAGIC_COST, 20)
target:delMod(dsp.mod.BLACK_MAGIC_CAST, 20)
target:delMod(dsp.mod.BLACK_MAGIC_RECAST, 20)
target:delMod(dsp.mod.LIGHT_ARTS_REGEN, regen)
target:delMod(dsp.mod.REGEN_DURATION, regen*2)
end
target:recalculateSkillsTable()
end | 0 | 0.576484 | 1 | 0.576484 | game-dev | MEDIA | 0.972468 | game-dev | 0.5125 | 1 | 0.5125 |
pret/pokefirered | 3,204 | src/cereader_tool.c | #include "global.h"
#include "gflib.h"
#include "util.h"
#include "save.h"
#include "cereader_tool.h"
#define SEC30_SIZE (offsetof(struct EReaderTrainerTowerSet, floors[4]))
#define SEC31_SIZE (sizeof(struct EReaderTrainerTowerSet) - SEC30_SIZE)
// The trainer tower data exceeds SECTOR_DATA_SIZE. They're allowed to use the full save sector up to the counter field.
STATIC_ASSERT(SEC30_SIZE + SEC31_SIZE <= SECTOR_COUNTER_OFFSET * 2, EReaderTrainerTowerSetFreeSpace);
static u8 GetTrainerHillUnkVal(void)
{
return (gSaveBlock1Ptr->trainerTower[0].unk9 + 1) % 256;
}
static bool32 ValidateTrainerTowerTrainer(struct TrainerTowerFloor * floor)
{
if (floor->floorIdx < 1 || floor->floorIdx > MAX_TRAINER_TOWER_FLOORS)
return FALSE;
if (floor->challengeType > CHALLENGE_TYPE_KNOCKOUT)
return FALSE;
if (CalcByteArraySum((const u8 *)floor, offsetof(typeof(*floor), checksum)) != floor->checksum)
return FALSE;
return TRUE;
}
bool32 ValidateTrainerTowerData(struct EReaderTrainerTowerSet * ttdata)
{
u32 numFloors = ttdata->numFloors;
s32 i;
if (numFloors < 1 || numFloors > MAX_TRAINER_TOWER_FLOORS)
return FALSE;
for (i = 0; i < numFloors; i++)
{
if (!ValidateTrainerTowerTrainer(&ttdata->floors[i]))
return FALSE;
}
if (CalcByteArraySum((const u8 *)ttdata->floors, numFloors * sizeof(ttdata->floors[0])) != ttdata->checksum)
return FALSE;
return TRUE;
}
static bool32 CEReaderTool_SaveTrainerTower_r(struct EReaderTrainerTowerSet * ttdata, u8 * buffer)
{
AGB_ASSERT_EX(ttdata->dummy == 0, ABSPATH("cereader_tool.c"), 198);
AGB_ASSERT_EX(ttdata->id == 0, ABSPATH("cereader_tool.c"), 199)
memset(buffer, 0, SECTOR_SIZE);
memcpy(buffer, ttdata, SEC30_SIZE);
buffer[1] = GetTrainerHillUnkVal();
if (TryWriteSpecialSaveSector(SECTOR_ID_TRAINER_TOWER_1, buffer) != TRUE)
return FALSE;
memset(buffer, 0, SECTOR_SIZE);
memcpy(buffer, (u8 *)ttdata + SEC30_SIZE, SEC31_SIZE);
if (TryWriteSpecialSaveSector(SECTOR_ID_TRAINER_TOWER_2, buffer) != TRUE)
return FALSE;
return TRUE;
}
bool32 CEReaderTool_SaveTrainerTower(struct EReaderTrainerTowerSet * ttdata)
{
u8 * buffer = AllocZeroed(SECTOR_SIZE);
bool32 result = CEReaderTool_SaveTrainerTower_r(ttdata, buffer);
Free(buffer);
return result;
}
static bool32 CEReaderTool_LoadTrainerTower_r(struct EReaderTrainerTowerSet * ttdata, void *buffer)
{
if (TryReadSpecialSaveSector(SECTOR_ID_TRAINER_TOWER_1, buffer) != 1)
return FALSE;
memcpy(ttdata + 0x000, buffer, SEC30_SIZE);
if (TryReadSpecialSaveSector(SECTOR_ID_TRAINER_TOWER_2, buffer) != 1)
return FALSE;
memcpy((u8 *)ttdata + SEC30_SIZE, buffer, SEC31_SIZE);
if (!ValidateTrainerTowerData(ttdata))
return FALSE;
return TRUE;
}
bool32 CEReaderTool_LoadTrainerTower(struct EReaderTrainerTowerSet * ttdata)
{
void *buffer = AllocZeroed(SECTOR_SIZE);
bool32 success = CEReaderTool_LoadTrainerTower_r(ttdata, buffer);
Free(buffer);
return success;
}
bool32 ReadTrainerTowerAndValidate(void)
{
// Stubbed out. Populated in Emerald
return FALSE;
}
| 0 | 0.922744 | 1 | 0.922744 | game-dev | MEDIA | 0.548226 | game-dev | 0.812453 | 1 | 0.812453 |
JumpAttacker/EnsageSharp | 1,927 | ArcNew/Manager/IllusionManager.cs | using System.Collections.Generic;
using ArcAnnihilation.Units;
using ArcAnnihilation.Utils;
using Ensage;
using Ensage.Common;
using Ensage.SDK.Extensions;
namespace ArcAnnihilation.Manager
{
public class IllusionManager
{
private static IllusionManager _illusionManager;
public IllusionManager()
{
GetIllusions = new List<Illusion>();
ObjectManager.OnAddEntity += args =>
{
DelayAction.Add(150, () =>
{
var hero = args.Entity as Hero;
if (hero == null || !hero.IsIllusion || hero.Team != Core.MainHero.Hero.Team ||
!hero.IsControllable ||
hero.HasModifier("modifier_kill")) return;
Printer.Both("added illusion: " + hero.Name);
var ill = new Illusion(hero);
ill.Init();
GetIllusions.Add(ill);
});
};
Entity.OnInt32PropertyChange += (sender, args) =>
{
var hero = sender as Hero;
if (hero == null || !hero.IsIllusion) return;
if (args.PropertyName != "m_iHealth") return;
if (args.NewValue == 0)
{
var target = GetIllusions.Find(x => x.Hero.Equals(hero));
if (target != null)
{
target.Orbwalker.Unload();
GetIllusions.Remove(target);
Printer.Both("removed illusion: " + hero.Name);
}
}
};
}
public static List<Illusion> GetIllusions { get; private set; }
public static IllusionManager GetCreepManager()
{
return _illusionManager ?? (_illusionManager = new IllusionManager());
}
}
} | 0 | 0.883324 | 1 | 0.883324 | game-dev | MEDIA | 0.913286 | game-dev | 0.983211 | 1 | 0.983211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.