custom_achievements.sp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /**
  2. * [CSRD] Custom Achievements
  3. *
  4. * The custom achievement implementation for Pikachu's Canadian Server of Romance and Drama.
  5. */
  6. #pragma semicolon 1
  7. #include <sourcemod>
  8. #include <tf2_stocks>
  9. #include <sdktools_sound>
  10. #pragma newdecls required
  11. #include <stocksoup/log_server>
  12. #include <stocksoup/tf/tempents_stocks>
  13. #define PLUGIN_VERSION "0.1.2"
  14. public Plugin myinfo = {
  15. name = "[CSRD] Custom Achievements",
  16. author = "nosoop",
  17. description = "Provides a lightweight API for custom achievements.",
  18. version = PLUGIN_VERSION,
  19. url = "https://git.csrd.science/"
  20. }
  21. // Maximum language shortcode length (2-3 characters usually, though 'pt_p' is a thing).
  22. #define MAX_LANG_SC_LENGTH 8
  23. // Head attachment point index for player.
  24. #define ATTACHMENT_HEAD 1
  25. public APLRes AskPluginLoad2(Handle hPlugin, bool late, char[] error, int err_max) {
  26. RegPluginLibrary("custom-achievements");
  27. CreateNative("CustomAchievement.CustomAchievement", Native_RegisterAchievement);
  28. CreateNative("CustomAchievement.AwardToAccountID", Native_AwardAchievement);
  29. CreateNative("CustomAchievement.FetchMetadataByAccountID", Native_FetchAchievementMetadata);
  30. CreateNative("CustomAchievement.StoreMetadataByAccountID", Native_StoreAchievementMetadata);
  31. CreateNative("CustomAchievement.ResetByAccountID", Native_ResetAchievement);
  32. return APLRes_Success;
  33. }
  34. ConVar g_ConVarDebug;
  35. Database g_Database;
  36. DBStatement g_QueryRegisterAchievement;
  37. DBStatement g_QueryGetAchievementIdentifier;
  38. Handle g_ForwardOnCustomAchievementAwarded;
  39. float g_flLastEarnedAchievementTime[MAXPLAYERS+1];
  40. public void OnPluginStart() {
  41. g_ConVarDebug = CreateConVar("custom_achievement_debug", "0", "Generate debug spew?");
  42. char error[64];
  43. if ((g_Database = SQLite_UseDatabase("custom-achievements", error, sizeof(error)))
  44. == INVALID_HANDLE) {
  45. SetFailState("Could not use database custom-achievements for custom achievements: %s",
  46. error);
  47. }
  48. g_QueryRegisterAchievement = SQL_PrepareQuery(g_Database,
  49. "INSERT OR IGNORE INTO achievements (name, displaytype) VALUES (?, ?)",
  50. error, sizeof(error));
  51. if (!g_QueryRegisterAchievement) {
  52. SetFailState("Could not create achievement instantiation query: %s", error);
  53. }
  54. g_QueryGetAchievementIdentifier = SQL_PrepareQuery(g_Database,
  55. "SELECT achievement_id FROM achievements WHERE name = ?",
  56. error, sizeof(error));
  57. if (!g_QueryGetAchievementIdentifier) {
  58. SetFailState("Could not create achievement identifier query: %s", error);
  59. }
  60. g_ForwardOnCustomAchievementAwarded = CreateGlobalForward("OnCustomAchievementAwarded",
  61. ET_Ignore, Param_Cell, Param_Cell);
  62. HookEvent("achievement_earned", OnAchievementEarned);
  63. }
  64. public void OnClientConnected(int client) {
  65. g_flLastEarnedAchievementTime[client] = 0.0;
  66. }
  67. public void OnAchievementEarned(Event event, const char[] name, bool dontBroadcast) {
  68. int recipient = event.GetInt("player");
  69. if (recipient && recipient <= MaxClients) {
  70. g_flLastEarnedAchievementTime[recipient] = GetGameTime();
  71. }
  72. }
  73. public int Native_RegisterAchievement(Handle hPlugin, int argc) {
  74. int internalNameLength;
  75. GetNativeStringLength(1, internalNameLength);
  76. internalNameLength++;
  77. char[] internalName = new char[internalNameLength];
  78. GetNativeString(1, internalName, internalNameLength);
  79. int achievementStyle = GetNativeCell(2);
  80. // Attempt to fetch achievement first, creating it if it doesn't exist.
  81. g_QueryGetAchievementIdentifier.BindString(0, internalName, false);
  82. DBResultSet achievementResults = SQL_ExecuteStatement(g_QueryGetAchievementIdentifier);
  83. int iAchievement;
  84. if (achievementResults.FetchRow()) {
  85. iAchievement = achievementResults.FetchInt(0);
  86. } else {
  87. g_QueryRegisterAchievement.BindString(0, internalName, false);
  88. g_QueryRegisterAchievement.BindInt(1, achievementStyle, false);
  89. DBResultSet registerResults = SQL_ExecuteStatement(g_QueryRegisterAchievement);
  90. iAchievement = registerResults.InsertId;
  91. }
  92. LogDebug("Achievement '%s' registered under identifier %d", internalName, iAchievement);
  93. return iAchievement;
  94. }
  95. public int Native_AwardAchievement(Handle hPlugin, int argc) {
  96. int iAchievement = GetNativeCell(1);
  97. int steamid3 = GetNativeCell(2);
  98. bool notify = GetNativeCell(3) != 0;
  99. char query[1024];
  100. Format(query, sizeof(query), "SELECT achieved FROM achievement_status "
  101. ... "WHERE steamid3 = '%d' AND achievement_id = '%d'",
  102. steamid3, iAchievement);
  103. DataPack recipientData = new DataPack();
  104. recipientData.WriteCell(iAchievement);
  105. recipientData.WriteCell(steamid3);
  106. recipientData.WriteCell(notify);
  107. LogDebug("Awarding achievement %d to steamid %d", iAchievement, steamid3);
  108. SQL_TQuery(g_Database, SQLT_OnPreAchievementAwarded, query, recipientData);
  109. }
  110. public void SQLT_OnPreAchievementAwarded(Handle hOwner, Handle hChild, const char[] error,
  111. DataPack recipientData) {
  112. recipientData.Reset();
  113. int iAchievement = recipientData.ReadCell();
  114. int steamid3 = recipientData.ReadCell();
  115. bool notify = recipientData.ReadCell() != 0;
  116. delete recipientData;
  117. DBResultSet resultSet = view_as<DBResultSet>(hChild);
  118. if (!resultSet || !resultSet.FetchRow() || resultSet.FetchInt(0) == 0) {
  119. LogDebug("Account %d does not have achievement yet. Granting.", steamid3);
  120. char query[1024];
  121. Transaction transaction = new Transaction();
  122. // update player row to indicate achievement
  123. Format(query, sizeof(query), "UPDATE OR IGNORE achievement_status SET achieved=%d "
  124. ... "WHERE steamid3 = '%d' AND achievement_id = '%d'",
  125. GetTime(), steamid3, iAchievement);
  126. transaction.AddQuery(query);
  127. // create new row for player achievement if it doesn't exist
  128. Format(query, sizeof(query), "INSERT OR IGNORE INTO achievement_status "
  129. ..."(achievement_id, steamid3, achieved) VALUES (%d, %d, %d)",
  130. iAchievement, steamid3, GetTime());
  131. transaction.AddQuery(query);
  132. // transaction is autoclosed
  133. SQL_ExecuteTransaction(g_Database, transaction);
  134. if (notify) {
  135. // perform query to get all localized strings, then fetch each and send to clients as appropriate
  136. CallOnCustomAchievementAwarded(steamid3, iAchievement);
  137. }
  138. }
  139. }
  140. public int Native_FetchAchievementMetadata(Handle hPlugin, int argc) {
  141. int iAchievement = GetNativeCell(1);
  142. int steamid3 = GetNativeCell(2);
  143. DataPack fetchPack = new DataPack();
  144. fetchPack.WriteCell(iAchievement);
  145. fetchPack.WriteCell(hPlugin);
  146. fetchPack.WriteFunction(GetNativeFunction(3));
  147. fetchPack.WriteCell(GetNativeCell(4));
  148. char query[1024];
  149. Format(query, sizeof(query), "SELECT metadata FROM achievement_status "
  150. ... "WHERE achievement_id = %d AND steamid3 = %d", iAchievement, steamid3);
  151. SQL_TQuery(g_Database, SQLT_OnMetadataReceived, query, fetchPack);
  152. }
  153. public void SQLT_OnMetadataReceived(Handle owner, Handle child, const char[] error,
  154. DataPack fetchPack) {
  155. fetchPack.Reset();
  156. int iAchievement = fetchPack.ReadCell();
  157. Handle hPlugin = fetchPack.ReadCell();
  158. Function callback = fetchPack.ReadFunction();
  159. any data = fetchPack.ReadCell();
  160. delete fetchPack;
  161. if (GetPluginStatus(hPlugin) != Plugin_Running) {
  162. ThrowError("Calling plugin was unloaded before a query callback");
  163. return;
  164. }
  165. Call_StartFunction(hPlugin, callback);
  166. Call_PushCell(iAchievement);
  167. DBResultSet resultSet = view_as<DBResultSet>(child);
  168. if (resultSet && resultSet.FetchRow()) {
  169. int metadataLength = resultSet.FetchSize(0) + 1;
  170. char[] metadata = new char[metadataLength];
  171. resultSet.FetchString(0, metadata, metadataLength);
  172. Call_PushString(metadata);
  173. /**
  174. * quirk: we have to finish the call before metadata goes out of scope, otherwise the
  175. * callback gets an empty string???
  176. */
  177. Call_PushCell(data);
  178. Call_Finish();
  179. } else {
  180. Call_PushString("");
  181. Call_PushCell(data);
  182. Call_Finish();
  183. }
  184. }
  185. public int Native_StoreAchievementMetadata(Handle hPlugin, int argc) {
  186. int iAchievement = GetNativeCell(1);
  187. int steamid3 = GetNativeCell(2);
  188. int metadataLength;
  189. GetNativeStringLength(3, metadataLength);
  190. metadataLength++;
  191. metadataLength *= 2; // buffer must be at least 2*strlen(string)+1 [when SQL escaping]
  192. char[] metadata = new char[metadataLength];
  193. GetNativeString(3, metadata, metadataLength);
  194. SQL_EscapeString(g_Database, metadata, metadata, metadataLength);
  195. int queryLength = metadataLength + 1024;
  196. char[] query = new char[queryLength];
  197. // attempt to update an existing row
  198. Transaction transaction = new Transaction();
  199. Format(query, queryLength, "UPDATE OR IGNORE achievement_status SET metadata='%s' "
  200. ... "WHERE steamid3 = '%d' AND achievement_id = '%d'",
  201. metadata, steamid3, iAchievement);
  202. transaction.AddQuery(query);
  203. // create row if it doesn't
  204. Format(query, queryLength, "INSERT OR IGNORE INTO achievement_status "
  205. ..."(achievement_id, steamid3, metadata) VALUES (%d, %d, '%s')",
  206. iAchievement, steamid3, metadata);
  207. transaction.AddQuery(query);
  208. // transaction is autoclosed
  209. SQL_ExecuteTransaction(g_Database, transaction);
  210. LogDebug("Wrote metadata for achievement %d under steamid3 %d (%s)", iAchievement, steamid3,
  211. metadata);
  212. }
  213. public int Native_ResetAchievement(Handle hPlugin, int argc) {
  214. int iAchievement = GetNativeCell(1);
  215. int steamid3 = GetNativeCell(2);
  216. char query[256];
  217. // We update the entries instead of deleting the row in case the row is regenerated anyways
  218. Transaction transaction = new Transaction();
  219. Format(query, sizeof(query), "UPDATE OR IGNORE achievement_status "
  220. ... "SET metadata='', achieved=0 "
  221. ... "WHERE steamid3 = '%d' AND achievement_id = '%d'",
  222. steamid3, iAchievement);
  223. transaction.AddQuery(query);
  224. SQL_ExecuteTransaction(g_Database, transaction);
  225. LogDebug("Reset achievement %d for steamid3 %d", iAchievement, steamid3);
  226. }
  227. void CallOnCustomAchievementAwarded(int steamid3, int iAchievement) {
  228. int recipient = FindClientByAccountID(steamid3);
  229. if (recipient) {
  230. char recipientName[MAX_NAME_LENGTH];
  231. GetClientName(recipient, recipientName, sizeof(recipientName));
  232. // int nClients;
  233. // int clients[MAXPLAYERS+1];
  234. TransmitAchievementEvent(recipient, iAchievement);
  235. Call_StartForward(g_ForwardOnCustomAchievementAwarded);
  236. Call_PushCell(recipient);
  237. Call_PushCell(iAchievement);
  238. Call_Finish();
  239. LogDebug("%N was awarded achievement %d", recipient, iAchievement);
  240. }
  241. }
  242. /**
  243. * Prepares the achievement event by pulling localization strings.
  244. * If no localization strings are available, the achievement effects (particles and sound) are
  245. * not played.
  246. */
  247. void TransmitAchievementEvent(int recipient, int iAchievement) {
  248. char query[512];
  249. Format(query, sizeof(query),
  250. "SELECT language_shortcode, achievement_local_name, achievement_local_description "
  251. ... "FROM achievement_languages JOIN achievements ON achievement_name = name "
  252. ... "WHERE achievement_id = '%d'", iAchievement);
  253. DataPack pack = new DataPack();
  254. pack.WriteCell(GetClientUserId(recipient));
  255. pack.WriteCell(iAchievement);
  256. SQL_TQuery(g_Database, SQLT_OnLocalizedAchievementStringsReceived, query, pack);
  257. }
  258. public void SQLT_OnLocalizedAchievementStringsReceived(Handle hOwner, Handle hChild,
  259. const char[] error, DataPack pack) {
  260. pack.Reset();
  261. int recipient = GetClientOfUserId(pack.ReadCell());
  262. int iAchievement = pack.ReadCell();
  263. if (recipient) {
  264. DBResultSet resultSet = view_as<DBResultSet>(hChild);
  265. if (resultSet && resultSet.RowCount > 0) {
  266. KeyValues localizedStrings = new KeyValues("Achievement");
  267. // Put all name / descriptions into sections corresponding to language shortcodes.
  268. while (resultSet.FetchRow()) {
  269. int nNameLength, nDescriptionLength;
  270. char languageShortCode[MAX_LANG_SC_LENGTH];
  271. resultSet.FetchString(0, languageShortCode, sizeof(languageShortCode));
  272. nNameLength = resultSet.FetchSize(1) + 1;
  273. char[] achievementName = new char[nNameLength];
  274. resultSet.FetchString(1, achievementName, nNameLength);
  275. nDescriptionLength = resultSet.FetchSize(2) + 1;
  276. char[] achievementDescription = new char[nDescriptionLength];
  277. resultSet.FetchString(2, achievementDescription, nDescriptionLength);
  278. if (localizedStrings.JumpToKey(languageShortCode, true)) {
  279. localizedStrings.SetString("name", achievementName);
  280. localizedStrings.SetString("description", achievementDescription);
  281. localizedStrings.GoBack();
  282. }
  283. }
  284. localizedStrings.Rewind();
  285. char serverLanguageShortCode[MAX_LANG_SC_LENGTH];
  286. GetLanguageInfo(GetServerLanguage(), serverLanguageShortCode,
  287. sizeof(serverLanguageShortCode));
  288. // Ensure the server's language is localized as a fallback measure.
  289. if (localizedStrings.JumpToKey(serverLanguageShortCode)) {
  290. localizedStrings.GoBack();
  291. // Identify and send localized translations to each client, if possible.
  292. for (int i = 1; i <= MaxClients; i++) {
  293. if (IsClientInGame(i) && !IsFakeClient(i)) {
  294. char languageShortCode[MAX_LANG_SC_LENGTH];
  295. GetLanguageInfo(GetClientLanguage(i), languageShortCode,
  296. sizeof(languageShortCode));
  297. // Use server (default) language if client language isn't available.
  298. if (localizedStrings.JumpToKey(languageShortCode)
  299. || localizedStrings.JumpToKey(serverLanguageShortCode)) {
  300. char localName[64], localDescription[256];
  301. localizedStrings.GetString("name", localName, sizeof(localName));
  302. localizedStrings.GetString("description", localDescription,
  303. sizeof(localDescription));
  304. SendAchievementMessageToOne(recipient, i, localName,
  305. localDescription);
  306. localizedStrings.GoBack();
  307. }
  308. }
  309. }
  310. TransmitAchievementEffects(recipient);
  311. g_flLastEarnedAchievementTime[recipient] = GetGameTime();
  312. } else {
  313. LogMessage("Achievement %d is missing server / fallback localization entries "
  314. ... "in server's language '%s'. Achievement will not be displayed.",
  315. iAchievement, serverLanguageShortCode);
  316. }
  317. delete localizedStrings;
  318. } else {
  319. LogMessage("Achievement %d does not have any localized strings.", iAchievement);
  320. }
  321. }
  322. delete pack;
  323. }
  324. /**
  325. * Plays the achievement sound and displays the related particle on the recipient.
  326. */
  327. void TransmitAchievementEffects(int recipient) {
  328. /**
  329. * TODO add temporal filter if event `achievement_earned` or this function was called within
  330. * the last second so the effect is only used once.
  331. */
  332. if (GetGameTime() - g_flLastEarnedAchievementTime[recipient] > 1.0) {
  333. TFTeam recipientTeam = TF2_GetClientTeam(recipient);
  334. if (recipientTeam != TFTeam_Unassigned && recipientTeam != TFTeam_Spectator) {
  335. EmitGameSoundToAll("Achievement.Earned", recipient);
  336. // TODO prevent custom models from allowing this?
  337. if (IsPlayerAlive(recipient)) {
  338. TE_SetupTFParticleEffect("achieved", NULL_VECTOR, NULL_VECTOR, NULL_VECTOR,
  339. recipient, PATTACH_POINT_FOLLOW, ATTACHMENT_HEAD);
  340. TE_SendToAll();
  341. }
  342. }
  343. }
  344. }
  345. /**
  346. * Returns a client with the specified Steam account ID, or 0 if none.
  347. */
  348. stock int FindClientByAccountID(int steamid3) {
  349. if (steamid3) {
  350. for (int i = 1; i <= MaxClients; i++) {
  351. if (IsClientConnected(i) && !IsFakeClient(i) && IsClientAuthorized(i)) {
  352. if (steamid3 == GetSteamAccountID(i)) {
  353. return i;
  354. }
  355. }
  356. }
  357. }
  358. return 0;
  359. }
  360. /**
  361. * Sends the "<recipient> has earned the achievement <achievement>" message to the specified
  362. * client.
  363. *
  364. * If a description is specified, the description is enclosed in parentheses.
  365. */
  366. void SendAchievementMessageToOne(int recipient, int client, const char[] achievementName,
  367. const char[] achievementDescription = "") {
  368. char recipientName[MAX_NAME_LENGTH];
  369. GetClientName(recipient, recipientName, sizeof(recipientName));
  370. int clients[1];
  371. clients[0] = client;
  372. if (!strlen(achievementDescription)) {
  373. // no description provided
  374. SendSayText2Message(recipient, clients, 1, "#Achievement_Earned", recipientName,
  375. achievementName);
  376. } else {
  377. int bufferLength = strlen(achievementName) + strlen(achievementDescription) + 16;
  378. char[] achievementBuffer = new char[bufferLength];
  379. Format(achievementBuffer, bufferLength, "%s \x01(%s)", achievementName,
  380. achievementDescription);
  381. SendSayText2Message(recipient, clients, 1, "#Achievement_Earned", recipientName,
  382. achievementBuffer);
  383. }
  384. }
  385. void SendSayText2Message(int author, int[] clients, int nClients,
  386. const char[] localizationToken, const char[] name, const char[] message) {
  387. Handle buffer = StartMessage("SayText2", clients, nClients,
  388. USERMSG_RELIABLE | USERMSG_BLOCKHOOKS);
  389. BfWrite bitbuf = view_as<BfWrite>(buffer);
  390. bitbuf.WriteByte(author);
  391. bitbuf.WriteByte(true);
  392. bitbuf.WriteString(localizationToken);
  393. bitbuf.WriteString(name);
  394. bitbuf.WriteString(message);
  395. EndMessage();
  396. }
  397. void LogDebug(const char[] format, any ...) {
  398. if (g_ConVarDebug.BoolValue) {
  399. char message[256];
  400. VFormat(message, sizeof(message), format, 2);
  401. LogServer(message);
  402. }
  403. }
  404. /**
  405. * Executes a prepared statement and returns it as a result set view.
  406. * The handle should not be closed.
  407. */
  408. DBResultSet SQL_ExecuteStatement(DBStatement query) {
  409. SQL_Execute(query);
  410. return view_as<DBResultSet>(query);
  411. }