Compare commits

...

10 Commits

Author SHA1 Message Date
Anton Tarasenko 0c928a5a33 Change Futility classes to support new AcediaCore 1 year ago
Anton Tarasenko b4cde8c458 Change commands to adapt to new AcediaCore 1 year ago
Anton Tarasenko 6ca93f0ade Improve db-related commands 1 year ago
Anton Tarasenko 759d1d3840 Fix "db" command 2 years ago
Anton Tarasenko 739376fbc4 Fix `string`s not useding correct `Text` conversion methods 2 years ago
Anton Tarasenko fad8994111 Change "userdata" param from object to general JSON 2 years ago
Anton Tarasenko 65ece4757b Change "db" command to use JSON parameter 2 years ago
Anton Tarasenko 171a2a8d26 Change "spawn" command to auto-resolve entity aliases 2 years ago
Anton Tarasenko 076c9eae79 Change "feature" command to support new AcediaCore features 2 years ago
Anton Tarasenko e40883134f Squashed commit of the following: 2 years ago
  1. 55
      config/FutilityChat.ini
  2. 142
      config/FutilityNicknames.ini
  3. 225
      sources/Commands/ACommandDB.uc
  4. 35
      sources/Commands/ACommandDosh.uc
  5. 613
      sources/Commands/ACommandFeature.uc
  6. 430
      sources/Commands/ACommandFeature_Announcer.uc
  7. 30
      sources/Commands/ACommandGod.uc
  8. 66
      sources/Commands/ACommandInventory.uc
  9. 38
      sources/Commands/ACommandNick.uc
  10. 109
      sources/Commands/ACommandSpawn.uc
  11. 104
      sources/Commands/ACommandTrader.uc
  12. 142
      sources/Commands/ACommandUserData.uc
  13. 112
      sources/Features/FutileChat/FutilityChat.uc
  14. 114
      sources/Features/FutileChat/FutilityChat_Feature.uc
  15. 164
      sources/Features/FutileNickames/FutilityNicknames.uc
  16. 368
      sources/Features/FutileNickames/FutilityNicknames_Feature.uc
  17. 12
      sources/Futility.uc
  18. 6
      sources/Futility_Feature.uc
  19. 345
      sources/Tools/PendingConfigsTool.uc

55
config/FutilityChat.ini

@ -1,31 +1,34 @@
[default FutilityChat] [default FutilityChat]
; This feature allows to configure color of text chat messages.
autoEnable=true autoEnable=true
; How to color text chat messages? ;= How to color text chat messages?
; 1. `CCS_DoNothing` - do not change color in any way; ;=
; 2. `CCS_TeamColorForced` - force players' team colors for ;= 1. `CCS_DoNothing` - do not change color in any way;
; their messages; ;= 2. `CCS_TeamColorForced` - force players' team colors for
; 3. `CCS_ConfigColorForced` - force `configuredColor` value for ;= their messages;
; players' messages; ;= 3. `CCS_ConfigColorForced` - force `configuredColor` value for
; 4. `CCS_TeamColorCustom` - use players' team colors for ;= players' messages;
; their messages by default, but allow to change color with formatted ;= 4. `CCS_TeamColorCustom` - use players' team colors for
; tags (e.g. "Stop right there, {$crimson criminal} scum!"); ;= their messages by default, but allow to change color with formatted tags
; 5. `CCS_ConfigColorCustom` - use `configuredColor` value for ;= (e.g. "Stop right there, {$crimson criminal} scum!");
; messages by default, but allow to change color with formatted ;= 5. `CCS_ConfigColorCustom` - use `configuredColor` value for
; tags (e.g. "Stop right there, {$crimson criminal} scum!"); ;= messages by default, but allow to change color with formatted
; Default is `CCS_DoNothing`, corresponding to vanilla behaviour. ;= tags (e.g. "Stop right there, {$crimson criminal} scum!");
;=
;= Default is `CCS_DoNothing`, corresponding to vanilla behaviour.
colorSetting=CCS_DoNothing colorSetting=CCS_DoNothing
; Color that will be used if either of `CCS_ConfigColorForced` or ;= Color that will be used if either of `CCS_ConfigColorForced` or
; `CCS_ConfigColorCustom` options were used in `colorSetting`. ;= `CCS_ConfigColorCustom` options were used in `colorSetting`.
; Default value is white: (R=255,G=255,B=255,A=255), ;= Default value is white: (R=255,G=255,B=255,A=255), has no vanilla
; has no vanilla equivalent. ;= equivalent.
configuredColor=(R=255,G=255,B=255,A=255) configuredColor=(R=255,G=255,B=255,A=255)
; Allows to modify team color's value for the chat messages ;= Allows to modify team color's value for the chat messages
; (if either of `CCS_TeamColorForced` or `CCS_TeamColorCustom` options ;= (if either of `CCS_TeamColorForced` or `CCS_TeamColorCustom` options
; were used) to be lighter or darker. ;= were used) to be lighter or darker.
; This value is clamped between -1 and 1. ;= This value is clamped between -1 and 1:
; * `0` means using the same color; ;=
; * range (0; 1) - gives you lighter colors (`1` being white); ;= * `0` means using the same color;
; * range (-1; 0) - gives you darker colors (`-1` being black); ;= * range (0; 1) - gives you lighter colors (`1` being white);
; Default value is `0.6`, has no vanilla equivalent. ;= * range (-1; 0) - gives you darker colors (`-1` being black);
;=
;= Default value is `0.6`, has no vanilla equivalent.
teamColorModifier=0.6 teamColorModifier=0.6

142
config/FutilityNicknames.ini

@ -1,64 +1,67 @@
[default FutilityNicknames] [default FutilityNicknames]
; This feature allows to configure nickname limitations for the server. ;= This feature allows to configure nickname limitations for the server.
; It allows you to customize vanilla limitations for nickname length and ;= It allows you to customize vanilla limitations for nickname length and
; color with those of your own design. Enabling this feature overwrites ;= color with those of your own design. Enabling this feature overwrites
; default behaviour. ;= default behaviour.
autoEnable=true autoEnable=true
; How to treat whitespace characters inside players' nicknames. ;= How to treat whitespace characters inside players' nicknames.
; * `NSA_DoNothing` - does nothing, leaving whitespaces as they are; ;=
; * `NSA_Trim` - removes leading and trailing whitespaces for nicknames; ;= * `NSA_DoNothing` - does nothing, leaving whitespaces as they are;=
; * `NSA_Simplify` - removes leading and trailing whitespaces ;= * `NSA_Trim` - removes leading and trailing whitespaces for nicknames;=
; for nicknames, also reducing a sequence of whitespaces inside ;= * `NSA_Simplify` - removes leading and trailing whitespaces
; nickname to a single space, e.g. "my nick" becomes "my nick". ;= for nicknames, also reducing a sequence of whitespaces inside
; Default is `NSA_DoNothing`, same as on vanilla. ;= nickname to a single space, e.g. "my nick" becomes "my nick".
;=
;= Default is `NSA_DoNothing`, same as on vanilla.
spacesAction=NSA_DoNothing spacesAction=NSA_DoNothing
; How to treat colored nicknames. ;= How to treat colored nicknames.
; * `NCP_ForbidColor` - completely strips down any color from nicknames; ;= * `NCP_ForbidColor` - completely strips down any color from nicknames;=
; * `NCP_ForceTeamColor` - forces all nicknames to have player's current ;= * `NCP_ForceTeamColor` - forces all nicknames to have player's current
; team's color; ;= team's color;=
; * `NCP_ForceSingleColor` - allows nickname to be painted with a single ;= * `NCP_ForceSingleColor` - allows nickname to be painted with a single
; color (sets nickname's color to that of the first character); ;= color (sets nickname's color to that of the first character);=
; * `NCP_AllowAnyColor` - allows nickname to be colored in any way player ;= * `NCP_AllowAnyColor` - allows nickname to be colored in any way player
; wants. ;= wants.
; Default is `NCP_ForbidColor`, same as on vanilla. ;= Default is `NCP_ForbidColor`, same as on vanilla.
colorPermissions=NCP_ForbidColor colorPermissions=NCP_ForbidColor
; Set this to `true` if you wish to replace all whitespace characters with ;= Set this to `true` if you wish to replace all whitespace characters with
; underscores and `false` to leave them as is. ;= underscores and `false` to leave them as is.
; Default is `true`, same as on vanilla. However there is one difference: ;= Default is `true`, same as on vanilla. However there is one difference:
; Futility replaces all whitespace characters (including tabulations, ;= Futility replaces all whitespace characters (including tabulations,
; non-breaking spaces, etc.) instead of only ' '. ;= non-breaking spaces, etc.) instead of only ' '.
replaceSpacesWithUnderscores=true replaceSpacesWithUnderscores=true
; Set this to `true` to remove single 'quotation marks' and `false` to ;= Set this to `true` to remove single 'quotation marks' and `false` to
; leave them. Default is `false`, same as on vanilla. ;= leave them. Default is `false`, same as on vanilla.
removeSingleQuotationMarks=false removeSingleQuotationMarks=false
; Set this to `true` to remove dobule 'quotation marks' and `false` to ;= Set this to `true` to remove dobule 'quotation marks' and `false` to
; leave them. Default is `true`, same as on vanilla. ;= leave them. Default is `true`, same as on vanilla.
removeDoubleQuotationMarks=true removeDoubleQuotationMarks=true
; Max allowed nickname length. Negative values disable any length limits. ;= Max allowed nickname length. Negative values disable any length limits.
; ;=
; NOTE #1: `0` resets all nicknames to be empty and, ;= NOTE #1: `0` resets all nicknames to be empty and,
; if `correctEmptyNicknames` is set to `true`, they will be replaced with ;= if `correctEmptyNicknames` is set to `true`, they will be replaced with
; one of the fallback nicknames ;= one of the fallback nicknames
; (see `correctEmptyNicknames` and `fallbackNickname`). ;= (see `correctEmptyNicknames` and `fallbackNickname`).
; NOTE #2: Because of how color swapping in vanilla Killing Floor works, ;=
; every color swap makes text count as being about 4 characters longer. ;= NOTE #2: Because of how color swapping in vanilla Killing Floor works,
; So if one uses too many colors in the nickname, for drawing functions ;= every color swap makes text count as being about 4 characters longer.
; it will appear to be longer than it actually is and it *will* mess up ;= So if one uses too many colors in the nickname, for drawing functions
; UI. Unless you are using custom HUD it is recommended to keep this value ;= it will appear to be longer than it actually is and it *will* mess up
; at default `20` and forbid colored nicknames ;= UI. Unless you are using custom HUD it is recommended to keep this value
; (by setting `colorPermissions=NCP_ForbidColor`). Or to allow only one ;= at default `20` and forbid colored nicknames
; color (by setting `colorPermissions=NCP_ForceSingleColor` or ;= (by setting `colorPermissions=NCP_ForbidColor`). Or to allow only one
; `colorPermissions=NCP_ForceTeamColor`) and reducing `maxNicknameLength` ;= color (by setting `colorPermissions=NCP_ForceSingleColor` or
; to `16` (20 characters - 4 for color swap). ;= `colorPermissions=NCP_ForceTeamColor`) and reducing `maxNicknameLength`
; If you want to increase the limit above that, you can also do your ;= to `16` (20 characters - 4 for color swap).
; own research by testing nicknames of various length on ;= If you want to increase the limit above that, you can also do your
; screen resolutions you care about. ;= own research by testing nicknames of various length on
;= screen resolutions you care about.
maxNicknameLength=20 maxNicknameLength=20
; Should we replace empty player nicknames with a random fallback nickname ;= Should we replace empty player nicknames with a random fallback nickname
; (defined in `fallbackNickname` array)? ;= (defined in `fallbackNickname` array)?
correctEmptyNicknames=true correctEmptyNicknames=true
; Array of fallback nicknames that will be used to replace any empty nicknames ;= Array of fallback nicknames that will be used to replace any empty nicknames
; if `correctEmptyNicknames` is set to `true`. ;= if `correctEmptyNicknames` is set to `true`.
fallbackNickname="Fresh Meat" fallbackNickname="Fresh Meat"
fallbackNickname="Rotten Meat" fallbackNickname="Rotten Meat"
fallbackNickname="Troll Meat" fallbackNickname="Troll Meat"
@ -70,20 +73,21 @@ fallbackNickname="Boar Meat"
fallbackNickname="Walrus Meat" fallbackNickname="Walrus Meat"
fallbackNickname="Bug Meat" fallbackNickname="Bug Meat"
fallbackNickname="Horse Meat" fallbackNickname="Horse Meat"
; Guaranteed order of applying changes (only chosen ones) is as following: ;= Guaranteed order of applying changes (only chosen ones) is as following:
; 1. Trim/simplify spaces; ;= 1. Trim/simplify spaces;=
; 2. Remove single and double quotation marks; ;= 2. Remove single and double quotation marks;=
; 3. Enforce max limit of nickname's length; ;= 3. Enforce max limit of nickname's length;=
; 4. Replace empty nickname with fallback nickname (no further changes ;= 4. Replace empty nickname with fallback nickname (no further changes
; will be applied to fallback nickname in that case); ;= will be applied to fallback nickname in that case);=
; 5. Enforce color limitation; ;= 5. Enforce color limitation;=
; 6. Replace remaining whitespaces with underscores. ;= 6. Replace remaining whitespaces with underscores.
; ;=
; NOTE #1: as follows from the instruction described above, no changes will ;= NOTE #1: as follows from the instruction described above, no changes will
; ever be applied to fallback nicknames (unless player's nickname ;= ever be applied to fallback nicknames (unless player's nickname
; coincides with one by pure accident). ;= coincides with one by pure accident).
; NOTE #2: whitespaces inside steam nicknames are converted into underscores ;=
; before they are passed into the game and this is a change Futility ;= NOTE #2: whitespaces inside steam nicknames are converted into underscores
; cannot currently abort. ;= before they are passed into the game and this is a change Futility
; Therefore all changes relevant to whitespaces inside nicknames will only ;= cannot currently abort.
; be applied to in-game changes. ;= Therefore all changes relevant to whitespaces inside nicknames will only
;= be applied to in-game changes.

225
sources/Commands/ACommandDB.uc

@ -1,6 +1,6 @@
/** /**
* Command for working with databases. * Command for working with databases.
* Copyright 2021-2022 Anton Tarasenko * Copyright 2021-2023 Anton Tarasenko
*------------------------------------------------------------------------------ *------------------------------------------------------------------------------
* This file is part of Acedia. * This file is part of Acedia.
* *
@ -65,87 +65,63 @@ struct DBPointerPair
}; };
var protected const int TCREATE, TDELETE, TLIST, TREAD, TSIZE, TKEYS, TREMOVE; var protected const int TCREATE, TDELETE, TLIST, TREAD, TSIZE, TKEYS, TREMOVE;
var protected const int TWRITE, TWRITE_ARRAY, TWRITE_NULL, TWRITE_BOOLEAN; var protected const int TWRITE, TINCREMENT, TDATABASE_NAME, TDATABASE_LINK;
var protected const int TWRITE_INTEGER, TWRITE_FLOAT, TWRITE_STRING, TINCREMENT; var protected const int TJSON_VALUE, TQUERY_INVALID_POINTER, TQUERY_INVALID_DB;
var protected const int TDATABASE_NAME, TDATABASE_LINK, TJSON_VALUE;
var protected const int TOBJECT_KEYS_ARE, TOBJECT_SIZE_IS, TQUERY_COMPLETED; var protected const int TOBJECT_KEYS_ARE, TOBJECT_SIZE_IS, TQUERY_COMPLETED;
var protected const int TQUERY_INVALID_POINTER, TQUERY_INVALID_DB;
var protected const int TQUERY_INVALID_DATA, TAVAILABLE_DATABASES, TDA_DELETED; var protected const int TQUERY_INVALID_DATA, TAVAILABLE_DATABASES, TDA_DELETED;
var protected const int TDB_DOESNT_EXIST, TDB_ALREADY_EXISTS, TDB_CREATED; var protected const int TDB_DOESNT_EXIST, TDB_ALREADY_EXISTS, TDB_CREATED;
var protected const int TDB_CANNOT_BE_CREATED, TNO_DEFAULT_COMMAND, TBAD_DBLINK; var protected const int TDB_CANNOT_BE_CREATED, TNO_DEFAULT_COMMAND, TBAD_DBLINK;
protected function BuildData(CommandDataBuilder builder) protected function BuildData(CommandDataBuilder builder)
{ {
builder.Name(P("db")).Group(P("admin")) builder.Group(P("admin"));
.Summary(P("Read and edit data in your databases." builder.Summary(P("Read and edit data in your databases."
@ "Databases' values are addressed with links:" @ "Databases' values are addressed with links:"
@ "\"<db_name>:<json_path>\"")); @ "\"<db_name>:<json_path>\""));
builder.SubCommand(T(TCREATE)) builder.SubCommand(T(TCREATE));
.ParamText(T(TDATABASE_NAME)) builder.ParamText(T(TDATABASE_NAME));
.Describe(P("Creates new database with a specified name.")); builder.Describe(P("Creates new database with a specified name."));
builder.SubCommand(T(TDELETE)) builder.SubCommand(T(TDELETE));
.ParamText(T(TDATABASE_NAME)) builder.ParamText(T(TDATABASE_NAME));
.Describe(P("Completely deletes specified database.")); builder.Describe(P("Completely deletes specified database."));
builder.SubCommand(T(TLIST)) builder.SubCommand(T(TLIST));
.Describe(P("Lists available databases.")); builder.Describe(P("Lists available databases."));
builder.SubCommand(T(TREAD)) builder.SubCommand(T(TREAD));
.ParamText(T(TDATABASE_LINK)) builder.ParamText(T(TDATABASE_LINK));
.Describe(P("Reads data from location given by the `databaseLink`.")); builder.Describe(P("Reads data from location given by the `databaseLink`."));
builder.SubCommand(T(TSIZE)) builder.SubCommand(T(TSIZE));
.ParamText(T(TDATABASE_LINK)) builder.ParamText(T(TDATABASE_LINK));
.Describe(P("Gets amount of elements inside JSON array or object at" builder.Describe(P("Gets amount of elements inside JSON array or object at"
@ "location given by the `databaseLink`.")); @ "location given by the `databaseLink`."));
builder.SubCommand(T(TKEYS)) builder.SubCommand(T(TKEYS));
.ParamText(T(TDATABASE_LINK)) builder.ParamText(T(TDATABASE_LINK));
.Describe(P("Lists keys of JSON object at location given by" builder.Describe(P("Lists keys of JSON object at location given by"
@ "the `databaseLink`.")); @ "the `databaseLink`."));
builder.SubCommand(T(TREMOVE)) builder.SubCommand(T(TREMOVE));
.ParamText(T(TDATABASE_LINK)) builder.ParamText(T(TDATABASE_LINK));
.Describe(P("Removes data from location given by the `databaseLink`.")); builder.Describe(P("Removes data from location given by the `databaseLink`."));
builder.SubCommand(T(TWRITE)) builder.SubCommand(T(TWRITE));
.ParamText(T(TDATABASE_LINK)) builder.ParamText(T(TDATABASE_LINK));
.ParamObject(T(TJSON_VALUE)) builder.ParamJSON(T(TJSON_VALUE));
.Describe(P("Writes specified JSON object into location given by" builder.Describe(P("Writes specified JSON value into location given by"
@ "the `databaseLink`.")); @ "the `databaseLink`."));
builder.SubCommand(T(TWRITE_ARRAY)) builder.Option(T(TINCREMENT));
.ParamText(T(TDATABASE_LINK)) builder.Describe(F("Specifying this option for any of the"
.ParamArray(T(TJSON_VALUE))
.Describe(P("Writes specified JSON array into location given by"
@ "the `databaseLink`."));
builder.SubCommand(T(TWRITE_NULL))
.ParamText(T(TDATABASE_LINK))
.Describe(P("Writes specified null value into location given by"
@ "the `databaseLink`."));
builder.SubCommand(T(TWRITE_BOOLEAN))
.ParamText(T(TDATABASE_LINK))
.ParamBoolean(T(TJSON_VALUE))
.Describe(P("Writes specified JSON boolean into location given by"
@ "the `databaseLink`."));
builder.SubCommand(T(TWRITE_INTEGER))
.ParamText(T(TDATABASE_LINK))
.ParamInteger(T(TJSON_VALUE))
.Describe(P("Writes specified integer as JSON number into location"
@ "given by the `databaseLink`."));
builder.SubCommand(T(TWRITE_FLOAT))
.ParamText(T(TDATABASE_LINK))
.ParamNumber(T(TJSON_VALUE))
.Describe(P("Writes specified float as JSON number into location"
@ "given by the `databaseLink`."));
builder.SubCommand(T(TWRITE_STRING))
.ParamText(T(TDATABASE_LINK))
.ParamText(T(TJSON_VALUE))
.Describe(P("Writes specified JSON string into location given by"
@ "the `databaseLink`."));
builder.Option(T(TINCREMENT))
.Describe(F("Specifying this option for any of the"
@ "{$TextEmphasis 'write'} subcommands will cause them to append" @ "{$TextEmphasis 'write'} subcommands will cause them to append"
@ "data to the old one, instead of rewriting it.")); @ "data to the old one, instead of rewriting it."));
} }
protected function PushPlayer(EPlayer nextPlayer, Database callDatabase) protected function PushPlayer(EPlayer nextPlayer, Database callDatabase)
{ {
queueWaitingListPlayers[queueWaitingListPlayers.length] = local EPlayer playerCopy;
EPlayer(nextPlayer.Copy());
if (nextPlayer != none) {
playerCopy = EPlayer(nextPlayer.Copy());
}
if (callDatabase != none) {
callDatabase.NewRef();
}
queueWaitingListPlayers[queueWaitingListPlayers.length] = playerCopy;
queueWaitingListDatabases[queueWaitingListDatabases.length] = callDatabase; queueWaitingListDatabases[queueWaitingListDatabases.length] = callDatabase;
} }
@ -159,9 +135,10 @@ protected function EPlayer PopPlayer(Database relevantDatabase)
while (i < queueWaitingListDatabases.length) while (i < queueWaitingListDatabases.length)
{ {
if (queueWaitingListDatabases[i] != relevantDatabase) if (queueWaitingListDatabases[i].IsEqual(relevantDatabase))
{ {
result = queueWaitingListPlayers[i]; result = queueWaitingListPlayers[i];
queueWaitingListDatabases[i].FreeSelf();
queueWaitingListPlayers.Remove(i, 1); queueWaitingListPlayers.Remove(i, 1);
queueWaitingListDatabases.Remove(i, 1); queueWaitingListDatabases.Remove(i, 1);
break; break;
@ -175,8 +152,11 @@ protected function EPlayer PopPlayer(Database relevantDatabase)
return none; return none;
} }
protected function Executed(CallData arguments, EPlayer instigator) protected function Executed(
{ CallData arguments,
EPlayer instigator,
CommandPermissions permissions
) {
local AcediaObject valueToWrite; local AcediaObject valueToWrite;
local DBPointerPair pair; local DBPointerPair pair;
local Text subCommand; local Text subCommand;
@ -196,7 +176,7 @@ protected function Executed(CallData arguments, EPlayer instigator)
} }
// Remember the last player we are making a query to and make that query // Remember the last player we are making a query to and make that query
PushPlayer(instigator, pair.database); PushPlayer(instigator, pair.database);
if (subCommand.StartsWith(T(TWRITE))) if (subCommand.Compare(T(TWRITE)))
{ {
valueToWrite = arguments.parameters.GetItem(T(TJSON_VALUE)); valueToWrite = arguments.parameters.GetItem(T(TJSON_VALUE));
if (arguments.options.HasKey(T(TINCREMENT))) if (arguments.options.HasKey(T(TINCREMENT)))
@ -266,11 +246,11 @@ private function DBPointerPair TryLoadingDB(BaseText databaseLink)
if (databaseLink == none) { if (databaseLink == none) {
return result; return result;
} }
result.database = _.db.Load(databaseLink); result.database = _server.db.Load(databaseLink);
if (result.database == none) { if (result.database == none) {
return result; return result;
} }
result.pointer = _.db.GetPointer(databaseLink); result.pointer = _server.db.GetPointer(databaseLink);
return result; return result;
} }
@ -279,12 +259,12 @@ protected function CreateDatabase(EPlayer instigator, Text databaseName)
if (instigator == none) { if (instigator == none) {
return; return;
} }
if (_.db.ExistsLocal(databaseName)) if (_server.db.ExistsLocal(databaseName))
{ {
callerConsole.WriteLine(T(TDB_ALREADY_EXISTS)); callerConsole.WriteLine(T(TDB_ALREADY_EXISTS));
return; return;
} }
if (_.db.NewLocal(databaseName) != none) { if (_server.db.NewLocal(databaseName) != none) {
callerConsole.WriteLine(T(TDB_CREATED)); callerConsole.WriteLine(T(TDB_CREATED));
} }
else { else {
@ -297,7 +277,7 @@ protected function DeleteDatabase(EPlayer instigator, Text databaseName)
if (instigator == none) { if (instigator == none) {
return; return;
} }
if (_.db.DeleteLocal(databaseName)) { if (_server.db.DeleteLocal(databaseName)) {
callerConsole.WriteLine(T(TDA_DELETED)); callerConsole.WriteLine(T(TDA_DELETED));
} }
else { else {
@ -314,7 +294,7 @@ protected function ListDatabases(EPlayer instigator)
if (instigator == none) { if (instigator == none) {
return; return;
} }
availableDatabases = _.db.ListLocal(); availableDatabases = _server.db.ListLocal();
console = callerConsole; console = callerConsole;
console.Write(T(TAVAILABLE_DATABASES)); console.Write(T(TAVAILABLE_DATABASES));
for (i = 0; i < availableDatabases.length; i += 1) for (i = 0; i < availableDatabases.length; i += 1)
@ -352,7 +332,8 @@ protected function OutputStatus(
protected function DisplayData( protected function DisplayData(
Database.DBQueryResult result, Database.DBQueryResult result,
AcediaObject data, AcediaObject data,
Database source) Database source,
int requestID)
{ {
local Text printedJSON; local Text printedJSON;
local EPlayer instigator; local EPlayer instigator;
@ -373,7 +354,8 @@ protected function DisplayData(
protected function DisplaySize( protected function DisplaySize(
Database.DBQueryResult result, Database.DBQueryResult result,
int size, int size,
Database source) Database source,
int requestID)
{ {
local Text sizeAsText; local Text sizeAsText;
local EPlayer instigator; local EPlayer instigator;
@ -396,7 +378,8 @@ protected function DisplaySize(
protected function DisplayKeys( protected function DisplayKeys(
Database.DBQueryResult result, Database.DBQueryResult result,
ArrayList keys, ArrayList keys,
Database source) Database source,
int requestID)
{ {
local int i; local int i;
local Text nextKey; local Text nextKey;
@ -430,7 +413,8 @@ protected function DisplayKeys(
protected function DisplayResponse( protected function DisplayResponse(
Database.DBQueryResult result, Database.DBQueryResult result,
Database source) Database source,
int requestID)
{ {
local EPlayer instigator; local EPlayer instigator;
@ -441,6 +425,7 @@ protected function DisplayResponse(
defaultproperties defaultproperties
{ {
preferredName = "db"
TCREATE = 0 TCREATE = 0
stringConstants(0) = "create" stringConstants(0) = "create"
TDELETE = 1 TDELETE = 1
@ -457,52 +442,40 @@ defaultproperties
stringConstants(6) = "remove" stringConstants(6) = "remove"
TWRITE = 7 TWRITE = 7
stringConstants(7) = "write" stringConstants(7) = "write"
TWRITE_ARRAY = 8 TINCREMENT = 8
stringConstants(8) = "write_array" stringConstants(8) = "increment"
TWRITE_NULL = 9 TDATABASE_NAME = 9
stringConstants(9) = "write_null" stringConstants(9) = "databaseName"
TWRITE_BOOLEAN = 10 TDATABASE_LINK = 10
stringConstants(10) = "write_boolean" stringConstants(10) = "databaseLink"
TWRITE_INTEGER = 11 TJSON_VALUE = 11
stringConstants(11) = "write_integer" stringConstants(11) = "jsonValue"
TWRITE_FLOAT = 12 TOBJECT_KEYS_ARE = 12
stringConstants(12) = "write_float" stringConstants(12) = "{$TextEmphasis Object keys are:} "
TWRITE_STRING = 13 TOBJECT_SIZE_IS = 13
stringConstants(13) = "write_string" stringConstants(13) = "{$TextEmphasis Object size is:} "
TINCREMENT = 14 TQUERY_COMPLETED = 14
stringConstants(14) = "increment" stringConstants(14) = "{$TextPositive Database query was completed!}"
TDATABASE_NAME = 15 TQUERY_INVALID_POINTER = 15
stringConstants(15) = "databaseName" stringConstants(15) = "{$TextFailure Query was provided with an invalid JSON pointer.}"
TDATABASE_LINK = 16 TQUERY_INVALID_DB = 16
stringConstants(16) = "databaseLink" stringConstants(16) = "{$TextFailure Operation could not finish because database is damaged and unusable.}"
TJSON_VALUE = 17 TQUERY_INVALID_DATA = 17
stringConstants(17) = "jsonValue" stringConstants(17) = "{$TextFailure Query data is invalid.}"
TOBJECT_KEYS_ARE = 18 TAVAILABLE_DATABASES = 18
stringConstants(18) = "{$TextEmphasis Object keys are:} " stringConstants(18) = "{$TextEmphasis Available databases:} "
TOBJECT_SIZE_IS = 19 TDA_DELETED = 19
stringConstants(19) = "{$TextEmphasis Object size is:} " stringConstants(19) = "{$TextPositive Database was deleted.}"
TQUERY_COMPLETED = 20 TDB_DOESNT_EXIST = 20
stringConstants(20) = "{$TextPositive Database query was completed!}" stringConstants(20) = "{$TextFailure Database with specified name does not exist.}"
TQUERY_INVALID_POINTER = 21 TDB_ALREADY_EXISTS = 21
stringConstants(21) = "{$TextNegative Query was provided with an invalid JSON pointer.}" stringConstants(21) = "{$TextFailure Database with specified name already exists.}"
TQUERY_INVALID_DB = 22 TDB_CREATED = 22
stringConstants(22) = "{$TextNegative Operation could not finish because database is damaged and unusable.}" stringConstants(22) = "{$TextPositive Database was created.}"
TQUERY_INVALID_DATA = 23 TDB_CANNOT_BE_CREATED = 23
stringConstants(23) = "{$TextNegative Query data is invalid.}" stringConstants(23) = "{$TextFailure Database cannot be created.}"
TAVAILABLE_DATABASES = 24 TNO_DEFAULT_COMMAND = 24
stringConstants(24) = "{$TextEmphasis Available databases:} " stringConstants(24) = "{$TextFailure Default command does nothing. Use on of the sub-commands.}"
TDA_DELETED = 25 TBAD_DBLINK = 25
stringConstants(25) = "{$TextPositive Database was deleted.}" stringConstants(25) = "{$TextFailure Database could not be read for the specified link.}"
TDB_DOESNT_EXIST = 26
stringConstants(26) = "{$TextNegative Database with specified name does not exist.}"
TDB_ALREADY_EXISTS = 27
stringConstants(27) = "{$TextNegative Database with specified name already exists.}"
TDB_CREATED = 28
stringConstants(28) = "{$TextPositive Database was created.}"
TDB_CANNOT_BE_CREATED = 29
stringConstants(29) = "{$TextNegative Database cannot be created.}"
TNO_DEFAULT_COMMAND = 30
stringConstants(30) = "{$TextNegative Default command does nothing. Use on of the sub-commands.}"
TBAD_DBLINK = 31
stringConstants(31) = "{$TextNegative Database could not be read for the specified link.}"
} }

35
sources/Commands/ACommandDosh.uc

@ -29,23 +29,23 @@ protected function Finalizer()
protected function BuildData(CommandDataBuilder builder) protected function BuildData(CommandDataBuilder builder)
{ {
builder.Name(P("dosh")).Group(P("gameplay")) builder.Group(P("gameplay"));
.Summary(P("Changes amount of money.")); builder.Summary(P("Changes amount of money."));
builder.RequireTarget(); builder.RequireTarget();
builder.ParamInteger(P("amount")) builder.ParamInteger(P("amount"));
.Describe(P("Gives (or takes if negative) players a specified <amount>" builder.Describe(P("Gives (or takes if negative) players a specified <amount>"
@ "of money.")); @ "of money."));
builder.SubCommand(P("set")) builder.SubCommand(P("set"));
.ParamInteger(P("amount")) builder.ParamInteger(P("amount"));
.Describe(P("Sets player's money to a specified <amount>.")); builder.Describe(P("Sets player's money to a specified <amount>."));
builder.Option(P("min")) builder.Option(P("min"));
.ParamInteger(P("minValue")) builder.ParamInteger(P("minValue"));
.Describe(F("Players will retain at least this amount of dosh after" builder.Describe(F("Players will retain at least this amount of dosh after"
@ "the command's execution. In case of conflict, overrides" @ "the command's execution. In case of conflict, overrides"
@ "'{$TextEmphasis --max}' option. `0` is assumed by default.")); @ "'{$TextEmphasis --max}' option. `0` is assumed by default."));
builder.Option(P("max"), P("M")) builder.Option(P("max"), P("M"));
.ParamInteger(P("maxValue")) builder.ParamInteger(P("maxValue"));
.Describe(F("Players will have at most this amount of dosh after" builder.Describe(F("Players will have at most this amount of dosh after"
@ "the command's execution. In case of conflict, it is overridden" @ "the command's execution. In case of conflict, it is overridden"
@ "by '{$TextEmphasis --min}' option.")); @ "by '{$TextEmphasis --min}' option."));
announcer = ACommandDosh_Announcer( announcer = ACommandDosh_Announcer(
@ -55,8 +55,9 @@ protected function BuildData(CommandDataBuilder builder)
protected function ExecutedFor( protected function ExecutedFor(
EPlayer target, EPlayer target,
CallData arguments, CallData arguments,
EPlayer instigator) EPlayer instigator,
{ CommandPermissions permissions
) {
local int oldAmount, newAmount; local int oldAmount, newAmount;
local int amount, minValue, maxValue; local int amount, minValue, maxValue;
@ -88,6 +89,6 @@ protected function ExecutedFor(
} }
} }
defaultproperties defaultproperties {
{ preferredName = "dosh"
} }

613
sources/Commands/ACommandFeature.uc

@ -17,230 +17,563 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Acedia. If not, see <https://www.gnu.org/licenses/>. * along with Acedia. If not, see <https://www.gnu.org/licenses/>.
*/ */
class ACommandFeature extends Command; class ACommandFeature extends Command
dependson(PendingConfigsTool);
// TODO: autoconf, newconf, deleteconf, setconf var private class<Feature> selectedFeatureClass;
// TODO: when displaying features - display which one is enabled var private Text selectedFeatureName;
var private Text selectedConfigName;
var private PendingConfigsTool pendingConfigs;
var private ACommandFeature_Announcer announcer; var private ACommandFeature_Announcer announcer;
protected function Finalizer() protected function Constructor() {
{ pendingConfigs = PendingConfigsTool(_.memory.Allocate(class'PendingConfigsTool'));
super.Constructor();
}
protected function Finalizer() {
_.memory.Free(announcer); _.memory.Free(announcer);
_.memory.Free(pendingConfigs);
super.Finalizer(); super.Finalizer();
} }
protected function BuildData(CommandDataBuilder builder) protected function BuildData(CommandDataBuilder builder) {
{ builder.Group(P("admin"));
builder.Name(P("feature")).Group(P("admin")) builder.Summary(P("Managing features."));
.Summary(P("Managing features.")) builder.Describe(P("Command for managing features and their configs."));
.Describe(P("Command for displaying and enabling/disabling features.")); builder.SubCommand(P("enable"));
builder.SubCommand(P("enable")) builder.ParamText(P("feature"),, P("feature"));
.ParamText(P("feature")) builder.OptionalParams();
.OptionalParams() builder.ParamText(P("config"));
.ParamText(P("config")) builder.Describe(P("Enables specified <feature>. If <config> isn't specified -"
.Describe(P("Enables specified <feature>.")); @ "choses the \"default\" one, making new config with default"
builder.SubCommand(P("disable")) @ "settings if it doesn't exist."));
.ParamText(P("feature")) builder.SubCommand(P("disable"));
.Describe(P("Disables specified <feature>.")); builder.ParamText(P("feature"),, P("feature"));
builder.Describe(P("Disables specified <feature>."));
builder.SubCommand(P("showconf"));
builder.ParamText(P("feature"),, P("feature"));
builder.OptionalParams();
builder.ParamText(P("config"));
builder.Describe(P("Show given <config> for the given <feature>."));
builder.SubCommand(P("editconf"));
builder.ParamText(P("feature"),, P("feature"));
builder.ParamText(P("config"));
builder.ParamText(P("variable_path"));
builder.ParamJSON(P("value"));
builder.Describe(P("Changes a value inside given <config> of the given"
@ "<feature> by setting value at JSON path <variable_path> to"
@ "the JSON value <value>. Changes won't be immediately applied to"
@ "the game and kept as pending."));
builder.SubCommand(P("saveconf"));
builder.ParamText(P("feature"),, P("feature"));
builder.ParamText(P("config"));
builder.Describe(P("Saves pending changes for the given <config> of the given"
@ "<feature>."));
builder.SubCommand(P("newconf"));
builder.ParamText(P("feature"),, P("feature"));
builder.ParamText(P("config"));
builder.Describe(P("Creates new config for the given <feature>."));
builder.SubCommand(P("removeconf"));
builder.ParamText(P("feature"),, P("feature"));
builder.ParamText(P("config"));
builder.Describe(P("Removes specified <config> of the specified <feature>."));
builder.SubCommand(P("autoconf"));
builder.ParamText(P("feature"),, P("feature"));
builder.OptionalParams();
builder.ParamText(P("config"));
builder.Describe(P("Changes current auto config config of the specified"
@ "<feature>. Auto config is a config that is supposed to be"
@ "automatically enabled at the start of the Acedia, unless"
@ "otherwise specified for the loader."));
builder.Option(P("all"));
builder.Describe(F("Affects subcommand {$TextEmphasis showconf} by making it"
@ "show all available configs."));
builder.Option(P("save"));
builder.Describe(F("Affects subcommand {$TextEmphasis editconf} by making it"
@ "also save all pending changes."));
announcer = ACommandFeature_Announcer( announcer = ACommandFeature_Announcer(
_.memory.Allocate(class'ACommandFeature_Announcer')); _.memory.Allocate(class'ACommandFeature_Announcer'));
} }
protected function Executed(CallData arguments, EPlayer instigator) protected function Executed(
{ CallData arguments,
EPlayer instigator,
CommandPermissions permissions
) {
local bool saveFlag, allFlag;
announcer.Setup(none, instigator, othersConsole); announcer.Setup(none, instigator, othersConsole);
saveFlag = arguments.options.HasKey(P("save"));
allFlag = arguments.options.HasKey(P("all"));
SelectFeatureAndConfig(arguments);
if (arguments.subCommandName.IsEmpty()) { if (arguments.subCommandName.IsEmpty()) {
ShowAllFeatures(); ShowAllFeatures();
} else if (arguments.subCommandName.Compare(P("enable"))) {
EnableFeature();
} else if (arguments.subCommandName.Compare(P("disable"))) {
DisableFeature();
} else if (arguments.subCommandName.Compare(P("showconf"))) {
ShowSelectedConfigs(allFlag);
} else if (arguments.subCommandName.Compare(P("editconf"))) {
EditFeatureConfig(
arguments.parameters.GetText(P("variable_path")),
arguments.parameters.GetItem(P("value")),
saveFlag);
} else if (arguments.subCommandName.Compare(P("saveconf"))) {
SaveFeatureConfig();
} else if (arguments.subCommandName.Compare(P("newconf"))) {
NewFeatureConfig();
} else if (arguments.subCommandName.Compare(P("removeconf"))) {
RemoveFeatureConfig();
} else if (arguments.subCommandName.Compare(P("autoconf"))) {
SetAutoFeatureConfig();
} }
else if (arguments.subCommandName.Compare(P("enable"))) _.memory.Free2(selectedConfigName, selectedFeatureName);
{ selectedConfigName = none;
EnableFeature( selectedFeatureName = none;
arguments.parameters.GetText(P("feature")),
arguments.parameters.GetText(P("config")));
}
else if (arguments.subCommandName.Compare(P("disable"))) {
DisableFeature(arguments.parameters.GetText(P("feature")));
}
} }
protected function EnableFeature(BaseText featureName, BaseText configParameter) protected function SelectFeatureAndConfig(CallData arguments) {
{ local Text featureClassName, userGivenConfigName;
local bool wasEnabled;
local Text oldConfig, newConfig;
local Feature instance;
local class<Feature> featureClass;
featureClass = LoadFeatureClass(featureName); selectedFeatureName = arguments.parameters.GetTextBy(P("/feature/alias"));
if (featureClass == none) { featureClassName = arguments.parameters.GetTextBy(P("/feature/value"));
selectedFeatureClass = LoadFeatureClass(featureClassName);
if (selectedFeatureClass == none && !arguments.subCommandName.IsEmpty()) {
_.memory.Free(selectedFeatureName);
selectedFeatureName = none;
return; return;
} }
wasEnabled = featureClass.static.IsEnabled(); _.memory.Free(featureClassName);
oldConfig = featureClass.static.GetCurrentConfig(); userGivenConfigName = arguments.parameters.GetText(P("config"));
newConfig = GetConfigFromParameter(configParameter, featureClass); if (userGivenConfigName != none) {
selectedConfigName = userGivenConfigName.LowerCopy();
userGivenConfigName.FreeSelf();
}
pendingConfigs.SelectConfig(selectedFeatureClass, selectedConfigName);
}
protected function EnableFeature() {
local bool wasEnabled;
local Text oldConfig, newConfig;
local Feature instance;
wasEnabled = selectedFeatureClass.static.IsEnabled();
oldConfig = selectedFeatureClass.static.GetCurrentConfig();
newConfig = PickConfigBasedOnParameter();
// Already enabled with the same config! // Already enabled with the same config!
if (oldConfig != none && oldConfig.Compare(newConfig, SCASE_INSENSITIVE)) if (oldConfig != none && oldConfig.Compare(newConfig, SCASE_INSENSITIVE)) {
{ announcer.AnnounceFailedAlreadyEnabled(selectedFeatureName, newConfig);
announcer.AnnounceFailedAlreadyEnabled(featureClass, newConfig);
_.memory.Free(newConfig); _.memory.Free(newConfig);
_.memory.Free(oldConfig); _.memory.Free(oldConfig);
return; return;
} }
// Try enabling and report the result // Try enabling and report the result
instance = featureClass.static.EnableMe(newConfig); instance = selectedFeatureClass.static.EnableMe(newConfig);
if (instance == none) { if (instance == none) {
announcer.AnnounceFailedCannotEnableFeature(featureClass, newConfig); announcer.AnnounceFailedCannotEnableFeature(
} selectedFeatureName,
else if (wasEnabled) { newConfig);
announcer.AnnounceSwappedConfig(featureClass, oldConfig, newConfig); } else if (wasEnabled) {
} announcer.AnnounceSwappedConfig(
else { selectedFeatureName,
announcer.AnnounceEnabledFeature(featureClass, newConfig); oldConfig,
newConfig);
} else {
announcer.AnnounceEnabledFeature(selectedFeatureName, newConfig);
} }
_.memory.Free(newConfig); _.memory.Free(newConfig);
_.memory.Free(oldConfig); _.memory.Free(oldConfig);
} }
protected function DisableFeature(Text featureName) protected function DisableFeature() {
{ if (!selectedFeatureClass.static.IsEnabled()) {
local class<Feature> featureClass; announcer.AnnounceFailedAlreadyDisabled(selectedFeatureName);
featureClass = LoadFeatureClass(featureName);
if (featureClass == none) {
return;
}
if (!featureClass.static.IsEnabled())
{
announcer.AnnounceFailedAlreadyDisabled(featureClass);
return; return;
} }
featureClass.static.DisableMe(); selectedFeatureClass.static.DisableMe();
// It is possible that this command itself is destroyed after above command // It is possible that this command itself is destroyed after above command
// so do the check just in case // so do the check just in case
if (IsAllocated()) { if (IsAllocated()) {
announcer.AnnounceDisabledFeature(featureClass); announcer.AnnounceDisabledFeature(selectedFeatureName);
} }
} }
protected function Text GetConfigFromParameter( protected function ShowSelectedConfigs(bool showAllFeatures) {
BaseText configParameter, local int i;
class<Feature> featureClass) local array<Text> availableConfigs;
{ local MutableText configList;
local Text resolvedConfig; local class<FeatureConfig> configClass;
local class<FeatureConfig> configClass;
if (featureClass == none) { if (showAllFeatures) {
return none; configClass = selectedFeatureClass.default.configClass;
if (configClass != none) {
availableConfigs = configClass.static.AvailableConfigs();
}
for (i = 0; i < availableConfigs.length; i += 1) {
ShowFeatureConfig(availableConfigs[i]);
}
_.memory.FreeMany(availableConfigs);
return;
} }
configClass = featureClass.default.configClass; if (selectedConfigName != none) {
if (configClass == none) ShowFeatureConfig(selectedConfigName);
{ return;
announcer.AnnounceFailedNoConfigClass(featureClass); }
configList = PrintConfigList(selectedFeatureClass);
callerConsole
.Flush()
.Write(P("Available configs: "))
.WriteLine(configList);
_.memory.Free(configList);
}
protected function ShowFeatureConfig(BaseText configName) {
local MutableText dataAsJSON;
local HashTable currentData, pendingData;
if (configName == none) {
return;
}
currentData = GetCurrentConfigData(configName);
if (currentData == none) {
announcer.AnnounceFailedNoDataForConfig(
selectedFeatureName,
configName);
return;
}
// Display current data
dataAsJSON = _.json.PrettyPrint(currentData);
announcer.AnnounceCurrentConfig(selectedFeatureName, configName);
callerConsole.Flush().WriteLine(dataAsJSON);
_.memory.Free(dataAsJSON);
// Display pending data
pendingConfigs.SelectConfig(selectedFeatureClass, configName);
pendingData = pendingConfigs.GetPendingConfigData();
if (pendingData != none) {
dataAsJSON = _.json.PrettyPrint(pendingData);
announcer.AnnouncePendingConfig(
selectedFeatureName,
configName);
callerConsole.Flush().WriteLine(dataAsJSON);
_.memory.Free(dataAsJSON);
}
_.memory.Free(pendingData);
_.memory.Free(currentData);
}
protected function Text PickConfigBasedOnParameter() {
local Text resolvedConfig;
local class<FeatureConfig> configClass;
configClass = selectedFeatureClass.default.configClass;
if (configClass == none) {
announcer.AnnounceFailedNoConfigClass(selectedFeatureName);
return none; return none;
} }
// If config was specified - simply check that it exists // If config was specified - simply check that it exists
if (configParameter != none) if (selectedConfigName != none) {
{ if (configClass.static.Exists(selectedConfigName)) {
if (configClass.static.Exists(configParameter)) { return selectedConfigName.Copy();
return configParameter.Copy();
} }
announcer.AnnounceFailedConfigMissing(configParameter); announcer.AnnounceFailedConfigMissing(selectedConfigName);
return none; return none;
} }
// If it wasn't specified - try auto config instead // If it wasn't specified - try auto config instead
resolvedConfig = configClass.static.GetAutoEnabledConfig(); resolvedConfig = configClass.static.GetAutoEnabledConfig();
if (resolvedConfig == none) { if (resolvedConfig == none) {
announcer.AnnounceFailedNoConfigProvided(featureClass); announcer.AnnounceFailedNoConfigProvided(selectedFeatureName);
} }
return resolvedConfig; return resolvedConfig;
} }
protected function class<Feature> LoadFeatureClass(BaseText featureName) protected function class<Feature> LoadFeatureClass(BaseText featureClassName) {
{ local class<Feature> featureClass;
local Text featureClassName;
local class<Feature> featureClass; if (featureClassName == none) {
if (featureName == none) {
return none; return none;
} }
if (featureName.StartsWith(P("$"))) {
featureClassName = _.alias.ResolveFeature(featureName, true);
}
else {
featureClassName = featureName.Copy();
}
featureClass = class<Feature>(_.memory.LoadClass(featureClassName)); featureClass = class<Feature>(_.memory.LoadClass(featureClassName));
if (featureClass == none) { if (featureClass == none) {
announcer.AnnounceFailedToLoadFeatureClass(featureName); announcer.AnnounceFailedToLoadFeatureClass(featureClassName);
} }
_.memory.Free(featureClassName);
return featureClass; return featureClass;
} }
protected function ShowAllFeatures() protected function ShowAllFeatures() {
{ local int i;
local int i; local array< class<Feature> > availableFeatures;
local array< class<Feature> > availableFeatures;
availableFeatures = _.environment.GetAvailableFeatures(); availableFeatures = _.environment.GetAvailableFeatures();
for (i = 0; i < availableFeatures.length; i ++) { for (i = 0; i < availableFeatures.length; i ++) {
ShowFeature(availableFeatures[i]); ShowFeature(availableFeatures[i]);
} }
} }
protected function ShowFeature(class<Feature> feature) protected function ShowFeature(class<Feature> featureClass)
{ {
local int i; local MutableText featureName;
local Text autoConfig; local MutableText configList;
local MutableText featureName, builder;
local ListBuilder configList;
local array<Text> availableConfigs;
local class<FeatureConfig> configClass;
if (feature == none) { if (featureClass == none) {
return; return;
} }
configClass = feature.default.configClass;
if (configClass != none) {
availableConfigs = configClass.static.AvailableConfigs();
}
featureName = _.text featureName = _.text
.FromClassM(feature) .FromClassM(featureClass)
.ChangeDefaultColor(_.color.TextEmphasis); .ChangeDefaultColor(_.color.TextEmphasis);
builder = _.text.Empty(); configList = PrintConfigList(featureClass);
if (feature.static.IsEnabled()) { callerConsole.Flush();
builder.Append(F("[ {$TextPositive enabled} ] ")); if (featureClass.static.IsEnabled()) {
callerConsole.Write(F("[ {$TextPositive enabled} ] "));
} }
else { else {
builder.Append(F("[ {$TextNegative disabled} ] ")); callerConsole.Write(F("[ {$TextNegative disabled} ] "));
} }
builder.Append(featureName); callerConsole.Write(featureName)
.Write(P(" with configs: "))
.WriteLine(configList);
_.memory.Free(featureName); _.memory.Free(featureName);
if (availableConfigs.length == 1) { _.memory.Free(configList);
builder.Append(P(" with config:")); }
}
else if (availableConfigs.length > 1) { protected function MutableText PrintConfigList(class<Feature> featureClass) {
builder.Append(P(" with configs:")); local int i;
} local Text autoConfig, enabledConfig;
callerConsole.Write(builder); local ListBuilder configList;
_.memory.Free(builder); local MutableText result, nextConfig;
configList = ListBuilder(_.memory.Allocate(class'ListBuilder')); local array<Text> availableConfigs;
local class<FeatureConfig> configClass;
if (featureClass == none) return none;
configClass = featureClass.default.configClass;
if (configClass == none) return none;
availableConfigs = configClass.static.AvailableConfigs();
enabledConfig = featureClass.static.GetCurrentConfig();
autoConfig = configClass.static.GetAutoEnabledConfig(); autoConfig = configClass.static.GetAutoEnabledConfig();
for (i = 0; i < availableConfigs.length; i += 1) configList = ListBuilder(_.memory.Allocate(class'ListBuilder'));
{ for (i = 0; i < availableConfigs.length; i += 1) {
configList.Item(availableConfigs[i]); nextConfig = availableConfigs[i].MutableCopy();
if ( autoConfig != none if (enabledConfig != none && enabledConfig.Compare(nextConfig, SCASE_INSENSITIVE)) {
&& autoConfig.Compare(availableConfigs[i], SCASE_INSENSITIVE)) nextConfig.ChangeDefaultColor(_.color.TextPositive);
{ }
configList.Comment(F("{$TextPositive auto enabled}")); if (pendingConfigs.HasPendingConfigFor(featureClass, nextConfig)) {
nextConfig.Append(F("{$TextEmphasis *}"));
}
configList.Item(nextConfig);
_.memory.Free(nextConfig);
if (autoConfig != none && autoConfig.Compare(availableConfigs[i], SCASE_INSENSITIVE)) {
if (autoConfig.Compare(enabledConfig, SCASE_INSENSITIVE)) {
configList.Comment(F("{$TextPositive auto enabled}"));
} else {
configList.Comment(F("{$TextNegative auto enabled}"));
}
} }
} }
builder = configList.GetMutable(); result = configList.GetMutable();
callerConsole.WriteLine(builder); _.memory.Free3(configList, autoConfig, enabledConfig);
_.memory.FreeMany(availableConfigs); _.memory.FreeMany(availableConfigs);
_.memory.Free(configList); return result;
_.memory.Free(autoConfig);
_.memory.Free(builder);
} }
defaultproperties protected function MutableText PrettyPrintValueAt(BaseText pathToValue) {
{ local MutableText printedValue;
local AcediaObject value;
local HashTable relevantData;
relevantData = pendingConfigs.GetPendingConfigData();
if (relevantData == none) {
relevantData = GetCurrentSelectedConfigData();
}
if (relevantData != none) {
value = relevantData.GetItemBy(pathToValue);
}
if (value != none) {
printedValue = _.json.PrettyPrint(value);
_.memory.Free(value);
}
_.memory.Free(relevantData);
return printedValue;
}
protected function EditFeatureConfig(BaseText pathToValue, AcediaObject newValue, bool saveConfig) {
local MutableText printedOldValue;
local MutableText printedNewValue;
local PendingConfigsTool.PendingConfigToolResult error;
if (selectedFeatureClass == none) {
return;
}
printedOldValue = PrettyPrintValueAt(pathToValue);
error = pendingConfigs.EditConfig(pathToValue, newValue);
if (error == PCTE_None) {
printedNewValue = PrettyPrintValueAt(pathToValue);
}
if (error == PCTE_ConfigMissing) {
announcer.AnnounceFailedConfigMissing(selectedConfigName);
}
else if (error == PCTE_ExpectedObject) {
announcer.AnnounceFailedExpectedObject();
} else if (error == PCTE_BadPointer) {
announcer.AnnounceFailedBadPointer(
selectedFeatureName,
selectedConfigName,
pathToValue);
} else if (printedOldValue == none) {
announcer.AnnounceConfigNewValue(
selectedFeatureName,
selectedConfigName,
pathToValue,
printedNewValue);
} else {
announcer.AnnounceConfigEdited(
selectedFeatureName,
selectedConfigName,
pathToValue,
printedOldValue,
printedNewValue);
}
if (saveConfig && error == PCTE_None) {
SaveFeatureConfig();
}
_.memory.Free(printedOldValue);
_.memory.Free(printedNewValue);
_.memory.Free(pathToValue);
_.memory.Free(newValue);
}
protected function SaveFeatureConfig() {
local BaseText enabledConfigName;
local HashTable pendingData;
local class<FeatureConfig> configClass;
configClass = selectedFeatureClass.default.configClass;
if (configClass == none) {
announcer.AnnounceFailedNoConfigClass(selectedFeatureName);
return;
}
pendingData = pendingConfigs.GetPendingConfigData();
if (pendingData == none) {
announcer.AnnounceFailedPendingConfigMissing(selectedConfigName);
return;
}
// Make sure config exists
configClass.static.NewConfig(selectedConfigName);
configClass.static.SaveData(selectedConfigName, pendingData);
// Re-apply config if it is active?
enabledConfigName = selectedFeatureClass.static.GetCurrentConfig();
if (selectedConfigName.Compare(enabledConfigName, SCASE_INSENSITIVE)) {
selectedFeatureClass.static.EnableMe(selectedConfigName);
announcer.AnnouncePublicPendingConfigSaved(selectedFeatureName);
} else {
announcer.AnnouncePrivatePendingConfigSaved(selectedFeatureName, selectedConfigName);
}
_.memory.Free(enabledConfigName);
pendingData.FreeSelf();
pendingConfigs.RemoveConfig();
return;
}
protected function NewFeatureConfig() {
local BaseText enabledConfigName;
local class<FeatureConfig> configClass;
configClass = selectedFeatureClass.default.configClass;
if (configClass == none) {
announcer.AnnounceFailedNoConfigClass(selectedFeatureName);
return;
}
if (configClass.static.Exists(selectedConfigName)) {
announcer.AnnounceFailedConfigAlreadyExists(selectedFeatureName, selectedConfigName);
return;
}
if (!configClass.static.NewConfig(selectedConfigName)) {
announcer.AnnounceFailedBadConfigName(selectedConfigName);
return;
}
enabledConfigName = selectedFeatureClass.static.GetCurrentConfig();
if (selectedConfigName.Compare(enabledConfigName, SCASE_INSENSITIVE)) {
selectedFeatureClass.static.EnableMe(selectedConfigName);
announcer.AnnouncePublicPendingConfigSaved(selectedFeatureName);
}
_.memory.Free(enabledConfigName);
announcer.AnnounceConfigCreated(selectedFeatureName, selectedConfigName);
}
protected function RemoveFeatureConfig() {
local class<FeatureConfig> configClass;
configClass = selectedFeatureClass.default.configClass;
if (configClass == none) {
announcer.AnnounceFailedNoConfigClass(selectedFeatureName);
return;
}
if (!configClass.static.Exists(selectedConfigName)) {
announcer.AnnounceFailedConfigDoesNotExist(
selectedFeatureName,
selectedConfigName);
return;
}
pendingConfigs.RemoveConfig();
configClass.static.DeleteConfig(selectedConfigName);
announcer.AnnounceConfigRemoved(selectedFeatureName, selectedConfigName);
}
protected function SetAutoFeatureConfig() {
local Text currentAutoEnabledConfig;
local class<FeatureConfig> configClass;
configClass = selectedFeatureClass.default.configClass;
if (configClass == none) {
announcer.AnnounceFailedNoConfigClass(selectedFeatureName);
return;
}
if (selectedConfigName != none && !configClass.static.Exists(selectedConfigName)) {
announcer.AnnounceFailedConfigDoesNotExist(selectedFeatureName, selectedConfigName);
return;
}
currentAutoEnabledConfig = configClass.static.GetAutoEnabledConfig();
if (selectedConfigName == none && currentAutoEnabledConfig == none) {
announcer.AnnounceFailedAlreadyNoAutoEnabled(selectedFeatureName);
}
else if (selectedConfigName != none &&
selectedConfigName.Compare(currentAutoEnabledConfig, SCASE_INSENSITIVE)) {
announcer.AnnounceFailedAlreadySameAutoEnabled(
selectedFeatureName,
selectedConfigName);
} else {
configClass.static.SetAutoEnabledConfig(selectedConfigName);
if (selectedConfigName != none) {
announcer.AnnounceAutoEnabledConfig(
selectedFeatureName,
selectedConfigName);
} else {
announcer.AnnounceRemovedAutoEnabledConfig(selectedFeatureName);
}
}
_.memory.Free(currentAutoEnabledConfig);
}
private function HashTable GetCurrentConfigData(BaseText configName) {
local class<FeatureConfig> configClass;
if (configName == none) {
return none;
}
configClass = selectedFeatureClass.default.configClass;
if (configClass == none) {
announcer.AnnounceFailedNoConfigClass(selectedFeatureName);
return none;
}
return configClass.static.LoadData(configName);
}
private function HashTable GetCurrentSelectedConfigData() {
return GetCurrentConfigData(selectedConfigName);
}
defaultproperties {
preferredName = "feature"
} }

430
sources/Commands/ACommandFeature_Announcer.uc

@ -20,31 +20,63 @@
class ACommandFeature_Announcer extends CommandAnnouncer; class ACommandFeature_Announcer extends CommandAnnouncer;
var private AnnouncementVariations enabledFeature, disabledFeature; var private AnnouncementVariations enabledFeature, disabledFeature;
var private AnnouncementVariations swappedConfig; var private AnnouncementVariations swappedConfig, pendingConfigSaved;
var private AnnouncementVariations showCurrentConfig, showPendingConfig;
var private AnnouncementVariations configCreated, configRemoved, configEdited;
var private AnnouncementVariations configEditedNew;
var private AnnouncementVariations pendingConfigSavedPublic;
var private AnnouncementVariations pendingConfigSavedPrivate;
var private AnnouncementVariations autoEnabled, removedAutoEnabled;
var private AnnouncementVariations failedAlreadyNoAutoEnabled;
var private AnnouncementVariations failedAlreadySameAutoEnabled;
var private AnnouncementVariations failedConfigAlreadyExists;
var private AnnouncementVariations failedConfigDoesNotExists;
var private AnnouncementVariations failedToLoadFeatureClass; var private AnnouncementVariations failedToLoadFeatureClass;
var private AnnouncementVariations failedNoConfigProvided, failedConfigMissing; var private AnnouncementVariations failedNoConfigProvided, failedConfigMissing;
var private AnnouncementVariations failedCannotEnableFeature; var private AnnouncementVariations failedCannotEnableFeature;
var private AnnouncementVariations failedNoConfigClass; var private AnnouncementVariations failedNoConfigClass, failedBadConfigName;
var private AnnouncementVariations failedAlreadyEnabled, failedAlreadyDisabled; var private AnnouncementVariations failedAlreadyEnabled, failedAlreadyDisabled;
var private AnnouncementVariations failedNoDataForConfig, failedExpectedObject;
var private AnnouncementVariations failedBadPointer, failedPendingConfigMissing;
protected function Finalizer() protected function Finalizer()
{ {
FreeVariations(enabledFeature); FreeVariations(enabledFeature);
FreeVariations(disabledFeature); FreeVariations(disabledFeature);
FreeVariations(swappedConfig); FreeVariations(swappedConfig);
FreeVariations(pendingConfigSaved);
FreeVariations(showCurrentConfig);
FreeVariations(showPendingConfig);
FreeVariations(configCreated);
FreeVariations(configRemoved);
FreeVariations(configEdited);
FreeVariations(configEditedNew);
FreeVariations(pendingConfigSavedPublic);
FreeVariations(pendingConfigSavedPrivate);
FreeVariations(autoEnabled);
FreeVariations(removedAutoEnabled);
FreeVariations(failedAlreadyNoAutoEnabled);
FreeVariations(failedAlreadySameAutoEnabled);
FreeVariations(failedConfigAlreadyExists);
FreeVariations(failedConfigDoesNotExists);
FreeVariations(failedToLoadFeatureClass); FreeVariations(failedToLoadFeatureClass);
FreeVariations(failedNoConfigProvided); FreeVariations(failedNoConfigProvided);
FreeVariations(failedConfigMissing); FreeVariations(failedConfigMissing);
FreeVariations(failedCannotEnableFeature); FreeVariations(failedCannotEnableFeature);
FreeVariations(failedNoConfigClass); FreeVariations(failedNoConfigClass);
FreeVariations(failedBadConfigName);
FreeVariations(failedAlreadyEnabled); FreeVariations(failedAlreadyEnabled);
FreeVariations(failedAlreadyDisabled); FreeVariations(failedAlreadyDisabled);
FreeVariations(failedNoDataForConfig);
FreeVariations(failedExpectedObject);
FreeVariations(failedBadPointer);
FreeVariations(failedPendingConfigMissing);
super.Finalizer(); super.Finalizer();
} }
public final function AnnounceEnabledFeature( public final function AnnounceEnabledFeature(
class<Feature> featureClass, BaseText featureName,
BaseText configName) BaseText configName)
{ {
local int i; local int i;
local array<TextTemplate> templates; local array<TextTemplate> templates;
@ -61,12 +93,12 @@ public final function AnnounceEnabledFeature(
} }
templates = MakeArray(enabledFeature); templates = MakeArray(enabledFeature);
for (i = 0; i < templates.length; i += 1) { for (i = 0; i < templates.length; i += 1) {
templates[i].Reset().ArgClass(featureClass).Arg(configName); templates[i].Reset().Arg(featureName).Arg(configName);
} }
MakeAnnouncement(enabledFeature); MakeAnnouncement(enabledFeature);
} }
public final function AnnounceDisabledFeature(class<Feature> featureClass) public final function AnnounceDisabledFeature(BaseText featureName)
{ {
local int i; local int i;
local array<TextTemplate> templates; local array<TextTemplate> templates;
@ -82,15 +114,15 @@ public final function AnnounceDisabledFeature(class<Feature> featureClass)
} }
templates = MakeArray(disabledFeature); templates = MakeArray(disabledFeature);
for (i = 0; i < templates.length; i += 1) { for (i = 0; i < templates.length; i += 1) {
templates[i].Reset().ArgClass(featureClass); templates[i].Reset().Arg(featureName);
} }
MakeAnnouncement(disabledFeature); MakeAnnouncement(disabledFeature);
} }
public final function AnnounceSwappedConfig( public final function AnnounceSwappedConfig(
class<Feature> featureClass, BaseText featureName,
BaseText oldConfig, BaseText oldConfig,
BaseText newConfig) BaseText newConfig)
{ {
local int i; local int i;
local array<TextTemplate> templates; local array<TextTemplate> templates;
@ -110,13 +142,275 @@ public final function AnnounceSwappedConfig(
{ {
templates[i] templates[i]
.Reset() .Reset()
.ArgClass(featureClass) .Arg(featureName)
.Arg(oldConfig) .Arg(oldConfig)
.Arg(newConfig); .Arg(newConfig);
} }
MakeAnnouncement(swappedConfig); MakeAnnouncement(swappedConfig);
} }
public final function AnnouncePublicPendingConfigSaved(
BaseText featureName)
{
local int i;
local array<TextTemplate> templates;
if (!pendingConfigSavedPublic.initialized)
{
pendingConfigSavedPublic.initialized = true;
pendingConfigSavedPublic.toSelfReport = _.text.MakeTemplate_S(
"Active config for feature {$TextEmphasis `%1`} was"
@ "{$TextNeutral modified}");
pendingConfigSavedPublic.toSelfPublic = _.text.MakeTemplate_S(
"%%instigator%% {$TextNeutral modified} active config for feature"
@ "{$TextEmphasis `%1`}");
}
templates = MakeArray(pendingConfigSavedPublic);
for (i = 0; i < templates.length; i += 1) {
templates[i].Reset().Arg(featureName);
}
MakeAnnouncement(pendingConfigSavedPublic);
}
public final function AnnouncePrivatePendingConfigSaved(BaseText featureName, BaseText configName)
{
if (!pendingConfigSavedPrivate.initialized)
{
pendingConfigSavedPrivate.initialized = true;
pendingConfigSavedPrivate.toSelfReport = _.text.MakeTemplate_S(
"Config \"%2\" for feature {$TextEmphasis `%1`} was"
@ "{$TextNeutral modified}");
}
pendingConfigSavedPrivate.toSelfReport
.Reset()
.Arg(featureName)
.Arg(configName);
MakeAnnouncement(pendingConfigSavedPrivate);
}
public final function AnnounceCurrentConfig(
BaseText featureName,
BaseText config)
{
if (!showCurrentConfig.initialized)
{
showCurrentConfig.initialized = true;
showCurrentConfig.toSelfReport = _.text.MakeTemplate_S(
"Current config \"%2\" for feature {$TextEmphasis `%1`}:");
}
showCurrentConfig.toSelfReport
.Reset()
.Arg(featureName)
.Arg(config);
MakeAnnouncement(showCurrentConfig);
}
public final function AnnouncePendingConfig(
BaseText featureName,
BaseText config)
{
if (!showPendingConfig.initialized)
{
showPendingConfig.initialized = true;
showPendingConfig.toSelfReport = _.text.MakeTemplate_S(
"Pending config \"%2\" for feature {$TextEmphasis `%1`}:");
}
showPendingConfig.toSelfReport
.Reset()
.Arg(featureName)
.Arg(config);
MakeAnnouncement(showPendingConfig);
}
public final function AnnounceConfigCreated(
BaseText featureName,
BaseText config)
{
if (!configCreated.initialized)
{
configCreated.initialized = true;
configCreated.toSelfReport = _.text.MakeTemplate_S(
"{$TextPositive Created config} \"%2\" for feature"
@ "{$TextEmphasis `%1`}");
}
configCreated.toSelfReport
.Reset()
.Arg(featureName)
.Arg(config);
MakeAnnouncement(configCreated);
}
public final function AnnounceConfigRemoved(
BaseText featureName,
BaseText config)
{
if (!configRemoved.initialized)
{
configRemoved.initialized = true;
configRemoved.toSelfReport = _.text.MakeTemplate_S(
"{$TextNegative Removed config} \"%2\" for feature"
@ "{$TextEmphasis `%1`}");
}
configRemoved.toSelfReport
.Reset()
.Arg(featureName)
.Arg(config);
MakeAnnouncement(configRemoved);
}
public final function AnnounceConfigEdited(
BaseText featureName,
BaseText config,
BaseText pathToValue,
BaseText oldValue,
BaseText newValue)
{
if (!configEdited.initialized)
{
configEdited.initialized = true;
configEdited.toSelfReport = _.text.MakeTemplate_S(
"{$TextNeutral Edited config} \"%2\" for feature"
@ "{$TextEmphasis `%1`} by replacing old value %4 at \"%3\""
@ "with new value %5");
}
configEdited.toSelfReport
.Reset()
.Arg(featureName)
.Arg(config)
.Arg(pathToValue)
.Arg(oldValue)
.Arg(newValue);
MakeAnnouncement(configEdited);
}
public final function AnnounceConfigNewValue(
BaseText featureName,
BaseText config,
BaseText pathToValue,
BaseText newValue)
{
if (!configEditedNew.initialized)
{
configEditedNew.initialized = true;
configEditedNew.toSelfReport = _.text.MakeTemplate_S(
"{$TextNeutral Edited config} \"%2\" for feature"
@ "{$TextEmphasis `%1`} by adding value %4 at \"%3\"");
}
configEditedNew.toSelfReport
.Reset()
.Arg(featureName)
.Arg(config)
.Arg(pathToValue)
.Arg(newValue);
MakeAnnouncement(configEditedNew);
}
public final function AnnounceAutoEnabledConfig(
BaseText featureName,
BaseText config)
{
if (!autoEnabled.initialized)
{
autoEnabled.initialized = true;
autoEnabled.toSelfReport = _.text.MakeTemplate_S(
"Config \"%2\" for feature {$TextEmphasis `%1`} will now be"
@ "{$TextPositive auto-enabled}!");
}
autoEnabled.toSelfReport
.Reset()
.Arg(featureName)
.Arg(config);
MakeAnnouncement(autoEnabled);
}
public final function AnnounceRemovedAutoEnabledConfig(
BaseText featureName)
{
if (!removedAutoEnabled.initialized)
{
removedAutoEnabled.initialized = true;
removedAutoEnabled.toSelfReport = _.text.MakeTemplate_S(
"No config for feature {$TextEmphasis `%1`} will now be"
@ "{$TextPositive auto-enabled}!");
}
removedAutoEnabled.toSelfReport
.Reset()
.Arg(featureName);
MakeAnnouncement(removedAutoEnabled);
}
public final function AnnounceFailedAlreadyNoAutoEnabled(
BaseText featureName)
{
if (!failedAlreadyNoAutoEnabled.initialized)
{
failedAlreadyNoAutoEnabled.initialized = true;
failedAlreadyNoAutoEnabled.toSelfReport = _.text.MakeTemplate_S(
"{$TextFailure Cannot remove} auto-enabled config status for"
@ "feature {$TextEmphasis `%1`}: it already has"
@ "{$TextNeutral no auto-enabled config}!");
}
failedAlreadyNoAutoEnabled.toSelfReport
.Reset()
.Arg(featureName);
MakeAnnouncement(failedAlreadyNoAutoEnabled);
}
public final function AnnounceFailedAlreadySameAutoEnabled(
BaseText featureName,
BaseText config)
{
if (!failedAlreadySameAutoEnabled.initialized)
{
failedAlreadySameAutoEnabled.initialized = true;
failedAlreadySameAutoEnabled.toSelfReport = _.text.MakeTemplate_S(
"{$TextFailure Cannot make} config \"%2\" auto-enabled for feature"
@ "{$TextEmphasis `%1`}: it already"
@ "{$TextNeutral is auto-enabled}!");
}
failedAlreadySameAutoEnabled.toSelfReport
.Reset()
.Arg(featureName)
.Arg(config);
MakeAnnouncement(failedAlreadySameAutoEnabled);
}
public final function AnnounceFailedConfigAlreadyExists(
BaseText featureName,
BaseText config)
{
if (!failedConfigAlreadyExists.initialized)
{
failedConfigAlreadyExists.initialized = true;
failedConfigAlreadyExists.toSelfReport = _.text.MakeTemplate_S(
"Config \"%2\" for feature {$TextEmphasis `%1`}"
@ "{$TextFailure already exists}");
}
failedConfigAlreadyExists.toSelfReport
.Reset()
.Arg(featureName)
.Arg(config);
MakeAnnouncement(failedConfigAlreadyExists);
}
public final function AnnounceFailedConfigDoesNotExist(
BaseText featureName,
BaseText config)
{
if (!failedConfigDoesNotExists.initialized)
{
failedConfigDoesNotExists.initialized = true;
failedConfigDoesNotExists.toSelfReport = _.text.MakeTemplate_S(
"Config \"%2\" for feature {$TextEmphasis `%1`}"
@ "{$TextFailure doesn't exist}");
}
failedConfigDoesNotExists.toSelfReport
.Reset()
.Arg(featureName)
.Arg(config);
MakeAnnouncement(failedConfigDoesNotExists);
}
public final function AnnounceFailedToLoadFeatureClass(BaseText failedClassName) public final function AnnounceFailedToLoadFeatureClass(BaseText failedClassName)
{ {
if (!failedToLoadFeatureClass.initialized) if (!failedToLoadFeatureClass.initialized)
@ -130,16 +424,16 @@ public final function AnnounceFailedToLoadFeatureClass(BaseText failedClassName)
} }
public final function AnnounceFailedNoConfigProvided( public final function AnnounceFailedNoConfigProvided(
class<Feature> featureClass) BaseText featureName)
{ {
if (!failedNoConfigProvided.initialized) if (!failedNoConfigProvided.initialized)
{ {
failedNoConfigProvided.initialized = true; failedNoConfigProvided.initialized = true;
failedNoConfigProvided.toSelfReport = _.text.MakeTemplate_S( failedNoConfigProvided.toSelfReport = _.text.MakeTemplate_S(
"{$TextFailue No config specified} and {$TextFailure no" "{$TextFailure No config specified} and {$TextFailure no"
@ "auto-enabled config} exists for feature {$TextEmphasis `%1`}"); @ "auto-enabled config} exists for feature {$TextEmphasis `%1`}");
} }
failedNoConfigProvided.toSelfReport.Reset().ArgClass(featureClass); failedNoConfigProvided.toSelfReport.Reset().Arg(featureName);
MakeAnnouncement(failedNoConfigProvided); MakeAnnouncement(failedNoConfigProvided);
} }
@ -149,15 +443,28 @@ public final function AnnounceFailedConfigMissing(BaseText config)
{ {
failedConfigMissing.initialized = true; failedConfigMissing.initialized = true;
failedConfigMissing.toSelfReport = _.text.MakeTemplate_S( failedConfigMissing.toSelfReport = _.text.MakeTemplate_S(
"Specified config \"%1\" {$TextFailue doesn't exist}"); "Specified config \"%1\" {$TextFailure doesn't exist}");
} }
failedConfigMissing.toSelfReport.Reset().Arg(config); failedConfigMissing.toSelfReport.Reset().Arg(config);
MakeAnnouncement(failedConfigMissing); MakeAnnouncement(failedConfigMissing);
} }
public final function AnnounceFailedPendingConfigMissing(BaseText config)
{
if (!failedPendingConfigMissing.initialized)
{
failedPendingConfigMissing.initialized = true;
failedPendingConfigMissing.toSelfReport = _.text.MakeTemplate_S(
"Specified config \"%1\" {$TextFailure doesn't have} any pending"
@ "changes");
}
failedPendingConfigMissing.toSelfReport.Reset().Arg(config);
MakeAnnouncement(failedPendingConfigMissing);
}
public final function AnnounceFailedCannotEnableFeature( public final function AnnounceFailedCannotEnableFeature(
class<Feature> featureClass, BaseText featureName,
BaseText config) BaseText config)
{ {
if (!failedCannotEnableFeature.initialized) if (!failedCannotEnableFeature.initialized)
{ {
@ -168,57 +475,120 @@ public final function AnnounceFailedCannotEnableFeature(
} }
failedCannotEnableFeature.toSelfReport failedCannotEnableFeature.toSelfReport
.Reset() .Reset()
.ArgClass(featureClass) .Arg(featureName)
.Arg(config); .Arg(config);
MakeAnnouncement(failedCannotEnableFeature); MakeAnnouncement(failedCannotEnableFeature);
} }
public final function AnnounceFailedNoConfigClass( public final function AnnounceFailedNoConfigClass(
class<Feature> featureClass) BaseText featureName)
{ {
if (!failedNoConfigClass.initialized) if (!failedNoConfigClass.initialized)
{ {
failedNoConfigClass.initialized = true; failedNoConfigClass.initialized = true;
failedNoConfigClass.toSelfReport = _.text.MakeTemplate_S( failedNoConfigClass.toSelfReport = _.text.MakeTemplate_S(
"Feature {$TextEmphasis `%1`} {$TextFailure does not have config" "Feature {$TextEmphasis `%1`} {$TextFailure does not have} config"
@ "class}! This is most likely caused by its faulty" @ "class! This is most likely caused by its faulty"
@ "implementation"); @ "implementation");
} }
failedNoConfigClass.toSelfReport.Reset().ArgClass(featureClass); failedNoConfigClass.toSelfReport.Reset().Arg(featureName);
MakeAnnouncement(failedNoConfigClass); MakeAnnouncement(failedNoConfigClass);
} }
public final function AnnounceFailedBadConfigName(BaseText configName)
{
if (!failedBadConfigName.initialized)
{
failedBadConfigName.initialized = true;
failedBadConfigName.toSelfReport = _.text.MakeTemplate_S(
"{$TextFailure Cannot create} a config with invalid name \"%1\"");
}
failedBadConfigName.toSelfReport.Reset().Arg(configName);
MakeAnnouncement(failedBadConfigName);
}
public final function AnnounceFailedAlreadyDisabled( public final function AnnounceFailedAlreadyDisabled(
class<Feature> featureClass) BaseText featureName)
{ {
if (!failedAlreadyDisabled.initialized) if (!failedAlreadyDisabled.initialized)
{ {
failedAlreadyDisabled.initialized = true; failedAlreadyDisabled.initialized = true;
failedAlreadyDisabled.toSelfReport = _.text.MakeTemplate_S( failedAlreadyDisabled.toSelfReport = _.text.MakeTemplate_S(
"Feature {$TextEmphasis `%1`} is already {$TextNegative disabled}"); "{$TextFailure Cannot disable} feature {$TextEmphasis `%1`}: it is"
@ "already {$TextNegative disabled}");
} }
failedAlreadyDisabled.toSelfReport.Reset().ArgClass(featureClass); failedAlreadyDisabled.toSelfReport.Reset().Arg(featureName);
MakeAnnouncement(failedAlreadyDisabled); MakeAnnouncement(failedAlreadyDisabled);
} }
public final function AnnounceFailedAlreadyEnabled( public final function AnnounceFailedAlreadyEnabled(
class<Feature> featureClass, BaseText featureName,
BaseText config) BaseText config)
{ {
if (!failedAlreadyEnabled.initialized) if (!failedAlreadyEnabled.initialized)
{ {
failedAlreadyEnabled.initialized = true; failedAlreadyEnabled.initialized = true;
failedAlreadyEnabled.toSelfReport = _.text.MakeTemplate_S( failedAlreadyEnabled.toSelfReport = _.text.MakeTemplate_S(
"Feature {$TextEmphasis `%1`} is already {$TextNegative enabled}" "{$TextFailure Cannot enable} feature {$TextEmphasis `%1`}: it is"
@ "with specified config \"%2\""); @ "already {$TextPositive enabled} with specified config \"%2\"");
} }
failedAlreadyEnabled.toSelfReport failedAlreadyEnabled.toSelfReport
.Reset() .Reset()
.ArgClass(featureClass) .Arg(featureName)
.Arg(config); .Arg(config);
MakeAnnouncement(failedAlreadyEnabled); MakeAnnouncement(failedAlreadyEnabled);
} }
public final function AnnounceFailedNoDataForConfig(
BaseText featureName,
BaseText config)
{
if (!failedNoDataForConfig.initialized)
{
failedNoDataForConfig.initialized = true;
failedNoDataForConfig.toSelfReport = _.text.MakeTemplate_S(
"Feature {$TextEmphasis `%1`} is {$TextFailure missing data} for"
@ "config \"%2\"");
}
failedNoDataForConfig.toSelfReport
.Reset()
.Arg(featureName)
.Arg(config);
MakeAnnouncement(failedNoDataForConfig);
}
public final function AnnounceFailedExpectedObject()
{
if (!failedExpectedObject.initialized)
{
failedExpectedObject.initialized = true;
failedExpectedObject.toSelfReport = _.text.MakeTemplate_S(
"Value change {$TextFailure failed}, because when changing"
@ "the value of the whole config, a JSON object must be provided");
}
MakeAnnouncement(failedExpectedObject);
}
public final function AnnounceFailedBadPointer(
BaseText featureName,
BaseText config,
BaseText pointer)
{
if (!failedBadPointer.initialized)
{
failedBadPointer.initialized = true;
failedBadPointer.toSelfReport = _.text.MakeTemplate_S(
"Provided JSON pointer \"%3\" is {$TextFailure invalid} for config"
@ "\"%2\" of feature {$TextEmphasis `%1`}");
}
failedBadPointer.toSelfReport
.Reset()
.Arg(featureName)
.Arg(config)
.Arg(pointer);
MakeAnnouncement(failedBadPointer);
}
defaultproperties defaultproperties
{ {
} }

30
sources/Commands/ACommandGod.uc

@ -46,21 +46,21 @@ protected function Finalizer()
protected function BuildData(CommandDataBuilder builder) protected function BuildData(CommandDataBuilder builder)
{ {
builder.Name(P("god")).Group(P("gameplay")) builder.Group(P("gameplay"));
.Summary(P("Command for making player immortal.")); builder.Summary(P("Command for making player immortal."));
builder.RequireTarget() builder.RequireTarget();
.Describe(P("Gives targeted players god status, making them" builder.Describe(P("Gives targeted players god status, making them"
@ "invincible.")); @ "invincible."));
builder.SubCommand(P("list")) builder.SubCommand(P("list"));
.Describe(P("Reports godhood status of targeted players.")); builder.Describe(P("Reports godhood status of targeted players."));
builder.SubCommand(P("strip")) builder.SubCommand(P("strip"));
.Describe(P("Strips targeted players from the godhood status.")); builder.Describe(P("Strips targeted players from the godhood status."));
builder.Option(P("demi")) builder.Option(P("demi"));
.Describe(P("This flag makes targeted players \"demigods\" instead -" builder.Describe(P("This flag makes targeted players \"demigods\" instead -"
@ "they still cannot die, but they can take any non-lethal" @ "they still cannot die, but they can take any non-lethal"
@ "damage.")); @ "damage."));
builder.Option(P("unmovable")) builder.Option(P("unmovable"));
.Describe(P("This flag also prevents targeted players from being" builder.Describe(P("This flag also prevents targeted players from being"
@ "affected by the momentum trasnferred from damaging attacks.")); @ "affected by the momentum trasnferred from damaging attacks."));
announcer = ACommandGod_Announcer( announcer = ACommandGod_Announcer(
_.memory.Allocate(class'ACommandGod_Announcer')); _.memory.Allocate(class'ACommandGod_Announcer'));
@ -69,8 +69,9 @@ protected function BuildData(CommandDataBuilder builder)
protected function ExecutedFor( protected function ExecutedFor(
EPlayer target, EPlayer target,
CallData arguments, CallData arguments,
EPlayer instigator) EPlayer instigator,
{ CommandPermissions permissions
) {
local GodStatus newGodStatus; local GodStatus newGodStatus;
announcer.Setup(target, instigator, othersConsole); announcer.Setup(target, instigator, othersConsole);
@ -215,6 +216,7 @@ private final function UpdateHealthSignalConnection()
defaultproperties defaultproperties
{ {
preferredName = "god"
TDAMAGE = 0 TDAMAGE = 0
stringConstants(0) = "damage" stringConstants(0) = "damage"
TMOMENTUM = 1 TMOMENTUM = 1

66
sources/Commands/ACommandInventory.uc

@ -34,57 +34,57 @@ var protected const int TLISTS_SKIPPED;
protected function BuildData(CommandDataBuilder builder) protected function BuildData(CommandDataBuilder builder)
{ {
builder.Name(T(TINVENTORY)).Group(P("gameplay")) builder.Group(P("gameplay"));
.Summary(P("Manages player's inventory.")) builder.Summary(P("Manages player's inventory."));
.Describe(P("Command for displaying and editing players' inventories." builder.Describe(P("Command for displaying and editing players' inventories."
@ "If called without specifying subcommand - simply displays" @ "If called without specifying subcommand - simply displays"
@ "targeted player's inventory.")); @ "targeted player's inventory."));
builder.RequireTarget(); builder.RequireTarget();
builder.SubCommand(T(TADD)) builder.SubCommand(T(TADD));
.OptionalParams() builder.OptionalParams();
.ParamTextList(T(TITEMS)) builder.ParamTextList(T(TITEMS));
.Describe(P("This command adds items (based on listed templates) to" builder.Describe(P("This command adds items (based on listed templates) to"
@ "the targeted player's inventory." @ "the targeted player's inventory."
@ "Instead of templates item aliases can be specified.")); @ "Instead of templates item aliases can be specified."));
builder.SubCommand(T(TREMOVE)) builder.SubCommand(T(TREMOVE));
.OptionalParams() builder.OptionalParams();
.ParamTextList(T(TITEMS)) builder.ParamTextList(T(TITEMS));
.Describe(P("This command removes items (based on listed templates)" builder.Describe(P("This command removes items (based on listed templates)"
@ "from the targeted player's inventory." @ "from the targeted player's inventory."
@ "Instead of templates item aliases can be specified.")); @ "Instead of templates item aliases can be specified."));
builder.SubCommand(T(TSET)) builder.SubCommand(T(TSET));
.OptionalParams() builder.OptionalParams();
.ParamTextList(T(TITEMS)) builder.ParamTextList(T(TITEMS));
.Describe(P("This command acts like combination of two commands -" builder.Describe(P("This command acts like combination of two commands -"
@ "first removing all items from the player's current inventory and" @ "first removing all items from the player's current inventory and"
@ "then adding specified items. first clears inventory" @ "then adding specified items. first clears inventory"
@ "(based on specified options) and then ")); @ "(based on specified options) and then "));
builder.Option(T(TEQUIP)) builder.Option(T(TEQUIP));
.Describe(F("Affect items currently equipped by the targeted player." builder.Describe(F("Affect items currently equipped by the targeted player."
@ "Releveant for a {$TextEmphasis remove} subcommand.")); @ "Releveant for a {$TextEmphasis remove} subcommand."));
builder.Option(T(TLIST)) builder.Option(T(TLIST));
.Describe(P("Include weapons from specified group into the list.")) builder.Describe(P("Include weapons from specified group into the list."));
.ParamTextList(T(TLISTS_NAMES)); builder.ParamTextList(T(TLISTS_NAMES));
builder.Option(T(TAMMO)) builder.Option(T(TAMMO));
.Describe(P("When adding weapons - signals that their" builder.Describe(P("When adding weapons - signals that their"
@ "ammo / charge / whatever has to be filled after addition.")); @ "ammo / charge / whatever has to be filled after addition."));
builder.Option(T(TKEEP)) builder.Option(T(TKEEP));
.Describe(F("Removing items by default means simply destroying them." builder.Describe(F("Removing items by default means simply destroying them."
@ "This flag makes command to try and keep them in some form." @ "This flag makes command to try and keep them in some form."
@ "Success for all items is not guaranteed.")); @ "Success for all items is not guaranteed."));
builder.Option(T(THIDDEN)) builder.Option(T(THIDDEN));
.Describe(F("Some of the items in the inventory are" builder.Describe(F("Some of the items in the inventory are"
@ "{$TextEmphasis hidden} and are not supposed to be seem by" @ "{$TextEmphasis hidden} and are not supposed to be seem by"
@ "the player. To avoid weird behavior, {$TextEmphasis inventory}" @ "the player. To avoid weird behavior, {$TextEmphasis inventory}"
@ "command by default ignores them when affecting groups of items" @ "command by default ignores them when affecting groups of items"
@ "(like when removing all items) unless they're directly" @ "(like when removing all items) unless they're directly"
@ "specified. This flag tells it to also affect hidden items.")); @ "specified. This flag tells it to also affect hidden items."));
builder.Option(T(TFORCE)) builder.Option(T(TFORCE));
.Describe(P("Sometimes adding and removing items is impossible due to" builder.Describe(P("Sometimes adding and removing items is impossible due to"
@ "the limitations imposed by the game. This option allows to" @ "the limitations imposed by the game. This option allows to"
@ "ignore some of those limitation.")); @ "ignore some of those limitation."));
builder.Option(T(TALL), P("A")) builder.Option(T(TALL), P("A"));
.Describe(F("This flag is used when removing items. If user has" builder.Describe(F("This flag is used when removing items. If user has"
@ "specified any weapon templates - it means" @ "specified any weapon templates - it means"
@ "\"remove all items with these tempaltes from inventory\"," @ "\"remove all items with these tempaltes from inventory\","
@ "but if user has not specified any templated it simply means" @ "but if user has not specified any templated it simply means"
@ -94,8 +94,9 @@ protected function BuildData(CommandDataBuilder builder)
protected function ExecutedFor( protected function ExecutedFor(
EPlayer target, EPlayer target,
CallData arguments, CallData arguments,
EPlayer instigator) EPlayer instigator,
{ CommandPermissions permissions
) {
local InventoryTool tool; local InventoryTool tool;
local ArrayList itemsArray, specifiedLists; local ArrayList itemsArray, specifiedLists;
LoadUserFlags(arguments.options); LoadUserFlags(arguments.options);
@ -286,6 +287,7 @@ protected function array<Text> LoadItemsList(
defaultproperties defaultproperties
{ {
preferredName = "inventory"
TINVENTORY = 0 TINVENTORY = 0
stringConstants(0) = "inventory" stringConstants(0) = "inventory"
TADD = 1 TADD = 1

38
sources/Commands/ACommandNick.uc

@ -34,30 +34,31 @@ protected function Finalizer()
protected function BuildData(CommandDataBuilder builder) protected function BuildData(CommandDataBuilder builder)
{ {
builder.Name(P("nick")).Group(P("gameplay")) builder.Group(P("gameplay"));
.Summary(P("Changes nickname.")); builder.Summary(P("Changes nickname."));
builder.RequireTarget(); builder.RequireTarget();
builder.ParamRemainder(P("nick")) builder.ParamRemainder(P("nick"));
.Describe(P("Changes nickname of targeted players to <nick>.")); builder.Describe(P("Changes nickname of targeted players to <nick>."));
builder.Option(P("plain")) builder.Option(P("plain"));
.Describe(P("Take nickname exactly as typed, without attempting to" builder.Describe(P("Take nickname exactly as typed, without attempting to"
@ "treat it like formatted string.")); @ "treat it like formatted string."));
builder.Option(P("fix"), P("f")) builder.Option(P("fix"), P("f"));
.Describe(P("In case of a nickname with erroroneous formatting or" builder.Describe(P("In case of a nickname with erroroneous formatting or"
@ "invalid default color (specified with `--color`)," @ "invalid default color (specified with `--color`),"
@ "try to fix/ignore it instead of simply rejecting it.")); @ "try to fix/ignore it instead of simply rejecting it."));
builder.Option(P("color")) builder.Option(P("color"));
.Describe(P("Color to use for the nickname. In case nickname is already" builder.Describe(P("Color to use for the nickname. In case nickname is already"
@ "colored, this flag will only affects uncolored parts.")) @ "colored, this flag will only affects uncolored parts."));
.ParamText(P("default_color")); builder.ParamText(P("default_color"));
announcer = ACommandNick_Announcer( announcer = ACommandNick_Announcer(
_.memory.Allocate(class'ACommandNick_Announcer')); _.memory.Allocate(class'ACommandNick_Announcer'));
} }
protected function Executed( protected function Executed(
CallData arguments, CallData arguments,
EPlayer callerPlayer) EPlayer callerPlayer,
{ CommandPermissions permissions
) {
local Text givenName; local Text givenName;
local array<FormattingErrorsReport.FormattedStringError> errors; local array<FormattingErrorsReport.FormattedStringError> errors;
@ -89,8 +90,9 @@ protected function Executed(
protected function ExecutedFor( protected function ExecutedFor(
EPlayer target, EPlayer target,
CallData arguments, CallData arguments,
EPlayer instigator) EPlayer instigator,
{ CommandPermissions permissions
) {
local Text alteredVersion; local Text alteredVersion;
if (!foundErrors || arguments.options.HasKey(P("fix"))) if (!foundErrors || arguments.options.HasKey(P("fix")))
@ -126,6 +128,6 @@ protected function bool TryChangeDefaultColor(BaseText specifiedColor)
return false; return false;
} }
defaultproperties defaultproperties {
{ preferredName = "nick"
} }

109
sources/Commands/ACommandSpawn.uc

@ -30,79 +30,76 @@ protected function Finalizer()
protected function BuildData(CommandDataBuilder builder) protected function BuildData(CommandDataBuilder builder)
{ {
builder.Name(P("spawn")).Group(P("debug")) builder.Group(P("debug"));
.Summary(P("Spawns new entity on the map.")); builder.Summary(P("Spawns new entity on the map."));
builder.ParamText(P("template")) builder.ParamText(P("template"),, P("entity"));
.Describe(P("Spawns new entity based on the given template at the point" builder.Describe(P("Spawns new entity based on the given template at the point"
@ "player is currently looking at.")); @ "player is currently looking at."));
builder.SubCommand(P("at")) builder.SubCommand(P("at"));
.ParamText(P("template")) builder.ParamText(P("template"),, P("entity"));
.ParamNumber(P("x")) builder.ParamNumber(P("x"));
.ParamNumber(P("y")) builder.ParamNumber(P("y"));
.ParamNumber(P("z")) builder.ParamNumber(P("z"));
.Describe(P("Spawns new entity based on the given template at" builder.Describe(P("Spawns new entity based on the given template at"
@ "the point, given by the coordinates")); @ "the point, given by the coordinates"));
announcer = ACommandSpawn_Announcer( announcer = ACommandSpawn_Announcer(
_.memory.Allocate(class'ACommandSpawn_Announcer')); _.memory.Allocate(class'ACommandSpawn_Announcer'));
} }
protected function Executed( protected function Executed(
CallData arguments, CallData arguments,
EPlayer instigator) EPlayer instigator,
{ CommandPermissions permissions
local Text givenTemplate, template; ) {
local Vector spawnLocation; local HashTable value;
local Vector spawnLocation;
announcer.Setup(none, instigator, othersConsole); announcer.Setup(none, instigator, othersConsole);
givenTemplate = arguments.parameters.GetText(P("template")); value = arguments.parameters.GetHashTable(P("template"));
if (givenTemplate.StartsWithS("$")) {
template = _.alias.ResolveEntity(givenTemplate, true);
}
else {
template = givenTemplate.Copy();
}
_.memory.Free(givenTemplate);
if (arguments.subCommandName.IsEmpty()) { if (arguments.subCommandName.IsEmpty()) {
SpawnInInstigatorSight(instigator, template); SpawnInInstigatorSight(instigator, value);
} } else if (arguments.subCommandName.Compare(P("at"), SCASE_INSENSITIVE)) {
else if (arguments.subCommandName.Compare(P("at"), SCASE_INSENSITIVE))
{
spawnLocation.x = arguments.parameters.GetFloat(P("x")); spawnLocation.x = arguments.parameters.GetFloat(P("x"));
spawnLocation.y = arguments.parameters.GetFloat(P("y")); spawnLocation.y = arguments.parameters.GetFloat(P("y"));
spawnLocation.z = arguments.parameters.GetFloat(P("z")); spawnLocation.z = arguments.parameters.GetFloat(P("z"));
SpawnAt(instigator, template, spawnLocation); SpawnAt(instigator, value, spawnLocation);
} }
_.memory.Free(template); _.memory.Free(value);
} }
private final function SpawnAt( private final function SpawnAt(
EPlayer instigator, EPlayer instigator,
BaseText template, HashTable value,
Vector spawnLocation) Vector spawnLocation
{ ) {
local Text humanReadable, template;
local EPlaceable result; local EPlaceable result;
humanReadable = value.GetText(P("alias"));
template = value.GetText(P("value"));
result = _server.kf.world.Spawn(template, spawnLocation); result = _server.kf.world.Spawn(template, spawnLocation);
if (result != none) { if (result != none) {
announcer.AnnounceSpawned(template); announcer.AnnounceSpawned(humanReadable);
} else {
announcer.AnnounceSpawningFailed(humanReadable);
} }
else { _.memory.Free2(humanReadable, result);
announcer.AnnounceSpawningFailed(template);
}
_.memory.Free(result);
} }
private final function SpawnInInstigatorSight( private final function SpawnInInstigatorSight(
EPlayer instigator, EPlayer instigator,
BaseText template) HashTable value
{ ) {
local EPlaceable result; local EPlaceable result;
local Vector spawnLocation; local Vector spawnLocation;
local TracingIterator iter; local TracingIterator iter;
local Text humanReadable, template;
humanReadable = value.GetText(P("alias"));
template = value.GetText(P("value"));
iter = _server.kf.world.TracePlayerSight(instigator); iter = _server.kf.world.TracePlayerSight(instigator);
if (iter.LeaveOnlyVisible().HasFinished()) iter.LeaveOnlyVisible();
{ if (iter.HasFinished()) {
announcer.AnnounceFailedTrace(); announcer.AnnounceFailedTrace();
return; return;
} }
@ -110,22 +107,18 @@ private final function SpawnInInstigatorSight(
result = _server.kf.world.Spawn(template, spawnLocation); result = _server.kf.world.Spawn(template, spawnLocation);
// Shift position back a little and try again; // Shift position back a little and try again;
// this should fix a ton of spawning failures // this should fix a ton of spawning failures
if (result == none) if (result == none) {
{ spawnLocation = spawnLocation + Normal(iter.GetTracingStart() - spawnLocation) * 100;
spawnLocation = spawnLocation +
Normal(iter.GetTracingStart() - spawnLocation) * 100;
result = _server.kf.world.Spawn(template, spawnLocation); result = _server.kf.world.Spawn(template, spawnLocation);
} }
if (result != none) { if (result != none) {
announcer.AnnounceSpawned(template); announcer.AnnounceSpawned(humanReadable);
} else {
announcer.AnnounceSpawningFailed(humanReadable);
} }
else { _.memory.Free4(result, iter, humanReadable, result);
announcer.AnnounceSpawningFailed(template);
}
_.memory.Free(result);
_.memory.Free(iter);
} }
defaultproperties defaultproperties {
{ preferredName = "spawn"
} }

104
sources/Commands/ACommandTrader.uc

@ -38,60 +38,60 @@ protected function Finalizer()
protected function BuildData(CommandDataBuilder builder) protected function BuildData(CommandDataBuilder builder)
{ {
builder.Name(T(TTRADER)).Group(P("gameplay")) builder.Group(P("gameplay"));
.Summary(P("Manages trader time and available traders.")) builder.Summary(P("Manages trader time and available traders."));
.Describe(P("Enables of disables trading.")) builder.Describe(P("Enables of disables trading."));
.ParamBoolean(T(TENABLE)); builder.ParamBoolean(T(TENABLE));
builder.SubCommand(T(TTIME)) builder.SubCommand(T(TTIME));
.Describe(F("Changes current trader time if numeric value is specified." builder.Describe(F("Changes current trader time if numeric value is specified."
@ "You can also pause trader countdown by specifying" @ "You can also pause trader countdown by specifying"
@ "{$TextEmphasis pause} or turn it back on with" @ "{$TextEmphasis pause} or turn it back on with"
@ "{$TextEmphasis unpause}.")) @ "{$TextEmphasis unpause}."));
.ParamText(T(TTRADER_TIME)); builder.ParamText(T(TTRADER_TIME));
builder.SubCommand(T(TLIST)) builder.SubCommand(T(TLIST));
.Describe(P("Lists names of all available traders and" builder.Describe(P("Lists names of all available traders and"
@ "marks closest one to the caller.")); @ "marks closest one to the caller."));
builder.SubCommand(T(TOPEN)) builder.SubCommand(T(TOPEN));
.Describe(P("Opens specified traders.")) builder.Describe(P("Opens specified traders."));
.OptionalParams() builder.OptionalParams();
.ParamTextList(T(TTRADERS)); builder.ParamTextList(T(TTRADERS));
builder.SubCommand(T(TCLOSE)) builder.SubCommand(T(TCLOSE));
.Describe(P("Closes specified traders.")) builder.Describe(P("Closes specified traders."));
.OptionalParams() builder.OptionalParams();
.ParamTextList(T(TTRADERS)); builder.ParamTextList(T(TTRADERS));
builder.SubCommand(T(TAUTO_OPEN)) builder.SubCommand(T(TAUTO_OPEN));
.Describe(P("Sets whether specified traders are open automatically.")) builder.Describe(P("Sets whether specified traders are open automatically."));
.ParamBoolean(T(TAUTO_OPEN_QUESTION)) builder.ParamBoolean(T(TAUTO_OPEN_QUESTION));
.OptionalParams() builder.OptionalParams();
.ParamTextList(T(TTRADERS)); builder.ParamTextList(T(TTRADERS));
builder.SubCommand(T(TSELECT)) builder.SubCommand(T(TSELECT));
.Describe(P("Selects specified trader.")) builder.Describe(P("Selects specified trader."));
.OptionalParams() builder.OptionalParams();
.ParamText(T(TTRADER)); builder.ParamText(T(TTRADER));
builder.SubCommand(T(TBOOT)) builder.SubCommand(T(TBOOT));
.Describe(P("Boots all players from specified traders. If no traders" builder.Describe(P("Boots all players from specified traders. If no traders"
@ "were specified - assumes that all of them should be affected.")) @ "were specified - assumes that all of them should be affected."));
.OptionalParams() builder.OptionalParams();
.ParamTextList(T(TTRADERS)); builder.ParamTextList(T(TTRADERS));
builder.SubCommand(T(TENABLE)) builder.SubCommand(T(TENABLE));
.Describe(P("Enables specified traders.")) builder.Describe(P("Enables specified traders."));
.OptionalParams() builder.OptionalParams();
.ParamTextList(T(TTRADERS)); builder.ParamTextList(T(TTRADERS));
builder.SubCommand(T(TDISABLE)) builder.SubCommand(T(TDISABLE));
.Describe(P("Disables specified traders.")) builder.Describe(P("Disables specified traders."));
.OptionalParams() builder.OptionalParams();
.ParamTextList(T(TTRADERS)); builder.ParamTextList(T(TTRADERS));
builder.Option(T(TALL)) builder.Option(T(TALL));
.Describe(P("If sub-command targets shops, this flag will make it" builder.Describe(P("If sub-command targets shops, this flag will make it"
@ "target all the available shops.")); @ "target all the available shops."));
builder.Option(T(TCLOSEST)) builder.Option(T(TCLOSEST));
.Describe(P("If sub-command targets shops, this flag will make it also" builder.Describe(P("If sub-command targets shops, this flag will make it also"
@ "target closest shop to the caller.")); @ "target closest shop to the caller."));
builder.Option(T(TIGNORE_DOORS)) builder.Option(T(TIGNORE_DOORS));
.Describe(F("When used with {$TextEmphasis select} sub-command, it will" builder.Describe(F("When used with {$TextEmphasis select} sub-command, it will"
@ "neither open or close doors.")); @ "neither open or close doors."));
builder.Option(T(TIGNORE_PLAYERS), P("I")) builder.Option(T(TIGNORE_PLAYERS), P("I"));
.Describe(P("Normally commands that close doors will automatically boot" builder.Describe(P("Normally commands that close doors will automatically boot"
@ "players from inside to prevent locking them in. This flag forces" @ "players from inside to prevent locking them in. This flag forces"
@ "this command to leave players inside. However they can still be" @ "this command to leave players inside. However they can still be"
@ "booted out at the end of trading time. Also it is impossible to" @ "booted out at the end of trading time. Also it is impossible to"
@ -100,8 +100,11 @@ protected function BuildData(CommandDataBuilder builder)
_.memory.Allocate(class'ACommandTrader_Announcer')); _.memory.Allocate(class'ACommandTrader_Announcer'));
} }
protected function Executed(CallData arguments, EPlayer instigator) protected function Executed(
{ CallData arguments,
EPlayer instigator,
CommandPermissions permissions
) {
local bool newTradingStatus; local bool newTradingStatus;
announcer.Setup(none, instigator, othersConsole); announcer.Setup(none, instigator, othersConsole);
@ -632,6 +635,7 @@ protected function WriteTraderTags(ETrader traderToWrite, bool isClosest)
defaultproperties defaultproperties
{ {
preferredName = "trader"
TLIST = 0 TLIST = 0
stringConstants(0) = "list" stringConstants(0) = "list"
TOPEN = 1 TOPEN = 1

142
sources/Commands/ACommandUserData.uc

@ -1,6 +1,6 @@
/** /**
* Command for changing amount of money players have. * Command for changing amount of money players have.
* Copyright 2022 Anton Tarasenko * Copyright 2022-2023 Anton Tarasenko
*------------------------------------------------------------------------------ *------------------------------------------------------------------------------
* This file is part of Acedia. * This file is part of Acedia.
* *
@ -21,24 +21,23 @@ class ACommandUserData extends Command;
var private array<EPlayer> playerQueue; var private array<EPlayer> playerQueue;
// TODO: Finish this command after JSON parameters are added
protected function BuildData(CommandDataBuilder builder) protected function BuildData(CommandDataBuilder builder)
{ {
builder.Name(P("userdata")).Group(P("admin")) builder.Group(P("admin"));
.Summary(P("Allows to read and write custom user data for players.")); builder.Summary(P("Allows to read and write custom user data for players."));
builder.RequireTarget(); builder.RequireTarget();
builder.ParamText(P("groupName")) builder.ParamText(P("groupName"));
.OptionalParams() builder.OptionalParams();
.ParamText(P("dataName")) builder.ParamText(P("dataName"));
.Describe(P("Reads user data stored for targeted user under group" builder.Describe(F("Reads user data stored for targeted user under group"
@ "{$TextEmphasis `groupName`} and name" @ "{$TextEmphasis `groupName`} and name"
@ "{$TextEmphasis `dataName`}. If {$TextEmphasis `dataName`} is" @ "{$TextEmphasis `dataName`}. If {$TextEmphasis `dataName`} is"
@ "omitted, the data inside the whjole group will be read.")); @ "omitted, the data inside the whole group will be read."));
builder.SubCommand(P("write")) builder.SubCommand(P("write"));
.ParamText(P("groupName")) builder.ParamText(P("groupName"));
.ParamText(P("dataName")) builder.ParamText(P("dataName"));
.ParamObject(P("newData")) builder.ParamJSON(P("newData"));
.Describe(P("Stores new user data {$TextEmphasis `newData`} for" builder.Describe(F("Stores new user data {$TextEmphasis `newData`} for"
@ "targeted user under group {$TextEmphasis `groupName`} and name" @ "targeted user under group {$TextEmphasis `groupName`} and name"
@ "{$TextEmphasis `dataName`}.")); @ "{$TextEmphasis `dataName`}."));
} }
@ -46,74 +45,85 @@ protected function BuildData(CommandDataBuilder builder)
protected function ExecutedFor( protected function ExecutedFor(
EPlayer target, EPlayer target,
CallData arguments, CallData arguments,
EPlayer instigator) EPlayer instigator,
{ CommandPermissions permissions
) {
local AcediaObject userData; local AcediaObject userData;
local Text groupName, dataName;
if (arguments.subCommandName.IsEmpty()) groupName = arguments.parameters.GetText(P("groupName"));
{ dataName = arguments.parameters.GetText(P("dataName"));
target userData = arguments.parameters.GetItem(P("newData"));
.GetIdentity() if (arguments.subCommandName.IsEmpty()) {
.ReadPersistentData( ReadUserData(target, groupName, dataName);
arguments.parameters.GetText(P("groupName")),
arguments.parameters.GetText(P("dataName")))
.connect = UserDataRead;
} }
else else {
{ WriteUserData(target, groupName, dataName, userData);
userData = arguments.parameters.GetHashTable(P("newData"));
target
.GetIdentity()
.WritePersistentData(
arguments.parameters.GetText(P("groupName")),
arguments.parameters.GetText(P("dataName")),
userData);
} }
playerQueue[playerQueue.length] = target; _.memory.Free(dataName);
target.NewRef(); _.memory.Free(groupName);
} }
private final function UserDataRead( private final function ReadUserData(
Database.DBQueryResult result, EPlayer targetPlayer,
AcediaObject userData, BaseText groupName,
Database source) BaseText dataName)
{ {
local User identity;
local AcediaObject rawData;
local MutableText dataAsJSON;
local Text targetPlayerName; local Text targetPlayerName;
local EPlayer targetPlayer;
local MutableText asJSON;
if (playerQueue.length <= 0) identity = targetPlayer.GetIdentity();
{ if (identity == none) {
targetPlayer
.BorrowConsole()
.UseColorOnce(_.color.TextFailure)
.Write(F("There was an internal error with `userdata` command. "))
.Write(P("Please report it!"));
return;
}
targetPlayer = playerQueue[0];
playerQueue.Remove(0, 1);
if (result != DBR_Success)
{
targetPlayer
.BorrowConsole()
.UseColorOnce(_.color.TextFailure)
.Write(F("There was an error reading user data, error code: "))
.WriteLine(_.text.FromInt(int(result)));
return; return;
} }
targetPlayerName = targetPlayer.GetName(); targetPlayerName = targetPlayer.GetName();
asJSON = _.json.PrettyPrint(userData); rawData = identity.GetPersistentData(groupName, dataName);
dataAsJSON = _.json.PrettyPrint(rawData);
targetPlayer.BorrowConsole() targetPlayer.BorrowConsole()
.Write(F("{$TextPositive User data for player}")) .Write(F("User data for player "))
.Write(targetPlayerName) .Write(targetPlayerName)
.Write(P(":")) .Write(P(": "))
.WriteLine(asJSON); .WriteLine(dataAsJSON);
_.memory.Free(targetPlayer); _.memory.Free(dataAsJSON);
_.memory.Free(asJSON); _.memory.Free(rawData);
_.memory.Free(targetPlayerName); _.memory.Free(targetPlayerName);
_.memory.Free(identity);
} }
defaultproperties private final function WriteUserData(
EPlayer targetPlayer,
BaseText groupName,
BaseText dataName,
AcediaObject rawData)
{ {
local User identity;
local Text targetPlayerName;
identity = targetPlayer.GetIdentity();
if (identity == none) {
return;
}
targetPlayerName = targetPlayer.GetName();
if (identity.SetPersistentData(groupName, dataName, rawData))
{
targetPlayer.BorrowConsole()
.Write(P("User data for player "))
.Write(targetPlayerName)
.WriteLine(F(" was {$TextPositive successfully} changed!"));
}
else
{
targetPlayer.BorrowConsole()
.Write(P("User data for player "))
.Write(targetPlayerName)
.WriteLine(F(" has {$TextPositive failed} to change!"));
}
_.memory.Free(targetPlayerName);
_.memory.Free(identity);
}
defaultproperties {
preferredName = "userdata"
} }

112
sources/Features/FutileChat/FutilityChat.uc

@ -1,6 +1,6 @@
/** /**
* Config object for `FutilityChat_Feature`. * Config class for storing map lists.
* Copyright 2022 Anton Tarasenko * Copyright 2022-2023 Anton Tarasenko
*------------------------------------------------------------------------------ *------------------------------------------------------------------------------
* This file is part of Acedia. * This file is part of Acedia.
* *
@ -21,8 +21,7 @@ class FutilityChat extends FeatureConfig
perobjectconfig perobjectconfig
config(FutilityChat); config(FutilityChat);
enum ChatColorSetting enum ChatColorSetting {
{
CCS_DoNothing, CCS_DoNothing,
CCS_TeamColorForced, CCS_TeamColorForced,
CCS_ConfigColorForced, CCS_ConfigColorForced,
@ -30,16 +29,45 @@ enum ChatColorSetting
CCS_ConfigColorCustom CCS_ConfigColorCustom
}; };
var public config ChatColorSetting colorSetting; /// How to color text chat messages?
var public config Color configuredColor; ///
var public config float teamColorModifier; /// 1. `CCS_DoNothing` - do not change color in any way;
/// 2. `CCS_TeamColorForced` - force players' team colors for
/// their messages;
/// 3. `CCS_ConfigColorForced` - force `configuredColor` value for
/// players' messages;
/// 4. `CCS_TeamColorCustom` - use players' team colors for
/// their messages by default, but allow to change color with formatted tags
/// (e.g. "Stop right there, {$crimson criminal} scum!");
/// 5. `CCS_ConfigColorCustom` - use `configuredColor` value for
/// messages by default, but allow to change color with formatted
/// tags (e.g. "Stop right there, {$crimson criminal} scum!");
///
/// Default is `CCS_DoNothing`, corresponding to vanilla behaviour.
var public config ChatColorSetting colorSetting;
/// Color that will be used if either of `CCS_ConfigColorForced` or
/// `CCS_ConfigColorCustom` options were used in `colorSetting`.
/// Default value is white: (R=255,G=255,B=255,A=255), has no vanilla
/// equivalent.
var public config Color configuredColor;
/// Allows to modify team color's value for the chat messages
/// (if either of `CCS_TeamColorForced` or `CCS_TeamColorCustom` options
/// were used) to be lighter or darker.
/// This value is clamped between -1 and 1:
///
/// * `0` means using the same color;
/// * range (0; 1) - gives you lighter colors (`1` being white);
/// * range (-1; 0) - gives you darker colors (`-1` being black);
///
/// Default value is `0.6`, has no vanilla equivalent.
var public config float teamColorModifier;
protected function HashTable ToData() protected function HashTable ToData() {
{
local HashTable data; local HashTable data;
local Text colorAsText; local Text colorAsText;
data = __().collections.EmptyHashTable(); data = __().collections.EmptyHashTable();
data.SetString(P("colorSetting"), string(colorSetting)); data.SetString(P("colorSetting"), StringFromColorSetting(colorSetting));
colorAsText = _.color.ToText(configuredColor); colorAsText = _.color.ToText(configuredColor);
data.SetItem(P("configuredColor"), colorAsText); data.SetItem(P("configuredColor"), colorAsText);
_.memory.Free(colorAsText); _.memory.Free(colorAsText);
@ -47,24 +75,21 @@ protected function HashTable ToData()
return data; return data;
} }
protected function FromData(HashTable source) protected function FromData(HashTable source) {
{
local Text storedText; local Text storedText;
if (source == none) {
return; if (source != none) {
storedText = source.GetText(P("colorSetting"));
colorSetting = ColorSettingFromText(storedText);
_.memory.Free(storedText);
storedText = source.GetText(P("configuredColor"));
_.color.Parse(storedText, configuredColor);
_.memory.Free(storedText);
teamColorModifier = source.GetFloat(P("teamColorModifier"), 0.5);
} }
storedText = source.GetText(P("colorSetting"));
colorSetting = ColorSettingFromText(storedText);
_.memory.Free(storedText);
storedText = source.GetText(P("configuredColor"));
_.color.Parse(storedText, configuredColor);
_.memory.Free(storedText);
teamColorModifier = source.GetFloat(P("teamColorModifier"), 0.5);
} }
private function ChatColorSetting ColorSettingFromText( private function ChatColorSetting ColorSettingFromText(BaseText permissions) {
BaseText permissions)
{
if (permissions == none) { if (permissions == none) {
return CCS_DoNothing; return CCS_DoNothing;
} }
@ -83,17 +108,34 @@ private function ChatColorSetting ColorSettingFromText(
return CCS_DoNothing; return CCS_DoNothing;
} }
protected function DefaultIt() private function string StringFromColorSetting(ChatColorSetting permissions) {
{ if (permissions == CCS_DoNothing) {
colorSetting = CCS_DoNothing; return "DoNothing";
configuredColor = _.color.RGB(255, 255, 255); }
teamColorModifier = 0.6; if (permissions == CCS_TeamColorForced) {
return "TeamColorForced";
}
if (permissions == CCS_ConfigColorForced) {
return "ConfigColorForced";
}
if (permissions == CCS_TeamColorCustom) {
return "TeamColorCustom";
}
if (permissions == CCS_ConfigColorCustom) {
return "ConfigColorCustom";
}
return "DoNothing";
}
protected function DefaultIt() {
colorSetting = CCS_DoNothing;
configuredColor = _.color.RGB(255, 255, 255);
teamColorModifier = 0.6;
} }
defaultproperties defaultproperties {
{
configName = "FutilityChat" configName = "FutilityChat"
colorSetting = CCS_DoNothing colorSetting = CCS_DoNothing
configuredColor = (R=255,G=255,B=255,A=255) configuredColor = (R=255,G=255,B=255,A=255)
teamColorModifier = 0.6 teamColorModifier = 0.6
} }

114
sources/Features/FutileChat/FutilityChat_Feature.uc

@ -1,6 +1,6 @@
/** /**
* This feature allows to configure color of text chat messages. * Config class for storing map lists.
* Copyright 2022 Anton Tarasenko * Copyright 2022-2023 Anton Tarasenko
*------------------------------------------------------------------------------ *------------------------------------------------------------------------------
* This file is part of Acedia. * This file is part of Acedia.
* *
@ -20,123 +20,82 @@
class FutilityChat_Feature extends Feature class FutilityChat_Feature extends Feature
dependson(FutilityChat); dependson(FutilityChat);
// How to color text chat messages? var private /*config*/ FutilityChat.ChatColorSetting colorSetting;
// 1. `CCS_DoNothing` - do not change color in any way; var private /*config*/ Color configuredColor;
// 2. `CCS_TeamColorForced` - force players' team colors for var private /*config*/ float teamColorModifier;
// their messages;
// 3. `CCS_ConfigColorForced` - force `configuredColor` value for
// players' messages;
// 4. `CCS_TeamColorCustom` - use players' team colors for
// their messages by default, but allow to change color with formatted
// tags (e.g. "Stop right there, {$crimson criminal} scum!");
// 5. `CCS_ConfigColorCustom` - use `configuredColor` value for
// messages by default, but allow to change color with formatted
// tags (e.g. "Stop right there, {$crimson criminal} scum!");
// Default is `CCS_DoNothing`, corresponding to vanilla behaviour.
var private /*config*/ FutilityChat.ChatColorSetting colorSetting;
// Color that will be used if either of `CCS_ConfigColorForced` or
// `CCS_ConfigColorCustom` options were used in `colorSetting`.
// Default value is white: (R=255,G=255,B=255,A=255),
// has no vanilla equivalent.
var private /*config*/ Color configuredColor;
// Allows to modify team color's value for the chat messages
// (if either of `CCS_TeamColorForced` or `CCS_TeamColorCustom` options
// were used) to be lighter or darker.
// This value is clamped between -1 and 1.
// * `0` means using the same color;
// * range (0; 1) - gives you lighter colors (`1` being white);
// * range (-1; 0) - gives you darker colors (`-1` being black);
// Default value is `0.6`, has no vanilla equivalent.
var private /*config*/ float teamColorModifier;
// Keep track of whether we connected to necessary signals, so that we can /// Keep track of whether we connected to necessary signals, so that we can
// connect to them or disconnect from them once setting get updated /// connect to them or disconnect from them once setting get updated
var private bool connectedToSignal; var private bool connectedToSignal;
protected function OnDisabled() protected function OnEnabled() {
{ if (colorSetting != CCS_DoNothing) {
if (connectedToSignal) _.chat.OnMessage(self).connect = ReformatChatMessage;
{ }
connectedToSignal = false; }
protected function OnDisabled() {
if (colorSetting != CCS_DoNothing) {
_.chat.OnMessage(self).Disconnect(); _.chat.OnMessage(self).Disconnect();
} }
} }
protected function SwapConfig(FeatureConfig config) protected function SwapConfig(FeatureConfig config)
{ {
local bool configRequiresSignal; local bool configRequiresSignal;
local FutilityChat newConfig; local FutilityChat newConfig;
newConfig = FutilityChat(config); newConfig = FutilityChat(config);
if (newConfig == none) { if (newConfig == none) {
return; return;
} }
colorSetting = newConfig.colorSetting; colorSetting = newConfig.colorSetting;
configuredColor = newConfig.configuredColor; configuredColor = newConfig.configuredColor;
teamColorModifier = newConfig.teamColorModifier; teamColorModifier = newConfig.teamColorModifier;
configRequiresSignal = (colorSetting != CCS_DoNothing); configRequiresSignal = (colorSetting != CCS_DoNothing);
// Enable or disable censoring if `IsAnyCensoringEnabled()`'s response
// has changed.
if (!connectedToSignal && configRequiresSignal)
{
connectedToSignal = true;
_.chat.OnMessage(self).connect = ReformatChatMessage;
}
if (connectedToSignal && !configRequiresSignal)
{
connectedToSignal = false;
_.chat.OnMessage(self).Disconnect();
}
} }
private function bool ReformatChatMessage( private function bool ReformatChatMessage(
EPlayer sender, EPlayer sender,
MutableText message, MutableText message,
bool teamMessage) bool teamMessage
{ ) {
local Text messageCopy; local Text messageCopy;
local BaseText.Formatting defaultFormatting; local BaseText.Formatting defaultFormatting;
if (sender == none) return true; if (sender == none) return true;
if (message == none) return true; if (message == none) return true;
if (colorSetting == CCS_DoNothing) return true; if (colorSetting == CCS_DoNothing) return true;
defaultFormatting.isColored = true; defaultFormatting.isColored = true;
if ( colorSetting == CCS_TeamColorForced if (colorSetting == CCS_TeamColorForced || colorSetting == CCS_TeamColorCustom) {
|| colorSetting == CCS_TeamColorCustom)
{
defaultFormatting.color = ModColor(sender.GetTeamColor()); defaultFormatting.color = ModColor(sender.GetTeamColor());
} } else {
else {
defaultFormatting.color = configuredColor; defaultFormatting.color = configuredColor;
} }
if (message.StartsWith(P("|"))) { if (message.StartsWith(P("|"))) {
message.Remove(0, 1); message.Remove(0, 1);
} } else if (colorSetting != CCS_TeamColorForced && colorSetting != CCS_ConfigColorForced) {
else if ( colorSetting != CCS_TeamColorForced
&& colorSetting != CCS_ConfigColorForced)
{
messageCopy = message.Copy(); messageCopy = message.Copy();
class'FormattingStringParser'.static class'FormattingStringParser'.static.ParseFormatted(messageCopy, message.Clear());
.ParseFormatted(messageCopy, message.Clear());
_.memory.Free(messageCopy); _.memory.Free(messageCopy);
} }
message.ChangeDefaultFormatting(defaultFormatting); message.ChangeDefaultFormatting(defaultFormatting);
return true; return true;
} }
private function Color ModColor(Color inputColor) private function Color ModColor(Color inputColor) {
{
local Color mixColor; local Color mixColor;
local Color outputColor; local Color outputColor;
local float clampedModifier; local float clampedModifier;
if (Abs(teamColorModifier) < 0.001) { if (Abs(teamColorModifier) < 0.001) {
return inputColor; return inputColor;
} }
clampedModifier = FClamp(teamColorModifier, -1.0, 1.0); clampedModifier = FClamp(teamColorModifier, -1.0, 1.0);
if (clampedModifier > 0) { if (clampedModifier > 0) {
mixColor = _.color.White; mixColor = _.color.White;
} } else {
else
{
mixColor = _.color.Black; mixColor = _.color.Black;
clampedModifier *= -1.0; clampedModifier *= -1.0;
} }
@ -147,7 +106,6 @@ private function Color ModColor(Color inputColor)
return outputColor; return outputColor;
} }
defaultproperties defaultproperties {
{
configClass = class'FutilityChat' configClass = class'FutilityChat'
} }

164
sources/Features/FutileNickames/FutilityNicknames.uc

@ -1,6 +1,6 @@
/** /**
* Config object for `FutileNickames_Feature`. * Config class for storing map lists.
* Copyright 2022 Anton Tarasenko * Copyright 2022-2023 Anton Tarasenko
*------------------------------------------------------------------------------ *------------------------------------------------------------------------------
* This file is part of Acedia. * This file is part of Acedia.
* *
@ -21,62 +21,108 @@ class FutilityNicknames extends FeatureConfig
perobjectconfig perobjectconfig
config(FutilityNicknames); config(FutilityNicknames);
enum NicknameSpacesAction enum NicknameSpacesAction {
{
NSA_DoNothing, NSA_DoNothing,
NSA_Trim, NSA_Trim,
NSA_Simplify NSA_Simplify
}; };
enum NicknameColorPermissions enum NicknameColorPermissions {
{
NCP_ForbidColor, NCP_ForbidColor,
NCP_ForceTeamColor, NCP_ForceTeamColor,
NCP_ForceSingleColor, NCP_ForceSingleColor,
NCP_AllowAnyColor NCP_AllowAnyColor
}; };
var public config NicknameSpacesAction spacesAction; /// How to treat whitespace characters inside players' nicknames:
var public config NicknameColorPermissions colorPermissions; ///
var public config bool replaceSpacesWithUnderscores; /// * `NSA_DoNothing` - does nothing, leaving whitespaces as they are;
var public config bool removeSingleQuotationMarks; /// * `NSA_Trim` - removes leading and trailing whitespaces for nicknames;
var public config bool removeDoubleQuotationMarks; /// * `NSA_Simplify` - removes leading and trailing whitespaces
var public config bool correctEmptyNicknames; /// for nicknames, also reducing a sequence of whitespaces inside
var public config int maxNicknameLength; /// nickname to a single space, e.g. "my nick" becomes "my nick".
var public config array<string> fallbackNickname; ///
/// Default is `NSA_DoNothing`, same as on vanilla.
var public config NicknameSpacesAction spacesAction;
/// How to treat colored nicknames:
///
/// * `NCP_ForbidColor` - completely strips down any color from nicknames;
/// * `NCP_ForceTeamColor` - forces all nicknames to have player's current
/// team's color;
/// * `NCP_ForceSingleColor` - allows nickname to be painted with a single
/// color (sets nickname's color to that of the first character);
/// * `NCP_AllowAnyColor` - allows nickname to be colored in any way player
/// wants.
/// Default is `NCP_ForbidColor`, same as on vanilla.
var public config NicknameColorPermissions colorPermissions;
/// Set this to `true` if you wish to replace all whitespace characters with
/// underscores and `false` to leave them as is.
/// Default is `true`, same as on vanilla. However there is one difference:
/// Futility replaces all whitespace characters (including tabulations,
/// non-breaking spaces, etc.) instead of only ' '.
var public config bool replaceSpacesWithUnderscores;
/// Set this to `true` to remove single 'quotation marks' and `false` to
/// leave them. Default is `false`, same as on vanilla.
var public config bool removeSingleQuotationMarks;
/// Set this to `true` to remove dobule 'quotation marks' and `false` to
/// leave them. Default is `true`, same as on vanilla.
var public config bool removeDoubleQuotationMarks;
/// Should we replace empty player nicknames with a random fallback nickname
/// (defined in `fallbackNickname` array)?
var public config bool correctEmptyNicknames;
/// Max allowed nickname length. Negative values disable any length limits.
///
/// NOTE #1: `0` resets all nicknames to be empty and,
/// if `correctEmptyNicknames` is set to `true`, they will be replaced with
/// one of the fallback nicknames (see `correctEmptyNicknames` and
/// `fallbackNickname`).
///
/// NOTE #2: Because of how color swapping in vanilla Killing Floor works,
/// every color swap makes text count as being about 4 characters longer.
/// So if one uses too many colors in the nickname, for drawing functions
/// it will appear to be longer than it actually is and it *will* mess up
/// UI. Unless you are using custom HUD it is recommended to keep this value
/// at default `20` and forbid colored nicknames (by setting
/// `colorPermissions=NCP_ForbidColor`). Or to allow only one color (by setting
/// `colorPermissions=NCP_ForceSingleColor` or
/// `colorPermissions=NCP_ForceTeamColor`) and reducing `maxNicknameLength` to
/// `16` (20 characters - 4 for color swap).
/// If you want to increase the limit above that, you can also do your own
/// research by testing nicknames of various length on screen resolutions you
/// care about.
var public config int maxNicknameLength;
/// Array of fallback nicknames that will be used to replace any empty nicknames
/// if `correctEmptyNicknames` is set to `true`.
var public config array<string> fallbackNickname;
protected function HashTable ToData() protected function HashTable ToData() {
{ local int i;
local int i;
local ArrayList fallbackNicknamesData; local ArrayList fallbackNicknamesData;
local HashTable data; local HashTable data;
data = __().collections.EmptyHashTable(); data = __().collections.EmptyHashTable();
data.SetString(P("spacesAction"), string(spacesAction)); data.SetString(P("spacesAction"), string(spacesAction));
data.SetString(P("colorPermissions"), string(colorPermissions)); data.SetString(P("colorPermissions"), string(colorPermissions));
data.SetBool( P("replaceSpacesWithUnderscores"), data.SetBool(P("replaceSpacesWithUnderscores"), replaceSpacesWithUnderscores);
replaceSpacesWithUnderscores); data.SetBool(P("removeSingleQuotationMarks"), removeSingleQuotationMarks);
data.SetBool( P("removeSingleQuotationMarks"), data.SetBool(P("removeDoubleQuotationMarks"), removeDoubleQuotationMarks);
removeSingleQuotationMarks);
data.SetBool( P("removeDoubleQuotationMarks"),
removeDoubleQuotationMarks);
data.SetBool(P("correctEmptyNicknames"), correctEmptyNicknames); data.SetBool(P("correctEmptyNicknames"), correctEmptyNicknames);
data.SetInt(P("maxNicknameLength"), maxNicknameLength); data.SetInt(P("maxNicknameLength"), maxNicknameLength);
fallbackNicknamesData = __().collections.EmptyArrayList(); fallbackNicknamesData = __().collections.EmptyArrayList();
for (i = 0; i < fallbackNickname.length; i += 1)
{ for (i = 0; i < fallbackNickname.length; i += 1) {
fallbackNicknamesData.AddItem( fallbackNicknamesData.AddItem(__().text.FromFormattedString(fallbackNickname[i]));
__().text.FromFormattedString(fallbackNickname[i]));
} }
data.SetItem(P("fallbackNickname"), fallbackNicknamesData); data.SetItem(P("fallbackNickname"), fallbackNicknamesData);
_.memory.Free(fallbackNicknamesData); _.memory.Free(fallbackNicknamesData);
return data; return data;
} }
protected function FromData(HashTable source) protected function FromData(HashTable source) {
{ local int i;
local int i; local Text nextNickName, storedText;
local Text nextNickName, storedText;
local ArrayList fallbackNicknamesData; local ArrayList fallbackNicknamesData;
if (source == none) { if (source == none) {
return; return;
} }
@ -86,25 +132,20 @@ protected function FromData(HashTable source)
storedText = source.GetText(P("colorPermissions")); storedText = source.GetText(P("colorPermissions"));
colorPermissions = ColorPermissionsFromText(storedText); colorPermissions = ColorPermissionsFromText(storedText);
_.memory.Free(storedText); _.memory.Free(storedText);
replaceSpacesWithUnderscores = replaceSpacesWithUnderscores = source.GetBool(P("replaceSpacesWithUnderscores"), true);
source.GetBool(P("replaceSpacesWithUnderscores"), true); removeSingleQuotationMarks = source.GetBool(P("removeSingleQuotationMarks"), true);
removeSingleQuotationMarks = removeDoubleQuotationMarks = source.GetBool(P("removeDoubleQuotationMarks"), true);
source.GetBool(P("removeSingleQuotationMarks"), true);
removeDoubleQuotationMarks =
source.GetBool(P("removeDoubleQuotationMarks"), true);
correctEmptyNicknames = source.GetBool(P("correctEmptyNicknames"), true); correctEmptyNicknames = source.GetBool(P("correctEmptyNicknames"), true);
maxNicknameLength = source.GetInt(P("correctEmptyNicknames"), 20); maxNicknameLength = source.GetInt(P("correctEmptyNicknames"), 20);
fallbackNicknamesData = source.GetArrayList(P("fallbackNickname")); fallbackNicknamesData = source.GetArrayList(P("fallbackNickname"));
if (fallbackNickname.length > 0) { if (fallbackNickname.length > 0) {
fallbackNickname.length = 0; fallbackNickname.length = 0;
} }
for (i = 0; i < fallbackNicknamesData.GetLength(); i += 1) for (i = 0; i < fallbackNicknamesData.GetLength(); i += 1) {
{
nextNickName = fallbackNicknamesData.GetText(i); nextNickName = fallbackNicknamesData.GetText(i);
if (nextNickName != none) { if (nextNickName != none) {
fallbackNickname[i] = nextNickName.ToFormattedString(); fallbackNickname[i] = nextNickName.ToFormattedString();
} } else {
else {
fallbackNickname[i] = ""; fallbackNickname[i] = "";
} }
_.memory.Free(nextNickName); _.memory.Free(nextNickName);
@ -112,8 +153,7 @@ protected function FromData(HashTable source)
_.memory.Free(fallbackNicknamesData); _.memory.Free(fallbackNicknamesData);
} }
private function NicknameSpacesAction SpaceActionFromText(BaseText action) private function NicknameSpacesAction SpaceActionFromText(BaseText action) {
{
if (action == none) { if (action == none) {
return NSA_DoNothing; return NSA_DoNothing;
} }
@ -129,9 +169,7 @@ private function NicknameSpacesAction SpaceActionFromText(BaseText action)
return NSA_DoNothing; return NSA_DoNothing;
} }
private function NicknameColorPermissions ColorPermissionsFromText( private function NicknameColorPermissions ColorPermissionsFromText(BaseText permissions) {
BaseText permissions)
{
if (permissions == none) { if (permissions == none) {
return NCP_ForbidColor; return NCP_ForbidColor;
} }
@ -150,15 +188,14 @@ private function NicknameColorPermissions ColorPermissionsFromText(
return NCP_ForbidColor; return NCP_ForbidColor;
} }
protected function DefaultIt() protected function DefaultIt() {
{ spacesAction = NSA_DoNothing;
spacesAction = NSA_DoNothing; colorPermissions = NCP_ForbidColor;
colorPermissions = NCP_ForbidColor; replaceSpacesWithUnderscores = true;
replaceSpacesWithUnderscores = true; removeSingleQuotationMarks = false;
removeSingleQuotationMarks = false; removeDoubleQuotationMarks = true;
removeDoubleQuotationMarks = true; correctEmptyNicknames = true;
correctEmptyNicknames = true; maxNicknameLength = 20;
maxNicknameLength = 20;
if (fallbackNickname.length > 0) { if (fallbackNickname.length > 0) {
fallbackNickname.length = 0; fallbackNickname.length = 0;
} }
@ -174,16 +211,15 @@ protected function DefaultIt()
fallbackNickname[9] = "Bug Meat"; fallbackNickname[9] = "Bug Meat";
} }
defaultproperties defaultproperties {
{
configName = "FutilityNicknames" configName = "FutilityNicknames"
spacesAction = NSA_DoNothing spacesAction = NSA_DoNothing
colorPermissions = NCP_ForbidColor colorPermissions = NCP_ForbidColor
replaceSpacesWithUnderscores = true replaceSpacesWithUnderscores = true
removeSingleQuotationMarks = false removeSingleQuotationMarks = false
removeDoubleQuotationMarks = true removeDoubleQuotationMarks = true
correctEmptyNicknames = true correctEmptyNicknames = true
maxNicknameLength = 20 maxNicknameLength = 20
fallbackNickname(0) = "Fresh Meat" fallbackNickname(0) = "Fresh Meat"
fallbackNickname(1) = "Rotten Meat" fallbackNickname(1) = "Rotten Meat"
fallbackNickname(2) = "Troll Meat" fallbackNickname(2) = "Troll Meat"

368
sources/Features/FutileNickames/FutilityNicknames_Feature.uc

@ -1,9 +1,6 @@
/** /**
* This feature allows to configure nickname limitations for the server. * Config class for storing map lists.
* It allows you to customize vanilla limitations for nickname length and * Copyright 2022-2023 Anton Tarasenko
* color with those of your own design. Enabling this feature overwrites
* default behaviour.
* Copyright 2022 Anton Tarasenko
*------------------------------------------------------------------------------ *------------------------------------------------------------------------------
* This file is part of Acedia. * This file is part of Acedia.
* *
@ -23,224 +20,133 @@
class FutilityNicknames_Feature extends Feature class FutilityNicknames_Feature extends Feature
dependson(FutilityNicknames); dependson(FutilityNicknames);
/** //! This feature's functionality is rather simple, but we will still break up
* This feature's functionality is rather simple, but we will still break up //! what its various components are.
* what its various components are. //!
* //! Fallback nicknames are picked at random from
* Fallback nicknames are picked at random from //! the `fallbackNicknames` array. This is done by copying that array into
* the `fallbackNicknames` array. This is done by copying that array into //! `unusedNicknames` and then picking and removing its random elements each
* `unusedNicknames` and then picking and removing its random elements each //! time we need a fallback. Once `unusedNicknames` is empty - it is copied from
* time we need a fallback. Once `unusedNicknames` is empty - it is copied from //! `fallbackNicknames` once again, letting already used nicknames to be reused.
* `fallbackNicknames` once again, letting already used nicknames to be reused. //! `unusedNicknames` contains same references as `fallbackNicknames`,
* `unusedNicknames` contains same references as `fallbackNicknames`, //! so they need to be separately deallocated and should also be forgotten once
* so they need to be separately deallocated and should also be forgotten once //! `fallbackNicknames` are deallocated`.
* `fallbackNicknames` are deallocated`. //! This is implemented inside `PickNextFallback()` method.
* This is implemented inside `PickNextFallback()` method. //!
* //! Nickname changes are applied inside `CensorNickname()` method that uses
* Nickname changes are applied inside `CensorNickname()` method that uses //! several auxiliary methods to perform different stages of "censoring".
* several auxiliary methods to perform different stages of "censoring". //! Censoring is performed:
* Censoring is performed: //! 1. On any player's name change
* 1. On any player's name change //! (using `OnPlayerNameChanging()` signal, connected to
* (using `OnPlayerNameChanging()` signal, connected to //! `HandleNicknameChange()`);
* `HandleNicknameChange()`); //! 2. When new player logins (using `OnNewPlayer()` signal,
* 2. When new player logins (using `OnNewPlayer()` signal, //! conneted to `CensorOriginalNickname()`) to enforce our own
* conneted to `CensorOriginalNickname()`) to enforce our own //! handling of player's original nickname.
* handling of player's original nickname;
* 3. When censoring is re-activated.
* In case all censoring options of this feature are disabled
* (checked by `IsAnyCensoringEnabled()`) - we do not attempt to
* catch any events or do anything at all.
* If settings change mid-execution, this feature might need to
* enable or disable censoring on-the-fly. To accomplish that we
* remember current status inside `censoringNicknames` boolean
* variable and enable/disable events if required by settings.
* So whenever we re-activate censoring we also need to update
* ("censor") current players' nicknames - a third occasion to
* call `CensorNickname()`, implemented inside
* `CensorCurrentPlayersNicknames()`.
*/
// How to treat whitespace characters inside players' nicknames.
// * `NSA_DoNothing` - does nothing, leaving whitespaces as they are;
// * `NSA_Trim` - removes leading and trailing whitespaces for nicknames;
// * `NSA_Simplify` - removes leading and trailing whitespaces
// for nicknames, also reducing a sequence of whitespaces inside
// nickname to a single space, e.g. "my nick" becomes "my nick".
// Default is `NSA_DoNothing`, same as on vanilla.
var private /*config*/ FutilityNicknames.NicknameSpacesAction spacesAction; var private /*config*/ FutilityNicknames.NicknameSpacesAction spacesAction;
// How to treat colored nicknames.
// * `NCP_ForbidColor` - completely strips down any color from nicknames;
// * `NCP_ForceTeamColor` - forces all nicknames to have player's current
// team's color;
// * `NCP_ForceSingleColor` - allows nickname to be painted with a single
// color (sets nickname's color to that of the first character);
// * `NCP_AllowAnyColor` - allows nickname to be colored in any way player
// wants.
// Default is `NCP_ForbidColor`, same as on vanilla.
var private /*config*/ FutilityNicknames.NicknameColorPermissions colorPermissions; var private /*config*/ FutilityNicknames.NicknameColorPermissions colorPermissions;
var private /*config*/ bool replaceSpacesWithUnderscores;
var private /*config*/ bool removeSingleQuotationMarks;
var private /*config*/ bool removeDoubleQuotationMarks;
var private /*config*/ int maxNicknameLength;
var private /*config*/ bool correctEmptyNicknames;
var private /*config*/ array<Text> fallbackNickname;
// Set this to `true` if you wish to replace all whitespace characters with /// Guaranteed order of applying changes (only chosen ones) is as following:
// underscores and `false` to leave them as is. ///
// Default is `true`, same as on vanilla. However there is one difference: /// 1. Trim/simplify spaces;
// Futility replaces all whitespace characters (including tabulations, /// 2. Remove single and double quotation marks;
// non-breaking spaces, etc.) instead of only ' '. /// 3. Enforce max limit of nickname's length;
var private /*config*/ bool replaceSpacesWithUnderscores; /// 4. Replace empty nickname with fallback nickname (no further changes
// Set this to `true` to remove single 'quotation marks' and `false` to /// will be applied to fallback nickname in that case);
// leave them. Default is `false`, same as on vanilla. /// 5. Enforce color limitation;
var private /*config*/ bool removeSingleQuotationMarks; /// 6. Replace remaining whitespaces with underscores.
// Set this to `true` to remove dobule 'quotation marks' and `false` to ///
// leave them. Default is `true`, same as on vanilla. /// NOTE #1: as follows from the instruction described above, no changes will
var private /*config*/ bool removeDoubleQuotationMarks; /// ever be applied to fallback nicknames (unless player's nickname coincides
/// with one by pure accident).
// Max allowed nickname length. Negative values disable any length limits. ///
// /// NOTE #2: whitespaces inside steam nicknames are converted into underscores
// NOTE #1: `0` resets all nicknames to be empty and, /// before they are passed into the game and this is a change Futility
// if `correctEmptyNicknames` is set to `true`, they will be replaced with /// cannot currently abort. Therefore all changes relevant to whitespaces inside
// one of the fallback nicknames /// nicknames will only be applied to in-game changes.
// (see `correctEmptyNicknames` and `fallbackNickname`).
// NOTE #2: Because of how color swapping in vanilla Killing Floor works,
// every color swap makes text count as being about 4 characters longer.
// So if one uses too many colors in the nickname, for drawing functions
// it will appear to be longer than it actually is and it *will* mess up
// UI. Unless you are using custom HUD it is recommended to keep this value
// at default `20` and forbid colored nicknames
// (by setting `colorPermissions=NCP_ForbidColor`). Or to allow only one
// color (by setting `colorPermissions=NCP_ForceSingleColor` or
// `colorPermissions=NCP_ForceTeamColor`) and reducing `maxNicknameLength`
// to `16` (20 characters - 4 for color swap).
// If you want to increase the limit above that, you can also do your
// own research by testing nicknames of various length on
// screen resolutions you care about.
var private /*config*/ int maxNicknameLength;
// Should we replace empty player nicknames with a random fallback nickname /// Nicknames from `fallbackNickname` that can still be picked in the current
// (defined in `fallbackNickname` array)? /// rotation.
var private /*config*/ bool correctEmptyNicknames;
// Array of fallback nicknames that will be used to replace any empty nicknames
// if `correctEmptyNicknames` is set to `true`.
var private /*config*/ array<Text> fallbackNickname;
// Guaranteed order of applying changes (only chosen ones) is as following:
// 1. Trim/simplify spaces;
// 2. Remove single and double quotation marks;
// 3. Enforce max limit of nickname's length;
// 4. Replace empty nickname with fallback nickname (no further changes
// will be applied to fallback nickname in that case);
// 5. Enforce color limitation;
// 6. Replace remaining whitespaces with underscores.
//
// NOTE #1: as follows from the instruction described above, no changes will
// ever be applied to fallback nicknames (unless player's nickname
// coincides with one by pure accident).
// NOTE #2: whitespaces inside steam nicknames are converted into underscores
// before they are passed into the game and this is a change Futility
// cannot currently abort.
// Therefore all changes relevant to whitespaces inside nicknames will only
// be applied to in-game changes.
// Nicknames from `fallbackNickname` that can still be picked in
// the current rotation.
var private array<Text> unusedNicknames; var private array<Text> unusedNicknames;
// Are we currently censoring nicknames?
// Set to `false` if none of the feature's options require
// any action (censoring) and, therefore, we do not listen to any signals.
var private bool censoringNicknames;
var private const int CODEPOINT_UNDERSCORE; var private const int CODEPOINT_UNDERSCORE;
protected function OnDisabled() protected function OnEnabled() {
{ if (IsAnyCensoringEnabled()) {
_.memory.FreeMany(fallbackNickname); // Do this before adding event handler to avoid censoring nicknames
// Free this `Text` data - it will be refilled with `SwapConfig()` // second time (censoring nickname will trigger `OnPlayerNameChanging()`
// if this feature is ever reenabled // signal)
if (fallbackNickname.length > 0) CensorCurrentPlayersNicknames();
{ _.players.OnPlayerNameChanging(self).connect = HandleNicknameChange;
_.memory.FreeMany(fallbackNickname); _.players.OnNewPlayer(self).connect = CensorOriginalNickname;
fallbackNickname.length = 0;
unusedNicknames.length = 0;
} }
if (censoringNicknames) }
{
censoringNicknames = false; protected function OnDisabled() {
_.memory.FreeMany(fallbackNickname);
_.memory.FreeMany(unusedNicknames);
fallbackNickname.length = 0;
unusedNicknames.length = 0;
if (IsAnyCensoringEnabled()) {
_.players.OnPlayerNameChanging(self).Disconnect(); _.players.OnPlayerNameChanging(self).Disconnect();
_.players.OnNewPlayer(self).Disconnect(); _.players.OnNewPlayer(self).Disconnect();
} }
} }
protected function SwapConfig(FeatureConfig config) protected function SwapConfig(FeatureConfig config) {
{
local bool configRequiresCensoring;
local FutilityNicknames newConfig; local FutilityNicknames newConfig;
newConfig = FutilityNicknames(config); newConfig = FutilityNicknames(config);
if (newConfig == none) { if (newConfig == none) {
return; return;
} }
replaceSpacesWithUnderscores = newConfig.replaceSpacesWithUnderscores; replaceSpacesWithUnderscores = newConfig.replaceSpacesWithUnderscores;
removeSingleQuotationMarks = newConfig.removeSingleQuotationMarks; removeSingleQuotationMarks = newConfig.removeSingleQuotationMarks;
removeDoubleQuotationMarks = newConfig.removeDoubleQuotationMarks; removeDoubleQuotationMarks = newConfig.removeDoubleQuotationMarks;
correctEmptyNicknames = newConfig.correctEmptyNicknames; correctEmptyNicknames = newConfig.correctEmptyNicknames;
spacesAction = newConfig.spacesAction; spacesAction = newConfig.spacesAction;
colorPermissions = newConfig.colorPermissions; colorPermissions = newConfig.colorPermissions;
maxNicknameLength = newConfig.maxNicknameLength; maxNicknameLength = newConfig.maxNicknameLength;
configRequiresCensoring = IsAnyCensoringEnabled();
// Enable or disable censoring if `IsAnyCensoringEnabled()`'s response
// has changed.
if (!censoringNicknames && configRequiresCensoring)
{
censoringNicknames = true;
// Do this before adding event handler to
// avoid censoring nicknames second time
CensorCurrentPlayersNicknames();
_.players.OnPlayerNameChanging(self).connect = HandleNicknameChange;
_.players.OnNewPlayer(self).connect = CensorOriginalNickname;
}
if (censoringNicknames && !configRequiresCensoring)
{
censoringNicknames = false;
_.players.OnPlayerNameChanging(self).Disconnect();
_.players.OnNewPlayer(self).Disconnect();
}
SwapFallbackNicknames(newConfig); SwapFallbackNicknames(newConfig);
} }
private function Text PickNextFallback() private function SwapFallbackNicknames(FutilityNicknames newConfig) {
{ local int i;
local int pickedIndex;
local Text result; _.memory.FreeMany(fallbackNickname);
if (fallbackNickname.length <= 0) fallbackNickname.length = 0;
{ for (i = 0; i < newConfig.fallbackNickname.length; i += 1) {
// Just in case this feature is really misconfigured fallbackNickname[i] = _.text.FromFormattedString(newConfig.fallbackNickname[i]);
}
unusedNicknames = fallbackNickname;
}
private function Text PickNextFallback() {
local int pickedIndex;
local Text result;
if (fallbackNickname.length <= 0) {
// Just in case this feature is really misconfigured
return P("Fresh Meat").Copy(); return P("Fresh Meat").Copy();
} }
if (unusedNicknames.length <= 0) { if (unusedNicknames.length <= 0) {
unusedNicknames = fallbackNickname; unusedNicknames = fallbackNickname;
} }
// Pick one nickname at random. // Pick one nickname at random.
// `pickedIndex` will belong to [0; unusedNicknames.length - 1] segment. // `pickedIndex` will belong to [0; unusedNicknames.length - 1] segment.
pickedIndex = Rand(unusedNicknames.length); pickedIndex = Rand(unusedNicknames.length);
result = unusedNicknames[pickedIndex].Copy(); result = unusedNicknames[pickedIndex].Copy();
unusedNicknames.Remove(pickedIndex, 1); unusedNicknames.Remove(pickedIndex, 1);
return result; return result;
} }
protected function SwapFallbackNicknames(FutilityNicknames newConfig) private function bool IsAnyCensoringEnabled() {
{
local int i;
_.memory.FreeMany(fallbackNickname);
if (fallbackNickname.length > 0) {
fallbackNickname.length = 0;
}
for (i = 0; i < newConfig.fallbackNickname.length; i += 1)
{
fallbackNickname[i] =
_.text.FromFormattedString(newConfig.fallbackNickname[i]);
}
unusedNicknames = fallbackNickname;
}
private function bool IsAnyCensoringEnabled()
{
return ( replaceSpacesWithUnderscores return ( replaceSpacesWithUnderscores
|| removeSingleQuotationMarks || removeSingleQuotationMarks
|| removeDoubleQuotationMarks || removeDoubleQuotationMarks
@ -250,40 +156,38 @@ private function bool IsAnyCensoringEnabled()
|| spacesAction != NSA_DoNothing); || spacesAction != NSA_DoNothing);
} }
// For nickname changes mid-game. // For nickname changes mid-game.
private function HandleNicknameChange( private function HandleNicknameChange(
EPlayer affectedPlayer, EPlayer affectedPlayer,
BaseText oldName, BaseText oldName,
MutableText newName) MutableText newName
{ ) {
CensorNickname(newName, affectedPlayer); CensorNickname(newName, affectedPlayer);
} }
// For handling of player's original nicknames. // For handling of player's original nicknames.
private function CensorOriginalNickname(EPlayer affectedPlayer) private function CensorOriginalNickname(EPlayer affectedPlayer) {
{
local Text originalNickname; local Text originalNickname;
if (affectedPlayer == none) { if (affectedPlayer == none) {
return; return;
} }
originalNickname = affectedPlayer.GetOriginalName(); originalNickname = affectedPlayer.GetOriginalName();
// This will automatically trigger `OnPlayerNameChanging()` signal and // This will automatically trigger `OnPlayerNameChanging()` signal and
// our `HandleNicknameChange()` handler. // our `HandleNicknameChange()` handler.
affectedPlayer.SetName(originalNickname); affectedPlayer.SetName(originalNickname);
_.memory.Free(originalNickname); _.memory.Free(originalNickname);
} }
// For handling nicknames of players after censoring is re-activated by // For handling nicknames of players after censoring is re-activated by
// config change. // config change.
private function CensorCurrentPlayersNicknames() private function CensorCurrentPlayersNicknames() {
{ local int i;
local int i; local Text nextNickname;
local Text nextNickname; local MutableText alteredNickname;
local MutableText alteredNickname; local array<EPlayer> currentPlayers;
local array<EPlayer> currentPlayers;
currentPlayers = _.players.GetAll(); currentPlayers = _.players.GetAll();
for (i = 0; i < currentPlayers.length; i += 1) for (i = 0; i < currentPlayers.length; i += 1) {
{
nextNickname = currentPlayers[i].GetName(); nextNickname = currentPlayers[i].GetName();
alteredNickname = nextNickname.MutableCopy(); alteredNickname = nextNickname.MutableCopy();
CensorNickname(alteredNickname, currentPlayers[i]); CensorNickname(alteredNickname, currentPlayers[i]);
@ -295,10 +199,10 @@ private function CensorCurrentPlayersNicknames()
} }
} }
private function CensorNickname(MutableText nickname, EPlayer affectedPlayer) private function CensorNickname(MutableText nickname, EPlayer affectedPlayer) {
{ local Text fallback;
local Text fallback; local BaseText.Formatting newFormatting;
local BaseText.Formatting newFormatting;
if (nickname == none) return; if (nickname == none) return;
if (affectedPlayer == none) return; if (affectedPlayer == none) return;
@ -314,25 +218,21 @@ private function CensorNickname(MutableText nickname, EPlayer affectedPlayer)
if (maxNicknameLength >= 0) { if (maxNicknameLength >= 0) {
nickname.Remove(maxNicknameLength); nickname.Remove(maxNicknameLength);
} }
if (correctEmptyNicknames && nickname.IsEmpty()) if (correctEmptyNicknames && nickname.IsEmpty()) {
{
fallback = PickNextFallback(); fallback = PickNextFallback();
nickname.Append(fallback); nickname.Append(fallback);
_.memory.Free(fallback); _.memory.Free(fallback);
return; return;
} }
if (colorPermissions != NCP_AllowAnyColor) if (colorPermissions != NCP_AllowAnyColor) {
{
if (colorPermissions == NCP_ForceSingleColor) { if (colorPermissions == NCP_ForceSingleColor) {
newFormatting = nickname.GetCharacter(0).formatting; newFormatting = nickname.GetCharacter(0).formatting;
} } else if (colorPermissions == NCP_ForceTeamColor) {
else if (colorPermissions == NCP_ForceTeamColor)
{
newFormatting.isColored = true; newFormatting.isColored = true;
newFormatting.color = affectedPlayer.GetTeamColor(); newFormatting.color = affectedPlayer.GetTeamColor();
} }
// `colorPermissions == NCP_ForbidColor` // `colorPermissions == NCP_ForbidColor`
// `newFormatting` is colorless by default // `newFormatting` is colorless by default
nickname.ChangeFormatting(newFormatting); nickname.ChangeFormatting(newFormatting);
} }
if (replaceSpacesWithUnderscores) { if (replaceSpacesWithUnderscores) {
@ -340,21 +240,18 @@ private function CensorNickname(MutableText nickname, EPlayer affectedPlayer)
} }
} }
// Asusmes `nickname != none`. // Asusmes `nickname != none`.
private function ReplaceSpaces(MutableText nickname) private function ReplaceSpaces(MutableText nickname) {
{ local int i;
local int i; local MutableText nicknameCopy;
local MutableText nicknameCopy; local BaseText.Character nextCharacter, underscoreCharacter;
local BaseText.Character nextCharacter, underscoreCharacter;
nicknameCopy = nickname.MutableCopy(); nicknameCopy = nickname.MutableCopy();
nickname.Clear(); nickname.Clear();
underscoreCharacter = underscoreCharacter = _.text.CharacterFromCodePoint(CODEPOINT_UNDERSCORE);
_.text.CharacterFromCodePoint(CODEPOINT_UNDERSCORE); for (i = 0; i < nicknameCopy.GetLength(); i += 1) {
for (i = 0; i < nicknameCopy.GetLength(); i += 1)
{
nextCharacter = nicknameCopy.GetCharacter(i); nextCharacter = nicknameCopy.GetCharacter(i);
if (_.text.IsWhitespace(nextCharacter)) if (_.text.IsWhitespace(nextCharacter)) {
{
// Replace character with underscore, leaving the formatting // Replace character with underscore, leaving the formatting
underscoreCharacter.formatting = nextCharacter.formatting; underscoreCharacter.formatting = nextCharacter.formatting;
nextCharacter = underscoreCharacter; nextCharacter = underscoreCharacter;
@ -364,8 +261,7 @@ private function ReplaceSpaces(MutableText nickname)
_.memory.Free(nicknameCopy); _.memory.Free(nicknameCopy);
} }
defaultproperties defaultproperties {
{
configClass = class'FutilityNicknames' configClass = class'FutilityNicknames'
CODEPOINT_UNDERSCORE = 95 // '_' CODEPOINT_UNDERSCORE = 95 // '_'
} }

12
sources/Futility.uc

@ -21,20 +21,16 @@ class Futility extends FeatureConfig
perobjectconfig perobjectconfig
config(Futility); config(Futility);
protected function HashTable ToData() protected function HashTable ToData() {
{
return _.collections.EmptyHashTable(); return _.collections.EmptyHashTable();
} }
protected function FromData(HashTable source) protected function FromData(HashTable source) {
{
} }
protected function DefaultIt() protected function DefaultIt() {
{
} }
defaultproperties defaultproperties {
{
configName = "Futility" configName = "Futility"
} }

6
sources/Futility_Feature.uc

@ -36,7 +36,7 @@ protected function OnEnabled()
return; return;
} }
for (i = 0; i < allCommandClasses.length; i += 1) { for (i = 0; i < allCommandClasses.length; i += 1) {
commandsFeature.RegisterCommand(allCommandClasses[i]); //commandsFeature.RegisterCommand(allCommandClasses[i]);
} }
_.environment.OnFeatureEnabled(self).connect = RegisterAllCommandClasses; _.environment.OnFeatureEnabled(self).connect = RegisterAllCommandClasses;
} }
@ -52,7 +52,7 @@ protected function OnDisabled()
return; return;
} }
for (i = 0; i < allCommandClasses.length; i += 1) { for (i = 0; i < allCommandClasses.length; i += 1) {
commandsFeature.RegisterCommand(allCommandClasses[i]); //ommandsFeature.RegisterCommand(allCommandClasses[i]);
} }
} }
@ -65,7 +65,7 @@ private final function RegisterAllCommandClasses(Feature enabledFeature)
return; return;
} }
for (i = 0; i < allCommandClasses.length; i += 1) { for (i = 0; i < allCommandClasses.length; i += 1) {
commandsFeature.RegisterCommand(allCommandClasses[i]); //commandsFeature.RegisterCommand(allCommandClasses[i]);
} }
} }

345
sources/Tools/PendingConfigsTool.uc

@ -0,0 +1,345 @@
/**
* Auxiliary object for `ACommandFeature` to help with managing pending
* configs for `Feature`s. Pending configs are `HashTable`s with config data
* that are yet to be applied to configs and `Feature`s. They allow users to
* make several changes to the data before actually applying changes to
* the gameplay.
* Copyright 2022 Anton Tarasenko
*------------------------------------------------------------------------------
* This file is part of Acedia.
*
* Acedia is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License, or
* (at your option) any later version.
*
* Acedia 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 Acedia. If not, see <https://www.gnu.org/licenses/>.
*/
class PendingConfigsTool extends AcediaObject;
/**
* This tool works by selecting feature (by class) and config (by `Text`
* name) on which it will operate with `SelectConfig()` method and then
* invoking the rest of its methods on these selections.
* There are some expections (`HasPendingConfigFor()` method) that
* explicitly take these values as parameters.
* This tool is supposed to be created once for the "feature" command and
* have its `SelectConfig()` called each execution with user-specified
* parameters.
*/
var private class<Feature> selectedFeatureClass;
var private Text selectedConfigName;
// Possible errors that might occur when working with pending configs
enum PendingConfigToolResult
{
// No error
PCTE_None,
// Pending version of specified config does not exist
PCTE_ConfigMissing,
// JSON object (`HashTable`) was expected as a parameter for the operation,
// but something else was given
PCTE_ExpectedObject,
// Specified JSON pointer points an non-existent location
PCTE_BadPointer
};
struct PendingConfigs
{
var class<Feature> featureClass;
var HashTable pendingSaves;
};
var private array<PendingConfigs> featurePendingEdits;
protected function Finalizer()
{
local int i;
for (i = 0; i < featurePendingEdits.length; i ++) {
_.memory.Free(featurePendingEdits[i].pendingSaves);
}
featurePendingEdits.length = 0;
}
/**
* Selects feature and config to perform all future operations on.
*
* @param featureClass Class of the feature for which to edit pending
* configs.
* @param configName Name of the pending config that caller tool will
* work with.
*/
public final function SelectConfig(
class<Feature> featureClass,
BaseText configName)
{
_.memory.Free(selectedConfigName);
selectedFeatureClass = featureClass;
selectedConfigName = none;
if (configName != none) {
selectedConfigName = configName.LowerCopy();
}
}
/**
* Checks wither caller tool has recorded pending config named `configName`
* for `Feature` defined by class `featureClass`.
* This method does no checks regarding existence of an actual config for
* the specified `Feature` - it only checks whether caller tool has pending
* version.
*
* @param featureClass Class of the `Feature` to check for pending config.
* @param configName Name of the config to check for existence of its
* pending version.
* @return `true` if specified pending config exists and `false` otherwise.
*/
public function bool HasPendingConfigFor(
class<Feature> featureClass,
BaseText configName)
{
local int i;
local bool result;
local Text lowerCaseConfigName;
if (featureClass == none) return false;
if (configName == none) return false;
for (i = 0; i < featurePendingEdits.length; i ++)
{
if (featurePendingEdits[i].featureClass == featureClass)
{
lowerCaseConfigName = configName.LowerCopy();
result = featurePendingEdits[i].pendingSaves
.HasKey(lowerCaseConfigName);
lowerCaseConfigName.FreeSelf();
return result;
}
}
return false;
}
/**
* Returns data recorded for the selected pending config inside caller tool.
*
* @param createIfMissing Method only returns data of the pending version of
* the config and if selected config does not yet have a pending version,
* it will, by default, return `none`. This parameter allows this method to
* create a pending config, based on current config with selected name
* (if it exists).
* @return Data recorded for the selected pending config. If selected config
* does not have a pending version, `createIfMissing` is set to `false`
* or not even current config with selected name exists - method returns
* `none`.
*/
public function HashTable GetPendingConfigData(optional bool createIfMissing)
{
local int editsIndex;
local HashTable result;
local PendingConfigs newRecord;
if (selectedConfigName == none) {
return none;
}
editsIndex = GetPendingConfigDataIndex();
if (editsIndex >= 0)
{
result = featurePendingEdits[editsIndex]
.pendingSaves
.GetHashTable(selectedConfigName);
if (result != none) {
return result;
}
}
if (createIfMissing)
{
if (editsIndex < 0)
{
editsIndex = featurePendingEdits.length;
newRecord.featureClass = selectedFeatureClass;
newRecord.pendingSaves = _.collections.EmptyHashTable();
featurePendingEdits[editsIndex] = newRecord;
}
result = GetCurrentConfigData();
if (result != none)
{
featurePendingEdits[editsIndex]
.pendingSaves
.SetItem(selectedConfigName, result);
}
}
return result;
}
/**
* Makes and edit to the config.
*
* @param pathToValue JSON path at which to make a change.
* @param newValue Value to record at the specified path.
* @return Result of the operation that reports any errors that have occured.
* Any changes are made iff result is `PCTE_None`.
*/
public function PendingConfigToolResult EditConfig(
BaseText pathToValue,
AcediaObject newValue)
{
local HashTable pendingData;
local MutableJsonPointer pointer;
local PendingConfigToolResult result;
if (pathToValue == none) {
return PCTE_BadPointer;
}
pendingData = GetPendingConfigData(true);
if (pendingData == none) {
return PCTE_ConfigMissing;
}
// Set new data
pointer = _.json.MutablePointer(pathToValue);
result = SetItemByJSON(pendingData, pointer, newValue);
pointer.FreeSelf();
pendingData.FreeSelf();
return result;
}
private function PendingConfigToolResult SetItemByJSON(
HashTable data,
MutableJsonPointer pointer,
AcediaObject jsonValue)
{
local Text containerIndex;
local AcediaObject container;
local PendingConfigToolResult result;
if (pointer.IsEmpty())
{
if (HashTable(jsonValue) != none)
{
result = ChangePendingConfigData(HashTable(jsonValue));
_.memory.Free(jsonValue);
return result;
}
_.memory.Free(jsonValue);
return PCTE_ExpectedObject;
}
// Since `!pointer.IsEmpty()`, we are guaranteed to pop a valid value
containerIndex = pointer.Pop();
container = data.GetItemByJSON(pointer);
if (container == none)
{
containerIndex.FreeSelf();
return PCTE_BadPointer;
}
result = SetContainerItemByText(container, containerIndex, jsonValue);
containerIndex.FreeSelf();
container.FreeSelf();
return result;
}
/*EditFeatureConfig #1: true
SetItemByJSON: true
SetContainerItemByText: true
EditFeatureConfig #2: true */
private function PendingConfigToolResult SetContainerItemByText(
AcediaObject container,
BaseText containerIndex,
AcediaObject jsonValue)
{
local int arrayIndex;
local Parser parser;
local ArrayList arrayListContainer;
local HashTable hashTableContainer;
hashTableContainer = HashTable(container);
arrayListContainer = ArrayList(container);
if (hashTableContainer != none) {
hashTableContainer.SetItem(containerIndex, jsonValue);
}
if (arrayListContainer != none)
{
parser = containerIndex.Parse();
if (parser.MInteger(arrayIndex, 10).Ok())
{
arrayListContainer.SetItem(arrayIndex, jsonValue);
parser.FreeSelf();
return PCTE_None;
}
parser.FreeSelf();
if (containerIndex.Compare(P("-"))) {
arrayListContainer.AddItem(jsonValue);
}
else {
return PCTE_BadPointer;
}
}
return PCTE_None;
}
/**
* Removes selected pending config.
*
* @return Result of the operation that reports any errors that have occured.
* Any changes are made iff result is `PCTE_None`.
*/
public final function PendingConfigToolResult RemoveConfig()
{
local int editIndex;
local HashTable pendingSaves;
editIndex = GetPendingConfigDataIndex();
if (editIndex < 0) return PCTE_ConfigMissing;
pendingSaves = featurePendingEdits[editIndex].pendingSaves;
if (!pendingSaves.HasKey(selectedConfigName)) return PCTE_ConfigMissing;
pendingSaves.RemoveItem(selectedConfigName);
if (pendingSaves.GetLength() <= 0)
{
pendingSaves.FreeSelf();
featurePendingEdits.Remove(editIndex, 1);
}
return PCTE_None;
}
private function int GetPendingConfigDataIndex()
{
local int i;
for (i = 0; i < featurePendingEdits.length; i ++)
{
if (featurePendingEdits[i].featureClass == selectedFeatureClass) {
return i;
}
}
return -1;
}
private function PendingConfigToolResult ChangePendingConfigData(
HashTable newData)
{
local int editsIndex;
if (selectedConfigName == none) {
return PCTE_None;
}
editsIndex = GetPendingConfigDataIndex();
if (editsIndex < 0) {
return PCTE_ConfigMissing;
}
featurePendingEdits[editsIndex].pendingSaves
.SetItem(selectedConfigName, newData);
return PCTE_None;
}
private function HashTable GetCurrentConfigData()
{
return selectedFeatureClass.default.configClass.static
.LoadData(selectedConfigName);
}
defaultproperties
{
}
Loading…
Cancel
Save