diff --git a/.gitignore b/.gitignore index 8e19d4018..d7c102f5a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,39 +1,44 @@ -*.orig -eressea.ini -Debug -Release - -# SlickEdit -*.vtg -*.vpwhistu - -# Microsoft Visual Studio build artefacts -src/Debug/ -src/Release/ -src/*.vcproj.*.user -Debug/ -Release/ -ipch/ -*.ipch -*.ncb -*.opensdf -*.pdb -*.sdf -*.suo -*.user - -*~ -*.bak -bin/ -build*/ -*.log -*.log.* -tags -Thumbs.db -.gdb_history -*.cfg -*.cmd -tmp/ -tests/config.lua -tests/reports/ -tests/data/185.dat +tolua/ +.vscode/ +*.orig +eressea.ini +Debug +Release + +# SlickEdit +*.vtg +*.vpwhistu + +# Microsoft Visual Studio build artefacts +src/Debug/ +src/Release/ +src/*.vcproj.*.user +Debug/ +Release/ +ipch/ +*.ipch +*.ncb +*.opensdf +*.pdb +*.sdf +*.suo +*.user + +*~ +*.bak +bin/ +build*/ +*.log +*.log.* +tags +Thumbs.db +.gdb_history +*.cfg +*.cmd +tmp/ +tests/config.lua +tests/reports/ +tests/data/185.dat +/quicklist/ +/cutest/ +/critbit/ diff --git a/.gitmodules b/.gitmodules index 81c45896e..7dff5ab6a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,18 +4,9 @@ [submodule "cmake"] path = cmake url = https://github.com/ennorehling/cmake.git -[submodule "quicklist"] - path = quicklist - url = https://github.com/ennorehling/quicklist.git -[submodule "critbit"] - path = critbit - url = https://github.com/ennorehling/critbit.git [submodule "dlmalloc"] path = dlmalloc url = https://github.com/ennorehling/dlmalloc.git -[submodule "cutest"] - path = cutest - url = https://github.com/ennorehling/cutest.git [submodule "iniparser"] path = iniparser url = https://github.com/ennorehling/iniparser.git @@ -26,6 +17,6 @@ path = storage url = https://github.com/ennorehling/storage.git branch = master -[submodule "tolua"] - path = tolua - url = https://github.com/ennorehling/tolua.git +[submodule "clibs"] + path = clibs + url = https://github.com/ennorehling/clibs diff --git a/.travis.yml b/.travis.yml index 003fb67ad..78aaf3648 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,8 @@ script: s/travis-build addons: apt: packages: - - liblua5.2-dev + - liblua5.1-dev + - libtolua-dev - libncurses5-dev - libsqlite3-dev - libxml2-dev diff --git a/CMakeLists.txt b/CMakeLists.txt index 1ad7b3528..405b86a03 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,6 @@ endif(WIN32) project (eressea-server C) - enable_testing() find_package (LibXml2) find_package (SQLite3) @@ -14,63 +13,14 @@ find_package (Curses) find_package (Lua REQUIRED) find_package (ToLua REQUIRED) -INCLUDE (CheckIncludeFiles) -INCLUDE (CheckSymbolExists) -CHECK_INCLUDE_FILES (stdbool.h HAVE_STDBOOL_H) -CHECK_INCLUDE_FILES (windows.h HAVE_WINDOWS_H) -CHECK_INCLUDE_FILES (io.h HAVE_IO_H) -CHECK_INCLUDE_FILES (strings.h HAVE_STRINGS_H) -CHECK_INCLUDE_FILES (unistd.h HAVE_UNISTD_H) -IF (HAVE_IO_H) -CHECK_SYMBOL_EXISTS (_access "io.h" HAVE__ACCESS) -ENDIF (HAVE_IO_H) -IF (HAVE_WINDOWS_H) -CHECK_SYMBOL_EXISTS (_sleep "windows.h" HAVE__SLEEP) -ENDIF(HAVE_WINDOWS_H) -IF(HAVE_STDBOOL_H) -CHECK_SYMBOL_EXISTS (_Bool "stdbool.h" HAVE__BOOL) -ENDIF(HAVE_STDBOOL_H) -IF(HAVE_UNISTD_H) -CHECK_SYMBOL_EXISTS (sleep "unistd.h" HAVE_SLEEP) -CHECK_SYMBOL_EXISTS (usleep "unistd.h" HAVE_USLEEP) -CHECK_SYMBOL_EXISTS (access "unistd.h" HAVE_ACCESS) -ENDIF(HAVE_UNISTD_H) -CHECK_SYMBOL_EXISTS (strlcpy "string.h" HAVE_STRLCPY) -CHECK_SYMBOL_EXISTS (strlcat "string.h" HAVE_STRLCAT) -CHECK_SYMBOL_EXISTS (slprintf "string.h" HAVE_SLPRINTF) -CHECK_SYMBOL_EXISTS (strcasecmp "string.h" HAVE_STRCASECMP) -CHECK_SYMBOL_EXISTS (strncasecmp "string.h" HAVE_STRNCASECMP) -CHECK_SYMBOL_EXISTS (_strlwr "string.h" HAVE__STRLWR) -CHECK_SYMBOL_EXISTS (_strcmpl "string.h" HAVE__STRCMPL) -CHECK_SYMBOL_EXISTS (_strdup "string.h" HAVE__STRDUP) -CHECK_SYMBOL_EXISTS (_stricmp "string.h" HAVE__STRICMP) -CHECK_SYMBOL_EXISTS (_memicmp "string.h" HAVE__MEMICMP) -CHECK_SYMBOL_EXISTS (strcmpl "string.h" HAVE_STRCMPL) -CHECK_SYMBOL_EXISTS (strdup "string.h" HAVE_STRDUP) -CHECK_SYMBOL_EXISTS (stricmp "string.h" HAVE_STRICMP) -CHECK_SYMBOL_EXISTS (memicmp "string.h" HAVE_MEMICMP) -CHECK_SYMBOL_EXISTS (strlwr "string.h" HAVE_STRLWR) -CHECK_SYMBOL_EXISTS (snprintf "stdio.h" HAVE_SNPRINTF) -CHECK_SYMBOL_EXISTS (_snprintf "stdio.h" HAVE__SNPRINTF) -CHECK_SYMBOL_EXISTS (mkdir "sys/stat.h" HAVE_SYS_STAT_MKDIR) -CHECK_SYMBOL_EXISTS (mkdir "direct.h" HAVE_DIRECT_MKDIR) -CHECK_SYMBOL_EXISTS (_mkdir "direct.h" HAVE_DIRECT__MKDIR) - -CONFIGURE_FILE ( - ${CMAKE_CURRENT_SOURCE_DIR}/autoconf.h.in - ${CMAKE_BINARY_DIR}/include/autoconf.h) -INCLUDE_DIRECTORIES (${CMAKE_BINARY_DIR}/include) -add_definitions(-DUSE_AUTOCONF) - -add_subdirectory (cutest) add_subdirectory (cJSON) add_subdirectory (storage) add_subdirectory (iniparser) -add_subdirectory (quicklist) -add_subdirectory (critbit) +add_subdirectory (clibs) add_subdirectory (process) add_subdirectory (src eressea) install(DIRECTORY res conf DESTINATION ${CMAKE_INSTALL_PREFIX} FILES_MATCHING PATTERN "*.xml") install(DIRECTORY res conf DESTINATION ${CMAKE_INSTALL_PREFIX} FILES_MATCHING PATTERN "*.json") install(DIRECTORY scripts DESTINATION ${CMAKE_INSTALL_PREFIX} FILES_MATCHING PATTERN "*.lua") +install(DIRECTORY lunit DESTINATION ${CMAKE_INSTALL_PREFIX} FILES_MATCHING PATTERN "*.lua") install(DIRECTORY share DESTINATION ${CMAKE_INSTALL_PREFIX}) diff --git a/autoconf.h.in b/autoconf.h.in deleted file mode 100644 index 1c151b6f9..000000000 --- a/autoconf.h.in +++ /dev/null @@ -1,159 +0,0 @@ -#pragma once -#ifndef CMAKE_AUTOCONF_H -#define CMAKE_AUTOCONF_H -#cmakedefine HAVE_STDBOOL_H 1 -#cmakedefine HAVE_STRINGS_H 1 -#cmakedefine HAVE_WINDOWS_H 1 -#cmakedefine HAVE_IO_H 1 -#cmakedefine HAVE_UNISTD_H 1 -#cmakedefine HAVE__BOOL 1 -#cmakedefine HAVE_STRCASECMP 1 -#cmakedefine HAVE_STRNCASECMP 1 -#cmakedefine HAVE__STRICMP 1 -#cmakedefine HAVE_SNPRINTF 1 -#cmakedefine HAVE__SNPRINTF 1 -#cmakedefine HAVE_ACCESS 1 -#cmakedefine HAVE__ACCESS 1 -#cmakedefine HAVE_SLEEP 1 -#cmakedefine HAVE_USLEEP 1 -#cmakedefine HAVE__SLEEP 1 -#cmakedefine HAVE_STRDUP 1 -#cmakedefine HAVE__STRDUP 1 -#cmakedefine HAVE_STRICMP 1 -#cmakedefine HAVE__STRCMPL 1 -#cmakedefine HAVE_STRCMPL 1 -#cmakedefine HAVE__MEMICMP 1 -#cmakedefine HAVE_MEMICMP 1 -#cmakedefine HAVE__STRLWR 1 -#cmakedefine HAVE_STRLWR 1 -#cmakedefine HAVE_STRLCPY 1 -#cmakedefine HAVE_STRLCAT 1 -#cmakedefine HAVE_SLPRINTF 1 -#cmakedefine HAVE_SYS_STAT_MKDIR 1 -#cmakedefine HAVE_DIRECT_MKDIR 1 -#cmakedefine HAVE_DIRECT__MKDIR 1 - -#if defined(HAVE_STRINGS_H) -#include -#endif - -#if defined(HAVE_UNISTD_H) -#include -#endif - -#if defined(HAVE_IO_H) -#include -#endif - -#if defined(HAVE_WINDOWS_H) -#include -#endif - -#if defined(HAVE_STDBOOL_H) -# include -#else -# if ! HAVE__BOOL -# ifdef __cplusplus -typedef bool _Bool; -# else -typedef unsigned char _Bool; -# endif -# endif -# define bool _Bool -# define false 0 -# define true 1 -# define __bool_true_false_are_defined 1 -#endif - -#ifndef HAVE__ACCESS -#ifdef HAVE_ACCESS -#define _access(path, mode) access(path, mode) -#endif -#endif - -#ifndef _A_RDONLY -#ifdef R_OK -#define _A_RDONLY R_OK -#endif -#endif - -#if !defined(HAVE__MEMICMP) -#if defined(HAVE_MEMICMP) -#define _memicmp(a, b, n) memicmp(a, b, n) -#elif defined(HAVE_STRNCASECMP) -#define _memicmp(a, b, n) strncasecmp(a, b, n) -#else -#define _memicmp(a, b, n) lcp_memicmp(a, b, n) -#endif -#endif - -#if !defined(HAVE__STRCMPL) -#if defined(HAVE_STRCMPL) -#define _strcmpl(a, b) strcmpl(a, b) -#elif defined(HAVE__STRICMP) -#define _strcmpl(a, b) _stricmp(a, b) -#elif defined(HAVE_STRICMP) -#define _strcmpl(a, b) stricmp(a, b) -#elif defined(HAVE_STRCASECMP) -#define _strcmpl(a, b) strcasecmp(a, b) -#else -#define _strcmpl(a, b) lcp_strcmpl(a, b) -#endif -#endif - -#if defined(HAVE_DIRECT__MKDIR) -#include -#elif defined(HAVE_DIRECT_MKDIR) -#include -#define _mkdir(a) mkdir(a) -#elif defined(HAVE_SYS_STAT_MKDIR) -#include -#define _mkdir(a) mkdir(a, 0777) -#endif - -#if !defined(HAVE__STRLWR) -#if defined(HAVE_STRLWR) -#define _strlwr(a) strlwr(a) -#else -#define _strlwr(a) lcp_strlwr(a) -#endif -#endif - -#if !defined(HAVE__STRDUP) -#if defined(HAVE_STRDUP) -#define _strdup(a) strdup(a) -#else -#define _strdup(a) lcp_strdup(a) -#endif -#endif - -#if !defined(HAVE__SLEEP) -#if defined(HAVE_USLEEP) -#define _sleep(a) usleep(a) -#elif defined(HAVE_SLEEP) -#define _sleep(a) sleep((a)/1000) -#else -#define _sleep(a) lcp_sleep(a) -#endif -#endif - -#if !defined(HAVE__SNPRINTF) -#if defined(HAVE_SNPRINTF) -#define _snprintf snprintf -#else -#define _snprintf lcp_snprintf -#endif -#endif - -#ifndef _min -#define _min(a,b) ((a) < (b) ? (a) : (b)) -#endif -#ifndef _max -#define _max(a,b) ((a) > (b) ? (a) : (b)) -#endif - -#if !defined(DBG_UNREFERENCED_PARAMETER) -#define DBG_UNREFERENCED_PARAMETER(x) x -#endif - -#endif diff --git a/clibs b/clibs new file mode 160000 index 000000000..d286006a2 --- /dev/null +++ b/clibs @@ -0,0 +1 @@ +Subproject commit d286006a28c8aa7cd70ed7fd4cd172b50ade9727 diff --git a/conf/e2/config.json b/conf/e2/config.json index 217cfffe9..f9f9b2df0 100644 --- a/conf/e2/config.json +++ b/conf/e2/config.json @@ -5,12 +5,11 @@ "e2/terrains.json" ], "disabled": [ - "pay", "jsreport" ], "settings": { - "game.id": 2, - "game.name": "Eressea", + "game.name" : "Eressea", + "game.id" : 2, "orders.default": "work", "NewbieImmunity": 8, "modules.wormholes": true, diff --git a/conf/e2/locales.xml b/conf/e2/locales.xml new file mode 100644 index 000000000..7a31bbc17 --- /dev/null +++ b/conf/e2/locales.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/conf/e2/config.xml b/conf/e2/rules.xml similarity index 56% rename from conf/e2/config.xml rename to conf/e2/rules.xml index f7f227824..8d0b01b27 100644 --- a/conf/e2/config.xml +++ b/conf/e2/rules.xml @@ -1,11 +1,5 @@ - - - - - - @@ -26,10 +20,9 @@ - - + @@ -42,30 +35,8 @@ - + - - - - - - - - - eressea-server@eressea.de - eressea-server@eressea.de - - - Bitte denke daran, deine Befehle mit dem Betreff - ERESSEA 2 BEFEHLE an eressea-server@eressea.de zu senden. - Remember to send your orders to - eressea-server@eressea.de with the subject ERESSEA 2 ORDERS. - - - ERESSEA 2 BEFEHLE - ERESSEA 2 ORDERS - - diff --git a/conf/e3/config.json b/conf/e3/config.json index c9a86c8da..1cecc89d2 100644 --- a/conf/e3/config.json +++ b/conf/e3/config.json @@ -1,9 +1,9 @@ { - "include": [ - "keywords.json", + "include": [ + "keywords.json", "prefixes.json", "e3/terrains.json" - ], + ], "disabled": [ "herbalism", "alchemy", @@ -25,8 +25,8 @@ "jsreport" ], "settings": { - "game.id": 3, - "game.name": "E3", + "game.name" : "Eressea", + "game.id" : 3, "orders.default": "work", "database.gameid": 7, "NewbieImmunity": 4, @@ -42,6 +42,7 @@ "nmr.timeout": 5, "nmr.removenewbie": 0, "GiveRestriction": 3, + "healing.forest": 2.0, "hunger.long": false, "hunger.damage": "1d9+9", "hunger.demons.skill": true, diff --git a/conf/e3/locales.xml b/conf/e3/locales.xml new file mode 100644 index 000000000..2d94bf202 --- /dev/null +++ b/conf/e3/locales.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/conf/e3/config.xml b/conf/e3/rules.xml similarity index 56% rename from conf/e3/config.xml rename to conf/e3/rules.xml index d337ead42..421b54d7a 100644 --- a/conf/e3/config.xml +++ b/conf/e3/rules.xml @@ -1,8 +1,5 @@ - - - @@ -15,8 +12,6 @@ - - @@ -28,14 +23,6 @@ - - - - - - - - @@ -44,20 +31,4 @@ - - - eressea-server@eressea.de - eressea-server@eressea.de - - - Bitte denke daran, deine Befehle mit dem Betreff - ERESSEA 3 BEFEHLE an eressea-server@eressea.de zu senden. - Remember to send your orders to - eressea-server@eressea.de with the subject E3 ORDERS. - - - ERESSEA 3 BEFEHLE - ERESSEA 3 ORDERS - - diff --git a/conf/e3/terrains.json b/conf/e3/terrains.json index 7b5ea980d..ee0eb0e37 100644 --- a/conf/e3/terrains.json +++ b/conf/e3/terrains.json @@ -222,14 +222,6 @@ "div": "100" } } - }, - "default": { - "size": 0, - "herbs": [], - "seed": 0, - "road": 0, - "flags": [ "land", "walk", "sail", "fly" ], - "production": {} } } } diff --git a/conf/e4/catalog.xml b/conf/e4/catalog.xml deleted file mode 100644 index 9987e72c8..000000000 --- a/conf/e4/catalog.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - diff --git a/conf/e4/config.json b/conf/e4/config.json deleted file mode 100644 index 7a73de86f..000000000 --- a/conf/e4/config.json +++ /dev/null @@ -1,95 +0,0 @@ -{ - "include": [ - "keywords.json", - "prefixes.json", - "e3/terrains.json" - ], - "disabled": [ - "herbalism", - "alchemy", - "entertainment", - "espionage", - "perception", - "stealth", - "taxation", - "trade", - "besiege", - "steal", - "buy", - "teach", - "sabotage", - "spy", - "tax", - "entertain", - "sell", - "jsreport" - ], - "settings": { - "game.id": 4, - "game.name": "Deveron", - "orders.default": "work", - "database.gameid": 7, - "NewbieImmunity": 4, - "modules.astralspace": false, - "modules.wormholes": false, - "modules.markets": true, - "magic.regeneration": 0.75, - "magic.power": 0.5, - "resource.factor": 0.25, - "skills.cost.tactics": 500, - "entertain.base": 0, - "entertain.perlevel": 20, - "nmr.timeout": 5, - "nmr.removenewbie": 0, - "GiveRestriction": 3, - "hunger.long": false, - "hunger.damage": "1d9+9", - "hunger.demons.skill": true, - "hunger.demons.peasant_tolerance": true, - "init_spells": 0, - "recruit.allow_merge": true, - "study.expensivemigrants": true, - "study.speedup": 2, - "study.produceexp": 12, - "world.era": 3, - "rules.reserve.twophase": true, - "rules.owners.force_leave": false, - "rules.transfermen": false, - "stealth.faction.other": false, - "rules.stealth.anon_battle": false, - "rules.check_overload": false, - "rules.combat.goblinbonus": 3, - "rules.alliances": true, - "rules.combat.herospeed": 3, - "rules.combat.demon_vampire": 5, - "rules.combat.skill_bonus": 0, - "rules.combat.nat_armor": 1, - "rules.items.loot_divisor": 2, - "rules.items.give_divisor": 2, - "rules.move.owner_leave": true, - "rules.region_owners": true, - "rules.cavalry.skill": 2, - "rules.cavalry.mode": 1, - "rules.magic.multipotion": true, - "rules.magic.wol_effect": 5, - "rules.magic.factionlist": true, - "rules.magic.wol_type": 2, - "rules.blessed_harvest.flags": 1, - "rules.magic.elfpower": true, - "rules.magic.playerschools": "gwyrrd illaun draig cerddor", - "rules.build.other_buildings": true, - "rules.economy.taxation": 1, - "rules.food.flags": 2, - "rules.economy.roqf": 5, - "rules.economy.herbrot": 0, - "rules.region_owner_pay_building": "market harbour lighthouse", - "rules.dwarf_castles": true, - "rules.limit.faction": 250, - "rules.grow.formula": 1, - "rules.tactics.formula": 1, - "rules.help.mask": "fight guard money give", - "movement.shipspeed.skillbonus": 6, - "alliance.auto": "fight", - "alliance.restricted": "fight" - } -} diff --git a/conf/e4/config.xml b/conf/e4/config.xml deleted file mode 100644 index 5c99f7d7e..000000000 --- a/conf/e4/config.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - eressea-server@eressea.de - eressea-server@eressea.de - - - Bitte denke daran, deine Befehle mit dem Betreff - ERESSEA 4 BEFEHLE an eressea-server@eressea.de zu senden. - Remember to send your orders to - eressea-server@eressea.de with the subject ERESSEA 4 ORDERS. - - - ERESSEA 4 BEFEHLE - ERESSEA 4 ORDERS - - - diff --git a/conf/eressea.ini b/conf/eressea.ini index e14d0af50..b6db180ca 100644 --- a/conf/eressea.ini +++ b/conf/eressea.ini @@ -1,5 +1,7 @@ - -[eressea] +[game] +email = eressea-server@kn-bremen.de +sender = Eressea Server +name = Eressea base = . report = reports verbose = 0 diff --git a/conf/keywords.json b/conf/keywords.json index 88ee6c2bd..7117217d7 100644 --- a/conf/keywords.json +++ b/conf/keywords.json @@ -1,69 +1,69 @@ { - "keywords": { - "en" : { - "grow": [ "GROW", "BREED", "PLANT" ], - "combat": [ "COMBAT", "FIGHT" ] - }, - "de": { - "//" : "//", - "banner": "BANNER", - "work": [ "ARBEITE", "ARBEITEN" ], - "attack": ["ATTACKIERE", "ATTACKIEREN"], - "steal": [ "BEKLAUE", "BEKLAUEN" ], - "besiege": ["BELAGERE", "BELAGERN" ], - "name": [ "BENENNE", "BENENNEN" ], - "use": [ "BENUTZE", "BENUTZEN" ], - "describe": [ "BESCHREIBE", "BESCHREIBEN" ], - "enter": ["BETRETE", "BETRETEN"], - "guard": ["BEWACHE", "BEWACHEN"], - "message": "BOTSCHAFT", - "end": "ENDE", - "ride": ["FAHRE", "FAHREN"], - "number": "NUMMER", - "follow": ["FOLGE","FOLGEN"], - "research": ["FORSCHE", "FORSCHEN"], - "give": "GIB", - "help": [ "HELFE", "HELFEN" ], - "combat": [ "KÄMPFE", "KÄMPFEN" ], - "ready" : "KAMPFZAUBER", - "buy" : [ "KAUFE", "KAUFEN"], - "contact": [ "KONTAKT", "KONTAKTIEREN"], - "teach": ["LEHRE", "LEHREN"], - "study": ["LERNE", "LERNEN"], - "make": ["MACHE", "MACHEN"], - "maketemp": ["MACHE TEMP", "MACHETEMP"], - "move" : "NACH", - "password" : "PASSWORT", - "loot" : ["PLÜNDERE", "PLÜNDERN"], - "recruit": ["REKRUTIERE", "REKRUTIEREN"], - "reserve": ["RESERVIERE", "RESERVIEREN"], - "route": "ROUTE", - "sabotage": ["SABOTIERE", "SABOTIEREN"], - "option": "OPTION", - "spy": ["SPIONIERE", "SPIONIEREN"], - "quit": "STIRB", - "hide": ["TARNE", "TARNEN"], - "carry": ["TRANSPORTIERE", "TRANSPORTIEREN"], - "tax": ["TREIBE", "TREIBEN", "STEUERN"], - "entertain": ["UNTERHALTE", "UNTERHALTEN"], - "sell": ["VERKAUFE", "VERKAUFEN"], - "leave": ["VERLASSE", "VERLASSEN"], - "forget": ["VERGISS", "VERGESSEN"], - "cast": ["ZAUBERE", "ZAUBERN"], - "show": ["ZEIGE", "ZEIGEN"], - "destroy": ["ZERSTÖRE", "ZERSTÖREN"], - "grow": ["ZÜCHTE", "PFLANZE", "ZÜCHTEN", "PFLANZEN"], - "default": "DEFAULT", - "origin": "URSPRUNG", - "email": "EMAIL", - "piracy": "PIRATERIE", - "group": "GRUPPE", - "sort": ["SORTIERE", "SORTIEREN"], - "prefix": "PRÄFIX", - "alliance": "ALLIANZ", - "claim": ["BEANSPRUCHE", "BEANSPRUCHEN"], - "promote": ["BEFÖRDERE", "BEFÖRDERUNG"], - "pay": ["BEZAHLE", "BEZAHLEN"] - } - } + "keywords": { + "en" : { + "grow": [ "GROW", "BREED", "PLANT" ], + "combat": [ "COMBAT", "FIGHT" ] + }, + "de": { + "//" : "//", + "banner": "BANNER", + "work": [ "ARBEITE", "ARBEITEN" ], + "attack": ["ATTACKIERE", "ATTACKIEREN"], + "steal": [ "BEKLAUE", "BEKLAUEN" ], + "besiege": ["BELAGERE", "BELAGERN" ], + "name": [ "BENENNE", "BENENNEN" ], + "use": [ "BENUTZE", "BENUTZEN" ], + "describe": [ "BESCHREIBE", "BESCHREIBEN" ], + "enter": ["BETRETE", "BETRETEN"], + "guard": ["BEWACHE", "BEWACHEN"], + "message": "BOTSCHAFT", + "end": "ENDE", + "ride": ["FAHRE", "FAHREN"], + "number": "NUMMER", + "follow": ["FOLGE","FOLGEN"], + "research": ["FORSCHE", "FORSCHEN"], + "give": "GIB", + "help": [ "HELFE", "HELFEN" ], + "combat": [ "KÄMPFE", "KÄMPFEN" ], + "ready" : "KAMPFZAUBER", + "buy" : [ "KAUFE", "KAUFEN"], + "contact": [ "KONTAKT", "KONTAKTIEREN"], + "teach": ["LEHRE", "LEHREN"], + "study": ["LERNE", "LERNEN"], + "make": ["MACHE", "MACHEN"], + "maketemp": ["MACHE TEMP", "MACHETEMP"], + "move" : "NACH", + "password" : "PASSWORT", + "loot" : ["PLÜNDERE", "PLÜNDERN"], + "recruit": ["REKRUTIERE", "REKRUTIEREN"], + "reserve": ["RESERVIERE", "RESERVIEREN"], + "route": "ROUTE", + "sabotage": ["SABOTIERE", "SABOTIEREN"], + "option": "OPTION", + "spy": ["SPIONIERE", "SPIONIEREN"], + "quit": "STIRB", + "hide": ["TARNE", "TARNEN"], + "carry": ["TRANSPORTIERE", "TRANSPORTIEREN"], + "tax": ["TREIBE", "TREIBEN", "STEUERN"], + "entertain": ["UNTERHALTE", "UNTERHALTEN"], + "sell": ["VERKAUFE", "VERKAUFEN"], + "leave": ["VERLASSE", "VERLASSEN"], + "forget": ["VERGISS", "VERGESSEN"], + "cast": ["ZAUBERE", "ZAUBERN"], + "show": ["ZEIGE", "ZEIGEN"], + "destroy": ["ZERSTÖRE", "ZERSTÖREN"], + "grow": ["ZÜCHTE", "PFLANZE", "ZÜCHTEN", "PFLANZEN"], + "default": "DEFAULT", + "origin": "URSPRUNG", + "email": "EMAIL", + "piracy": "PIRATERIE", + "group": "GRUPPE", + "sort": ["SORTIERE", "SORTIEREN"], + "prefix": "PRÄFIX", + "alliance": "ALLIANZ", + "claim": ["BEANSPRUCHE", "BEANSPRUCHEN"], + "promote": ["BEFÖRDERE", "BEFÖRDERUNG"], + "pay": ["BEZAHLE", "BEZAHLEN"] + } + } } diff --git a/critbit b/critbit deleted file mode 160000 index 971836241..000000000 --- a/critbit +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 971836241277e37274aa3110344836499816ff21 diff --git a/cutest b/cutest deleted file mode 160000 index 6e268687d..000000000 --- a/cutest +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 6e268687dbf6ae55afb63210c3753530d216a622 diff --git a/doc/gprof-v3.10.0-163-gdfab45d.txt b/doc/gprof-v3.10.0-163-gdfab45d.profile similarity index 100% rename from doc/gprof-v3.10.0-163-gdfab45d.txt rename to doc/gprof-v3.10.0-163-gdfab45d.profile diff --git a/process/compress.sh b/process/compress.sh index ff152b9f1..116b3d061 100755 --- a/process/compress.sh +++ b/process/compress.sh @@ -6,7 +6,7 @@ if [ -z $ERESSEA ]; then fi GAME=$ERESSEA/game-$1 -GAME_NAME=$(grep name $GAME/eressea.ini | sed 's/.*=\s*//') +GAME_NAME=$(grep -w name $GAME/eressea.ini | sed 's/.*=\s*//') TURN=$2 if [ -z $TURN ] @@ -20,5 +20,5 @@ if [ ! -d $GAME/reports ]; then fi cd $GAME/reports -$HOME/bin/compress.py $TURN "$GAME_NAME" +$ERESSEA/server/bin/compress.py $TURN "$GAME_NAME" cd - diff --git a/process/cron/preview.cron b/process/cron/preview.cron index b18038843..985ddf40b 100755 --- a/process/cron/preview.cron +++ b/process/cron/preview.cron @@ -7,7 +7,6 @@ if [ -e ${ERESSEA}/build/.preview ]; then fi SRC=${ERESSEA}/git ${SRC}/s/preview build ${branch} || exit $? -${SRC}/s/preview version for game in 2 3 4 ; do ${SRC}/s/preview -g ${game} run && \ ${SRC}/s/preview -g ${game} send diff --git a/process/orders-accept b/process/orders-accept index e90c3d48f..2f8f0bd29 100755 --- a/process/orders-accept +++ b/process/orders-accept @@ -3,22 +3,53 @@ from email.Utils import parseaddr from email.Parser import Parser -from os import mkdir, rename, stat, utime, unlink, symlink -from os.path import exists +import os +import os.path +import ConfigParser from re import compile, IGNORECASE from stat import ST_MTIME from string import upper, split, replace import logging -from sys import argv, stdin, exit +import sys +from sys import stdin from time import ctime, sleep, time from socket import gethostname from rfc822 import parsedate_tz, mktime_tz -LOG_FILENAME='/home/eressea/log/orders.log' +if 'ERESSEA' in os.environ: + dir = os.environ['ERESSEA'] +elif 'HOME' in os.environ: + dir = os.path.join(os.environ['HOME'], '/eressea') +else: # WTF? No HOME? + dir = "/home/eressea/eressea" +if not os.path.isdir(dir): + print "please set the ERESSEA environment variable to the install path" + sys.exit(1) +rootdir = dir + +game = int(sys.argv[1]) +gamedir = os.path.join(rootdir, "game-%d" % (game, )) +frommail = 'eressea-server@kn-bremen.de' +gamename = 'Eressea' +sender = '%s Server <%s>' % (gamename, frommail) + +inifile = os.path.join(gamedir, 'eressea.ini') +if not os.path.exists(inifile): + print "no such file: " . inifile +else: + config = ConfigParser.ConfigParser() + config.read(inifile) + if config.has_option('game', 'email'): + frommail = config.get('game', 'email') + if config.has_option('game', 'name'): + gamename = config.get('game', 'name') + if config.has_option('game', 'sender'): + sender = config.get('game', 'sender') + else: + sender = "%s Server <%s>" % (gamename, frommail) + config = None prefix = 'turn-' hostname = gethostname() -# base directory for all your games: -rootdir = "/home/eressea" orderbase = "orders.dir" sendmail = True # maximum number of reports per sender: @@ -28,36 +59,21 @@ writeheaders = True # reject all html email? rejecthtml = True -games = [ - { - "from" : "Eressea Server ", - "prefix" : "Eressea" - }, - { - "from" : "Eressea Server ", - "prefix": "E3" - }, - { - "from" : "Eressea Server ", - "prefix": "E4" - }, -] - def unlock_file(filename): try: - unlink(filename+".lock") + os.unlink(filename+".lock") except: print "could not unlock %s.lock, file not found" % filename def lock_file(filename): i = 0 wait = 1 - if not exists(filename): + if not os.path.exists(filename): file=open(filename, "w") file.close() while True: try: - symlink(filename, filename+".lock") + os.symlink(filename, filename+".lock") return except: i = i+1 @@ -74,17 +90,17 @@ messages = { "software and re-send the orders.", "multipart-de" : - "FEHLER: Die von dir eingeschickte Mail enthlt keinen " \ + "FEHLER: Die von dir eingeschickte Mail enth�lt keinen " \ "Text. Evtl. hast Du den Zug als HTML oder als anderweitig " \ - "ungltig formatierte Mail ingeschickt. Wir knnen ihn " \ - "deshalb nicht bercksichtigen. Schicke den Zug nochmals " \ + "ung�ltig formatierte Mail ingeschickt. Wir k�nnen ihn " \ + "deshalb nicht ber�cksichtigen. Schicke den Zug nochmals " \ "als reinen Text ohne Formatierungen ein.", "maildate-de": - "Es erreichte uns bereits ein Zug mit einem spteren " \ + "Es erreichte uns bereits ein Zug mit einem sp�teren " \ "Absendedatum (%s > %s). Entweder ist deine " \ "Systemzeit verstellt, oder ein Zug hat einen anderen Zug von " \ - "dir auf dem Transportweg berholt. Entscheidend fr die " \ + "dir auf dem Transportweg �berholt. Entscheidend f�r die " \ "Auswertungsreihenfolge ist das Absendedatum, d.h. der Date:-Header " \ "deiner Mail.", @@ -173,8 +189,8 @@ def available_file(dirname, basename): ver = 0 maxdate = 0 filename = "%s/%s,%s,%d" % (dirname, basename, hostname, ver) - while exists(filename): - maxdate = max(stat(filename)[ST_MTIME], maxdate) + while os.path.exists(filename): + maxdate = max(os.stat(filename)[ST_MTIME], maxdate) ver = ver + 1 filename = "%s/%s,%s,%d" % (dirname, basename, hostname, ver) if ver >= maxfiles: @@ -234,7 +250,7 @@ def copy_orders(message, filename, sender): from os.path import split dirname, basename = split(filename) dirname = dirname + '/headers' - if not exists(dirname): mkdir(dirname) + if not os.path.exists(dirname): os.mkdir(dirname) outfile = open(dirname + '/' + basename, "w") for name, value in message.items(): outfile.write(name + ": " + value + "\n") @@ -265,104 +281,98 @@ def copy_orders(message, filename, sender): # create a file, containing: # game=0 locale=de file=/path/to/filename email=rcpt@domain.to def accept(game, locale, stream, extend=None): - global rootdir, orderbase + global rootdir, orderbase, gamedir, gamename, sender if extend is not None: orderbase = orderbase + ".pre-" + extend - gamename = games[game-2]["prefix"] - gamedir = rootdir+"/eressea/game-%d" % (game, ) - savedir = gamedir+"/"+orderbase + savedir = os.path.join(gamedir, orderbase) # check if it's one of the pre-sent orders. # create the save-directories if they don't exist - if not exists(gamedir): mkdir(gamedir) - if not exists(savedir): mkdir(savedir) + if not os.path.exists(gamedir): os.mkdir(gamedir) + if not os.path.exists(savedir): os.mkdir(savedir) # parse message message = Parser().parse(stream) - sender = get_sender(message) - logger = logging.getLogger(sender) + email = get_sender(message) + logger = logging.getLogger(email) # write syslog - if sender is None or valid_email(sender)==0: - logger.warning("invalid email address: " + str(sender)) + if email is None or valid_email(email)==0: + logger.warning("invalid email address: " + str(email)) return -1 - logger.info("received orders from " + sender) + logger.info("received orders from " + email) # get an available filename lock_file(gamedir + "/orders.queue") - maxdate, filename = available_file(savedir, prefix + sender) + maxdate, filename = available_file(savedir, prefix + email) if filename is None: - logger.warning("more than " + str(maxfiles) + " orders from " + sender) + logger.warning("more than " + str(maxfiles) + " orders from " + email) return -1 # copy the orders to the file - text_ok = copy_orders(message, filename, sender) + text_ok = copy_orders(message, filename, email) unlock_file(gamedir + "/orders.queue") warning, msg, fail = None, "", False maildate = message.get("Date") if maildate != None: turndate = mktime_tz(parsedate_tz(maildate)) - utime(filename, (turndate, turndate)) + os.utime(filename, (turndate, turndate)) logger.debug("mail date is '%s' (%d)" % (maildate, turndate)) if turndate < maxdate: - logger.warning("inconsistent message date " + sender) + logger.warning("inconsistent message date " + email) warning = " (" + messages["warning-" + locale] + ")" msg = msg + formatpar(messages["maildate-" + locale] % (ctime(maxdate),ctime(turndate)), 76, 2) + "\n" else: - logger.warning("missing message date " + sender) + logger.warning("missing message date " + email) warning = " (" + messages["warning-" + locale] + ")" msg = msg + formatpar(messages["nodate-" + locale], 76, 2) + "\n" if not text_ok: warning = " (" + messages["error-" + locale] + ")" msg = msg + formatpar(messages["multipart-" + locale], 76, 2) + "\n" - logger.warning("rejected - no text/plain in orders from " + sender) - unlink(filename) + logger.warning("rejected - no text/plain in orders from " + email) + os.unlink(filename) savedir = savedir + "/rejected" - if not exists(savedir): mkdir(savedir) + if not os.path.exists(savedir): os.mkdir(savedir) lock_file(gamedir + "/orders.queue") - maxdate, filename = available_file(savedir, prefix + sender) + maxdate, filename = available_file(savedir, prefix + email) store_message(message, filename) unlock_file(gamedir + "/orders.queue") fail = True if sendmail and warning is not None: - frommail = games[key]["from"] subject = gamename + " " + messages["subject-"+locale] + warning - mail = "Subject: %s\nFrom: %s\nTo: %s\n\n" % (subject, frommail, sender) + msg + mail = "Subject: %s\nFrom: %s\nTo: %s\n\n" % (subject, sender, email) + msg from smtplib import SMTP server = SMTP("localhost") - server.sendmail(frommail, sender, mail) + server.sendmail(sender, email, mail) server.close() if not sendmail: - print text_ok, fail, sender + print text_ok, fail, email print filename if not fail: lock_file(gamedir + "/orders.queue") queue = open(gamedir + "/orders.queue", "a") - queue.write("email=%s file=%s locale=%s game=%s\n" % (sender, filename, locale, game)) + queue.write("email=%s file=%s locale=%s game=%s\n" % (email, filename, locale, game)) queue.close() unlock_file(gamedir + "/orders.queue") - logger.info("done - accepted orders from " + sender) + logger.info("done - accepted orders from " + email) return 0 # the main body of the script: +try: + os.mkdir(os.path.join(rootdir, 'log')) +except: + pass # already exists? +LOG_FILENAME=os.path.join(rootdir, 'log/orders.log') logging.basicConfig(level=logging.DEBUG, filename=LOG_FILENAME) logger = logging delay=None # TODO: parse the turn delay -try: - game = int(argv[1]) -except: - game = argv[1] - if game[:3]=='e3a': - game = 3 - elif game[:7]=='eressea': - game = 2 -locale = argv[2] +locale = sys.argv[2] infile = stdin -if len(argv)>3: - infile = open(argv[3], "r") +if len(sys.argv)>3: + infile = open(sys.argv[3], "r") retval = accept(game, locale, infile, delay) if infile!=stdin: infile.close() -exit(retval) +sys.exit(retval) diff --git a/process/orders-process b/process/orders-process index a4d932648..79c7b3378 100755 --- a/process/orders-process +++ b/process/orders-process @@ -2,7 +2,10 @@ # -*- coding: iso-8859-1 -*- from os import unlink, symlink, rename, popen, tmpfile -from os.path import exists +import sys +import os +import os.path +import ConfigParser from re import compile, IGNORECASE from string import split, join, upper, strip from sys import argv, exit @@ -14,9 +17,8 @@ from epasswd import EPasswd def pwd_get_email(faction, pwd, pwdfile=None): return None -def splitfilename(filename): - from os.path import split - return split(filename) +def split_filename(filename): + return os.path.split(filename) def unlock_file(filename): try: @@ -28,7 +30,7 @@ def unlock_file(filename): def lock_file(filename): i = 0 wait = 1 - if not exists(filename): + if not os.path.exists(filename): file=open(filename, "w") file.close() while True: @@ -62,17 +64,47 @@ messages = { "error-en": "Error", } +game = int(sys.argv[1]) +echeck_cmd = "/home/eressea/echeck/echeck.sh" +maxlines = 25 # base directory for all your games: -rootdir = "/home/eressea/eressea" -frommail = "Eressea Server " -orderbase = "orders.dir" -sendmail = True -maxlines = 25 -echeck_cmd = "/home/eressea/echeck/echeck.sh" +install_dir = "/home/eressea/eressea" +if 'ERESSEA' in os.environ: + install_dir = os.environ['ERESSEA'] +elif 'HOME' in os.environ: + install_dir = os.path.join(os.environ['HOME'], '/eressea') +if not os.path.isdir(install_dir): + print "please set the ERESSEA environment variable to the install path" + sys.exit(1) + +game_dir = os.path.join(install_dir, "game-%d" % (game, )) +frommail = 'eressea-server@kn-bremen.de' +gamename = 'Eressea' +sender = '%s Server <%s>' % (gamename, frommail) + +inifile = os.path.join(game_dir, 'eressea.ini') +if not os.path.exists(inifile): + print "no such file: " . inifile +else: + config = ConfigParser.ConfigParser() + config.read(inifile) + if config.has_option('game', 'email'): + frommail = config.get('game', 'email') + if config.has_option('game', 'name'): + gamename = config.get('game', 'name') + if config.has_option('game', 'sender'): + sender = config.get('game', 'sender') + else: + sender = "%s Server <%s>" % (gamename, frommail) + config = None + +queue_file = os.path.join(game_dir, "orders.queue") +if not os.path.exists(queue_file): + exit(0) # regular expression that finds the start of a faction -fact_re = compile("^\s*(eressea|vinyambar|partei|faction)\s+([a-zA-Z0-9]+)\s+\"?([^\"]*)\"?", IGNORECASE) +fact_re = compile("^\s*(eressea|partei|faction)\s+([a-zA-Z0-9]+)\s+\"?([^\"]*)\"?", IGNORECASE) def check_pwd(filename, email, pw_data): results = [] @@ -98,7 +130,7 @@ def check_pwd(filename, email, pw_data): return results def echeck(filename, locale, rules): - dirname, filename = splitfilename(filename) + dirname, filename = split_filename(filename) stream = popen("%s %s %s %s %s" % (echeck_cmd, locale, filename, dirname, rules), 'r') lines = stream.readlines() if len(lines)==0: @@ -111,14 +143,6 @@ def echeck(filename, locale, rules): stream.close() return mail -## the main body of the script -game = int(argv[1]) - -basedir = rootdir + "/game-%d" % (game, ) -queuename = basedir + "/orders.queue" -if not exists(queuename): - exit(0) - # parse the queue file - #print "connecting to SMTP..." from smtplib import SMTP @@ -127,16 +151,17 @@ try: except: print "could not connect to SMTP server" exit(0) + #print "reading password file..." -pw_data = EPasswd(basedir + "/passwd") +pw_data = EPasswd(os.path.join(game_dir,"passwd")) #print "reading orders.queue..." # move the queue file to a save space while locking it: try: - lock_file(queuename) + lock_file(queue_file) except: exit(0) -queuefile = open(queuename, "r") +queuefile = open(queue_file, "r") lines = queuefile.readlines() queuefile.close() @@ -154,9 +179,9 @@ tmpfile.close() openlog("orders") -unlink(queuename) +unlink(queue_file) try: - unlock_file(queuename) + unlock_file(queue_file) except: pass @@ -170,15 +195,15 @@ for line in lines: email = dict["email"] locale = dict["locale"] game = int(dict["game"]) - file = dict["file"] + infile = dict["file"] gamename='[E%d]' % game rules='e%d' % game warning = "" failed = True - results = check_pwd(file, email, pw_data) - logfile = open(basedir+"/zug.log", "a") - dirname, filename = splitfilename(file) - msg = messages["validate-"+locale] + " " + filename + "\n\n" + results = check_pwd(infile, email, pw_data) + logfile = open(os.path.join(game_dir, "zug.log"), "a") + dirname, filename = split_filename(infile) + msg = messages["validate-"+locale] + " " + infile + "\n\n" for faction, game_email, success, pwd in results: msg = msg + messages["faction-"+locale] + " " + faction + "\n" if success: failed = False @@ -189,25 +214,24 @@ for line in lines: if failed: warning = " (" + messages["warning-" + locale] + ")" - syslog("failed - no valid password in " + file) + syslog("failed - no valid password in " + infile) else: - result = echeck(file, locale, rules) - if email=='eressea': - print result - continue - elif result is None: + result = None + if os.path.exists(echeck_cmd): + result = echeck(infile, locale, rules) + if result is None: # echeck did not finish - msg = msg + "Echeck was killed. Your turn was accepted, but could not be verified.\n" + msg = msg + "Echeck is broken. Your turn was accepted, but could not be verified.\n" warning = " (" + messages["warning-" + locale] + ")" - syslog("process - echeck got killed, " + file) + syslog("process - echeck broken, " + infile) else: msg = msg + result - syslog("process - checked orders in " + file) + syslog("process - checked orders in " + infile) subject = gamename + " " + messages["subject-" + locale] + warning - msg = "Subject: %s\nFrom: %s\nTo: %s\nContent-Type: text/plain; charset=utf-8\n\n" % (subject, frommail, email) + msg + msg = "Subject: %s\nFrom: %s\nTo: %s\nContent-Type: text/plain; charset=utf-8\n\n" % (subject, sender, email) + msg try: - server.sendmail(frommail, email, msg) + server.sendmail(sender, email, msg) except: syslog("failed - cannot send to " + email) diff --git a/process/send-bz2-report b/process/send-bz2-report index e9962d539..983564bea 100755 --- a/process/send-bz2-report +++ b/process/send-bz2-report @@ -8,7 +8,6 @@ if [ ! -f reports.txt ]; then exit -2 fi source $HOME/bin/functions.sh -source $ERESSEA/etc/eressea.conf TEMPLATE=report-mail.txt if [ "$1" == "-Lde" ] diff --git a/process/sendreport.sh b/process/sendreport.sh index 003026f4a..93d52f0b4 100755 --- a/process/sendreport.sh +++ b/process/sendreport.sh @@ -8,13 +8,12 @@ if [ -z $ERESSEA ]; then exit -2 fi source $HOME/bin/functions.sh -source $HOME/etc/eressea.conf GAME=$1 EMAIL=$2 FACTION=$3 PASSWD=$4 -echo "$GAME $EMAIL $FACTION $PASSWD" >> /tmp/report.log +#echo "$GAME $EMAIL $FACTION $PASSWD" >> /tmp/report.log function reply() { echo $@ | mutt -s "Reportnachforderung Partei ${FACTION}" $EMAIL diff --git a/process/sendreports.sh b/process/sendreports.sh index fc24200b6..c2bfa741c 100755 --- a/process/sendreports.sh +++ b/process/sendreports.sh @@ -8,7 +8,6 @@ if [ -z $ERESSEA ]; then exit -2 fi source $HOME/bin/functions.sh -source $ERESSEA/etc/eressea.conf if [ ! -z $1 ]; then GAME=$ERESSEA/game-$1 diff --git a/quicklist b/quicklist deleted file mode 160000 index f837dd31e..000000000 --- a/quicklist +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f837dd31e5fcf13c706db1ac2c86b7de3e706578 diff --git a/res/adamantium.xml b/res/adamantium.xml index cc1cedadc..77e138f77 100644 --- a/res/adamantium.xml +++ b/res/adamantium.xml @@ -1,14 +1,11 @@ - + - - - - + diff --git a/res/buildings/castle-2.xml b/res/buildings/castle-2.xml index 593e9ae5e..7b015d199 100644 --- a/res/buildings/castle-2.xml +++ b/res/buildings/castle-2.xml @@ -1,24 +1,23 @@ - - + - + - + - + - + - + diff --git a/res/buildings/castle.xml b/res/buildings/castle.xml index 253f49811..6e9140222 100644 --- a/res/buildings/castle.xml +++ b/res/buildings/castle.xml @@ -1,26 +1,25 @@ - - + - + - + - + - + - + - + diff --git a/res/core/armor/plate.xml b/res/core/armor/plate.xml index a22064e90..97d855a73 100644 --- a/res/core/armor/plate.xml +++ b/res/core/armor/plate.xml @@ -1,7 +1,6 @@ - diff --git a/res/core/common/buildings.xml b/res/core/common/buildings.xml index 423e90deb..540e9f085 100644 --- a/res/core/common/buildings.xml +++ b/res/core/common/buildings.xml @@ -4,9 +4,7 @@ - - - + @@ -23,7 +21,7 @@ - + @@ -34,7 +32,7 @@ - + @@ -45,7 +43,7 @@ - + @@ -56,7 +54,7 @@ - + @@ -75,7 +73,7 @@ - + @@ -85,7 +83,7 @@ - + @@ -96,7 +94,7 @@ - + @@ -107,7 +105,7 @@ - + @@ -119,7 +117,7 @@ - + @@ -129,7 +127,7 @@ - + @@ -138,7 +136,7 @@ - + @@ -148,7 +146,7 @@ - + @@ -158,7 +156,7 @@ - + diff --git a/res/core/common/items.xml b/res/core/common/items.xml index 6afd220ff..35f9af2c5 100644 --- a/res/core/common/items.xml +++ b/res/core/common/items.xml @@ -61,16 +61,8 @@ - - - - - - - - - + @@ -78,9 +70,7 @@ - - - + @@ -100,45 +90,34 @@ - + - - - + - + + + + + + - - - + - - - + - - - + - - - - - - - - - + diff --git a/res/core/common/potions.xml b/res/core/common/potions.xml index 84b1e5f52..4812727dd 100644 --- a/res/core/common/potions.xml +++ b/res/core/common/potions.xml @@ -4,8 +4,7 @@ - - + @@ -15,8 +14,7 @@ - - + @@ -26,8 +24,7 @@ - - + @@ -37,8 +34,7 @@ - - + @@ -48,8 +44,7 @@ - - + @@ -61,8 +56,7 @@ - - + @@ -74,8 +68,7 @@ - - + @@ -87,8 +80,7 @@ - - + @@ -100,8 +92,7 @@ - - + @@ -113,8 +104,7 @@ - - + @@ -126,8 +116,7 @@ - - + @@ -139,8 +128,7 @@ - - + @@ -152,8 +140,7 @@ - - + @@ -166,8 +153,7 @@ - - + @@ -181,8 +167,7 @@ - - + diff --git a/res/core/de/strings.xml b/res/core/de/strings.xml index 4582644c7..46d5605b1 100644 --- a/res/core/de/strings.xml +++ b/res/core/de/strings.xml @@ -6,6 +6,10 @@ _x: preposition (15 /Schlumpf/schwerter) _a: including article (ein Schlumpf, a smurf) --> + + BEFEHLE + ORDERS + Wirbel vortex @@ -235,11 +239,6 @@ einzige Vorteil ihrer geringen Größe ist, dass sie sich leichter verstecken kann. - - Dieses magische Szepter, ein Geschenk Igjarjuks, sorgt für große - Verwirrung und Gedächtnisverlust. Syntax: BENUTZE "Szepter der - Tränen" - Setzt eine Einheit dieses Segel auf einem Schiff, so erhöht sich dessen Reichweite permanent um 1 Region. @@ -913,17 +912,9 @@ Traumschlößchen - + Struktur - - Akademie der Künste - academy of arts - - - Skulptur - sculpture - @@ -1467,12 +1458,6 @@ Amulette des wahren Sehens - - Katzenamulett - - - Katzenamulette - Ring der Unsichtbarkeit @@ -1614,14 +1599,6 @@ Akkreditionen des Xontormia-Expreß - - Szepter der Tränen - wand of tears - - - Szepter der Tränen - wands of tears - Schneeball snowball @@ -2388,19 +2365,19 @@ ghoul - + Juju-Zombie juju-zombie - + Juju-Zombies juju-zombies - + Juju-Zombies juju-zombies - + Juju-Zombie juju-zombie @@ -3828,10 +3805,6 @@ Meteorregen Meteor Shower - - Schattenruf - Shadow Call - Erschaffe einen Ring der Regeneration Create A Ring of Regeneration @@ -4512,10 +4485,6 @@ Verletzt alle Gegner. Injures all enemies. - - Ruft Schattenwesen. - Calls beings from shadow. - Panik. Panic. @@ -6636,53 +6605,17 @@ EINLADEN INVITE - - Steine - stones - - - Pferde - horses - - - Bauern - peasants - - - Silber - silver - - - Laen - laen - - - + Schößlinge saplings - + Mallornschößlinge mallorn saplings - - Bäume - trees - - - - Mallorn - mallorn - - - - Eisen - iron - - Winter winter diff --git a/res/core/en/strings.xml b/res/core/en/strings.xml index d80c742b9..14b2b817d 100644 --- a/res/core/en/strings.xml +++ b/res/core/en/strings.xml @@ -310,7 +310,7 @@ dam - + structure @@ -444,12 +444,6 @@ amulets of chastity - - amulet of the kitten - - - amulets of the kitten - amulet of darkness diff --git a/res/core/fr/strings.xml b/res/core/fr/strings.xml index d1801b338..13e6beb25 100644 --- a/res/core/fr/strings.xml +++ b/res/core/fr/strings.xml @@ -324,7 +324,7 @@ barrage - + bâtiment @@ -458,12 +458,6 @@ amulettes de chasteté - - amulette du chaton - - - amulettes du chaton - amulette de ténčbres @@ -1912,10 +1906,10 @@ zombie - + zombies juju - + zombie juju diff --git a/res/core/messages.xml b/res/core/messages.xml index c07393609..e312fcc7c 100644 --- a/res/core/messages.xml +++ b/res/core/messages.xml @@ -1,5 +1,23 @@ + + + + + + Bitte denke daran, deine Befehle mit dem Betreff + $subject an $email zu senden. + Remember to send your orders to + $email with the subject ${subject}. + + + + + + + "$unit($unit): '$command' - Dieser Befehl ist unbekannt." + "$unit($unit): '$command' - Parse error, unknown command." + Die Region ist verwüstet, der Boden karg. The region is ravaged, the ground infertile. @@ -1245,14 +1263,6 @@ "$unit($unit) dies from poison damage taken in $region($region)." - - - - - "$unit($unit) schwenkt sein Szepter und sorgt für Verwirrung und Chaos in der Region." - "$unit($unit) waves their scepter and causes chaos and confusion in the region." - - @@ -1565,20 +1575,6 @@ "$unit($mage) konnte $int($amount) $if($eq($amount,1),"Bauer","Bauern") anwerben." "$unit($mage) managed to recruit $int($amount) $if($eq($amount,1),"peasant","peasants")." - - - - - "Ein bohrender Schmerz durchzuckt $unit($unit), Verwirrung macht sich breit." - "Pain pulses through $unit($unit), confusion spreads." - - - - - - ""AAAAAAAGHHHHHH!" - Ein Schrei durchzieht die Region, $unit($unit) windet sich vor Schmerz." - ""AAAAAAAGHHHHHH!" - $unit($unit) screams and squirms with pain." - @@ -1590,14 +1586,6 @@ "$unit($unit) in $region($region): '$order($command)' - A higher power prevents $unit($unit) from giving the object away. 'IT IS YOURS MY CHILD. ONLY YOURS.'." - - - - - "$unit($unit) sendet ein Stoßgebet an den Herrn der Schreie." - "$unit($unit) sends a prayer to the Lord of Screams." - - @@ -1826,7 +1814,7 @@ "$unit($unit) in $region($region): '$order($command)' - Der Magier erschafft ein Traumgebäude." "$unit($unit) in $region($region): '$order($command)' - The magician creates an illusionary building." - + @@ -1922,10 +1910,9 @@ - - "$unit($unit) benutzt in $region($region) einen Antimagiekristall." - "$unit($unit) uses an antimagic crystal in $region($region)." + "$unit($unit) benutzt einen Antimagiekristall." + "$unit($unit) uses an antimagic crystal." @@ -2424,7 +2411,7 @@ "Eine Botschaft von $unit.dative($unit) in $region($region): 'Ups! Quack, Quack!'" "A message from $unit($unit) in $region($region): 'Oops! Croak, Croak!'" - + @@ -2434,7 +2421,7 @@ "$unit($unit) in $region($region): '$order($command)' - $unit($mage) kann Zauber, die durch $unit($unit) gewirkt werden, nicht zusätzlich in die Ferne richten." "$unit($unit) in $region($region): '$order($command)' - $unit($mage) cannot direct spells that are channeled through $unit($unit) into distant regions." - + @@ -2574,13 +2561,6 @@ "$unit($unit) in $region($region) regeneriert $int($amount) Aura." "$unit($unit) regenerates $int($amount) aura in $region($region)." - - - - - "$string" - "$string" - @@ -2618,13 +2598,6 @@ "$unit($teacher) lehrt $unit($student) $skill($skill)." "$unit($teacher) teaches $unit($student) $skill($skill)." - - - - - "$string" - "$string" - @@ -2856,13 +2829,6 @@ "$unit($unit) baut für $int($size) an $ship($ship) weiter." "$unit($unit) builds $int($size) more on $ship($ship)." - - - - - "$string" - "$string" - @@ -2900,15 +2866,7 @@ "$unit($unit) $if($eq($mode,1),"reitet", "wandert") von $region($start) nach $region($end).$if($isnull($regions),""," Dabei wurde $trail($regions) durchquert.")" "$unit($unit) $if($eq($mode,1),"rides", "walks") from $region($start) to $region($end)$if($isnull($regions),""," by way of $trail($regions)")." - - - - - - "$unit($unit) entdeckt dass im $direction($direction) $terrain($region) ist." - "$unit($unit) discovered that $terrain($region) lies in the $direction($direction)." - - + @@ -2917,7 +2875,7 @@ "$unit($unit) entdeckt, dass $region($region) $localize($terrain) ist." "$unit($unit) discovered that $region($region) is $localize($terrain)." - + @@ -2925,7 +2883,7 @@ "$unit($unit) ist in dieser Runde gelandet und kann nicht weiter ins Landesinnere nach $region($region) vorstossen." "$unit($unit) has just landed and cannot continue moving to $region($region)." - + @@ -2933,7 +2891,7 @@ "Die Mannschaft der $ship($ship) kann in letzter Sekunde verhindern, dass das Schiff in $region($region) auf Land aufläuft." "At the very last moment, the crew of the $ship($ship) saved the ship from running aground in $region($region)." - + @@ -2941,7 +2899,7 @@ "Die $ship($ship) konnte in $region($region) nicht einreisen, die Küste ist zu gefährlich für das Schiff." "The $ship($ship) could not berth in $region($region). The coast is too dangerous for the vessel." - + @@ -2949,7 +2907,7 @@ "Die Mannschaft der $ship($ship) weigert sich, nach $direction($direction) zu reisen." "The crew of the $ship($ship) refuses to travel to the $direction($direction)." - + @@ -2957,7 +2915,7 @@ "Die Mannschaft der $ship($ship) weigert sich, nach $region($region) zu reisen." "The crew of the $ship($ship) refuses to travel to $region($region)." - + @@ -2965,7 +2923,7 @@ "$unit($unit) weigert sich, nach $direction($direction) zu reisen." "$unit($unit) refuses to travel to the $direction($direction)." - + @@ -2973,7 +2931,7 @@ "$unit($unit) weigert sich, nach $region($region) zu reisen." "$unit($unit) refuses to travel to $region($region)." - + @@ -2981,7 +2939,7 @@ "Die $ship($ship) konnte $region($region) nicht verlassen." "The $ship($ship) could not leave $region($region)." - + @@ -2990,35 +2948,7 @@ "$unit($unit) wurde in $region($region) von $unit.dative($guard) aufgehalten." "$unit($unit) was kept in $region($region) by $unit($guard)." - - - - - "Wir haben den Krieg mit $faction($faction) beendet." - "We declared peace with $faction($faction)." - - - - - - "$faction($faction) hat den Krieg mit uns beendet." - "$faction($faction) has declared peace with us." - - - - - - "Wir haben $faction($faction) den Krieg erklärt." - "We declared war on $faction($faction)." - - - - - - "$faction($faction) hat uns den Krieg erklärt." - "$faction($faction) has declared war on us." - - + @@ -3027,7 +2957,7 @@ "$unit($unit) konnte nicht von $region($region) nach $region($target) reisen, da der Besitzer der Region es verhinderte." "$unit($unit) could not travel from $region($region) to $region($target) because the owner denied entrance." - + @@ -3051,7 +2981,7 @@ "$unit($follower) konnte $unit($unit) nicht folgen." "$unit($follower) could not follow $unit($unit)." - + @@ -3059,7 +2989,7 @@ "$unit($unit) entdeckt, dass es keinen Weg nach $direction($direction) gibt." "$unit($unit) discovers that there is no route going $direction($direction)." - + @@ -3068,13 +2998,6 @@ "$unit($unit) konnte von $region($region) nicht nach $direction($direction) ausreisen, der Nebel war zu dicht." "$unit($unit) could not travel $direction($direction) from $region($region), the fog was too dense." - - - - - "$string" - "$string" - @@ -3343,20 +3266,6 @@ "$unit($unit) marschiert in eine Antimagiezone und löst sich auf." "$unit($unit) walks into an antimagical zone and dissolves." - - - - - "$unit($unit) hat sich unbemerkt verflüchtigt." - "$unit($unit) has dissolved without a trace." - - - - - - "$unit($unit) wird sich bald verflüchtigen." - "$unit($unit) will dissolve soon." - @@ -3392,11 +3301,10 @@ - - "ERESSEA $int36($faction) \"${password}\" - Deine Befehle hatten ein falsches Passwort." - "ERESSEA $int36($faction) \"${password}\" - Your orders had the wrong password." + "Deine Befehle hatten ein falsches Passwort (${password})." + "Your orders had the wrong password (${password})." @@ -6967,13 +6875,6 @@ "$unit($unit) in $region($region): '$order($command)' - Man benötigt mindestens $int($minskill) $skill($skill), um $resource($product,0) zu produzieren." "$unit($unit) in $region($region): '$order($command)' - You need at least $int($minskill) $skill($skill), to produce $resource($product,0)." - - - - - "$string" - "$string" - @@ -6981,13 +6882,6 @@ "$string" "$string" - - - - - "$string" - "$string" - @@ -7019,7 +6913,6 @@ "$unit($target) erhält $int($amount) $resource($resource,$amount) von $unit($unit)." "$unit($target) receives $int($amount) $resource($resource,$amount) from $unit($unit)." - @@ -7222,7 +7115,7 @@ "$unit($unit) in $region($region): '$order($command)' - No pyramids may be build in this region. The closest region to build a pyramid in is between $int($mindist) and $int($maxdist) regions away." - + @@ -7512,7 +7405,7 @@ - "$unit($mage) weight $building($building)." + "$unit($mage) weiht $building($building)." "$unit($mage) blesses $building($building)." @@ -7614,16 +7507,6 @@ "$unit($mage) casts $spell($spell). $int($amount) fighters are temporarily losing some of their memories." - - - - - - - "$unit($mage) ruft $int($amount) $race($race, 0) zu Hilfe." - "$unit($mage) calls upon the help of $int($amount) $race($race, 0)." - - @@ -7643,7 +7526,7 @@ "Heer $int($index)($abbrev): $int($dead) Tote, $int($fled) Geflohene, $int($survived) Überlebende." "Army $int($index)($abbrev): $int($dead) dead, $int($fled) fled, $int($survived) survivors." - + diff --git a/res/core/resources/horse.xml b/res/core/resources/horse.xml index 53699c696..608fca20a 100644 --- a/res/core/resources/horse.xml +++ b/res/core/resources/horse.xml @@ -1,11 +1,6 @@ - + - - + - - - - diff --git a/res/core/resources/hp.xml b/res/core/resources/hp.xml index fb1b6e32f..aa0ad4d29 100644 --- a/res/core/resources/hp.xml +++ b/res/core/resources/hp.xml @@ -1,5 +1,4 @@ - diff --git a/res/core/resources/iron.xml b/res/core/resources/iron.xml index 7bc4cb428..70d5c1080 100644 --- a/res/core/resources/iron.xml +++ b/res/core/resources/iron.xml @@ -1,12 +1,9 @@ - - - - - + + + + - - diff --git a/res/core/resources/laen.xml b/res/core/resources/laen.xml index 571026a0a..4099f5ca9 100644 --- a/res/core/resources/laen.xml +++ b/res/core/resources/laen.xml @@ -1,10 +1,7 @@ - - - - - + + + + - - diff --git a/res/core/resources/log.xml b/res/core/resources/log.xml index 012fe9a20..e3710d496 100644 --- a/res/core/resources/log.xml +++ b/res/core/resources/log.xml @@ -1,13 +1,8 @@ - - - - - + + + + - - - - diff --git a/res/core/resources/mallorn.xml b/res/core/resources/mallorn.xml index 2d301758e..3dff091c6 100644 --- a/res/core/resources/mallorn.xml +++ b/res/core/resources/mallorn.xml @@ -1,13 +1,8 @@ - - - - - + + + + - - - - diff --git a/res/core/resources/peasant.xml b/res/core/resources/peasant.xml index 32e1e1ca1..bce23430c 100644 --- a/res/core/resources/peasant.xml +++ b/res/core/resources/peasant.xml @@ -1,5 +1,4 @@ - diff --git a/res/core/resources/stone.xml b/res/core/resources/stone.xml index c227dcc5c..e1c5651ed 100644 --- a/res/core/resources/stone.xml +++ b/res/core/resources/stone.xml @@ -1,11 +1,9 @@ - - - - - + + + + - diff --git a/res/core/weapons/axe.xml b/res/core/weapons/axe.xml index 80a872ad7..3f97a5b8a 100644 --- a/res/core/weapons/axe.xml +++ b/res/core/weapons/axe.xml @@ -1,7 +1,6 @@ - diff --git a/res/core/weapons/greatbow.xml b/res/core/weapons/greatbow.xml index 10b270e55..32f07a41e 100644 --- a/res/core/weapons/greatbow.xml +++ b/res/core/weapons/greatbow.xml @@ -1,7 +1,6 @@ - diff --git a/res/core/weapons/greatsword.xml b/res/core/weapons/greatsword.xml index cd48b8296..56285f6af 100644 --- a/res/core/weapons/greatsword.xml +++ b/res/core/weapons/greatsword.xml @@ -1,7 +1,6 @@ - diff --git a/res/core/weapons/halberd.xml b/res/core/weapons/halberd.xml index 5025f4793..7abc86902 100644 --- a/res/core/weapons/halberd.xml +++ b/res/core/weapons/halberd.xml @@ -1,7 +1,6 @@ - diff --git a/res/core/weapons/lance.xml b/res/core/weapons/lance.xml index abbb7f31f..4a02bc06f 100644 --- a/res/core/weapons/lance.xml +++ b/res/core/weapons/lance.xml @@ -1,7 +1,6 @@ - diff --git a/res/core/weapons/mallornlance.xml b/res/core/weapons/mallornlance.xml index 0186143e4..c67390d52 100644 --- a/res/core/weapons/mallornlance.xml +++ b/res/core/weapons/mallornlance.xml @@ -1,7 +1,6 @@ - diff --git a/res/core/weapons/rustyaxe.xml b/res/core/weapons/rustyaxe.xml index 2ff19570c..fea6b8642 100644 --- a/res/core/weapons/rustyaxe.xml +++ b/res/core/weapons/rustyaxe.xml @@ -1,7 +1,6 @@ - diff --git a/res/core/weapons/rustyhalberd.xml b/res/core/weapons/rustyhalberd.xml index c1b1f69a9..3f0bd93b7 100644 --- a/res/core/weapons/rustyhalberd.xml +++ b/res/core/weapons/rustyhalberd.xml @@ -1,7 +1,6 @@ - diff --git a/res/e3a/armor/plate.xml b/res/e3a/armor/plate.xml index 29cabbf1a..79391fbcb 100644 --- a/res/e3a/armor/plate.xml +++ b/res/e3a/armor/plate.xml @@ -1,7 +1,6 @@ - - + diff --git a/res/e3a/armor/scale.xml b/res/e3a/armor/scale.xml index 7039b4008..1038f4d6c 100644 --- a/res/e3a/armor/scale.xml +++ b/res/e3a/armor/scale.xml @@ -1,7 +1,6 @@ - - + diff --git a/res/e3a/armor/towershield.xml b/res/e3a/armor/towershield.xml index e80c03523..38e4f0928 100644 --- a/res/e3a/armor/towershield.xml +++ b/res/e3a/armor/towershield.xml @@ -1,7 +1,6 @@ - - + diff --git a/res/e3a/buildings.xml b/res/e3a/buildings.xml index 8ca30d27d..9eeca952f 100644 --- a/res/e3a/buildings.xml +++ b/res/e3a/buildings.xml @@ -3,23 +3,22 @@ - + - - + - + - + - + diff --git a/res/e3a/equipment.xml b/res/e3a/equipment.xml index bbd2ac5b7..9fe133f48 100644 --- a/res/e3a/equipment.xml +++ b/res/e3a/equipment.xml @@ -1,78 +1,9 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/res/e3a/items.xml b/res/e3a/items.xml index 7d7e6b286..0399043e5 100644 --- a/res/e3a/items.xml +++ b/res/e3a/items.xml @@ -7,83 +7,72 @@ - - + - - + - - + - - + - - + - - + - - + - - + - + - - - - + diff --git a/res/e3a/races.xml b/res/e3a/races.xml index 2b0f68b9d..8b0cfae6d 100644 --- a/res/e3a/races.xml +++ b/res/e3a/races.xml @@ -8,9 +8,8 @@ - + - @@ -32,11 +31,9 @@ - + - - @@ -47,11 +44,9 @@ - + - - @@ -76,11 +71,13 @@ - + - - @@ -104,9 +101,8 @@ - + - @@ -124,10 +120,12 @@ - + - - @@ -144,9 +142,8 @@ - + - @@ -167,9 +164,12 @@ - + - @@ -192,9 +192,8 @@ - + - @@ -219,9 +218,8 @@ - + - @@ -241,9 +239,8 @@ - + - @@ -263,9 +260,8 @@ - + - @@ -287,9 +283,8 @@ - + - @@ -311,9 +306,8 @@ - + - @@ -334,9 +328,8 @@ - + - @@ -361,9 +354,8 @@ - + - @@ -384,9 +376,8 @@ - + - @@ -409,9 +400,8 @@ - + - @@ -435,10 +425,8 @@ - + - - @@ -460,9 +448,8 @@ - + - @@ -484,9 +471,8 @@ - + - @@ -507,9 +493,8 @@ - + - @@ -535,9 +520,8 @@ - + - @@ -559,9 +543,8 @@ - + - @@ -582,9 +565,8 @@ - + - @@ -607,24 +589,21 @@ - - + - + - + - - - + @@ -672,77 +651,62 @@ - + - - + - - + - - + - + - - + - + - + - - + - - - - - - - - - + - - - + @@ -768,9 +732,8 @@ - - - + + @@ -787,10 +750,8 @@ - + - - @@ -806,9 +767,8 @@ - - - + + @@ -823,10 +783,8 @@ - + - - @@ -839,9 +797,8 @@ - - - + + @@ -855,10 +812,8 @@ - + - - @@ -871,16 +826,13 @@ - + - - + - - @@ -889,35 +841,4 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/res/e3a/resources/iron.xml b/res/e3a/resources/iron.xml index b245da358..01e0d8d6d 100644 --- a/res/e3a/resources/iron.xml +++ b/res/e3a/resources/iron.xml @@ -1,11 +1,8 @@ - - - - - + + + + - - diff --git a/res/e3a/resources/mallornseed.xml b/res/e3a/resources/mallornseed.xml index 4a348c212..576035b34 100644 --- a/res/e3a/resources/mallornseed.xml +++ b/res/e3a/resources/mallornseed.xml @@ -1,4 +1,4 @@ - + diff --git a/res/e3a/resources/seed.xml b/res/e3a/resources/seed.xml index 21652f364..62c971540 100644 --- a/res/e3a/resources/seed.xml +++ b/res/e3a/resources/seed.xml @@ -1,4 +1,4 @@ - + diff --git a/res/e3a/resources/stone.xml b/res/e3a/resources/stone.xml index 746b79c21..d8fd08573 100644 --- a/res/e3a/resources/stone.xml +++ b/res/e3a/resources/stone.xml @@ -1,10 +1,8 @@ - - - - - + + + + - diff --git a/res/e3a/spellbooks/gray.xml b/res/e3a/spellbooks/gray.xml index 5967d6265..9c0035e78 100644 --- a/res/e3a/spellbooks/gray.xml +++ b/res/e3a/spellbooks/gray.xml @@ -107,7 +107,6 @@ - diff --git a/res/e3a/spells.xml b/res/e3a/spells.xml index ec656c18f..74eb89146 100644 --- a/res/e3a/spells.xml +++ b/res/e3a/spells.xml @@ -665,9 +665,6 @@ - - - diff --git a/res/e3a/weapons.xml b/res/e3a/weapons.xml index 052266a02..fdc8f1f3a 100644 --- a/res/e3a/weapons.xml +++ b/res/e3a/weapons.xml @@ -1,18 +1,18 @@ - - - + + + diff --git a/res/e3a/weapons/axe.xml b/res/e3a/weapons/axe.xml new file mode 100644 index 000000000..6066c4cfc --- /dev/null +++ b/res/e3a/weapons/axe.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/res/e3a/weapons/greatbow.xml b/res/e3a/weapons/greatbow.xml index 7f08427c8..745d1793d 100644 --- a/res/e3a/weapons/greatbow.xml +++ b/res/e3a/weapons/greatbow.xml @@ -4,8 +4,7 @@ * has lower damage --> - - + diff --git a/res/e3a/weapons/halberd.xml b/res/e3a/weapons/halberd.xml index 2c11b62fc..c22e020b4 100644 --- a/res/e3a/weapons/halberd.xml +++ b/res/e3a/weapons/halberd.xml @@ -3,8 +3,7 @@ 1. you cannt use this with cavalry --> - - + diff --git a/res/e3a/weapons/lance.xml b/res/e3a/weapons/lance.xml new file mode 100644 index 000000000..285862484 --- /dev/null +++ b/res/e3a/weapons/lance.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/res/e3a/weapons/mallornlance.xml b/res/e3a/weapons/mallornlance.xml index 1fcad08c8..8eb25ceb4 100644 --- a/res/e3a/weapons/mallornlance.xml +++ b/res/e3a/weapons/mallornlance.xml @@ -1,7 +1,6 @@ - - + diff --git a/res/core/weapons/rep_crossbow.xml b/res/e3a/weapons/rep_crossbow.xml similarity index 87% rename from res/core/weapons/rep_crossbow.xml rename to res/e3a/weapons/rep_crossbow.xml index 66e3f9fc2..02f0d865f 100644 --- a/res/core/weapons/rep_crossbow.xml +++ b/res/e3a/weapons/rep_crossbow.xml @@ -1,7 +1,6 @@ - - + diff --git a/res/e3a/weapons/rustyhalberd.xml b/res/e3a/weapons/rustyhalberd.xml index ed25d5db7..a53aec515 100644 --- a/res/e3a/weapons/rustyhalberd.xml +++ b/res/e3a/weapons/rustyhalberd.xml @@ -3,8 +3,7 @@ 1. you cannot use this with cavalry --> - - + diff --git a/res/eressea/artrewards.xml b/res/eressea/artrewards.xml index 6cb836c52..b18fd5b20 100644 --- a/res/eressea/artrewards.xml +++ b/res/eressea/artrewards.xml @@ -1,32 +1,14 @@ - - - - - - - - - - - - - - - - - + - - - + diff --git a/res/eressea/buildings.xml b/res/eressea/buildings.xml index 64d65cff0..670ab484e 100644 --- a/res/eressea/buildings.xml +++ b/res/eressea/buildings.xml @@ -4,4 +4,5 @@ + diff --git a/res/eressea/equipment.xml b/res/eressea/equipment.xml index f35505bc0..efd4f2a3b 100644 --- a/res/eressea/equipment.xml +++ b/res/eressea/equipment.xml @@ -2,18 +2,18 @@ - + - + - + @@ -21,30 +21,30 @@ - + - + - + - + - + - + @@ -58,12 +58,12 @@ - + - + @@ -269,11 +269,6 @@ - - - - - diff --git a/res/eressea/items.xml b/res/eressea/items.xml index 8b2df7add..3f5cc3d17 100644 --- a/res/eressea/items.xml +++ b/res/eressea/items.xml @@ -17,21 +17,15 @@ - - - + - - - + - - - + @@ -44,65 +38,38 @@ - - - + - - - + - - - - - - - - - - - - - - - - + - - - + - - - + - - - + - - - + @@ -111,27 +78,13 @@ - - - - - - - - - - - - - - + + - - - + diff --git a/res/eressea/races.xml b/res/eressea/races.xml index 7c3a5ab0c..6deefacc9 100644 --- a/res/eressea/races.xml +++ b/res/eressea/races.xml @@ -1,7 +1,7 @@ - - + - @@ -27,9 +26,8 @@ - + - @@ -61,9 +59,8 @@ - + - @@ -90,9 +87,8 @@ - + - @@ -118,9 +114,8 @@ - + - @@ -148,9 +143,8 @@ - + - @@ -178,9 +172,8 @@ - + - @@ -209,9 +202,8 @@ - + - @@ -244,9 +236,8 @@ - + - @@ -275,9 +266,8 @@ - + - @@ -308,9 +298,8 @@ - + - @@ -339,10 +328,8 @@ - + - - @@ -370,9 +357,8 @@ - + - @@ -401,9 +387,8 @@ - + - @@ -431,9 +416,8 @@ - + - @@ -463,9 +447,8 @@ - + - @@ -495,9 +478,8 @@ - + - @@ -525,9 +507,8 @@ - + - @@ -558,9 +539,8 @@ - + - @@ -589,25 +569,22 @@ - - + - + - - - - + @@ -671,69 +648,61 @@ - + - - + - - + - - + - + - - + - + - + - - + - + - - + - - @@ -742,11 +711,8 @@ - + - - - @@ -755,11 +721,8 @@ - + - - - @@ -769,22 +732,13 @@ - - - - - - - + - - - + - @@ -801,9 +755,8 @@ - + - @@ -827,9 +780,8 @@ - + - @@ -860,9 +812,8 @@ - + - @@ -889,10 +840,8 @@ - + - - @@ -921,9 +870,8 @@ - + - @@ -954,8 +902,6 @@ - - @@ -978,7 +924,7 @@ - + @@ -1011,11 +957,11 @@ - + - + @@ -1023,7 +969,7 @@ - + @@ -1037,9 +983,8 @@ - - - + + @@ -1055,10 +1000,8 @@ - + - - @@ -1073,9 +1016,8 @@ - - - + + @@ -1089,10 +1031,8 @@ - + - - @@ -1104,9 +1044,8 @@ - - - + + @@ -1119,10 +1058,8 @@ - + - - @@ -1134,15 +1071,12 @@ - + - - + - - @@ -1150,9 +1084,10 @@ - + + - @@ -1180,10 +1115,8 @@ - - + - @@ -1208,9 +1141,8 @@ - + - @@ -1240,7 +1172,7 @@ - + @@ -1270,10 +1202,8 @@ - + - - @@ -1282,31 +1212,5 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/res/eressea/spellbooks/gray.xml b/res/eressea/spellbooks/gray.xml index a7f718f2a..ae7a1f611 100644 --- a/res/eressea/spellbooks/gray.xml +++ b/res/eressea/spellbooks/gray.xml @@ -123,7 +123,6 @@ - diff --git a/res/eressea/spells.xml b/res/eressea/spells.xml index 5af11913e..1d762f4bd 100644 --- a/res/eressea/spells.xml +++ b/res/eressea/spells.xml @@ -471,9 +471,6 @@ - - - diff --git a/res/eressea/strings.xml b/res/eressea/strings.xml index 61a35ebe5..8afeabbca 100644 --- a/res/eressea/strings.xml +++ b/res/eressea/strings.xml @@ -116,18 +116,6 @@ Eine Geburtstagstorte mit 10 Kerzen. Herzlichen Glückwunsch, Eressea! A birthday cake with 10 candles. Happy Birthday, Eressea! - - Dieses Fluggerät aus der Schmiede der Zwerge von Celeband galt wie die - 'Ebene der Herausforderung' seit Urzeiten als verschollen, ja man - zweifelte seine Existenz an. Die Sage überliefert, das derjenige, der - sie auf der Spitze des Turmes seiner Gesinnung benutzt, als einziger - die 'Ebene der Herausforderungen' verlassen kann. - - - Glückwunsch, mein Kind. Du bist im Besitz des mächtigsten - Artefaktes Eresseas. Ein Fluch, sagt man, liege auf ihm, denn - niemand hat es bisher lange sein Eigen genannt... - Kleines trockenes Dauergebäck, m od. s; - u. -es, - u. -e @@ -352,37 +340,9 @@ - - Horn des Tanzes - horn of dancing - - - Hörner des Tanzes - horns of dancing - - - Miniatur einer Akademie der Künste - academy of arts in a box - - - Miniaturen einer Akademie der Künste - academies of arts in a box - - - Miniatur einer Skulptur - art sculpture in a box - - - Miniaturen einer Skulptur - art sculptures in a box - - - Gefangener Windgeist - trapped air elemental - - - Gefangene Windgeister - trapped air elementals + + Akademie der Künste + academy of arts Auratrank @@ -402,29 +362,6 @@ - - - Auge des Dämon - eye of the demon - oeil du démon - - - Augen des Dämon - eyes of the demon - oeil du démon - - - Schwinge des Greifen - wing of the gryphon - aile du griffon - - - Schwingen des Greifen - wings of the gryphon - ailes du griffon - - - Adamantium adamantium @@ -455,5 +392,14 @@ Adamantiumrüstungen adamantium plates - + + Katzenamulett + amulet of the kitten + amulette du chaton + + + amulets of the kitten + Katzenamulette + amulettes du chaton + diff --git a/res/items.xml b/res/items.xml deleted file mode 100644 index 108e6d398..000000000 --- a/res/items.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/res/races.xml b/res/races.xml deleted file mode 100644 index fcfc1742b..000000000 --- a/res/races.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/res/races/aquarian.xml b/res/races/aquarian.xml index 776f17e93..19fd3aee7 100644 --- a/res/races/aquarian.xml +++ b/res/races/aquarian.xml @@ -1,7 +1,6 @@ - + - diff --git a/res/races/cat.xml b/res/races/cat.xml index 818b24b36..5986c223c 100644 --- a/res/races/cat.xml +++ b/res/races/cat.xml @@ -1,7 +1,6 @@ - + - diff --git a/res/races/demon.xml b/res/races/demon.xml index a350fef4a..69d98145f 100644 --- a/res/races/demon.xml +++ b/res/races/demon.xml @@ -1,12 +1,11 @@ - - diff --git a/res/races/dragon.xml b/res/races/dragon.xml index 907ff90a7..f42037312 100644 --- a/res/races/dragon.xml +++ b/res/races/dragon.xml @@ -1,11 +1,10 @@ - +income="1000" walk="yes" teach="no" getitem="yes" resistbash="yes" +dragon="yes"> - - diff --git a/res/races/dwarf.xml b/res/races/dwarf.xml index 20fb874c0..043b76aa7 100644 --- a/res/races/dwarf.xml +++ b/res/races/dwarf.xml @@ -1,7 +1,6 @@ - + - @@ -30,4 +29,4 @@ - \ No newline at end of file + diff --git a/res/races/elf.xml b/res/races/elf.xml index dfbd2f2ec..683ee823b 100644 --- a/res/races/elf.xml +++ b/res/races/elf.xml @@ -1,7 +1,6 @@ - + - @@ -26,4 +25,4 @@ - \ No newline at end of file + diff --git a/res/races/goblin-2.xml b/res/races/goblin-2.xml deleted file mode 100644 index 9a9c265be..000000000 --- a/res/races/goblin-2.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/res/races/goblin-3.xml b/res/races/goblin-3.xml index e85b0c645..a65d4c99a 100644 --- a/res/races/goblin-3.xml +++ b/res/races/goblin-3.xml @@ -1,14 +1,12 @@ - - - diff --git a/res/races/goblin.xml b/res/races/goblin.xml index 177c82ffe..84d2c5079 100644 --- a/res/races/goblin.xml +++ b/res/races/goblin.xml @@ -1,12 +1,11 @@ - - diff --git a/res/races/halfling.xml b/res/races/halfling.xml index 3875ca414..3628d2b35 100644 --- a/res/races/halfling.xml +++ b/res/races/halfling.xml @@ -1,8 +1,7 @@ - + - - + diff --git a/res/races/human.xml b/res/races/human.xml index 2e4b94af2..f91ba7daf 100644 --- a/res/races/human.xml +++ b/res/races/human.xml @@ -1,7 +1,6 @@ - + - diff --git a/res/races/insect.xml b/res/races/insect.xml index cecbf0193..75e16f7af 100644 --- a/res/races/insect.xml +++ b/res/races/insect.xml @@ -1,7 +1,6 @@ - + - @@ -27,4 +26,4 @@ - \ No newline at end of file + diff --git a/res/races/orc.xml b/res/races/orc.xml index d9d26ab25..4f4d96ed5 100644 --- a/res/races/orc.xml +++ b/res/races/orc.xml @@ -1,5 +1,5 @@ - + diff --git a/res/races/troll.xml b/res/races/troll.xml index a2341851b..9168a6d0e 100644 --- a/res/races/troll.xml +++ b/res/races/troll.xml @@ -1,12 +1,11 @@ - - diff --git a/res/races/wyrm.xml b/res/races/wyrm.xml index b5d3bd7a2..dab1a9e1f 100644 --- a/res/races/wyrm.xml +++ b/res/races/wyrm.xml @@ -1,7 +1,10 @@ - + - diff --git a/res/races/youngdragon.xml b/res/races/youngdragon.xml index d1b3a4752..df10a44e9 100644 --- a/res/races/youngdragon.xml +++ b/res/races/youngdragon.xml @@ -1,8 +1,10 @@ - + - - diff --git a/res/races/zombie.xml b/res/races/zombie.xml index faecf021d..fdfe97d8e 100644 --- a/res/races/zombie.xml +++ b/res/races/zombie.xml @@ -1,9 +1,9 @@ - diff --git a/s/build b/s/build index 178fa4f43..4ee259573 100755 --- a/s/build +++ b/s/build @@ -1,8 +1,5 @@ #!/bin/sh -ROOT=`pwd` -while [ ! -d $ROOT/.git ]; do - ROOT=`dirname $ROOT` -done +ROOT=$(git rev-parse --show-toplevel) [ -z "$BUILD" ] && BUILD=Debug if [ -z "$JOBS" ] ; then @@ -33,16 +30,15 @@ if [ ! -d $ROOT/$BUILD ]; then exit fi -git submodule update - -if [ -z `which tolua` ]; then -echo "build tolua" -cd $ROOT/tolua ; make -fi - echo "build eressea" cd $ROOT/$BUILD +BRANCH=$(git status -s -b | head -1 | cut -d\ -f 2 | sed 's/\..*//') +if [ "$BRANCH"=="master" ] ; then VERSION=$(git describe --match 'v*.*.*' --tags | sed 's/^v//') cmake -DERESSEA_VERSION="$VERSION" .. +else +REV=$(git rev-parse --short HEAD) +cmake -DERESSEA_BUILDNO="$REV" .. +fi make $MAKEOPTS && make test cd $OLDPWD diff --git a/s/cmake-init b/s/cmake-init index 35378d6a5..1ce7eccd3 100755 --- a/s/cmake-init +++ b/s/cmake-init @@ -1,25 +1,19 @@ #!/bin/sh -ROOT=$(pwd) -while [ ! -d $ROOT/.git ]; do - ROOT=$(dirname $ROOT) - if [ "$ROOT" == "/" ; then - echo "could not find root, are you in the git repository?" - exit - fi -done +ROOT=$(git rev-parse --show-toplevel) [ -z $BUILD ] && BUILD=Debug -MACHINE=`uname -m` [ -z "$CC" ] && [ ! -z `which clang` ] && CC="clang" [ -z "$CC" ] && [ ! -z `which gcc` ] && CC="gcc" [ -z "$CC" ] && [ ! -z `which tcc` ] && CC="tcc" [ -z "$CC" ] && [ ! -z `which cc` ] && CC="cc" + +MACHINE=`$CC -dumpmachine` +[ -z $MACHINE ] && MACHINE=`uname -m` BIN_DIR="$ROOT/build-$MACHINE-$CC-$BUILD" mkdir -p $BIN_DIR rm -f $BUILD ln -sf $BIN_DIR $BUILD -MACHINE=$(gcc -dumpmachine) rm -f CMakeCache.txt # use anything installed in /opt or /usr @@ -34,17 +28,31 @@ if [ -d $HOME/usr ]; then PREFIX_PATH=$HOME/usr:$HOME/usr/local:$PREFIX_PATH fi +DEST=$(dirname $ROOT)/server ARGS=" -DCMAKE_MODULE_PATH=$ROOT/cmake/Modules \ -DCMAKE_BUILD_TYPE=$BUILD \ -DCMAKE_LIBRARY_PATH=$LIBRARY_PATH \ -DCMAKE_INCLUDE_PATH=$INCLUDE_PATH \ -DCMAKE_PREFIX_PATH=$PREFIX_PATH \ - -DCMAKE_INSTALL_PREFIX=$HOME/eressea/server" + -DCMAKE_INSTALL_PREFIX=$DEST" + +git submodule update --init path="$(which tolua)" if [ "$HAVE_TOLUA" = "0" ] || [ -z $path ] ; then echo "tolua is not installed, building from source" - cd $ROOT/tolua ; make + cd $ROOT + if [ ! -d tolua ]; then + LUA_VERSION="5.2" + if [ -d /usr/include/lua5.1 ] || [ -d /usr/local/include/lua5.1 ]; then + LUA_VERSION="5.1" + fi + echo "fetching tolua ${LUA_VERSION} from github..." + git clone https://github.com/ennorehling/tolua-${LUA_VERSION}.git tolua + fi + echo "building tolua..." + cd tolua + make ARGS="$ARGS -DPC_TOLUA_DIR=$ROOT/tolua" else echo "tolua is $path" diff --git a/s/install b/s/install index 18cc2393f..962961063 100755 --- a/s/install +++ b/s/install @@ -8,14 +8,11 @@ while [ ! -d $ROOT/.git ]; do fi done -DEST=$(dirname $ROOT)/server - -MACHINE=`uname -m` [ -z "$CC" ] && [ ! -z `which clang` ] && CC="clang" [ -z "$CC" ] && [ ! -z `which gcc` ] && CC="gcc" [ -z "$CC" ] && [ ! -z `which tcc` ] && CC="tcc" [ -z "$CC" ] && [ ! -z `which cc` ] && CC="cc" -BIN_DIR="build-$MACHINE-$CC-Debug" +BIN_DIR="Debug" cd $ROOT/$BIN_DIR make install diff --git a/s/preview b/s/preview index 79411aea6..68fe6e39f 100755 --- a/s/preview +++ b/s/preview @@ -22,11 +22,12 @@ exit $2 # otherwise function build() { assert_dir $SOURCE cd $SOURCE +rm -rf crypto tolua git fetch || abort "failed to update source. do you have local changes?" [ -z $1 ] || git checkout $1 -git pull +git pull -q git submodule update -s/build || abort "build failed." +s/build > /dev/null || abort "build failed." } function assert_file() { @@ -44,13 +45,6 @@ function assert_dir() { [ -d $1 ] || abort "missing directory: $1" } -function version() { -assert_dir $SOURCE -cd $SOURCE -build=$(grep BUILD src/buildno.h | awk '{ print $3 }') -echo "eressea build $build" -} - function setup() { assert_dir $SOURCE assert_dir $LIVE @@ -85,9 +79,9 @@ SUPP="$SOURCE/share/debian-7_8.supp" SERVER="$SOURCE/Debug/eressea/eressea" VALGRIND=$(which valgrind) if [ ! -z $VALGRIND ]; then -SERVER="$VALGRIND --suppressions=$SUPP --error-exitcode=1 --leak-check=no $SERVER" +SERVER="$VALGRIND --quiet --suppressions=$SUPP --error-exitcode=1 --leak-check=no $SERVER" fi -$SERVER -v$verbose -t$turn -re$game $SOURCE/scripts/run-turn.lua +$SERVER -v$verbose -t$turn $SOURCE/scripts/run-turn.lua let turn=$turn+1 [ -e data/$turn.dat ] || abort "no data file created" } @@ -137,9 +131,6 @@ shift $((OPTIND-1)) while [ ! -z $1 ]; do case "$1" in -"version") - version - ;; "build") shift build $* @@ -169,7 +160,7 @@ case "$1" in done if [ $sent -eq 0 ]; then if [ -e ../$factions ]; then - for faction in $(cat ../$factions) ; do + for faction in $(grep -v -E '^#' ../$factions) ; do send $faction done fi diff --git a/s/runtests b/s/runtests index 2f22402dc..e42640de1 100755 --- a/s/runtests +++ b/s/runtests @@ -1,11 +1,7 @@ #!/bin/bash set -e -ROOT=$(pwd) -while [ ! -d $ROOT/.git ]; do - ROOT=$(dirname $ROOT) -done - +ROOT=$(git rev-parse --show-toplevel) [ -z $BUILD ] && BUILD=Debug ; export BUILD if [ ! -e $ROOT/$BUILD ]; then @@ -16,10 +12,9 @@ fi $ROOT/$BUILD/eressea/test_eressea cd $ROOT [ -e eressea.ini ] || ln -sf conf/eressea.ini -$ROOT/$BUILD/eressea/eressea -v0 scripts/run-tests.lua -$ROOT/$BUILD/eressea/eressea -v0 scripts/run-tests-e2.lua -$ROOT/$BUILD/eressea/eressea -v0 scripts/run-tests-e3.lua -$ROOT/$BUILD/eressea/eressea -v0 scripts/run-tests-e4.lua +$ROOT/$BUILD/eressea/eressea -v1 scripts/run-tests.lua +$ROOT/$BUILD/eressea/eressea -v1 scripts/run-tests-e2.lua +$ROOT/$BUILD/eressea/eressea -v1 scripts/run-tests-e3.lua rm -rf data reports orders.txt score score.alliances datum turn cd $OLDWPD diff --git a/s/setup b/s/setup index 0839d5b8f..e3e8e113d 100755 --- a/s/setup +++ b/s/setup @@ -1,5 +1,15 @@ #!/bin/bash +ROOT=$(pwd) +while [ ! -d $ROOT/.git ]; do + ROOT=$(dirname $ROOT) + if [ "/" = "$ROOT" ]; then + echo "could not find root, are you in the git repository?" + exit + fi +done +ERESSEA=$(dirname $ROOT) + function abort() { echo $1 [ -z $2 ] && exit -1 @@ -37,7 +47,6 @@ while getopts :d:g:r:s:hfn o; do done [ $game -gt 0 ] || abort "must use a positive integer for game id" -[ -d $ERESSEA ] || abort "invalid or missing env variable ERESSEA ($ERESSEA)" [ -z $SOURCE ] && SOURCE=$ERESSEA/$src [ -d $SOURCE ] || abort "invalid source directory $SOURCE" [ -z $rules ] && rules=e$game @@ -46,7 +55,8 @@ done [ -e $TOOLS ] || TOOLS=$SOURCE/bin [ -z $INIFILE ] && INIFILE=$TOOLS/inifile [ -e $INIFILE ] || INIFILE=$TOOLS/iniparser/inifile -#[ -e $INIFILE ] || abort "tool is not installed: $INIFILE" + +[ -e $SOURCE/conf/$rules/config.xml ] || abort "cannot find conf/$rules/config.xml" cd $ERESSEA if [ -d $dir ] ; then @@ -84,8 +94,10 @@ touch eressea.ini } ini_start -ini_sec eressea -ini_add eressea locales de,en +ini_sec game +ini_add game locales de,en +ini_add game id $game +ini_add game start 1 ini_sec lua ini_add lua install $SOURCE ini_add lua paths $SOURCE/scripts:$SOURCE/lunit diff --git a/s/travis-build b/s/travis-build index 45db05c60..9293ac12d 100755 --- a/s/travis-build +++ b/s/travis-build @@ -10,7 +10,7 @@ $BUILD/iniparser/inifile eressea.ini add lua:paths lunit:scripts fi } -integraton_tests() { +integration_tests() { cd tests ./write-reports.sh ./run-turn.sh @@ -18,11 +18,10 @@ cd tests set -e [ -z $BUILD ] && BUILD=Debug ; export BUILD -cmake --version s/cmake-init s/build cd $ROOT inifile s/runtests -integraton_tests +integration_tests diff --git a/s/upgrade b/s/upgrade new file mode 100755 index 000000000..9d9d5a313 --- /dev/null +++ b/s/upgrade @@ -0,0 +1,14 @@ +#!/bin/sh +set -e + +ROOT=`pwd` +while [ ! -d $ROOT/.git ]; do + ROOT=`dirname $ROOT` +done + +cd $ROOT +git pull +git submodule update +s/build +s/runtests +s/install diff --git a/scripts/eressea/autoseed.lua b/scripts/eressea/autoseed.lua index 562c39361..9e5060f85 100644 --- a/scripts/eressea/autoseed.lua +++ b/scripts/eressea/autoseed.lua @@ -1,3 +1,4 @@ +if not config.autoseed then return nil end local autoseed = {} -- minimum required resources in the 7-hex neighborhood: @@ -64,9 +65,9 @@ local function seed(r, email, race, lang) assert(f) local u = unit.create(f, r) assert(u) - equip_unit(u, "new_faction") - equip_unit(u, "first_unit") - equip_unit(u, "first_" .. race, 7) -- disable old callbacks + equip_unit(u, "autoseed_faction") + equip_unit(u, "autoseed_unit") + equip_unit(u, "autoseed_" .. race, 7) unit.create(f, r, 5):set_skill("mining", 30) unit.create(f, r, 5):set_skill("quarrying", 30) f:set_origin(r) diff --git a/scripts/eressea/e2/init.lua b/scripts/eressea/e2/init.lua index ed996c395..722078741 100644 --- a/scripts/eressea/e2/init.lua +++ b/scripts/eressea/e2/init.lua @@ -11,7 +11,7 @@ return { require('eressea.tunnels'), require('eressea.ponnuki'), require('eressea.astral'), - require('eressea.locales'), +-- require('eressea.locales'), require('eressea.jsreport'), require('eressea.ents'), require('eressea.cursed') diff --git a/scripts/eressea/e3/rules.lua b/scripts/eressea/e3/rules.lua index c0ac8978a..e7a54ff41 100644 --- a/scripts/eressea/e3/rules.lua +++ b/scripts/eressea/e3/rules.lua @@ -1,31 +1,3 @@ --- when appending to this, make sure the item has a canuse-function! -local goblin_denied = " plate lance mallornlance greatbow axe greatsword halberd rustyaxe rustyhalberd towershield scale " -function item_canuse(u, iname) - local race = u.race - if race=="goblin" then - if string.find(goblin_denied, " " .. iname .. " ") then - return false - end - end - if iname=="rep_crossbow" then - -- only dwarves and halflings allowed to use repeating crossbow - return race=="dwarf" or race=="halfling" - end - if iname=="scale" then - -- only dwarves and halflings can use scale - return race=="dwarf" or race=="halfling" - end - if iname=="towershield" then - -- only dwarves allowed to use towershield - return race=="dwarf" - end - if iname=="greatbow" then - -- only elves use greatbow - return race=="elf" - end - return true -end - function building_taxes(b, blevel) btype = b.type if btype=="castle" then diff --git a/scripts/eressea/e4/init.lua b/scripts/eressea/e4/init.lua deleted file mode 100644 index 32c0b8498..000000000 --- a/scripts/eressea/e4/init.lua +++ /dev/null @@ -1,11 +0,0 @@ -require 'eressea.e3.rules' -require 'eressea.spells' - -eressea.log.debug("rules for game E4") - -return { - require('eressea'), - -- require('eressea.markets'), - require('eressea.frost'), - require('eressea.ents') -} diff --git a/scripts/eressea/embassy.lua b/scripts/eressea/embassy.lua index efbe248b7..93ff66d7c 100644 --- a/scripts/eressea/embassy.lua +++ b/scripts/eressea/embassy.lua @@ -1,12 +1,14 @@ -- Muschelplateau +if not config.embassy then return nil end + local embassy = {} local home = nil -- global exports (use item) function use_seashell(u, amount) -- Muschelplateau... - local visit = u.faction.objects:get("embassy_muschel") + local visit = u.faction:get_key('mupL') if visit and u.region~= home then local turns = get_turn() - visit local msg = message.create('msg_event') @@ -32,10 +34,10 @@ function embassy.update() eressea.log.debug("updating embassies in " .. tostring(home)) local u for u in home.units do - if u.faction.objects:get('embassy_muschel')==nil then + if u.faction:get_key('mupL')==0 then if (u.faction:add_item('seashell', 1)>0) then eressea.log.debug("new seashell for " .. tostring(u.faction)) - u.faction.objects:set('embassy_muschel', get_turn()) + u.faction:set_key('mupL', get_turn()) end end end diff --git a/scripts/eressea/ents.lua b/scripts/eressea/ents.lua index c764d8e0a..7808917fa 100644 --- a/scripts/eressea/ents.lua +++ b/scripts/eressea/ents.lua @@ -2,7 +2,7 @@ local function create_ents(r, number) local f = get_faction(666) if f~=nil and number>0 then u = unit.create(f, r, number, "ent") - u.name = "Wütende Ents" + u.name = "Rasende Ents" u:set_skill("perception", 2) msg = message.create("entrise") @@ -13,21 +13,11 @@ local function create_ents(r, number) return nil end -local function repair_ents(r) - for u in r.units do - if u.faction.id==666 and u.race == "undead" and u.name == "Wütende Ents" then - eressea.log.info("ent repair: " .. tostring(u)) - u.race = "ent" - end - end -end - local ents = {} function ents.update() local r for r in regions() do - repair_ents(r) if r:get_flag(0) then -- RF_CHAOTIC if r.terrain == "plain" and r:get_resource("tree")==0 then if math.random(3)==1 then diff --git a/scripts/eressea/eternath.lua b/scripts/eressea/eternath.lua index 858a8d462..063577b74 100644 --- a/scripts/eressea/eternath.lua +++ b/scripts/eressea/eternath.lua @@ -1,5 +1,5 @@ -- DEPRECATED - +if not config.eternath then return nil end -- implements parts of a quest in E2 -- this module is deprecated, because it puts functions in the global environment for at_building_action diff --git a/scripts/eressea/ponnuki.lua b/scripts/eressea/ponnuki.lua index f220aa380..96bb0b5f1 100644 --- a/scripts/eressea/ponnuki.lua +++ b/scripts/eressea/ponnuki.lua @@ -1,3 +1,4 @@ +if not config.ponnuki then return nil end local ponnuki = {} local directions = { "NW", "NO", "O", "SO", "SW", "W" } @@ -25,11 +26,10 @@ function ponnuki.init() local home = get_region(-67, -5) local f = get_faction(666) if home and f then - u = add_unit(f, home) + u = unit.create(f, home, 1, "illusion") u.id = atoi36("ponn") u.name = "Ponnuki" u.info = "Go, Ponnuki, Go!" - u.race = "illusion" u:set_racename("Ritter von Go") else eressea.log.error("Ponnuki cannot find Magrathea") diff --git a/scripts/eressea/resources.lua b/scripts/eressea/resources.lua index 94908c1ab..fa6e1c4da 100644 --- a/scripts/eressea/resources.lua +++ b/scripts/eressea/resources.lua @@ -1,16 +1,5 @@ -- global functions used in items.xml -if not item_canuse then - -- define a default, everyone can use everything - function item_canuse(u, iname) - return true - end -end - -function peasant_getresource(u) - return u.region:get_resource("peasant") -end - function peasant_changeresource(u, delta) local p = u.region:get_resource("peasant") p = p + delta @@ -21,10 +10,6 @@ function peasant_changeresource(u, delta) return p end -function hp_getresource(u) - return u.hp -end - function hp_changeresource(u, delta) local hp = u.hp + delta @@ -38,8 +23,47 @@ function hp_changeresource(u, delta) return hp end +local function mallorn_region(r) + return r:get_flag(1) -- RF_MALLORN +end + +function seed_limit(r) + if mallorn_region(r) then + return 0 + end + return r:get_resource("seed") +end + +function seed_produce(r, n) + if not mallorn_region(r) then + local seeds = r:get_resource("seed") + if seeds>=n then + r:set_resource("seed", seeds-n) + else + r:set_resource("seed", 0) + end + end +end + +function mallornseed_limit(r) + if mallorn_region(r) then + return r:get_resource("seed") + end + return 0 +end + +function mallornseed_produce(r, n) + if mallorn_region(r) then + local seeds = r:get_resource("seed") + if seeds>=n then + r:set_resource("seed", seeds-n) + else + r:set_resource("seed", 0) + end + end +end function horse_limit(r) - return r:get_resource("horse") + return r:get_resource("horse") end function horse_produce(r, n) @@ -52,9 +76,6 @@ function horse_produce(r, n) end function log_limit(r) --- if r:get_flag(1) then -- RF_MALLORN --- return 0 --- end return r:get_resource("tree") + r:get_resource("sapling") end @@ -75,7 +96,7 @@ function log_produce(r, n) end function mallorn_limit(r) - if not r:get_flag(1) then -- RF_MALLORN + if not mallorn_region(r) then return 0 end return r:get_resource("tree") + r:get_resource("sapling") diff --git a/scripts/eressea/wedding.lua b/scripts/eressea/wedding.lua index 812bd3269..2c06d9891 100644 --- a/scripts/eressea/wedding.lua +++ b/scripts/eressea/wedding.lua @@ -1,4 +1,5 @@ -- DEPRECATED +if not config.wedding then return nil end -- this script contains the action functions for the two portals -- used on the jadee/wildente wedding island. the two _action functions diff --git a/scripts/eressea/xmas.lua b/scripts/eressea/xmas.lua index 36e755f45..0316e6265 100644 --- a/scripts/eressea/xmas.lua +++ b/scripts/eressea/xmas.lua @@ -1,3 +1,5 @@ +if not config.xmas then return nil end + local gifts = { e2 = { { year = 2015, turn = 959, item = 'snowglobe', msg='santa_f' }, diff --git a/scripts/eressea/xmasitems.lua b/scripts/eressea/xmasitems.lua index b31691d72..27ea641ee 100644 --- a/scripts/eressea/xmasitems.lua +++ b/scripts/eressea/xmasitems.lua @@ -25,6 +25,7 @@ end function use_stardust(u, amount) local p = u.region:get_resource("peasant") + assert(p>0) p = math.ceil(1.5 * p) u.region:set_resource("peasant", p) local msg = usepotion_message(u, "stardust") @@ -62,9 +63,7 @@ end function use_snowman(u, amount) if amount>0 and u.region.terrain == "glacier" then - local man = unit.create(u.faction, u.region) - man.race = "snowman" - man.number = amount + local man = unit.create(u.faction, u.region, amount, "snowman") return amount end return -4 diff --git a/scripts/eressea/xmlconf.lua b/scripts/eressea/xmlconf.lua index 9d87f3f3e..84f29eceb 100644 --- a/scripts/eressea/xmlconf.lua +++ b/scripts/eressea/xmlconf.lua @@ -4,6 +4,8 @@ if config.install then end if config.rules then local rules = config.rules .. '/' - assert(0 == read_xml(confdir .. rules .. 'config.xml', confdir .. rules .. 'catalog.xml'), "could not load XML data, did you compile with LIBXML2 ?") assert(0 == eressea.config.read(rules .. 'config.json', confdir), "could not read JSON data") + assert(0 == read_xml(confdir .. rules .. 'rules.xml', confdir .. rules .. 'catalog.xml'), "could not load XML data, did you compile with LIBXML2 ?") + assert(0 == read_xml(confdir .. rules .. 'locales.xml', confdir .. rules .. 'catalog.xml'), "could not load XML data, did you compile with LIBXML2 ?") end +eressea.game.reset() diff --git a/scripts/run-tests-e4.lua b/scripts/run-tests-e4.lua deleted file mode 100644 index f827baec0..000000000 --- a/scripts/run-tests-e4.lua +++ /dev/null @@ -1,23 +0,0 @@ --- Tests that work in E3. With game config of E3. --- Tests are under scripts/test/e3 and all files must be in scripts/test/e3/init.lua - -path = 'scripts' -if config.install then - path = config.install .. '/' .. path - package.path = package.path .. ';' .. config.install .. '/lunit/?.lua' - --needed to find lunit if not run form eressea root. Needs right [lua] install setting in eressea.ini (point to eressea root from the start folder) -end -package.path = package.path .. ';' .. path .. '/?.lua;' .. path .. '/?/init.lua' - -config.rules = 'e4' - -require 'eressea' -require 'eressea.path' -require 'eressea.xmlconf' -require 'tests.e3' -require 'lunit' - -eressea.settings.set("rules.alliances", "0") -rules = require('eressea.' .. config.rules) -result = lunit.main() -return result.errors + result.failed diff --git a/scripts/run-turn.lua b/scripts/run-turn.lua index 7ee9165ca..9118ed8ee 100644 --- a/scripts/run-turn.lua +++ b/scripts/run-turn.lua @@ -26,15 +26,17 @@ function callbacks(rules, name, ...) end local function dbupdate() - update_scores() - dbname = config.dbname or 'eressea.db' - edb = db.open(config.basepath..'/'..dbname) - if edb~=nil then - edb:update_factions() - edb:update_scores() - else - eressea.log.error("could not open "..config.basepath..'/'..dbname) - end + update_scores() + if config.dbname then + dbname = config.basepath..'/'..config.dbname + edb = db.open(dbame) + if edb~=nil then + edb:update_factions() + edb:update_scores() + else + eressea.log.error("could not open "..dbname) + end + end end local function write_emails(locales) @@ -144,7 +146,7 @@ function process(rules, orders) init_summary() -- run the turn: - if read_orders(orders) ~= 0 then + if eressea.read_orders(orders) ~= 0 then print("could not read " .. orders) return -1 end diff --git a/scripts/tests/bindings.lua b/scripts/tests/bindings.lua index 189d34769..9aab6fd57 100644 --- a/scripts/tests/bindings.lua +++ b/scripts/tests/bindings.lua @@ -34,7 +34,6 @@ function test_process() assert_equal("function", _G.type(eressea.process.siege)) assert_equal("function", _G.type(eressea.process.leave)) assert_equal("function", _G.type(eressea.process.promote)) - assert_equal("function", _G.type(eressea.process.renumber)) assert_equal("function", _G.type(eressea.process.restack)) assert_equal("function", _G.type(eressea.process.set_spells)) assert_equal("function", _G.type(eressea.process.set_help)) diff --git a/scripts/tests/common.lua b/scripts/tests/common.lua index c39f2ce30..4f6ed9cbb 100644 --- a/scripts/tests/common.lua +++ b/scripts/tests/common.lua @@ -330,17 +330,6 @@ function test_message() return msg end -function test_hashtable() - local f = faction.create("noreply1@eressea.de", "human", "de") - f.objects:set("enno", "smart guy") - f.objects:set("age", 10) - assert(f.objects:get("jesus") == nil) - assert(f.objects:get("enno") == "smart guy") - assert(f.objects:get("age") == 10) - f.objects:set("age", nil) - assert(f.objects:get("age") == nil) -end - function test_events() local fail = 1 local function msg_handler(u, evt) @@ -380,6 +369,21 @@ function test_events() assert(fail==0) end +function test_renumber_ship() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply4@eressea.de", "human", "de") + local u = unit.create(f, r) + local s = ship.create(r, config.ships[1]) + u.ship = s + u:add_order("NUMMER SCHIFF 1") + process_orders() + assert_equal(1, s.id) + u:clear_orders() + u:add_order("NUMMER SCHIFF 2") + process_orders() + assert_equal(2, s.id) +end + function test_recruit2() local r = region.create(0, 0, "plain") local f = faction.create("noreply4@eressea.de", "human", "de") @@ -434,10 +438,9 @@ function test_recruit() u:add_item("money", 110*n+20) u:add_order("REKRUTIERE " .. n) process_orders() - assert(u.number == n+1) + assert_equal(n+1, u.number) local p = r:get_resource("peasant") - assert(p<200 and p>=200-n) - -- assert(u:get_item("money")==10) + assert_true(p<200 and p>=200-n) end function test_produce() @@ -464,7 +467,7 @@ function test_work() u:clear_orders() u:add_order("ARBEITEN") process_orders() - assert(u:get_item("money")>=10) + assert_equal(20, u:get_item("money")) end function test_upkeep() @@ -476,7 +479,7 @@ function test_upkeep() u:clear_orders() u:add_order("LERNE Waffenbau") process_orders() - assert(u:get_item("money")==u.number) + assert_equal(u:get_item("money"), u.number) end function test_id() @@ -484,50 +487,39 @@ function test_id() local f = faction.create("noreply11@eressea.de", "human", "de") f.id = atoi36("42") - assert(get_faction(42)~=f) - assert(get_faction("42")==f) - assert(get_faction(atoi36("42"))==f) + assert_not_equal(f, get_faction(42)) + assert_equal(f, get_faction("42")) + assert_equal(f, get_faction(atoi36("42"))) local u = unit.create(f, r, 1) u.id = atoi36("42") - assert(get_unit(42)~=u) - assert(get_unit("42")==u) - assert(get_unit(atoi36("42"))==u) + assert_not_equal(get_unit(42), u) + assert_equal(get_unit("42"), u) + assert_equal(get_unit(atoi36("42")), u) local b = building.create(r, "castle") -- b.id = atoi36("42") local fortytwo = itoa36(b.id) - assert(get_building(fortytwo)==b) - assert(get_building(atoi36(fortytwo))==b) + assert_equal(get_building(fortytwo), b) + assert_equal(get_building(atoi36(fortytwo)), b) local s = _test_create_ship(r) assert_not_nil(s) -- s.id = atoi36("42") local fortytwo = itoa36(s.id) - assert(get_ship(fortytwo)==s) - assert(get_ship(atoi36(fortytwo))==s) -end - -function test_herbalism() - local r = region.create(0, 0, "plain") - local f = faction.create("noreply12@eressea.de", "human", "de") - local u = unit.create(f, r, 1) - u:add_item("money", u.number * 100) - u:set_skill("herbalism", 5) - u:clear_orders() - u:add_order("MACHE Samen") - process_orders() + assert_equal(get_ship(fortytwo), s) + assert_equal(get_ship(atoi36(fortytwo)), s) end function test_mallorn() local r = region.create(0, 0, "plain") r:set_flag(1, false) -- not mallorn r:set_resource("tree", 100) - assert(r:get_resource("tree")==100) + assert_equal(100, r:get_resource("tree")) local m = region.create(0, 0, "plain") m:set_flag(1, true) -- mallorn m:set_resource("tree", 100) - assert(m:get_resource("tree")==100) + assert_equal(100, m:get_resource("tree")) local f = faction.create("noreply13@eressea.de", "human", "de") @@ -1036,3 +1028,34 @@ function test_recruit() assert_equal(6, u.number) end end + +function test_give_horses() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + + r:set_resource("horse", 0) + u:add_item("horse", 21) + u:add_item("dolphin", 10) + u:add_order("GIB 0 7 PFERD") + u:add_order("GIB 0 5 DELPHIN") + process_orders() + assert_equal(7, r:get_resource("horse")) + assert_equal(5, u:get_item("dolphin")) + assert_equal(14, u:get_item("horse")) +end + +function test_give_silver() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + + r:set_resource("peasant", 0) + r:set_resource("money", 11) + u:clear_orders() + u:add_item("money", 20) + u:add_order("GIB 0 10 SILBER") + process_orders() + assert_equal(21, r:get_resource("money")) + assert_equal(10, u:get_item("money")) +end diff --git a/scripts/tests/config.lua b/scripts/tests/config.lua index d21ecda1e..e47b7f925 100644 --- a/scripts/tests/config.lua +++ b/scripts/tests/config.lua @@ -9,19 +9,15 @@ end function test_read_race() local f eressea.free_game() - f = faction.create("orc@example.com", "orc", "en") - assert_equal(nil, f) assert_not_nil(eressea.config) eressea.config.parse('{ "races": { "orc" : {}}}') f = faction.create("orc@example.com", "orc", "en") assert_not_nil(f) end -function test_read_ship() +function disable_test_read_ship() local s eressea.free_game() - s = ship.create(nil, "boat") - assert_equal(nil, s) assert_not_nil(eressea.config) conf = [[{ "ships": { diff --git a/scripts/tests/e2/e2features.lua b/scripts/tests/e2/e2features.lua index efed50ea1..da2a98d55 100644 --- a/scripts/tests/e2/e2features.lua +++ b/scripts/tests/e2/e2features.lua @@ -2,6 +2,38 @@ require "lunit" module("tests.e2.e2features", package.seeall, lunit.testcase ) +function setup() + eressea.free_game() + eressea.settings.set("nmr.timeout", "0") + eressea.settings.set("rules.food.flags", "4") + eressea.settings.set("rules.ship.storms", "0") + eressea.settings.set("rules.encounters", "0") +end + +function test_herbalism() +-- OBS: herbalism is currently an E2-only skill + local r = region.create(0, 0, "plain") + local f = faction.create("herbalism@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + + eressea.settings.set("rules.grow.formula", 0) -- plants do not grow + u:add_item("money", u.number * 100) + u:set_skill("herbalism", 5) + r:set_resource("seed", 100) + r:set_flag(1, false) -- regular trees + u:clear_orders() + u:add_order("MACHE Samen") + process_orders() + assert_equal(1, u:get_item("seed")) + assert_equal(99, r:get_resource("seed")) + r:set_flag(1, true) -- mallorn + u:clear_orders() + u:add_order("MACHE Mallornsamen") + process_orders() + assert_equal(1, u:get_item("mallornseed")) + assert_equal(98, r:get_resource("seed")) +end + function test_build_harbour() -- try to reproduce mantis bug 2221 local r = region.create(0, 0, "plain") @@ -42,13 +74,6 @@ local function two_units(r, f1, f2) return one_unit(r, f1), one_unit(r, f2) end -function setup() - eressea.free_game() - eressea.settings.set("nmr.timeout", "0") - eressea.settings.set("rules.food.flags", "4") - eressea.settings.set("rules.ship.storms", "0") -end - function test_learn() eressea.settings.set("study.random_progress", "0") local r = region.create(0, 0, "plain") @@ -205,24 +230,6 @@ function test_no_uruk() assert_equal(f1.race, "orc") end -function test_snowman() - local r = region.create(0, 0, "glacier") - local f = faction.create("noreply@eressea.de", "human", "de") - local u = unit.create(f, r, 1) - u:add_item("snowman", 1) - u:clear_orders() - u:add_order("BENUTZEN 1 Schneemann") - process_orders() - for u2 in r.units do - if u2.id~=u.id then - assert_equal(u2.race, "snowman") - u = nil - break - end - end - assert_equal(nil, u) -end - function test_block_movement() eressea.settings.set("rules.guard.base_stop_prob", "0.3") eressea.settings.set("rules.guard.amulet_stop_prob", "0.0") diff --git a/scripts/tests/e2/guard.lua b/scripts/tests/e2/guard.lua index f5be800c2..8e62a364d 100644 --- a/scripts/tests/e2/guard.lua +++ b/scripts/tests/e2/guard.lua @@ -13,24 +13,24 @@ function test_guard_unarmed() local r1 = region.create(0, 0, "plain") local f1 = faction.create("hodor@eressea.de", "human", "de") local u1 = unit.create(f1, r1, 1) - assert_equal(nil, u1.guard) + assert_equal(false, u1.guard) u1:clear_orders() u1:add_order("BEWACHE") process_orders() - assert_equal(nil, u1.guard) + assert_equal(false, u1.guard) end function test_guard_armed() local r1 = region.create(0, 0, "plain") local f1 = faction.create("hodor@eressea.de", "human", "de") local u1 = unit.create(f1, r1, 1) - assert_equal(nil, u1.guard) + assert_equal(false, u1.guard) u1:add_item("sword", 1) u1:set_skill("melee", 2) u1:clear_orders() u1:add_order("BEWACHE") process_orders() - assert_equal(249, u1.guard) + assert_equal(true, u1.guard) end function test_guard_allows_move_after_combat() -- bug 1493 @@ -47,7 +47,7 @@ function test_guard_allows_move_after_combat() -- bug 1493 u1:clear_orders() u1:add_order("BEWACHE") process_orders() - assert_equal(249, u1.guard) + assert_equal(true, u1.guard) u1:clear_orders() u1:add_order("NACH O") u1:add_order("ATTACKIERE " .. itoa36(u2.id)) @@ -67,7 +67,7 @@ function test_no_guard_no_move_after_combat() -- bug 1493 u1:add_order("BEWACHE") u1:add_item("sword", 10) u1:set_skill("melee", 2) - assert_equal(nil, u1.guard) + assert_equal(false, u1.guard) u1:clear_orders() u1:add_order("NACH O") u1:add_order("ATTACKIERE " .. itoa36(u2.id)) diff --git a/scripts/tests/e2/init.lua b/scripts/tests/e2/init.lua index 2fdad1898..5f81933d7 100644 --- a/scripts/tests/e2/init.lua +++ b/scripts/tests/e2/init.lua @@ -1,3 +1,5 @@ +require 'tests.economy' + require 'tests.e2.undead' require 'tests.e2.shiplanding' require 'tests.e2.e2features' @@ -6,6 +8,8 @@ require 'tests.e2.destroy' require 'tests.e2.guard' require 'tests.e2.spells' require 'tests.e2.stealth' +require 'tests.e2.items' +require 'tests.items' require 'tests.orders' require 'tests.common' require 'tests.report' diff --git a/scripts/tests/e2/items.lua b/scripts/tests/e2/items.lua new file mode 100644 index 000000000..24f27f4b2 --- /dev/null +++ b/scripts/tests/e2/items.lua @@ -0,0 +1,159 @@ +require "lunit" + +module("tests.e2.items", package.seeall, lunit.testcase ) + +function setup() + eressea.free_game() + eressea.settings.set("nmr.timeout", "0") + eressea.settings.set("rules.food.flags", "4") + eressea.settings.set("rules.ship.storms", "0") + eressea.settings.set("rules.encounters", "0") + eressea.settings.set("magic.regeneration.enable", "0") +end + +function test_nestwarmth_insect() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "insect", "de") + local u = unit.create(f, r, 1) + local flags = u.flags + u:add_item("nestwarmth", 2) + u:clear_orders() + u:add_order("BENUTZEN 1 Nestwaerme") + turn_begin() + turn_process() + assert_equal(flags+64, u.flags) -- UFL_WARMTH + assert_equal(1, u:get_item("nestwarmth")) + assert_equal(1, f:count_msg_type('usepotion')) + turn_end() +end + +function test_nestwarmth_other() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + local flags = u.flags + u:add_item("nestwarmth", 2) + u:clear_orders() + u:add_order("BENUTZEN 1 Nestwaerme") + turn_begin() + turn_process() + assert_equal(flags, u.flags) -- nothing happens + assert_equal(2, u:get_item("nestwarmth")) + assert_equal(1, f:count_msg_type('error163')) + turn_end() +end + +function test_meow() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + u:add_item("aoc", 1) + u:clear_orders() + u:add_order("BENUTZEN 1 Katzenamulett") + turn_begin() + turn_process() + assert_equal(1, u:get_item("aoc")) + assert_equal(1, r:count_msg_type('meow')) + turn_end() +end + +function test_aurapotion50() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + u:add_item("aurapotion50", 1) + u:set_skill('magic', 10); + u.magic = 'gwyrrd' + u.aura = 0 + u:clear_orders() + u:add_order("BENUTZEN 1 Auratrank") + turn_begin() + turn_process() + assert_equal(0, u:get_item("aurapotion50")) + assert_equal(1, f:count_msg_type('aurapotion50')) + assert_equal(50, u.aura) + turn_end() +end + +function test_bagpipe() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + turn_begin() + u:add_item("bagpipeoffear", 1) + u:clear_orders() + u:add_order("BENUTZEN 1 Dudelsack") + assert_equal(nil, r:get_curse('depression')) + turn_process() + assert_equal(0, r:get_curse('depression')) + assert_equal(1, u:get_item("bagpipeoffear")) + assert_equal(1, f:count_msg_type('bagpipeoffear_faction')) + assert_equal(1, r:count_msg_type('bagpipeoffear_region')) + turn_end() + -- duration is variable, but at least 4 + assert_equal(0, r:get_curse('depression')) +end + +function test_speedsail() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + + turn_begin() + u.ship = ship.create(r, "boat") + u:add_item("speedsail", 2) + u:clear_orders() + u:add_order("BENUTZEN 1 Sonnensegel") + assert_equal(nil, u.ship:get_curse('shipspeed')) + turn_process() + assert_equal(1, u.ship:get_curse('shipspeed')) + assert_equal(1, u:get_item("speedsail")) + assert_equal(1, f:count_msg_type('use_speedsail')) + turn_end() + assert_equal(1, u.ship:get_curse('shipspeed')) -- effect stays forever +end + +function test_foolpotion() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + turn_begin() + u:add_item("p7", 1) + u:clear_orders() + u:add_order("BENUTZEN 1 Dumpfbackenbrot 4242") + turn_process() + assert_equal(1, u:get_item("p7")) + assert_equal(1, f:count_msg_type('feedback_unit_not_found')) + local u2 = unit.create(f, r, 1) + + u:clear_orders() + u:add_order("BENUTZEN 1 Dumpfbackenbrot " .. itoa36(u2.id)) + turn_process() + assert_equal(1, u:get_item("p7")) + assert_equal(1, f:count_msg_type('error64')) + + u:set_skill("stealth", 1); + turn_process() + assert_equal(0, u:get_item("p7")) + assert_equal(1, f:count_msg_type('givedumb')) + turn_end() +end + +function test_snowman() + local r = region.create(0, 0, "glacier") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + u:add_item("snowman", 1) + u:clear_orders() + u:add_order("BENUTZEN 1 Schneemann") + process_orders() + for u2 in r.units do + if u2.id~=u.id then + assert_equal("snowman", u2.race) + assert_equal(1000, u2.hp) + u = nil + break + end + end + assert_equal(nil, u) +end diff --git a/scripts/tests/e3/castles.lua b/scripts/tests/e3/castles.lua index 1fd4e13e9..b16019159 100644 --- a/scripts/tests/e3/castles.lua +++ b/scripts/tests/e3/castles.lua @@ -11,30 +11,62 @@ function teardown() eressea.settings.set("rules.food.flags", "0") end +function test_build_watch() + local r = region.create(0, 0, "plain") + local f = faction.create("e3build@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + + u.number = 20 + u:add_item("log", 20) + u.id = 42 + + u:set_skill("building", 1) + u:add_order("MACHE Wache") + process_orders() + assert_not_nil(u.building) + assert_equal(5, u.building.size) + + u:set_skill("building", 2) + u:add_order("MACHE Wache " .. itoa36(u.building.id)) + process_orders() + assert_not_nil(u.building) + assert_equal(10, u.building.size) +end + +function test_watch() + local r = region.create(0, 0, "plain") + local b = building.create(r, "watch") + + assert_equal("scaffolding", b:get_typename(1)) + assert_equal("scaffolding", b:get_typename(4)) + assert_equal("guardhouse", b:get_typename(5)) + assert_equal("guardhouse", b:get_typename(9)) + assert_equal("guardtower", b:get_typename(10)) +end + function test_small_castles() - local r = region.create(0, 0, "plain") - local f1 = faction.create("noreply@eressea.de", "human", "de") - local u1 = unit.create(f1, r, 1) - local f2 = faction.create("noreply@eressea.de", "halfling", "de") - local u2 = unit.create(f2, r, 1) - u1:add_item("money", 10000) + local r = region.create(0, 0, "plain") + local f1 = faction.create("noreply@eressea.de", "human", "de") + local u1 = unit.create(f1, r, 1) + local f2 = faction.create("noreply@eressea.de", "halfling", "de") + local u2 = unit.create(f2, r, 1) - local b = building.create(r, "castle") - u2.building = b - u1.building = b + local b = building.create(r, "castle") + u2.building = b + u1.building = b - b.owner = u2 - assert_equal("site", b:get_typename(7)) - assert_equal("fortification", b:get_typename(8)) - b.owner = u1 - assert_equal("site", b:get_typename(9)) - assert_equal("fortification", b:get_typename(10)) + b.owner = u2 + assert_equal("site", b:get_typename(7)) + assert_equal("fortification", b:get_typename(8)) + b.owner = u1 + assert_equal("site", b:get_typename(9)) + assert_equal("fortification", b:get_typename(10)) end function test_build_normal() - local r = region.create(0, 0, "plain") - local f = faction.create("noreply@eressea.de", "human", "de") - local u = unit.create(f, r, 1) + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) u:clear_orders() u:add_item("stone", 10) u:set_skill("building", 10) @@ -45,9 +77,9 @@ function test_build_normal() end function test_build_packice() - local r = region.create(0, 0, "packice") - local f = faction.create("noreply@eressea.de", "human", "de") - local u = unit.create(f, r, 1) + local r = region.create(0, 0, "packice") + local f = faction.create("packice@eressea.de", "human", "de") + local u = unit.create(f, r, 1) u:clear_orders() u:add_item("stone", 10) u:set_skill("building", 10) diff --git a/scripts/tests/e3/init.lua b/scripts/tests/e3/init.lua index 4655fdcef..28a2cf6e5 100644 --- a/scripts/tests/e3/init.lua +++ b/scripts/tests/e3/init.lua @@ -4,8 +4,10 @@ require 'tests.e3.spells' require 'tests.e3.rules' require 'tests.e3.parser' require 'tests.e3.morale' +require 'tests.e3.items' require 'tests.orders' require 'tests.common' +require 'tests.items' -- require 'tests.report' require 'tests.magicbag' require 'tests.process' diff --git a/scripts/tests/e3/items.lua b/scripts/tests/e3/items.lua new file mode 100644 index 000000000..caf566468 --- /dev/null +++ b/scripts/tests/e3/items.lua @@ -0,0 +1,76 @@ +require "lunit" + +module("tests.e3.items", package.seeall, lunit.testcase ) + +function setup() + eressea.game.reset() + eressea.settings.set("rules.food.flags", "4") -- food is free + eressea.settings.set("NewbieImmunity", "0") +end + +function test_give_horses() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + + r:set_resource("horse", 0) + u:add_item("charger", 20) + u:add_order("GIB 0 10 Streitross") + process_orders() + assert_equal(10, r:get_resource("horse")) + assert_equal(10, u:get_item("charger")) +end + +function test_goblins() + local r = region.create(0, 0, "plain") + local f1 = faction.create("goblin@eressea.de", "goblin", "de") + local f2 = faction.create("dwarf@eressea.de", "dwarf", "de") + local f3 = faction.create("elf@eressea.de", "elf", "de") + local ud = unit.create(f1, r, 1) + local uh = unit.create(f1, r, 1) + uh.race = "halfling" + local u2 = unit.create(f2, r, 1) + local u3 = unit.create(f3, r, 1) + + local restricted = { + "towershield", "rep_crossbow", "plate", "lance", + "mallornlance", "greatbow", "greataxe", "axe", "scale", + "plate", "halberd", "greatsword", "rustyhalberd" + } + for k, v in ipairs(restricted) do + ud:add_item(v, 1) + uh:add_item(v, 1) + u2:add_item(v, 1) + u3:add_item(v, 1) + end + + uh:add_order("ATTACKIERE " .. itoa36(u2.id)) + uh:add_order("ATTACKIERE " .. itoa36(u3.id)) + ud:add_order("ATTACKIERE " .. itoa36(u2.id)) + ud:add_order("ATTACKIERE " .. itoa36(u3.id)) + process_orders() +end + +function test_make_horse() + eressea.settings.set("rules.horses.growth", "0") + local r = region.create(0, 0, "plain") + local f = faction.create("horses@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + u:set_skill("training", 4) + r:set_resource("horse", 100) + u:add_order("MACHE 1 PFERD") + process_orders() + assert_equal(1, u:get_item("horse")) + assert_equal(99, r:get_resource("horse")) + + u:clear_orders() + u:add_order("MACHE 1 STREITROSS") + u:add_item("money", 200) + u:add_item("iron", 1) + process_orders() + assert_equal(1, u:get_item("charger")) + assert_equal(0, u:get_item("horse")) + assert_equal(0, u:get_item("iron")) + assert_equal(0, u:get_item("money")) + assert_equal(99, r:get_resource("horse")) +end diff --git a/scripts/tests/e3/rules.lua b/scripts/tests/e3/rules.lua index 2cba83f21..2ecdf1ff7 100644 --- a/scripts/tests/e3/rules.lua +++ b/scripts/tests/e3/rules.lua @@ -626,11 +626,7 @@ function test_give_50_percent_of_money() u1:add_order("GIB " .. itoa36(u2.id) .. " 221 Silber") u2:clear_orders() u2:add_order("HELFEN " .. itoa36(u1.faction.id) .. " GIB") - u2:add_item("horse", 100) - u2:add_order("GIB 0 ALLES PFERD") - local h = r:get_resource("horse") process_orders() - assert_true(r:get_resource("horse")>=h+100) assert_equal(m1-221, u1:get_item("money")) assert_equal(m2+110, u2:get_item("money")) end @@ -990,4 +986,4 @@ function test_bug2187() -- write_report(f) set_rule("rules.food.flags", "4") -end \ No newline at end of file +end diff --git a/scripts/tests/economy.lua b/scripts/tests/economy.lua new file mode 100644 index 000000000..b628dd47b --- /dev/null +++ b/scripts/tests/economy.lua @@ -0,0 +1,146 @@ +require "lunit" + +module("tests.economy", package.seeall, lunit.testcase) + +function setup() + eressea.free_game() + eressea.settings.set("NewbieImmunity", "0") + eressea.settings.set("study.produceexp", "0") + eressea.settings.set("nmr.timeout", "0") + eressea.settings.set("rules.food.flags", "4") -- FOOD_IS_FREE + eressea.settings.set("rules.encounters", "0") +end + +function test_no_guards() + local r = region.create(0, 0, "plain") + r:set_resource("tree", 100) + local u = unit.create(faction.create("human"), r) + u:set_skill("forestry", 1) + u:add_order("MACHE HOLZ") + process_orders() + assert_equal(1, u:get_item("log")) + process_orders() + assert_equal(2, u:get_item("log")) +end + +function test_elf_guards_trees() + local r = region.create(0, 0, "plain") + r:set_resource("tree", 100) + local u = unit.create(faction.create("human"), r) + u:set_skill("forestry", 1) + local guard = unit.create(faction.create("elf"), r, 1, "elf") + guard:add_order("BEWACHEN") -- fails, because unarmed + u:add_order("MACHE HOLZ") + process_orders() + assert_equal(1, u:get_item("log")) + guard:add_item("sword", 1) + guard:set_skill("melee", 1) + guard:add_order("BEWACHEN") -- success + process_orders() + -- GUARD starts after MAKE: + assert_equal(2, u:get_item("log")) + process_orders() + -- GUARD was active this turn: + assert_equal(2, u:get_item("log")) +end + +function test_catapults_dont_guard() + local r = region.create(0, 0, "plain") + r:set_resource("tree", 100) + local u = unit.create(faction.create("human"), r) + u:set_skill("forestry", 1) + local guard = unit.create(faction.create("elf"), r, 1, "elf") + guard:add_order("BEWACHEN") + u:add_order("MACHE HOLZ") + process_orders() + assert_equal(1, u:get_item("log")) + guard:add_item("catapult", 1) + guard:set_skill("catapult", 1) + guard:add_order("BEWACHEN") + process_orders() + -- GUARD starts after MAKE: + assert_equal(2, u:get_item("log")) + process_orders() + -- GUARD was active this turn, but catapults do not count: + assert_equal(3, u:get_item("log")) +end + +function test_ent_guards_trees() + local r = region.create(0, 0, "plain") + r:set_resource("tree", 100) + local u = unit.create(faction.create("human"), r) + u:set_skill("forestry", 1) + local guard = unit.create(get_monsters(), r, 1, "ent") + guard:add_order("BEWACHEN") + u:add_order("MACHE HOLZ") + process_orders() + assert_equal(1, u:get_item("log")) + process_orders() + assert_equal(1, u:get_item("log")) +end + +function test_guard_stops_recruit() + local r = region.create(0, 0, "plain") + r:set_resource("peasant", 100) + local u = unit.create(faction.create("human"), r) + local guard = unit.create(get_monsters(), r, 1) + guard:add_order("BEWACHEN") + + u:add_item("money", 1000) + assert_equal(1, u.number) + u:add_order("REKRUTIERE 1") + process_orders() + assert_equal(2, u.number) + u:add_order("REKRUTIERE 1") + process_orders() + assert_equal(2, u.number) +end + +function test_guard_protects_iron() + local r = region.create(0, 0, "plain") + r:set_resource("iron", 100) + local level = r:get_resourcelevel("iron") + local u = unit.create(faction.create("human"), r) + u:set_skill("mining", level) + local guard = unit.create(get_monsters(), r, 1) + guard:add_order("BEWACHEN") + + u:add_order("MACHE EISEN") + process_orders() + assert_equal(level, u:get_item("iron")) + process_orders() + assert_equal(level, u:get_item("iron")) +end + +function test_ironkeeper_guards_iron() + local r = region.create(0, 0, "plain") + r:set_resource("iron", 100) + local level = r:get_resourcelevel("iron") + local u = unit.create(faction.create("human"), r) + u:set_skill("mining", level) + local guard = unit.create(faction.create("mountainguard"), r, 1, "mountainguard") + guard:add_order("BEWACHEN") + u:add_order("MACHE EISEN") + process_orders() + assert_equal(level, u:get_item("iron")) + process_orders() + assert_equal(level, u:get_item("iron")) +end + +function test_ent_guards_trees() + local r = region.create(0, 0, "plain") + r:set_resource("tree", 100) + local u = unit.create(faction.create("human"), r) + u:set_skill("mining", 1) + local guard = unit.create(get_monsters(), r, 1, "ent") + u:set_skill("forestry", 1) + guard:clear_orders() + u:clear_orders() + + guard:add_order("BEWACHEN") + u:add_order("MACHE HOLZ") + process_orders() + assert_equal(1, u:get_item("log")) + process_orders() + assert_equal(1, u:get_item("log")) +end diff --git a/scripts/tests/faction.lua b/scripts/tests/faction.lua index 38fdc4eb7..87a6b5100 100644 --- a/scripts/tests/faction.lua +++ b/scripts/tests/faction.lua @@ -17,7 +17,7 @@ function setup() end function test_faction_flags() - assert_equal(2, f.flags) -- FFL_ISNEW + assert_equal(6, f.flags) -- FFL_ISNEW|FFL_PWMSG f.flags = 42 assert_equal(42, f.flags) end diff --git a/scripts/tests/items.lua b/scripts/tests/items.lua new file mode 100644 index 000000000..aad52c2b2 --- /dev/null +++ b/scripts/tests/items.lua @@ -0,0 +1,169 @@ +require "lunit" + +module("tests.items", package.seeall, lunit.testcase ) + +function setup() + eressea.free_game() + eressea.settings.set("nmr.timeout", "0") + eressea.settings.set("rules.food.flags", "4") + eressea.settings.set("rules.ship.storms", "0") + eressea.settings.set("rules.encounters", "0") + eressea.settings.set("magic.regeneration.enable", "0") +end + +function test_mistletoe_okay() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + turn_begin() + u:add_item('mistletoe', 2) + u:clear_orders() + u:add_order("BENUTZEN 1 Mistelzweig") + assert_false(u:has_attrib('fleechance')) + turn_process() + assert_true(u:has_attrib('fleechance')) + assert_equal(1, u:get_item('mistletoe')) + assert_equal(1, f:count_msg_type('use_item')) + turn_end() +end + +function test_mistletoe_fail() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + turn_begin() + u:add_item('mistletoe', 1) + u:clear_orders() + u:add_order("BENUTZEN 1 Mistelzweig") + assert_false(u:has_attrib('fleechance')) + u.number = 2 + turn_process() + assert_false(u:has_attrib('fleechance')) + assert_equal(1, u:get_item('mistletoe')) + assert_equal(1, f:count_msg_type('use_singleperson')) + turn_end() +end + +function test_dreameye() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + u:add_item("dreameye", 2) + u:clear_orders() + u:add_order("BENUTZEN 1 Traumauge") + assert_nil(u:get_curse('skillmod')) + turn_begin() + turn_process() + assert_not_nil(u:get_curse('skillmod')) + assert_equal(1, u:get_item("dreameye")) + assert_equal(1, f:count_msg_type('use_tacticcrystal')) + turn_end() + assert_nil(u:get_curse('skillmod')) +end + +function test_manacrystal() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + u:add_item("manacrystal", 2) + u:clear_orders() + u.magic = "gwyrrd" + u:set_skill('magic', 1) + u.aura = 0 + u:add_order("BENUTZEN 1 Astralkristall") + turn_begin() + turn_process() + assert_equal(1, u:get_item("manacrystal")) + assert_equal(25, u.aura) + assert_equal(1, f:count_msg_type('manacrystal_use')) + turn_end() +end + +function test_skillpotion() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + u:add_item("skillpotion", 2) + u:clear_orders() + u:add_order("BENUTZEN 1 Talenttrunk") + process_orders() + assert_equal(1, u:get_item("skillpotion")) + assert_equal(1, f:count_msg_type('skillpotion_use')) +end + +function test_studypotion() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + turn_begin() + u:add_item("studypotion", 2) + u:clear_orders() + u:add_order("LERNE Unterhaltung") + u:add_order("BENUTZEN 1 Lerntrank") + turn_process() + -- cannot sense the "learning" attribute, because study_cmd + -- removes it during processing :( + assert_equal(1, u:get_item("studypotion")) + turn_end() +end + +function test_antimagic() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + + turn_begin() + u:add_item("antimagic", 2) + u:clear_orders() + u:add_order("BENUTZEN 1 Antimagiekristall") + assert_equal(nil, r:get_curse('antimagiczone')) + turn_process() + assert_equal(5, r:get_curse('antimagiczone')) + assert_equal(1, r:count_msg_type('use_antimagiccrystal')) + assert_equal(1, u:get_item("antimagic")) + turn_end() + assert_equal(5, r:get_curse('antimagiczone')) -- haelt zwei wochen + turn_end() -- hack: age the curse again + assert_equal(nil, r:get_curse('antimagiczone')) +end + +function test_ointment() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + local hp = u.hp + u.hp = 1 + u:add_item("ointment", 1) + u:clear_orders() + u:add_order("BENUTZEN 1 Wundsalbe") + process_orders() + assert_equal(0, u:get_item("ointment")) + assert_equal(1, f:count_msg_type('usepotion')) + assert_equal(hp, u.hp) +end + +function test_bloodpotion_demon() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "demon", "de") + local u = unit.create(f, r, 1) + u:add_item("peasantblood", 1) + u:clear_orders() + u:add_order("BENUTZEN 1 Bauernblut") + process_orders() + assert_equal(0, u:get_item("peasantblood")) + assert_equal(1, f:count_msg_type('usepotion')) + assert_equal("demon", u.race) +end + +function test_bloodpotion_other() + local r = region.create(0, 0, "plain") + local f = faction.create("noreply@eressea.de", "human", "de") + local u = unit.create(f, r, 1) + u:add_item("peasantblood", 1) + u:clear_orders() + u:add_order("BENUTZEN 1 Bauernblut") + process_orders() + assert_equal(0, u:get_item("peasantblood")) + assert_equal(1, f:count_msg_type('usepotion')) + assert_equal("smurf", u.race) +end diff --git a/scripts/tests/laws.lua b/scripts/tests/laws.lua index f0fef15a9..6f41fc54b 100644 --- a/scripts/tests/laws.lua +++ b/scripts/tests/laws.lua @@ -95,6 +95,7 @@ function test_force_leave_postcombat() u1.building = b1 u2.building = b1 eressea.settings.set("rules.owners.force_leave", "1") + eressea.settings.set("NewbieImmunity", "0") u1:clear_orders() u1:add_order("ATTACKIERE " .. itoa36(u2.id)) u2:clear_orders() @@ -109,6 +110,7 @@ function test_force_leave_postcombat() end end assert_not_equal(nil, u3) + assert_equal(nil, u2.building) assert_equal(nil, u3.building) assert_equal(1, u3.number) end diff --git a/scripts/tests/orders.lua b/scripts/tests/orders.lua index a0b03f825..dde9508e9 100644 --- a/scripts/tests/orders.lua +++ b/scripts/tests/orders.lua @@ -165,7 +165,7 @@ end function test_process_renumber() u:add_order("NUMMER EINHEIT 'ii'") - eressea.process.renumber() + process_orders() assert_equal(666, u.id) end diff --git a/scripts/tests/xmas.lua b/scripts/tests/xmas.lua index e1cd4753b..459984901 100644 --- a/scripts/tests/xmas.lua +++ b/scripts/tests/xmas.lua @@ -6,6 +6,10 @@ function setup() eressea.free_game() eressea.settings.set("nmr.timeout", "0") eressea.settings.set("rules.grow.formula", "0") + eressea.settings.set("rules.peasants.growth.factor", "0") + eressea.settings.set("volcano.active.percent", "0") + eressea.settings.set("volcano.outbreak.percent", "0") + eressea.settings.set("volcano.stop.percent", "0") end function test_snowglobe_fail() @@ -42,23 +46,17 @@ function test_snowglobe() local r2 = region.create(1, 0, "ocean") local f = faction.create("snowglobe2@eressea.de", "human", "de") local u = unit.create(f, r1, 1) - local have = 6 local fail = 0 u:add_item("snowglobe", have) - local xform = { ocean = "glacier", glacier = "glacier", firewall = "volcano", volcano = "mountain", desert = "plain", plain = "plain" } - u:clear_orders() - u:add_order("BENUTZEN 1 Schneekugel Ost") + local xform = { ocean = "glacier", glacier = "glacier", firewall = "volcano", desert = "plain", volcano = "mountain", plain = "plain" } for k, v in pairs(xform) do r2.terrain = k - process_orders() - -- TODO: re-enable! assert_equal(v, r2.terrain) - if k~=v then - have=have - 1 - else + use_snowglobe(u, 1, "Ost", nil) + assert_equal(v, r2.terrain) + if k==v then fail = fail + 1 assert_equal(fail, f:count_msg_type('target_region_invalid')) end - assert_equal(have, u:get_item("snowglobe")) end end diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index df92085db..7be3dd3b1 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -2,11 +2,9 @@ cmake_minimum_required(VERSION 2.8) project (server C) include_directories (${CMAKE_CURRENT_SOURCE_DIR}) -include_directories (${CRITBIT_INCLUDE_DIR}) include_directories (${CJSON_INCLUDE_DIR}) +include_directories (${CLIBS_INCLUDE_DIR}) include_directories (${STORAGE_INCLUDE_DIR}) -include_directories (${QUICKLIST_INCLUDE_DIR}) -include_directories (${CUTEST_INCLUDE_DIR}) include_directories (${LUA_INCLUDE_DIR}) include_directories (${TOLUA_INCLUDE_DIR}) include_directories (${BSON_INCLUDE_DIR}) @@ -17,12 +15,18 @@ set_source_files_properties(kernel/version.c PROPERTIES COMPILE_DEFINITIONS ERESSEA_VERSION="${ERESSEA_VERSION}") ENDIF() -IF(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_CLANG) -# SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wconversion -Wno-sign-conversion") - SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pedantic -Wsign-compare -Wall -Werror -Wno-unknown-pragmas -Wstrict-prototypes -Wpointer-arith -Wno-char-subscripts -Wno-long-long") +IF(DEFINED ERESSEA_BUILDNO) +set_source_files_properties(kernel/version.c PROPERTIES +COMPILE_DEFINITIONS ERESSEA_BUILDNO="${ERESSEA_BUILDNO}") +ENDIF() + +IF (CMAKE_COMPILER_IS_GNUCC) SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-error=unused-but-set-variable") - SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99") - add_definitions(-DHAVE__BOOL) +ENDIF() +IF (CMAKE_COMPILER_IS_GNUCC OR CMAKE_C_COMPILER_ID MATCHES "Clang") +# SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wconversion -Wno-sign-conversion") + SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wsign-compare -Wall -Werror -Wno-unknown-pragmas -Wstrict-prototypes -Wpointer-arith -Wno-char-subscripts -Wno-long-long") + SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c89") ELSEIF(MSVC) SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /Wall /WX /MP") set(CMAKE_EXE_LINKER_FLAGS_DEBUG @@ -82,6 +86,7 @@ TOLUA_BINDING(settings.pkg kenel/config.h) ENDIF() set (ERESSEA_SRC + vortex.c calendar.c move.c piracy.c @@ -90,7 +95,6 @@ set (ERESSEA_SRC alchemy.c academy.c upkeep.c - vortex.c names.c lighthouse.c reports.c @@ -99,7 +103,6 @@ set (ERESSEA_SRC prefix.c donations.c eressea.c - callback.c direction.c keyword.c skill.c @@ -113,8 +116,8 @@ set (ERESSEA_SRC magic.c market.c morale.c - monster.c randenc.c + renumber.c volcano.c chaos.c spy.c @@ -144,7 +147,6 @@ set(SERVER_SRC bind_locale.c bind_eressea.c bind_faction.c - bind_dict.c bind_order.c bindings.c bind_message.c @@ -179,19 +181,28 @@ target_link_libraries(eressea game ${TOLUA_LIBRARIES} ${LUA_LIBRARIES} - ${QUICKLIST_LIBRARIES} ${STORAGE_LIBRARIES} - ${CRITBIT_LIBRARIES} + ${CLIBS_LIBRARIES} ${CJSON_LIBRARIES} ${INIPARSER_LIBRARIES} ) +add_executable(convert convert.c) +target_link_libraries(convert + game + ${LUA_MATH_LIBRARY} + ${STORAGE_LIBRARIES} + ${CLIBS_LIBRARIES} + ${INIPARSER_LIBRARIES} +) + set(TESTS_SRC monsters.test.c names.test.c donations.test.c wormhole.test.c alchemy.test.c + guard.test.c test_eressea.c tests.c battle.test.c @@ -203,7 +214,6 @@ set(TESTS_SRC report.test.c summary.test.c travelthru.test.c - callback.test.c direction.test.c economy.test.c json.test.c @@ -217,6 +227,7 @@ set(TESTS_SRC move.test.c piracy.test.c prefix.test.c + renumber.test.c skill.test.c spells.test.c spy.test.c @@ -234,11 +245,10 @@ set(TESTS_SRC add_executable(test_eressea ${TESTS_SRC}) target_link_libraries(test_eressea game - ${CUTEST_LIBRARIES} + cutest ${LUA_LIBRARIES} - ${QUICKLIST_LIBRARIES} + ${CLIBS_LIBRARIES} ${STORAGE_LIBRARIES} - ${CRITBIT_LIBRARIES} ${CJSON_LIBRARIES} ${INIPARSER_LIBRARIES} ) @@ -267,6 +277,7 @@ endif(CURSES_FOUND) if (LIBXML2_FOUND) include_directories (${LIBXML2_INCLUDE_DIR}) target_link_libraries(eressea ${LIBXML2_LIBRARIES}) +target_link_libraries(convert ${LIBXML2_LIBRARIES}) target_link_libraries(test_eressea ${LIBXML2_LIBRARIES}) add_definitions(-DUSE_LIBXML2) endif (LIBXML2_FOUND) diff --git a/src/academy.c b/src/academy.c index f6b70873e..496c1ef8e 100644 --- a/src/academy.c +++ b/src/academy.c @@ -35,7 +35,7 @@ bool academy_can_teach(unit *teacher, unit *student, skill_t sk) { const struct building_type *btype = bt_find("academy"); if (active_building(teacher, btype) && active_building(student, btype)) { int j = study_cost(student, sk); - j = _max(50, j * 2); + j = MAX(50, j * 2); /* kann Einheit das zahlen? */ return get_pooled(student, get_resourcetype(R_SILVER), GET_DEFAULT, j) >= j; /* sonst nehmen sie nicht am Unterricht teil */ diff --git a/src/alchemy.c b/src/alchemy.c index 89b00c5f0..aff3485ef 100644 --- a/src/alchemy.c +++ b/src/alchemy.c @@ -19,7 +19,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include "alchemy.h" -#include "move.h" +#include "guard.h" #include "skill.h" #include "study.h" @@ -61,7 +61,7 @@ void herbsearch(unit * u, int max) return; } - if (is_guarded(r, u, GUARD_PRODUCE)) { + if (is_guarded(r, u)) { cmistake(u, u->thisorder, 70, MSG_EVENT); return; } @@ -73,12 +73,12 @@ void herbsearch(unit * u, int max) } if (max) - max = _min(max, rherbs(r)); + max = MIN(max, rherbs(r)); else max = rherbs(r); herbsfound = ntimespprob(effsk * u->number, (double)rherbs(r) / 100.0F, -0.01F); - herbsfound = _min(herbsfound, max); + herbsfound = MIN(herbsfound, max); rsetherbs(r, (short) (rherbs(r) - herbsfound)); if (herbsfound) { @@ -156,12 +156,13 @@ static int potion_water_of_life(unit * u, region *r, int amount) { } static int potion_healing(unit * u, int amount) { - u->hp = _min(unit_max_hp(u) * u->number, u->hp + 400 * amount); + u->hp = MIN(unit_max_hp(u) * u->number, u->hp + 400 * amount); return amount; } static int potion_luck(unit *u, region *r, attrib_type *atype, int amount) { attrib *a = (attrib *)a_find(r->attribs, atype); + UNUSED_ARG(u); if (!a) { a = a_add(&r->attribs, a_new(atype)); } @@ -170,8 +171,8 @@ static int potion_luck(unit *u, region *r, attrib_type *atype, int amount) { } static int potion_truth(unit *u) { - // TODO: this potion does nothing! - // fset(u, UFL_DISBELIEVES); + UNUSED_ARG(u); + /* TODO: this potion does nothing! */ return 1; } @@ -181,8 +182,8 @@ static int potion_power(unit *u, int amount) { if (u->number % 10 > 0) ++use; amount = use; } - /* Verfnffacht die HP von max. 10 Personen in der Einheit */ - u->hp += _min(u->number, 10 * amount) * unit_max_hp(u) * 4; + /* Verf�nffacht die HP von max. 10 Personen in der Einheit */ + u->hp += MIN(u->number, 10 * amount) * unit_max_hp(u) * 4; return amount; } @@ -241,15 +242,14 @@ static void init_potiondelay(attrib * a) a->data.v = malloc(sizeof(potiondelay)); } -static void free_potiondelay(attrib * a) -{ +static void free_potiondelay(attrib * a) { free(a->data.v); } static int age_potiondelay(attrib * a, void *owner) { potiondelay *pd = (potiondelay *)a->data.v; - unused_arg(owner); + UNUSED_ARG(owner); pd->amount = do_potion(pd->u, pd->r, pd->ptype, pd->amount); return AT_AGE_REMOVE; } @@ -296,7 +296,7 @@ static void a_initeffect(attrib * a) a->data.v = calloc(sizeof(effect_data), 1); } -static void a_finalizeeffect(attrib * a) +static void a_finalizeeffect(attrib * a) /*-V524 */ { free(a->data.v); } @@ -305,6 +305,7 @@ static void a_writeeffect(const attrib * a, const void *owner, struct storage *store) { effect_data *edata = (effect_data *)a->data.v; + UNUSED_ARG(owner); WRITE_TOK(store, resourcename(edata->type->itype->rtype, 0)); WRITE_INT(store, edata->value); } @@ -317,6 +318,7 @@ static int a_readeffect(attrib * a, void *owner, struct gamedata *data) effect_data *edata = (effect_data *)a->data.v; char zText[32]; + UNUSED_ARG(owner); READ_TOK(store, zText, sizeof(zText)); rtype = rt_find(zText); @@ -325,7 +327,7 @@ static int a_readeffect(attrib * a, void *owner, struct gamedata *data) return AT_READ_FAIL; } if (rtype->ptype==oldpotiontype[P_HEAL]) { - // healing potions used to have long-term effects + /* healing potions used to have long-term effects */ return AT_READ_FAIL; } edata->type = rtype->ptype; diff --git a/src/alchemy.test.c b/src/alchemy.test.c index 7fd2da8e1..c281a1c98 100644 --- a/src/alchemy.test.c +++ b/src/alchemy.test.c @@ -30,7 +30,7 @@ static void test_herbsearch(CuTest * tc) rc = rc_get_or_create("dragon"); rc->flags |= RCF_UNARMEDGUARD; u2 = test_create_unit(test_create_faction(rc), r); - guard(u2, GUARD_PRODUCE); + setguard(u2, true); f = test_create_faction(0); u = test_create_unit(f, r); @@ -41,14 +41,14 @@ static void test_herbsearch(CuTest * tc) test_clear_messages(f); set_level(u, SK_HERBALISM, 1); - CuAssertPtrEquals(tc, u2, is_guarded(r, u, GUARD_PRODUCE)); + CuAssertPtrEquals(tc, u2, is_guarded(r, u)); herbsearch(u, INT_MAX); CuAssertPtrNotNull(tc, test_find_messagetype(f->msgs, "error70")); CuAssertPtrEquals(tc, 0, test_find_messagetype(f->msgs, "error59")); test_clear_messages(f); - guard(u2, GUARD_NONE); - CuAssertPtrEquals(tc, 0, is_guarded(r, u, GUARD_PRODUCE)); + setguard(u2, false); + CuAssertPtrEquals(tc, 0, is_guarded(r, u)); CuAssertPtrEquals(tc, 0, (void *)rherbtype(r)); herbsearch(u, INT_MAX); CuAssertPtrNotNull(tc, test_find_messagetype(f->msgs, "error108")); diff --git a/src/attributes/CMakeLists.txt b/src/attributes/CMakeLists.txt index 1419f9e9a..d0aa252ee 100644 --- a/src/attributes/CMakeLists.txt +++ b/src/attributes/CMakeLists.txt @@ -16,7 +16,6 @@ matmod.c moved.c movement.c dict.c -orcification.c otherfaction.c overrideroads.c racename.c diff --git a/src/attributes/attributes.c b/src/attributes/attributes.c index a82e1941d..0fe42a92e 100644 --- a/src/attributes/attributes.c +++ b/src/attributes/attributes.c @@ -22,10 +22,10 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "laws.h" #include "move.h" -#include "guard.h" /* attributes includes */ #include "follow.h" +#include "fleechance.h" #include "hate.h" #include "iceberg.h" #include "key.h" @@ -34,7 +34,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "moved.h" #include "movement.h" #include "dict.h" -#include "orcification.h" #include "otherfaction.h" #include "overrideroads.h" #include "racename.h" @@ -50,7 +49,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include #include #include @@ -61,9 +59,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include -attrib_type at_scare = { // monster scares peasants - "scare", NULL, NULL, NULL, a_writeint, a_readint -}; attrib_type at_unitdissolve = { "unitdissolve", NULL, NULL, NULL, a_writechars, a_readchars @@ -81,7 +76,6 @@ static int read_ext(attrib * a, void *owner, gamedata *data) void register_attributes(void) { /* Alle speicherbaren Attribute mssen hier registriert werden */ - at_register(&at_scare); at_register(&at_shiptrail); at_register(&at_familiar); at_register(&at_familiarmage); @@ -100,12 +94,12 @@ void register_attributes(void) at_register(&at_woodcount); /* neue UNIT-Attribute */ + at_register(&at_fleechance); at_register(&at_siege); at_register(&at_effect); at_register(&at_private); at_register(&at_icastle); - at_register(&at_guard); at_register(&at_group); at_register(&at_building_generic_type); @@ -121,9 +115,12 @@ void register_attributes(void) at_register(&at_germs); + at_deprecate("hurting", a_readint); /* an old arena attribute */ at_deprecate("xontormiaexpress", a_readint); /* required for old datafiles */ + at_deprecate("orcification", a_readint); /* required for old datafiles */ at_deprecate("lua", read_ext); /* required for old datafiles */ at_deprecate("gm", a_readint); + at_deprecate("guard", a_readint); /* used to contain guard-flags (v3.10.0-259-g8597e8b) */ at_register(&at_stealth); at_register(&at_dict); at_register(&at_unitdissolve); @@ -134,7 +131,6 @@ void register_attributes(void) at_register(&at_keys); at_register(&at_follow); at_register(&at_targetregion); - at_register(&at_orcification); at_register(&at_hate); at_register(&at_reduceproduction); at_register(&at_otherfaction); diff --git a/src/attributes/attributes.h b/src/attributes/attributes.h index 91184ad98..4ec3150ec 100644 --- a/src/attributes/attributes.h +++ b/src/attributes/attributes.h @@ -23,7 +23,6 @@ extern "C" { #endif struct attrib_type; - extern struct attrib_type at_scare; extern void register_attributes(void); #ifdef __cplusplus diff --git a/src/attributes/dict.c b/src/attributes/dict.c index cb24b148b..f95555734 100644 --- a/src/attributes/dict.c +++ b/src/attributes/dict.c @@ -19,17 +19,19 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include "dict.h" +#include "key.h" /* kernel includes */ #include #include #include -#include #include #include /* util includes */ #include +#include +#include #include #include @@ -40,6 +42,10 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include +typedef enum { + TNONE = 0, TINTEGER = 1, TREAL = 2 +} dict_type; + typedef struct dict_data { dict_type type; char *name; @@ -55,230 +61,110 @@ typedef struct dict_data { } data; } dict_data; -static void -dict_write(const attrib * a, const void *owner, struct storage *store) -{ - const dict_data *data = (dict_data *)a->data.v; - int type = (int)data->type; - WRITE_TOK(store, data->name); - WRITE_INT(store, type); - switch (data->type) { - case TINTEGER: - WRITE_INT(store, data->data.i); - break; - case TREAL: - WRITE_FLT(store, (float)data->data.real); - break; - case TSTRING: - WRITE_STR(store, data->data.str); - break; - case TUNIT: - write_unit_reference(data->data.u, store); - break; - case TFACTION: - write_faction_reference(data->data.f, store); - break; - case TBUILDING: - write_building_reference(data->data.b, store); - break; - case TSHIP: - /* write_ship_reference(data->data.sh, store); */ - assert(!"not implemented"); - break; - case TREGION: - write_region_reference(data->data.r, store); - break; - case TNONE: - break; - default: - assert(!"illegal type in object-attribute"); - } -} - static int dict_read(attrib * a, void *owner, gamedata *data) { storage *store = data->store; char name[NAMESIZE]; dict_data *dd = (dict_data *)a->data.v; - int result, n; - float flt; + int n; READ_STR(store, name, sizeof(name)); - dd->name = _strdup(name); + dd->name = strdup(name); READ_INT(store, &n); dd->type = (dict_type)n; - switch (dd->type) { - case TINTEGER: + if (dd->type == TINTEGER) { READ_INT(store, &dd->data.i); - break; - case TREAL: + } + else if (dd->type == TREAL) { + float flt; READ_FLT(store, &flt); - if ((int)flt == flt) { - dd->type = TINTEGER; - dd->data.i = (int)flt; - } - else { - dd->data.real = flt; - } - break; - case TSTRING: - READ_STR(store, name, sizeof(name)); - dd->data.str = _strdup(name); - break; - case TBUILDING: - result = - read_reference(&dd->data.b, data, read_building_reference, - resolve_building); - if (result == 0 && !dd->data.b) { - return AT_READ_FAIL; - } - break; - case TUNIT: - result = - read_reference(&dd->data.u, data, read_unit_reference, resolve_unit); - if (result == 0 && !dd->data.u) { - return AT_READ_FAIL; - } - break; - case TFACTION: - result = - read_reference(&dd->data.f, data, read_faction_reference, - resolve_faction); - if (result == 0 && !dd->data.f) { - return AT_READ_FAIL; - } - break; - case TREGION: - result = - read_reference(&dd->data.r, data, read_region_reference, - RESOLVE_REGION(data->version)); - if (result == 0 && !dd->data.r) { - return AT_READ_FAIL; - } - break; - case TSHIP: - /* return read_ship_reference(&data->data.sh, store); */ - assert(!"not implemented"); - break; - case TNONE: - break; - default: + dd->data.real = flt; + } + else { + log_error("read dict, invalid type %d", n); return AT_READ_FAIL; } - return AT_READ_OK; + return AT_READ_DEPR; } static void dict_init(attrib * a) { - dict_data *data; + dict_data *dd; a->data.v = malloc(sizeof(dict_data)); - data = (dict_data *)a->data.v; - data->type = TNONE; + dd = (dict_data *)a->data.v; + dd->type = TNONE; } static void dict_done(attrib * a) { - dict_data *data = (dict_data *)a->data.v; - if (data->type == TSTRING) - free(data->data.str); - free(data->name); + dict_data *dd = (dict_data *)a->data.v; + free(dd->name); free(a->data.v); } +static void upgrade_keyval(const dict_data *dd, int keyval[], int v) { + if (strcmp(dd->name, "embassy_muschel") == 0) { + keyval[0] = atoi36("mupL"); + keyval[1] = v; + } + else { + log_error("dict conversion, bad entry %s", dd->name); + } +} + +static void dict_upgrade(attrib **alist, attrib *abegin) { + int n = 0, *keys = 0; + int i = 0, val[8]; + attrib *a, *ak = a_find(*alist, &at_keys); + if (ak) { + keys = (int *)ak->data.v; + if (keys) n = keys[0]; + } + for (a = abegin; a && a->type == abegin->type; a = a->next) { + dict_data *dd = (dict_data *)a->data.v; + if (dd->type == TINTEGER) { + upgrade_keyval(dd, val + i * 2, dd->data.i); + ++i; + } + else if (dd->type == TREAL) { + upgrade_keyval(dd, val + i * 2, (int)dd->data.real); + ++i; + } + else { + log_error("dict conversion, bad type %d for %s", dd->type, dd->name); + assert(!"invalid input"); + } + if (i == 4) { + keys = realloc(keys, sizeof(int) * (n + i + 1)); + memcpy(keys + n + 1, val, sizeof(val)); + n += i; + i = 0; + } + } + if (i > 0) { + keys = realloc(keys, sizeof(int) * (2 * (n + i) + 1)); + memcpy(keys + n*2 + 1, val, sizeof(int)*i*2); + if (!ak) { + ak = a_add(alist, a_new(&at_keys)); + } + } + if (ak) { + ak->data.v = keys; + if (keys) { + keys[0] = n + i; + } + } +} + attrib_type at_dict = { "object", dict_init, dict_done, NULL, - dict_write, dict_read + NULL, dict_read, dict_upgrade }; -const char *dict_name(const attrib * a) +void dict_set(attrib * a, const char * name, int value) { - dict_data *data = (dict_data *)a->data.v; - return data->name; -} - -struct attrib *dict_create(const char *name, dict_type type, variant value) -{ - attrib *a = a_new(&at_dict); - dict_data *data = (dict_data *)a->data.v; - data->name = _strdup(name); - - dict_set(a, type, value); - return a; -} - -void dict_set(attrib * a, dict_type type, variant value) -{ - dict_data *data = (dict_data *)a->data.v; - - if (data->type == TSTRING) - free(data->data.str); - data->type = type; - switch (type) { - case TSTRING: - data->data.str = value.v ? _strdup(value.v) : NULL; - break; - case TINTEGER: - data->data.i = value.i; - break; - case TREAL: - data->data.real = value.f; - break; - case TREGION: - data->data.r = (region *)value.v; - break; - case TBUILDING: - data->data.b = (building *)value.v; - break; - case TFACTION: - data->data.f = (faction *)value.v; - break; - case TUNIT: - data->data.u = (unit *)value.v; - break; - case TSHIP: - data->data.sh = (ship *)value.v; - break; - case TNONE: - break; - default: - assert(!"invalid object-type"); - break; - } -} - -void dict_get(const struct attrib *a, dict_type * type, variant * value) -{ - dict_data *data = (dict_data *)a->data.v; - *type = data->type; - switch (data->type) { - case TSTRING: - value->v = data->data.str; - break; - case TINTEGER: - value->i = data->data.i; - break; - case TREAL: - value->f = (float)data->data.real; - break; - case TREGION: - value->v = data->data.r; - break; - case TBUILDING: - value->v = data->data.b; - break; - case TFACTION: - value->v = data->data.f; - break; - case TUNIT: - value->v = data->data.u; - break; - case TSHIP: - value->v = data->data.sh; - break; - case TNONE: - break; - default: - assert(!"invalid object-type"); - break; - } + dict_data *dd = (dict_data *)a->data.v; + dd->name = strdup(name); + dd->type = TINTEGER; + dd->data.i = value; } diff --git a/src/attributes/dict.h b/src/attributes/dict.h index 5b282779e..aa6b4566a 100644 --- a/src/attributes/dict.h +++ b/src/attributes/dict.h @@ -13,25 +13,16 @@ #ifndef H_ATTRIBUTE_OBJECT #define H_ATTRIBUTE_OBJECT -#include +struct attrib_type; +struct attrib; #ifdef __cplusplus extern "C" { #endif - typedef enum { - TNONE = 0, TINTEGER = 1, TREAL = 2, TSTRING = 3, - TUNIT = 10, TFACTION = 11, TREGION = 12, TBUILDING = 13, TSHIP = 14 - } dict_type; + extern struct attrib_type at_dict; /* DEPRECATED: at_dict has been replaced with at_keys */ - extern struct attrib_type at_dict; - - struct attrib *dict_create(const char *name, dict_type type, - variant value); - void dict_get(const struct attrib *a, dict_type * type, - variant * value); - void dict_set(struct attrib *a, dict_type type, variant value); - const char *dict_name(const struct attrib *a); + void dict_set(struct attrib * a, const char * name, int value); #ifdef __cplusplus } diff --git a/src/attributes/fleechance.c b/src/attributes/fleechance.c index 232037972..b8012fba5 100644 --- a/src/attributes/fleechance.c +++ b/src/attributes/fleechance.c @@ -21,6 +21,8 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include +#include + attrib_type at_fleechance = { "fleechance", NULL, @@ -36,8 +38,3 @@ attrib *make_fleechance(float fleechance) a->data.flt = fleechance; return a; } - -void init_fleechance(void) -{ - at_register(&at_fleechance); -} diff --git a/src/attributes/fleechance.h b/src/attributes/fleechance.h index b2f75671c..d5817b8b7 100644 --- a/src/attributes/fleechance.h +++ b/src/attributes/fleechance.h @@ -25,7 +25,6 @@ extern "C" { extern struct attrib_type at_fleechance; struct attrib *make_fleechance(float fleechance); - void init_fleechance(void); #ifdef __cplusplus } diff --git a/src/attributes/hate.c b/src/attributes/hate.c index 98a36a029..17155fc71 100644 --- a/src/attributes/hate.c +++ b/src/attributes/hate.c @@ -30,7 +30,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. static int verify_hate(attrib * a, void *owner) { - unused_arg(owner); + UNUSED_ARG(owner); if (a->data.v == NULL) { return 0; } diff --git a/src/attributes/iceberg.c b/src/attributes/iceberg.c index 661a2ec80..e36e6303a 100644 --- a/src/attributes/iceberg.c +++ b/src/attributes/iceberg.c @@ -20,7 +20,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include "iceberg.h" -#include #include attrib_type at_iceberg = { diff --git a/src/attributes/key.c b/src/attributes/key.c index 39c7dab66..31580bccf 100644 --- a/src/attributes/key.c +++ b/src/attributes/key.c @@ -20,7 +20,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include "key.h" -#include #include #include #include @@ -31,19 +30,30 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. static void a_writekeys(const attrib *a, const void *o, storage *store) { int i, *keys = (int *)a->data.v; - for (i = 0; i <= keys[0]; ++i) { - WRITE_INT(store, keys[i]); + WRITE_INT(store, keys[0]); + for (i = 0; i < keys[0]; ++i) { + WRITE_INT(store, keys[i * 2 + 1]); + WRITE_INT(store, keys[i * 2 + 2]); } } static int a_readkeys(attrib * a, void *owner, gamedata *data) { int i, *p = 0; READ_INT(data->store, &i); - assert(i < 4096 && i>0); - a->data.v = p = malloc(sizeof(int)*(i + 1)); + assert(i < 4096 && i>=0); + if (i == 0) { + return AT_READ_FAIL; + } + a->data.v = p = malloc(sizeof(int)*(i*2 + 1)); *p++ = i; while (i--) { READ_INT(data->store, p++); + if (data->version >= KEYVAL_VERSION) { + READ_INT(data->store, p++); + } + else { + *p++ = 1; + } } return AT_READ_OK; } @@ -67,32 +77,37 @@ attrib_type at_keys = { NULL }; -void a_upgradekeys(attrib **alist, attrib *abegin) { +static void a_upgradekeys(attrib **alist, attrib *abegin) { int n = 0, *keys = 0; - int i = 0, val[4]; + int i = 0, val[8]; attrib *a, *ak = a_find(*alist, &at_keys); if (ak) { keys = (int *)ak->data.v; if (keys) n = keys[0]; } for (a = abegin; a && a->type == abegin->type; a = a->next) { - val[i++] = a->data.i; - if (i == 4) { - keys = realloc(keys, sizeof(int) * (n + i + 1)); - memcpy(keys + n + 1, val, sizeof(int)*i); + val[i * 2] = a->data.i; + val[i * 2 + 1] = 1; + if (++i == 4) { + keys = realloc(keys, sizeof(int) * (2 * (n + i) + 1)); + memcpy(keys + 2 * n + 1, val, sizeof(val)); n += i; i = 0; } } if (i > 0) { - keys = realloc(keys, sizeof(int) * (n + i + 1)); - memcpy(keys + n + 1, val, sizeof(int)*i); + keys = realloc(keys, sizeof(int) * (2 * (n + i) + 1)); + memcpy(keys + 2 * n + 1, val, sizeof(int)*i*2); if (!ak) { ak = a_add(alist, a_new(&at_keys)); } } - ak->data.v = keys; - keys[0] = n + i; + if (ak) { + ak->data.v = keys; + if (keys) { + keys[0] = n + i; + } + } } attrib_type at_key = { @@ -105,9 +120,9 @@ attrib_type at_key = { a_upgradekeys }; -void key_set(attrib ** alist, int key) +void key_set(attrib ** alist, int key, int val) { - int *keys, n = 1; + int *keys, n = 0; attrib *a; assert(key != 0); a = a_find(*alist, &at_keys); @@ -116,12 +131,13 @@ void key_set(attrib ** alist, int key) } keys = (int *)a->data.v; if (keys) { - n = keys[0] + 1; + n = keys[0]; } - keys = realloc(keys, sizeof(int) *(n + 1)); - // TODO: does insertion sort pay off here? - keys[0] = n; - keys[n] = key; + keys = realloc(keys, sizeof(int) *(2 * n + 3)); + /* TODO: does insertion sort pay off here? prob. not. */ + keys[0] = n + 1; + keys[2 * n + 1] = key; + keys[2 * n + 2] = val; a->data.v = keys; } @@ -133,29 +149,31 @@ void key_unset(attrib ** alist, int key) if (a) { int i, *keys = (int *)a->data.v; if (keys) { - for (i = 1; i <= keys[0]; ++i) { - if (keys[i] == key) { - keys[i] = keys[keys[0]]; + int n = keys[0]; + for (i = 0; i != n; ++i) { + if (keys[2 * i + 1] == key) { + memmove(keys + 2 * i + 1, keys + 2 * n - 1, 2 * sizeof(int)); keys[0]--; + break; } } } } } -bool key_get(attrib *alist, int key) { +int key_get(attrib *alist, int key) { attrib *a; assert(key != 0); a = a_find(alist, &at_keys); if (a) { int i, *keys = (int *)a->data.v; if (keys) { - for (i = 1; i <= keys[0]; ++i) { - if (keys[i] == key) { - return true; + for (i = 0; i != keys[0]; ++i) { + if (keys[i*2+1] == key) { + return keys[i * 2 + 2]; } } } } - return false; + return 0; } diff --git a/src/attributes/key.h b/src/attributes/key.h index 89292db1d..0b3ab748f 100644 --- a/src/attributes/key.h +++ b/src/attributes/key.h @@ -18,17 +18,20 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef H_ATTRIBUTE_KEY #define H_ATTRIBUTE_KEY + +#include + #ifdef __cplusplus extern "C" { #endif struct attrib; struct attrib_type; - extern struct attrib_type at_key; + extern struct attrib_type at_key; /* DEPRECATED: at_key has been replaced with at_keys */ extern struct attrib_type at_keys; - void key_set(struct attrib **alist, int key); + void key_set(struct attrib **alist, int key, int value); void key_unset(struct attrib **alist, int key); - bool key_get(struct attrib *alist, int key); + int key_get(struct attrib *alist, int key); #ifdef __cplusplus } diff --git a/src/attributes/key.test.c b/src/attributes/key.test.c index 46343d19f..b816e1d86 100644 --- a/src/attributes/key.test.c +++ b/src/attributes/key.test.c @@ -1,21 +1,24 @@ #include #include "key.h" +#include "dict.h" #include +#include #include +#include static void test_get_set_keys(CuTest *tc) { attrib *a = 0; - key_set(&a, 42); - key_set(&a, 43); - key_set(&a, 44); - CuAssertTrue(tc, key_get(a, 42)); - CuAssertTrue(tc, key_get(a, 43)); - CuAssertTrue(tc, key_get(a, 44)); + key_set(&a, 42, 1); + key_set(&a, 43, 2); + key_set(&a, 44, 3); + CuAssertIntEquals(tc, 1, key_get(a, 42)); + CuAssertIntEquals(tc, 2, key_get(a, 43)); + CuAssertIntEquals(tc, 3, key_get(a, 44)); key_unset(&a, 42); - CuAssertTrue(tc, !key_get(a, 42)); - CuAssertTrue(tc, key_get(a, 43)); - CuAssertTrue(tc, key_get(a, 44)); + CuAssertIntEquals(tc, 0, key_get(a, 42)); + CuAssertIntEquals(tc, 2, key_get(a, 43)); + CuAssertIntEquals(tc, 3, key_get(a, 44)); a_removeall(&a, NULL); } @@ -25,7 +28,7 @@ static attrib *key_set_orig(attrib **alist, int key) { return a; } -static void test_upgrade(CuTest *tc) { +static void test_upgrade_key(CuTest *tc) { attrib *alist = 0; key_set_orig(&alist, 40); key_set_orig(&alist, 41); @@ -34,18 +37,31 @@ static void test_upgrade(CuTest *tc) { key_set_orig(&alist, 44); CuAssertPtrNotNull(tc, alist->type->upgrade); alist->type->upgrade(&alist, alist); - CuAssertTrue(tc, key_get(alist, 40)); - CuAssertTrue(tc, key_get(alist, 41)); - CuAssertTrue(tc, key_get(alist, 42)); - CuAssertTrue(tc, key_get(alist, 43)); - CuAssertTrue(tc, key_get(alist, 44)); + CuAssertIntEquals(tc, 1, key_get(alist, 40)); + CuAssertIntEquals(tc, 1, key_get(alist, 41)); + CuAssertIntEquals(tc, 1, key_get(alist, 42)); + CuAssertIntEquals(tc, 1, key_get(alist, 43)); + CuAssertIntEquals(tc, 1, key_get(alist, 44)); a_removeall(&alist, NULL); } +static void test_upgrade_dict(CuTest *tc) { + attrib *a; + + a = a_new(&at_dict); + + dict_set(a, "embassy_muschel", 42); + CuAssertPtrNotNull(tc, a->type->upgrade); + a->type->upgrade(&a, a); + CuAssertIntEquals(tc, 42, key_get(a, atoi36("mupL"))); + a_removeall(&a, NULL); +} + CuSuite *get_key_suite(void) { CuSuite *suite = CuSuiteNew(); SUITE_ADD_TEST(suite, test_get_set_keys); - SUITE_ADD_TEST(suite, test_upgrade); + SUITE_ADD_TEST(suite, test_upgrade_key); + SUITE_ADD_TEST(suite, test_upgrade_dict); return suite; } diff --git a/src/attributes/matmod.c b/src/attributes/matmod.c index f885de99b..0cf1955d8 100644 --- a/src/attributes/matmod.c +++ b/src/attributes/matmod.c @@ -20,6 +20,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "matmod.h" #include +#include attrib_type at_matmod = { "matmod", diff --git a/src/attributes/moved.c b/src/attributes/moved.c index 3da2a4c3b..c66a5489c 100644 --- a/src/attributes/moved.c +++ b/src/attributes/moved.c @@ -27,7 +27,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. static int age_moved(attrib * a, void *owner) { - unused_arg(owner); + UNUSED_ARG(owner); --a->data.i; return a->data.i > 0; } diff --git a/src/attributes/movement.c b/src/attributes/movement.c index 0ad08030e..4d79039ef 100644 --- a/src/attributes/movement.c +++ b/src/attributes/movement.c @@ -20,7 +20,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include "movement.h" -#include #include #include @@ -68,7 +67,7 @@ void set_movement(attrib ** alist, int type) static int age_speedup(attrib * a, void *owner) { - unused_arg(owner); + UNUSED_ARG(owner); if (a->data.sa[0] > 0) { assert(a->data.sa[0] - a->data.sa[1] >= SHRT_MIN); assert(a->data.sa[0] - a->data.sa[1] <= SHRT_MAX); diff --git a/src/attributes/orcification.c b/src/attributes/orcification.c deleted file mode 100644 index dfb8f32f4..000000000 --- a/src/attributes/orcification.c +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#include -#include -#include "orcification.h" - -#include -#include - -/* - * simple attributes that do not yet have their own file - */ - -attrib_type at_orcification = { - "orcification", NULL, NULL, NULL, a_writeint, a_readint, NULL, ATF_UNIQUE -}; - -attrib *make_orcification(int orcification) -{ - attrib *a = a_new(&at_orcification); - a->data.i = orcification; - return a; -} diff --git a/src/attributes/orcification.h b/src/attributes/orcification.h deleted file mode 100644 index 3f1e2d418..000000000 --- a/src/attributes/orcification.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#ifdef __cplusplus -extern "C" { -#endif - extern struct attrib_type at_orcification; - - extern struct attrib *make_orcification(int orcification); - -#ifdef __cplusplus -} -#endif diff --git a/src/attributes/overrideroads.c b/src/attributes/overrideroads.c index 72d2260bc..ef466de2d 100644 --- a/src/attributes/overrideroads.c +++ b/src/attributes/overrideroads.c @@ -20,9 +20,8 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include "overrideroads.h" -#include #include attrib_type at_overrideroads = { - "roads_override", NULL, NULL, NULL, &a_writestring, &a_readstring + "roads_override", NULL, NULL, NULL, a_writestring, a_readstring }; diff --git a/src/attributes/racename.c b/src/attributes/racename.c index f60340b0c..c45fa3815 100644 --- a/src/attributes/racename.c +++ b/src/attributes/racename.c @@ -20,7 +20,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include "racename.h" -#include #include /* libc includes */ @@ -44,7 +43,7 @@ void set_racename(attrib ** palist, const char *name) attrib *a = a_find(*palist, &at_racename); if (!a && name) { a = a_add(palist, a_new(&at_racename)); - a->data.v = _strdup(name); + a->data.v = strdup(name); } else if (a && !name) { a_remove(palist, a); @@ -52,7 +51,7 @@ void set_racename(attrib ** palist, const char *name) else if (a) { if (strcmp(a->data.v, name) != 0) { free(a->data.v); - a->data.v = _strdup(name); + a->data.v = strdup(name); } } } diff --git a/src/attributes/raceprefix.c b/src/attributes/raceprefix.c index 308c75292..a87edfb80 100644 --- a/src/attributes/raceprefix.c +++ b/src/attributes/raceprefix.c @@ -19,7 +19,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include "raceprefix.h" -#include #include @@ -42,7 +41,7 @@ void set_prefix(attrib ** ap, const char *str) free(a->data.v); } assert(a->type == &at_raceprefix); - a->data.v = _strdup(str); + a->data.v = strdup(str); } const char *get_prefix(attrib * a) @@ -54,7 +53,7 @@ const char *get_prefix(attrib * a) str = (char *)a->data.v; /* conversion of old prefixes */ if (strncmp(str, "prefix_", 7) == 0) { - ((attrib *)a)->data.v = _strdup(str + 7); + ((attrib *)a)->data.v = strdup(str + 7); free(str); str = (char *)a->data.v; } diff --git a/src/attributes/reduceproduction.c b/src/attributes/reduceproduction.c index 3f31938d3..01041380a 100644 --- a/src/attributes/reduceproduction.c +++ b/src/attributes/reduceproduction.c @@ -19,7 +19,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include "reduceproduction.h" -#include #include #include #include diff --git a/src/attributes/stealth.c b/src/attributes/stealth.c index b7336efc7..db2ec5304 100644 --- a/src/attributes/stealth.c +++ b/src/attributes/stealth.c @@ -1,7 +1,6 @@ #include #include #include -#include #include #include diff --git a/src/attributes/targetregion.c b/src/attributes/targetregion.c index 93ef08d0b..f61214dfc 100644 --- a/src/attributes/targetregion.c +++ b/src/attributes/targetregion.c @@ -21,7 +21,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include -#include #include #include diff --git a/src/battle.c b/src/battle.c index 1bbaaadfe..e8eb426e3 100644 --- a/src/battle.c +++ b/src/battle.c @@ -21,10 +21,11 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "battle.h" #include "alchemy.h" #include "chaos.h" -#include "move.h" +#include "guard.h" #include "laws.h" +#include "monsters.h" +#include "move.h" #include "skill.h" -#include "monster.h" #include #include @@ -63,7 +64,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include +#include #include #include @@ -75,16 +76,14 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include -static FILE *bdebug; - #define TACTICS_BONUS 1 /* when undefined, we have a tactics round. else this is the bonus tactics give */ #define TACTICS_MODIFIER 1 /* modifier for generals in the front/rear */ #define CATAPULT_INITIAL_RELOAD 4 /* erster schuss in runde 1 + rng_int() % INITIAL */ #define CATAPULT_STRUCTURAL_DAMAGE -#define BASE_CHANCE 70 /* 70% Basis-berlebenschance */ -#define TDIFF_CHANGE 5 /* 5% hher pro Stufe */ +#define BASE_CHANCE 70 /* 70% Basis-�berlebenschance */ +#define TDIFF_CHANGE 5 /* 5% h�her pro Stufe */ #define DAMAGE_QUOTIENT 2 /* damage += skilldiff/DAMAGE_QUOTIENT */ #define DEBUG_SELECT /* should be disabled if select_enemy works */ @@ -94,9 +93,6 @@ typedef enum combatmagic { DO_POSTCOMBATSPELL } combatmagic_t; -/* globals */ -static int obs_count = 0; - #define MINSPELLRANGE 1 #define MAXSPELLRANGE 7 @@ -302,11 +298,11 @@ static int dead_fighters(const fighter * df) } fighter *select_corpse(battle * b, fighter * af) -/* Whlt eine Leiche aus, der af hilft. casualties ist die Anzahl der +/* W�hlt eine Leiche aus, der af hilft. casualties ist die Anzahl der * Toten auf allen Seiten (im Array). Wenn af == NULL, wird die - * Parteizugehrigkeit ignoriert, und irgendeine Leiche genommen. + * Parteizugeh�rigkeit ignoriert, und irgendeine Leiche genommen. * - * Untote werden nicht ausgewhlt (casualties, not dead) */ + * Untote werden nicht ausgew�hlt (casualties, not dead) */ { int si, maxcasualties = 0; fighter *df; @@ -322,7 +318,7 @@ fighter *select_corpse(battle * b, fighter * af) side *s; for (s = b->sides; s != b->sides + b->nsides; ++s) { for (df = s->fighters; df; df = df->next) { - /* Geflohene haben auch 0 hp, drfen hier aber nicht ausgewhlt + /* Geflohene haben auch 0 hp, d�rfen hier aber nicht ausgew�hlt * werden! */ int dead = dead_fighters(df); if (!playerrace(u_race(df->unit))) @@ -438,7 +434,7 @@ static int get_row(const side * s, int row, const side * vs) /* every entry in the size[] array means someone trying to defend us. * 'retreat' is the number of rows falling. */ - result = _max(FIRST_ROW, row - retreat); + result = MAX(FIRST_ROW, row - retreat); return result; } @@ -507,6 +503,9 @@ contest_new(int skilldiff, const troop dt, const armor_type * ar, const armor_type * sh) { double tohit = 0.5 + skilldiff * 0.1; + + UNUSED_ARG(sh); + UNUSED_ARG(ar); if (tohit < 0.5) tohit = 0.5; if (chance(tohit)) { @@ -577,10 +576,7 @@ static weapon *select_weapon(const troop t, bool attacking, static bool i_canuse(const unit * u, const item_type * itype) { - if (itype->canuse) { - return itype->canuse(u, itype); - } - return true; + return rc_can_use(u_race(u), itype); } static int @@ -598,12 +594,12 @@ weapon_skill(const weapon_type * wtype, const unit * u, bool attacking) if (u_race(u) == get_race(RC_ORC)) { int sword = effskill(u, SK_MELEE, 0); int spear = effskill(u, SK_SPEAR, 0); - skill = _max(sword, spear) - 3; + skill = MAX(sword, spear) - 3; if (attacking) { - skill = _max(skill, u_race(u)->at_default); + skill = MAX(skill, u_race(u)->at_default); } else { - skill = _max(skill, u_race(u)->df_default); + skill = MAX(skill, u_race(u)->df_default); } } else { @@ -616,7 +612,7 @@ weapon_skill(const weapon_type * wtype, const unit * u, bool attacking) } } else { - /* der rassen-defaultwert kann hher sein als der Talentwert von + /* der rassen-defaultwert kann h�her sein als der Talentwert von * waffenloser kampf */ if (attacking) { if (skill < u_race(u)->at_default) @@ -683,7 +679,7 @@ static int CavalryBonus(const unit * u, troop enemy, int type) /* only half against trolls */ if (skl > 0) { if (type == BONUS_SKILL) { - int dmg = _min(skl, 8); + int dmg = MIN(skl, 8); if (u_race(enemy.fighter->unit) == get_race(RC_TROLL)) { dmg = dmg / 4; } @@ -694,7 +690,7 @@ static int CavalryBonus(const unit * u, troop enemy, int type) } else { skl = skl / 2; - return _min(skl, 4); + return MIN(skl, 4); } } } @@ -704,7 +700,7 @@ static int CavalryBonus(const unit * u, troop enemy, int type) static int weapon_effskill(troop t, troop enemy, const weapon * w, bool attacking, bool missile) -/* effektiver Waffenskill whrend des Kampfes */ +/* effektiver Waffenskill w�hrend des Kampfes */ { /* In dieser Runde alle die Modifier berechnen, die fig durch die * Waffen bekommt. */ @@ -761,24 +757,20 @@ bool missile) if (is_riding(t) && (wtype == NULL || (fval(wtype, WTF_HORSEBONUS) && !fval(wtype, WTF_MISSILE)))) { skill += CavalryBonus(tu, enemy, BONUS_SKILL); - if (wtype) - skill = - skillmod(urace(tu)->attribs, tu, tu->region, wtype->skill, skill, - SMF_RIDING); } if (t.index < tf->elvenhorses) { /* Elfenpferde: Helfen dem Reiter, egal ob und welche Waffe. Das ist - * eleganter, und vor allem einfacher, sonst mu man noch ein + * eleganter, und vor allem einfacher, sonst mu� man noch ein * WMF_ELVENHORSE einbauen. */ skill += 2; } if (skill > 0 && !attacking && missile) { /* - * Wenn ich verteidige, und nicht direkt meinem Feind gegenberstehe, - * halbiert sich mein Skill: (z.B. gegen Fernkmpfer. Nahkmpfer - * knnen mich eh nicht treffen) + * Wenn ich verteidige, und nicht direkt meinem Feind gegen�berstehe, + * halbiert sich mein Skill: (z.B. gegen Fernk�mpfer. Nahk�mpfer + * k�nnen mich eh nicht treffen) */ skill /= 2; } @@ -814,9 +806,9 @@ static const armor_type *select_armor(troop t, bool shield) } /* Hier ist zu beachten, ob und wie sich Zauber und Artefakte, die - * Rstungschutz geben, addieren. - * - Artefakt "trollbelt" gibt Rstung +1 - * - Zauber Rindenhaut gibt Rstung +3 + * R�stungschutz geben, addieren. + * - Artefakt "trollbelt" gibt R�stung +1 + * - Zauber Rindenhaut gibt R�stung +3 */ static int trollbelts(const unit *u) { const struct resource_type *belt = rt_find("trollbelt"); @@ -834,9 +826,10 @@ int select_magicarmor(troop t) return ma; } -/* Sind side ds und Magier des meffect verbndet, dann return 1*/ +/* Sind side ds und Magier des meffect verb�ndet, dann return 1*/ bool meffect_protection(battle * b, meffect * s, side * ds) { + UNUSED_ARG(b); if (!s->magician->alive) return false; if (s->duration <= 0) @@ -851,6 +844,7 @@ bool meffect_protection(battle * b, meffect * s, side * ds) /* Sind side as und Magier des meffect verfeindet, dann return 1*/ bool meffect_blocked(battle * b, meffect * s, side * as) { + UNUSED_ARG(b); if (!s->magician->alive) return false; if (s->duration <= 0) @@ -870,7 +864,7 @@ void rmfighter(fighter * df, int i) assert(df->alive >= i); assert(df->alive <= df->unit->number); - /* erst ziehen wir die Anzahl der Personen von den Kmpfern in der + /* erst ziehen wir die Anzahl der Personen von den K�mpfern in der * Schlacht, dann von denen auf dieser Seite ab*/ df->side->alive -= i; df->side->battle->alive -= i; @@ -928,14 +922,12 @@ void kill_troop(troop dt) if (!df->alive) { char eqname[64]; const struct equipment *eq; - if (u_race(du)->itemdrop) { - item *drops = u_race(du)->itemdrop(u_race(du), du->number - df->run.number); - - if (drops != NULL) { - i_merge(&du->items, &drops); - } + const race *rc = u_race(du); + item *drops = item_spoil(rc, du->number - df->run.number); + if (drops != NULL) { + i_merge(&du->items, &drops); } - sprintf(eqname, "%s_spoils", u_race(du)->_name); + sprintf(eqname, "%s_spoils", rc->_name); eq = get_equipment(eqname); if (eq != NULL) { equip_items(&du->items, eq); @@ -1006,30 +998,25 @@ static void vampirism(troop at, int damage) if (gain > 0) { int maxhp = unit_max_hp(at.fighter->unit); at.fighter->person[at.index].hp = - _min(gain + at.fighter->person[at.index].hp, maxhp); + MIN(gain + at.fighter->person[at.index].hp, maxhp); } } } #define MAXRACES 128 -static int armor_bonus(const race *rc) { - return get_param_int(rc->parameters, "armor.stamina", -1); -} - int natural_armor(unit * du) { const race *rc = u_race(du); - int bonus, an = rc->armor; + int an; assert(rc); - bonus = armor_bonus(rc); - if (bonus > 0) { + an = rc_armor_bonus(rc); + if (an > 0) { int sk = effskill(du, SK_STAMINA, 0); - sk /= bonus; - an += sk; + return rc->armor + sk / an; } - return an; + return rc->armor; } static int rc_specialdamage(const unit *au, const unit *du, const struct weapon_type *wtype) @@ -1069,7 +1056,7 @@ static int rc_specialdamage(const unit *au, const unit *du, const struct weapon_ return modifier; } -int calculate_armor(troop dt, const weapon_type *dwtype, const weapon_type *awtype, double *magres) { +int calculate_armor(troop dt, const weapon_type *dwtype, const weapon_type *awtype, variant *magres) { fighter *df = dt.fighter; unit *du = df->unit; int ar = 0, an, am; @@ -1090,15 +1077,15 @@ int calculate_armor(troop dt, const weapon_type *dwtype, const weapon_type *awty } } - /* natrliche Rstung */ + /* nat�rliche R�stung */ an = natural_armor(du); - /* magische Rstung durch Artefakte oder Sprche */ - /* Momentan nur Trollgrtel und Werwolf-Eigenschaft */ + /* magische R�stung durch Artefakte oder Spr�che */ + /* Momentan nur Trollg�rtel und Werwolf-Eigenschaft */ am = select_magicarmor(dt); if (rule_nat_armor == 0) { - /* natrliche Rstung ist halbkumulativ */ + /* nat�rliche R�stung ist halbkumulativ */ if (ar > 0) { ar += an / 2; } @@ -1119,22 +1106,32 @@ int calculate_armor(troop dt, const weapon_type *dwtype, const weapon_type *awty ar += am; if (magres) { - // calculate damage multiplier for magical damage - double res = 1.0 - magic_resistance(du); + /* calculate damage multiplier for magical damage */ + variant res; + + res = frac_sub(frac_one, magic_resistance(du)); if (u_race(du)->battle_flags & BF_EQUIPMENT) { /* der Effekt von Laen steigt nicht linear */ - if (armor && fval(armor, ATF_LAEN)) - res *= (1 - armor->magres); - if (shield && fval(shield, ATF_LAEN)) - res *= (1 - shield->magres); - if (dwtype) - res *= (1 - dwtype->magres); + if (armor && fval(armor, ATF_LAEN)) { + res = frac_mul(res, frac_sub(frac_one, armor->magres)); + } + if (shield && fval(shield, ATF_LAEN)) { + res = frac_mul(res, frac_sub(frac_one, shield->magres)); + } + if (dwtype) { + res = frac_mul(res, frac_sub(frac_one, dwtype->magres)); + } } - /* gegen Magie wirkt nur natrliche und magische Rstung */ + /* gegen Magie wirkt nur natuerliche und magische Ruestung */ ar = an + am; - *magres = res > 0 ? res : 0; + if (res.sa[0] >= 0) { + *magres = res; + } + else { + *magres = frac_make(0, 1); + } } return ar; @@ -1157,7 +1154,7 @@ terminate(troop dt, troop at, int type, const char *damage, bool missile) const weapon_type *dwtype = NULL; const weapon_type *awtype = NULL; const weapon *weapon; - double res = 1.0; + variant res = frac_make(1, 1); int rda, sk = 0, sd; bool magic = false; @@ -1200,22 +1197,19 @@ terminate(troop dt, troop at, int type, const char *damage, bool missile) return false; } - /* TODO not sure if res could be > 1 here */ if (magic) { - da = (int)(_max(da * res, 0)); + res = frac_mul(frac_make(da, 1), res); + da = res.sa[0] / res.sa[1]; } if (type != AT_COMBATSPELL && type != AT_SPELL) { if (rule_damage & DAMAGE_CRITICAL) { double kritchance = (sk * 3 - sd) / 200.0; - kritchance = _max(kritchance, 0.005); - kritchance = _min(0.9, kritchance); + kritchance = MAX(kritchance, 0.005); + kritchance = MIN(0.9, kritchance); while (chance(kritchance)) { - if (bdebug) { - fprintf(bdebug, "%s/%d lands a critical hit\n", unitid(au), at.index); - } da += dice_rand(damage); } } @@ -1237,17 +1231,17 @@ terminate(troop dt, troop at, int type, const char *damage, bool missile) /* Skilldifferenzbonus */ if (rule_damage & DAMAGE_SKILL_BONUS) { - da += _max(0, (sk - sd) / DAMAGE_QUOTIENT); + da += MAX(0, (sk - sd) / DAMAGE_QUOTIENT); } } - rda = _max(da - ar, 0); + rda = MAX(da - ar, 0); if ((u_race(du)->battle_flags & BF_INV_NONMAGIC) && !magic) rda = 0; else { int qi; - quicklist *ql; + selist *ql; unsigned int i = 0; if (u_race(du)->battle_flags & BF_RES_PIERCE) @@ -1261,8 +1255,8 @@ terminate(troop dt, troop at, int type, const char *damage, bool missile) rda /= 2; /* Schilde */ - for (qi = 0, ql = b->meffects; ql; ql_advance(&ql, &qi, 1)) { - meffect *me = (meffect *)ql_get(ql, qi); + for (qi = 0, ql = b->meffects; ql; selist_advance(&ql, &qi, 1)) { + meffect *me = (meffect *)selist_get(ql, qi); if (meffect_protection(b, me, ds) != 0) { assert(0 <= rda); /* rda sollte hier immer mindestens 0 sein */ /* jeder Schaden wird um effect% reduziert bis der Schild duration @@ -1272,9 +1266,9 @@ terminate(troop dt, troop at, int type, const char *damage, bool missile) rda -= hp; me->duration -= hp; } - /* gibt Rstung +effect fr duration Treffer */ + /* gibt R�stung +effect f�r duration Treffer */ if (me->typ == SHIELD_ARMOR) { - rda = _max(rda - me->effect, 0); + rda = MAX(rda - me->effect, 0); me->duration--; } } @@ -1295,11 +1289,7 @@ terminate(troop dt, troop at, int type, const char *damage, bool missile) } } - if (df->person[dt.index].hp > 0) { /* Hat berlebt */ - if (bdebug) { - fprintf(bdebug, "Damage %d, armor %d: %d -> %d HP\n", - da, ar, df->person[dt.index].hp + rda, df->person[dt.index].hp); - } + if (df->person[dt.index].hp > 0) { /* Hat �berlebt */ if (u_race(au) == get_race(RC_DAEMON)) { if (!(df->person[dt.index].flags & (FL_COURAGE | FL_DAZZLED))) { df->person[dt.index].flags |= FL_DAZZLED; @@ -1317,10 +1307,10 @@ terminate(troop dt, troop at, int type, const char *damage, bool missile) if (oldpotiontype[P_HEAL] && !fval(&df->person[dt.index], FL_HEALING_USED)) { if (i_get(du->items, oldpotiontype[P_HEAL]->itype) > 0) { - i_change(&du->items, oldpotiontype[P_HEAL]->itype, -1); message *m = msg_message("battle::potionsave", "unit", du); message_faction(b, du->faction, m); msg_release(m); + i_change(&du->items, oldpotiontype[P_HEAL]->itype, -1); fset(&df->person[dt.index], FL_HEALING_USED); df->person[dt.index].hp = u_race(du)->hitpoints * 5; /* give the person a buffer */ return false; @@ -1328,10 +1318,6 @@ terminate(troop dt, troop at, int type, const char *damage, bool missile) } ++at.fighter->kills; - if (bdebug) { - fprintf(bdebug, "Damage %d, armor %d, type %d: %d -> %d HP, tot.\n", - da, ar, type, df->person[dt.index].hp + rda, df->person[dt.index].hp); - } for (pitm = &du->items; *pitm;) { item *itm = *pitm; const item_type *itype = itm->type; @@ -1473,7 +1459,7 @@ troop select_enemy(fighter * af, int minrow, int maxrow, int select) minrow = FIGHT_ROW; maxrow = BEHIND_ROW; } - minrow = _max(minrow, FIGHT_ROW); + minrow = MAX(minrow, FIGHT_ROW); enemies = count_enemies(b, af, minrow, maxrow, select); @@ -1573,7 +1559,7 @@ static troop select_opponent(battle * b, troop at, int mindist, int maxdist) dt = select_enemy(at.fighter, FIGHT_ROW, BEHIND_ROW, SELECT_ADVANCE); } else { - mindist = _max(mindist, FIGHT_ROW); + mindist = MAX(mindist, FIGHT_ROW); dt = select_enemy(at.fighter, mindist, maxdist, SELECT_ADVANCE); } @@ -1602,11 +1588,11 @@ static troop select_opponent(battle * b, troop at, int mindist, int maxdist) return dt; } -quicklist *fighters(battle * b, const side * vs, int minrow, int maxrow, +selist *fighters(battle * b, const side * vs, int minrow, int maxrow, int mask) { side *s; - quicklist *fightervp = 0; + selist *fightervp = 0; assert(vs != NULL); @@ -1628,7 +1614,7 @@ quicklist *fighters(battle * b, const side * vs, int minrow, int maxrow, for (fig = s->fighters; fig; fig = fig->next) { int row = get_unitrow(fig, vs); if (row >= minrow && row <= maxrow) { - ql_push(&fightervp, fig); + selist_push(&fightervp, fig); } } } @@ -1701,7 +1687,7 @@ void do_combatmagic(battle * b, combatmagic_t was) unit *mage = fig->unit; if (fig->alive <= 0) - continue; /* fighter kann im Kampf gettet worden sein */ + continue; /* fighter kann im Kampf get�tet worden sein */ level = effskill(mage, SK_MAGIC, r); if (level > 0) { @@ -1734,7 +1720,7 @@ void do_combatmagic(battle * b, combatmagic_t was) level = eff_spelllevel(mage, sp, level, 1); if (sl > 0) - level = _min(sl, level); + level = MIN(sl, level); if (level < 0) { report_failed_spell(b, mage, sp); free_order(ord); @@ -1762,8 +1748,8 @@ void do_combatmagic(battle * b, combatmagic_t was) for (co = spellranks[rank].begin; co; co = co->next) { fighter *fig = co->magician.fig; const spell *sp = co->sp; - int level = co->level; + level = co->level; if (!sp->cast) { log_error("spell '%s' has no function.\n", sp->sname); } @@ -1800,7 +1786,7 @@ static void do_combatspell(troop at) unit *caster = fi->unit; battle *b = fi->side->battle; region *r = b->region; - quicklist *ql; + selist *ql; int level, qi; double power; int fumblechance = 0; @@ -1810,18 +1796,18 @@ static void do_combatspell(troop at) sp = get_combatspell(caster, 1); if (sp == NULL) { - fi->magic = 0; /* Hat keinen Kampfzauber, kmpft nichtmagisch weiter */ + fi->magic = 0; /* Hat keinen Kampfzauber, k�mpft nichtmagisch weiter */ return; } ord = create_order(K_CAST, lang, "'%s'", spell_name(sp, lang)); if (!cancast(caster, sp, 1, 1, ord)) { - fi->magic = 0; /* Kann nicht mehr Zaubern, kmpft nichtmagisch weiter */ + fi->magic = 0; /* Kann nicht mehr Zaubern, k�mpft nichtmagisch weiter */ return; } level = eff_spelllevel(caster, sp, fi->magic, 1); if ((sl = get_combatspelllevel(caster, 1)) > 0) - level = _min(level, sl); + level = MIN(level, sl); if (fumble(r, caster, sp, level)) { report_failed_spell(b, caster, sp); @@ -1829,8 +1815,8 @@ static void do_combatspell(troop at) return; } - for (qi = 0, ql = b->meffects; ql; ql_advance(&ql, &qi, 1)) { - meffect *mblock = (meffect *)ql_get(ql, qi); + for (qi = 0, ql = b->meffects; ql; selist_advance(&ql, &qi, 1)) { + meffect *mblock = (meffect *)selist_get(ql, qi); if (mblock->typ == SHIELD_BLOCK) { if (meffect_blocked(b, mblock, fi->side) != 0) { fumblechance += mblock->duration; @@ -1839,7 +1825,7 @@ static void do_combatspell(troop at) } } - /* Antimagie die Fehlschlag erhht */ + /* Antimagie die Fehlschlag erh�ht */ if (rng_int() % 100 < fumblechance) { report_failed_spell(b, caster, sp); pay_spell(caster, sp, level, 1); @@ -1863,16 +1849,19 @@ static void do_combatspell(troop at) } /* Sonderattacken: Monster patzern nicht und zahlen auch keine - * Spruchkosten. Da die Spruchstrke direkt durch den Level bestimmt + * Spruchkosten. Da die Spruchst�rke direkt durch den Level bestimmt * wird, wirkt auch keine Antimagie (wird sonst in spellpower * gemacht) */ static void do_extra_spell(troop at, const att * a) { - const spell *sp = a->data.sp; + const spell *sp = spellref_get(a->data.sp); - if (sp->cast == NULL) { - log_error("spell '%s' has no function.\n", sp->sname); + if (!sp) { + log_error("no such spell: '%s'", a->data.sp->name); + } + else if (sp->cast == NULL) { + log_error("spell '%s' has no function.", sp->sname); } else { assert(a->level > 0); @@ -1886,7 +1875,13 @@ int skilldiff(troop at, troop dt, int dist) unit *au = af->unit, *du = df->unit; int is_protected = 0, skdiff = 0; weapon *awp = select_weapon(at, true, dist > 1); + static int rc_cache; + static const race *rc_halfling, *rc_goblin; + if (rc_changed(&rc_cache)) { + rc_halfling = get_race(RC_HALFLING); + rc_goblin = get_race(RC_GOBLIN); + } skdiff += af->person[at.index].attack; skdiff -= df->person[dt.index].defence; @@ -1894,37 +1889,38 @@ int skilldiff(troop at, troop dt, int dist) skdiff += 2; /* Effekte durch Rassen */ - if (awp != NULL && u_race(au) == get_race(RC_HALFLING) && dragonrace(u_race(du))) { + if (awp != NULL && u_race(au) == rc_halfling && dragonrace(u_race(du))) { skdiff += 5; } - - if (u_race(au) == get_race(RC_GOBLIN)) { + else if (u_race(au) == rc_goblin) { if (af->side->size[SUM_ROW] >= df->side->size[SUM_ROW] * rule_goblin_bonus) { skdiff += 1; } } if (df->building) { - if (df->building->attribs) { + building *b = df->building; + if (b->attribs) { const curse_type *strongwall_ct = ct_find("strongwall"); if (strongwall_ct) { - curse *c = get_curse(df->building->attribs, strongwall_ct); + curse *c = get_curse(b->attribs, strongwall_ct); if (curse_active(c)) { - /* wirkt auf alle Gebude */ + /* wirkt auf alle Geb�ude */ skdiff -= curse_geteffect_int(c); is_protected = 2; } } } - if (df->building->type->protection) { - int beff = df->building->type->protection(df->building, du, DEFENSE_BONUS); - if (beff) { + if (b->type->flags & BTF_FORTIFICATION) { + int stage = buildingeffsize(b, false); + int beff = building_protection(b->type, stage); + if (beff > 0) { skdiff -= beff; is_protected = 2; - if (df->building->attribs) { + if (b->attribs) { const curse_type *magicwalls_ct = ct_find("magicwalls"); if (magicwalls_ct - && curse_active(get_curse(df->building->attribs, magicwalls_ct))) { + && curse_active(get_curse(b->attribs, magicwalls_ct))) { /* Verdoppelt Burgenbonus */ skdiff -= beff; } @@ -1968,20 +1964,6 @@ int getreload(troop at) return at.fighter->person[at.index].reload; } -static void -debug_hit(troop at, const weapon * awp, troop dt, const weapon * dwp, -int skdiff, int dist, bool success) -{ - fprintf(bdebug, "%.4s/%d [%6s/%d] %s %.4s/%d [%6s/%d] with %d, distance %d\n", - unitid(at.fighter->unit), at.index, - LOC(default_locale, awp ? resourcename(awp->type->itype->rtype, - 0) : "unarmed"), weapon_effskill(at, dt, awp, true, dist > 1), - success ? "hits" : "misses", unitid(dt.fighter->unit), dt.index, - LOC(default_locale, dwp ? resourcename(dwp->type->itype->rtype, - 0) : "unarmed"), weapon_effskill(dt, at, dwp, false, dist > 1), skdiff, - dist); -} - int hits(troop at, troop dt, weapon * awp) { fighter *af = at.fighter, *df = dt.fighter; @@ -2015,39 +1997,27 @@ int hits(troop at, troop dt, weapon * awp) } skdiff = skilldiff(at, dt, dist); - /* Verteidiger bekommt eine Rstung */ + /* Verteidiger bekommt eine R�stung */ armor = select_armor(dt, true); if (dwp == NULL || (dwp->type->flags & WTF_USESHIELD)) { shield = select_armor(dt, false); } if (contest(skdiff, dt, armor, shield)) { - if (bdebug) { - debug_hit(at, awp, dt, dwp, skdiff, dist, true); - } return 1; } - if (bdebug) { - debug_hit(at, awp, dt, dwp, skdiff, dist, false); - } return 0; } void dazzle(battle * b, troop * td) { + UNUSED_ARG(b); /* Nicht kumulativ ! */ - if (td->fighter->person[td->index].flags & FL_DAZZLED) - return; - #ifdef TODO_RUNESWORD if (td->fighter->weapon[WP_RUNESWORD].count > td->index) { return; } #endif - if (td->fighter->person[td->index].flags & FL_COURAGE) { - return; - } - - if (td->fighter->person[td->index].flags & FL_DAZZLED) { + if (td->fighter->person[td->index].flags & (FL_COURAGE|FL_DAZZLED)) { return; } @@ -2057,11 +2027,11 @@ void dazzle(battle * b, troop * td) void damage_building(battle * b, building * bldg, int damage_abs) { - bldg->size = _max(1, bldg->size - damage_abs); + bldg->size = MAX(1, bldg->size - damage_abs); - /* Wenn Burg, dann gucken, ob die Leute alle noch in das Gebude passen. */ + /* Wenn Burg, dann gucken, ob die Leute alle noch in das Geb�ude passen. */ - if (bldg->type->protection) { + if (bldg->type->flags & BTF_FORTIFICATION) { side *s; bldg->sizeleft = bldg->size; @@ -2117,7 +2087,7 @@ static void attack(battle * b, troop ta, const att * a, int numattack) switch (a->type) { case AT_COMBATSPELL: /* Magier versuchen immer erstmal zu zaubern, erst wenn das - * fehlschlgt, wird af->magic == 0 und der Magier kmpft + * fehlschl�gt, wird af->magic == 0 und der Magier k�mpft * konventionell weiter */ if (numattack == 0 && af->magic > 0) { /* wenn der magier in die potenzielle Reichweite von Attacken des @@ -2129,7 +2099,7 @@ static void attack(battle * b, troop ta, const att * a, int numattack) } } break; - case AT_STANDARD: /* Waffen, mag. Gegenstnde, Kampfzauber */ + case AT_STANDARD: /* Waffen, mag. Gegenst�nde, Kampfzauber */ if (numattack > 0 || af->magic <= 0) { weapon *wp = ta.fighter->person[ta.index].missile; int melee = @@ -2146,7 +2116,7 @@ static void attack(battle * b, troop ta, const att * a, int numattack) bool standard_attack = true; bool reload = false; /* spezialattacken der waffe nur, wenn erste attacke in der runde. - * sonst helden mit feuerschwertern zu mchtig */ + * sonst helden mit feuerschwertern zu m�chtig */ if (numattack == 0 && wp && wp->type->attack) { int dead = 0; standard_attack = wp->type->attack(&ta, wp->type, &dead); @@ -2185,16 +2155,12 @@ static void attack(battle * b, troop ta, const att * a, int numattack) } } if (reload && wp && wp->type->reload && !getreload(ta)) { - int i = setreload(ta); - if (bdebug) { - fprintf(bdebug, "%s/%d reloading %d turns\n", unitid(au), - ta.index, i); - } + setreload(ta); } } } break; - case AT_SPELL: /* Extra-Sprche. Kampfzauber in AT_COMBATSPELL! */ + case AT_SPELL: /* Extra-Spr�che. Kampfzauber in AT_COMBATSPELL! */ do_extra_spell(ta, a); break; case AT_NATURAL: @@ -2279,14 +2245,14 @@ void do_attack(fighter * af) assert(au && au->number); /* Da das Zuschlagen auf Einheiten und nicht auf den einzelnen - * Kmpfern beruht, darf die Reihenfolge und Gre der Einheit keine + * K�mpfern beruht, darf die Reihenfolge und Gr��e der Einheit keine * Rolle spielen, Das tut sie nur dann, wenn jeder, der am Anfang der - * Runde lebte, auch zuschlagen darf. Ansonsten ist der, der zufllig - * mit einer groen Einheit zuerst drankommt, extrem bevorteilt. */ + * Runde lebte, auch zuschlagen darf. Ansonsten ist der, der zuf�llig + * mit einer gro�en Einheit zuerst drankommt, extrem bevorteilt. */ ta.index = af->fighting; while (ta.index--) { - /* Wir suchen eine beliebige Feind-Einheit aus. An der knnen + /* Wir suchen eine beliebige Feind-Einheit aus. An der k�nnen * wir feststellen, ob noch jemand da ist. */ int apr, attacks = attacks_per_round(ta); if (!count_enemies(b, af, FIGHT_ROW, LAST_ROW, SELECT_FIND)) @@ -2311,7 +2277,7 @@ void do_attack(fighter * af) } } } - /* Der letzte Katapultschtze setzt die + /* Der letzte Katapultsch�tze setzt die * Ladezeit neu und generiert die Meldung. */ if (af->catmsg >= 0) { struct message *m = @@ -2333,7 +2299,7 @@ void do_regenerate(fighter * af) while (ta.index--) { struct person *p = af->person + ta.index; p->hp += effskill(au, SK_STAMINA, 0); - p->hp = _min(unit_max_hp(au), p->hp); + p->hp = MIN(unit_max_hp(au), p->hp); } } @@ -2342,11 +2308,11 @@ static void add_tactics(tactics * ta, fighter * fig, int value) if (value == 0 || value < ta->value) return; if (value > ta->value) { - ql_free(ta->fighters); + selist_free(ta->fighters); ta->fighters = 0; } - ql_push(&ta->fighters, fig); - ql_push(&fig->side->battle->leaders, fig); + selist_push(&ta->fighters, fig); + selist_push(&fig->side->battle->leaders, fig); ta->value = value; } @@ -2385,17 +2351,17 @@ double fleechance(unit * u) { double c = 0.20; /* Fluchtwahrscheinlichkeit in % */ attrib *a = a_find(u->attribs, &at_fleechance); - /* Einheit u versucht, dem Getmmel zu entkommen */ + /* Einheit u versucht, dem Get�mmel zu entkommen */ c += (effskill(u, SK_STEALTH, 0) * 0.05); c += horse_fleeing_bonus(u); if (u_race(u) == get_race(RC_HALFLING)) { c += 0.20; - c = _min(c, 0.90); + c = MIN(c, 0.90); } else { - c = _min(c, 0.75); + c = MIN(c, 0.75); } if (a != NULL) @@ -2420,7 +2386,7 @@ side *make_side(battle * b, const faction * f, const group * g, else { unit *u; for (u = b->region->units; u; u = u->next) { - if (is_guard(u, HELP_ALL)) { + if (is_guard(u)) { if (alliedunit(u, f, HELP_GUARD)) { flags |= SIDE_HASGUARDS; break; @@ -2488,9 +2454,10 @@ troop select_ally(fighter * af, int minrow, int maxrow, int allytype) static int loot_quota(const unit * src, const unit * dst, const item_type * type, int n) { + UNUSED_ARG(type); if (dst && src && src->faction != dst->faction) { double divisor = config_get_flt("rules.items.loot_divisor", 1); - assert(divisor == 0 || divisor >= 1); + assert(divisor <= 0 || divisor >= 1); if (divisor >= 1) { double r = n / divisor; int x = (int)r; @@ -2519,7 +2486,7 @@ static void loot_items(fighter * corpse) float lootfactor = (float)dead / (float)u->number; /* only loot the dead! */ int maxloot = (int)((float)itm->number * lootfactor); if (maxloot > 0) { - int i = _min(10, maxloot); + int i = MIN(10, maxloot); for (; i != 0; --i) { int loot = maxloot / i; @@ -2600,7 +2567,7 @@ static void battle_effects(battle * b, int dead_players) { region *r = b->region; int dead_peasants = - _min(rpeasants(r), (int)(dead_players * PopulationDamage())); + MIN(rpeasants(r), (int)(dead_players * PopulationDamage())); if (dead_peasants) { deathcounts(r, dead_peasants + dead_players); add_chaoscount(r, dead_peasants / 2); @@ -2637,7 +2604,6 @@ static void reorder_fleeing(region * r) static void aftermath(battle * b) { region *r = b->region; - ship *sh; side *s; int dead_players = 0; bfaction *bf; @@ -2673,7 +2639,7 @@ static void aftermath(battle * b) for (s = b->sides; s != b->sides + b->nsides; ++s) { int snumber = 0; fighter *df; - bool relevant = false; /* Kampf relevant fr diese Partei? */ + bool relevant = false; /* Kampf relevant f�r diese Partei? */ if (!fval(s, SIDE_HASGUARDS)) { relevant = true; } @@ -2713,7 +2679,7 @@ static void aftermath(battle * b) /* Report the casualties */ reportcasualties(b, df, dead); - /* Zuerst drfen die Feinde plndern, die mitgenommenen Items + /* Zuerst d�rfen die Feinde pl�ndern, die mitgenommenen Items * stehen in fig->run.items. Dann werden die Fliehenden auf * die leere (tote) alte Einheit gemapt */ if (!fval(df, FIG_NOLOOT)) { @@ -2721,7 +2687,7 @@ static void aftermath(battle * b) } scale_number(du, df->run.number); du->hp = df->run.hp; - setguard(du, GUARD_NONE); + setguard(du, false); /* must leave ships or buildings, or a stealthy hobbit * can hold castles indefinitely */ if (!fval(r->terrain, SEA_REGION)) { @@ -2748,7 +2714,7 @@ static void aftermath(battle * b) } else { if (df->alive == 0) { - /* alle sind tot, niemand geflohen. Einheit auflsen */ + /* alle sind tot, niemand geflohen. Einheit aufl�sen */ df->run.number = 0; df->run.hp = 0; @@ -2758,7 +2724,7 @@ static void aftermath(battle * b) /* Distribute Loot */ loot_items(df); - setguard(du, GUARD_NONE); + setguard(du, false); scale_number(du, 0); } else { @@ -2810,7 +2776,7 @@ static void aftermath(battle * b) /* Wir benutzen drifted, um uns zu merken, ob ein Schiff * schonmal Schaden genommen hat. (moved und drifted - * sollten in flags berfhrt werden */ + * sollten in flags �berf�hrt werden */ for (s = b->sides; s != b->sides + b->nsides; ++s) { fighter *df; @@ -2831,9 +2797,10 @@ static void aftermath(battle * b) } /* Wenn sich die Einheit auf einem Schiff befindet, wird - * dieses Schiff beschdigt. Andernfalls ein Schiff, welches + * dieses Schiff besch�digt. Andernfalls ein Schiff, welches * evt. zuvor verlassen wurde. */ if (ships_damaged) { + ship *sh; if (du->ship) sh = du->ship; else @@ -2868,13 +2835,6 @@ static void aftermath(battle * b) } reorder_fleeing(r); - - if (bdebug) { - fprintf(bdebug, "The battle lasted %d turns, %s and %s.\n", - b->turn, - b->has_tactics_turn ? "had a tactic turn" : "had no tactic turn", - ships_damaged ? "was relevant" : "was not relevant."); - } } static void battle_punit(unit * u, battle * b) @@ -2888,10 +2848,6 @@ static void battle_punit(unit * u, battle * b) spunit(&S, f, u, 4, seen_battle); for (x = S; x; x = x->next) { fbattlerecord(b, f, x->s); - if (bdebug && u->faction == f) { - fputs(x->s, bdebug); - fputc('\n', bdebug); - } } if (S) freestrlist(S); @@ -3071,17 +3027,6 @@ static void print_stats(battle * b) fbattlerecord(b, f, buf); } - if (bdebug && s->faction) { - if (f_get_alliance(s->faction)) { - fprintf(bdebug, "##### %s (%s/%d)\n", s->faction->name, - itoa36(s->faction->no), - s->faction->alliance ? s->faction->alliance->id : 0); - } - else { - fprintf(bdebug, "##### %s (%s)\n", s->faction->name, - itoa36(s->faction->no)); - } - } print_fighters(b, s); } @@ -3092,19 +3037,19 @@ static void print_stats(battle * b) b->max_tactics = 0; for (s = b->sides; s != b->sides + b->nsides; ++s) { - if (!ql_empty(s->leader.fighters)) { - b->max_tactics = _max(b->max_tactics, s->leader.value); + if (!selist_empty(s->leader.fighters)) { + b->max_tactics = MAX(b->max_tactics, s->leader.value); } } if (b->max_tactics > 0) { for (s = b->sides; s != b->sides + b->nsides; ++s) { if (s->leader.value == b->max_tactics) { - quicklist *ql; + selist *ql; int qi; - for (qi = 0, ql = s->leader.fighters; ql; ql_advance(&ql, &qi, 1)) { - fighter *tf = (fighter *)ql_get(ql, qi); + for (qi = 0, ql = s->leader.fighters; ql; selist_advance(&ql, &qi, 1)) { + fighter *tf = (fighter *)selist_get(ql, qi); unit *u = tf->unit; message *m = NULL; if (!is_attacker(tf)) { @@ -3123,7 +3068,7 @@ static void print_stats(battle * b) static int weapon_weight(const weapon * w, bool missile) { - if (missile == i2b(fval(w->type, WTF_MISSILE))) { + if (missile == !!(fval(w->type, WTF_MISSILE))) { return w->attackskill + w->defenseskill; } return 0; @@ -3204,8 +3149,8 @@ fighter *make_fighter(battle * b, unit * u, side * s1, bool attack) else if (!stealthfaction) { s1->stealthfaction = NULL; } - /* Zu diesem Zeitpunkt ist attacked noch 0, da die Einheit fr noch - * keinen Kampf ausgewhlt wurde (sonst wrde ein fighter existieren) */ + /* Zu diesem Zeitpunkt ist attacked noch 0, da die Einheit f�r noch + * keinen Kampf ausgew�hlt wurde (sonst w�rde ein fighter existieren) */ } fig = (struct fighter*)calloc(1, sizeof(struct fighter)); @@ -3213,8 +3158,8 @@ fighter *make_fighter(battle * b, unit * u, side * s1, bool attack) s1->fighters = fig; fig->unit = u; - /* In einer Burg mu man a) nicht Angreifer sein, und b) drin sein, und - * c) noch Platz finden. d) menschanhnlich sein */ + /* In einer Burg mu� man a) nicht Angreifer sein, und b) drin sein, und + * c) noch Platz finden. d) menschan�hnlich sein */ if (attack) { set_attacker(fig); } @@ -3240,7 +3185,7 @@ fighter *make_fighter(battle * b, unit * u, side * s1, bool attack) assert(h); rest = u->hp % u->number; - /* Effekte von Sprchen */ + /* Effekte von Spr�chen */ if (u->attribs) { const curse_type *speed_ct; @@ -3259,9 +3204,9 @@ fighter *make_fighter(battle * b, unit * u, side * s1, bool attack) /* change_effect wird in ageing gemacht */ /* Effekte von Artefakten */ - strongmen = _min(fig->unit->number, trollbelts(u)); + strongmen = MIN(fig->unit->number, trollbelts(u)); - /* Hitpoints, Attack- und Defence-Boni fr alle Personen */ + /* Hitpoints, Attack- und Defence-Boni f�r alle Personen */ for (i = 0; i < fig->alive; i++) { assert(i < fig->unit->number); fig->person[i].hp = h; @@ -3282,8 +3227,8 @@ fighter *make_fighter(battle * b, unit * u, side * s1, bool attack) } } - /* Fr alle Waffengattungen wird bestimmt, wie viele der Personen mit - * ihr kmpfen knnten, und was ihr Wert darin ist. */ + /* F�r alle Waffengattungen wird bestimmt, wie viele der Personen mit + * ihr k�mpfen k�nnten, und was ihr Wert darin ist. */ if (u_race(u)->battle_flags & BF_EQUIPMENT) { int oi = 0, di = 0, w = 0; for (itm = u->items; itm && w != WMAX; itm = itm->next) { @@ -3401,12 +3346,12 @@ fighter *make_fighter(battle * b, unit * u, side * s1, bool attack) } } - /* Jetzt mu noch geschaut werden, wo die Einheit die jeweils besten - * Werte hat, das kommt aber erst irgendwo spter. Ich entscheide - * wrend des Kampfes, welche ich nehme, je nach Gegner. Deswegen auch + /* Jetzt mu� noch geschaut werden, wo die Einheit die jeweils besten + * Werte hat, das kommt aber erst irgendwo sp�ter. Ich entscheide + * w�rend des Kampfes, welche ich nehme, je nach Gegner. Deswegen auch * keine addierten boni. */ - /* Zuerst mal die Spezialbehandlung gewisser Sonderflle. */ + /* Zuerst mal die Spezialbehandlung gewisser Sonderf�lle. */ fig->magic = effskill(u, SK_MAGIC, 0); if (fig->horses) { @@ -3449,7 +3394,7 @@ fighter *make_fighter(battle * b, unit * u, side * s1, bool attack) else p_bonus += 3; } while (rnd >= 97); - bonus = _max(p_bonus, bonus); + bonus = MAX(p_bonus, bonus); } tactics += bonus; } @@ -3513,28 +3458,6 @@ static int join_battle(battle * b, unit * u, bool attack, fighter ** cp) return false; } -static const char *simplename(region * r) -{ - int i; - static char name[17]; - const char *cp = rname(r, default_locale); - for (i = 0; *cp && i != 16; ++i, ++cp) { - int c = *(unsigned char *)cp; - while (c && !isalpha(c) && !isxspace(c)) { - ++cp; - c = *(unsigned char *)cp; - } - if (isxspace(c)) - name[i] = '_'; - else - name[i] = *cp; - if (c == 0) - break; - } - name[i] = 0; - return name; -} - battle *make_battle(region * r) { battle *b = (battle *)calloc(1, sizeof(battle)); @@ -3546,32 +3469,9 @@ battle *make_battle(region * r) for (bld = r->buildings; bld != NULL; bld = bld->next) bld->sizeleft = bld->size; - if (battledebug) { - char zText[MAX_PATH]; - char zFilename[MAX_PATH]; - join_path(basepath(), "battles", zText, sizeof(zText)); - if (_mkdir(zText) != 0) { - log_error("could not create subdirectory for battle logs: %s", zText); - battledebug = false; - } - else { - sprintf(zFilename, "battle-%d-%s.log", obs_count++, simplename(r)); - join_path(zText, zFilename, zText, sizeof(zText)); - bdebug = fopen(zText, "w"); - if (!bdebug) - log_error("battles cannot be debugged"); - else { - const unsigned char utf8_bom[4] = { 0xef, 0xbb, 0xbf, 0 }; - fwrite(utf8_bom, 1, 3, bdebug); - fprintf(bdebug, "In %s findet ein Kampf statt:\n", rname(r, - default_locale)); - } - } - } - b->region = r; b->plane = getplane(r); - /* Finde alle Parteien, die den Kampf beobachten knnen: */ + /* Finde alle Parteien, die den Kampf beobachten k�nnen: */ for (u = r->units; u; u = u->next) { if (u->number > 0) { if (!fval(u->faction, FFL_MARK)) { @@ -3600,7 +3500,7 @@ battle *make_battle(region * r) static void free_side(side * si) { - ql_free(si->leader.fighters); + selist_free(si->leader.fighters); } static void free_fighter(fighter * fig) @@ -3638,19 +3538,15 @@ static void battle_free(battle * b) { void free_battle(battle * b) { - if (bdebug) { - fclose(bdebug); - } - while (b->factions) { bfaction *bf = b->factions; b->factions = bf->next; free(bf); } - ql_free(b->leaders); - ql_foreach(b->meffects, free); - ql_free(b->meffects); + selist_free(b->leaders); + selist_foreach(b->meffects, free); + selist_free(b->meffects); battle_free(b); } @@ -3760,18 +3656,18 @@ static void join_allies(battle * b) for (s = b->sides; s != s_end; ++s) { side *se; - /* Wenn alle attackierten noch FFL_NOAID haben, dann kmpfe nicht mit. */ + /* Wenn alle attackierten noch FFL_NOAID haben, dann k�mpfe nicht mit. */ if (fval(s->faction, FFL_NOAID)) continue; if (s->faction != f) { /* Wenn wir attackiert haben, kommt niemand mehr hinzu: */ if (s->bf->attacker) continue; - /* alliiert mssen wir schon sein, sonst ist's eh egal : */ + /* alliiert m�ssen wir schon sein, sonst ist's eh egal : */ if (!alliedunit(u, s->faction, HELP_FIGHT)) continue; /* wenn die partei verborgen ist, oder gar eine andere - * vorgespiegelt wird, und er sich uns gegenber nicht zu + * vorgespiegelt wird, und er sich uns gegen�ber nicht zu * erkennen gibt, helfen wir ihm nicht */ if (s->stealthfaction) { if (!allysfm(s, u->faction, HELP_FSTEALTH)) { @@ -3779,7 +3675,7 @@ static void join_allies(battle * b) } } } - /* einen alliierten angreifen drfen sie nicht, es sei denn, der + /* einen alliierten angreifen d�rfen sie nicht, es sei denn, der * ist mit einem alliierten verfeindet, der nicht attackiert * hat: */ for (se = b->sides; se != s_end; ++se) { @@ -3793,7 +3689,7 @@ static void join_allies(battle * b) } if (se == s_end) continue; - /* Wenn die Einheit belagert ist, mu auch einer der Alliierten belagert sein: */ + /* Wenn die Einheit belagert ist, mu� auch einer der Alliierten belagert sein: */ if (besieged(u)) { fighter *ally; for (ally = s->fighters; ally; ally = ally->next) { @@ -3804,15 +3700,9 @@ static void join_allies(battle * b) if (ally == NULL) continue; } - /* keine Einwnde, also soll er mitmachen: */ + /* keine Einw�nde, also soll er mitmachen: */ if (c == NULL) { - if (join_battle(b, u, false, &c)) { - if (battledebug) { - fprintf(bdebug, "%s joins to help %s against %s.\n", - unitname(u), factionname(s->faction), factionname(se->faction)); - } - } - else if (c == NULL) { + if (!join_battle(b, u, false, &c)) { continue; } } @@ -3820,12 +3710,7 @@ static void join_allies(battle * b) /* the enemy of my friend is my enemy: */ for (se = b->sides; se != s_end; ++se) { if (se->faction != u->faction && enemy(s, se)) { - if (set_enemy(se, c->side, false) && battledebug) { - fprintf(bdebug, - "%u/%s hates %u/%s because they are enemies with %u/%s.\n", - c->side->index, sidename(c->side), se->index, sidename(se), - s->index, sidename(s)); - } + set_enemy(se, c->side, false); } } } @@ -3873,7 +3758,7 @@ static void flee(const troop dt) fig->run.hp += fig->person[dt.index].hp; ++fig->run.number; - setguard(u, GUARD_NONE); + setguard(u, false); kill_troop(dt); } @@ -3920,7 +3805,7 @@ static bool start_battle(region * r, battle ** bp) continue; } - /* ist ein Flchtling aus einem andern Kampf */ + /* ist ein Fl�chtling aus einem andern Kampf */ if (fval(u, UFL_LONGACTION)) continue; @@ -3936,12 +3821,12 @@ static bool start_battle(region * r, battle ** bp) if ((u->ship != NULL && !fval(r->terrain, SEA_REGION)) || (lsh = leftship(u)) != NULL) { - if (is_guarded(r, u, GUARD_TRAVELTHRU)) { + if (is_guarded(r, u)) { if (lsh) { cmistake(u, ord, 234, MSG_BATTLE); } else { - /* Fehler: "Das Schiff mu erst verlassen werden" */ + /* Fehler: "Das Schiff mu� erst verlassen werden" */ cmistake(u, ord, 19, MSG_BATTLE); } continue; @@ -3985,7 +3870,7 @@ static bool start_battle(region * r, battle ** bp) while (a && a->type == &at_curse) { curse *c = (curse *)a->data.v; if (c->type == calm_ct - && curse_geteffect(c) == u2->faction->subscription) { + && curse_geteffect_int(c) == u2->faction->subscription) { if (curse_active(c)) { calm = true; break; @@ -4006,18 +3891,8 @@ static bool start_battle(region * r, battle ** bp) } b = make_battle(r); } - if (join_battle(b, u, true, &c1)) { - if (battledebug) { - fprintf(bdebug, "%s joins by attacking %s.\n", - unitname(u), unitname(u2)); - } - } - if (join_battle(b, u2, false, &c2)) { - if (battledebug) { - fprintf(bdebug, "%s joins because of an attack from %s.\n", - unitname(u2), unitname(u)); - } - } + join_battle(b, u, true, &c1); + join_battle(b, u2, false, &c2); /* Hat die attackierte Einheit keinen Noaid-Status, * wird das Flag von der Faction genommen, andere @@ -4026,15 +3901,11 @@ static bool start_battle(region * r, battle ** bp) freset(u2->faction, FFL_NOAID); if (c1 != NULL && c2 != NULL) { - /* Merken, wer Angreifer ist, fr die Rckzahlung der - * Prcombataura bei kurzem Kampf. */ + /* Merken, wer Angreifer ist, f�r die R�ckzahlung der + * Pr�combataura bei kurzem Kampf. */ c1->side->bf->attacker = true; - if (set_enemy(c1->side, c2->side, true) && battledebug) { - fprintf(bdebug, "%u/%s hates %u/%s because they attacked them.\n", - c2->side->index, sidename(c2->side), - c1->side->index, sidename(c1->side)); - } + set_enemy(c1->side, c2->side, true); fighting = true; } } @@ -4060,7 +3931,7 @@ static void battle_attacks(battle * b) && get_tactics(s, NULL) == b->max_tactics)) { for (fig = s->fighters; fig; fig = fig->next) { - /* ist in dieser Einheit noch jemand handlungsfhig? */ + /* ist in dieser Einheit noch jemand handlungsf�hig? */ if (fig->fighting <= 0) continue; @@ -4104,8 +3975,8 @@ static void battle_flee(battle * b) unit *u = fig->unit; troop dt; int runners = 0; - /* Flucht nicht bei mehr als 600 HP. Damit Wyrme ttbar bleiben. */ - int runhp = _min(600, (int)(0.9 + unit_max_hp(u) * hpflee(u->status))); + /* Flucht nicht bei mehr als 600 HP. Damit Wyrme t�tbar bleiben. */ + int runhp = MIN(600, (int)(0.9 + unit_max_hp(u) * hpflee(u->status))); if (u->ship && fval(u->region->terrain, SEA_REGION)) { /* keine Flucht von Schiffen auf hoher See */ @@ -4148,15 +4019,11 @@ static void battle_flee(battle * b) if (fig->person[dt.index].flags & FL_PANICED) { ispaniced = EFFECT_PANIC_SPELL; } - if (chance(_min(fleechance(u) + ispaniced, 0.90))) { + if (chance(MIN(fleechance(u) + ispaniced, 0.90))) { ++runners; flee(dt); } } - if (bdebug && runners > 0) { - fprintf(bdebug, "Fleeing: %d from %s\n", runners, - itoa36(fig->unit->no)); - } } } } @@ -4224,7 +4091,7 @@ void do_battle(region * r) return; /* Bevor wir die alliierten hineinziehen, sollten wir schauen, * - * Ob jemand fliehen kann. Dann erbrigt sich das ganze ja + * Ob jemand fliehen kann. Dann er�brigt sich das ganze ja * vielleicht schon. */ print_header(b); if (!fighting) { @@ -4243,7 +4110,7 @@ void do_battle(region * r) freset(sh, SF_DAMAGED); /* Gibt es eine Taktikrunde ? */ - if (!ql_empty(b->leaders)) { + if (!selist_empty(b->leaders)) { b->turn = 0; b->has_tactics_turn = true; } @@ -4259,9 +4126,6 @@ void do_battle(region * r) log_debug("battle in %s (%d, %d) : ", regionname(r, 0), r->x, r->y); for (; battle_report(b) && b->turn <= max_turns; ++b->turn) { - if (bdebug) { - fprintf(bdebug, "*** Turn: %d\n", b->turn); - } battle_flee(b); battle_update(b); battle_attacks(b); @@ -4273,12 +4137,10 @@ void do_battle(region * r) if (rule_force_leave(FORCE_LEAVE_POSTCOMBAT)) { force_leave(b->region, b); } - /* Hier ist das Gefecht beendet, und wir knnen die - * Hilfsstrukturen * wieder lschen: */ + /* Hier ist das Gefecht beendet, und wir k�nnen die + * Hilfsstrukturen * wieder l�schen: */ - if (b) { - free_battle(b); - } + free_battle(b); } void do_battles(void) { diff --git a/src/battle.h b/src/battle.h index 3e156070d..85e65cf66 100644 --- a/src/battle.h +++ b/src/battle.h @@ -20,17 +20,21 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #define H_KRNL_BATTLE #include +#include #ifdef __cplusplus extern "C" { #endif + struct message; + struct selist; + /** more defines **/ #define FS_ENEMY 1 #define FS_HELP 2 /***** Verteidigungslinien. - * Eressea hat 4 Verteidigungslinien. 1 ist vorn, 5. enthlt Summen + * Eressea hat 4 Verteidigungslinien. 1 ist vorn, 5. enthaelt Summen */ #define NUMROWS 5 @@ -43,7 +47,6 @@ extern "C" { #define LAST_ROW FLEE_ROW #define MAXSIDES 192 /* if there are ever more than this, we're fucked. */ - struct message; typedef struct bfaction { struct bfaction *next; @@ -53,7 +56,7 @@ extern "C" { } bfaction; typedef struct tactics { - struct quicklist *fighters; + struct selist *fighters; int value; } tactics; @@ -72,9 +75,9 @@ extern "C" { unsigned char relations[MAXSIDES]; struct side *enemies[MAXSIDES]; struct fighter *fighters; - int index; /* Eintrag der Fraktion in b->matrix/b->enemies */ + unsigned int index; /* Eintrag der Fraktion in b->matrix/b->enemies */ int size[NUMROWS]; /* Anzahl Personen in Reihe X. 0 = Summe */ - int nonblockers[NUMROWS]; /* Anzahl nichtblockierender Kmpfer, z.B. Schattenritter. */ + int nonblockers[NUMROWS]; /* Anzahl nichtblockierender Kaempfer, z.B. Schattenritter. */ int alive; /* Die Partei hat den Kampf verlassen */ int removed; /* stoned */ int flee; @@ -86,7 +89,7 @@ extern "C" { } side; typedef struct battle { - struct quicklist *leaders; + struct selist *leaders; struct region *region; struct plane *plane; bfaction *factions; @@ -94,7 +97,7 @@ extern "C" { int nfighters; side sides[MAXSIDES]; int nsides; - struct quicklist *meffects; + struct selist *meffects; int max_tactics; int turn; bool has_tactics_turn; @@ -131,7 +134,7 @@ extern "C" { /*** fighter::person::flags ***/ #define FL_TIRED 1 -#define FL_DAZZLED 2 /* durch Untote oder Dmonen eingeschchtert */ +#define FL_DAZZLED 2 /* durch Untote oder Daemonen eingeschuechtert */ #define FL_PANICED 4 #define FL_COURAGE 8 /* Helden fliehen nie */ #define FL_SLEEPING 16 @@ -156,17 +159,17 @@ extern "C" { typedef struct fighter { struct fighter *next; struct side *side; - struct unit *unit; /* Die Einheit, die hier kmpft */ - struct building *building; /* Gebude, in dem die Einheit evtl. steht */ + struct unit *unit; /* Die Einheit, die hier kaempft */ + struct building *building; /* Gebaeude, in dem die Einheit evtl. steht */ status_t status; /* Kampfstatus */ struct weapon *weapons; - struct armor *armors; /* Anzahl Rstungen jeden Typs */ + struct armor *armors; /* Anzahl Ruestungen jeden Typs */ int alive; /* Anzahl der noch nicht Toten in der Einheit */ - int fighting; /* Anzahl der Kmpfer in der aktuellen Runde */ + int fighting; /* Anzahl der Kaempfer in der aktuellen Runde */ int removed; /* Anzahl Kaempfer, die nicht tot sind, aber aus dem Kampf raus sind (zB weil sie versteinert wurden). Diese werden auch - in alive noch mitgezhlt! */ + in alive noch mitgezaehlt! */ int magic; /* Magietalent der Einheit */ int horses; /* Anzahl brauchbarer Pferde der Einheit */ int elvenhorses; /* Anzahl brauchbarer Elfenpferde der Einheit */ @@ -179,7 +182,7 @@ extern "C" { int defence : 8; /* (Magie) Paradenbonus der Personen */ int damage : 8; /* (Magie) Schadensbonus der Personen im Nahkampf */ int damage_rear : 8; /* (Magie) Schadensbonus der Personen im Fernkampf */ - int flags : 8; /* (Magie) Diverse Flags auf Kmpfern */ + int flags : 8; /* (Magie) Diverse Flags auf Kaempfern */ int speed : 8; /* (Magie) Geschwindigkeitsmultiplkator. */ int reload : 4; /* Anzahl Runden, die die Waffe x noch laden muss. * dahinter steckt ein array[RL_MAX] wenn er min. eine hat. */ @@ -245,14 +248,14 @@ extern "C" { int count_enemies(struct battle *b, const struct fighter *af, int minrow, int maxrow, int select); int natural_armor(struct unit * u); - int calculate_armor(troop dt, const struct weapon_type *dwtype, const struct weapon_type *awtype, double *magres); + int calculate_armor(troop dt, const struct weapon_type *dwtype, const struct weapon_type *awtype, union variant *magres); bool terminate(troop dt, troop at, int type, const char *damage, bool missile); extern void message_all(battle * b, struct message *m); extern int hits(troop at, troop dt, weapon * awp); extern void damage_building(struct battle *b, struct building *bldg, int damage_abs); - struct quicklist *fighters(struct battle *b, const struct side *vs, + struct selist *fighters(struct battle *b, const struct side *vs, int minrow, int maxrow, int mask); int count_allies(const struct side *as, int minrow, int maxrow, int select, int allytype); diff --git a/src/battle.test.c b/src/battle.test.c index 7228ef90e..b00d06a98 100644 --- a/src/battle.test.c +++ b/src/battle.test.c @@ -26,7 +26,7 @@ static void test_make_fighter(CuTest * tc) faction * f; const resource_type *rtype; - test_cleanup(); + test_setup(); test_create_horse(); r = test_create_region(0, 0, 0); f = test_create_faction(NULL); @@ -60,8 +60,17 @@ static void test_make_fighter(CuTest * tc) test_cleanup(); } -static int add_two(const building * b, const unit * u, building_bonus bonus) { - return 2; +static building_type * setup_castle(void) { + building_type * btype; + construction *cons; + + btype = bt_get_or_create("castle"); + btype->flags |= BTF_FORTIFICATION; + cons = btype->construction = calloc(1, sizeof(construction)); + cons->maxsize = 5; + cons = cons->improvement = calloc(1, sizeof(construction)); + cons->maxsize = -1; + return btype; } static void test_defenders_get_building_bonus(CuTest * tc) @@ -72,16 +81,13 @@ static void test_defenders_get_building_bonus(CuTest * tc) fighter *df, *af; battle *b; side *ds, *as; - int diff; troop dt, at; building_type * btype; - test_cleanup(); + test_setup(); + btype = setup_castle(); r = test_create_region(0, 0, 0); - btype = bt_get_or_create("castle"); - btype->protection = &add_two; bld = test_create_building(r, btype); - bld->size = 10; du = test_create_unit(test_create_faction(NULL), r); au = test_create_unit(test_create_faction(NULL), r); @@ -101,11 +107,14 @@ static void test_defenders_get_building_bonus(CuTest * tc) at.fighter = af; at.index = 0; - diff = skilldiff(at, dt, 0); - CuAssertIntEquals(tc, -2, diff); + bld->size = 10; /* stage 1 building */ + CuAssertIntEquals(tc, -1, skilldiff(at, dt, 0)); + CuAssertIntEquals(tc, 0, skilldiff(dt, at, 0)); + + bld->size = 1; /* stage 0 building */ + CuAssertIntEquals(tc, 0, skilldiff(at, dt, 0)); + CuAssertIntEquals(tc, 0, skilldiff(dt, at, 0)); - diff = skilldiff(dt, at, 0); - CuAssertIntEquals(tc, 0, diff); free_battle(b); test_cleanup(); } @@ -120,10 +129,10 @@ static void test_attackers_get_no_building_bonus(CuTest * tc) side *as; building_type * btype; - test_cleanup(); + test_setup(); r = test_create_region(0, 0, 0); - btype = bt_get_or_create("castle"); - btype->protection = &add_two; + btype = setup_castle(); + btype->flags |= BTF_FORTIFICATION; bld = test_create_building(r, btype); bld->size = 10; @@ -150,10 +159,10 @@ static void test_building_bonus_respects_size(CuTest * tc) building_type * btype; faction * f; - test_cleanup(); + test_setup(); + btype = setup_castle(); r = test_create_region(0, 0, 0); - btype = bt_get_or_create("castle"); - btype->protection = &add_two; + btype->flags |= BTF_FORTIFICATION; bld = test_create_building(r, btype); bld->size = 10; @@ -178,28 +187,25 @@ static void test_building_bonus_respects_size(CuTest * tc) static void test_building_defence_bonus(CuTest * tc) { - unit *au; - region *r; - building * bld; building_type * btype; - faction * f; - int def; - test_cleanup(); - r = test_create_region(0, 0, 0); - btype = test_create_buildingtype("castle"); - btype->protection = (int(*)(const struct building *, const struct unit *, building_bonus))get_function("building_protection"); - btype->construction->defense_bonus = 3; - bld = test_create_building(r, btype); - bld->size = 1; + test_setup(); + btype = setup_castle(); - f = test_create_faction(NULL); - au = test_create_unit(f, r); - scale_number(au, 1); - u_set_building(au, bld); + btype->maxsize = -1; /* unlimited buildigs get the castle bonus */ + CuAssertIntEquals(tc, 0, building_protection(btype, 0)); + CuAssertIntEquals(tc, 1, building_protection(btype, 1)); + CuAssertIntEquals(tc, 3, building_protection(btype, 2)); + CuAssertIntEquals(tc, 5, building_protection(btype, 3)); + CuAssertIntEquals(tc, 8, building_protection(btype, 4)); + CuAssertIntEquals(tc, 12, building_protection(btype, 5)); + CuAssertIntEquals(tc, 12, building_protection(btype, 6)); - def = btype->protection(bld, au, DEFENSE_BONUS); - CuAssertIntEquals(tc, 3, def); + btype->maxsize = 10; /* limited-size buildings are treated like an E3 watchtower */ + CuAssertIntEquals(tc, 0, building_protection(btype, 0)); + CuAssertIntEquals(tc, 1, building_protection(btype, 1)); + CuAssertIntEquals(tc, 2, building_protection(btype, 2)); + CuAssertIntEquals(tc, 2, building_protection(btype, 3)); test_cleanup(); } @@ -219,14 +225,17 @@ static void test_natural_armor(CuTest * tc) race *rc; unit *u; - test_cleanup(); + test_setup(); rc = test_create_race("human"); u = test_create_unit(test_create_faction(rc), test_create_region(0, 0, 0)); set_level(u, SK_STAMINA, 2); + CuAssertIntEquals(tc, 0, rc_armor_bonus(rc)); CuAssertIntEquals(tc, 0, natural_armor(u)); - set_param(&rc->parameters, "armor.stamina", "1"); + rc_set_param(rc, "armor.stamina", "1"); + CuAssertIntEquals(tc, 1, rc_armor_bonus(rc)); CuAssertIntEquals(tc, 2, natural_armor(u)); - set_param(&rc->parameters, "armor.stamina", "2"); + rc_set_param(rc, "armor.stamina", "2"); + CuAssertIntEquals(tc, 2, rc_armor_bonus(rc)); CuAssertIntEquals(tc, 1, natural_armor(u)); test_cleanup(); } @@ -241,23 +250,24 @@ static void test_calculate_armor(CuTest * tc) armor_type *ashield, *achain; item_type *ibelt, *ishield, *ichain; race *rc; - double magres = 0.0; + variant magres = frac_zero; + variant v50p = frac_make(1, 2); - test_cleanup(); + test_setup(); r = test_create_region(0, 0, 0); ibelt = it_get_or_create(rt_get_or_create("trollbelt")); ishield = it_get_or_create(rt_get_or_create("shield")); - ashield = new_armortype(ishield, 0.0, 0.5, 1, ATF_SHIELD); + ashield = new_armortype(ishield, 0.0, v50p, 1, ATF_SHIELD); ichain = it_get_or_create(rt_get_or_create("chainmail")); - achain = new_armortype(ichain, 0.0, 0.5, 3, ATF_NONE); - wtype = new_weapontype(it_get_or_create(rt_get_or_create("sword")), 0, 0.5, 0, 0, 0, 0, SK_MELEE, 1); + achain = new_armortype(ichain, 0.0, v50p, 3, ATF_NONE); + wtype = new_weapontype(it_get_or_create(rt_get_or_create("sword")), 0, v50p, 0, 0, 0, 0, SK_MELEE, 1); rc = test_create_race("human"); du = test_create_unit(test_create_faction(rc), r); dt.index = 0; dt.fighter = setup_fighter(&b, du); CuAssertIntEquals_Msg(tc, "default ac", 0, calculate_armor(dt, 0, 0, &magres)); - CuAssertDblEquals_Msg(tc, "magres unmodified", 1.0, magres, 0.01); + CuAssertIntEquals_Msg(tc, "magres unmodified", magres.sa[0], magres.sa[1]); free_battle(b); b = NULL; @@ -290,13 +300,13 @@ static void test_calculate_armor(CuTest * tc) wtype->flags = WTF_NONE; CuAssertIntEquals_Msg(tc, "magical attack", 3, calculate_armor(dt, 0, 0, &magres)); - CuAssertDblEquals_Msg(tc, "magres unmodified", 1.0, magres, 0.01); + CuAssertIntEquals_Msg(tc, "magres unmodified", magres.sa[1], magres.sa[0]); ashield->flags |= ATF_LAEN; achain->flags |= ATF_LAEN; - magres = 1.0; + magres = frac_one; CuAssertIntEquals_Msg(tc, "laen armor", 3, calculate_armor(dt, 0, 0, &magres)); - CuAssertDblEquals_Msg(tc, "laen magres bonus", 0.25, magres, 0.01); + CuAssertIntEquals_Msg(tc, "laen magres bonus", 4, magres.sa[1]); free_battle(b); test_cleanup(); } @@ -310,38 +320,42 @@ static void test_magic_resistance(CuTest *tc) armor_type *ashield, *achain; item_type *ishield, *ichain; race *rc; - double magres; + variant magres; + variant v50p = frac_make(1, 2); + variant v10p = frac_make(1, 10); - test_cleanup(); + test_setup(); r = test_create_region(0, 0, 0); ishield = it_get_or_create(rt_get_or_create("shield")); - ashield = new_armortype(ishield, 0.0, 0.5, 1, ATF_SHIELD); + ashield = new_armortype(ishield, 0.0, v50p, 1, ATF_SHIELD); ichain = it_get_or_create(rt_get_or_create("chainmail")); - achain = new_armortype(ichain, 0.0, 0.5, 3, ATF_NONE); + achain = new_armortype(ichain, 0.0, v50p, 3, ATF_NONE); rc = test_create_race("human"); du = test_create_unit(test_create_faction(rc), r); dt.index = 0; + i_change(&du->items, ishield, 1); dt.fighter = setup_fighter(&b, du); calculate_armor(dt, 0, 0, &magres); - CuAssertDblEquals_Msg(tc, "no magres bonus", 0.0, magic_resistance(du), 0.01); - CuAssertDblEquals_Msg(tc, "no magres reduction", 1.0, magres, 0.01); + CuAssertIntEquals_Msg(tc, "no magres reduction", magres.sa[1], magres.sa[0]); + magres = magic_resistance(du); + CuAssertIntEquals_Msg(tc, "no magres reduction", 0, magres.sa[0]); ashield->flags |= ATF_LAEN; - ashield->magres = 0.1; + ashield->magres = v10p; calculate_armor(dt, 0, 0, &magres); + CuAssert(tc, "laen reduction => 10%%", frac_equal(frac_make(9, 10), magres)); free_battle(b); b = NULL; - i_change(&du->items, ishield, 1); i_change(&du->items, ichain, 1); achain->flags |= ATF_LAEN; - achain->magres = 0.1; + achain->magres = v10p; ashield->flags |= ATF_LAEN; - ashield->magres = 0.1; + ashield->magres = v10p; dt.fighter = setup_fighter(&b, du); calculate_armor(dt, 0, 0, &magres); - CuAssertDblEquals_Msg(tc, "laen reduction", 0.81, magres, 0.01); + CuAssert(tc, "2x laen reduction => 81%%", frac_equal(frac_make(81, 100), magres)); free_battle(b); b = NULL; @@ -350,17 +364,20 @@ static void test_magic_resistance(CuTest *tc) set_level(du, SK_MAGIC, 2); dt.fighter = setup_fighter(&b, du); calculate_armor(dt, 0, 0, &magres); - CuAssertDblEquals_Msg(tc, "skill bonus", 0.1, magic_resistance(du), 0.01); - CuAssertDblEquals_Msg(tc, "skill reduction", 0.9, magres, 0.01); - rc->magres = 0.5; /* gets added to skill bonus */ + CuAssert(tc, "skill reduction => 90%%", frac_equal(magres, frac_make(9, 10))); + magres = magic_resistance(du); + CuAssert(tc, "skill reduction", frac_equal(magres, v10p)); + rc->magres = v50p; /* percentage, gets added to skill bonus */ calculate_armor(dt, 0, 0, &magres); - CuAssertDblEquals_Msg(tc, "race bonus", 0.6, magic_resistance(du), 0.01); - CuAssertDblEquals_Msg(tc, "race reduction", 0.4, magres, 0.01); + CuAssert(tc, "race reduction => 40%%", frac_equal(magres, frac_make(4, 10))); + magres = magic_resistance(du); + CuAssert(tc, "race bonus => 60%%", frac_equal(magres, frac_make(60, 100))); - rc->magres = 1.5; /* should not cause negative damage multiplier */ - CuAssertDblEquals_Msg(tc, "magic resistance is never > 0.9", 0.9, magic_resistance(du), 0.01); + rc->magres = frac_make(15, 10); /* 150% resistance should not cause negative damage multiplier */ + magres = magic_resistance(du); + CuAssert(tc, "magic resistance is never > 0.9", frac_equal(magres, frac_make(9, 10))); calculate_armor(dt, 0, 0, &magres); - CuAssertDblEquals_Msg(tc, "damage reduction is never < 0.1", 0.1, magres, 0.01); + CuAssert(tc, "damage reduction is never < 0.1", frac_equal(magres, frac_make(1, 10))); free_battle(b); test_cleanup(); @@ -376,14 +393,15 @@ static void test_projectile_armor(CuTest * tc) armor_type *ashield, *achain; item_type *ishield, *ichain; race *rc; + variant v50p = frac_make(1, 2); - test_cleanup(); + test_setup(); r = test_create_region(0, 0, 0); ishield = it_get_or_create(rt_get_or_create("shield")); - ashield = new_armortype(ishield, 0.0, 0.5, 1, ATF_SHIELD); + ashield = new_armortype(ishield, 0.0, v50p, 1, ATF_SHIELD); ichain = it_get_or_create(rt_get_or_create("chainmail")); - achain = new_armortype(ichain, 0.0, 0.5, 3, ATF_NONE); - wtype = new_weapontype(it_get_or_create(rt_get_or_create("sword")), 0, 0.5, 0, 0, 0, 0, SK_MELEE, 1); + achain = new_armortype(ichain, 0.0, v50p, 3, ATF_NONE); + wtype = new_weapontype(it_get_or_create(rt_get_or_create("sword")), 0, v50p, 0, 0, 0, 0, SK_MELEE, 1); rc = test_create_race("human"); rc->battle_flags |= BF_EQUIPMENT; du = test_create_unit(test_create_faction(rc), r); @@ -411,7 +429,7 @@ static void test_battle_skilldiff(CuTest *tc) unit *ua, *ud; battle *b = NULL; - test_cleanup(); + test_setup(); r = test_create_region(0, 0, 0); ud = test_create_unit(test_create_faction(0), r); @@ -430,18 +448,14 @@ static void test_battle_skilldiff(CuTest *tc) td.fighter->person[0].flags |= FL_SLEEPING; CuAssertIntEquals(tc, 3, skilldiff(ta, td, 0)); - // TODO: unarmed halfling vs. dragon: +5 - // TODO: rule_goblin_bonus - // TODO: weapon modifiers, missiles, skill_formula + /* TODO: unarmed halfling vs. dragon: +5 */ + /* TODO: rule_goblin_bonus */ + /* TODO: weapon modifiers, missiles, skill_formula */ free_battle(b); test_cleanup(); } -static int protect(const building *b, const unit *u, building_bonus bonus) { - return (bonus == DEFENSE_BONUS) ? 4 : 0; -} - static void test_battle_skilldiff_building(CuTest *tc) { troop ta, td; @@ -451,8 +465,8 @@ static void test_battle_skilldiff_building(CuTest *tc) building_type *btype; const curse_type *strongwall_ct, *magicwalls_ct; - test_cleanup(); - btype = test_create_buildingtype("castle"); + test_setup(); + btype = setup_castle(); strongwall_ct = ct_find("strongwall"); magicwalls_ct = ct_find("magicwalls"); @@ -467,14 +481,14 @@ static void test_battle_skilldiff_building(CuTest *tc) ua = test_create_unit(test_create_faction(0), r); CuAssertIntEquals(tc, 0, skilldiff(ta, td, 0)); - btype->protection = protect; - CuAssertIntEquals(tc, -4, skilldiff(ta, td, 0)); + ud->building->size = 10; + CuAssertIntEquals(tc, -1, skilldiff(ta, td, 0)); create_curse(NULL, &ud->building->attribs, magicwalls_ct, 1, 1, 1, 1); - CuAssertIntEquals(tc, -8, skilldiff(ta, td, 0)); + CuAssertIntEquals(tc, -2, skilldiff(ta, td, 0)); create_curse(NULL, &ud->building->attribs, strongwall_ct, 1, 1, 2, 1); - CuAssertIntEquals(tc, -10, skilldiff(ta, td, 0)); + CuAssertIntEquals(tc, -4, skilldiff(ta, td, 0)); free_battle(b); test_cleanup(); diff --git a/src/bind_building.c b/src/bind_building.c index 3724d4db5..ea689bfb5 100644 --- a/src/bind_building.c +++ b/src/bind_building.c @@ -13,7 +13,6 @@ without prior permission by the authors of Eressea. #include #include "bind_building.h" #include "bind_unit.h" -#include "bind_dict.h" #include #include @@ -41,13 +40,6 @@ int tolua_buildinglist_next(lua_State * L) return 0; /* no more values to return */ } -static int tolua_building_get_objects(lua_State * L) -{ - building *self = (building *)tolua_tousertype(L, 1, 0); - tolua_pushusertype(L, (void *)&self->attribs, USERTYPE_DICT); - return 1; -} - static int tolua_building_set_working(lua_State * L) { building *self = (building *)tolua_tousertype(L, 1, 0); @@ -92,7 +84,7 @@ static int tolua_building_set_info(lua_State * L) const char *info = tolua_tostring(L, 2, 0); free(self->display); if (info) - self->display = _strdup(info); + self->display = strdup(info); else self->display = NULL; return 0; @@ -258,7 +250,6 @@ void tolua_building_open(lua_State * L) tolua_variable(L, TOLUA_CAST "size", tolua_building_get_size, tolua_building_set_size); tolua_function(L, TOLUA_CAST "get_typename", tolua_building_get_typename); - tolua_variable(L, TOLUA_CAST "objects", tolua_building_get_objects, 0); tolua_variable(L, TOLUA_CAST "working", tolua_building_get_working, tolua_building_set_working); } diff --git a/src/bind_config.c b/src/bind_config.c index 3959cc22c..b4aa68d58 100644 --- a/src/bind_config.c +++ b/src/bind_config.c @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include #include #include @@ -18,8 +20,8 @@ #include "kernel/terrain.h" void config_reset(void) { - default_locale = 0; - free_locales(); + free_config(); + free_nrmesssages(); free_spells(); free_buildingtypes(); free_shiptypes(); @@ -33,7 +35,6 @@ int config_parse(const char *json) if (conf) { json_config(conf); cJSON_Delete(conf); - init_locales(); return 0; } else { @@ -45,7 +46,7 @@ int config_parse(const char *json) if (xp >= ep) break; } xp = (ep > json + 10) ? ep - 10 : json; - strncpy(buffer, xp, sizeof(buffer)); + strlcpy(buffer, xp, sizeof(buffer)); buffer[9] = 0; log_error("json parse error in line %d, position %d, near `%s`\n", line, ep - lp, buffer); } diff --git a/src/bind_dict.c b/src/bind_dict.c deleted file mode 100644 index 32d3c498d..000000000 --- a/src/bind_dict.c +++ /dev/null @@ -1,185 +0,0 @@ -/* -+-------------------+ -| | Enno Rehling -| Eressea PBEM host | Christian Schlittchen -| (c) 1998 - 2008 | Katja Zedel -| | Henning Peters -+-------------------+ - -This program may not be used, modified or distributed -without prior permission by the authors of Eressea. -*/ - -#include -#include "bind_dict.h" - -#include -#include -#include -#include - -#include - -#include -#include - -#include -#include - -#include -#include - -static int tolua_dict_get(lua_State * L) -{ - dict self = (dict)tolua_tousertype(L, 1, 0); - const char *name = tolua_tostring(L, 2, 0); - attrib *a = a_find(*self, &at_dict); - - for (; a && a->type == &at_dict; a = a->next) { - const char *obj_name = dict_name(a); - if (obj_name && name && strcmp(obj_name, name) == 0) { - variant val; - dict_type type; - - dict_get(a, &type, &val); - switch (type) { - case TNONE: - lua_pushnil(L); - break; - case TINTEGER: - lua_pushinteger(L, val.i); - break; - case TREAL: - lua_pushnumber(L, (lua_Number)val.f); - break; - case TREGION: - tolua_pushusertype(L, val.v, TOLUA_CAST "region"); - break; - case TBUILDING: - tolua_pushusertype(L, val.v, TOLUA_CAST "building"); - break; - case TUNIT: - tolua_pushusertype(L, val.v, TOLUA_CAST "unit"); - break; - case TSHIP: - tolua_pushusertype(L, val.v, TOLUA_CAST "ship"); - break; - case TSTRING: - tolua_pushstring(L, (const char *)val.v); - break; - default: - assert(!"not implemented"); - } - return 1; - } - } - lua_pushnil(L); - return 1; -} - -static int tolua_dict_set_number(lua_State * L) -{ - dict self = (dict)tolua_tousertype(L, 1, 0); - const char *name = tolua_tostring(L, 2, 0); - lua_Number value = tolua_tonumber(L, 3, 0); - attrib *a = a_find(*self, &at_dict); - variant val; - - val.f = (float)value; - - for (; a && a->type == &at_dict; a = a->next) { - if (strcmp(dict_name(a), name) == 0) { - dict_set(a, TREAL, val); - return 0; - } - } - - a = a_add(self, dict_create(name, TREAL, val)); - return 0; -} - -static int tolua_dict_set_string(lua_State * L) -{ - dict self = (dict)tolua_tousertype(L, 1, 0); - const char *name = tolua_tostring(L, 2, 0); - const char *value = tolua_tostring(L, 3, 0); - attrib *a = a_find(*self, &at_dict); - variant val; - - val.v = _strdup(value); - - for (; a && a->type == &at_dict; a = a->next) { - if (strcmp(dict_name(a), name) == 0) { - dict_set(a, TSTRING, val); - return 0; - } - } - - a = a_add(self, dict_create(name, TSTRING, val)); - return 0; -} - -static int tolua_dict_set_usertype(lua_State * L, int type) -{ - dict self = (dict)tolua_tousertype(L, 1, 0); - const char *name = tolua_tostring(L, 2, 0); - unit *value = tolua_tousertype(L, 3, 0); - attrib *a = a_find(*self, &at_dict); - variant val; - - val.v = value; - - for (; a && a->type == &at_dict; a = a->next) { - if (strcmp(dict_name(a), name) == 0) { - dict_set(a, type, val); - return 0; - } - } - - a = a_add(self, dict_create(name, type, val)); - return 0; -} - -static int tolua_dict_set(lua_State * L) -{ - tolua_Error tolua_err; - if (tolua_isnumber(L, 3, 0, &tolua_err)) { - return tolua_dict_set_number(L); - } - else if (tolua_isusertype(L, 3, TOLUA_CAST "unit", 0, &tolua_err)) { - return tolua_dict_set_usertype(L, TUNIT); - } - else if (tolua_isusertype(L, 3, TOLUA_CAST "faction", 0, &tolua_err)) { - return tolua_dict_set_usertype(L, TFACTION); - } - else if (tolua_isusertype(L, 3, TOLUA_CAST "ship", 0, &tolua_err)) { - return tolua_dict_set_usertype(L, TSHIP); - } - else if (tolua_isusertype(L, 3, TOLUA_CAST "building", 0, &tolua_err)) { - return tolua_dict_set_usertype(L, TBUILDING); - } - else if (tolua_isusertype(L, 3, TOLUA_CAST "region", 0, &tolua_err)) { - return tolua_dict_set_usertype(L, TREGION); - } - return tolua_dict_set_string(L); -} - -void tolua_dict_open(lua_State * L) -{ - /* register user types */ - tolua_usertype(L, USERTYPE_DICT); - - tolua_module(L, NULL, 0); - tolua_beginmodule(L, NULL); - { - tolua_cclass(L, USERTYPE_DICT, USERTYPE_DICT, - TOLUA_CAST "", NULL); - tolua_beginmodule(L, USERTYPE_DICT); - { - tolua_function(L, TOLUA_CAST "get", tolua_dict_get); - tolua_function(L, TOLUA_CAST "set", tolua_dict_set); - } - tolua_endmodule(L); - } - tolua_endmodule(L); -} diff --git a/src/bind_dict.h b/src/bind_dict.h deleted file mode 100644 index 83ca1efbf..000000000 --- a/src/bind_dict.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -+-------------------+ -| | Enno Rehling -| Eressea PBEM host | Christian Schlittchen -| (c) 1998 - 2008 | Katja Zedel -| | Henning Peters -+-------------------+ - -This program may not be used, modified or distributed -without prior permission by the authors of Eressea. -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#define USERTYPE_DICT ((char *)"dict") - - struct lua_State; - void tolua_dict_open(struct lua_State *L); - - typedef struct attrib **dict; - -#ifdef __cplusplus -} -#endif diff --git a/src/bind_eressea.c b/src/bind_eressea.c index d7683ec18..de8751306 100755 --- a/src/bind_eressea.c +++ b/src/bind_eressea.c @@ -9,6 +9,8 @@ #include #include +#include + #include #include @@ -16,10 +18,11 @@ void eressea_free_game(void) { free_gamedata(); init_resources(); + init_locales(); } int eressea_read_game(const char * filename) { - return readgame(filename, false); + return readgame(filename); } int eressea_write_game(const char * filename) { diff --git a/src/bind_faction.c b/src/bind_faction.c index a4302f3c9..518ccccac 100644 --- a/src/bind_faction.c +++ b/src/bind_faction.c @@ -13,13 +13,11 @@ without prior permission by the authors of Eressea. #include #include "bind_faction.h" #include "bind_unit.h" -#include "bind_dict.h" #include "bindings.h" #include "helpers.h" #include #include -#include #include #include #include @@ -28,15 +26,33 @@ without prior permission by the authors of Eressea. #include #include #include +#include +#include #include #include #include -#include - #include #include +#include + +typedef struct helpmode { + const char *name; + int status; +} helpmode; + +static helpmode helpmodes[] = { + { "all", HELP_ALL }, + { "money", HELP_MONEY }, + { "fight", HELP_FIGHT }, + { "observe", HELP_OBSERVE }, + { "give", HELP_GIVE }, + { "guard", HELP_GUARD }, + { "stealth", HELP_FSTEALTH }, + { "travel", HELP_TRAVEL }, + { NULL, 0 } +}; int tolua_factionlist_next(lua_State * L) { @@ -226,6 +242,32 @@ static int tolua_faction_addnotice(lua_State * L) return 0; } +static int tolua_faction_getkey(lua_State * L) +{ + faction *self = (faction *)tolua_tousertype(L, 1, 0); + const char *name = tolua_tostring(L, 2, 0); + int flag = atoi36(name); + + lua_pushinteger(L, key_get(self->attribs, flag)); + return 1; +} + +static int tolua_faction_setkey(lua_State * L) +{ + faction *self = (faction *)tolua_tousertype(L, 1, 0); + const char *name = tolua_tostring(L, 2, 0); + int value = (int)tolua_tonumber(L, 3, 0); + int flag = atoi36(name); + + if (value) { + key_set(&self->attribs, flag, value); + } + else { + key_unset(&self->attribs, flag); + } + return 0; +} + static int tolua_faction_count_msg_type(lua_State *L) { faction *self = (faction *)tolua_tousertype(L, 1, 0); const char *str = tolua_tostring(L, 2, 0); @@ -243,13 +285,6 @@ static int tolua_faction_count_msg_type(lua_State *L) { return 1; } -static int tolua_faction_get_objects(lua_State * L) -{ - faction *self = (faction *)tolua_tousertype(L, 1, 0); - tolua_pushusertype(L, (void *)&self->attribs, USERTYPE_DICT); - return 1; -} - static int tolua_faction_get_policy(lua_State * L) { faction *self = (faction *)tolua_tousertype(L, 1, 0); @@ -346,7 +381,7 @@ static int tolua_faction_get_origin(lua_State * L) static int tolua_faction_destroy(lua_State * L) { faction **fp, *f = (faction *)tolua_tousertype(L, 1, 0); - // TODO: this loop is slow af, but what can we do? + /* TODO: this loop is slow af, but what can we do? */ for (fp = &factions; *fp; fp = &(*fp)->next) { if (*fp == f) { destroyfaction(fp); @@ -376,7 +411,7 @@ static int tolua_faction_create(lua_State * L) f = addfaction(email, NULL, frace, loc, 0); } if (!f) { - log_error("faction.create(%s, %s, %s)\n", email, racename, locale_name(loc)); + log_error("cannot create %s faction for %s, unknown race.", racename, email); } tolua_pushusertype(L, f, TOLUA_CAST "faction"); return 1; @@ -603,8 +638,8 @@ void tolua_faction_open(lua_State * L) /* tech debt hack, siehe https://paper.dropbox.com/doc/Weihnachten-2015-5tOx5r1xsgGDBpb0gILrv#:h=Probleme-mit-Tests-(Nachtrag-0 */ tolua_function(L, TOLUA_CAST "count_msg_type", tolua_faction_count_msg_type); - tolua_variable(L, TOLUA_CAST "objects", tolua_faction_get_objects, - NULL); + tolua_function(L, TOLUA_CAST "get_key", tolua_faction_getkey); + tolua_function(L, TOLUA_CAST "set_key", tolua_faction_setkey); } tolua_endmodule(L); } diff --git a/src/bind_gmtool.c b/src/bind_gmtool.c index 3c07bb3b7..e4ae939f9 100644 --- a/src/bind_gmtool.c +++ b/src/bind_gmtool.c @@ -133,14 +133,14 @@ static int tolua_selected_regions(lua_State * L) static int tolua_state_open(lua_State * L) { - unused_arg(L); + UNUSED_ARG(L); state_open(); return 0; } static int tolua_state_close(lua_State * L) { - unused_arg(L); + UNUSED_ARG(L); state_close(current_state); return 0; } @@ -188,7 +188,7 @@ static void lua_paint_info(struct window *wnd, const struct state *st) break; else { size_t len = end - str; - int bytes = _min((int)len, size); + int bytes = MIN((int)len, size); mvwaddnstr(win, line++, 1, str, bytes); wclrtoeol(win); str = end + 1; diff --git a/src/bind_log.c b/src/bind_log.c deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/bind_log.h b/src/bind_log.h deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/bind_message.c b/src/bind_message.c index 15673f4f6..a3ab95d39 100644 --- a/src/bind_message.c +++ b/src/bind_message.c @@ -1,6 +1,4 @@ #include -#include - #include "spells.h" /* kernel includes */ diff --git a/src/bind_monsters.c b/src/bind_monsters.c index 271045491..4ac15aa24 100644 --- a/src/bind_monsters.c +++ b/src/bind_monsters.c @@ -1,6 +1,5 @@ #include #include "spells/shipcurse.h" -#include "monster.h" #include "monsters.h" #include @@ -12,8 +11,6 @@ #include -#include - #include #include @@ -47,40 +44,18 @@ static int tolua_spawn_dragons(lua_State * L) return 0; } +static int tolua_get_monsters(lua_State * L) +{ + tolua_pushusertype(L, get_monsters(), "faction"); + return 1; +} + static int tolua_spawn_undead(lua_State * L) { spawn_undead(); return 0; } -static int fix_familiars(struct lua_State *L) -{ - faction *f; - for (f = factions; f; f = f->next) { - unit *u; - for (u = f->units; u; u = u->nextF) { - struct sc_mage *mage = get_mage(u); - if (mage && is_familiar(u)) { - if (mage->spellbook && mage->magietyp == M_GRAY) { - equipment *eq; - char buffer[64]; - - spellbook_clear(mage->spellbook); - free(mage->spellbook); - mage->spellbook = 0; - - _snprintf(buffer, sizeof(buffer), "%s_familiar", u_race(u)->_name); - eq = get_equipment(buffer); - if (eq) { - equip_unit_mask(u, eq, EQUIP_SPELLS); - } - } - } - } - } - return 0; -} - void bind_monsters(struct lua_State *L) { tolua_module(L, NULL, 0); @@ -90,7 +65,7 @@ void bind_monsters(struct lua_State *L) tolua_function(L, TOLUA_CAST "plan_monsters", tolua_planmonsters); tolua_function(L, TOLUA_CAST "spawn_undead", tolua_spawn_undead); tolua_function(L, TOLUA_CAST "spawn_dragons", tolua_spawn_dragons); - tolua_function(L, TOLUA_CAST "fix_familiars", &fix_familiars); + tolua_function(L, TOLUA_CAST "get_monsters", tolua_get_monsters); } tolua_endmodule(L); } diff --git a/src/bind_order.c b/src/bind_order.c index 90fc7d3b0..84399deec 100644 --- a/src/bind_order.c +++ b/src/bind_order.c @@ -1,5 +1,4 @@ #include -#include /* kernel includes */ #include diff --git a/src/bind_process.c b/src/bind_process.c index e8420c654..2b44eb19d 100755 --- a/src/bind_process.c +++ b/src/bind_process.c @@ -182,11 +182,6 @@ void process_promote(void) { process_cmd(K_PROMOTION, promotion_cmd, 0); } -void process_renumber(void) { - process_cmd(K_NUMBER, renumber_cmd, 0); - renumber_factions(); -} - void process_restack(void) { restack_units(); } diff --git a/src/bind_region.c b/src/bind_region.c index e56c3443c..fdab4a10f 100644 --- a/src/bind_region.c +++ b/src/bind_region.c @@ -14,12 +14,12 @@ without prior permission by the authors of Eressea. #include "bind_region.h" #include "bind_unit.h" #include "bind_ship.h" -#include "bind_dict.h" #include "bind_building.h" #include "chaos.h" #include +#include #include #include #include @@ -30,22 +30,41 @@ without prior permission by the authors of Eressea. #include #include #include +#include #include #include #include #include #include -#include #include #include +#include + #include #include #include #include +static int tolua_region_count_msg_type(lua_State *L) { + region *self = (region *)tolua_tousertype(L, 1, 0); + const char *str = tolua_tostring(L, 2, 0); + int n = 0; + if (self->msgs) { + mlist * ml = self->msgs->begin; + while (ml) { + if (strcmp(str, ml->msg->type->name) == 0) { + ++n; + } + ml = ml->next; + } + } + lua_pushinteger(L, n); + return 1; +} + int tolua_regionlist_next(lua_State * L) { region **region_ptr = (region **)lua_touserdata(L, lua_upvalueindex(1)); @@ -341,20 +360,16 @@ static int tolua_region_get_resourcelevel(lua_State * L) #define LUA_ASSERT(c, s) if (!(c)) { log_error("%s(%d): %s\n", __FILE__, __LINE__, (s)); return 0; } -static critbit_tree * special_resources(void) -{ - static critbit_tree cb = CRITBIT_TREE(); - if (!cb.root) { - const char * special[] = { "seed", "sapling", "tree", "grave", "chaos", 0 }; - char buffer[32]; - int i; - for (i = 0; special[i]; ++i) { - size_t len = strlen(special[i]); - len = cb_new_kv(special[i], len, &i, sizeof(int), buffer); - cb_insert(&cb, buffer, len); +static int special_resource(const char *type) { + const char * special[] = { "seed", "sapling", "tree", "grave", "chaos", 0 }; + int i; + + for (i = 0; special[i]; ++i) { + if (strcmp(type, special[i]) == 0) { + return i; } } - return &cb; + return -1; } static int tolua_region_get_resource(lua_State * L) @@ -362,32 +377,27 @@ static int tolua_region_get_resource(lua_State * L) region *r; const char *type; const resource_type *rtype; - int result = 0; - void * match; - critbit_tree * cb = special_resources(); + int result; r = (region *)tolua_tousertype(L, 1, 0); LUA_ASSERT(r != NULL, "invalid parameter"); type = tolua_tostring(L, 2, 0); LUA_ASSERT(type != NULL, "invalid parameter"); - - if (cb_find_prefix(cb, type, strlen(type) + 1, &match, 1, 0)) { - cb_get_kv(match, &result, sizeof(result)); - switch (result) { - case 0: - case 1: - case 2: - result = rtrees(r, result); - break; - case 3: - result = deathcount(r); - break; - case 4: - result = get_chaoscount(r); - break; - } - } - else { + + result = special_resource(type); + switch (result) { + case 0: + case 1: + case 2: + result = rtrees(r, result); + break; + case 3: + result = deathcount(r); + break; + case 4: + result = get_chaoscount(r); + break; + default: rtype = rt_find(type); if (rtype) { result = region_getresource(r, rtype); @@ -406,27 +416,23 @@ static int tolua_region_set_resource(lua_State * L) region *r = (region *)tolua_tousertype(L, 1, 0); const char *type = tolua_tostring(L, 2, 0); int result, value = (int)tolua_tonumber(L, 3, 0); - critbit_tree * cb = special_resources(); - void * match; + const resource_type *rtype; - if (cb_find_prefix(cb, type, strlen(type) + 1, &match, 1, 0)) { - cb_get_kv(match, &result, sizeof(result)); - switch (result) { - case 0: - case 1: - case 2: - rsettrees(r, result, value); - break; - case 3: - deathcounts(r, value - deathcount(r)); - break; - case 4: - add_chaoscount(r, value - get_chaoscount(r)); - break; - } - } - else { - const resource_type *rtype = rt_find(type); + result = special_resource(type); + switch (result) { + case 0: + case 1: + case 2: + rsettrees(r, result, value); + break; + case 3: + deathcounts(r, value - deathcount(r)); + break; + case 4: + add_chaoscount(r, value - get_chaoscount(r)); + break; + default: + rtype = rt_find(type); if (rtype != NULL) { region_setresource(r, rtype, value); } @@ -434,13 +440,6 @@ static int tolua_region_set_resource(lua_State * L) return 0; } -static int tolua_region_get_objects(lua_State * L) -{ - region *self = (region *)tolua_tousertype(L, 1, 0); - tolua_pushusertype(L, (void *)&self->attribs, USERTYPE_DICT); - return 1; -} - static int tolua_region_destroy(lua_State * L) { region *self = (region *)tolua_tousertype(L, 1, 0); @@ -474,9 +473,6 @@ static int tolua_region_create(lua_State * L) } if (result) { terraform_region(result, terrain); - if (result->land) { - fix_demand(result); - } } tolua_pushusertype(L, result, TOLUA_CAST "region"); @@ -554,11 +550,11 @@ static int tolua_region_setkey(lua_State * L) { region *self = (region *)tolua_tousertype(L, 1, 0); const char *name = tolua_tostring(L, 2, 0); - int value = tolua_toboolean(L, 3, 0); + int value = (int)tolua_tonumber(L, 3, 0); int flag = atoi36(name); if (value) { - key_set(&self->attribs, flag); + key_set(&self->attribs, flag, value); } else { key_unset(&self->attribs, flag); @@ -618,7 +614,7 @@ static int tolua_plane_set_name(lua_State * L) const char *str = tolua_tostring(L, 2, 0); free(self->name); if (str) - self->name = _strdup(str); + self->name = strdup(str); else self->name = 0; return 0; @@ -675,6 +671,27 @@ static int tolua_distance(lua_State * L) return 1; } +static int tolua_region_get_curse(lua_State *L) { + region *self = (region *)tolua_tousertype(L, 1, 0); + const char *name = tolua_tostring(L, 2, 0); + if (self->attribs) { + curse * c = get_curse(self->attribs, ct_find(name)); + if (c) { + lua_pushnumber(L, curse_geteffect(c)); + return 1; + } + } + return 0; +} + +static int tolua_region_has_attrib(lua_State *L) { + region *self = (region *)tolua_tousertype(L, 1, 0); + const char *name = tolua_tostring(L, 2, 0); + attrib * a = a_find(self->attribs, at_find(name)); + lua_pushboolean(L, a != NULL); + return 1; +} + void tolua_region_open(lua_State * L) { /* register user types */ @@ -694,6 +711,10 @@ void tolua_region_open(lua_State * L) tolua_function(L, TOLUA_CAST "destroy", tolua_region_destroy); tolua_function(L, TOLUA_CAST "__tostring", tolua_region_tostring); + tolua_function(L, TOLUA_CAST "count_msg_type", tolua_region_count_msg_type); + + tolua_function(L, TOLUA_CAST "get_curse", &tolua_region_get_curse); + tolua_function(L, TOLUA_CAST "has_attrib", &tolua_region_has_attrib); /* flags */ tolua_variable(L, TOLUA_CAST "blocked", tolua_region_get_blocked, tolua_region_set_blocked); @@ -736,8 +757,6 @@ void tolua_region_open(lua_State * L) tolua_function(L, TOLUA_CAST "get_key", tolua_region_getkey); tolua_function(L, TOLUA_CAST "set_key", tolua_region_setkey); - - tolua_variable(L, TOLUA_CAST "objects", tolua_region_get_objects, 0); } tolua_endmodule(L); diff --git a/src/bind_ship.c b/src/bind_ship.c index f1c1c412a..c5e0735ed 100644 --- a/src/bind_ship.c +++ b/src/bind_ship.c @@ -13,15 +13,16 @@ without prior permission by the authors of Eressea. #include #include "bind_ship.h" #include "bind_unit.h" -#include "bind_dict.h" #include "move.h" +#include #include #include #include #include +#include #include #include @@ -94,7 +95,7 @@ static int tolua_ship_set_display(lua_State * L) { ship *self = (ship *)tolua_tousertype(L, 1, 0); free(self->display); - self->display = _strdup(tolua_tostring(L, 2, 0)); + self->display = strdup(tolua_tostring(L, 2, 0)); return 0; } @@ -115,13 +116,6 @@ static int tolua_ship_get_units(lua_State * L) return 1; } -static int tolua_ship_get_objects(lua_State * L) -{ - ship *self = (ship *)tolua_tousertype(L, 1, 0); - tolua_pushusertype(L, (void *)&self->attribs, USERTYPE_DICT); - return 1; -} - static int tolua_ship_create(lua_State * L) { region *r = (region *)tolua_tousertype(L, 1, 0); @@ -206,6 +200,27 @@ static int tolua_ship_set_damage(lua_State * L) return 0; } +static int tolua_ship_get_curse(lua_State *L) { + ship *self = (ship *)tolua_tousertype(L, 1, 0); + const char *name = tolua_tostring(L, 2, 0); + if (self->attribs) { + curse * c = get_curse(self->attribs, ct_find(name)); + if (c) { + lua_pushnumber(L, curse_geteffect(c)); + return 1; + } + } + return 0; +} + +static int tolua_ship_has_attrib(lua_State *L) { + ship *self = (ship *)tolua_tousertype(L, 1, 0); + const char *name = tolua_tostring(L, 2, 0); + attrib * a = a_find(self->attribs, at_find(name)); + lua_pushboolean(L, a != NULL); + return 1; +} + void tolua_ship_open(lua_State * L) { /* register user types */ @@ -233,7 +248,9 @@ void tolua_ship_open(lua_State * L) tolua_variable(L, TOLUA_CAST "type", tolua_ship_get_type, 0); tolua_variable(L, TOLUA_CAST "damage", tolua_ship_get_damage, tolua_ship_set_damage); - tolua_variable(L, TOLUA_CAST "objects", tolua_ship_get_objects, 0); + + tolua_function(L, TOLUA_CAST "get_curse", &tolua_ship_get_curse); + tolua_function(L, TOLUA_CAST "has_attrib", &tolua_ship_has_attrib); tolua_function(L, TOLUA_CAST "create", tolua_ship_create); } diff --git a/src/bind_storage.c b/src/bind_storage.c index 489255d3f..68ac36179 100644 --- a/src/bind_storage.c +++ b/src/bind_storage.c @@ -11,7 +11,6 @@ without prior permission by the authors of Eressea. */ #include -#include #include "bind_storage.h" #include @@ -101,7 +100,10 @@ static int tolua_storage_tostring(lua_State * L) { gamedata *data = (gamedata *)tolua_tousertype(L, 1, 0); char name[64]; - _snprintf(name, sizeof(name), "", (void *)data, data->version); + /* safe to use sprintf here, because: + * %p is at most 16 characters, %d 20, text is 16, + * comes to 53 with \0 */ + sprintf(name, "", (void *)data, data->version); lua_pushstring(L, name); return 1; } diff --git a/src/bind_unit.c b/src/bind_unit.c index 3f3848e78..8247e13d5 100755 --- a/src/bind_unit.c +++ b/src/bind_unit.c @@ -13,7 +13,6 @@ without prior permission by the authors of Eressea. #include #include "bind_unit.h" -#include "bind_dict.h" #include "alchemy.h" #include "bindings.h" #include "move.h" @@ -27,6 +26,7 @@ without prior permission by the authors of Eressea. /* kernel includes */ #include #include +#include #include #include #include @@ -46,7 +46,7 @@ without prior permission by the authors of Eressea. #include #include #include -#include +#include #include @@ -67,12 +67,6 @@ static int tolua_bufunit(lua_State * L) { return 1; } -static int tolua_unit_get_objects(lua_State * L) -{ - unit *self = (unit *)tolua_tousertype(L, 1, 0); - tolua_pushusertype(L, (void *)&self->attribs, USERTYPE_DICT); - return 1; -} int tolua_unitlist_nextf(lua_State * L) { @@ -258,18 +252,15 @@ static int tolua_unit_set_flags(lua_State * L) static int tolua_unit_get_guard(lua_State * L) { unit *self = (unit *)tolua_tousertype(L, 1, 0); - if (is_guard(self, GUARD_ALL)) { - lua_pushinteger(L, getguard(self)); - return 1; - } - return 0; + lua_pushboolean(L, is_guard(self)); + return 1; } static int tolua_unit_set_guard(lua_State * L) { unit *self = (unit *)tolua_tousertype(L, 1, 0); unsigned int flags = (unsigned int)tolua_tonumber(L, 2, 0); - setguard(self, flags); + setguard(self, flags!=0); return 0; } @@ -756,14 +747,12 @@ static int tolua_unit_get_spells(lua_State * L) unit *self = (unit *) tolua_tousertype(L, 1, 0); sc_mage *mage = self ? get_mage(self) : 0; spellbook *sb = mage ? mage->spellbook : 0; - quicklist *slist = 0; + selist *slist = 0; if (sb) { - quicklist **slist_ptr = &sb->spells; - if (slist_ptr) { - slist = *slist_ptr; - } + selist **slist_ptr = &sb->spells; + slist = *slist_ptr; } - return tolua_quicklist_push(L, "spellbook", "spell_entry", slist); + return tolua_selist_push(L, "spellbook", "spell_entry", slist); } static int tolua_unit_get_orders(lua_State * L) @@ -782,6 +771,27 @@ static int tolua_unit_get_orders(lua_State * L) return 1; } +static int tolua_unit_get_curse(lua_State *L) { + unit *self = (unit *)tolua_tousertype(L, 1, 0); + const char *name = tolua_tostring(L, 2, 0); + if (self->attribs) { + curse * c = get_curse(self->attribs, ct_find(name)); + if (c) { + lua_pushnumber(L, curse_geteffect(c)); + return 1; + } + } + return 0; +} + +static int tolua_unit_has_attrib(lua_State *L) { + unit *self = (unit *)tolua_tousertype(L, 1, 0); + const char *name = tolua_tostring(L, 2, 0); + attrib * a = self->attribs ? a_find(self->attribs, at_find(name)) : NULL; + lua_pushboolean(L, a != NULL); + return 1; +} + static int tolua_unit_get_flag(lua_State * L) { unit *self = (unit *)tolua_tousertype(L, 1, 0); @@ -798,7 +808,7 @@ static int tolua_unit_set_flag(lua_State * L) int value = (int)tolua_tonumber(L, 3, 0); int flag = atoi36(name); if (value) { - key_set(&self->attribs, flag); + key_set(&self->attribs, flag, value); } else { key_unset(&self->attribs, flag); @@ -869,13 +879,15 @@ static int tolua_unit_create(lua_State * L) { faction *f = (faction *)tolua_tousertype(L, 1, 0); region *r = (region *)tolua_tousertype(L, 2, 0); + unit *u; const char *rcname = tolua_tostring(L, 4, NULL); int num = (int)tolua_tonumber(L, 3, 1); const race *rc; + assert(f && r); rc = rcname ? rc_find(rcname) : f->race; assert(rc); - unit *u = create_unit(r, f, num, rc, 0, NULL, NULL); + u = create_unit(r, f, num, rc, 0, NULL, NULL); tolua_pushusertype(L, u, TOLUA_CAST "unit"); return 1; } @@ -966,6 +978,9 @@ void tolua_unit_open(lua_State * L) tolua_function(L, TOLUA_CAST "clear_orders", &tolua_unit_clear_orders); tolua_variable(L, TOLUA_CAST "orders", &tolua_unit_get_orders, 0); + tolua_function(L, TOLUA_CAST "get_curse", &tolua_unit_get_curse); + tolua_function(L, TOLUA_CAST "has_attrib", &tolua_unit_has_attrib); + /* key-attributes for named flags: */ tolua_function(L, TOLUA_CAST "set_flag", &tolua_unit_set_flag); tolua_function(L, TOLUA_CAST "get_flag", &tolua_unit_get_flag); @@ -1018,7 +1033,6 @@ void tolua_unit_open(lua_State * L) tolua_unit_set_race); tolua_variable(L, TOLUA_CAST "hp_max", &tolua_unit_get_hpmax, 0); - tolua_variable(L, TOLUA_CAST "objects", &tolua_unit_get_objects, 0); tolua_function(L, TOLUA_CAST "show", &tolua_bufunit); } tolua_endmodule(L); diff --git a/src/bindings.c b/src/bindings.c index aa2e177c1..1d6270b35 100755 --- a/src/bindings.c +++ b/src/bindings.c @@ -15,7 +15,6 @@ without prior permission by the authors of Eressea. #include "bind_unit.h" #include "bind_storage.h" #include "bind_building.h" -#include "bind_dict.h" #include "bind_message.h" #include "bind_building.h" #include "bind_faction.h" @@ -54,7 +53,7 @@ without prior permission by the authors of Eressea. #include "summary.h" #include "teleport.h" #include "laws.h" -#include "monster.h" +#include "monsters.h" #include "market.h" #include @@ -66,7 +65,7 @@ without prior permission by the authors of Eressea. #include #include #include -#include +#include #include #include #include @@ -80,9 +79,10 @@ without prior permission by the authors of Eressea. #include #include +#include #include -#define TOLUA_PKG(NAME) extern void tolua_##NAME##_open(lua_State * L) +#define TOLUA_PKG(NAME) void tolua_##NAME##_open(lua_State * L) TOLUA_PKG(eressea); TOLUA_PKG(process); @@ -114,16 +114,16 @@ int tolua_orderlist_next(lua_State * L) return 0; } -static int tolua_quicklist_iter(lua_State * L) +static int tolua_selist_iter(lua_State * L) { - quicklist **qlp = (quicklist **)lua_touserdata(L, lua_upvalueindex(1)); - quicklist *ql = *qlp; + selist **qlp = (selist **)lua_touserdata(L, lua_upvalueindex(1)); + selist *ql = *qlp; if (ql != NULL) { int index = (int)lua_tointeger(L, lua_upvalueindex(2)); const char *type = lua_tostring(L, lua_upvalueindex(3)); - void *data = ql_get(ql, index); + void *data = selist_get(ql, index); tolua_pushusertype(L, data, TOLUA_CAST type); - ql_advance(qlp, &index, 1); + selist_advance(qlp, &index, 1); lua_pushinteger(L, index); lua_replace(L, lua_upvalueindex(2)); return 1; @@ -131,18 +131,18 @@ static int tolua_quicklist_iter(lua_State * L) return 0; } -int tolua_quicklist_push(struct lua_State *L, const char *list_type, - const char *elem_type, struct quicklist *list) +int tolua_selist_push(struct lua_State *L, const char *list_type, + const char *elem_type, struct selist *list) { if (list) { - quicklist **qlist_ptr = - (quicklist **)lua_newuserdata(L, sizeof(quicklist *)); + selist **qlist_ptr = + (selist **)lua_newuserdata(L, sizeof(selist *)); *qlist_ptr = list; luaL_getmetatable(L, list_type); lua_setmetatable(L, -2); lua_pushinteger(L, 0); lua_pushstring(L, elem_type); - lua_pushcclosure(L, tolua_quicklist_iter, 3); /* OBS: this closure has multiple upvalues (list, index, type_name) */ + lua_pushcclosure(L, tolua_selist_iter, 3); /* OBS: this closure has multiple upvalues (list, index, type_name) */ } else { lua_pushnil(L); @@ -206,10 +206,10 @@ static int tolua_translate(lua_State * L) static int tolua_setkey(lua_State * L) { const char *name = tolua_tostring(L, 1, 0); - int value = tolua_toboolean(L, 2, 0); + int value = (int)tolua_tonumber(L, 3, 0); int flag = atoi36(name); if (value) { - key_set(&global.attribs, flag); + key_set(&global.attribs, flag, value); } else { key_unset(&global.attribs, flag); @@ -223,14 +223,6 @@ static int tolua_rng_int(lua_State * L) return 1; } -static int tolua_read_orders(lua_State * L) -{ - const char *filename = tolua_tostring(L, 1, 0); - int result = readorders(filename); - lua_pushinteger(L, result); - return 1; -} - static int tolua_message_unit(lua_State * L) { unit *sender = (unit *)tolua_tousertype(L, 1, 0); @@ -318,23 +310,6 @@ static int tolua_dice_rand(lua_State * L) return 1; } -static int tolua_addequipment(lua_State * L) -{ - const char *eqname = tolua_tostring(L, 1, 0); - const char *iname = tolua_tostring(L, 2, 0); - const char *value = tolua_tostring(L, 3, 0); - int result = -1; - if (iname != NULL) { - const struct item_type *itype = it_find(iname); - if (itype != NULL) { - equipment_setitem(create_equipment(eqname), itype, value); - result = 0; - } - } - lua_pushinteger(L, result); - return 1; -} - static int tolua_get_season(lua_State * L) { int turnno = (int)tolua_tonumber(L, 1, 0); @@ -460,7 +435,7 @@ static int tolua_equipment_setitem(lua_State * L) if (iname != NULL) { const struct item_type *itype = it_find(iname); if (itype != NULL) { - equipment_setitem(create_equipment(eqname), itype, value); + equipment_setitem(get_or_create_equipment(eqname), itype, value); result = 0; } } @@ -505,45 +480,30 @@ static int tolua_write_reports(lua_State * L) return 1; } -static void reset_game(void) -{ - region *r; - faction *f; - for (r = regions; r; r = r->next) { - unit *u; - building *b; - r->flags &= RF_SAVEMASK; - for (u = r->units; u; u = u->next) { - u->flags &= UFL_SAVEMASK; - } - for (b = r->buildings; b; b = b->next) { - b->flags &= BLD_SAVEMASK; - } - if (r->land && r->land->ownership && r->land->ownership->owner) { - faction *owner = r->land->ownership->owner; - if (owner == get_monsters()) { - /* some compat-fix, i believe. */ - owner = update_owners(r); - } - if (owner) { - fset(r, RF_GUARDED); - } - } - } - for (f = factions; f; f = f->next) { - f->flags &= FFL_SAVEMASK; - } - init_locales(); -} - static int tolua_process_orders(lua_State * L) { - ++turn; - reset_game(); processorders(); return 0; } +static int tolua_turn_begin(lua_State * L) +{ + turn_begin(); + return 0; +} + +static int tolua_turn_process(lua_State * L) +{ + turn_process(); + return 0; +} + +static int tolua_turn_end(lua_State * L) +{ + turn_end(); + return 0; +} + static int tolua_write_passwords(lua_State * L) { int result = writepasswd(); @@ -671,7 +631,7 @@ static int tolua_get_factions(lua_State * L) static int tolua_get_alliance_factions(lua_State * L) { alliance *self = (alliance *)tolua_tousertype(L, 1, 0); - return tolua_quicklist_push(L, "faction_list", "faction", self->members); + return tolua_selist_push(L, "faction_list", "faction", self->members); } static int tolua_get_alliance_id(lua_State * L) @@ -697,11 +657,11 @@ static int tolua_set_alliance_name(lua_State * L) static int config_get_ships(lua_State * L) { - quicklist *ql; + selist *ql; int qi, i = 0; - lua_createtable(L, ql_length(shiptypes), 0); - for (qi = 0, ql = shiptypes; ql; ql_advance(&ql, &qi, 1)) { - ship_type *stype = (ship_type *)ql_get(ql, qi); + lua_createtable(L, selist_length(shiptypes), 0); + for (qi = 0, ql = shiptypes; ql; selist_advance(&ql, &qi, 1)) { + ship_type *stype = (ship_type *)selist_get(ql, qi); tolua_pushstring(L, TOLUA_CAST stype->_name); lua_rawseti(L, -2, ++i); } @@ -710,11 +670,11 @@ static int config_get_ships(lua_State * L) static int config_get_buildings(lua_State * L) { - quicklist *ql; + selist *ql; int qi, i = 0; - lua_createtable(L, ql_length(buildingtypes), 0); - for (qi = 0, ql = buildingtypes; ql; ql_advance(&ql, &qi, 1)) { - building_type *btype = (building_type *)ql_get(ql, qi); + lua_createtable(L, selist_length(buildingtypes), 0); + for (qi = 0, ql = buildingtypes; ql; selist_advance(&ql, &qi, 1)) { + building_type *btype = (building_type *)selist_get(ql, qi); tolua_pushstring(L, TOLUA_CAST btype->_name); lua_rawseti(L, -2, ++i); } @@ -936,7 +896,7 @@ static int tolua_get_spell_entry_level(lua_State * L) static int tolua_get_spells(lua_State * L) { - return tolua_quicklist_push(L, "spell_list", "spell", spells); + return tolua_selist_push(L, "spell_list", "spell", spells); } static int init_data(const char *filename, const char *catalog) @@ -948,7 +908,7 @@ static int init_data(const char *filename, const char *catalog) return l; } if (turn < 0) { - turn = first_turn; + turn = first_turn(); } return 0; } @@ -978,7 +938,7 @@ static int tolua_report_unit(lua_State * L) return 1; } -static void parse_inifile(lua_State * L, dictionary * d, const char *section) +static void parse_inifile(lua_State * L, const dictionary * d, const char *section) { int i; const char *arg; @@ -1018,7 +978,7 @@ static void parse_inifile(lua_State * L, dictionary * d, const char *section) void tolua_bind_open(lua_State * L); -int tolua_bindings_open(lua_State * L) +int tolua_bindings_open(lua_State * L, const dictionary *inifile) { tolua_open(L); @@ -1072,7 +1032,7 @@ int tolua_bindings_open(lua_State * L) tolua_module(L, TOLUA_CAST "config", 1); tolua_beginmodule(L, TOLUA_CAST "config"); { - parse_inifile(L, global.inifile, "lua"); + parse_inifile(L, inifile, "lua"); tolua_variable(L, TOLUA_CAST "locales", &config_get_locales, 0); tolua_function(L, TOLUA_CAST "get_resource", &config_get_resource); tolua_variable(L, TOLUA_CAST "buildings", &config_get_buildings, 0); @@ -1089,8 +1049,9 @@ int tolua_bindings_open(lua_State * L) tolua_function(L, TOLUA_CAST "factions", tolua_get_factions); tolua_function(L, TOLUA_CAST "regions", tolua_get_regions); tolua_function(L, TOLUA_CAST "read_turn", tolua_read_turn); -// tolua_function(L, TOLUA_CAST "write_map", &tolua_write_map); - tolua_function(L, TOLUA_CAST "read_orders", tolua_read_orders); + tolua_function(L, TOLUA_CAST "turn_begin", tolua_turn_begin); + tolua_function(L, TOLUA_CAST "turn_process", tolua_turn_process); + tolua_function(L, TOLUA_CAST "turn_end", tolua_turn_end); tolua_function(L, TOLUA_CAST "process_orders", tolua_process_orders); tolua_function(L, TOLUA_CAST "init_reports", tolua_init_reports); tolua_function(L, TOLUA_CAST "write_reports", tolua_write_reports); @@ -1111,7 +1072,6 @@ int tolua_bindings_open(lua_State * L) tolua_function(L, TOLUA_CAST "get_season", tolua_get_season); tolua_function(L, TOLUA_CAST "equipment_setitem", tolua_equipment_setitem); tolua_function(L, TOLUA_CAST "equip_unit", tolua_equipunit); - tolua_function(L, TOLUA_CAST "add_equipment", tolua_addequipment); tolua_function(L, TOLUA_CAST "atoi36", tolua_atoi36); tolua_function(L, TOLUA_CAST "itoa36", tolua_itoa36); tolua_function(L, TOLUA_CAST "dice_roll", tolua_dice_rand); @@ -1142,12 +1102,12 @@ void lua_done(lua_State * L) { lua_close(L); } -lua_State *lua_init(void) { +lua_State *lua_init(const dictionary *inifile) { lua_State *L = luaL_newstate(); openlibs(L); register_tolua_helpers(); - tolua_bindings_open(L); + tolua_bindings_open(L, inifile); tolua_eressea_open(L); #ifdef USE_SQLITE tolua_sqlite_open(L); @@ -1160,7 +1120,6 @@ lua_State *lua_init(void) { tolua_unit_open(L); tolua_message_open(L); tolua_order_open(L); - tolua_dict_open(L); #ifdef USE_CURSES tolua_gmtool_open(L); #endif @@ -1168,32 +1127,55 @@ lua_State *lua_init(void) { return L; } +static int run_script(lua_State *L, const char *luafile) { + int err; + FILE *F; + + F = fopen(luafile, "r"); + if (!F) { + log_debug("dofile('%s'): %s", luafile, strerror(errno)); + return errno; + } + fclose(F); + + log_debug("executing script %s", luafile); + lua_getglobal(L, "dofile"); + lua_pushstring(L, luafile); + err = lua_pcall(L, 1, 1, -3); /* error handler (debug.traceback) is now at stack -3 */ + if (err != 0) { + log_lua_error(L); + assert(!"Lua syntax error? check log."); + } + else { + if (lua_isnumber(L, -1)) { + err = (int)lua_tonumber(L, -1); + } + lua_pop(L, 1); + } + return err; +} + int eressea_run(lua_State *L, const char *luafile) { - int err = 0; - + int err; global.vm_state = L; + + /* push an error handling function on the stack: */ + lua_getglobal(L, "debug"); + lua_getfield(L, -1, "traceback"); + lua_remove(L, -2); + + /* try to run configuration scripts: */ + err = run_script(L, "custom.lua"); + /* run the main script */ if (luafile) { - log_debug("executing script %s\n", luafile); - - lua_getglobal(L, "debug"); - lua_getfield(L, -1, "traceback"); - lua_remove(L, -2); - lua_getglobal(L, "dofile"); - lua_pushstring(L, luafile); - err = lua_pcall(L, 1, 1, -3); - if (err != 0) { - log_lua_error(L); - assert(!"Lua syntax error? check log."); - } - else { - if (lua_isnumber(L, -1)) { - err = (int)lua_tonumber(L, -1); - } - lua_pop(L, 1); - } - return err; + err = run_script(L, luafile); } - return lua_console(L); + else { + err = lua_console(L); + } + /* pop error handler off the stack: */ + lua_pop(L, 1); + return err; } diff --git a/src/bindings.h b/src/bindings.h index 6c71ecf94..354bb199a 100755 --- a/src/bindings.h +++ b/src/bindings.h @@ -15,20 +15,20 @@ extern "C" { #endif struct lua_State; - struct quicklist; + struct _dictionary_; + struct selist; int tolua_sqlite_open(struct lua_State *L); - int tolua_bindings_open(struct lua_State *L); - int tolua_spelllist_next(struct lua_State *L); + int tolua_bindings_open(struct lua_State *L, const struct _dictionary_ *d); int tolua_itemlist_next(struct lua_State *L); int tolua_orderlist_next(struct lua_State *L); - int tolua_quicklist_push(struct lua_State *L, const char *list_type, - const char *elem_type, struct quicklist *list); + int tolua_selist_push(struct lua_State *L, const char *list_type, + const char *elem_type, struct selist *list); int log_lua_error(struct lua_State *L); void lua_done(struct lua_State *L); - struct lua_State *lua_init(void); + struct lua_State *lua_init(const struct _dictionary_ *d); int eressea_run(struct lua_State *L, const char *luafile); #ifdef __cplusplus diff --git a/src/building_action.c b/src/building_action.c index 5c533f4d0..f72af4412 100644 --- a/src/building_action.c +++ b/src/building_action.c @@ -93,7 +93,7 @@ lc_write(const struct attrib *a, const void *owner, struct storage *store) const char *fname = data->fname; const char *fparam = data->param; - unused_arg(owner); + UNUSED_ARG(owner); WRITE_TOK(store, fname); WRITE_TOK(store, fparam ? fparam : NULLSTRING); } @@ -116,7 +116,7 @@ static int lc_read(struct attrib *a, void *owner, gamedata *data) b = 0; } else { - bd->fname = _strdup(name); + bd->fname = strdup(name); } READ_TOK(store, name, sizeof(name)); if (strcmp(name, "tnnL") == 0) { @@ -127,7 +127,7 @@ static int lc_read(struct attrib *a, void *owner, gamedata *data) if (strcmp(name, NULLSTRING) == 0) bd->param = 0; else { - bd->param = _strdup(name); + bd->param = strdup(name); } if (result == 0 && !b) { return AT_READ_FAIL; @@ -146,8 +146,8 @@ void building_addaction(building * b, const char *fname, const char *param) { attrib *a = a_add(&b->attribs, a_new(&at_building_action)); building_action *data = (building_action *)a->data.v; - data->fname = _strdup(fname); + data->fname = strdup(fname); if (param) { - data->param = _strdup(param); + data->param = strdup(param); } } diff --git a/src/calendar.c b/src/calendar.c index 7a27328a7..2099b6631 100644 --- a/src/calendar.c +++ b/src/calendar.c @@ -1,10 +1,10 @@ #include #include "calendar.h" +#include #include #include -int first_turn = 0; int first_month = 0; int weeks_per_month = 4; int months_per_year = 12; @@ -16,10 +16,15 @@ int *month_season = NULL; char *agename = NULL; int seasons = 0; +int first_turn(void) +{ + return config_get_int("game.start", 1); +} + const gamedate *get_gamedate(int turn, gamedate * gd) { int weeks_per_year = months_per_year * weeks_per_month; - int t = turn - first_turn; + int t = turn - first_turn(); assert(gd); if (t < 0) diff --git a/src/calendar.h b/src/calendar.h index 86f665c1a..d398cd77c 100644 --- a/src/calendar.h +++ b/src/calendar.h @@ -13,7 +13,6 @@ extern "C" { }; extern char *agename; - extern int first_turn; extern int first_month; extern int seasons; @@ -35,8 +34,9 @@ extern "C" { int week; } gamedate; - extern const gamedate *get_gamedate(int turn, gamedate * gd); - extern void calendar_cleanup(void); +const gamedate *get_gamedate(int turn, gamedate * gd); +void calendar_cleanup(void); +int first_turn(void); #ifdef __cplusplus } diff --git a/src/callback.c b/src/callback.c deleted file mode 100644 index 79bd69b71..000000000 --- a/src/callback.c +++ /dev/null @@ -1,61 +0,0 @@ -#include -#include "callback.h" -#include -#include - -static struct reg { - struct reg * next; - HCALLBACK cb; - char *name; -} *registry; - -HCALLBACK create_callback(void(*cbv)(va_list va)) { - HCALLBACK cb; - cb.cbv = cbv; - return cb; -} - -void reset_callbacks(void) { - while (registry) { - struct reg *r = registry; - registry = r->next; - free(r->name); - free(r); - } - registry = 0; -} - -HCALLBACK register_callback(const char *name, void(*cbv)(va_list va)) -{ - struct reg * r = (struct reg *)malloc(sizeof(struct reg)); - r->next = registry; - r->name = _strdup(name); - r->cb.cbv = cbv; - registry = r; - return r->cb; -} - -int find_callback(const char *name, HCALLBACK *result) { - if (result && name) { - struct reg *r; - for (r = registry; r; r = r->next) { - if (strcmp(r->name, name) == 0) { - *result = r->cb; - return 0; - } - } - } - return -1; -} - -int call_callback(HCALLBACK cb, const char *name, ...) { - va_list ap; - if (name) { - int err = find_callback(name, &cb); - if (err) return err; - } - va_start(ap, name); - cb.cbv(ap); - va_end(ap); - return 0; -} diff --git a/src/callback.h b/src/callback.h deleted file mode 100644 index 288a148e9..000000000 --- a/src/callback.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef H_CALLBACK_H -#define H_CALLBACK_H - -#include - -typedef struct { - void(*cbv)(va_list va); -} HCALLBACK; - -HCALLBACK register_callback(const char *name, void(*cbv)(va_list va)); -HCALLBACK create_callback(void(*cbv)(va_list va)); -int find_callback(const char *name, HCALLBACK *result); -int call_callback(HCALLBACK cb, const char *name, ...); -void reset_callbacks(void); - -#endif diff --git a/src/callback.test.c b/src/callback.test.c deleted file mode 100644 index 317cc6d50..000000000 --- a/src/callback.test.c +++ /dev/null @@ -1,51 +0,0 @@ -#include "callback.h" -#include -#include - -void callback(va_list ap) { - int i = (int)va_arg(ap, int); - int *p = va_arg(ap, int *); - *p += i; -} - -static void test_find_callback(CuTest *tc) { - HCALLBACK cb; - reset_callbacks(); - CuAssertIntEquals(tc, -1, find_callback("test", &cb)); - cb = register_callback("test", callback); - CuAssertIntEquals(tc, 0, find_callback("test", &cb)); - reset_callbacks(); -} - -static void test_call_by_handle(CuTest *tc) { - HCALLBACK cb; - int x = 0; - reset_callbacks(); - cb = create_callback(callback); - CuAssertIntEquals(tc, 0, call_callback(cb, 0, 42, &x)); - CuAssertIntEquals(tc, 42, x); - reset_callbacks(); -} - -static void test_call_by_name(CuTest *tc) { - HCALLBACK cb = { 0 }; - HCALLBACK ca = { 0 }; - int x = 0; - reset_callbacks(); - CuAssertIntEquals(tc, -1, call_callback(cb, "test", 42, &x)); - cb = register_callback("test", callback); - CuAssertIntEquals(tc, 0, call_callback(cb, "test", 42, &x)); - CuAssertIntEquals(tc, 42, x); - CuAssertIntEquals(tc, 0, call_callback(ca, "test", 42, &x)); - CuAssertIntEquals(tc, 84, x); - reset_callbacks(); -} - -CuSuite *get_callback_suite(void) -{ - CuSuite *suite = CuSuiteNew(); - SUITE_ADD_TEST(suite, test_find_callback); - SUITE_ADD_TEST(suite, test_call_by_name); - SUITE_ADD_TEST(suite, test_call_by_handle); - return suite; -} diff --git a/src/chaos.c b/src/chaos.c index afa787b29..58cd7af73 100644 --- a/src/chaos.c +++ b/src/chaos.c @@ -19,7 +19,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include "chaos.h" -#include "monster.h" +#include "monsters.h" #include "move.h" #include @@ -28,7 +28,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include #include #include #include @@ -86,7 +85,7 @@ static const terrain_type *chaosterrain(void) if (numtypes == 0) { const terrain_type *terrain; for (terrain = terrains(); terrain != NULL; terrain = terrain->next) { - if (fval(terrain, LAND_REGION) && terrain->herbs) { + if ((terrain->flags & LAND_REGION) && terrain->herbs) { ++numtypes; } } @@ -94,7 +93,7 @@ static const terrain_type *chaosterrain(void) types = malloc(sizeof(terrain_type *) * numtypes); numtypes = 0; for (terrain = terrains(); terrain != NULL; terrain = terrain->next) { - if (fval(terrain, LAND_REGION) && terrain->herbs) { + if ((terrain->flags & LAND_REGION) && terrain->herbs) { types[numtypes++] = terrain; } } @@ -140,7 +139,7 @@ static void chaos(region * r) if (rng_int() % 100 < 8) { switch (rng_int() % 3) { case 0: /* Untote */ - if (!fval(r->terrain, SEA_REGION)) { + if (!(r->terrain->flags & SEA_REGION)) { unit *u = random_unit(r); if (u && playerrace(u_race(u))) { ADDMSG(&u->faction->msgs, msg_message("chaos_disease", "unit", u)); @@ -162,29 +161,28 @@ static void chaos(region * r) break; case 1: mfac = 500; - u = - create_unit(r, get_monsters(), rng_int() % 4 + 1, + u = create_unit(r, get_monsters(), rng_int() % 4 + 1, get_race(RC_DRAGON), 0, NULL, NULL); break; default: mfac = 1000; - u = - create_unit(r, get_monsters(), rng_int() % 2 + 1, + u = create_unit(r, get_monsters(), rng_int() % 2 + 1, get_race(RC_WYRM), 0, NULL, NULL); break; } - if (mfac) + if (mfac) { set_money(u, u->number * (rng_int() % mfac)); - fset(u, UFL_ISNEW | UFL_MOVED); + } + u->flags |= (UFL_ISNEW | UFL_MOVED); } break; - case 2: /* Terrainvernderung */ - if (!fval(r->terrain, FORBIDDEN_REGION)) { - if (!fval(r->terrain, SEA_REGION)) { + case 2: /* Terrainver�nderung */ + if (!(r->terrain->flags & FORBIDDEN_REGION)) { + if (!(r->terrain->flags & SEA_REGION)) { direction_t dir; for (dir = 0; dir != MAXDIRECTIONS; ++dir) { region *rn = rconnect(r, dir); - if (rn && fval(rn->terrain, SEA_REGION)) + if (rn && (rn->terrain->flags & SEA_REGION)) break; } if (dir != MAXDIRECTIONS) { @@ -225,7 +223,7 @@ static void chaos(region * r) direction_t dir; for (dir = 0; dir != MAXDIRECTIONS; ++dir) { region *rn = rconnect(r, dir); - if (rn && fval(rn->terrain, SEA_REGION)) + if (rn && (rn->terrain->flags & SEA_REGION)) break; } if (dir != MAXDIRECTIONS) { @@ -243,7 +241,7 @@ void chaos_update(void) { for (r = regions; r; r = r->next) { int i; - if (fval(r, RF_CHAOTIC)) { + if ((r->flags & RF_CHAOTIC)) { chaos(r); } i = get_chaoscount(r); diff --git a/src/console.h b/src/console.h index a00a3ad58..fdc869f11 100644 --- a/src/console.h +++ b/src/console.h @@ -18,6 +18,9 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef H_LUA_CONSOLE #define H_LUA_CONSOLE + +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/src/convert.c b/src/convert.c new file mode 100644 index 000000000..a67c5a287 --- /dev/null +++ b/src/convert.c @@ -0,0 +1,44 @@ +#include + + +#ifdef USE_LIBXML2 +#include +#include +#endif +#include +#include +#include + +#include + +#include + +static int usage(void) { + return -1; +} + +int main(int argc, char **argv) { + const char *mode; + + register_races(); +#ifdef USE_LIBXML2 + register_xmlreader(); +#endif + if (argc < 2) return usage(); + mode = argv[1]; +#ifdef USE_LIBXML2 + if (strcmp(mode, "rules")==0) { + const char *xmlfile, *catalog; + if (argc < 4) return usage(); + xmlfile = argv[2]; + catalog = argv[3]; + read_xml(xmlfile, catalog); + write_rules("rules.dat"); + return 0; + } +#endif + if (strcmp(mode, "po")==0) { + return 0; + } + return usage(); +} diff --git a/src/creport.c b/src/creport.c index 5e7442030..c2d10d1c0 100644 --- a/src/creport.c +++ b/src/creport.c @@ -1,4 +1,4 @@ -/* +/* +-------------------+ Enno Rehling | Eressea PBEM host | Christian Schlittchen | (c) 1998 - 2008 | Katja Zedel @@ -11,6 +11,8 @@ without prior permission by the authors of Eressea. #include #include #include "creport.h" +#include "market.h" +#include "guard.h" #include "travelthru.h" /* tweakable features */ @@ -23,7 +25,6 @@ without prior permission by the authors of Eressea. /* attributes include */ #include -#include #include #include #include @@ -57,7 +58,6 @@ without prior permission by the authors of Eressea. #include #include #include -#include /* util includes */ #include @@ -68,8 +68,9 @@ without prior permission by the authors of Eressea. #include #include #include -#include +#include #include +#include /* libc includes */ #include @@ -124,7 +125,7 @@ static const char *translate(const char *key, const char *value) } else t = malloc(sizeof(translation)); - t->key = _strdup(key); + t->key = strdup(key); t->value = value; t->next = translation_table[kk]; translation_table[kk] = t; @@ -177,7 +178,7 @@ static void print_items(FILE * F, item * items, const struct locale *lang) } static void -cr_output_curses(stream *out, const faction * viewer, const void *obj, objtype_t typ) +cr_output_curses(struct stream *out, const faction * viewer, const void *obj, objtype_t typ) { bool header = false; attrib *a = NULL; @@ -185,9 +186,9 @@ cr_output_curses(stream *out, const faction * viewer, const void *obj, objtype_t region *r; /* Die Sichtbarkeit eines Zaubers und die Zaubermeldung sind bei - * Gebäuden und Schiffen je nach, ob man Besitzer ist, verschieden. + * Gebaeuden und Schiffen je nach, ob man Besitzer ist, verschieden. * Bei Einheiten sieht man Wirkungen auf eigene Einheiten immer. - * Spezialfälle (besonderes Talent, verursachender Magier usw. werde + * Spezialfaelle (besonderes Talent, verursachender Magier usw. werde * bei jedem curse gesondert behandelt. */ if (typ == TYP_SHIP) { ship *sh = (ship *)obj; @@ -285,7 +286,7 @@ cr_output_curses(stream *out, const faction * viewer, const void *obj, objtype_t } static void cr_output_curses_compat(FILE *F, const faction * viewer, const void *obj, objtype_t typ) { - // TODO: eliminate this function + /* TODO: eliminate this function */ stream strm; fstream_init(&strm, F); cr_output_curses(&strm, viewer, obj, typ); @@ -360,7 +361,7 @@ static int cr_race(variant var, char *buffer, const void *userdata) static int cr_alliance(variant var, char *buffer, const void *userdata) { const alliance *al = (const alliance *)var.v; - unused_arg(userdata); + UNUSED_ARG(userdata); if (al != NULL) { sprintf(buffer, "%d", al->id); } @@ -371,7 +372,7 @@ static int cr_skill(variant var, char *buffer, const void *userdata) { const faction *report = (const faction *)userdata; skill_t sk = (skill_t)var.i; - unused_arg(userdata); + UNUSED_ARG(userdata); if (sk != NOSKILL) sprintf(buffer, "\"%s\"", translate(mkname("skill", skillnames[sk]), skillname(sk, @@ -384,7 +385,7 @@ static int cr_skill(variant var, char *buffer, const void *userdata) static int cr_order(variant var, char *buffer, const void *userdata) { order *ord = (order *)var.v; - unused_arg(userdata); + UNUSED_ARG(userdata); if (ord != NULL) { char cmd[ORDERSIZE]; char *wp = buffer; @@ -711,12 +712,13 @@ static void cr_output_spells(stream *out, const unit * u, int maxlevel) if (book) { const faction * f = u->faction; - quicklist *ql; + selist *ql; int qi, header = 0; - for (ql = book->spells, qi = 0; ql; ql_advance(&ql, &qi, 1)) { - spellbook_entry * sbe = (spellbook_entry *)ql_get(ql, qi); + for (ql = book->spells, qi = 0; ql; selist_advance(&ql, &qi, 1)) { + spellbook_entry * sbe = (spellbook_entry *)selist_get(ql, qi); if (sbe->level <= maxlevel) { + /* TODO: no need to deref spref here, spref->name == sp->sname */ spell * sp = sbe->sp; const char *name = translate(mkname("spell", sp->sname), spell_name(sp, f->locale)); if (!header) { @@ -750,7 +752,7 @@ void cr_output_unit(stream *out, const region * r, const faction * f, const char *prefix; assert(u && u->number); - assert(u->region == r); // TODO: if this holds true, then why did we pass in r? + assert(u->region == r); /* TODO: if this holds true, then why did we pass in r? */ if (fval(u_race(u), RCF_INVISIBLE)) return; @@ -781,7 +783,7 @@ void cr_output_unit(stream *out, const region * r, const faction * f, if (sf != u->faction) stream_printf(out, "%d;Verkleidung\n", sf->no); if (fval(u, UFL_ANON_FACTION)) - stream_printf(out, "%d;Parteitarnung\n", i2b(fval(u, UFL_ANON_FACTION))); + stream_printf(out, "%d;Parteitarnung\n", (u->flags & UFL_ANON_FACTION)!=0); if (otherfaction && otherfaction != u->faction) { stream_printf(out, "%d;Anderepartei\n", otherfaction->no); } @@ -793,7 +795,7 @@ void cr_output_unit(stream *out, const region * r, const faction * f, else { if (fval(u, UFL_ANON_FACTION)) { /* faction info is hidden */ - stream_printf(out, "%d;Parteitarnung\n", i2b(fval(u, UFL_ANON_FACTION))); + stream_printf(out, "%d;Parteitarnung\n", (u->flags & UFL_ANON_FACTION) != 0); } else { const attrib *a_otherfaction = a_find(u->attribs, &at_otherfaction); @@ -849,7 +851,7 @@ void cr_output_unit(stream *out, const region * r, const faction * f, assert(u->ship->region); stream_printf(out, "%d;Schiff\n", u->ship->no); } - if (is_guard(u, GUARD_ALL) != 0) { + if (is_guard(u)) { stream_printf(out, "%d;bewacht\n", 1); } if ((b = usiege(u)) != NULL) { @@ -988,7 +990,7 @@ void cr_output_unit(stream *out, const region * r, const faction * f, static void cr_output_unit_compat(FILE * F, const region * r, const faction * f, const unit * u, int mode) { - // TODO: eliminate this function + /* TODO: eliminate this function */ stream strm; fstream_init(&strm, F); cr_output_unit(&strm, r, f, u, mode); @@ -1026,12 +1028,12 @@ static void show_alliances_cr(FILE * F, const faction * f) /* = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = */ /* this is a copy of laws.c->find_address output changed. */ -static void cr_find_address(FILE * F, const faction * uf, quicklist * addresses) +static void cr_find_address(FILE * F, const faction * uf, selist * addresses) { int i = 0; - quicklist *flist = addresses; + selist *flist = addresses; while (flist) { - const faction *f = (const faction *)ql_get(flist, i); + const faction *f = (const faction *)selist_get(flist, i); if (uf != f) { fprintf(F, "PARTEI %d\n", f->no); fprintf(F, "\"%s\";Parteiname\n", f->name); @@ -1044,7 +1046,7 @@ static void cr_find_address(FILE * F, const faction * uf, quicklist * addresses) fprintf(F, "%d;alliance\n", f->alliance->id); } } - ql_advance(&flist, &i, 1); + selist_advance(&flist, &i, 1); } } @@ -1328,9 +1330,6 @@ static void cr_output_region(FILE * F, report_context * ctx, region * r) if (fval(r->terrain, LAND_REGION)) { assert(r->land); fprintf(F, "%d;Bauern\n", rpeasants(r)); - if (fval(r, RF_ORCIFIED)) { - fprintf(F, "1;Verorkt\n"); - } fprintf(F, "%d;Pferde\n", rhorses(r)); if (r->seen.mode >= seen_unit) { @@ -1470,14 +1469,14 @@ static void cr_output_region(FILE * F, report_context * ctx, region * r) /* main function of the creport. creates the header and traverses all regions */ static int -report_computer(const char *filename, report_context * ctx, const char *charset) +report_computer(const char *filename, report_context * ctx, const char *bom) { static int era = -1; int i; faction *f = ctx->f; const char *prefix; region *r; - const char *mailto = LOC(f->locale, "mailto"); + const char *mailto = config_get("game.email"); const attrib *a; FILE *F = fopen(filename, "w"); static const race *rc_human; @@ -1490,9 +1489,8 @@ report_computer(const char *filename, report_context * ctx, const char *charset) perror(filename); return -1; } - else if (_strcmpl(charset, "utf-8") == 0 || _strcmpl(charset, "utf8") == 0) { - const unsigned char utf8_bom[4] = { 0xef, 0xbb, 0xbf, 0 }; - fwrite(utf8_bom, 1, 3, F); + else if (bom) { + fwrite(bom, 1, strlen(bom), F); } /* must call this to get all the neighbour regions */ @@ -1500,8 +1498,8 @@ report_computer(const char *filename, report_context * ctx, const char *charset) /* initialisations, header and lists */ fprintf(F, "VERSION %d\n", C_REPORT_VERSION); - fprintf(F, "\"%s\";charset\n", charset); - fprintf(F, "\"%s\";locale\n", locale_name(f->locale)); + fprintf(F, "\"UTF-8\";charset\n\"%s\";locale\n", + locale_name(f->locale)); fprintf(F, "%d;noskillpoints\n", 1); fprintf(F, "%lld;date\n", (long long)ctx->report_time); fprintf(F, "\"%s\";Spiel\n", game_name()); @@ -1513,8 +1511,9 @@ report_computer(const char *filename, report_context * ctx, const char *charset) fprintf(F, "%d;Zeitalter\n", era); fprintf(F, "\"%s\";Build\n", eressea_version()); if (mailto != NULL) { + const char * mailcmd = get_mailcmd(f->locale); fprintf(F, "\"%s\";mailto\n", mailto); - fprintf(F, "\"%s\";mailcmd\n", LOC(f->locale, "mailcmd")); + fprintf(F, "\"%s\";mailcmd\n", mailcmd); } show_alliances_cr(F, f); diff --git a/src/creport.test.c b/src/creport.test.c index 3a84ea566..21a6c09b7 100644 --- a/src/creport.test.c +++ b/src/creport.test.c @@ -1,5 +1,4 @@ #include -#include #include "creport.h" #include "move.h" #include "travelthru.h" @@ -19,7 +18,6 @@ #include #include -#include #include #include diff --git a/src/donations.c b/src/donations.c index 8f820df2b..b923df73b 100644 --- a/src/donations.c +++ b/src/donations.c @@ -1,10 +1,11 @@ +#include #include #include "donations.h" #include #include #include -#include +#include #include #include @@ -15,7 +16,7 @@ typedef struct transfer { int amount; } transfer; -static quicklist *transfers = 0; +static selist *transfers = 0; int cmp_transfer(const void *v1, const void *v2) { const transfer *t1 = (const transfer *)v1; @@ -35,46 +36,42 @@ int cmp_transfer(const void *v1, const void *v2) { void add_donation(faction * f1, faction * f2, int amount, region * r) { transfer tr, *tf; - quicklist *ql = transfers; + selist *ql = transfers; int qi = 0; tr.r = r; tr.f1 = f1; tr.f2 = f2; tr.amount = amount; - if (ql_set_find_ex(&ql, &qi, &tr, cmp_transfer)) { - tf = (transfer *)ql_get(ql, qi); + if (selist_set_find(&ql, &qi, &tr, cmp_transfer)) { + tf = (transfer *)selist_get(ql, qi); tf->amount += amount; } else { tf = malloc(sizeof(transfer)); memcpy(tf, &tr, sizeof(transfer)); } - ql_set_insert_ex(&transfers, tf, cmp_transfer); + selist_set_insert(&transfers, tf, cmp_transfer); } void free_donations(void) { - ql_foreach(transfers, free); - ql_free(transfers); + selist_foreach(transfers, free); + selist_free(transfers); transfers = 0; } -static void report_transfer(faction *f1, faction *f2, region *r, int amount) { - struct message *msg = msg_message("donation", - "from to amount", f1, f2, amount); - r_addmessage(r, f1, msg); - r_addmessage(r, f2, msg); - msg_release(msg); +static void report_transfer(void *data) { + transfer *tf = (transfer *)data; + if (tf->amount > 0) { + struct message *msg = msg_message("donation", + "from to amount", tf->f1, tf->f2, tf->amount); + r_addmessage(tf->r, tf->f1, msg); + r_addmessage(tf->r, tf->f2, msg); + msg_release(msg); + } } void report_donations(void) { - ql_iter qli = qli_init(&transfers); - - while (qli_more(qli)) { - transfer *tf = (transfer *)qli_next(&qli); - if (tf->amount > 0) { - report_transfer(tf->f1, tf->f2, tf->r, tf->amount); - } - } + selist_foreach(transfers, report_transfer); } diff --git a/src/donations.test.c b/src/donations.test.c index 068aba74a..09cd31977 100644 --- a/src/donations.test.c +++ b/src/donations.test.c @@ -1,3 +1,4 @@ +#include #include "donations.h" #include diff --git a/src/economy.c b/src/economy.c index 06b8c0f84..ab6862aa4 100644 --- a/src/economy.c +++ b/src/economy.c @@ -24,13 +24,14 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "alchemy.h" #include "direction.h" #include "donations.h" +#include "guard.h" #include "give.h" #include "laws.h" #include "randenc.h" #include "spy.h" #include "study.h" #include "move.h" -#include "monster.h" +#include "monsters.h" #include "morale.h" #include "reports.h" #include "calendar.h" @@ -68,7 +69,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include -#include /* libs includes */ #include @@ -97,7 +97,7 @@ static request *nextentertainer; static int entertaining; static unsigned int norders; -static request *oa; +static request *g_requests; #define RECRUIT_MERGE 1 static int rules_recruit = -1; @@ -112,22 +112,27 @@ static void recruit_init(void) } } +int entertainmoney(const region * r) +{ + double n; + + if (is_cursed(r->attribs, C_DEPRESSION, 0)) { + return 0; + } + + n = rmoney(r) / (double)ENTERTAINFRACTION; + + if (is_cursed(r->attribs, C_GENEROUS, 0)) { + n *= get_curseeffect(r->attribs, C_GENEROUS, 0); + } + + return (int)n; +} + int income(const unit * u) { - // TODO: make this a property, like race.income, no hard-coding of values - if (fval(u_race(u), RCF_DRAGON)) { - switch (old_race(u_race(u))) { - case RC_FIREDRAGON: - return 150 * u->number; - case RC_DRAGON: - return 1000 * u->number; - case RC_WYRM: - return 5000 * u->number; - default: - break; - } - } - return 20 * u->number; + const race *rc = u_race(u); + return rc->income * u->number; } static void scramble(void *data, unsigned int n, size_t width) @@ -166,21 +171,21 @@ static void expandorders(region * r, request * requests) if (norders > 0) { int i = 0; - oa = (request *)calloc(norders, sizeof(request)); + g_requests = (request *)calloc(norders, sizeof(request)); for (o = requests; o; o = o->next) { if (o->qty > 0) { unsigned int j; for (j = o->qty; j; j--) { - oa[i] = *o; - oa[i].unit->n = 0; + g_requests[i] = *o; + g_requests[i].unit->n = 0; i++; } } } - scramble(oa, norders, sizeof(request)); + scramble(g_requests, norders, sizeof(request)); } else { - oa = NULL; + g_requests = NULL; } while (requests) { request *o = requests->next; @@ -192,15 +197,6 @@ static void expandorders(region * r, request * requests) /* ------------------------------------------------------------- */ -static void change_level(unit * u, skill_t sk, int bylevel) -{ - skill *sv = unit_skill(u, sk); - assert(bylevel > 0); - if (sv == 0) - sv = add_skill(u, sk); - sk_set(sv, sv->level + bylevel); -} - typedef struct recruitment { struct recruitment *next; faction *f; @@ -270,10 +266,6 @@ void add_recruits(unit * u, int number, int wanted) strlcat(equipment, "_unit", sizeof(equipment)); equip_unit(unew, get_equipment(equipment)); - if (u_race(unew)->ec_flags & ECF_REC_HORSES) { - change_level(unew, SK_RIDING, 1); - } - if (unew != u) { transfermen(unew, u, unew->number); remove_unit(&r->units, unew); @@ -290,24 +282,6 @@ static int any_recruiters(const struct race *rc, int qty) return (int)(qty * 2 * rc->recruit_multi); } -/*static int peasant_recruiters(const struct race *rc, int qty) -{ -if (rc->ec_flags & ECF_REC_ETHEREAL) -return -1; -if (rc->ec_flags & ECF_REC_HORSES) -return -1; -return (int)(qty * 2 * rc->recruit_multi); -}*/ - -static int horse_recruiters(const struct race *rc, int qty) -{ - if (rc->ec_flags & ECF_REC_ETHEREAL) - return -1; - if (rc->ec_flags & ECF_REC_HORSES) - return (int)(qty * 2.0 * rc->recruit_multi); - return -1; -} - static int do_recruiting(recruitment * recruits, int available) { recruitment *rec; @@ -363,11 +337,11 @@ static int do_recruiting(recruitment * recruits, int available) int number, dec; double multi = 2.0 * rc->recruit_multi; - number = _min(req->qty, (int)(get / multi)); + number = MIN(req->qty, (int)(get / multi)); if (rc->recruitcost) { int afford = get_pooled(u, get_resourcetype(R_SILVER), GET_DEFAULT, number * rc->recruitcost) / rc->recruitcost; - number = _min(number, afford); + number = MIN(number, afford); } if (u->number + number > UNIT_MAXSIZE) { ADDMSG(&u->faction->msgs, msg_feedback(u, req->ord, "error_unit_size", @@ -383,8 +357,8 @@ static int do_recruiting(recruitment * recruits, int available) /* unit is empty, dead, and cannot recruit */ number = 0; } + add_recruits(u, number, req->qty); if (number > 0) { - add_recruits(u, number, req->qty); dec = (int)(number * multi); if ((rc->ec_flags & ECF_REC_ETHEREAL) == 0) { recruited += dec; @@ -419,17 +393,6 @@ static void expandrecruit(region * r, request * recruitorders) int orc_total = 0; - /* centaurs: */ - recruits = select_recruitment(&recruitorders, horse_recruiters, &orc_total); - if (recruits) { - int recruited, horses = rhorses(r) * 2; - if (orc_total < horses) - horses = orc_total; - recruited = do_recruiting(recruits, horses); - rsethorses(r, (horses - recruited) / 2); - free_recruitments(recruits); - } - /* peasant limited: */ recruits = select_recruitment(&recruitorders, any_recruiters, &orc_total); if (recruits) { @@ -459,13 +422,9 @@ static void expandrecruit(region * r, request * recruitorders) static int recruit_cost(const faction * f, const race * rc) { - if (is_monsters(f) || f->race == rc) { + if (is_monsters(f) || valid_race(f, rc)) { return rc->recruitcost; } - else if (valid_race(f, rc)) { - return rc->recruitcost; - /* return get_param_int(f->race->parameters, "other_cost", -1); */ - } return -1; } @@ -513,7 +472,7 @@ static void recruit(unit * u, struct order *ord, request ** recruitorders) /* this is a very special case because the recruiting unit may be empty * at this point and we have to look at the creating unit instead. This * is done in cansee, which is called indirectly by is_guarded(). */ - if (is_guarded(r, u, GUARD_RECRUIT)) { + if (is_guarded(r, u)) { cmistake(u, ord, 70, MSG_EVENT); return; } @@ -551,13 +510,6 @@ static void recruit(unit * u, struct order *ord, request ** recruitorders) return; } - if (!(rc->ec_flags & ECF_REC_HORSES) && fval(r, RF_ORCIFIED)) { - if (rc != get_race(RC_ORC)) { - cmistake(u, ord, 238, MSG_EVENT); - return; - } - } - if (recruitcost) { pl = getplane(r); if (pl && fval(pl, PFL_NORECRUITS)) { @@ -582,7 +534,7 @@ static void recruit(unit * u, struct order *ord, request ** recruitorders) } if (has_skill(u, SK_MAGIC)) { /* error158;de;{unit} in {region}: '{command}' - Magier arbeiten - * grundstzlich nur alleine! */ + * grunds�tzlich nur alleine! */ cmistake(u, ord, 158, MSG_EVENT); return; } @@ -595,7 +547,7 @@ static void recruit(unit * u, struct order *ord, request ** recruitorders) if (recruitcost > 0) { int pooled = get_pooled(u, get_resourcetype(R_SILVER), GET_DEFAULT, recruitcost * n); - n = _min(n, pooled / recruitcost); + n = MIN(n, pooled / recruitcost); } u->wants = n; @@ -717,7 +669,7 @@ static int maintain(building * b) { int c; region *r = b->region; - bool paid = true, work = true; + bool paid = true; unit *u; if (fval(b, BLD_MAINTAINED) || b->type == NULL || b->type->maintenance == NULL) { @@ -738,78 +690,40 @@ static int maintain(building * b) return 0; } } - for (c = 0; b->type->maintenance[c].number; ++c) { + for (c = 0; b->type->maintenance[c].number && paid; ++c) { const maintenance *m = b->type->maintenance + c; int need = m->number; if (fval(m, MTF_VARIABLE)) need = need * b->size; - if (u) { - /* first ist im ersten versuch true, im zweiten aber false! Das - * bedeutet, das in der Runde in die Region geschafften Resourcen - * nicht genutzt werden knnen, weil die reserviert sind! */ - need -= get_pooled(u, m->rtype, GET_DEFAULT, need); - } + need -= get_pooled(u, m->rtype, GET_DEFAULT, need); if (need > 0) { - if (!fval(m, MTF_VITAL)) - work = false; - else { - paid = false; - break; - } + paid = false; } } if (fval(b, BLD_DONTPAY)) { + ADDMSG(&r->msgs, msg_message("maintenance_nowork", "building", b)); return 0; } - u = building_owner(b); - if (!u) { + if (!paid) { + ADDMSG(&u->faction->msgs, msg_message("maintenancefail", "unit building", u, b)); + ADDMSG(&r->msgs, msg_message("maintenance_nowork", "building", b)); return 0; } for (c = 0; b->type->maintenance[c].number; ++c) { const maintenance *m = b->type->maintenance + c; - int need = m->number; + int cost = m->number; - if (fval(m, MTF_VARIABLE)) - need = need * b->size; - if (u) { - need -= get_pooled(u, m->rtype, GET_DEFAULT, need); - if (need > 0) { - work = false; - if (fval(m, MTF_VITAL)) { - paid = false; - break; - } - } + if (fval(m, MTF_VARIABLE)) { + cost = cost * b->size; } + cost -= + use_pooled(u, m->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, + cost); + assert(cost == 0); } - if (paid && c > 0) { - if (!work) { - ADDMSG(&u->faction->msgs, msg_message("maintenancefail", "unit building", u, b)); - return 0; - } - - for (c = 0; b->type->maintenance[c].number; ++c) { - const maintenance *m = b->type->maintenance + c; - int cost = m->number; - - if (!fval(m, MTF_VITAL) && !work) - continue; - if (fval(m, MTF_VARIABLE)) - cost = cost * b->size; - - cost -= - use_pooled(u, m->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, - cost); - assert(cost == 0); - } - if (work) { - ADDMSG(&u->faction->msgs, msg_message("maintenance", "unit building", u, b)); - return BLD_MAINTAINED; - } - } - ADDMSG(&u->faction->msgs, msg_message("maintenancefail", "unit building", u, b)); - return 0; + ADDMSG(&u->faction->msgs, msg_message("maintenance", "unit building", u, b)); + return BLD_MAINTAINED; } void maintain_buildings(region * r) @@ -824,19 +738,6 @@ void maintain_buildings(region * r) flags = maintain(b); } fset(b, flags); - - if (!fval(b, BLD_MAINTAINED)) { - unit *u = building_owner(b); - struct message *msg = msg_message("maintenance_nowork", "building", b); - if (u) { - add_message(&u->faction->msgs, msg); - r_addmessage(r, u->faction, msg); - } - else { - add_message(&r->msgs, msg); - } - msg_release(msg); - } bp = &b->next; } } @@ -962,7 +863,7 @@ static void manufacture(unit * u, const item_type * itype, int want) typedef struct allocation { struct allocation *next; int want, get; - double save; + variant save; unsigned int flags; unit *unit; } allocation; @@ -977,24 +878,42 @@ typedef struct allocation_list { static allocation_list *allocations; -static bool can_guard(const unit * guard, const unit * u) -{ - if (fval(guard, UFL_ISNEW)) - return false; - if (guard->number <= 0 || !cansee(guard->faction, guard->region, u, 0)) - return false; - if (besieged(guard) || !(fval(u_race(guard), RCF_UNARMEDGUARD) - || armedmen(guard, true))) - return false; - - return !alliedunit(guard, u->faction, HELP_GUARD); -} - enum { AFL_DONE = 1 << 0, AFL_LOWSKILL = 1 << 1 }; +struct message * get_modifiers(unit *u, const resource_mod *mod, variant *savep, int *skillp) { + struct building *b = inside_building(u); + const struct building_type *btype = building_is_active(b) ? b->type : NULL; + int save_n = 1, save_d = 1; + int skill = 0; + + for (; mod->flags != 0; ++mod) { + if (mod->btype == NULL || mod->btype == btype) { + if (mod->race == NULL || mod->race == u_race(u)) { + if (mod->flags & RMF_SAVEMATERIAL) { + save_n *= mod->value.sa[0]; + save_d *= mod->value.sa[1]; + } + if (mod->flags & RMF_SKILL) { + skill += mod->value.i; + } + } + } else if (mod->flags & RMF_REQUIREDBUILDING) { + return msg_error(u, u->thisorder, 104); + } + } + *skillp = skill; + assert(save_n < SHRT_MAX); + assert(save_n > SHRT_MIN); + assert(save_d < SHRT_MAX); + assert(save_d > SHRT_MIN); + savep->sa[0] = (short)save_n; + savep->sa[1] = (short)save_d; + return NULL; +} + static void allocate_resource(unit * u, const resource_type * rtype, int want) { const item_type *itype = resource2item(rtype); @@ -1002,19 +921,17 @@ static void allocate_resource(unit * u, const resource_type * rtype, int want) int dm = 0; allocation_list *alist; allocation *al; - attrib *a = a_find(rtype->attribs, &at_resourcelimit); - resource_limit *rdata = (resource_limit *)a->data.v; const resource_type *rring; - int amount, skill; + int amount, skill, skill_mod = 0; + variant save_mod; - /* momentan kann man keine ressourcen abbauen, wenn man dafr + /* momentan kann man keine ressourcen abbauen, wenn man daf�r * Materialverbrauch hat: */ assert(itype != NULL && (itype->construction == NULL || itype->construction->materials == NULL)); - assert(rdata != NULL); - if (rdata->limit != NULL) { - int avail = rdata->limit(r, rtype); + if (!rtype->raw) { + int avail = limit_resource(r, rtype); if (avail <= 0) { cmistake(u, u->thisorder, 121, MSG_PRODUCE); return; @@ -1026,39 +943,26 @@ static void allocate_resource(unit * u, const resource_type * rtype, int want) return; } - if (rdata->modifiers) { - resource_mod *mod = rdata->modifiers; - for (; mod->flags != 0; ++mod) { - if (mod->flags & RMF_REQUIREDBUILDING) { - struct building *b = inside_building(u); - const struct building_type *btype = building_is_active(b) ? b->type : NULL; - if (mod->btype && mod->btype != btype) { - cmistake(u, u->thisorder, 104, MSG_PRODUCE); - return; - } - } + if (rtype->modifiers) { + message *msg = get_modifiers(u, rtype->modifiers, &save_mod, &skill_mod); + if (msg) { + ADDMSG(&u->faction->msgs, msg); + return; } } - - if (rdata->guard != 0) { - unit *u2; - for (u2 = r->units; u2; u2 = u2->next) { - if (is_guard(u2, rdata->guard) != 0 && can_guard(u2, u)) { - ADDMSG(&u->faction->msgs, - msg_feedback(u, u->thisorder, "region_guarded", "guard", u2)); - return; - } - } + else { + save_mod.sa[0] = 1; + save_mod.sa[1] = 1; } - /* Bergwchter knnen Abbau von Eisen/Laen durch Bewachen verhindern. - * Als magische Wesen 'sehen' Bergwchter alles und werden durch + /* Bergw�chter k�nnen Abbau von Eisen/Laen durch Bewachen verhindern. + * Als magische Wesen 'sehen' Bergw�chter alles und werden durch * Belagerung nicht aufgehalten. (Ansonsten wie oben bei Elfen anpassen). */ if (itype->rtype && (itype->rtype == get_resourcetype(R_IRON) || itype->rtype == rt_find("laen"))) { unit *u2; for (u2 = r->units; u2; u2 = u2->next) { - if (is_guard(u, GUARD_MINING) + if (is_guard(u) && !fval(u2, UFL_ISNEW) && u2->number && !alliedunit(u2, u->faction, HELP_GUARD)) { ADDMSG(&u->faction->msgs, @@ -1085,23 +989,7 @@ static void allocate_resource(unit * u, const resource_type * rtype, int want) itype->rtype)); return; } - else { - struct building *b = inside_building(u); - const struct building_type *btype = building_is_active(b) ? b->type : NULL; - - if (rdata->modifiers) { - resource_mod *mod = rdata->modifiers; - for (; mod->flags != 0; ++mod) { - if (mod->flags & RMF_SKILL) { - if (mod->btype == NULL || mod->btype == btype) { - if (mod->race == NULL || mod->race == u_race(u)) { - skill += mod->value.i; - } - } - } - } - } - } + skill += skill_mod; amount = skill * u->number; /* nun ist amount die Gesamtproduktion der Einheit (in punkten) */ @@ -1109,12 +997,12 @@ static void allocate_resource(unit * u, const resource_type * rtype, int want) rring = get_resourcetype(R_RING_OF_NIMBLEFINGER); if (rring) { int dm = i_get(u->items, rring->itype); - amount += skill * _min(u->number, dm) * (roqf_factor() - 1); + amount += skill * MIN(u->number, dm) * (roqf_factor() - 1); } /* Schaffenstrunk: */ if ((dm = get_effect(u, oldpotiontype[P_DOMORE])) != 0) { - dm = _min(dm, u->number); + dm = MIN(dm, u->number); change_effect(u, oldpotiontype[P_DOMORE], -dm); amount += dm * skill; /* dm Personen produzieren doppelt */ } @@ -1136,34 +1024,18 @@ static void allocate_resource(unit * u, const resource_type * rtype, int want) } al = new_allocation(); al->want = amount; - al->save = 1.0; + al->save = save_mod; al->next = alist->data; al->unit = u; alist->data = al; - - if (rdata->modifiers) { - struct building *b = inside_building(u); - const struct building_type *btype = building_is_active(b) ? b->type : NULL; - - resource_mod *mod = rdata->modifiers; - for (; mod->flags != 0; ++mod) { - if (mod->flags & RMF_SAVEMATERIAL) { - if (mod->btype == NULL || mod->btype == btype) { - if (mod->race == NULL || mod->race == u_race(u)) { - al->save *= mod->value.f; - } - } - } - } - } } -static int required(int want, double save) +static int required(int want, variant save) { - int norders = (int)(want * save); - if (norders < want * save) - ++norders; - return norders; + int req = (int)(want * save.sa[0] / save.sa[1]); + int r = want * save.sa[0] % save.sa[1]; + if (r>0) ++req; + return req; } static void @@ -1177,7 +1049,7 @@ leveled_allocation(const resource_type * rtype, region * r, allocation * alist) if (rm != NULL) { do { int avail = rm->amount; - int norders = 0; + int nreq = 0; allocation *al; if (avail <= 0) { @@ -1196,7 +1068,7 @@ leveled_allocation(const resource_type * rtype, region * r, allocation * alist) if (effskill(al->unit, itype->construction->skill, 0) >= rm->level + itype->construction->minskill - 1) { if (req) { - norders += req; + nreq += req; } else { fset(al, AFL_DONE); @@ -1208,31 +1080,31 @@ leveled_allocation(const resource_type * rtype, region * r, allocation * alist) fset(al, AFL_LOWSKILL); } } - need = norders; + need = nreq; - avail = _min(avail, norders); + avail = MIN(avail, nreq); if (need > 0) { int use = 0; for (al = alist; al; al = al->next) if (!fval(al, AFL_DONE)) { if (avail > 0) { int want = required(al->want - al->get, al->save); - int x = avail * want / norders; - /* Wenn Rest, dann wrfeln, ob ich was bekomme: */ - if (rng_int() % norders < (avail * want) % norders) - ++x; + int x = avail * want / nreq; + int r = (avail * want) % nreq; + /* Wenn Rest, dann wuerfeln, ob ich etwas bekomme: */ + if (r > 0 && rng_int() % nreq < r) ++x; avail -= x; use += x; - norders -= want; + nreq -= want; need -= x; - al->get = _min(al->want, al->get + (int)(x / al->save)); + al->get = MIN(al->want, al->get + x * al->save.sa[1] / al->save.sa[0]); } } if (use) { assert(use <= rm->amount); rm->type->use(rm, r, use); } - assert(avail == 0 || norders == 0); + assert(avail == 0 || nreq == 0); } first = false; } while (need > 0); @@ -1243,40 +1115,41 @@ static void attrib_allocation(const resource_type * rtype, region * r, allocation * alist) { allocation *al; - int norders = 0; - attrib *a = a_find(rtype->attribs, &at_resourcelimit); - resource_limit *rdata = (resource_limit *)a->data.v; - int avail = rdata->value; + int nreq = 0; + int avail = 0; for (al = alist; al; al = al->next) { - norders += required(al->want, al->save); + nreq += required(al->want, al->save); } - if (rdata->limit) { - avail = rdata->limit(r, rtype); - if (avail < 0) + if (!rtype->raw) { + avail = limit_resource(r, rtype); + if (avail < 0) { avail = 0; + } } - avail = _min(avail, norders); + avail = MIN(avail, nreq); for (al = alist; al; al = al->next) { if (avail > 0) { int want = required(al->want, al->save); - int x = avail * want / norders; - /* Wenn Rest, dann wrfeln, ob ich was bekomme: */ - if (rng_int() % norders < (avail * want) % norders) - ++x; + int x = avail * want / nreq; + int rx = (avail * want) % nreq; + /* Wenn Rest, dann wuerfeln, ob ich was bekomme: */ + if (rx>0 && rng_int() % nreq < rx) ++x; avail -= x; - norders -= want; - al->get = _min(al->want, (int)(x / al->save)); - if (rdata->produce) { + nreq -= want; + al->get = x * al->save.sa[0] / al->save.sa[1]; + al->get = MIN(al->want, al->get); + if (!rtype->raw) { int use = required(al->get, al->save); - if (use) - rdata->produce(r, rtype, use); + if (use) { + produce_resource(r, rtype, use); + } } } } - assert(avail == 0 || norders == 0); + assert(avail == 0 || nreq == 0); } typedef void(*allocate_function) (const resource_type *, struct region *, @@ -1284,16 +1157,10 @@ typedef void(*allocate_function) (const resource_type *, struct region *, static allocate_function get_allocator(const struct resource_type *rtype) { - attrib *a = a_find(rtype->attribs, &at_resourcelimit); - - if (a != NULL) { - resource_limit *rdata = (resource_limit *)a->data.v; - if (rdata->value > 0 || rdata->limit != NULL) { - return attrib_allocation; - } + if (rtype->raw) { return leveled_allocation; } - return NULL; + return attrib_allocation; } void split_allocations(region * r) @@ -1371,11 +1238,11 @@ static void create_potion(unit * u, const potion_type * ptype, int want) } } -static void create_item(unit * u, const item_type * itype, int want) +void make_item(unit * u, const item_type * itype, int want) { if (itype->construction && fval(itype->rtype, RTF_LIMITED)) { #if GUARD_DISABLES_PRODUCTION == 1 - if (is_guarded(u->region, u, GUARD_PRODUCE)) { + if (is_guarded(u->region, u)) { cmistake(u, u->thisorder, 70, MSG_EVENT); return; } @@ -1414,7 +1281,7 @@ int make_cmd(unit * u, struct order *ord) s = gettoken(token, sizeof(token)); if (s) { - m = atoi((const char *)s); + m = atoip(s); sprintf(ibuf, "%d", m); if (!strcmp(ibuf, (const char *)s)) { /* a quantity was given */ @@ -1525,7 +1392,7 @@ int make_cmd(unit * u, struct order *ord) } } else if (itype != NULL) { - create_item(u, itype, m); + make_item(u, itype, m); } else { ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "error_cannotmake", "")); @@ -1576,15 +1443,15 @@ static void expandbuying(region * r, request * buyorders) return; /* Initialisation. multiplier ist der Multiplikator auf den - * Verkaufspreis. Fr max_products Produkte kauft man das Produkt zum - * einfachen Verkaufspreis, danach erhht sich der Multiplikator um 1. - * counter ist ein Zhler, der die gekauften Produkte zhlt. money - * wird fr die debug message gebraucht. */ + * Verkaufspreis. F�r max_products Produkte kauft man das Produkt zum + * einfachen Verkaufspreis, danach erh�ht sich der Multiplikator um 1. + * counter ist ein Z�hler, der die gekauften Produkte z�hlt. money + * wird f�r die debug message gebraucht. */ max_products = rpeasants(r) / TRADE_FRACTION; - /* Kauf - auch so programmiert, da er leicht erweiterbar auf mehrere - * Gter pro Monat ist. j sind die Befehle, i der Index des + /* Kauf - auch so programmiert, da� er leicht erweiterbar auf mehrere + * G�ter pro Monat ist. j sind die Befehle, i der Index des * gehandelten Produktes. */ if (max_products > 0) { unsigned int j; @@ -1594,22 +1461,22 @@ static void expandbuying(region * r, request * buyorders) for (j = 0; j != norders; j++) { int price, multi; - ltype = oa[j].type.ltype; + ltype = g_requests[j].type.ltype; trade = trades; while (trade->type != ltype) ++trade; multi = trade->multi; price = ltype->price * multi; - if (get_pooled(oa[j].unit, rsilver, GET_DEFAULT, + if (get_pooled(g_requests[j].unit, rsilver, GET_DEFAULT, price) >= price) { - unit *u = oa[j].unit; + unit *u = g_requests[j].unit; item *items; - /* litems zhlt die Gter, die verkauft wurden, u->n das Geld, das - * verdient wurde. Dies mu gemacht werden, weil der Preis stndig sinkt, + /* litems z�hlt die G�ter, die verkauft wurden, u->n das Geld, das + * verdient wurde. Dies mu� gemacht werden, weil der Preis st�ndig sinkt, * man sich also das verdiente Geld und die verkauften Produkte separat - * merken mu. */ + * merken mu�. */ attrib *a = a_find(u->attribs, &at_luxuries); if (a == NULL) a = a_add(&u->attribs, a_new(&at_luxuries)); @@ -1617,7 +1484,7 @@ static void expandbuying(region * r, request * buyorders) items = a->data.v; i_change(&items, ltype->itype, 1); a->data.v = items; - i_change(&oa[j].unit->items, ltype->itype, 1); + i_change(&g_requests[j].unit->items, ltype->itype, 1); use_pooled(u, rsilver, GET_DEFAULT, price); if (u->n < 0) u->n = 0; @@ -1626,7 +1493,7 @@ static void expandbuying(region * r, request * buyorders) rsetmoney(r, rmoney(r) + price); /* Falls mehr als max_products Bauern ein Produkt verkauft haben, steigt - * der Preis Multiplikator fr das Produkt um den Faktor 1. Der Zhler + * der Preis Multiplikator f�r das Produkt um den Faktor 1. Der Z�hler * wird wieder auf 0 gesetzt. */ if (++trade->number == max_products) { trade->number = 0; @@ -1635,7 +1502,7 @@ static void expandbuying(region * r, request * buyorders) fset(u, UFL_LONGACTION | UFL_NOTMOVING); } } - free(oa); + free(g_requests); /* Ausgabe an Einheiten */ @@ -1677,16 +1544,16 @@ static void buy(unit * u, request ** buyorders, struct order *ord) keyword_t kwd; const char *s; - if (u->ship && is_guarded(r, u, GUARD_CREWS)) { + if (u->ship && is_guarded(r, u)) { cmistake(u, ord, 69, MSG_INCOME); return; } - if (u->ship && is_guarded(r, u, GUARD_CREWS)) { + if (u->ship && is_guarded(r, u)) { cmistake(u, ord, 69, MSG_INCOME); return; } /* Im Augenblick kann man nur 1 Produkt kaufen. expandbuying ist aber - * schon dafr ausgerstet, mehrere Produkte zu kaufen. */ + * schon daf�r ausger�stet, mehrere Produkte zu kaufen. */ kwd = init_order(ord); assert(kwd == K_BUY); @@ -1696,7 +1563,7 @@ static void buy(unit * u, request ** buyorders, struct order *ord) return; } if (besieged(u)) { - /* Belagerte Einheiten knnen nichts kaufen. */ + /* Belagerte Einheiten k�nnen nichts kaufen. */ cmistake(u, ord, 60, MSG_COMMERCE); return; } @@ -1710,7 +1577,7 @@ static void buy(unit * u, request ** buyorders, struct order *ord) } } else { - /* ...oder in der Region mu es eine Burg geben. */ + /* ...oder in der Region mu� es eine Burg geben. */ building *b = 0; if (r->buildings) { static int cache; @@ -1731,11 +1598,11 @@ static void buy(unit * u, request ** buyorders, struct order *ord) } } - /* Ein Hndler kann nur 10 Gter pro Talentpunkt handeln. */ + /* Ein H�ndler kann nur 10 G�ter pro Talentpunkt handeln. */ k = u->number * 10 * effskill(u, SK_TRADE, 0); - /* hat der Hndler bereits gehandelt, muss die Menge der bereits - * verkauften/gekauften Gter abgezogen werden */ + /* hat der H�ndler bereits gehandelt, muss die Menge der bereits + * verkauften/gekauften G�ter abgezogen werden */ a = a_find(u->attribs, &at_trades); if (!a) { a = a_add(&u->attribs, a_new(&at_trades)); @@ -1744,7 +1611,7 @@ static void buy(unit * u, request ** buyorders, struct order *ord) k -= a->data.i; } - n = _min(n, k); + n = MIN(n, k); if (!n) { cmistake(u, ord, 102, MSG_COMMERCE); @@ -1752,7 +1619,7 @@ static void buy(unit * u, request ** buyorders, struct order *ord) } assert(n >= 0); - /* die Menge der verkauften Gter merken */ + /* die Menge der verkauften G�ter merken */ a->data.i += n; s = gettoken(token, sizeof(token)); @@ -1785,7 +1652,7 @@ static void add_income(unit * u, int type, int want, int qty) "unit region mode wanted amount", u, u->region, type, want, qty)); } -/* Steuerstze in % bei Burggre */ +/* Steuers�tze in % bei Burggr��e */ static int tax_per_size[7] = { 0, 6, 12, 18, 24, 30, 36 }; static void expandselling(region * r, request * sellorders, int limit) @@ -1820,11 +1687,11 @@ static void expandselling(region * r, request * sellorders, int limit) } memset(counter, 0, sizeof(int) * ncounter); - if (!sellorders) { /* NEIN, denn Insekten knnen in || !r->buildings) */ - return; /* Smpfen und Wsten auch so handeln */ + if (!sellorders) { /* NEIN, denn Insekten k�nnen in || !r->buildings) */ + return; /* S�mpfen und W�sten auch so handeln */ } - /* Stelle Eigentmer der grten Burg fest. Bekommt Steuern aus jedem - * Verkauf. Wenn zwei Burgen gleicher Gre bekommt gar keiner etwas. */ + /* Stelle Eigent�mer der gr��ten Burg fest. Bekommt Steuern aus jedem + * Verkauf. Wenn zwei Burgen gleicher Gr��e bekommt gar keiner etwas. */ for (b = rbuildings(r); b; b = b->next) { if (b->size > maxsize && building_owner(b) != NULL && b->type == castle_bt) { @@ -1847,13 +1714,13 @@ static void expandselling(region * r, request * sellorders, int limit) maxowner = (unit *)NULL; } } - /* Die Region muss genug Geld haben, um die Produkte kaufen zu knnen. */ + /* Die Region muss genug Geld haben, um die Produkte kaufen zu k�nnen. */ money = rmoney(r); - /* max_products sind 1/100 der Bevlkerung, falls soviele Produkte + /* max_products sind 1/100 der Bev�lkerung, falls soviele Produkte * verkauft werden - counter[] - sinkt die Nachfrage um 1 Punkt. - * multiplier speichert r->demand fr die debug message ab. */ + * multiplier speichert r->demand f�r die debug message ab. */ max_products = rpeasants(r) / TRADE_FRACTION; if (max_products <= 0) @@ -1872,12 +1739,12 @@ static void expandselling(region * r, request * sellorders, int limit) for (j = 0; j != norders; j++) { const luxury_type *search = NULL; - const luxury_type *ltype = oa[j].type.ltype; + const luxury_type *ltype = g_requests[j].type.ltype; int multi = r_demand(r, ltype); int i; int use = 0; for (i = 0, search = luxurytypes; search != ltype; search = search->next) { - // TODO: this is slow and lame! + /* TODO: this is slow and lame! */ ++i; } if (counter[i] >= limit) @@ -1889,7 +1756,7 @@ static void expandselling(region * r, request * sellorders, int limit) if (money >= price) { int abgezogenhafen = 0; int abgezogensteuer = 0; - unit *u = oa[j].unit; + unit *u = g_requests[j].unit; item *itm; attrib *a = a_find(u->attribs, &at_luxuries); if (a == NULL) @@ -1921,11 +1788,11 @@ static void expandselling(region * r, request * sellorders, int limit) change_money(u, price); fset(u, UFL_LONGACTION | UFL_NOTMOVING); - /* r->money -= price; --- dies wird eben nicht ausgefhrt, denn die - * Produkte knnen auch als Steuern eingetrieben werden. In der Region - * wurden Silberstcke gegen Luxusgter des selben Wertes eingetauscht! + /* r->money -= price; --- dies wird eben nicht ausgef�hrt, denn die + * Produkte k�nnen auch als Steuern eingetrieben werden. In der Region + * wurden Silberst�cke gegen Luxusg�ter des selben Wertes eingetauscht! * Falls mehr als max_products Kunden ein Produkt gekauft haben, sinkt - * die Nachfrage fr das Produkt um 1. Der Zhler wird wieder auf 0 + * die Nachfrage f�r das Produkt um 1. Der Z�hler wird wieder auf 0 * gesetzt. */ if (++counter[i] > max_products) { @@ -1937,12 +1804,12 @@ static void expandselling(region * r, request * sellorders, int limit) } } if (use > 0) { - use_pooled(oa[j].unit, ltype->itype->rtype, GET_DEFAULT, use); + use_pooled(g_requests[j].unit, ltype->itype->rtype, GET_DEFAULT, use); } } - free(oa); + free(g_requests); - /* Steuern. Hier werden die Steuern dem Besitzer der grten Burg gegeben. */ + /* Steuern. Hier werden die Steuern dem Besitzer der gr��ten Burg gegeben. */ if (maxowner) { if (taxcollected > 0) { change_money(maxowner, (int)taxcollected); @@ -1995,11 +1862,11 @@ static bool sell(unit * u, request ** sellorders, struct order *ord) caravan_bt = bt_find("caravan"); } - if (u->ship && is_guarded(r, u, GUARD_CREWS)) { + if (u->ship && is_guarded(r, u)) { cmistake(u, ord, 69, MSG_INCOME); return false; } - /* sellorders sind KEIN array, weil fr alle items DIE SELBE resource + /* sellorders sind KEIN array, weil f�r alle items DIE SELBE resource * (das geld der region) aufgebraucht wird. */ kwd = init_order(ord); @@ -2018,19 +1885,19 @@ static bool sell(unit * u, request ** sellorders, struct order *ord) } } else { - n = s ? atoi(s) : 0; + n = s ? atoip(s) : 0; if (n == 0) { cmistake(u, ord, 27, MSG_COMMERCE); return false; } } - /* Belagerte Einheiten knnen nichts verkaufen. */ + /* Belagerte Einheiten k�nnen nichts verkaufen. */ if (besieged(u)) { ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "error60", "")); return false; } - /* In der Region mu es eine Burg geben. */ + /* In der Region mu� es eine Burg geben. */ if (u_race(u) == get_race(RC_INSECT)) { if (r->terrain != newterrain(T_SWAMP) && r->terrain != newterrain(T_DESERT) @@ -2040,7 +1907,7 @@ static bool sell(unit * u, request ** sellorders, struct order *ord) } } else { - /* ...oder in der Region mu es eine Burg geben. */ + /* ...oder in der Region mu� es eine Burg geben. */ building *b = 0; if (r->buildings) { for (b = r->buildings; b; b = b->next) { @@ -2053,9 +1920,9 @@ static bool sell(unit * u, request ** sellorders, struct order *ord) } } - /* Ein Hndler kann nur 10 Gter pro Talentpunkt verkaufen. */ + /* Ein H�ndler kann nur 10 G�ter pro Talentpunkt verkaufen. */ - n = _min(n, u->number * 10 * effskill(u, SK_TRADE, 0)); + n = MIN(n, u->number * 10 * effskill(u, SK_TRADE, 0)); if (!n) { cmistake(u, ord, 54, MSG_COMMERCE); @@ -2064,7 +1931,7 @@ static bool sell(unit * u, request ** sellorders, struct order *ord) s = gettoken(token, sizeof(token)); itype = s ? finditemtype(s, u->faction->locale) : 0; ltype = itype ? resource2luxury(itype->rtype) : 0; - if (ltype == NULL) { + if (ltype == NULL || itype == NULL) { cmistake(u, ord, 126, MSG_COMMERCE); return false; } @@ -2079,33 +1946,33 @@ static bool sell(unit * u, request ** sellorders, struct order *ord) } available = get_pooled(u, itype->rtype, GET_DEFAULT, INT_MAX); - /* Wenn andere Einheiten das selbe verkaufen, mu ihr Zeug abgezogen + /* Wenn andere Einheiten das selbe verkaufen, mu� ihr Zeug abgezogen * werden damit es nicht zweimal verkauft wird: */ for (o = *sellorders; o; o = o->next) { if (o->type.ltype == ltype && o->unit->faction == u->faction) { int fpool = o->qty - get_pooled(o->unit, itype->rtype, GET_RESERVE, INT_MAX); - available -= _max(0, fpool); + available -= MAX(0, fpool); } } - n = _min(n, available); + n = MIN(n, available); if (n <= 0) { cmistake(u, ord, 264, MSG_COMMERCE); return false; } /* Hier wird request->type verwendet, weil die obere limit durch - * das silber gegeben wird (region->money), welches fr alle + * das silber gegeben wird (region->money), welches f�r alle * (!) produkte als summe gilt, als nicht wie bei der - * produktion, wo fr jedes produkt einzeln eine obere limite + * produktion, wo f�r jedes produkt einzeln eine obere limite * existiert, so dass man arrays von orders machen kann. */ - /* Ein Hndler kann nur 10 Gter pro Talentpunkt handeln. */ + /* Ein H�ndler kann nur 10 G�ter pro Talentpunkt handeln. */ k = u->number * 10 * effskill(u, SK_TRADE, 0); - /* hat der Hndler bereits gehandelt, muss die Menge der bereits - * verkauften/gekauften Gter abgezogen werden */ + /* hat der H�ndler bereits gehandelt, muss die Menge der bereits + * verkauften/gekauften G�ter abgezogen werden */ a = a_find(u->attribs, &at_trades); if (!a) { a = a_add(&u->attribs, a_new(&at_trades)); @@ -2114,9 +1981,9 @@ static bool sell(unit * u, request ** sellorders, struct order *ord) k -= a->data.i; } - n = _min(n, k); + n = MIN(n, k); assert(n >= 0); - /* die Menge der verkauften Gter merken */ + /* die Menge der verkauften G�ter merken */ a->data.i += n; o = (request *)calloc(1, sizeof(request)); o->unit = u; @@ -2140,14 +2007,14 @@ static void expandstealing(region * r, request * stealorders) expandorders(r, stealorders); if (!norders) return; - /* Fr jede unit in der Region wird Geld geklaut, wenn sie Opfer eines - * Beklauen-Orders ist. Jedes Opfer mu einzeln behandelt werden. + /* F�r jede unit in der Region wird Geld geklaut, wenn sie Opfer eines + * Beklauen-Orders ist. Jedes Opfer mu� einzeln behandelt werden. * * u ist die beklaute unit. oa.unit ist die klauende unit. */ - for (j = 0; j != norders && oa[j].unit->n <= oa[j].unit->wants; j++) { - unit *u = findunitg(oa[j].no, r); + for (j = 0; j != norders && g_requests[j].unit->n <= g_requests[j].unit->wants; j++) { + unit *u = findunitg(g_requests[j].no, r); int n = 0; if (u && u->region == r) { n = get_pooled(u, rsilver, GET_ALL, INT_MAX); @@ -2171,17 +2038,17 @@ static void expandstealing(region * r, request * stealorders) n = 10; } if (n > 0) { - n = _min(n, oa[j].unit->wants); + n = MIN(n, g_requests[j].unit->wants); use_pooled(u, rsilver, GET_ALL, n); - oa[j].unit->n = n; - change_money(oa[j].unit, n); + g_requests[j].unit->n = n; + change_money(g_requests[j].unit, n); ADDMSG(&u->faction->msgs, msg_message("stealeffect", "unit region amount", u, u->region, n)); } - add_income(oa[j].unit, IC_STEAL, oa[j].unit->wants, oa[j].unit->n); - fset(oa[j].unit, UFL_LONGACTION | UFL_NOTMOVING); + add_income(g_requests[j].unit, IC_STEAL, g_requests[j].unit->wants, g_requests[j].unit->n); + fset(g_requests[j].unit, UFL_LONGACTION | UFL_NOTMOVING); } - free(oa); + free(g_requests); } /* ------------------------------------------------------------- */ @@ -2196,28 +2063,28 @@ static void plant(unit * u, int raw) if (!fval(r->terrain, LAND_REGION)) { return; } - if (rherbtype(r) == NULL) { + itype = rherbtype(r); + if (itype == NULL) { cmistake(u, u->thisorder, 108, MSG_PRODUCE); return; } - /* Skill prfen */ + /* Skill pr�fen */ skill = effskill(u, SK_HERBALISM, 0); - itype = rherbtype(r); if (skill < 6) { ADDMSG(&u->faction->msgs, msg_feedback(u, u->thisorder, "plant_skills", "skill minskill product", SK_HERBALISM, 6, itype->rtype, 1)); return; } - /* Wasser des Lebens prfen */ + /* Wasser des Lebens pr�fen */ if (get_pooled(u, rt_water, GET_DEFAULT, 1) == 0) { ADDMSG(&u->faction->msgs, msg_feedback(u, u->thisorder, "resource_missing", "missing", rt_water)); return; } n = get_pooled(u, itype->rtype, GET_DEFAULT, skill * u->number); - /* Kruter prfen */ + /* Kr�uter pr�fen */ if (n == 0) { ADDMSG(&u->faction->msgs, msg_feedback(u, u->thisorder, "resource_missing", "missing", @@ -2225,9 +2092,9 @@ static void plant(unit * u, int raw) return; } - n = _min(skill * u->number, n); - n = _min(raw, n); - /* Fr jedes Kraut Talent*10% Erfolgschance. */ + n = MIN(skill * u->number, n); + n = MIN(raw, n); + /* F�r jedes Kraut Talent*10% Erfolgschance. */ for (i = n; i > 0; i--) { if (rng_int() % 10 < skill) planted++; @@ -2252,10 +2119,10 @@ static void planttrees(unit * u, int raw) return; } - /* Mallornbume kann man nur in Mallornregionen zchten */ + /* Mallornb�ume kann man nur in Mallornregionen z�chten */ rtype = get_resourcetype(fval(r, RF_MALLORN) ? R_MALLORNSEED : R_SEED); - /* Skill prfen */ + /* Skill pr�fen */ skill = effskill(u, SK_HERBALISM, 0); if (skill < 6) { ADDMSG(&u->faction->msgs, @@ -2271,16 +2138,16 @@ static void planttrees(unit * u, int raw) } /* wenn eine Anzahl angegeben wurde, nur soviel verbrauchen */ - raw = _min(raw, skill * u->number); + raw = MIN(raw, skill * u->number); n = get_pooled(u, rtype, GET_DEFAULT, raw); if (n == 0) { ADDMSG(&u->faction->msgs, msg_feedback(u, u->thisorder, "resource_missing", "missing", rtype)); return; } - n = _min(raw, n); + n = MIN(raw, n); - /* Fr jeden Samen Talent*10% Erfolgschance. */ + /* F�r jeden Samen Talent*10% Erfolgschance. */ for (i = n; i > 0; i--) { if (rng_int() % 10 < skill) planted++; @@ -2295,7 +2162,7 @@ static void planttrees(unit * u, int raw) "unit region amount herb", u, r, planted, rtype)); } -/* zchte bume */ +/* z�chte b�ume */ static void breedtrees(unit * u, int raw) { int n, i, skill, planted = 0; @@ -2307,7 +2174,7 @@ static void breedtrees(unit * u, int raw) get_gamedate(turn, &date); current_season = date.season; - /* Bume zchten geht nur im Frhling */ + /* B�ume z�chten geht nur im Fr�hling */ if (current_season != SEASON_SPRING) { planttrees(u, raw); return; @@ -2317,10 +2184,10 @@ static void breedtrees(unit * u, int raw) return; } - /* Mallornbume kann man nur in Mallornregionen zchten */ + /* Mallornb�ume kann man nur in Mallornregionen z�chten */ rtype = get_resourcetype(fval(r, RF_MALLORN) ? R_MALLORNSEED : R_SEED); - /* Skill prfen */ + /* Skill pr�fen */ skill = effskill(u, SK_HERBALISM, 0); if (skill < 12) { planttrees(u, raw); @@ -2328,17 +2195,17 @@ static void breedtrees(unit * u, int raw) } /* wenn eine Anzahl angegeben wurde, nur soviel verbrauchen */ - raw = _min(skill * u->number, raw); + raw = MIN(skill * u->number, raw); n = get_pooled(u, rtype, GET_DEFAULT, raw); - /* Samen prfen */ + /* Samen pr�fen */ if (n == 0) { ADDMSG(&u->faction->msgs, msg_feedback(u, u->thisorder, "resource_missing", "missing", rtype)); return; } - n = _min(raw, n); + n = MIN(raw, n); - /* Fr jeden Samen Talent*5% Erfolgschance. */ + /* F�r jeden Samen Talent*5% Erfolgschance. */ for (i = n; i > 0; i--) { if (rng_int() % 100 < skill * 5) planted++; @@ -2353,7 +2220,7 @@ static void breedtrees(unit * u, int raw) "unit region amount herb", u, r, planted, rtype)); } -/* zchte pferde */ +/* z�chte pferde */ static void breedhorses(unit * u) { int n, c, breed = 0; @@ -2378,7 +2245,7 @@ static void breedhorses(unit * u) } effsk = effskill(u, SK_HORSE_TRAINING, 0); n = u->number * effsk; - n = _min(n, horses); + n = MIN(n, horses); for (c = 0; c < n; c++) { if (rng_int() % 100 < effsk) { @@ -2406,11 +2273,11 @@ static void breed_cmd(unit * u, struct order *ord) return; } - /* zchte [] */ + /* z�chte [] */ (void)init_order(ord); s = gettoken(token, sizeof(token)); - m = s ? atoi((const char *)s) : 0; + m = s ? atoip(s) : 0; if (m != 0) { /* first came a want-paramter */ s = gettoken(token, sizeof(token)); @@ -2568,8 +2435,8 @@ static void steal_cmd(unit * u, struct order *ord, request ** stealorders) f = u2->faction; } else { - // TODO: is this really necessary? it's the only time we use faction.c/deadhash - // it allows stealing from a unit in a dead faction, but why? + /* TODO: is this really necessary? it's the only time we use faction.c/deadhash + * it allows stealing from a unit in a dead faction, but why? */ f = dfindhash(id); } @@ -2627,7 +2494,7 @@ static void steal_cmd(unit * u, struct order *ord, request ** stealorders) } } - i = _min(u->number, i_get(u->items, rring->itype)); + i = MIN(u->number, i_get(u->items, rring->itype)); if (i > 0) { n *= STEALINCOME * (u->number + i * (roqf_factor() - 1)); } @@ -2649,7 +2516,7 @@ static void steal_cmd(unit * u, struct order *ord, request ** stealorders) /* Nur soviel PRODUCEEXP wie auch tatsaechlich gemacht wurde */ - produceexp(u, SK_STEALTH, _min(n, u->number)); + produceexp(u, SK_STEALTH, MIN(n, u->number)); } /* ------------------------------------------------------------- */ @@ -2672,8 +2539,8 @@ static void expandentertainment(region * r) m -= u->n; entertaining -= o->qty; - /* Nur soviel PRODUCEEXP wie auch tatschlich gemacht wurde */ - produceexp(u, SK_ENTERTAINMENT, _min(u->n, u->number)); + /* Nur soviel PRODUCEEXP wie auch tats�chlich gemacht wurde */ + produceexp(u, SK_ENTERTAINMENT, MIN(u->n, u->number)); add_income(u, IC_ENTERTAIN, o->qty, u->n); fset(u, UFL_LONGACTION | UFL_NOTMOVING); } @@ -2710,7 +2577,7 @@ void entertain_cmd(unit * u, struct order *ord) cmistake(u, ord, 60, MSG_INCOME); return; } - if (u->ship && is_guarded(r, u, GUARD_CREWS)) { + if (u->ship && is_guarded(r, u)) { cmistake(u, ord, 69, MSG_INCOME); return; } @@ -2724,7 +2591,7 @@ void entertain_cmd(unit * u, struct order *ord) max_e = getuint(); if (max_e != 0) { - u->wants = _min(u->wants, max_e); + u->wants = MIN(u->wants, max_e); } o = nextentertainer++; o->unit = u; @@ -2756,8 +2623,9 @@ expandwork(region * r, request * work_begin, request * work_end, int maxwork) if (jobs >= working) workers = u->number; else { + int r = (u->number * jobs) % working; workers = u->number * jobs / working; - if (rng_int() % working < (u->number * jobs) % working) + if (r > 0 && rng_int() % working < r) workers++; } @@ -2784,7 +2652,7 @@ expandwork(region * r, request * work_begin, request * work_end, int maxwork) if (blessedharvest_ct) { int happy = (int)curse_geteffect(get_curse(r->attribs, blessedharvest_ct)); - happy = _min(happy, jobs); + happy = MIN(happy, jobs); earnings += happy; } } @@ -2807,7 +2675,7 @@ static int do_work(unit * u, order * ord, request * o) cmistake(u, ord, 60, MSG_INCOME); return -1; } - if (u->ship && is_guarded(r, u, GUARD_CREWS)) { + if (u->ship && is_guarded(r, u)) { if (ord) cmistake(u, ord, 69, MSG_INCOME); return -1; @@ -2830,7 +2698,7 @@ static void expandloot(region * r, request * lootorders) { unit *u; unsigned int i; - int looted = 0; + int m, looted = 0; int startmoney = rmoney(r); expandorders(r, lootorders); @@ -2838,18 +2706,18 @@ static void expandloot(region * r, request * lootorders) return; for (i = 0; i != norders && startmoney > looted + TAXFRACTION * 2; i++) { - change_money(oa[i].unit, TAXFRACTION); - oa[i].unit->n += TAXFRACTION; + change_money(g_requests[i].unit, TAXFRACTION); + g_requests[i].unit->n += TAXFRACTION; /*Looting destroys double the money*/ looted += TAXFRACTION * 2; } rsetmoney(r, startmoney - looted); - free(oa); + free(g_requests); /* Lowering morale by 1 depending on the looted money (+20%) */ - if (rng_int() % 100 < 20 + (looted * 80) / startmoney) { - int m = region_get_morale(r); - if (m) { + m = region_get_morale(r); + if (m && startmoney>0) { + if (rng_int() % 100 < 20 + (looted * 80) / startmoney) { /*Nur Moral -1, turns is not changed, so the first time nothing happens if the morale is good*/ region_set_morale(r, m - 1, -1); } @@ -2873,11 +2741,11 @@ void expandtax(region * r, request * taxorders) return; for (i = 0; i != norders && rmoney(r) > TAXFRACTION; i++) { - change_money(oa[i].unit, TAXFRACTION); - oa[i].unit->n += TAXFRACTION; + change_money(g_requests[i].unit, TAXFRACTION); + g_requests[i].unit->n += TAXFRACTION; rsetmoney(r, rmoney(r) - TAXFRACTION); } - free(oa); + free(g_requests); for (u = r->units; u; u = u->next) { if (u->n >= 0) { @@ -2938,13 +2806,13 @@ void tax_cmd(unit * u, struct order *ord, request ** taxorders) max = INT_MAX; } if (!playerrace(u_race(u))) { - u->wants = _min(income(u), max); + u->wants = MIN(income(u), max); } else { - u->wants = _min(n * effskill(u, SK_TAXING, 0) * taxperlevel, max); + u->wants = MIN(n * effskill(u, SK_TAXING, 0) * taxperlevel, max); } - u2 = is_guarded(r, u, GUARD_TAX); + u2 = is_guarded(r, u); if (u2) { ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "region_guarded", "guard", u2)); @@ -2999,7 +2867,7 @@ void loot_cmd(unit * u, struct order *ord, request ** lootorders) return; } - u2 = is_guarded(r, u, GUARD_TAX); + u2 = is_guarded(r, u); if (u2) { ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "region_guarded", "guard", u2)); @@ -3012,12 +2880,12 @@ void loot_cmd(unit * u, struct order *ord, request ** lootorders) max = INT_MAX; } if (!playerrace(u_race(u))) { - u->wants = _min(income(u), max); + u->wants = MIN(income(u), max); } else { /* For player start with 20 Silver +10 every 5 level of close combat skill*/ - int skbonus = (_max(effskill(u, SK_MELEE, 0), effskill(u, SK_SPEAR, 0)) * 2 / 10) + 2; - u->wants = _min(n * skbonus * 10, max); + int skbonus = (MAX(effskill(u, SK_MELEE, 0), effskill(u, SK_SPEAR, 0)) * 2 / 10) + 2; + u->wants = MIN(n * skbonus * 10, max); } o = (request *)calloc(1, sizeof(request)); @@ -3044,7 +2912,7 @@ void auto_work(region * r) } } if (nextworker != workers) { - expandwork(r, workers, nextworker, maxworkingpeasants(r)); + expandwork(r, workers, nextworker, region_maxworkers(r)); } } @@ -3075,9 +2943,10 @@ static void peasant_taxes(region * r) maxsize = buildingeffsize(b, false); if (maxsize > 0) { double taxfactor = money * b->type->taxes(b, maxsize); - double morale = money * region_get_morale(r) * MORALE_TAX_FACTOR; - if (taxfactor > morale) + double morale = MORALE_TAX_FACTOR * money * region_get_morale(r); + if (taxfactor > morale) { taxfactor = morale; + } if (taxfactor > 0) { int taxmoney = (int)taxfactor; change_money(u, taxmoney); @@ -3243,12 +3112,12 @@ void produce(struct region *r) /* Entertainment (expandentertainment) und Besteuerung (expandtax) vor den * Befehlen, die den Bauern mehr Geld geben, damit man aus den Zahlen der - * letzten Runde berechnen kann, wieviel die Bauern fr Unterhaltung + * letzten Runde berechnen kann, wieviel die Bauern f�r Unterhaltung * auszugeben bereit sind. */ if (entertaining) expandentertainment(r); if (!rule_autowork()) { - expandwork(r, workers, nextworker, maxworkingpeasants(r)); + expandwork(r, workers, nextworker, region_maxworkers(r)); } if (taxorders) expandtax(r, taxorders); @@ -3258,7 +3127,7 @@ void produce(struct region *r) /* An erster Stelle Kaufen (expandbuying), die Bauern so Geld bekommen, um * nachher zu beim Verkaufen (expandselling) den Spielern abkaufen zu - * knnen. */ + * k�nnen. */ if (buyorders) expandbuying(r, buyorders); diff --git a/src/economy.h b/src/economy.h index 4bce314a9..7b0eed8c9 100644 --- a/src/economy.h +++ b/src/economy.h @@ -48,6 +48,7 @@ extern "C" { struct request; int income(const struct unit *u); + int entertainmoney(const struct region *r); void economics(struct region *r); void produce(struct region *r); @@ -55,6 +56,7 @@ extern "C" { enum { IC_WORK, IC_ENTERTAIN, IC_TAX, IC_TRADE, IC_TRADETAX, IC_STEAL, IC_MAGIC, IC_LOOT }; void maintain_buildings(struct region *r); + void make_item(struct unit * u, const struct item_type * itype, int want); int make_cmd(struct unit *u, struct order *ord); void split_allocations(struct region *r); int give_control_cmd(struct unit *u, struct order *ord); diff --git a/src/economy.test.c b/src/economy.test.c index fbcc720bc..8b1b0b0fa 100644 --- a/src/economy.test.c +++ b/src/economy.test.c @@ -11,10 +11,12 @@ #include #include #include +#include #include #include #include +#include #include #include @@ -209,7 +211,7 @@ static void test_tax_cmd(CuTest *tc) { silver = get_resourcetype(R_SILVER)->itype; sword = it_get_or_create(rt_get_or_create("sword")); - new_weapontype(sword, 0, 0.0, NULL, 0, 0, 0, SK_MELEE, 1); + new_weapontype(sword, 0, frac_zero, NULL, 0, 0, 0, SK_MELEE, 1); i_change(&u->items, sword, 1); set_level(u, SK_MELEE, 1); @@ -241,11 +243,15 @@ static void test_tax_cmd(CuTest *tc) { test_cleanup(); } +/** + * see https://bugs.eressea.de/view.php?id=2234 + */ static void test_maintain_buildings(CuTest *tc) { region *r; building *b; building_type *btype; unit *u; + faction *f; maintenance *req; item_type *itype; @@ -253,39 +259,53 @@ static void test_maintain_buildings(CuTest *tc) { btype = test_create_buildingtype("Hort"); btype->maxsize = 10; r = test_create_region(0, 0, 0); - u = test_create_unit(test_create_faction(0), r); + f = test_create_faction(0); + u = test_create_unit(f, r); b = test_create_building(r, btype); itype = test_create_itemtype("money"); b->size = btype->maxsize; u_set_building(u, b); - // this building has no upkeep, it just works: + /* this building has no upkeep, it just works: */ b->flags = 0; maintain_buildings(r); CuAssertIntEquals(tc, BLD_MAINTAINED, fval(b, BLD_MAINTAINED)); + CuAssertPtrEquals(tc, 0, f->msgs); + CuAssertPtrEquals(tc, 0, r->msgs); req = calloc(2, sizeof(maintenance)); req[0].number = 100; req[0].rtype = itype->rtype; btype->maintenance = req; - // we cannot afford to pay: + /* we cannot afford to pay: */ b->flags = 0; maintain_buildings(r); CuAssertIntEquals(tc, 0, fval(b, BLD_MAINTAINED)); - - // we can afford to pay: + CuAssertPtrNotNull(tc, test_find_messagetype(f->msgs, "maintenancefail")); + CuAssertPtrNotNull(tc, test_find_messagetype(r->msgs, "maintenance_nowork")); + test_clear_messagelist(&f->msgs); + test_clear_messagelist(&r->msgs); + + /* we can afford to pay: */ i_change(&u->items, itype, 100); b->flags = 0; maintain_buildings(r); CuAssertIntEquals(tc, BLD_MAINTAINED, fval(b, BLD_MAINTAINED)); CuAssertIntEquals(tc, 0, i_get(u->items, itype)); + CuAssertPtrEquals(tc, 0, r->msgs); + CuAssertPtrEquals(tc, 0, test_find_messagetype(f->msgs, "maintenance_nowork")); + CuAssertPtrNotNull(tc, test_find_messagetype(f->msgs, "maintenance")); + test_clear_messagelist(&f->msgs); - // this building has no owner, it doesn't work: + /* this building has no owner, it doesn't work: */ u_set_building(u, NULL); b->flags = 0; maintain_buildings(r); CuAssertIntEquals(tc, 0, fval(b, BLD_MAINTAINED)); + CuAssertPtrEquals(tc, 0, f->msgs); + CuAssertPtrNotNull(tc, test_find_messagetype(r->msgs, "maintenance_noowner")); + test_clear_messagelist(&r->msgs); test_cleanup(); } @@ -310,11 +330,97 @@ static void test_recruit(CuTest *tc) { test_cleanup(); } +static void test_income(CuTest *tc) +{ + race *rc; + unit *u; + test_setup(); + rc = test_create_race("nerd"); + u = test_create_unit(test_create_faction(rc), test_create_region(0, 0, 0)); + CuAssertIntEquals(tc, 20, income(u)); + u->number = 5; + CuAssertIntEquals(tc, 100, income(u)); + test_cleanup(); +} + +static void test_make_item(CuTest *tc) { + unit *u; + struct item_type *itype; + const struct resource_type *rt_silver; + resource_type *rtype; + double d = 0.6; + + test_setup(); + init_resources(); + + /* make items from other items (turn silver to stone) */ + rt_silver = get_resourcetype(R_SILVER); + itype = test_create_itemtype("stone"); + rtype = itype->rtype; + u = test_create_unit(test_create_faction(0), test_create_region(0,0,0)); + make_item(u, itype, 1); + CuAssertPtrNotNull(tc, test_find_messagetype(u->faction->msgs, "error_cannotmake")); + CuAssertIntEquals(tc, 0, get_item(u, itype)); + test_clear_messages(u->faction); + itype->construction = calloc(1, sizeof(construction)); + itype->construction->skill = SK_ALCHEMY; + itype->construction->minskill = 1; + itype->construction->maxsize = 1; + itype->construction->reqsize = 1; + itype->construction->materials = calloc(2, sizeof(requirement)); + itype->construction->materials[0].rtype = rt_silver; + itype->construction->materials[0].number = 1; + set_level(u, SK_ALCHEMY, 1); + set_item(u, rt_silver->itype, 1); + make_item(u, itype, 1); + CuAssertIntEquals(tc, 1, get_item(u, itype)); + CuAssertIntEquals(tc, 0, get_item(u, rt_silver->itype)); + + /* make level-based raw materials, no materials used in construction */ + free(itype->construction->materials); + itype->construction->materials = 0; + rtype->flags |= RTF_LIMITED; + rmt_create(rtype); + add_resource(u->region, 1, 300, 150, rtype); + u->region->resources->amount = 300; /* there are 300 stones at level 1 */ + set_level(u, SK_ALCHEMY, 10); + + make_item(u, itype, 10); + split_allocations(u->region); + CuAssertIntEquals(tc, 11, get_item(u, itype)); + CuAssertIntEquals(tc, 290, u->region->resources->amount); /* used 10 stones to make 10 stones */ + + rtype->modifiers = calloc(2, sizeof(resource_mod)); + rtype->modifiers[0].flags = RMF_SAVEMATERIAL; + rtype->modifiers[0].race = u->_race; + rtype->modifiers[0].value.sa[0] = (short)(0.5+100*d); + rtype->modifiers[0].value.sa[1] = 100; + make_item(u, itype, 10); + split_allocations(u->region); + CuAssertIntEquals(tc, 21, get_item(u, itype)); + CuAssertIntEquals(tc, 284, u->region->resources->amount); /* 60% saving = 6 stones make 10 stones */ + + make_item(u, itype, 1); + split_allocations(u->region); + CuAssertIntEquals(tc, 22, get_item(u, itype)); + CuAssertIntEquals(tc, 283, u->region->resources->amount); /* no free lunches */ + + rtype->modifiers[0].flags = RMF_REQUIREDBUILDING; + rtype->modifiers[0].race = NULL; + rtype->modifiers[0].btype = bt_get_or_create("mine"); + make_item(u, itype, 10); + CuAssertPtrNotNull(tc, test_find_messagetype(u->faction->msgs, "error104")); + + test_cleanup(); +} + CuSuite *get_economy_suite(void) { CuSuite *suite = CuSuiteNew(); SUITE_ADD_TEST(suite, test_give_control_building); SUITE_ADD_TEST(suite, test_give_control_ship); + SUITE_ADD_TEST(suite, test_income); + SUITE_ADD_TEST(suite, test_make_item); SUITE_ADD_TEST(suite, test_steal_okay); SUITE_ADD_TEST(suite, test_steal_ocean); SUITE_ADD_TEST(suite, test_steal_nosteal); diff --git a/src/eressea.c b/src/eressea.c index dead153cb..2d53c2511 100755 --- a/src/eressea.c +++ b/src/eressea.c @@ -8,9 +8,6 @@ #if MUSEUM_MODULE #include #endif -#if ARENA_MODULE -#include -#endif #include #include #include @@ -21,7 +18,9 @@ #include #include #include -#include +#include +#include + #include #include #include @@ -75,13 +74,11 @@ void game_init(void) register_itemfunctions(); #if MUSEUM_MODULE register_museum(); -#endif -#if ARENA_MODULE - register_arena(); #endif wormholes_register(); - register_itemtypes(); + register_weapons(); + register_xerewards(); #ifdef USE_LIBXML2 register_xmlreader(); #endif diff --git a/src/game.pkg b/src/game.pkg index 88b3bda9a..dc2b324e4 100644 --- a/src/game.pkg +++ b/src/game.pkg @@ -1,6 +1,5 @@ $#undef tolua_reg_types $#define tolua_reg_types tolua_reg_types_game -$#include "config.h" $#include "bind_eressea.h" module eressea { diff --git a/src/game.pkg.c b/src/game.pkg.c index abd7832ca..30671021d 100644 --- a/src/game.pkg.c +++ b/src/game.pkg.c @@ -20,7 +20,6 @@ LUALIB_API int luaopen_game (lua_State* tolua_S); #undef tolua_reg_types #define tolua_reg_types tolua_reg_types_game -#include "config.h" #include "bind_eressea.h" /* function to register type */ diff --git a/src/give.c b/src/give.c index 80f4a1ab5..5cd19710e 100644 --- a/src/give.c +++ b/src/give.c @@ -1,4 +1,4 @@ -/* +/* +-------------------+ Christian Schlittchen | | Enno Rehling | Eressea PBEM host | Katja Zedel @@ -19,6 +19,7 @@ /* kernel includes */ #include +#include #include #include #include @@ -34,7 +35,6 @@ /* attributes includes */ #include -#include /* util includes */ #include @@ -71,8 +71,8 @@ static bool can_give(const unit * u, const unit * u2, const item_type * itype, i { if (u2) { if (u2->number==0 && !fval(u2, UFL_ISNEW)) { - // https://bugs.eressea.de/view.php?id=2230 - // cannot give anything to dead units + /* https://bugs.eressea.de/view.php?id=2230 + * cannot give anything to dead units */ return false; } else if (u->faction != u2->faction) { int rule = rule_give(); @@ -138,7 +138,7 @@ int give_quota(const unit * src, const unit * dst, const item_type * type, } if (dst && src && src->faction != dst->faction) { divisor = config_get_flt("rules.items.give_divisor", 1); - assert(divisor == 0 || divisor >= 1); + assert(divisor <= 0 || divisor >= 1); if (divisor >= 1) { /* predictable > correct: */ int x = (int)(n / divisor); @@ -148,17 +148,35 @@ int give_quota(const unit * src, const unit * dst, const item_type * type, return n; } +static void +give_horses(unit * s, const item_type * itype, int n) +{ + region *r = s->region; + if (r->land) { + rsethorses(r, rhorses(r) + n); + } +} + +static void +give_money(unit * s, const item_type * itype, int n) +{ + region *r = s->region; + if (r->land) { + rsetmoney(r, rmoney(r) + n); + } +} + int give_item(int want, const item_type * itype, unit * src, unit * dest, struct order *ord) { short error = 0; - int n, r; + int n, delta; assert(itype != NULL); n = get_pooled(src, item2resource(itype), GET_SLACK | GET_POOLED_SLACK, want); - n = _min(want, n); - r = n; + n = MIN(want, n); + delta = n; if (dest && src->faction != dest->faction && src->faction->age < GiveRestriction()) { if (ord != NULL) { @@ -179,18 +197,19 @@ struct order *ord) else if (itype->flags & ITF_CURSED) { error = 25; } - else if (itype->give == NULL || itype->give(src, dest, itype, n, ord) != 0) { + else { int use = use_pooled(src, item2resource(itype), GET_SLACK, n); + if (use < n) use += use_pooled(src, item2resource(itype), GET_POOLED_SLACK, n - use); if (dest) { - r = give_quota(src, dest, itype, n); - i_change(&dest->items, itype, r); + delta = give_quota(src, dest, itype, n); + i_change(&dest->items, itype, delta); #ifdef RESERVE_GIVE #ifdef RESERVE_DONATIONS - change_reservation(dest, itype, r); + change_reservation(dest, itype, delta); #else if (src->faction == dest->faction) { change_reservation(dest, item2resource(itype), r); @@ -200,14 +219,25 @@ struct order *ord) #if MUSEUM_MODULE && defined(TODO) /* TODO: use a trigger for the museum warden! */ if (a_find(dest->attribs, &at_warden)) { - warden_add_give(src, dest, itype, r); + warden_add_give(src, dest, itype, delta); } #endif handle_event(dest->attribs, "receive", src); } + else { + /* return horses to the region */ + if (itype->construction && itype->flags & ITF_ANIMAL) { + if (itype->construction->skill == SK_HORSE_TRAINING) { + give_horses(src, itype, n); + } + } + else if (itype->rtype == get_resourcetype(R_SILVER)) { + give_money(src, itype, n); + } + } handle_event(src->attribs, "give", dest); } - add_give(src, dest, n, r, item2resource(itype), ord, error); + add_give(src, dest, n, delta, item2resource(itype), ord, error); if (error) return -1; return 0; @@ -224,12 +254,8 @@ static bool unit_has_cursed_item(const unit * u) return false; } -static bool can_give_men(const unit *u, order *ord, message **msg) { - if (u_race(u) == get_race(RC_SNOTLING)) { - /* snotlings may not be given to the peasants. */ - if (msg) *msg = msg_error(u, ord, 307); - } - else if (unit_has_cursed_item(u)) { +static bool can_give_men(const unit *u, const unit *dst, order *ord, message **msg) { + if (unit_has_cursed_item(u)) { if (msg) *msg = msg_error(u, ord, 78); } else if (has_skill(u, SK_MAGIC)) { @@ -263,9 +289,9 @@ message * give_men(int n, unit * u, unit * u2, struct order *ord) message * msg; int maxt = max_transfers(); - assert(u2); + assert(u2); /* use disband_men for GIVE 0 */ - if (!can_give_men(u, ord, &msg)) { + if (!can_give_men(u, u2, ord, &msg)) { return msg; } @@ -400,20 +426,21 @@ message * give_men(int n, unit * u, unit * u2, struct order *ord) message * disband_men(int n, unit * u, struct order *ord) { message * msg; + static const race *rc_snotling; + static int rccache; - if (!can_give_men(u, ord, &msg)) { + if (rc_changed(&rccache)) { + rc_snotling = get_race(RC_SNOTLING); + } + + if (u_race(u) == rc_snotling) { + /* snotlings may not be given to the peasants. */ + return msg_error(u, ord, 307); + } + if (!can_give_men(u, NULL, ord, &msg)) { return msg; } transfermen(u, NULL, n); -#ifdef ORCIFICATION - if (u_race(u) == get_race(RC_SNOTLING) && !fval(u->region, RF_ORCIFIED)) { - attrib *a = a_find(u->region->attribs, &at_orcification); - if (!a) { - a = a_add(&u->region->attribs, a_new(&at_orcification)); - } - a->data.i += n; - } -#endif if (fval(u->region->terrain, SEA_REGION)) { return msg_message("give_person_ocean", "unit amount", u, n); } @@ -604,16 +631,19 @@ void give_cmd(unit * u, order * ord) } if (u2 && u_race(u2) == get_race(RC_SPELL)) { - ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "feedback_unit_not_found", - "")); + ADDMSG(&u->faction->msgs, msg_feedback(u, ord, + "feedback_unit_not_found", "")); return; } - else if (u2 && !alliedunit(u2, u->faction, HELP_GIVE) && !ucontact(u2, u)) { cmistake(u, ord, 40, MSG_COMMERCE); return; } - + else if (p == NOPARAM) { + /* the most likely case: giving items to someone. + * let's catch this and save ourselves the rest of the param_t checks. + */ + } else if (p == P_HERBS) { bool given = false; if ((u_race(u)->ec_flags & ECF_KEEP_ITEM) && u2 != NULL) { @@ -773,7 +803,7 @@ void give_cmd(unit * u, order * ord) msg_feedback(u, ord, "race_noregroup", "race", u_race(u))); return; } - n = _min(u->number, n); + n = MIN(u->number, n); msg = u2 ? give_men(n, u, u2, ord) : disband_men(n, u, ord); if (msg) { ADDMSG(&u->faction->msgs, msg); @@ -782,7 +812,7 @@ void give_cmd(unit * u, order * ord) } if (u2 != NULL) { - if ((u_race(u)->ec_flags & ECF_KEEP_ITEM) && u2 != NULL) { + if ((u_race(u)->ec_flags & ECF_KEEP_ITEM)) { ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "race_nogive", "race", u_race(u))); return; diff --git a/src/give.h b/src/give.h index 9c06e89ca..94eee729c 100644 --- a/src/give.h +++ b/src/give.h @@ -12,6 +12,9 @@ */ #ifndef H_GC_GIVE #define H_GC_GIVE + +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/src/give.test.c b/src/give.test.c index e65c2861c..fbb71cf3c 100644 --- a/src/give.test.c +++ b/src/give.test.c @@ -23,6 +23,7 @@ #include struct give { + struct locale * lang; struct unit *src, *dst; struct region *r; struct faction *f1, *f2; @@ -46,11 +47,16 @@ static void setup_give(struct give *env) { ally * al = ally_add(&env->f2->allies, env->f1); al->status = HELP_GIVE; } + if (env->lang) { + locale_setstring(env->lang, env->itype->rtype->_name, "SILBER"); + init_locale(env->lang); + env->f1->locale = env->lang; + } } static void test_give_unit_to_peasants(CuTest * tc) { - struct give env; - test_cleanup(); + struct give env = { 0 }; + test_setup_ex(tc); env.f1 = test_create_faction(0); env.f2 = 0; setup_give(&env); @@ -62,8 +68,8 @@ static void test_give_unit_to_peasants(CuTest * tc) { } static void test_give_unit(CuTest * tc) { - struct give env; - test_cleanup(); + struct give env = { 0 }; + test_setup_ex(tc); env.f1 = test_create_faction(0); env.f2 = test_create_faction(0); setup_give(&env); @@ -81,8 +87,8 @@ static void test_give_unit(CuTest * tc) { } static void test_give_unit_in_ocean(CuTest * tc) { - struct give env; - test_cleanup(); + struct give env = { 0 }; + test_setup_ex(tc); env.f1 = test_create_faction(0); env.f2 = 0; setup_give(&env); @@ -93,8 +99,8 @@ static void test_give_unit_in_ocean(CuTest * tc) { } static void test_give_men(CuTest * tc) { - struct give env; - test_cleanup(); + struct give env = { 0 }; + test_setup_ex(tc); env.f2 = env.f1 = test_create_faction(0); setup_give(&env); CuAssertPtrEquals(tc, 0, give_men(1, env.src, env.dst, NULL)); @@ -103,10 +109,35 @@ static void test_give_men(CuTest * tc) { test_cleanup(); } -static void test_give_men_limit(CuTest * tc) { - struct give env; - message *msg; +static void test_give_men_magicians(CuTest * tc) { + struct give env = { 0 }; + int p; + message * msg; + + test_setup_ex(tc); + env.f2 = env.f1 = test_create_faction(0); + setup_give(&env); + set_level(env.src, SK_MAGIC, 1); + CuAssertPtrNotNull(tc, msg = give_men(1, env.src, env.dst, NULL)); + CuAssertStrEquals(tc, "error158", (const char *)msg->parameters[3].v); + CuAssertIntEquals(tc, 1, env.dst->number); + CuAssertIntEquals(tc, 1, env.src->number); + msg_release(msg); + + p = rpeasants(env.r); + CuAssertPtrNotNull(tc, msg = disband_men(1, env.dst, NULL)); + CuAssertStrEquals(tc, "give_person_peasants", (const char *)msg->parameters[0].v); + CuAssertIntEquals(tc, 0, env.dst->number); + CuAssertIntEquals(tc, p+1, rpeasants(env.r)); + msg_release(msg); + test_cleanup(); +} + +static void test_give_men_limit(CuTest * tc) { + struct give env = { 0 }; + message *msg; + test_setup_ex(tc); env.f2 = test_create_faction(0); env.f1 = test_create_faction(0); setup_give(&env); @@ -134,10 +165,10 @@ static void test_give_men_limit(CuTest * tc) { } static void test_give_men_in_ocean(CuTest * tc) { - struct give env; + struct give env = { 0 }; message * msg; - test_cleanup(); + test_setup_ex(tc); env.f1 = test_create_faction(0); env.f2 = 0; setup_give(&env); @@ -150,8 +181,8 @@ static void test_give_men_in_ocean(CuTest * tc) { } static void test_give_men_too_many(CuTest * tc) { - struct give env; - test_cleanup(); + struct give env = { 0 }; + test_setup_ex(tc); env.f2 = env.f1 = test_create_faction(0); setup_give(&env); CuAssertPtrEquals(tc, 0, give_men(2, env.src, env.dst, NULL)); @@ -161,10 +192,10 @@ static void test_give_men_too_many(CuTest * tc) { } static void test_give_men_none(CuTest * tc) { - struct give env; + struct give env = { 0 }; message * msg; - test_cleanup(); + test_setup_ex(tc); env.f2 = env.f1 = test_create_faction(0); setup_give(&env); msg = give_men(0, env.src, env.dst, NULL); @@ -176,10 +207,10 @@ static void test_give_men_none(CuTest * tc) { } static void test_give_men_other_faction(CuTest * tc) { - struct give env; + struct give env = { 0 }; message * msg; - test_cleanup(); + test_setup_ex(tc); env.f1 = test_create_faction(0); env.f2 = test_create_faction(0); setup_give(&env); @@ -193,12 +224,11 @@ static void test_give_men_other_faction(CuTest * tc) { } static void test_give_men_requires_contact(CuTest * tc) { - struct give env; + struct give env = { 0 }; message * msg; order *ord; - char cmd[32]; - test_cleanup(); + test_setup_ex(tc); env.f1 = test_create_faction(0); env.f2 = test_create_faction(0); setup_give(&env); @@ -207,8 +237,7 @@ static void test_give_men_requires_contact(CuTest * tc) { CuAssertIntEquals(tc, 1, env.dst->number); CuAssertIntEquals(tc, 1, env.src->number); - _snprintf(cmd, sizeof(cmd), "%s ALLES PERSONEN", itoa36(env.dst->no)); - ord = create_order(K_GIVE, env.f1->locale, cmd); + ord = create_order(K_GIVE, env.f1->locale, "%s ALLES PERSONEN", itoa36(env.dst->no)); test_clear_messages(env.f1); give_cmd(env.src, ord); CuAssertPtrEquals(tc, 0, test_find_messagetype(env.f1->msgs, "give_person")); @@ -220,9 +249,9 @@ static void test_give_men_requires_contact(CuTest * tc) { } static void test_give_men_not_to_self(CuTest * tc) { - struct give env; + struct give env = { 0 }; message * msg; - test_cleanup(); + test_setup_ex(tc); env.f2 = env.f1 = test_create_faction(0); setup_give(&env); msg = give_men(1, env.src, env.src, NULL); @@ -233,10 +262,10 @@ static void test_give_men_not_to_self(CuTest * tc) { } static void test_give_peasants(CuTest * tc) { - struct give env; + struct give env = { 0 }; message * msg; - test_cleanup(); + test_setup_ex(tc); env.f1 = test_create_faction(0); env.f2 = 0; setup_give(&env); @@ -250,9 +279,9 @@ static void test_give_peasants(CuTest * tc) { } static void test_give(CuTest * tc) { - struct give env; + struct give env = { 0 }; - test_cleanup(); + test_setup_ex(tc); env.f2 = env.f1 = test_create_faction(0); setup_give(&env); @@ -267,19 +296,38 @@ static void test_give(CuTest * tc) { test_cleanup(); } -static void test_give_herbs(CuTest * tc) { - struct give env; +static void test_give_cmd(CuTest * tc) { + struct give env = { 0 }; struct order *ord; - char cmd[32]; + test_setup_ex(tc); + env.lang = test_create_locale(); + env.f2 = env.f1 = test_create_faction(0); + setup_give(&env); + + i_change(&env.src->items, env.itype, 10); + + ord = create_order(K_GIVE, env.f1->locale, "%s 5 %s", itoa36(env.dst->no), LOC(env.f1->locale, env.itype->rtype->_name)); + assert(ord); + give_cmd(env.src, ord); + CuAssertIntEquals(tc, 5, i_get(env.src->items, env.itype)); + CuAssertIntEquals(tc, 5, i_get(env.dst->items, env.itype)); + + free_order(ord); test_cleanup(); +} + +static void test_give_herbs(CuTest * tc) { + struct give env = { 0 }; + struct order *ord; + + test_setup_ex(tc); test_create_world(); env.f2 = env.f1 = test_create_faction(0); setup_give(&env); i_change(&env.src->items, env.itype, 10); - _snprintf(cmd, sizeof(cmd), "%s %s", itoa36(env.dst->no), LOC(env.f1->locale, parameters[P_HERBS])); - ord = create_order(K_GIVE, env.f1->locale, cmd); + ord = create_order(K_GIVE, env.f1->locale, "%s %s", itoa36(env.dst->no), LOC(env.f1->locale, parameters[P_HERBS])); assert(ord); give_cmd(env.src, ord); @@ -290,9 +338,9 @@ static void test_give_herbs(CuTest * tc) { } static void test_give_okay(CuTest * tc) { - struct give env; + struct give env = { 0 }; - test_cleanup(); + test_setup_ex(tc); env.f2 = env.f1 = test_create_faction(0); setup_give(&env); @@ -302,10 +350,10 @@ static void test_give_okay(CuTest * tc) { } static void test_give_denied_by_rules(CuTest * tc) { - struct give env; + struct give env = { 0 }; struct message *msg; - test_cleanup(); + test_setup_ex(tc); env.f1 = test_create_faction(0); env.f2 = test_create_faction(0); setup_give(&env); @@ -317,10 +365,10 @@ static void test_give_denied_by_rules(CuTest * tc) { } static void test_give_dead_unit(CuTest * tc) { - struct give env; + struct give env = { 0 }; struct message *msg; - test_cleanup(); + test_setup_ex(tc); env.f1 = test_create_faction(0); env.f2 = test_create_faction(0); setup_give(&env); @@ -332,9 +380,9 @@ static void test_give_dead_unit(CuTest * tc) { } static void test_give_new_unit(CuTest * tc) { - struct give env; + struct give env = { 0 }; - test_cleanup(); + test_setup_ex(tc); env.f1 = test_create_faction(0); env.f2 = test_create_faction(0); setup_give(&env); @@ -345,11 +393,11 @@ static void test_give_new_unit(CuTest * tc) { } static void test_give_invalid_target(CuTest *tc) { - // bug https://bugs.eressea.de/view.php?id=1685 - struct give env; + /* bug https://bugs.eressea.de/view.php?id=1685 */ + struct give env = { 0 }; order *ord; - test_cleanup(); + test_setup_ex(tc); env.f1 = test_create_faction(0); env.f2 = 0; setup_give(&env); @@ -369,7 +417,9 @@ CuSuite *get_give_suite(void) { CuSuite *suite = CuSuiteNew(); SUITE_ADD_TEST(suite, test_give); + SUITE_ADD_TEST(suite, test_give_cmd); SUITE_ADD_TEST(suite, test_give_men); + SUITE_ADD_TEST(suite, test_give_men_magicians); SUITE_ADD_TEST(suite, test_give_men_limit); SUITE_ADD_TEST(suite, test_give_men_in_ocean); SUITE_ADD_TEST(suite, test_give_men_none); diff --git a/src/gmtool.c b/src/gmtool.c index 47b7794a2..148aafe6d 100644 --- a/src/gmtool.c +++ b/src/gmtool.c @@ -26,9 +26,6 @@ #if MUSEUM_MODULE #include #endif -#if ARENA_MODULE -#include -#endif #include #include @@ -47,7 +44,6 @@ #include #include -#include #include #include @@ -87,7 +83,7 @@ static void unicode_remove_diacritics(const char *rp, char *wp) { while (*rp) { if (gm_codepage >=0 && *rp & 0x80) { size_t sz = 0; - char ch; + unsigned char ch; switch (gm_codepage) { case 1252: unicode_utf8_to_cp1252(&ch, rp, &sz); @@ -100,7 +96,7 @@ static void unicode_remove_diacritics(const char *rp, char *wp) { break; } rp += sz; - *wp++ = ch; + *wp++ = (char)ch; } else { *wp++ = *rp++; @@ -184,7 +180,7 @@ map_region *mr_get(const view * vi, int xofs, int yofs) static point *coor2point(const coordinate * c, point * p) { assert(c && p); - p->x = c->x * TWIDTH + c->y * TWIDTH / 2; + p->x = c->x * TWIDTH + c->y * TWIDTH / 2; /*-V537 */ p->y = c->y * THEIGHT; return p; } @@ -262,7 +258,7 @@ static chtype mr_tile(const map_region * mr, int highlight) const region *r = mr->r; switch (r->terrain->_name[0]) { case 'o': - return '.' | COLOR_PAIR(hl + COLOR_CYAN) | A_BOLD; + return '.' | COLOR_PAIR(hl + COLOR_CYAN) | A_BOLD; /*-V525 */ case 'd': return 'D' | COLOR_PAIR(hl + COLOR_YELLOW) | A_BOLD; case 't': @@ -427,7 +423,7 @@ static void paint_info_region(window * wnd, const state * st) int line = 0, maxline = getmaxy(win) - 2; map_region *mr = cursor_region(&st->display, &st->cursor); - unused_arg(st); + UNUSED_ARG(st); werase(win); wxborder(win); if (mr && mr->r) { @@ -823,8 +819,7 @@ void loaddata(state *st) { askstring(st->wnd_status->handle, "save as:", datafile, sizeof(datafile)); if (strlen(datafile) > 0) { - create_backup(datafile); - readgame(datafile, false); + readgame(datafile); st->modified = 0; } } @@ -834,7 +829,6 @@ void savedata(state *st) { askstring(st->wnd_status->handle, "save as:", datafile, sizeof(datafile)); if (strlen(datafile) > 0) { - create_backup(datafile); remove_empty_units(); writegame(datafile); st->modified = 0; @@ -1169,7 +1163,7 @@ static void handlekey(state * st, int c) region *first = (mr && mr->r && mr->r->next) ? mr->r->next : regions; if (findmode == 'f') { - sprintf(sbuffer, "find-faction: %s", locate); + slprintf(sbuffer, sizeof(sbuffer), "find-faction: %s", locate); statusline(st->wnd_status->handle, sbuffer); f = findfaction(atoi36(locate)); if (f == NULL) { @@ -1400,7 +1394,7 @@ int curses_readline(struct lua_State *L, char *buffer, size_t size, const char *prompt) { - unused_arg(L); + UNUSED_ARG(L); askstring(hstatus, prompt, buffer, size); return buffer[0] != 0; } diff --git a/src/guard.c b/src/guard.c index da879fa53..07640452c 100644 --- a/src/guard.c +++ b/src/guard.c @@ -1,4 +1,4 @@ -/* +/* Copyright (c) 1998-2015, Enno Rehling Katja Zedel #include #include "guard.h" +#include "laws.h" +#include "monsters.h" -#include +#include #include #include #include #include #include -#include #include -attrib_type at_guard = { - "guard", - DEFAULT_INIT, - DEFAULT_FINALIZE, - DEFAULT_AGE, - a_writeint, - a_readint, - NULL, - ATF_UNIQUE -}; +guard_t can_start_guarding(const unit * u) +{ + if (u->status >= ST_FLEE || fval(u, UFL_FLEEING)) + return E_GUARD_FLEEING; + /* Monster der Monsterpartei duerfen immer bewachen */ + if (is_monsters(u->faction) || fval(u_race(u), RCF_UNARMEDGUARD)) + return E_GUARD_OK; + if (!armedmen(u, true)) + return E_GUARD_UNARMED; + if (IsImmune(u->faction)) + return E_GUARD_NEWBIE; + return E_GUARD_OK; +} void update_guards(void) { @@ -51,97 +55,102 @@ void update_guards(void) for (u = r->units; u; u = u->next) { if (fval(u, UFL_GUARD)) { if (can_start_guarding(u) != E_GUARD_OK) { - setguard(u, GUARD_NONE); - } - else { - attrib *a = a_find(u->attribs, &at_guard); - if (a && a->data.i == (int)guard_flags(u)) { - /* this is really rather not necessary */ - a_remove(&u->attribs, a); - } + setguard(u, false); } } } } } -unsigned int guard_flags(const unit * u) +void setguard(unit * u, bool enabled) { - // TODO: this should be a property of the race, like race.guard_flags - static int rc_cache; - static const race *rc_elf, *rc_ent, *rc_ironkeeper; - const race *rc = u_race(u); - unsigned int flags = - GUARD_CREWS | GUARD_LANDING | GUARD_TRAVELTHRU | GUARD_TAX; - // TODO: configuration, not define -#if GUARD_DISABLES_PRODUCTION == 1 - flags |= GUARD_PRODUCE; -#endif -#if GUARD_DISABLES_RECRUIT == 1 - flags |= GUARD_RECRUIT; -#endif - if (rc_changed(&rc_cache)) { - rc_elf = get_race(RC_ELF); - rc_ent = get_race(RC_TREEMAN); - rc_ironkeeper = get_race(RC_IRONKEEPER); + if (!enabled) { + freset(u, UFL_GUARD); + } else { + assert(!fval(u, UFL_MOVED)); + assert(u->status < ST_FLEE); + fset(u, UFL_GUARD); + fset(u->region, RF_GUARDED); } - if (rc == rc_elf) { - if (u->faction->race == u_race(u)) { - flags |= GUARD_TREES; +} + +void guard(unit * u) +{ + setguard(u, true); +} + +static bool is_guardian_u(const unit * guard, unit * u) +{ + if (guard->faction == u->faction) + return false; + if (is_guard(guard) == 0) + return false; + if (alliedunit(guard, u->faction, HELP_GUARD)) + return false; + if (ucontact(guard, u)) + return false; + if (!cansee(guard->faction, u->region, u, 0)) + return false; + if (!(u_race(guard)->flags & RCF_FLY) && u_race(u)->flags & RCF_FLY) + return false; + + return true; +} + +static bool is_guardian_r(const unit * guard) +{ + if (guard->number == 0) + return false; + if (besieged(guard)) + return false; + + /* if region_owners exist then they may be guardians: */ + if (guard->building && rule_region_owners() && guard == building_owner(guard->building)) { + faction *owner = region_get_owner(guard->region); + if (owner == guard->faction) { + building *bowner = largestbuilding(guard->region, &cmp_taxes, false); + if (bowner == guard->building) { + return true; + } } } - else if (rc == rc_ent) { - flags |= GUARD_TREES; - } - else if (rc == rc_ironkeeper) { - flags = GUARD_MINING; - } - return flags; + + if ((guard->flags & UFL_GUARD) == 0) + return false; + return fval(u_race(guard), RCF_UNARMEDGUARD) || is_monsters(guard->faction) || (armedmen(guard, true) > 0); } -void setguard(unit * u, unsigned int flags) +bool is_guard(const struct unit * u) { - /* setzt die guard-flags der Einheit */ - attrib *a = NULL; - assert(flags == 0 || !fval(u, UFL_MOVED)); - assert(flags == 0 || u->status < ST_FLEE); - if (fval(u, UFL_GUARD)) { - a = a_find(u->attribs, &at_guard); - } - if (flags == GUARD_NONE) { - freset(u, UFL_GUARD); - if (a) - a_remove(&u->attribs, a); - return; - } - fset(u, UFL_GUARD); - fset(u->region, RF_GUARDED); - if (flags == guard_flags(u)) { - if (a) - a_remove(&u->attribs, a); - } - else { - if (!a) - a = a_add(&u->attribs, a_new(&at_guard)); - a->data.i = (int)flags; - } + return is_guardian_r(u); } -unsigned int getguard(const unit * u) +unit *is_guarded(region * r, unit * u) { - attrib *a; + unit *u2; + bool noguards = true; - assert(fval(u, UFL_GUARD) || (u->building && u == building_owner(u->building)) - || !"you're doing it wrong! check is_guard first"); - a = a_find(u->attribs, &at_guard); - if (a) { - return (unsigned int)a->data.i; + if (!fval(r, RF_GUARDED)) { + return NULL; } - return guard_flags(u); -} -void guard(unit * u, unsigned int mask) -{ - unsigned int flags = guard_flags(u); - setguard(u, flags & mask); + /* at this point, u2 is the last unit we tested to + * be a guard (and failed), or NULL + * i is the position of the first free slot in the cache */ + + for (u2 = r->units; u2; u2 = u2->next) { + if (is_guardian_r(u2)) { + noguards = false; + if (is_guardian_u(u2, u)) { + /* u2 is our guard. stop processing (we might have to go further next time) */ + return u2; + } + } + } + + if (noguards) { + /* you are mistaken, sir. there are no guards in these lands */ + freset(r, RF_GUARDED); + } + return NULL; } diff --git a/src/guard.h b/src/guard.h index 564be61a2..101369f40 100644 --- a/src/guard.h +++ b/src/guard.h @@ -1,24 +1,26 @@ -#pragma once +#pragma once #ifndef H_GUARD #define H_GUARD + +#include + #ifdef __cplusplus extern "C" { #endif struct unit; - + struct region; + typedef enum { E_GUARD_OK, E_GUARD_UNARMED, E_GUARD_NEWBIE, E_GUARD_FLEEING } guard_t; - extern struct attrib_type at_guard; - guard_t can_start_guarding(const struct unit * u); void update_guards(void); - unsigned int guard_flags(const struct unit * u); - unsigned int getguard(const struct unit * u); - void setguard(struct unit * u, unsigned int flags); + void setguard(struct unit * u, bool enabled); + void guard(struct unit *u); - void guard(struct unit * u, unsigned int mask); + struct unit *is_guarded(struct region *r, struct unit *u); + bool is_guard(const struct unit *u); #ifdef __cplusplus } diff --git a/src/guard.test.c b/src/guard.test.c new file mode 100644 index 000000000..17aa2891c --- /dev/null +++ b/src/guard.test.c @@ -0,0 +1,141 @@ +#include + +#include "guard.h" +#include "laws.h" +#include "monsters.h" + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include "tests.h" + +static void test_is_guarded(CuTest *tc) { + unit *u1, *u2; + region *r; + race *rc; + + test_cleanup(); + rc = rc_get_or_create("dragon"); + rc->flags |= RCF_UNARMEDGUARD; + r = test_create_region(0, 0, 0); + u1 = test_create_unit(test_create_faction(0), r); + u2 = test_create_unit(test_create_faction(rc), r); + CuAssertPtrEquals(tc, 0, is_guarded(r, u1)); + setguard(u2, true); + CuAssertPtrEquals(tc, u2, is_guarded(r, u1)); + test_cleanup(); +} + +static void test_guard_unskilled(CuTest * tc) +/* TODO: it would be better to test armedmen() */ +{ + unit *u, *ug; + region *r; + item_type *itype; + + test_setup(); + itype = it_get_or_create(rt_get_or_create("sword")); + new_weapontype(itype, 0, frac_zero, NULL, 0, 0, 0, SK_MELEE, 2); + r = test_create_region(0, 0, 0); + u = test_create_unit(test_create_faction(0), r); + ug = test_create_unit(test_create_faction(0), r); + i_change(&ug->items, itype, 1); + set_level(ug, SK_MELEE, 1); + setguard(ug, true); + CuAssertPtrEquals(tc, 0, is_guarded(r, u)); + test_cleanup(); +} + +static void test_guard_armed(CuTest * tc) +{ + unit *u, *ug; + region *r; + item_type *itype; + + test_setup(); + itype = it_get_or_create(rt_get_or_create("sword")); + new_weapontype(itype, 0, frac_zero, NULL, 0, 0, 0, SK_MELEE, 2); + r = test_create_region(0, 0, 0); + u = test_create_unit(test_create_faction(0), r); + ug = test_create_unit(test_create_faction(0), r); + i_change(&ug->items, itype, 1); + set_level(ug, SK_MELEE, 2); + setguard(ug, true); + CuAssertPtrEquals(tc, ug, is_guarded(r, u)); + test_cleanup(); +} + +static void test_is_guard(CuTest * tc) +{ + unit *ug; + region *r; + item_type *itype; + + test_setup(); + itype = it_get_or_create(rt_get_or_create("sword")); + new_weapontype(itype, 0, frac_zero, NULL, 0, 0, 0, SK_MELEE, 2); + r = test_create_region(0, 0, 0); + ug = test_create_unit(test_create_faction(0), r); + i_change(&ug->items, itype, 1); + set_level(ug, SK_MELEE, 2); + setguard(ug, true); + CuAssertIntEquals(tc, 1, armedmen(ug, false)); + CuAssertTrue(tc, is_guard(ug)); + set_level(ug, SK_MELEE, 1); + CuAssertIntEquals(tc, 0, armedmen(ug, false)); + CuAssertTrue(tc, !is_guard(ug)); + set_level(ug, SK_MELEE, 2); + CuAssertIntEquals(tc, 1, armedmen(ug, false)); + CuAssertTrue(tc, is_guard(ug)); + test_cleanup(); +} + +static void test_guard_unarmed(CuTest * tc) +{ + unit *u, *ug; + region *r; + race *rc; + + test_setup(); + rc = test_create_race("mountainguard"); + rc->flags |= RCF_UNARMEDGUARD; + r = test_create_region(0, 0, 0); + u = test_create_unit(test_create_faction(0), r); + ug = test_create_unit(test_create_faction(rc), r); + setguard(ug, true); + CuAssertPtrEquals(tc, ug, is_guarded(r, u)); + test_cleanup(); +} + +static void test_guard_monsters(CuTest * tc) +{ + unit *u, *ug; + region *r; + + test_setup(); + r = test_create_region(0, 0, 0); + u = test_create_unit(test_create_faction(0), r); + ug = test_create_unit(get_monsters(), r); + setguard(ug, true); + CuAssertPtrEquals(tc, ug, is_guarded(r, u)); + test_cleanup(); +} + +CuSuite *get_guard_suite(void) +{ + CuSuite *suite = CuSuiteNew(); + SUITE_ADD_TEST(suite, test_is_guarded); + SUITE_ADD_TEST(suite, test_is_guard); + SUITE_ADD_TEST(suite, test_guard_unskilled); + SUITE_ADD_TEST(suite, test_guard_armed); + SUITE_ADD_TEST(suite, test_guard_unarmed); + SUITE_ADD_TEST(suite, test_guard_monsters); + return suite; +} diff --git a/src/helpers.c b/src/helpers.c index aa9bc12eb..402ecdd48 100644 --- a/src/helpers.c +++ b/src/helpers.c @@ -13,6 +13,7 @@ without prior permission by the authors of Eressea. #include #include "helpers.h" #include "vortex.h" +#include "alchemy.h" #include #include @@ -27,6 +28,7 @@ without prior permission by the authors of Eressea. #include #include #include +#include #include #include #include @@ -78,7 +80,7 @@ lua_giveitem(unit * s, unit * d, const item_type * itype, int n, struct order *o return result; } -static int limit_resource(const region * r, const resource_type * rtype) +static int limit_resource_lua(const region * r, const resource_type * rtype) { char fname[64]; int result = -1; @@ -110,7 +112,7 @@ static int limit_resource(const region * r, const resource_type * rtype) } static void -produce_resource(region * r, const resource_type * rtype, int norders) +produce_resource_lua(region * r, const resource_type * rtype, int norders) { lua_State *L = (lua_State *)global.vm_state; char fname[64]; @@ -167,7 +169,7 @@ static int lua_callspell(castorder * co) if (hashpos != NULL) { ptrdiff_t len = hashpos - fname; assert(len < (ptrdiff_t) sizeof(fbuf)); - strncpy(fbuf, fname, len); + memcpy(fbuf, fname, len); fbuf[len] = '\0'; fname = fbuf; } @@ -318,34 +320,6 @@ static int lua_getresource(unit * u, const struct resource_type *rtype) return result; } -static bool lua_canuse_item(const unit * u, const struct item_type *itype) -{ - bool result = true; - lua_State *L = (lua_State *)global.vm_state; - const char *fname = "item_canuse"; - - lua_getglobal(L, fname); - if (lua_isfunction(L, -1)) { - tolua_pushusertype(L, (void *)u, TOLUA_CAST "unit"); - tolua_pushstring(L, itype->rtype->_name); - - if (lua_pcall(L, 2, 1, 0) != 0) { - const char *error = lua_tostring(L, -1); - log_error("use(%s) calling '%s': %s.\n", unitname(u), fname, error); - lua_pop(L, 1); - } - else { - result = lua_toboolean(L, -1); - lua_pop(L, 1); - } - } - else { - log_error("use(%s) calling '%s': not a function.\n", unitname(u), fname); - lua_pop(L, 1); - } - return result; -} - static int lua_wage(const region * r, const faction * f, const race * rc, int in_turn) { @@ -489,17 +463,22 @@ static int lua_equipmentcallback(const struct equipment *eq, unit * u) } /** callback for an item-use function written in lua. */ -int -lua_useitem(struct unit *u, const struct item_type *itype, int amount, -struct order *ord) +static int +use_item_lua(unit *u, const item_type *itype, int amount, struct order *ord) { lua_State *L = (lua_State *)global.vm_state; int result = 0; char fname[64]; + int (*callout)(unit *, const item_type *, int, struct order *); strlcpy(fname, "use_", sizeof(fname)); strlcat(fname, itype->rtype->_name, sizeof(fname)); + callout = (int(*)(unit *, const item_type *, int, struct order *))get_function(fname); + if (callout) { + return callout(u, itype, amount, ord); + } + lua_getglobal(L, fname); if (lua_isfunction(L, -1)) { tolua_pushusertype(L, (void *)u, TOLUA_CAST "unit"); @@ -515,11 +494,15 @@ struct order *ord) result = (int)lua_tonumber(L, -1); lua_pop(L, 1); } + return result; } - else { - log_error("use(%s) calling '%s': not a function.\n", unitname(u), fname); - lua_pop(L, 1); + lua_pop(L, 1); + if (itype->rtype->ptype) { + return use_potion(u, itype, amount, ord); + } else { + log_error("no such callout: %s", fname); } + log_error("use(%s) calling '%s': not a function.\n", unitname(u), fname); return result; } @@ -550,11 +533,8 @@ void register_tolua_helpers(void) register_function((pf_generic)lua_callspell, TOLUA_CAST "lua_castspell"); register_function((pf_generic)lua_initfamiliar, TOLUA_CAST "lua_initfamiliar"); - register_item_use(&lua_useitem, TOLUA_CAST "lua_useitem"); register_function((pf_generic)lua_getresource, TOLUA_CAST "lua_getresource"); - register_function((pf_generic)lua_canuse_item, - TOLUA_CAST "lua_canuse_item"); register_function((pf_generic)lua_changeresource, TOLUA_CAST "lua_changeresource"); register_function((pf_generic)lua_equipmentcallback, @@ -564,9 +544,8 @@ void register_tolua_helpers(void) register_function((pf_generic)lua_maintenance, TOLUA_CAST "lua_maintenance"); - register_function((pf_generic)produce_resource, - TOLUA_CAST "lua_produceresource"); - register_function((pf_generic)limit_resource, - TOLUA_CAST "lua_limitresource"); + item_use_fun = use_item_lua; + res_produce_fun = produce_resource_lua; + res_limit_fun = limit_resource_lua; register_item_give(lua_giveitem, TOLUA_CAST "lua_giveitem"); } diff --git a/src/items.c b/src/items.c index 5e9a357e6..78f6e3188 100644 --- a/src/items.c +++ b/src/items.c @@ -1,8 +1,9 @@ #include -#include #include "items.h" +#include "alchemy.h" #include "study.h" +#include "economy.h" #include "move.h" #include "magic.h" @@ -14,16 +15,24 @@ #include #include #include +#include #include #include #include #include -#include +#include + +/* triggers includes */ +#include +#include #include +#include +#include #include #include +#include #include #include @@ -34,7 +43,7 @@ static int use_studypotion(struct unit *u, const struct item_type *itype, int amount, struct order *ord) { - if (init_order(u->thisorder) == K_STUDY) { + if (u->thisorder && init_order(u->thisorder) == K_STUDY) { char token[128]; skill_t sk = NOSKILL; skill *sv = 0; @@ -61,9 +70,9 @@ struct order *ord) if (amount > MAXGAIN) { amount = MAXGAIN; } - teach->value += amount * 30; - if (teach->value > MAXGAIN * 30) { - teach->value = MAXGAIN * 30; + teach->value += amount * STUDYDAYS; + if (teach->value > MAXGAIN * STUDYDAYS) { + teach->value = MAXGAIN * STUDYDAYS; } i_change(&u->items, itype, -amount); return 0; @@ -71,7 +80,6 @@ struct order *ord) } return EUNUSABLE; } - /* END studypotion */ /* BEGIN speedsail */ @@ -89,9 +97,8 @@ struct order *ord) } effect = SPEEDSAIL_EFFECT; - c = - create_curse(u, &sh->attribs, ct_find("shipspeedup"), 20, INT_MAX, effect, - 0); + c = create_curse(u, &sh->attribs, ct_find("shipspeedup"), 20, INT_MAX, + effect, 0); c_setflag(c, CURSE_NOAGE); ADDMSG(&u->faction->msgs, msg_message("use_speedsail", "unit speed", u, @@ -114,31 +121,30 @@ struct order *ord) const resource_type *rt_crystal = NULL; int i; - if (rt_crystal == NULL) { - rt_crystal = rt_find("antimagic"); - assert(rt_crystal != NULL); - } + rt_crystal = rt_find("antimagic"); + assert(rt_crystal != NULL); + for (i = 0; i != amount; ++i) { int effect, duration = 2; double force; spell *sp = find_spell("antimagiczone"); attrib **ap = &r->attribs; - unused_arg(ord); + UNUSED_ARG(ord); assert(sp); - /* Reduziert die Strke jedes Spruchs um effect */ + /* Reduziert die St�rke jedes Spruchs um effect */ effect = 5; - /* Hlt Sprche bis zu einem summierten Gesamtlevel von power aus. + /* H�lt Spr�che bis zu einem summierten Gesamtlevel von power aus. * Jeder Zauber reduziert die 'Lebenskraft' (vigour) der Antimagiezone * um seine Stufe */ force = effect * 20; /* Stufe 5 =~ 100 */ - /* Regionszauber auflsen */ + /* Regionszauber aufl�sen */ while (*ap && force > 0) { curse *c; attrib *a = *ap; - if (!fval(a->type, ATF_CURSE)) { + if (!(a->type->flags & ATF_CURSE)) { do { ap = &(*ap)->next; } while (*ap && a->type == (*ap)->type); @@ -146,7 +152,7 @@ struct order *ord) } c = (curse *)a->data.v; - /* Immunitt prfen */ + /* Immunit�t pr�fen */ if (c_flags(c) & CURSE_IMMUNE) { do { ap = &(*ap)->next; @@ -168,52 +174,7 @@ struct order *ord) } } use_pooled(u, rt_crystal, GET_DEFAULT, amount); - ADDMSG(&u->faction->msgs, msg_message("use_antimagiccrystal", - "unit region", u, r)); - return 0; -} - -static int -use_instantartsculpture(struct unit *u, const struct item_type *itype, -int amount, struct order *ord) -{ - building *b; - - if (u->region->land == NULL) { - ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "error_onlandonly", "")); - return -1; - } - - b = new_building(bt_find("artsculpture"), u->region, u->faction->locale); - b->size = 100; - - ADDMSG(&u->region->msgs, msg_message("artsculpture_create", "unit region", - u, u->region)); - - use_pooled(u, itype->rtype, GET_DEFAULT, 1); - - return 0; -} - -static int -use_instantartacademy(struct unit *u, const struct item_type *itype, -int amount, struct order *ord) -{ - building *b; - - if (u->region->land == NULL) { - ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "error_onlandonly", "")); - return -1; - } - - b = new_building(bt_find("artacademy"), u->region, u->faction->locale); - b->size = 100; - - ADDMSG(&u->region->msgs, msg_message("artacademy_create", "unit region", u, - u->region)); - - use_pooled(u, itype->rtype, GET_DEFAULT, 1); - + ADDMSG(&u->region->msgs, msg_message("use_antimagiccrystal", "unit", u)); return 0; } @@ -266,14 +227,204 @@ int amount, struct order *ord) return 0; } +static int +use_birthdayamulet(unit * u, const struct item_type *itype, int amount, +struct order *ord) +{ + direction_t d; + message *msg = msg_message("meow", ""); + + UNUSED_ARG(ord); + UNUSED_ARG(amount); + UNUSED_ARG(itype); + + add_message(&u->region->msgs, msg); + for (d = 0; d < MAXDIRECTIONS; d++) { + region *tr = rconnect(u->region, d); + if (tr) + add_message(&tr->msgs, msg); + } + msg_release(msg); + return 0; +} + +static int use_foolpotion(unit *u, const item_type *itype, int amount, + struct order *ord) +{ + int targetno = read_unitid(u->faction, u->region); + unit *target = findunit(targetno); + if (target == NULL || u->region != target->region) { + ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "feedback_unit_not_found", + "")); + return ECUSTOM; + } + if (effskill(u, SK_STEALTH, 0) <= effskill(target, SK_PERCEPTION, 0)) { + cmistake(u, ord, 64, MSG_EVENT); + return ECUSTOM; + } + ADDMSG(&u->faction->msgs, msg_message("givedumb", + "unit recipient amount", u, target, amount)); + + change_effect(target, itype->rtype->ptype, amount); + use_pooled(u, itype->rtype, GET_DEFAULT, amount); + return 0; +} + +static int +use_bloodpotion(struct unit *u, const struct item_type *itype, int amount, +struct order *ord) +{ + if (u->number == 0 || u_race(u) == get_race(RC_DAEMON)) { + change_effect(u, itype->rtype->ptype, 100 * amount); + } + else { + const race *irace = u_irace(u); + if (irace == u_race(u)) { + const race *rcfailure = rc_find("smurf"); + if (!rcfailure) { + rcfailure = rc_find("toad"); + } + if (rcfailure) { + trigger *trestore = trigger_changerace(u, u_race(u), irace); + if (trestore) { + int duration = 2 + rng_int() % 8; + + add_trigger(&u->attribs, "timer", trigger_timeout(duration, + trestore)); + u->irace = NULL; + u_setrace(u, rcfailure); + } + } + } + } + use_pooled(u, itype->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, + amount); + usetpotionuse(u, itype->rtype->ptype); + + ADDMSG(&u->faction->msgs, msg_message("usepotion", + "unit potion", u, itype->rtype)); + return 0; +} + +static int heal(unit * user, int effect) +{ + int req = unit_max_hp(user) * user->number - user->hp; + if (req > 0) { + req = MIN(req, effect); + effect -= req; + user->hp += req; + } + return effect; +} + +static int +use_healingpotion(struct unit *user, const struct item_type *itype, int amount, +struct order *ord) +{ + int effect = amount * 400; + unit *u = user->region->units; + effect = heal(user, effect); + while (effect > 0 && u != NULL) { + if (u->faction == user->faction) { + effect = heal(u, effect); + } + u = u->next; + } + use_pooled(user, itype->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, + amount); + usetpotionuse(user, itype->rtype->ptype); + + ADDMSG(&user->faction->msgs, msg_message("usepotion", + "unit potion", user, itype->rtype)); + return 0; +} + +/* ------------------------------------------------------------- */ +/* Kann auch von Nichtmagier benutzt werden, modifiziert Taktik fuer diese +* Runde um -1 - 4 Punkte. */ +static int +use_tacticcrystal(unit * u, const struct item_type *itype, int amount, + struct order *ord) +{ + int i; + for (i = 0; i != amount; ++i) { + int duration = 1; /* wirkt nur in dieser Runde */ + curse *c; + float effect; + float power = 5; /* Widerstand gegen Antimagiesprueche, ist in diesem + Fall egal, da der curse fuer den Kampf gelten soll, + der vor den Antimagiezaubern passiert */ + + effect = (float)(rng_int() % 6 - 1); + c = create_curse(u, &u->attribs, ct_find("skillmod"), power, + duration, effect, u->number); + c->data.i = SK_TACTICS; + UNUSED_ARG(ord); + } + use_pooled(u, itype->rtype, GET_DEFAULT, amount); + ADDMSG(&u->faction->msgs, msg_message("use_tacticcrystal", + "unit region", u, u->region)); + return 0; +} + +static int +use_mistletoe(struct unit *user, const struct item_type *itype, int amount, + struct order *ord) +{ + int mtoes = + get_pooled(user, itype->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, + user->number); + + if (user->number > mtoes) { + ADDMSG(&user->faction->msgs, msg_message("use_singleperson", + "unit item region command", user, itype->rtype, user->region, ord)); + return -1; + } + use_pooled(user, itype->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, + user->number); + a_add(&user->attribs, make_fleechance((float)1.0)); + ADDMSG(&user->faction->msgs, + msg_message("use_item", "unit item", user, itype->rtype)); + + return 0; +} + +static int use_warmthpotion(unit *u, const item_type *itype, + int amount, struct order *ord) +{ + if (u->faction->race == get_race(RC_INSECT)) { + u->flags |= UFL_WARMTH; + } + else { + /* nur fuer insekten: */ + cmistake(u, ord, 163, MSG_EVENT); + return ECUSTOM; + } + use_pooled(u, itype->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, + amount); + usetpotionuse(u, itype->rtype->ptype); + + ADDMSG(&u->faction->msgs, msg_message("usepotion", + "unit potion", u, itype->rtype)); + return 0; +} + void register_itemfunctions(void) { - register_demonseye(); - register_item_use(use_antimagiccrystal, "use_antimagiccrystal"); - register_item_use(use_instantartsculpture, "use_instantartsculpture"); + /* have tests: */ + register_item_use(use_mistletoe, "use_mistletoe"); + register_item_use(use_tacticcrystal, "use_dreameye"); register_item_use(use_studypotion, "use_studypotion"); + register_item_use(use_antimagiccrystal, "use_antimagic"); register_item_use(use_speedsail, "use_speedsail"); - register_item_use(use_instantartacademy, "use_instantartacademy"); register_item_use(use_bagpipeoffear, "use_bagpipeoffear"); register_item_use(use_aurapotion50, "use_aurapotion50"); + register_item_use(use_birthdayamulet, "use_aoc"); + register_item_use(use_foolpotion, "use_p7"); + register_item_use(use_bloodpotion, "use_peasantblood"); + register_item_use(use_healingpotion, "use_ointment"); + register_item_use(use_warmthpotion, "use_nestwarmth"); + + /* ungetestet: Wasser des Lebens */ + register_item_use(use_potion_delayed, "use_p2"); } diff --git a/src/items/CMakeLists.txt b/src/items/CMakeLists.txt index 0a2c581b4..37777f9e4 100644 --- a/src/items/CMakeLists.txt +++ b/src/items/CMakeLists.txt @@ -5,10 +5,6 @@ xerewards.test.c ) SET(_FILES -artrewards.c -demonseye.c -itemtypes.c -seed.c speedsail.c weapons.c xerewards.c diff --git a/src/items/artrewards.c b/src/items/artrewards.c deleted file mode 100644 index 8b6288f61..000000000 --- a/src/items/artrewards.c +++ /dev/null @@ -1,157 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#include -#include -#include "artrewards.h" - -/* kernel includes */ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* util includes */ -#include -#include - -/* libc includes */ -#include -#include -#include -#include - -#define HORNRANGE 10 -#define HORNDURATION 3 -#define HORNIMMUNITY 30 - -static int age_peaceimmune(attrib * a, void *owner) -{ - unused_arg(owner); - return (--a->data.i > 0) ? AT_AGE_KEEP : AT_AGE_REMOVE; -} - -static attrib_type at_peaceimmune = { - "peaceimmune", - NULL, NULL, - age_peaceimmune, - a_writeint, - a_readint -}; - -static int -use_hornofdancing(struct unit *u, const struct item_type *itype, -int amount, struct order *ord) -{ - region *r; - int regionsPacified = 0; - - for (r = regions; r; r = r->next) { - if (distance(u->region, r) < HORNRANGE) { - if (a_find(r->attribs, &at_peaceimmune) == NULL) { - attrib *a; - - create_curse(u, &r->attribs, ct_find("peacezone"), - 20, HORNDURATION, 1.0, 0); - - a = a_add(&r->attribs, a_new(&at_peaceimmune)); - a->data.i = HORNIMMUNITY; - - ADDMSG(&r->msgs, msg_message("hornofpeace_r_success", - "unit region", u, u->region)); - - regionsPacified++; - } - else { - ADDMSG(&r->msgs, msg_message("hornofpeace_r_nosuccess", - "unit region", u, u->region)); - } - } - } - - if (regionsPacified > 0) { - ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "hornofpeace_u_success", - "pacified", regionsPacified)); - } - else { - ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "hornofpeace_u_nosuccess", - "")); - } - - return 0; -} - -#define SPEEDUP 2 - -static int -useonother_trappedairelemental(struct unit *u, int shipId, -const struct item_type *itype, int amount, struct order *ord) -{ - curse *c; - ship *sh; - - if (shipId <= 0) { - cmistake(u, ord, 20, MSG_MOVE); - return -1; - } - - sh = findshipr(u->region, shipId); - if (!sh) { - cmistake(u, ord, 20, MSG_MOVE); - return -1; - } - - c = - create_curse(u, &sh->attribs, ct_find("shipspeedup"), 20, INT_MAX, SPEEDUP, - 0); - c_setflag(c, CURSE_NOAGE); - - ADDMSG(&u->faction->msgs, msg_message("trappedairelemental_success", - "unit region command ship", u, u->region, ord, sh)); - - use_pooled(u, itype->rtype, GET_DEFAULT, 1); - - return 0; -} - -static int -use_trappedairelemental(struct unit *u, -const struct item_type *itype, int amount, struct order *ord) -{ - ship *sh = u->ship; - - if (sh == NULL) { - cmistake(u, ord, 20, MSG_MOVE); - return -1; - } - return useonother_trappedairelemental(u, sh->no, itype, amount, ord); -} - -void register_artrewards(void) -{ - at_register(&at_peaceimmune); - register_item_use(use_hornofdancing, "use_hornofdancing"); - register_item_use(use_trappedairelemental, "use_trappedairelemental"); - register_item_useonother(useonother_trappedairelemental, - "useonother_trappedairelemental"); -} diff --git a/src/items/artrewards.h b/src/items/artrewards.h deleted file mode 100644 index 779e7cc5f..000000000 --- a/src/items/artrewards.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#ifndef H_ITM_ARTREWARDS -#define H_ITM_ARTREWARDS -#ifdef __cplusplus -extern "C" { -#endif - - extern void register_artrewards(void); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/items/demonseye.c b/src/items/demonseye.c deleted file mode 100644 index 704e77f4c..000000000 --- a/src/items/demonseye.c +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#include -#include -#include "demonseye.h" - -/* kernel includes */ -#include -#include -#include -#include -#include -#include - -/* util includes */ -#include - -/* libc includes */ -#include - -static int -summon_igjarjuk(struct unit *u, const struct item_type *itype, int amount, -struct order *ord) -{ - struct plane *p = rplane(u->region); - unused_arg(amount); - unused_arg(itype); - if (p != NULL) { - ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "use_realworld_only", "")); - return EUNUSABLE; - } - else { - assert(!"not implemented"); - return EUNUSABLE; - } -} - -static int -give_igjarjuk(struct unit *src, struct unit *d, const struct item_type *itype, -int n, struct order *ord) -{ - ADDMSG(&src->faction->msgs, msg_feedback(src, ord, "error_giveeye", "")); - return 0; -} - -void register_demonseye(void) -{ - register_item_use(summon_igjarjuk, "useigjarjuk"); - register_item_give(give_igjarjuk, "giveigjarjuk"); -} diff --git a/src/items/demonseye.h b/src/items/demonseye.h deleted file mode 100644 index 8d878a174..000000000 --- a/src/items/demonseye.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#ifndef H_ITM_DEMONSEYE -#define H_ITM_DEMONSEYE -#ifdef __cplusplus -extern "C" { -#endif - - void register_demonseye(void); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/items/itemtypes.c b/src/items/itemtypes.c deleted file mode 100644 index ca56b1273..000000000 --- a/src/items/itemtypes.c +++ /dev/null @@ -1,34 +0,0 @@ -/* - +-------------------+ Christian Schlittchen - | | Enno Rehling - | Eressea PBEM host | Katja Zedel - | (c) 1998 - 2003 | Henning Peters - | | Ingo Wilken - +-------------------+ Stefan Reich - - This program may not be used, modified or distributed - without prior permission by the authors of Eressea. - */ - -#include -#include -#include "itemtypes.h" - -#include "xerewards.h" -#include "artrewards.h" -#include "weapons.h" -#include "seed.h" - -void register_itemtypes(void) -{ - /* registering misc. functions */ - register_weapons(); - register_xerewards(); - register_artrewards(); -} - -void init_itemtypes(void) -{ - init_seed(); - init_mallornseed(); -} diff --git a/src/items/itemtypes.h b/src/items/itemtypes.h deleted file mode 100644 index ec705c55b..000000000 --- a/src/items/itemtypes.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - +-------------------+ Christian Schlittchen - | | Enno Rehling - | Eressea PBEM host | Katja Zedel - | (c) 1998 - 2003 | Henning Peters - | | Ingo Wilken - +-------------------+ Stefan Reich - - This program may not be used, modified or distributed - without prior permission by the authors of Eressea. - */ - -#ifndef H_ITM_ITEMS -#define H_ITM_ITEMS -#ifdef __cplusplus -extern "C" { -#endif - - extern void init_itemtypes(void); - extern void register_itemtypes(void); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/items/seed.c b/src/items/seed.c deleted file mode 100644 index 0e4b54e98..000000000 --- a/src/items/seed.c +++ /dev/null @@ -1,99 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#include -#include - -#include "seed.h" - -/* kernel includes */ -#include -#include -#include -#include - -/* util includes */ -#include -#include - -/* libc includes */ -#include - -static void produce_seeds(region * r, const resource_type * rtype, int norders) -{ - assert(r->land && r->land->trees[0] >= norders); - r->land->trees[0] -= norders; -} - -static int limit_seeds(const region * r, const resource_type * rtype) -{ - if (fval(r, RF_MALLORN)) { - return 0; - } - return r->land ? r->land->trees[0] : 0; -} - -void init_seed(void) -{ - attrib *a; - resource_limit *rdata; - resource_type *rtype; - - rtype = rt_find("seed"); - if (rtype != NULL) { - a = a_add(&rtype->attribs, a_new(&at_resourcelimit)); - rdata = (resource_limit *)a->data.v; - rdata->limit = limit_seeds; - rdata->produce = produce_seeds; - } -} - -/* mallorn */ - -static void -produce_mallornseeds(region * r, const resource_type * rtype, int norders) -{ - assert(fval(r, RF_MALLORN)); - r->land->trees[0] -= norders; -} - -static int limit_mallornseeds(const region * r, const resource_type * rtype) -{ - if (!fval(r, RF_MALLORN)) { - return 0; - } - return r->land ? r->land->trees[0] : 0; -} - -void init_mallornseed(void) -{ - attrib *a; - resource_limit *rdata; - resource_type *rtype; - - rtype = rt_find("mallornseed"); - if (rtype != NULL) { - rtype->flags |= RTF_LIMITED; - rtype->flags |= RTF_POOLED; - - a = a_add(&rtype->attribs, a_new(&at_resourcelimit)); - rdata = (resource_limit *)a->data.v; - rdata->limit = limit_mallornseeds; - rdata->produce = produce_mallornseeds; - } -} diff --git a/src/items/seed.h b/src/items/seed.h deleted file mode 100644 index c853adfde..000000000 --- a/src/items/seed.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#ifndef H_ITM_SEED -#define H_ITM_SEED -#ifdef __cplusplus -extern "C" { -#endif - - extern void init_seed(void); - extern void init_mallornseed(void); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/items/speedsail.c b/src/items/speedsail.c index 9d5aad747..cb40e9a8c 100644 --- a/src/items/speedsail.c +++ b/src/items/speedsail.c @@ -17,7 +17,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "speedsail.h" /* kernel includes */ @@ -43,8 +42,8 @@ use_speedsail(struct unit *u, const struct item_type *itype, int amount, struct order *ord) { struct plane *p = rplane(u->region); - unused_arg(amount); - unused_arg(itype); + UNUSED_ARG(amount); + UNUSED_ARG(itype); if (p != NULL) { ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "use_realworld_only", "")); } diff --git a/src/items/weapons.c b/src/items/weapons.c index f5015e39a..a23110a81 100644 --- a/src/items/weapons.c +++ b/src/items/weapons.c @@ -17,7 +17,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "weapons.h" #include "battle.h" @@ -107,7 +106,7 @@ int *casualties) } enemies = count_enemies(b, af, FIGHT_ROW, FIGHT_ROW, SELECT_ADVANCE); - enemies = _min(enemies, CATAPULT_ATTACKS); + enemies = MIN(enemies, CATAPULT_ATTACKS); if (enemies == 0) { return true; /* allow further attacks */ } diff --git a/src/items/xerewards.c b/src/items/xerewards.c index 98e099070..a6d1ad2ea 100644 --- a/src/items/xerewards.c +++ b/src/items/xerewards.c @@ -17,7 +17,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "xerewards.h" #include "magic.h" @@ -73,7 +72,7 @@ struct order *ord) } for (i = 0; i != amount; ++i) { - sp += _max(25, max_spellpoints(u->region, u) / 2); + sp += MAX(25, max_spellpoints(u->region, u) / 2); change_spellpoints(u, sp); } diff --git a/src/json.c b/src/json.c index 007c3aeda..e6eacced9 100644 --- a/src/json.c +++ b/src/json.c @@ -1,8 +1,9 @@ #include "platform.h" -#include #include "json.h" +#include +#include #include #include #include @@ -22,12 +23,20 @@ int json_import(struct stream * out) { assert(out && out->api); while (!out->api->readln(out->handle, buffer, sizeof(buffer))) { size_t len = strlen(buffer); - data = (char *)realloc(data, sz + len + 1); + char *tmp; + tmp = (char *)realloc(data, sz + len + 1); + if (!tmp) { + log_fatal("allocation failure in json_import"); + free(data); + return 1; + } + data = tmp; memcpy(data + sz, buffer, len); sz += len; data[sz] = 0; } json = cJSON_Parse(data); + free(data); child = cJSON_GetObjectItem(json, "regions"); if (child && child->type == cJSON_Object) { cJSON *j; @@ -58,13 +67,13 @@ int json_export(stream * out, int flags) { cJSON *json, *root = cJSON_CreateObject(); assert(out && out->api); if (regions && (flags & EXPORT_REGIONS)) { - char id[32]; + char id[32]; /* TODO: static_assert(INT_MAX < 10^32) */ region * r; plane * p; cJSON_AddItemToObject(root, "planes", json = cJSON_CreateObject()); for (p = planes; p; p = p->next) { cJSON *data; - _snprintf(id, sizeof(id), "%u", p->id); + sprintf(id, "%d", p->id); /* safe, unless int is bigger than 64 bit */ cJSON_AddItemToObject(json, id, data = cJSON_CreateObject()); cJSON_AddNumberToObject(data, "x", p->minx); cJSON_AddNumberToObject(data, "y", p->miny); @@ -76,7 +85,7 @@ int json_export(stream * out, int flags) { cJSON_AddItemToObject(root, "regions", json = cJSON_CreateObject()); for (r = regions; r; r = r->next) { cJSON *data; - _snprintf(id, sizeof(id), "%u", r->uid); + sprintf(id, "%d", r->uid); /* safe, unless int is bigger than 64 bit */ cJSON_AddItemToObject(json, id, data = cJSON_CreateObject()); cJSON_AddNumberToObject(data, "x", r->x); cJSON_AddNumberToObject(data, "y", r->y); diff --git a/src/json.test.c b/src/json.test.c index 528b734a4..57cb6e136 100644 --- a/src/json.test.c +++ b/src/json.test.c @@ -16,7 +16,7 @@ static char *strip(char *str) { char *s = str, *b = str, *e = str; - // b is where text begins, e where it ends, s where we insert it. + /* b is where text begins, e where it ends, s where we insert it. */ for (; *b && isspace(*b); ++b) {}; for (e = b; *e && !isspace(*e); ++e) {}; while (*b) { diff --git a/src/jsreport.c b/src/jsreport.c index d75b7919d..dc22c760a 100644 --- a/src/jsreport.c +++ b/src/jsreport.c @@ -1,4 +1,4 @@ -#include "reports.h" +#include "reports.h" #include "jsreport.h" #include #include diff --git a/src/kernel/CMakeLists.txt b/src/kernel/CMakeLists.txt index 6bb860ad7..b8423ae03 100644 --- a/src/kernel/CMakeLists.txt +++ b/src/kernel/CMakeLists.txt @@ -20,7 +20,7 @@ order.test.c plane.test.c pool.test.c race.test.c -# region.test.c +region.test.c # resources.test.c save.test.c ship.test.c @@ -54,6 +54,7 @@ pool.c race.c region.c resources.c +rules.c save.c ship.c skills.c diff --git a/src/kernel/alliance.c b/src/kernel/alliance.c index 7a65c4db5..0feb8407d 100644 --- a/src/kernel/alliance.c +++ b/src/kernel/alliance.c @@ -23,7 +23,6 @@ without prior permission by the authors of Eressea. #include #include #include -#include #include /* util includes */ @@ -32,10 +31,11 @@ without prior permission by the authors of Eressea. #include #include #include -#include #include #include +#include + /* libc includes */ #include #include @@ -50,7 +50,7 @@ void free_alliances(void) alliances = al->next; free(al->name); if (al->members) { - ql_free(al->members); + selist_free(al->members); } free(al); } @@ -83,7 +83,7 @@ alliance *new_alliance(int id, const char *name) { al = calloc(1, sizeof(alliance)); al->id = id; if (name) { - al->name = _strdup(name); + al->name = strdup(name); } else { al->flags |= ALF_NON_ALLIED; @@ -116,7 +116,7 @@ faction *alliance_get_leader(alliance * al) { if (!al->_leader) { if (al->members) { - al->_leader = (faction *)ql_get(al->members, 0); + al->_leader = (faction *)selist_get(al->members, 0); } } return al->_leader; @@ -357,19 +357,19 @@ void setalliance(faction * f, alliance * al) return; if (f->alliance != NULL) { int qi; - quicklist **flistp = &f->alliance->members; + selist **flistp = &f->alliance->members; - for (qi = 0; *flistp; ql_advance(flistp, &qi, 1)) { - faction *data = (faction *)ql_get(*flistp, qi); + for (qi = 0; *flistp; selist_advance(flistp, &qi, 1)) { + faction *data = (faction *)selist_get(*flistp, qi); if (data == f) { - ql_delete(flistp, qi); + selist_delete(flistp, qi); break; } } if (f->alliance->_leader == f) { if (f->alliance->members) { - f->alliance->_leader = (faction *)ql_get(f->alliance->members, 0); + f->alliance->_leader = (faction *)selist_get(f->alliance->members, 0); } else { f->alliance->_leader = NULL; @@ -379,7 +379,7 @@ void setalliance(faction * f, alliance * al) f->alliance = al; f->alliance_joindate = turn; if (al != NULL) { - ql_push(&al->members, f); + selist_push(&al->members, f); if (al->_leader == NULL) { al->_leader = f; } @@ -447,7 +447,7 @@ void alliance_setname(alliance * self, const char *name) { free(self->name); if (name) - self->name = _strdup(name); + self->name = strdup(name); else self->name = NULL; } diff --git a/src/kernel/alliance.h b/src/kernel/alliance.h index 907fc65f7..8e112e8c9 100644 --- a/src/kernel/alliance.h +++ b/src/kernel/alliance.h @@ -18,6 +18,9 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef H_KRNL_ALLIANCE #define H_KRNL_ALLIANCE + +#include + #ifdef __cplusplus extern "C" { #endif @@ -27,6 +30,7 @@ extern "C" { struct unit; struct faction; struct region; + struct selist; enum { ALLIANCE_KICK, @@ -46,7 +50,7 @@ extern "C" { typedef struct alliance { struct alliance *next; struct faction *_leader; - struct quicklist *members; + struct selist *members; int flags; int id; char *name; diff --git a/src/kernel/alliance.test.c b/src/kernel/alliance.test.c index 72a31a42c..c0ec03fbc 100644 --- a/src/kernel/alliance.test.c +++ b/src/kernel/alliance.test.c @@ -7,7 +7,7 @@ #include "alliance.h" #include #include -#include +#include #include @@ -76,10 +76,10 @@ static void test_alliance_dead_faction(CuTest *tc) { setalliance(f, al); setalliance(f2, al); CuAssertPtrEquals(tc, f, alliance_get_leader(al)); - CuAssertIntEquals(tc, 2, ql_length(al->members)); + CuAssertIntEquals(tc, 2, selist_length(al->members)); CuAssertPtrEquals(tc, al, f->alliance); destroyfaction(&factions); - CuAssertIntEquals(tc, 1, ql_length(al->members)); + CuAssertIntEquals(tc, 1, selist_length(al->members)); CuAssertPtrEquals(tc, f2, alliance_get_leader(al)); CuAssertPtrEquals(tc, NULL, f->alliance); CuAssertTrue(tc, !f->_alive); diff --git a/src/kernel/ally.c b/src/kernel/ally.c index 3152ab4b7..759d556f4 100644 --- a/src/kernel/ally.c +++ b/src/kernel/ally.c @@ -3,7 +3,6 @@ #include "types.h" #include "ally.h" -#include "save.h" #include "unit.h" #include "region.h" #include "group.h" @@ -77,7 +76,7 @@ int AllianceAuto(void) const char *str = config_get("alliance.auto"); value = 0; if (str != NULL) { - char *sstr = _strdup(str); + char *sstr = strdup(str); char *tok = strtok(sstr, " "); while (tok) { value |= ally_flag(tok, -1); @@ -133,19 +132,21 @@ attrib_type at_npcfaction = { */ int HelpMask(void) { - const char *str = config_get("rules.help.mask"); - int rule = 0; - if (str != NULL) { - char *sstr = _strdup(str); - char *tok = strtok(sstr, " "); - while (tok) { - rule |= ally_flag(tok, -1); - tok = strtok(NULL, " "); + static int config, rule = 0; + if (config_changed(&config)) { + const char *str = config_get("rules.help.mask"); + if (str != NULL) { + char *sstr = strdup(str); + char *tok = strtok(sstr, " "); + while (tok) { + rule |= ally_flag(tok, -1); + tok = strtok(NULL, " "); + } + free(sstr); + } + else { + rule = HELP_ALL; } - free(sstr); - } - else { - rule = HELP_ALL; } return rule; } @@ -155,7 +156,7 @@ static int AllianceRestricted(void) const char *str = config_get("alliance.restricted"); int rule = 0; if (str != NULL) { - char *sstr = _strdup(str); + char *sstr = strdup(str); char *tok = strtok(sstr, " "); while (tok) { rule |= ally_flag(tok, -1); diff --git a/src/kernel/build.c b/src/kernel/build.c index 6bc953241..88ab35fd2 100644 --- a/src/kernel/build.c +++ b/src/kernel/build.c @@ -24,6 +24,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "direction.h" #include "move.h" #include "study.h" +#include "guard.h" #include "laws.h" #include "skill.h" #include "lighthouse.h" @@ -113,7 +114,7 @@ static void destroy_road(unit * u, int nmax, struct order *ord) } for (u2 = r->units; u2; u2 = u2->next) { - if (u2->faction != u->faction && is_guard(u2, GUARD_TAX) + if (u2->faction != u->faction && is_guard(u2) && cansee(u2->faction, u->region, u, 0) && !alliedunit(u, u2->faction, HELP_GUARD)) { cmistake(u, ord, 70, MSG_EVENT); @@ -122,11 +123,11 @@ static void destroy_road(unit * u, int nmax, struct order *ord) } road = rroad(r, d); - n = _min(n, road); + n = MIN(n, road); if (n != 0) { region *r2 = rconnect(r, d); int willdo = effskill(u, SK_ROAD_BUILDING, 0) * u->number; - willdo = _min(willdo, n); + willdo = MIN(willdo, n); if (willdo == 0) { /* TODO: error message */ } @@ -248,7 +249,7 @@ int destroy_cmd(unit * u, struct order *ord) } if (con) { - /* TODO: Nicht an ZERSTRE mit Punktangabe angepasst! */ + /* TODO: Nicht an ZERST�RE mit Punktangabe angepasst! */ int c; for (c = 0; con->materials[c].number; ++c) { const requirement *rq = con->materials + c; @@ -326,7 +327,7 @@ void build_road(unit * u, int size, direction_t d) } if (size > 0) - left = _min(size, left); + left = MIN(size, left); /* baumaximum anhand der rohstoffe */ if (u_race(u) == get_race(RC_STONEGOLEM)) { n = u->number * GOLEM_STONE; @@ -338,7 +339,7 @@ void build_road(unit * u, int size, direction_t d) return; } } - left = _min(n, left); + left = MIN(n, left); /* n = maximum by skill. try to maximize it */ n = u->number * effsk; @@ -346,7 +347,7 @@ void build_road(unit * u, int size, direction_t d) const resource_type *ring = get_resourcetype(R_RING_OF_NIMBLEFINGER); item *itm = ring ? *i_find(&u->items, ring->itype) : 0; if (itm != NULL && itm->number > 0) { - int rings = _min(u->number, itm->number); + int rings = MIN(u->number, itm->number); n = n * ((roqf_factor() - 1) * rings + u->number) / u->number; } } @@ -354,15 +355,15 @@ void build_road(unit * u, int size, direction_t d) int dm = get_effect(u, oldpotiontype[P_DOMORE]); if (dm != 0) { int todo = (left - n + effsk - 1) / effsk; - todo = _min(todo, u->number); - dm = _min(dm, todo); + todo = MIN(todo, u->number); + dm = MIN(dm, todo); change_effect(u, oldpotiontype[P_DOMORE], -dm); n += dm * effsk; } /* Auswirkung Schaffenstrunk */ } /* make minimum of possible and available: */ - n = _min(left, n); + n = MIN(left, n); /* n is now modified by several special effects, so we have to * minimize it again to make sure the road will not grow beyond @@ -379,7 +380,7 @@ void build_road(unit * u, int size, direction_t d) else { use_pooled(u, get_resourcetype(R_STONE), GET_DEFAULT, n); /* Nur soviel PRODUCEEXP wie auch tatsaechlich gemacht wurde */ - produceexp(u, SK_ROAD_BUILDING, _min(n, u->number)); + produceexp(u, SK_ROAD_BUILDING, MIN(n, u->number)); } ADDMSG(&u->faction->msgs, msg_message("buildroad", "region unit size", r, u, n)); @@ -396,7 +397,7 @@ static int required(int size, int msize, int maxneed) * braucht man required von maxneed resourcen */ { int used; - + assert(msize > 0); used = size * maxneed / msize; if (size * maxneed % msize) ++used; @@ -427,6 +428,76 @@ int roqf_factor(void) return value; } +static int use_materials(unit *u, const construction *type, int n, int completed) { + if (type->materials) { + int c; + for (c = 0; type->materials[c].number; c++) { + const struct resource_type *rtype = type->materials[c].rtype; + int prebuilt = + required(completed, type->reqsize, type->materials[c].number); + int need = + required(completed + n, type->reqsize, type->materials[c].number); + int multi = 1; + int canuse = 100; /* normalization */ + if (building_is_active(u->building) && inside_building(u)) { + canuse = matmod(u->building->type->attribs, u, rtype, canuse); + } + if (canuse < 0) { + return canuse; /* pass errors to caller */ + } + canuse = matmod(type->attribs, u, rtype, canuse); + + assert(canuse % 100 == 0 + || !"only constant multipliers are implemented in build()"); + multi = canuse / 100; + if (canuse < 0) { + return canuse; /* pass errors to caller */ + } + use_pooled(u, rtype, GET_DEFAULT, + (need - prebuilt + multi - 1) / multi); + } + } + return 0; +} + +static int count_materials(unit *u, const construction *type, int n, int completed) +{ + if (type->materials) { + int c; + for (c = 0; n > 0 && type->materials[c].number; c++) { + const struct resource_type *rtype = type->materials[c].rtype; + int need, prebuilt; + int canuse = get_pooled(u, rtype, GET_DEFAULT, INT_MAX); + + if (building_is_active(u->building) && inside_building(u)) { + canuse = matmod(u->building->type->attribs, u, rtype, canuse); + } + + if (canuse < 0) + return canuse; /* pass errors to caller */ + canuse = matmod(type->attribs, u, rtype, canuse); + if (type->reqsize > 1) { + prebuilt = + required(completed, type->reqsize, type->materials[c].number); + for (; n;) { + need = + required(completed + n, type->reqsize, type->materials[c].number); + if (need - prebuilt <= canuse) + break; + --n; /* TODO: optimieren? */ + } + } + else { + int maxn = canuse / type->materials[c].number; + if (maxn < n) { + n = maxn; + } + } + } + } + return n; +} + /** Use up resources for building an object. * Build up to 'size' points of 'type', where 'completed' * of the first object have already been finished. return the @@ -485,13 +556,13 @@ int build(unit * u, const construction * ctype, int completed, int want) if (dm != 0) { /* Auswirkung Schaffenstrunk */ - dm = _min(dm, u->number); + dm = MIN(dm, u->number); change_effect(u, oldpotiontype[P_DOMORE], -dm); skills += dm * effsk; } } for (; want > 0 && skills > 0;) { - int c, n; + int err, n; /* skip over everything that's already been done: * type->improvement==NULL means no more improvements, but no size limits @@ -512,8 +583,8 @@ int build(unit * u, const construction * ctype, int completed, int want) /* Hier ist entweder maxsize == -1, oder completed < maxsize. * Andernfalls ist das Datenfile oder sonstwas kaputt... - * (enno): Nein, das ist fr Dinge, bei denen die nchste Ausbaustufe - * die gleiche wie die vorherige ist. z.b. gegenstnde. + * (enno): Nein, das ist f�r Dinge, bei denen die n�chste Ausbaustufe + * die gleiche wie die vorherige ist. z.b. gegenst�nde. */ if (type->maxsize > 0) { completed = completed % type->maxsize; @@ -544,7 +615,7 @@ int build(unit * u, const construction * ctype, int completed, int want) item *itm = ring ? *i_find(&u->items, ring->itype) : 0; int i = itm ? itm->number : 0; if (i > 0) { - int rings = _min(u->number, i); + int rings = MIN(u->number, i); n = n * ((roqf_factor() - 1) * rings + u->number) / u->number; } } @@ -552,80 +623,30 @@ int build(unit * u, const construction * ctype, int completed, int want) if (want < n) n = want; if (type->maxsize > 0) { - n = _min(type->maxsize - completed, n); + n = MIN(type->maxsize - completed, n); if (type->improvement == NULL) { want = n; } } - if (type->materials) - for (c = 0; n > 0 && type->materials[c].number; c++) { - const struct resource_type *rtype = type->materials[c].rtype; - int need, prebuilt; - int canuse = get_pooled(u, rtype, GET_DEFAULT, INT_MAX); - - if (building_is_active(u->building) && inside_building(u)) { - canuse = matmod(u->building->type->attribs, u, rtype, canuse); - } - - if (canuse < 0) - return canuse; /* pass errors to caller */ - canuse = matmod(type->attribs, u, rtype, canuse); - if (type->reqsize > 1) { - prebuilt = - required(completed, type->reqsize, type->materials[c].number); - for (; n;) { - need = - required(completed + n, type->reqsize, type->materials[c].number); - if (need - prebuilt <= canuse) - break; - --n; /* TODO: optimieren? */ - } - } - else { - int maxn = canuse / type->materials[c].number; - if (maxn < n) - n = maxn; - } - } + n = count_materials(u, type, n, completed); if (n <= 0) { if (made == 0) return ENOMATERIALS; else break; } - if (type->materials) - for (c = 0; type->materials[c].number; c++) { - const struct resource_type *rtype = type->materials[c].rtype; - int prebuilt = - required(completed, type->reqsize, type->materials[c].number); - int need = - required(completed + n, type->reqsize, type->materials[c].number); - int multi = 1; - int canuse = 100; /* normalization */ - if (building_is_active(u->building) && inside_building(u)) { - canuse = matmod(u->building->type->attribs, u, rtype, canuse); - } - if (canuse < 0) - return canuse; /* pass errors to caller */ - canuse = matmod(type->attribs, u, rtype, canuse); - - assert(canuse % 100 == 0 - || !"only constant multipliers are implemented in build()"); - multi = canuse / 100; - if (canuse < 0) - return canuse; /* pass errors to caller */ - - use_pooled(u, rtype, GET_DEFAULT, - (need - prebuilt + multi - 1) / multi); - } + err = use_materials(u, type, n, completed); + if (err < 0) { + return err; + } made += n; skills -= n * type->minskill; want -= n; completed = completed + n; } /* Nur soviel PRODUCEEXP wie auch tatsaechlich gemacht wurde */ - produceexp(u, ctype->skill, _min(made, u->number)); + produceexp(u, ctype->skill, MIN(made, u->number)); return made; } @@ -670,7 +691,7 @@ int maxbuild(const unit * u, const construction * cons) return 0; } else - maximum = _min(maximum, have / need); + maximum = MIN(maximum, have / need); } return maximum; } @@ -758,10 +779,8 @@ build_building(unit * u, const building_type * btype, int id, int want, order * return 0; } } - } - - if (b) built = b->size; + } if (n <= 0 || n == INT_MAX) { if (b == NULL) { if (btype->maxsize > 0) { @@ -816,11 +835,11 @@ build_building(unit * u, const building_type * btype, int id, int want, order * btname = LOC(lang, btype->_name); if (want - built <= 0) { - /* gebude fertig */ + /* geb�ude fertig */ new_order = default_order(lang); } else if (want != INT_MAX && btname) { - /* reduzierte restgre */ + /* reduzierte restgr��e */ const char *hasspace = strchr(btname, ' '); if (hasspace) { new_order = @@ -832,7 +851,7 @@ build_building(unit * u, const building_type * btype, int id, int want, order * } } else if (btname) { - /* Neues Haus, Befehl mit Gebudename */ + /* Neues Haus, Befehl mit Geb�udename */ const char *hasspace = strchr(btname, ' '); if (hasspace) { new_order = create_order(K_MAKE, lang, "\"%s\" %i", btname, b->no); @@ -880,7 +899,7 @@ static void build_ship(unit * u, ship * sh, int want) } if (sh->damage && can) { - int repair = _min(sh->damage, can * DAMAGE_SCALE); + int repair = MIN(sh->damage, can * DAMAGE_SCALE); n += repair / DAMAGE_SCALE; if (repair % DAMAGE_SCALE) ++n; @@ -924,7 +943,7 @@ order * ord) return; } if (want > 0) - want = _min(want, msize); + want = MIN(want, msize); else want = msize; @@ -983,7 +1002,7 @@ void continue_ship(unit * u, int want) return; } if (want > 0) - want = _min(want, msize); + want = MIN(want, msize); else want = msize; diff --git a/src/kernel/build.h b/src/kernel/build.h index 38fefb88a..7780a6cd2 100644 --- a/src/kernel/build.h +++ b/src/kernel/build.h @@ -45,9 +45,6 @@ extern "C" { int maxsize; /* maximum size of this type */ int reqsize; /* size of object using up 1 set of requirement. */ - int defense_bonus; /* protection bonus (defense) during combat */ - int close_combat_bonus; /* close combat attack bonus*/ - int ranged_bonus; /* ranged attack bonus */ requirement *materials; /* material req'd to build one object */ const struct building_type *btype; /* building type required to make this thing */ diff --git a/src/kernel/build.test.c b/src/kernel/build.test.c index 9ea473725..77efcfd73 100644 --- a/src/kernel/build.test.c +++ b/src/kernel/build.test.c @@ -200,7 +200,7 @@ static void test_build_with_potion(CuTest *tc) { CuAssertIntEquals(tc, 4, build(u, &bf.cons, 0, 20)); CuAssertIntEquals(tc, 2, get_effect(u, ptype)); set_level(u, SK_ARMORER, bf.cons.minskill); - scale_number(u, 2); // OBS: this scales the effects, too: + scale_number(u, 2); /* OBS: this scales the effects, too: */ CuAssertIntEquals(tc, 4, get_effect(u, ptype)); CuAssertIntEquals(tc, 4, build(u, &bf.cons, 0, 20)); CuAssertIntEquals(tc, 2, get_effect(u, ptype)); @@ -318,7 +318,7 @@ unit *test_create_guard(region *r, faction *f, race *rc) { f = test_create_faction(rc); } ug = test_create_unit(f, r); - guard(ug, GUARD_TAX); + setguard(ug, true); return ug; } @@ -345,7 +345,7 @@ static void test_build_destroy_road_guard(CuTest *tc) CuAssertPtrEquals(tc, 0, test_find_messagetype(f->msgs, "destroy_road")); test_clear_messages(f); - guard(ug, GUARD_NONE); + setguard(ug, false); CuAssertIntEquals(tc, 0, destroy_cmd(u, ord)); CuAssertIntEquals(tc, 99, rroad(r, D_EAST)); diff --git a/src/kernel/building.c b/src/kernel/building.c index 0056fba1e..6d0db8f43 100644 --- a/src/kernel/building.c +++ b/src/kernel/building.c @@ -22,13 +22,14 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "building.h" /* kernel includes */ +#include "curse.h" #include "item.h" #include "unit.h" #include "faction.h" #include "race.h" #include "region.h" #include "skill.h" -#include "save.h" +#include "terrain.h" #include "lighthouse.h" /* util includes */ @@ -40,7 +41,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include +#include #include #include @@ -53,6 +54,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include /* attributes includes */ +#include #include typedef struct building_typelist { @@ -60,18 +62,18 @@ typedef struct building_typelist { building_type *type; } building_typelist; -quicklist *buildingtypes = NULL; +selist *buildingtypes = NULL; /* Returns a building type for the (internal) name */ static building_type *bt_find_i(const char *name) { - quicklist *ql; + selist *ql; int qi; assert(name); - for (qi = 0, ql = buildingtypes; ql; ql_advance(&ql, &qi, 1)) { - building_type *btype = (building_type *)ql_get(ql, qi); + for (qi = 0, ql = buildingtypes; ql; selist_advance(&ql, &qi, 1)) { + building_type *btype = (building_type *)selist_get(ql, qi); if (strcmp(btype->_name, name) == 0) return btype; } @@ -100,7 +102,7 @@ void bt_register(building_type * type) if (type->init) { type->init(type); } - ql_push(&buildingtypes, (void *)type); + selist_push(&buildingtypes, (void *)type); ++bt_changes; } @@ -113,8 +115,8 @@ static void free_buildingtype(void *ptr) { } void free_buildingtypes(void) { - ql_foreach(buildingtypes, free_buildingtype); - ql_free(buildingtypes); + selist_foreach(buildingtypes, free_buildingtype); + selist_free(buildingtypes); buildingtypes = 0; ++bt_changes; } @@ -125,7 +127,7 @@ building_type *bt_get_or_create(const char *name) building_type *btype = bt_find_i(name); if (btype == NULL) { btype = calloc(sizeof(building_type), 1); - btype->_name = _strdup(name); + btype->_name = strdup(name); btype->auraregen = 1.0; btype->maxsize = -1; btype->capacity = 1; @@ -141,7 +143,7 @@ int buildingcapacity(const building * b) { if (b->type->capacity >= 0) { if (b->type->maxcapacity >= 0) { - return _min(b->type->maxcapacity, b->size * b->type->capacity); + return MIN(b->type->maxcapacity, b->size * b->type->capacity); } return b->size * b->type->capacity; } @@ -312,19 +314,24 @@ const building_type *findbuildingtype(const char *name, bn = bn->next; } if (!bn) { - quicklist *ql = buildingtypes; + selist *ql = buildingtypes; int qi; bn = (local_names *)calloc(sizeof(local_names), 1); bn->next = bnames; bn->lang = lang; - for (qi = 0, ql = buildingtypes; ql; ql_advance(&ql, &qi, 1)) { - building_type *btype = (building_type *)ql_get(ql, qi); + for (qi = 0, ql = buildingtypes; ql; selist_advance(&ql, &qi, 1)) { + building_type *btype = (building_type *)selist_get(ql, qi); const char *n = LOC(lang, btype->_name); - type.v = (void *)btype; - addtoken((struct tnode **)&bn->names, n, type); + if (!n) { + log_error("building type %s has no translation in %s", + btype->_name, locale_name(lang)); + } else { + type.v = (void *)btype; + addtoken((struct tnode **)&bn->names, n, type); + } } bnames = bn; } @@ -333,41 +340,26 @@ const building_type *findbuildingtype(const char *name, return (const building_type *)type.v; } -static int building_protection(const building * b, const unit * u, building_bonus bonus) +int cmp_castle_size(const building * b, const building * a) { - int i = 0; - int bsize = buildingeffsize(b, false); - const construction *cons = b->type->construction; - if (!cons) { - return 0; + if (!b || !(b->type->flags & BTF_FORTIFICATION) || !building_owner(b)) { + return -1; } - - for (i = 0; i < bsize; i++) - { - cons = cons->improvement; - } - - switch (bonus) - { - case DEFENSE_BONUS: - return cons->defense_bonus; - case CLOSE_COMBAT_ATTACK_BONUS: - return cons->close_combat_bonus; - case RANGED_ATTACK_BONUS: - return cons->ranged_bonus; - default: - return 0; + if (!a || !(a->type->flags & BTF_FORTIFICATION) || !building_owner(a)) { + return 1; } + return b->size - a->size; } -void register_buildings(void) +static const int castle_bonus[6] = { 0, 1, 3, 5, 8, 12 }; +static const int watch_bonus[3] = { 0, 1, 2 }; + +int building_protection(const building_type * btype, int stage) { - register_function((pf_generic)building_protection, - "building_protection"); - register_function((pf_generic)init_smithy, "init_smithy"); - register_function((pf_generic)castle_name, "castle_name"); - register_function((pf_generic)castle_name_2, "castle_name_2"); - register_function((pf_generic)fort_name, "fort_name"); + if (btype->maxsize < 0) { + return castle_bonus[MIN(stage, 5)]; + } + return watch_bonus[MIN(stage, 2)]; } void write_building_reference(const struct building *b, struct storage *store) @@ -427,8 +419,8 @@ building *new_building(const struct building_type * btype, region * r, bname = parameters[P_GEBAEUDE]; } assert(bname); - slprintf(buffer, sizeof(buffer), "%s %s", bname, buildingid(b)); - b->name = _strdup(bname); + slprintf(buffer, sizeof(buffer), "%s %s", bname, itoa36(b->no)); + b->name = strdup(bname); return b; } @@ -457,9 +449,9 @@ void remove_building(building ** blist, building * b) update_lighthouse(b); bunhash(b); - /* Falls Karawanserei, Damm oder Tunnel einstrzen, wird die schon - * gebaute Strae zur Hlfte vernichtet */ - // TODO: caravan, tunnel, dam modularization ? is_building_type ? + /* Falls Karawanserei, Damm oder Tunnel einst�rzen, wird die schon + * gebaute Strasse zur Haelfte vernichtet */ + /* TODO: caravan, tunnel, dam modularization ? is_building_type ? */ if (b->type == bt_caravan || b->type == bt_dam || b->type == bt_tunnel) { region *r = b->region; int d; @@ -571,7 +563,7 @@ void building_set_owner(struct unit * owner) static unit *building_owner_ex(const building * bld, const struct faction * last_owner) { unit *u, *heir = 0; - /* Eigentmer tot oder kein Eigentmer vorhanden. Erste lebende Einheit + /* Eigent�mer tot oder kein Eigent�mer vorhanden. Erste lebende Einheit * nehmen. */ for (u = bld->region->units; u; u = u->next) { if (u->building == bld) { @@ -602,10 +594,11 @@ static unit *building_owner_ex(const building * bld, const struct faction * last unit *building_owner(const building * bld) { + unit *owner; if (!bld) { return NULL; } - unit *owner = bld->_owner; + owner = bld->_owner; if (!owner || (owner->building != bld || owner->number <= 0)) { unit * heir = building_owner_ex(bld, owner ? owner->faction : 0); return (heir && heir->number > 0) ? heir : 0; @@ -627,7 +620,7 @@ void building_setname(building * self, const char *name) { free(self->name); if (name) - self->name = _strdup(name); + self->name = strdup(name); else self->name = NULL; } @@ -703,3 +696,226 @@ bool is_building_type(const struct building_type *btype, const char *name) { assert(btype); return name && strcmp(btype->_name, name)==0; } + +building *largestbuilding(const region * r, cmp_building_cb cmp_gt, + bool imaginary) +{ + building *b, *best = NULL; + + for (b = rbuildings(r); b; b = b->next) { + if (cmp_gt(b, best) <= 0) + continue; + if (!imaginary) { + const attrib *a = a_find(b->attribs, &at_icastle); + if (a) + continue; + } + best = b; + } + return best; +} +/* Lohn bei den einzelnen Burgstufen f�r Normale Typen, Orks, Bauern, + * Modifikation f�r St�dter. */ + +static const int wagetable[7][4] = { + { 10, 10, 11, -7 }, /* Baustelle */ + { 10, 10, 11, -5 }, /* Handelsposten */ + { 11, 11, 12, -3 }, /* Befestigung */ + { 12, 11, 13, -1 }, /* Turm */ + { 13, 12, 14, 0 }, /* Burg */ + { 14, 12, 15, 1 }, /* Festung */ + { 15, 13, 16, 2 } /* Zitadelle */ +}; + +static int +default_wage(const region * r, const faction * f, const race * rc, int in_turn) +{ + building *b = largestbuilding(r, &cmp_wage, false); + int esize = 0; + double wage; + static int ct_cache; + static const struct curse_type *drought_ct; + + if (ct_changed(&ct_cache)) { + drought_ct = ct_find("drought"); + } + if (b != NULL) { + /* TODO: this reveals imaginary castles */ + esize = buildingeffsize(b, false); + } + + if (f != NULL) { + int index = 0; + if (rc == get_race(RC_ORC) || rc == get_race(RC_SNOTLING)) { + index = 1; + } + wage = wagetable[esize][index]; + } + else { + if (is_mourning(r, in_turn)) { + wage = 10; + } + else if (fval(r->terrain, SEA_REGION)) { + wage = 11; + } + else { + wage = wagetable[esize][2]; + } + if (rule_blessed_harvest() == HARVEST_WORK) { + /* E1 rules */ + wage += curse_geteffect(get_curse(r->attribs, ct_find("blessedharvest"))); + } + } + + /* Artsculpture: Income +5 */ + for (b = r->buildings; b; b = b->next) { + if (is_building_type(b->type, "artsculpture")) { + wage += 5; + } + } + + if (r->attribs) { + attrib *a; + const struct curse_type *ctype; + /* Godcurse: Income -10 */ + ctype = ct_find("godcursezone"); + if (ctype && curse_active(get_curse(r->attribs, ctype))) { + wage = MAX(0, wage - 10); + } + + /* Bei einer D�rre verdient man nur noch ein Viertel */ + if (drought_ct) { + curse *c = get_curse(r->attribs, drought_ct); + if (curse_active(c)) + wage /= curse_geteffect(c); + } + + a = a_find(r->attribs, &at_reduceproduction); + if (a) { + wage = (wage * a->data.sa[0]) / 100; + } + } + return (int)wage; +} + +static int +minimum_wage(const region * r, const faction * f, const race * rc, int in_turn) +{ + if (f && rc) { + return rc->maintenance; + } + return default_wage(r, f, rc, in_turn); +} + +/* Gibt Arbeitslohn f�r entsprechende Rasse zur�ck, oder f�r +* die Bauern wenn f == NULL. */ +int wage(const region * r, const faction * f, const race * rc, int in_turn) +{ + if (global.functions.wage) { + return global.functions.wage(r, f, rc, in_turn); + } + return default_wage(r, f, rc, in_turn); +} + +int cmp_wage(const struct building *b, const building * a) +{ + if (is_building_type(b->type, "castle")) { + if (!a) + return 1; + if (b->size > a->size) + return 1; + if (b->size == a->size) + return 0; + } + return -1; +} + +bool is_owner_building(const struct building * b) +{ + region *r = b->region; + if (b->type->taxes && r->land && r->land->ownership) { + unit *u = building_owner(b); + return u && u->faction == r->land->ownership->owner; + } + return false; +} + +int cmp_taxes(const building * b, const building * a) +{ + faction *f = region_get_owner(b->region); + if (b->type->taxes) { + unit *u = building_owner(b); + if (!u) { + return -1; + } + else if (a) { + int newsize = buildingeffsize(b, false); + double newtaxes = b->type->taxes(b, newsize); + int oldsize = buildingeffsize(a, false); + double oldtaxes = a->type->taxes(a, oldsize); + + if (newtaxes < oldtaxes) + return -1; + else if (newtaxes > oldtaxes) + return 1; + else if (b->size < a->size) + return -1; + else if (b->size > a->size) + return 1; + else { + if (u && u->faction == f) { + u = building_owner(a); + if (u && u->faction == f) + return -1; + return 1; + } + } + } + else { + return 1; + } + } + return -1; +} + +int cmp_current_owner(const building * b, const building * a) +{ + faction *f = region_get_owner(b->region); + + assert(rule_region_owners()); + if (f && b->type->taxes) { + unit *u = building_owner(b); + if (!u || u->faction != f) + return -1; + if (a) { + int newsize = buildingeffsize(b, false); + double newtaxes = b->type->taxes(b, newsize); + int oldsize = buildingeffsize(a, false); + double oldtaxes = a->type->taxes(a, oldsize); + + if (newtaxes > oldtaxes) { + return 1; + } + if (newtaxes < oldtaxes) { + return -1; + } + if (newsize != oldsize) { + return newsize - oldsize; + } + return (b->size - a->size); + } + else { + return 1; + } + } + return -1; +} + +void register_buildings(void) +{ + register_function((pf_generic)minimum_wage, "minimum_wage"); + register_function((pf_generic)init_smithy, "init_smithy"); + register_function((pf_generic)castle_name, "castle_name"); + register_function((pf_generic)castle_name_2, "castle_name_2"); + register_function((pf_generic)fort_name, "fort_name"); +} diff --git a/src/kernel/building.h b/src/kernel/building.h index dad9ffdde..6d66aa9ab 100644 --- a/src/kernel/building.h +++ b/src/kernel/building.h @@ -22,6 +22,9 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include +#include +#include + #ifdef __cplusplus extern "C" { #endif @@ -31,7 +34,6 @@ extern "C" { /* maintenance::flags */ #define MTF_NONE 0x00 #define MTF_VARIABLE 0x01 /* resource usage scales with size */ -#define MTF_VITAL 0x02 /* if resource missing, building may crash */ typedef struct maintenance { const struct resource_type *rtype; /* type of resource required */ @@ -49,22 +51,16 @@ extern "C" { #define BTF_MAGIC 0x40 /* magical effect */ #define BTF_ONEPERTURN 0x80 /* one one sizepoint can be added per turn */ #define BTF_NAMECHANGE 0x100 /* name and description can be changed more than once */ -#define BTF_FORTIFICATION 0x200 /* safe from monsters */ - - typedef enum { - DEFENSE_BONUS, - CLOSE_COMBAT_ATTACK_BONUS, // TODO: only DEFENSE_BONUS is in use? - RANGED_ATTACK_BONUS, - } building_bonus; +#define BTF_FORTIFICATION 0x200 /* building_protection, safe from monsters */ typedef struct building_type { char *_name; int flags; /* flags */ - int capacity; /* Kapazitt pro Grenpunkt */ - int maxcapacity; /* Max. Kapazitt */ + int capacity; /* Kapazit�t pro Gr��enpunkt */ + int maxcapacity; /* Max. Kapazit�t */ int maxsize; /* how big can it get, with all the extensions? */ - int magres; /* how well it resists against spells */ + variant magres; /* how well it resists against spells */ int magresbonus; /* bonus it gives the target against spells */ int fumblebonus; /* bonus that reduces fumbling */ double auraregen; /* modifier for aura regeneration inside building */ @@ -75,14 +71,15 @@ extern "C" { const struct building * b, int size); void(*init) (struct building_type *); void(*age) (struct building *); - int(*protection) (const struct building *, const struct unit *, building_bonus bonus); double(*taxes) (const struct building *, int size); struct attrib *attribs; } building_type; - extern struct quicklist *buildingtypes; + extern struct selist *buildingtypes; extern struct attrib_type at_building_action; + int cmp_castle_size(const struct building *b, const struct building *a); + int building_protection(const struct building_type *btype, int stage); building_type *bt_get_or_create(const char *name); bool bt_changed(int *cache); const building_type *bt_find(const char *name); @@ -132,7 +129,17 @@ extern "C" { int id, int size, struct order *ord); bool building_finished(const struct building *b); - /* Alte Gebudetypen: */ + int wage(const struct region *r, const struct faction *f, + const struct race *rc, int in_turn); + + typedef int(*cmp_building_cb) (const struct building * b, + const struct building * a); + struct building *largestbuilding(const struct region *r, cmp_building_cb, + bool imaginary); + int cmp_wage(const struct building *b, const struct building *bother); + int cmp_taxes(const struct building *b, const struct building *bother); + int cmp_current_owner(const struct building *b, + const struct building *bother); /* old functions, still in build.c: */ int buildingeffsize(const building * b, int imaginary); diff --git a/src/kernel/building.test.c b/src/kernel/building.test.c index 755e9319f..2819d4a16 100644 --- a/src/kernel/building.test.c +++ b/src/kernel/building.test.c @@ -22,7 +22,7 @@ static void test_register_building(CuTest * tc) test_cleanup(); btype = (building_type *)calloc(sizeof(building_type), 1); - btype->_name = _strdup("herp"); + btype->_name = strdup("herp"); CuAssertIntEquals(tc, true, bt_changed(&cache)); CuAssertIntEquals(tc, false, bt_changed(&cache)); bt_register(btype); @@ -376,13 +376,12 @@ static void test_btype_defaults(CuTest *tc) { CuAssertTrue(tc, !btype->name); CuAssertTrue(tc, !btype->init); CuAssertTrue(tc, !btype->age); - CuAssertTrue(tc, !btype->protection); CuAssertTrue(tc, !btype->taxes); CuAssertDblEquals(tc, 1.0, btype->auraregen, 0.0); CuAssertIntEquals(tc, -1, btype->maxsize); CuAssertIntEquals(tc, 1, btype->capacity); CuAssertIntEquals(tc, -1, btype->maxcapacity); - CuAssertIntEquals(tc, 0, btype->magres); + CuAssertIntEquals(tc, 0, btype->magres.sa[0]); CuAssertIntEquals(tc, 0, btype->magresbonus); CuAssertIntEquals(tc, 0, btype->fumblebonus); CuAssertIntEquals(tc, 0, btype->flags); @@ -405,8 +404,8 @@ static void test_buildingtype_exists(CuTest * tc) r = findregion(-1, 0); b = new_building(btype, r, default_locale); - b->size = 10; CuAssertPtrNotNull(tc, b); + b->size = 10; CuAssertTrue(tc, !buildingtype_exists(r, NULL, false)); CuAssertTrue(tc, !buildingtype_exists(r, btype2, false)); @@ -493,12 +492,61 @@ static void test_building_type(CuTest *tc) { test_cleanup(); } +static void test_cmp_castle_size(CuTest *tc) { + region *r; + building *b1, *b2; + unit *u1, *u2; + + test_setup(); + r = test_create_region(0, 0, 0); + b1 = test_create_building(r, NULL); + b2 = test_create_building(r, NULL); + u1 = test_create_unit(test_create_faction(0), r); + u_set_building(u1, b1); + u2 = test_create_unit(test_create_faction(0), r); + u_set_building(u2, b2); + b1->size = 5; + b2->size = 10; + CuAssertTrue(tc, cmp_castle_size(b1, b2)<0); + CuAssertTrue(tc, cmp_castle_size(b2, b1)>0); + CuAssertTrue(tc, cmp_castle_size(b1, NULL)>0); + CuAssertTrue(tc, cmp_castle_size(NULL, b1)<0); + test_cleanup(); +} + +static void test_building_effsize(CuTest *tc) { + building *b; + building_type *btype; + construction *cons; + + test_setup(); + btype = bt_get_or_create("castle"); + cons = btype->construction = calloc(1, sizeof(construction)); + cons->maxsize = 5; + cons = cons->improvement = calloc(1, sizeof(construction)); + cons->maxsize = 5; + cons = cons->improvement = calloc(1, sizeof(construction)); + cons->maxsize = -1; + b = test_create_building(test_create_region(0,0,0), btype); + b->size = 1; + CuAssertIntEquals(tc, 0, buildingeffsize(b, false)); + b->size = 5; + CuAssertIntEquals(tc, 1, buildingeffsize(b, false)); + b->size = 10; + CuAssertIntEquals(tc, 2, buildingeffsize(b, false)); + b->size = 20; + CuAssertIntEquals(tc, 2, buildingeffsize(b, false)); + test_cleanup(); +} + CuSuite *get_building_suite(void) { CuSuite *suite = CuSuiteNew(); + SUITE_ADD_TEST(suite, test_cmp_castle_size); SUITE_ADD_TEST(suite, test_register_building); SUITE_ADD_TEST(suite, test_btype_defaults); SUITE_ADD_TEST(suite, test_building_set_owner); + SUITE_ADD_TEST(suite, test_building_effsize); SUITE_ADD_TEST(suite, test_buildingowner_resets_when_empty); SUITE_ADD_TEST(suite, test_buildingowner_goes_to_next_when_empty); SUITE_ADD_TEST(suite, test_buildingowner_goes_to_other_when_empty); diff --git a/src/kernel/command.test.c b/src/kernel/command.test.c index f38c7e443..25e75fdc3 100644 --- a/src/kernel/command.test.c +++ b/src/kernel/command.test.c @@ -10,7 +10,9 @@ without prior permission by the authors of Eressea. */ +#include #include "command.h" + #include "unit.h" #include "order.h" diff --git a/src/kernel/config.c b/src/kernel/config.c index aaecd2c91..3f04b03b3 100644 --- a/src/kernel/config.c +++ b/src/kernel/config.c @@ -19,9 +19,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include -/* attributes includes */ -#include - /* kernel includes */ #include "alliance.h" #include "ally.h" @@ -66,11 +63,9 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include #include #include #include -#include #include #include @@ -96,77 +91,15 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include +#include struct settings global = { "Eressea", /* gamename */ }; bool lomem = false; -FILE *logfile; -bool battledebug = false; int turn = -1; -int NewbieImmunity(void) -{ - return config_get_int("NewbieImmunity", 0); -} - -bool IsImmune(const faction * f) -{ - return !fval(f, FFL_NPC) && f->age < NewbieImmunity(); -} - -bool ExpensiveMigrants(void) -{ - return config_get_int("study.expensivemigrants", 0) != 0; -} - -int LongHunger(const struct unit *u) -{ - if (u != NULL) { - if (!fval(u, UFL_HUNGER)) - return false; - if (u_race(u) == get_race(RC_DAEMON)) - return false; - } - return config_get_int("hunger.long", 0); -} - -int NMRTimeout(void) -{ - return config_get_int("nmr.timeout", 0); -} - -race_t old_race(const struct race * rc) -{ - race_t i; - // TODO: this sucks so bad! - for (i = 0; i != MAXRACES; ++i) { - if (get_race(i) == rc) return i; - } - return NORACE; -} - -helpmode helpmodes[] = { - { "all", HELP_ALL } - , - { "money", HELP_MONEY } - , - { "fight", HELP_FIGHT } - , - { "observe", HELP_OBSERVE } - , - { "give", HELP_GIVE } - , - { "guard", HELP_GUARD } - , - { "stealth", HELP_FSTEALTH } - , - { "travel", HELP_TRAVEL } - , - { NULL, 0 } -}; - const char *parameters[MAXPARAMS] = { "LOCALE", "ALLES", @@ -190,7 +123,7 @@ const char *parameters[MAXPARAMS] = { "TEMP", "FLIEHE", "GEBAEUDE", - "GIB", /* Fr HELFE */ + "GIB", /* F�r HELFE */ "KAEMPFE", "DURCHREISE", "BEWACHE", @@ -214,43 +147,6 @@ const char *parameters[MAXPARAMS] = { "ALLIANZ" }; -const char *report_options[MAX_MSG] = { - "Kampf", - "Ereignisse", - "Bewegung", - "Einkommen", - "Handel", - "Produktion", - "Orkvermehrung", - "Zauber", - "", - "" -}; - -const char *message_levels[ML_MAX] = { - "Wichtig", - "Debug", - "Fehler", - "Warnungen", - "Infos" -}; - -const char *options[MAXOPTIONS] = { - "AUSWERTUNG", - "COMPUTER", - "ZUGVORLAGE", - NULL, - "STATISTIK", - "DEBUG", - "ZIPPED", - "ZEITUNG", /* Option hat Sonderbehandlung! */ - NULL, - "ADRESSEN", - "BZIP2", - "PUNKTE", - "SHOWSKCHANGE" -}; - FILE *debug; void @@ -284,18 +180,6 @@ parse(keyword_t kword, int(*dofun) (unit *, struct order *), bool thisorder) } } -const struct race *findrace(const char *s, const struct locale *lang) -{ - void **tokens = get_translations(lang, UT_RACES); - variant token; - - assert(lang); - if (tokens && findtoken(*tokens, s, &token) == E_TOK_SUCCESS) { - return (const struct race *)token.v; - } - return NULL; -} - int findoption(const char *s, const struct locale *lang) { void **tokens = get_translations(lang, UT_OPTIONS); @@ -319,7 +203,7 @@ param_t findparam(const char *s, const struct locale * lang) void **tokens = get_translations(lang, UT_PARAMS); critbit_tree *cb = (critbit_tree *)*tokens; if (!cb) { - log_error("no parameters defined in locale %s", locale_name(lang)); + log_warning("no parameters defined in locale %s", locale_name(lang)); } else if (cb_find_prefix(cb, str, strlen(str), &match, 1, 0)) { cb_get_kv(match, &i, sizeof(int)); @@ -329,6 +213,27 @@ param_t findparam(const char *s, const struct locale * lang) return result; } +param_t findparam_block(const char *s, const struct locale *lang, bool any_locale) +{ + param_t p; + if (!s || s[0] == '@') { + return NOPARAM; + } + p = findparam(s, lang); + if (any_locale && p==NOPARAM) { + const struct locale *loc; + for (loc=locales;loc;loc=nextlocale(loc)) { + if (loc!=lang) { + p = findparam(s, loc); + if (p==P_FACTION || p==P_GAMENAME) { + break; + } + } + } + } + return p; +} + param_t findparam_ex(const char *s, const struct locale * lang) { param_t result = findparam(s, lang); @@ -366,42 +271,10 @@ unit *getnewunit(const region * r, const faction * f) return findnewunit(r, f, n); } -/* - Namen der Strukturen -------------------------------------- */ -char *untilde(char *ibuf) -{ - char *p = ibuf; - - while (*p) { - if (*p == '~') { - *p = ' '; - } - ++p; - } - return ibuf; -} - -building *largestbuilding(const region * r, cmp_building_cb cmp_gt, - bool imaginary) -{ - building *b, *best = NULL; - - for (b = rbuildings(r); b; b = b->next) { - if (cmp_gt(b, best) <= 0) - continue; - if (!imaginary) { - const attrib *a = a_find(b->attribs, &at_icastle); - if (a) - continue; - } - best = b; - } - return best; -} /* -- Erschaffung neuer Einheiten ------------------------------ */ static const char *forbidden[] = { "t", "te", "tem", "temp", NULL }; -// PEASANT: "b", "ba", "bau", "baue", "p", "pe", "pea", "peas" static int *forbidden_ids; int forbiddenid(int id) @@ -444,13 +317,6 @@ int newcontainerid(void) return random_no; } -int maxworkingpeasants(const struct region *r) -{ - int size = production(r); - int treespace = (rtrees(r, 2) + rtrees(r, 1) / 2) * TREESIZE; - return _max(size - treespace, _min(size / 10, 200)); -} - static const char * parameter_key(int i) { assert(i < MAXPARAMS && i >= 0); @@ -516,7 +382,7 @@ void init_locale(struct locale *lang) str = "gwyrrd illaun draig cerddor tybied"; } - sstr = _strdup(str); + sstr = strdup(str); tok = strtok(sstr, " "); while (tok) { const char *name; @@ -624,19 +490,19 @@ int check_param(const struct param *p, const char *key, const char *searchvalue) { int result = 0; const char *value = get_param(p, key); + char *v, *p_value; if (!value) { return 0; } - char *p_value = _strdup(value); - const char *delimiter = " ,;"; - char *v = strtok(p_value, delimiter); + p_value = strdup(value); + v = strtok(p_value, " ,;"); while (v != NULL) { if (strcmp(v, searchvalue) == 0) { result = 1; break; } - v = strtok(NULL, delimiter); + v = strtok(NULL, " ,;"); } free(p_value); return result; @@ -690,7 +556,7 @@ static const char * relpath(char *buf, size_t sz, const char *path) { static const char *g_datadir; const char *datapath(void) { - static char zText[MAX_PATH]; // FIXME: static return value + static char zText[4096]; if (g_datadir) return g_datadir; return relpath(zText, sizeof(zText), "data"); @@ -704,7 +570,7 @@ void set_datapath(const char *path) static const char *g_reportdir; const char *reportpath(void) { - static char zText[MAX_PATH]; // FIXME: static return value + static char zText[4096]; if (g_reportdir) return g_reportdir; return relpath(zText, sizeof(zText), "reports"); @@ -717,12 +583,12 @@ void set_reportpath(const char *path) int create_directories(void) { int err; - err = _mkdir(datapath()); + err = mkdir(datapath(), 0777); if (err) { if (errno == EEXIST) errno = 0; else return err; } - err = _mkdir(reportpath()); + err = mkdir(reportpath(), 0777); if (err && errno == EEXIST) { errno = 0; } @@ -731,7 +597,7 @@ int create_directories(void) { double get_param_flt(const struct param *p, const char *key, double def) { - const char *str = get_param(p, key); + const char *str = p ? get_param(p, key) : NULL; return str ? atof(str) : def; } @@ -740,7 +606,9 @@ void kernel_done(void) /* calling this function releases memory assigned to static variables, etc. * calling it is optional, e.g. a release server will most likely not do it. */ +#ifdef USE_LIBXML2 xml_done(); +#endif attrib_done(); item_done(); message_done(); @@ -751,118 +619,12 @@ void kernel_done(void) translation_done(); } -#ifndef HAVE_STRDUP -char *_strdup(const char *s) -{ - return strcpy((char *)malloc(sizeof(char) * (strlen(s) + 1)), s); -} -#endif - -/* Lohn bei den einzelnen Burgstufen fr Normale Typen, Orks, Bauern, - * Modifikation fr Stdter. */ - -static const int wagetable[7][4] = { - { 10, 10, 11, -7 }, /* Baustelle */ - { 10, 10, 11, -5 }, /* Handelsposten */ - { 11, 11, 12, -3 }, /* Befestigung */ - { 12, 11, 13, -1 }, /* Turm */ - { 13, 12, 14, 0 }, /* Burg */ - { 14, 12, 15, 1 }, /* Festung */ - { 15, 13, 16, 2 } /* Zitadelle */ -}; - -int cmp_wage(const struct building *b, const building * a) -{ - if (is_building_type(b->type, "castle")) { - if (!a) - return 1; - if (b->size > a->size) - return 1; - if (b->size == a->size) - return 0; - } - return -1; -} - -bool is_owner_building(const struct building * b) -{ - region *r = b->region; - if (b->type->taxes && r->land && r->land->ownership) { - unit *u = building_owner(b); - return u && u->faction == r->land->ownership->owner; - } - return false; -} - -int cmp_taxes(const building * b, const building * a) -{ - faction *f = region_get_owner(b->region); - if (b->type->taxes) { - unit *u = building_owner(b); - if (!u) { - return -1; - } - else if (a) { - int newsize = buildingeffsize(b, false); - double newtaxes = b->type->taxes(b, newsize); - int oldsize = buildingeffsize(a, false); - double oldtaxes = a->type->taxes(a, oldsize); - - if (newtaxes < oldtaxes) - return -1; - else if (newtaxes > oldtaxes) - return 1; - else if (b->size < a->size) - return -1; - else if (b->size > a->size) - return 1; - else { - if (u && u->faction == f) { - u = building_owner(a); - if (u && u->faction == f) - return -1; - return 1; - } - } - } - else { - return 1; - } - } - return -1; -} - -int cmp_current_owner(const building * b, const building * a) -{ - faction *f = region_get_owner(b->region); - - assert(rule_region_owners()); - if (f && b->type->taxes) { - unit *u = building_owner(b); - if (!u || u->faction != f) - return -1; - if (a) { - int newsize = buildingeffsize(b, false); - double newtaxes = b->type->taxes(b, newsize); - int oldsize = buildingeffsize(a, false); - double oldtaxes = a->type->taxes(a, oldsize); - - if (newtaxes != oldtaxes) - return (newtaxes > oldtaxes) ? 1 : -1; - if (newsize != oldsize) - return newsize - oldsize; - return (b->size - a->size); - } - else { - return 1; - } - } - return -1; -} - bool rule_stealth_other(void) { - int rule = config_get_int("stealth.faction.other", 1); + static int rule, config; + if (config_changed(&config)) { + rule = config_get_int("stealth.faction.other", 1); + } return rule != 0; } @@ -917,113 +679,11 @@ int rule_faction_limit(void) return rule; } -static int -default_wage(const region * r, const faction * f, const race * rc, int in_turn) -{ - building *b = largestbuilding(r, &cmp_wage, false); - int esize = 0; - double wage; - static int ct_cache; - static const struct curse_type *drought_ct; - - if (ct_changed(&ct_cache)) { - drought_ct = ct_find("drought"); - } - if (b != NULL) { - /* TODO: this reveals imaginary castles */ - esize = buildingeffsize(b, false); - } - - if (f != NULL) { - int index = 0; - if (rc == get_race(RC_ORC) || rc == get_race(RC_SNOTLING)) { - index = 1; - } - wage = wagetable[esize][index]; - } - else { - if (is_mourning(r, in_turn)) { - wage = 10; - } - else if (fval(r->terrain, SEA_REGION)) { - wage = 11; - } - else if (fval(r, RF_ORCIFIED)) { - wage = wagetable[esize][1]; - } - else { - wage = wagetable[esize][2]; - } - if (rule_blessed_harvest() == HARVEST_WORK) { - /* E1 rules */ - wage += curse_geteffect(get_curse(r->attribs, ct_find("blessedharvest"))); - } - } - - /* Artsculpture: Income +5 */ - for (b = r->buildings; b; b = b->next) { - if (is_building_type(b->type, "artsculpture")) { - wage += 5; - } - } - - if (r->attribs) { - attrib *a; - const struct curse_type *ctype; - /* Godcurse: Income -10 */ - ctype = ct_find("godcursezone"); - if (ctype && curse_active(get_curse(r->attribs, ctype))) { - wage = _max(0, wage - 10); - } - - /* Bei einer Drre verdient man nur noch ein Viertel */ - if (drought_ct) { - curse *c = get_curse(r->attribs, drought_ct); - if (curse_active(c)) - wage /= curse_geteffect(c); - } - - a = a_find(r->attribs, &at_reduceproduction); - if (a) { - wage = (wage * a->data.sa[0]) / 100; - } - } - return (int)wage; -} - -static int -minimum_wage(const region * r, const faction * f, const race * rc, int in_turn) -{ - if (f && rc) { - return rc->maintenance; - } - return default_wage(r, f, rc, in_turn); -} - -/* Gibt Arbeitslohn fr entsprechende Rasse zurck, oder fr -* die Bauern wenn f == NULL. */ -int wage(const region * r, const faction * f, const race * rc, int in_turn) -{ - if (global.functions.wage) { - return global.functions.wage(r, f, rc, in_turn); - } - return default_wage(r, f, rc, in_turn); -} - -int lovar(double xpct_x2) -{ - int n = (int)(xpct_x2 * 500) + 1; - if (n == 0) - return 0; - return (rng_int() % n + rng_int() % n) / 1000; -} - void kernel_init(void) { register_reports(); mt_clear(); translation_init(); - register_function((pf_generic)minimum_wage, "minimum_wage"); } static order * defaults[MAXLOCALES]; @@ -1050,23 +710,6 @@ order *default_order(const struct locale *lang) return result ? copy_order(result) : 0; } -int entertainmoney(const region * r) -{ - double n; - - if (is_cursed(r->attribs, C_DEPRESSION, 0)) { - return 0; - } - - n = rmoney(r) / ENTERTAINFRACTION; - - if (is_cursed(r->attribs, C_GENEROUS, 0)) { - n *= get_curseeffect(r->attribs, C_GENEROUS, 0); - } - - return (int)n; -} - int rule_give(void) { static int config; @@ -1077,11 +720,6 @@ int rule_give(void) return rule; } -bool markets_module(void) -{ - return (bool)config_get_int("modules.markets", 0); -} - static struct param *configuration; static int config_cache_key = 1; @@ -1094,6 +732,39 @@ bool config_changed(int *cache_key) { return false; } +#define MAXKEYS 16 +void config_set_from(const dictionary *d) +{ + int s, nsec = iniparser_getnsec(d); + for (s=0;s!=nsec;++s) { + char key[128]; + const char *sec = iniparser_getsecname(d, s); + int k, nkeys = iniparser_getsecnkeys(d, sec); + const char *keys[MAXKEYS]; + size_t slen = strlen(sec); + assert(nkeys <= MAXKEYS); + assert(slenr) { + *r++ = (char)toupper(*c++); + } + *r = '\0'; + return result; +} + int game_id(void) { return config_get_int("game.id", 0); } - diff --git a/src/kernel/config.h b/src/kernel/config.h index 74565e25e..e38d1dd56 100644 --- a/src/kernel/config.h +++ b/src/kernel/config.h @@ -24,22 +24,19 @@ extern "C" { #endif /* this should always be the first thing included after platform.h */ +#include +#include #include "types.h" -struct param; -#define DISPLAYSIZE 8192 /* max. Lnge einer Beschreibung, incl trailing 0 */ + struct param; + struct _dictionary_; + +#define DISPLAYSIZE 8192 /* max. L�nge einer Beschreibung, incl trailing 0 */ #define ORDERSIZE (DISPLAYSIZE*2) /* max. length of an order */ -#define NAMESIZE 128 /* max. Lnge eines Namens, incl trailing 0 */ -#define IDSIZE 16 /* max. Lnge einer no (als String), incl trailing 0 */ -#define OBJECTIDSIZE (NAMESIZE+5+IDSIZE) /* max. Lnge der Strings, die - * von struct unitname, etc. zurckgegeben werden. ohne die 0 */ - - /* ----------------- Befehle ----------------------------------- */ - -#define want(option) (1<flags & (i)) #define fset(u, i) ((u)->flags |= (i)) @@ -48,20 +45,14 @@ struct param; int findoption(const char *s, const struct locale *lang); param_t findparam(const char *s, const struct locale *lang); + param_t findparam_block(const char *s, const struct locale *lang, bool any_locale); param_t findparam_ex(const char *s, const struct locale * lang); bool isparam(const char *s, const struct locale * lang, param_t param); param_t getparam(const struct locale *lang); -#define unitid(x) itoa36((x)->no) - -#define buildingid(x) itoa36((x)->no) -#define shipid(x) itoa36((x)->no) -#define factionid(x) itoa36((x)->no) -#define curseid(x) itoa36((x)->no) - const char * game_name(void); + const char * game_name_upper(void); int game_id(void); - int lovar(double xpct_x2); /* returns a value between [0..xpct_2], generated with two dice */ void init_locale(struct locale *lang); @@ -69,20 +60,9 @@ struct param; int forbiddenid(int id); int newcontainerid(void); - char *untilde(char *s); - - typedef int(*cmp_building_cb) (const struct building * b, - const struct building * a); - struct building *largestbuilding(const struct region *r, cmp_building_cb, - bool imaginary); - int cmp_wage(const struct building *b, const struct building *bother); - int cmp_taxes(const struct building *b, const struct building *bother); - int cmp_current_owner(const struct building *b, - const struct building *bother); - bool rule_region_owners(void); - bool rule_stealth_other(void); // units can pretend to be another faction, TARNE PARTEI - bool rule_stealth_anon(void); // units can anonymize their faction, TARNE PARTEI [NICHT] + bool rule_stealth_other(void); /* units can pretend to be another faction, TARNE PARTEI */ + bool rule_stealth_anon(void); /* units can anonymize their faction, TARNE PARTEI [NICHT] */ int rule_alliance_limit(void); int rule_faction_limit(void); #define HARVEST_WORK 0x00 @@ -98,8 +78,6 @@ struct param; #define GIVE_DEFAULT (GIVE_SELF|GIVE_PEASANTS|GIVE_LUXURIES|GIVE_HERBS|GIVE_GOODS) int rule_give(void); - const struct race *findrace(const char *, const struct locale *); - /* grammatik-flags: */ #define GF_NONE 0 /* singular, ohne was dran */ @@ -110,34 +88,10 @@ struct param; #define GF_SPECIFIC 16 /* der, die, das vs. ein, eine */ #define GF_DETAILED 32 - /* mehr Informationen. z.b. strae zu 50% */ + /* mehr Informationen. z.b. stra�e zu 50% */ #define GF_PURE 64 /* untranslated */ -#define GUARD_NONE 0 -#define GUARD_TAX 1 - /* Verhindert Steuereintreiben */ -#define GUARD_MINING 2 - /* Verhindert Bergbau */ -#define GUARD_TREES 4 - /* Verhindert Waldarbeiten */ -#define GUARD_TRAVELTHRU 8 - /* Blockiert Durchreisende */ -#define GUARD_LANDING 16 - /* Verhindert Ausstieg + Weiterreise */ -#define GUARD_CREWS 32 - /* Verhindert Unterhaltung auf Schiffen */ -#define GUARD_RECRUIT 64 - /* Verhindert Rekrutieren */ -#define GUARD_PRODUCE 128 - /* Verhindert Abbau von Resourcen mit RTF_LIMITED */ -#define GUARD_ALL 0xFFFF - - int maxworkingpeasants(const struct region *r); - bool markets_module(void); - int wage(const struct region *r, const struct faction *f, - const struct race *rc, int in_turn); - const char *datapath(void); void set_datapath(const char *path); @@ -158,19 +112,12 @@ struct param; struct attrib *attribs; unsigned int data_turn; void *vm_state; - int data_version; /* TODO: eliminate in favor of gamedata.version */ - struct _dictionary_ *inifile; struct global_functions { int(*wage) (const struct region * r, const struct faction * f, const struct race * rc, int in_turn); } functions; } settings; - typedef struct helpmode { - const char *name; - int status; - } helpmode; - void set_param(struct param **p, const char *key, const char *value); const char *get_param(const struct param *p, const char *key); int get_param_int(const struct param *p, const char *key, int def); @@ -179,6 +126,7 @@ struct param; void free_params(struct param **pp); void config_set(const char *key, const char *value); + void config_set_from(const struct _dictionary_ *d); const char *config_get(const char *key); int config_get_int(const char *key, int def); double config_get_flt(const char *key, double def); @@ -186,32 +134,19 @@ struct param; bool config_changed(int *cache_key); char * join_path(const char *p1, const char *p2, char *dst, size_t len); - bool ExpensiveMigrants(void); - int NMRTimeout(void); - int LongHunger(const struct unit *u); - int NewbieImmunity(void); - bool IsImmune(const struct faction *f); struct order *default_order(const struct locale *lang); - int entertainmoney(const struct region *r); void init_parameters(struct locale *lang); void free_gamedata(void); void free_config(void); - extern struct helpmode helpmodes[]; extern const char *parameters[]; - extern const char *localenames[]; extern settings global; - extern bool battledebug; - extern bool sqlpatch; extern bool lomem; /* save memory */ extern int turn; - extern bool getunitpeasants; - - extern const char *options[MAXOPTIONS]; /* report options */ #ifdef __cplusplus } diff --git a/src/kernel/config.test.c b/src/kernel/config.test.c index 405587443..9a10a4c56 100644 --- a/src/kernel/config.test.c +++ b/src/kernel/config.test.c @@ -9,6 +9,8 @@ #include #include +#include + #include #include @@ -49,7 +51,7 @@ static void test_read_unitid(CuTest *tc) { CuAssertIntEquals(tc, -1, read_unitid(u->faction, u->region)); free_order(ord); - // bug https://bugs.eressea.de/view.php?id=1685 + /* bug https://bugs.eressea.de/view.php?id=1685 */ ord = create_order(K_GIVE, lang, "##"); init_order(ord); CuAssertIntEquals(tc, -1, read_unitid(u->faction, u->region)); @@ -96,14 +98,14 @@ static void test_getunit(CuTest *tc) { CuAssertPtrEquals(tc, NULL, u2); free_order(ord); - // bug https://bugs.eressea.de/view.php?id=1685 + /* bug https://bugs.eressea.de/view.php?id=1685 */ ord = create_order(K_GIVE, lang, "TEMP ##"); init_order(ord); CuAssertIntEquals(tc, GET_NOTFOUND, getunit(u->region, u->faction, &u2)); CuAssertPtrEquals(tc, NULL, u2); free_order(ord); - // bug https://bugs.eressea.de/view.php?id=1685 + /* bug https://bugs.eressea.de/view.php?id=1685 */ ord = create_order(K_GIVE, lang, "##"); init_order(ord); CuAssertIntEquals(tc, GET_NOTFOUND, getunit(u->region, u->faction, &u2)); @@ -233,9 +235,50 @@ static void test_rules(CuTest *tc) { CuAssertIntEquals(tc, 1000, rule_faction_limit()); } +static void test_config_inifile(CuTest *tc) { + dictionary *ini; + test_setup(); + ini = dictionary_new(0); + dictionary_set(ini, "game", NULL); + iniparser_set(ini, "game:id", "42"); + iniparser_set(ini, "game:name", "Eressea"); + config_set_from(ini); + CuAssertStrEquals(tc, "Eressea", config_get("game.name")); + CuAssertStrEquals(tc, "Eressea", game_name()); + CuAssertStrEquals(tc, "ERESSEA", game_name_upper()); + CuAssertIntEquals(tc, 42, game_id()); + iniparser_freedict(ini); + test_cleanup(); +} + +static void test_findparam(CuTest *tc) { + struct locale *en, *de; + test_setup(); + en = get_or_create_locale("en"); + locale_setstring(en, parameters[P_FACTION], "FACTION"); + CuAssertIntEquals(tc, NOPARAM, findparam("FACTION", en)); + init_parameters(en); + CuAssertIntEquals(tc, P_FACTION, findparam("FACTION", en)); + de = get_or_create_locale("de"); + locale_setstring(de, parameters[P_FACTION], "PARTEI"); + CuAssertIntEquals(tc, NOPARAM, findparam("PARTEI", de)); + init_parameters(de); + CuAssertIntEquals(tc, P_FACTION, findparam("PARTEI", de)); + CuAssertIntEquals(tc, NOPARAM, findparam("HODOR", de)); + + CuAssertIntEquals(tc, NOPARAM, findparam("PARTEI", en)); + CuAssertIntEquals(tc, NOPARAM, findparam_block("HODOR", de, false)); + CuAssertIntEquals(tc, P_FACTION, findparam_block("PARTEI", de, true)); + CuAssertIntEquals(tc, NOPARAM, findparam_block("PARTEI", en, false)); + CuAssertIntEquals(tc, P_FACTION, findparam_block("PARTEI", en, true)); + test_cleanup(); +} + CuSuite *get_config_suite(void) { CuSuite *suite = CuSuiteNew(); + SUITE_ADD_TEST(suite, test_findparam); + SUITE_ADD_TEST(suite, test_config_inifile); SUITE_ADD_TEST(suite, test_config_cache); SUITE_ADD_TEST(suite, test_get_set_param); SUITE_ADD_TEST(suite, test_param_int); diff --git a/src/kernel/connection.c b/src/kernel/connection.c index 9bbff5778..43caee729 100644 --- a/src/kernel/connection.c +++ b/src/kernel/connection.c @@ -21,7 +21,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "connection.h" #include "region.h" -#include "save.h" #include "terrain.h" #include "unit.h" @@ -30,7 +29,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include +#include #include #include @@ -132,7 +131,7 @@ static connection **get_borders_i(const region * r1, const region * r2) int key = reg_hashkey(r1); int k2 = reg_hashkey(r2); - key = _min(k2, key) % BORDER_MAXHASH; + key = MIN(k2, key) % BORDER_MAXHASH; bp = &borders[key]; while (*bp) { connection *b = *bp; @@ -212,7 +211,7 @@ border_type *find_bordertype(const char *name) { border_type *bt = bordertypes; - while (bt && strcmp(bt->__name, name)) + while (bt && strcmp(bt->__name, name)!=0) bt = bt->next; return bt; } @@ -259,31 +258,31 @@ void b_write(const connection * b, storage * store) bool b_transparent(const connection * b, const struct faction *f) { - unused_arg(b); - unused_arg(f); + UNUSED_ARG(b); + UNUSED_ARG(f); return true; } bool b_opaque(const connection * b, const struct faction * f) { - unused_arg(b); - unused_arg(f); + UNUSED_ARG(b); + UNUSED_ARG(f); return false; } bool b_blockall(const connection * b, const unit * u, const region * r) { - unused_arg(u); - unused_arg(r); - unused_arg(b); + UNUSED_ARG(u); + UNUSED_ARG(r); + UNUSED_ARG(b); return true; } bool b_blocknone(const connection * b, const unit * u, const region * r) { - unused_arg(u); - unused_arg(r); - unused_arg(b); + UNUSED_ARG(u); + UNUSED_ARG(r); + UNUSED_ARG(b); return false; } @@ -295,39 +294,39 @@ bool b_rvisible(const connection * b, const region * r) bool b_fvisible(const connection * b, const struct faction * f, const region * r) { - unused_arg(r); - unused_arg(f); - unused_arg(b); + UNUSED_ARG(r); + UNUSED_ARG(f); + UNUSED_ARG(b); return true; } bool b_uvisible(const connection * b, const unit * u) { - unused_arg(u); - unused_arg(b); + UNUSED_ARG(u); + UNUSED_ARG(b); return true; } bool b_rinvisible(const connection * b, const region * r) { - unused_arg(r); - unused_arg(b); + UNUSED_ARG(r); + UNUSED_ARG(b); return false; } bool b_finvisible(const connection * b, const struct faction * f, const region * r) { - unused_arg(r); - unused_arg(f); - unused_arg(b); + UNUSED_ARG(r); + UNUSED_ARG(f); + UNUSED_ARG(b); return false; } bool b_uinvisible(const connection * b, const unit * u) { - unused_arg(u); - unused_arg(b); + UNUSED_ARG(u); + UNUSED_ARG(b); return false; } @@ -346,7 +345,7 @@ attrib_type at_countdown = { void age_borders(void) { - quicklist *deleted = NULL, *ql; + selist *deleted = NULL, *ql; int i; for (i = 0; i != BORDER_MAXHASH; ++i) { @@ -356,17 +355,17 @@ void age_borders(void) for (; b; b = b->next) { if (b->type->age) { if (b->type->age(b) == AT_AGE_REMOVE) { - ql_push(&deleted, b); + selist_push(&deleted, b); } } } } } - for (ql = deleted, i = 0; ql; ql_advance(&ql, &i, 1)) { - connection *b = (connection *)ql_get(ql, i); + for (ql = deleted, i = 0; ql; selist_advance(&ql, &i, 1)) { + connection *b = (connection *)selist_get(ql, i); erase_border(b); } - ql_free(deleted); + selist_free(deleted); } /******** @@ -381,9 +380,9 @@ static const char *b_namewall(const connection * b, const region * r, { const char *bname = "wall"; - unused_arg(f); - unused_arg(r); - unused_arg(b); + UNUSED_ARG(f); + UNUSED_ARG(r); + UNUSED_ARG(b); if (gflags & GF_ARTICLE) bname = "a_wall"; if (gflags & GF_PURE) @@ -422,9 +421,9 @@ border_type bt_noway = { static const char *b_namefogwall(const connection * b, const region * r, const struct faction *f, int gflags) { - unused_arg(f); - unused_arg(b); - unused_arg(r); + UNUSED_ARG(f); + UNUSED_ARG(b); + UNUSED_ARG(r); if (gflags & GF_PURE) return "fogwall"; if (gflags & GF_ARTICLE) @@ -435,7 +434,7 @@ static const char *b_namefogwall(const connection * b, const region * r, static bool b_blockfogwall(const connection * b, const unit * u, const region * r) { - unused_arg(b); + UNUSED_ARG(b); if (!u) return true; return (bool)(effskill(u, SK_PERCEPTION, r) > 4); /* Das ist die alte Nebelwand */ @@ -460,8 +459,8 @@ static const char *b_nameillusionwall(const connection * b, const region * r, const struct faction *f, int gflags) { int fno = b->data.i; - unused_arg(b); - unused_arg(r); + UNUSED_ARG(b); + UNUSED_ARG(r); if (gflags & GF_PURE) return (f && fno == f->no) ? "illusionwall" : "wall"; if (gflags & GF_ARTICLE) { @@ -497,7 +496,7 @@ static const char *b_nameroad(const connection * b, const region * r, int local = (r == b->from) ? b->data.sa[0] : b->data.sa[1]; static char buffer[64]; - unused_arg(f); + UNUSED_ARG(f); if (gflags & GF_PURE) return "road"; if (gflags & GF_ARTICLE) { @@ -513,7 +512,7 @@ static const char *b_nameroad(const connection * b, const region * r, } } else { - int percent = _max(1, 100 * local / r->terrain->max_road); + int percent = MAX(1, 100 * local / r->terrain->max_road); if (local) { slprintf(buffer, sizeof(buffer), LOC(f->locale, mkname("border", "a_road_percent")), percent); @@ -621,7 +620,6 @@ int read_borders(gamedata *data) assert(type || !"connection type not registered"); } - READ_INT(store, &bid); if (data->version < UIDHASH_VERSION) { int fx, fy, tx, ty; @@ -640,18 +638,16 @@ int read_borders(gamedata *data) to = findregionbyid(tid); } if (!to || !from) { - if (!to || !from) { - log_error("%s connection %d has missing regions", zText, bid); - } + log_error("%s connection %d has missing regions", zText, bid); if (type->read) { - // skip ahead + /* skip ahead */ connection dummy; type->read(&dummy, data); } continue; } - if (to == from && type && from) { + if (to == from && from) { direction_t dir = (direction_t)(rng_int() % MAXDIRECTIONS); region *r = rconnect(from, dir); log_error("[read_borders] invalid %s in %s\n", type->__name, regionname(from, NULL)); @@ -660,7 +656,7 @@ int read_borders(gamedata *data) } if (type->read) { connection *b = new_border(type, from, to); - nextborder--; /* new_border erhht den Wert */ + nextborder--; /* new_border erh�ht den Wert */ b->id = bid; assert(bid <= nextborder); type->read(b, data); diff --git a/src/kernel/connection.h b/src/kernel/connection.h index 7eef0f52a..80177c638 100644 --- a/src/kernel/connection.h +++ b/src/kernel/connection.h @@ -20,7 +20,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #define H_KRNL_BORDER #include - +#include #ifdef __cplusplus extern "C" { #endif diff --git a/src/kernel/curse.c b/src/kernel/curse.c index ac2e917a7..25f89ec1f 100644 --- a/src/kernel/curse.c +++ b/src/kernel/curse.c @@ -109,7 +109,7 @@ int curse_age(attrib * a, void *owner) curse *c = (curse *)a->data.v; int result = 0; - unused_arg(owner); + UNUSED_ARG(owner); c_clearflag(c, CURSE_ISNEW); if (c_flags(c) & CURSE_NOAGE) { @@ -122,7 +122,7 @@ int curse_age(attrib * a, void *owner) c->duration = 0; } else if (c->duration != INT_MAX) { - c->duration = _max(0, c->duration - 1); + c->duration = MAX(0, c->duration - 1); } return (c->duration > 0) ? AT_AGE_KEEP : AT_AGE_REMOVE; } @@ -287,10 +287,10 @@ attrib_type at_curse = { /* Spruch identifizieren */ #include -#include +#include #define MAXCTHASH 128 -static quicklist *cursetypes[MAXCTHASH]; +static selist *cursetypes[MAXCTHASH]; static int ct_changes = 1; bool ct_changed(int *cache) @@ -306,25 +306,25 @@ bool ct_changed(int *cache) void ct_register(const curse_type * ct) { unsigned int hash = tolower(ct->cname[0]) & 0xFF; - quicklist **ctlp = cursetypes + hash; + selist **ctlp = cursetypes + hash; - ql_set_insert(ctlp, (void *)ct); + selist_set_insert(ctlp, (void *)ct, NULL); ++ct_changes; } void ct_remove(const char *c) { unsigned int hash = tolower(c[0]); - quicklist *ctl = cursetypes[hash]; + selist *ctl = cursetypes[hash]; if (ctl) { int qi; - for (qi = 0; ctl; ql_advance(&ctl, &qi, 1)) { - curse_type *type = (curse_type *)ql_get(ctl, qi); + for (qi = 0; ctl; selist_advance(&ctl, &qi, 1)) { + curse_type *type = (curse_type *)selist_get(ctl, qi); if (strcmp(c, type->cname) == 0) { - ql_delete(&ctl, qi); + selist_delete(&ctl, qi); ++ct_changes; break; } @@ -335,21 +335,21 @@ void ct_remove(const char *c) const curse_type *ct_find(const char *c) { unsigned int hash = tolower(c[0]); - quicklist *ctl = cursetypes[hash]; + selist *ctl = cursetypes[hash]; if (ctl) { size_t c_len = strlen(c); int qi; - for (qi = 0; ctl; ql_advance(&ctl, &qi, 1)) { - curse_type *type = (curse_type *)ql_get(ctl, qi); + for (qi = 0; ctl; selist_advance(&ctl, &qi, 1)) { + curse_type *type = (curse_type *)selist_get(ctl, qi); if (strcmp(c, type->cname) == 0) { return type; } else { - size_t k = _min(c_len, strlen(type->cname)); - if (!_memicmp(c, type->cname, k)) { + size_t k = MIN(c_len, strlen(type->cname)); + if (!memcmp(c, type->cname, k)) { return type; } } @@ -360,12 +360,12 @@ const curse_type *ct_find(const char *c) void ct_checknames(void) { int i, qi; - quicklist *ctl; + selist *ctl; for (i = 0; i < MAXCTHASH; ++i) { ctl = cursetypes[i]; - for (qi = 0; ctl; ql_advance(&ctl, &qi, 1)) { - curse_type *type = (curse_type *)ql_get(ctl, qi); + for (qi = 0; ctl; selist_advance(&ctl, &qi, 1)) { + curse_type *type = (curse_type *)selist_get(ctl, qi); curse_name(type, default_locale); } @@ -507,7 +507,7 @@ int get_cursedmen(unit * u, const curse * c) cursedmen = c->data.i; } - return _min(u->number, cursedmen); + return MIN(u->number, cursedmen); } /* setzt die Anzahl der betroffenen Personen auf cursedmen */ @@ -522,6 +522,24 @@ static void set_cursedmen(curse * c, int cursedmen) } } +static int newcurseid(void) { + int random_no; + int start_random_no; + random_no = 1 + (rng_int() % MAX_UNIT_NR); + start_random_no = random_no; + + while (findcurse(random_no)) { + random_no++; + if (random_no == MAX_UNIT_NR + 1) { + random_no = 1; + } + if (random_no == start_random_no) { + random_no = (int)MAX_UNIT_NR + 1; + } + } + return random_no; +} + /* ------------------------------------------------------------- */ /* Legt eine neue Verzauberung an. Sollte es schon einen Zauber * dieses Typs geben, gibt es den bestehenden zurck. @@ -543,7 +561,7 @@ static curse *make_curse(unit * mage, attrib ** ap, const curse_type * ct, c->effect = effect; c->magician = mage; - c->no = newunitid(); + c->no = newcurseid(); chash(c); switch (c->type->typ) { @@ -578,7 +596,7 @@ curse *create_curse(unit * magician, attrib ** ap, const curse_type * ct, /* es gibt schon eins diese Typs */ if (c && ct->mergeflags != NO_MERGE) { if (ct->mergeflags & M_DURATION) { - c->duration = _max(c->duration, duration); + c->duration = MAX(c->duration, duration); } if (ct->mergeflags & M_SUMDURATION) { c->duration += duration; @@ -587,10 +605,10 @@ curse *create_curse(unit * magician, attrib ** ap, const curse_type * ct, c->effect += effect; } if (ct->mergeflags & M_MAXEFFECT) { - c->effect = _max(c->effect, effect); + c->effect = MAX(c->effect, effect); } if (ct->mergeflags & M_VIGOUR) { - c->vigour = _max(vigour, c->vigour); + c->vigour = MAX(vigour, c->vigour); } if (ct->mergeflags & M_VIGOUR_ADD) { c->vigour = vigour + c->vigour; @@ -678,7 +696,7 @@ void transfer_curse(unit * u, unit * u2, int n) int curse_cansee(const curse *c, const faction *viewer, objtype_t typ, const void *obj, int self) { if (self < 3 && c->magician && c->magician->faction == viewer) { - // magicians can see their own curses better than anybody, no exceptions + /* magicians can see their own curses better than anybody, no exceptions */ self = 3; } else if (c->type->cansee) { @@ -774,9 +792,9 @@ message *cinfo_simple(const void *obj, objtype_t typ, const struct curse * c, { struct message *msg; - unused_arg(typ); - unused_arg(self); - unused_arg(obj); + UNUSED_ARG(typ); + UNUSED_ARG(self); + UNUSED_ARG(obj); msg = msg_message(mkname("curseinfo", c->type->cname), "id", c->no); if (msg == NULL) { @@ -807,7 +825,7 @@ double destr_curse(curse * c, int cast_level, double force) c->type->change_vigour(c, -(cast_level + 1) / 2); } else { - c->vigour -= cast_level + 1 / 2; + c->vigour -= (cast_level + 1) / 2.0; } } } @@ -829,7 +847,7 @@ double destr_curse(curse * c, int cast_level, double force) void curses_done(void) { int i; for (i = 0; i != MAXCTHASH; ++i) { - ql_free(cursetypes[i]); + selist_free(cursetypes[i]); cursetypes[i] = 0; } ++ct_changes; diff --git a/src/kernel/curse.h b/src/kernel/curse.h index a1518bbdd..543755c2b 100644 --- a/src/kernel/curse.h +++ b/src/kernel/curse.h @@ -22,6 +22,8 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include "objtypes.h" +#include + #ifdef __cplusplus extern "C" { #endif @@ -30,6 +32,8 @@ extern "C" { struct curse_type; struct gamedata; struct storage; + struct attrib; + struct faction; /* Sprueche in der struct region und auf Einheiten, Schiffen oder Burgen * (struct attribute) @@ -206,7 +210,7 @@ extern "C" { typedef struct curse { variant data; /* pointer auf spezielle curse-unterstructs */ struct curse *nexthash; - const curse_type *type; /* Zeiger auf ein curse_type-struct */ + const curse_type *type; /* Zeiger auf ein curse_type-struct */ struct unit *magician; /* Pointer auf den Magier, der den Spruch gewirkt hat */ double vigour; /* Strke der Verzauberung, Widerstand gegen Antimagie */ double effect; @@ -280,7 +284,6 @@ extern "C" { * */ struct curse *get_curse(struct attrib *ap, const curse_type * ctype); - int find_cursebyname(const char *c); const curse_type *ct_find(const char *c); bool ct_changed(int *cache); void ct_register(const curse_type *); diff --git a/src/kernel/curse.test.c b/src/kernel/curse.test.c index d7c86b9b0..56c3288f8 100644 --- a/src/kernel/curse.test.c +++ b/src/kernel/curse.test.c @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -54,7 +55,6 @@ static void setup_curse(curse_fixture *fix, const char *name) { } static void cleanup_curse(curse_fixture *fix) { - // destroy_curse(fix->c); test_cleanup(); } @@ -175,6 +175,43 @@ static void test_curse_cache(CuTest *tc) test_cleanup(); } +static void test_curse_ids(CuTest *tc) { + const curse_type ct_dummy = { "dummy", CURSETYP_NORM, 0, M_SUMEFFECT, NULL }; + curse *c1, *c2; + attrib *a1 = 0, *a2 = 0; + + test_setup(); + rng_init(0); + c1 = create_curse(NULL, &a1, &ct_dummy, 1, 1, 1, 1); + rng_init(0); + c2 = create_curse(NULL, &a2, &ct_dummy, 1, 1, 1, 1); + CuAssertTrue(tc, c1->no != c2->no); + a_remove(&a1, a1); + a_remove(&a2, a2); + test_cleanup(); +} + +static void test_curse_flags(CuTest *tc) { + const curse_type ct_dummy = { "dummy", CURSETYP_NORM, 0, M_SUMEFFECT, NULL }; + curse *c1, *c2; + unit *u; + + test_setup(); + u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); + c1 = create_curse(u, &u->attribs, &ct_dummy, 1, 1, 1, 0); + CuAssertPtrEquals(tc, u, c1->magician); + CuAssertIntEquals(tc, 1, (int)c1->effect); + CuAssertIntEquals(tc, 1, (int)c1->vigour); + CuAssertIntEquals(tc, 1, c1->duration); + c2 = create_curse(u, &u->attribs, &ct_dummy, 1, 1, 1, 0); + CuAssertPtrEquals(tc, c1, c2); + CuAssertPtrEquals(tc, u, c1->magician); + CuAssertIntEquals(tc, 2, (int)c1->effect); + CuAssertIntEquals(tc, 1, (int)c1->vigour); + CuAssertIntEquals(tc, 1, c1->duration); + test_cleanup(); +} + CuSuite *get_curse_suite(void) { CuSuite *suite = CuSuiteNew(); @@ -186,5 +223,7 @@ CuSuite *get_curse_suite(void) SUITE_ADD_TEST(suite, test_bad_dreams); SUITE_ADD_TEST(suite, test_memstream); SUITE_ADD_TEST(suite, test_write_flag); + SUITE_ADD_TEST(suite, test_curse_flags); + SUITE_ADD_TEST(suite, test_curse_ids); return suite; } diff --git a/src/kernel/equipment.c b/src/kernel/equipment.c index 424352347..d9a971455 100644 --- a/src/kernel/equipment.c +++ b/src/kernel/equipment.c @@ -25,10 +25,10 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "unit.h" #include "faction.h" #include "race.h" -#include "spellbook.h" +#include "spell.h" /* util includes */ -#include +#include #include #include @@ -39,7 +39,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. static equipment *equipment_sets; -equipment *create_equipment(const char *eqname) +equipment *get_or_create_equipment(const char *eqname) { equipment **eqp = &equipment_sets; for (;;) { @@ -47,7 +47,7 @@ equipment *create_equipment(const char *eqname) int i = eq ? strcmp(eq->name, eqname) : 1; if (i > 0) { eq = (equipment *)calloc(1, sizeof(equipment)); - eq->name = _strdup(eqname); + eq->name = strdup(eqname); eq->next = *eqp; memset(eq->skills, 0, sizeof(eq->skills)); *eqp = eq; @@ -78,7 +78,7 @@ void equipment_setskill(equipment * eq, skill_t sk, const char *value) { if (eq != NULL) { if (value != NULL) { - eq->skills[sk] = _strdup(value); + eq->skills[sk] = strdup(value); } else if (eq->skills[sk]) { free(eq->skills[sk]); @@ -86,13 +86,18 @@ void equipment_setskill(equipment * eq, skill_t sk, const char *value) } } -void equipment_addspell(equipment * eq, struct spell * sp, int level) +typedef struct lazy_spell { + struct spellref *spref; + int level; +} lazy_spell; + +void equipment_addspell(equipment * eq, const char * name, int level) { if (eq) { - if (!eq->spellbook) { - eq->spellbook = create_spellbook(0); - } - spellbook_add(eq->spellbook, sp, level); + lazy_spell *ls = malloc(sizeof(lazy_spell)); + ls->spref = spellref_create(NULL, name); + ls->level = level; + selist_push(&eq->spells, ls); } } @@ -108,7 +113,7 @@ equipment_setitem(equipment * eq, const item_type * itype, const char *value) if (idata == NULL) { idata = (itemdata *)malloc(sizeof(itemdata)); idata->itype = itype; - idata->value = _strdup(value); + idata->value = strdup(value); idata->next = eq->items; eq->items = idata; } @@ -148,14 +153,15 @@ void equip_unit_mask(struct unit *u, const struct equipment *eq, int mask) } if (mask & EQUIP_SPELLS) { - if (eq->spellbook) { - quicklist * ql = eq->spellbook->spells; + if (eq->spells) { + selist * ql = eq->spells; int qi; sc_mage * mage = get_mage(u); - for (qi = 0; ql; ql_advance(&ql, &qi, 1)) { - spellbook_entry *sbe = (spellbook_entry *)ql_get(ql, qi); - unit_add_spell(u, mage, sbe->sp, sbe->level); + for (qi = 0; ql; selist_advance(&ql, &qi, 1)) { + lazy_spell *sbe = (lazy_spell *)selist_get(ql, qi); + spell *sp = spellref_get(sbe->spref); + unit_add_spell(u, mage, sp, sbe->level); } } } @@ -224,6 +230,12 @@ void equip_items(struct item **items, const struct equipment *eq) } } +void free_ls(void *arg) { + lazy_spell *ls = (lazy_spell*)arg; + spellref_free(ls->spref); + free(ls); +} + void equipment_done(void) { equipment **eqp = &equipment_sets; while (*eqp) { @@ -231,9 +243,9 @@ void equipment_done(void) { equipment *eq = *eqp; *eqp = eq->next; free(eq->name); - if (eq->spellbook) { - spellbook_clear(eq->spellbook); - free(eq->spellbook); + if (eq->spells) { + selist_foreach(eq->spells, free_ls); + selist_free(eq->spells); } while (eq->items) { itemdata *next = eq->items->next; @@ -241,7 +253,7 @@ void equipment_done(void) { free(eq->items); eq->items = next; } - // TODO: subsets, skills + /* TODO: subsets, skills */ for (i=0;i!=MAXSKILLS;++i) { free(eq->skills[i]); } diff --git a/src/kernel/equipment.h b/src/kernel/equipment.h index 11511d99a..53475b510 100644 --- a/src/kernel/equipment.h +++ b/src/kernel/equipment.h @@ -48,7 +48,7 @@ extern "C" { char *name; struct itemdata *items; char *skills[MAXSKILLS]; - struct spellbook *spellbook; + struct selist *spells; struct subset *subsets; struct equipment *next; void(*callback) (const struct equipment *, struct unit *); @@ -56,14 +56,14 @@ extern "C" { void equipment_done(void); - struct equipment *create_equipment(const char *eqname); + struct equipment *get_or_create_equipment(const char *eqname); struct equipment *get_equipment(const char *eqname); void equipment_setitem(struct equipment *eq, const struct item_type *itype, const char *value); void equipment_setskill(struct equipment *eq, skill_t sk, const char *value); - void equipment_addspell(struct equipment *eq, struct spell *sp, int level); + void equipment_addspell(struct equipment *eq, const char *name, int level); void equipment_setcallback(struct equipment *eq, void(*callback) (const struct equipment *, struct unit *)); diff --git a/src/kernel/equipment.test.c b/src/kernel/equipment.test.c index 490a44a78..afd53849e 100644 --- a/src/kernel/equipment.test.c +++ b/src/kernel/equipment.test.c @@ -7,8 +7,6 @@ #include #include -#include - #include #include @@ -29,12 +27,12 @@ void test_equipment(CuTest * tc) CuAssertPtrNotNull(tc, sp); CuAssertPtrEquals(tc, 0, get_equipment("herpderp")); - eq = create_equipment("herpderp"); + eq = get_or_create_equipment("herpderp"); CuAssertPtrEquals(tc, eq, get_equipment("herpderp")); equipment_setitem(eq, it_horses, "1"); equipment_setskill(eq, SK_MAGIC, "5"); - equipment_addspell(eq, sp, 1); + equipment_addspell(eq, sp->sname, 1); u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); equip_unit_mask(u, eq, EQUIP_ALL); diff --git a/src/kernel/faction.c b/src/kernel/faction.c index 823932f88..57cd5d3af 100755 --- a/src/kernel/faction.c +++ b/src/kernel/faction.c @@ -29,7 +29,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "plane.h" #include "race.h" #include "region.h" -#include "save.h" #include "spellbook.h" #include "terrain.h" #include "unit.h" @@ -49,11 +48,10 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include #include -#include +#include #include /* libc includes */ @@ -104,7 +102,7 @@ static void free_faction(faction * f) free(f->_password); free(f->name); if (f->seen_factions) { - ql_free(f->seen_factions); + selist_free(f->seen_factions); f->seen_factions = 0; } @@ -249,10 +247,6 @@ faction *addfaction(const char *email, const char *password, log_warning("Invalid email address for faction %s: %s\n", itoa36(f->no), email); } - if (!password) password = itoa36(rng_int()); - faction_setpassword(f, password_encode(password, PASSWORD_DEFAULT)); - ADDMSG(&f->msgs, msg_message("changepasswd", "value", password)); - f->alliance_joindate = turn; f->lastorders = turn; f->_alive = true; @@ -261,7 +255,11 @@ faction *addfaction(const char *email, const char *password, f->magiegebiet = 0; f->locale = loc; f->subscription = subscription; - f->flags = FFL_ISNEW; + f->flags = FFL_ISNEW|FFL_PWMSG; + + if (!password) password = itoa36(rng_int()); + faction_setpassword(f, password_encode(password, PASSWORD_DEFAULT)); + ADDMSG(&f->msgs, msg_message("changepasswd", "value", password)); f->options = want(O_REPORT) | want(O_ZUGVORLAGE) | want(O_COMPUTER) | want(O_COMPRESS) | @@ -275,11 +273,11 @@ faction *addfaction(const char *email, const char *password, addlist(&factions, f); fhash(f); - slprintf(buf, sizeof(buf), "%s %s", LOC(loc, "factiondefault"), factionid(f)); - f->name = _strdup(buf); + slprintf(buf, sizeof(buf), "%s %s", LOC(loc, "factiondefault"), itoa36(f->no)); + f->name = strdup(buf); if (!f->race) { - log_warning("creating a faction that has no race", factionid(f)); + log_warning("creating a faction that has no race", itoa36(f->no)); } return f; @@ -288,15 +286,15 @@ faction *addfaction(const char *email, const char *password, unit *addplayer(region * r, faction * f) { unit *u; - char buffer[32]; + const struct equipment* eq; assert(f->units == NULL); faction_setorigin(f, 0, r->x, r->y); u = create_unit(r, f, 1, f->race, 0, NULL, NULL); - equip_items(&u->faction->items, get_equipment("new_faction")); - equip_unit(u, get_equipment("first_unit")); - sprintf(buffer, "first_%s", u_race(u)->_name); - equip_unit(u, get_equipment(buffer)); + eq = get_equipment("first_unit"); + if (eq) { + equip_items(&u->items, eq); + } u->hp = unit_max_hp(u) * u->number; fset(u, UFL_ISNEW); if (f->race == get_race(RC_DAEMON)) { @@ -368,7 +366,7 @@ void destroyfaction(faction ** fp) } if (f->seen_factions) { - ql_free(f->seen_factions); + selist_free(f->seen_factions); f->seen_factions = 0; } @@ -387,19 +385,14 @@ void destroyfaction(faction ** fp) const race *rc = u_race(u); int m = rmoney(r); + /* Personen gehen nur an die Bauern, wenn sie auch von dort + * stammen */ if ((rc->ec_flags & ECF_REC_ETHEREAL) == 0) { int p = rpeasants(u->region); int h = rhorses(u->region); item *itm; - /* Personen gehen nur an die Bauern, wenn sie auch von dort - * stammen */ - if (rc->ec_flags & ECF_REC_HORSES) { /* Zentauren an die Pferde */ - h += u->number; - } - else { /* Orks zählen nur zur Hälfte */ - p += (int)(u->number * rc->recruit_multi); - } + p += (int)(u->number * rc->recruit_multi); for (itm = u->items; itm; itm = itm->next) { if (itm->type->flags & ITF_ANIMAL) { h += itm->number; @@ -456,7 +449,7 @@ void destroyfaction(faction ** fp) /* units of other factions that were disguised as this faction * have their disguise replaced by ordinary faction hiding. */ if (rule_stealth_other()) { - // TODO: f.alive should be tested for in get_otherfaction + /* TODO: f.alive should be tested for in get_otherfaction */ region *rc; for (rc = regions; rc; rc = rc->next) { for (u = rc->units; u; u = u->next) { @@ -530,7 +523,7 @@ void faction_setname(faction * self, const char *name) { free(self->name); if (name) - self->name = _strdup(name); + self->name = strdup(name); } const char *faction_getemail(const faction * self) @@ -542,7 +535,7 @@ void faction_setemail(faction * self, const char *email) { free(self->email); if (email) - self->email = _strdup(email); + self->email = strdup(email); } const char *faction_getbanner(const faction * self) @@ -554,15 +547,14 @@ void faction_setbanner(faction * self, const char *banner) { free(self->banner); if (banner) - self->banner = _strdup(banner); + self->banner = strdup(banner); } void faction_setpassword(faction * f, const char *pwhash) { assert(pwhash); - // && pwhash[0] == '$'); free(f->_password); - f->_password = _strdup(pwhash); + f->_password = strdup(pwhash); } bool valid_race(const struct faction *f, const struct race *rc) @@ -570,10 +562,7 @@ bool valid_race(const struct faction *f, const struct race *rc) if (f->race == rc) return true; else { - const char *str = get_param(f->race->parameters, "other_race"); - if (str) - return (bool)(rc_find(str) == rc); - return false; + return rc_otherrace(f->race) == rc; } } @@ -600,11 +589,11 @@ static int allied_skillcount(const faction * f, skill_t sk) { int num = 0; alliance *a = f_get_alliance(f); - quicklist *members = a->members; + selist *members = a->members; int qi; - for (qi = 0; members; ql_advance(&members, &qi, 1)) { - faction *m = (faction *)ql_get(members, qi); + for (qi = 0; members; selist_advance(&members, &qi, 1)) { + faction *m = (faction *)selist_get(members, qi); num += count_skill(m, sk); } return num; @@ -760,12 +749,9 @@ int count_migrants(const faction * f) return count_faction(f, COUNT_MIGRANTS); } -#define MIGRANTS_NONE 0 -#define MIGRANTS_LOG10 1 - int count_maxmigrants(const faction * f) { - int formula = get_param_int(f->race->parameters, "migrants.formula", 0); + int formula = rc_migrants_formula(f->race); if (formula == MIGRANTS_LOG10) { int nsize = count_all(f); @@ -796,14 +782,26 @@ attrib_type at_maxmagicians = { int max_magicians(const faction * f) { - int m = config_get_int("rules.maxskills.magic", MAXMAGICIANS); - attrib *a; + static int rule, config, rc_cache; + static const race *rc_elf; + int m; - if ((a = a_find(f->attribs, &at_maxmagicians)) != NULL) { - m = a->data.i; + if (config_changed(&config)) { + rule = config_get_int("rules.maxskills.magic", MAXMAGICIANS); } - if (f->race == get_race(RC_ELF)) + m = rule; + if (f->attribs) { + attrib *a = a_find(f->attribs, &at_maxmagicians); + if (a) { + m = a->data.i; + } + } + if (rc_changed(&rc_cache)) { + rc_elf = get_race(RC_ELF); + } + if (f->race == rc_elf) { ++m; + } return m; } @@ -822,8 +820,8 @@ int writepasswd(void) log_info("writing passwords..."); for (f = factions; f; f = f->next) { - fprintf(F, "%s:%s:%s:%u\n", - factionid(f), f->email, f->_password, f->subscription); + fprintf(F, "%s:%s:%s:%d\n", + itoa36(f->no), f->email, f->_password, f->subscription); } fclose(F); return 0; diff --git a/src/kernel/faction.h b/src/kernel/faction.h index de5524294..0a0ac39d6 100644 --- a/src/kernel/faction.h +++ b/src/kernel/faction.h @@ -22,6 +22,8 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "skill.h" #include "types.h" #include +#include + #ifdef __cplusplus extern "C" { #endif @@ -31,21 +33,23 @@ extern "C" { struct seen_region; struct attrib_type; struct gamedata; + struct selist; extern struct attrib_type at_maxmagicians; /* faction flags */ -#define FFL_NEWID (1<<0) /* Die Partei hat bereits einmal ihre no gewechselt */ +#define FFL_NEWID (1<<0) /* Die Partei hat bereits einmal ihre no gewechselt */ #define FFL_ISNEW (1<<1) +#define FFL_PWMSG (1<<2) /* received a "new password" message */ #define FFL_QUIT (1<<3) -#define FFL_CURSED (1<<4) /* you're going to have a bad time */ +#define FFL_CURSED (1<<4) /* you're going to have a bad time */ #define FFL_DEFENDER (1<<10) #define FFL_SELECT (1<<18) /* ehemals f->dh, u->dh, r->dh, etc... */ #define FFL_NOAID (1<<21) /* Hilfsflag Kampf */ -#define FFL_MARK (1<<23) /* fr markierende algorithmen, die das - * hinterher auch wieder lschen mssen! +#define FFL_MARK (1<<23) /* f�r markierende algorithmen, die das + * hinterher auch wieder l�schen m�ssen! * (FFL_SELECT muss man vorher initialisieren, - * FL_MARK hinterher lschen) */ + * FL_MARK hinterher l�schen) */ #define FFL_NOIDLEOUT (1<<24) /* Partei stirbt nicht an NMRs */ #define FFL_NPC (1<<25) /* eine Partei mit Monstern */ #define FFL_SAVEMASK (FFL_DEFENDER|FFL_NEWID|FFL_NPC|FFL_NOIDLEOUT|FFL_CURSED) @@ -95,12 +99,14 @@ extern "C" { struct message_list *msgs; } *battles; struct item *items; /* items this faction can claim */ - struct quicklist *seen_factions; + struct selist *seen_factions; bool _alive; /* enno: sollte ein flag werden */ } faction; extern struct faction *factions; +#define want(option) (1< #include #include +#include #include #include -#include +#include #include #include #include -#include "monster.h" +#include "monsters.h" #include #include -#include +#include #include #include @@ -47,10 +48,10 @@ static void test_remove_empty_factions_alliance(CuTest *tc) { al = makealliance(0, "Hodor"); setalliance(f, al); CuAssertPtrEquals(tc, f, alliance_get_leader(al)); - CuAssertIntEquals(tc, 1, ql_length(al->members)); + CuAssertIntEquals(tc, 1, selist_length(al->members)); remove_empty_factions(); CuAssertPtrEquals(tc, 0, al->_leader); - CuAssertIntEquals(tc, 0, ql_length(al->members)); + CuAssertIntEquals(tc, 0, selist_length(al->members)); test_cleanup(); } @@ -117,7 +118,7 @@ static void test_addfaction(CuTest *tc) { CuAssertTrue(tc, checkpasswd(f, "hurrdurr")); CuAssertPtrEquals(tc, (void *)lang, (void *)f->locale); CuAssertIntEquals(tc, 1234, f->subscription); - CuAssertIntEquals(tc, FFL_ISNEW, f->flags); + CuAssertIntEquals(tc, FFL_ISNEW|FFL_PWMSG, f->flags); CuAssertIntEquals(tc, 0, f->age); CuAssertTrue(tc, faction_alive(f)); CuAssertIntEquals(tc, M_GRAY, f->magiegebiet); @@ -191,9 +192,43 @@ static void test_set_origin_bug(CuTest *tc) { test_cleanup(); } +static void test_max_migrants(CuTest *tc) { + faction *f; + unit *u; + race *rc; + + test_setup(); + rc = test_create_race("human"); + f = test_create_faction(rc); + u = test_create_unit(f, test_create_region(0, 0, 0)); + CuAssertIntEquals(tc, 0, count_maxmigrants(f)); + rc->flags |= RCF_MIGRANTS; + CuAssertIntEquals(tc, 0, count_maxmigrants(f)); + scale_number(u, 250); + CuAssertIntEquals(tc, 13, count_maxmigrants(f)); + test_cleanup(); +} + +static void test_valid_race(CuTest *tc) { + race * rc1, *rc2; + faction *f; + + test_setup(); + rc1 = test_create_race("human"); + rc2 = test_create_race("elf"); + f = test_create_faction(rc1); + CuAssertTrue(tc, valid_race(f, rc1)); + CuAssertTrue(tc, !valid_race(f, rc2)); + rc_set_param(rc1, "other_race", "elf"); + CuAssertTrue(tc, valid_race(f, rc1)); + CuAssertTrue(tc, valid_race(f, rc2)); + test_cleanup(); +} + CuSuite *get_faction_suite(void) { CuSuite *suite = CuSuiteNew(); + SUITE_ADD_TEST(suite, test_max_migrants); SUITE_ADD_TEST(suite, test_addfaction); SUITE_ADD_TEST(suite, test_remove_empty_factions); SUITE_ADD_TEST(suite, test_destroyfaction_allies); @@ -203,5 +238,6 @@ CuSuite *get_faction_suite(void) SUITE_ADD_TEST(suite, test_set_origin); SUITE_ADD_TEST(suite, test_set_origin_bug); SUITE_ADD_TEST(suite, test_check_passwd); + SUITE_ADD_TEST(suite, test_valid_race); return suite; } diff --git a/src/kernel/group.c b/src/kernel/group.c index 054cf44dc..06f2f9f49 100755 --- a/src/kernel/group.c +++ b/src/kernel/group.c @@ -23,7 +23,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* kernel includes */ #include "ally.h" #include "faction.h" -#include "save.h" #include "unit.h" /* attrib includes */ @@ -58,8 +57,8 @@ group *new_group(faction * f, const char *name, int gid) gp = &(*gp)->next; *gp = g; - maxgid = _max(gid, maxgid); - g->name = _strdup(name); + maxgid = MAX(gid, maxgid); + g->name = strdup(name); g->gid = gid; g->nexthash = ghash[index]; diff --git a/src/kernel/group.test.c b/src/kernel/group.test.c index 22d55e36f..e95458114 100644 --- a/src/kernel/group.test.c +++ b/src/kernel/group.test.c @@ -82,9 +82,9 @@ static void test_group_readwrite(CuTest * tc) mstream_init(&data.strm); gamedata_init(&data, &store, RELEASE_VERSION); f = test_create_faction(0); - g = new_group(f, "NW", 42); + new_group(f, "NW", 42); g = new_group(f, "Egoisten", 43); - key_set(&g->attribs, 44); + key_set(&g->attribs, 44, 44); al = ally_add(&g->allies, f); al->status = HELP_GIVE; write_groups(&store, f); @@ -108,7 +108,7 @@ static void test_group_readwrite(CuTest * tc) CuAssertStrEquals(tc, "Egoisten", f->groups->next->name); CuAssertPtrEquals(tc, 0, f->groups->allies); g = f->groups->next; - CuAssertTrue(tc, key_get(g->attribs, 44)); + CuAssertIntEquals(tc, 44, key_get(g->attribs, 44)); CuAssertPtrNotNull(tc, g->allies); CuAssertPtrEquals(tc, 0, g->allies->next); CuAssertPtrEquals(tc, f, g->allies->faction); diff --git a/src/kernel/item.c b/src/kernel/item.c index 66e361156..1197e7ce5 100644 --- a/src/kernel/item.c +++ b/src/kernel/item.c @@ -30,27 +30,23 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "pool.h" #include "race.h" #include "region.h" -#include "save.h" #include "skill.h" #include "terrain.h" #include "unit.h" -/* triggers includes */ -#include -#include - /* util includes */ #include #include -#include -#include #include #include #include #include #include -#include #include +#include + +#include +#include /* libc includes */ #include @@ -154,8 +150,11 @@ const char *resourcename(const resource_type * rtype, int flags) } } if (flags & NMF_PLURAL) { - static char name[64]; // FIXME: static return value - _snprintf(name, sizeof(name), "%s_p", rtype->_name); + static char name[64]; /* FIXME: static return value */ + size_t len = strlen(rtype->_name); + assert(len <= sizeof(name) - 3); + memcpy(name, rtype->_name, len); + strcpy(name + len, "_p"); return name; } return rtype->_name; @@ -185,7 +184,7 @@ resource_type *rt_get_or_create(const char *name) { perror("resource_type allocation failed"); } else { - rtype->_name = _strdup(name); + rtype->_name = strdup(name); rt_register(rtype); return rt_find(name); } @@ -238,7 +237,6 @@ item_type *it_get_or_create(resource_type *rtype) { item_type * itype; assert(rtype); itype = it_find(rtype->_name); - assert(!itype || !itype->rtype || itype->rtype == rtype); if (!itype) { itype = (item_type *)calloc(sizeof(item_type), 1); } @@ -272,7 +270,7 @@ luxury_type *new_luxurytype(item_type * itype, int price) } weapon_type *new_weapontype(item_type * itype, - int wflags, double magres, const char *damage[], int offmod, int defmod, + int wflags, variant magres, const char *damage[], int offmod, int defmod, int reload, skill_t sk, int minskill) { weapon_type *wtype; @@ -282,8 +280,8 @@ weapon_type *new_weapontype(item_type * itype, wtype = calloc(sizeof(weapon_type), 1); if (damage) { - wtype->damage[0] = _strdup(damage[0]); - wtype->damage[1] = _strdup(damage[1]); + wtype->damage[0] = strdup(damage[0]); + wtype->damage[1] = strdup(damage[1]); } wtype->defmod = defmod; wtype->flags |= wflags; @@ -298,7 +296,7 @@ weapon_type *new_weapontype(item_type * itype, return wtype; } -armor_type *new_armortype(item_type * itype, double penalty, double magres, +armor_type *new_armortype(item_type * itype, double penalty, variant magres, int prot, unsigned int flags) { armor_type *atype; @@ -342,7 +340,7 @@ void it_set_appearance(item_type *itype, const char *appearance) { assert(itype); assert(itype->rtype); if (appearance) { - itype->_appearance[0] = _strdup(appearance); + itype->_appearance[0] = strdup(appearance); itype->_appearance[1] = strcat(strcpy((char *)malloc(strlen((char *)appearance) + 3), (char *)appearance), "_p"); } else { itype->_appearance[0] = 0; @@ -567,46 +565,6 @@ item *i_new(const item_type * itype, int size) #include "region.h" -static int -give_horses(unit * s, unit * d, const item_type * itype, int n, -struct order *ord) -{ - if (d == NULL) { - int use = use_pooled(s, item2resource(itype), GET_SLACK, n); - region *r = s->region; - if (use < n) { - use += - use_pooled(s, item2resource(itype), GET_RESERVE | GET_POOLED_SLACK, - n - use); - } - if (r->land) { - rsethorses(r, rhorses(r) + use); - } - return 0; - } - return -1; /* use the mechanism */ -} - -static int -give_money(unit * s, unit * d, const item_type * itype, int n, -struct order *ord) -{ - if (d == NULL) { - int use = use_pooled(s, item2resource(itype), GET_SLACK, n); - region *r = s->region; - if (use < n) { - use += - use_pooled(s, item2resource(itype), GET_RESERVE | GET_POOLED_SLACK, - n - use); - } - if (r->land) { - rsetmoney(r, rmoney(r) + use); - } - return 0; - } - return -1; /* use the mechanism */ -} - #define R_MINOTHER R_SILVER #define R_MINHERB R_PLAIN_1 #define R_MINPOTION R_FAST @@ -635,11 +593,14 @@ static const char *resourcenames[MAX_RESOURCES] = { const resource_type *get_resourcetype(resource_t type) { static int update; static struct resource_type * rtypes[MAX_RESOURCES]; + const resource_type *rtype = NULL; if (update != num_resources) { memset(rtypes, 0, sizeof(rtypes)); update = num_resources; } - const resource_type *rtype = rtypes[type]; + else { + rtype = rtypes[type]; + } if (!rtype) { rtype = rtypes[type] = rt_find(resourcenames[type]); } @@ -669,27 +630,6 @@ int set_item(unit * u, const item_type *itype, int value) return value; } -static int -use_birthdayamulet(unit * u, const struct item_type *itype, int amount, -struct order *ord) -{ - direction_t d; - message *msg = msg_message("meow", ""); - - unused_arg(ord); - unused_arg(amount); - unused_arg(itype); - - add_message(&u->region->msgs, msg); - for (d = 0; d < MAXDIRECTIONS; d++) { - region *tr = rconnect(u->region, d); - if (tr) - add_message(&tr->msgs, msg); - } - msg_release(msg); - return 0; -} - /* t_item::flags */ #define FL_ITEM_CURSED (1<<0) #define FL_ITEM_NOTLOST (1<<1) @@ -697,34 +637,6 @@ struct order *ord) #define FL_ITEM_ANIMAL (1<<3) /* ist ein Tier */ #define FL_ITEM_MOUNT ((1<<4) | FL_ITEM_ANIMAL) /* ist ein Reittier */ -/* ------------------------------------------------------------- */ -/* Kann auch von Nichtmagier benutzt werden, modifiziert Taktik fuer diese - * Runde um -1 - 4 Punkte. */ -static int -use_tacticcrystal(unit * u, const struct item_type *itype, int amount, -struct order *ord) -{ - int i; - for (i = 0; i != amount; ++i) { - int duration = 1; /* wirkt nur eine Runde */ - curse *c; - float effect; - float power = 5; /* Widerstand gegen Antimagiesprueche, ist in diesem - Fall egal, da der curse fuer den Kampf gelten soll, - der vor den Antimagiezaubern passiert */ - - effect = (float)(rng_int() % 6 - 1); - c = create_curse(u, &u->attribs, ct_find("skillmod"), power, - duration, effect, u->number); - c->data.i = SK_TACTICS; - unused_arg(ord); - } - use_pooled(u, itype->rtype, GET_DEFAULT, amount); - ADDMSG(&u->faction->msgs, msg_message("use_tacticcrystal", - "unit region", u, u->region)); - return 0; -} - typedef struct t_item { const char *name; /* [0]: Einzahl fuer eigene; [1]: Mehrzahl fuer eigene; @@ -746,31 +658,20 @@ mod_elves_only(const unit * u, const region * r, skill_t sk, int value) { if (u_race(u) == get_race(RC_ELF)) return value; - unused_arg(r); + UNUSED_ARG(r); return -118; } static int mod_dwarves_only(const unit * u, const region * r, skill_t sk, int value) { - unused_arg(r); + UNUSED_ARG(r); if (u_race(u) == get_race(RC_DWARF) || (u_race(u)->flags & RCF_IRONGOLEM)) { return value; } return -118; } -static int heal(unit * user, int effect) -{ - int req = unit_max_hp(user) * user->number - user->hp; - if (req > 0) { - req = _min(req, effect); - effect -= req; - user->hp += req; - } - return effect; -} - void register_item_give(int(*foo) (struct unit *, struct unit *, const struct item_type *, int, struct order *), const char *name) @@ -785,173 +686,6 @@ struct order *), const char *name) register_function((pf_generic)foo, name); } -void -register_item_useonother(int(*foo) (struct unit *, int, -const struct item_type *, int, struct order *), const char *name) -{ - register_function((pf_generic)foo, name); -} - -static int -use_healingpotion(struct unit *user, const struct item_type *itype, int amount, -struct order *ord) -{ - int effect = amount * 400; - unit *u = user->region->units; - effect = heal(user, effect); - while (effect > 0 && u != NULL) { - if (u->faction == user->faction) { - effect = heal(u, effect); - } - u = u->next; - } - use_pooled(user, itype->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, - amount); - usetpotionuse(user, itype->rtype->ptype); - - ADDMSG(&user->faction->msgs, msg_message("usepotion", - "unit potion", user, itype->rtype)); - return 0; -} - -static int -use_warmthpotion(struct unit *u, const struct item_type *itype, int amount, -struct order *ord) -{ - if (u->faction->race == get_race(RC_INSECT)) { - fset(u, UFL_WARMTH); - } - else { - /* nur fuer insekten: */ - cmistake(u, ord, 163, MSG_EVENT); - return ECUSTOM; - } - use_pooled(u, itype->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, - amount); - usetpotionuse(u, itype->rtype->ptype); - - ADDMSG(&u->faction->msgs, msg_message("usepotion", - "unit potion", u, itype->rtype)); - return 0; -} - -static int -use_foolpotion(struct unit *u, int targetno, const struct item_type *itype, -int amount, struct order *ord) -{ - unit *target = findunit(targetno); - if (target == NULL || u->region != target->region) { - ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "feedback_unit_not_found", - "")); - return ECUSTOM; - } - if (effskill(u, SK_STEALTH, 0) <= effskill(target, SK_PERCEPTION, 0)) { - cmistake(u, ord, 64, MSG_EVENT); - return ECUSTOM; - } - ADDMSG(&u->faction->msgs, msg_message("givedumb", - "unit recipient amount", u, target, amount)); - - change_effect(target, itype->rtype->ptype, amount); - use_pooled(u, itype->rtype, GET_DEFAULT, amount); - return 0; -} - -static int -use_bloodpotion(struct unit *u, const struct item_type *itype, int amount, -struct order *ord) -{ - if (u->number == 0 || u_race(u) == get_race(RC_DAEMON)) { - change_effect(u, itype->rtype->ptype, 100 * amount); - } - else { - const race *irace = u_irace(u); - if (irace == u_race(u)) { - const race *rcfailure = rc_find("smurf"); - if (!rcfailure) { - rcfailure = rc_find("toad"); - } - if (rcfailure) { - trigger *trestore = trigger_changerace(u, u_race(u), irace); - if (trestore) { - int duration = 2 + rng_int() % 8; - - add_trigger(&u->attribs, "timer", trigger_timeout(duration, - trestore)); - u->irace = NULL; - u_setrace(u, rcfailure); - } - } - } - } - use_pooled(u, itype->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, - amount); - usetpotionuse(u, itype->rtype->ptype); - - ADDMSG(&u->faction->msgs, msg_message("usepotion", - "unit potion", u, itype->rtype)); - return 0; -} - -#include -static int -use_mistletoe(struct unit *user, const struct item_type *itype, int amount, -struct order *ord) -{ - int mtoes = - get_pooled(user, itype->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, - user->number); - - if (user->number > mtoes) { - ADDMSG(&user->faction->msgs, msg_message("use_singleperson", - "unit item region command", user, itype->rtype, user->region, ord)); - return -1; - } - use_pooled(user, itype->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, - user->number); - a_add(&user->attribs, make_fleechance((float)1.0)); - ADDMSG(&user->faction->msgs, - msg_message("use_item", "unit item", user, itype->rtype)); - - return 0; -} - -static int -use_magicboost(struct unit *user, const struct item_type *itype, int amount, -struct order *ord) -{ - int mtoes = - get_pooled(user, itype->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, - user->number); - faction *f = user->faction; - if (user->number > mtoes) { - ADDMSG(&user->faction->msgs, msg_message("use_singleperson", - "unit item region command", user, itype->rtype, user->region, ord)); - return -1; - } - if (!is_mage(user) || key_get(f->attribs, atoi36("mbst"))) { - cmistake(user, user->thisorder, 214, MSG_EVENT); - return -1; - } - use_pooled(user, itype->rtype, GET_SLACK | GET_RESERVE | GET_POOLED_SLACK, - user->number); - - key_set(&f->attribs, atoi36("mbst")); - set_level(user, SK_MAGIC, 3); - - ADDMSG(&user->faction->msgs, msg_message("use_item", - "unit item", user, itype->rtype)); - - return 0; -} - -static int -use_snowball(struct unit *user, const struct item_type *itype, int amount, -struct order *ord) -{ - return 0; -} - static void init_oldpotions(void) { const char *potionnames[MAX_POTIONS] = { @@ -972,27 +706,22 @@ void init_resources(void) { resource_type *rtype; - rtype = rt_get_or_create(resourcenames[R_PERSON]); // lousy hack + rt_get_or_create(resourcenames[R_PERSON]); /* lousy hack */ rtype = rt_get_or_create(resourcenames[R_PEASANT]); rtype->uchange = res_changepeasants; - // R_SILVER rtype = rt_get_or_create(resourcenames[R_SILVER]); rtype->flags |= RTF_ITEM | RTF_POOLED; rtype->uchange = res_changeitem; rtype->itype = it_get_or_create(rtype); - rtype->itype->give = give_money; - // R_PERMAURA rtype = rt_get_or_create(resourcenames[R_PERMAURA]); rtype->uchange = res_changepermaura; - // R_LIFE rtype = rt_get_or_create(resourcenames[R_LIFE]); rtype->uchange = res_changehp; - // R_AURA rtype = rt_get_or_create(resourcenames[R_AURA]); rtype->uchange = res_changeaura; @@ -1157,23 +886,7 @@ const item_type *finditemtype(const char *name, const struct locale *lang) return 0; } -static void init_resourcelimit(attrib * a) -{ - a->data.v = calloc(sizeof(resource_limit), 1); -} - -static void finalize_resourcelimit(attrib * a) -{ - free(a->data.v); -} - -attrib_type at_resourcelimit = { - "resourcelimit", - init_resourcelimit, - finalize_resourcelimit, -}; - -static item *default_spoil(const struct race *rc, int size) +item *item_spoil(const struct race *rc, int size) { item *itm = NULL; @@ -1190,6 +903,46 @@ static item *default_spoil(const struct race *rc, int size) return itm; } +void read_items(struct storage *store, item ** ilist) +{ + for (;;) { + char ibuf[32]; + const item_type *itype; + int i; + READ_STR(store, ibuf, sizeof(ibuf)); + if (!strcmp("end", ibuf)) { + break; + } + itype = it_find(ibuf); + READ_INT(store, &i); + if (i <= 0) { + log_error("data contains an entry with %d %s", i, ibuf); + } + else { + if (itype && itype->rtype) { + i_change(ilist, itype, i); + } + else { + log_error("data contains unknown item type %s.", ibuf); + } + assert(itype && itype->rtype); + } + } +} + +void write_items(struct storage *store, item * ilist) +{ + item *itm; + for (itm = ilist; itm; itm = itm->next) { + assert(itm->number >= 0); + if (itm->number) { + WRITE_TOK(store, resourcename(itm->type->rtype, 0)); + WRITE_INT(store, itm->number); + } + } + WRITE_TOK(store, "end"); +} + static void free_itype(item_type *itype) { assert(itype); free(itype->construction); @@ -1210,12 +963,12 @@ void free_rtype(resource_type *rtype) { if (rtype->wtype) { free_wtype(rtype->wtype); } - if (rtype->atype) { - free(rtype->atype); - } if (rtype->itype) { free_itype(rtype->itype); } + free(rtype->atype); + free(rtype->modifiers); + free(rtype->raw); free(rtype->_name); free(rtype); } @@ -1261,19 +1014,4 @@ void register_resources(void) register_function((pf_generic)res_changepermaura, "changepermaura"); register_function((pf_generic)res_changehp, "changehp"); register_function((pf_generic)res_changeaura, "changeaura"); - register_function((pf_generic)default_spoil, "defaultdrops"); - - register_item_use(use_potion, "usepotion"); - register_item_use(use_potion_delayed, "usepotion_delayed"); - register_item_use(use_tacticcrystal, "use_tacticcrystal"); - register_item_use(use_birthdayamulet, "use_birthdayamulet"); - register_item_use(use_warmthpotion, "usewarmthpotion"); - register_item_use(use_bloodpotion, "usebloodpotion"); - register_item_use(use_healingpotion, "usehealingpotion"); - register_item_useonother(use_foolpotion, "usefoolpotion"); - register_item_use(use_mistletoe, "usemistletoe"); - register_item_use(use_magicboost, "usemagicboost"); - register_item_use(use_snowball, "usesnowball"); - - register_item_give(give_horses, "givehorses"); } diff --git a/src/kernel/item.h b/src/kernel/item.h index c3b33070e..77fe1a9c2 100644 --- a/src/kernel/item.h +++ b/src/kernel/item.h @@ -29,12 +29,17 @@ extern "C" { struct unit; struct attrib; struct attrib_type; + struct race; struct region; struct resource_type; struct locale; struct troop; struct item; struct order; + struct storage; + struct gamedata; + struct rawmaterial_type; + struct resource_mod; typedef struct item { struct item *next; @@ -63,17 +68,16 @@ extern "C" { typedef int(*rtype_uchange) (struct unit * user, const struct resource_type * rtype, int delta); - typedef int(*rtype_uget) (const struct unit * user, - const struct resource_type * rtype); typedef char *(*rtype_name) (const struct resource_type * rtype, int flags); typedef struct resource_type { /* --- constants --- */ - char *_name; /* wie es heit */ + char *_name; /* wie es hei�t */ unsigned int flags; /* --- functions --- */ rtype_uchange uchange; - rtype_uget uget; rtype_name name; + struct rawmaterial_type *raw; + struct resource_mod *modifiers; /* --- pointers --- */ struct attrib *attribs; struct item_type *itype; @@ -89,30 +93,9 @@ extern "C" { /* resource-limits for regions */ #define RMF_SKILL 0x01 /* int, bonus on resource production skill */ -#define RMF_SAVEMATERIAL 0x02 /* float, multiplier on resource usage */ -#define RMF_SAVERESOURCE 0x03 /* int, bonus on resource production skill */ +#define RMF_SAVEMATERIAL 0x02 /* fraction (sa[0]/sa[1]), multiplier on resource usage */ #define RMF_REQUIREDBUILDING 0x04 /* building, required to build */ - typedef struct resource_mod { - variant value; - const struct building_type *btype; - const struct race *race; - unsigned int flags; - } resource_mod; - - extern struct attrib_type at_resourcelimit; - typedef int(*rlimit_limit) (const struct region * r, - const struct resource_type * rtype); - typedef void(*rlimit_produce) (struct region * r, - const struct resource_type * rtype, int n); - typedef struct resource_limit { - rlimit_limit limit; - rlimit_produce produce; - unsigned int guard; /* how to guard against theft */ - int value; - resource_mod *modifiers; - } resource_limit; - /* bitfield values for item_type::flags */ #define ITF_NONE 0x0000 #define ITF_HERB 0x0001 /* this item is a herb */ @@ -121,6 +104,7 @@ extern "C" { #define ITF_BIG 0x0008 /* big item, e.g. does not fit in a bag of holding */ #define ITF_ANIMAL 0x0010 /* an animal */ #define ITF_VEHICLE 0x0020 /* a vehicle, drawn by two animals */ +#define ITF_CANUSE 0x0040 /* can be used with use_item_fun callout */ /* error codes for item_type::use */ #define ECUSTOM -1 @@ -134,17 +118,10 @@ extern "C" { unsigned int flags; int weight; int capacity; + int mask_allow; + int mask_deny; struct construction *construction; - char *_appearance[2]; /* wie es fr andere aussieht */ - /* --- functions --- */ - bool(*canuse) (const struct unit * user, - const struct item_type * itype); - int(*use) (struct unit * user, const struct item_type * itype, int amount, - struct order * ord); - int(*useonother) (struct unit * user, int targetno, - const struct item_type * itype, int amount, struct order * ord); - int(*give) (struct unit * src, struct unit * dest, - const struct item_type * itm, int number, struct order * ord); + char *_appearance[2]; /* wie es f�r andere aussieht */ int score; } item_type; @@ -195,7 +172,7 @@ extern "C" { const item_type *itype; unsigned int flags; double penalty; - double magres; + variant magres; int prot; float projectile; /* chance, dass ein projektil abprallt */ } armor_type; @@ -219,7 +196,7 @@ extern "C" { int minskill; int offmod; int defmod; - double magres; + variant magres; int reload; /* time to reload this weapon */ weapon_mod *modifiers; /* --- functions --- */ @@ -248,6 +225,9 @@ extern "C" { void i_freeall(item ** i); item *i_new(const item_type * it, int number); + void read_items(struct storage *store, struct item **it); + void write_items(struct storage *store, struct item *it); + /* convenience: */ item *i_change(item ** items, const item_type * it, int delta); int i_get(const item * i, const item_type * it); @@ -255,14 +235,12 @@ extern "C" { /* creation */ resource_type *rt_get_or_create(const char *name); item_type *it_get_or_create(resource_type *rtype); - item_type *new_itemtype(resource_type * rtype, int iflags, int weight, - int capacity); luxury_type *new_luxurytype(item_type * itype, int price); weapon_type *new_weapontype(item_type * itype, int wflags, - double magres, const char *damage[], int offmod, int defmod, int reload, + variant magres, const char *damage[], int offmod, int defmod, int reload, skill_t sk, int minskill); armor_type *new_armortype(item_type * itype, double penalty, - double magres, int prot, unsigned int flags); + variant magres, int prot, unsigned int flags); potion_type *new_potiontype(item_type * itype, int level); typedef enum { @@ -306,7 +284,10 @@ extern "C" { extern const struct potion_type *oldpotiontype[]; const struct resource_type *get_resourcetype(resource_t rt); + struct item *item_spoil(const struct race *rc, int size); + int get_item(const struct unit * u, const struct item_type *itype); + int set_item(struct unit * u, const struct item_type *itype, int value); int get_money(const struct unit *); int set_money(struct unit *, int); int change_money(struct unit *, int); @@ -321,8 +302,6 @@ extern "C" { const struct item_type *, int, struct order *), const char *name); void register_item_use(int(*foo) (struct unit *, const struct item_type *, int, struct order *), const char *name); - void register_item_useonother(int(*foo) (struct unit *, int, - const struct item_type *, int, struct order *), const char *name); void free_resources(void); diff --git a/src/kernel/item.test.c b/src/kernel/item.test.c index 231b45d00..e8b8d79e3 100644 --- a/src/kernel/item.test.c +++ b/src/kernel/item.test.c @@ -19,7 +19,7 @@ static void test_resourcename_no_appearance(CuTest *tc) { const resource_type *rtype; test_cleanup(); - init_resources(); // creates R_SILVER + init_resources(); /* creates R_SILVER */ rtype = get_resourcetype(R_SILVER); assert(rtype && rtype->itype); assert(rtype->itype->_appearance[0] == 0); @@ -162,7 +162,6 @@ static void test_core_resources(CuTest *tc) { CuAssertPtrNotNull(tc, rtype = rt_find("money")); CuAssertPtrNotNull(tc, rtype->itype); CuAssertPtrNotNull(tc, rtype->uchange); - CuAssertPtrNotNull(tc, rtype->itype->give); CuAssertPtrNotNull(tc, rtype = rt_find("peasant")); CuAssertPtrEquals(tc, 0, rtype->itype); CuAssertPtrNotNull(tc, rtype = rt_find("person")); diff --git a/src/kernel/jsonconf.c b/src/kernel/jsonconf.c index 721e6e60f..287aa61db 100644 --- a/src/kernel/jsonconf.c +++ b/src/kernel/jsonconf.c @@ -106,7 +106,7 @@ static void json_maintenance_i(cJSON *json, maintenance *mt) { break; case cJSON_Array: if (strcmp(child->string, "flags") == 0) { - const char * flags[] = { "variable", "required", 0 }; + const char * flags[] = { "variable", 0 }; mt->flags = json_flags(child, flags); } else { @@ -146,6 +146,8 @@ static void json_maintenance(cJSON *json, maintenance **mtp) { static void json_construction(cJSON *json, construction **consp) { cJSON *child; + construction * cons; + if (json->type == cJSON_Array) { int size = 0; for (child = json->child; child; child = child->next) { @@ -164,7 +166,7 @@ static void json_construction(cJSON *json, construction **consp) { log_error("construction %s is not a json object: %d", json->string, json->type); return; } - construction * cons = (construction *)calloc(sizeof(construction), 1); + cons = (construction *)calloc(sizeof(construction), 1); for (child = json->child; child; child = child->next) { switch (child->type) { case cJSON_Object: @@ -191,8 +193,8 @@ static void json_construction(cJSON *json, construction **consp) { } static void json_terrain_production(cJSON *json, terrain_production *prod) { - assert(json->type == cJSON_Object); cJSON *child; + assert(json->type == cJSON_Object); for (child = json->child; child; child = child->next) { char **dst = 0; switch (child->type) { @@ -224,7 +226,7 @@ static void json_terrain_production(cJSON *json, terrain_production *prod) { if (dst) { free(*dst); assert(child->type == cJSON_String); - *dst = _strdup(child->valuestring); + *dst = strdup(child->valuestring); } } } @@ -453,15 +455,15 @@ static void json_race(cJSON *json, race *rc) { switch (child->type) { case cJSON_String: if (strcmp(child->string, "damage") == 0) { - rc->def_damage = _strdup(child->valuestring); + rc->def_damage = strdup(child->valuestring); } break; case cJSON_Number: if (strcmp(child->string, "magres") == 0) { - rc->magres = (float)child->valuedouble; + rc->magres = frac_make(child->valueint, 100); } else if (strcmp(child->string, "maxaura") == 0) { - rc->maxaura = (float)child->valuedouble; + rc->maxaura = child->valueint; } else if (strcmp(child->string, "regaura") == 0) { rc->regaura = (float)child->valuedouble; @@ -481,13 +483,16 @@ static void json_race(cJSON *json, race *rc) { else if (strcmp(child->string, "capacity") == 0) { rc->capacity = child->valueint; } + else if (strcmp(child->string, "income") == 0) { + rc->income = child->valueint; + } else if (strcmp(child->string, "hp") == 0) { rc->hitpoints = child->valueint; } else if (strcmp(child->string, "ac") == 0) { rc->armor = child->valueint; } - // TODO: studyspeed (orcs only) + /* TODO: studyspeed (orcs only) */ break; case cJSON_Array: if (strcmp(child->string, "flags") == 0) { @@ -520,6 +525,8 @@ static void disable_feature(const char *str) { char name[32]; int k; skill_t sk; + size_t len; + sk = findskill(str); if (sk != NOSKILL) { enable_skill(sk, false); @@ -531,7 +538,10 @@ static void disable_feature(const char *str) { enable_keyword(k, false); return; } - _snprintf(name, sizeof(name), "%s.enabled", str); + len = strlen(str); + assert(len <= sizeof(name) - 9); + memcpy(name, str, len); + strcpy(name+len, ".enabled"); log_info("disable feature %s\n", name); config_set(name, "0"); } @@ -591,7 +601,7 @@ static void json_spells(cJSON *json) { sp->fumble = (fumble_f)get_function(item->valuestring); } else if (strcmp(item->string, "syntax") == 0) { - sp->syntax = _strdup(item->valuestring); + sp->syntax = strdup(item->valuestring); } } } @@ -646,7 +656,7 @@ static void json_strings(cJSON *json) { } for (child = json->child; child; child = child->next) { if (child->type == cJSON_Object) { - struct locale *lang = get_or_create_locale(child->string); + struct locale *lang = get_locale(child->string); json_locale(child, lang); } else { @@ -687,7 +697,7 @@ static void json_directions(cJSON *json) { return; } for (child = json->child; child; child = child->next) { - struct locale * lang = get_or_create_locale(child->string); + struct locale * lang = get_locale(child->string); json_direction(child, lang); } } @@ -763,7 +773,7 @@ static void json_skills(cJSON *json) { return; } for (child = json->child; child; child = child->next) { - struct locale * lang = get_or_create_locale(child->string); + struct locale * lang = get_locale(child->string); json_skill(child, lang); } } @@ -775,7 +785,7 @@ static void json_keywords(cJSON *json) { return; } for (child = json->child; child; child = child->next) { - struct locale * lang = get_or_create_locale(child->string); + struct locale * lang = get_locale(child->string); json_keyword(child, lang); } } @@ -793,12 +803,14 @@ static void json_settings(cJSON *json) { else { char value[32]; if (child->type == cJSON_Number && child->valuedouble && child->valueintvaluedouble) { - _snprintf(value, sizeof(value), "%lf", child->valuedouble); + sprintf(value, "%f", child->valuedouble); } else { - _snprintf(value, sizeof(value), "%d", child->valueint); + sprintf(value, "%d", child->valueint); + } + if (config_get(child->string) == NULL) { + config_set(child->string, value); } - config_set(child->string, value); } } } diff --git a/src/kernel/jsonconf.test.c b/src/kernel/jsonconf.test.c index 38b2047e6..8b8ac8c14 100644 --- a/src/kernel/jsonconf.test.c +++ b/src/kernel/jsonconf.test.c @@ -69,12 +69,15 @@ static void test_settings(CuTest * tc) "\"string\" : \"1d4\"," "\"integer\" : 14," "\"true\": true," + "\"game.id\": 4," "\"false\": false," "\"float\" : 1.5 }}"; cJSON *json = cJSON_Parse(data); test_cleanup(); + config_set("game.id", "42"); /* should not be replaced */ json_config(json); + CuAssertStrEquals(tc, "42", config_get("game.id")); CuAssertStrEquals(tc, "1", config_get("true")); CuAssertStrEquals(tc, "0", config_get("false")); CuAssertStrEquals(tc, "1d4", config_get("string")); @@ -133,14 +136,15 @@ static void test_races(CuTest * tc) { const char * data = "{\"races\": { \"orc\" : { " "\"damage\" : \"1d4\"," - "\"magres\" : 1.0," - "\"maxaura\" : 2.0," + "\"magres\" : 100," + "\"maxaura\" : 200," "\"regaura\" : 3.0," "\"speed\" : 4.0," "\"recruitcost\" : 1," "\"maintenance\" : 2," "\"weight\" : 3," "\"capacity\" : 4," + "\"income\" : 30," "\"hp\" : 5," "\"ac\" : 6," "\"flags\" : [ \"npc\", \"walk\", \"undead\" ]" @@ -159,14 +163,16 @@ static void test_races(CuTest * tc) CuAssertPtrNotNull(tc, rc); CuAssertIntEquals(tc, RCF_NPC | RCF_WALK | RCF_UNDEAD, rc->flags); CuAssertStrEquals(tc, "1d4", rc->def_damage); - CuAssertDblEquals(tc, 1.0, rc->magres, 0.0); - CuAssertDblEquals(tc, 2.0, rc->maxaura, 0.0); + CuAssertTrue(tc, frac_equal(frac_one, rc->magres)); + CuAssertIntEquals(tc, 200, rc->maxaura); + CuAssertDblEquals(tc, 2.0, rc_maxaura(rc), 0.0); CuAssertDblEquals(tc, 3.0, rc->regaura, 0.0); CuAssertDblEquals(tc, 4.0, rc->speed, 0.0); CuAssertIntEquals(tc, 1, rc->recruitcost); CuAssertIntEquals(tc, 2, rc->maintenance); CuAssertIntEquals(tc, 3, rc->weight); CuAssertIntEquals(tc, 4, rc->capacity); + CuAssertIntEquals(tc, 30, rc->income); CuAssertIntEquals(tc, 5, rc->hitpoints); CuAssertIntEquals(tc, 6, rc->armor); cJSON_Delete(json); @@ -319,7 +325,7 @@ static void test_spells(CuTest * tc) static const char * building_data = "{\"buildings\": { " "\"house\" : { " "\"maintenance\" : " -"{ \"type\" : \"iron\", \"amount\" : 1, \"flags\" : [ \"required\", \"variable\" ] }" +"{ \"type\" : \"iron\", \"amount\" : 1, \"flags\" : [ \"variable\" ] }" "," "\"construction\" : {" "\"maxsize\" : 20," @@ -363,7 +369,7 @@ static void test_buildings(CuTest * tc) CuAssertPtrNotNull(tc, bt->maintenance); CuAssertIntEquals(tc, 1, bt->maintenance[0].number); CuAssertPtrEquals(tc, (void *)get_resourcetype(R_IRON), (void *)bt->maintenance[0].rtype); - CuAssertIntEquals(tc, MTF_VARIABLE | MTF_VITAL, bt->maintenance[0].flags); + CuAssertIntEquals(tc, MTF_VARIABLE, bt->maintenance[0].flags); CuAssertIntEquals(tc, 0, bt->maintenance[1].number); CuAssertPtrNotNull(tc, bt->construction); @@ -446,7 +452,7 @@ static void test_configs(CuTest * tc) CuAssertPtrEquals(tc, 0, buildingtypes); json_config(json); CuAssertPtrNotNull(tc, buildingtypes); - if (unlink("test.json")!=0 && errno==ENOENT) { + if (remove("test.json")!=0 && errno==ENOENT) { errno = 0; } cJSON_Delete(json); @@ -481,7 +487,7 @@ static void test_terrains(CuTest * tc) CuAssertPtrEquals(tc, rt_get_or_create("h0"), ter->herbs[0]->rtype); CuAssertPtrEquals(tc, rt_get_or_create("h1"), ter->herbs[1]->rtype); CuAssertPtrEquals(tc, 0, (void *)ter->herbs[2]); - CuAssertPtrNotNull(tc, ter->name); // anything named "plain" uses plain_name() + CuAssertPtrNotNull(tc, ter->name); /* anything named "plain" uses plain_name() */ CuAssertPtrNotNull(tc, ter->production); CuAssertPtrEquals(tc, rt_get_or_create("stone"), (resource_type *)ter->production[0].type); CuAssertDblEquals(tc, 0.1, ter->production[0].chance, 0.01); @@ -593,9 +599,10 @@ static void test_infinitive_from_config(CuTest *tc) { cJSON *json = cJSON_Parse(data); CuAssertPtrNotNull(tc, json); + test_setup(); + lang = get_or_create_locale("de"); json_config(json); - lang = get_or_create_locale("de"); CuAssertIntEquals(tc, K_STUDY, get_keyword("LERN", lang)); CuAssertIntEquals(tc, K_STUDY, get_keyword("LERNE", lang)); CuAssertIntEquals(tc, K_STUDY, get_keyword("LERNEN", lang)); diff --git a/src/kernel/messages.c b/src/kernel/messages.c index 330c2feeb..f74e9c0d7 100644 --- a/src/kernel/messages.c +++ b/src/kernel/messages.c @@ -92,10 +92,11 @@ struct message *msg_feedback(const struct unit *u, struct order *ord, if (!mtype) { log_warning("trying to create message of unknown type \"%s\"\n", name); if (!mt_find("missing_feedback")) { - mt_register(mt_new_va("missing_feedback", "unit:unit", "region:region", "command:order", "name:string", 0)); + mt_register(mt_new_va("missing_feedback", "unit:unit", + "region:region", "command:order", "name:string", 0)); } - return msg_message("missing_feedback", "unit region command name", u, - u->region, ord, name); + return msg_message("missing_feedback", "name unit region command", + name, u, u->region, ord); } var.v = (void *)u; @@ -211,31 +212,13 @@ caddmessage(region * r, faction * f, const char *s, msg_t mtype, int level) { message *m = NULL; - unused_arg(level); + UNUSED_ARG(level); switch (mtype) { - case MSG_INCOME: - assert(f); - m = add_message(&f->msgs, msg_message("msg_economy", "string", s)); - break; case MSG_BATTLE: assert(0 || !"battle messages must not use addmessage"); break; - case MSG_MOVE: - assert(f); - m = add_message(&f->msgs, msg_message("msg_movement", "string", s)); - break; - case MSG_COMMERCE: - assert(f); - m = add_message(&f->msgs, msg_message("msg_economy", "string", s)); - break; - case MSG_PRODUCE: - assert(f); - m = add_message(&f->msgs, msg_message("msg_production", "string", s)); - break; case MSG_MAGIC: - case MSG_COMMENT: case MSG_MESSAGE: - case MSG_ORCVERMEHRUNG: case MSG_EVENT: /* Botschaften an REGION oder einzelne PARTEI */ m = msg_message("msg_event", "string", s); @@ -274,7 +257,7 @@ message * msg_error(const unit * u, struct order *ord, int mno) { message * cmistake(const unit * u, struct order *ord, int mno, int mtype) { message * result; - unused_arg(mtype); + UNUSED_ARG(mtype); result = msg_error(u, ord, mno); ADDMSG(&u->faction->msgs, result); return result; @@ -287,8 +270,6 @@ void syntax_error(const struct unit *u, struct order *ord) ADDMSG(&u->faction->msgs, result); } -extern unsigned int new_hashstring(const char *s); - void free_messagelist(mlist *msgs) { struct mlist **mlistptr; diff --git a/src/kernel/messages.h b/src/kernel/messages.h index 866eecba7..a42342153 100644 --- a/src/kernel/messages.h +++ b/src/kernel/messages.h @@ -57,7 +57,7 @@ extern "C" { struct mlist ** merge_messages(message_list *mlist, message_list *append); void split_messages(message_list *mlist, struct mlist **split); -#define ADDMSG(msgs, mcreate) { message * m = mcreate; if (m) { assert(m->refcount>=1); add_message(msgs, m); msg_release(m); } } +#define ADDMSG(msgs, mcreate) { message * mx = mcreate; if (mx) { assert(mx->refcount>=1); add_message(msgs, mx); msg_release(mx); } } void syntax_error(const struct unit *u, struct order *ord); struct message * cmistake(const struct unit *u, struct order *ord, int mno, int mtype); diff --git a/src/kernel/messages.test.c b/src/kernel/messages.test.c index fc6079dfe..7b0f2dd5e 100644 --- a/src/kernel/messages.test.c +++ b/src/kernel/messages.test.c @@ -39,7 +39,7 @@ void test_message(CuTest *tc) { static void test_merge_split(CuTest *tc) { message_list *mlist = 0, *append = 0; - struct mlist **split; // TODO: why is this a double asterisk? + struct mlist **split; /* TODO: why is this a double asterisk? */ message_type *mtype = mt_new("custom", NULL); message *msg; @@ -74,4 +74,5 @@ CuSuite *get_messages_suite(void) { SUITE_ADD_TEST(suite, test_merge_split); SUITE_ADD_TEST(suite, test_message); return suite; -} \ No newline at end of file +} + diff --git a/src/kernel/order.c b/src/kernel/order.c index f79b2dd68..776190b67 100644 --- a/src/kernel/order.c +++ b/src/kernel/order.c @@ -285,7 +285,7 @@ static order *create_order_i(keyword_t kwd, const char *sptr, bool persistent, order *ord = NULL; int lindex; - if ((int)kwd > 0 && keyword_disabled(kwd)) { + if (kwd == NOKEYWORD || keyword_disabled(kwd)) { log_error("trying to create an order for disabled keyword %s.", keyword(kwd)); return NULL; } @@ -405,10 +405,10 @@ order *parse_order(const char *s, const struct locale * lang) } } if (kwd != NOKEYWORD) { - while (isxspace(*(unsigned char *)sptr)) ++sptr; + while (isspace(*(unsigned char *)sptr)) ++sptr; s = sptr; + return create_order_i(kwd, s, persistent, lang); } - return create_order_i(kwd, s, persistent, lang); } return NULL; } diff --git a/src/kernel/order.h b/src/kernel/order.h index 8ad5592b7..7f4b00a5e 100644 --- a/src/kernel/order.h +++ b/src/kernel/order.h @@ -12,12 +12,15 @@ #ifndef KRNL_ORDER_H #define KRNL_ORDER_H + +#include "keyword.h" +#include +#include + #ifdef __cplusplus extern "C" { #endif -#include "keyword.h" - /* Encapsulation of an order * * This structure contains one order given by a unit. These used to be diff --git a/src/kernel/order.test.c b/src/kernel/order.test.c index 635e6e078..f5eb51c6f 100644 --- a/src/kernel/order.test.c +++ b/src/kernel/order.test.c @@ -1,5 +1,4 @@ #include -#include #include #include "order.h" diff --git a/src/kernel/pathfinder.c b/src/kernel/pathfinder.c index 8ae9bf128..ba45f926c 100644 --- a/src/kernel/pathfinder.c +++ b/src/kernel/pathfinder.c @@ -18,7 +18,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include -#include +#include #include "pathfinder.h" #include "region.h" @@ -102,10 +102,10 @@ static void free_nodes(node * root) } } -struct quicklist *regions_in_range(struct region *start, int maxdist, +struct selist *regions_in_range(struct region *start, int maxdist, bool(*allowed) (const struct region *, const struct region *)) { - quicklist * rlist = NULL; + selist * rlist = NULL; node *root = new_node(start, 0, NULL); node **end = &root->next; node *n = root; @@ -127,7 +127,7 @@ struct quicklist *regions_in_range(struct region *start, int maxdist, continue; /* can't go there */ /* add the region to the list of available ones. */ - ql_push(&rlist, rn); + selist_push(&rlist, rn); /* make sure we don't go here again, and put the region into the set for further BFS'ing */ diff --git a/src/kernel/pathfinder.h b/src/kernel/pathfinder.h index 81692e835..682fa4d25 100644 --- a/src/kernel/pathfinder.h +++ b/src/kernel/pathfinder.h @@ -34,7 +34,7 @@ extern "C" { const struct region *target); extern bool allowed_walk(const struct region *src, const struct region *target); - extern struct quicklist *regions_in_range(struct region *src, int maxdist, + extern struct selist *regions_in_range(struct region *src, int maxdist, bool(*allowed) (const struct region *, const struct region *)); extern void pathfinder_cleanup(void); diff --git a/src/kernel/plane.c b/src/kernel/plane.c index 7e9650d13..0b2fdc0d3 100644 --- a/src/kernel/plane.c +++ b/src/kernel/plane.c @@ -234,7 +234,7 @@ plane *create_new_plane(int id, const char *name, int minx, int maxx, int miny, pl->next = NULL; pl->id = id; if (name) - pl->name = _strdup(name); + pl->name = strdup(name); pl->minx = minx; pl->maxx = maxx; pl->miny = miny; diff --git a/src/kernel/pool.c b/src/kernel/pool.c index 6ceeda63d..8dfd589c3 100644 --- a/src/kernel/pool.c +++ b/src/kernel/pool.c @@ -40,11 +40,11 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. int get_resource(const unit * u, const resource_type * rtype) { assert(rtype); - if (rtype->uget) { - /* this resource is probably special */ - int i = rtype->uget(u, rtype); - if (i >= 0) - return i; + if (rtype == get_resourcetype(R_PEASANT)) { + return u->region->land ? u->region->land->peasants : 0; + } + else if (rtype == rt_find("hp")) { + return u->hp; } else if (rtype->uchange) { /* this resource is probably special */ @@ -168,7 +168,7 @@ int count) use = have; else if (rtype->itype && mode & (GET_SLACK | GET_RESERVE)) { int reserve = get_reservation(u, rtype->itype); - int slack = _max(0, have - reserve); + int slack = MAX(0, have - reserve); if (mode & GET_RESERVE) use = have - slack; else if (mode & GET_SLACK) @@ -176,10 +176,10 @@ int count) } if (rtype->flags & RTF_POOLED && mode & ~(GET_SLACK | GET_RESERVE)) { for (v = r->units; v && use < count; v = v->next) - if (u != v && (v->items || rtype->uget)) { + if (u != v) { int mask; - if ((urace(v)->ec_flags & ECF_KEEP_ITEM)) + if ((u_race(v)->ec_flags & ECF_KEEP_ITEM)) continue; if (v->faction == f) { @@ -209,18 +209,18 @@ use_pooled(unit * u, const resource_type * rtype, unsigned int mode, int count) } if ((mode & GET_SLACK) && (mode & GET_RESERVE)) { - n = _min(use, have); + n = MIN(use, have); } else if (rtype->itype) { int reserve = get_reservation(u, rtype->itype); - int slack = _max(0, have - reserve); + int slack = MAX(0, have - reserve); if (mode & GET_RESERVE) { n = have - slack; - n = _min(use, n); + n = MIN(use, n); change_reservation(u, rtype->itype, -n); } else if (mode & GET_SLACK) { - n = _min(use, slack); + n = MIN(use, slack); } } if (n > 0) { @@ -232,9 +232,7 @@ use_pooled(unit * u, const resource_type * rtype, unsigned int mode, int count) for (v = r->units; use > 0 && v != NULL; v = v->next) { if (u != v) { int mask; - if ((urace(v)->ec_flags & ECF_KEEP_ITEM)) - continue; - if (v->items == NULL && rtype->uget == NULL) + if ((u_race(v)->ec_flags & ECF_KEEP_ITEM)) continue; if (v->faction == f) { diff --git a/src/kernel/race.c b/src/kernel/race.c index 4003c701e..8a8cc906e 100644 --- a/src/kernel/race.c +++ b/src/kernel/race.c @@ -32,6 +32,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "region.h" #include "ship.h" #include "skill.h" +#include "spell.h" #include "terrain.h" #include "unit.h" @@ -39,9 +40,11 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include +#include #include #include #include +#include #include @@ -51,6 +54,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* libc includes */ #include #include +#include #include #include #include @@ -63,7 +67,7 @@ static int rc_changes = 1; static const char *racenames[MAXRACES] = { "dwarf", "elf", NULL, "goblin", "human", "troll", "demon", "insect", - "halfling", "cat", "aquarian", "orc", "snotling", "undead", "illusion", + "halfling", "cat", "aquarian", "orc", "snotling", "undead", NULL, "youngdragon", "dragon", "wyrm", "ent", "catdragon", "dracoid", NULL, "spell", "irongolem", "stonegolem", "shadowdemon", "shadowmaster", "mountainguard", "alp", "toad", "braineater", "peasant", @@ -71,10 +75,96 @@ static const char *racenames[MAXRACES] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "seaserpent", "shadowknight", NULL, "skeleton", "skeletonlord", "zombie", - "juju-zombie", "ghoul", "ghast", NULL, NULL, "template", + "juju", "ghoul", "ghast", NULL, NULL, "template", "clone" }; +#define MAXOPTIONS 4 +typedef struct rcoption { + unsigned char key[MAXOPTIONS]; + variant value[MAXOPTIONS]; +} rcoption; + +enum { + RCO_NONE, + RCO_SCARE, /* races that scare and eat peasants */ + RCO_OTHER, /* may recruit from another race */ + RCO_STAMINA, /* every n levels of stamina add +1 RC */ + RCO_HUNGER, /* custom hunger.damage override (char *) */ + RCO_TRADELUX, + RCO_TRADEHERB +}; + + +static void rc_setoption(race *rc, int k, const char *value) { + unsigned char key = (unsigned char)k; + int i; + variant *v = NULL; + if (!rc->options) { + rc->options = malloc(sizeof(rcoption)); + rc->options->key[0] = key; + rc->options->key[1] = RCO_NONE; + v = rc->options->value; + } else { + for (i=0;!v && i < MAXOPTIONS && rc->options->key[i]!=RCO_NONE;++i) { + if (rc->options->key[i]==key) { + v = rc->options->value+i; + } + } + if (!v) { + assert(ioptions->value+i; + rc->options->key[i] = key; + if (i+1options->key[i+1]=RCO_NONE; + } + } + } + assert(v); + if (key == RCO_SCARE) { + v->i = atoi(value); + } + else if (key == RCO_STAMINA) { + v->i = atoi(value); + } + else if (key == RCO_OTHER) { + v->v = rc_get_or_create(value); + } + else if (key == RCO_HUNGER) { + v->v = strdup(value); + } + else if (key == RCO_TRADEHERB) { + v->i = atoi(value); + } + else if (key == RCO_TRADELUX) { + v->i = atoi(value); + } +} + +static variant *rc_getoption(const race *rc, int key) { + if (rc->options) { + int i; + for (i=0;i!=MAXOPTIONS && rc->options->key[i]!=RCO_NONE;++i) { + if (rc->options->key[i]==key) { + return rc->options->value+i; + } + } + } + return NULL; +} + +const struct race *findrace(const char *s, const struct locale *lang) +{ + void **tokens = get_translations(lang, UT_RACES); + variant token; + + assert(lang); + if (tokens && findtoken(*tokens, s, &token) == E_TOK_SUCCESS) { + return (const struct race *)token.v; + } + return NULL; +} + const struct race *get_race(race_t rt) { const char * name; @@ -86,6 +176,50 @@ const struct race *get_race(race_t rt) { return rc_find(name); } +typedef struct xref { + race_t id; + const race *rc; +} rc_xref; + +int cmp_xref(const void *a, const void *b) +{ + const rc_xref *l = (const rc_xref *)a; + const rc_xref *r = (const rc_xref *)b; + if (l->rcrc) return -1; + if (l->rc>r->rc) return 1; + return 0; +} + +static rc_xref *xrefs; +race_t old_race(const struct race * rc) +{ + static int cache; + int i, l, r; + + if (rc_changed(&cache)) { + if (!xrefs) { + xrefs = malloc(sizeof(rc_xref) * MAXRACES); + } + for (i = 0; i != MAXRACES; ++i) { + xrefs[i].rc = get_race(i); + xrefs[i].id = (race_t)i; + } + qsort(xrefs, MAXRACES, sizeof(rc_xref), cmp_xref); + } + l=0; r=MAXRACES-1; + while (l<=r) { + int m = (l+r)/2; + if (rcxrefs[m].rc) { + l = m+1; + } else { + return (race_t)xrefs[m].id; + } + } + return NORACE; +} + race_list *get_familiarraces(void) { static int init = 0; @@ -94,7 +228,7 @@ race_list *get_familiarraces(void) if (!init) { race *rc = races; for (; rc != NULL; rc = rc->next) { - if (rc->init_familiar != NULL) { + if (rc->flags & RCF_FAMILIAR) { racelist_insert(&familiarraces, rc); } } @@ -124,8 +258,29 @@ void racelist_insert(struct race_list **rl, const struct race *r) void free_races(void) { while (races) { + int i; race * rc = races->next; - free_params(&races->parameters); + rcoption * opt = races->options; + + if (opt) { + for (i=0;i!=MAXOPTIONS && opt->key[i]!=RCO_NONE;++i) { + if (opt->key[i]==RCO_HUNGER) { + free(opt->value[i].v); + } + } + free(opt); + } + for (i = 0; races->attack[i].type!=AT_NONE; ++i) { + att *at = races->attack + i; + if (at->type == AT_SPELL) { + spellref_free(at->data.sp); + } + else { + free(at->data.dice); + } + } + free(xrefs); + xrefs = 0; free(races->_name); free(races->def_damage); free(races); @@ -143,9 +298,16 @@ static race *rc_find_i(const char *name) while (rc && strcmp(rname, rc->_name) != 0) { rc = rc->next; } - if (!rc && strcmp(name, "uruk") == 0) { - rc = rc_find_i("orc"); - log_warning("a reference was made to the retired race '%s', returning '%s'.", name, rc->_name); + if (!rc) { + const char *rc_depr[] = { "uruk", "orc", "illusion", "template", "juju-zombie", "juju", NULL }; + int i; + for (i = 0; rc_depr[i]; i += 2) { + if (strcmp(name, rc_depr[i]) == 0) { + rc = rc_find_i(rc_depr[i + 1]); + log_warning("a reference was made to the retired race '%s', returning '%s'.", name, rc->_name); + break; + } + } } return rc; } @@ -163,16 +325,30 @@ bool rc_changed(int *cache) { return false; } +bool rc_can_use(const struct race *rc, const struct item_type *itype) +{ + if (itype->mask_allow) { + return (itype->mask_allow & rc->mask_item) != 0; + } + if (itype->mask_deny) { + return (itype->mask_deny & rc->mask_item) == 0; + } + return true; +} + race *rc_create(const char *zName) { race *rc; int i; + char zText[64]; assert(zName); rc = (race *)calloc(sizeof(race), 1); + rc->magres.sa[1] = 1; rc->hitpoints = 1; rc->weight = PERSON_WEIGHT; rc->capacity = 540; + rc->income = 20; rc->recruit_multi = 1.0F; rc->regaura = 1.0F; rc->speed = 1.0F; @@ -181,8 +357,7 @@ race *rc_create(const char *zName) log_error("race '%s' has an invalid name. remove spaces\n", zName); assert(strchr(zName, ' ') == NULL); } - rc->_name = _strdup(zName); - rc->precombatspell = NULL; + rc->_name = strdup(zName); rc->attack[0].type = AT_COMBATSPELL; for (i = 1; i < RACE_ATTACKS; ++i) @@ -190,6 +365,13 @@ race *rc_create(const char *zName) rc->index = num_races++; ++rc_changes; rc->next = races; + + snprintf(zText, sizeof(zText), "age_%s", zName); + rc->age_unit = (race_func)get_function(zText); + + snprintf(zText, sizeof(zText), "name_%s", zName); + rc->name_unit = (race_func)get_function(zText); + return races = rc; } @@ -215,6 +397,93 @@ bool r_insectstalled(const region * r) return fval(r->terrain, ARCTIC_REGION); } +variant rc_magres(const race *rc) { + return rc->magres; +} + +double rc_maxaura(const race *rc) { + return rc->maxaura / 100.0; +} + +const char * rc_hungerdamage(const race *rc) +{ + variant *v = rc_getoption(rc, RCO_HUNGER); + return v ? (const char *)v->v : NULL; +} + +int rc_armor_bonus(const race *rc) +{ + variant *v = rc_getoption(rc, RCO_STAMINA); + return v ? v->i : 0; +} + +int rc_scare(const struct race *rc) +{ + variant *v = rc_getoption(rc, RCO_SCARE); + return v ? v->i : 0; +} + +int rc_luxury_trade(const struct race *rc) +{ + if (rc) { + variant *v = rc_getoption(rc, RCO_TRADELUX); + if (v) return v->i; + } + return 1000; +} + +int rc_herb_trade(const struct race *rc) +{ + if (rc) { + variant *v = rc_getoption(rc, RCO_TRADEHERB); + if (v) return v->i; + } + return 500; +} + +const race *rc_otherrace(const race *rc) +{ + variant *v = rc_getoption(rc, RCO_OTHER); + return v ? (const race *)v->v : NULL; +} + +int rc_migrants_formula(const race *rc) +{ + return (rc->flags&RCF_MIGRANTS) ? MIGRANTS_LOG10 : MIGRANTS_NONE; +} + +void rc_set_param(struct race *rc, const char *key, const char *value) { + if (strcmp(key, "recruit_multi") == 0) { + rc->recruit_multi = atof(value); + } + else if (strcmp(key, "migrants.formula") == 0) { + if (value[0] == '1') { + rc->flags |= RCF_MIGRANTS; + } + } + else if (strcmp(key, "other_race")==0) { + rc_setoption(rc, RCO_OTHER, value); + } + else if (strcmp(key, "ai.scare")==0) { + rc_setoption(rc, RCO_SCARE, value); + } + else if (strcmp(key, "hunger.damage")==0) { + rc_setoption(rc, RCO_HUNGER, value); + } + else if (strcmp(key, "armor.stamina")==0) { + rc_setoption(rc, RCO_STAMINA, value); + } + else if (strcmp(key, "luxury_trade")==0) { + rc_setoption(rc, RCO_TRADELUX, value); + } + else if (strcmp(key, "herb_trade")==0) { + rc_setoption(rc, RCO_TRADEHERB, value); + } + else { + log_error("unknown property for race %s: %s=%s", rc->_name, key, value); + } +} + const char* rc_name(const race * rc, name_t n, char *name, size_t size) { const char * postfix = 0; if (!rc) { @@ -228,7 +497,7 @@ const char* rc_name(const race * rc, name_t n, char *name, size_t size) { default: assert(!"invalid name_t enum in rc_name_s"); } if (postfix) { - _snprintf(name, size, "race::%s%s", rc->_name, postfix); + snprintf(name, size, "race::%s%s", rc->_name, postfix); return name; } return NULL; @@ -236,7 +505,7 @@ const char* rc_name(const race * rc, name_t n, char *name, size_t size) { const char *rc_name_s(const race * rc, name_t n) { - static char name[64]; // FIXME: static return value + static char name[64]; /* FIXME: static return value */ return rc_name(rc, n, name, sizeof(name)); } @@ -257,7 +526,7 @@ const char *racename(const struct locale *loc, const unit * u, const race * rc) const char *str, *prefix = raceprefix(u); if (prefix != NULL) { - static char lbuf[80]; // FIXME: static return value + static char lbuf[80]; /* FIXME: static return value */ char *bufp = lbuf; size_t size = sizeof(lbuf) - 1; int ch, bytes; @@ -302,17 +571,6 @@ variant read_race_reference(struct storage *store) return result; } -void register_race_description_function(race_desc_func func, const char *name) { +void register_race_function(race_func func, const char *name) { register_function((pf_generic)func, name); } - -void register_race_name_function(race_name_func func, const char *name) { - register_function((pf_generic)func, name); -} - -char * race_namegen(const struct race *rc, struct unit *u) { - if (rc->generate_name) { - rc->generate_name(u); - } - return NULL; -} diff --git a/src/kernel/race.h b/src/kernel/race.h index 17c2bc61f..fcd78ae19 100644 --- a/src/kernel/race.h +++ b/src/kernel/race.h @@ -18,13 +18,14 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef H_KRNL_RACE_H #define H_KRNL_RACE_H +#include +#include "magic.h" /* wegen MAXMAGIETYP */ +#include "skill.h" + #ifdef __cplusplus extern "C" { #endif -#include "magic.h" /* wegen MAXMAGIETYP */ -#include "skill.h" - #define AT_NONE 0 #define AT_STANDARD 1 #define AT_DRAIN_EXP 2 @@ -44,6 +45,10 @@ extern "C" { struct param; struct spell; + struct spellref; + struct locale; + struct rcoption; + struct item_type; extern int num_races; @@ -61,8 +66,8 @@ extern "C" { RC_ORC, RC_SNOTLING, RC_UNDEAD, - RC_ILLUSION, - RC_FIREDRAGON, + + RC_FIREDRAGON = 15, RC_DRAGON, RC_WYRM, RC_TREEMAN, @@ -101,56 +106,51 @@ extern "C" { typedef struct att { int type; union { - const char *dice; - const struct spell *sp; + char *dice; + struct spellref *sp; } data; int flags; int level; } att; - typedef const char *(*race_desc_func)(const struct race *rc, const struct locale *lang); - typedef void (*race_name_func)(struct unit *); + typedef void (*race_func) (struct unit *); typedef struct race { char *_name; - float magres; - float healing; - double maxaura; /* Faktor auf Maximale Aura */ + variant magres; + int healing; + int maxaura; /* Faktor auf Maximale Aura */ double regaura; /* Faktor auf Regeneration */ - double recruit_multi; /* Faktor fr Bauernverbrauch */ + double recruit_multi; /* Faktor f�r Bauernverbrauch */ int index; int recruitcost; int maintenance; int splitsize; int weight; int capacity; + int income; float speed; - float aggression; /* chance that a monster will attack */ int hitpoints; char *def_damage; int armor; int at_default; /* Angriffsskill Unbewaffnet (default: -2) */ int df_default; /* Verteidigungsskill Unbewaffnet (default: -2) */ - int at_bonus; /* Verndert den Angriffsskill (default: 0) */ - int df_bonus; /* Verndert den Verteidigungskill (default: 0) */ - struct param *parameters; // additional properties, for an example see natural_armor - const struct spell *precombatspell; + int at_bonus; /* Ver�ndert den Angriffsskill (default: 0) */ + int df_bonus; /* Ver�ndert den Verteidigungskill (default: 0) */ signed char *study_speed; /* study-speed-bonus in points/turn (0=30 Tage) */ int flags; int battle_flags; int ec_flags; + int mask_item; struct att attack[RACE_ATTACKS]; signed char bonus[MAXSKILLS]; - race_name_func generate_name; - race_desc_func describe; - void(*age) (struct unit * u); - bool(*move_allowed) (const struct region *, const struct region *); - struct item *(*itemdrop) (const struct race *, int size); - void(*init_familiar) (struct unit *); + race_func name_unit; + race_func age_unit; + + struct rcoption *options; /* rarely used properties */ const struct race *familiars[MAXMAGIETYP]; - struct attrib *attribs; struct race *next; } race; @@ -162,6 +162,7 @@ extern "C" { void racelist_clear(struct race_list **rl); void racelist_insert(struct race_list **rl, const struct race *r); + const struct race *findrace(const char *, const struct locale *); struct race_list *get_familiarraces(void); struct race *races; @@ -175,10 +176,27 @@ extern "C" { const race *rc_find(const char *); void free_races(void); + bool rc_can_use(const struct race *rc, const struct item_type *itype); + typedef enum name_t { NAME_SINGULAR, NAME_PLURAL, NAME_DEFINITIVE, NAME_CATEGORY } name_t; const char * rc_name_s(const race *rc, name_t n); const char * rc_name(const race *rc, name_t n, char *name, size_t size); + void rc_set_param(struct race *rc, const char *key, const char *value); + + int rc_luxury_trade(const struct race *rc); + int rc_herb_trade(const struct race *rc); + variant rc_magres(const struct race *rc); + double rc_maxaura(const struct race *rc); + int rc_armor_bonus(const struct race *rc); + int rc_scare(const struct race *rc); + const char * rc_hungerdamage(const race *rc); + const race *rc_otherrace(const race *rc); + +#define MIGRANTS_NONE 0 +#define MIGRANTS_LOG10 1 + int rc_migrants_formula(const race *rc); + /* Flags. Do not reorder these without changing json_race() in jsonconf.c */ #define RCF_NPC (1<<0) /* cannot be the race for a player faction (and other limits?) */ #define RCF_KILLPEASANTS (1<<1) /* a monster that eats peasants */ @@ -189,20 +207,20 @@ extern "C" { #define RCF_LEARN (1<<6) /* Lernt automatisch wenn struct faction == 0 */ #define RCF_FLY (1<<7) /* kann fliegen */ #define RCF_SWIM (1<<8) /* kann schwimmen */ -#define RCF_WALK (1<<9) /* kann ber Land gehen */ +#define RCF_WALK (1<<9) /* kann �ber Land gehen */ #define RCF_NOLEARN (1<<10) /* kann nicht normal lernen */ #define RCF_NOTEACH (1<<11) /* kann nicht lehren */ #define RCF_HORSE (1<<12) /* Einheit ist Pferd, sozusagen */ #define RCF_DESERT (1<<13) /* 5% Chance, das Einheit desertiert */ #define RCF_ILLUSIONARY (1<<14) /* (Illusion & Spell) Does not drop items. */ -#define RCF_ABSORBPEASANTS (1<<15) /* Ttet und absorbiert Bauern */ +#define RCF_ABSORBPEASANTS (1<<15) /* T�tet und absorbiert Bauern */ #define RCF_NOHEAL (1<<16) /* Einheit kann nicht geheilt werden */ #define RCF_NOWEAPONS (1<<17) /* Einheit kann keine Waffen benutzen */ #define RCF_SHAPESHIFT (1<<18) /* Kann TARNE RASSE benutzen. */ #define RCF_SHAPESHIFTANY (1<<19) /* Kann TARNE RASSE "string" benutzen. */ #define RCF_UNDEAD (1<<20) /* Undead. */ -#define RCF_DRAGON (1<<21) /* Drachenart (fr Zauber) */ -#define RCF_COASTAL (1<<22) /* kann in Landregionen an der Kste sein */ +#define RCF_DRAGON (1<<21) /* Drachenart (f�r Zauber) */ +#define RCF_COASTAL (1<<22) /* kann in Landregionen an der K�ste sein */ #define RCF_UNARMEDGUARD (1<<23) /* kann ohne Waffen bewachen */ #define RCF_CANSAIL (1<<24) /* Einheit darf Schiffe betreten */ #define RCF_INVISIBLE (1<<25) /* not visible in any report */ @@ -210,19 +228,20 @@ extern "C" { #define RCF_STONEGOLEM (1<<27) /* race gets stonegolem properties */ #define RCF_IRONGOLEM (1<<28) /* race gets irongolem properties */ #define RCF_ATTACK_MOVED (1<<29) /* may attack if it has moved */ +#define RCF_MIGRANTS (1<<30) /* may have migrant units (human bonus) */ +#define RCF_FAMILIAR (1<<31) /* may be a familiar */ /* Economic flags */ -#define ECF_KEEP_ITEM (1<<1) /* gibt Gegenstnde weg */ -#define GIVEPERSON (1<<2) /* bergibt Personen */ -#define GIVEUNIT (1<<3) /* Einheiten an andere Partei bergeben */ -#define GETITEM (1<<4) /* nimmt Gegenstnde an */ -#define ECF_REC_HORSES (1<<6) /* Rekrutiert aus Pferden */ +#define ECF_KEEP_ITEM (1<<1) /* gibt Gegenst�nde weg */ +#define GIVEPERSON (1<<2) /* �bergibt Personen */ +#define GIVEUNIT (1<<3) /* Einheiten an andere Partei �bergeben */ +#define GETITEM (1<<4) /* nimmt Gegenst�nde an */ #define ECF_REC_ETHEREAL (1<<7) /* Rekrutiert aus dem Nichts */ #define ECF_REC_UNLIMITED (1<<8) /* Rekrutiert ohne Limit */ /* Battle-Flags */ -#define BF_EQUIPMENT (1<<0) /* Kann Ausrstung benutzen */ -#define BF_NOBLOCK (1<<1) /* Wird in die Rckzugsberechnung nicht einbezogen */ +#define BF_EQUIPMENT (1<<0) /* Kann Ausr�stung benutzen */ +#define BF_NOBLOCK (1<<1) /* Wird in die R�ckzugsberechnung nicht einbezogen */ #define BF_RES_PIERCE (1<<2) /* Halber Schaden durch PIERCE */ #define BF_RES_CUT (1<<3) /* Halber Schaden durch CUT */ #define BF_RES_BASH (1<<4) /* Halber Schaden durch BASH */ @@ -232,10 +251,10 @@ extern "C" { const char *racename(const struct locale *lang, const struct unit *u, const race * rc); -#define playerrace(rc) (!fval((rc), RCF_NPC)) -#define dragonrace(rc) (fval(rc, RCF_DRAGON)) -#define humanoidrace(rc) (fval((rc), RCF_UNDEAD) || (rc)==get_race(RC_DRACOID) || playerrace(rc)) -#define illusionaryrace(rc) (fval(rc, RCF_ILLUSIONARY)) +#define playerrace(rc) (!((rc)->flags & RCF_NPC)) +#define dragonrace(rc) ((rc)->flags & RCF_DRAGON) +#define humanoidrace(rc) (((rc)->flags & RCF_UNDEAD) || (rc)==get_race(RC_DRACOID) || playerrace(rc)) +#define illusionaryrace(rc) ((rc)->flags & RCF_ILLUSIONARY) bool allowed_dragon(const struct region *src, const struct region *target); @@ -247,9 +266,7 @@ extern "C" { variant read_race_reference(struct storage *store); const char *raceprefix(const struct unit *u); - void register_race_name_function(race_name_func, const char *); - void register_race_description_function(race_desc_func, const char *); - char * race_namegen(const struct race *rc, struct unit *u); + void register_race_function(race_func, const char *); #ifdef __cplusplus } diff --git a/src/kernel/race.test.c b/src/kernel/race.test.c index ec4b40f92..2db76a6fd 100644 --- a/src/kernel/race.test.c +++ b/src/kernel/race.test.c @@ -1,10 +1,13 @@ #include #include #include "race.h" -#include +#include "item.h" + #include +#include #include +#include #include static void test_rc_name(CuTest *tc) { @@ -23,8 +26,10 @@ static void test_rc_defaults(CuTest *tc) { test_setup(); rc = rc_get_or_create("human"); CuAssertStrEquals(tc, "human", rc->_name); - CuAssertDblEquals(tc, 0.0, rc->magres, 0.0); - CuAssertDblEquals(tc, 0.0, rc->maxaura, 0.0); + CuAssertIntEquals(tc, 0, rc_armor_bonus(rc)); + CuAssertIntEquals(tc, 0, rc->magres.sa[0]); + CuAssertIntEquals(tc, 0, rc->healing); + CuAssertDblEquals(tc, 0.0, rc_maxaura(rc), 0.0); CuAssertDblEquals(tc, 1.0, rc->recruit_multi, 0.0); CuAssertDblEquals(tc, 1.0, rc->regaura, 0.0); CuAssertDblEquals(tc, 1.0, rc->speed, 0.0); @@ -32,6 +37,7 @@ static void test_rc_defaults(CuTest *tc) { CuAssertIntEquals(tc, 0, rc->recruitcost); CuAssertIntEquals(tc, 0, rc->maintenance); CuAssertIntEquals(tc, 540, rc->capacity); + CuAssertIntEquals(tc, 20, rc->income); CuAssertIntEquals(tc, 1, rc->hitpoints); CuAssertIntEquals(tc, 0, rc->armor); CuAssertIntEquals(tc, 0, rc->at_bonus); @@ -65,13 +71,96 @@ static void test_race_get(CuTest *tc) { test_cleanup(); } +static void test_old_race(CuTest *tc) +{ + race * rc1, *rc2; + test_setup(); + test_create_race("dwarf"); + rc1 = test_create_race("elf"); + rc2 = test_create_race("onkel"); + CuAssertIntEquals(tc, RC_ELF, old_race(rc1)); + CuAssertIntEquals(tc, NORACE, old_race(rc2)); + rc2 = test_create_race("human"); + CuAssertIntEquals(tc, RC_ELF, old_race(rc1)); + CuAssertIntEquals(tc, RC_HUMAN, old_race(rc2)); + test_cleanup(); +} + +static void test_rc_set_param(CuTest *tc) { + race *rc; + test_setup(); + rc = test_create_race("human"); + CuAssertPtrEquals(tc, NULL, rc->options); + rc_set_param(rc, "recruit_multi", "0.5"); + CuAssertDblEquals(tc, 0.5, rc->recruit_multi, 0.0); + rc_set_param(rc, "migrants.formula", "1"); + CuAssertIntEquals(tc, RCF_MIGRANTS, rc->flags&RCF_MIGRANTS); + CuAssertIntEquals(tc, MIGRANTS_LOG10, rc_migrants_formula(rc)); + rc_set_param(rc, "ai.scare", "400"); + CuAssertIntEquals(tc, 400, rc_scare(rc)); + rc_set_param(rc, "hunger.damage", "1d10+12"); + CuAssertStrEquals(tc, "1d10+12", rc_hungerdamage(rc)); + test_cleanup(); +} + +static void test_rc_can_use(CuTest *tc) { + race *rc; + item_type *itype; + + test_setup(); + rc = test_create_race("goblin"); + itype = test_create_itemtype("plate"); + CuAssertTrue(tc, rc_can_use(rc, itype)); + + /* default case. all items and races in E2 */ + itype->mask_deny = 0; + rc->mask_item = 0; + CuAssertTrue(tc, rc_can_use(rc, itype)); + + /* some race is forbidden from using this item. */ + itype->mask_deny = 1; + + /* we are not that race. */ + rc->mask_item = 2; + CuAssertTrue(tc, rc_can_use(rc, itype)); + + /* we are that race */ + rc->mask_item = 1; + CuAssertTrue(tc, ! rc_can_use(rc, itype)); + + /* we are not a special race at all */ + rc->mask_item = 0; + CuAssertTrue(tc, rc_can_use(rc, itype)); + + /* only one race is allowed to use this item */ + itype->mask_deny = 0; + itype->mask_allow = 1; + + /* we are not that race */ + rc->mask_item = 2; + CuAssertTrue(tc, ! rc_can_use(rc, itype)); + + /* we are that race */ + rc->mask_item = 1; + CuAssertTrue(tc, rc_can_use(rc, itype)); + + /* we are not special */ + rc->mask_item = 0; + CuAssertTrue(tc, ! rc_can_use(rc, itype)); + + test_cleanup(); +} + CuSuite *get_race_suite(void) { CuSuite *suite = CuSuiteNew(); SUITE_ADD_TEST(suite, test_race_get); + SUITE_ADD_TEST(suite, test_old_race); SUITE_ADD_TEST(suite, test_rc_name); SUITE_ADD_TEST(suite, test_rc_defaults); SUITE_ADD_TEST(suite, test_rc_find); + SUITE_ADD_TEST(suite, test_rc_set_param); + SUITE_ADD_TEST(suite, test_rc_can_use); return suite; } diff --git a/src/kernel/region.c b/src/kernel/region.c index 4c66e04f8..e4f33db33 100644 --- a/src/kernel/region.c +++ b/src/kernel/region.c @@ -32,13 +32,13 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "plane.h" #include "region.h" #include "resources.h" -#include "save.h" #include "ship.h" #include "terrain.h" #include "terrainid.h" #include "unit.h" /* util includes */ +#include #include #include #include @@ -135,6 +135,13 @@ const char *regionname(const region * r, const faction * f) return write_regionname(r, f, buf[index], sizeof(buf[index])); } +int region_maxworkers(const region *r) +{ + int size = production(r); + int treespace = (rtrees(r, 2) + rtrees(r, 1) / 2) * TREESIZE; + return MAX(size - treespace, MIN(size / 10, 200)); +} + int deathcount(const region * r) { attrib *a = a_find(r->attribs, &at_deathcount); @@ -397,7 +404,7 @@ koor_distance_wrap_xy(int x1, int y1, int x2, int y2, int width, int height) int dx = x1 - x2; int dy = y1 - y2; int result, dist; - int mindist = _min(width, height) >> 1; + int mindist = MIN(width, height) >> 1; /* Bei negativem dy am Ursprung spiegeln, das veraendert * den Abstand nicht @@ -420,13 +427,13 @@ koor_distance_wrap_xy(int x1, int y1, int x2, int y2, int width, int height) if (result <= mindist) return result; } - dist = _max(dx, height - dy); + dist = MAX(dx, height - dy); if (dist >= 0 && dist < result) { result = dist; if (result <= mindist) return result; } - dist = _max(width - dx, dy); + dist = MAX(width - dx, dy); if (dist >= 0 && dist < result) result = dist; return result; @@ -691,6 +698,7 @@ void r_setdemand(region * r, const luxury_type * ltype, int value) d = *dp; if (!d) { d = *dp = malloc(sizeof(struct demand)); + assert_alloc(d); d->next = NULL; d->type = ltype; } @@ -762,6 +770,7 @@ region *new_region(int x, int y, struct plane *pl, int uid) return r; } r = calloc(1, sizeof(region)); + assert_alloc(r); r->x = x; r->y = y; r->uid = uid; @@ -1009,6 +1018,20 @@ void setluxuries(region * r, const luxury_type * sale) } } +int fix_demand(region * rd) { + luxury_type * ltype; + int maxluxuries = get_maxluxuries(); + if (maxluxuries > 0) { + int sale = rng_int() % maxluxuries; + for (ltype = luxurytypes; sale != 0 && ltype; ltype = ltype->next) { + --sale; + } + setluxuries(rd, ltype); + return 0; + } + return -1; +} + void terraform_region(region * r, const terrain_type * terrain) { /* Resourcen, die nicht mehr vorkommen knnen, lschen */ @@ -1057,7 +1080,6 @@ void terraform_region(region * r, const terrain_type * terrain) rsetmoney(r, 0); freset(r, RF_ENCOUNTER); freset(r, RF_MALLORN); - /* Beschreibung und Namen lschen */ return; } @@ -1082,6 +1104,7 @@ void terraform_region(region * r, const terrain_type * terrain) r->land->ownership = NULL; region_set_morale(r, MORALE_DEFAULT, -1); region_setname(r, makename()); + fix_demand(r); for (d = 0; d != MAXDIRECTIONS; ++d) { region *nr = rconnect(r, d); if (nr && nr->land) { @@ -1112,7 +1135,7 @@ void terraform_region(region * r, const terrain_type * terrain) } } if (!nb) { - // TODO: this is really lame + /* TODO: this is really lame */ int i = get_maxluxuries(); if (i > 0) { i = rng_int() % i; @@ -1194,8 +1217,8 @@ void terraform_region(region * r, const terrain_type * terrain) if (!fval(r, RF_CHAOTIC)) { int peasants; - peasants = (maxworkingpeasants(r) * (20 + dice_rand("6d10"))) / 100; - rsetpeasants(r, _max(100, peasants)); + peasants = (region_maxworkers(r) * (20 + dice_rand("6d10"))) / 100; + rsetpeasants(r, MAX(100, peasants)); rsetmoney(r, rpeasants(r) * ((wage(r, NULL, NULL, INT_MAX) + 1) + rng_int() % 5)); } @@ -1304,9 +1327,17 @@ struct message *msg) struct faction *region_get_owner(const struct region *r) { - assert(rule_region_owners()); - if (r->land && r->land->ownership) { - return r->land->ownership->owner; + if (r->land) { + if (rule_region_owners()) { + if (r->land->ownership) { + return r->land->ownership->owner; + } + } + else { + building *b = largestbuilding(r, cmp_castle_size, false); + unit * u = b ? building_owner(b) : NULL; + return u ? u->faction : NULL; + } } return NULL; } @@ -1375,7 +1406,7 @@ faction *update_owners(region * r) else if (f || new_owner->faction != region_get_last_owner(r)) { alliance *al = region_get_alliance(r); if (al && new_owner->faction->alliance == al) { - int morale = _max(0, region_get_morale(r) - MORALE_TRANSFER); + int morale = MAX(0, region_get_morale(r) - MORALE_TRANSFER); region_set_morale(r, morale, turn); } else { @@ -1398,7 +1429,7 @@ faction *update_owners(region * r) void region_setinfo(struct region *r, const char *info) { free(r->display); - r->display = info ? _strdup(info) : 0; + r->display = info ? strdup(info) : 0; } const char *region_getinfo(const region * r) @@ -1410,7 +1441,7 @@ void region_setname(struct region *r, const char *name) { if (r->land) { free(r->land->name); - r->land->name = name ? _strdup(name) : 0; + r->land->name = name ? strdup(name) : 0; } } diff --git a/src/kernel/region.h b/src/kernel/region.h index 6e231529d..9fa1a2daa 100644 --- a/src/kernel/region.h +++ b/src/kernel/region.h @@ -20,6 +20,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #define H_KRNL_REGION #include +#include #include "types.h" #include "direction.h" @@ -44,7 +45,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #define RF_ENCOUNTER (1<<9) /* persistent */ #define RF_MAPPER_HIGHLIGHT (1<<10) #define RF_LIGHTHOUSE (1<<11) /* this region may contain a lighthouse */ -#define RF_ORCIFIED (1<<12) /* persistent */ #define RF_MIGRATION (1<<13) #define RF_UNUSED_14 (1<<14) @@ -58,7 +58,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #define RF_ALL 0xFFFFFF -#define RF_SAVEMASK (RF_CHAOTIC|RF_MALLORN|RF_BLOCKED|RF_ENCOUNTER|RF_ORCIFIED|RF_GUARDED|RF_LIGHTHOUSE) +#define RF_SAVEMASK (RF_CHAOTIC|RF_MALLORN|RF_BLOCKED|RF_ENCOUNTER|RF_GUARDED|RF_LIGHTHOUSE) struct message; struct message_list; struct rawmaterial; @@ -160,6 +160,7 @@ extern "C" { #define reg_hashkey(r) (r->index) + extern int fix_demand(struct region *r); int distance(const struct region *, const struct region *); int koor_distance(int ax, int ay, int bx, int by); struct region *findregion(int x, int y); @@ -264,6 +265,7 @@ extern "C" { const char *regionname(const struct region *r, const struct faction *f); + int region_maxworkers(const struct region *r); const char *region_getname(const struct region *self); void region_setname(struct region *self, const char *name); const char *region_getinfo(const struct region *self); diff --git a/src/kernel/region.test.c b/src/kernel/region.test.c new file mode 100644 index 000000000..892b37a8e --- /dev/null +++ b/src/kernel/region.test.c @@ -0,0 +1,61 @@ +#include + +#include "region.h" +#include "building.h" +#include "unit.h" +#include "terrain.h" +#include "item.h" + +#include +#include + +void test_terraform(CuTest *tc) { + region *r; + terrain_type *t_plain, *t_ocean; + item_type *itype; + + test_setup(); + itype = test_create_itemtype("ointment"); + itype->rtype->flags |= (RTF_ITEM | RTF_POOLED); + new_luxurytype(itype, 0); + + t_plain = test_create_terrain("plain", LAND_REGION); + t_ocean = test_create_terrain("ocean", SEA_REGION); + r = test_create_region(0, 0, t_ocean); + CuAssertPtrEquals(tc, 0, r->land); + terraform_region(r, t_plain); + CuAssertPtrNotNull(tc, r->land); + CuAssertPtrNotNull(tc, r->land->demands); + CuAssertPtrEquals(tc, itype, (void *)r->land->demands->type->itype); + CuAssertIntEquals(tc, 0, r->land->demands->type->price); + terraform_region(r, t_ocean); + CuAssertPtrEquals(tc, 0, r->land); + test_cleanup(); +} + +static void test_region_get_owner(CuTest *tc) { + region *r; + building *b1, *b2; + unit *u1, *u2; + + test_setup(); + r = test_create_region(0, 0, 0); + b1 = test_create_building(r, NULL); + b2 = test_create_building(r, NULL); + b1->size = 5; + b2->size = 10; + u1 = test_create_unit(test_create_faction(0), r); + u_set_building(u1, b1); + u2 = test_create_unit(test_create_faction(0), r); + u_set_building(u2, b2); + CuAssertPtrEquals(tc, u2->faction, region_get_owner(r)); + test_cleanup(); +} + +CuSuite *get_region_suite(void) +{ + CuSuite *suite = CuSuiteNew(); + SUITE_ADD_TEST(suite, test_terraform); + SUITE_ADD_TEST(suite, test_region_get_owner); + return suite; +} diff --git a/src/kernel/resources.c b/src/kernel/resources.c index 658445c69..10cb2bab6 100644 --- a/src/kernel/resources.c +++ b/src/kernel/resources.c @@ -46,7 +46,7 @@ extern int dice_rand(const char *s); static void update_resource(struct rawmaterial *res, double modifier) { - double amount = 1 + (res->level - res->startlevel) * res->divisor / 100.0; + double amount = (res->level - res->startlevel) / 100.0 * res->divisor + 1; amount = ResourceFactor() * res->base * amount * modifier; if (amount < 1.0) res->amount = 1; @@ -69,6 +69,7 @@ const resource_type * rtype) rm->divisor = divisor; rm->flags = 0; rm->type = rmt_get(rtype); + assert(rm->type); update_resource(rm, 1.0); rm->type->terraform(rm, r); } @@ -111,7 +112,7 @@ static void terraform_default(struct rawmaterial *res, const region * r) res->amount = (int)(res->amount * modifier); /* random adjustment, +/- 91% */ if (res->amount < 1) res->amount = 1; - unused_arg(r); + UNUSED_ARG(r); } #ifdef RANDOM_CHANGE @@ -183,35 +184,53 @@ struct rawmaterial *rm_get(region * r, const struct resource_type *rtype) return rm; } -struct rawmaterial_type *rawmaterialtypes = 0; - struct rawmaterial_type *rmt_find(const char *str) { - rawmaterial_type *rmt = rawmaterialtypes; - while (rmt && strcmp(rmt->name, str) != 0) - rmt = rmt->next; - return rmt; + resource_type *rtype = rt_find(str); + if (!rtype && strncmp(str, "rm_", 3) == 0) { + rtype = rt_find(str+3); + } + assert(rtype); + return rtype ? rtype->raw : NULL; } struct rawmaterial_type *rmt_get(const struct resource_type *rtype) { - rawmaterial_type *rmt = rawmaterialtypes; - while (rmt && rmt->rtype != rtype) - rmt = rmt->next; - return rmt; + return rtype->raw; } -struct rawmaterial_type *rmt_create(const struct resource_type *rtype, - const char *name) +struct rawmaterial_type *rmt_create(struct resource_type *rtype) { - rawmaterial_type *rmtype = malloc(sizeof(rawmaterial_type)); - rmtype->name = _strdup(name); + rawmaterial_type *rmtype; + + assert(!rtype->raw); + rmtype = rtype->raw = malloc(sizeof(rawmaterial_type)); rmtype->rtype = rtype; rmtype->terraform = terraform_default; rmtype->update = NULL; rmtype->use = use_default; rmtype->visible = visible_default; - rmtype->next = rawmaterialtypes; - rawmaterialtypes = rmtype; return rmtype; } + +int(*item_use_fun)(struct unit *u, const struct item_type *itype, int amount, + struct order *ord); +int(*res_limit_fun)(const struct region *, const struct resource_type *); +void(*res_produce_fun)(struct region *, const struct resource_type *, int); + +int limit_resource(const struct region *r, const resource_type *rtype) +{ + assert(!rtype->raw); + if (res_limit_fun) { + return res_limit_fun(r, rtype); + } + return -1; +} + +void produce_resource(struct region *r, const struct resource_type *rtype, int amount) +{ + assert(!rtype->raw); + if (res_produce_fun) { + res_produce_fun(r, rtype, amount); + } +} diff --git a/src/kernel/resources.h b/src/kernel/resources.h index 32c69036c..7f48fa0dd 100644 --- a/src/kernel/resources.h +++ b/src/kernel/resources.h @@ -15,6 +15,9 @@ extern "C" { #endif + struct building_type; + struct race; + enum { RM_USED = 1 << 0, /* resource has been used */ RM_MALLORN = 1 << 1 /* this is not wood. it's mallorn */ @@ -40,34 +43,41 @@ extern "C" { struct rawmaterial *next; } rawmaterial; + typedef struct resource_mod { + variant value; + const struct building_type *btype; + const struct race *race; + unsigned int flags; + } resource_mod; + typedef struct rawmaterial_type { - char *name; const struct resource_type *rtype; void(*terraform) (struct rawmaterial *, const struct region *); void(*update) (struct rawmaterial *, const struct region *); void(*use) (struct rawmaterial *, const struct region *, int amount); int(*visible) (const struct rawmaterial *, int skilllevel); - - /* no initialization required */ - struct rawmaterial_type *next; } rawmaterial_type; extern struct rawmaterial_type *rawmaterialtypes; - extern void update_resources(struct region *r); - extern void terraform_resources(struct region *r); - extern void read_resources(struct region *r); - extern void write_resources(struct region *r); - extern struct rawmaterial *rm_get(struct region *, + void update_resources(struct region *r); + void terraform_resources(struct region *r); + struct rawmaterial *rm_get(struct region *, const struct resource_type *); - extern struct rawmaterial_type *rmt_find(const char *str); - extern struct rawmaterial_type *rmt_get(const struct resource_type *); + struct rawmaterial_type *rmt_find(const char *str); + struct rawmaterial_type *rmt_get(const struct resource_type *); - extern void add_resource(struct region *r, int level, int base, int divisor, + void add_resource(struct region *r, int level, int base, int divisor, const struct resource_type *rtype); - extern struct rawmaterial_type *rmt_create(const struct resource_type *rtype, - const char *name); + struct rawmaterial_type *rmt_create(struct resource_type *rtype); + + extern int(*res_limit_fun)(const struct region *, const struct resource_type *); + extern void(*res_produce_fun)(struct region *, const struct resource_type *, int); + extern int (*item_use_fun)(struct unit *, const struct item_type *, int amount, + struct order *ord); + int limit_resource(const struct region *r, const struct resource_type *rtype); + void produce_resource(struct region *r, const struct resource_type *rtype, int amount); #ifdef __cplusplus } diff --git a/src/kernel/rules.c b/src/kernel/rules.c new file mode 100644 index 000000000..c7499fe0c --- /dev/null +++ b/src/kernel/rules.c @@ -0,0 +1,12 @@ +#include +#include "rules.h" + +int write_rules(const char *filename) { + return -1; +} + +int read_rules(const char *filename) +{ + return -1; +} + diff --git a/src/kernel/rules.h b/src/kernel/rules.h new file mode 100644 index 000000000..98f0bf240 --- /dev/null +++ b/src/kernel/rules.h @@ -0,0 +1,5 @@ +#pragma once + +int read_rules(const char *filename); +int write_rules(const char * filename); + diff --git a/src/kernel/save.c b/src/kernel/save.c index 34a408113..e487737f9 100644 --- a/src/kernel/save.c +++ b/src/kernel/save.c @@ -1,4 +1,4 @@ -/* +/* Copyright (c) 1998-2015, Enno Rehling Katja Zedel @@ -52,6 +52,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include /* util includes */ +#include #include #include #include @@ -71,7 +72,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include -#include +#include #include #include #include @@ -93,6 +94,8 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* exported symbols symbols */ int firstx = 0, firsty = 0; + +/* TODO: is this still important? */ int enc_gamedata = ENCODING_UTF8; /* local symbols */ @@ -207,12 +210,14 @@ static unit *unitorders(FILE * F, int enc, struct faction *f) if (*ordp) { ordp = &(*ordp)->next; } + else { + ADDMSG(&f->msgs, msg_message("parse_error", "unit command", u, s)); + } } } } else { - /* cmistake(?, buf, 160, MSG_EVENT); */ return NULL; } return u; @@ -231,8 +236,7 @@ static faction *factionorders(void) if (!checkpasswd(f, (const char *)pass)) { log_debug("Invalid password for faction %s", itoa36(fid)); - ADDMSG(&f->msgs, msg_message("wrongpasswd", "faction password", - f->no, pass)); + ADDMSG(&f->msgs, msg_message("wrongpasswd", "password", pass)); return 0; } /* Die Partei hat sich zumindest gemeldet, so dass sie noch @@ -276,7 +280,7 @@ int readorders(const char *filename) const char *s; init_tokens_str(b); s = gettoken(token, sizeof(token)); - p = (s && s[0] != '@') ? findparam(s, lang) : NOPARAM; + p = findparam_block(s, lang, true); switch (p) { case P_GAMENAME: case P_FACTION: @@ -294,7 +298,7 @@ int readorders(const char *filename) * vermerkt. */ case P_UNIT: - if (!f || !unitorders(F, enc_gamedata, f)) + if (!f || !unitorders(F, enc_gamedata, f)) { do { b = getbuf(F, enc_gamedata); if (!b) { @@ -305,7 +309,8 @@ int readorders(const char *filename) p = (s && s[0] != '@') ? findparam(s, lang) : NOPARAM; } while ((p != P_UNIT || !f) && p != P_FACTION && p != P_NEXT && p != P_GAMENAME); - break; + } + break; /* Falls in unitorders() abgebrochen wird, steht dort entweder eine neue * Partei, eine neue Einheit oder das File-Ende. Das switch() wird erneut @@ -374,49 +379,6 @@ race_t typus2race(unsigned char typus) return NORACE; } -void create_backup(char *file) -{ -#ifdef HAVE_LINK - char bfile[MAX_PATH]; - int c = 1; - - if (access(file, R_OK) == 0) - return; - do { - sprintf(bfile, "%s.backup%d", file, c); - c++; - } while (access(bfile, R_OK) == 0); - link(file, bfile); -#endif -} - -void read_items(struct storage *store, item ** ilist) -{ - for (;;) { - char ibuf[32]; - const item_type *itype; - int i; - READ_STR(store, ibuf, sizeof(ibuf)); - if (!strcmp("end", ibuf)) { - break; - } - itype = it_find(ibuf); - READ_INT(store, &i); - if (i <= 0) { - log_error("data contains an entry with %d %s", i, resourcename(itype->rtype, NMF_PLURAL)); - } - else { - if (itype && itype->rtype) { - i_change(ilist, itype, i); - } - else { - log_error("data contains unknown item type %s.", ibuf); - } - assert(itype && itype->rtype); - } - } -} - static void read_alliances(struct gamedata *data) { storage *store = data->store; @@ -474,7 +436,7 @@ void read_planes(gamedata *data) { } pl->id = id; READ_STR(store, name, sizeof(name)); - pl->name = _strdup(name); + pl->name = strdup(name); READ_INT(store, &pl->minx); READ_INT(store, &pl->maxx); READ_INT(store, &pl->miny); @@ -506,7 +468,7 @@ void read_planes(gamedata *data) { } } read_attribs(data, &pl->attribs, pl); - if (pl->id != 1094969858) { // Regatta + if (pl->id != 1094969858) { /* Regatta */ addlist(&planes, pl); } } @@ -549,19 +511,6 @@ void write_alliances(struct gamedata *data) WRITE_SECTION(data->store); } -void write_items(struct storage *store, item * ilist) -{ - item *itm; - for (itm = ilist; itm; itm = itm->next) { - assert(itm->number >= 0); - if (itm->number) { - WRITE_TOK(store, resourcename(itm->type->rtype, 0)); - WRITE_INT(store, itm->number); - } - } - WRITE_TOK(store, "end"); -} - static int resolve_owner(variant id, void *address) { region_owner *owner = (region_owner *)address; @@ -666,36 +615,6 @@ writeorder(struct gamedata *data, const struct order *ord, WRITE_STR(data->store, obuf); } -int read_attribs(gamedata *data, attrib **alist, void *owner) { - int result; - if (data->version < ATHASH_VERSION) { - result = a_read_orig(data, alist, owner); - } - else { - result = a_read(data, alist, owner); - } - if (result == AT_READ_DEPR) { - /* handle deprecated attributes */ - attrib *a = *alist; - while (a) { - if (a->type->upgrade) { - a->type->upgrade(alist, a); - } - a = a->nexttype; - } - } - return result; -} - -void write_attribs(storage *store, attrib *alist, const void *owner) -{ -#if RELEASE_VERSION < ATHASH_VERSION - a_write_orig(store, alist, owner); -#else - a_write(store, alist, owner); -#endif -} - unit *read_unit(struct gamedata *data) { unit *u; @@ -728,6 +647,7 @@ unit *read_unit(struct gamedata *data) } else { u = calloc(sizeof(unit), 1); + assert_alloc(u); u->no = n; uhash(u); } @@ -746,13 +666,19 @@ unit *read_unit(struct gamedata *data) } READ_STR(data->store, obuf, sizeof(obuf)); - u->_name = obuf[0] ? _strdup(obuf) : 0; + if (unicode_utf8_trim(obuf)!=0) { + log_warning("trim unit %s name to '%s'", itoa36(u->no), obuf); + } + u->_name = obuf[0] ? strdup(obuf) : 0; if (lomem) { READ_STR(data->store, NULL, 0); } else { READ_STR(data->store, obuf, sizeof(obuf)); - u->display = obuf[0] ? _strdup(obuf) : 0; + if (unicode_utf8_trim(obuf)!=0) { + log_warning("trim unit %s info to '%s'", itoa36(u->no), obuf); + } + u->display = obuf[0] ? strdup(obuf) : 0; } READ_INT(data->store, &number); set_number(u, number); @@ -771,17 +697,6 @@ unit *read_unit(struct gamedata *data) else u->irace = NULL; - if (rc->describe) { - const char *rcdisp = rc->describe(rc, u->faction->locale); - if (u->display && rcdisp) { - /* see if the data file contains old descriptions */ - if (strcmp(rcdisp, u->display) == 0) { - free(u->display); - u->display = NULL; - } - } - } - READ_INT(data->store, &n); if (n > 0) { building * b = findbuilding(n); @@ -985,6 +900,9 @@ static region *readregion(struct gamedata *data, int x, int y) else { char info[DISPLAYSIZE]; READ_STR(data->store, info, sizeof(info)); + if (unicode_utf8_trim(info)!=0) { + log_warning("trim region %d info to '%s'", uid, info); + }; region_setinfo(r, info); } @@ -1002,7 +920,10 @@ static region *readregion(struct gamedata *data, int x, int y) if (fval(r->terrain, LAND_REGION)) { r->land = calloc(1, sizeof(land_region)); READ_STR(data->store, name, sizeof(name)); - r->land->name = _strdup(name); + if (unicode_utf8_trim(name)!=0) { + log_warning("trim region %d name to '%s'", uid, name); + }; + r->land->name = strdup(name); } if (r->land) { int i; @@ -1097,10 +1018,13 @@ static region *readregion(struct gamedata *data, int x, int y) READ_INT(data->store, &n); r_setdemand(r, rtype->ltype, n); } + if (!r->land->demands) { + fix_demand(r); + } read_items(data->store, &r->land->items); if (data->version >= REGIONOWNER_VERSION) { READ_INT(data->store, &n); - region_set_morale(r, _max(0, (short)n), -1); + region_set_morale(r, MAX(0, (short)n), -1); read_owner(data, &r->land->ownership); } } @@ -1108,6 +1032,17 @@ static region *readregion(struct gamedata *data, int x, int y) return r; } +region *read_region(gamedata *data) +{ + storage *store = data->store; + region *r; + int x, y; + READ_INT(store, &x); + READ_INT(store, &y); + r = readregion(data, x, y); + return r; +} + void writeregion(struct gamedata *data, const region * r) { assert(r); @@ -1135,7 +1070,7 @@ void writeregion(struct gamedata *data, const region * r) WRITE_INT(data->store, rhorses(r)); while (res) { - WRITE_TOK(data->store, res->type->name); + WRITE_TOK(data->store, res->type->rtype->_name); WRITE_INT(data->store, res->level); WRITE_INT(data->store, res->amount); WRITE_INT(data->store, res->startlevel); @@ -1172,6 +1107,14 @@ void writeregion(struct gamedata *data, const region * r) WRITE_SECTION(data->store); } +void write_region(gamedata *data, const region *r) +{ + storage *store = data->store; + WRITE_INT(store, r->x); + WRITE_INT(store, r->y); + writeregion(data, r); +} + static ally **addally(const faction * f, ally ** sfp, int aid, int state) { struct faction *af = findfaction(aid); @@ -1226,56 +1169,6 @@ int get_spell_level_faction(const spell * sp, void * cbdata) return 0; } -void read_spellbook(spellbook **bookp, gamedata *data, int(*get_level)(const spell * sp, void *), void * cbdata) -{ - for (;;) { - spell *sp = 0; - char spname[64]; - int level = 0; - - READ_TOK(data->store, spname, sizeof(spname)); - if (strcmp(spname, "end") == 0) - break; - if (bookp) { - sp = find_spell(spname); - if (!sp) { - log_error("read_spells: could not find spell '%s'", spname); - } - } - if (data->version >= SPELLBOOK_VERSION) { - READ_INT(data->store, &level); - } - if (sp) { - spellbook * sb = *bookp; - if (level <= 0 && get_level) { - level = get_level(sp, cbdata); - } - if (!sb) { - *bookp = create_spellbook(0); - sb = *bookp; - } - if (level > 0 && (data->version >= SPELLBOOK_VERSION || !spellbook_get(sb, sp))) { - spellbook_add(sb, sp, level); - } - } - } -} - -void write_spellbook(const struct spellbook *book, struct storage *store) -{ - quicklist *ql; - int qi; - - if (book) { - for (ql = book->spells, qi = 0; ql; ql_advance(&ql, &qi, 1)) { - spellbook_entry *sbe = (spellbook_entry *)ql_get(ql, qi); - WRITE_TOK(store, sbe->sp->sname); - WRITE_INT(store, sbe->level); - } - } - WRITE_TOK(store, "end"); -} - static char * getpasswd(int fno) { const char *prefix = itoa36(fno); size_t len = strlen(prefix); @@ -1289,7 +1182,7 @@ static char * getpasswd(int fno) { assert(line[slen] == '\n'); line[slen] = 0; fclose(F); - return _strdup(line + len + 1); + return strdup(line + len + 1); } } fclose(F); @@ -1304,7 +1197,7 @@ static void read_password(gamedata *data, faction *f) { char * pass = getpasswd(f->no); if (pass) { faction_setpassword(f, password_encode(pass, PASSWORD_DEFAULT)); - free(pass); // TODO: remove this allocation! + free(pass); /* TODO: remove this allocation! */ } else { log_error("data version is BADCRYPT but %s not in password.txt", itoa36(f->no)); @@ -1327,11 +1220,7 @@ void _test_write_password(gamedata *data, const faction *f) { write_password(data, f); } -/** Reads a faction from a file. - * This function requires no context, can be called in any state. The - * faction may not already exist, however. - */ -faction *readfaction(struct gamedata * data) +faction *read_faction(struct gamedata * data) { ally **sfp; int planes, n; @@ -1346,9 +1235,10 @@ faction *readfaction(struct gamedata * data) f->no = n; } else { - f->allies = NULL; /* mem leak */ - while (f->attribs) + f->allies = NULL; /* FIXME: mem leak */ + while (f->attribs) { a_remove(&f->attribs, f->attribs); + } } READ_INT(data->store, &f->subscription); @@ -1366,7 +1256,7 @@ faction *readfaction(struct gamedata * data) assert(!al->members || !"non-allied dummy-alliance has more than one member"); } - ql_push(&al->members, f); + selist_push(&al->members, f); } else if (rule_region_owners()) { /* compat fix for non-allied factions */ @@ -1382,11 +1272,17 @@ faction *readfaction(struct gamedata * data) } READ_STR(data->store, name, sizeof(name)); - f->name = _strdup(name); + if (unicode_utf8_trim(name)!=0) { + log_warning("trim faction %s name to '%s'", itoa36(f->no), name); + }; + f->name = strdup(name); READ_STR(data->store, name, sizeof(name)); - f->banner = _strdup(name); + if (unicode_utf8_trim(name)!=0) { + log_warning("trim faction %s banner to '%s'", itoa36(f->no), name); + }; + f->banner = strdup(name); - log_debug(" - Lese Partei %s (%s)", f->name, factionid(f)); + log_debug(" - Lese Partei %s (%s)", f->name, itoa36(f->no)); READ_STR(data->store, name, sizeof(name)); if (set_email(&f->email, name) != 0) { @@ -1476,7 +1372,7 @@ faction *readfaction(struct gamedata * data) return f; } -void writefaction(struct gamedata *data, const faction * f) +void write_faction(struct gamedata *data, const faction * f) { ally *sf; ursprung *ur; @@ -1555,7 +1451,7 @@ static int cb_sb_maxlevel(spellbook_entry *sbe, void *cbdata) { return 0; } -int readgame(const char *filename, bool backup) +int readgame(const char *filename) { int n; char path[MAX_PATH]; @@ -1565,14 +1461,9 @@ int readgame(const char *filename, bool backup) FILE *F; size_t sz; - init_locales(); log_debug("- reading game data from %s", filename); join_path(datapath(), filename, path, sizeof(path)); - if (backup) { - create_backup(path); - } - F = fopen(path, "rb"); if (!F) { perror(path); @@ -1602,30 +1493,142 @@ int readgame(const char *filename, bool backup) return n; } -int read_game(gamedata *data) { +void write_building(gamedata *data, const building *b) +{ + storage *store = data->store; + + write_building_reference(b, store); + WRITE_STR(store, b->name); + WRITE_STR(store, b->display ? b->display : ""); + WRITE_INT(store, b->size); + WRITE_TOK(store, b->type->_name); + write_attribs(store, b->attribs, b); +} + +struct building *read_building(gamedata *data) { char name[DISPLAYSIZE]; - int n, p, nread; + building *b; + storage * store = data->store; + + b = (building *)calloc(1, sizeof(building)); + READ_INT(store, &b->no); + bhash(b); + READ_STR(store, name, sizeof(name)); + if (unicode_utf8_trim(name)!=0) { + log_warning("trim building %s name to '%s'", itoa36(b->no), name); + } + b->name = strdup(name); + if (lomem) { + READ_STR(store, NULL, 0); + } + else { + READ_STR(store, name, sizeof(name)); + if (unicode_utf8_trim(name)!=0) { + log_warning("trim building %s info to '%s'", itoa36(b->no), name); + } + b->display = strdup(name); + } + READ_INT(store, &b->size); + READ_STR(store, name, sizeof(name)); + b->type = bt_find(name); + if (!b->type) { + log_error("building %d has unknown type %s", b->no, name); + b->type = bt_find("building"); + assert(b->type); + } + read_attribs(data, &b->attribs, b); + + /* repairs, bug 2221: */ + if (b->type->maxsize>0 && b->size>b->type->maxsize) { + log_error("building too big: %s (%s size %d of %d), fixing.", buildingname(b), b->type->_name, b->size, b->type->maxsize); + b->size = b->type->maxsize; + } + return b; +} + +void write_ship(gamedata *data, const ship *sh) +{ + storage *store = data->store; + write_ship_reference(sh, store); + WRITE_STR(store, (const char *)sh->name); + WRITE_STR(store, sh->display ? (const char *)sh->display : ""); + WRITE_TOK(store, sh->type->_name); + WRITE_INT(store, sh->size); + WRITE_INT(store, sh->damage); + WRITE_INT(store, sh->flags & SFL_SAVEMASK); + assert((sh->type->flags & SFL_NOCOAST) == 0 || sh->coast == NODIRECTION); + WRITE_INT(store, sh->coast); + write_attribs(store, sh->attribs, sh); +} + +ship *read_ship(struct gamedata *data) +{ + char name[DISPLAYSIZE]; + ship *sh; + int n; + storage *store = data->store; + + sh = (ship *)calloc(1, sizeof(ship)); + READ_INT(store, &sh->no); + shash(sh); + READ_STR(store, name, sizeof(name)); + if (unicode_utf8_trim(name)!=0) { + log_warning("trim ship %s name to '%s'", itoa36(sh->no), name); + } + sh->name = strdup(name); + if (lomem) { + READ_STR(store, NULL, 0); + } + else { + READ_STR(store, name, sizeof(name)); + if (unicode_utf8_trim(name)!=0) { + log_warning("trim ship %s info to '%s'", itoa36(sh->no), name); + } + sh->display = strdup(name); + } + READ_STR(store, name, sizeof(name)); + sh->type = st_find(name); + if (sh->type == NULL) { + /* old datafiles */ + sh->type = st_find((const char *)LOC(default_locale, name)); + } + assert(sh->type || !"ship_type not registered!"); + + READ_INT(store, &sh->size); + READ_INT(store, &sh->damage); + if (data->version >= FOSS_VERSION) { + READ_INT(store, &sh->flags); + } + + /* Attribute rekursiv einlesen */ + + READ_INT(store, &n); + sh->coast = (direction_t)n; + if (sh->type->flags & SFL_NOCOAST) { + sh->coast = NODIRECTION; + } + read_attribs(data, &sh->attribs, sh); + return sh; +} + + +int read_game(gamedata *data) { + int p, nread; faction *f, **fp; region *r; - building *b, **bp; + building **bp; ship **shp; unit *u; int rmax = maxregions; - const struct building_type *bt_lighthouse = bt_find("lighthouse"); storage * store = data->store; + const struct building_type *bt_lighthouse = bt_find("lighthouse"); + if (data->version >= SAVEGAMEID_VERSION) { int gameid; READ_INT(store, &gameid); if (gameid != game_id()) { - int c; log_warning("game mismatch: datafile contains game %d, but config is for %d", gameid, game_id()); - printf("WARNING: invalid game id. any key to continue, Ctrl-C to stop\n"); - c = getchar(); - if (c == EOF) { - log_error("aborting."); - abort(); - } } } else { @@ -1644,11 +1647,12 @@ int read_game(gamedata *data) { READ_INT(store, &nread); log_debug(" - Einzulesende Parteien: %d\n", nread); fp = &factions; - while (*fp) + while (*fp) { fp = &(*fp)->next; + } while (--nread >= 0) { - faction *f = readfaction(data); + faction *f = read_faction(data); *fp = f; fp = &f->next; @@ -1664,53 +1668,23 @@ int read_game(gamedata *data) { rmax = nread; } log_debug(" - Einzulesende Regionen: %d/%d\r", rmax, nread); + while (--nread >= 0) { unit **up; - int x, y; - READ_INT(store, &x); - READ_INT(store, &y); - if ((nread & 0x3FF) == 0) { /* das spart extrem Zeit */ - log_debug(" - Einzulesende Regionen: %d/%d * %d,%d \r", rmax, nread, x, y); - } - --rmax; - - r = readregion(data, x, y); + r = read_region(data); /* Burgen */ READ_INT(store, &p); bp = &r->buildings; while (--p >= 0) { - - b = (building *)calloc(1, sizeof(building)); - READ_INT(store, &b->no); - *bp = b; - bp = &b->next; - bhash(b); - READ_STR(store, name, sizeof(name)); - b->name = _strdup(name); - if (lomem) { - READ_STR(store, NULL, 0); - } - else { - READ_STR(store, name, sizeof(name)); - b->display = _strdup(name); - } - READ_INT(store, &b->size); - READ_STR(store, name, sizeof(name)); - b->type = bt_find(name); - b->region = r; - read_attribs(data, &b->attribs, b); + building *b = *bp = read_building(data); if (b->type == bt_lighthouse) { r->flags |= RF_LIGHTHOUSE; } - - // repairs, bug 2221: - if (b->type->maxsize>0 && b->size>b->type->maxsize) { - log_error("building too big: %s (%s size %d of %d), fixing.", buildingname(b), b->type->_name, b->size, b->type->maxsize); - b->size = b->type->maxsize; - } + b->region = r; + bp = &b->next; } /* Schiffe */ @@ -1718,43 +1692,9 @@ int read_game(gamedata *data) { shp = &r->ships; while (--p >= 0) { - ship *sh = (ship *)calloc(1, sizeof(ship)); + ship *sh = *shp = read_ship(data); sh->region = r; - READ_INT(store, &sh->no); - *shp = sh; shp = &sh->next; - shash(sh); - READ_STR(store, name, sizeof(name)); - sh->name = _strdup(name); - if (lomem) { - READ_STR(store, NULL, 0); - } - else { - READ_STR(store, name, sizeof(name)); - sh->display = _strdup(name); - } - READ_STR(store, name, sizeof(name)); - sh->type = st_find(name); - if (sh->type == NULL) { - /* old datafiles */ - sh->type = st_find((const char *)LOC(default_locale, name)); - } - assert(sh->type || !"ship_type not registered!"); - - READ_INT(store, &sh->size); - READ_INT(store, &sh->damage); - if (data->version >= FOSS_VERSION) { - READ_INT(store, &sh->flags); - } - - /* Attribute rekursiv einlesen */ - - READ_INT(store, &n); - sh->coast = (direction_t)n; - if (sh->type->flags & SFL_NOCOAST) { - sh->coast = NODIRECTION; - } - read_attribs(data, &sh->attribs, sh); } *shp = 0; @@ -1779,8 +1719,13 @@ int read_game(gamedata *data) { *up = u; up = &u->next; - update_interval(u->faction, u->region); + update_interval(u->faction, r); } + + if ((nread & 0x3FF) == 0) { /* das spart extrem Zeit */ + log_debug(" - Einzulesende Regionen: %d/%d * %d,%d \r", rmax, nread, r->x, r->y); + } + --rmax; } read_borders(data); @@ -1872,7 +1817,7 @@ int writegame(const char *filename) join_path(datapath(), filename, path, sizeof(path)); #ifdef HAVE_UNISTD_H /* make sure we don't overwrite an existing file (hard links) */ - if (unlink(path)!=0) { + if (remove(path)!=0) { if (errno==ENOENT) { errno = 0; } @@ -1930,7 +1875,7 @@ int write_game(gamedata *data) { if (fval(f, FFL_NPC)) { clear_npc_orders(f); } - writefaction(data, f); + write_faction(data, f); WRITE_SECTION(store); } @@ -1950,44 +1895,26 @@ int write_game(gamedata *data) { log_debug(" - Schreibe Regionen: %d", n); } WRITE_SECTION(store); - WRITE_INT(store, r->x); - WRITE_INT(store, r->y); - writeregion(data, r); + write_region(data, r); WRITE_INT(store, listlen(r->buildings)); WRITE_SECTION(store); for (b = r->buildings; b; b = b->next) { - write_building_reference(b, store); - WRITE_STR(store, b->name); - WRITE_STR(store, b->display ? b->display : ""); - WRITE_INT(store, b->size); - WRITE_TOK(store, b->type->_name); - WRITE_SECTION(store); - write_attribs(store, b->attribs, b); - WRITE_SECTION(store); + assert(b->region == r); + write_building(data, b); } WRITE_INT(store, listlen(r->ships)); WRITE_SECTION(store); for (sh = r->ships; sh; sh = sh->next) { assert(sh->region == r); - write_ship_reference(sh, store); - WRITE_STR(store, (const char *)sh->name); - WRITE_STR(store, sh->display ? (const char *)sh->display : ""); - WRITE_TOK(store, sh->type->_name); - WRITE_INT(store, sh->size); - WRITE_INT(store, sh->damage); - WRITE_INT(store, sh->flags & SFL_SAVEMASK); - assert((sh->type->flags & SFL_NOCOAST) == 0 || sh->coast == NODIRECTION); - WRITE_INT(store, sh->coast); - WRITE_SECTION(store); - write_attribs(store, sh->attribs, sh); - WRITE_SECTION(store); + write_ship(data, sh); } WRITE_INT(store, listlen(r->units)); WRITE_SECTION(store); for (u = r->units; u; u = u->next) { + assert(u->region == r); write_unit(data, u); } } @@ -1997,92 +1924,3 @@ int write_game(gamedata *data) { return 0; } - -int a_readint(attrib * a, void *owner, struct gamedata *data) -{ - /* assert(sizeof(int)==sizeof(a->data)); */ - READ_INT(data->store, &a->data.i); - return AT_READ_OK; -} - -void a_writeint(const attrib * a, const void *owner, struct storage *store) -{ - WRITE_INT(store, a->data.i); -} - -int a_readshorts(attrib * a, void *owner, struct gamedata *data) -{ - int n; - READ_INT(data->store, &n); - a->data.sa[0] = (short)n; - READ_INT(data->store, &n); - a->data.sa[1] = (short)n; - return AT_READ_OK; -} - -void a_writeshorts(const attrib * a, const void *owner, struct storage *store) -{ - WRITE_INT(store, a->data.sa[0]); - WRITE_INT(store, a->data.sa[1]); -} - -int a_readchars(attrib * a, void *owner, struct gamedata *data) -{ - int i; - for (i = 0; i != 4; ++i) { - int n; - READ_INT(data->store, &n); - a->data.ca[i] = (char)n; - } - return AT_READ_OK; -} - -void a_writechars(const attrib * a, const void *owner, struct storage *store) -{ - int i; - - for (i = 0; i != 4; ++i) { - WRITE_INT(store, a->data.ca[i]); - } -} - -int a_readvoid(attrib * a, void *owner, struct gamedata *data) -{ - return AT_READ_OK; -} - -void a_writevoid(const attrib * a, const void *owner, struct storage *store) -{ -} - -int a_readstring(attrib * a, void *owner, struct gamedata *data) -{ - char buf[DISPLAYSIZE]; - char * result = 0; - int e; - size_t len = 0; - do { - e = READ_STR(data->store, buf, sizeof(buf)); - if (result) { - result = realloc(result, len + DISPLAYSIZE - 1); - strcpy(result + len, buf); - len += DISPLAYSIZE - 1; - } - else { - result = _strdup(buf); - } - } while (e == ENOMEM); - a->data.v = result; - return AT_READ_OK; -} - -void a_writestring(const attrib * a, const void *owner, struct storage *store) -{ - assert(a->data.v); - WRITE_STR(store, (const char *)a->data.v); -} - -void a_finalizestring(attrib * a) -{ - free(a->data.v); -} diff --git a/src/kernel/save.h b/src/kernel/save.h index 3cd443926..763ff66b6 100644 --- a/src/kernel/save.h +++ b/src/kernel/save.h @@ -30,52 +30,39 @@ extern "C" { struct spell; struct spellbook; struct unit; + struct building; + struct faction; + struct region; + struct ship; struct gamedata; #define MAX_INPUT_SIZE DISPLAYSIZE*2 /* Nach MAX_INPUT_SIZE brechen wir das Einlesen der Zeile ab und nehmen an, * dass hier ein Fehler (fehlende ") vorliegt */ - extern int data_version; + /* TODO: is this *really* still in use? */ extern int enc_gamedata; int readorders(const char *filename); - int creategame(void); - int readgame(const char *filename, bool backup); + int readgame(const char *filename); int writegame(const char *filename); int current_turn(void); - void read_items(struct storage *store, struct item **it); - void write_items(struct storage *store, struct item *it); - - void read_spellbook(struct spellbook **bookp, struct gamedata *data, int(*get_level)(const struct spell * sp, void *), void * cbdata); - void write_spellbook(const struct spellbook *book, struct storage *store); - - void write_attribs(struct storage *store, struct attrib *alist, const void *owner); - int read_attribs(struct gamedata *store, struct attrib **alist, void *owner); - void write_unit(struct gamedata *data, const struct unit *u); struct unit *read_unit(struct gamedata *data); + + void write_faction(struct gamedata *data, const struct faction *f); + struct faction *read_faction(struct gamedata *data); - int a_readint(struct attrib *a, void *owner, struct gamedata *); - void a_writeint(const struct attrib *a, const void *owner, - struct storage *store); - int a_readshorts(struct attrib *a, void *owner, struct gamedata *); - void a_writeshorts(const struct attrib *a, const void *owner, - struct storage *store); - int a_readchars(struct attrib *a, void *owner, struct gamedata *); - void a_writechars(const struct attrib *a, const void *owner, - struct storage *store); - int a_readvoid(struct attrib *a, void *owner, struct gamedata *); - void a_writevoid(const struct attrib *a, const void *owner, - struct storage *); - int a_readstring(struct attrib *a, void *owner, struct gamedata *); - void a_writestring(const struct attrib *a, const void *owner, - struct storage *); - void a_finalizestring(struct attrib *a); + void write_region(struct gamedata *data, const struct region *r); + struct region *read_region(struct gamedata *data); - void create_backup(char *file); + void write_building(struct gamedata *data, const struct building *b); + struct building *read_building(struct gamedata *data); + + void write_ship(struct gamedata *data, const struct ship *sh); + struct ship *read_ship(struct gamedata *data); int write_game(struct gamedata *data); int read_game(struct gamedata *data); diff --git a/src/kernel/save.test.c b/src/kernel/save.test.c index 00b5ff96c..9501df896 100644 --- a/src/kernel/save.test.c +++ b/src/kernel/save.test.c @@ -6,6 +6,8 @@ #include "save.h" #include "version.h" +#include "building.h" +#include "ship.h" #include "unit.h" #include "group.h" #include "ally.h" @@ -27,6 +29,7 @@ #include #include +#include #include static void test_readwrite_data(CuTest * tc) @@ -35,7 +38,7 @@ static void test_readwrite_data(CuTest * tc) char path[MAX_PATH]; test_setup(); CuAssertIntEquals(tc, 0, writegame(filename)); - CuAssertIntEquals(tc, 0, readgame(filename, false)); + CuAssertIntEquals(tc, 0, readgame(filename)); join_path(datapath(), filename, path, sizeof(path)); CuAssertIntEquals(tc, 0, remove(path)); test_cleanup(); @@ -55,7 +58,8 @@ static void test_readwrite_unit(CuTest * tc) f = test_create_faction(0); fno = f->no; u = test_create_unit(f, r); - + unit_setname(u, " Hodor "); + CuAssertStrEquals(tc, " Hodor ", u->_name); mstream_init(&data.strm); gamedata_init(&data, &store, RELEASE_VERSION); write_unit(&data, u); @@ -69,11 +73,135 @@ static void test_readwrite_unit(CuTest * tc) u = read_unit(&data); CuAssertPtrNotNull(tc, u); CuAssertPtrEquals(tc, f, u->faction); + CuAssertStrEquals(tc, "Hodor", u->_name); CuAssertPtrEquals(tc, 0, u->region); mstream_done(&data.strm); gamedata_done(&data); - move_unit(u, r, NULL); // this makes sure that u doesn't leak + move_unit(u, r, NULL); /* this makes sure that u doesn't leak */ + test_cleanup(); +} + +static void test_readwrite_faction(CuTest * tc) +{ + gamedata data; + storage store; + faction *f; + + test_setup(); + f = test_create_faction(0); + free(f->name); + f->name = strdup(" Hodor "); + CuAssertStrEquals(tc, " Hodor ", f->name); + mstream_init(&data.strm); + gamedata_init(&data, &store, RELEASE_VERSION); + write_faction(&data, f); + + data.strm.api->rewind(data.strm.handle); + free_gamedata(); + gamedata_init(&data, &store, RELEASE_VERSION); + f = read_faction(&data); + CuAssertPtrNotNull(tc, f); + CuAssertStrEquals(tc, "Hodor", f->name); + CuAssertPtrEquals(tc, 0, f->units); + factions = f; + + mstream_done(&data.strm); + gamedata_done(&data); + test_cleanup(); +} + +static void test_readwrite_region(CuTest * tc) +{ + gamedata data; + storage store; + region *r; + + test_setup(); + r = test_create_region(0, 0, 0); + free(r->land->name); + r->land->name = strdup(" Hodor "); + CuAssertStrEquals(tc, " Hodor ", r->land->name); + mstream_init(&data.strm); + gamedata_init(&data, &store, RELEASE_VERSION); + write_region(&data, r); + + data.strm.api->rewind(data.strm.handle); + free_gamedata(); + gamedata_init(&data, &store, RELEASE_VERSION); + r = read_region(&data); + CuAssertPtrNotNull(tc, r); + CuAssertStrEquals(tc, "Hodor", r->land->name); + regions = r; + + mstream_done(&data.strm); + gamedata_done(&data); + test_cleanup(); +} + +static void test_readwrite_building(CuTest * tc) +{ + gamedata data; + storage store; + building *b; + region *r; + + test_setup(); + r = test_create_region(0, 0, 0); + b = test_create_building(r, 0); + free(b->name); + b->name = strdup(" Hodor "); + CuAssertStrEquals(tc, " Hodor ", b->name); + mstream_init(&data.strm); + gamedata_init(&data, &store, RELEASE_VERSION); + write_building(&data, b); + + data.strm.api->rewind(data.strm.handle); + free_gamedata(); + r = test_create_region(0, 0, 0); + gamedata_init(&data, &store, RELEASE_VERSION); + b = read_building(&data); + CuAssertPtrNotNull(tc, b); + CuAssertStrEquals(tc, "Hodor", b->name); + CuAssertPtrEquals(tc, 0, b->region); + b->region = r; + r->buildings = b; + + mstream_done(&data.strm); + gamedata_done(&data); + test_cleanup(); +} + +static void test_readwrite_ship(CuTest * tc) +{ + gamedata data; + storage store; + ship *sh; + region *r; + + test_setup(); + r = test_create_region(0, 0, 0); + sh = test_create_ship(r, 0); + free(sh->name); + sh->name = strdup(" Hodor "); + CuAssertStrEquals(tc, " Hodor ", sh->name); + mstream_init(&data.strm); + gamedata_init(&data, &store, RELEASE_VERSION); + write_ship(&data, sh); + + data.strm.api->rewind(data.strm.handle); + free_gamedata(); + r = test_create_region(0, 0, 0); + gamedata_init(&data, &store, RELEASE_VERSION); + sh = read_ship(&data); + CuAssertPtrNotNull(tc, sh); + CuAssertStrEquals(tc, "Hodor", sh->name); + CuAssertPtrEquals(tc, 0, sh->region); + sh->region = r; + r->ships = sh; + + mstream_done(&data.strm); + gamedata_done(&data); test_cleanup(); } @@ -83,8 +211,8 @@ static void test_readwrite_attrib(CuTest *tc) { attrib *a = NULL; test_setup(); - key_set(&a, 41); - key_set(&a, 42); + key_set(&a, 41, 42); + key_set(&a, 42, 43); mstream_init(&data.strm); gamedata_init(&data, &store, RELEASE_VERSION); write_attribs(data.store, a, NULL); @@ -95,8 +223,8 @@ static void test_readwrite_attrib(CuTest *tc) { read_attribs(&data, &a, NULL); mstream_done(&data.strm); gamedata_done(&data); - CuAssertTrue(tc, key_get(a, 41)); - CuAssertTrue(tc, key_get(a, 42)); + CuAssertIntEquals(tc, 42, key_get(a, 41)); + CuAssertIntEquals(tc, 43, key_get(a, 42)); a_removeall(&a, NULL); test_cleanup(); @@ -326,6 +454,10 @@ CuSuite *get_save_suite(void) SUITE_ADD_TEST(suite, test_readwrite_attrib); SUITE_ADD_TEST(suite, test_readwrite_data); SUITE_ADD_TEST(suite, test_readwrite_unit); + SUITE_ADD_TEST(suite, test_readwrite_faction); + SUITE_ADD_TEST(suite, test_readwrite_region); + SUITE_ADD_TEST(suite, test_readwrite_building); + SUITE_ADD_TEST(suite, test_readwrite_ship); SUITE_ADD_TEST(suite, test_readwrite_dead_faction_createunit); SUITE_ADD_TEST(suite, test_readwrite_dead_faction_changefaction); SUITE_ADD_TEST(suite, test_readwrite_dead_faction_regionowner); diff --git a/src/kernel/ship.c b/src/kernel/ship.c index 02a980b68..b9ac0b170 100644 --- a/src/kernel/ship.c +++ b/src/kernel/ship.c @@ -38,7 +38,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include +#include #include #include @@ -51,7 +51,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include -quicklist *shiptypes = NULL; +selist *shiptypes = NULL; static local_names *snames; @@ -66,15 +66,15 @@ const ship_type *findshiptype(const char *name, const struct locale *lang) sn = sn->next; } if (!sn) { - quicklist *ql; + selist *ql; int qi; sn = (local_names *)calloc(sizeof(local_names), 1); sn->next = snames; sn->lang = lang; - for (qi = 0, ql = shiptypes; ql; ql_advance(&ql, &qi, 1)) { - ship_type *stype = (ship_type *)ql_get(ql, qi); + for (qi = 0, ql = shiptypes; ql; selist_advance(&ql, &qi, 1)) { + ship_type *stype = (ship_type *)selist_get(ql, qi); variant var2; const char *n = LOC(lang, stype->_name); var2.v = (void *)stype; @@ -89,11 +89,11 @@ const ship_type *findshiptype(const char *name, const struct locale *lang) static ship_type *st_find_i(const char *name) { - quicklist *ql; + selist *ql; int qi; - for (qi = 0, ql = shiptypes; ql; ql_advance(&ql, &qi, 1)) { - ship_type *stype = (ship_type *)ql_get(ql, qi); + for (qi = 0, ql = shiptypes; ql; selist_advance(&ql, &qi, 1)) { + ship_type *stype = (ship_type *)selist_get(ql, qi); if (strcmp(stype->_name, name) == 0) { return stype; } @@ -109,9 +109,9 @@ ship_type *st_get_or_create(const char * name) { ship_type * st = st_find_i(name); if (!st) { st = (ship_type *)calloc(sizeof(ship_type), 1); - st->_name = _strdup(name); + st->_name = strdup(name); st->storm = 1.0; - ql_push(&shiptypes, (void *)st); + selist_push(&shiptypes, (void *)st); } return st; } @@ -201,8 +201,8 @@ ship *new_ship(const ship_type * stype, region * r, const struct locale *lang) sname = parameters[P_SHIP]; } assert(sname); - slprintf(buffer, sizeof(buffer), "%s %s", sname, shipid(sh)); - sh->name = _strdup(buffer); + slprintf(buffer, sizeof(buffer), "%s %s", sname, itoa36(sh->no)); + sh->name = strdup(buffer); shash(sh); if (r) { addlist(&r->ships, sh); @@ -250,8 +250,8 @@ static void free_shiptype(void *ptr) { } void free_shiptypes(void) { - ql_foreach(shiptypes, free_shiptype); - ql_free(shiptypes); + selist_foreach(shiptypes, free_shiptype); + selist_free(shiptypes); shiptypes = 0; } @@ -297,10 +297,9 @@ int crew_skill(const ship *sh) { int shipspeed(const ship * sh, const unit * u) { - int k = sh->type->range; attrib *a; struct curse *c; - int bonus; + int k, bonus; assert(sh); if (!u) u = ship_owner(sh); @@ -310,6 +309,7 @@ int shipspeed(const ship * sh, const unit * u) assert(sh->type->construction); assert(sh->type->construction->improvement == NULL); /* sonst ist construction::size nicht ship_type::maxsize */ + k = sh->type->range; if (sh->size != sh->type->construction->maxsize) return 0; @@ -333,8 +333,8 @@ int shipspeed(const ship * sh, const unit * u) int crew = crew_skill(sh); int crew_bonus = (crew / sh->type->sumskill / 2) - 1; if (crew_bonus > 0) { - bonus = _min(bonus, crew_bonus); - bonus = _min(bonus, sh->type->range_max - sh->type->range); + bonus = MIN(bonus, crew_bonus); + bonus = MIN(bonus, sh->type->range_max - sh->type->range); } else { bonus = 0; @@ -417,7 +417,7 @@ static unit * ship_owner_ex(const ship * sh, const struct faction * last_owner) { unit *u, *heir = 0; - /* Eigentmer tot oder kein Eigentmer vorhanden. Erste lebende Einheit + /* Eigent�mer tot oder kein Eigent�mer vorhanden. Erste lebende Einheit * nehmen. */ for (u = sh->region->units; u; u = u->next) { if (u->ship == sh) { @@ -458,7 +458,7 @@ void write_ship_reference(const struct ship *sh, struct storage *store) void ship_setname(ship * self, const char *name) { free(self->name); - self->name = name ? _strdup(name) : 0; + self->name = name ? strdup(name) : 0; } const char *ship_getname(const ship * self) diff --git a/src/kernel/ship.h b/src/kernel/ship.h index 73b8a9718..285c29cc0 100644 --- a/src/kernel/ship.h +++ b/src/kernel/ship.h @@ -18,13 +18,16 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef H_KRNL_SHIP #define H_KRNL_SHIP -#ifdef __cplusplus -extern "C" { -#endif #include "types.h" #include "direction.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + #define DAMAGE_SCALE 100 /* multiplier for sh->damage */ /* ship_type::flags */ @@ -51,8 +54,8 @@ extern "C" { int minskill; /* min. skill to sail this (crew) */ int sumskill; /* min. sum of crew+captain */ - int at_bonus; /* Verndert den Angriffsskill (default: 0) */ - int df_bonus; /* Verndert den Verteidigungskill (default: 0) */ + int at_bonus; /* Ver�ndert den Angriffsskill (default: 0) */ + int df_bonus; /* Ver�ndert den Verteidigungskill (default: 0) */ float tac_bonus; struct terrain_type ** coasts; /* coast that this ship can land on */ @@ -60,7 +63,7 @@ extern "C" { struct construction *construction; /* how to build a ship */ } ship_type; - extern struct quicklist *shiptypes; + extern struct selist *shiptypes; /* Alte Schiffstypen: */ @@ -70,12 +73,12 @@ extern "C" { #define NOSHIP NULL -#define SF_DRIFTED 1<<0 -#define SF_MOVED 1<<1 -#define SF_DAMAGED 1<<2 /* for use in combat */ -#define SF_SELECT 1<<3 /* previously FL_DH */ -#define SF_FISHING 1<<4 /* was on an ocean, can fish */ -#define SF_FLYING 1<<5 /* the ship can fly */ +#define SF_DRIFTED (1<<0) +#define SF_MOVED (1<<1) +#define SF_DAMAGED (1<<2) /* for use in combat */ +#define SF_SELECT (1<<3) /* previously FL_DH */ +#define SF_FISHING (1<<4) /* was on an ocean, can fish */ +#define SF_FLYING (1<<5) /* the ship can fly */ #define SFL_SAVEMASK (SF_FLYING) #define INCOME_FISHING 10 diff --git a/src/kernel/skills.c b/src/kernel/skills.c index 9a6c0f1d7..488800115 100644 --- a/src/kernel/skills.c +++ b/src/kernel/skills.c @@ -21,7 +21,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "skill.h" #include "curse.h" -#include "item.h" #include "race.h" #include "region.h" #include "terrain.h" @@ -184,9 +183,13 @@ void sk_set(skill * sv, int level) sv->level = level; } -static int rule_random_progress(void) +static bool rule_random_progress(void) { - return config_get_int("study.random_progress", 1); + static int rule, config; + if (config_changed(&config)) { + rule = config_get_int("study.random_progress", 1); + } + return rule != 0; } int skill_weeks(int level) diff --git a/src/kernel/spell.c b/src/kernel/spell.c index 8e14ec2c0..212b0a7d2 100644 --- a/src/kernel/spell.c +++ b/src/kernel/spell.c @@ -26,7 +26,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include +#include /* libc includes */ #include @@ -34,7 +34,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include static critbit_tree cb_spells; -quicklist * spells; +selist * spells; static void free_spell(spell *sp) { free(sp->syntax); @@ -50,14 +50,14 @@ static void free_spell_cb(void *cbdata) { void free_spells(void) { cb_clear(&cb_spells); - ql_foreach(spells, free_spell_cb); - ql_free(spells); + selist_foreach(spells, free_spell_cb); + selist_free(spells); spells = 0; } -void add_spell(struct quicklist **slistp, spell * sp) +void add_spell(struct selist **slistp, spell * sp) { - if (!ql_set_insert(slistp, sp)) { + if (!selist_set_insert(slistp, sp, NULL)) { log_error("add_spell: the list already contains the spell '%s'.\n", sp->sname); } } @@ -78,7 +78,7 @@ spell * create_spell(const char * name, unsigned int id) len = cb_new_kv(name, len, &sp, sizeof(sp), buffer); if (cb_insert(&cb_spells, buffer, len) == CB_SUCCESS) { sp->id = id ? id : hashstring(name); - sp->sname = _strdup(name); + sp->sname = strdup(name); add_spell(&spells, sp); return sp; } @@ -123,19 +123,19 @@ spell *find_spell(const char *name) spell *find_spellbyid(unsigned int id) { - quicklist *ql; + selist *ql; int qi; if (id == 0) return NULL; - for (qi = 0, ql = spells; ql; ql_advance(&ql, &qi, 1)) { - spell *sp = (spell *)ql_get(ql, qi); + for (qi = 0, ql = spells; ql; selist_advance(&ql, &qi, 1)) { + spell *sp = (spell *)selist_get(ql, qi); if (sp->id == id) { return sp; } } - for (qi = 0, ql = spells; ql; ql_advance(&ql, &qi, 1)) { - spell *sp = (spell *)ql_get(ql, qi); + for (qi = 0, ql = spells; ql; selist_advance(&ql, &qi, 1)) { + spell *sp = (spell *)selist_get(ql, qi); unsigned int hashid = hashstring(sp->sname); if (hashid == id) { return sp; @@ -145,3 +145,39 @@ spell *find_spellbyid(unsigned int id) log_warning("cannot find spell by id: %u\n", id); return NULL; } + +struct spellref *spellref_create(spell *sp, const char *name) +{ + spellref *spref = malloc(sizeof(spellref)); + + if (sp) { + spref->sp = sp; + spref->name = strdup(sp->sname); + } + else if (name) { + spref->name = strdup(name); + spref->sp = NULL; + } + return spref; +} + +void spellref_free(spellref *spref) +{ + if (spref) { + free(spref->name); + free(spref); + } +} + +struct spell *spellref_get(struct spellref *spref) +{ + if (!spref->sp) { + assert(spref->name); + spref->sp = find_spell(spref->name); + if (spref->sp) { + free(spref->name); + spref->name = NULL; + } + } + return spref->sp; +} diff --git a/src/kernel/spell.h b/src/kernel/spell.h index b447f51d4..e7592f082 100644 --- a/src/kernel/spell.h +++ b/src/kernel/spell.h @@ -27,7 +27,7 @@ extern "C" { struct region; struct spell; struct spell_component; - struct quicklist; + struct selist; struct attrib_type; typedef int(*spell_f)(struct castorder * co); @@ -45,23 +45,32 @@ extern "C" { fumble_f fumble; } spell; + typedef struct spellref { + char * name; + struct spell *sp; + } spellref; + + struct spellref *spellref_create(struct spell *sp, const char *name); + void spellref_free(struct spellref *spref); + struct spell *spellref_get(struct spellref *spref); + int sp_antimagiczone(struct castorder *co); struct spell * create_spell(const char * name, unsigned int id); struct spell * find_spell(const char *name); struct spell * find_spellbyid(unsigned int i); - void add_spell(struct quicklist **slistp, spell * sp); + void add_spell(struct selist **slistp, spell * sp); void free_spells(void); /** globals **/ extern struct attrib_type at_unitdissolve; extern struct attrib_type at_wdwpyramid; - extern struct quicklist * spells; + extern struct selist * spells; #ifdef __cplusplus } #endif #endif -/* ------------------------------------------------------------- *//* Erluterungen zu den Spruchdefinitionen +/* ------------------------------------------------------------- *//* Erl�uterungen zu den Spruchdefinitionen * * Spruchstukturdefinition: * spell{ @@ -79,35 +88,35 @@ extern "C" { * id: * SPL_NOSPELL muss der letzte Spruch in der Liste spelldaten sein, * denn nicht auf die Reihenfolge in der Liste sondern auf die id wird - * geprft + * gepr�ft * * sptyp: * besondere Spruchtypen und Flags * (Regionszauber, Kampfzauber, Farcastbar, Stufe variable, ..) * * rank: - * gibt die Prioritt und damit die Reihenfolge an, in der der Spruch + * gibt die Priorit�t und damit die Reihenfolge an, in der der Spruch * gezaubert wird. - * 1: Aura bertragen + * 1: Aura �bertragen * 2: Antimagie - * 3: Magierverndernde Sprche (Magic Boost, ..) + * 3: Magierver�ndernde Spr�che (Magic Boost, ..) * 4: Monster erschaffen * 5: Standartlevel * 7: Teleport * - * Komponenten[Anzahl mgl. Items][Art:Anzahl:Kostentyp] + * Komponenten[Anzahl m�gl. Items][Art:Anzahl:Kostentyp] * * R_AURA: - * Grundkosten fr einen Zauber. Soviel Mp mssen mindestens investiert - * werden, um den Spruch zu wirken. Zustzliche Mp knnen unterschiedliche + * Grundkosten f�r einen Zauber. Soviel Mp m�ssen mindestens investiert + * werden, um den Spruch zu wirken. Zus�tzliche Mp k�nnen unterschiedliche * Auswirkungen haben, die in der Spruchfunktionsroutine definiert werden. * * R_PERMAURA: * Kosten an permantenter Aura * * Komponenten Kostentyp: - * SPC_LEVEL == Spruch mit Levelabhngigen Magiekosten. Die angegeben - * Kosten mssen fr Stufe 1 berechnet sein. + * SPC_LEVEL == Spruch mit Levelabh�ngigen Magiekosten. Die angegeben + * Kosten m�ssen f�r Stufe 1 berechnet sein. * SPC_FIX == Feste Kosten * * Wenn keine spezielle Syntax angegeben ist, wird die @@ -128,34 +137,34 @@ extern "C" { * * u : eine Einheitennummer * r : hier kommen zwei Regionskoordinaten x y - * b : Gebude- oder Burgnummer + * b : Geb�ude- oder Burgnummer * s : Schiffsnummer - * c : String, wird ohne Weiterverarbeitung bergeben - * i : Zahl (int), wird ohne Weiterverarbeitung bergeben + * c : String, wird ohne Weiterverarbeitung �bergeben + * i : Zahl (int), wird ohne Weiterverarbeitung �bergeben * k : Keywort - dieser String gibt den Paramter an, der folgt. Der * Parameter wird mit findparam() identifiziert. - * k muss immer von einem c als Platzhalter fr das Objekt gefolgt + * k muss immer von einem c als Platzhalter f�r das Objekt gefolgt * werden. - * Ein gutes Beispiel sind hierfr die Sprche zur Magieanalyse. + * Ein gutes Beispiel sind hierf�r die Spr�che zur Magieanalyse. * + : gibt an, das der vorherige Parameter mehrfach vorkommen kann. Da * ein Ende nicht definiert werden kann, muss dies immer am Schluss * kommen. * - * Flags fr das Parsing: + * Flags f�r das Parsing: * TESTRESISTANCE : alle Zielobjekte, also alle Parameter vom Typ Unit, * Burg, Schiff oder Region, werden auf ihre - * Magieresistenz berprft + * Magieresistenz �berpr�ft * TESTCANSEE : jedes Objekt vom Typ Einheit wird auf seine - * Sichtbarkeit berprft + * Sichtbarkeit �berpr�ft * SEARCHLOCAL : die Zielobjekte werden nur regional gesucht * REGIONSPELL : Ziel ist die Region, auch wenn kein Zielobjekt * angegeben wird. Ist TESTRESISTANCE gesetzt, so wird - * die Magieresistenz der Region berprft + * die Magieresistenz der Region �berpr�ft * * Bei fehlendem Ziel oder wenn dieses dem Zauber widersteht, wird die * Spruchfunktion nicht aufgerufen. * Sind zu wenig Parameter vorhanden, wird der Zauber ebenfalls nicht - * ausgefhrt. + * ausgef�hrt. * Ist eins von mehreren Zielobjekten resistent, so wird das Flag * pa->param[n]->flag == TARGET_RESISTS * Ist eins von mehreren Zielobjekten nicht gefunden worden, so ist diff --git a/src/kernel/spell.test.c b/src/kernel/spell.test.c index f61c0fffe..b500f94cc 100644 --- a/src/kernel/spell.test.c +++ b/src/kernel/spell.test.c @@ -6,7 +6,6 @@ #include #include -#include #include #include @@ -70,9 +69,27 @@ static void test_create_spell_with_id(CuTest * tc) test_cleanup(); } +static void test_spellref(CuTest *tc) +{ + spellref *ref; + spell *sp; + test_setup(); + ref = spellref_create(NULL, "hodor"); + CuAssertPtrNotNull(tc, ref); + CuAssertPtrEquals(tc, NULL, ref->sp); + CuAssertStrEquals(tc, "hodor", ref->name); + CuAssertPtrEquals(tc, NULL, spellref_get(ref)); + sp = create_spell("hodor", 0); + CuAssertPtrNotNull(tc, sp); + CuAssertPtrEquals(tc, sp, spellref_get(ref)); + spellref_free(ref); + test_cleanup(); +} + CuSuite *get_spell_suite(void) { CuSuite *suite = CuSuiteNew(); + SUITE_ADD_TEST(suite, test_spellref); SUITE_ADD_TEST(suite, test_create_a_spell); SUITE_ADD_TEST(suite, test_create_duplicate_spell); SUITE_ADD_TEST(suite, test_create_spell_with_id); diff --git a/src/kernel/spellbook.c b/src/kernel/spellbook.c index 96410170b..b7f65420c 100644 --- a/src/kernel/spellbook.c +++ b/src/kernel/spellbook.c @@ -1,11 +1,14 @@ #include #include #include -#include +#include #include +#include #include "spellbook.h" +#include + #include #include #include @@ -13,12 +16,62 @@ spellbook * create_spellbook(const char * name) { spellbook *result = (spellbook *)malloc(sizeof(spellbook)); - result->name = name ? _strdup(name) : 0; + result->name = name ? strdup(name) : 0; result->spells = 0; return result; } -void spellbook_add(spellbook *sb, struct spell * sp, int level) +void read_spellbook(spellbook **bookp, gamedata *data, int(*get_level)(const spell * sp, void *), void * cbdata) +{ + for (;;) { + spell *sp = 0; + char spname[64]; + int level = 0; + + READ_TOK(data->store, spname, sizeof(spname)); + if (strcmp(spname, "end") == 0) + break; + if (bookp) { + sp = find_spell(spname); + if (!sp) { + log_error("read_spells: could not find spell '%s'", spname); + } + } + if (data->version >= SPELLBOOK_VERSION) { + READ_INT(data->store, &level); + } + if (sp) { + spellbook * sb = *bookp; + if (level <= 0 && get_level) { + level = get_level(sp, cbdata); + } + if (!sb) { + *bookp = create_spellbook(0); + sb = *bookp; + } + if (level > 0 && (data->version >= SPELLBOOK_VERSION || !spellbook_get(sb, sp))) { + spellbook_add(sb, sp, level); + } + } + } +} + +void write_spellbook(const struct spellbook *book, struct storage *store) +{ + selist *ql; + int qi; + + if (book) { + for (ql = book->spells, qi = 0; ql; selist_advance(&ql, &qi, 1)) { + spellbook_entry *sbe = (spellbook_entry *)selist_get(ql, qi); + WRITE_TOK(store, sbe->sp->sname); + WRITE_INT(store, sbe->level); + } + } + WRITE_TOK(store, "end"); +} + +void spellbook_add(spellbook *sb, spell *sp, int level) { spellbook_entry * sbe; @@ -31,30 +84,30 @@ void spellbook_add(spellbook *sb, struct spell * sp, int level) sbe = (spellbook_entry *)malloc(sizeof(spellbook_entry)); sbe->sp = sp; sbe->level = level; - ql_push(&sb->spells, sbe); + selist_push(&sb->spells, sbe); } void spellbook_clear(spellbook *sb) { - quicklist *ql; + selist *ql; int qi; assert(sb); - for (qi = 0, ql = sb->spells; ql; ql_advance(&ql, &qi, 1)) { - spellbook_entry *sbe = (spellbook_entry *)ql_get(ql, qi); + for (qi = 0, ql = sb->spells; ql; selist_advance(&ql, &qi, 1)) { + spellbook_entry *sbe = (spellbook_entry *)selist_get(ql, qi); free(sbe); } - ql_free(sb->spells); + selist_free(sb->spells); free(sb->name); } int spellbook_foreach(spellbook *sb, int(*callback)(spellbook_entry *, void *), void * data) { - quicklist *ql; + selist *ql; int qi; - for (qi = 0, ql = sb->spells; ql; ql_advance(&ql, &qi, 1)) { - spellbook_entry *sbe = (spellbook_entry *)ql_get(ql, qi); + for (qi = 0, ql = sb->spells; ql; selist_advance(&ql, &qi, 1)) { + spellbook_entry *sbe = (spellbook_entry *)selist_get(ql, qi); int result = callback(sbe, data); if (result) { return result; @@ -63,19 +116,18 @@ int spellbook_foreach(spellbook *sb, int(*callback)(spellbook_entry *, void *), return 0; } -spellbook_entry * spellbook_get(spellbook *sb, const struct spell * sp) +spellbook_entry * spellbook_get(spellbook *sb, const struct spell *sp) { if (sb) { - quicklist *ql; + selist *ql; int qi; - for (qi = 0, ql = sb->spells; ql; ql_advance(&ql, &qi, 1)) { - spellbook_entry *sbe = (spellbook_entry *)ql_get(ql, qi); - if (sp == sbe->sp) { + for (qi = 0, ql = sb->spells; ql; selist_advance(&ql, &qi, 1)) { + spellbook_entry *sbe = (spellbook_entry *)selist_get(ql, qi); + if (sbe->sp==sp) { return sbe; } } } return 0; } - diff --git a/src/kernel/spellbook.h b/src/kernel/spellbook.h index d0e25da23..fb3438a8b 100644 --- a/src/kernel/spellbook.h +++ b/src/kernel/spellbook.h @@ -24,25 +24,30 @@ extern "C" { #endif struct spell; - struct quicklist; + struct storage; + struct gamedata; + struct selist; typedef struct spellbook_entry { - struct spell * sp; + struct spell *sp; int level; } spellbook_entry; typedef struct spellbook { char * name; - struct quicklist * spells; + struct selist * spells; } spellbook; spellbook * create_spellbook(const char * name); - void spellbook_add(spellbook *sbp, struct spell * sp, int level); + void read_spellbook(struct spellbook **bookp, struct gamedata *data, int(*get_level)(const struct spell * sp, void *), void * cbdata); + void write_spellbook(const struct spellbook *book, struct storage *store); + + void spellbook_add(spellbook *sbp, struct spell *sp, int level); int spellbook_foreach(spellbook *sb, int(*callback)(spellbook_entry *, void *), void * data); void spellbook_clear(spellbook *sb); - spellbook_entry * spellbook_get(spellbook *sb, const struct spell * sp); + spellbook_entry * spellbook_get(spellbook *sb, const struct spell *sp); #ifdef __cplusplus } diff --git a/src/kernel/spellbook.test.c b/src/kernel/spellbook.test.c index 2f78fd87d..8b997557b 100644 --- a/src/kernel/spellbook.test.c +++ b/src/kernel/spellbook.test.c @@ -2,7 +2,6 @@ #include #include -#include #include #include diff --git a/src/kernel/terrain.c b/src/kernel/terrain.c index ac4a49fe9..3d6f4c313 100644 --- a/src/kernel/terrain.c +++ b/src/kernel/terrain.c @@ -110,11 +110,11 @@ terrain_type * get_or_create_terrain(const char *name) { if (!terrain) { terrain = (terrain_type *)calloc(sizeof(terrain_type), 1); if (terrain) { - terrain->_name = _strdup(name); + terrain->_name = strdup(name); terrain->next = registered_terrains; registered_terrains = terrain; if (strcmp("plain", name) == 0) { - // TODO: this is awful, it belongs in config + /* TODO: this is awful, it belongs in config */ terrain->name = &plain_name; } } diff --git a/src/kernel/types.h b/src/kernel/types.h index e0521635e..b9faefce7 100644 --- a/src/kernel/types.h +++ b/src/kernel/types.h @@ -19,14 +19,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef ERESSEA_TYPES_H #define ERESSEA_TYPES_H -/* - * Features enabled: - * If you are lacking the settings.h, create a new file common/settings.h, - * and write #include (or whatever settings you want - * your game to use) in there. - * !!! DO NOT COMMIT THE SETTINGS.H FILE TO CVS !!! - * settings.h should always be the first thing you include (after platform.h). - */ #include #include @@ -51,7 +43,7 @@ struct luxury_type; struct order; struct plane; struct potion_type; -struct quicklist; +struct selist; struct race; struct region; struct region_list; @@ -144,7 +136,7 @@ typedef enum { P_TREES, P_ALLIANCE, MAXPARAMS, - NOPARAM = -1 + NOPARAM } param_t; typedef enum { /* Fehler und Meldungen im Report */ @@ -154,9 +146,7 @@ typedef enum { /* Fehler und Meldungen im Report */ MSG_INCOME, MSG_COMMERCE, MSG_PRODUCE, - MSG_ORCVERMEHRUNG, MSG_MESSAGE, - MSG_COMMENT, MSG_MAGIC, MAX_MSG } msg_t; diff --git a/src/kernel/unit.c b/src/kernel/unit.c index 4623e895e..4592d0bc7 100644 --- a/src/kernel/unit.c +++ b/src/kernel/unit.c @@ -34,7 +34,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "region.h" #include "spell.h" #include "spellbook.h" -#include "save.h" #include "ship.h" #include "skill.h" #include "terrain.h" @@ -121,10 +120,10 @@ unit *findunitr(const region * r, int n) return (u && u->region == r) ? u : 0; } -// TODO: deprecated, replace with findunit(n) +/* TODO: deprecated, replace with findunit(n) */ unit *findunitg(int n, const region * hint) { - unused_arg(hint); + UNUSED_ARG(hint); /* Abfangen von Syntaxfehlern. */ if (n <= 0) return NULL; @@ -367,7 +366,7 @@ int gift_items(unit * u, int flags) static unit *deleted_units = NULL; #define DMAXHASH 7919 -#undef DMAXHASH // TODO: makes dfindhash slow! +#undef DMAXHASH /* TODO: makes dfindhash slow! */ #ifdef DMAXHASH typedef struct dead { struct dead *nexthash; @@ -456,7 +455,6 @@ int remove_unit(unit ** ulist, unit * u) #ifdef DMAXHASH dhash(u->no, u->faction); #endif - // u_setfaction(u, NULL); u->region = NULL; @@ -495,6 +493,10 @@ attrib_type at_alias = { NO_READ }; +/** remember old unit.no (for the creport, mostly) + * if alias is positive, then this unit was a TEMP + * if alias is negative, then this unit has been RENUMBERed + */ int ualias(const unit * u) { attrib *a = a_find(u->attribs, &at_alias); @@ -508,7 +510,7 @@ int a_readprivate(attrib * a, void *owner, gamedata *data) struct storage *store = data->store; char lbuf[DISPLAYSIZE]; READ_STR(store, lbuf, sizeof(lbuf)); - a->data.v = _strdup(lbuf); + a->data.v = strdup(lbuf); return (a->data.v) ? AT_READ_OK : AT_READ_FAIL; } @@ -529,8 +531,15 @@ const char *u_description(const unit * u, const struct locale *lang) if (u->display && u->display[0]) { return u->display; } - else if (u_race(u)->describe) { - return u_race(u)->describe(u->_race, lang); + else { + char zText[64]; + const char * d; + const race * rc = u_race(u); + snprintf(zText, sizeof(zText), "describe_%s", rc->_name); + d = locale_getstring(lang, zText); + if (d) { + return d; + } } return NULL; } @@ -559,7 +568,7 @@ void usetprivate(unit * u, const char *str) if (a->data.v) { free(a->data.v); } - a->data.v = _strdup(str); + a->data.v = strdup(str); } /*********************/ @@ -806,8 +815,8 @@ void set_level(unit * u, skill_t sk, int value) static int leftship_age(struct attrib *a, void *owner) { /* must be aged, so it doesn't affect report generation (cansee) */ - unused_arg(a); - unused_arg(owner); + UNUSED_ARG(a); + UNUSED_ARG(owner); return AT_AGE_REMOVE; /* remove me */ } @@ -883,15 +892,16 @@ void leave_building(unit * u) bool can_leave(unit * u) { - int rule_leave; + static int config; + static bool rule_leave; if (!u->building) { return true; } - - rule_leave = config_get_int("rules.move.owner_leave", 0); - - if (rule_leave != 0 && u->building && u == building_owner(u->building)) { + if (config_changed(&config)) { + rule_leave = config_get_int("rules.move.owner_leave", 0) != 0; + } + if (rule_leave && u->building && u == building_owner(u->building)) { return false; } return true; @@ -913,11 +923,6 @@ bool leave(unit * u, bool force) return true; } -const struct race *urace(const struct unit *u) -{ - return u->_race; -} - bool can_survive(const unit * u, const region * r) { if ((fval(r->terrain, WALK_INTO) && (u_race(u)->flags & RCF_WALK)) @@ -947,7 +952,7 @@ void move_unit(unit * u, region * r, unit ** ulist) if (!ulist) ulist = (&r->units); if (u->region) { - setguard(u, GUARD_NONE); + setguard(u, false); fset(u, UFL_MOVED); if (u->ship || u->building) { /* can_leave must be checked in travel_i */ @@ -1083,15 +1088,9 @@ void transfermen(unit * u, unit * dst, int n) else if (r->land) { if ((u_race(u)->ec_flags & ECF_REC_ETHEREAL) == 0) { const race *rc = u_race(u); - if (rc->ec_flags & ECF_REC_HORSES) { /* Zentauren an die Pferde */ - int h = rhorses(r) + n; - rsethorses(r, h); - } - else { - int p = rpeasants(r); - p += (int)(n * rc->recruit_multi); - rsetpeasants(r, p); - } + int p = rpeasants(r); + p += (int)(n * rc->recruit_multi); + rsetpeasants(r, p); } } } @@ -1171,7 +1170,6 @@ void u_setfaction(unit * u, faction * f) } } -/* vorsicht Sprueche koennen u->number == RS_FARVISION haben! */ void set_number(unit * u, int count) { assert(count >= 0); @@ -1253,24 +1251,6 @@ static int item_invis(const unit *u) { + (rsphere ? i_get(u->items, rsphere->itype) * 100 : 0); } -#ifdef NEWATSROI -static int item_modification(const unit * u, skill_t sk, int val) -{ - if (sk == SK_STEALTH) { - if (item_invis(u) >= u->number) { - val += ROIBONUS; - } - } - if (sk == SK_PERCEPTION) { - const struct resource_type *rtype = get_resourcetype(R_AMULET_OF_TRUE_SEEING); - if (i_get(u->items, rtype->itype) >= u->number) { - val += ATSBONUS; - } - } - return val; -} -#endif - static int att_modification(const unit * u, skill_t sk) { double result = 0; @@ -1309,7 +1289,7 @@ static int att_modification(const unit * u, skill_t sk) while (a && a->type == &at_curse) { curse *c = (curse *)a->data.v; - if (curse_active(c) && c->type == gbdream_ct) { + if (c->magician && curse_active(c) && c->type == gbdream_ct) { int effect = curse_geteffect_int(c); bool allied = alliedunit(c->magician, u->faction, HELP_GUARD); if (allied) { @@ -1343,11 +1323,6 @@ int get_modifier(const unit * u, skill_t sk, int level, const region * r, bool n skill += rc_skillmod(u_race(u), r, sk); skill += att_modification(u, sk); -#ifdef NEWATSROI - if (!noitem) { - skill = item_modification(u, sk, skill); - } -#endif skill = skillmod(u->attribs, u, r, sk, skill, SMF_ALWAYS); if (fval(u, UFL_HUNGER)) { @@ -1390,15 +1365,12 @@ int effskill_study(const unit * u, skill_t sk, const region * r) int invisible(const unit * target, const unit * viewer) { -#ifdef NEWATSROI - return 0; -#else if (viewer && viewer->faction == target->faction) return 0; else { int hidden = item_invis(target); if (hidden) { - hidden = _min(hidden, target->number); + hidden = MIN(hidden, target->number); if (viewer) { const resource_type *rtype = get_resourcetype(R_AMULET_OF_TRUE_SEEING); hidden -= i_get(viewer->items, rtype->itype); @@ -1406,7 +1378,6 @@ int invisible(const unit * target, const unit * viewer) } return hidden; } -#endif } /** remove the unit from memory. @@ -1437,6 +1408,26 @@ void free_unit(unit * u) } } +static int newunitid(void) +{ + int random_unit_no; + int start_random_no; + random_unit_no = 1 + (rng_int() % MAX_UNIT_NR); + start_random_no = random_unit_no; + + while (ufindhash(random_unit_no) || dfindhash(random_unit_no) + || forbiddenid(random_unit_no)) { + random_unit_no++; + if (random_unit_no == MAX_UNIT_NR + 1) { + random_unit_no = 1; + } + if (random_unit_no == start_random_no) { + random_unit_no = (int)MAX_UNIT_NR + 1; + } + } + return random_unit_no; +} + static void createunitid(unit * u, int id) { if (id <= 0 || id > MAX_UNIT_NR || ufindhash(id) || dfindhash(id) @@ -1468,15 +1459,12 @@ void default_name(const unit *u, char name[], int len) { void name_unit(unit * u) { - if (u_race(u)->generate_name) { - char *gen_name = race_namegen(u_race(u), u); - if (gen_name) { - free(u->_name); - u->_name = gen_name; - } - else { - unit_setname(u, racename(u->faction->locale, u, u_race(u))); - } + const race *rc = u_race(u); + if (rc->name_unit) { + rc->name_unit(u); + } + else if (u->faction->flags & FFL_NPC) { + unit_setname(u, NULL); } else { char name[32]; @@ -1527,9 +1515,9 @@ unit *create_unit(region * r, faction * f, int number, const struct race *urace, u->hp = unit_max_hp(u) * number; if (dname) { - u->_name = _strdup(dname); + u->_name = strdup(dname); } - else if (urace->generate_name || playerrace(urace)) { + else if (urace->name_unit || playerrace(urace)) { name_unit(u); } @@ -1634,7 +1622,7 @@ void unit_setname(unit * u, const char *name) { free(u->_name); if (name && name[0]) - u->_name = _strdup(name); + u->_name = strdup(name); else u->_name = NULL; } @@ -1648,7 +1636,7 @@ void unit_setinfo(unit * u, const char *info) { free(u->display); if (info) - u->display = _strdup(info); + u->display = strdup(info); else u->display = NULL; } @@ -1699,6 +1687,7 @@ int unit_getcapacity(const unit * u) } void renumber_unit(unit *u, int no) { + if (no == 0) no = newunitid(); uunhash(u); if (!ualias(u)) { attrib *a = a_add(&u->attribs, a_new(&at_alias)); @@ -1721,9 +1710,13 @@ int unit_max_hp(const unit * u) { int h; double p; - int rule_stamina = config_get_int("rules.stamina", STAMINA_AFFECTS_HP); + static int config; + static int rule_stamina; h = u_race(u)->hitpoints; + if (config_changed(&config)) { + rule_stamina = config_get_int("rules.stamina", STAMINA_AFFECTS_HP); + } if (rule_stamina & 1) { p = pow(effskill(u, SK_STAMINA, u->region) / 2.0, 1.5) * 0.2; h += (int)(h * p + 0.5); @@ -1925,27 +1918,6 @@ bool unit_can_study(const unit *u) { return !((u_race(u)->flags & RCF_NOLEARN) || fval(u, UFL_WERE)); } -/* ID's fr Einheiten und Zauber */ -int newunitid(void) -{ - int random_unit_no; - int start_random_no; - random_unit_no = 1 + (rng_int() % MAX_UNIT_NR); - start_random_no = random_unit_no; - - while (ufindhash(random_unit_no) || dfindhash(random_unit_no) - || forbiddenid(random_unit_no)) { - random_unit_no++; - if (random_unit_no == MAX_UNIT_NR + 1) { - random_unit_no = 1; - } - if (random_unit_no == start_random_no) { - random_unit_no = (int)MAX_UNIT_NR + 1; - } - } - return random_unit_no; -} - static int read_newunitid(const faction * f, const region * r) { int n; @@ -2057,3 +2029,26 @@ bool has_limited_skills(const struct unit * u) return false; } +double u_heal_factor(const unit * u) +{ + const race * rc = u_race(u); + if (rc->healing>0) { + return rc->healing / 100.0; + } + if (r_isforest(u->region)) { + static int rc_cache; + static const race *rc_elf; + if (rc_changed(&rc_cache)) { + rc_elf = get_race(RC_ELF); + } + if (rc == rc_elf) { + static int cache; + static double elf_regen; + if (config_changed(&cache)) { + elf_regen = config_get_flt("healing.forest", 1.0); + } + return elf_regen; + } + } + return 1.0; +} diff --git a/src/kernel/unit.h b/src/kernel/unit.h index 32e48a950..14096c872 100644 --- a/src/kernel/unit.h +++ b/src/kernel/unit.h @@ -22,6 +22,8 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include "types.h" #include "skills.h" +#include + #ifdef __cplusplus extern "C" { #endif @@ -141,8 +143,6 @@ extern "C" { struct unit *utarget(const struct unit *u); void usettarget(struct unit *u, const struct unit *b); - extern const struct race *urace(const struct unit *u); - const char *uprivate(const struct unit *u); void usetprivate(struct unit *u, const char *c); @@ -190,6 +190,7 @@ extern "C" { bool leave(struct unit *u, bool force); bool can_leave(struct unit *u); + double u_heal_factor(const struct unit * u); void u_set_building(struct unit * u, struct building * b); void u_set_ship(struct unit * u, struct ship * sh); void leave_ship(struct unit * u); @@ -258,7 +259,6 @@ extern "C" { #define GET_PEASANTS 2 int getunit(const struct region * r, const struct faction * f, struct unit **uresult); - int newunitid(void); int read_unitid(const struct faction *f, const struct region *r); void setstatus(struct unit *u, int status); diff --git a/src/kernel/unit.test.c b/src/kernel/unit.test.c index 054a45652..7c7bb087b 100644 --- a/src/kernel/unit.test.c +++ b/src/kernel/unit.test.c @@ -8,9 +8,11 @@ #include #include #include +#include +#include #include #include -#include +#include #include #include #include @@ -139,37 +141,34 @@ static void test_scale_number(CuTest *tc) { static void test_unit_name(CuTest *tc) { unit *u; - char name[32]; test_cleanup(); test_create_world(); u = test_create_unit(test_create_faction(test_create_race("human")), findregion(0, 0)); + renumber_unit(u, 666); unit_setname(u, "Hodor"); - _snprintf(name, sizeof(name), "Hodor (%s)", itoa36(u->no)); - CuAssertStrEquals(tc, name, unitname(u)); + CuAssertStrEquals(tc, "Hodor (ii)", unitname(u)); test_cleanup(); } static void test_unit_name_from_race(CuTest *tc) { unit *u; - char name[32]; struct locale *lang; test_cleanup(); test_create_world(); u = test_create_unit(test_create_faction(test_create_race("human")), findregion(0, 0)); + renumber_unit(u, 666); unit_setname(u, NULL); lang = get_or_create_locale("de"); locale_setstring(lang, rc_name_s(u->_race, NAME_SINGULAR), "Mensch"); locale_setstring(lang, rc_name_s(u->_race, NAME_PLURAL), "Menschen"); - _snprintf(name, sizeof(name), "Mensch (%s)", itoa36(u->no)); - CuAssertStrEquals(tc, name, unitname(u)); + CuAssertStrEquals(tc, "Mensch (ii)", unitname(u)); CuAssertStrEquals(tc, "Mensch", unit_getname(u)); u->number = 2; - _snprintf(name, sizeof(name), "Menschen (%s)", itoa36(u->no)); - CuAssertStrEquals(tc, name, unitname(u)); + CuAssertStrEquals(tc, "Menschen (ii)", unitname(u)); CuAssertStrEquals(tc, "Menschen", unit_getname(u)); test_cleanup(); @@ -242,9 +241,9 @@ static void test_default_name(CuTest *tc) { } static int cb_skillmod(const unit *u, const region *r, skill_t sk, int level) { - unused_arg(u); - unused_arg(r); - unused_arg(sk); + UNUSED_ARG(u); + UNUSED_ARG(r); + UNUSED_ARG(sk); return level + 3; } @@ -261,7 +260,7 @@ static void test_skillmod(CuTest *tc) { CuAssertIntEquals(tc, 10, effskill(u, SK_ARMORER, 0)); a_remove(&u->attribs, a); - a_add(&u->attribs, a = make_skillmod(NOSKILL, SMF_ALWAYS, 0, 2.0, 0)); // NOSKILL means any skill + a_add(&u->attribs, a = make_skillmod(NOSKILL, SMF_ALWAYS, 0, 2.0, 0)); /* NOSKILL means any skill */ CuAssertIntEquals(tc, 10, effskill(u, SK_ARMORER, 0)); a_remove(&u->attribs, a); @@ -297,7 +296,7 @@ static void test_skill_familiar(CuTest *tc) { test_cleanup(); - // setup two units + /* setup two units */ mag = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); fam = test_create_unit(mag->faction, test_create_region(0, 0, 0)); set_level(fam, SK_PERCEPTION, 6); @@ -305,14 +304,14 @@ static void test_skill_familiar(CuTest *tc) { set_level(mag, SK_PERCEPTION, 6); CuAssertIntEquals(tc, 6, effskill(mag, SK_PERCEPTION, 0)); - // make them mage and familiar to each other + /* make them mage and familiar to each other */ CuAssertIntEquals(tc, true, create_newfamiliar(mag, fam)); - // when they are in the same region, the mage gets half their skill as a bonus + /* when they are in the same region, the mage gets half their skill as a bonus */ CuAssertIntEquals(tc, 6, effskill(fam, SK_PERCEPTION, 0)); CuAssertIntEquals(tc, 9, effskill(mag, SK_PERCEPTION, 0)); - // when they are further apart, divide bonus by distance + /* when they are further apart, divide bonus by distance */ r = test_create_region(3, 0, 0); move_unit(fam, r, &r->units); CuAssertIntEquals(tc, 7, effskill(mag, SK_PERCEPTION, 0)); @@ -324,7 +323,6 @@ static void test_age_familiar(CuTest *tc) { test_cleanup(); - // setup two units mag = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); fam = test_create_unit(mag->faction, test_create_region(0, 0, 0)); CuAssertPtrEquals(tc, 0, get_familiar(mag)); @@ -392,14 +390,24 @@ static void test_limited_skills(CuTest *tc) { static void test_unit_description(CuTest *tc) { race *rc; unit *u; + struct locale *lang; + test_setup(); + lang = test_create_locale(); rc = test_create_race("hodor"); u = test_create_unit(test_create_faction(rc), test_create_region(0,0,0)); + CuAssertPtrEquals(tc, 0, u->display); - CuAssertStrEquals(tc, 0, u_description(u, u->faction->locale)); - u->display = _strdup("Hodor"); + CuAssertStrEquals(tc, 0, u_description(u, lang)); + u->display = strdup("Hodor"); CuAssertStrEquals(tc, "Hodor", u_description(u, NULL)); - CuAssertStrEquals(tc, "Hodor", u_description(u, u->faction->locale)); + CuAssertStrEquals(tc, "Hodor", u_description(u, lang)); + + free(u->display); + u->display = NULL; + locale_setstring(lang, "describe_hodor", "HODOR"); + CuAssertStrEquals(tc, "HODOR", u_description(u, lang)); + test_cleanup(); } @@ -427,33 +435,90 @@ static void test_remove_unit(CuTest *tc) { remove_unit(&r->units, u1); CuAssertIntEquals(tc, 0, u1->number); CuAssertPtrEquals(tc, 0, u1->region); - // money is given to a survivor: + /* money is given to a survivor: */ CuAssertPtrEquals(tc, 0, u1->items); CuAssertIntEquals(tc, 0, region_getresource(r, rtype)); CuAssertIntEquals(tc, 100, i_get(u2->items, rtype->itype)); - // unit is removed from f->units: + /* unit is removed from f->units: */ CuAssertPtrEquals(tc, 0, u1->nextF); CuAssertPtrEquals(tc, u2, f->units); CuAssertPtrEquals(tc, 0, u2->nextF); CuAssertPtrEquals(tc, 0, u2->prevF); - // unit is no longer in r->units: + /* unit is no longer in r->units: */ CuAssertPtrEquals(tc, u2, r->units); CuAssertPtrEquals(tc, 0, u2->next); - // unit is in deleted_units: + /* unit is in deleted_units: */ CuAssertPtrEquals(tc, 0, findunit(uno)); CuAssertPtrEquals(tc, f, dfindhash(uno)); remove_unit(&r->units, u2); - // no survivor, give money to peasants: + /* no survivor, give money to peasants: */ CuAssertIntEquals(tc, 100, region_getresource(r, rtype)); - // there are now no more units: + /* there are now no more units: */ CuAssertPtrEquals(tc, 0, r->units); CuAssertPtrEquals(tc, 0, f->units); test_cleanup(); } +static void test_renumber_unit(CuTest *tc) { + unit *u1, *u2; + test_setup(); + u1 = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); + u2 = test_create_unit(u1->faction, u1->region); + rng_init(0); + renumber_unit(u1, 0); + rng_init(0); + renumber_unit(u2, 0); + CuAssertTrue(tc, u1->no != u2->no); + test_cleanup(); +} + +static void gen_name(unit *u) +{ + unit_setname(u, "Hodor"); +} + +static void test_name_unit(CuTest *tc) { + race *rc; + unit * u; + + test_setup(); + rc = test_create_race("skeleton"); + u = test_create_unit(test_create_faction(rc), test_create_region(0, 0, 0)); + rc->name_unit = gen_name; + name_unit(u); + CuAssertStrEquals(tc, "Hodor", unit_getname(u)); + test_cleanup(); +} + +static void test_heal_factor(CuTest *tc) { + unit * u; + region *r; + race *rc; + terrain_type *t_plain; + + test_setup(); + t_plain = test_create_terrain("plain", LAND_REGION|FOREST_REGION); + rc = rc_get_or_create("human"); + u = test_create_unit(test_create_faction(rc), r = test_create_region(0, 0, t_plain)); + rsettrees(r, 1, r->terrain->size / TREESIZE); + rsettrees(r, 2, 0); + CuAssertTrue(tc, r_isforest(r)); + CuAssertDblEquals(tc, 1.0, u_heal_factor(u), 0.0); + rc->healing = 200; + CuAssertDblEquals(tc, 2.0, u_heal_factor(u), 0.0); + rc->healing = 0; + rc = rc_get_or_create("elf"); + CuAssertPtrEquals(tc, (void *)rc, (void *)get_race(RC_ELF)); + u_setrace(u, get_race(RC_ELF)); + CuAssertDblEquals(tc, 1.0, u_heal_factor(u), 0.0); + config_set("healing.forest", "1.5"); + CuAssertDblEquals(tc, 1.5, u_heal_factor(u), 0.0); + test_cleanup(); +} + CuSuite *get_unit_suite(void) { CuSuite *suite = CuSuiteNew(); @@ -476,5 +541,8 @@ CuSuite *get_unit_suite(void) SUITE_ADD_TEST(suite, test_age_familiar); SUITE_ADD_TEST(suite, test_inside_building); SUITE_ADD_TEST(suite, test_limited_skills); + SUITE_ADD_TEST(suite, test_renumber_unit); + SUITE_ADD_TEST(suite, test_name_unit); + SUITE_ADD_TEST(suite, test_heal_factor); return suite; } diff --git a/src/kernel/version.c b/src/kernel/version.c index 6de6ddb40..39f4f30e6 100644 --- a/src/kernel/version.c +++ b/src/kernel/version.c @@ -4,16 +4,20 @@ #include #ifndef ERESSEA_VERSION -// the version number, if it was not passed to make with -D -#define ERESSEA_VERSION "3.10.0-devel" +/* the version number, if it was not passed to make with -D */ +#define ERESSEA_VERSION "3.12.0" #endif const char *eressea_version(void) { +#ifdef ERESSEA_BUILDNO + return ERESSEA_VERSION "-" ERESSEA_BUILDNO; +#else return ERESSEA_VERSION; +#endif } int version_no(const char *str) { - int maj = 0, min = 0, bld = 0; - sscanf(str, "%d.%d.%d", &maj, &min, &bld); - return (maj << 16) | (min << 8) | bld; + int maj = 0, min = 0, pat = 0; + sscanf(str, "%d.%d.%d", &maj, &min, &pat); + return (maj << 16) | (min << 8) | pat; } diff --git a/src/kernel/xmlreader.c b/src/kernel/xmlreader.c index 68f62d11f..4db528853 100644 --- a/src/kernel/xmlreader.c +++ b/src/kernel/xmlreader.c @@ -15,6 +15,7 @@ without prior permission by the authors of Eressea. #include "xmlreader.h" #include "building.h" +#include "guard.h" #include "equipment.h" #include "item.h" #include "keyword.h" @@ -60,30 +61,38 @@ without prior permission by the authors of Eressea. #include #ifdef USE_LIBXML2 + +static variant xml_fraction(xmlNodePtr node, const char *name) { + xmlChar *propValue = xmlGetProp(node, BAD_CAST name); + if (propValue != NULL) { + int num, den = 100; + double fval = atof((const char *)propValue); + num = (int)(fval * den + 0.5); + xmlFree(propValue); + return frac_make(num, den); + } + return frac_make(0, 1); +} + static void xml_readtext(xmlNodePtr node, struct locale **lang, xmlChar ** text) { xmlChar *propValue = xmlGetProp(node, BAD_CAST "locale"); assert(propValue != NULL); *lang = get_locale((const char *)propValue); -#ifdef MAKE_LOCALES - if (*lang == NULL) - *lang = get_or_create_locale((const char *)propValue); -#endif xmlFree(propValue); *text = xmlNodeListGetString(node->doc, node->children, 1); } -static const spell *xml_spell(xmlNode * node, const char *name) +static spellref *xml_spellref(xmlNode * node, const char *name) { - const spell *sp = NULL; xmlChar *propValue = xmlGetProp(node, BAD_CAST name); if (propValue != NULL) { - sp = find_spell((const char *)propValue); - assert(sp); + spellref *ref = spellref_create(NULL, (const char *)propValue); xmlFree(propValue); + return ref; } - return sp; + return NULL; } static xmlChar *xml_cleanup_string(xmlChar * str) @@ -93,8 +102,8 @@ static xmlChar *xml_cleanup_string(xmlChar * str) while (*read) { /* eat leading whitespace */ - if (*read && isxspace(*read)) { - while (*read && isxspace(*read)) { + if (*read && isspace(*read)) { + while (*read && isspace(*read)) { ++read; } *write++ = ' '; @@ -171,9 +180,6 @@ construction ** consPtr) con->maxsize = xml_ivalue(node, "maxsize", -1); con->minskill = xml_ivalue(node, "minskill", -1); con->reqsize = xml_ivalue(node, "reqsize", 1); - con->defense_bonus = xml_ivalue(node, "defense_bonus", 0); - con->close_combat_bonus = xml_ivalue(node, "close_combat_bonus", 0); - con->ranged_bonus = xml_ivalue(node, "ranged_bonus", 0); propValue = xmlGetProp(node, BAD_CAST "building"); if (propValue != NULL) { @@ -252,7 +258,7 @@ static int parse_buildings(xmlDocPtr doc) btype->maxcapacity = xml_ivalue(node, "maxcapacity", btype->maxcapacity); btype->maxsize = xml_ivalue(node, "maxsize", btype->maxsize); - btype->magres = xml_ivalue(node, "magres", btype->magres); + btype->magres = frac_make(xml_ivalue(node, "magres", 0), 100); btype->magresbonus = xml_ivalue(node, "magresbonus", btype->magresbonus); btype->fumblebonus = xml_ivalue(node, "fumblebonus", btype->fumblebonus); btype->auraregen = xml_fvalue(node, "auraregen", btype->auraregen); @@ -305,9 +311,6 @@ static int parse_buildings(xmlDocPtr doc) else if (strcmp((const char *)propValue, "age") == 0) { btype->age = (void(*)(struct building *))fun; } - else if (strcmp((const char *)propValue, "protection") == 0) { - btype->protection = (int(*)(const struct building *, const struct unit *, building_bonus))fun; - } else if (strcmp((const char *)propValue, "taxes") == 0) { btype->taxes = (double(*)(const struct building *, int))fun; } @@ -339,9 +342,6 @@ static int parse_buildings(xmlDocPtr doc) if (xml_bvalue(node, "variable", false)) mt->flags |= MTF_VARIABLE; - if (xml_bvalue(node, "vital", false)) - mt->flags |= MTF_VITAL; - } xmlXPathFreeObject(result); @@ -361,27 +361,27 @@ static int parse_calendar(xmlDocPtr doc) xmlXPathContextPtr xpath = xmlXPathNewContext(doc); xmlXPathObjectPtr xpathCalendars; xmlNodeSetPtr nsetCalendars; - int c, rv = 0; - /* reading eressea/buildings/building */ xpathCalendars = xmlXPathEvalExpression(BAD_CAST "/eressea/calendar", xpath); nsetCalendars = xpathCalendars->nodesetval; - months_per_year = 0; - if (nsetCalendars == NULL || nsetCalendars->nodeNr == 0) { - rv = -1; - } - else + if (nsetCalendars != NULL && nsetCalendars->nodeNr != 0) { + int c; for (c = 0; c != nsetCalendars->nodeNr; ++c) { xmlNodePtr calendar = nsetCalendars->nodeTab[c]; xmlXPathObjectPtr xpathWeeks, xpathMonths, xpathSeasons; xmlNodeSetPtr nsetWeeks, nsetMonths, nsetSeasons; xmlChar *propValue = xmlGetProp(calendar, BAD_CAST "name"); xmlChar *newyear = xmlGetProp(calendar, BAD_CAST "newyear"); + xmlChar *start; - first_turn = xml_ivalue(calendar, "start", first_turn); + start = xmlGetProp(calendar, BAD_CAST "start"); + if (start && config_get("game.start") == NULL) { + config_set("game.start", (const char *)start); + xmlFree(start); + } if (propValue) { free(agename); - agename = _strdup(mkname("calendar", (const char *)propValue)); + agename = strdup(mkname("calendar", (const char *)propValue)); xmlFree(propValue); } @@ -400,7 +400,7 @@ static int parse_calendar(xmlDocPtr doc) xmlNodePtr week = nsetWeeks->nodeTab[i]; xmlChar *propValue = xmlGetProp(week, BAD_CAST "name"); if (propValue) { - weeknames[i] = _strdup(mkname("calendar", (const char *)propValue)); + weeknames[i] = strdup(mkname("calendar", (const char *)propValue)); weeknames2[i] = malloc(strlen(weeknames[i]) + 3); sprintf(weeknames2[i], "%s_d", weeknames[i]); xmlFree(propValue); @@ -423,7 +423,7 @@ static int parse_calendar(xmlDocPtr doc) xmlChar *propValue = xmlGetProp(season, BAD_CAST "name"); if (propValue) { seasonnames[i] = - _strdup(mkname("calendar", (const char *)propValue)); + strdup(mkname("calendar", (const char *)propValue)); xmlFree(propValue); } } @@ -453,7 +453,7 @@ static int parse_calendar(xmlDocPtr doc) xmlFree(newyear); newyear = NULL; } - monthnames[i] = _strdup(mkname("calendar", (const char *)propValue)); + monthnames[i] = strdup(mkname("calendar", (const char *)propValue)); xmlFree(propValue); } if (nsetSeasons) { @@ -475,10 +475,11 @@ static int parse_calendar(xmlDocPtr doc) xmlFree(newyear); newyear = NULL; } + } xmlXPathFreeObject(xpathCalendars); xmlXPathFreeContext(xpath); - return rv; + return 0; } static int parse_ships(xmlDocPtr doc) @@ -594,7 +595,7 @@ static armor_type *xml_readarmor(xmlXPathContextPtr xpath, item_type * itype) unsigned int flags = ATF_NONE; int ac = xml_ivalue(node, "ac", 0); double penalty = xml_fvalue(node, "penalty", 0.0); - double magres = xml_fvalue(node, "magres", 0.0); + variant magres = xml_fraction(node, "magres"); if (xml_bvalue(node, "laen", false)) flags |= ATF_LAEN; @@ -619,7 +620,7 @@ static weapon_type *xml_readweapon(xmlXPathContextPtr xpath, item_type * itype) int offmod = xml_ivalue(node, "offmod", 0); int defmod = xml_ivalue(node, "defmod", 0); int reload = xml_ivalue(node, "reload", 0); - double magres = xml_fvalue(node, "magres", 0.0); + variant magres = xml_fraction(node, "magres"); if (xml_bvalue(node, "armorpiercing", false)) flags |= WTF_ARMORPIERCING; @@ -665,7 +666,7 @@ static weapon_type *xml_readweapon(xmlXPathContextPtr xpath, item_type * itype) xmlFree(propValue); propValue = xmlGetProp(node, BAD_CAST "value"); - wtype->damage[pos] = _strdup((const char *)propValue); // TODO: this is a memory leak + wtype->damage[pos] = strdup((const char *)propValue); /* TODO: this is a memory leak */ if (k == 0) wtype->damage[1 - pos] = wtype->damage[pos]; xmlFree(propValue); @@ -756,6 +757,28 @@ static weapon_type *xml_readweapon(xmlXPathContextPtr xpath, item_type * itype) return wtype; } +static int race_mask = 1; + +static void mask_races(xmlNodePtr node, const char *key, int *maskp) { + xmlChar *propValue = xmlGetProp(node, BAD_CAST key); + int mask = 0; + assert(maskp); + if (propValue) { + char * tok = strtok((char *)propValue, " ,"); + while (tok) { + race * rc = rc_get_or_create(tok); + if (!rc->mask_item) { + rc->mask_item = race_mask; + race_mask = race_mask << 1; + } + mask |= rc->mask_item; + tok = strtok(NULL, " ,"); + } + xmlFree(propValue); + } + *maskp = mask; +} + static item_type *xml_readitem(xmlXPathContextPtr xpath, resource_type * rtype) { xmlNodePtr node = xpath->node; @@ -766,6 +789,8 @@ static item_type *xml_readitem(xmlXPathContextPtr xpath, resource_type * rtype) if (xml_bvalue(node, "cursed", false)) flags |= ITF_CURSED; + if (xml_bvalue(node, "use", false)) + flags |= ITF_CANUSE; if (xml_bvalue(node, "notlost", false)) flags |= ITF_NOTLOST; if (xml_bvalue(node, "herb", false)) @@ -779,6 +804,8 @@ static item_type *xml_readitem(xmlXPathContextPtr xpath, resource_type * rtype) itype = rtype->itype ? rtype->itype : it_get_or_create(rtype); itype->weight = xml_ivalue(node, "weight", 0); itype->capacity = xml_ivalue(node, "capacity", 0); + mask_races(node, "allow", &itype->mask_allow); + mask_races(node, "deny", &itype->mask_deny); itype->flags |= flags; /* reading item/construction */ @@ -802,6 +829,10 @@ static item_type *xml_readitem(xmlXPathContextPtr xpath, resource_type * rtype) result = xmlXPathEvalExpression(BAD_CAST "potion", xpath); assert(result->nodesetval->nodeNr <= 1); if (result->nodesetval->nodeNr != 0) { + if ((itype->flags & ITF_CANUSE) == 0) { + log_error("potion %s has no use attribute", rtype->_name); + itype->flags |= ITF_CANUSE; + } xpath->node = result->nodesetval->nodeTab[0]; rtype->ptype = xml_readpotion(xpath, itype); } @@ -842,28 +873,7 @@ static item_type *xml_readitem(xmlXPathContextPtr xpath, resource_type * rtype) continue; } assert(propValue != NULL); - if (strcmp((const char *)propValue, "give") == 0) { - itype->give = - (int(*)(struct unit *, struct unit *, const struct item_type *, int, - struct order *))fun; - } - else if (strcmp((const char *)propValue, "use") == 0) { - itype->use = - (int(*)(struct unit *, const struct item_type *, int, - struct order *))fun; - } - else if (strcmp((const char *)propValue, "canuse") == 0) { - itype->canuse = - (bool(*)(const struct unit *, const struct item_type *))fun; - } - else if (strcmp((const char *)propValue, "useonother") == 0) { - itype->useonother = - (int(*)(struct unit *, int, const struct item_type *, int, - struct order *))fun; - } - else { - log_error("unknown function type '%s' for item '%s'\n", (const char *)propValue, rtype->_name); - } + log_error("unknown function type '%s' for item '%s'\n", (const char *)propValue, rtype->_name); xmlFree(propValue); } itype->score = xml_ivalue(node, "score", 0); @@ -932,8 +942,6 @@ static int parse_resources(xmlDocPtr doc) if (xml_bvalue(node, "pooled", true)) flags |= RTF_POOLED; - if (xml_bvalue(node, "limited", false)) - flags |= RTF_LIMITED; name = xmlGetProp(node, BAD_CAST "name"); if (!name) { @@ -945,12 +953,6 @@ static int parse_resources(xmlDocPtr doc) rtype->flags |= flags; xmlFree(name); - name = xmlGetProp(node, BAD_CAST "material"); - if (name) { - rmt_create(rtype, (const char *)name); - xmlFree(name); - } - /* reading eressea/resources/resource/function */ xpath->node = node; result = xmlXPathEvalExpression(BAD_CAST "function", xpath); @@ -970,9 +972,6 @@ static int parse_resources(xmlDocPtr doc) if (strcmp((const char *)propValue, "change") == 0) { rtype->uchange = (rtype_uchange)fun; } - else if (strcmp((const char *)propValue, "get") == 0) { - rtype->uget = (rtype_uget)fun; - } else if (strcmp((const char *)propValue, "name") == 0) { rtype->name = (rtype_name)fun; } @@ -983,129 +982,66 @@ static int parse_resources(xmlDocPtr doc) } xmlXPathFreeObject(result); - /* reading eressea/resources/resource/resourcelimit */ - xpath->node = node; - result = xmlXPathEvalExpression(BAD_CAST "resourcelimit", xpath); - assert(result->nodesetval->nodeNr <= 1); - if (result->nodesetval->nodeNr != 0) { - resource_limit *rdata; - attrib *a = a_find(rtype->attribs, &at_resourcelimit); - xmlNodePtr limit = result->nodesetval->nodeTab[0]; + if (xml_bvalue(node, "material", false)) { + rmt_create(rtype); + } - if (a == NULL) - a = a_add(&rtype->attribs, a_new(&at_resourcelimit)); - rdata = (resource_limit *)a->data.v; + if (xml_bvalue(node, "limited", false)) { rtype->flags |= RTF_LIMITED; - xpath->node = limit; - xmlXPathFreeObject(result); + } + /* reading eressea/resources/resource/modifier */ + xpath->node = node; + result = xmlXPathEvalExpression(BAD_CAST "modifier", xpath); + if (result->nodesetval != NULL && result->nodesetval->nodeNr > 0) { + rtype->modifiers = + calloc(result->nodesetval->nodeNr + 1, sizeof(resource_mod)); + for (k = 0; k != result->nodesetval->nodeNr; ++k) { + xmlNodePtr node = result->nodesetval->nodeTab[k]; + building_type *btype = NULL; + const race *rc = NULL; - result = xmlXPathEvalExpression(BAD_CAST "modifier", xpath); - if (result->nodesetval != NULL) { - rdata->modifiers = - calloc(result->nodesetval->nodeNr + 1, sizeof(resource_mod)); - for (k = 0; k != result->nodesetval->nodeNr; ++k) { - xmlNodePtr node = result->nodesetval->nodeTab[k]; - building_type *btype = NULL; - const race *rc = NULL; - - propValue = xmlGetProp(node, BAD_CAST "race"); - if (propValue != NULL) { - rc = rc_find((const char *)propValue); - if (rc == NULL) - rc = rc_get_or_create((const char *)propValue); - xmlFree(propValue); - } - rdata->modifiers[k].race = rc; - - propValue = xmlGetProp(node, BAD_CAST "building"); - if (propValue != NULL) { - btype = bt_get_or_create((const char *)propValue); - xmlFree(propValue); - } - rdata->modifiers[k].btype = btype; - - propValue = xmlGetProp(node, BAD_CAST "type"); - assert(propValue != NULL); - if (strcmp((const char *)propValue, "skill") == 0) { - rdata->modifiers[k].value.i = xml_ivalue(node, "value", 0); - rdata->modifiers[k].flags = RMF_SKILL; - } - else if (strcmp((const char *)propValue, "material") == 0) { - rdata->modifiers[k].value.f = (float)xml_fvalue(node, "value", 0); - rdata->modifiers[k].flags = RMF_SAVEMATERIAL; - } - else if (strcmp((const char *)propValue, "resource") == 0) { - rdata->modifiers[k].value.f = (float)xml_fvalue(node, "value", 0); - rdata->modifiers[k].flags = RMF_SAVERESOURCE; - } - else if (strcmp((const char *)propValue, "require") == 0) { - xmlChar *propBldg = xmlGetProp(node, BAD_CAST "building"); - if (propBldg != NULL) { - btype = bt_get_or_create((const char *)propBldg); - rdata->modifiers[k].btype = btype; - rdata->modifiers[k].flags = RMF_REQUIREDBUILDING; - xmlFree(propBldg); - } - } - else { - log_error("unknown type '%s' for resourcelimit-modifier '%s'\n", (const char *)propValue, rtype->_name); - } + propValue = xmlGetProp(node, BAD_CAST "race"); + if (propValue != NULL) { + rc = rc_find((const char *)propValue); + if (rc == NULL) + rc = rc_get_or_create((const char *)propValue); xmlFree(propValue); } + rtype->modifiers[k].race = rc; + + propValue = xmlGetProp(node, BAD_CAST "building"); + if (propValue != NULL) { + btype = bt_get_or_create((const char *)propValue); + xmlFree(propValue); + } + rtype->modifiers[k].btype = btype; + + propValue = xmlGetProp(node, BAD_CAST "type"); + assert(propValue != NULL); + if (strcmp((const char *)propValue, "skill") == 0) { + rtype->modifiers[k].value.i = xml_ivalue(node, "value", 0); + rtype->modifiers[k].flags = RMF_SKILL; + } + else if (strcmp((const char *)propValue, "material") == 0) { + rtype->modifiers[k].value = xml_fraction(node, "value"); + rtype->modifiers[k].flags = RMF_SAVEMATERIAL; + } + else if (strcmp((const char *)propValue, "require") == 0) { + xmlChar *propBldg = xmlGetProp(node, BAD_CAST "building"); + if (propBldg != NULL) { + btype = bt_get_or_create((const char *)propBldg); + rtype->modifiers[k].btype = btype; + rtype->modifiers[k].flags = RMF_REQUIREDBUILDING; + xmlFree(propBldg); + } + } + else { + log_error("unknown type '%s' for resourcelimit-modifier '%s'\n", (const char *)propValue, rtype->_name); + } + xmlFree(propValue); } - xmlXPathFreeObject(result); - - result = xmlXPathEvalExpression(BAD_CAST "guard", xpath); - if (result->nodesetval != NULL) - for (k = 0; k != result->nodesetval->nodeNr; ++k) { - xmlNodePtr node = result->nodesetval->nodeTab[k]; - xmlChar *propFlag = xmlGetProp(node, BAD_CAST "flag"); - - if (propFlag != NULL) { - if (strcmp((const char *)propFlag, "logging") == 0) { - rdata->guard |= GUARD_TREES; - } - else if (strcmp((const char *)propFlag, "mining") == 0) { - rdata->guard |= GUARD_MINING; - } - xmlFree(propFlag); - } - } - xmlXPathFreeObject(result); - - /* reading eressea/resources/resource/resourcelimit/function */ - result = xmlXPathEvalExpression(BAD_CAST "function", xpath); - if (result->nodesetval != NULL) - for (k = 0; k != result->nodesetval->nodeNr; ++k) { - xmlNodePtr node = result->nodesetval->nodeTab[k]; - pf_generic fun; - - propValue = xmlGetProp(node, BAD_CAST "value"); - assert(propValue != NULL); - fun = get_function((const char *)propValue); - if (fun == NULL) { - log_error("unknown limit '%s' for resource %s\n", (const char *)propValue, rtype->_name); - xmlFree(propValue); - continue; - } - xmlFree(propValue); - - propValue = xmlGetProp(node, BAD_CAST "name"); - assert(propValue != NULL); - if (strcmp((const char *)propValue, "produce") == 0) { - rdata->produce = (rlimit_produce)fun; - } - else if (strcmp((const char *)propValue, "limit") == 0) { - rdata->limit = (rlimit_limit)fun; - } - else { - log_error("unknown limit '%s' for resource %s\n", (const char *)propValue, rtype->_name); - } - xmlFree(propValue); - } } xmlXPathFreeObject(result); - /* reading eressea/resources/resource/resourcelimit/function */ xpath->node = node; result = xmlXPathEvalExpression(BAD_CAST "resourcelimit/function", xpath); @@ -1133,7 +1069,6 @@ static int parse_resources(xmlDocPtr doc) /* make sure old items (used in requirements) are available */ init_resources(); - init_itemtypes(); return 0; } @@ -1191,22 +1126,18 @@ static void add_spells(equipment * eq, xmlNodeSetPtr nsetItems) for (i = 0; i != nsetItems->nodeNr; ++i) { xmlNodePtr node = nsetItems->nodeTab[i]; xmlChar *propValue; - struct spell *sp; + int level; + const char *name; propValue = xmlGetProp(node, BAD_CAST "name"); assert(propValue != NULL); - sp = find_spell((const char *)propValue); - if (!sp) { - log_error("no spell '%s' for equipment-set '%s'\n", (const char *)propValue, eq->name); + name = (const char *)propValue; + level = xml_ivalue(node, "level", 0); + if (level > 0) { + equipment_addspell(eq, name, level); } else { - int level = xml_ivalue(node, "level", 0); - if (level > 0) { - equipment_addspell(eq, sp, level); - } - else { - log_error("spell '%s' for equipment-set '%s' has no level\n", sp->sname, eq->name); - } + log_error("spell '%s' for equipment-set '%s' has no level\n", name, eq->name); } xmlFree(propValue); } @@ -1285,7 +1216,7 @@ add_subsets(xmlDocPtr doc, equipment * eq, xmlNodeSetPtr nsetSubsets) assert(propValue != NULL); eq->subsets[i].sets[set].chance = chance; eq->subsets[i].sets[set].set = - create_equipment((const char *)propValue); + get_or_create_equipment((const char *)propValue); xmlFree(propValue); } } @@ -1315,7 +1246,7 @@ static int parse_equipment(xmlDocPtr doc) xmlChar *propName = xmlGetProp(node, BAD_CAST "name"); if (propName != NULL) { - equipment *eq = create_equipment((const char *)propName); + equipment *eq = get_or_create_equipment((const char *)propName); xmlXPathObjectPtr xpathResult; xpath->node = node; @@ -1331,7 +1262,7 @@ static int parse_equipment(xmlDocPtr doc) xmlXPathFreeObject(xpathResult); xpathResult = xmlXPathEvalExpression(BAD_CAST "spell", xpath); - assert(!eq->spellbook); + assert(!eq->spells); add_spells(eq, xpathResult->nodesetval); xmlXPathFreeObject(xpathResult); @@ -1450,13 +1381,13 @@ static int parse_spells(xmlDocPtr doc) propValue = xmlGetProp(node, BAD_CAST "parameters"); if (propValue) { - sp->parameter = _strdup((const char *)propValue); + sp->parameter = strdup((const char *)propValue); xmlFree(propValue); } propValue = xmlGetProp(node, BAD_CAST "syntax"); if (propValue) { - sp->syntax = _strdup((const char *)propValue); + sp->syntax = strdup((const char *)propValue); xmlFree(propValue); } #ifdef TODO /* no longer need it, spellbooks! */ @@ -1593,29 +1524,16 @@ static int parse_spells(xmlDocPtr doc) return 0; } -static void parse_param(struct param **params, xmlNodePtr node) -{ - xmlChar *propName = xmlGetProp(node, BAD_CAST "name"); - xmlChar *propValue = xmlGetProp(node, BAD_CAST "value"); - - set_param(params, (const char *)propName, (const char *)propValue); - - xmlFree(propName); - xmlFree(propValue); -} - static void parse_ai(race * rc, xmlNodePtr node) { - int n; - - n = xml_ivalue(node, "scare", 0); - if (n>0) { - attrib *a = a_new(&at_scare); - a->data.i = n; - a_add(&rc->attribs, a); + xmlChar *propValue; + + propValue = xmlGetProp(node, BAD_CAST "scare"); + if (propValue) { + rc_set_param(rc, "ai.scare", (const char *)propValue); + xmlFree(propValue); } rc->splitsize = xml_ivalue(node, "splitsize", 0); - rc->aggression = (float)xml_fvalue(node, "aggression", 0.04); if (xml_bvalue(node, "killpeasants", false)) rc->flags |= RCF_KILLPEASANTS; if (xml_bvalue(node, "moverandom", false)) @@ -1652,17 +1570,18 @@ static int parse_races(xmlDocPtr doc) propValue = xmlGetProp(node, BAD_CAST "damage"); assert(propValue != NULL); - rc->def_damage = _strdup((const char *)propValue); + rc->def_damage = strdup((const char *)propValue); xmlFree(propValue); - rc->magres = (float)xml_fvalue(node, "magres", rc->magres); - rc->healing = (float)xml_fvalue(node, "healing", rc->healing); - rc->maxaura = (float)xml_fvalue(node, "maxaura", rc->maxaura); + rc->magres = frac_make(xml_ivalue(node, "magres", 100), 100); + rc->healing = (int)(xml_fvalue(node, "healing", rc->healing) * 100); /* TODO: store as int in XML */ + rc->maxaura = (int)(xml_fvalue(node, "maxaura", rc->maxaura) * 100); /* TODO: store as int in XML */ rc->regaura = (float)xml_fvalue(node, "regaura", rc->regaura); rc->recruitcost = xml_ivalue(node, "recruitcost", rc->recruitcost); rc->maintenance = xml_ivalue(node, "maintenance", rc->maintenance); rc->weight = xml_ivalue(node, "weight", rc->weight); rc->capacity = xml_ivalue(node, "capacity", rc->capacity); + rc->income = xml_ivalue(node, "income", rc->income); rc->speed = (float)xml_fvalue(node, "speed", rc->speed); rc->hitpoints = xml_ivalue(node, "hp", rc->hitpoints); rc->armor = (char)xml_ivalue(node, "ac", rc->armor); @@ -1736,15 +1655,13 @@ static int parse_races(xmlDocPtr doc) rc->ec_flags |= GIVEUNIT; if (xml_bvalue(node, "getitem", false)) rc->ec_flags |= GETITEM; - if (xml_bvalue(node, "recruithorses", false)) - rc->ec_flags |= ECF_REC_HORSES; if (xml_bvalue(node, "recruitethereal", false)) rc->ec_flags |= ECF_REC_ETHEREAL; if (xml_bvalue(node, "recruitunlimited", false)) rc->ec_flags |= ECF_REC_UNLIMITED; if (xml_bvalue(node, "equipment", false)) - rc->battle_flags |= BF_EQUIPMENT; // TODO: invert this flag, so rc_get_or_create gets simpler + rc->battle_flags |= BF_EQUIPMENT; /* TODO: invert this flag, so rc_get_or_create gets simpler */ if (xml_bvalue(node, "noblock", false)) rc->battle_flags |= BF_NOBLOCK; if (xml_bvalue(node, "invinciblenonmagic", false)) @@ -1758,15 +1675,19 @@ static int parse_races(xmlDocPtr doc) if (xml_bvalue(node, "noattack", false)) rc->battle_flags |= BF_NO_ATTACK; + rc->recruit_multi = 1.0; for (child = node->children; child; child = child->next) { if (strcmp((const char *)child->name, "ai") == 0) { parse_ai(rc, child); } else if (strcmp((const char *)child->name, "param") == 0) { - parse_param(&rc->parameters, child); + xmlChar *propName = xmlGetProp(child, BAD_CAST "name"); + xmlChar *propValue = xmlGetProp(child, BAD_CAST "value"); + rc_set_param(rc, (const char *)propName, (const char *)propValue); + xmlFree(propName); + xmlFree(propValue); } } - rc->recruit_multi = get_param_flt(rc->parameters, "recruit_multi", 1.0); /* reading eressea/races/race/skill */ xpath->node = node; @@ -1796,46 +1717,6 @@ static int parse_races(xmlDocPtr doc) } xmlXPathFreeObject(result); - /* reading eressea/races/race/function */ - xpath->node = node; - result = xmlXPathEvalExpression(BAD_CAST "function", xpath); - for (k = 0; k != result->nodesetval->nodeNr; ++k) { - xmlNodePtr node = result->nodesetval->nodeTab[k]; - pf_generic fun; - - parse_function(node, &fun, &propValue); - if (fun == NULL) { - log_error("unknown function name '%s' for race %s\n", (const char *)propValue, rc->_name); - xmlFree(propValue); - continue; - } - assert(propValue != NULL); - if (strcmp((const char *)propValue, "name") == 0) { - rc->generate_name = (race_name_func)fun; - } - else if (strcmp((const char *)propValue, "describe") == 0) { - rc->describe = (race_desc_func)fun; - } - else if (strcmp((const char *)propValue, "age") == 0) { - rc->age = (void(*)(struct unit *))fun; - } - else if (strcmp((const char *)propValue, "move") == 0) { - rc->move_allowed = - (bool(*)(const struct region *, const struct region *))fun; - } - else if (strcmp((const char *)propValue, "itemdrop") == 0) { - rc->itemdrop = (struct item * (*)(const struct race *, int))fun; - } - else if (strcmp((const char *)propValue, "initfamiliar") == 0) { - rc->init_familiar = (void(*)(struct unit *))fun; - } - else { - log_error("unknown function type '%s' for race %s\n", (const char *)propValue, rc->_name); - } - xmlFree(propValue); - } - xmlXPathFreeObject(result); - /* reading eressea/races/race/familiar */ xpath->node = node; result = xmlXPathEvalExpression(BAD_CAST "familiar", xpath); @@ -1850,6 +1731,7 @@ static int parse_races(xmlDocPtr doc) propValue = xmlGetProp(node, BAD_CAST "race"); assert(propValue != NULL); frc = rc_get_or_create((const char *)propValue); + frc->flags |= RCF_FAMILIAR; if (xml_bvalue(node, "default", false)) { rc->familiars[k] = rc->familiars[0]; rc->familiars[0] = frc; @@ -1866,17 +1748,6 @@ static int parse_races(xmlDocPtr doc) } xmlXPathFreeObject(result); - /* reading eressea/races/race/precombatspell */ - xpath->node = node; - result = xmlXPathEvalExpression(BAD_CAST "precombatspell", xpath); - assert(rc->precombatspell == NULL - || !"precombatspell is already initialized"); - for (k = 0; k != result->nodesetval->nodeNr; ++k) { - xmlNodePtr node = result->nodesetval->nodeTab[k]; - rc->precombatspell = xml_spell(node, "spell"); - } - xmlXPathFreeObject(result); - /* reading eressea/races/race/attack */ xpath->node = node; result = xmlXPathEvalExpression(BAD_CAST "attack", xpath); @@ -1894,15 +1765,15 @@ static int parse_races(xmlDocPtr doc) propValue = xmlGetProp(node, BAD_CAST "damage"); if (propValue != NULL) { - attack->data.dice = _strdup((const char *)propValue); + attack->data.dice = strdup((const char *)propValue); xmlFree(propValue); } else { - attack->data.sp = xml_spell(node, "spell"); + attack->data.sp = xml_spellref(node, "spell"); if (attack->data.sp) { attack->level = xml_ivalue(node, "level", 0); if (attack->level <= 0) { - log_error("magical attack '%s' for race '%s' needs a level: %d\n", attack->data.sp->sname, rc->_name, attack->level); + log_error("magical attack '%s' for race '%s' needs a level: %d\n", attack->data.sp->name, rc->_name, attack->level); } } } @@ -1957,7 +1828,7 @@ static int parse_messages(xmlDocPtr doc) (const char *)propType); xmlFree(propName); xmlFree(propType); - argv[k] = _strdup(zBuffer); + argv[k] = strdup(zBuffer); } argv[result->nodesetval->nodeNr] = NULL; } @@ -2089,17 +1960,20 @@ static int parse_strings(xmlDocPtr doc) void register_xmlreader(void) { - xml_register_callback(parse_strings); - xml_register_callback(parse_messages); - xml_register_callback(parse_resources); xml_register_callback(parse_rules); - xml_register_callback(parse_buildings); /* requires resources */ - xml_register_callback(parse_ships); /* requires terrains */ - xml_register_callback(parse_spells); /* requires resources */ - xml_register_callback(parse_spellbooks); /* requires spells */ - xml_register_callback(parse_equipment); /* requires spells */ - xml_register_callback(parse_races); /* requires spells */ + xml_register_callback(parse_races); xml_register_callback(parse_calendar); + xml_register_callback(parse_resources); + + xml_register_callback(parse_buildings); /* requires resources */ + xml_register_callback(parse_ships); /* requires resources, terrains */ + xml_register_callback(parse_equipment); /* requires resources */ + + xml_register_callback(parse_spells); /* requires resources */ + xml_register_callback(parse_spellbooks); /* requires spells */ + + xml_register_callback(parse_strings); + xml_register_callback(parse_messages); } #endif diff --git a/src/kernel/xmlreader.h b/src/kernel/xmlreader.h index 5dfb643f1..290b785c3 100644 --- a/src/kernel/xmlreader.h +++ b/src/kernel/xmlreader.h @@ -12,6 +12,9 @@ without prior permission by the authors of Eressea. #ifndef H_KRNL_XMLREADER_H #define H_KRNL_XMLREADER_H + +struct spell; + #ifdef __cplusplus extern "C" { #endif diff --git a/src/keyword.c b/src/keyword.c index 0bd699836..ba05cbe4b 100644 --- a/src/keyword.c +++ b/src/keyword.c @@ -13,7 +13,10 @@ const char * keyword(keyword_t kwd) { - static char result[32]; // FIXME: static return value + static char result[32]; /* FIXME: static return value */ + if (kwd==NOKEYWORD) { + return NULL; + } if (!result[0]) { strcpy(result, "keyword::"); } diff --git a/src/keyword.h b/src/keyword.h index 9d5e20f64..19e55e88f 100644 --- a/src/keyword.h +++ b/src/keyword.h @@ -2,6 +2,8 @@ #define H_KEYWORD_H #include "kernel/types.h" +#include + #ifdef __cplusplus extern "C" { @@ -70,7 +72,7 @@ extern "C" K_PAY, K_LOOT, MAXKEYWORDS, - NOKEYWORD = -1 + NOKEYWORD } keyword_t; extern const char *keywords[MAXKEYWORDS]; @@ -82,7 +84,6 @@ extern "C" bool keyword_disabled(keyword_t kwd); void enable_keyword(keyword_t kwd, bool enabled); const char *keyword(keyword_t kwd); - // #define keyword(kwd) mkname("keyword", keywords[kwd]) #ifdef __cplusplus #endif diff --git a/src/keyword.test.c b/src/keyword.test.c index 903eb0c13..75c31904a 100644 --- a/src/keyword.test.c +++ b/src/keyword.test.c @@ -11,11 +11,13 @@ static void test_init_keywords(CuTest *tc) { struct locale *lang; - test_cleanup(); + test_setup(); lang = get_or_create_locale("en"); locale_setstring(lang, "keyword::move", "MOVE"); init_keywords(lang); CuAssertIntEquals(tc, K_MOVE, get_keyword("move", lang)); + CuAssertStrEquals(tc, "keyword::move", keyword(K_MOVE)); + CuAssertPtrEquals(tc, NULL, (void *)keyword(NOKEYWORD)); test_cleanup(); } diff --git a/src/laws.c b/src/laws.c old mode 100755 new mode 100644 index f854ed7ef..b8291440f --- a/src/laws.c +++ b/src/laws.c @@ -1,4 +1,4 @@ -/* +/* Copyright (c) 1998-2014, Enno Rehling Katja Zedel #include #include -#include #include #include #include @@ -79,17 +79,17 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include +#include #include #include -#include #include #include #include -#include -#include +#include #include +#include #include /* libc includes */ #include @@ -117,6 +117,33 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* - exported global symbols ----------------------------------- */ +int NewbieImmunity(void) +{ + int result = config_get_int("NewbieImmunity", 0); + return result; +} + +bool IsImmune(const faction * f) +{ + return !fval(f, FFL_NPC) && f->age < NewbieImmunity(); +} + +int NMRTimeout(void) +{ + return config_get_int("nmr.timeout", 0); +} + +bool LongHunger(const struct unit *u) +{ + if (u != NULL) { + if (!fval(u, UFL_HUNGER)) + return false; + if (u_race(u) == get_race(RC_DAEMON)) + return false; + } + return config_get_int("hunger.long", 0) != 0; +} + static bool RemoveNMRNewbie(void) { int value = config_get_int("nmr.removenewbie", 0); @@ -125,15 +152,22 @@ static bool RemoveNMRNewbie(void) static void age_unit(region * r, unit * u) { - if (u_race(u) == get_race(RC_SPELL)) { + static int rc_cache; + static const race *rc_spell; + + if (rc_changed(&rc_cache)) { + rc_spell = get_race(RC_SPELL); + } + if (u_race(u) == rc_spell) { if (--u->age <= 0) { remove_unit(&r->units, u); } } else { + const race *rc = u_race(u); ++u->age; - if (u->number > 0 && u_race(u)->age) { - u_race(u)->age(u); + if (u->number > 0 && rc->age_unit) { + rc->age_unit(u); } } if (u->region && is_astral(u->region)) { @@ -177,7 +211,7 @@ static void live(region * r) } /* bestes Talent raussuchen */ if (sb != NULL) { - int weeks = _min(effect, u->number); + int weeks = MIN(effect, u->number); reduce_skill(u, sb, weeks); ADDMSG(&u->faction->msgs, msg_message("dumbeffect", "unit weeks skill", u, weeks, (skill_t)sb->id)); @@ -216,7 +250,7 @@ static void live(region * r) static void calculate_emigration(region * r) { int i; - int maxp = maxworkingpeasants(r); + int maxp = region_maxworkers(r); int rp = rpeasants(r); int max_immigrants = MAX_IMMIGRATION(maxp - rp); @@ -231,11 +265,11 @@ static void calculate_emigration(region * r) if (rc != NULL && fval(rc->terrain, LAND_REGION)) { int rp2 = rpeasants(rc); - int maxp2 = maxworkingpeasants(rc); + int maxp2 = region_maxworkers(rc); int max_emigration = MAX_EMIGRATION(rp2 - maxp2); if (max_emigration > 0) { - max_emigration = _min(max_emigration, max_immigrants); + max_emigration = MIN(max_emigration, max_immigrants); r->land->newpeasants += max_emigration; rc->land->newpeasants -= max_emigration; max_immigrants -= max_emigration; @@ -286,7 +320,7 @@ int peasant_luck_effect(int peasants, int luck, int maxp, double variance) double mean; if (luck == 0) return 0; - mean = peasant_luck_factor() * peasant_growth_factor() * _min(luck, peasants); + mean = peasant_luck_factor() * peasant_growth_factor() * MIN(luck, peasants); mean *= ((peasants / (double)maxp < .9) ? 1 : PEASANTFORCE); births = RAND_ROUND(normalvariate(mean, variance * mean)); @@ -299,7 +333,7 @@ int peasant_luck_effect(int peasants, int luck, int maxp, double variance) #endif -static void peasants(region * r) +static void peasants(region * r, int rule) { int peasants = rpeasants(r); int money = rmoney(r); @@ -307,7 +341,7 @@ static void peasants(region * r) int n, satiated; int dead = 0; - if (peasants > 0 && config_get_int("rules.peasants.growth", 1)) { + if (peasants > 0 && rule > 0) { int luck = 0; double fraction = peasants * peasant_growth_factor(); int births = RAND_ROUND(fraction); @@ -325,7 +359,7 @@ static void peasants(region * r) /* Alle werden satt, oder halt soviele für die es auch Geld gibt */ - satiated = _min(peasants, money / maintenance_cost(NULL)); + satiated = MIN(peasants, money / maintenance_cost(NULL)); rsetmoney(r, money - satiated * maintenance_cost(NULL)); /* Von denjenigen, die nicht satt geworden sind, verhungert der @@ -334,7 +368,7 @@ static void peasants(region * r) /* Es verhungert maximal die unterernährten Bevölkerung. */ - n = _min(peasants - satiated, rpeasants(r)); + n = MIN(peasants - satiated, rpeasants(r)); dead += (int)(0.5 + n * PEASANT_STARVATION_CHANCE); if (dead > 0) { @@ -414,8 +448,8 @@ static void horses(region * r) direction_t n; /* Logistisches Wachstum, Optimum bei halbem Maximalbesatz. */ - maxhorses = maxworkingpeasants(r) / 10; - maxhorses = _max(0, maxhorses); + maxhorses = region_maxworkers(r) / 10; + maxhorses = MAX(0, maxhorses); horses = rhorses(r); if (horses > 0) { if (is_cursed(r->attribs, C_CURSED_BY_THE_GODS, 0)) { @@ -449,7 +483,7 @@ static void horses(region * r) if (r2 && fval(r2->terrain, WALK_INTO)) { int pt = (rhorses(r) * HORSEMOVE) / 100; pt = (int)normalvariate(pt, pt / 4.0); - pt = _max(0, pt); + pt = MAX(0, pt); if (fval(r2, RF_MIGRATION)) rsethorses(r2, rhorses(r2) + pt); else { @@ -562,7 +596,7 @@ growing_trees(region * r, const int current_season, const int last_weeks_season) a = a_find(r->attribs, &at_germs); if (a && last_weeks_season == SEASON_SPRING) { /* ungekeimte Samen bleiben erhalten, Sprößlinge wachsen */ - sprout = _min(a->data.sa[1], rtrees(r, 1)); + sprout = MIN(a->data.sa[1], rtrees(r, 1)); /* aus dem gesamt Sprößlingepool abziehen */ rsettrees(r, 1, rtrees(r, 1) - sprout); /* zu den Bäumen hinzufügen */ @@ -582,7 +616,7 @@ growing_trees(region * r, const int current_season, const int last_weeks_season) /* Grundchance 1.0% */ /* Jeder Elf in der Region erhöht die Chance marginal */ - elves = _min(elves, production(r) / 8); + elves = MIN(elves, production(r) / 8); if (elves) { seedchance += 1.0 - pow(0.99999, elves * RESOURCE_QUANTITY); } @@ -616,7 +650,7 @@ growing_trees(region * r, const int current_season, const int last_weeks_season) * verfügbaren Fläche ab. In Gletschern gibt es weniger * Möglichkeiten als in Ebenen. */ sprout = 0; - seedchance = (1000 * maxworkingpeasants(r2)) / r2->terrain->size; + seedchance = (1000.0 * region_maxworkers(r2)) / r2->terrain->size; for (i = 0; i < seeds / MAXDIRECTIONS; i++) { if (rng_int() % 10000 < seedchance) sprout++; @@ -648,7 +682,7 @@ growing_trees(region * r, const int current_season, const int last_weeks_season) /* Raubbau abfangen, es dürfen nie mehr Samen wachsen, als aktuell * in der Region sind */ - seeds = _min(a->data.sa[0], rtrees(r, 0)); + seeds = MIN(a->data.sa[0], rtrees(r, 0)); sprout = 0; for (i = 0; i < seeds; i++) { @@ -668,7 +702,7 @@ growing_trees(region * r, const int current_season, const int last_weeks_season) * der Region entfernt werden können, da Jungbäume in der gleichen * Runde nachwachsen, wir also nicht mehr zwischen diesjährigen und * 'alten' Jungbäumen unterscheiden könnten */ - sprout = _min(a->data.sa[1], rtrees(r, 1)); + sprout = MIN(a->data.sa[1], rtrees(r, 1)); grownup_trees = 0; for (i = 0; i < sprout; i++) { @@ -703,19 +737,19 @@ growing_herbs(region * r, const int current_season, const int last_weeks_season) void immigration(void) { region *r; - log_info(" - Einwanderung..."); int repopulate = config_get_int("rules.economy.repopulate_maximum", 90); + log_info(" - Einwanderung..."); for (r = regions; r; r = r->next) { if (r->land && r->land->newpeasants) { int rp = rpeasants(r) + r->land->newpeasants; - rsetpeasants(r, _max(0, rp)); + rsetpeasants(r, MAX(0, rp)); } /* Genereate some (0-6 depending on the income) peasants out of nothing */ /* if less than 50 are in the region and there is space and no monster or demon units in the region */ if (repopulate) { int peasants = rpeasants(r); int income = wage(r, NULL, NULL, turn) - maintenance_cost(NULL) + 1; - if (income >= 0 && r->land && (peasants < repopulate) && maxworkingpeasants(r) >(peasants + 30) * 2) { + if (income >= 0 && r->land && (peasants < repopulate) && region_maxworkers(r) >(peasants + 30) * 2) { int badunit = 0; unit *u; for (u = r->units; u; u = u->next) { @@ -778,6 +812,8 @@ void demographics(void) static int last_weeks_season = -1; static int current_season = -1; int plant_rules = config_get_int("rules.grow.formula", 2); + int horse_rules = config_get_int("rules.horses.growth", 1); + int peasant_rules = config_get_int("rules.peasants.growth", 1); const struct building_type *bt_harbour = bt_find("harbour"); if (current_season < 0) { @@ -809,9 +845,10 @@ void demographics(void) * und gewandert sind */ calculate_emigration(r); - peasants(r); + peasants(r, peasant_rules); + if (r->age > 20) { - double mwp = _max(maxworkingpeasants(r), 1); + double mwp = MAX(region_maxworkers(r), 1); double prob = pow(rpeasants(r) / (mwp * wage(r, NULL, NULL, turn) * 0.13), 4.0) * PLAGUE_CHANCE; @@ -820,7 +857,9 @@ void demographics(void) plagues(r); } } - horses(r); + if (horse_rules > 0) { + horses(r); + } if (plant_rules == 2) { /* E2 */ growing_trees(r, current_season, last_weeks_season); growing_herbs(r, current_season, last_weeks_season); @@ -965,7 +1004,7 @@ int quit_cmd(unit * u, struct order *ord) char buffer[64]; write_order(ord, buffer, sizeof(buffer)); cmistake(u, ord, 86, MSG_EVENT); - log_warning("QUIT with illegal password for faction %s: %s\n", factionid(f), buffer); + log_warning("QUIT with illegal password for faction %s: %s\n", itoa36(f->no), buffer); } return 0; } @@ -1237,7 +1276,6 @@ static void remove_idle_players(void) } else { if (fval(f, FFL_NOIDLEOUT)) { f->lastorders = turn; - fp = &f->next; } else if (turn != f->lastorders) { char info[256]; @@ -1249,7 +1287,7 @@ static void remove_idle_players(void) } log_info(" - beseitige Spieler, die sich nach der Anmeldung nicht gemeldet haben..."); - age = calloc(_max(4, turn + 1), sizeof(int)); + age = calloc(MAX(4, turn + 1), sizeof(int)); for (fp = &factions; *fp;) { faction *f = *fp; if (!is_monsters(f)) { @@ -1506,16 +1544,6 @@ int prefix_cmd(unit * u, struct order *ord) return 0; } -static cmp_building_cb get_cmp_region_owner(void) -{ - if (rule_region_owners()) { - return &cmp_current_owner; - } - else { - return &cmp_wage; - } -} - int display_cmd(unit * u, struct order *ord) { char token[128]; @@ -1565,15 +1593,7 @@ int display_cmd(unit * u, struct order *ord) break; case P_REGION: - if (!u->building) { - cmistake(u, ord, 145, MSG_EVENT); - break; - } - if (building_owner(u->building) != u) { - cmistake(u, ord, 148, MSG_EVENT); - break; - } - if (u->building != largestbuilding(r, get_cmp_region_owner(), false)) { + if (u->faction != region_get_owner(r)) { cmistake(u, ord, 147, MSG_EVENT); break; } @@ -1590,7 +1610,7 @@ int display_cmd(unit * u, struct order *ord) free(*s); if (s2) { - *s = _strdup(s2); + *s = strdup(s2); if (strlen(s2) >= DISPLAYSIZE) { (*s)[DISPLAYSIZE] = 0; } @@ -1621,6 +1641,7 @@ bool renamed_building(const building * b) static int rename_cmd(unit * u, order * ord, char **s, const char *s2) { + char name[NAMESIZE]; assert(s2); if (!s2[0]) { cmistake(u, ord, 84, MSG_EVENT); @@ -1629,12 +1650,11 @@ static int rename_cmd(unit * u, order * ord, char **s, const char *s2) /* TODO: Validate to make sure people don't have illegal characters in * names, phishing-style? () come to mind. */ + strlcpy(name, s2, sizeof(name)); + unicode_utf8_trim(name); free(*s); - *s = _strdup(s2); - if (strlen(s2) >= NAMESIZE) { - (*s)[NAMESIZE] = 0; - } + *s = strdup(name); return 0; } @@ -1860,16 +1880,7 @@ int name_cmd(struct unit *u, struct order *ord) break; case P_REGION: - if (!b) { - cmistake(u, ord, 145, MSG_EVENT); - break; - } - if (building_owner(b) != u) { - cmistake(u, ord, 148, MSG_EVENT); - break; - } - - if (b != largestbuilding(r, get_cmp_region_owner(), false)) { + if (u->faction != region_get_owner(r)) { cmistake(u, ord, 147, MSG_EVENT); break; } @@ -2119,11 +2130,12 @@ int mail_cmd(unit * u, struct order *ord) int banner_cmd(unit * u, struct order *ord) { - init_order(ord); - const char * s = getstrtoken(); + const char * s; free(u->faction->banner); - u->faction->banner = s ? _strdup(s) : 0; + init_order(ord); + s = getstrtoken(); + u->faction->banner = s ? strdup(s) : 0; add_message(&u->faction->msgs, msg_message("changebanner", "value", u->faction->banner)); @@ -2183,6 +2195,7 @@ int password_cmd(unit * u, struct order *ord) faction_setpassword(u->faction, password_encode(pwbuf, PASSWORD_DEFAULT)); ADDMSG(&u->faction->msgs, msg_message("changepasswd", "value", pwbuf)); + u->faction->flags |= FFL_PWMSG; return 0; } @@ -2325,23 +2338,23 @@ static void display_race(unit * u, const race * rc) } } if (rc->battle_flags & BF_EQUIPMENT) { - if (wrptr(&bufp, &size, _snprintf(bufp, size, " %s", LOC(f->locale, "stat_equipment"))) != 0) + if (wrptr(&bufp, &size, snprintf(bufp, size, " %s", LOC(f->locale, "stat_equipment"))) != 0) WARN_STATIC_BUFFER(); } if (rc->battle_flags & BF_RES_PIERCE) { - if (wrptr(&bufp, &size, _snprintf(bufp, size, " %s", LOC(f->locale, "stat_pierce"))) != 0) + if (wrptr(&bufp, &size, snprintf(bufp, size, " %s", LOC(f->locale, "stat_pierce"))) != 0) WARN_STATIC_BUFFER(); } if (rc->battle_flags & BF_RES_CUT) { - if (wrptr(&bufp, &size, _snprintf(bufp, size, " %s", LOC(f->locale, "stat_cut"))) != 0) + if (wrptr(&bufp, &size, snprintf(bufp, size, " %s", LOC(f->locale, "stat_cut"))) != 0) WARN_STATIC_BUFFER(); } if (rc->battle_flags & BF_RES_BASH) { - if (wrptr(&bufp, &size, _snprintf(bufp, size, " %s", LOC(f->locale, "stat_bash"))) != 0) + if (wrptr(&bufp, &size, snprintf(bufp, size, " %s", LOC(f->locale, "stat_bash"))) != 0) WARN_STATIC_BUFFER(); } - if (wrptr(&bufp, &size, _snprintf(bufp, size, " %d %s", at_count, LOC(f->locale, (at_count == 1) ? "stat_attack" : "stat_attacks"))) != 0) + if (wrptr(&bufp, &size, snprintf(bufp, size, " %d %s", at_count, LOC(f->locale, (at_count == 1) ? "stat_attack" : "stat_attacks"))) != 0) WARN_STATIC_BUFFER(); for (a = 0; a < RACE_ATTACKS; a++) { @@ -2354,12 +2367,12 @@ static void display_race(unit * u, const race * rc) switch (rc->attack[a].type) { case AT_STANDARD: bytes = - (size_t)_snprintf(bufp, size, "%s (%s)", + (size_t)snprintf(bufp, size, "%s (%s)", LOC(f->locale, "attack_standard"), rc->def_damage); break; case AT_NATURAL: bytes = - (size_t)_snprintf(bufp, size, "%s (%s)", + (size_t)snprintf(bufp, size, "%s (%s)", LOC(f->locale, "attack_natural"), rc->attack[a].data.dice); break; case AT_SPELL: @@ -2367,11 +2380,11 @@ static void display_race(unit * u, const race * rc) case AT_DRAIN_ST: case AT_DRAIN_EXP: case AT_DAZZLE: - bytes = (size_t)_snprintf(bufp, size, "%s", LOC(f->locale, "attack_magical")); + bytes = (size_t)snprintf(bufp, size, "%s", LOC(f->locale, "attack_magical")); break; case AT_STRUCTURAL: bytes = - (size_t)_snprintf(bufp, size, "%s (%s)", + (size_t)snprintf(bufp, size, "%s (%s)", LOC(f->locale, "attack_structural"), rc->attack[a].data.dice); break; default: @@ -2408,12 +2421,12 @@ static void reshow_other(unit * u, struct order *ord, const char *s) { rc = findrace(s, u->faction->locale); if (itype) { - // if this is a potion, we need the right alchemy skill + /* if this is a potion, we need the right alchemy skill */ int i = i_get(u->items, itype); - err = 36; // we do not have this item? + err = 36; /* we do not have this item? */ if (i <= 0) { - // we don't have the item, but it may be a potion that we know + /* we don't have the item, but it may be a potion that we know */ const potion_type *ptype = resource2potion(item2resource(itype)); if (ptype) { if (2 * ptype->level > effskill(u, SK_ALCHEMY, 0)) { @@ -2550,7 +2563,7 @@ int guard_off_cmd(unit * u, struct order *ord) init_order(ord); if (getparam(u->faction->locale) == P_NOT) { - setguard(u, GUARD_NONE); + setguard(u, false); } return 0; } @@ -2639,7 +2652,7 @@ int combatspell_cmd(unit * u, struct order *ord) if (findparam(s, u->faction->locale) == P_LEVEL) { /* Merken, setzen kommt erst später */ level = getint(); - level = _max(0, level); + level = MAX(0, level); s = gettoken(token, sizeof(token)); } @@ -2665,20 +2678,6 @@ int combatspell_cmd(unit * u, struct order *ord) return 0; } -guard_t can_start_guarding(const unit * u) -{ - if (u->status >= ST_FLEE || fval(u, UFL_FLEEING)) - return E_GUARD_FLEEING; - /* Monster der Monsterpartei dürfen immer bewachen */ - if (is_monsters(u->faction) || fval(u_race(u), RCF_UNARMEDGUARD)) - return E_GUARD_OK; - if (!armedmen(u, true)) - return E_GUARD_UNARMED; - if (IsImmune(u->faction)) - return E_GUARD_NEWBIE; - return E_GUARD_OK; -} - int guard_on_cmd(unit * u, struct order *ord) { assert(getkeyword(ord) == K_GUARD); @@ -2706,7 +2705,7 @@ int guard_on_cmd(unit * u, struct order *ord) else { int err = can_start_guarding(u); if (err == E_GUARD_OK) { - guard(u, GUARD_ALL); + setguard(u, true); } else if (err == E_GUARD_UNARMED) { ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "unit_unarmed", "")); @@ -2732,13 +2731,13 @@ void sinkships(struct region * r) if (!sh->type->construction || sh->size >= sh->type->construction->maxsize) { if (fval(r->terrain, SEA_REGION)) { if (!enoughsailors(sh, crew_skill(sh))) { - // ship is at sea, but not enough people to control it + /* ship is at sea, but not enough people to control it */ double dmg = config_get_flt("rules.ship.damage.nocrewocean", 0.3); damage_ship(sh, dmg); } } else if (!ship_owner(sh)) { - // any ship lying around without an owner slowly rots + /* any ship lying around without an owner slowly rots */ double dmg = config_get_flt("rules.ship.damage.nocrew", 0.05); damage_ship(sh, dmg); } @@ -2751,74 +2750,6 @@ void sinkships(struct region * r) } } -static attrib_type at_number = { - "faction_renum", - NULL, NULL, NULL, NULL, NULL, NULL, - ATF_UNIQUE -}; - -void renumber_factions(void) -/* gibt parteien neue nummern */ -{ - struct renum { - struct renum *next; - int want; - faction *faction; - attrib *attrib; - } *renum = NULL, *rp; - faction *f; - for (f = factions; f; f = f->next) { - attrib *a = a_find(f->attribs, &at_number); - int want; - struct renum **rn; - faction *old; - - if (!a) - continue; - want = a->data.i; - if (fval(f, FFL_NEWID)) { - ADDMSG(&f->msgs, msg_message("renumber_twice", "id", want)); - continue; - } - old = findfaction(want); - if (old) { - a_remove(&f->attribs, a); - ADDMSG(&f->msgs, msg_message("renumber_inuse", "id", want)); - continue; - } - if (!faction_id_is_unused(want)) { - a_remove(&f->attribs, a); - ADDMSG(&f->msgs, msg_message("renumber_inuse", "id", want)); - continue; - } - for (rn = &renum; *rn; rn = &(*rn)->next) { - if ((*rn)->want >= want) - break; - } - if (*rn && (*rn)->want == want) { - ADDMSG(&f->msgs, msg_message("renumber_inuse", "id", want)); - } - else { - struct renum *r = calloc(sizeof(struct renum), 1); - r->next = *rn; - r->attrib = a; - r->faction = f; - r->want = want; - *rn = r; - } - } - for (rp = renum; rp; rp = rp->next) { - f = rp->faction; - a_remove(&f->attribs, rp->attrib); - renumber_faction(f, rp->want); - } - while (renum) { - rp = renum->next; - free(renum); - renum = rp; - } -} - void restack_units(void) { region *r; @@ -2906,121 +2837,6 @@ void restack_units(void) } } -int renumber_cmd(unit * u, order * ord) -{ - char token[128]; - const char *s; - int i; - faction *f = u->faction; - - init_order(ord); - s = gettoken(token, sizeof(token)); - switch (findparam_ex(s, u->faction->locale)) { - - case P_FACTION: - s = gettoken(token, sizeof(token)); - if (s && *s) { - int id = atoi36((const char *)s); - attrib *a = a_find(f->attribs, &at_number); - if (!a) - a = a_add(&f->attribs, a_new(&at_number)); - a->data.i = id; - } - break; - - case P_UNIT: - s = gettoken(token, sizeof(token)); - if (s == NULL || *s == 0) { - i = newunitid(); - } - else { - i = atoi36((const char *)s); - if (i <= 0 || i > MAX_UNIT_NR) { - cmistake(u, ord, 114, MSG_EVENT); - break; - } - - if (forbiddenid(i)) { - cmistake(u, ord, 116, MSG_EVENT); - break; - } - - if (findunitg(i, u->region)) { - cmistake(u, ord, 115, MSG_EVENT); - break; - } - } - renumber_unit(u, i); - break; - - case P_SHIP: - if (!u->ship) { - cmistake(u, ord, 144, MSG_EVENT); - break; - } - if (ship_owner(u->ship) != u) { - cmistake(u, ord, 146, MSG_EVENT); - break; - } - if (u->ship->coast != NODIRECTION) { - cmistake(u, ord, 116, MSG_EVENT); - break; - } - s = gettoken(token, sizeof(token)); - if (s == NULL || *s == 0) { - i = newcontainerid(); - } - else { - i = atoi36((const char *)s); - if (i <= 0 || i > MAX_CONTAINER_NR) { - cmistake(u, ord, 114, MSG_EVENT); - break; - } - if (findship(i) || findbuilding(i)) { - cmistake(u, ord, 115, MSG_EVENT); - break; - } - } - sunhash(u->ship); - u->ship->no = i; - shash(u->ship); - break; - case P_BUILDING: - case P_GEBAEUDE: - if (!u->building) { - cmistake(u, ord, 145, MSG_EVENT); - break; - } - if (building_owner(u->building) != u) { - cmistake(u, ord, 148, MSG_EVENT); - break; - } - s = gettoken(token, sizeof(token)); - if (*s == 0) { - i = newcontainerid(); - } - else { - i = atoi36((const char *)s); - if (i <= 0 || i > MAX_CONTAINER_NR) { - cmistake(u, ord, 114, MSG_EVENT); - break; - } - if (findship(i) || findbuilding(i)) { - cmistake(u, ord, 115, MSG_EVENT); - break; - } - } - bunhash(u->building); - u->building->no = i; - bhash(u->building); - break; - - default: - cmistake(u, ord, 239, MSG_EVENT); - } - return 0; -} - /* blesses stone circles create an astral protection in the astral region * above the shield, which prevents chaos suction and other spells. * The shield is created when a magician enters the blessed stone circle, @@ -3069,14 +2885,14 @@ static void age_stonecircle(building *b) { float effect = 100; /* the mage reactivates the circle */ c = create_curse(mage, &rt->attribs, ct_astralblock, - (float)_max(1, sk), _max(1, sk / 2), effect, 0); + (float)MAX(1, sk), MAX(1, sk / 2), effect, 0); ADDMSG(&r->msgs, msg_message("astralshield_activate", "region unit", r, mage)); } else { int sk = effskill(mage, SK_MAGIC, 0); - c->duration = _max(c->duration, sk / 2); - c->vigour = _max(c->vigour, (float)sk); + c->duration = MAX(c->duration, sk / 2); + c->vigour = MAX(c->vigour, (float)sk); } } } @@ -3121,12 +2937,12 @@ static void ageing(void) /* Goliathwasser */ int i = get_effect(u, oldpotiontype[P_STRONG]); if (i > 0) { - change_effect(u, oldpotiontype[P_STRONG], -1 * _min(u->number, i)); + change_effect(u, oldpotiontype[P_STRONG], -1 * MIN(u->number, i)); } /* Berserkerblut */ i = get_effect(u, oldpotiontype[P_BERSERK]); if (i > 0) { - change_effect(u, oldpotiontype[P_BERSERK], -1 * _min(u->number, i)); + change_effect(u, oldpotiontype[P_BERSERK], -1 * MIN(u->number, i)); } if (is_cursed(u->attribs, C_OLDRACE, 0)) { @@ -3160,9 +2976,9 @@ static void ageing(void) for (up = &r->units; *up;) { unit *u = *up; a_age(&u->attribs, u); - if (u == *up) + if (u == *up) handle_event(u->attribs, "timer", u); - if (u == *up) + if (u == *up) /*-V581 */ up = &(*up)->next; } @@ -3172,7 +2988,7 @@ static void ageing(void) a_age(&s->attribs, s); if (s == *sp) handle_event(s->attribs, "timer", s); - if (s == *sp) + if (s == *sp) /*-V581 */ sp = &(*sp)->next; } @@ -3200,7 +3016,7 @@ static int maxunits(const faction * f) if (flimit == 0) { return alimit; } - return _min(alimit, flimit); + return MIN(alimit, flimit); } int checkunitnumber(const faction * f, int add) @@ -3296,11 +3112,11 @@ void new_units(void) s = gettoken(token, sizeof(token)); if (s && s[0]) { - name = _strdup(s); + name = strdup(s); } u2 = create_unit(r, u->faction, 0, u->faction->race, alias, name, u); if (name != NULL) - free(name); // TODO: use a buffer on the stack instead? + free(name); /* TODO: use a buffer on the stack instead? */ fset(u2, UFL_ISNEW); a_add(&u2->attribs, a_new(&at_alias))->data.i = alias; @@ -3349,10 +3165,10 @@ void update_long_order(unit * u) free_orders(&u->old_orders); } - // hungry units do not get long orders: + /* hungry units do not get long orders: */ if (hunger) { if (u->old_orders) { - // keep looking for repeated orders that might clear the old_orders + /* keep looking for repeated orders that might clear the old_orders */ continue; } break; @@ -3360,19 +3176,19 @@ void update_long_order(unit * u) if (is_long(kwd)) { if (thiskwd == NOKEYWORD) { - // we have found the (first) long order - // some long orders can have multiple instances: + /* we have found the (first) long order + * some long orders can have multiple instances: */ switch (kwd) { /* Wenn gehandelt wird, darf kein langer Befehl ausgeführt - * werden. Da Handel erst nach anderen langen Befehlen kommt, - * muss das vorher abgefangen werden. Wir merken uns also - * hier, ob die Einheit handelt. */ + * werden. Da Handel erst nach anderen langen Befehlen kommt, + * muss das vorher abgefangen werden. Wir merken uns also + * hier, ob die Einheit handelt. */ case K_BUY: case K_SELL: case K_CAST: - // non-exclusive orders can be used with others. BUY can be paired with SELL, - // CAST with other CAST orders. compatibility is checked once the second - // long order is analyzed (below). + /* non-exclusive orders can be used with others. BUY can be paired with SELL, + * CAST with other CAST orders. compatibility is checked once the second + * long order is analyzed (below). */ exclusive = false; break; @@ -3383,8 +3199,8 @@ void update_long_order(unit * u) thiskwd = kwd; } else { - // we have found a second long order. this is okay for some, but not all commands. - // u->thisorder is already set, and should not have to be updated. + /* we have found a second long order. this is okay for some, but not all commands. + * u->thisorder is already set, and should not have to be updated. */ switch (kwd) { case K_CAST: if (thiskwd != K_CAST) { @@ -3405,9 +3221,8 @@ void update_long_order(unit * u) } break; default: - // TODO: decide https://bugs.eressea.de/view.php?id=2080#c6011 if (kwd > thiskwd) { - // swap out thisorder for the new one + /* swap out thisorder for the new one */ cmistake(u, u->thisorder, 52, MSG_EVENT); set_order(&u->thisorder, copy_order(ord)); } @@ -3420,11 +3235,11 @@ void update_long_order(unit * u) } } if (hunger) { - // Hungernde Einheiten führen NUR den default-Befehl aus + /* Hungernde Einheiten führen NUR den default-Befehl aus */ set_order(&u->thisorder, default_order(u->faction->locale)); } else if (!exclusive) { - // Wenn die Einheit handelt oder zaubert, muss der Default-Befehl gelöscht werden. + /* Wenn die Einheit handelt oder zaubert, muss der Default-Befehl gelöscht werden. */ set_order(&u->thisorder, NULL); } } @@ -3432,11 +3247,6 @@ void update_long_order(unit * u) static int use_item(unit * u, const item_type * itype, int amount, struct order *ord) { int i; - int target = -1; - - if (itype->useonother) { - target = read_unitid(u->faction, u->region); - } i = get_pooled(u, itype->rtype, GET_DEFAULT, amount); if (amount > i) { @@ -3447,43 +3257,14 @@ static int use_item(unit * u, const item_type * itype, int amount, struct order return ENOITEM; } - if (target == -1) { - if (itype->use) { - int result = itype->use(u, itype, amount, ord); - if (result > 0) { - use_pooled(u, itype->rtype, GET_DEFAULT, result); - } - return result; + if (itype->flags & ITF_CANUSE) { + int result = item_use_fun(u, itype, amount, ord); + if (result > 0) { + use_pooled(u, itype->rtype, GET_DEFAULT, result); } - return EUNUSABLE; + return result; } - else { - return itype->useonother(u, target, itype, amount, ord); - } -} - -static double heal_factor(const unit * u) -{ - const race * rc = u_race(u); - if (rc->healing>0) { - return rc->healing; - } - if (r_isforest(u->region)) { - static int rc_cache; - static const race *rc_elf; - if (rc_changed(&rc_cache)) { - rc_elf = get_race(RC_ELF); - } - if (rc==rc_elf) { - static int config; - static double elf_regen = 1.0; - if (config_changed(&config)) { - elf_regen = get_param_flt(u_race(u)->parameters, "regen.forest", 1.0F); - } - return elf_regen; - } - } - return 1.0; + return EUNUSABLE; } void monthly_healing(void) @@ -3525,9 +3306,9 @@ void monthly_healing(void) continue; } - p *= heal_factor(u); + p *= u_heal_factor(u); if (u->hp < umhp) { - double maxheal = _max(u->number, umhp / 20.0); + double maxheal = MAX(u->number, umhp / 20.0); int addhp; if (active_building(u, bt_find("inn"))) { p *= 1.5; @@ -3542,7 +3323,7 @@ void monthly_healing(void) ++addhp; /* Aufaddieren der geheilten HP. */ - u->hp = _min(u->hp + addhp, umhp); + u->hp = MIN(u->hp + addhp, umhp); /* soll man an negativer regeneration sterben können? */ assert(u->hp > 0); @@ -3592,7 +3373,7 @@ void defaultorders(void) free_order(ord); if (!neworders) { /* lange Befehle aus orders und old_orders löschen zu gunsten des neuen */ - // TODO: why only is_exclusive, not is_long? what about CAST, BUY, SELL? + /* TODO: why only is_exclusive, not is_long? what about CAST, BUY, SELL? */ remove_exclusive(&u->orders); remove_exclusive(&u->old_orders); neworders = true; @@ -3644,10 +3425,10 @@ static void copy_spells(const spellbook * src, spellbook * dst, int maxlevel) { assert(dst); if (src && src->spells) { - quicklist *ql; + selist *ql; int qi; - for (qi = 0, ql = src->spells; ql; ql_advance(&ql, &qi, 1)) { - spellbook_entry * sbe = (spellbook_entry *)ql_get(ql, qi); + for (qi = 0, ql = src->spells; ql; selist_advance(&ql, &qi, 1)) { + spellbook_entry * sbe = (spellbook_entry *)selist_get(ql, qi); if (sbe->level <= maxlevel) { if (!spellbook_get(dst, sbe->sp)) { spellbook_add(dst, sbe->sp, sbe->level); @@ -3705,7 +3486,7 @@ int use_cmd(unit * u, struct order *ord) cmistake(u, ord, 43, MSG_PRODUCE); return err; } - n = atoi((const char *)t); + n = atoip((const char *)t); if (n == 0) { if (isparam(t, u->faction->locale, P_ANY)) { /* BENUTZE ALLES Yanxspirit */ @@ -3737,7 +3518,7 @@ int use_cmd(unit * u, struct order *ord) cmistake(u, ord, 50, MSG_PRODUCE); break; default: - // no error + /* no error */ break; } return err; @@ -3749,12 +3530,13 @@ int pay_cmd(unit * u, struct order *ord) cmistake(u, ord, 6, MSG_EVENT); } else { + building *b = NULL; param_t p; int id; + init_order(ord); p = getparam(u->faction->locale); id = getid(); - building *b = NULL; if (p == P_NOT) { unit *owner = building_owner(u->building); /* If the unit is not the owner of the building: error */ @@ -3801,7 +3583,7 @@ int pay_cmd(unit * u, struct order *ord) static int reserve_i(unit * u, struct order *ord, int flags) { char token[128]; - if (u->number > 0 && (urace(u)->ec_flags & GETITEM)) { + if (u->number > 0 && (u_race(u)->ec_flags & GETITEM)) { int use, count, para; const item_type *itype; const char *s; @@ -3853,7 +3635,7 @@ int claim_cmd(unit * u, struct order *ord) t = gettoken(token, sizeof(token)); if (t) { - n = atoi((const char *)t); + n = atoip((const char *)t); if (n == 0) { n = 1; } @@ -3867,7 +3649,7 @@ int claim_cmd(unit * u, struct order *ord) if (itype) { item **iclaim = i_find(&u->faction->items, itype); if (iclaim && *iclaim) { - n = _min(n, (*iclaim)->number); + n = MIN(n, (*iclaim)->number); i_change(iclaim, itype, -n); i_change(&u->items, itype, n); } @@ -4110,7 +3892,7 @@ int armedmen(const unit * u, bool siege_weapons) { item *itm; int n = 0; - if (!(urace(u)->flags & RCF_NOWEAPONS)) { + if (!(u_race(u)->flags & RCF_NOWEAPONS)) { if (effskill(u, SK_WEAPONLESS, 0) >= 1) { /* kann ohne waffen bewachen: fuer drachen */ n = u->number; @@ -4125,10 +3907,10 @@ int armedmen(const unit * u, bool siege_weapons) if (effskill(u, wtype->skill, 0) >= wtype->minskill) n += itm->number; /* if (effskill(u, wtype->skill) >= wtype->minskill) n += itm->number; */ - if (n > u->number) + if (n >= u->number) break; } - n = _min(n, u->number); + n = MIN(n, u->number); } } return n; @@ -4164,9 +3946,9 @@ int siege_cmd(unit * u, order * ord) rt_catapult = rt_find("catapult"); d = i_get(u->items, rt_catapult->itype); - d = _min(u->number, d); + d = MIN(u->number, d); pooled = get_pooled(u, rt_catapultammo, GET_DEFAULT, d); - d = _min(pooled, d); + d = MIN(pooled, d); if (effskill(u, SK_CATAPULT, 0) >= 1) { katapultiere = d; d *= effskill(u, SK_CATAPULT, 0); @@ -4182,7 +3964,7 @@ int siege_cmd(unit * u, order * ord) return 80; } - if (!is_guard(u, GUARD_TRAVELTHRU)) { + if (!is_guard(u)) { /* abbruch, wenn die einheit nicht vorher die region bewacht - als * warnung fuer alle anderen! */ cmistake(u, ord, 81, MSG_EVENT); @@ -4193,11 +3975,11 @@ int siege_cmd(unit * u, order * ord) * einheiten wieder abgesucht werden muessen! */ usetsiege(u, b); - b->besieged += _max(bewaffnete, katapultiere); + b->besieged += MAX(bewaffnete, katapultiere); /* definitiver schaden eingeschraenkt */ - d = _min(d, b->size - 1); + d = MIN(d, b->size - 1); /* meldung, schaden anrichten */ if (d && !curse_active(get_curse(b->attribs, magicwalls_ct))) { @@ -4409,16 +4191,54 @@ void init_processor(void) } } -void processorders(void) +static void reset_game(void) +{ + region *r; + faction *f; + for (r = regions; r; r = r->next) { + unit *u; + building *b; + r->flags &= RF_SAVEMASK; + for (u = r->units; u; u = u->next) { + u->flags &= UFL_SAVEMASK; + } + for (b = r->buildings; b; b = b->next) { + b->flags &= BLD_SAVEMASK; + } + if (r->land && r->land->ownership && r->land->ownership->owner) { + faction *owner = r->land->ownership->owner; + if (owner == get_monsters()) { + /* some compat-fix, i believe. */ + owner = update_owners(r); + } + if (owner) { + fset(r, RF_GUARDED); + } + } + } + for (f = factions; f; f = f->next) { + f->flags &= FFL_SAVEMASK; + } +} + +void turn_begin(void) +{ + ++turn; + reset_game(); +} + +void turn_process(void) { init_processor(); process(); - /*************************************************/ if (config_get_int("modules.markets", 0)) { do_markets(); } +} +void turn_end(void) +{ log_info(" - Attribute altern"); ageing(); remove_empty_units(); @@ -4433,10 +4253,17 @@ void processorders(void) update_spells(); } +void processorders(void) +{ + turn_begin(); + turn_process(); + turn_end(); +} + void update_subscriptions(void) { FILE *F; - char zText[MAX_PATH]; + char zText[4096]; join_path(basepath(), "subscriptions", zText, sizeof(zText)); F = fopen(zText, "r"); @@ -4496,7 +4323,7 @@ cansee(const faction * f, const region * r, const unit * u, int modifier) return false; /* simple visibility, just gotta have a unit in the region to see 'em */ - if (is_guard(u, GUARD_ALL) != 0 || usiege(u) || u->building || u->ship) { + if (is_guard(u) || usiege(u) || u->building || u->ship) { return true; } @@ -4535,7 +4362,7 @@ bool cansee_unit(const unit * u, const unit * target, int modifier) else { int n, rings, o; - if (is_guard(target, GUARD_ALL) != 0 || usiege(target) || target->building + if (is_guard(target) || usiege(target) || target->building || target->ship) { return true; } @@ -4579,7 +4406,7 @@ cansee_durchgezogen(const faction * f, const region * r, const unit * u, else { int rings; - if (is_guard(u, GUARD_ALL) != 0 || usiege(u) || u->building || u->ship) { + if (is_guard(u) || usiege(u) || u->building || u->ship) { return true; } diff --git a/src/laws.h b/src/laws.h index 6c8633536..090d2b978 100755 --- a/src/laws.h +++ b/src/laws.h @@ -20,7 +20,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #define H_GC_LAWS #include -#include "guard.h" +#include #ifdef __cplusplus extern "C" { @@ -53,14 +53,15 @@ extern "C" { int enter_building(struct unit *u, struct order *ord, int id, bool report); int enter_ship(struct unit *u, struct order *ord, int id, bool report); - /* eressea-specific. put somewhere else, please. */ void processorders(void); + void turn_begin(void); + void turn_process(void); + void turn_end(void); void new_units(void); void defaultorders(void); void quit(void); void monthly_healing(void); - void renumber_factions(void); void restack_units(void); void update_long_order(struct unit *u); void sinkships(struct region * r); @@ -84,7 +85,6 @@ extern "C" { int leave_cmd(struct unit *u, struct order *ord); int pay_cmd(struct unit *u, struct order *ord); int promotion_cmd(struct unit *u, struct order *ord); - int renumber_cmd(struct unit *u, struct order *ord); int combatspell_cmd(struct unit *u, struct order *ord); int contact_cmd(struct unit *u, struct order *ord); int guard_on_cmd(struct unit *u, struct order *ord); @@ -111,8 +111,11 @@ extern "C" { #define FORCE_LEAVE_POSTCOMBAT 1 #define FORCE_LEAVE_ALL 2 bool rule_force_leave(int flag); + bool LongHunger(const struct unit *u); + int NMRTimeout(void); + int NewbieImmunity(void); + bool IsImmune(const struct faction *f); bool help_enter(struct unit *uo, struct unit *u); - guard_t can_start_guarding(const struct unit * u); #ifdef __cplusplus } diff --git a/src/laws.test.c b/src/laws.test.c index 66cb5ef10..c27651d83 100644 --- a/src/laws.test.c +++ b/src/laws.test.c @@ -1,7 +1,8 @@ #include #include "laws.h" #include "battle.h" -#include "monster.h" +#include "guard.h" +#include "monsters.h" #include #include @@ -228,6 +229,11 @@ static void test_display_cmd(CuTest *tc) { CuAssertPtrEquals(tc, NULL, u->display); free_order(ord); + ord = create_order(K_DISPLAY, f->locale, "%s Hodor", LOC(f->locale, parameters[P_REGION])); + CuAssertIntEquals(tc, 0, display_cmd(u, ord)); + CuAssertPtrEquals(tc, NULL, r->display); + free_order(ord); + test_cleanup(); } @@ -520,7 +526,6 @@ static void test_pay_cmd_other_building(CuTest *tc) { order *ord; faction *f; building *b; - char cmd[32]; test_setup(); setup_pay_cmd(&fix); @@ -530,8 +535,7 @@ static void test_pay_cmd_other_building(CuTest *tc) { config_set("rules.region_owner_pay_building", "lighthouse"); update_owners(b->region); - _snprintf(cmd, sizeof(cmd), "NOT %s", itoa36(b->no)); - ord = create_order(K_PAY, f->locale, cmd); + ord = create_order(K_PAY, f->locale, "NOT %s", itoa36(b->no)); assert(ord); CuAssertPtrEquals(tc, fix.u1, building_owner(b)); CuAssertIntEquals(tc, 0, pay_cmd(fix.u1, ord)); @@ -607,7 +611,7 @@ void setup_guard(guard_fixture *fix, bool armed) { if (armed) { item_type *itype; itype = it_get_or_create(rt_get_or_create("sword")); - new_weapontype(itype, 0, 0.0, NULL, 0, 0, 0, SK_MELEE, 2); + new_weapontype(itype, 0, frac_zero, NULL, 0, 0, 0, SK_MELEE, 2); i_change(&u->items, itype, 1); set_level(u, SK_MELEE, 2); } @@ -754,8 +758,9 @@ static void test_peasant_luck_effect(CuTest *tc) { static void test_luck_message(CuTest *tc) { region* r; + attrib *a; - test_cleanup(); + test_setup(); r = test_create_region(0, 0, NULL); rsetpeasants(r, 1); @@ -763,7 +768,7 @@ static void test_luck_message(CuTest *tc) { CuAssertPtrEquals_Msg(tc, "unexpected message", (void *)NULL, r->msgs); - attrib *a = (attrib *)a_find(r->attribs, &at_peasantluck); + a = (attrib *)a_find(r->attribs, &at_peasantluck); if (!a) a = a_add(&r->attribs, a_new(&at_peasantluck)); a->data.i += 10; @@ -778,7 +783,7 @@ static void test_luck_message(CuTest *tc) { static unit * setup_name_cmd(void) { faction *f; - test_cleanup(); + test_setup(); f = test_create_faction(0); return test_create_unit(f, test_create_region(0, 0, 0)); } @@ -813,10 +818,7 @@ static void test_name_region(CuTest *tc) { f = u->faction; ord = create_order(K_NAME, f->locale, "%s Hodor", LOC(f->locale, parameters[P_REGION])); - name_cmd(u, ord); - CuAssertPtrNotNull(tc, test_find_messagetype(f->msgs, "error145")); - - u->building = test_create_building(u->region, 0); + u_set_building(u, test_create_building(u->region, 0)); name_cmd(u, ord); CuAssertStrEquals(tc, "Hodor", u->region->land->name); free_order(ord); @@ -885,7 +887,7 @@ static void test_name_ship(CuTest *tc) { } static void test_long_order_normal(CuTest *tc) { - // TODO: write more tests + /* TODO: write more tests */ unit *u; order *ord; @@ -905,7 +907,7 @@ static void test_long_order_normal(CuTest *tc) { } static void test_long_order_none(CuTest *tc) { - // TODO: write more tests + /* TODO: write more tests */ unit *u; test_cleanup(); u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); @@ -917,7 +919,7 @@ static void test_long_order_none(CuTest *tc) { } static void test_long_order_cast(CuTest *tc) { - // TODO: write more tests + /* TODO: write more tests */ unit *u; test_cleanup(); u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); @@ -931,7 +933,7 @@ static void test_long_order_cast(CuTest *tc) { } static void test_long_order_buy_sell(CuTest *tc) { - // TODO: write more tests + /* TODO: write more tests */ unit *u; test_cleanup(); u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); @@ -946,7 +948,7 @@ static void test_long_order_buy_sell(CuTest *tc) { } static void test_long_order_multi_long(CuTest *tc) { - // TODO: write more tests + /* TODO: write more tests */ unit *u; test_cleanup(); u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); @@ -960,7 +962,7 @@ static void test_long_order_multi_long(CuTest *tc) { } static void test_long_order_multi_buy(CuTest *tc) { - // TODO: write more tests + /* TODO: write more tests */ unit *u; test_cleanup(); u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); @@ -974,7 +976,7 @@ static void test_long_order_multi_buy(CuTest *tc) { } static void test_long_order_multi_sell(CuTest *tc) { - // TODO: write more tests + /* TODO: write more tests */ unit *u; test_cleanup(); u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); @@ -989,7 +991,7 @@ static void test_long_order_multi_sell(CuTest *tc) { } static void test_long_order_buy_cast(CuTest *tc) { - // TODO: write more tests + /* TODO: write more tests */ unit *u; test_cleanup(); u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); @@ -1023,7 +1025,7 @@ static void test_ally_cmd_errors(CuTest *tc) { int fid; order *ord; - test_cleanup(); + test_setup(); u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); fid = u->faction->no + 1; CuAssertPtrEquals(tc, 0, findfaction(fid)); @@ -1036,12 +1038,81 @@ static void test_ally_cmd_errors(CuTest *tc) { test_cleanup(); } +static void test_name_cmd(CuTest *tc) { + unit *u; + faction *f; + order *ord; + + test_setup(); + u = test_create_unit(f = test_create_faction(0), test_create_region(0, 0, 0)); + + ord = create_order(K_NAME, f->locale, "%s ' Ho\tdor '", LOC(f->locale, parameters[P_UNIT])); + name_cmd(u, ord); + CuAssertStrEquals(tc, "Hodor", u->_name); + free_order(ord); + + ord = create_order(K_NAME, f->locale, "%s ' Ho\tdor '", LOC(f->locale, parameters[P_FACTION])); + name_cmd(u, ord); + CuAssertStrEquals(tc, "Hodor", f->name); + free_order(ord); + + ord = create_order(K_NAME, f->locale, "%s ' Ho\tdor '", LOC(f->locale, parameters[P_SHIP])); + u->ship = test_create_ship(u->region, 0); + name_cmd(u, ord); + CuAssertStrEquals(tc, "Hodor", u->ship->name); + free_order(ord); + + ord = create_order(K_NAME, f->locale, "%s ' Ho\tdor '", LOC(f->locale, parameters[P_BUILDING])); + u_set_building(u, test_create_building(u->region, 0)); + name_cmd(u, ord); + CuAssertStrEquals(tc, "Hodor", u->building->name); + free_order(ord); + + ord = create_order(K_NAME, f->locale, "%s ' Ho\tdor '", LOC(f->locale, parameters[P_REGION])); + name_cmd(u, ord); + CuAssertStrEquals(tc, "Hodor", u->region->land->name); + free_order(ord); + + test_cleanup(); +} + +static void test_name_cmd_2274(CuTest *tc) { + unit *u1, *u2, *u3; + faction *f; + region *r; + + test_setup(); + r = test_create_region(0, 0, 0); + u1 = test_create_unit(test_create_faction(0), r); + u2 = test_create_unit(test_create_faction(0), r); + u3 = test_create_unit(u2->faction, r); + u_set_building(u1, test_create_building(r, NULL)); + u1->building->size = 10; + u_set_building(u2, test_create_building(r, NULL)); + u2->building->size = 20; + + f = u2->faction; + u2->thisorder = create_order(K_NAME, f->locale, "%s Heimat", LOC(f->locale, parameters[P_REGION])); + name_cmd(u2, u2->thisorder); + CuAssertStrEquals(tc, "Heimat", r->land->name); + f = u3->faction; + u3->thisorder = create_order(K_NAME, f->locale, "%s Hodor", LOC(f->locale, parameters[P_REGION])); + name_cmd(u3, u3->thisorder); + CuAssertStrEquals(tc, "Hodor", r->land->name); + f = u1->faction; + u1->thisorder = create_order(K_NAME, f->locale, "%s notallowed", LOC(f->locale, parameters[P_REGION])); + name_cmd(u1, u1->thisorder); + CuAssertStrEquals(tc, "Hodor", r->land->name); + + test_cleanup(); +} + static void test_ally_cmd(CuTest *tc) { unit *u; faction * f; order *ord; - test_cleanup(); + test_setup(); u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); f = test_create_faction(0); @@ -1402,11 +1473,49 @@ static void test_demon_hunger(CuTest * tc) test_cleanup(); } +static void test_armedmen(CuTest *tc) { + /* TODO: test RCF_NOWEAPONS and SK_WEAPONLESS */ + unit *u; + item_type *it_sword; + weapon_type *wtype; + test_setup(); + u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); + it_sword = test_create_itemtype("sword"); + wtype = new_weapontype(it_sword, 0, frac_make(1, 2), 0, 0, 0, 0, SK_MELEE, 1); + CuAssertIntEquals(tc, 0, armedmen(u, false)); + CuAssertIntEquals(tc, 0, armedmen(u, true)); + set_level(u, SK_MELEE, 1); + CuAssertIntEquals(tc, 0, armedmen(u, false)); + i_change(&u->items, it_sword, 1); + CuAssertIntEquals(tc, 1, armedmen(u, false)); + i_change(&u->items, it_sword, 1); + CuAssertIntEquals(tc, 1, armedmen(u, false)); + scale_number(u, 2); + set_level(u, SK_MELEE, 1); + CuAssertIntEquals(tc, 2, armedmen(u, false)); + set_level(u, SK_MELEE, 0); + CuAssertIntEquals(tc, 0, armedmen(u, false)); + set_level(u, SK_MELEE, 1); + i_change(&u->items, it_sword, -1); + CuAssertIntEquals(tc, 1, armedmen(u, false)); + wtype->minskill = 2; + CuAssertIntEquals(tc, 0, armedmen(u, false)); + set_level(u, SK_MELEE, 2); + CuAssertIntEquals(tc, 1, armedmen(u, false)); + CuAssertIntEquals(tc, 1, armedmen(u, true)); + wtype->flags |= WTF_SIEGE; + CuAssertIntEquals(tc, 0, armedmen(u, false)); + CuAssertIntEquals(tc, 1, armedmen(u, true)); + test_cleanup(); +} + CuSuite *get_laws_suite(void) { CuSuite *suite = CuSuiteNew(); SUITE_ADD_TEST(suite, test_nmr_warnings); SUITE_ADD_TEST(suite, test_ally_cmd); + SUITE_ADD_TEST(suite, test_name_cmd); + SUITE_ADD_TEST(suite, test_name_cmd_2274); SUITE_ADD_TEST(suite, test_ally_cmd_errors); SUITE_ADD_TEST(suite, test_long_order_normal); SUITE_ADD_TEST(suite, test_long_order_none); @@ -1464,6 +1573,7 @@ CuSuite *get_laws_suite(void) SUITE_ADD_TEST(suite, test_show_race); SUITE_ADD_TEST(suite, test_immigration); SUITE_ADD_TEST(suite, test_demon_hunger); + SUITE_ADD_TEST(suite, test_armedmen); return suite; } diff --git a/src/lighthouse.c b/src/lighthouse.c index 96b42b333..d29d58b71 100644 --- a/src/lighthouse.c +++ b/src/lighthouse.c @@ -14,9 +14,9 @@ #include #include -const attrib_type at_lighthouse = { +attrib_type at_lighthouse = { "lighthouse" - /* Rest ist NULL; temporres, nicht alterndes Attribut */ + /* Rest ist NULL; tempor�res, nicht alterndes Attribut */ }; /* update_lighthouse: call this function whenever the size of a lighthouse changes @@ -73,20 +73,18 @@ int lighthouse_range(const building * b, const faction * f) region *r = b->region; int c = 0; int cap = buildingcapacity(b); - unit *u; + unit *u, *uown = building_owner(b); for (u = r->units; u; u = u->next) { - if (u->building == b || u == building_owner(b)) { - if (u->building == b) { - c += u->number; - } + if (u->building == b || u == uown) { + c += u->number; if (c > cap) { break; } else if (f == NULL || u->faction == f) { int sk = effskill(u, SK_PERCEPTION, 0) / 3; - d = _max(d, sk); - d = _min(maxd, d); + d = MAX(d, sk); + d = MIN(maxd, d); if (d == maxd) break; } @@ -129,7 +127,7 @@ bool check_leuchtturm(region * r, faction * f) c += u->number; if (c > buildingcapacity(b)) break; - if (f == NULL || u->faction == f) { + if (u->faction == f) { if (!d) d = distance(r, r2); if (maxd < d) diff --git a/src/lighthouse.h b/src/lighthouse.h index 518b05b5a..f2974ddf1 100644 --- a/src/lighthouse.h +++ b/src/lighthouse.h @@ -19,6 +19,8 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef LIGHTHOUSE_H #define LIGHTHOUSE_H +#include + #ifdef __cplusplus extern "C" { #endif @@ -29,7 +31,7 @@ extern "C" { struct building; struct attrib; - extern const struct attrib_type at_lighthouse; + extern struct attrib_type at_lighthouse; /* leuchtturm */ bool check_leuchtturm(struct region *r, struct faction *f); void update_lighthouse(struct building *lh); diff --git a/src/listbox.c b/src/listbox.c index 3686cbba1..057240fad 100644 --- a/src/listbox.c +++ b/src/listbox.c @@ -27,7 +27,7 @@ insert_selection(list_selection ** p_sel, list_selection * prev, const char *str, void *payload) { list_selection *sel = calloc(sizeof(list_selection), 1); - sel->str = _strdup(str); + sel->str = strdup(str); sel->data = payload; if (*p_sel) { list_selection *s; @@ -88,7 +88,6 @@ list_selection *do_selection(list_selection * sel, const char *title, width = (int)strlen(s->str); } ++height; - log_debug("s %s w %d h %d\n", s->str, width, height); } if (height == 0 || width == 0) return 0; @@ -97,8 +96,6 @@ list_selection *do_selection(list_selection * sel, const char *title, if (height + 2 > SY) height = SY - 2; - log_debug("w %d h %d\n", width, height); - wn = newwin(height + 2, width + 4, (SY - height - 2) / 2, (SX - width - 4) / 2); diff --git a/src/magic.c b/src/magic.c index 83899f583..de1336d66 100644 --- a/src/magic.c +++ b/src/magic.c @@ -1,4 +1,4 @@ -/* +/* Copyright (c) 1998-2014, Enno Rehling Katja Zedel #include #include -#include #include #include #include @@ -59,7 +58,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include +#include #include #include #include @@ -119,7 +118,7 @@ static double MagicPower(double force) if (force > 0) { const char *str = config_get("magic.power"); double value = str ? atof(str) : 1.0; - return _max(value * force, 1.0f); + return MAX(value * force, 1.0f); } return 0; } @@ -147,7 +146,7 @@ static void a_writeicastle(const attrib * a, const void *owner, struct storage *store) { icastle_data *data = (icastle_data *)a->data.v; - unused_arg(owner); + UNUSED_ARG(owner); WRITE_TOK(store, data->type->_name); WRITE_INT(store, data->time); } @@ -174,7 +173,7 @@ static void a_initicastle(struct attrib *a) a->data.v = calloc(sizeof(icastle_data), 1); } -static void a_finalizeicastle(struct attrib *a) +static void a_finalizeicastle(struct attrib *a) /*-V524 */ { free(a->data.v); } @@ -225,10 +224,14 @@ static void free_mage(attrib * a) bool FactionSpells(void) { - return config_get_int("rules.magic.factionlist", 0) != 0; + static int config, rule; + if (config_changed(&config)) { + rule = config_get_int("rules.magic.factionlist", 0); + } + return rule != 0; } -void read_spells(struct quicklist **slistp, magic_t mtype, +void read_spells(struct selist **slistp, magic_t mtype, struct storage *store) { for (;;) { @@ -302,13 +305,13 @@ static int read_mage(attrib * a, void *owner, struct gamedata *data) return AT_READ_OK; } -void write_spells(struct quicklist *slist, struct storage *store) +void write_spells(struct selist *slist, struct storage *store) { - quicklist *ql; + selist *ql; int qi; - for (ql = slist, qi = 0; ql; ql_advance(&ql, &qi, 1)) { - spell *sp = (spell *)ql_get(ql, qi); + for (ql = slist, qi = 0; ql; selist_advance(&ql, &qi, 1)) { + spell *sp = (spell *)selist_get(ql, qi); WRITE_TOK(store, sp->sname); } WRITE_TOK(store, "end"); @@ -344,7 +347,7 @@ attrib_type at_mage = { bool is_mage(const unit * u) { - return i2b(get_mage(u) != NULL); + return get_mage(u) != NULL; } sc_mage *get_mage(const unit * u) @@ -373,7 +376,7 @@ static int read_seenspell(attrib * a, void *owner, struct gamedata *data) char token[32]; READ_TOK(store, token, sizeof(token)); - i = atoi(token); + i = atoip(token); if (i != 0) { sp = find_spellbyid((unsigned int)i); } @@ -421,13 +424,12 @@ static bool already_seen(const faction * f, const spell * sp) void show_new_spells(faction * f, int level, const spellbook *book) { if (book) { - quicklist *ql = book->spells; + selist *ql = book->spells; int qi; - for (qi = 0; ql; ql_advance(&ql, &qi, 1)) { - spellbook_entry *sbe = (spellbook_entry *)ql_get(ql, qi); + for (qi = 0; ql; selist_advance(&ql, &qi, 1)) { + spellbook_entry *sbe = (spellbook_entry *)selist_get(ql, qi); if (sbe->level <= level) { - if (!already_seen(f, sbe->sp)) { attrib * a = a_new(&at_reportspell); spellbook_entry * entry = (spellbook_entry *)a->data.v; @@ -448,14 +450,14 @@ void pick_random_spells(faction * f, int level, spellbook * book, int num_spells { spellbook_entry *commonspells[MAXSPELLS]; int qi, numspells = 0; - quicklist *ql; + selist *ql; if (level <= f->max_spelllevel) { return; } - for (qi = 0, ql = book->spells; ql; ql_advance(&ql, &qi, 1)) { - spellbook_entry * sbe = (spellbook_entry *)ql_get(ql, qi); + for (qi = 0, ql = book->spells; ql; selist_advance(&ql, &qi, 1)) { + spellbook_entry * sbe = (spellbook_entry *)selist_get(ql, qi); if (sbe->level <= level) { commonspells[numspells++] = sbe; } @@ -473,18 +475,20 @@ void pick_random_spells(faction * f, int level, spellbook * book, int num_spells spellno = rng_int() % maxspell; sbe = commonspells[spellno]; if (sbe->level > f->max_spelllevel) { - // not going to pick it in this round, move it to the end for later + /* not going to pick it in this round, move it to the end for later */ commonspells[spellno] = commonspells[--maxspell]; commonspells[maxspell] = sbe; sbe = 0; } - else if (f->spellbook && spellbook_get(f->spellbook, sbe->sp)) { - // already have this spell, remove it from the list of candidates - commonspells[spellno] = commonspells[--numspells]; - if (maxspell > numspells) { - maxspell = numspells; + else { + if (f->spellbook && spellbook_get(f->spellbook, sbe->sp)) { + /* already have this spell, remove it from the list of candidates */ + commonspells[spellno] = commonspells[--numspells]; + if (maxspell > numspells) { + maxspell = numspells; + } + sbe = 0; } - sbe = 0; } } @@ -540,7 +544,7 @@ int get_combatspelllevel(const unit * u, int nr) assert(nr < MAXCOMBATSPELLS); if (m) { int level = effskill(u, SK_MAGIC, 0); - return _min(m->combatspells[nr].level, level); + return MIN(m->combatspells[nr].level, level); } return -1; } @@ -557,10 +561,6 @@ const spell *get_combatspell(const unit * u, int nr) if (m) { return m->combatspells[nr].sp; } - else if (u_race(u)->precombatspell != NULL) { - return u_race(u)->precombatspell; - } - return NULL; } @@ -676,7 +676,7 @@ int change_spellpoints(unit * u, int mp) } /* verhindere negative Magiepunkte */ - sp = _max(m->spellpoints + mp, 0); + sp = MAX(m->spellpoints + mp, 0); m->spellpoints = sp; return sp; @@ -712,7 +712,7 @@ static int use_item_aura(const region * r, const unit * u) int sk, n; sk = effskill(u, SK_MAGIC, r); - n = (int)(sk * sk * u_race(u)->maxaura / 4); + n = (int)(sk * sk * rc_maxaura(u_race(u)) / 4); return n; } @@ -720,13 +720,13 @@ static int use_item_aura(const region * r, const unit * u) int max_spellpoints(const region * r, const unit * u) { int sk; - double n, msp; + double n, msp = 0; double potenz = 2.1; double divisor = 1.2; const struct resource_type *rtype; sk = effskill(u, SK_MAGIC, r); - msp = u_race(u)->maxaura * (pow(sk, potenz) / divisor + 1) + get_spchange(u); + msp = rc_maxaura(u_race(u)) * (pow(sk, potenz) / divisor + 1) + get_spchange(u); rtype = rt_find("aurafocus"); if (rtype && i_get(u->items, rtype->itype) > 0) { @@ -736,7 +736,7 @@ int max_spellpoints(const region * r, const unit * u) if (n > 0) { msp = (msp * n) / 100; } - return _max((int)msp, 0); + return MAX((int)msp, 0); } int change_maxspellpoints(unit * u, int csp) @@ -771,7 +771,7 @@ int countspells(unit * u, int step) count = m->spellcount + step; /* negative Werte abfangen. */ - m->spellcount = _max(0, count); + m->spellcount = MAX(0, count); return m->spellcount; } @@ -864,7 +864,7 @@ int eff_spelllevel(unit * u, const spell * sp, int cast_level, int range) } else if (sp->components[k].cost == SPC_LEVEL) { costtyp = SPC_LEVEL; - cast_level = _min(cast_level, maxlevel); + cast_level = MIN(cast_level, maxlevel); /* bei Typ Linear müssen die Kosten in Höhe der Stufe vorhanden * sein, ansonsten schlägt der Spruch fehl */ } @@ -882,7 +882,7 @@ int eff_spelllevel(unit * u, const spell * sp, int cast_level, int range) if (sb) { spellbook_entry * sbe = spellbook_get(sb, sp); if (sbe) { - return _min(cast_level, sbe->level); + return MIN(cast_level, sbe->level); } } log_error("spell %s is not in the spellbook for %s\n", sp->sname, unitname(u)); @@ -1027,9 +1027,8 @@ cancast(unit * u, const spell * sp, int level, int range, struct order * ord) double spellpower(region * r, unit * u, const spell * sp, int cast_level, struct order *ord) { - curse *c; double force = cast_level; - int elf_power; + static int elf_power, config; const struct resource_type *rtype; if (sp == NULL) { @@ -1042,55 +1041,66 @@ spellpower(region * r, unit * u, const spell * sp, int cast_level, struct order if (btype && btype->flags & BTF_MAGIC) ++force; } - elf_power = config_get_int("rules.magic.elfpower", 0); - - if (elf_power && u_race(u) == get_race(RC_ELF) && r_isforest(r)) { - ++force; + if (config_changed(&config)) { + elf_power = config_get_int("rules.magic.elfpower", 0); + } + if (elf_power) { + static int rc_cache; + static const race *rc_elf; + if (rc_changed(&rc_cache)) { + rc_elf = get_race(RC_ELF); + } + if (u_race(u) == rc_elf && r_isforest(r)) { + ++force; + } } rtype = rt_find("rop"); if (rtype && i_get(u->items, rtype->itype) > 0) { ++force; } - /* Antimagie in der Zielregion */ - c = get_curse(r->attribs, ct_find("antimagiczone")); - if (curse_active(c)) { - unit *mage = c->magician; - force -= curse_geteffect(c); - curse_changevigour(&r->attribs, c, -cast_level); - cmistake(u, ord, 185, MSG_MAGIC); - if (mage != NULL && mage->faction != NULL) { - if (force > 0) { - ADDMSG(&mage->faction->msgs, msg_message("reduce_spell", - "self mage region", mage, u, r)); + if (r->attribs) { + curse *c; + + /* Antimagie in der Zielregion */ + c = get_curse(r->attribs, ct_find("antimagiczone")); + if (curse_active(c)) { + unit *mage = c->magician; + force -= curse_geteffect(c); + curse_changevigour(&r->attribs, c, -cast_level); + cmistake(u, ord, 185, MSG_MAGIC); + if (mage != NULL && mage->faction != NULL) { + if (force > 0) { + ADDMSG(&mage->faction->msgs, msg_message("reduce_spell", + "self mage region", mage, u, r)); + } + else { + ADDMSG(&mage->faction->msgs, msg_message("block_spell", + "self mage region", mage, u, r)); + } } - else { - ADDMSG(&mage->faction->msgs, msg_message("block_spell", - "self mage region", mage, u, r)); + } + + /* Patzerfluch-Effekt: */ + c = get_curse(r->attribs, ct_find("fumble")); + if (curse_active(c)) { + unit *mage = c->magician; + force -= curse_geteffect(c); + curse_changevigour(&u->attribs, c, -1); + cmistake(u, ord, 185, MSG_MAGIC); + if (mage != NULL && mage->faction != NULL) { + if (force > 0) { + ADDMSG(&mage->faction->msgs, msg_message("reduce_spell", + "self mage region", mage, u, r)); + } + else { + ADDMSG(&mage->faction->msgs, msg_message("block_spell", + "self mage region", mage, u, r)); + } } } } - - /* Patzerfluch-Effekt: */ - c = get_curse(r->attribs, ct_find("fumble")); - if (curse_active(c)) { - unit *mage = c->magician; - force -= curse_geteffect(c); - curse_changevigour(&u->attribs, c, -1); - cmistake(u, ord, 185, MSG_MAGIC); - if (mage != NULL && mage->faction != NULL) { - if (force > 0) { - ADDMSG(&mage->faction->msgs, msg_message("reduce_spell", - "self mage region", mage, u, r)); - } - else { - ADDMSG(&mage->faction->msgs, msg_message("block_spell", - "self mage region", mage, u, r)); - } - } - } - - return _max(force, 0); + return MAX(force, 0); } /* ------------------------------------------------------------- */ @@ -1125,27 +1135,29 @@ static int farcasting(unit * magician, region * r) /* allgemeine Magieresistenz einer Einheit, * reduziert magischen Schaden */ -double magic_resistance(unit * target) +variant magic_resistance(unit * target) { attrib *a; curse *c; const curse_type * ct_goodresist = 0, *ct_badresist = 0; const resource_type *rtype; const race *rc = u_race(target); - double probability = rc->magres; + variant v, prob = rc_magres(rc); const plane *pl = rplane(target->region); if (rc == get_race(RC_HIRNTOETER) && !pl) { - probability /= 2; + prob.sa[1] *= 2; } assert(target->number > 0); /* Magier haben einen Resistenzbonus vom Magietalent * 5% */ - probability += effskill(target, SK_MAGIC, 0) * 0.05; + prob = frac_add(prob, frac_make(effskill(target, SK_MAGIC, 0), 20)); /* Auswirkungen von Zaubern auf der Einheit */ c = get_curse(target->attribs, ct_find("magicresistance")); if (c) { - probability += 0.01 * curse_geteffect(c) * get_cursedmen(target, c); + /* TODO: legacy. magicresistance-effect is an integer-percentage stored in a double */ + int effect = curse_geteffect_int(c) * get_cursedmen(target, c); + prob = frac_add(prob, frac_make(effect, 100)); } /* Unicorn +10 */ @@ -1153,7 +1165,7 @@ double magic_resistance(unit * target) if (rtype) { int n = i_get(target->items, rtype->itype); if (n) { - probability += n * 0.1 / target->number; + prob = frac_add(prob, frac_make(n, target->number * 10)); } } @@ -1170,13 +1182,15 @@ double magic_resistance(unit * target) if (mage != NULL) { if (ct_goodresist && c->type == ct_goodresist) { if (alliedunit(mage, target->faction, HELP_GUARD)) { - probability += curse_geteffect(c) * 0.01; + /* TODO: legacy. magicresistance-effect is an integer-percentage stored in a double */ + prob = frac_add(prob, frac_make(curse_geteffect_int(c), 100)); ct_goodresist = 0; /* only one effect per region */ } } else if (ct_badresist && c->type == ct_badresist) { if (!alliedunit(mage, target->faction, HELP_GUARD)) { - probability -= curse_geteffect(c) * 0.01; + /* TODO: legacy. magicresistance-effect is an integer-percentage stored in a double */ + prob = frac_sub(prob, frac_make(curse_geteffect_int(c), 100)); ct_badresist = 0; /* only one effect per region */ } } @@ -1192,11 +1206,18 @@ double magic_resistance(unit * target) const struct building_type *btype = building_is_active(b) ? b->type : NULL; /* gesegneter Steinkreis gibt 30% dazu */ - if (btype) - probability += btype->magresbonus * 0.01; + if (btype) { + /* TODO: legacy. building-bonus is an integer-percentage */ + prob = frac_add(prob, frac_make(btype->magresbonus, 100)); + } } - return (probability<0.9) ? probability : 0.9; + /* resistance must never be more than 90% */ + v = frac_make(9, 10); + if (frac_sign(frac_sub(prob, v)) > 0) { /* prob < 90% */ + return v; /* at most 90% */ + } + return prob; } /* ------------------------------------------------------------- */ @@ -1213,12 +1234,12 @@ double magic_resistance(unit * target) bool target_resists_magic(unit * magician, void *obj, int objtyp, int t_bonus) { - double probability = 0.0; + variant v02p, v98p, prob = frac_make(t_bonus, 100); + attrib *a = NULL; - if (magician == NULL) - return true; - if (obj == NULL) + if (magician == NULL || obj == NULL) { return true; + } switch (objtyp) { case TYP_UNIT: @@ -1227,6 +1248,9 @@ target_resists_magic(unit * magician, void *obj, int objtyp, int t_bonus) skill *sv; unit *u = (unit *)obj; + if (u_race(u)==get_race(RC_SPELL)) { + return true; + } at = effskill(magician, SK_MAGIC, 0); for (sv = u->skills; sv != u->skills + u->skill_size; ++sv) { @@ -1235,43 +1259,56 @@ target_resists_magic(unit * magician, void *obj, int objtyp, int t_bonus) pa = sk; } - /* Contest */ - probability = 0.05 * (10 + pa - at); - - probability += magic_resistance((unit *)obj); + /* Contest, probability = 0.05 * (10 + pa - at); */ + prob = frac_add(prob, frac_make(10 + pa - at, 20)); + prob = frac_add(prob, magic_resistance((unit *)obj)); break; } case TYP_REGION: - /* Bonus durch Zauber */ + /* Bonus durch Zauber probability += - 0.01 * get_curseeffect(((region *)obj)->attribs, C_RESIST_MAGIC, 0); + 0.01 * get_curseeffect(((region *)obj)->attribs, C_RESIST_MAGIC, 0); */ + a = ((region *)obj)->attribs; break; case TYP_BUILDING: - /* Bonus durch Zauber */ + /* Bonus durch Zauber probability += - 0.01 * get_curseeffect(((building *)obj)->attribs, C_RESIST_MAGIC, 0); - - /* Bonus durch Typ */ - probability += 0.01 * ((building *)obj)->type->magres; - + 0.01 * get_curseeffect(((building *)obj)->attribs, C_RESIST_MAGIC, 0); */ + a = ((building *)obj)->attribs; + /* Bonus durch Typ + probability += 0.01 * ((building *)obj)->type->magres; */ + prob = frac_add(prob, ((building *)obj)->type->magres); break; case TYP_SHIP: /* Bonus durch Zauber */ - probability += - 0.01 * get_curseeffect(((ship *)obj)->attribs, C_RESIST_MAGIC, 0); + a = ((ship *)obj)->attribs; break; } - probability = _max(0.02, probability + t_bonus * 0.01); - probability = _min(0.98, probability); + if (a) { + const struct curse_type *ct_resist = ct_find(oldcursename(C_RESIST_MAGIC)); + curse * c = get_curse(a, ct_resist); + int effect = curse_geteffect_int(c); + prob = frac_add(prob, frac_make(effect, 100)); + } + + /* ignore results < 2% and > 98% */ + v02p = frac_make(1, 50); + v98p = frac_make(49, 50); + if (frac_sign(frac_sub(prob, v02p)) < 0) { + prob = v02p; + } + else if (frac_sign(frac_sub(prob, v98p)) > 0) { + prob = v98p; + } /* gibt true, wenn die Zufallszahl kleiner als die chance ist und * false, wenn sie gleich oder größer ist, dh je größer die * Magieresistenz (chance) desto eher gibt die Funktion true zurück */ - return chance(probability); + return rng_int() % prob.sa[1] < prob.sa[0]; } /* ------------------------------------------------------------- */ @@ -1408,7 +1445,7 @@ static void do_fumble(castorder * co) case 2: /* temporary skill loss */ - duration = _max(rng_int() % level / 2, 2); + duration = MAX(rng_int() % level / 2, 2); effect = level / -2.0; c = create_curse(u, &u->attribs, ct_find("skillmod"), level, duration, effect, 1); @@ -1516,14 +1553,14 @@ void regenerate_aura(void) reg_aura -= regen; if (chance(reg_aura)) ++regen; - regen = _max(1, regen); - regen = _min((auramax - aura), regen); + regen = MAX(1, regen); + regen = MIN((auramax - aura), regen); aura += regen; ADDMSG(&u->faction->msgs, msg_message("regenaura", "unit region amount", u, r, regen)); } - set_spellpoints(u, _min(aura, auramax)); + set_spellpoints(u, MIN(aura, auramax)); } } } @@ -1840,7 +1877,7 @@ static int addparam_string(const char *const param[], spllprm ** spobjp) spobj->flag = 0; spobj->typ = SPP_STRING; - spobj->data.xs = _strdup(param[0]); + spobj->data.xs = strdup(param[0]); return 1; } @@ -2154,7 +2191,7 @@ typedef struct familiar_data { bool is_familiar(const unit * u) { attrib *a = a_find(u->attribs, &at_familiarmage); - return i2b(a != NULL); + return a != NULL; } static void @@ -2415,7 +2452,7 @@ static int age_unit(attrib * a, void *owner) /* if unit is gone or dead, remove the attribute */ { unit *u = (unit *)a->data.v; - unused_arg(owner); + UNUSED_ARG(owner); return (u != NULL && u->number > 0) ? AT_AGE_KEEP : AT_AGE_REMOVE; } @@ -2554,7 +2591,7 @@ static castorder *cast_cmd(unit * u, order * ord) /* für Syntax ' STUFE x REGION y z ' */ if (param == P_LEVEL) { int p = getint(); - level = _min(p, level); + level = MIN(p, level); if (level < 1) { /* Fehler "Das macht wenig Sinn" */ syntax_error(u, ord); @@ -2584,7 +2621,7 @@ static castorder *cast_cmd(unit * u, order * ord) * hier nach REGION nochmal auf STUFE prüfen */ if (param == P_LEVEL) { int p = getint(); - level = _min(p, level); + level = MIN(p, level); if (level < 1) { /* Fehler "Das macht wenig Sinn" */ syntax_error(u, ord); @@ -2715,7 +2752,7 @@ static castorder *cast_cmd(unit * u, order * ord) * löschen, zaubern kann er noch */ range *= 2; set_order(&caster->thisorder, NULL); - level = _min(level, effskill(caster, SK_MAGIC, 0) / 2); + level = MIN(level, effskill(caster, SK_MAGIC, 0) / 2); } } /* Weitere Argumente zusammenbasteln */ @@ -2738,7 +2775,7 @@ static castorder *cast_cmd(unit * u, order * ord) break; } } - params[p++] = _strdup(s); + params[p++] = strdup(s); } params[p] = 0; args = @@ -2780,6 +2817,8 @@ void magic(void) int rank; castorder *co; spellrank spellranks[MAX_SPELLRANK]; + const race *rc_spell = get_race(RC_SPELL); + const race *rc_insect = get_race(RC_INSECT); memset(spellranks, 0, sizeof(spellranks)); @@ -2788,10 +2827,10 @@ void magic(void) for (u = r->units; u; u = u->next) { order *ord; - if (u->number <= 0 || u_race(u) == get_race(RC_SPELL)) + if (u->number <= 0 || u_race(u) == rc_spell) continue; - if (u_race(u) == get_race(RC_INSECT) && r_insectstalled(r) && + if (u_race(u) == rc_insect && r_insectstalled(r) && !is_cursed(u->attribs, C_KAELTESCHUTZ, 0)) continue; @@ -2930,6 +2969,7 @@ const char *spell_info(const spell * sp, const struct locale *lang) return LOC(lang, mkname("spellinfo", sp->sname)); } +/* TODO: should take the name, not the spell (spellref optimizations) */ const char *spell_name(const spell * sp, const struct locale *lang) { return LOC(lang, mkname("spell", sp->sname)); @@ -2941,23 +2981,22 @@ const char *curse_name(const curse_type * ctype, const struct locale *lang) } static void select_spellbook(void **tokens, spellbook *sb, const struct locale * lang) { - quicklist * ql; + selist * ql; int qi; assert(sb); assert(lang); - for (qi = 0, ql = sb->spells; ql; ql_advance(&ql, &qi, 1)) { - spellbook_entry *sbe = (spellbook_entry *)ql_get(ql, qi); - spell *sp = sbe->sp; + for (qi = 0, ql = sb->spells; ql; selist_advance(&ql, &qi, 1)) { + spellbook_entry *sbe = (spellbook_entry *)selist_get(ql, qi); - const char *n = spell_name(sp, lang); + const char *n = spell_name(sbe->sp, lang); if (!n) { - log_error("no translation in locale %s for spell %s\n", locale_name(lang), sp->sname); + log_error("no translation in locale %s for spell %s\n", locale_name(lang), sbe->sp->sname); } else { variant token; - token.v = sp; + token.v = sbe->sp; addtoken((struct tnode **)tokens, n, token); } } @@ -2972,7 +3011,7 @@ spell *unit_getspell(struct unit *u, const char *name, const struct locale * lan if (sb) { select_spellbook(&tokens, sb, lang); } -#if 0 // TODO: some familiars can cast spells from the mage's spellbook? +#if 0 /* TODO: some familiars can cast spells from the mage's spellbook? */ u = get_familiar_mage(u); if (u) { sb = unit_get_spellbook(u); diff --git a/src/magic.h b/src/magic.h index 257ba11c4..37fe33eae 100644 --- a/src/magic.h +++ b/src/magic.h @@ -20,6 +20,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #define H_KRNL_MAGIC #include +#include #ifdef __cplusplus extern "C" { @@ -58,7 +59,7 @@ extern "C" { sppobj_t typ; int flag; union { - struct region *r; //TODO: V117 http://www.viva64.com/en/V117 Memsize type is used in the union. + struct region *r; struct unit *u; struct building *b; struct ship *sh; @@ -184,12 +185,6 @@ extern "C" { SPC_LINEAR /* Komponenten pro Level und mssen vorhanden sein */ }; - enum { - RS_DUMMY, - RS_FARVISION, - MAX_REGIONSPELLS - }; - /* ------------------------------------------------------------- */ /* Prototypen */ @@ -320,7 +315,7 @@ extern "C" { bool is_magic_resistant(struct unit *magician, struct unit *target, int resist_bonus); /* Mapperfunktion fr target_resists_magic() vom Typ struct unit. */ - extern double magic_resistance(struct unit *target); + variant magic_resistance(struct unit *target); /* gibt die Chance an, mit der einem Zauber widerstanden wird. Je * grer, desto resistenter ist da Opfer */ bool target_resists_magic(struct unit *magician, void *obj, int objtyp, @@ -354,8 +349,8 @@ extern "C" { struct order *ord, const struct spllprm *spobj); bool FactionSpells(void); - void write_spells(struct quicklist *slist, struct storage *store); - void read_spells(struct quicklist **slistp, magic_t mtype, + void write_spells(struct selist *slist, struct storage *store); + void read_spells(struct selist **slistp, magic_t mtype, struct storage *store); struct spellbook * get_spellbook(const char * name); diff --git a/src/magic.test.c b/src/magic.test.c index 4ba867b96..a5a842172 100644 --- a/src/magic.test.c +++ b/src/magic.test.c @@ -2,6 +2,7 @@ #include "magic.h" #include "teleport.h" +#include "give.h" #include #include @@ -13,7 +14,7 @@ #include #include #include -#include +#include #include #include @@ -41,7 +42,7 @@ void test_updatespells(CuTest * tc) CuAssertPtrEquals(tc, 0, f->spellbook); pick_random_spells(f, 1, book, 1); CuAssertPtrNotNull(tc, f->spellbook); - CuAssertIntEquals(tc, 1, ql_length(f->spellbook->spells)); + CuAssertIntEquals(tc, 1, selist_length(f->spellbook->spells)); CuAssertPtrNotNull(tc, spellbook_get(f->spellbook, sp)); free_spellbook(book); test_cleanup(); @@ -370,10 +371,10 @@ void test_hasspell(CuTest * tc) test_cleanup(); } -static quicklist * casts; +static selist * casts; static int cast_fireball(struct castorder * co) { - ql_push(&casts, co); + selist_push(&casts, co); return 0; } @@ -401,8 +402,8 @@ void test_multi_cast(CuTest *tc) { CuAssertPtrEquals(tc, casts, 0); magic(); CuAssertPtrNotNull(tc, casts); - CuAssertIntEquals(tc, 2, ql_length(casts)); - ql_free(casts); + CuAssertIntEquals(tc, 2, selist_length(casts)); + selist_free(casts); test_cleanup(); } @@ -413,15 +414,56 @@ static void test_magic_resistance(CuTest *tc) { test_setup(); rc = test_create_race("human"); u = test_create_unit(test_create_faction(rc), test_create_region(0, 0, 0)); - CuAssertDblEquals(tc, rc->magres, magic_resistance(u), 0.01); - rc->magres = 1.0; - CuAssertDblEquals_Msg(tc, "magic resistance is capped at 0.9", 0.9, magic_resistance(u), 0.01); + CuAssertTrue(tc, frac_equal(rc->magres, magic_resistance(u))); + rc->magres = frac_one; + CuAssert(tc, "magic resistance is capped at 0.9", frac_equal(magic_resistance(u), frac_make(9, 10))); rc = test_create_race("braineater"); - rc->magres = 1.0; + rc->magres = frac_one; u_setrace(u, rc); - CuAssertDblEquals_Msg(tc, "brain eaters outside astral space have 50% magres", 0.5, magic_resistance(u), 0.01); + CuAssert(tc, "brain eaters outside astral space have 50% magres", frac_equal(magic_resistance(u), frac_make(1, 2))); u->region->_plane = get_astralplane(); - CuAssertDblEquals_Msg(tc, "brain eaters in astral space have full magres", 0.9, magic_resistance(u), 0.01); + CuAssert(tc, "brain eaters in astral space have full magres", frac_equal(magic_resistance(u), frac_make(9, 10))); + test_cleanup(); +} + +static void test_max_spellpoints(CuTest *tc) { + unit *u; + race *rc; + + test_setup(); + rc = test_create_race("human"); + u = test_create_unit(test_create_faction(rc), test_create_region(0, 0, 0)); + CuAssertIntEquals(tc, 1, max_spellpoints(u->region, u)); + rc->maxaura = 100; + CuAssertIntEquals(tc, 1, max_spellpoints(u->region, u)); + rc->maxaura = 200; + CuAssertIntEquals(tc, 2, max_spellpoints(u->region, u)); + create_mage(u, M_GRAY); + set_level(u, SK_MAGIC, 1); + CuAssertIntEquals(tc, 3, max_spellpoints(u->region, u)); + set_level(u, SK_MAGIC, 2); + CuAssertIntEquals(tc, 9, max_spellpoints(u->region, u)); + /* permanent aura loss: */ + CuAssertIntEquals(tc, 7, change_maxspellpoints(u, -2)); + CuAssertIntEquals(tc, 7, max_spellpoints(u->region, u)); + test_cleanup(); +} + +static void test_familiar_mage(CuTest *tc) { + unit *um, *uf, *ut; + test_setup(); + um = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); + uf = test_create_unit(um->faction, um->region); + ut = test_create_unit(um->faction, um->region); + set_number(ut, 0); + CuAssertTrue(tc, create_newfamiliar(um, uf)); + CuAssertTrue(tc, is_familiar(uf)); + CuAssertTrue(tc, !is_familiar(um)); + CuAssertPtrEquals(tc, um, get_familiar_mage(uf)); + CuAssertPtrEquals(tc, uf, get_familiar(um)); + + CuAssertPtrEquals(tc, NULL, give_men(1, um, ut, NULL)); + CuAssertPtrEquals(tc, ut, get_familiar_mage(uf)); test_cleanup(); } @@ -441,5 +483,7 @@ CuSuite *get_magic_suite(void) SUITE_ADD_TEST(suite, test_set_post_combatspell); SUITE_ADD_TEST(suite, test_hasspell); SUITE_ADD_TEST(suite, test_magic_resistance); + SUITE_ADD_TEST(suite, test_max_spellpoints); + DISABLE_TEST(suite, test_familiar_mage); return suite; } diff --git a/src/main.c b/src/main.c index 58a15edc0..dd65ec9e1 100644 --- a/src/main.c +++ b/src/main.c @@ -54,50 +54,52 @@ static void load_inifile(dictionary * d) assert(d); - str = iniparser_getstring(d, "eressea:base", basedir); + str = iniparser_getstring(d, "game:base", basedir); if (str != basedir) { set_basepath(str); } - str = iniparser_getstring(d, "eressea:report", reportdir); + str = iniparser_getstring(d, "game:report", reportdir); if (str != reportdir) { set_reportpath(str); } - str = iniparser_getstring(d, "eressea:data", datadir); + str = iniparser_getstring(d, "game:data", datadir); if (str != datadir) { set_datapath(str); } - lomem = iniparser_getint(d, "eressea:lomem", lomem) ? 1 : 0; + lomem = iniparser_getint(d, "game:lomem", lomem) ? 1 : 0; - str = iniparser_getstring(d, "eressea:encoding", NULL); - if (str && (_strcmpl(str, "utf8") == 0 || _strcmpl(str, "utf-8") == 0)) { - enc_gamedata = ENCODING_UTF8; - } - - verbosity = iniparser_getint(d, "eressea:verbose", 2); - battledebug = iniparser_getint(d, "eressea:debug", battledebug) ? 1 : 0; - - str = iniparser_getstring(d, "eressea:locales", "de,en"); - make_locales(str); - - if (global.inifile) iniparser_freedict(global.inifile); - global.inifile = d; + verbosity = iniparser_getint(d, "game:verbose", 2); } -static void parse_config(const char *filename) +static dictionary *parse_config(const char *filename) { - dictionary *d = iniparser_load(filename); + char path[MAX_PATH]; + dictionary *d; + const char *str, *cfgpath = config_get("config.path"); + + if (cfgpath) { + join_path(cfgpath, filename, path, sizeof(path)); + log_debug("reading from configuration file %s\n", path); + d = iniparser_load(path); + } else { + log_debug("reading from configuration file %s\n", filename); + d = iniparser_load(filename); + } if (d) { load_inifile(d); - log_debug("reading from configuration file %s\n", filename); + config_set_from(d); - memdebug = iniparser_getint(d, "eressea:memcheck", memdebug); + memdebug = iniparser_getint(d, "game:memcheck", memdebug); #ifdef USE_CURSES /* only one value in the [editor] section */ force_color = iniparser_getint(d, "editor:color", force_color); gm_codepage = iniparser_getint(d, "editor:codepage", gm_codepage); #endif } + str = config_get("game.locales"); + make_locales(str ? str : "de,en"); + return d; } static int usage(const char *prog, const char *arg) @@ -184,6 +186,10 @@ static int parse_args(int argc, char **argv, int *exitcode) else { const char *arg; switch (argi[1]) { + case 'c': + i = get_arg(argc, argv, 2, i, &arg, 0); + config_set("config.path", arg); + break; case 'r': i = get_arg(argc, argv, 2, i, &arg, 0); config_set("config.rules", arg); @@ -217,11 +223,11 @@ static int parse_args(int argc, char **argv, int *exitcode) } } - // open logfile on disk: + /* open logfile on disk: */ log_flags = verbosity_to_flags(log_flags); log_open(logfile, log_flags); - // also log to stderr: + /* also log to stderr: */ log_stderr = verbosity_to_flags(verbosity); if (log_stderr) { log_to_file(log_stderr | LOG_FLUSH | LOG_BRIEF, stderr); @@ -262,27 +268,6 @@ static int setup_signal_handler(void) } #endif -#undef CRTDBG -#ifdef CRTDBG -#include -void init_crtdbg(void) -{ -#if (defined(_MSC_VER)) - int flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); - if (memdebug == 1) { - flags |= _CRTDBG_CHECK_ALWAYS_DF; /* expensive */ - } else if (memdebug == 2) { - flags = (flags & 0x0000FFFF) | _CRTDBG_CHECK_EVERY_16_DF; - } else if (memdebug == 3) { - flags = (flags & 0x0000FFFF) | _CRTDBG_CHECK_EVERY_128_DF; - } else if (memdebug == 4) { - flags = (flags & 0x0000FFFF) | _CRTDBG_CHECK_EVERY_1024_DF; - } - _CrtSetDbgFlag(flags); -#endif -} -#endif - void locale_init(void) { setlocale(LC_CTYPE, ""); @@ -299,22 +284,19 @@ int main(int argc, char **argv) { int err = 0; lua_State *L; + dictionary *d = 0; setup_signal_handler(); - /* ini file sets defaults for arguments*/ - parse_config(inifile); - if (!global.inifile) { - log_error("could not open ini configuration %s\n", inifile); - } /* parse arguments again, to override ini file */ parse_args(argc, argv, &err); + d = parse_config(inifile); + if (!d) { + log_error("could not open ini configuration %s\n", inifile); + } + locale_init(); -#ifdef CRTDBG - init_crtdbg(); -#endif - - L = lua_init(); + L = lua_init(d); game_init(); bind_monsters(L); err = eressea_run(L, luafile); @@ -325,8 +307,8 @@ int main(int argc, char **argv) game_done(); lua_done(L); log_close(); - if (global.inifile) { - iniparser_freedict(global.inifile); + if (d) { + iniparser_freedict(d); } return 0; } diff --git a/src/market.c b/src/market.c index efcaf0d98..8fd4e3f0d 100644 --- a/src/market.c +++ b/src/market.c @@ -17,7 +17,7 @@ without prior permission by the authors of Eressea. #include #include -#include +#include #include #include @@ -66,28 +66,17 @@ attrib_type at_market = { NULL, NULL, NULL, ATF_UNIQUE }; -static int rc_luxury_trade(const struct race *rc) -{ - if (rc) { - return get_param_int(rc->parameters, "luxury_trade", 1000); - } - return 1000; -} - -static int rc_herb_trade(const struct race *rc) -{ - if (rc) { - return get_param_int(rc->parameters, "herb_trade", 500); - } - return 500; -} - #define MAX_MARKETS 128 #define MIN_PEASANTS 50 /* if there are at least this many peasants, you will get 1 good */ +bool markets_module(void) +{ + return (bool)config_get_int("modules.markets", 0); +} + void do_markets(void) { - quicklist *traders = 0; + selist *traders = 0; unit *markets[MAX_MARKETS]; region *r; for (r = regions; r; r = r->next) { @@ -119,7 +108,7 @@ void do_markets(void) attrib *a = a_find(u->attribs, &at_market); if (a == NULL) { a = a_add(&u->attribs, a_new(&at_market)); - ql_push(&traders, u); + selist_push(&traders, u); } items = (item *)a->data.v; i_change(&items, lux, 1); @@ -133,7 +122,7 @@ void do_markets(void) attrib *a = a_find(u->attribs, &at_market); if (a == NULL) { a = a_add(&u->attribs, a_new(&at_market)); - ql_push(&traders, u); + selist_push(&traders, u); } items = (item *)a->data.v; i_change(&items, herb, 1); @@ -146,10 +135,10 @@ void do_markets(void) } if (traders) { - quicklist *qliter = traders; + selist *qliter = traders; int qli = 0; - for (qli = 0; qliter; ql_advance(&qliter, &qli, 1)) { - unit *u = (unit *)ql_get(qliter, qli); + for (qli = 0; qliter; selist_advance(&qliter, &qli, 1)) { + unit *u = (unit *)selist_get(qliter, qli); attrib *a = a_find(u->attribs, &at_market); item *items = (item *)a->data.v; @@ -171,6 +160,6 @@ void do_markets(void) a_remove(&u->attribs, a); } - ql_free(traders); + selist_free(traders); } } diff --git a/src/market.h b/src/market.h index dd15253ef..8f1d39eb4 100644 --- a/src/market.h +++ b/src/market.h @@ -12,12 +12,20 @@ without prior permission by the authors of Eressea. */ #ifndef H_GC_MARKET #define H_GC_MARKET + +#include + #ifdef __cplusplus extern "C" { #endif struct building; + struct race; - extern void do_markets(void); + bool markets_module(void); + void do_markets(void); + + int rc_luxury_trade(const struct race *rc); + int rc_herb_trade(const struct race *rc); #ifdef __cplusplus } diff --git a/src/market.test.c b/src/market.test.c index 43e070b5e..b4d5f05f5 100644 --- a/src/market.test.c +++ b/src/market.test.c @@ -46,7 +46,7 @@ static void test_market_curse(CuTest * tc) config_set("rules.region_owners", "1"); btype = (building_type *)calloc(1, sizeof(building_type)); - btype->_name = _strdup("market"); + btype->_name = strdup("market"); bt_register(btype); terrain = get_terrain("plain"); @@ -80,9 +80,23 @@ static void test_market_curse(CuTest * tc) CuAssertIntEquals(tc, 35, i_get(u->items, ltype)); } +static void test_rc_trade(CuTest *tc) { + race *rc; + test_setup(); + rc = test_create_race("human"); + CuAssertIntEquals(tc, 1000, rc_luxury_trade(rc)); + CuAssertIntEquals(tc, 500, rc_herb_trade(rc)); + rc_set_param(rc, "luxury_trade", "100"); + rc_set_param(rc, "herb_trade", "50"); + CuAssertIntEquals(tc, 100, rc_luxury_trade(rc)); + CuAssertIntEquals(tc, 50, rc_herb_trade(rc)); + test_cleanup(); +} + CuSuite *get_market_suite(void) { CuSuite *suite = CuSuiteNew(); SUITE_ADD_TEST(suite, test_market_curse); + SUITE_ADD_TEST(suite, test_rc_trade); return suite; } diff --git a/src/modules/CMakeLists.txt b/src/modules/CMakeLists.txt index 633c486f5..82dee9ec4 100644 --- a/src/modules/CMakeLists.txt +++ b/src/modules/CMakeLists.txt @@ -1,6 +1,5 @@ PROJECT(modules C) SET(_FILES -arena.c autoseed.c gmcmd.c museum.c diff --git a/src/modules/arena.c b/src/modules/arena.c deleted file mode 100644 index 97488218a..000000000 --- a/src/modules/arena.c +++ /dev/null @@ -1,565 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#include -#include - -#if ARENA_MODULE -#include "arena.h" - -/* modules include */ -#include "score.h" - -/* items include */ -#include - -/* kernel includes */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -/* util include */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -/* libc include */ -#include -#include -#include -#include - -/* exports: */ -plane *arena = NULL; - -/* local vars */ -#define CENTRAL_VOLCANO 1 - -#ifdef ARENA_CREATION -static unsigned int arena_id = 0; -static region *arena_center = NULL; -static int newarena = 0; -#endif -static region *tower_region[6]; -static region *start_region[6]; - -static region *arena_region(int school) -{ - return tower_region[school]; -} - -static building *arena_tower(int school) -{ - return arena_region(school)->buildings; -} - -static int leave_fail(unit * u) -{ - ADDMSG(&u->faction->msgs, msg_message("arena_leave_fail", "unit", u)); - return 1; -} - -static int -leave_arena(struct unit *u, const struct item_type *itype, int amount, -order * ord) -{ - if (!u->building && leave_fail(u)) { - return -1; - } - if (u->building != arena_tower(u->faction->magiegebiet) && leave_fail(u)) { - return -1; - } - unused_arg(amount); - unused_arg(ord); - unused_arg(itype); - assert(!"not implemented"); - return 0; -} - -static int enter_fail(unit * u) -{ - ADDMSG(&u->faction->msgs, msg_message("arena_enter_fail", "region unit", - u->region, u)); - return 1; -} - -static int -enter_arena(unit * u, const item_type * itype, int amount, order * ord) -{ - skill_t sk; - region *r = u->region; - unit *u2; - int fee = 2000; - unused_arg(ord); - unused_arg(amount); - unused_arg(itype); - if (u->faction->score > fee * 5) { - score_t score = u->faction->score / 5; - if (score < INT_MAX) { - fee = (int)score; - } - else { - fee = INT_MAX; - } - } - if (getplane(r) == arena) - return -1; - if (u->number != 1 && enter_fail(u)) - return -1; - if (get_pooled(u, get_resourcetype(R_SILVER), GET_DEFAULT, fee) < fee - && enter_fail(u)) - return -1; - for (sk = 0; sk != MAXSKILLS; ++sk) { - if (get_level(u, sk) > 1 && enter_fail(u)) - return -1; - } - for (u2 = r->units; u2; u2 = u2->next) - if (u2->faction == u->faction) - break; - - assert(!"not implemented"); - /* - for (res=0;res!=MAXRESOURCES;++res) if (res!=R_SILVER && res!=R_ARENA_GATE && (is_item(res) || is_herb(res) || is_potion(res))) { - int x = get_resource(u, res); - if (x) { - if (u2) { - change_resource(u2, res, x); - change_resource(u, res, -x); - } - else if (enter_fail(u)) return -1; - } - } - */ - if (get_money(u) > fee) { - if (u2) - change_money(u2, get_money(u) - fee); - else if (enter_fail(u)) - return -1; - } - ADDMSG(&u->faction->msgs, msg_message("arena_enter_fail", "region unit", - u->region, u)); - use_pooled(u, itype->rtype, GET_SLACK | GET_RESERVE, 1); - use_pooled(u, get_resourcetype(R_SILVER), GET_DEFAULT, fee); - set_money(u, 109); - fset(u, UFL_ANON_FACTION); - move_unit(u, start_region[rng_int() % 6], NULL); - return 0; -} - -/*** - ** Szepter der Trnen, Demo-Item - ***/ - -static int -use_wand_of_tears(unit * user, const struct item_type *itype, int amount, -order * ord) -{ - int n; - unused_arg(ord); - for (n = 0; n != amount; ++n) { - unit *u; - for (u = user->region->units; u; u = u->next) { - if (u->faction != user->faction) { - int i; - - for (i = 0; i != u->skill_size; ++i) { - if (rng_int() % 3) - reduce_skill(u, u->skills + i, 1); - } - ADDMSG(&u->faction->msgs, msg_message("wand_of_tears_effect", - "unit", u)); - } - } - } - ADDMSG(&user->region->msgs, msg_message("wand_of_tears_usage", "unit", user)); - return 0; -} - -/** - * Tempel der Schreie, Demo-Gebude **/ - -static int age_hurting(attrib * a, void *owner) -{ - building *b = (building *)a->data.v; - unit *u; - int active = 0; - assert(owner == b); - if (b == NULL) - return AT_AGE_REMOVE; - for (u = b->region->units; u; u = u->next) { - if (u->building == b) { - if (u->faction->magiegebiet == M_DRAIG) { - active++; - ADDMSG(&b->region->msgs, msg_message("praytoigjarjuk", "unit", u)); - } - } - } - if (active) - for (u = b->region->units; u; u = u->next) - if (playerrace(u->faction->race)) { - int i; - if (u->faction->magiegebiet != M_DRAIG) { - for (i = 0; i != active; ++i) - u->hp = (u->hp + 1) / 2; /* make them suffer, but not die */ - ADDMSG(&b->region->msgs, msg_message("cryinpain", "unit", u)); - } - } - return AT_AGE_KEEP; -} - -static void -write_hurting(const attrib * a, const void *owner, struct storage *store) -{ - building *b = a->data.v; - WRITE_INT(store, b->no); -} - -static int read_hurting(attrib * a, void *owner, struct gamedata *data) -{ - int i; - READ_INT(data->store, &i); - a->data.v = (void *)findbuilding(i); - if (a->data.v == NULL) { - log_error("temple of pain is broken\n"); - return AT_READ_FAIL; - } - return AT_READ_OK; -} - -static attrib_type at_hurting = { - "hurting", NULL, NULL, age_hurting, write_hurting, read_hurting -}; - -#ifdef ARENA_CREATION -static void make_temple(region * r) -{ - const building_type *btype = bt_find("temple"); - building *b; - if (btype == NULL) { - log_error("could not find buildingtype 'temple'\n"); - return; - } - - b = r->buildings; - while (b != NULL && b->type != btype) - b = b->next; - if (b != NULL) - return; /* gibt schon einen */ - - b = new_building(btype, r, NULL); - b->size = btype->maxsize; - b->name = _strdup("Igjarjuk's Tempel der Schreie"); - b->display = - _strdup - ("Ein Schrein aus spitzen Knochen und lodernden Flammen, gewidmet dem Wyrm der Wyrme"); - a_add(&b->attribs, a_new(&at_hurting))->data.v = b; -} -#endif - -/** - * Initialisierung Trme */ - -#ifdef ARENA_CREATION -static void tower_init(void) -{ - int i, first = newarena; - item_type *it_demonseye = it_find("demonseye"); - item_type *it_griphonwing = it_find("griphonwing"); - assert(it_griphonwing && it_demonseye); - for (i = 0; i != 6; ++i) { - region *r = tower_region[i] = - findregion(arena_center->x + delta_x[i] * 3, - arena_center->y + delta_y[i] * 3); - if (r) { - start_region[i] = - findregion(arena_center->x + delta_x[i] * 2, - arena_center->y + delta_y[i] * 2); - if (rterrain(r) != T_DESERT) - terraform(r, T_DESERT); - if (!r->buildings) { - building *b = new_building(bt_find("castle"), r, NULL); - b->size = 10; - if (i != 0) { - sprintf(buf, "Turm des %s", - LOC(default_locale, mkname("school", magic_school[i]))); - } else - sprintf(buf, "Turm der Ahnungslosen"); - set_string(&b->name, buf); - } - } - } - if (first && !arena_center->buildings) { - building *b = new_building(bt_find("castle"), arena_center, NULL); - attrib *a; - item *items; - - i_add(&items, i_new(it_griphonwing, 1)); - i_add(&items, i_new(it_demonseye, 1)); - a = a_add(&b->attribs, make_giveitem(b, items)); - - b->size = 10; - set_string(&b->name, "Hhle des Greifen"); - } -} -#endif - -#ifdef ARENA_CREATION -static void guardian_faction(plane * pl, int id) -{ - region *r; - faction *f = findfaction(id); - - if (!f) { - f = calloc(1, sizeof(faction)); - f->banner = _strdup("Sie dienen dem groen Wyrm"); - f->passw = _strdup(itoa36(rng_int())); - set_email(&f->email, "igjarjuk@eressea.de"); - f->name = _strdup("Igjarjuks Kundschafter"); - f->race = get_race(RC_ILLUSION); - f->age = turn; - f->locale = get_locale("de"); - f->options = - want(O_COMPRESS) | want(O_REPORT) | want(O_COMPUTER) | want(O_ADRESSEN) | - want(O_DEBUG); - - f->no = id; - addlist(&factions, f); - fhash(f); - } - if (f->race != get_race(RC_ILLUSION)) { - assert(!"guardian id vergeben"); - exit(0); - } - f->lastorders = turn; - f->alive = true; - for (r = regions; r; r = r->next) - if (getplane(r) == pl && rterrain(r) != T_FIREWALL) { - unit *u; - freset(r, RF_ENCOUNTER); - for (u = r->units; u; u = u->next) { - if (u->faction == f) - break; - } - if (u) - continue; - u = create_unit(r, f, 1, get_race(RC_GOBLIN), 0, NULL, NULL); - set_string(&u->name, "Igjarjuks Auge"); - i_change(&u->items, it_find("roi"), 1); - set_order(&u->thisorder, NULL); - fset(u, UFL_ANON_FACTION); - set_money(u, 1000); - } -} -#endif - -#define BLOCKSIZE 9 - -#ifdef ARENA_CREATION -static void block_create(int x1, int y1, char terrain) -{ - int x, y; - for (x = 0; x != BLOCKSIZE; ++x) { - for (y = 0; y != BLOCKSIZE; ++y) { - region *r = new_region(x1 + x, y1 + y, 0); - terraform(r, terrain); - } - } -} -#endif - -#ifdef CENTRAL_VOLCANO - -static int caldera_handle(trigger * t, void *data) -{ - /* call an event handler on caldera. - * data.v -> ( variant event, int timer ) - */ - building *b = (building *)t->data.v; - if (b != NULL) { - unit **up = &b->region->units; - while (*up) { - unit *u = *up; - if (u->building == b) { - message *msg; - if (u->items) { - item **ip = &u->items; - msg = msg_message("caldera_handle_1", "unit items", u, u->items); - while (*ip) { - item *i = *ip; - i_remove(ip, i); - if (*ip == i) - ip = &i->next; - } - } - else { - msg = msg_message("caldera_handle_0", "unit", u); - } - add_message(&u->region->msgs, msg); - set_number(u, 0); - } - if (*up == u) - up = &u->next; - } - } - else { - log_error("could not perform caldera::handle()\n"); - } - unused_arg(data); - return 0; -} - -static void caldera_write(const trigger * t, struct storage *store) -{ - building *b = (building *)t->data.v; - write_building_reference(b, store); -} - -static int caldera_read(trigger * t, struct gamedata *data) -{ - int rb = - read_reference(&t->data.v, data, read_building_reference, - resolve_building); - if (rb == 0 && !t->data.v) { - return AT_READ_FAIL; - } - return AT_READ_OK; -} - -struct trigger_type tt_caldera = { - "caldera", - NULL, - NULL, - caldera_handle, - caldera_write, - caldera_read -}; - -#ifdef ARENA_CREATION -static trigger *trigger_caldera(building * b) -{ - trigger *t = t_new(&tt_caldera); - t->data.v = b; - return t; -} -#endif - -#ifdef ARENA_CREATION -static void init_volcano(void) -{ - building *b; - region *r = arena_center; - assert(arena_center); - if (rterrain(r) != T_DESERT) - return; /* been done before */ - terraform(arena_center, T_VOLCANO_SMOKING); - b = new_building(bt_find("caldera"), r, NULL); - b->size = 1; - b->name = _strdup("Igjarjuk's Schlund"); - b->display = - _strdup - ("Feurige Lava fliet aus dem Krater des groen Vulkans. Alles wird von ihr verschlungen."); - add_trigger(&b->attribs, "timer", trigger_caldera(b)); - tt_register(&tt_caldera); -} -#endif -#endif - -#ifdef ARENA_CREATION -void create_arena(void) -{ - int x; - arena_id = hashstring("arena"); - arena = getplanebyid(arena_id); - if (arena != NULL) - return; - score(); /* ist wichtig, damit alle Parteien einen score haben, wenn sie durchs Tor wollen. */ - guardian_faction(arena, 999); - if (arena) - arena_center = findregion(plane_center_x(arena), plane_center_y(arena)); - if (!arena_center) { - newarena = 1; - arena = - create_new_plane(arena_id, "Arena", -10000, -10000, 0, BLOCKSIZE - 1, - PFL_LOWSTEALING | PFL_NORECRUITS | PFL_NOALLIANCES); - block_create(arena->minx, arena->miny, T_OCEAN); - arena_center = findregion(plane_center_x(arena), plane_center_y(arena)); - for (x = 0; x != BLOCKSIZE; ++x) { - int y; - for (y = 0; y != BLOCKSIZE; ++y) { - region *r = findregion(arena->minx + x, arena->miny + y); - freset(r, RF_ENCOUNTER); - r->planep = arena; - switch (distance(r, arena_center)) { - case 4: - terraform(r, T_FIREWALL); - break; - case 0: - terraform(r, T_GLACIER); - break; - case 1: - terraform(r, T_SWAMP); - break; - case 2: - terraform(r, T_MOUNTAIN); - break; - } - } - } - } - make_temple(arena_center); -#ifdef CENTRAL_VOLCANO - init_volcano(); -#else - if (arena_center->terrain != T_DESERT) - terraform(arena_center, T_DESERT); -#endif - rsetmoney(arena_center, 0); - rsetpeasants(arena_center, 0); - tower_init(); -} -#endif -void register_arena(void) -{ - at_register(&at_hurting); - register_item_use(use_wand_of_tears, "use_wand_of_tears"); - register_function((pf_generic)enter_arena, "enter_arena"); - register_function((pf_generic)leave_arena, "leave_arena"); - tt_register(&tt_caldera); -} - -#endif /* def ARENA_MODULE */ diff --git a/src/modules/arena.h b/src/modules/arena.h deleted file mode 100644 index 64bfc7e87..000000000 --- a/src/modules/arena.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#ifndef ARENA_H -#define ARENA_H -#ifdef __cplusplus -extern "C" { -#endif - -#if ARENA_MODULE == 0 -#error "must define ARENA_MODULE to use this module" -#endif - /* exports: */ - extern struct plane *arena; - - extern void register_arena(void); -#ifdef ARENA_CREATION - extern void create_arena(void); -#endif - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/modules/autoseed.c b/src/modules/autoseed.c index e8855683e..1e2d2d23f 100644 --- a/src/modules/autoseed.c +++ b/src/modules/autoseed.c @@ -14,6 +14,8 @@ #include #include "autoseed.h" +#include "market.h" + /* kernel includes */ #include #include @@ -36,7 +38,7 @@ #include #include #include -#include +#include #include #include @@ -132,20 +134,6 @@ static bool f_nolux(const region * r) return (r->land && count_demand(r) != get_maxluxuries()); } -int fix_demand(region * rd) { - luxury_type * ltype; - int maxluxuries = get_maxluxuries(); - if (maxluxuries > 0) { - int sale = rng_int() % maxluxuries; - for (ltype = luxurytypes; sale != 0 && ltype; ltype = ltype->next) { - --sale; - } - setluxuries(rd, ltype); - return 0; - } - return -1; -} - int fix_all_demand(region *rd) { region_list *rl, *rlist = NULL; recurse_regions(rd, &rlist, f_nolux); @@ -211,7 +199,7 @@ newfaction *read_newfactions(const char *filename) free(nf); continue; } - nf->password = _strdup(password); + nf->password = strdup(password); nf->race = rc_find(race); nf->subscription = subscription; if (alliances != NULL) { @@ -307,17 +295,17 @@ static bool virgin_region(const region * r) return true; } -static quicklist * get_island(region * root) +static selist * get_island(region * root) { - quicklist * ql, *result = 0; + selist * ql, *result = 0; int qi = 0; fset(root, RF_MARK); - ql_push(&result, root); + selist_push(&result, root); - for (ql = result, qi = 0; ql; ql_advance(&ql, &qi, 1)) { + for (ql = result, qi = 0; ql; selist_advance(&ql, &qi, 1)) { int dir; - region *r = (region *)ql_get(ql, qi); + region *r = (region *)selist_get(ql, qi); region * next[MAXDIRECTIONS]; get_neighbours(r, next); @@ -326,13 +314,13 @@ static quicklist * get_island(region * root) region *rn = next[dir]; if (rn != NULL && rn->land && !fval(rn, RF_MARK)) { fset(rn, RF_MARK); - ql_push(&result, rn); + selist_push(&result, rn); } } } - for (ql = result, qi = 0; ql; ql_advance(&ql, &qi, 1)) { - region *r = (region *)ql_get(ql, qi); + for (ql = result, qi = 0; ql; selist_advance(&ql, &qi, 1)) { + region *r = (region *)selist_get(ql, qi); freset(r, RF_MARK); } return result; @@ -342,14 +330,14 @@ static void get_island_info(region * root, int *size_p, int *inhabited_p, int *maxage_p) { int qi, size = 0, maxage = 0, inhabited = 0; - quicklist *ql, *island = NULL; + selist *ql, *island = NULL; - ql_push(&island, root); + selist_push(&island, root); fset(root, RF_MARK); - for (ql = island, qi = 0; ql; ql_advance(&ql, &qi, 1)) { + for (ql = island, qi = 0; ql; selist_advance(&ql, &qi, 1)) { int d; - region *r = (region *)ql_get(ql, qi); + region *r = (region *)selist_get(ql, qi); if (r->units) { unit *u; for (u = r->units; u; u = u->next) { @@ -363,16 +351,16 @@ get_island_info(region * root, int *size_p, int *inhabited_p, int *maxage_p) for (d = 0; d != MAXDIRECTIONS; ++d) { region *rn = rconnect(r, d); if (rn && !fval(rn, RF_MARK) && rn->land) { - ql_push(&island, rn); + selist_push(&island, rn); fset(rn, RF_MARK); } } } - for (ql = island, qi = 0; ql; ql_advance(&ql, &qi, 1)) { - region *r = (region *)ql_get(ql, qi); + for (ql = island, qi = 0; ql; selist_advance(&ql, &qi, 1)) { + region *r = (region *)selist_get(ql, qi); freset(r, RF_MARK); } - ql_free(island); + selist_free(island); if (size_p) *size_p = size; if (inhabited_p) @@ -514,11 +502,11 @@ int autoseed(newfaction ** players, int nsize, int max_agediff) } if (rmin != NULL) { faction *f; - quicklist *ql, *rlist = get_island(rmin); + selist *ql, *rlist = get_island(rmin); int qi; - for (ql = rlist, qi = 0; ql; ql_advance(&ql, &qi, 1)) { - region *r = (region *)ql_get(ql, qi); + for (ql = rlist, qi = 0; ql; selist_advance(&ql, &qi, 1)) { + region *r = (region *)selist_get(ql, qi); unit *u; for (u = r->units; u; u = u->next) { f = u->faction; @@ -528,7 +516,7 @@ int autoseed(newfaction ** players, int nsize, int max_agediff) } } } - ql_free(rlist); + selist_free(rlist); if (psize > 0) { for (f = factions; f; f = f->next) { freset(f, FFL_MARK); @@ -974,8 +962,8 @@ int build_island_e3(newfaction ** players, int x, int y, int numfactions, int mi q = region_quality(r, rn); if (q >= MIN_QUALITY && nfactions < numfactions && *players) { starting_region(players, r, rn); - minq = _min(minq, q); - maxq = _max(maxq, q); + minq = MIN(minq, q); + maxq = MAX(maxq, q); ++nfactions; } } @@ -989,8 +977,8 @@ int build_island_e3(newfaction ** players, int x, int y, int numfactions, int mi q = region_quality(r, rn); if (q >= MIN_QUALITY * 4 / 3 && nfactions < numfactions && *players) { starting_region(players, r, rn); - minq = _min(minq, q); - maxq = _max(maxq, q); + minq = MIN(minq, q); + maxq = MAX(maxq, q); ++nfactions; } } diff --git a/src/modules/autoseed.h b/src/modules/autoseed.h index 3cfe6225c..06ce646c2 100644 --- a/src/modules/autoseed.h +++ b/src/modules/autoseed.h @@ -35,7 +35,6 @@ extern "C" { extern int autoseed(newfaction ** players, int nsize, int max_agediff); extern newfaction *read_newfactions(const char *filename); - extern int fix_demand(struct region *r); extern const struct terrain_type *random_terrain(const struct terrain_type *terrains[], int distribution[], int size); diff --git a/src/modules/gmcmd.c b/src/modules/gmcmd.c index b9e1bc342..c911e3de4 100644 --- a/src/modules/gmcmd.c +++ b/src/modules/gmcmd.c @@ -16,10 +16,8 @@ #include /* misc includes */ -#include #include #include -#include /* kernel includes */ #include @@ -29,7 +27,6 @@ #include #include #include -#include #include #include #include diff --git a/src/modules/museum.c b/src/modules/museum.c index 5ad9092a4..1eee3529f 100644 --- a/src/modules/museum.c +++ b/src/modules/museum.c @@ -32,7 +32,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include #include #include #include @@ -311,7 +310,7 @@ order * ord) unit *warden = findunit(atoi36("mwar")); int unit_cookie; - unused_arg(amount); + UNUSED_ARG(amount); /* Prfen ob in Eingangshalle */ if (u->region->x != 9525 || u->region->y != 9525) { @@ -366,7 +365,7 @@ order * ord) region *r = u->region; plane *pl = rplane(r); - unused_arg(amount); + UNUSED_ARG(amount); /* Pruefen ob in normaler Plane und nur eine Person */ if (pl != get_homeplane()) { @@ -418,8 +417,8 @@ static const char *b_namequestportal(const connection * b, const region * r, { const char *bname; int lock = b->data.i; - unused_arg(b); - unused_arg(r); + UNUSED_ARG(b); + UNUSED_ARG(r); if (gflags & GF_ARTICLE) { if (lock > 0) { @@ -498,9 +497,10 @@ void register_museum(void) at_register(&at_museumgivebackcookie); at_register(&at_museumgiveback); - register_item_use(use_museumticket, "use_museumticket"); - register_item_use(use_museumkey, "use_museumkey"); register_item_use(use_museumexitticket, "use_museumexitticket"); + register_item_use(use_museumticket, "use_museumticket"); + register_item_use(use_museumkey, "use_questkey1"); + register_item_use(use_museumkey, "use_questkey2"); } #endif diff --git a/src/modules/score.c b/src/modules/score.c index 89cf90655..0776d6507 100644 --- a/src/modules/score.c +++ b/src/modules/score.c @@ -67,7 +67,7 @@ void score(void) region *r; faction *fc; score_t allscores = 0; - char path[MAX_PATH]; + char path[4096]; for (fc = factions; fc; fc = fc->next) fc->score = 0; @@ -169,7 +169,7 @@ void score(void) fprintf(scoreFP, "%30.30s (%3.3s) %5s (%3d)\n", f->name, f->race->_name, - factionid(f), + itoa36(f->no), f->age); } fclose(scoreFP); diff --git a/src/modules/score.h b/src/modules/score.h index b0f1b2a91..4fc1f52bb 100644 --- a/src/modules/score.h +++ b/src/modules/score.h @@ -18,6 +18,8 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef SCORE_H #define SCORE_H + +#include #ifdef __cplusplus extern "C" { #endif diff --git a/src/monster.c b/src/monster.c deleted file mode 100644 index 42e334fde..000000000 --- a/src/monster.c +++ /dev/null @@ -1,228 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#include -#include -#include "monster.h" - -/* gamecode includes */ -#include "economy.h" -#include "give.h" -#include "move.h" - -/* attributes includes */ -#include -#include -#include - -/* kernel includes */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* util includes */ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* libc includes */ -#include -#include -#include - -#define MOVECHANCE 25 /* chance fuer bewegung */ - -#define MAXILLUSION_TEXTS 3 - -bool monster_is_waiting(const unit * u) -{ - int test = fval(u_race(u), RCF_ATTACK_MOVED) ? UFL_ISNEW : UFL_ISNEW | UFL_MOVED; - if (fval(u, test)) - return true; - return false; -} - -static void eaten_by_monster(unit * u) -{ - /* adjustment for smaller worlds */ - static double multi = 0.0; - int n = 0; - int horse = -1; - const resource_type *rhorse = get_resourcetype(R_HORSE); - const race *rc = u_race(u); - attrib *a; - - if (multi == 0.0) { - multi = RESOURCE_QUANTITY * newterrain(T_PLAIN)->size / 10000.0; - } - - a = a_find(rc->attribs, &at_scare); - if (a) { - n = rng_int() & a->data.i * u->number; - } else { - n = rng_int() % (u->number / 20 + 1); - horse = 0; - } - horse = horse ? i_get(u->items, rhorse->itype) : 0; - - n = (int)(n * multi); - if (n > 0) { - n = lovar(n); - n = _min(rpeasants(u->region), n); - - if (n > 0) { - deathcounts(u->region, n); - rsetpeasants(u->region, rpeasants(u->region) - n); - ADDMSG(&u->region->msgs, msg_message("eatpeasants", "unit amount", u, n)); - } - } - if (horse > 0) { - i_change(&u->items, rhorse->itype, -horse); - ADDMSG(&u->region->msgs, msg_message("eathorse", "unit amount", u, horse)); - } -} - -static void absorbed_by_monster(unit * u) -{ - int n = rng_int() % (u->number / 20 + 1); - - if (n > 0) { - n = lovar(n); - n = _min(rpeasants(u->region), n); - if (n > 0) { - rsetpeasants(u->region, rpeasants(u->region) - n); - scale_number(u, u->number + n); - ADDMSG(&u->region->msgs, msg_message("absorbpeasants", - "unit race amount", u, u_race(u), n)); - } - } -} - -static int scareaway(region * r, int anzahl) -{ - int n, p, diff = 0, emigrants[MAXDIRECTIONS]; - direction_t d; - - anzahl = _min(_max(1, anzahl), rpeasants(r)); - - /* Wandern am Ende der Woche (normal) oder wegen Monster. Die - * Wanderung wird erst am Ende von demographics () ausgefuehrt. - * emigrants[] ist local, weil r->newpeasants durch die Monster - * vielleicht schon hochgezaehlt worden ist. */ - - for (d = 0; d != MAXDIRECTIONS; d++) - emigrants[d] = 0; - - p = rpeasants(r); - assert(p >= 0 && anzahl >= 0); - for (n = _min(p, anzahl); n; n--) { - direction_t dir = (direction_t)(rng_int() % MAXDIRECTIONS); - region *rc = rconnect(r, dir); - - if (rc && fval(rc->terrain, LAND_REGION)) { - ++diff; - rc->land->newpeasants++; - emigrants[dir]++; - } - } - rsetpeasants(r, p - diff); - assert(p >= diff); - return diff; -} - -static void scared_by_monster(unit * u) -{ - int n; - const race *rc = u_race(u); - attrib *a; - a = a_find(rc->attribs, &at_scare); - if (a) { - n = rng_int() & a->data.i * u->number; - } else { - n = rng_int() % (u->number / 4 + 1); - } - if (n > 0) { - n = lovar(n); - n = _min(rpeasants(u->region), n); - if (n > 0) { - n = scareaway(u->region, n); - if (n > 0) { - ADDMSG(&u->region->msgs, msg_message("fleescared", - "amount unit", n, u)); - } - } - } -} - -void monster_kills_peasants(unit * u) -{ - if (!monster_is_waiting(u)) { - if (u_race(u)->flags & RCF_SCAREPEASANTS) { - scared_by_monster(u); - } - if (u_race(u)->flags & RCF_KILLPEASANTS) { - eaten_by_monster(u); - } - if (u_race(u)->flags & RCF_ABSORBPEASANTS) { - absorbed_by_monster(u); - } - } -} - -faction *get_or_create_monsters(void) -{ - faction *f = findfaction(MONSTER_ID); - if (!f) { - const race *rc = rc_get_or_create("dragon"); - const char *email = config_get("monster.email"); - f = addfaction(email ? email : "noreply@eressea.de", NULL, rc, default_locale, 0); - renumber_faction(f, MONSTER_ID); - faction_setname(f, "Monster"); - fset(f, FFL_NPC | FFL_NOIDLEOUT); - } - return f; -} - -faction *get_monsters(void) { - return get_or_create_monsters(); -} - -void make_zombie(unit * u) -{ - u_setfaction(u, get_monsters()); - scale_number(u, 1); - u->hp = unit_max_hp(u) * u->number; - u_setrace(u, get_race(RC_ZOMBIE)); - u->irace = NULL; -} diff --git a/src/monster.h b/src/monster.h deleted file mode 100644 index 476bcb73e..000000000 --- a/src/monster.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#ifndef H_GC_MONSTER -#define H_GC_MONSTER -#ifdef __cplusplus -extern "C" { -#endif - - struct unit; - - void monster_kills_peasants(struct unit *u); - bool monster_is_waiting(const struct unit *u); - struct faction *get_monsters(void); - struct faction *get_or_create_monsters(void); - void make_zombie(struct unit * u); - -#define MONSTER_ID 666 -#define is_monsters(f) (fval(f, FFL_NPC) && f==get_monsters()) - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/monsters.c b/src/monsters.c index 78999e015..0d9857024 100644 --- a/src/monsters.c +++ b/src/monsters.c @@ -25,7 +25,7 @@ #include "economy.h" #include "chaos.h" #include "give.h" -#include "monster.h" +#include "guard.h" #include "laws.h" #include "keyword.h" #include "study.h" @@ -64,15 +64,15 @@ #include #include -#include +#include /* libc includes */ #include #include #include -#define MOVECHANCE .25 /* chance fuer bewegung */ -#define DRAGON_RANGE 20 /* Max. Distanz zum nchsten Drachenziel */ +#define DRAGON_RANGE 20 /* max. Distanz zum nchsten Drachenziel */ +#define MOVE_PERCENT 25 /* chance fuer bewegung */ #define MAXILLUSION_TEXTS 3 static double attack_chance; /* rules.monsters.attack_chance, or default 0.4 */ @@ -84,7 +84,12 @@ static void give_peasants(unit *u, const item_type *itype, int reduce) { } static double random_move_chance(void) { - return config_get_flt("rules.monsters.random_move_chance", MOVECHANCE); + static int rule; + static int config; + if (config_changed(&config)) { + rule = config_get_int("rules.monsters.random_move_percent", MOVE_PERCENT); + } + return rule * 0.01; } static void reduce_weight(unit * u) @@ -94,7 +99,7 @@ static void reduce_weight(unit * u) int horses = get_resource(u, get_resourcetype(R_HORSE)); if (horses > 0) { - horses = _min(horses, (u->number * 2)); + horses = MIN(horses, (u->number * 2)); change_resource(u, get_resourcetype(R_HORSE), -horses); } @@ -123,7 +128,7 @@ static void reduce_weight(unit * u) if (itype->weight >= 10 && itype->rtype->wtype == 0 && itype->rtype->atype == 0) { if (itype->capacity < itype->weight) { - int reduce = _min(itm->number, -((capacity - weight) / itype->weight)); + int reduce = MIN(itm->number, -((capacity - weight) / itype->weight)); give_peasants(u, itm->type, reduce); weight -= reduce * itype->weight; } @@ -138,7 +143,7 @@ static void reduce_weight(unit * u) const item_type *itype = itm->type; weight += itm->number * itype->weight; if (itype->capacity < itype->weight) { - int reduce = _min(itm->number, -((capacity - weight) / itype->weight)); + int reduce = MIN(itm->number, -((capacity - weight) / itype->weight)); give_peasants(u, itm->type, reduce); weight -= reduce * itype->weight; } @@ -159,6 +164,29 @@ static order *monster_attack(unit * u, const unit * target) return create_order(K_ATTACK, u->faction->locale, "%i", target->no); } +void monsters_desert(struct faction *monsters) +{ + region *r; + + assert(monsters!=NULL); + for (r = regions; r; r = r->next) { + unit *u; + + for (u = r->units; u; u = u->next) { + if (u->faction!=monsters + && (u_race(u)->flags & RCF_DESERT)) { + if (fval(u, UFL_ISNEW)) + continue; + if (rng_int() % 100 < 5) { + ADDMSG(&u->faction->msgs, msg_message("desertion", + "unit region", u, r)); + u_setfaction(u, monsters); + } + } + } + } +} + int monster_attacks(unit * monster, bool respect_buildings, bool rich_only) { region *r = monster->region; @@ -188,7 +216,7 @@ static order *get_money_for_dragon(region * r, unit * udragon, int wanted) /* falls genug geld in der region ist, treiben wir steuern ein. */ if (rmoney(r) >= wanted) { /* 5% chance, dass der drache aus einer laune raus attackiert */ - if (!attacks || chance(1.0 - u_race(udragon)->aggression)) { + if (!attacks) { /* Drachen haben in E3 und E4 keine Einnahmen. Neuer Befehl Pluendern erstmal nur fuer Monster?*/ return create_order(K_LOOT, default_locale, NULL); } @@ -197,7 +225,7 @@ static order *get_money_for_dragon(region * r, unit * udragon, int wanted) /* falls der drache launisch ist, oder das regionssilber knapp, greift er alle an * und holt sich Silber von Einheiten, vorausgesetzt er bewacht bereits */ money = 0; - if (attacks && is_guard(udragon, GUARD_TAX)) { + if (attacks && is_guard(udragon)) { money += monster_attacks(udragon, true, true); } @@ -264,47 +292,57 @@ static direction_t richest_neighbour(region * r, faction * f, int absolut) static bool room_for_race_in_region(region * r, const race * rc) { - unit *u; - int c = 0; + if (rc->splitsize > 0) { + unit *u; + int c = 0; - for (u = r->units; u; u = u->next) { - if (u_race(u) == rc) - c += u->number; + for (u = r->units; u; u = u->next) { + if (u_race(u) == rc) { + c += u->number; + if (c > rc->splitsize * 2) { + return false; + } + } + } } - - if (c > (rc->splitsize * 2)) - return false; - return true; } static direction_t random_neighbour(region * r, unit * u) { int i; - region *rc; - region * next[MAXDIRECTIONS]; + region *next[MAXDIRECTIONS], *backup[MAXDIRECTIONS]; + region **pick; int rr, c = 0, c2 = 0; + const race *rc = u_race(u); get_neighbours(r, next); /* Nachsehen, wieviele Regionen in Frage kommen */ for (i = 0; i != MAXDIRECTIONS; i++) { - rc = next[i]; - if (rc && can_survive(u, rc)) { - if (room_for_race_in_region(rc, u_race(u))) { + region *rn = next[i]; + if (rn && can_survive(u, rn)) { + if (room_for_race_in_region(rn, rc)) { c++; + } else { + next[i] = NULL; } + backup[i] = rn; c2++; + } else { + next[i] = NULL; + backup[i] = NULL; } } + pick = next; if (c == 0) { if (c2 == 0) { return NODIRECTION; } else { + pick = backup; c = c2; - c2 = 0; /* c2 == 0 -> room_for_race nicht beachten */ } } @@ -314,18 +352,14 @@ static direction_t random_neighbour(region * r, unit * u) /* Durchzhlen */ - c = -1; + c = 0; for (i = 0; i != MAXDIRECTIONS; i++) { - rc = next[i]; - if (rc && can_survive(u, rc)) { - if (c2 == 0) { - c++; - } - else if (room_for_race_in_region(rc, u_race(u))) { - c++; - } - if (c == rr) + region *rn = pick[i]; + if (rn) { + if (c == rr) { return (direction_t)i; + } + c++; } } @@ -416,11 +450,11 @@ static attrib *set_new_dragon_target(unit * u, region * r, int range) { int max_affinity = 0; region *max_region = NULL; - quicklist *ql, *rlist = regions_in_range(r, range, allowed_dragon); + selist *ql, *rlist = regions_in_range(r, range, allowed_dragon); int qi; - for (qi = 0, ql = rlist; ql; ql_advance(&ql, &qi, 1)) { - region *r2 = (region *)ql_get(ql, qi); + for (qi = 0, ql = rlist; ql; selist_advance(&ql, &qi, 1)) { + region *r2 = (region *)selist_get(ql, qi); int affinity = dragon_affinity_value(r2, u); if (affinity > max_affinity) { max_affinity = affinity; @@ -428,7 +462,7 @@ static attrib *set_new_dragon_target(unit * u, region * r, int range) } } - ql_free(rlist); + selist_free(rlist); if (max_region && max_region != r) { attrib *a = a_find(u->attribs, &at_targetregion); @@ -541,19 +575,21 @@ static order *monster_learn(unit * u) return NULL; } -static bool check_overpopulated(unit * u) +static bool check_overpopulated(const unit * u) { - unit *u2; - int c = 0; + const race *rc = u_race(u); + if (rc->splitsize > 0) { + unit *u2; + int c = 0; - for (u2 = u->region->units; u2; u2 = u2->next) { - if (u_race(u2) == u_race(u) && u != u2) - c += u2->number; + for (u2 = u->region->units; u2; u2 = u2->next) { + if (u != u2 && u_race(u2) == rc) { + c += u2->number; + if (c > rc->splitsize * 2) + return true; + } + } } - - if (c > u_race(u)->splitsize * 2) - return true; - return false; } @@ -637,7 +673,7 @@ static order *plan_dragon(unit * u) } if (tr != NULL) { assert(long_order == NULL); - // TODO: per-race planning functions? + /* TODO: per-race planning functions? */ if (rc == rc_wyrm) { long_order = make_movement_order(u, tr, 1, allowed_dragon); } @@ -681,7 +717,7 @@ static order *plan_dragon(unit * u) int attempts = 0; skill_t sk = SK_PERCEPTION; /* study perception (or a random useful skill) */ - while ((!skill_enabled(sk) || (attempts < MAXSKILLS && u_race(u)->bonus[sk] < (++attempts < 10?1:-5 )))) { + while (!skill_enabled(sk) || (attempts < MAXSKILLS && u_race(u)->bonus[sk] < (++attempts < 10?1:-5 ))) { sk = (skill_t)(rng_int() % MAXSKILLS); } long_order = create_order(K_STUDY, u->faction->locale, "'%s'", @@ -722,7 +758,7 @@ void plan_monsters(faction * f) setstatus(u, ST_FIGHT); /* all monsters fight */ } - if (attacking && (!r->land || is_guard(u, GUARD_TAX))) { + if (attacking && (!r->land || is_guard(u))) { monster_attacks(u, true, false); } @@ -959,3 +995,162 @@ void spawn_undead(void) } } } + +bool monster_is_waiting(const unit * u) +{ + int test = fval(u_race(u), RCF_ATTACK_MOVED) ? UFL_ISNEW : UFL_ISNEW | UFL_MOVED; + if (fval(u, test)) + return true; + return false; +} + +static void eaten_by_monster(unit * u) +{ + /* adjustment for smaller worlds */ + double multi = RESOURCE_QUANTITY * newterrain(T_PLAIN)->size / 10000.0; + int n = 0; + int horse = -1; + const resource_type *rhorse = get_resourcetype(R_HORSE); + const race *rc = u_race(u); + int scare; + + scare = rc_scare(rc); + if (scare>0) { + n = rng_int() % scare * u->number; + } else { + n = rng_int() % (u->number / 20 + 1); + horse = 0; + } + horse = horse ? i_get(u->items, rhorse->itype) : 0; + + n = (int)(n * multi); + if (n > 0) { + n = lovar(n); + n = MIN(rpeasants(u->region), n); + + if (n > 0) { + deathcounts(u->region, n); + rsetpeasants(u->region, rpeasants(u->region) - n); + ADDMSG(&u->region->msgs, msg_message("eatpeasants", "unit amount", u, n)); + } + } + if (horse > 0) { + i_change(&u->items, rhorse->itype, -horse); + ADDMSG(&u->region->msgs, msg_message("eathorse", "unit amount", u, horse)); + } +} + +static void absorbed_by_monster(unit * u) +{ + int n = rng_int() % (u->number / 20 + 1); + + if (n > 0) { + n = lovar(n); + n = MIN(rpeasants(u->region), n); + if (n > 0) { + rsetpeasants(u->region, rpeasants(u->region) - n); + scale_number(u, u->number + n); + ADDMSG(&u->region->msgs, msg_message("absorbpeasants", + "unit race amount", u, u_race(u), n)); + } + } +} + +static int scareaway(region * r, int anzahl) +{ + int n, p, diff = 0, emigrants[MAXDIRECTIONS]; + direction_t d; + + anzahl = MIN(MAX(1, anzahl), rpeasants(r)); + + /* Wandern am Ende der Woche (normal) oder wegen Monster. Die + * Wanderung wird erst am Ende von demographics () ausgefuehrt. + * emigrants[] ist local, weil r->newpeasants durch die Monster + * vielleicht schon hochgezaehlt worden ist. */ + + for (d = 0; d != MAXDIRECTIONS; d++) + emigrants[d] = 0; + + p = rpeasants(r); + assert(p >= 0 && anzahl >= 0); + for (n = MIN(p, anzahl); n; n--) { + direction_t dir = (direction_t)(rng_int() % MAXDIRECTIONS); + region *rc = rconnect(r, dir); + + if (rc && fval(rc->terrain, LAND_REGION)) { + ++diff; + rc->land->newpeasants++; + emigrants[dir]++; + } + } + rsetpeasants(r, p - diff); + assert(p >= diff); + return diff; +} + +static void scared_by_monster(unit * u) +{ + int n; + const race *rc = u_race(u); + int scare; + + scare = rc_scare(rc); + if (scare>0) { + n = rng_int() % scare * u->number; + } else { + n = rng_int() % (u->number / 4 + 1); + } + if (n > 0) { + n = lovar(n); + n = MIN(rpeasants(u->region), n); + if (n > 0) { + n = scareaway(u->region, n); + if (n > 0) { + ADDMSG(&u->region->msgs, msg_message("fleescared", + "amount unit", n, u)); + } + } + } +} + +void monster_kills_peasants(unit * u) +{ + if (!monster_is_waiting(u)) { + if (u_race(u)->flags & RCF_SCAREPEASANTS) { + scared_by_monster(u); + } + if (u_race(u)->flags & RCF_KILLPEASANTS) { + eaten_by_monster(u); + } + if (u_race(u)->flags & RCF_ABSORBPEASANTS) { + absorbed_by_monster(u); + } + } +} + +faction *get_or_create_monsters(void) +{ + faction *f = findfaction(MONSTER_ID); + if (!f) { + const race *rc = rc_get_or_create("dragon"); + const char *email = config_get("monster.email"); + f = addfaction(email ? email : "noreply@eressea.de", NULL, rc, default_locale, 0); + renumber_faction(f, MONSTER_ID); + faction_setname(f, "Monster"); + fset(f, FFL_NPC | FFL_NOIDLEOUT); + } + return f; +} + +faction *get_monsters(void) { + return get_or_create_monsters(); +} + +void make_zombie(unit * u) +{ + u_setfaction(u, get_monsters()); + scale_number(u, 1); + u->hp = unit_max_hp(u) * u->number; + u_setrace(u, get_race(RC_ZOMBIE)); + u->irace = NULL; +} diff --git a/src/monsters.h b/src/monsters.h index 02e41c0a4..a5a3ccd15 100644 --- a/src/monsters.h +++ b/src/monsters.h @@ -1,8 +1,48 @@ -#pragma once +/* +Copyright (c) 1998-2015, Enno Rehling +Katja Zedel -struct unit; -struct region; -struct faction; +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. -struct unit *spawn_seaserpent(struct region *r, struct faction *f); -void spawn_dragons(void); +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +**/ + +#ifndef H_GC_MONSTER +#define H_GC_MONSTER + +#include + +#ifdef __cplusplus +extern "C" { +#endif + + struct unit; + struct region; + struct faction; + + struct unit *spawn_seaserpent(struct region *r, struct faction *f); + void spawn_dragons(void); + void monsters_desert(struct faction *monsters); + + void monster_kills_peasants(struct unit *u); + bool monster_is_waiting(const struct unit *u); + struct faction *get_monsters(void); + struct faction *get_or_create_monsters(void); + void make_zombie(struct unit * u); + +#define MONSTER_ID 666 +#define is_monsters(f) ((f->flags & FFL_NPC) && f==get_monsters()) + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/monsters.test.c b/src/monsters.test.c index 6797a9ce0..3f2782173 100644 --- a/src/monsters.test.c +++ b/src/monsters.test.c @@ -10,7 +10,6 @@ #include #include -#include "monster.h" #include "monsters.h" #include "guard.h" #include "reports.h" @@ -74,7 +73,7 @@ static void test_monsters_attack(CuTest * tc) create_monsters(&f, &f2, &u, &m); - guard(m, GUARD_TAX); + setguard(m, true); config_set("rules.monsters.attack_chance", "1"); @@ -91,7 +90,7 @@ static void test_monsters_attack_ocean(CuTest * tc) unit *u, *m; create_monsters(&f, &f2, &u, &m); - r = findregion(-1, 0); // ocean + r = findregion(-1, 0); /* ocean */ u = test_create_unit(u->faction, r); unit_setid(u, 2); m = test_create_unit(m->faction, r); @@ -111,7 +110,7 @@ static void test_monsters_waiting(CuTest * tc) unit *u, *m; create_monsters(&f, &f2, &u, &m); - guard(m, GUARD_TAX); + setguard(m, true); fset(m, UFL_ISNEW); monster_attacks(m, false, false); CuAssertPtrEquals(tc, 0, find_order("attack 1", m)); @@ -126,7 +125,7 @@ static void test_seaserpent_piracy(CuTest * tc) race *rc; create_monsters(&f, &f2, &u, &m); - r = findregion(-1, 0); // ocean + r = findregion(-1, 0); /* ocean */ u = test_create_unit(u->faction, r); unit_setid(u, 2); m = test_create_unit(m->faction, r); @@ -150,8 +149,8 @@ static void test_monsters_attack_not(CuTest * tc) create_monsters(&f, &f2, &u, &m); - guard(m, GUARD_TAX); - guard(u, GUARD_TAX); + setguard(m, true); + setguard(u, true); config_set("rules.monsters.attack_chance", "0"); @@ -170,7 +169,7 @@ static void test_dragon_attacks_the_rich(CuTest * tc) create_monsters(&f, &f2, &u, &m); init_resources(); - guard(m, GUARD_TAX); + setguard(m, true); set_level(m, SK_WEAPONLESS, 10); rsetmoney(findregion(0, 0), 1); @@ -199,7 +198,7 @@ static void test_dragon_moves(CuTest * tc) create_monsters(&f, &f2, &u, &m); rsetmoney(findregion(1, 0), 1000); - r = findregion(0, 0); // plain + r = findregion(0, 0); /* plain */ rsetpeasants(r, 0); rsetmoney(r, 0); diff --git a/src/morale.c b/src/morale.c index 8dc22ccb5..67108333e 100644 --- a/src/morale.c +++ b/src/morale.c @@ -31,10 +31,9 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include -static double rc_popularity(const struct race *rc) +static double popularity(void) { - int pop = get_param_int(rc->parameters, "morale", MORALE_AVERAGE); - return 1.0 / (pop - MORALE_COOLDOWN); /* 10 turns average */ + return 1.0 / (MORALE_AVERAGE - MORALE_COOLDOWN); /* 10 turns average */ } void morale_update(region *r) { @@ -52,7 +51,7 @@ void morale_update(region *r) { if (morale < maxmorale) { if (stability > MORALE_COOLDOWN && r->land->ownership->owner && morale < MORALE_MAX) { - double ch = rc_popularity(r->land->ownership->owner->race); + double ch = popularity(); if (is_cursed(r->attribs, C_GENEROUS, 0)) { ch *= 1.2; /* 20% improvement */ } @@ -73,7 +72,7 @@ void morale_update(region *r) { void morale_change(region *r, int value) { int morale = region_get_morale(r); if (morale > 0) { - morale = _max(0, morale - value); + morale = MAX(0, morale - value); region_set_morale(r, morale, turn); } } diff --git a/src/move.c b/src/move.c index 63c79dd6b..8ad25bc5a 100644 --- a/src/move.c +++ b/src/move.c @@ -1,4 +1,4 @@ -/* +/* Copyright (c) 1998-2014, Enno Rehling Katja Zedel #include #include "move.h" +#include "guard.h" #include "laws.h" #include "reports.h" #include "study.h" #include "alchemy.h" #include "travelthru.h" #include "vortex.h" -#include "monster.h" +#include "monsters.h" #include "lighthouse.h" #include "piracy.h" @@ -43,7 +44,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include #include #include #include @@ -151,8 +151,8 @@ static void shiptrail_finalize(attrib * a) static int shiptrail_age(attrib * a, void *owner) { traveldir *t = (traveldir *)(a->data.v); - unused_arg(owner); + (void)owner; t->age--; return (t->age > 0) ? AT_AGE_KEEP : AT_AGE_REMOVE; } @@ -163,6 +163,7 @@ static int shiptrail_read(attrib * a, void *owner, struct gamedata *data) int n; traveldir *t = (traveldir *)(a->data.v); + UNUSED_ARG(owner); READ_INT(store, &t->no); READ_INT(store, &n); t->dir = (direction_t)n; @@ -174,6 +175,8 @@ static void shiptrail_write(const attrib * a, const void *owner, struct storage *store) { traveldir *t = (traveldir *)(a->data.v); + + UNUSED_ARG(owner); WRITE_INT(store, t->no); WRITE_INT(store, t->dir); WRITE_INT(store, t->age); @@ -204,6 +207,8 @@ static bool entrance_allowed(const struct unit *u, const struct region *r) return true; return false; #else + UNUSED_ARG(u); + UNUSED_ARG(r); return true; #endif } @@ -267,12 +272,12 @@ static int ridingcapacity(unit * u) ** tragen nichts (siehe walkingcapacity). Ein Wagen zählt nur, wenn er ** von zwei Pferden gezogen wird */ - animals = _min(animals, effskill(u, SK_RIDING, 0) * u->number * 2); + animals = MIN(animals, effskill(u, SK_RIDING, 0) * u->number * 2); if (fval(u_race(u), RCF_HORSE)) animals += u->number; /* maximal diese Pferde können zum Ziehen benutzt werden */ - vehicles = _min(animals / HORSESNEEDED, vehicles); + vehicles = MIN(animals / HORSESNEEDED, vehicles); return vehicles * vcap + animals * acap; } @@ -291,7 +296,7 @@ int walkingcapacity(const struct unit *u) /* Das Gewicht, welches die Pferde tragen, plus das Gewicht, welches * die Leute tragen */ - pferde_fuer_wagen = _min(animals, effskill(u, SK_RIDING, 0) * u->number * 4); + pferde_fuer_wagen = MIN(animals, effskill(u, SK_RIDING, 0) * u->number * 4); if (fval(u_race(u), RCF_HORSE)) { animals += u->number; people = 0; @@ -301,7 +306,7 @@ int walkingcapacity(const struct unit *u) } /* maximal diese Pferde können zum Ziehen benutzt werden */ - wagen_mit_pferden = _min(vehicles, pferde_fuer_wagen / HORSESNEEDED); + wagen_mit_pferden = MIN(vehicles, pferde_fuer_wagen / HORSESNEEDED); n = wagen_mit_pferden * vcap; @@ -311,7 +316,7 @@ int walkingcapacity(const struct unit *u) wagen_ohne_pferde = vehicles - wagen_mit_pferden; /* Genug Trolle, um die Restwagen zu ziehen? */ - wagen_mit_trollen = _min(u->number / 4, wagen_ohne_pferde); + wagen_mit_trollen = MIN(u->number / 4, wagen_ohne_pferde); /* Wagenkapazität hinzuzählen */ n += wagen_mit_trollen * vcap; @@ -335,7 +340,7 @@ int walkingcapacity(const struct unit *u) int belts = i_get(u->items, rbelt->itype); if (belts) { int multi = config_get_int("rules.trollbelt.multiplier", STRENGTHMULTIPLIER); - n += _min(people, belts) * (multi - 1) * u_race(u)->capacity; + n += MIN(people, belts) * (multi - 1) * u_race(u)->capacity; } } @@ -366,7 +371,7 @@ static int canwalk(unit * u) effsk = effskill(u, SK_RIDING, 0); maxwagen = effsk * u->number * 2; if (u_race(u) == get_race(RC_TROLL)) { - maxwagen = _max(maxwagen, u->number / 4); + maxwagen = MAX(maxwagen, u->number / 4); } maxpferde = effsk * u->number * 4 + u->number; @@ -466,6 +471,8 @@ static int canride(unit * u) static bool cansail(const region * r, ship * sh) { + UNUSED_ARG(r); + /* sonst ist construction:: size nicht ship_type::maxsize */ assert(!sh->type->construction || sh->type->construction->improvement == NULL); @@ -490,6 +497,8 @@ static bool cansail(const region * r, ship * sh) static double overload(const region * r, ship * sh) { + UNUSED_ARG(r); + /* sonst ist construction:: size nicht ship_type::maxsize */ assert(!sh->type->construction || sh->type->construction->improvement == NULL); @@ -500,12 +509,12 @@ static double overload(const region * r, ship * sh) else { int n = 0, p = 0; int mcabins = sh->type->cabins; + double ovl; getshipweight(sh, &n, &p); - - double ovl = n / (double)sh->type->cargo; + ovl = n / (double)sh->type->cargo; if (mcabins) - ovl = _max(ovl, p / (double)mcabins); + ovl = MAX(ovl, p / (double)mcabins); return ovl; } } @@ -571,7 +580,7 @@ direction_t reldirection(const region * from, const region * to) return NODIRECTION; } -static void leave_trail(ship * sh, region * from, region_list * route) +void leave_trail(ship * sh, region * from, region_list * route) { region *r = from; @@ -595,7 +604,7 @@ static void leave_trail(ship * sh, region * from, region_list * route) a = a->next; } - if (a == NULL) { + if (a == NULL || a->type != &at_shiptrail) { a = a_add(&(r->attribs), a_new(&at_shiptrail)); td = (traveldir *)a->data.v; td->no = sh->no; @@ -752,7 +761,7 @@ double damage_overload(double overload) badness = overload - overload_worse(); if (badness >= 0) { assert(overload_worst() > overload_worse() || !"overload.worst must be > overload.worse"); - damage += _min(badness, overload_worst() - overload_worse()) * + damage += MIN(badness, overload_worst() - overload_worse()) * (overload_max_damage() - damage) / (overload_worst() - overload_worse()); } @@ -792,7 +801,7 @@ region * drift_target(ship *sh) { if (rn != NULL && check_ship_allowed(sh, rn) >= 0) { rnext = rn; if (!fval(rnext->terrain, SEA_REGION)) { - // prefer drifting towards non-ocean regions + /* prefer drifting towards non-ocean regions */ break; } } @@ -934,7 +943,7 @@ static unit *bewegung_blockiert_von(unit * reisender, region * r) if (fval(u_race(reisender), RCF_ILLUSIONARY)) return NULL; for (u = r->units; u; u = u->next) { - if (is_guard(u, GUARD_TRAVELTHRU)) { + if (is_guard(u)) { int sk = effskill(u, SK_PERCEPTION, r); if (invisible(reisender, u) >= reisender->number) continue; @@ -943,10 +952,10 @@ static unit *bewegung_blockiert_von(unit * reisender, region * r) if ((u->faction == reisender->faction) || (ucontact(u, reisender)) || (alliedunit(u, reisender->faction, HELP_GUARD))) guard_count = guard_count - u->number; else if (sk >= stealth) { - guard_count += u->number; double prob_u = (sk - stealth) * skill_prob; + guard_count += u->number; /* amulet counts at most once */ - prob_u += _min(1, _min(u->number, i_get(u->items, ramulet->itype))) * amulet_prob; + prob_u += MIN(1, MIN(u->number, i_get(u->items, ramulet->itype))) * amulet_prob; if (u->building && (u->building->type == castle_bt) && u == building_owner(u->building)) prob_u += castle_prob*buildingeffsize(u->building, 0); if (prob_u >= prob) { @@ -977,82 +986,6 @@ static unit *bewegung_blockiert_von(unit * reisender, region * r) return NULL; } -static bool is_guardian_u(const unit * guard, unit * u, unsigned int mask) -{ - if (guard->faction == u->faction) - return false; - if (is_guard(guard, mask) == 0) - return false; - if (alliedunit(guard, u->faction, HELP_GUARD)) - return false; - if (ucontact(guard, u)) - return false; - if (!cansee(guard->faction, u->region, u, 0)) - return false; - if (!(u_race(guard)->flags & RCF_FLY) && u_race(u)->flags & RCF_FLY) - return false; - - return true; -} - -static bool is_guardian_r(const unit * guard) -{ - if (guard->number == 0) - return false; - if (besieged(guard)) - return false; - - /* if region_owners exist then they may be guardians: */ - if (guard->building && rule_region_owners() && guard == building_owner(guard->building)) { - faction *owner = region_get_owner(guard->region); - if (owner == guard->faction) { - building *bowner = largestbuilding(guard->region, &cmp_taxes, false); - if (bowner == guard->building) { - return true; - } - } - } - - if ((guard->flags & UFL_GUARD) == 0) - return false; - return armedmen(guard, true) > 0 || fval(u_race(guard), RCF_UNARMEDGUARD); -} - -bool is_guard(const struct unit * u, unsigned int mask) -{ - return is_guardian_r(u) && (getguard(u) & mask) != 0; -} - -unit *is_guarded(region * r, unit * u, unsigned int mask) -{ - unit *u2; - int noguards = 1; - - if (!fval(r, RF_GUARDED)) { - return NULL; - } - - /* at this point, u2 is the last unit we tested to - * be a guard (and failed), or NULL - * i is the position of the first free slot in the cache */ - - for (u2 = r->units; u2; u2 = u2->next) { - if (is_guardian_r(u2)) { - noguards = 0; - if (is_guardian_u(u2, u, mask)) { - /* u2 is our guard. stop processing (we might have to go further next time) */ - return u2; - } - } - } - - if (noguards) { - /* you are mistaken, sir. there are no guards in these lands */ - freset(r, RF_GUARDED); - } - return NULL; -} - bool move_blocked(const unit * u, const region * r, const region * r2) { connection *b; @@ -1316,9 +1249,9 @@ static bool roadto(const region * r, direction_t dir) if (!r || dir >= MAXDIRECTIONS || dir < 0) return false; r2 = rconnect(r, dir); - if (r == NULL || r2 == NULL) + if (!r2) { return false; - + } if (r->attribs || r2->attribs) { const curse_type *roads_ct = ct_find("magicstreet"); if (roads_ct != NULL) { @@ -1473,7 +1406,7 @@ static int movement_speed(unit * u) return BP_DRAGON; } switch (old_race(u_race(u))) { - case RC_BIRTHDAYDRAGON: // FIXME: catdragon has RCF_DRAGON, so this cannot happen + case RC_BIRTHDAYDRAGON: /* FIXME: catdragon has RCF_DRAGON, so this cannot happen */ case RC_SONGDRAGON: mp = BP_DRAGON; break; @@ -1540,9 +1473,9 @@ static arg_regions *var_copy_regions(const region_list * begin, int size) if (size > 0) { int i = 0; + arg_regions *dst; assert(size > 0); - arg_regions *dst = - (arg_regions *)malloc(sizeof(arg_regions) + sizeof(region *) * (size_t)size); + dst = (arg_regions *)malloc(sizeof(arg_regions) + sizeof(region *) * (size_t)size); assert_alloc(dst); dst->nregions = size; dst->regions = (region **)(dst + 1); @@ -1691,7 +1624,7 @@ static const region_list *travel_route(unit * u, /* the unit has moved at least one region */ int walkmode; - setguard(u, GUARD_NONE); + setguard(u, false); cycle_route(ord, u, steps); if (mode == TRAVEL_RUNNING) { @@ -1719,7 +1652,7 @@ static const region_list *travel_route(unit * u, /* make orders for the followers */ } fset(u, UFL_LONGACTION | UFL_NOTMOVING); - setguard(u, GUARD_NONE); + setguard(u, false); assert(u->region == current); return iroute; } @@ -1790,7 +1723,7 @@ bool can_takeoff(const ship * sh, const region * from, const region * to) return true; } -static void sail(unit * u, order * ord, region_list ** routep) +static void sail(unit * u, order * ord, region_list ** routep, bool drifting) { region *starting_point = u->region; region *current_point, *last_point; @@ -1800,8 +1733,8 @@ static void sail(unit * u, order * ord, region_list ** routep) faction *f = u->faction; region *next_point = NULL; int error; - double damage_storm = config_get_flt("rules.ship.damage_storm", 0.02); - bool storms_enabled = config_get_int("rules.ship.storms", 1) != 0; + bool storms_enabled = drifting && (config_get_int("rules.ship.storms", 1) != 0); + double damage_storm = storms_enabled ? config_get_flt("rules.ship.damage_storm", 0.02) : 0.0; int lighthouse_div = config_get_int("rules.storm.lighthouse.divisor", 0); const char *token = getstrtoken(); @@ -1837,8 +1770,6 @@ static void sail(unit * u, order * ord, region_list ** routep) * befahrene Region. */ while (next_point && current_point != next_point && step < k) { - const char *token; - int error; const terrain_type *tthis = current_point->terrain; /* these values need to be updated if next_point changes (due to storms): */ const terrain_type *tnext = next_point->terrain; @@ -1909,7 +1840,7 @@ static void sail(unit * u, order * ord, region_list ** routep) } } } - } // storms_enabled + } /* storms_enabled */ if (!fval(tthis, SEA_REGION)) { if (!fval(tnext, SEA_REGION)) { /* check that you're not traveling from one land region to another. */ @@ -2061,7 +1992,7 @@ static void sail(unit * u, order * ord, region_list ** routep) const luxury_type *ltype = resource2luxury(itm->type->rtype); if (ltype != NULL && itm->number > 0) { int st = itm->number * effskill(harbourmaster, SK_TRADE, 0) / 50; - st = _min(itm->number, st); + st = MIN(itm->number, st); if (st > 0) { i_change(&u2->items, itm->type, -st); @@ -2130,7 +2061,9 @@ static const region_list *travel_i(unit * u, const region_list * route_begin, route_end = cap_route(r, route_begin, route_end, movement_speed(u)); route_end = travel_route(u, route_begin, route_end, ord, mode); - get_followers(u, r, route_end, followers); + if (u->flags&UFL_FOLLOWED) { + get_followers(u, r, route_end, followers); + } /* transportation */ for (ord = u->orders; ord; ord = ord->next) { @@ -2217,7 +2150,7 @@ static void travel(unit * u, region_list ** routep) sh = NULL; } if (sh) { - unit *guard = is_guarded(r, u, GUARD_LANDING); + unit *guard = is_guarded(r, u); if (guard) { ADDMSG(&u->faction->msgs, msg_feedback(u, u->thisorder, "region_guarded", "guard", guard)); @@ -2277,7 +2210,8 @@ void move_cmd(unit * u, order * ord) assert(u->number); if (u->ship && u == ship_owner(u->ship)) { - sail(u, ord, &route); + bool drifting = (getkeyword(ord) == K_MOVE); + sail(u, ord, &route, drifting); } else { travel(u, &route); diff --git a/src/move.h b/src/move.h index 70dddbb0b..4d0b4e9f2 100644 --- a/src/move.h +++ b/src/move.h @@ -16,11 +16,12 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ +#include "direction.h" +#include + #ifndef H_KRNL_MOVEMENT #define H_KRNL_MOVEMENT -#include "direction.h" - #ifdef __cplusplus extern "C" { #endif @@ -60,11 +61,11 @@ extern "C" { int personcapacity(const struct unit *u); void movement(void); void run_to(struct unit *u, struct region *to); - struct unit *is_guarded(struct region *r, struct unit *u, unsigned int mask); - bool is_guard(const struct unit *u, unsigned int mask); int enoughsailors(const struct ship *sh, int sumskill); bool canswim(struct unit *u); bool canfly(struct unit *u); + void leave_trail(struct ship *sh, struct region *from, + struct region_list *route); struct ship *move_ship(struct ship *sh, struct region *from, struct region *to, struct region_list *route); int walkingcapacity(const struct unit *u); diff --git a/src/move.test.c b/src/move.test.c index 2ce9cccda..c444fe4a8 100644 --- a/src/move.test.c +++ b/src/move.test.c @@ -2,8 +2,8 @@ #include #include "move.h" -#include "guard.h" #include "keyword.h" +#include "lighthouse.h" #include #include @@ -201,30 +201,6 @@ static void test_walkingcapacity(CuTest *tc) { test_cleanup(); } -static void test_is_guarded(CuTest *tc) { - unit *u1, *u2; - region *r; - race *rc; - - test_cleanup(); - rc = rc_get_or_create("dragon"); - rc->flags |= RCF_UNARMEDGUARD; - r = test_create_region(0, 0, 0); - u1 = test_create_unit(test_create_faction(0), r); - u2 = test_create_unit(test_create_faction(rc), r); - CuAssertPtrEquals(tc, 0, is_guarded(r, u1, GUARD_TRAVELTHRU)); - CuAssertPtrEquals(tc, 0, is_guarded(r, u1, GUARD_PRODUCE)); - CuAssertPtrEquals(tc, 0, is_guarded(r, u1, GUARD_TREES)); - CuAssertPtrEquals(tc, 0, is_guarded(r, u1, GUARD_MINING)); - guard(u2, GUARD_MINING | GUARD_PRODUCE); - CuAssertIntEquals(tc, GUARD_CREWS | GUARD_LANDING | GUARD_TRAVELTHRU | GUARD_TAX | GUARD_PRODUCE | GUARD_RECRUIT, guard_flags(u2)); - CuAssertPtrEquals(tc, 0, is_guarded(r, u1, GUARD_TRAVELTHRU)); - CuAssertPtrEquals(tc, 0, is_guarded(r, u1, GUARD_TREES)); - CuAssertPtrEquals(tc, 0, is_guarded(r, u1, GUARD_MINING)); - CuAssertPtrEquals(tc, u2, is_guarded(r, u1, GUARD_PRODUCE)); - test_cleanup(); -} - static void test_ship_trails(CuTest *tc) { ship *sh; region *r1, *r2, *r3; @@ -298,10 +274,10 @@ void setup_drift (struct drift_fixture *fix) { fix->st_boat->cabins = 20000; fix->u = test_create_unit(fix->f = test_create_faction(0), fix->r=findregion(-1,0)); - assert(fix->r); + assert(fix->r && fix->u && fix->f); set_level(fix->u, SK_SAILING, fix->st_boat->sumskill); u_set_ship(fix->u, fix->sh = test_create_ship(fix->u->region, fix->st_boat)); - assert(fix->f && fix->u && fix->sh); + assert(fix->sh); } static void test_ship_no_overload(CuTest *tc) { @@ -458,8 +434,9 @@ static void test_follow_ship_msg(CuTest * tc) { order *ord; traveldir *td = NULL; attrib *a; - - test_cleanup(); + void *p; + + test_setup(); test_create_world(); f = test_create_faction(0); r = findregion(0, 0); @@ -491,7 +468,7 @@ static void test_follow_ship_msg(CuTest * tc) { follow_ship(u, ord); CuAssertPtrNotNull(tc, msg = test_find_messagetype(u->faction->msgs, "error18")); - void *p = msg->parameters[2].v; + p = msg->parameters[2].v; CuAssertPtrNotNull(tc, p); CuAssertIntEquals(tc, K_FOLLOW, getkeyword((order *)p)); @@ -503,7 +480,7 @@ static void test_drifting_ships(CuTest *tc) { region *r1, *r2, *r3; terrain_type *t_ocean, *t_plain; ship_type *st_boat; - test_cleanup(); + test_setup(); t_ocean = test_create_terrain("ocean", SEA_REGION); t_plain = test_create_terrain("plain", LAND_REGION); r1 = test_create_region(0, 0, t_ocean); @@ -516,17 +493,46 @@ static void test_drifting_ships(CuTest *tc) { test_cleanup(); } +static void test_ship_leave_trail(CuTest *tc) { + ship *s1, *s2; + region *r1, *r2; + terrain_type *t_ocean; + ship_type *st_boat; + region_list *route = NULL; + + test_setup(); + t_ocean = test_create_terrain("ocean", SEA_REGION); + r1 = test_create_region(0, 0, t_ocean); + add_regionlist(&route, test_create_region(2, 0, t_ocean)); + add_regionlist(&route, r2 = test_create_region(1, 0, t_ocean)); + st_boat = test_create_shiptype("boat"); + s1 = test_create_ship(r1, st_boat); + s2 = test_create_ship(r1, st_boat); + leave_trail(s1, r1, route); + a_add(&r1->attribs, a_new(&at_lighthouse)); + leave_trail(s2, r1, route); + a_add(&r2->attribs, a_new(&at_lighthouse)); + CuAssertPtrEquals(tc, &at_shiptrail, (void *)r1->attribs->type); + CuAssertPtrEquals(tc, &at_shiptrail, (void *)r1->attribs->next->type); + CuAssertPtrEquals(tc, &at_lighthouse, (void *)r1->attribs->next->next->type); + CuAssertPtrEquals(tc, &at_shiptrail, (void *)r2->attribs->type); + CuAssertPtrEquals(tc, &at_shiptrail, (void *)r2->attribs->next->type); + CuAssertPtrEquals(tc, &at_lighthouse, (void *)r2->attribs->next->next->type); + free_regionlist(route); + test_cleanup(); +} + CuSuite *get_move_suite(void) { CuSuite *suite = CuSuiteNew(); SUITE_ADD_TEST(suite, test_walkingcapacity); SUITE_ADD_TEST(suite, test_ship_not_allowed_in_coast); + SUITE_ADD_TEST(suite, test_ship_leave_trail); SUITE_ADD_TEST(suite, test_ship_allowed_without_harbormaster); SUITE_ADD_TEST(suite, test_ship_blocked_by_harbormaster); SUITE_ADD_TEST(suite, test_ship_has_harbormaster_contact); SUITE_ADD_TEST(suite, test_ship_has_harbormaster_ally); SUITE_ADD_TEST(suite, test_ship_has_harbormaster_same_faction); - SUITE_ADD_TEST(suite, test_is_guarded); SUITE_ADD_TEST(suite, test_ship_trails); SUITE_ADD_TEST(suite, test_age_trails); SUITE_ADD_TEST(suite, test_ship_no_overload); diff --git a/src/names.c b/src/names.c index 99c21a05e..bc740a704 100644 --- a/src/names.c +++ b/src/names.c @@ -45,13 +45,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include -static const char *describe_race(const race * rc, const struct locale *lang) -{ - char zText[32]; - sprintf(zText, "describe_%s", rc->_name); - return locale_getstring(lang, zText); -} - static void count_particles(const char *monster, int *num_prefix, int *num_name, int *num_postfix) { char zText[32]; @@ -219,15 +212,6 @@ const char *silbe3[SIL3] = { "bus", }; -static void generic_name(unit * u) -{ - const char * name = rc_name_s(u_race(u), (u->number == 1) ? NAME_SINGULAR : NAME_PLURAL); - name = LOC(u->faction->locale, name); - if (name) { - unit_setname(u, name); - } -} - static void dragon_name(unit * u) { char name[NAMESIZE + 1]; @@ -284,7 +268,7 @@ static void dragon_name(unit * u) if (u->number > 1) { const char *no_article = strchr((const char *)str, ' '); assert(no_article); - // TODO: localization + /* TODO: localization */ sprintf(name, "Die %sn von %s", no_article + 1, rname(u->region, default_locale)); } @@ -369,7 +353,7 @@ static void dracoid_name(unit * u) size_t sz; /* ignore u */ - unused_arg(u); + UNUSED_ARG(u); /* Wieviele Mittelteile? */ mid_syllabels = rng_int() % 4; @@ -398,30 +382,30 @@ const char *abkz(const char *s, char *buf, size_t buflen, size_t maxchars) size_t size; int result; - /* Prfen, ob Kurz genug */ - + UNUSED_ARG(buflen); + /* Pr�fen, ob Kurz genug */ if (strlen(s) <= maxchars) { return s; } - /* Anzahl der Wrter feststellen */ + /* Anzahl der W�rter feststellen */ while (*p != 0) { result = unicode_utf8_to_ucs4(&ucs, p, &size); assert(result == 0 || "damnit, we're not handling invalid input here!"); - /* Leerzeichen berspringen */ + /* Leerzeichen �berspringen */ while (*p != 0 && !iswalnum((wint_t)ucs)) { p += size; result = unicode_utf8_to_ucs4(&ucs, p, &size); assert(result == 0 || "damnit, we're not handling invalid input here!"); } - /* Counter erhhen */ + /* Counter erh�hen */ if (*p != 0) ++c; - /* alnums berspringen */ + /* alnums �berspringen */ while (*p != 0 && iswalnum((wint_t)ucs)) { p += size; result = unicode_utf8_to_ucs4(&ucs, p, &size); @@ -429,10 +413,10 @@ const char *abkz(const char *s, char *buf, size_t buflen, size_t maxchars) } } - /* Buchstaben pro Teilkrzel = _max(1,max/AnzWort) */ - bpt = (c > 0) ? _max(1, maxchars / c) : 1; + /* Buchstaben pro Teilk�rzel = MAX(1,max/AnzWort) */ + bpt = (c > 0) ? MAX(1, maxchars / c) : 1; - /* Einzelne Wrter anspringen und jeweils die ersten BpT kopieren */ + /* Einzelne W�rter anspringen und jeweils die ersten BpT kopieren */ p = s; c = 0; @@ -442,7 +426,7 @@ const char *abkz(const char *s, char *buf, size_t buflen, size_t maxchars) assert(result == 0 || "damnit, we're not handling invalid input here!"); while (*p != 0 && c < maxchars) { - /* Leerzeichen berspringen */ + /* Leerzeichen �berspringen */ while (*p != 0 && !iswalnum((wint_t)ucs)) { p += size; @@ -450,7 +434,7 @@ const char *abkz(const char *s, char *buf, size_t buflen, size_t maxchars) assert(result == 0 || "damnit, we're not handling invalid input here!"); } - /* alnums bertragen */ + /* alnums �bertragen */ for (i = 0; i < bpt && *p != 0 && iswalnum((wint_t)ucs); ++i) { memcpy(bufp, p, size); @@ -462,7 +446,7 @@ const char *abkz(const char *s, char *buf, size_t buflen, size_t maxchars) assert(result == 0 || "damnit, we're not handling invalid input here!"); } - /* Bis zum nchsten Leerzeichen */ + /* Bis zum n�chsten Leerzeichen */ while (c < maxchars && *p != 0 && iswalnum((wint_t)ucs)) { p += size; @@ -478,15 +462,16 @@ const char *abkz(const char *s, char *buf, size_t buflen, size_t maxchars) void register_names(void) { - register_race_description_function(describe_race, "describe_race"); /* function name * generate a name for a nonplayerunit - * race->generate_name() */ - register_race_name_function(undead_name, "nameundead"); - register_race_name_function(skeleton_name, "nameskeleton"); - register_race_name_function(zombie_name, "namezombie"); - register_race_name_function(ghoul_name, "nameghoul"); - register_race_name_function(dracoid_name, "namedracoid"); - register_race_name_function(dragon_name, "namedragon"); - register_race_name_function(generic_name, "namegeneric"); + * race->name_unit() */ + + register_race_function(undead_name, "name_undead"); + register_race_function(skeleton_name, "name_skeleton"); + register_race_function(zombie_name, "name_zombie"); + register_race_function(ghoul_name, "name_ghoul"); + register_race_function(dracoid_name, "name_dracoid"); + register_race_function(dragon_name, "name_dragon"); + register_race_function(dragon_name, "name_youngdragon"); + register_race_function(dragon_name, "name_wyrm"); } diff --git a/src/names.h b/src/names.h index 63e9c8628..d7ab417c1 100644 --- a/src/names.h +++ b/src/names.h @@ -18,6 +18,9 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef H_KRNL_NAMES #define H_KRNL_NAMES + +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/src/names.test.c b/src/names.test.c index f50937f17..7d62d4752 100644 --- a/src/names.test.c +++ b/src/names.test.c @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -12,27 +13,51 @@ static void test_names(CuTest * tc) { - race_name_func foo; unit *u; race *rc; test_cleanup(); register_names(); + CuAssertPtrNotNull(tc, get_function("name_undead")); + CuAssertPtrNotNull(tc, get_function("name_skeleton")); + CuAssertPtrNotNull(tc, get_function("name_zombie")); + CuAssertPtrNotNull(tc, get_function("name_ghoul")); + CuAssertPtrNotNull(tc, get_function("name_dragon")); + CuAssertPtrNotNull(tc, get_function("name_youngdragon")); + CuAssertPtrNotNull(tc, get_function("name_wyrm")); + CuAssertPtrNotNull(tc, get_function("name_dracoid")); default_locale = test_create_locale(); - u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); rc = test_create_race("undead"); + u = test_create_unit(test_create_faction(rc), test_create_region(0, 0, 0)); locale_setstring(default_locale, "undead_name_0", "Graue"); locale_setstring(default_locale, "undead_postfix_0", "Kobolde"); - CuAssertPtrNotNull(tc, foo = (race_name_func)get_function("nameundead")); - rc->generate_name = foo; - race_namegen(rc, u); + CuAssertPtrNotNull(tc, rc->name_unit); + CuAssertTrue(tc, rc->name_unit == (race_func)get_function("name_undead")); + name_unit(u); CuAssertStrEquals(tc, "Graue Kobolde", u->_name); - CuAssertPtrNotNull(tc, get_function("nameskeleton")); - CuAssertPtrNotNull(tc, get_function("namezombie")); - CuAssertPtrNotNull(tc, get_function("nameghoul")); - CuAssertPtrNotNull(tc, get_function("namedragon")); - CuAssertPtrNotNull(tc, get_function("namedracoid")); - CuAssertPtrNotNull(tc, get_function("namegeneric")); - CuAssertPtrNotNull(tc, get_function("describe_race")); + test_cleanup(); +} + +static void test_monster_names(CuTest *tc) { + unit *u; + faction *f; + race *rc; + + test_setup(); + register_names(); + default_locale = test_create_locale(); + locale_setstring(default_locale, "race::irongolem", "Eisengolem"); + locale_setstring(default_locale, "race::irongolem_p", "Eisengolems"); + rc = test_create_race("irongolem"); + f = test_create_faction(rc); + f->flags |= FFL_NPC; + u = test_create_unit(f, test_create_region(0, 0, 0)); + unit_setname(u, "Hodor"); + CuAssertPtrNotNull(tc, u->_name); + name_unit(u); + CuAssertPtrEquals(tc, NULL, u->_name); + CuAssertStrEquals(tc, "Eisengolem", unit_getname(u)); + u->number = 2; + CuAssertStrEquals(tc, "Eisengolems", unit_getname(u)); test_cleanup(); } @@ -40,5 +65,6 @@ CuSuite *get_names_suite(void) { CuSuite *suite = CuSuiteNew(); SUITE_ADD_TEST(suite, test_names); + SUITE_ADD_TEST(suite, test_monster_names); return suite; } diff --git a/src/piracy.c b/src/piracy.c index b2f96c596..80b1dd47a 100644 --- a/src/piracy.c +++ b/src/piracy.c @@ -149,8 +149,8 @@ void piracy_cmd(unit * u) region *rc = rconnect(r, dir); aff[dir].value = 0; aff[dir].target = 0; - // TODO this could still result in an illegal movement order (through a wall or whatever) - // which will be prevented by move_cmd below + /* TODO this could still result in an illegal movement order (through a wall or whatever) + * which will be prevented by move_cmd below */ if (rc && ((sh && !fval(rc->terrain, FORBIDDEN_REGION) && can_takeoff(sh, r, rc)) || (canswim(u) && fval(rc->terrain, SWIM_INTO) && fval(rc->terrain, SEA_REGION)))) { @@ -161,7 +161,8 @@ void piracy_cmd(unit * u) faction *f = visible_faction(cap->faction, cap); if (alliedunit(u, f, HELP_FIGHT)) continue; - if (!il || intlist_find(il, cap->faction->no)) { // TODO: shouldn't this be f->no? + if (!il || intlist_find(il, cap->faction->no)) { + /* TODO: shouldn't this be f->no? */ ++aff[dir].value; if (rng_int() % aff[dir].value == 0) { aff[dir].target = f; @@ -202,8 +203,8 @@ void piracy_cmd(unit * u) "ship unit region dir", sh, u, r, target_dir)); /* Befehl konstruieren */ - // TODO: why change u->thisorder? - // FIXME: when u->thisorder == ord, set_order calls free, destroys both. + /* TODO: why change u->thisorder? */ + /* FIXME: when u->thisorder == ord, set_order calls free, destroys both. */ ord = create_order(K_MOVE, u->faction->locale, "%s", LOC(u->faction->locale, directions[target_dir])); /* Bewegung ausfhren */ diff --git a/src/piracy.test.c b/src/piracy.test.c index affb6f5c4..d690776f1 100644 --- a/src/piracy.test.c +++ b/src/piracy.test.c @@ -83,12 +83,12 @@ static void test_piracy_cmd(CuTest * tc) { t_ocean = get_or_create_terrain("ocean"); st_boat = st_get_or_create("boat"); u2 = test_create_unit(test_create_faction(0), test_create_region(1, 0, t_ocean)); - u_set_ship(u2, test_create_ship(u2->region, st_boat)); assert(u2); + u_set_ship(u2, test_create_ship(u2->region, st_boat)); u = test_create_unit(f = test_create_faction(0), r = test_create_region(0, 0, t_ocean)); + assert(f && u); set_level(u, SK_SAILING, st_boat->sumskill); u_set_ship(u, test_create_ship(u->region, st_boat)); - assert(f && u); f->locale = get_or_create_locale("de"); u->thisorder = create_order(K_PIRACY, f->locale, "%s", itoa36(u2->faction->no)); @@ -97,7 +97,7 @@ static void test_piracy_cmd(CuTest * tc) { CuAssertTrue(tc, u->region != r); CuAssertPtrEquals(tc, u2->region, u->region); CuAssertPtrEquals(tc, u2->region, u->ship->region); - CuAssertPtrNotNullMsg(tc, "successful PIRACY sets attribute", r->attribs); // FIXME: this is testing implementation, not interface + CuAssertPtrNotNullMsg(tc, "successful PIRACY sets attribute", r->attribs); /* FIXME: this is testing implementation, not interface */ CuAssertPtrNotNullMsg(tc, "successful PIRACY message", test_find_messagetype(f->msgs, "piratesawvictim")); CuAssertPtrNotNullMsg(tc, "successful PIRACY movement", test_find_messagetype(f->msgs, "shipsail")); @@ -183,14 +183,14 @@ static void test_piracy_cmd_land_to_land(CuTest * tc) { t_plain = get_or_create_terrain("plain"); stype = test_create_shiptype("boat"); - // create a target: + /* create a target: */ r = test_create_region(0, 0, t_plain); f = test_create_faction(0); u = test_create_unit(f, r); u->ship = test_create_ship(r, stype); target = f->no; - // create a pirate: + /* create a pirate: */ r = test_create_region(1, 0, t_plain); f = test_create_faction(0); u = test_create_unit(f, r); diff --git a/src/platform.h b/src/platform.h index 77a767875..6ccbb8d6d 100644 --- a/src/platform.h +++ b/src/platform.h @@ -1,133 +1,46 @@ -/* -Copyright (c) 1998-2015, Enno Rehling - Katja Zedel +#pragma once -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#ifndef CONFIG_H -#define CONFIG_H - -#ifdef NDEBUG -#define LOMEM -#endif +#ifndef UNILIB_H +#define UNILIB_H #ifdef _MSC_VER -# define VC_EXTRALEAN -# define WIN32_LEAN_AND_MEAN -#pragma warning(push) -#pragma warning(disable:4820 4255 4668) -# include -# include -#pragma warning(pop) -# undef MOUSE_MOVED -# define STDIO_CP 1252 /* log.c, convert to console character set */ -# pragma warning (disable: 4201 4214 4514 4115 4711) -#if _MSC_VER >= 1900 -# pragma warning(disable: 4710) -/* warning C4710: function not inlined */ -# pragma warning(disable: 4456) -/* warning C4456 : declaration of hides previous local declaration */ -# pragma warning(disable: 4457) -/* warning C4457: declaration of hides function parameter */ -# pragma warning(disable: 4459) -/* warning C4459: declaration of hides global declaration */ +#ifndef __STDC__ +#define __STDC__ 1 // equivalent to /Za #endif -# pragma warning(disable: 4056) -/* warning C4056: overflow in floating point constant arithmetic */ -# pragma warning(disable: 4201) -/* warning C4201: nonstandard extension used : nameless struct/union */ -# pragma warning(disable: 4214) -/* warning C4214: nonstandard extension used : bit field types other than int */ -# pragma warning(disable: 4100) -/* warning C4100: : unreferenced formal parameter */ -# pragma warning(disable: 4996) -/* is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */ -# pragma warning(disable: 4668) -/* : bytes padding after data member */ -# pragma warning(disable: 4820) - -/* warning C4100: was declared deprecated */ -#ifndef _CRT_SECURE_NO_DEPRECATE -# define _CRT_SECURE_NO_DEPRECATE +#define NO_STRDUP +#define NO_MKDIR +#define _CRT_SECURE_NO_WARNINGS +#pragma warning(disable: 4710 4820) +#pragma warning(disable: 4100) // unreferenced formal parameter +#pragma warning(disable: 4456) // declaration hides previous +#pragma warning(disable: 4457) // declaration hides function parameter +#pragma warning(disable: 4459) // declaration hides global +#else /* assume gcc */ +#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L +# define va_copy(a,b) __va_copy(a,b) #endif -/* - * http://msdn2.microsoft.com/en-us/library/ms235505(VS.80).aspx - * Defining _CRT_DISABLE_PERFCRIT_LOCKS forces all I/O operations to assume a - * single-threaded I/O model and use the _nolock forms of the functions. - */ -#ifndef _CRT_DISABLE_PERFCRIT_LOCKS -# define _CRT_DISABLE_PERFCRIT_LOCKS #endif -/* define CRTDBG to enable MSVC CRT Debug library functions */ -#if defined(_DEBUG) && defined(CRTDBG) -# include -# define _CRTDBG_MAP_ALLOC +#define _POSIX_C_SOURCE 200809L + +#ifndef MAX_PATH +# define MAX_PATH 4096 #endif -#endif /* _MSC_VER_ */ +#define UNUSED_ARG(a) (void)(a) -#if defined __GNUC__ -# undef _BSD_SOURCE -# define _BSD_SOURCE -# undef __USE_BSD -# define __USE_BSD -#endif - -#ifdef _BSD_SOURCE -# undef __EXTENSIONS__ -# define __EXTENSIONS__ -#endif - -#ifdef SOLARIS -# define _SYS_PROCSET_H -#undef _XOPEN_SOURCE -# define _XOPEN_SOURCE -#endif - -#define unused_arg (void) - -#ifndef INLINE_FUNCTION -# define INLINE_FUNCTION -#endif - -#define iswxspace(c) (c==160 || iswspace(c)) -#define isxspace(c) (c==160 || isspace(c)) +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) #define TOLUA_CAST (char*) -#ifdef USE_AUTOCONF -# include +#ifdef NO_STRDUP +char * strdup(const char *s); #endif -#if !defined(MAX_PATH) -#if defined(PATH_MAX) -# define MAX_PATH PATH_MAX -#else -# define MAX_PATH 256 -#endif -#endif - -#ifdef HAVE_UNISTD_H -#include -#endif - -#ifdef HAVE_STRINGS_H -#include +#ifdef NO_MKDIR +int mkdir(const char *pathname, int mode); #endif #endif - diff --git a/src/prefix.c b/src/prefix.c index b6adb7c02..1a22e6982 100644 --- a/src/prefix.c +++ b/src/prefix.c @@ -1,6 +1,8 @@ #include #include "prefix.h" +#include + #include #include #include @@ -10,7 +12,7 @@ char **race_prefixes = NULL; static size_t size = 4; static unsigned int next = 0; -void add_raceprefix(const char *prefix) +int add_raceprefix(const char *prefix) { assert(prefix); if (race_prefixes == NULL) { @@ -19,11 +21,18 @@ void add_raceprefix(const char *prefix) race_prefixes = malloc(size * sizeof(char *)); } if (next + 1 == size) { + char **tmp; + tmp = realloc(race_prefixes, 2 * size * sizeof(char *)); + if (!tmp) { + log_fatal("allocation failure"); + return 1; + } + race_prefixes = tmp; size *= 2; - race_prefixes = realloc(race_prefixes, size * sizeof(char *)); } - race_prefixes[next++] = _strdup(prefix); + race_prefixes[next++] = strdup(prefix); race_prefixes[next] = NULL; + return 0; } void free_prefixes(void) { diff --git a/src/prefix.h b/src/prefix.h index 9c5b84907..96d07aa02 100644 --- a/src/prefix.h +++ b/src/prefix.h @@ -7,8 +7,8 @@ extern "C" { #endif - void add_raceprefix(const char *); - char **race_prefixes; // zero-terminated array of valid prefixes + int add_raceprefix(const char *); + char **race_prefixes; /* zero-terminated array of valid prefixes */ void free_prefixes(void); #ifdef __cplusplus diff --git a/src/prefix.test.c b/src/prefix.test.c index 222c19f85..a914426fa 100644 --- a/src/prefix.test.c +++ b/src/prefix.test.c @@ -8,11 +8,11 @@ static void test_add_prefix(CuTest *tc) { test_setup(); CuAssertPtrEquals(tc, 0, race_prefixes); - add_raceprefix("sea"); + CuAssertIntEquals(tc, 0, add_raceprefix("sea")); CuAssertPtrNotNull(tc, race_prefixes); CuAssertStrEquals(tc, "sea", race_prefixes[0]); CuAssertPtrEquals(tc, 0, race_prefixes[1]); - add_raceprefix("moon"); + CuAssertIntEquals(tc, 0, add_raceprefix("moon")); CuAssertStrEquals(tc, "sea", race_prefixes[0]); CuAssertStrEquals(tc, "moon", race_prefixes[1]); CuAssertPtrEquals(tc, 0, race_prefixes[2]); diff --git a/src/process.pkg b/src/process.pkg index 5db5c7344..a81917293 100755 --- a/src/process.pkg +++ b/src/process.pkg @@ -25,7 +25,6 @@ module eressea { void process_leave @ leave(void); /* LEAVE */ void process_maintenance @ maintenance(void); /* PAY */ void process_promote @ promote(void); /* PROMOTE */ - void process_renumber @ renumber(void); /* RENUMBER */ void process_restack @ restack(void); /* SORT */ void process_setspells @ set_spells(void); /* COMBATSPELL */ void process_sethelp @ set_help(void); /* HELP */ diff --git a/src/process.pkg.c b/src/process.pkg.c index 787258a96..42dff20ff 100644 --- a/src/process.pkg.c +++ b/src/process.pkg.c @@ -531,30 +531,6 @@ static int tolua_process_eressea_process_promote00(lua_State* tolua_S) #endif } -/* function: process_renumber */ -static int tolua_process_eressea_process_renumber00(lua_State* tolua_S) -{ -#ifndef TOLUA_RELEASE - tolua_Error tolua_err; - if ( - !tolua_isnoobj(tolua_S,1,&tolua_err) - ) - goto tolua_lerror; - else -#endif - { - { - process_renumber(); - } - } - return 0; -#ifndef TOLUA_RELEASE - tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'renumber'.",&tolua_err); - return 0; -#endif -} - /* function: process_restack */ static int tolua_process_eressea_process_restack00(lua_State* tolua_S) { @@ -1021,7 +997,6 @@ LUALIB_API int luaopen_process (lua_State* tolua_S) tolua_function(tolua_S,"leave",tolua_process_eressea_process_leave00); tolua_function(tolua_S,"maintenance",tolua_process_eressea_process_maintenance00); tolua_function(tolua_S,"promote",tolua_process_eressea_process_promote00); - tolua_function(tolua_S,"renumber",tolua_process_eressea_process_renumber00); tolua_function(tolua_S,"restack",tolua_process_eressea_process_restack00); tolua_function(tolua_S,"set_spells",tolua_process_eressea_process_set_spells00); tolua_function(tolua_S,"set_help",tolua_process_eressea_process_set_help00); diff --git a/src/races/CMakeLists.txt b/src/races/CMakeLists.txt index 1f3044e3a..ff6025581 100644 --- a/src/races/CMakeLists.txt +++ b/src/races/CMakeLists.txt @@ -1,7 +1,6 @@ PROJECT(races C) SET(_FILES dragons.c -illusion.c races.c zombies.c ) diff --git a/src/races/dragons.c b/src/races/dragons.c index 828e68c64..aa79a783a 100644 --- a/src/races/dragons.c +++ b/src/races/dragons.c @@ -13,7 +13,6 @@ */ #include -#include /* kernel includes */ #include @@ -23,7 +22,7 @@ /* util includes */ #include -#define age_chance(a,b,p) (_max(0,a-b)*p) +#define age_chance(a,b,p) (MAX(0,a-b)*p) #define DRAGONAGE 27 #define WYRMAGE 68 diff --git a/src/races/illusion.c b/src/races/illusion.c deleted file mode 100644 index e2a05cfd3..000000000 --- a/src/races/illusion.c +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Eressea PB(E)M host Copyright (C) 1998-2015 - * Christian Schlittchen (corwin@amber.kn-bremen.de) - * Katja Zedel (katze@felidae.kn-bremen.de) - * Henning Peters (faroul@beyond.kn-bremen.de) - * Enno Rehling (enno@eressea.de) - * Ingo Wilken (Ingo.Wilken@informatik.uni-oldenburg.de) - * - * This program may not be used, modified or distributed without - * prior permission by the authors of Eressea. - */ - -#include -#include - -/* kernel includes */ -#include -#include -#include -#include - -/* libc includes */ -#include -#include - -#define ILLUSIONMAX 6 - -void age_illusion(unit * u) -{ - if (u->faction->race != get_race(RC_ILLUSION)) { - if (u->age == ILLUSIONMAX) { - ADDMSG(&u->faction->msgs, msg_message("warnillusiondissolve", "unit", u)); - } - else if (u->age > ILLUSIONMAX) { - set_number(u, 0); - ADDMSG(&u->faction->msgs, msg_message("illusiondissolve", "unit", u)); - } - } -} diff --git a/src/races/races.c b/src/races/races.c index 68b3c5ae2..92a3d3e3d 100644 --- a/src/races/races.c +++ b/src/races/races.c @@ -9,7 +9,6 @@ */ #include -#include #include "races.h" #include @@ -32,22 +31,11 @@ void age_firedragon(struct unit *u); void age_dragon(struct unit *u); -void age_illusion(struct unit *u); void age_undead(struct unit *u); void age_skeleton(struct unit *u); void age_zombie(struct unit *u); void age_ghoul(struct unit *u); -static void oldfamiliars(unit * u) -{ - char fname[64]; - /* these familiars have no special skills. - */ - _snprintf(fname, sizeof(fname), "%s_familiar", u_race(u)->_name); - create_mage(u, M_GRAY); - equip_unit(u, get_equipment(fname)); -} - static void equip_newunits(const struct equipment *eq, struct unit *u) { struct region *r = u->region; @@ -89,30 +77,17 @@ static void equip_newunits(const struct equipment *eq, struct unit *u) } } -/* Die Funktionen werden ber den hier registrierten Namen in races.xml +/* Die Funktionen werden �ber den hier registrierten Namen in races.xml * in die jeweilige Rassendefiniton eingebunden */ void register_races(void) { - /* function initfamiliar */ - register_function((pf_generic)oldfamiliars, "oldfamiliars"); - - register_function((pf_generic)allowed_dragon, "movedragon"); - - register_function((pf_generic)allowed_swim, "moveswimming"); - register_function((pf_generic)allowed_fly, "moveflying"); - register_function((pf_generic)allowed_walk, "movewalking"); + register_function((pf_generic)equip_newunits, "equip_newunits"); /* function age for race->age() */ - register_function((pf_generic)age_undead, "ageundead"); - register_function((pf_generic)age_illusion, "ageillusion"); - register_function((pf_generic)age_skeleton, "ageskeleton"); - register_function((pf_generic)age_zombie, "agezombie"); - register_function((pf_generic)age_ghoul, "ageghoul"); - register_function((pf_generic)age_dragon, "agedragon"); - register_function((pf_generic)age_firedragon, "agefiredragon"); - - /* function itemdrop - * to generate battle spoils - * race->itemdrop() */ - register_function((pf_generic)equip_newunits, "equip_newunits"); + register_function((pf_generic)age_undead, "age_undead"); + register_function((pf_generic)age_skeleton, "age_skeleton"); + register_function((pf_generic)age_zombie, "age_zombie"); + register_function((pf_generic)age_ghoul, "age_ghoul"); + register_function((pf_generic)age_dragon, "age_dragon"); + register_function((pf_generic)age_firedragon, "age_youngdragon"); } diff --git a/src/races/races.h b/src/races/races.h index c0a516430..ea7be1337 100644 --- a/src/races/races.h +++ b/src/races/races.h @@ -14,6 +14,7 @@ #ifdef __cplusplus extern "C" { #endif + struct unit; void register_races(void); void make_undead_unit(struct unit *); diff --git a/src/races/zombies.c b/src/races/zombies.c index d86074d26..ea26298b2 100644 --- a/src/races/zombies.c +++ b/src/races/zombies.c @@ -13,7 +13,6 @@ */ #include -#include /* kernel includes */ #include @@ -25,7 +24,7 @@ /* util iclude */ #include -#include "monster.h" +#include "monsters.h" /* libc includes */ #include @@ -34,13 +33,13 @@ #define UNDEAD_BREAKUP 25 /* chance dafuer */ #define UNDEAD_BREAKUP_FRACTION (25+rng_int()%70) /* anteil der weg geht */ -#define age_chance(a,b,p) (_max(0,a-b)*p) +#define age_chance(a,b,p) (MAX(0,a-b)*p) void make_undead_unit(unit * u) { free_orders(&u->orders); name_unit(u); - fset(u, UFL_ISNEW); + u->flags |= UFL_ISNEW; } void age_undead(unit * u) @@ -71,7 +70,7 @@ void age_undead(unit * u) void age_skeleton(unit * u) { if (is_monsters(u->faction) && rng_int() % 100 < age_chance(u->age, 27, 1)) { - int n = _max(1, u->number / 2); + int n = MAX(1, u->number / 2); double q = (double)u->hp / (double)(unit_max_hp(u) * u->number); u_setrace(u, get_race(RC_SKELETON_LORD)); u->irace = NULL; @@ -83,7 +82,7 @@ void age_skeleton(unit * u) void age_zombie(unit * u) { if (is_monsters(u->faction) && rng_int() % 100 < age_chance(u->age, 27, 1)) { - int n = _max(1, u->number / 2); + int n = MAX(1, u->number / 2); double q = (double)u->hp / (double)(unit_max_hp(u) * u->number); u_setrace(u, get_race(RC_ZOMBIE_LORD)); u->irace = NULL; @@ -95,7 +94,7 @@ void age_zombie(unit * u) void age_ghoul(unit * u) { if (is_monsters(u->faction) && rng_int() % 100 < age_chance(u->age, 27, 1)) { - int n = _max(1, u->number / 2); + int n = MAX(1, u->number / 2); double q = (double)u->hp / (double)(unit_max_hp(u) * u->number); u_setrace(u, get_race(RC_GHOUL_LORD)); u->irace = NULL; diff --git a/src/randenc.c b/src/randenc.c index 85c3dd8d3..ab51d64b1 100644 --- a/src/randenc.c +++ b/src/randenc.c @@ -22,7 +22,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "volcano.h" #include "economy.h" -#include "monster.h" +#include "monsters.h" #include "move.h" #include "chaos.h" #include "study.h" @@ -67,10 +67,9 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include extern struct attrib_type at_unitdissolve; -extern struct attrib_type at_orcification; /* In a->data.ca[1] steht der Prozentsatz mit dem sich die Einheit - * auflst, in a->data.ca[0] kann angegeben werden, wohin die Personen + * aufl�st, in a->data.ca[0] kann angegeben werden, wohin die Personen * verschwinden. Passiert bereits in der ersten Runde! */ static void dissolve_units(void) { @@ -443,12 +442,12 @@ static void melt_iceberg(region * r) ADDMSG(&u->faction->msgs, msg_message("iceberg_melt", "region", r)); } - /* driftrichtung lschen */ + /* driftrichtung l�schen */ a = a_find(r->attribs, &at_iceberg); if (a) a_remove(&r->attribs, a); - /* Gebude lschen */ + /* Geb�ude l�schen */ while (r->buildings) { remove_building(&r->buildings, r->buildings); } @@ -456,7 +455,7 @@ static void melt_iceberg(region * r) /* in Ozean wandeln */ terraform_region(r, newterrain(T_OCEAN)); - /* Einheiten, die nicht schwimmen knnen oder in Schiffen sind, + /* Einheiten, die nicht schwimmen k�nnen oder in Schiffen sind, * ertrinken */ drown(r); } @@ -520,13 +519,13 @@ static void move_iceberg(region * r) freset(sh, SF_SELECT); for (sh = r->ships; sh; sh = sh->next) { - /* Meldung an Kapitn */ + /* Meldung an Kapit�n */ double dmg = config_get_flt("rules.ship.damage.intoiceberg", 0.1); damage_ship(sh, dmg); fset(sh, SF_SELECT); } - /* Personen, Schiffe und Gebude verschieben */ + /* Personen, Schiffe und Geb�ude verschieben */ while (rc->buildings) { rc->buildings->region = r; translist(&rc->buildings, &r->buildings, rc->buildings); @@ -545,7 +544,7 @@ static void move_iceberg(region * r) u_set_building(u, b); /* undo leave-prevention */ } - /* Beschdigte Schiffe knnen sinken */ + /* Besch�digte Schiffe k�nnen sinken */ for (sh = r->ships; sh;) { shn = sh->next; @@ -726,16 +725,21 @@ static void orc_growth(void) } } -/** Talente von Dmonen verschieben sich. +/** Talente von D�monen verschieben sich. */ static void demon_skillchanges(void) { region *r; + static const race *rc_demon; + static int rc_cache; + if (rc_changed(&rc_cache)) { + rc_demon = get_race(RC_DAEMON); + } for (r = regions; r; r = r->next) { unit *u; for (u = r->units; u; u = u->next) { - if (u_race(u) == get_race(RC_DAEMON)) { + if (u_race(u) == rc_demon) { demon_skillchange(u); } } @@ -756,7 +760,7 @@ static void icebergs(void) } #define HERBS_ROT /* herbs owned by units have a chance to rot. */ -#define HERBROTCHANCE 5 /* Verrottchance fr Kruter (ifdef HERBS_ROT) */ +#define HERBROTCHANCE 5 /* Verrottchance f�r Kr�uter (ifdef HERBS_ROT) */ #ifdef HERBS_ROT static void rotting_herbs(void) { @@ -781,7 +785,7 @@ static void rotting_herbs(void) if (fval(itm->type, ITF_HERB)) { double nv = normalvariate(k, k / 4); int inv = (int)nv; - int delta = _min(n, inv); + int delta = MIN(n, inv); if (!i_change(itmp, itm->type, -delta)) { continue; } @@ -802,44 +806,6 @@ void randomevents(void) godcurse(); orc_growth(); demon_skillchanges(); - - /* Orkifizierte Regionen mutieren und mutieren zurck */ - - for (r = regions; r; r = r->next) { - if (fval(r, RF_ORCIFIED)) { - direction_t dir; - double probability = 0.0; - for (dir = 0; dir < MAXDIRECTIONS; dir++) { - region *rc = rconnect(r, dir); - if (rc && rpeasants(rc) > 0 && !fval(rc, RF_ORCIFIED)) - probability += 0.02; - } - if (chance(probability)) { - ADDMSG(&r->msgs, msg_message("deorcified", "region", r)); - freset(r, RF_ORCIFIED); - } - } - else { - attrib *a = a_find(r->attribs, &at_orcification); - if (a != NULL) { - double probability = 0.0; - if (rpeasants(r) <= 0) - continue; - probability = a->data.i / (double)rpeasants(r); - if (chance(probability)) { - fset(r, RF_ORCIFIED); - a_remove(&r->attribs, a); - ADDMSG(&r->msgs, msg_message("orcified", "region", r)); - } - else { - a->data.i -= _max(10, a->data.i / 10); - if (a->data.i <= 0) - a_remove(&r->attribs, a); - } - } - } - } - volcano_update(); /* Monumente zerfallen, Schiffe verfaulen */ @@ -848,7 +814,7 @@ void randomevents(void) while (*blist) { building *b = *blist; if (fval(b->type, BTF_DECAY) && !building_owner(b)) { - b->size -= _max(1, (b->size * 20) / 100); + b->size -= MAX(1, (b->size * 20) / 100); if (b->size == 0) { remove_building(blist, r->buildings); } @@ -860,22 +826,7 @@ void randomevents(void) /* monster-einheiten desertieren */ if (monsters) { - for (r = regions; r; r = r->next) { - unit *u; - - for (u = r->units; u; u = u->next) { - if (u->faction && !is_monsters(u->faction) - && (u_race(u)->flags & RCF_DESERT)) { - if (fval(u, UFL_ISNEW)) - continue; - if (rng_int() % 100 < 5) { - ADDMSG(&u->faction->msgs, msg_message("desertion", - "unit region", u, r)); - u_setfaction(u, monsters); - } - } - } - } + monsters_desert(monsters); } chaos_update(); diff --git a/src/renumber.c b/src/renumber.c new file mode 100644 index 000000000..de2b5a490 --- /dev/null +++ b/src/renumber.c @@ -0,0 +1,191 @@ +#include +#include "renumber.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +static attrib_type at_number = { + "faction_renum", + NULL, NULL, NULL, NULL, NULL, NULL, + ATF_UNIQUE +}; + +void renumber_factions(void) +/* gibt parteien neue nummern */ +{ + struct renum { + struct renum *next; + int want; + faction *faction; + attrib *attrib; + } *renum = NULL, *rp; + faction *f; + for (f = factions; f; f = f->next) { + attrib *a = a_find(f->attribs, &at_number); + int want; + struct renum **rn; + + if (!a) + continue; + want = a->data.i; + if (fval(f, FFL_NEWID)) { + ADDMSG(&f->msgs, msg_message("renumber_twice", "id", want)); + continue; + } + if (!faction_id_is_unused(want)) { + a_remove(&f->attribs, a); + ADDMSG(&f->msgs, msg_message("renumber_inuse", "id", want)); + continue; + } + for (rn = &renum; *rn; rn = &(*rn)->next) { + if ((*rn)->want >= want) + break; + } + if (*rn && (*rn)->want == want) { + ADDMSG(&f->msgs, msg_message("renumber_inuse", "id", want)); + } + else { + struct renum *r = calloc(sizeof(struct renum), 1); + r->next = *rn; + r->attrib = a; + r->faction = f; + r->want = want; + *rn = r; + } + } + for (rp = renum; rp; rp = rp->next) { + f = rp->faction; + a_remove(&f->attribs, rp->attrib); + renumber_faction(f, rp->want); + } + while (renum) { + rp = renum->next; + free(renum); + renum = rp; + } +} + +int renumber_cmd(unit * u, order * ord) +{ + char token[128]; + const char *s; + int i = 0; + faction *f = u->faction; + + init_order(ord); + s = gettoken(token, sizeof(token)); + switch (findparam_ex(s, u->faction->locale)) { + + case P_FACTION: + s = gettoken(token, sizeof(token)); + if (s && *s) { + int id = atoi36((const char *)s); + attrib *a = a_find(f->attribs, &at_number); + if (!a) + a = a_add(&f->attribs, a_new(&at_number)); + a->data.i = id; + } + break; + + case P_UNIT: + s = gettoken(token, sizeof(token)); + if (s && *s) { + i = atoi36((const char *)s); + if (i <= 0 || i > MAX_UNIT_NR) { + cmistake(u, ord, 114, MSG_EVENT); + break; + } + + if (forbiddenid(i)) { + cmistake(u, ord, 116, MSG_EVENT); + break; + } + + if (findunitg(i, u->region)) { + cmistake(u, ord, 115, MSG_EVENT); + break; + } + } + renumber_unit(u, i); + break; + + case P_SHIP: + if (!u->ship) { + cmistake(u, ord, 144, MSG_EVENT); + break; + } + if (ship_owner(u->ship) != u) { + cmistake(u, ord, 146, MSG_EVENT); + break; + } + if (u->ship->coast != NODIRECTION) { + cmistake(u, ord, 116, MSG_EVENT); + break; + } + s = gettoken(token, sizeof(token)); + if (s == NULL || *s == 0) { + i = newcontainerid(); + } + else { + i = atoi36((const char *)s); + if (i <= 0 || i > MAX_CONTAINER_NR) { + cmistake(u, ord, 114, MSG_EVENT); + break; + } + if (findship(i)) { + cmistake(u, ord, 115, MSG_EVENT); + break; + } + } + sunhash(u->ship); + u->ship->no = i; + shash(u->ship); + break; + case P_BUILDING: + case P_GEBAEUDE: + if (!u->building) { + cmistake(u, ord, 145, MSG_EVENT); + break; + } + if (building_owner(u->building) != u) { + cmistake(u, ord, 148, MSG_EVENT); + break; + } + s = gettoken(token, sizeof(token)); + if (*s == 0) { + i = newcontainerid(); + } + else { + i = atoi36((const char *)s); + if (i <= 0 || i > MAX_CONTAINER_NR) { + cmistake(u, ord, 114, MSG_EVENT); + break; + } + if (findbuilding(i)) { + cmistake(u, ord, 115, MSG_EVENT); + break; + } + } + bunhash(u->building); + u->building->no = i; + bhash(u->building); + break; + + default: + cmistake(u, ord, 239, MSG_EVENT); + } + return 0; +} + diff --git a/src/renumber.h b/src/renumber.h new file mode 100644 index 000000000..244b8043f --- /dev/null +++ b/src/renumber.h @@ -0,0 +1,12 @@ +#pragma once + +#ifndef H_RENUMBER +#define H_RENUMBER + + struct unit; + struct order; + + void renumber_factions(void); + int renumber_cmd(struct unit *u, struct order *ord); + +#endif diff --git a/src/renumber.test.c b/src/renumber.test.c new file mode 100644 index 000000000..8f6f91a59 --- /dev/null +++ b/src/renumber.test.c @@ -0,0 +1,234 @@ +#include +#include "renumber.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +static void test_renumber_faction(CuTest *tc) { + unit *u; + int uno, no; + const struct locale *lang; + + test_setup_ex(tc); + u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); + no = u->faction->no; + uno = (no > 1) ? no - 1 : no + 1; + lang = u->faction->locale; + u->thisorder = create_order(K_NUMBER, lang, "%s %s", LOC(lang, parameters[P_FACTION]), itoa36(uno)); + renumber_cmd(u, u->thisorder); + renumber_factions(); + CuAssertIntEquals(tc, uno, u->faction->no); + test_cleanup(); +} + +static void test_renumber_faction_duplicate(CuTest *tc) { + unit *u; + faction *f, *f2; + int no; + const struct locale *lang; + + test_setup_ex(tc); + f2 = test_create_faction(0); + u = test_create_unit(f = test_create_faction(0), test_create_region(0, 0, 0)); + no = f->no; + lang = f->locale; + u->thisorder = create_order(K_NUMBER, lang, "%s %s", LOC(lang, parameters[P_FACTION]), itoa36(f2->no)); + renumber_cmd(u, u->thisorder); + renumber_factions(); + CuAssertPtrNotNull(tc, test_find_messagetype(f->msgs, "renumber_inuse")); + CuAssertIntEquals(tc, no, u->faction->no); + test_cleanup(); +} + +static void test_renumber_building(CuTest *tc) { + unit *u; + int uno, no; + const struct locale *lang; + + test_setup_ex(tc); + u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); + u->building = test_create_building(u->region, 0); + no = u->building->no; + uno = (no > 1) ? no - 1 : no + 1; + lang = u->faction->locale; + u->thisorder = create_order(K_NUMBER, lang, "%s %s", LOC(lang, parameters[P_BUILDING]), itoa36(uno)); + renumber_cmd(u, u->thisorder); + CuAssertIntEquals(tc, uno, u->building->no); + test_cleanup(); +} + +static void test_renumber_building_duplicate(CuTest *tc) { + unit *u; + faction *f; + int uno, no; + const struct locale *lang; + + test_setup_ex(tc); + u = test_create_unit(f = test_create_faction(0), test_create_region(0, 0, 0)); + u->building = test_create_building(u->region, 0); + uno = u->building->no; + u->building = test_create_building(u->region, 0); + no = u->building->no; + lang = f->locale; + u->thisorder = create_order(K_NUMBER, lang, "%s %s", LOC(lang, parameters[P_BUILDING]), itoa36(uno)); + renumber_cmd(u, u->thisorder); + CuAssertPtrNotNull(tc, test_find_messagetype(f->msgs, "error115")); + CuAssertIntEquals(tc, no, u->building->no); + test_cleanup(); +} + +static void test_renumber_ship(CuTest *tc) { + unit *u; + int uno, no; + const struct locale *lang; + + test_setup_ex(tc); + u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); + u->ship = test_create_ship(u->region, 0); + no = u->ship->no; + uno = (no > 1) ? no - 1 : no + 1; + lang = u->faction->locale; + u->thisorder = create_order(K_NUMBER, lang, "%s %s", LOC(lang, parameters[P_SHIP]), itoa36(uno)); + renumber_cmd(u, u->thisorder); + CuAssertIntEquals(tc, uno, u->ship->no); + test_cleanup(); +} + +static void test_renumber_ship_twice(CuTest *tc) { + unit *u; + int uno, no; + const struct locale *lang; + + test_setup_ex(tc); + u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); + u->ship = test_create_ship(u->region, 0); + no = u->ship->no; + uno = (no > 1) ? no - 1 : no + 1; + lang = u->faction->locale; + u->thisorder = create_order(K_NUMBER, lang, "%s %s", LOC(lang, parameters[P_SHIP]), itoa36(uno)); + renumber_cmd(u, u->thisorder); + CuAssertIntEquals(tc, uno, u->ship->no); + free_order(u->thisorder); + u->thisorder = create_order(K_NUMBER, lang, "%s %s", LOC(lang, parameters[P_SHIP]), itoa36(no)); + renumber_cmd(u, u->thisorder); + CuAssertIntEquals(tc, no, u->ship->no); + test_cleanup(); +} + +static void test_renumber_ship_duplicate(CuTest *tc) { + unit *u; + faction *f; + int uno, no; + const struct locale *lang; + + test_setup_ex(tc); + u = test_create_unit(f = test_create_faction(0), test_create_region(0, 0, 0)); + u->ship = test_create_ship(u->region, 0); + uno = u->ship->no; + u->ship = test_create_ship(u->region, 0); + no = u->ship->no; + lang = f->locale; + u->thisorder = create_order(K_NUMBER, lang, "%s %s", LOC(lang, parameters[P_SHIP]), itoa36(uno)); + renumber_cmd(u, u->thisorder); + CuAssertPtrNotNull(tc, test_find_messagetype(f->msgs, "error115")); + CuAssertIntEquals(tc, no, u->ship->no); + test_cleanup(); +} + +static void test_renumber_unit(CuTest *tc) { + unit *u; + int uno, no; + const struct locale *lang; + + test_setup_ex(tc); + u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); + no = u->no; + uno = (no > 1) ? no - 1 : no + 1; + lang = u->faction->locale; + u->thisorder = create_order(K_NUMBER, lang, "%s %s", LOC(lang, parameters[P_UNIT]), itoa36(uno)); + renumber_cmd(u, u->thisorder); + CuAssertIntEquals(tc, uno, u->no); + CuAssertIntEquals(tc, -no, ualias(u)); + test_cleanup(); +} + +static void test_renumber_unit_duplicate(CuTest *tc) { + unit *u, *u2; + faction *f; + int no; + const struct locale *lang; + + test_setup_ex(tc); + u = test_create_unit(f = test_create_faction(0), test_create_region(0, 0, 0)); + no = u->no; + u2 = test_create_unit(f, u->region); + lang = f->locale; + u->thisorder = create_order(K_NUMBER, lang, "%s %s", LOC(lang, parameters[P_UNIT]), itoa36(u2->no)); + renumber_cmd(u, u->thisorder); + CuAssertIntEquals(tc, no, u->no); + CuAssertPtrNotNull(tc, test_find_messagetype(f->msgs, "error115")); + CuAssertIntEquals(tc, 0, ualias(u)); + test_cleanup(); +} + +static void test_renumber_unit_limit(CuTest *tc) { + unit *u; + faction *f; + int no; + const struct locale *lang; + + test_setup_ex(tc); + u = test_create_unit(f = test_create_faction(0), test_create_region(0, 0, 0)); + no = u->no; + lang = f->locale; + u->thisorder = create_order(K_NUMBER, lang, "%s 10000", LOC(lang, parameters[P_UNIT])); + renumber_cmd(u, u->thisorder); + CuAssertIntEquals(tc, no, u->no); + CuAssertPtrNotNull(tc, test_find_messagetype(f->msgs, "error114")); + CuAssertIntEquals(tc, 0, ualias(u)); + test_cleanup(); +} + +static void test_renumber_unit_invalid(CuTest *tc) { + unit *u; + faction *f; + int no; + const struct locale *lang; + + test_setup_ex(tc); + u = test_create_unit(f = test_create_faction(0), test_create_region(0, 0, 0)); + no = u->no; + lang = f->locale; + u->thisorder = create_order(K_NUMBER, lang, "%s TEMP", LOC(lang, parameters[P_UNIT])); + renumber_cmd(u, u->thisorder); + CuAssertIntEquals(tc, no, u->no); + CuAssertPtrNotNull(tc, test_find_messagetype(f->msgs, "error116")); + CuAssertIntEquals(tc, 0, ualias(u)); + test_cleanup(); +} + +CuSuite *get_renumber_suite(void) +{ + CuSuite *suite = CuSuiteNew(); + SUITE_ADD_TEST(suite, test_renumber_unit); + SUITE_ADD_TEST(suite, test_renumber_unit_limit); + SUITE_ADD_TEST(suite, test_renumber_unit_duplicate); + SUITE_ADD_TEST(suite, test_renumber_unit_invalid); + SUITE_ADD_TEST(suite, test_renumber_building); + SUITE_ADD_TEST(suite, test_renumber_building_duplicate); + SUITE_ADD_TEST(suite, test_renumber_ship); + SUITE_ADD_TEST(suite, test_renumber_ship_twice); + SUITE_ADD_TEST(suite, test_renumber_ship_duplicate); + SUITE_ADD_TEST(suite, test_renumber_faction); + SUITE_ADD_TEST(suite, test_renumber_faction_duplicate); + return suite; +} diff --git a/src/report.c b/src/report.c index c7093da73..cf00abbc3 100644 --- a/src/report.c +++ b/src/report.c @@ -1,4 +1,4 @@ -/* +/* Copyright (c) 1998-2015, Enno Rehling Katja Zedel @@ -23,9 +23,11 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "report.h" #include "reports.h" +#include "guard.h" #include "laws.h" +#include "market.h" +#include "monsters.h" #include "travelthru.h" -#include "monster.h" /* modules includes */ #include @@ -62,7 +64,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include #include #include #include @@ -81,9 +82,10 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include +#include #include #include +#include /* libc includes */ #include @@ -98,7 +100,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #if defined(_MSC_VER) && _MSC_VER >= 1900 -# pragma warning(disable: 4774) // TODO: remove this +# pragma warning(disable: 4774) /* TODO: remove this */ #endif extern int *storms; @@ -118,7 +120,7 @@ static void check_errno(const char * file, int line) { static char *gamedate_season(const struct locale *lang) { - static char buf[256]; // FIXME: static return value + static char buf[256]; /* FIXME: static return value */ gamedate gd; get_gamedate(turn, &gd); @@ -132,11 +134,11 @@ static char *gamedate_season(const struct locale *lang) return buf; } -void newline(stream *out) { +void newline(struct stream *out) { sputs("", out); } -void write_spaces(stream *out, size_t num) { +void write_spaces(struct stream *out, size_t num) { static const char spaces[REPORTWIDTH] = " "; while (num > 0) { size_t bytes = (num > REPORTWIDTH) ? REPORTWIDTH : num; @@ -145,7 +147,7 @@ void write_spaces(stream *out, size_t num) { } } -static void centre(stream *out, const char *s, bool breaking) +static void centre(struct stream *out, const char *s, bool breaking) { /* Bei Namen die genau 80 Zeichen lang sind, kann es hier Probleme * geben. Seltsamerweise wird i dann auf MAXINT oder aehnlich @@ -169,7 +171,7 @@ static void centre(stream *out, const char *s, bool breaking) } static void -paragraph(stream *out, const char *str, ptrdiff_t indent, int hanging_indent, +paragraph(struct stream *out, const char *str, ptrdiff_t indent, int hanging_indent, char marker) { size_t length = REPORTWIDTH; @@ -232,7 +234,7 @@ paragraph(stream *out, const char *str, ptrdiff_t indent, int hanging_indent, } while (*begin); } -static size_t write_spell_modifier(spell * sp, int flag, const char * str, bool cont, char * bufp, size_t size) { +static size_t write_spell_modifier(const spell * sp, int flag, const char * str, bool cont, char * bufp, size_t size) { if (sp->sptyp & flag) { size_t bytes = 0; if (cont) { @@ -247,13 +249,13 @@ static size_t write_spell_modifier(spell * sp, int flag, const char * str, bool return 0; } -void nr_spell_syntax(stream *out, spellbook_entry * sbe, const struct locale *lang) +void nr_spell_syntax(struct stream *out, spellbook_entry * sbe, const struct locale *lang) { int bytes; char buf[4096]; char *bufp = buf; size_t size = sizeof(buf) - 1; - spell * sp = sbe->sp; + const spell * sp = sbe->sp; const char *params = sp->parameter; if (sp->sptyp & ISCOMBATSPELL) { @@ -267,17 +269,17 @@ void nr_spell_syntax(stream *out, spellbook_entry * sbe, const struct locale *la /* Reihenfolge beachten: Erst REGION, dann STUFE! */ if (sp->sptyp & FARCASTING) { - bytes = _snprintf(bufp, size, " [%s x y]", LOC(lang, parameters[P_REGION])); + bytes = snprintf(bufp, size, " [%s x y]", LOC(lang, parameters[P_REGION])); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); } if (sp->sptyp & SPELLLEVEL) { - bytes = _snprintf(bufp, size, " [%s n]", LOC(lang, parameters[P_LEVEL])); + bytes = snprintf(bufp, size, " [%s n]", LOC(lang, parameters[P_LEVEL])); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); } - bytes = (int)_snprintf(bufp, size, " \"%s\"", spell_name(sp, lang)); + bytes = (int)snprintf(bufp, size, " \"%s\"", spell_name(sp, lang)); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); @@ -303,12 +305,12 @@ void nr_spell_syntax(stream *out, spellbook_entry * sbe, const struct locale *la if (cp == 'u') { targetp = targets + 1; locp = LOC(lang, targetp->vars); - bytes = (int)_snprintf(bufp, size, " <%s>", locp); + bytes = (int)snprintf(bufp, size, " <%s>", locp); if (*params == '+') { ++params; if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); - bytes = (int)_snprintf(bufp, size, " [<%s> ...]", locp); + bytes = (int)snprintf(bufp, size, " [<%s> ...]", locp); } if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); @@ -316,12 +318,12 @@ void nr_spell_syntax(stream *out, spellbook_entry * sbe, const struct locale *la else if (cp == 's') { targetp = targets + 2; locp = LOC(lang, targetp->vars); - bytes = (int)_snprintf(bufp, size, " <%s>", locp); + bytes = (int)snprintf(bufp, size, " <%s>", locp); if (*params == '+') { ++params; if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); - bytes = (int)_snprintf(bufp, size, " [<%s> ...]", locp); + bytes = (int)snprintf(bufp, size, " [<%s> ...]", locp); } if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); @@ -340,12 +342,12 @@ void nr_spell_syntax(stream *out, spellbook_entry * sbe, const struct locale *la else if (cp == 'b') { targetp = targets + 3; locp = LOC(lang, targetp->vars); - bytes = (int)_snprintf(bufp, size, " <%s>", locp); + bytes = (int)snprintf(bufp, size, " <%s>", locp); if (*params == '+') { ++params; if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); - bytes = (int)_snprintf(bufp, size, " [<%s> ...]", locp); + bytes = (int)snprintf(bufp, size, " [<%s> ...]", locp); } if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); @@ -380,17 +382,17 @@ void nr_spell_syntax(stream *out, spellbook_entry * sbe, const struct locale *la if (targetp->param && targetp->vars) { locp = LOC(lang, targetp->vars); bytes = - (int)_snprintf(bufp, size, " %s <%s>", parameters[targetp->param], + (int)snprintf(bufp, size, " %s <%s>", parameters[targetp->param], locp); if (multi) { if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); - bytes = (int)_snprintf(bufp, size, " [<%s> ...]", locp); + bytes = (int)snprintf(bufp, size, " [<%s> ...]", locp); } } else { bytes = - (int)_snprintf(bufp, size, " %s", parameters[targetp->param]); + (int)snprintf(bufp, size, " %s", parameters[targetp->param]); } if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); @@ -411,17 +413,19 @@ void nr_spell_syntax(stream *out, spellbook_entry * sbe, const struct locale *la } else { char substr[32]; - strncpy(substr, syntaxp, cstr - syntaxp); - substr[cstr - syntaxp] = 0; + size_t len = cstr - syntaxp; + assert(sizeof(substr) > len); + memcpy(substr, syntaxp, len); + substr[len] = 0; locp = LOC(lang, mkname("spellpar", substr)); syntaxp = substr + 1; } if (*params == '?') { ++params; - bytes = (int)_snprintf(bufp, size, " [<%s>]", locp); + bytes = (int)snprintf(bufp, size, " [<%s>]", locp); } else { - bytes = (int)_snprintf(bufp, size, " <%s>", locp); + bytes = (int)snprintf(bufp, size, " <%s>", locp); } if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); @@ -435,13 +439,13 @@ void nr_spell_syntax(stream *out, spellbook_entry * sbe, const struct locale *la } -void nr_spell(stream *out, spellbook_entry * sbe, const struct locale *lang) +void nr_spell(struct stream *out, spellbook_entry * sbe, const struct locale *lang) { int bytes, k, itemanz, costtyp; char buf[4096]; char *startp, *bufp = buf; size_t size = sizeof(buf) - 1; - spell * sp = sbe->sp; + const spell * sp = sbe->sp; newline(out); centre(out, spell_name(sp, lang), true); @@ -490,18 +494,18 @@ void nr_spell(stream *out, spellbook_entry * sbe, const struct locale *lang) bufp = buf; if (sp->sptyp & SPELLLEVEL) { bytes = - _snprintf(bufp, size, " %d %s", itemanz, LOC(lang, resourcename(rtype, + snprintf(bufp, size, " %d %s", itemanz, LOC(lang, resourcename(rtype, itemanz != 1))); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); if (costtyp == SPC_LEVEL || costtyp == SPC_LINEAR) { - bytes = _snprintf(bufp, size, " * %s", LOC(lang, "nr_level")); + bytes = snprintf(bufp, size, " * %s", LOC(lang, "nr_level")); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); } } else { - bytes = _snprintf(bufp, size, "%d %s", itemanz, LOC(lang, resourcename(rtype, itemanz != 1))); + bytes = snprintf(bufp, size, "%d %s", itemanz, LOC(lang, resourcename(rtype, itemanz != 1))); if (wrptr(&bufp, &size, bytes) != 0) { WARN_STATIC_BUFFER(); } @@ -553,7 +557,7 @@ void nr_spell(stream *out, spellbook_entry * sbe, const struct locale *lang) } static void -nr_curses_i(stream *out, int indent, const faction *viewer, objtype_t typ, const void *obj, attrib *a, int self) +nr_curses_i(struct stream *out, int indent, const faction *viewer, objtype_t typ, const void *obj, attrib *a, int self) { for (; a; a = a->next) { char buf[4096]; @@ -581,7 +585,7 @@ nr_curses_i(stream *out, int indent, const faction *viewer, objtype_t typ, const } } -static void nr_curses(stream *out, int indent, const faction *viewer, objtype_t typ, const void *obj) +static void nr_curses(struct stream *out, int indent, const faction *viewer, objtype_t typ, const void *obj) { int self = 0; attrib *a = NULL; @@ -651,7 +655,7 @@ static void nr_curses(stream *out, int indent, const faction *viewer, objtype_t nr_curses_i(out, indent, viewer, typ, obj, a, self); } -static void rps_nowrap(stream *out, const char *s) +static void rps_nowrap(struct stream *out, const char *s) { const char *x = s; size_t indent = 0; @@ -674,7 +678,7 @@ static void rps_nowrap(stream *out, const char *s) } static void -nr_unit(stream *out, const faction * f, const unit * u, int indent, seen_mode mode) +nr_unit(struct stream *out, const faction * f, const unit * u, int indent, seen_mode mode) { attrib *a_otherfaction; char marker; @@ -716,7 +720,7 @@ nr_unit(stream *out, const faction * f, const unit * u, int indent, seen_mode mo } static void -rp_messages(stream *out, message_list * msgs, faction * viewer, int indent, +rp_messages(struct stream *out, message_list * msgs, faction * viewer, int indent, bool categorized) { nrsection *section; @@ -752,7 +756,7 @@ rp_messages(stream *out, message_list * msgs, faction * viewer, int indent, } } -static void rp_battles(stream *out, faction * f) +static void rp_battles(struct stream *out, faction * f) { if (f->battles != NULL) { struct bmsg *bm = f->battles; @@ -772,7 +776,7 @@ static void rp_battles(stream *out, faction * f) } } -static void prices(stream *out, const region * r, const faction * f) +static void prices(struct stream *out, const region * r, const faction * f) { const luxury_type *sale = NULL; struct demand *dmd; @@ -874,7 +878,7 @@ bool see_border(const connection * b, const faction * f, const region * r) return cs; } -static void describe(stream *out, const region * r, faction * f) +static void describe(struct stream *out, const region * r, faction * f) { int n; bool dh; @@ -913,17 +917,19 @@ static void describe(stream *out, const region * r, faction * f) bool transparent = b->type->transparent(b, f); const char *name = border_name(b, r, f, GF_DETAILED | GF_ARTICLE); - if (!transparent) + if (!transparent) { see[d] = false; + } if (!see_border(b, f, r)) { b = b->next; continue; } - while (e && (e->transparent != transparent || strcmp(name, e->name))) + while (e && (e->transparent != transparent || strcmp(name, e->name)!=0)) { e = e->next; + } if (!e) { e = calloc(sizeof(struct edge), 1); - e->name = _strdup(name); + e->name = strdup(name); e->transparent = transparent; e->next = edges; edges = e; @@ -939,13 +945,13 @@ static void describe(stream *out, const region * r, faction * f) WARN_STATIC_BUFFER(); if (r->seen.mode == seen_travel) { - bytes = _snprintf(bufp, size, " (%s)", LOC(f->locale, "see_travel")); + bytes = snprintf(bufp, size, " (%s)", LOC(f->locale, "see_travel")); } else if (r->seen.mode == seen_neighbour) { - bytes = _snprintf(bufp, size, " (%s)", LOC(f->locale, "see_neighbour")); + bytes = snprintf(bufp, size, " (%s)", LOC(f->locale, "see_neighbour")); } else if (r->seen.mode == seen_lighthouse) { - bytes = _snprintf(bufp, size, " (%s)", LOC(f->locale, "see_lighthouse")); + bytes = snprintf(bufp, size, " (%s)", LOC(f->locale, "see_lighthouse")); } else { bytes = 0; @@ -968,7 +974,7 @@ static void describe(stream *out, const region * r, faction * f) saplings = rtrees(r, 1); if (production(r)) { if (trees > 0 || saplings > 0) { - bytes = _snprintf(bufp, size, ", %d/%d ", trees, saplings); + bytes = snprintf(bufp, size, ", %d/%d ", trees, saplings); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); @@ -998,7 +1004,7 @@ static void describe(stream *out, const region * r, faction * f) for (n = 0; n < numresults; ++n) { if (result[n].number >= 0 && result[n].level >= 0) { - bytes = _snprintf(bufp, size, ", %d %s/%d", result[n].number, + bytes = snprintf(bufp, size, ", %d %s/%d", result[n].number, LOC(f->locale, result[n].name), result[n].level); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); @@ -1009,34 +1015,23 @@ static void describe(stream *out, const region * r, faction * f) /* peasants & silver */ if (rpeasants(r)) { int n = rpeasants(r); - bytes = _snprintf(bufp, size, ", %d", n); + bytes = snprintf(bufp, size, ", %d", n); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); if (r->land->ownership) { const char *str = LOC(f->locale, mkname("morale", itoa10(region_get_morale(r)))); - bytes = _snprintf(bufp, size, " %s", str); + bytes = snprintf(bufp, size, " %s", str); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); } - if (fval(r, RF_ORCIFIED)) { - bytes = (int)strlcpy(bufp, " ", size); - if (wrptr(&bufp, &size, bytes) != 0) - WARN_STATIC_BUFFER(); - - bytes = - (int)strlcpy(bufp, LOC(f->locale, n == 1 ? "rc_orc" : "rc_orc_p"), - size); - } - else { - bytes = (int)strlcpy(bufp, " ", size); - if (wrptr(&bufp, &size, bytes) != 0) - WARN_STATIC_BUFFER(); - bytes = - (int)strlcpy(bufp, LOC(f->locale, n == 1 ? "peasant" : "peasant_p"), - size); - } + bytes = (int)strlcpy(bufp, " ", size); + if (wrptr(&bufp, &size, bytes) != 0) + WARN_STATIC_BUFFER(); + bytes = + (int)strlcpy(bufp, LOC(f->locale, n == 1 ? "peasant" : "peasant_p"), + size); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); if (is_mourning(r, turn + 1)) { @@ -1046,7 +1041,7 @@ static void describe(stream *out, const region * r, faction * f) } } if (rmoney(r) && r->seen.mode >= seen_travel) { - bytes = _snprintf(bufp, size, ", %d ", rmoney(r)); + bytes = snprintf(bufp, size, ", %d ", rmoney(r)); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); bytes = @@ -1058,7 +1053,7 @@ static void describe(stream *out, const region * r, faction * f) /* Pferde */ if (rhorses(r)) { - bytes = _snprintf(bufp, size, ", %d ", rhorses(r)); + bytes = snprintf(bufp, size, ", %d ", rhorses(r)); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); bytes = @@ -1146,7 +1141,7 @@ static void describe(stream *out, const region * r, faction * f) if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); f_regionid(r2, f, regname, sizeof(regname)); - bytes = _snprintf(bufp, size, trailinto(r2, f->locale), regname); + bytes = snprintf(bufp, size, trailinto(r2, f->locale), regname); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); } @@ -1200,7 +1195,7 @@ static void describe(stream *out, const region * r, faction * f) bufp = buf; size = sizeof(buf) - 1; - // this localization might not work for every language but is fine for de and en + /* this localization might not work for every language but is fine for de and en */ bytes = (int)strlcpy(bufp, LOC(f->locale, "nr_schemes_prefix"), size); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); @@ -1242,7 +1237,7 @@ static void describe(stream *out, const region * r, faction * f) for (d = 0; d != MAXDIRECTIONS; ++d) { if (!e->exist[d]) continue; - // this localization might not work for every language but is fine for de and en + /* this localization might not work for every language but is fine for de and en */ if (first) bytes = (int)strlcpy(bufp, LOC(f->locale, "nr_borderlist_prefix"), size); else if (e->lastd == d) @@ -1256,8 +1251,8 @@ static void describe(stream *out, const region * r, faction * f) WARN_STATIC_BUFFER(); first = false; } - // TODO name is localized? Works for roads anyway... - // TODO: creating messages during reporting makes them not show up in CR? + /* TODO name is localized? Works for roads anyway... */ + /* TODO: creating messages during reporting makes them not show up in CR? */ msg = msg_message("nr_borderlist_postfix", "transparent object", e->transparent, e->name); bytes = (int)nr_render(msg, f->locale, bufp, size, f); @@ -1278,7 +1273,7 @@ static void describe(stream *out, const region * r, faction * f) } } -static void statistics(stream *out, const region * r, const faction * f) +static void statistics(struct stream *out, const region * r, const faction * f) { const unit *u; int number = 0, p = rpeasants(r); @@ -1386,7 +1381,7 @@ static int buildingmaintenance(const building * b, const resource_type * rtype) } static int -report_template(const char *filename, report_context * ctx, const char *charset) +report_template(const char *filename, report_context * ctx, const char *bom) { const resource_type *rsilver = get_resourcetype(R_SILVER); faction *f = ctx->f; @@ -1396,7 +1391,6 @@ report_template(const char *filename, report_context * ctx, const char *charset) char buf[8192], *bufp; size_t size; int bytes; - bool utf8 = _strcmpl(charset, "utf8") == 0 || _strcmpl(charset, "utf-8") == 0; const curse_type *nocost_ct = ct_find("nocostbuilding"); if (F == NULL) { @@ -1405,9 +1399,8 @@ report_template(const char *filename, report_context * ctx, const char *charset) } fstream_init(&strm, F); - if (utf8) { - const unsigned char utf8_bom[4] = { 0xef, 0xbb, 0xbf, 0 }; - swrite(utf8_bom, 1, 3, out); + if (bom) { + swrite(bom, 1, strlen(bom), out); } newline(out); @@ -1415,7 +1408,7 @@ report_template(const char *filename, report_context * ctx, const char *charset) newline(out); newline(out); - sprintf(buf, "%s %s \"password\"", LOC(f->locale, "ERESSEA"), factionid(f)); + sprintf(buf, "%s %s \"password\"", LOC(f->locale, parameters[P_FACTION]), itoa36(f->no)); rps_nowrap(out, buf); newline(out); newline(out); @@ -1460,9 +1453,9 @@ report_template(const char *filename, report_context * ctx, const char *charset) bufp = buf; size = sizeof(buf) - 1; - bytes = _snprintf(bufp, size, "%s %s; %s [%d,%d$", + bytes = snprintf(bufp, size, "%s %s; %s [%d,%d$", LOC(u->faction->locale, parameters[P_UNIT]), - unitid(u), unit_getname(u), u->number, get_money(u)); + itoa36(u->no), unit_getname(u), u->number, get_money(u)); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); if (u->building && building_owner(u->building) == u) { @@ -1488,7 +1481,7 @@ report_template(const char *filename, report_context * ctx, const char *charset) } if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); - bytes = (int)strlcpy(bufp, shipid(u->ship), size); + bytes = (int)strlcpy(bufp, itoa36(u->ship->no), size); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); } @@ -1630,7 +1623,7 @@ show_allies(const faction * f, const ally * allies, char *buf, size_t size) *bufp = 0; } -static void allies(stream *out, const faction * f) +static void allies(struct stream *out, const faction * f) { const group *g = f->groups; char buf[16384]; @@ -1638,7 +1631,7 @@ static void allies(stream *out, const faction * f) if (f->allies) { int bytes; size_t size = sizeof(buf); - bytes = _snprintf(buf, size, "%s ", LOC(f->locale, "faction_help")); + bytes = snprintf(buf, size, "%s ", LOC(f->locale, "faction_help")); size -= bytes; show_allies(f, f->allies, buf + bytes, size); paragraph(out, buf, 0, 0, 0); @@ -1649,7 +1642,7 @@ static void allies(stream *out, const faction * f) if (g->allies) { int bytes; size_t size = sizeof(buf); - bytes = _snprintf(buf, size, "%s %s ", g->name, LOC(f->locale, "group_help")); + bytes = snprintf(buf, size, "%s %s ", g->name, LOC(f->locale, "group_help")); size -= bytes; show_allies(f, g->allies, buf + bytes, size); paragraph(out, buf, 0, 0, 0); @@ -1659,7 +1652,7 @@ static void allies(stream *out, const faction * f) } } -static void guards(stream *out, const region * r, const faction * see) +static void guards(struct stream *out, const region * r, const faction * see) { /* die Partei see sieht dies; wegen * "unbekannte Partei", wenn man es selbst ist... */ @@ -1671,7 +1664,7 @@ static void guards(stream *out, const region * r, const faction * see) /* Bewachung */ for (u = r->units; u; u = u->next) { - if (is_guard(u, GUARD_ALL) != 0) { + if (is_guard(u) != 0) { faction *f = u->faction; faction *fv = visible_faction(see, u); @@ -1732,26 +1725,26 @@ static void guards(stream *out, const region * r, const faction * see) } } -static void rpline(stream *out) +static void rpline(struct stream *out) { static char line[REPORTWIDTH + 1]; if (line[0] != '-') { memset(line, '-', sizeof(line)); line[REPORTWIDTH] = '\n'; } - swrite(line, sizeof(char), sizeof(line), out); + swrite(line, sizeof(line), 1, out); } -static void list_address(stream *out, const faction * uf, quicklist * seenfactions) +static void list_address(struct stream *out, const faction * uf, selist * seenfactions) { int qi = 0; - quicklist *flist = seenfactions; + selist *flist = seenfactions; centre(out, LOC(uf->locale, "nr_addresses"), false); newline(out); while (flist != NULL) { - const faction *f = (const faction *)ql_get(flist, qi); + const faction *f = (const faction *)selist_get(flist, qi); if (!is_monsters(f)) { char buf[8192]; char label = '-'; @@ -1766,14 +1759,14 @@ static void list_address(stream *out, const faction * uf, quicklist * seenfactio label = '+'; paragraph(out, buf, 4, 0, label); } - ql_advance(&flist, &qi, 1); + selist_advance(&flist, &qi, 1); } newline(out); rpline(out); } static void -nr_ship(stream *out, const region *r, const ship * sh, const faction * f, +nr_ship(struct stream *out, const region *r, const ship * sh, const faction * f, const unit * captain) { char buffer[8192], *bufp = buffer; @@ -1788,12 +1781,12 @@ nr_ship(stream *out, const region *r, const ship * sh, const faction * f, getshipweight(sh, &n, &p); n = (n + 99) / 100; /* 1 Silber = 1 GE */ - bytes = _snprintf(bufp, size, "%s, %s, (%d/%d)", shipname(sh), + bytes = snprintf(bufp, size, "%s, %s, (%d/%d)", shipname(sh), LOC(f->locale, sh->type->_name), n, shipcapacity(sh) / 100); } else { bytes = - _snprintf(bufp, size, "%s, %s", shipname(sh), LOC(f->locale, + snprintf(bufp, size, "%s, %s", shipname(sh), LOC(f->locale, sh->type->_name)); } if (wrptr(&bufp, &size, bytes) != 0) @@ -1801,7 +1794,7 @@ nr_ship(stream *out, const region *r, const ship * sh, const faction * f, assert(sh->type->construction->improvement == NULL); /* sonst ist construction::size nicht ship_type::maxsize */ if (sh->size != sh->type->construction->maxsize) { - bytes = _snprintf(bufp, size, ", %s (%d/%d)", + bytes = snprintf(bufp, size, ", %s (%d/%d)", LOC(f->locale, "nr_undercons"), sh->size, sh->type->construction->maxsize); if (wrptr(&bufp, &size, bytes) != 0) @@ -1810,7 +1803,7 @@ nr_ship(stream *out, const region *r, const ship * sh, const faction * f, if (sh->damage) { int percent = ship_damage_percent(sh); bytes = - _snprintf(bufp, size, ", %d%% %s", percent, LOC(f->locale, "nr_damaged")); + snprintf(bufp, size, ", %d%% %s", percent, LOC(f->locale, "nr_damaged")); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); } @@ -1846,7 +1839,7 @@ nr_ship(stream *out, const region *r, const ship * sh, const faction * f, } static void -nr_building(stream *out, const region *r, const building *b, const faction *f) +nr_building(struct stream *out, const region *r, const building *b, const faction *f) { int i, bytes; const char *name, *bname, *billusion = NULL; @@ -1859,7 +1852,7 @@ nr_building(stream *out, const region *r, const building *b, const faction *f) lang = f->locale; newline(out); bytes = - _snprintf(bufp, size, "%s, %s %d, ", buildingname(b), LOC(lang, + snprintf(bufp, size, "%s, %s %d, ", buildingname(b), LOC(lang, "nr_size"), b->size); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); @@ -1874,7 +1867,7 @@ nr_building(stream *out, const region *r, const building *b, const faction *f) if (owner && owner->faction == f) { /* illusion. report real type */ name = LOC(lang, bname); - bytes = _snprintf(bufp, size, " (%s)", name); + bytes = snprintf(bufp, size, " (%s)", name); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); } @@ -1918,7 +1911,7 @@ nr_building(stream *out, const region *r, const building *b, const faction *f) } } -static void nr_paragraph(stream *out, message * m, faction * f) +static void nr_paragraph(struct stream *out, message * m, faction * f) { int bytes; char buf[4096], *bufp = buf; @@ -1934,14 +1927,14 @@ static void nr_paragraph(stream *out, message * m, faction * f) } typedef struct cb_data { - stream *out; + struct stream *out; char *start, *writep; size_t size; const faction *f; int maxtravel, counter; } cb_data; -static void init_cb(cb_data *data, stream *out, char *buffer, size_t size, const faction *f) { +static void init_cb(cb_data *data, struct stream *out, char *buffer, size_t size, const faction *f) { data->out = out; data->writep = buffer; data->start = buffer; @@ -1994,7 +1987,7 @@ static void cb_write_travelthru(region *r, unit *u, void *cbdata) { } } if (len >= size || data->counter == data->maxtravel) { - // buffer is full + /* buffer is full */ *writep = 0; paragraph(data->out, data->start, 0, 0, 0); data->writep = data->start; @@ -2006,7 +1999,7 @@ static void cb_write_travelthru(region *r, unit *u, void *cbdata) { } } -void write_travelthru(stream *out, region *r, const faction *f) +void write_travelthru(struct stream *out, region *r, const faction *f) { int maxtravel; char buf[8192]; @@ -2033,7 +2026,7 @@ void write_travelthru(stream *out, region *r, const faction *f) int report_plaintext(const char *filename, report_context * ctx, - const char *charset) + const char *bom) { int flag = 0; char ch; @@ -2051,7 +2044,6 @@ report_plaintext(const char *filename, report_context * ctx, stream strm = { 0 }, *out = &strm; char buf[8192]; char *bufp; - bool utf8 = _strcmpl(charset, "utf8") == 0 || _strcmpl(charset, "utf-8") == 0; size_t size; int thisseason; int nextseason; @@ -2068,9 +2060,8 @@ report_plaintext(const char *filename, report_context * ctx, } fstream_init(&strm, F); - if (utf8) { - const unsigned char utf8_bom[4] = { 0xef, 0xbb, 0xbf, 0 }; - fwrite(utf8_bom, 1, 3, F); + if (bom) { + fwrite(bom, 1, strlen(bom), F); } strftime(pzTime, 64, "%A, %d. %B %Y, %H:%M", localtime(&ctx->report_time)); @@ -2090,19 +2081,24 @@ report_plaintext(const char *filename, report_context * ctx, } if (f->age <= 2) { - const char *s; - s = locale_getstring(f->locale, "newbie_info_game"); - if (s) { - newline(out); - centre(out, s, true); + const char *email; + const char *subject; + email = config_get("game.email"); + subject = get_mailcmd(f->locale); + m = msg_message("newbie_info_game", "email subject", email, subject); + if (m) { + nr_render(m, f->locale, buf, sizeof(buf), f); + msg_release(m); + centre(out, buf, true); } if ((f->options & want(O_COMPUTER)) == 0) { - f->options |= want(O_COMPUTER); + const char *s; s = locale_getstring(f->locale, "newbie_info_cr"); if (s) { newline(out); centre(out, s, true); } + f->options |= want(O_COMPUTER); } } newline(out); @@ -2177,7 +2173,7 @@ report_plaintext(const char *filename, report_context * ctx, bufp = buf; size = sizeof(buf) - 1; - bytes = _snprintf(buf, size, "%s:", LOC(f->locale, "nr_options")); + bytes = snprintf(buf, size, "%s:", LOC(f->locale, "nr_options")); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); for (op = 0; op != MAXOPTIONS; op++) { @@ -2229,14 +2225,14 @@ report_plaintext(const char *filename, report_context * ctx, newline(out); centre(out, LOC(f->locale, pname), true); - _snprintf(buf, sizeof(buf), "%s %d", LOC(f->locale, "nr_level"), + snprintf(buf, sizeof(buf), "%s %d", LOC(f->locale, "nr_level"), ptype->level); centre(out, buf, true); newline(out); bufp = buf; size = sizeof(buf) - 1; - bytes = _snprintf(bufp, size, "%s: ", LOC(f->locale, "nr_herbsrequired")); + bytes = snprintf(bufp, size, "%s: ", LOC(f->locale, "nr_herbsrequired")); if (wrptr(&bufp, &size, bytes) != 0) WARN_STATIC_BUFFER(); @@ -2257,10 +2253,8 @@ report_plaintext(const char *filename, report_context * ctx, *bufp = 0; centre(out, buf, true); newline(out); - if (description == NULL) { - const char *potiontext = mkname("potion", pname); - description = LOC(f->locale, potiontext); - } + description = mkname("potion", pname); + description = LOC(f->locale, description); centre(out, description, true); } } @@ -2338,7 +2332,6 @@ report_plaintext(const char *filename, report_context * ctx, /* Nachrichten an REGION in der Region */ if (r->seen.mode == seen_unit || r->seen.mode == seen_travel) { - // TODO: Bug 2073 message_list *mlist = r_getmessages(r, f); if (mlist) { struct mlist **split = merge_messages(mlist, r->msgs); diff --git a/src/report.test.c b/src/report.test.c index cf074b284..aa3c52695 100644 --- a/src/report.test.c +++ b/src/report.test.c @@ -1,5 +1,4 @@ #include -#include #include "report.h" #include "move.h" #include "travelthru.h" @@ -19,7 +18,6 @@ #include #include -#include #include #include @@ -141,7 +139,7 @@ static void cleanup_spell_fixture(spell_fixture *spf) { static void set_parameter(spell_fixture spell, char *value) { free(spell.sp->parameter); - spell.sp->parameter = _strdup(value); + spell.sp->parameter = strdup(value); } static void check_spell_syntax(CuTest *tc, char *msg, spell_fixture *spell, char *syntax) { @@ -212,14 +210,14 @@ static void test_write_spell_syntax(CuTest *tc) { set_parameter(spell, "bc"); free(spell.sp->syntax); - spell.sp->syntax = _strdup("hodor"); + spell.sp->syntax = strdup("hodor"); check_spell_syntax(tc, "bc hodor", &spell, " ZAUBERE \"Testzauber\" "); free(spell.sp->syntax); spell.sp->syntax = 0; set_parameter(spell, "c?"); free(spell.sp->syntax); - spell.sp->syntax = _strdup("hodor"); + spell.sp->syntax = strdup("hodor"); check_spell_syntax(tc, "c?", &spell, " ZAUBERE \"Testzauber\" []"); free(spell.sp->syntax); spell.sp->syntax = 0; diff --git a/src/reports.c b/src/reports.c index 504ab299d..a93a8a3cb 100644 --- a/src/reports.c +++ b/src/reports.c @@ -19,6 +19,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include "reports.h" +#include "guard.h" #include "laws.h" #include "travelthru.h" #include "lighthouse.h" @@ -56,7 +57,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include +#include /* libc includes */ #include @@ -76,7 +77,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "move.h" #if defined(_MSC_VER) && _MSC_VER >= 1900 -# pragma warning(disable: 4774) // TODO: remove this +# pragma warning(disable: 4774) /* TODO: remove this */ #endif #define SCALEWEIGHT 100 /* Faktor, um den die Anzeige von Gewichten skaliert wird */ @@ -104,15 +105,30 @@ const char *coasts[MAXDIRECTIONS] = { "coast::w" }; +const char *options[MAXOPTIONS] = { + "AUSWERTUNG", + "COMPUTER", + "ZUGVORLAGE", + NULL, + "STATISTIK", + "DEBUG", + "ZIPPED", + "ZEITUNG", /* Option hat Sonderbehandlung! */ + NULL, + "ADRESSEN", + "BZIP2", + "PUNKTE", + "SHOWSKCHANGE" +}; + bool omniscient(const faction *f) { - static const race *rc_template, *rc_illusion; + static const race *rc_template; static int cache; if (rc_changed(&cache)) { - rc_illusion = get_race(RC_ILLUSION); rc_template = get_race(RC_TEMPLATE); } - return (f->race == rc_template || f->race == rc_illusion); + return (f->race == rc_template); } @@ -123,7 +139,7 @@ static char *groupid(const struct group *g, const struct faction *f) static name idbuf[8]; static int nextbuf = 0; char *buf = idbuf[(++nextbuf) % 8]; - sprintf(buf, "%s (%s)", g->name, factionid(f)); + sprintf(buf, "%s (%s)", g->name, itoa36(f->no)); return buf; } @@ -140,10 +156,10 @@ size_t report_status(const unit * u, const struct locale *lang, char *fsbuf, siz if (!status) { const char *lname = locale_name(lang); - struct locale *wloc = get_or_create_locale(lname); - log_error("no translation for combat status %s in %s", combatstatus[u->status], lname); - locale_setstring(wloc, combatstatus[u->status], combatstatus[u->status]); - len = strlcpy(fsbuf, combatstatus[u->status], buflen); + struct locale *wloc = get_locale(lname); + log_warning("no translation for combat status %s in %s", combatstatus[u->status], lname); + locale_setstring(wloc, combatstatus[u->status], combatstatus[u->status]+7); + len = strlcpy(fsbuf, combatstatus[u->status]+7, buflen); } else { len = strlcpy(fsbuf, status, buflen); @@ -396,32 +412,32 @@ const faction * viewer, bool see_unit) if (money) { if (n >= size) return -1; - report_resource(result + n, "rm_money", money, -1); + report_resource(result + n, "money", money, -1); ++n; } if (peasants) { if (n >= size) return -1; - report_resource(result + n, "rm_peasant", peasants, -1); + report_resource(result + n, "peasant", peasants, -1); ++n; } if (horses) { if (n >= size) return -1; - report_resource(result + n, "rm_horse", horses, -1); + report_resource(result + n, "horse", horses, -1); ++n; } if (saplings) { if (n >= size) return -1; - report_resource(result + n, mallorn ? "rm_mallornsapling" : "rm_sapling", + report_resource(result + n, mallorn ? "mallornsapling" : "sapling", saplings, -1); ++n; } if (trees) { if (n >= size) return -1; - report_resource(result + n, mallorn ? "rm_mallorn" : "rm_tree", trees, + report_resource(result + n, mallorn ? "mallorn" : "tree", trees, -1); ++n; } @@ -453,7 +469,7 @@ const faction * viewer, bool see_unit) if (level >= 0 && visible >= 0) { if (n >= size) return -1; - report_resource(result + n, res->type->name, visible, level); + report_resource(result + n, res->type->rtype->_name, visible, level); n++; } res = res->next; @@ -472,13 +488,14 @@ size_t size) building *b; bool isbattle = (bool)(mode == seen_battle); item *itm, *show = NULL; - faction *fv = visible_faction(f, u); + faction *fv; char *bufp = buf; int result = 0; item results[MAX_INVENTORY]; + assert(f); bufp = STRLCPY(bufp, unitname(u), size); - + fv = visible_faction(f, u); if (!isbattle) { attrib *a_otherfaction = a_find(u->attribs, &at_otherfaction); if (u->faction == f) { @@ -511,7 +528,7 @@ size_t size) if (a_otherfaction && alliedunit(u, f, HELP_FSTEALTH)) { faction *f = get_otherfaction(a_otherfaction); int result = - _snprintf(bufp, size, ", %s (%s)", factionname(f), + snprintf(bufp, size, ", %s (%s)", factionname(f), factionname(u->faction)); if (wrptr(&bufp, &size, result) != 0) WARN_STATIC_BUFFER(); @@ -526,7 +543,7 @@ size_t size) bufp = STRLCPY(bufp, ", ", size); - if (wrptr(&bufp, &size, _snprintf(bufp, size, "%d ", u->number))) + if (wrptr(&bufp, &size, snprintf(bufp, size, "%d ", u->number))) WARN_STATIC_BUFFER(); pzTmp = get_racename(u->attribs); @@ -582,7 +599,7 @@ size_t size) } } } - if (is_guard(u, GUARD_ALL) != 0) { + if (is_guard(u)) { bufp = STRLCPY(bufp, ", ", size); bufp = STRLCPY(bufp, LOC(f->locale, "unit_guards"), size); } @@ -623,7 +640,7 @@ size_t size) bufp = STRLCPY(bufp, ", ", size); if (!dh) { - result = _snprintf(bufp, size, "%s: ", LOC(f->locale, "nr_inventory")); + result = snprintf(bufp, size, "%s: ", LOC(f->locale, "nr_inventory")); if (wrptr(&bufp, &size, result) != 0) WARN_STATIC_BUFFER(); dh = 1; @@ -632,7 +649,7 @@ size_t size) bufp = STRLCPY(bufp, ic, size); } else { - if (wrptr(&bufp, &size, _snprintf(bufp, size, "%d %s", in, ic))) + if (wrptr(&bufp, &size, snprintf(bufp, size, "%d %s", in, ic))) WARN_STATIC_BUFFER(); } } @@ -641,19 +658,19 @@ size_t size) spellbook *book = unit_get_spellbook(u); if (book) { - quicklist *ql = book->spells; + selist *ql = book->spells; int qi, header, maxlevel = effskill(u, SK_MAGIC, 0); - int result = _snprintf(bufp, size, ". Aura %d/%d", get_spellpoints(u), max_spellpoints(u->region, u)); + int result = snprintf(bufp, size, ". Aura %d/%d", get_spellpoints(u), max_spellpoints(u->region, u)); if (wrptr(&bufp, &size, result) != 0) { WARN_STATIC_BUFFER(); } - for (header = 0, qi = 0; ql; ql_advance(&ql, &qi, 1)) { - spellbook_entry * sbe = (spellbook_entry *)ql_get(ql, qi); + for (header = 0, qi = 0; ql; selist_advance(&ql, &qi, 1)) { + spellbook_entry * sbe = (spellbook_entry *)selist_get(ql, qi); if (sbe->level <= maxlevel) { int result = 0; if (!header) { - result = _snprintf(bufp, size, ", %s: ", LOC(f->locale, "nr_spells")); + result = snprintf(bufp, size, ", %s: ", LOC(f->locale, "nr_spells")); header = 1; } else { @@ -662,6 +679,7 @@ size_t size) if (wrptr(&bufp, &size, result) != 0) { WARN_STATIC_BUFFER(); } + /* TODO: no need to deref the spellref here (spref->name is good) */ bufp = STRLCPY(bufp, spell_name(sbe->sp, f->locale), size); } } @@ -672,7 +690,7 @@ size_t size) } if (i != MAXCOMBATSPELLS) { int result = - _snprintf(bufp, size, ", %s: ", LOC(f->locale, "nr_combatspells")); + snprintf(bufp, size, ", %s: ", LOC(f->locale, "nr_combatspells")); if (wrptr(&bufp, &size, result) != 0) WARN_STATIC_BUFFER(); @@ -690,7 +708,7 @@ size_t size) int sl = get_combatspelllevel(u, i); bufp = STRLCPY(bufp, spell_name(sp, u->faction->locale), size); if (sl > 0) { - result = _snprintf(bufp, size, " (%d)", sl); + result = snprintf(bufp, size, " (%d)", sl); if (wrptr(&bufp, &size, result) != 0) WARN_STATIC_BUFFER(); } @@ -702,7 +720,7 @@ size_t size) } } if (!isbattle) { - bool printed = 0; + int printed = 0; order *ord;; for (ord = u->old_orders; ord; ord = ord->next) { keyword_t kwd = getkeyword(ord); @@ -753,7 +771,7 @@ size_t size) } dh = 0; - if (!getarnt && f) { + if (!getarnt) { if (alliedfaction(rplane(u->region), f, fv, HELP_ALL)) { dh = 1; } @@ -801,13 +819,13 @@ const struct unit * u, struct skill * sv, int *dh, int days) if (sv->id == SK_STEALTH && fval(u, UFL_STEALTH)) { i = u_geteffstealth(u); if (i >= 0) { - if (wrptr(&bufp, &size, _snprintf(bufp, size, "%d/", i)) != 0) + if (wrptr(&bufp, &size, snprintf(bufp, size, "%d/", i)) != 0) WARN_STATIC_BUFFER(); } } effsk = eff_skill(u, sv, 0); - if (wrptr(&bufp, &size, _snprintf(bufp, size, "%d", effsk)) != 0) + if (wrptr(&bufp, &size, snprintf(bufp, size, "%d", effsk)) != 0) WARN_STATIC_BUFFER(); if (u->faction->options & want(O_SHOWSKCHANGE)) { @@ -818,11 +836,11 @@ const struct unit * u, struct skill * sv, int *dh, int days) oldeff = sv->old + get_modifier(u, sv->id, sv->old, u->region, false); } - oldeff = _max(0, oldeff); + oldeff = MAX(0, oldeff); diff = effsk - oldeff; if (diff != 0) { - if (wrptr(&bufp, &size, _snprintf(bufp, size, " (%s%d)", (diff > 0) ? "+" : "", diff)) != 0) + if (wrptr(&bufp, &size, snprintf(bufp, size, " (%s%d)", (diff > 0) ? "+" : "", diff)) != 0) WARN_STATIC_BUFFER(); } } @@ -831,12 +849,8 @@ const struct unit * u, struct skill * sv, int *dh, int days) void split_paragraph(strlist ** SP, const char *s, unsigned int indent, unsigned int width, char mark) { - - /* Die Liste SP wird mit dem String s aufgefuellt, mit indent und einer - * mark, falls angegeben. SP wurde also auf 0 gesetzt vor dem Aufruf. - * Vgl. spunit (). */ bool firstline; - static char buf[REPORTWIDTH + 1]; // FIXME: static buffer, artificial limit + static char buf[REPORTWIDTH + 1]; /* FIXME: static buffer, artificial limit */ size_t len = strlen(s); assert(width <= REPORTWIDTH); @@ -863,11 +877,11 @@ void split_paragraph(strlist ** SP, const char *s, unsigned int indent, unsigned firstline = false; } if (!cut) { - cut = s + _min(len, REPORTWIDTH); + cut = s + MIN(len, REPORTWIDTH); } - strncpy(buf + indent, s, cut - s); + memcpy(buf + indent, s, cut - s); buf[indent + (cut - s)] = 0; - addstrlist(SP, buf); // TODO: too much string copying, cut out this function + addstrlist(SP, buf); /* TODO: too much string copying, cut out this function */ while (*cut == ' ') { ++cut; } @@ -955,8 +969,7 @@ int stealth_modifier(seen_mode mode) } } -void transfer_seen(quicklist ** dst, quicklist ** src) -{ +static void transfer_seen(selist ** dst, selist ** src) { assert(!*dst); *dst = *src; *src = NULL; @@ -970,8 +983,8 @@ int cmp_faction(const void *lhs, const void *rhs) { return -1; } -static void add_seen_faction_i(struct quicklist **flist, faction *f) { - ql_set_insert_ex(flist, f, cmp_faction); +static void add_seen_faction_i(struct selist **flist, faction *f) { + selist_set_insert(flist, f, cmp_faction); } void add_seen_faction(faction *self, faction *seen) { @@ -980,7 +993,7 @@ void add_seen_faction(faction *self, faction *seen) { typedef struct address_data { faction *f, *lastf; - quicklist **flist; + selist **flist; int stealthmod; } address_data; @@ -1002,8 +1015,8 @@ static void cb_add_address(region *r, unit *ut, void *cbdata) { } } -static void add_travelthru_addresses(region *r, faction *f, quicklist **flist, int stealthmod) { - // for each traveling unit: add the faction of any unit is can see +static void add_travelthru_addresses(region *r, faction *f, selist **flist, int stealthmod) { + /* for each traveling unit: add the faction of any unit is can see */ address_data cbdata = { 0 }; cbdata.f = f; cbdata.flist = flist; @@ -1016,18 +1029,18 @@ static void get_addresses(report_context * ctx) /* "TODO: travelthru" */ region *r; const faction *lastf = NULL; - quicklist *flist = 0; + selist *flist = 0; transfer_seen(&flist, &ctx->f->seen_factions); ctx->f->seen_factions = NULL; /* do not delete it twice */ - ql_push(&flist, ctx->f); + selist_push(&flist, ctx->f); if (f_get_alliance(ctx->f)) { - quicklist *ql = ctx->f->alliance->members; + selist *ql = ctx->f->alliance->members; int qi; - for (qi = 0; ql; ql_advance(&ql, &qi, 1)) { - add_seen_faction_i(&flist, (faction *)ql_get(ql, qi)); + for (qi = 0; ql; selist_advance(&ql, &qi, 1)) { + add_seen_faction_i(&flist, (faction *)selist_get(ql, qi)); } } @@ -1153,31 +1166,31 @@ int get_regions_distance_arr(region *rc, int radius, region *result[], int size) return n; } -quicklist *get_regions_distance(region * root, int radius) +selist *get_regions_distance(region * root, int radius) { - quicklist *ql, *rlist = NULL; + selist *ql, *rlist = NULL; int qi = 0; - ql_push(&rlist, root); + selist_push(&rlist, root); fset(root, RF_MARK); ql = rlist; while (ql) { - region *r = (region *)ql_get(ql, qi); + region *r = (region *)selist_get(ql, qi); region * next[MAXDIRECTIONS]; int d; get_neighbours(r, next); for (d = 0; d != MAXDIRECTIONS; ++d) { if (next[d] && !fval(next[d], RF_MARK) && distance(next[d], root) <= radius) { - ql_push(&rlist, next[d]); + selist_push(&rlist, next[d]); fset(next[d], RF_MARK); } } - ql_advance(&ql, &qi, 1); + selist_advance(&ql, &qi, 1); } - for (ql = rlist, qi = 0; ql; ql_advance(&ql, &qi, 1)) { - region *r = (region *)ql_get(ql, qi); + for (ql = rlist, qi = 0; ql; selist_advance(&ql, &qi, 1)) { + region *r = (region *)selist_get(ql, qi); freset(r, RF_MARK); } return rlist; @@ -1211,32 +1224,31 @@ static void add_seen_nb(faction *f, region *r, seen_mode mode) { /** mark all regions seen by the lighthouse. */ -static void prepare_lighthouse_ql(faction *f, quicklist *rlist) { - quicklist *ql; +static void prepare_lighthouse_ql(faction *f, selist *rlist) { + selist *ql; int qi; - for (ql = rlist, qi = 0; ql; ql_advance(&ql, &qi, 1)) { - region *rl = (region *)ql_get(ql, qi); + for (ql = rlist, qi = 0; ql; selist_advance(&ql, &qi, 1)) { + region *rl = (region *)selist_get(ql, qi); if (!fval(rl->terrain, FORBIDDEN_REGION)) { add_seen_nb(f, rl, seen_lighthouse); } } - ql_free(rlist); + selist_free(rlist); } -static void prepare_lighthouse(building * b, report_context *ctx) +static void prepare_lighthouse(faction *f, region *r, int range) { - faction *f = ctx->f; - int range = lighthouse_range(b, f); - if (range > 3) { - prepare_lighthouse_ql(f, get_regions_distance(b->region, range)); + selist *rlist = get_regions_distance(r, range); + prepare_lighthouse_ql(f, rlist); + selist_free(rlist); } else { region *result[64]; int n, i; - n = get_regions_distance_arr(b->region, range, result, 64); + n = get_regions_distance_arr(r, range, result, 64); assert(n > 0 && n <= 64); for (i = 0; i != n; ++i) { region *rl = result[i]; @@ -1369,17 +1381,6 @@ static void cb_add_seen(region *r, unit *u, void *cbdata) { } } -static bool unit_cansee(const unit *u) -{ - const race *rc = u_race(u); - static const race *rc_spell; - static int rc_cache; - if (rc_changed(&rc_cache)) { - rc_spell = get_race(RC_SPELL); - } - return (rc!=rc_spell || u->number == RS_FARVISION); -} - /** set region.seen based on visibility by one faction. * * this function may also update ctx->last and ctx->first for potential @@ -1388,7 +1389,6 @@ static bool unit_cansee(const unit *u) void prepare_report(report_context *ctx, faction *f) { region *r; - building *b; static int config; static bool rule_region_owners; const struct building_type *bt_lighthouse = bt_find("lighthouse"); @@ -1397,62 +1397,68 @@ void prepare_report(report_context *ctx, faction *f) rule_region_owners = config_token("rules.region_owner_pay_building", bt_lighthouse->_name); } + if (f->age<=2) { + if ((f->flags&FFL_PWMSG)==0) { + /* TODO: this assumes unencrypted passwords */ + f->flags |= FFL_PWMSG; + ADDMSG(&f->msgs, msg_message("changepasswd", "value", f->_password)); + } + } + ctx->f = f; ctx->report_time = time(NULL); ctx->addresses = NULL; ctx->userdata = NULL; - // [first,last) interval of regions with a unit in it: + /* [first,last) interval of regions with a unit in it: */ ctx->first = firstregion(f); ctx->last = lastregion(f); for (r = ctx->first; r!=ctx->last; r = r->next) { + int range = 0; unit *u; + if (fval(r, RF_LIGHTHOUSE) && bt_lighthouse) { + if (rule_region_owners && f == region_get_owner(r)) { + /* region owners get the report from lighthouses */ + building *b; - if (fval(r, RF_LIGHTHOUSE)) { - /* region owners get the report from lighthouses */ - if (rule_region_owners && bt_lighthouse) { - for (b = rbuildings(r); b; b = b->next) { - if (b && b->type == bt_lighthouse) { - u = building_owner(b); - if (u && u->faction==f) { - prepare_lighthouse(b, ctx); - if (unit_cansee(u)) { - add_seen_nb(f, r, seen_unit); - } - } + for (b = r->buildings; b; b = b->next) { + if (b->type == bt_lighthouse) { + int br = lighthouse_range(b, NULL); + if (br > range) range = br; } } } - } for (u = r->units; u; u = u->next) { - if (u->faction==f) { - if (unit_cansee(u)) { - add_seen_nb(f, r, seen_unit); - } - if (fval(r, RF_LIGHTHOUSE)) { + if (u->faction == f) { + add_seen_nb(f, r, seen_unit); + if (fval(r, RF_LIGHTHOUSE) && bt_lighthouse) { if (u->building && u->building->type == bt_lighthouse && inside_building(u)) { - /* we are in a lighthouse. add the regions we can see from here! */ - prepare_lighthouse(u->building, ctx); + int br = lighthouse_range(u->building, f); + if (br > range) range = br; } } } } + if (range > 0) { + /* we are in at least one lighthouse. add the regions we can see from here! */ + prepare_lighthouse(f, r, range); + } if (fval(r, RF_TRAVELUNIT) && r->seen.modefirst = firstregion(f); ctx->last = lastregion(f); } void finish_reports(report_context *ctx) { region *r; - ql_free(ctx->addresses); + selist_free(ctx->addresses); for (r = ctx->first; r != ctx->last; r = r->next) { r->seen.mode = seen_none; } @@ -1460,12 +1466,10 @@ void finish_reports(report_context *ctx) { int write_reports(faction * f, time_t ltime) { - unsigned int backup = 1, maxbackup = 128 * 1000; bool gotit = false; struct report_context ctx; - const char *encoding = "UTF-8"; + const unsigned char utf8_bom[4] = { 0xef, 0xbb, 0xbf, 0 }; report_type *rtype; - if (noreports) { return false; } @@ -1477,31 +1481,24 @@ int write_reports(faction * f, time_t ltime) int error = 0; do { char filename[32]; - char path[MAX_PATH]; - sprintf(filename, "%d-%s.%s", turn, factionid(f), + char path[4096]; + sprintf(filename, "%d-%s.%s", turn, itoa36(f->no), rtype->extension); join_path(reportpath(), filename, path, sizeof(path)); errno = 0; - if (rtype->write(path, &ctx, encoding) == 0) { + if (rtype->write(path, &ctx, (const char *)utf8_bom) == 0) { gotit = true; } if (errno) { - char zText[64]; - log_warning("retrying, error %d during %s report for faction %s", errno, rtype->extension, factionname(f)); - sprintf(zText, "waiting %u seconds before we retry", backup); - perror(zText); - _sleep(backup); - if (backup < maxbackup) { - backup *= 2; - } error = errno; + log_fatal("error %d during %s report for faction %s: %s", errno, rtype->extension, factionname(f), strerror(error)); errno = 0; } } while (error); } } if (!gotit) { - log_warning("No report for faction %s!", factionid(f)); + log_warning("No report for faction %s!", itoa36(f->no)); } finish_reports(&ctx); return 0; @@ -1512,7 +1509,7 @@ static void write_script(FILE * F, const faction * f) report_type *rtype; char buf[1024]; - fprintf(F, "faction=%s:email=%s:lang=%s", factionid(f), f->email, + fprintf(F, "faction=%s:email=%s:lang=%s", itoa36(f->no), f->email, locale_name(f->locale)); if (f->options & (1 << O_BZIP2)) fputs(":compression=bz2", F); @@ -1554,7 +1551,7 @@ int reports(void) FILE *mailit; time_t ltime = time(NULL); int retval = 0; - char path[MAX_PATH]; + char path[4096]; const char * rpath = reportpath(); log_info("Writing reports for turn %d:", turn); @@ -1581,7 +1578,7 @@ int reports(void) static variant var_copy_string(variant x) { - x.v = x.v ? _strdup((const char *)x.v) : 0; + x.v = x.v ? strdup((const char *)x.v) : 0; return x; } @@ -1646,7 +1643,7 @@ static void var_free_resources(variant x) x.v = 0; } -static void var_free_regions(variant x) +static void var_free_regions(variant x) /*-V524 */ { free(x.v); } @@ -1685,7 +1682,7 @@ f_regionid(const region * r, const faction * f, char *buffer, size_t size) pnormalize(&nx, &ny, pl); adjust_coordinates(f, &nx, &ny, pl); len = strlcpy(buffer, rname(r, f ? f->locale : 0), size); - _snprintf(buffer + len, size - len, " (%d,%d%s%s)", nx, ny, named ? "," : "", (named) ? name : ""); + snprintf(buffer + len, size - len, " (%d,%d%s%s)", nx, ny, named ? "," : "", (named) ? name : ""); buffer[size - 1] = 0; len = strlen(buffer); } @@ -1694,7 +1691,7 @@ f_regionid(const region * r, const faction * f, char *buffer, size_t size) static char *f_regionid_s(const region * r, const faction * f) { - static char buf[NAMESIZE + 20]; // FIXME: static return value + static char buf[NAMESIZE + 20]; /* FIXME: static return value */ f_regionid(r, f, buf, sizeof(buf)); return buf; @@ -1753,11 +1750,10 @@ static void eval_spell(struct opstack **stack, const void *userdata) const struct spell *sp = (const struct spell *)opop(stack).v; const char *c = sp ? spell_name(sp, f->locale) : LOC(f->locale, "an_unknown_spell"); - assert(c || !"spell without description!"); - size_t len = strlen(c); variant var; - var.v = strcpy(balloc(len + 1), c); + assert(c || !"spell without description!"); + var.v = strcpy(balloc(strlen(c) + 1), c); opush(stack, var); } @@ -1767,23 +1763,10 @@ static void eval_curse(struct opstack **stack, const void *userdata) const struct curse_type *sp = (const struct curse_type *)opop(stack).v; const char *c = sp ? curse_name(sp, f->locale) : LOC(f->locale, "an_unknown_curse"); + variant var; + assert(c || !"spell effect without description!"); - size_t len = strlen(c); - variant var; - - var.v = strcpy(balloc(len + 1), c); - opush(stack, var); -} - -static void eval_unitname(struct opstack **stack, const void *userdata) -{ /* unit -> string */ - const struct faction *f = (const struct faction *)userdata; - const struct unit *u = (const struct unit *)opop(stack).v; - const char *c = u ? unit_getname(u) : LOC(f->locale, "an_unknown_unit"); - size_t len = strlen(c); - variant var; - - var.v = strcpy(balloc(len + 1), c); + var.v = strcpy(balloc(strlen(c) + 1), c); opush(stack, var); } @@ -1895,16 +1878,16 @@ static void eval_weight(struct opstack **stack, const void *userdata) sprintf(buffer, "1 %s", LOC(lang, "weight_unit")); } else { - sprintf(buffer, "%u %s", weight / SCALEWEIGHT, LOC(lang, + sprintf(buffer, "%d %s", weight / SCALEWEIGHT, LOC(lang, "weight_unit_p")); } } else { if (weight == 1) { - sprintf(buffer, "1 %s %u", LOC(lang, "weight_per"), SCALEWEIGHT); + sprintf(buffer, "1 %s %d", LOC(lang, "weight_per"), SCALEWEIGHT); } else { - sprintf(buffer, "%u %s %u", weight, LOC(lang, "weight_per_p"), + sprintf(buffer, "%d %s %d", weight, LOC(lang, "weight_per_p"), SCALEWEIGHT); } } @@ -1948,7 +1931,7 @@ static void eval_order(struct opstack **stack, const void *userdata) size_t len; variant var; - unused_arg(userdata); + UNUSED_ARG(userdata); write_order(ord, buf, sizeof(buf)); len = strlen(buf); var.v = strcpy(balloc(len + 1), buf); @@ -1968,7 +1951,7 @@ static void eval_resources(struct opstack **stack, const void *userdata) while (res != NULL && size > 4) { const char *rname = resourcename(res->type, (res->number != 1) ? NMF_PLURAL : 0); - int result = _snprintf(bufp, size, "%d %s", res->number, LOC(lang, rname)); + int result = snprintf(bufp, size, "%d %s", res->number, LOC(lang, rname)); if (wrptr(&bufp, &size, result) != 0 || size < sizeof(buf) / 2) { WARN_STATIC_BUFFER(); break; @@ -1991,23 +1974,23 @@ static void eval_regions(struct opstack **stack, const void *userdata) const faction *report = (const faction *)userdata; int i = opop(stack).i; int end, begin = opop(stack).i; - const arg_regions *regions = (const arg_regions *)opop(stack).v; + const arg_regions *aregs = (const arg_regions *)opop(stack).v; char buf[256]; size_t size = sizeof(buf) - 1; variant var; char *bufp = buf; - if (regions == NULL) { + if (aregs == NULL) { end = begin; } else { if (i >= 0) end = begin + i; else - end = regions->nregions + i; + end = aregs->nregions + i; } for (i = begin; i < end; ++i) { - const char *rname = (const char *)regionname(regions->regions[i], report); + const char *rname = (const char *)regionname(aregs->regions[i], report); bufp = STRLCPY(bufp, rname, size); if (i + 1 < end && size > 2) { @@ -2021,29 +2004,36 @@ static void eval_regions(struct opstack **stack, const void *userdata) opush(stack, var); } +const char *get_mailcmd(const struct locale *loc) +{ + static char result[64]; /* FIXME: static return buffer */ + snprintf(result, sizeof(result), "%s %d %s", game_name_upper(), game_id(), LOC(loc, "mailcmd")); + return result; +} + static void eval_trail(struct opstack **stack, const void *userdata) { /* order -> string */ const faction *report = (const faction *)userdata; const struct locale *lang = report ? report->locale : default_locale; int i, end = 0, begin = 0; - const arg_regions *regions = (const arg_regions *)opop(stack).v; + const arg_regions *aregs = (const arg_regions *)opop(stack).v; char buf[512]; size_t size = sizeof(buf) - 1; variant var; char *bufp = buf; #ifdef _SECURECRT_ERRCODE_VALUES_DEFINED - /* stupid MS broke _snprintf */ + /* stupid MS broke snprintf */ int eold = errno; #endif - if (regions != NULL) { - end = regions->nregions; + if (aregs != NULL) { + end = aregs->nregions; for (i = begin; i < end; ++i) { - region *r = regions->regions[i]; + region *r = aregs->regions[i]; const char *trail = trailinto(r, lang); const char *rn = f_regionid_s(r, report); - if (wrptr(&bufp, &size, _snprintf(bufp, size, trail, rn)) != 0) + if (wrptr(&bufp, &size, snprintf(bufp, size, trail, rn)) != 0) WARN_STATIC_BUFFER(); if (i + 2 < end) { @@ -2099,7 +2089,7 @@ static void eval_int36(struct opstack **stack, const void *userdata) var.v = strcpy(balloc(len + 1), c); opush(stack, var); - unused_arg(userdata); + UNUSED_ARG(userdata); } /*** END MESSAGE RENDERING ***/ @@ -2126,12 +2116,12 @@ int stream_printf(struct stream * out, const char *format, ...) { int result; char buffer[4096]; size_t bytes = sizeof(buffer); - // TODO: should be in storage/stream.c (doesn't exist yet) + /* TODO: should be in storage/stream.c (doesn't exist yet) */ va_start(args, format); result = vsnprintf(buffer, bytes, format, args); if (result >= 0 && (size_t)result < bytes) { bytes = (size_t)result; - // TODO: else = buffer too small + /* TODO: else = buffer too small */ } out->api->write(out->handle, buffer, bytes); va_end(args); @@ -2195,7 +2185,6 @@ void register_reports(void) add_function("ship", &eval_ship); add_function("unit", &eval_unit); add_function("unit.dative", &eval_unit_dative); - add_function("unit.name", &eval_unitname); add_function("unit.id", &eval_unitid); add_function("unit.size", &eval_unitsize); add_function("building", &eval_building); diff --git a/src/reports.h b/src/reports.h index e2484de74..520a074d4 100644 --- a/src/reports.h +++ b/src/reports.h @@ -20,17 +20,19 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef H_KRNL_REPORTS #define H_KRNL_REPORTS -#include #include #include #include +#include -struct stream; -struct seen_region; #ifdef __cplusplus extern "C" { #endif + struct selist; + struct stream; + struct seen_region; + /* Alter, ab dem der Score angezeigt werden soll: */ #define DISPLAYSCORE 12 /* Breite einer Reportzeile: */ @@ -43,13 +45,14 @@ extern "C" { extern bool nocr; extern bool noreports; extern const char *visibility[]; + extern const char *options[MAXOPTIONS]; /* report options */ void reports_done(void); struct unit *can_find(struct faction *, struct faction *); bool omniscient(const struct faction *f); - struct quicklist *get_regions_distance(struct region * root, int radius); + struct selist *get_regions_distance(struct region * root, int radius); int get_regions_distance_arr(struct region *r, int radius, struct region *result[], int size); /* funktionen zum schreiben eines reports */ void sparagraph(struct strlist **SP, const char *s, unsigned int indent, char mark); @@ -71,7 +74,7 @@ extern "C" { typedef struct report_context { struct faction *f; - struct quicklist *addresses; + struct selist *addresses; struct region *first, *last; void *userdata; time_t report_time; @@ -129,6 +132,7 @@ extern "C" { int stream_printf(struct stream * out, const char *format, ...); int count_travelthru(struct region *r, const struct faction *f); + const char *get_mailcmd(const struct locale *loc); #define GR_PLURAL 0x01 /* grammar: plural */ #define MAX_INVENTORY 128 /* maimum number of different items in an inventory */ diff --git a/src/reports.test.c b/src/reports.test.c index bef1047d8..673522535 100644 --- a/src/reports.test.c +++ b/src/reports.test.c @@ -1,5 +1,4 @@ #include -#include #include "reports.h" #include "move.h" @@ -7,6 +6,7 @@ #include "travelthru.h" #include "keyword.h" +#include #include #include #include @@ -23,7 +23,7 @@ #include #include -#include +#include #include #include @@ -108,14 +108,14 @@ static void test_seen_faction(CuTest *tc) { f1 = test_create_faction(rc); f2 = test_create_faction(rc); add_seen_faction(f1, f2); - CuAssertPtrEquals(tc, f2, ql_get(f1->seen_factions, 0)); - CuAssertIntEquals(tc, 1, ql_length(f1->seen_factions)); + CuAssertPtrEquals(tc, f2, selist_get(f1->seen_factions, 0)); + CuAssertIntEquals(tc, 1, selist_length(f1->seen_factions)); add_seen_faction(f1, f2); - CuAssertIntEquals(tc, 1, ql_length(f1->seen_factions)); + CuAssertIntEquals(tc, 1, selist_length(f1->seen_factions)); add_seen_faction(f1, f1); - CuAssertIntEquals(tc, 2, ql_length(f1->seen_factions)); - f2 = (faction *)ql_get(f1->seen_factions, 1); - f1 = (faction *)ql_get(f1->seen_factions, 0); + CuAssertIntEquals(tc, 2, selist_length(f1->seen_factions)); + f2 = (faction *)selist_get(f1->seen_factions, 1); + f1 = (faction *)selist_get(f1->seen_factions, 0); CuAssertTrue(tc, f1->no < f2->no); test_cleanup(); } @@ -226,6 +226,23 @@ static void test_arg_resources(CuTest *tc) { test_cleanup(); } +static void test_newbie_password_message(CuTest *tc) { + report_context ctx; + faction *f; + test_setup(); + f = test_create_faction(0); + f->age = 5; + f->flags = 0; + prepare_report(&ctx, f); + CuAssertIntEquals(tc, 0, f->flags&FFL_PWMSG); + CuAssertPtrEquals(tc, 0, test_find_messagetype(f->msgs, "changepasswd")); + f->age=2; + prepare_report(&ctx, f); + CuAssertIntEquals(tc, FFL_PWMSG, f->flags&FFL_PWMSG); + CuAssertPtrNotNull(tc, test_find_messagetype(f->msgs, "changepasswd")); + test_cleanup(); +} + static void test_prepare_travelthru(CuTest *tc) { report_context ctx; faction *f, *f2; @@ -344,6 +361,43 @@ static void test_prepare_lighthouse(CuTest *tc) { test_cleanup(); } +static void test_prepare_lighthouse_owners(CuTest *tc) { + report_context ctx; + faction *f; + region *r1, *r2, *r3; + unit *u; + building *b; + building_type *btype; + const struct terrain_type *t_ocean, *t_plain; + + test_setup(); + config_set("rules.region_owner_pay_building", "lighthouse"); + config_set("rules.region_owners", "1"); + t_ocean = test_create_terrain("ocean", SEA_REGION); + t_plain = test_create_terrain("plain", LAND_REGION); + f = test_create_faction(0); + r1 = test_create_region(0, 0, t_plain); + r2 = test_create_region(1, 0, t_ocean); + r3 = test_create_region(2, 0, t_ocean); + btype = test_create_buildingtype("lighthouse"); + b = test_create_building(r1, btype); + b->flags |= BLD_MAINTAINED; + b->size = 10; + update_lighthouse(b); + u = test_create_unit(f, r1); + u = test_create_unit(test_create_faction(0), r1); + u->building = b; + set_level(u, SK_PERCEPTION, 3); + region_set_owner(b->region, f, 0); + prepare_report(&ctx, f); + CuAssertPtrEquals(tc, r1, ctx.first); + CuAssertPtrEquals(tc, NULL, ctx.last); + CuAssertIntEquals(tc, seen_unit, r1->seen.mode); + CuAssertIntEquals(tc, seen_lighthouse, r2->seen.mode); + CuAssertIntEquals(tc, seen_neighbour, r3->seen.mode); + test_cleanup(); +} + static void test_prepare_report(CuTest *tc) { report_context ctx; faction *f; @@ -463,21 +517,21 @@ static void test_region_distance(CuTest *tc) { static void test_region_distance_ql(CuTest *tc) { region *r; - quicklist *ql; + selist *ql; test_setup(); r = test_create_region(0, 0, 0); ql = get_regions_distance(r, 0); - CuAssertIntEquals(tc, 1, ql_length(ql)); - CuAssertPtrEquals(tc, r, ql_get(ql, 0)); - ql_free(ql); + CuAssertIntEquals(tc, 1, selist_length(ql)); + CuAssertPtrEquals(tc, r, selist_get(ql, 0)); + selist_free(ql); test_create_region(1, 0, 0); test_create_region(0, 1, 0); ql = get_regions_distance(r, 1); - CuAssertIntEquals(tc, 3, ql_length(ql)); - ql_free(ql); + CuAssertIntEquals(tc, 3, selist_length(ql)); + selist_free(ql); ql = get_regions_distance(r, 2); - CuAssertIntEquals(tc, 3, ql_length(ql)); - ql_free(ql); + CuAssertIntEquals(tc, 3, selist_length(ql)); + selist_free(ql); test_cleanup(); } @@ -487,10 +541,12 @@ CuSuite *get_reports_suite(void) SUITE_ADD_TEST(suite, test_region_distance); SUITE_ADD_TEST(suite, test_region_distance_max); SUITE_ADD_TEST(suite, test_region_distance_ql); + SUITE_ADD_TEST(suite, test_newbie_password_message); SUITE_ADD_TEST(suite, test_prepare_report); SUITE_ADD_TEST(suite, test_seen_neighbours); SUITE_ADD_TEST(suite, test_seen_travelthru); SUITE_ADD_TEST(suite, test_prepare_lighthouse); + SUITE_ADD_TEST(suite, test_prepare_lighthouse_owners); SUITE_ADD_TEST(suite, test_prepare_lighthouse_capacity); SUITE_ADD_TEST(suite, test_prepare_travelthru); SUITE_ADD_TEST(suite, test_reorder_units); diff --git a/src/settings.h b/src/settings.h index c44bc0f2a..e7ec39305 100644 --- a/src/settings.h +++ b/src/settings.h @@ -10,10 +10,6 @@ without prior permission by the authors of Eressea. */ -/* - * Contains defines for the "free" game (Eressea) . - * Include this file from settings.h to make eressea work. - */ #define ENTERTAINFRACTION 20 #define TEACHDIFFERENCE 2 #define GUARD_DISABLES_RECRUIT 1 @@ -24,7 +20,7 @@ #undef NEWATSROI /* Vermehrungsrate Bauern in 1/10000. -* TODO: Evt. Berechnungsfehler, reale Vermehrungsraten scheinen hher. */ +* TODO: Evt. Berechnungsfehler, reale Vermehrungsraten scheinen hoeher. */ #define PEASANTGROWTH 10 #define PEASANTLUCK 10 @@ -35,28 +31,26 @@ * or both. We don't want separate binaries for different games */ #define MUSEUM_MODULE 1 -#define ARENA_MODULE 1 #undef REGIONOWNERS /* (WIP) region-owner uses HELP_TRAVEL to control entry to region */ /* experimental gameplay features (that don't affect the savefile) */ /* TODO: move these settings to settings.h or into configuration files */ -#define GOBLINKILL /* Goblin-Spezialklau kann tdlich enden */ -#define INSECT_POTION /* Spezialtrank fr Insekten */ -#define ORCIFICATION /* giving snotlings to the peasants gets counted */ +#define GOBLINKILL /* Goblin-Spezialklau kann toedlich enden */ +#define INSECT_POTION /* Spezialtrank fuer Insekten */ #define TREESIZE (8) /* space used by trees (in #peasants) */ #define PEASANTFORCE 0.75 /* Chance einer Vermehrung trotz 90% Auslastung */ - /* Gebudegre = Minimalbelagerer */ + /* Gebaeudegroesse = Minimalbelagerer */ #define SIEGEFACTOR 2 /** Magic */ #define MAXMAGICIANS 3 #define MAXALCHEMISTS 3 -#define ENCCHANCE 10 /* %-Chance fr einmalige Zufallsbegegnung */ -#define BAGCAPACITY 20000 /* soviel pat in einen Bag of Holding */ +#define ENCCHANCE 10 /* %-Chance fuer einmalige Zufallsbegegnung */ +#define BAGCAPACITY 20000 /* soviel passt in einen Bag of Holding */ #define PERSON_WEIGHT 1000 /* weight of a "normal" human unit */ #define STAMINA_AFFECTS_HP 1<<0 diff --git a/src/skill.h b/src/skill.h index 8b0c0c155..24f96a844 100644 --- a/src/skill.h +++ b/src/skill.h @@ -3,7 +3,7 @@ #ifndef H_SKILL_H #define H_SKILL_H -#include +#include struct locale; typedef enum { diff --git a/src/spells.c b/src/spells.c index 4f2d49d9d..fcee1b51b 100644 --- a/src/spells.c +++ b/src/spells.c @@ -15,13 +15,14 @@ #include #include +#include "guard.h" #include "spy.h" #include "vortex.h" #include "laws.h" #include "spells.h" #include "direction.h" #include "randenc.h" -#include "monster.h" +#include "monsters.h" #include "teleport.h" #include @@ -33,10 +34,10 @@ #include /* kernel includes */ -#include -#include #include #include +#include +#include #include #include #include @@ -46,7 +47,6 @@ #include #include #include -#include #include #include #include @@ -60,6 +60,7 @@ #include #include #include +#include #include #include #include @@ -94,7 +95,6 @@ #include #include #include -#include /* attributes includes */ #include @@ -107,10 +107,6 @@ static double zero_effect = 0.0; -attrib_type at_wdwpyramid = { - "wdwpyramid", NULL, NULL, NULL, a_writevoid, a_readvoid -}; - /* ----------------------------------------------------------------------- */ static void report_spell(unit * mage, region * r, message * msg) @@ -153,7 +149,7 @@ static void magicanalyse_region(region * r, unit * mage, double force) * mehr als 100% probability und damit immer ein Erfolg. */ probability = curse_chance(c, force); mon = c->duration + (rng_int() % 10) - 5; - mon = _max(1, mon); + mon = MAX(1, mon); found = true; if (chance(probability)) { /* Analyse geglueckt */ @@ -194,7 +190,7 @@ static void magicanalyse_unit(unit * u, unit * mage, double force) * mehr als 100% probability und damit immer ein Erfolg. */ probability = curse_chance(c, force); mon = c->duration + (rng_int() % 10) - 5; - mon = _max(1, mon); + mon = MAX(1, mon); if (chance(probability)) { /* Analyse geglueckt */ if (c_flags(c) & CURSE_NOAGE) { @@ -235,7 +231,7 @@ static void magicanalyse_building(building * b, unit * mage, double force) * mehr als 100% probability und damit immer ein Erfolg. */ probability = curse_chance(c, force); mon = c->duration + (rng_int() % 10) - 5; - mon = _max(1, mon); + mon = MAX(1, mon); if (chance(probability)) { /* Analyse geglueckt */ if (c_flags(c) & CURSE_NOAGE) { @@ -276,7 +272,7 @@ static void magicanalyse_ship(ship * sh, unit * mage, double force) * mehr als 100% probability und damit immer ein Erfolg. */ probability = curse_chance(c, force); mon = c->duration + (rng_int() % 10) - 5; - mon = _max(1, mon); + mon = MAX(1, mon); if (chance(probability)) { /* Analyse geglueckt */ if (c_flags(c) & CURSE_NOAGE) { @@ -401,6 +397,7 @@ static void report_effect(region * r, unit * mage, message * seen, message * unseen) { int err = report_action(r, mage, seen, ACTION_RESET | ACTION_CANSEE); + UNUSED_ARG(unseen); if (err) { report_action(r, mage, seen, ACTION_CANNOTSEE); } @@ -450,7 +447,7 @@ report_effect(region * r, unit * mage, message * seen, message * unseen) * Vertrauten sehen, und durch den Vertrauten zaubern, allerdings nur * mit seiner halben Stufe. Je nach Vertrautem erhaelt der Magier * evtl diverse Skillmodifikationen. Der Typ des Vertrauten ist - * zufaellig bestimmt, wird aber durch Magiegebiet und Rasse beeinflut. + * zufaellig bestimmt, wird aber durch Magiegebiet und Rasse beeinflu�t. * "Tierische" Vertraute brauchen keinen Unterhalt. * * Ein paar Moeglichkeiten: @@ -517,11 +514,16 @@ static const race *select_familiar(const race * magerace, magic_t magiegebiet) static void make_familiar(unit * familiar, unit * mage) { /* skills and spells: */ - if (u_race(familiar)->init_familiar != NULL) { - u_race(familiar)->init_familiar(familiar); + const struct equipment *eq; + char eqname[64]; + const race * rc = u_race(familiar); + snprintf(eqname, sizeof(eqname), "%s_familiar", rc->_name); + eq = get_equipment(eqname); + if (eq != NULL) { + equip_items(&familiar->items, eq); } else { - log_error("could not perform initialization for familiar %s.\n", familiar->faction->race->_name); + log_error("could not perform initialization for familiar %s.\n", rc->_name); } /* triggers: */ @@ -708,7 +710,7 @@ static int sp_destroy_magic(castorder * co) "unit region command", mage, mage->region, co->order)); } - return _max(succ, 1); + return MAX(succ, 1); } /* ------------------------------------------------------------- */ @@ -777,7 +779,7 @@ static int sp_transferaura(castorder * co) return 0; } - gain = _min(aura, scm_src->spellpoints) / multi; + gain = MIN(aura, scm_src->spellpoints) / multi; scm_src->spellpoints -= gain * multi; scm_dst->spellpoints += gain; @@ -916,7 +918,7 @@ static int sp_summonent(castorder * co) return 0; } - ents = _min((int)(power * power), rtrees(r, 2)); + ents = MIN((int)(power * power), rtrees(r, 2)); u = create_unit(r, mage->faction, ents, get_race(RC_TREEMAN), 0, NULL, mage); @@ -1308,7 +1310,7 @@ static int sp_rosthauch(castorder * co) for (; iweapon != NULL; iweapon = iweapon->next) { item **ip = i_find(&u->items, iweapon->type); if (*ip) { - float chance = (float)_min((*ip)->number, force); + float chance = (float)MIN((*ip)->number, force); if (iweapon->chance < 1.0) { chance *= iweapon->chance; } @@ -1347,7 +1349,7 @@ static int sp_rosthauch(castorder * co) * unguenstigsten Fall kann pro Stufe nur eine Waffe verzaubert werden, * darum wird hier nur fuer alle Faelle in denen noch weniger Waffen * betroffen wurden ein Kostennachlass gegeben */ - return _min(success, cast_level); + return MIN(success, cast_level); } /* ------------------------------------------------------------- */ @@ -1377,7 +1379,7 @@ static int sp_kaelteschutz(castorder * co) unit *mage = co->magician.u; int cast_level = co->level; double force = co->force; - int duration = _max(cast_level, (int)force) + 1; + int duration = MAX(cast_level, (int)force) + 1; spellparameter *pa = co->par; double effect; @@ -1603,7 +1605,7 @@ static int sp_create_stonegolem(castorder * co) } /* ------------------------------------------------------------- */ -/* Name: Groe Duerre +/* Name: Gro�e Duerre * Stufe: 17 * Kategorie: Region, negativ * Gebiet: Gwyrrd @@ -1911,7 +1913,7 @@ static int sp_treewalkexit(castorder * co) return 0; } - /* Koordinaten setzen und Region loeschen fuer berpruefung auf + /* Koordinaten setzen und Region loeschen fuer �berpruefung auf * Gueltigkeit */ rt = pa->param[0]->data.r; tax = rt->x; @@ -2141,8 +2143,8 @@ static int sp_drought(castorder * co) */ c = get_curse(r->attribs, ct_find("drought")); if (c) { - c->vigour = _max(c->vigour, power); - c->duration = _max(c->duration, (int)power); + c->vigour = MAX(c->vigour, power); + c->duration = MAX(c->duration, (int)power); } else { double effect = 4.0; @@ -2196,9 +2198,9 @@ static int sp_ironkeeper(castorder * co) /*keeper->age = cast_level + 2; */ setstatus(keeper, ST_AVOID); /* kaempft nicht */ - guard(keeper, GUARD_MINING); + setguard(keeper, true); fset(keeper, UFL_ISNEW); - /* Parteitarnen, damit man nicht sofort wei, wer dahinter steckt */ + /* Parteitarnen, damit man nicht sofort wei�, wer dahinter steckt */ if (rule_stealth_anon()) { fset(keeper, UFL_ANON_FACTION); } @@ -2339,8 +2341,8 @@ static int sp_earthquake(castorder * co) if (burg->size != 0 && !is_cursed(burg->attribs, C_MAGICWALLS, 0)) { /* Magieresistenz */ if (!target_resists_magic(mage, burg, TYP_BUILDING, 0)) { - kaputt = _min(10 * cast_level, burg->size / 4); - kaputt = _max(kaputt, 1); + kaputt = MIN(10 * cast_level, burg->size / 4); + kaputt = MAX(kaputt, 1); burg->size -= kaputt; if (burg->size == 0) { /* TODO: sollten die Insassen nicht Schaden nehmen? */ @@ -2386,7 +2388,6 @@ void patzer_peasantmob(const castorder * co) create_unit(r, f, n, get_race(RC_PEASANT), 0, LOC(f->locale, "angry_mob"), NULL); fset(u, UFL_ISNEW); - /* guard(u, GUARD_ALL); hier zu frueh! Befehl BEWACHE setzten */ addlist(&u->orders, create_order(K_GUARD, lang, NULL)); set_order(&u->thisorder, default_order(lang)); a = a_new(&at_unitdissolve); @@ -2506,7 +2507,7 @@ static int sp_forest_fire(castorder * co) * das Zaubern. Patzer werden warscheinlicher. * Jeder Zauber muss erst gegen den Wiederstand des Fluchs gezaubert * werden und schwaecht dessen Antimagiewiederstand um 1. - * Wirkt _max(Stufe(Magier) - Stufe(Ziel), rand(3)) Wochen + * Wirkt MAX(Stufe(Magier) - Stufe(Ziel), rand(3)) Wochen * Patzer: * Magier wird selbst betroffen * @@ -2534,7 +2535,7 @@ static int sp_fumblecurse(castorder * co) rx = rng_int() % 3; sx = cast_level - effskill(target, SK_MAGIC, 0); - duration = _max(sx, rx) + 1; + duration = MAX(sx, rx) + 1; effect = force / 2; c = create_curse(mage, &target->attribs, ct_find("fumble"), @@ -2577,7 +2578,7 @@ void patzer_fumblecurse(const castorder * co) * * Wirkung: * In einer Wueste, Sumpf oder Gletscher gezaubert kann innerhalb der - * naechsten 6 Runden ein bis 6 Dracheneinheiten bis Groee Wyrm + * naechsten 6 Runden ein bis 6 Dracheneinheiten bis Groe�e Wyrm * entstehen. * * Mit Stufe 12-15 erscheinen Jung- oder normaler Drachen, mit Stufe @@ -2700,8 +2701,8 @@ static int sp_firewall(castorder * co) } else { fd = (wall_data *)b->data.v; - fd->force = (int)_max(fd->force, force / 2 + 0.5); - fd->countdown = _max(fd->countdown, cast_level + 1); + fd->force = (int)MAX(fd->force, force / 2 + 0.5); + fd->countdown = MAX(fd->countdown, cast_level + 1); } /* melden, 1x pro Partei */ @@ -2822,7 +2823,7 @@ static int change_hitpoints(unit * u, int value) hp += value; - /* Jede Person bentigt mindestens 1 HP */ + /* Jede Person ben�tigt mindestens 1 HP */ if (hp < u->number) { if (hp < 0) { /* Einheit tot */ hp = 0; @@ -2850,7 +2851,8 @@ static int dc_age(struct curse *c) while (*up != NULL) { unit *u = *up; int hp; - double damage = c->effect * u->number; + variant dmg = frac_make(u->number, 1); + double damage = c->effect; if (u->number <= 0 || target_resists_magic(mage, u, TYP_UNIT, 0)) { up = &u->next; @@ -2858,7 +2860,9 @@ static int dc_age(struct curse *c) } /* Reduziert durch Magieresistenz */ - damage *= (1.0 - magic_resistance(u)); + dmg = frac_mul(dmg, frac_sub(frac_make(1,1), magic_resistance(u))); + damage *= dmg.sa[0]; + damage /= dmg.sa[1]; hp = change_hitpoints(u, -(int)damage); ADDMSG(&u->faction->msgs, msg_message((hp>0)?"poison_damage":"poison_death", "region unit", r, u)); @@ -2899,6 +2903,8 @@ static int dc_read_compat(struct attrib *a, void *target, gamedata *data) float strength; int rx, ry; + UNUSED_ARG(a); + UNUSED_ARG(target); READ_INT(store, &duration); READ_FLT(store, &strength); READ_INT(store, &var.i); @@ -2943,7 +2949,7 @@ attrib_type at_deathcloud_compat = { * Ruestung wirkt nicht * Patzer: * Magier geraet in den Staub und verliert zufaellige Zahl von HP bis -* auf _max(hp,2) +* auf MAX(hp,2) * Besonderheiten: * Nicht als curse implementiert, was schlecht ist - man kann dadurch * kein dispell machen. Wegen fix unter Zeitdruck erstmal nicht zu @@ -3123,8 +3129,10 @@ static bool chaosgate_valid(const connection * b) } static struct region *chaosgate_move(const connection * b, struct unit *u, -struct region *from, struct region *to, bool routing) + struct region *from, struct region *to, bool routing) { + UNUSED_ARG(from); + UNUSED_ARG(b); if (!routing) { int maxhp = u->hp / 4; if (maxhp < u->number) @@ -3242,8 +3250,7 @@ static int sp_magicboost(castorder * co) } effect = 6; - c = create_curse(mage, &mage->attribs, ct_magicboost, power, 10, effect, 1); - + create_curse(mage, &mage->attribs, ct_magicboost, power, 10, effect, 1); /* one aura boost with 200% aura now: */ effect = 200; c = create_curse(mage, &mage->attribs, ct_auraboost, power, 4, effect, 1); @@ -3367,7 +3374,7 @@ static int sp_summonundead(castorder * co) return 0; } - undead = _min(deathcount(r), 2 + lovar(force)); + undead = MIN(deathcount(r), 2 + lovar(force)); if (cast_level <= 8) { race = get_race(RC_SKELETON); @@ -3415,7 +3422,7 @@ static int sp_auraleak(castorder * co) int cast_level = co->level; message *msg; - lost = _min(0.95, cast_level * 0.05); + lost = MIN(0.95, cast_level * 0.05); for (u = r->units; u; u = u->next) { if (is_mage(u)) { @@ -3746,7 +3753,7 @@ static int sp_rallypeasantmob(castorder * co) rsetpeasants(r, rpeasants(r) + u->number); rsetmoney(r, rmoney(r) + get_money(u)); set_money(u, 0); - setguard(u, GUARD_NONE); + setguard(u, false); set_number(u, 0); erfolg = cast_level; } @@ -3769,7 +3776,7 @@ static int sp_rallypeasantmob(castorder * co) * Gebiet: Cerddor * Wirkung: * Wiegelt 60% bis 90% der Bauern einer Region auf. Bauern werden ein - * groer Mob, der zur Monsterpartei gehoert und die Region bewacht. + * gro�er Mob, der zur Monsterpartei gehoert und die Region bewacht. * Regionssilber sollte auch nicht durch Unterhaltung gewonnen werden * koennen. * @@ -3798,8 +3805,8 @@ static int sp_raisepeasantmob(castorder * co) anteil = 6 + (rng_int() % 4); n = rpeasants(r) * anteil / 10; - n = _max(0, n); - n = _min(n, rpeasants(r)); + n = MAX(0, n); + n = MIN(n, rpeasants(r)); if (n <= 0) { report_failure(mage, co->order); @@ -3813,7 +3820,7 @@ static int sp_raisepeasantmob(castorder * co) create_unit(r, monsters, n, get_race(RC_PEASANT), 0, LOC(monsters->locale, "furious_mob"), NULL); fset(u, UFL_ISNEW); - guard(u, GUARD_ALL); + setguard(u, true); a = a_new(&at_unitdissolve); a->data.ca[0] = 1; /* An rpeasants(r). */ a->data.ca[1] = 15; /* 15% */ @@ -4030,21 +4037,21 @@ static int sp_recruit(castorder * co) return 0; } /* Immer noch zuviel auf niedrigen Stufen. Deshalb die Rekrutierungskosten - * mit einfliessen lassen und dafuer den Exponenten etwas groeer. + * mit einfliessen lassen und dafuer den Exponenten etwas groe�er. * Wenn die Rekrutierungskosten deutlich hoeher sind als der Faktor, * ist das Verhaeltniss von ausgegebene Aura pro Bauer bei Stufe 2 * ein mehrfaches von Stufe 1, denn in beiden Faellen gibt es nur 1 * Bauer, nur die Kosten steigen. */ n = (pow(force, 1.6) * 100) / f->race->recruitcost; - if (rc->recruit_multi != 0) { + if (rc->recruit_multi > 0) { double multp = (double)maxp / rc->recruit_multi; - n = _min(multp, n); - n = _max(n, 1); + n = MIN(multp, n); + n = MAX(n, 1); rsetpeasants(r, maxp - (int)(n * rc->recruit_multi)); } else { - n = _min(maxp, n); - n = _max(n, 1); + n = MIN(maxp, n); + n = MAX(n, 1); rsetpeasants(r, maxp - (int)n); } @@ -4061,7 +4068,7 @@ static int sp_recruit(castorder * co) } /* ------------------------------------------------------------- */ -/* Name: Wanderprediger - Groe Anwerbung +/* Name: Wanderprediger - Gro�e Anwerbung * Stufe: 14 * Gebiet: Cerddor * Wirkung: @@ -4089,13 +4096,13 @@ static int sp_bigrecruit(castorder * co) n = (int)force + lovar((force * force * 1000) / (float)f->race->recruitcost); if (f->race == get_race(RC_ORC)) { - n = _min(2 * maxp, n); - n = _max(n, 1); + n = MIN(2 * maxp, n); + n = MAX(n, 1); rsetpeasants(r, maxp - (n + 1) / 2); } else { - n = _min(maxp, n); - n = _max(n, 1); + n = MIN(maxp, n); + n = MAX(n, 1); rsetpeasants(r, maxp - n); } @@ -4117,8 +4124,8 @@ static int sp_bigrecruit(castorder * co) * Gebiet: Cerddor * Wirkung: * Erliegt die Einheit dem Zauber, so wird sie dem Magier alles - * erzaehlen, was sie ueber die gefragte Region wei. Ist in der Region - * niemand ihrer Partei, so wei sie nichts zu berichten. Auch kann + * erzaehlen, was sie ueber die gefragte Region wei�. Ist in der Region + * niemand ihrer Partei, so wei� sie nichts zu berichten. Auch kann * sie nur das erzaehlen, was sie selber sehen koennte. * Flags: * (UNITSPELL | TESTCANSEE) @@ -4168,7 +4175,7 @@ static int sp_pump(castorder * co) } u = - create_unit(rt, mage->faction, RS_FARVISION, get_race(RC_SPELL), 0, + create_unit(rt, mage->faction, 1, get_race(RC_SPELL), 0, "spell/pump", NULL); u->age = 2; set_level(u, SK_PERCEPTION, effskill(target, SK_PERCEPTION, 0)); @@ -4181,10 +4188,10 @@ static int sp_pump(castorder * co) * Stufe: 6 * Gebiet: Cerddor * Wirkung: - * Betoert eine Einheit, so das sie ihm den groeten Teil ihres Bargelds + * Betoert eine Einheit, so das sie ihm den groe�ten Teil ihres Bargelds * und 50% ihres Besitzes schenkt. Sie behaelt jedoch immer soviel, wie * sie zum ueberleben braucht. Wirkt gegen Magieresistenz. - * _min(Stufe*1000$, u->money - maintenace) + * MIN(Stufe*1000$, u->money - maintenace) * Von jedem Item wird 50% abgerundet ermittelt und uebergeben. Dazu * kommt Itemzahl%2 mit 50% chance * @@ -4195,7 +4202,7 @@ static int sp_seduce(castorder * co) { const resource_type *rsilver = get_resourcetype(R_SILVER); unit *target; - item **itmp, *items = 0;; + item **itmp, *items = 0; unit *mage = co->magician.u; spellparameter *pa = co->par; int cast_level = co->level; @@ -4221,8 +4228,8 @@ static int sp_seduce(castorder * co) int loot; if (itm->type->rtype == rsilver) { loot = - _min(cast_level * 1000, get_money(target) - (maintenance_cost(target))); - loot = _max(loot, 0); + MIN(cast_level * 1000, get_money(target) - (maintenance_cost(target))); + loot = MAX(loot, 0); } else { loot = itm->number / 2; @@ -4230,7 +4237,7 @@ static int sp_seduce(castorder * co) loot += rng_int() % 2; } if (loot > 0) { - loot = _min(loot, (int)(force * 5)); + loot = MIN(loot, (int)(force * 5)); } } if (loot > 0) { @@ -4338,7 +4345,7 @@ static int sp_headache(castorder * co) if (target->number == 0 || pa->param[0]->flag == TARGET_NOTFOUND) return 0; - /* finde das groete Talent: */ + /* finde das groe�te Talent: */ for (i = 0; i != target->skill_size; ++i) { skill *sv = target->skills + i; if (smax == NULL || skill_compare(sv, smax) > 0) { @@ -4347,7 +4354,7 @@ static int sp_headache(castorder * co) } if (smax != NULL) { /* wirkt auf maximal 10 Personen */ - unsigned int change = _min(10, target->number) * (rng_uint() % 2 + 1) / target->number; + unsigned int change = MIN(10, target->number) * (rng_uint() % 2 + 1) / target->number; reduce_skill(target, smax, change); } set_order(&target->thisorder, NULL); @@ -4391,7 +4398,7 @@ static int sp_raisepeasants(castorder * co) "error_nopeasants", "")); return 0; } - bauern = _min(rpeasants(r), (int)(power * 250)); + bauern = MIN(rpeasants(r), (int)(power * 250)); rsetpeasants(r, rpeasants(r) - bauern); u2 = @@ -4474,7 +4481,7 @@ int sp_puttorest(castorder * co) message *seen = msg_message("puttorest", "mage", mage); message *unseen = msg_message("puttorest", "mage", NULL); - laid_to_rest = _max(laid_to_rest, dead); + laid_to_rest = MAX(laid_to_rest, dead); deathcounts(r, -laid_to_rest); @@ -4484,7 +4491,7 @@ int sp_puttorest(castorder * co) return co->level; } -/* Name: Traumschloechen +/* Name: Traumschloe�chen * Stufe: 3 * Kategorie: Region, Gebaeude, positiv * Gebiet: Illaun @@ -4519,7 +4526,7 @@ int sp_icastle(castorder * co) b = new_building(bt_illusion, r, mage->faction->locale); - /* Groee festlegen. */ + /* Groe�e festlegen. */ if (type == bt_illusion) { b->size = (rng_int() % (int)((power * power) + 1) * 10); } @@ -4697,7 +4704,7 @@ int sp_baddreams(castorder * co) * Kategorie: * Wirkung: * Dieser Zauber ermoeglicht es dem Traeumer, den Schlaf aller aliierten - * Einheiten in der Region so zu beeinflussen, da sie fuer einige Zeit + * Einheiten in der Region so zu beeinflussen, da� sie fuer einige Zeit * einen Bonus von 1 Talentstufe in allen Talenten * bekommen. Der Zauber wirkt erst im Folgemonat. * Flags: @@ -4715,19 +4722,18 @@ static int sp_gbdreams(castorder * co, const char *curse_name, int effect) int cast_level = co->level; double power = co->force; region *r = co_get_region(co); - curse *c; /* wirkt erst in der Folgerunde, soll mindestens eine Runde wirken, * also duration+2 */ - duration = (int)_max(1, power / 2); /* Stufe 1 macht sonst mist */ + duration = (int)MAX(1, power / 2); /* Stufe 1 macht sonst mist */ duration = 2 + rng_int() % duration; /* Nichts machen als ein entsprechendes Attribut in die Region legen. */ - c = create_curse(mage, &r->attribs, ct_find(curse_name), power, duration, effect, 0); - + create_curse(mage, &r->attribs, ct_find(curse_name), power, duration, effect, 0); + /* Erfolg melden */ ADDMSG(&mage->faction->msgs, msg_message("regionmagic_effect", - "unit region command", c->magician, mage->region, co->order)); + "unit region command", mage, mage->region, co->order)); return cast_level; } @@ -4758,7 +4764,7 @@ int sp_clonecopy(castorder * co) return 0; } - _snprintf(name, sizeof(name), (const char *)LOC(mage->faction->locale, + slprintf(name, sizeof(name), (const char *)LOC(mage->faction->locale, "clone_of"), unitname(mage)); clone = create_unit(target_region, mage->faction, 1, get_race(RC_CLONE), 0, name, @@ -4812,7 +4818,7 @@ int sp_dreamreading(castorder * co) } u2 = - create_unit(u->region, mage->faction, RS_FARVISION, get_race(RC_SPELL), 0, + create_unit(u->region, mage->faction, 1, get_race(RC_SPELL), 0, "spell/dreamreading", NULL); set_number(u2, 1); u2->age = 2; /* Nur fuer diese Runde. */ @@ -4842,7 +4848,6 @@ int sp_sweetdreams(castorder * co) /* Schleife ueber alle angegebenen Einheiten */ for (n = 0; n < pa->length; n++) { - curse *c; unit *u; double effect; message *msg; @@ -4861,14 +4866,14 @@ int sp_sweetdreams(castorder * co) cmistake(mage, co->order, 40, MSG_EVENT); continue; } - men = _min(opfer, u->number); + men = MIN(opfer, u->number); opfer -= men; /* Nichts machen als ein entsprechendes Attribut an die Einheit legen. */ effect = 0.05f; - c = create_curse(mage, &u->attribs, ct_find("orcish"), power, duration, effect, men); + create_curse(mage, &u->attribs, ct_find("orcish"), power, duration, effect, men); - msg = msg_message("sp_sweetdreams_effect", "mage unit region", c->magician, u, r); + msg = msg_message("sp_sweetdreams_effect", "mage unit region", mage, u, r); r_addmessage(r, mage->faction, msg); if (u->faction != mage->faction) { r_addmessage(r, u->faction, msg); @@ -4887,13 +4892,12 @@ int sp_disturbingdreams(castorder * co) double power = co->force; int duration = 1 + (int)(power / 6); double effect; - curse *c; effect = 10; - c = create_curse(mage, &r->attribs, ct_find("badlearn"), power, duration, effect, 0); + create_curse(mage, &r->attribs, ct_find("badlearn"), power, duration, effect, 0); ADDMSG(&mage->faction->msgs, msg_message("sp_disturbingdreams_effect", - "mage region", c->magician, r)); + "mage region", mage, r)); return cast_level; } @@ -4975,7 +4979,7 @@ int sp_itemcloak(castorder * co) spellparameter *pa = co->par; int cast_level = co->level; double power = co->force; - int duration = (int)_max(2.0, power + 1); /* works in the report, and ageing this round would kill it if it's <=1 */ + int duration = (int)MAX(2.0, power + 1); /* works in the report, and ageing this round would kill it if it's <=1 */ /* wenn kein Ziel gefunden, Zauber abbrechen */ if (pa->param[0]->flag == TARGET_NOTFOUND) @@ -5033,7 +5037,7 @@ int sp_resist_magic_bonus(castorder * co) u = pa->param[n]->data.u; - m = _min(u->number, victims); + m = MIN(u->number, victims); victims -= m; create_curse(mage, &u->attribs, ct_find("magicresistance"), @@ -5049,8 +5053,8 @@ int sp_resist_magic_bonus(castorder * co) msg_release(msg); } - cast_level = _min(cast_level, (int)(cast_level * (victims + 4) / maxvictims)); - return _max(cast_level, 1); + cast_level = MIN(cast_level, (int)(cast_level * (victims + 4) / maxvictims)); + return MAX(cast_level, 1); } /** spell 'Astraler Weg'. @@ -5662,7 +5666,7 @@ int sp_showastral(castorder * co) free_regionlist(rl); return cast_level; - unused_arg(co); + UNUSED_ARG(co); return 0; } #endif @@ -5691,7 +5695,7 @@ int sp_viewreality(castorder * co) region *rt = rl2->data; if (!is_cursed(rt->attribs, C_ASTRALBLOCK, 0)) { u = - create_unit(rt, mage->faction, RS_FARVISION, get_race(RC_SPELL), 0, + create_unit(rt, mage->faction, 1, get_race(RC_SPELL), 0, "spell/viewreality", NULL); set_level(u, SK_PERCEPTION, co->level / 2); u->age = 2; @@ -5913,7 +5917,7 @@ int sp_permtransfer(castorder * co) return 0; } - aura = _min(get_spellpoints(mage) - spellcost(mage, sp), aura); + aura = MIN(get_spellpoints(mage) - spellcost(mage, sp), aura); change_maxspellpoints(mage, -aura); change_spellpoints(mage, -aura); @@ -6222,7 +6226,7 @@ int sp_speed2(castorder * co) spellparameter *pa = co->par; maxmen = 2 * cast_level * cast_level; - dur = _max(1, cast_level / 2); + dur = MAX(1, cast_level / 2); for (n = 0; n < pa->length; n++) { double effect; @@ -6236,7 +6240,7 @@ int sp_speed2(castorder * co) u = pa->param[n]->data.u; - men = _min(maxmen, u->number); + men = MIN(maxmen, u->number); effect = 2; create_curse(mage, &u->attribs, ct_find("speed"), force, dur, effect, men); maxmen -= men; @@ -6247,7 +6251,7 @@ int sp_speed2(castorder * co) "unit region amount", mage, mage->region, used)); /* Effektiv benoetigten cast_level (mindestens 1) zurueckgeben */ used = (int)sqrt(used / 2); - return _max(1, used); + return MAX(1, used); } /* ------------------------------------------------------------- */ @@ -6296,21 +6300,21 @@ int sp_q_antimagie(castorder * co) { unit *u = pa->param[0]->data.u; ap = &u->attribs; - ts = unitid(u); + ts = itoa36(u->no); break; } case SPP_BUILDING: { building *b = pa->param[0]->data.b; ap = &b->attribs; - ts = buildingid(b); + ts = itoa36(b->no); break; } case SPP_SHIP: { ship *sh = pa->param[0]->data.sh; ap = &sh->attribs; - ts = shipid(sh); + ts = itoa36(sh->no); break; } default: @@ -6330,7 +6334,7 @@ int sp_q_antimagie(castorder * co) ADDMSG(&mage->faction->msgs, msg_message("destroy_magic_noeffect", "unit region command", mage, mage->region, co->order)); } - return _max(succ, 1); + return MAX(succ, 1); } /* ------------------------------------------------------------- */ @@ -6389,21 +6393,21 @@ int sp_break_curse(castorder * co) { unit *u = pa->param[0]->data.u; ap = &u->attribs; - ts = unitid(u); + ts = itoa36(u->no); break; } case SPP_BUILDING: { building *b = pa->param[0]->data.b; ap = &b->attribs; - ts = buildingid(b); + ts = itoa36(b->no); break; } case SPP_SHIP: { ship *sh = pa->param[0]->data.sh; ap = &sh->attribs; - ts = shipid(sh); + ts = itoa36(sh->no); break; } default: @@ -6443,6 +6447,7 @@ int sp_break_curse(castorder * co) /* ------------------------------------------------------------- */ int sp_becomewyrm(castorder * co) { + UNUSED_ARG(co); return 0; } @@ -6599,7 +6604,6 @@ static spelldata spell_functions[] = { { "powerful_dragonbreath", sp_dragonodem, 0 }, { "drain_skills", sp_dragonodem, 0 }, { "aura_of_fear", sp_flee, 0 }, - { "shadowcall", sp_shadowcall, 0 }, { "immolation", sp_immolation, 0 }, { "firestorm", sp_immolation, 0 }, { "coldfront", sp_immolation, 0 }, @@ -6723,7 +6727,6 @@ void register_spells(void) { register_borders(); - at_register(&at_wdwpyramid); at_register(&at_deathcloud_compat); /* init_firewall(); */ diff --git a/src/spells.test.c b/src/spells.test.c index 3c773d489..07a980e03 100644 --- a/src/spells.test.c +++ b/src/spells.test.c @@ -25,8 +25,9 @@ static void test_good_dreams(CuTest *tc) { unit *u1, *u2; int level; castorder co; - - test_cleanup(); + curse *curse; + + test_setup(); test_create_world(); r = findregion(0, 0); f1 = test_create_faction(0); @@ -38,7 +39,7 @@ static void test_good_dreams(CuTest *tc) { level = sp_gooddreams(&co); CuAssertIntEquals(tc, 10, level); - curse *curse = get_curse(r->attribs, ct_find("gbdream")); + curse = get_curse(r->attribs, ct_find("gbdream")); CuAssertTrue(tc, curse && curse->duration > 1); CuAssertTrue(tc, curse->effect == 1); @@ -81,8 +82,9 @@ static void test_bad_dreams(CuTest *tc) { unit *u1, *u2; int level; castorder co; - - test_cleanup(); + curse *curse; + + test_setup(); test_create_world(); r = findregion(0, 0); f1 = test_create_faction(0); @@ -94,7 +96,7 @@ static void test_bad_dreams(CuTest *tc) { level = sp_baddreams(&co); CuAssertIntEquals(tc, 10, level); - curse *curse = get_curse(r->attribs, ct_find("gbdream")); + curse = get_curse(r->attribs, ct_find("gbdream")); CuAssertTrue(tc, curse && curse->duration > 1); CuAssertTrue(tc, curse->effect == -1); diff --git a/src/spells/borders.c b/src/spells/borders.c index 474d37796..00019e92c 100644 --- a/src/spells/borders.c +++ b/src/spells/borders.c @@ -8,7 +8,6 @@ #include #include #include -#include #include #include @@ -207,7 +206,7 @@ struct region *from, struct region *to, bool routing) wall_data *fd = (wall_data *)b->data.v; if (!routing && fd->active) { int hp = dice(3, fd->force) * u->number; - hp = _min(u->hp, hp); + hp = MIN(u->hp, hp); u->hp -= hp; if (u->hp) { ADDMSG(&u->faction->msgs, msg_message("firewall_damage", @@ -228,9 +227,9 @@ static const char *b_namefirewall(const connection * b, const region * r, const faction * f, int gflags) { const char *bname; - unused_arg(f); - unused_arg(r); - unused_arg(b); + UNUSED_ARG(f); + UNUSED_ARG(r); + UNUSED_ARG(b); if (gflags & GF_ARTICLE) bname = "a_firewall"; else diff --git a/src/spells/borders.h b/src/spells/borders.h index 31823df94..b14661b9f 100644 --- a/src/spells/borders.h +++ b/src/spells/borders.h @@ -1,5 +1,8 @@ #ifndef H_KRNL_CURSES #define H_KRNL_CURSES + +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/src/spells/buildingcurse.c b/src/spells/buildingcurse.c index d3b5ddf36..158383fd2 100644 --- a/src/spells/buildingcurse.c +++ b/src/spells/buildingcurse.c @@ -12,7 +12,6 @@ */ #include -#include #include "buildingcurse.h" /* kernel includes */ @@ -37,7 +36,7 @@ message *cinfo_building(const void *obj, objtype_t typ, const curse * c, int self) { const building *b = (const building *)obj; - unused_arg(typ); + UNUSED_ARG(typ); assert(typ == TYP_BUILDING); assert(obj); assert(c); diff --git a/src/spells/combatspells.c b/src/spells/combatspells.c index bcbbb1b52..37191d177 100644 --- a/src/spells/combatspells.c +++ b/src/spells/combatspells.c @@ -10,7 +10,6 @@ without prior permission by the authors of Eressea. */ #include -#include #include "combatspells.h" /* kernel includes */ @@ -39,7 +38,7 @@ #include #include -#include +#include /* libc includes */ #include @@ -48,8 +47,9 @@ #define EFFECT_HEALING_SPELL 5 -// Some spells with a fixed, known ID (in XML). -// TODO: this method of identifying spells is error-prone, do not use it for new spells. +/* Some spells with a fixed, known ID (in XML). + * TODO: this method of identifying spells is error-prone, + * do not use it for new spells. */ enum { SPL_FIREBALL = 4, SPL_HAGEL = 5, @@ -81,7 +81,7 @@ static const char *spell_damage(int sp) { switch (sp) { case 0: - /* meist tdlich 20-65 HP */ + /* meist t�dlich 20-65 HP */ return "5d10+15"; case 1: /* sehr variabel 4-48 HP */ @@ -90,7 +90,7 @@ static const char *spell_damage(int sp) /* leicht verwundet 4-18 HP */ return "2d8+2"; case 3: - /* fast immer tdlich 30-50 HP */ + /* fast immer t�dlich 30-50 HP */ return "5d5+25"; case 4: /* verwundet 11-26 HP */ @@ -296,15 +296,15 @@ int sp_stun(struct castorder * co) /** randomly shuffle an array * for correctness, see Donald E. Knuth, The Art of Computer Programming */ -static void scramble_fighters(quicklist * ql) +static void scramble_fighters(selist * ql) { - int qi, qlen = ql_length(ql); + int qi, qlen = selist_length(ql); for (qi = 0; qi != qlen; ++qi) { int qj = qi + (rng_int() % (qlen - qi)); - void *a = ql_get(ql, qi); - void *b = ql_replace(ql, qj, a); - ql_replace(ql, qi, b); + void *a = selist_get(ql, qi); + void *b = selist_replace(ql, qj, a); + selist_replace(ql, qi, b); } } @@ -315,7 +315,7 @@ int sp_combatrosthauch(struct castorder * co) int level = co->level; double power = co->force; battle *b = fi->side->battle; - quicklist *ql, *fgs; + selist *ql, *fgs; int force = lovar(power * 15); int qi, k = 0; @@ -330,22 +330,22 @@ int sp_combatrosthauch(struct castorder * co) fgs = fighters(b, fi->side, FIGHT_ROW, BEHIND_ROW - 1, FS_ENEMY); scramble_fighters(fgs); - for (qi = 0, ql = fgs; ql; ql_advance(&ql, &qi, 1)) { - fighter *df = (fighter *)ql_get(ql, qi); + for (qi = 0, ql = fgs; ql; selist_advance(&ql, &qi, 1)) { + fighter *df = (fighter *)selist_get(ql, qi); if (df->alive == 0) continue; if (force <= 0) break; - /* da n _min(force, x), sollte force maximal auf 0 sinken */ + /* da n MIN(force, x), sollte force maximal auf 0 sinken */ assert(force >= 0); if (df->weapons) { int w; for (w = 0; df->weapons[w].type != NULL; ++w) { weapon *wp = df->weapons; - int n = _min(force, wp->used); + int n = MIN(force, wp->used); if (n) { requirement *mat = wp->type->itype->construction->materials; bool iron = false; @@ -379,14 +379,14 @@ int sp_combatrosthauch(struct castorder * co) } } } - ql_free(fgs); + selist_free(fgs); if (k == 0) { - /* keine Waffen mehr da, die zerstrt werden knnten */ + /* keine Waffen mehr da, die zerst�rt werden k�nnten */ message *msg = msg_message("rust_effect_1", "mage", fi->unit); message_all(b, msg); msg_release(msg); - fi->magic = 0; /* kmpft nichtmagisch weiter */ + fi->magic = 0; /* k�mpft nichtmagisch weiter */ level = 0; } else { @@ -453,7 +453,7 @@ int sp_speed(struct castorder * co) allies = count_allies(fi->side, FIGHT_ROW, BEHIND_ROW, SELECT_ADVANCE, ALLY_ANY); - /* maximal 2*allies Versuche ein Opfer zu finden, ansonsten bestnde + /* maximal 2*allies Versuche ein Opfer zu finden, ansonsten best�nde * die Gefahr eine Endlosschleife*/ allies *= 2; @@ -546,7 +546,7 @@ int sp_mindblast_temp(struct castorder * co) assert(dt.fighter); du = dt.fighter->unit; - if (fval(du, UFL_MARK)) { + if (du->flags & UFL_MARK) { /* not this one again */ continue; } @@ -564,7 +564,7 @@ int sp_mindblast_temp(struct castorder * co) } force -= du->number; } - fset(du, UFL_MARK); + du->flags |= UFL_MARK; reset = 1; enemies -= du->number; } @@ -572,7 +572,7 @@ int sp_mindblast_temp(struct castorder * co) if (reset) { unit *u; for (u = b->region->units; u; u = u->next) { - freset(u, UFL_MARK); + u->flags &= ~UFL_MARK; } } @@ -612,7 +612,7 @@ int sp_mindblast(struct castorder * co) assert(dt.fighter); du = dt.fighter->unit; - if (fval(du, UFL_MARK)) { + if (du->flags & UFL_MARK) { /* not this one again */ continue; } @@ -640,7 +640,7 @@ int sp_mindblast(struct castorder * co) else { /* only works against humanoids, don't try others. but do remove them * from 'force' once or we may never terminate. */ - fset(du, UFL_MARK); + du->flags |= UFL_MARK; reset = 1; } enemies -= du->number; @@ -649,7 +649,7 @@ int sp_mindblast(struct castorder * co) if (reset) { unit *u; for (u = b->region->units; u; u = u->next) { - freset(u, UFL_MARK); + u->flags &= ~UFL_MARK; } } @@ -721,7 +721,7 @@ int sp_immolation(struct castorder * co) troop at; int force, qi, killed = 0; const char *damage; - quicklist *fgs, *ql; + selist *fgs, *ql; message *m; /* 2d4 HP */ @@ -741,8 +741,8 @@ int sp_immolation(struct castorder * co) at.index = 0; fgs = fighters(b, fi->side, FIGHT_ROW, AVOID_ROW, FS_ENEMY); - for (qi = 0, ql = fgs; ql; ql_advance(&ql, &qi, 1)) { - fighter *df = (fighter *)ql_get(ql, qi); + for (qi = 0, ql = fgs; ql; selist_advance(&ql, &qi, 1)) { + fighter *df = (fighter *)selist_get(ql, qi); int n = df->alive - df->removed; troop dt; @@ -756,7 +756,7 @@ int sp_immolation(struct castorder * co) if (force == 0) break; } - ql_free(fgs); + selist_free(fgs); m = msg_message("battle::combatspell", "mage spell killed", fi->unit, sp, @@ -816,42 +816,6 @@ int sp_drainodem(fighter * fi, int level, double power, spell * sp) /* ------------------------------------------------------------- */ /* PRECOMBAT */ -int sp_shadowcall(struct castorder * co) -{ - fighter * fi = co->magician.fig; - int level = co->level; - double power = co->force; - battle *b = fi->side->battle; - region *r = b->region; - unit *mage = fi->unit; - attrib *a; - int force = (int)(get_force(power, 3) / 2); - unit *u; - const char *races[3] = { "shadowbat", "nightmare", "vampunicorn" }; - const race *rc = rc_find(races[rng_int() % 3]); - message *msg; - - u = create_unit(r, mage->faction, force, rc, 0, NULL, mage); - setstatus(u, ST_FIGHT); - - set_level(u, SK_WEAPONLESS, (int)(power / 2)); - set_level(u, SK_STAMINA, (int)(power / 2)); - u->hp = u->number * unit_max_hp(u); - - a = a_new(&at_unitdissolve); - a->data.ca[0] = 0; - a->data.ca[1] = 100; - a_add(&u->attribs, a); - - make_fighter(b, u, fi->side, is_attacker(fi)); - msg = - msg_message("sp_shadowcall_effect", "mage amount race", mage, u->number, - u_race(u)); - message_all(b, msg); - msg_release(msg); - return level; -} - static fighter *summon_allies(const fighter *fi, const race *rc, int number) { attrib *a; unit *mage = fi->unit; @@ -866,8 +830,8 @@ static fighter *summon_allies(const fighter *fi, const race *rc, int number) { u->hp = u->number * unit_max_hp(u); - if (fval(mage, UFL_ANON_FACTION)) { - fset(u, UFL_ANON_FACTION); + if (mage->flags & UFL_ANON_FACTION) { + u->flags |= UFL_ANON_FACTION; } a = a_new(&at_unitdissolve); @@ -922,7 +886,7 @@ int sp_shadowknights(struct castorder * co) region *r = b->region; unit *mage = fi->unit; attrib *a; - int force = _max(1, (int)get_force(power, 3)); + int force = MAX(1, (int)get_force(power, 3)); message *msg; u = @@ -932,8 +896,8 @@ int sp_shadowknights(struct castorder * co) u->hp = u->number * unit_max_hp(u); - if (fval(mage, UFL_ANON_FACTION)) { - fset(u, UFL_ANON_FACTION); + if (mage->flags & UFL_ANON_FACTION) { + u->flags |= UFL_ANON_FACTION; } a = a_new(&at_unitdissolve); @@ -988,7 +952,7 @@ int sp_chaosrow(struct castorder * co) const spell * sp = co->sp; battle *b = fi->side->battle; unit *mage = fi->unit; - quicklist *fgs, *ql; + selist *fgs, *ql; message *m; const char *mtype; int qi, k = 0; @@ -1008,15 +972,15 @@ int sp_chaosrow(struct castorder * co) fgs = fighters(b, fi->side, FIGHT_ROW, NUMROWS, FS_ENEMY); scramble_fighters(fgs); - for (qi = 0, ql = fgs; ql; ql_advance(&ql, &qi, 1)) { - fighter *df = (fighter *)ql_get(ql, qi); + for (qi = 0, ql = fgs; ql; selist_advance(&ql, &qi, 1)) { + fighter *df = (fighter *)selist_get(ql, qi); int n = df->unit->number; if (df->alive == 0) continue; if (power <= 0.0) break; - /* force sollte wegen des _max(0,x) nicht unter 0 fallen knnen */ + /* force sollte wegen des MAX(0,x) nicht unter 0 fallen k�nnen */ if (is_magic_resistant(mage, df->unit, 0)) continue; @@ -1051,9 +1015,9 @@ int sp_chaosrow(struct castorder * co) } k += df->alive; } - power = _max(0, power - n); + power = MAX(0, power - n); } - ql_free(fgs); + selist_free(fgs); if (sp->id == SPL_CHAOSROW) { mtype = (k > 0) ? "sp_chaosrow_effect_1" : "sp_chaosrow_effect_0"; @@ -1068,7 +1032,7 @@ int sp_chaosrow(struct castorder * co) } /* Gesang der Furcht (Kampfzauber) */ -/* Panik (Prkampfzauber) */ +/* Panik (Pr�kampfzauber) */ int sp_flee(struct castorder * co) { @@ -1078,7 +1042,7 @@ int sp_flee(struct castorder * co) const spell * sp = co->sp; battle *b = fi->side->battle; unit *mage = fi->unit; - quicklist *fgs, *ql; + selist *fgs, *ql; int force, n, qi; int panik = 0; message *msg; @@ -1107,20 +1071,20 @@ int sp_flee(struct castorder * co) fgs = fighters(b, fi->side, FIGHT_ROW, AVOID_ROW, FS_ENEMY); scramble_fighters(fgs); - for (qi = 0, ql = fgs; ql; ql_advance(&ql, &qi, 1)) { - fighter *df = (fighter *)ql_get(ql, qi); + for (qi = 0, ql = fgs; ql; selist_advance(&ql, &qi, 1)) { + fighter *df = (fighter *)selist_get(ql, qi); for (n = 0; n != df->alive; ++n) { if (force < 0) break; - if (df->person[n].flags & FL_PANICED) { /* bei SPL_SONG_OF_FEAR mglich */ + if (df->person[n].flags & FL_PANICED) { /* bei SPL_SONG_OF_FEAR m�glich */ df->person[n].attack -= 1; --force; ++panik; } else if (!(df->person[n].flags & FL_COURAGE) - || !fval(u_race(df->unit), RCF_UNDEAD)) { + || !(u_race(df->unit)->flags & RCF_UNDEAD)) { if (!is_magic_resistant(mage, df->unit, 0)) { df->person[n].flags |= FL_PANICED; ++panik; @@ -1129,7 +1093,7 @@ int sp_flee(struct castorder * co) } } } - ql_free(fgs); + selist_free(fgs); msg = msg_message("sp_flee_effect_1", "mage spell amount", mage, sp, panik); message_all(b, msg); @@ -1155,17 +1119,17 @@ int sp_hero(struct castorder * co) switch (sp->id) { case SPL_HERO: df_bonus = (int)(power / 5); - force = _max(1, lovar(get_force(power, 4))); + force = MAX(1, lovar(get_force(power, 4))); break; default: df_bonus = 1; - force = _max(1, (int)power); + force = MAX(1, (int)power); } allies = count_allies(fi->side, FIGHT_ROW, BEHIND_ROW, SELECT_ADVANCE, ALLY_ANY); - /* maximal 2*allies Versuche ein Opfer zu finden, ansonsten bestnde + /* maximal 2*allies Versuche ein Opfer zu finden, ansonsten best�nde * die Gefahr eine Endlosschleife*/ allies *= 2; @@ -1209,7 +1173,7 @@ int sp_berserk(struct castorder * co) switch (sp->id) { case SPL_BERSERK: case SPL_BLOODTHIRST: - at_bonus = _max(1, level / 3); + at_bonus = MAX(1, level / 3); df_malus = 2; force = (int)get_force(power, 2); break; @@ -1222,7 +1186,7 @@ int sp_berserk(struct castorder * co) allies = count_allies(fi->side, FIGHT_ROW, BEHIND_ROW - 1, SELECT_ADVANCE, ALLY_ANY); - /* maximal 2*allies Versuche ein Opfer zu finden, ansonsten bestnde + /* maximal 2*allies Versuche ein Opfer zu finden, ansonsten best�nde * die Gefahr eine Endlosschleife*/ allies *= 2; @@ -1265,7 +1229,7 @@ int sp_frighten(struct castorder * co) int targets = 0; message *m; - at_malus = _max(1, level - 4); + at_malus = MAX(1, level - 4); df_malus = 2; force = (int)get_force(power, 2); @@ -1419,7 +1383,7 @@ int sp_reeling_arrows(struct castorder * co) } /* Magier weicht dem Kampf aus. Wenn er sich bewegen kann, zieht er in - * eine Nachbarregion, wobei ein NACH bercksichtigt wird. Ansonsten + * eine Nachbarregion, wobei ein NACH ber�cksichtigt wird. Ansonsten * bleibt er stehen und nimmt nicht weiter am Kampf teil. */ int sp_denyattack(struct castorder * co) { @@ -1432,17 +1396,16 @@ int sp_denyattack(struct castorder * co) region *r = b->region; message *m; - /* Fliehende Einheiten verlassen auf jeden Fall Gebude und Schiffe. */ - if (!fval(r->terrain, SEA_REGION)) { + /* Fliehende Einheiten verlassen auf jeden Fall Geb�ude und Schiffe. */ + if (!(r->terrain->flags & SEA_REGION)) { leave(mage, false); } /* und bewachen nicht */ - setguard(mage, GUARD_NONE); + setguard(mage, false); /* irgendwie den langen befehl sperren */ - /* fset(fi, FIG_ATTACKED); */ - /* wir tun so, als wre die Person geflohen */ - fset(fi, FIG_NOLOOT); + /* wir tun so, als w�re die Person geflohen */ + fi->flags |= FIG_NOLOOT; fi->run.hp = mage->hp; fi->run.number = mage->number; /* fighter leeren */ @@ -1459,7 +1422,7 @@ static void do_meffect(fighter * af, int typ, int effect, int duration) { battle *b = af->side->battle; meffect *me = (meffect *)malloc(sizeof(struct meffect)); - ql_push(&b->meffects, me); + selist_push(&b->meffects, me); me->magician = af; me->typ = typ; me->effect = effect; @@ -1480,7 +1443,7 @@ int sp_armorshield(struct castorder * co) message_all(b, m); msg_release(m); - /* gibt Rstung +effect fr duration Treffer */ + /* gibt R�stung +effect f�r duration Treffer */ switch (sp->id) { case SPL_ARMORSHIELD: @@ -1539,7 +1502,7 @@ int sp_fumbleshield(struct castorder * co) message_all(b, m); msg_release(m); - /* der erste Zauber schlgt mit 100% fehl */ + /* der erste Zauber schl�gt mit 100% fehl */ switch (sp->id) { case SPL_DRAIG_FUMBLESHIELD: @@ -1547,7 +1510,7 @@ int sp_fumbleshield(struct castorder * co) case SPL_CERDDOR_FUMBLESHIELD: case SPL_TYBIED_FUMBLESHIELD: duration = 100; - effect = _max(1, 25 - level); + effect = MAX(1, 25 - level); break; default: @@ -1598,14 +1561,14 @@ int sp_reanimate(struct castorder * co) } healable = count_healable(b, fi); - healable = (int)_min(k, healable); + healable = (int)MIN(k, healable); while (healable--) { fighter *tf = select_corpse(b, fi); if (tf != NULL && tf->side->casualties > 0 && u_race(tf->unit) != get_race(RC_DAEMON) && (chance(c))) { assert(tf->alive < tf->unit->number); - /* t.fighter->person[].hp beginnt mit t.index = 0 zu zhlen, + /* t.fighter->person[].hp beginnt mit t.index = 0 zu z�hlen, * t.fighter->alive ist jedoch die Anzahl lebender in der Einheit, * also sind die hp von t.fighter->alive * t.fighter->hitpoints[t.fighter->alive-1] und der erste Tote @@ -1651,24 +1614,24 @@ int sp_keeploot(struct castorder * co) message_all(b, m); msg_release(m); - b->keeploot = (int)_max(25, b->keeploot + 5 * power); + b->keeploot = (int)MAX(25, b->keeploot + 5 * power); return level; } -static int heal_fighters(quicklist * fgs, int *power, bool heal_monsters) +static int heal_fighters(selist * fgs, int *power, bool heal_monsters) { int healhp = *power, healed = 0, qi; - quicklist *ql; + selist *ql; - for (qi = 0, ql = fgs; ql; ql_advance(&ql, &qi, 1)) { - fighter *df = (fighter *)ql_get(ql, qi); + for (qi = 0, ql = fgs; ql; selist_advance(&ql, &qi, 1)) { + fighter *df = (fighter *)selist_get(ql, qi); if (healhp <= 0) break; /* Untote kann man nicht heilen */ - if (df->unit->number == 0 || fval(u_race(df->unit), RCF_NOHEAL)) + if (df->unit->number == 0 || (u_race(df->unit)->flags & RCF_NOHEAL)) continue; /* wir heilen erstmal keine Monster */ @@ -1682,10 +1645,10 @@ static int heal_fighters(quicklist * fgs, int *power, bool heal_monsters) ++wound; if (wound > 0 && wound < hp) { - int heal = _min(healhp, wound); + int heal = MIN(healhp, wound); assert(heal >= 0); df->person[n].hp += heal; - healhp = _max(0, healhp - heal); + healhp = MAX(0, healhp - heal); ++healed; if (healhp <= 0) break; @@ -1707,12 +1670,12 @@ int sp_healing(struct castorder * co) unit *mage = fi->unit; int j = 0; int healhp = (int)power * 200; - quicklist *fgs; + selist *fgs; message *msg; bool use_item = has_ao_healing(mage); - /* bis zu 11 Personen pro Stufe (einen HP mssen sie ja noch - * haben, sonst wren sie tot) knnen geheilt werden */ + /* bis zu 11 Personen pro Stufe (einen HP m�ssen sie ja noch + * haben, sonst w�ren sie tot) k�nnen geheilt werden */ if (use_item) { healhp *= 2; @@ -1725,7 +1688,7 @@ int sp_healing(struct castorder * co) scramble_fighters(fgs); j += heal_fighters(fgs, &healhp, false); j += heal_fighters(fgs, &healhp, true); - ql_free(fgs); + selist_free(fgs); if (j <= 0) { level = j; @@ -1752,18 +1715,18 @@ int sp_undeadhero(struct castorder * co) battle *b = fi->side->battle; unit *mage = fi->unit; region *r = b->region; - quicklist *fgs, *ql; + selist *fgs, *ql; int qi, n, undead = 0; message *msg; int force = (int)get_force(power, 0); double c = 0.50 + 0.02 * power; - /* Liste aus allen Kmpfern */ + /* Liste aus allen K�mpfern */ fgs = fighters(b, fi->side, FIGHT_ROW, AVOID_ROW, FS_ENEMY | FS_HELP); scramble_fighters(fgs); - for (qi = 0, ql = fgs; ql; ql_advance(&ql, &qi, 1)) { - fighter *df = (fighter *)ql_get(ql, qi); + for (qi = 0, ql = fgs; ql; selist_advance(&ql, &qi, 1)) { + fighter *df = (fighter *)selist_get(ql, qi); unit *du = df->unit; if (force <= 0) @@ -1776,7 +1739,7 @@ int sp_undeadhero(struct castorder * co) if (df->alive + df->run.number < du->number) { int j = 0; - /* Wieviele Untote knnen wir aus dieser Einheit wecken? */ + /* Wieviele Untote k�nnen wir aus dieser Einheit wecken? */ for (n = df->alive + df->run.number; n != du->number; n++) { if (chance(c)) { ++j; @@ -1800,7 +1763,7 @@ int sp_undeadhero(struct castorder * co) unit_setinfo(u, NULL); } setstatus(u, du->status); - setguard(u, GUARD_NONE); + setguard(u, false); for (ilist = &du->items; *ilist;) { item *itm = *ilist; int loot = itm->number * j / du->number; @@ -1818,8 +1781,8 @@ int sp_undeadhero(struct castorder * co) } /* inherit stealth from magician */ - if (fval(mage, UFL_ANON_FACTION)) { - fset(u, UFL_ANON_FACTION); + if (mage->flags & UFL_ANON_FACTION) { + u->flags |= UFL_ANON_FACTION; } /* transfer dead people to new unit, set hitpoints to those of old unit */ @@ -1834,9 +1797,9 @@ int sp_undeadhero(struct castorder * co) } } } - ql_free(fgs); + selist_free(fgs); - level = _min(level, undead); + level = MIN(level, undead); if (undead == 0) { msg = msg_message("summonundead_effect_0", "mage region", mage, mage->region); diff --git a/src/spells/combatspells.h b/src/spells/combatspells.h index 4e3173a66..cf07c2a89 100644 --- a/src/spells/combatspells.h +++ b/src/spells/combatspells.h @@ -49,7 +49,6 @@ extern "C" { int sp_armorshield(struct castorder * co); int sp_stun(struct castorder * co); int sp_undeadhero(struct castorder * co); - int sp_shadowcall(struct castorder * co); int sp_immolation(struct castorder * co); #ifdef __cplusplus diff --git a/src/spells/flyingship.c b/src/spells/flyingship.c index 4a3c62e5e..2057b72e0 100644 --- a/src/spells/flyingship.c +++ b/src/spells/flyingship.c @@ -1,5 +1,4 @@ #include -#include #include "flyingship.h" #include @@ -27,8 +26,8 @@ * Stufe: 6 * * Wirkung: -* Laet ein Schiff eine Runde lang fliegen. Wirkt nur auf Boote -* bis Kapazitt 50. +* Lae�t ein Schiff eine Runde lang fliegen. Wirkt nur auf Boote +* bis Kapazit�t 50. * Kombinierbar mit "Guenstige Winde", aber nicht mit "Sturmwind". * * Flag: @@ -81,18 +80,20 @@ int sp_flying_ship(castorder * co) /* melden, 1x pro Partei */ for (u = r->units; u; u = u->next) - freset(u->faction, FFL_SELECT); + u->faction->flags &= ~FFL_SELECT; for (u = r->units; u; u = u->next) { /* das sehen natuerlich auch die Leute an Land */ - if (!fval(u->faction, FFL_SELECT)) { - fset(u->faction, FFL_SELECT); - if (!m) + if (!(u->faction->flags & FFL_SELECT)) { + u->faction->flags |= FFL_SELECT; + if (!m) { m = msg_message("flying_ship_result", "mage ship", mage, sh); + } add_message(&u->faction->msgs, m); } } - if (m) + if (m) { msg_release(m); + } return cast_level; } @@ -120,7 +121,7 @@ static int flyingship_age(curse * c) { ship *sh = (ship *)c->data.v; if (sh && c->duration == 1) { - freset(sh, SF_FLYING); + sh->flags &= ~SF_FLYING; return 1; } return 0; diff --git a/src/spells/flyingship.h b/src/spells/flyingship.h index 087357b9e..52013ac13 100644 --- a/src/spells/flyingship.h +++ b/src/spells/flyingship.h @@ -3,6 +3,8 @@ #ifndef FLYINGSHIP_H #define FLYINGSHIP_H +#include + #ifdef __cplusplus extern "C" { #endif @@ -22,4 +24,5 @@ extern "C" { } #endif -#endif \ No newline at end of file +#endif + diff --git a/src/spells/magicresistance.c b/src/spells/magicresistance.c index 3587a1be6..7b0c1413d 100644 --- a/src/spells/magicresistance.c +++ b/src/spells/magicresistance.c @@ -1,9 +1,10 @@ #include -#include #include #include #include +#include + static struct message *cinfo_magicresistance(const void *obj, objtype_t typ, const struct curse * c, int self) { if (typ == TYP_UNIT) { diff --git a/src/spells/magicresistance.test.c b/src/spells/magicresistance.test.c index 4b0d69388..e9cc98e34 100644 --- a/src/spells/magicresistance.test.c +++ b/src/spells/magicresistance.test.c @@ -1,5 +1,4 @@ #include -#include #include #include #include diff --git a/src/spells/regioncurse.c b/src/spells/regioncurse.c index 382b13b86..b10f3046f 100644 --- a/src/spells/regioncurse.c +++ b/src/spells/regioncurse.c @@ -12,7 +12,6 @@ */ #include -#include #include "regioncurse.h" #include "magic.h" @@ -46,11 +45,11 @@ static message *cinfo_cursed_by_the_gods(const void *obj, objtype_t typ, { region *r = (region *)obj; - unused_arg(typ); - unused_arg(self); + UNUSED_ARG(typ); + UNUSED_ARG(self); assert(typ == TYP_REGION); - if (fval(r->terrain, SEA_REGION)) { + if (r->terrain->flags & SEA_REGION) { return msg_message("curseinfo::godcurseocean", "id", c->no); } return msg_message("curseinfo::godcurse", "id", c->no); @@ -69,9 +68,9 @@ static struct curse_type ct_godcursezone = { static message *cinfo_dreamcurse(const void *obj, objtype_t typ, const curse * c, int self) { - unused_arg(self); - unused_arg(typ); - unused_arg(obj); + UNUSED_ARG(self); + UNUSED_ARG(typ); + UNUSED_ARG(obj); assert(typ == TYP_REGION); if (c->effect > 0) { @@ -95,9 +94,9 @@ static struct curse_type ct_gbdream = { static message *cinfo_magicstreet(const void *obj, objtype_t typ, const curse * c, int self) { - unused_arg(typ); - unused_arg(self); - unused_arg(obj); + UNUSED_ARG(typ); + UNUSED_ARG(self); + UNUSED_ARG(obj); assert(typ == TYP_REGION); /* Warnung vor Auflsung */ @@ -118,9 +117,9 @@ static struct curse_type ct_magicstreet = { static message *cinfo_antimagiczone(const void *obj, objtype_t typ, const curse * c, int self) { - unused_arg(typ); - unused_arg(self); - unused_arg(obj); + UNUSED_ARG(typ); + UNUSED_ARG(self); + UNUSED_ARG(obj); assert(typ == TYP_REGION); /* Magier spren eine Antimagiezone */ @@ -140,7 +139,7 @@ const curse * c, int self) unit *u = NULL; unit *mage = c->magician; - unused_arg(typ); + UNUSED_ARG(typ); assert(typ == TYP_REGION); r = (region *)obj; @@ -168,8 +167,8 @@ static struct curse_type ct_antimagiczone = { static message *cinfo_farvision(const void *obj, objtype_t typ, const curse * c, int self) { - unused_arg(typ); - unused_arg(obj); + UNUSED_ARG(typ); + UNUSED_ARG(obj); assert(typ == TYP_REGION); diff --git a/src/spells/shipcurse.c b/src/spells/shipcurse.c index 8da3c7c89..b6a722ad3 100644 --- a/src/spells/shipcurse.c +++ b/src/spells/shipcurse.c @@ -12,7 +12,6 @@ */ #include -#include #include "shipcurse.h" /* kernel includes */ @@ -39,8 +38,8 @@ message *cinfo_ship(const void *obj, objtype_t typ, const curse * c, int self) { message *msg; - unused_arg(typ); - unused_arg(obj); + UNUSED_ARG(typ); + UNUSED_ARG(obj); assert(typ == TYP_SHIP); if (self != 0) { /* owner or inside */ @@ -63,7 +62,7 @@ static message *cinfo_shipnodrift(const void *obj, objtype_t typ, const curse * { ship *sh = (ship *)obj; - unused_arg(typ); + UNUSED_ARG(typ); assert(typ == TYP_SHIP); if (self != 0) { diff --git a/src/spells/unitcurse.c b/src/spells/unitcurse.c index 944db2032..ded4a1676 100644 --- a/src/spells/unitcurse.c +++ b/src/spells/unitcurse.c @@ -12,7 +12,6 @@ */ #include -#include #include "unitcurse.h" /* kernel includes */ @@ -47,7 +46,7 @@ static message *cinfo_auraboost(const void *obj, objtype_t typ, const curse * c, int self) { struct unit *u = (struct unit *)obj; - unused_arg(typ); + UNUSED_ARG(typ); assert(typ == TYP_UNIT); if (self != 0) { @@ -81,7 +80,7 @@ static message *cinfo_slave(const void *obj, objtype_t typ, const curse * c, int self) { unit *u; - unused_arg(typ); + UNUSED_ARG(typ); assert(typ == TYP_UNIT); u = (unit *)obj; @@ -105,7 +104,7 @@ cinfo_slave static message *cinfo_calm(const void *obj, objtype_t typ, const curse * c, int self) { - unused_arg(typ); + UNUSED_ARG(typ); assert(typ == TYP_UNIT); if (c->magician && c->magician->faction) { @@ -134,7 +133,7 @@ static struct curse_type ct_calmmonster = { static message *cinfo_speed(const void *obj, objtype_t typ, const curse * c, int self) { - unused_arg(typ); + UNUSED_ARG(typ); assert(typ == TYP_UNIT); if (self != 0) { @@ -157,7 +156,7 @@ static struct curse_type ct_speed = { */ message *cinfo_unit(const void *obj, objtype_t typ, const curse * c, int self) { - unused_arg(typ); + UNUSED_ARG(typ); assert(typ == TYP_UNIT); assert(obj); @@ -182,7 +181,7 @@ static struct curse_type ct_orcish = { static message *cinfo_kaelteschutz(const void *obj, objtype_t typ, const curse * c, int self) { - unused_arg(typ); + UNUSED_ARG(typ); assert(typ == TYP_UNIT); if (self != 0) { @@ -234,7 +233,7 @@ static message *cinfo_sparkle(const void *obj, objtype_t typ, const curse * c, }; int m, begin = 0, end = 0; unit *u; - unused_arg(typ); + UNUSED_ARG(typ); assert(typ == TYP_UNIT); u = (unit *)obj; @@ -325,7 +324,7 @@ write_skill(struct storage *store, const curse * c, const void *target) static message *cinfo_skillmod(const void *obj, objtype_t typ, const curse * c, int self) { - unused_arg(typ); + UNUSED_ARG(typ); if (self != 0) { unit *u = (unit *)obj; diff --git a/src/spy.c b/src/spy.c index 9b8fe4601..d4082cad7 100644 --- a/src/spy.c +++ b/src/spy.c @@ -1,4 +1,4 @@ -/* +/* Copyright (c) 1998-2015, Enno Rehling Katja Zedel @@ -17,14 +17,15 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "spy.h" +#include "guard.h" #include "laws.h" #include "move.h" #include "reports.h" #include "study.h" /* kernel includes */ +#include #include #include #include @@ -43,8 +44,8 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /* util includes */ #include #include +#include #include -#include #include #include @@ -97,13 +98,13 @@ void spy_message(int spy, const unit * u, const unit * target) first = 0; } else { - strncat(buf, ", ", sizeof(buf) - 1); + strlcat(buf, ", ", sizeof(buf)); } - strncat(buf, (const char *)skillname((skill_t)sv->id, u->faction->locale), - sizeof(buf) - 1); - strncat(buf, " ", sizeof(buf) - 1); - strncat(buf, itoa10(eff_skill(target, sv, target->region)), - sizeof(buf) - 1); + strlcat(buf, (const char *)skillname((skill_t)sv->id, u->faction->locale), + sizeof(buf)); + strlcat(buf, " ", sizeof(buf)); + strlcat(buf, itoa10(eff_skill(target, sv, target->region)), + sizeof(buf)); } } if (found) { @@ -145,7 +146,7 @@ int spy_cmd(unit * u, struct order *ord) * Fuer jeden Talentpunkt, den das Spionagetalent das Tarnungstalent * des Opfers uebersteigt, erhoeht sich dieses um 5%*/ spy = effskill(u, SK_SPY, 0) - effskill(target, SK_STEALTH, r); - spychance = 0.1 + _max(spy * 0.05, 0.0); + spychance = 0.1 + MAX(spy * 0.05, 0.0); if (chance(spychance)) { produceexp(u, SK_SPY, u->number); @@ -161,7 +162,7 @@ int spy_cmd(unit * u, struct order *ord) - (effskill(u, SK_STEALTH, 0) + effskill(u, SK_SPY, 0) / 2); if (invisible(u, target) >= u->number) { - observe = _min(observe, 0); + observe = MIN(observe, 0); } /* Anschliessend wird - unabhaengig vom Erfolg - gewuerfelt, ob der @@ -228,7 +229,7 @@ int setstealth_cmd(unit * u, struct order *ord) return 0; } - if (isdigit(s[0])) { + if (isdigit(*(const unsigned char *)s)) { /* Tarnungslevel setzen */ level = atoi((const char *)s); if (level > effskill(u, SK_STEALTH, 0)) { @@ -292,19 +293,19 @@ int setstealth_cmd(unit * u, struct order *ord) s = gettoken(token, sizeof(token)); if (rule_stealth_anon()) { if (!s || *s == 0) { - fset(u, UFL_ANON_FACTION); + u->flags |= UFL_ANON_FACTION; break; } else if (findparam(s, u->faction->locale) == P_NOT) { - freset(u, UFL_ANON_FACTION); + u->flags &= ~UFL_ANON_FACTION; break; } } if (rule_stealth_other()) { if (get_keyword(s, u->faction->locale) == K_NUMBER) { - s = gettoken(token, sizeof(token)); int nr = -1; + s = gettoken(token, sizeof(token)); if (s) { nr = atoi36(s); } @@ -351,7 +352,7 @@ static int top_skill(region * r, faction * f, ship * sh, skill_t sk) for (u = r->units; u; u = u->next) { if (u->ship == sh && u->faction == f) { int s = effskill(u, sk, 0); - value = _max(s, value); + value = MAX(s, value); } } return value; @@ -413,18 +414,18 @@ static void sink_ship(region * r, ship * sh, unit * saboteur) /* slight optimization to avoid dereferencing u->faction each time */ if (f != u->faction) { f = u->faction; - freset(f, FFL_SELECT); + f->flags &= ~FFL_SELECT; } } /* figure out what a unit's chances of survival are: */ - if (!fval(r->terrain, SEA_REGION)) { + if (!(r->terrain->flags & SEA_REGION)) { probability = CANAL_SWIMMER_CHANCE; } else { for (d = 0; d != MAXDIRECTIONS; ++d) { region *rn = rconnect(r, d); - if (rn && !fval(rn->terrain, SEA_REGION) && !move_blocked(NULL, r, rn)) { + if (rn && !(rn->terrain->flags & SEA_REGION) && !move_blocked(NULL, r, rn)) { safety = rn; probability = OCEAN_SWIMMER_CHANCE; break; @@ -435,7 +436,7 @@ static void sink_ship(region * r, ship * sh, unit * saboteur) unit *u = *ui; /* inform this faction about the sinking ship: */ - if (!fval(u->faction, FFL_SELECT)) { + if (!(u->faction->flags & FFL_SELECT)) { fset(u->faction, FFL_SELECT); if (sink_msg == NULL) { sink_msg = msg_message("sink_msg", "ship region", sh, r); @@ -463,7 +464,7 @@ static void sink_ship(region * r, ship * sh, unit * saboteur) } leave_ship(u); if (r != safety) { - setguard(u, GUARD_NONE); + setguard(u, false); } while (u->items) { i_remove(&u->items, u->items); diff --git a/src/spy.h b/src/spy.h index 72694d4b1..d3ee0c728 100644 --- a/src/spy.h +++ b/src/spy.h @@ -25,6 +25,7 @@ extern "C" { struct unit; struct region; struct strlist; + struct order; extern int setstealth_cmd(struct unit *u, struct order *ord); extern int spy_cmd(struct unit *u, struct order *ord); diff --git a/src/spy.test.c b/src/spy.test.c index 299e4b3a6..ae1550689 100644 --- a/src/spy.test.c +++ b/src/spy.test.c @@ -60,6 +60,7 @@ static void set_factionstealth(unit *u, faction *f) { static void test_all_spy_message(CuTest *tc) { spy_fixture fix; + item_type *itype; setup_spy(&fix); @@ -69,9 +70,8 @@ static void test_all_spy_message(CuTest *tc) { create_mage(fix.victim, M_DRAIG); set_factionstealth(fix.victim, fix.spy->faction); - item_type *itype; itype = it_get_or_create(rt_get_or_create("sword")); - new_weapontype(itype, 0, 0.0, NULL, 0, 0, 0, SK_MELEE, 2); + new_weapontype(itype, 0, frac_zero, NULL, 0, 0, 0, SK_MELEE, 2); i_change(&fix.victim->items, itype, 1); spy_message(99, fix.spy, fix.victim); @@ -146,6 +146,26 @@ static void test_sabotage_other_fail(CuTest *tc) { test_cleanup(); } +static void test_setstealth_cmd(CuTest *tc) { + unit *u; + const struct locale *lang; + + test_setup(); + u = test_create_unit(test_create_faction(0), test_create_region(0,0,0)); + lang = u->faction->locale; + u->flags = UFL_ANON_FACTION|UFL_SIEGE; + u->thisorder = create_order(K_SETSTEALTH, lang, "%s %s", + LOC(lang, parameters[P_FACTION]), + LOC(lang, parameters[P_NOT])); + setstealth_cmd(u, u->thisorder); + CuAssertIntEquals(tc, UFL_SIEGE, u->flags); + free_order(u->thisorder); + u->thisorder = create_order(K_SETSTEALTH, lang, "%s", + LOC(lang, parameters[P_FACTION])); + setstealth_cmd(u, u->thisorder); + CuAssertIntEquals(tc, UFL_SIEGE|UFL_ANON_FACTION, u->flags); + test_cleanup(); +} static void test_sabotage_other_success(CuTest *tc) { unit *u, *u2; @@ -178,6 +198,7 @@ CuSuite *get_spy_suite(void) SUITE_ADD_TEST(suite, test_simple_spy_message); SUITE_ADD_TEST(suite, test_all_spy_message); SUITE_ADD_TEST(suite, test_sabotage_self); + SUITE_ADD_TEST(suite, test_setstealth_cmd); SUITE_ADD_TEST(suite, test_sabotage_other_fail); SUITE_ADD_TEST(suite, test_sabotage_other_success); return suite; diff --git a/src/sqlite.c b/src/sqlite.c index 37535c9d1..edb5bfc62 100644 --- a/src/sqlite.c +++ b/src/sqlite.c @@ -3,11 +3,10 @@ #include #include #include -#include #include #include #include -#include +#include #include #include #include @@ -73,10 +72,10 @@ typedef struct db_faction { char *name; } db_faction; -static struct quicklist * +static struct selist * read_factions(sqlite3 * db, int game_id) { int res; - quicklist *result = 0; + selist *result = 0; const char * sql = "SELECT f.id, fd.code, fd.name, fd.email FROM faction f" " LEFT OUTER JOIN faction_data fd" @@ -95,10 +94,10 @@ read_factions(sqlite3 * db, int game_id) { text = (const char *)sqlite3_column_text(stmt, 1); if (text) dbf->no = atoi36(text); text = (const char *)sqlite3_column_text(stmt, 2); - if (text) dbf->name = _strdup(text); + if (text) dbf->name = strdup(text); text = (const char *)sqlite3_column_text(stmt, 3); - if (text) dbf->email = _strdup(text); - ql_push(&result, dbf); + if (text) dbf->email = strdup(text); + selist_push(&result, dbf); res = sqlite3_step(stmt); } sqlite3_finalize(stmt); @@ -134,54 +133,71 @@ static void update_faction(sqlite3 *db, const faction *f) { sqlite3_finalize(stmt); } -int db_update_factions(sqlite3 * db, bool force, int game_id) { - quicklist *ql = read_factions(db, game_id); - faction *f; - sqlite3_exec(db, "BEGIN", 0, 0, 0); - for (f = factions; f; f = f->next) { - bool update = force; - db_faction *dbf = 0; - ql_iter it = qli_init(&ql); - while (qli_more(it)) { - db_faction *df = (db_faction*)qli_next(&it); - if (f->no == df->no || strcmp(f->email, df->email) == 0 || strcmp(f->name, df->name) == 0) { - dbf = df; - } - if (f->subscription == df->uid) { - dbf = df; - break; - } - } - if (dbf) { - if (dbf->uid != f->subscription) { - log_warning("faction %s(%d) not found in database, but matches %d\n", itoa36(f->no), f->subscription, dbf->uid); - f->subscription = dbf->uid; - } - update = (dbf->no != f->no) || (strcmp(f->email, dbf->email) != 0) || (strcmp(f->name, dbf->name) != 0); - } - else { - f->subscription = insert_faction(db, game_id, f); - log_warning("faction %s not found in database, created as %d\n", itoa36(f->no), f->subscription); - update = true; - } - if (update) { - update_faction(db, f); - log_debug("faction %s updated\n", itoa36(f->no)); - } +struct cb_data { + const faction *f; + sqlite3 *db; + db_faction *dbf; +}; + +static bool db_faction_cb(void *el, void *arg) { + db_faction *df = (db_faction *)el; + struct cb_data *cb = (struct cb_data *)arg; + const faction *f = cb->f; + + if (f->no == df->no || strcmp(f->email, df->email) == 0 || strcmp(f->name, df->name) == 0) { + cb->dbf = df; + } + if (f->subscription == df->uid) { + cb->dbf = df; + return false; + } + return true; +} + +int db_update_factions(sqlite3 * db, bool force, int game_id) { + selist *ql = read_factions(db, game_id); + if (ql) { + faction *f; + struct cb_data cbdata; + cbdata.db = db; + cbdata.dbf = NULL; + sqlite3_exec(db, "BEGIN", 0, 0, 0); + for (f = factions; f; f = f->next) { + bool update = force; + cbdata.f = f; + selist_foreach_ex(ql, db_faction_cb, &cbdata); + if (cbdata.dbf) { + const db_faction *dbf = cbdata.dbf; + if (dbf->uid != f->subscription) { + log_warning("faction %s(%d) not found in database, but matches %d\n", itoa36(f->no), f->subscription, dbf->uid); + f->subscription = dbf->uid; + } + update = (dbf->no != f->no) || (strcmp(f->email, dbf->email) != 0) || (strcmp(f->name, dbf->name) != 0); + } + else { + f->subscription = insert_faction(db, game_id, f); + log_warning("faction %s not found in database, created as %d\n", itoa36(f->no), f->subscription); + update = true; + } + if (update) { + update_faction(db, f); + log_debug("faction %s updated\n", itoa36(f->no)); + } + } + sqlite3_exec(db, "COMMIT", 0, 0, 0); } - sqlite3_exec(db, "COMMIT", 0, 0, 0); return SQLITE_OK; } int db_update_scores(sqlite3 * db, bool force) { /* - const char *sql_ins = + const char *sselist_ins = "INSERT OR FAIL INTO score (value,faction_id,turn) VALUES (?,?,?)"; - sqlite3_stmt *stmt_ins = stmt_cache_get(db, sql_ins); - const char *sql_upd = + sqlite3_stmt *stmt_ins = stmt_cache_get(db, sselist_ins); + const char *sselist_upd = "UPDATE score set value=? WHERE faction_id=? AND turn=?"; - sqlite3_stmt *stmt_upd = stmt_cache_get(db, sql_upd); + sqlite3_stmt *stmt_upd = stmt_cache_get(db, sselist_upd); faction *f; sqlite3_exec(db, "BEGIN", 0, 0, 0); for (f = factions; f; f = f->next) { diff --git a/src/study.c b/src/study.c index eb5cec12d..27443e996 100644 --- a/src/study.c +++ b/src/study.c @@ -1,4 +1,4 @@ -/* +/* Copyright (c) 1998-2015, Enno Rehling Katja Zedel @@ -22,8 +22,9 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include "study.h" +#include "laws.h" #include "move.h" -#include "monster.h" +#include "monsters.h" #include "alchemy.h" #include "academy.h" @@ -51,6 +52,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include +#include /* libc includes */ #include @@ -198,7 +200,7 @@ teach_unit(unit * teacher, unit * student, int nteaching, skill_t sk, * steigen. * * n ist die Anzahl zusaetzlich gelernter Tage. n darf max. die Differenz - * von schon gelernten Tagen zum _max(30 Tage pro Mann) betragen. */ + * von schon gelernten Tagen zum MAX(30 Tage pro Mann) betragen. */ if (magic_lowskill(student)) { cmistake(teacher, teacher->thisorder, 292, MSG_EVENT); @@ -212,27 +214,14 @@ teach_unit(unit * teacher, unit * student, int nteaching, skill_t sk, n -= teach->value; } - n = _min(n, nteaching); + n = MIN(n, nteaching); if (n != 0) { - int index = 0; - if (teach == NULL) { a = a_add(&student->attribs, a_new(&at_learning)); teach = (teaching_info *)a->data.v; } - else { - while (teach->teachers[index] && index != MAXTEACHERS) - ++index; - } - if (index < MAXTEACHERS) - teach->teachers[index++] = teacher; - if (index < MAXTEACHERS) { - teach->teachers[index] = NULL; - } - else { - log_error("MAXTEACHERS=%d is too low for student %s, teacher %s", MAXTEACHERS, unitname(student), unitname(teacher)); - } + selist_push(&teach->teachers, teacher); teach->value += n; if (student->building && teacher->building == student->building) { @@ -277,7 +266,7 @@ teach_unit(unit * teacher, unit * student, int nteaching, skill_t sk, * die Talentaenderung (enno). */ - nteaching = _max(0, nteaching - student->number * 30); + nteaching = MAX(0, nteaching - student->number * 30); } return n; @@ -313,7 +302,7 @@ int teach_cmd(unit * u, struct order *ord) teaching = u->number * 30 * TEACHNUMBER; if ((i = get_effect(u, oldpotiontype[P_FOOL])) > 0) { /* Trank "Dumpfbackenbrot" */ - i = _min(i, u->number * TEACHNUMBER); + i = MIN(i, u->number * TEACHNUMBER); /* Trank wirkt pro Schueler, nicht pro Lehrer */ teaching -= i * 30; change_effect(u, oldpotiontype[P_FOOL], -i); @@ -438,7 +427,7 @@ int teach_cmd(unit * u, struct order *ord) strncat(zOrder, " ", sz - 1); --sz; } - sz -= strlcpy(zOrder + 4096 - sz, unitid(u2), sz); + sz -= strlcpy(zOrder + 4096 - sz, itoa36(u2->no), sz); if (getkeyword(u2->thisorder) != K_STUDY) { ADDMSG(&u->faction->msgs, @@ -472,8 +461,8 @@ int teach_cmd(unit * u, struct order *ord) * Lehrer seines Gebietes */ sc_mage *mage1 = get_mage(u); sc_mage *mage2 = get_mage(u2); - if (!mage2 || !mage1 || (mage2->magietyp != M_GRAY - && mage1->magietyp != mage2->magietyp)) { + if (mage2 && mage1 && mage2->magietyp != M_GRAY + && mage1->magietyp != mage2->magietyp) { if (feedback) { ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "error_different_magic", "target", u2)); @@ -531,6 +520,46 @@ static double study_speedup(unit * u, skill_t s, study_rule_t rule) return 1.0; } +static bool ExpensiveMigrants(void) +{ + static bool rule; + static int cache; + if (config_changed(&cache)) { + rule = config_get_int("study.expensivemigrants", 0) != 0; + } + return rule; +} + +struct teach_data { + unit *u; + skill_t sk; +}; + +static bool cb_msg_teach(void *el, void *arg) { + struct teach_data *td = (struct teach_data *)arg; + unit *ut = (unit *)el; + unit * u = td->u; + skill_t sk = td->sk; + if (ut->faction != u->faction) { + bool feedback = alliedunit(u, ut->faction, HELP_GUARD); + if (feedback) { + ADDMSG(&ut->faction->msgs, msg_message("teach_teacher", + "teacher student skill level", ut, u, sk, + effskill(u, sk, 0))); + } + ADDMSG(&u->faction->msgs, msg_message("teach_student", + "teacher student skill", ut, u, sk)); + } + return true; +} + +static void msg_teachers(struct selist *teachers, struct unit *u, skill_t sk) { + struct teach_data cbdata; + cbdata.sk = sk; + cbdata.u = u; + selist_foreach_ex(teachers, cb_msg_teach, &cbdata); +} + int study_cmd(unit * u, order * ord) { region *r = u->region; @@ -546,6 +575,12 @@ int study_cmd(unit * u, order * ord) int maxalchemy = 0; int speed_rule = (study_rule_t)config_get_int("study.speedup", 0); bool learn_newskills = config_get_int("study.newskills", 1) != 0; + static const race *rc_snotling; + static int rc_cache; + + if (rc_changed(&rc_cache)) { + rc_snotling = get_race(RC_SNOTLING); + } if (!unit_can_study(u)) { ADDMSG(&u->faction->msgs, msg_feedback(u, ord, "error_race_nolearn", "race", @@ -575,7 +610,7 @@ int study_cmd(unit * u, order * ord) } /* snotlings koennen Talente nur bis T8 lernen */ - if (u_race(u) == get_race(RC_SNOTLING)) { + if (u_race(u) == rc_snotling) { if (get_level(u, sk) >= 8) { cmistake(u, ord, 308, MSG_EVENT); return 0; @@ -598,7 +633,7 @@ int study_cmd(unit * u, order * ord) } /* Akademie: */ if (active_building(u, bt_find("academy"))) { - studycost = _max(50, studycost * 2); + studycost = MAX(50, studycost * 2); } if (sk == SK_MAGIC) { @@ -685,11 +720,11 @@ int study_cmd(unit * u, order * ord) if (studycost) { int cost = studycost * u->number; money = get_pooled(u, get_resourcetype(R_SILVER), GET_DEFAULT, cost); - money = _min(money, cost); + money = MIN(money, cost); } if (money < studycost * u->number) { studycost = p; /* Ohne Univertreurung */ - money = _min(money, studycost); + money = MIN(money, studycost); if (p > 0 && money < studycost * u->number) { cmistake(u, ord, 65, MSG_EVENT); multi = money / (double)(studycost * u->number); @@ -700,7 +735,7 @@ int study_cmd(unit * u, order * ord) a = a_add(&u->attribs, a_new(&at_learning)); teach = (teaching_info *)a->data.v; assert(teach); - teach->teachers[0] = 0; + teach->teachers = NULL; } if (money > 0) { use_pooled(u, get_resourcetype(R_SILVER), GET_DEFAULT, money); @@ -709,12 +744,12 @@ int study_cmd(unit * u, order * ord) } if (get_effect(u, oldpotiontype[P_WISE])) { - l = _min(u->number, get_effect(u, oldpotiontype[P_WISE])); + l = MIN(u->number, get_effect(u, oldpotiontype[P_WISE])); teach->value += l * 10; change_effect(u, oldpotiontype[P_WISE], -l); } if (get_effect(u, oldpotiontype[P_FOOL])) { - l = _min(u->number, get_effect(u, oldpotiontype[P_FOOL])); + l = MIN(u->number, get_effect(u, oldpotiontype[P_FOOL])); teach->value -= l * 30; change_effect(u, oldpotiontype[P_FOOL], -l); } @@ -749,24 +784,13 @@ int study_cmd(unit * u, order * ord) learn_skill(u, sk, days); if (a != NULL) { - int index = 0; - while (teach->teachers[index] && index != MAXTEACHERS) { - unit *teacher = teach->teachers[index++]; - if (teacher->faction != u->faction) { - bool feedback = alliedunit(u, teacher->faction, HELP_GUARD); - if (feedback) { - ADDMSG(&teacher->faction->msgs, msg_message("teach_teacher", - "teacher student skill level", teacher, u, sk, - effskill(u, sk, 0))); - } - ADDMSG(&u->faction->msgs, msg_message("teach_student", - "teacher student skill", teacher, u, sk)); - } + if (teach->teachers) { + msg_teachers(teach->teachers, u, sk); } a_remove(&u->attribs, a); a = NULL; } - fset(u, UFL_LONGACTION | UFL_NOTMOVING); + u->flags |= (UFL_LONGACTION | UFL_NOTMOVING); /* Anzeigen neuer Traenke */ /* Spruchlistenaktualiesierung ist in Regeneration */ @@ -800,7 +824,11 @@ int study_cmd(unit * u, order * ord) } static int produceexp_days(void) { - return config_get_int("study.produceexp", 10); + static int config, rule; + if (config_changed(&config)) { + rule = config_get_int("study.produceexp", 10); + } + return rule; } void produceexp_ex(struct unit *u, skill_t sk, int n, learn_fun learn) @@ -863,7 +891,11 @@ void demon_skillchange(unit *u) if (fval(u, UFL_HUNGER)) { /* hungry demons only go down, never up in skill */ - int rule_hunger = config_get_int("hunger.demon.skill", 0) != 0; + static int config; + static bool rule_hunger; + if (config_changed(&config)) { + rule_hunger = config_get_int("hunger.demon.skill", 0) != 0; + } if (rule_hunger) { upchance = 0; downchance = 15; diff --git a/src/study.h b/src/study.h index e136d7345..0f8ae70f5 100644 --- a/src/study.h +++ b/src/study.h @@ -27,6 +27,7 @@ extern "C" { #endif struct unit; + struct selist; int teach_cmd(struct unit *u, struct order *ord); int study_cmd(struct unit *u, struct order *ord); @@ -45,10 +46,9 @@ extern "C" { void demon_skillchange(struct unit *u); -#define MAXTEACHERS 20 #define TEACHNUMBER 10 typedef struct teaching_info { - struct unit *teachers[MAXTEACHERS]; + struct selist *teachers; int value; } teaching_info; diff --git a/src/study.test.c b/src/study.test.c index 47976930d..3b411c7df 100644 --- a/src/study.test.c +++ b/src/study.test.c @@ -2,6 +2,7 @@ #include "study.h" +#include #include #include #include @@ -10,15 +11,18 @@ #include #include #include +#include #include #include #include #include #include +#include +#include + #include -#include #define MAXLOG 4 typedef struct log_entry { @@ -299,7 +303,7 @@ static void test_demon_skillchanges(CuTest *tc) { CuAssertPtrNotNull(tc, u); set_level(u, SK_CROSSBOW, 1); demon_skillchange(u); - // TODO: sensing here + /* TODO: sensing here */ test_cleanup(); } @@ -381,6 +385,34 @@ static void test_study_cost(CuTest *tc) { test_cleanup(); } +static void test_teach_magic(CuTest *tc) { + unit *u, *ut; + faction *f; + const struct item_type *itype; + + test_setup(); + init_resources(); + itype = get_resourcetype(R_SILVER)->itype; + f = test_create_faction(0); + f->magiegebiet = M_GWYRRD; + u = test_create_unit(f, test_create_region(0, 0, 0)); + u->thisorder = create_order(K_STUDY, f->locale, "%s", skillnames[SK_MAGIC]); + i_change(&u->items, itype, study_cost(u, SK_MAGIC)); + ut = test_create_unit(f, u->region); + set_level(ut, SK_MAGIC, TEACHDIFFERENCE); + create_mage(ut, M_GWYRRD); + ut->thisorder = create_order(K_TEACH, f->locale, "%s", itoa36(u->no)); + learn_inject(); + teach_cmd(ut, ut->thisorder); + study_cmd(u, u->thisorder); + learn_reset(); + CuAssertPtrEquals(tc, u, log_learners[0].u); + CuAssertIntEquals(tc, SK_MAGIC, log_learners[0].sk); + CuAssertIntEquals(tc, STUDYDAYS*2, log_learners[0].days); + CuAssertIntEquals(tc, 0, i_get(u->items, itype)); + test_cleanup(); +} + static void test_teach_cmd(CuTest *tc) { unit *u, *ut; test_setup(); @@ -483,6 +515,7 @@ static void test_teach_one_to_many(CuTest *tc) { static void test_teach_many_to_one(CuTest *tc) { unit *u, *u1, *u2; + test_setup(); init_resources(); u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); @@ -505,6 +538,47 @@ static void test_teach_many_to_one(CuTest *tc) { test_cleanup(); } +static void test_teach_message(CuTest *tc) { + unit *u, *u1, *u2; + attrib *a; + ally *al; + teaching_info *teach; + + test_setup(); + init_resources(); + u = test_create_unit(test_create_faction(0), test_create_region(0, 0, 0)); + scale_number(u, 20); + u->thisorder = create_order(K_STUDY, u->faction->locale, "CROSSBOW"); + u1 = test_create_unit(test_create_faction(0), u->region); + set_level(u1, SK_CROSSBOW, TEACHDIFFERENCE); + u1->thisorder = create_order(K_TEACH, u->faction->locale, itoa36(u->no)); + u2 = test_create_unit(test_create_faction(0), u->region); + al = ally_add(&u->faction->allies, u2->faction); + al->status = HELP_GUARD; + set_level(u2, SK_CROSSBOW, TEACHDIFFERENCE); + u2->thisorder = create_order(K_TEACH, u->faction->locale, itoa36(u->no)); + CuAssertTrue(tc, !alliedunit(u, u1->faction, HELP_GUARD)); + CuAssertTrue(tc, alliedunit(u, u2->faction, HELP_GUARD)); + teach_cmd(u1, u1->thisorder); + teach_cmd(u2, u2->thisorder); + a = a_find(u->attribs, &at_learning); + CuAssertPtrNotNull(tc, a); + CuAssertPtrNotNull(tc, a->data.v); + teach = (teaching_info *)a->data.v; + CuAssertPtrNotNull(tc, teach->teachers); + CuAssertIntEquals(tc, 600, teach->value); + CuAssertIntEquals(tc, 2, selist_length(teach->teachers)); + CuAssertPtrEquals(tc, u1, selist_get(teach->teachers, 0)); + CuAssertPtrEquals(tc, u2, selist_get(teach->teachers, 1)); + study_cmd(u, u->thisorder); + CuAssertPtrEquals(tc, NULL, test_find_messagetype(u1->faction->msgs, "teach_teacher")); + CuAssertPtrNotNull(tc, test_find_messagetype(u2->faction->msgs, "teach_teacher")); + CuAssertPtrNotNull(tc, test_find_messagetype(u->faction->msgs, "teach_student")); + a = a_find(u->attribs, &at_learning); + CuAssertPtrEquals(tc, NULL, a); + test_cleanup(); +} + static void test_teach_many_to_many(CuTest *tc) { unit *s1, *s2, *t1, *t2; region *r; @@ -550,10 +624,12 @@ CuSuite *get_study_suite(void) SUITE_ADD_TEST(suite, test_study_cost); SUITE_ADD_TEST(suite, test_study_magic); SUITE_ADD_TEST(suite, test_teach_cmd); + SUITE_ADD_TEST(suite, test_teach_magic); SUITE_ADD_TEST(suite, test_teach_two); SUITE_ADD_TEST(suite, test_teach_one_to_many); SUITE_ADD_TEST(suite, test_teach_many_to_one); SUITE_ADD_TEST(suite, test_teach_many_to_many); + SUITE_ADD_TEST(suite, test_teach_message); SUITE_ADD_TEST(suite, test_teach_two_skills); SUITE_ADD_TEST(suite, test_learn_skill_single); SUITE_ADD_TEST(suite, test_learn_skill_multi); diff --git a/src/summary.c b/src/summary.c index cbc998b4a..32416a263 100644 --- a/src/summary.c +++ b/src/summary.c @@ -1,4 +1,4 @@ -/* +/* * +-------------------+ Christian Schlittchen * | | Enno Rehling * | Eressea PBEM host | Katja Zedel @@ -14,7 +14,7 @@ #include "summary.h" #include "laws.h" -#include "monster.h" +#include "monsters.h" #include "calendar.h" #include @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include @@ -59,7 +58,6 @@ typedef struct summary { int landregionen; int regionen_mit_spielern; int landregionen_mit_spielern; - int orkifizierte_regionen; int inactive_volcanos; int active_volcanos; int spielerpferde; @@ -98,12 +96,12 @@ int update_nmrs(void) int nmr = turn - f->lastorders + 1; if (timeout>0) { if (nmr < 0 || nmr > timeout) { - log_error("faction %s has %d NMR", factionid(f), nmr); - nmr = _max(0, nmr); - nmr = _min(nmr, timeout); + log_error("faction %s has %d NMR", itoa36(f->no), nmr); + nmr = MAX(0, nmr); + nmr = MIN(nmr, timeout); } if (nmr > 0) { - log_debug("faction %s has %d NMR", factionid(f), nmr); + log_debug("faction %s has %d NMR", itoa36(f->no), nmr); } ++nmrs[nmr]; } @@ -166,7 +164,7 @@ static char *gamedate2(const struct locale *lang) static void writeturn(void) { - char zText[MAX_PATH]; + char zText[4096]; FILE *f; join_path(basepath(), "datum", zText, sizeof(zText)); @@ -192,7 +190,7 @@ void report_summary(summary * s, summary * o, bool full) FILE *F = NULL; int i, newplayers = 0; faction *f; - char zText[MAX_PATH]; + char zText[4096]; int timeout = NMRTimeout(); if (full) { @@ -222,12 +220,11 @@ void report_summary(summary * s, summary * o, bool full) fprintf(F, " Helden: %s\n", pcomp(s->heroes, o->heroes)); if (full) { - fprintf(F, "Regionen: %d\n", listlen(regions)); + fprintf(F, "Regionen: %d\n", (int)listlen(regions)); fprintf(F, "Bewohnte Regionen: %d\n", s->inhabitedregions); fprintf(F, "Landregionen: %d\n", s->landregionen); fprintf(F, "Spielerregionen: %d\n", s->regionen_mit_spielern); fprintf(F, "Landspielerregionen: %d\n", s->landregionen_mit_spielern); - fprintf(F, "Orkifizierte Regionen: %d\n", s->orkifizierte_regionen); fprintf(F, "Inaktive Vulkane: %d\n", s->inactive_volcanos); fprintf(F, "Aktive Vulkane: %d\n\n", s->active_volcanos); } @@ -422,9 +419,6 @@ summary *make_summary(void) if (r->units) { s->landregionen_mit_spielern++; } - if (fval(r, RF_ORCIFIED)) { - s->orkifizierte_regionen++; - } if (r->terrain == newterrain(T_VOLCANO)) { s->inactive_volcanos++; } diff --git a/src/summary.h b/src/summary.h index ea8daeee1..b12d74009 100644 --- a/src/summary.h +++ b/src/summary.h @@ -11,6 +11,8 @@ #ifndef H_GC_SUMMARY #define H_GC_SUMMARY +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/src/teleport.c b/src/teleport.c index 5b7f71831..f81f2f9f0 100644 --- a/src/teleport.c +++ b/src/teleport.c @@ -34,7 +34,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include "skill.h" -#include "monster.h" +#include "monsters.h" /* libc includes */ #include @@ -176,14 +176,16 @@ bool is_astral(const region * r) plane *get_astralplane(void) { plane *astralspace = 0; - int rule_astralplane = config_get_int("modules.astralspace", 1); - + static int config; + static bool rule_astralplane; + + if (config_changed(&config)) { + rule_astralplane = config_get_int("modules.astralspace", 1) != 0; + } if (!rule_astralplane) { return NULL; } - if (!astralspace) { - astralspace = getplanebyname("Astralraum"); - } + astralspace = getplanebyname("Astralraum"); if (!astralspace) { astralspace = create_new_plane(1, "Astralraum", TE_CENTER_X - 500, TE_CENTER_X + 500, diff --git a/src/test_eressea.c b/src/test_eressea.c index df4b762f3..1d991725f 100644 --- a/src/test_eressea.c +++ b/src/test_eressea.c @@ -6,6 +6,7 @@ #include #include #include +#include #pragma warning(disable: 4210) @@ -33,7 +34,7 @@ static void add_suite(CuSuite *(*csuite)(void), const char *name, int argc, char } if (s) { s->next = suites; - s->name = _strdup(name); + s->name = strdup(name); s->csuite = csuite(); suites = s; } @@ -52,20 +53,23 @@ void RunTests(CuSuite * suite, const char *name) { bool list = false; #define ADD_SUITE(name) \ - CuSuite *get_##name##_suite(void); \ - if (list) printf("%s\n", #name); \ - if (!list || argc>0) add_suite(get_##name##_suite, #name, argc, argv) + do { \ + CuSuite *get_##name##_suite(void); \ + if (list) printf("%s\n", #name); \ + if (!list || argc>0) add_suite(get_##name##_suite, #name, argc, argv); \ + } while (0) + int RunAllTests(int argc, char *argv[]) { /* self-test */ ADD_SUITE(tests); - ADD_SUITE(callback); ADD_SUITE(json); ADD_SUITE(jsonconf); ADD_SUITE(direction); ADD_SUITE(skill); ADD_SUITE(keyword); + ADD_SUITE(message); ADD_SUITE(order); ADD_SUITE(race); /* util */ @@ -82,6 +86,7 @@ int RunAllTests(int argc, char *argv[]) ADD_SUITE(unicode); ADD_SUITE(strings); ADD_SUITE(log); + ADD_SUITE(variant); ADD_SUITE(rng); /* items */ ADD_SUITE(xerewards); @@ -100,6 +105,7 @@ int RunAllTests(int argc, char *argv[]) ADD_SUITE(magic); ADD_SUITE(alchemy); ADD_SUITE(reports); + ADD_SUITE(region); ADD_SUITE(save); ADD_SUITE(ship); ADD_SUITE(spellbook); @@ -110,9 +116,9 @@ int RunAllTests(int argc, char *argv[]) ADD_SUITE(ally); ADD_SUITE(messages); /* gamecode */ + ADD_SUITE(guard); ADD_SUITE(report); -// ADD_SUITE(creport); - ADD_SUITE(prefix); + ADD_SUITE(creport); ADD_SUITE(summary); ADD_SUITE(names); ADD_SUITE(battle); @@ -128,6 +134,8 @@ int RunAllTests(int argc, char *argv[]) ADD_SUITE(monsters); ADD_SUITE(move); ADD_SUITE(piracy); + ADD_SUITE(prefix); + ADD_SUITE(renumber); ADD_SUITE(key); ADD_SUITE(stealth); ADD_SUITE(otherfaction); diff --git a/src/tests.c b/src/tests.c index 53f5ea470..c448a27ae 100644 --- a/src/tests.c +++ b/src/tests.c @@ -40,7 +40,7 @@ struct race *test_create_race(const char *name) race *rc = rc_get_or_create(name); rc->maintenance = 10; rc->hitpoints = 20; - rc->maxaura = 1.0; + rc->maxaura = 100; rc->ec_flags |= GETITEM; rc->battle_flags = BF_EQUIPMENT; return rc; @@ -196,9 +196,15 @@ static void test_reset(void) { } } -void test_setup(void) { +void test_setup_test(CuTest *tc, const char *file, int line) { test_log_stderr(LOG_CPERROR); test_reset(); + if (tc) { + log_debug("start test: %s", tc->name); + } + else { + log_debug("start test in %s:%d", file, line); + } } void test_cleanup(void) @@ -211,14 +217,24 @@ terrain_type * test_create_terrain(const char * name, unsigned int flags) { terrain_type * t = get_or_create_terrain(name); + if (flags & LAND_REGION) { + t->size = 1000; + } t->flags = flags; return t; } building * test_create_building(region * r, const building_type * btype) { - building * b = new_building(btype ? btype : test_create_buildingtype("castle"), r, default_locale); - b->size = b->type->maxsize > 0 ? b->type->maxsize : 1; + building * b; + assert(r); + if (!btype) { + building_type *bt_castle = test_create_buildingtype("castle"); + bt_castle->flags |= BTF_FORTIFICATION; + btype = bt_castle; + } + b = new_building(btype, r, default_locale); + b->size = btype->maxsize > 0 ? btype->maxsize : 1; return b; } @@ -452,6 +468,14 @@ struct message * test_find_messagetype(struct message_list *msgs, const char *na return test_find_messagetype_ex(msgs, name, NULL); } +void test_clear_messagelist(message_list **msgs) { + if (*msgs) { + free_messagelist((*msgs)->begin); + free(*msgs); + *msgs = NULL; + } +} + void test_clear_messages(faction *f) { if (f->msgs) { free_messagelist(f->msgs->begin); diff --git a/src/tests.h b/src/tests.h index 10934c3d7..c99147e6a 100644 --- a/src/tests.h +++ b/src/tests.h @@ -31,7 +31,10 @@ extern "C" { struct CuTest; - void test_setup(void); + void test_setup_test(struct CuTest *tc, const char *file, int line); +#define test_setup() test_setup_test(NULL, __FILE__, __LINE__) +#define test_setup_ex(tc) test_setup_test(tc, __FILE__, __LINE__) + void test_cleanup(void); void test_log_stderr(int on); struct log_t * test_log_start(int flags, struct strlist **slist); @@ -61,6 +64,7 @@ extern "C" { struct message * test_find_messagetype(struct message_list *msgs, const char *name); struct message * test_get_last_message(struct message_list *mlist); void test_clear_messages(struct faction *f); + void test_clear_messagelist(struct message_list **msgs); void assert_message(struct CuTest * tc, struct message *msg, char *name, int numpar); void assert_pointer_parameter(struct CuTest * tc, struct message *msg, int index, void *arg); diff --git a/src/travelthru.c b/src/travelthru.c index e55cacaa0..73aa97757 100644 --- a/src/travelthru.c +++ b/src/travelthru.c @@ -1,4 +1,4 @@ -/* +/* Copyright (c) 1998-2015, Enno Rehling Katja Zedel @@ -33,14 +33,14 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include -#include +#include #include #include static void travel_done(attrib *a) { - quicklist *ql = (quicklist *)a->data.v; - ql_free(ql); + selist *ql = (selist *)a->data.v; + selist_free(ql); } /*********************/ @@ -67,7 +67,7 @@ void travelthru_add(region * r, unit * u) region *next[MAXDIRECTIONS]; int d; attrib *a; - quicklist *ql; + selist *ql; assert(r); assert(u); @@ -76,10 +76,10 @@ void travelthru_add(region * r, unit * u) if (!a) { a = a_add(&r->attribs, a_new(&at_travelunit)); } - ql = (quicklist *)a->data.v; + ql = (selist *)a->data.v; fset(r, RF_TRAVELUNIT); - ql_push(&ql, u); + selist_push(&ql, u); a->data.v = ql; /* the first and last region of the faction gets reset, because travelthrough @@ -99,18 +99,31 @@ bool travelthru_cansee(const struct region *r, const struct faction *f, const st return false; } -void travelthru_map(region * r, void(*cb)(region *, struct unit *, void *), void *cbdata) +struct cb_data { + void(*call)(region *, struct unit *, void *); + void *data; + struct region *r; +}; + +static bool cb_map(void *data, void *ex) { + struct cb_data *cb = (struct cb_data *)ex; + struct unit *u = (struct unit *)data; + cb->call(cb->r, u, cb->data); + return true; +} + +void travelthru_map(region * r, void(*cb)(region *, struct unit *, void *), void *data) { attrib *a; + struct cb_data cbdata; + assert(r); + cbdata.call = cb; + cbdata.data = data; + cbdata.r = r; a = a_find(r->attribs, &at_travelunit); if (a) { - quicklist *ql; - ql_iter qi; - ql = (quicklist *)a->data.v; - for (qi = qli_init(&ql); qli_more(qi);) { - unit *u = (unit *)qli_next(&qi); - cb(r, u, cbdata); - } + selist *ql = (selist *)a->data.v; + selist_foreach_ex(ql, cb_map, &cbdata); } } diff --git a/src/travelthru.h b/src/travelthru.h index 4e43dd25a..16452869a 100644 --- a/src/travelthru.h +++ b/src/travelthru.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef H_TRAVELTHRU #define H_TRAVELTHRU diff --git a/src/travelthru.test.c b/src/travelthru.test.c index 74ab29b7e..09d807674 100644 --- a/src/travelthru.test.c +++ b/src/travelthru.test.c @@ -1,4 +1,4 @@ -#include +#include #include #include #include @@ -15,7 +15,7 @@ struct attrib; static void count_travelers(region *r, unit *u, void *cbdata) { int *n = (int *)cbdata; - unused_arg(r); + UNUSED_ARG(r); *n += u->number; } diff --git a/src/triggers/CMakeLists.txt b/src/triggers/CMakeLists.txt index 18561f521..e123698d6 100644 --- a/src/triggers/CMakeLists.txt +++ b/src/triggers/CMakeLists.txt @@ -11,8 +11,6 @@ killunit.c shock.c timeout.c triggers.c -unguard.c -unitmessage.c ) FOREACH(_FILE ${_FILES}) LIST(APPEND _SOURCES ${PROJECT_NAME}/${_FILE}) diff --git a/src/triggers/changefaction.c b/src/triggers/changefaction.c index 13785dfb9..e8b6a4879 100644 --- a/src/triggers/changefaction.c +++ b/src/triggers/changefaction.c @@ -17,12 +17,10 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "changefaction.h" /* kernel includes */ #include -#include #include /* util includes */ @@ -72,7 +70,7 @@ static int changefaction_handle(trigger * t, void *data) else { log_error("could not perform changefaction::handle()\n"); } - unused_arg(data); + UNUSED_ARG(data); return 0; } @@ -94,7 +92,6 @@ static int changefaction_read(trigger * t, gamedata *data) return AT_READ_FAIL; } ur_add(var, &td->faction, resolve_faction); - // read_reference(&td->faction, store, read_faction_reference, resolve_faction); return AT_READ_OK; } diff --git a/src/triggers/changerace.c b/src/triggers/changerace.c index 0e7fc997e..a9f282698 100644 --- a/src/triggers/changerace.c +++ b/src/triggers/changerace.c @@ -17,7 +17,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "changerace.h" /* kernel includes */ @@ -75,7 +74,7 @@ static int changerace_handle(trigger * t, void *data) else { log_error("could not perform changerace::handle()\n"); } - unused_arg(data); + UNUSED_ARG(data); return 0; } diff --git a/src/triggers/changerace.h b/src/triggers/changerace.h index 1b08110b3..e6b19dcb0 100644 --- a/src/triggers/changerace.h +++ b/src/triggers/changerace.h @@ -26,6 +26,7 @@ extern "C" { struct trigger_type; struct trigger; struct unit; + struct race; extern struct trigger_type tt_changerace; diff --git a/src/triggers/clonedied.c b/src/triggers/clonedied.c index 37693fdbf..f3d1fc00b 100644 --- a/src/triggers/clonedied.c +++ b/src/triggers/clonedied.c @@ -17,7 +17,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "clonedied.h" #include "magic.h" @@ -59,7 +58,7 @@ static int clonedied_handle(trigger * t, void *data) } else log_error("could not perform clonedied::handle()\n"); - unused_arg(data); + UNUSED_ARG(data); return 0; } diff --git a/src/triggers/createcurse.c b/src/triggers/createcurse.c index fe39e8b7f..3eb0891ca 100644 --- a/src/triggers/createcurse.c +++ b/src/triggers/createcurse.c @@ -17,7 +17,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "createcurse.h" /* kernel includes */ @@ -77,7 +76,7 @@ static int createcurse_handle(trigger * t, void *data) else { log_error("could not perform createcurse::handle()\n"); } - unused_arg(data); + UNUSED_ARG(data); return 0; } diff --git a/src/triggers/createunit.c b/src/triggers/createunit.c index 2fec00ade..1148b1d5a 100644 --- a/src/triggers/createunit.c +++ b/src/triggers/createunit.c @@ -17,7 +17,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "createunit.h" /* kernel includes */ @@ -75,7 +74,7 @@ static int createunit_handle(trigger * t, void *data) else { log_error("could not perform createunit::handle()\n"); } - unused_arg(data); + UNUSED_ARG(data); return 0; } @@ -103,7 +102,6 @@ static int createunit_read(trigger * t, gamedata *data) else { result = AT_READ_FAIL; } - // read_reference(&td->f, store, read_faction_reference, resolve_faction); read_reference(&td->r, data, read_region_reference, RESOLVE_REGION(data->version)); diff --git a/src/triggers/createunit.h b/src/triggers/createunit.h index 31649b868..d2337d306 100644 --- a/src/triggers/createunit.h +++ b/src/triggers/createunit.h @@ -28,6 +28,7 @@ extern "C" { struct region; struct faction; struct unit; + struct race; extern struct trigger_type tt_createunit; diff --git a/src/triggers/gate.c b/src/triggers/gate.c index acf2bb5d4..c70163a14 100644 --- a/src/triggers/gate.c +++ b/src/triggers/gate.c @@ -10,7 +10,6 @@ without prior permission by the authors of Eressea. */ #include -#include #include "gate.h" /* kernel includes */ @@ -58,7 +57,7 @@ static int gate_handle(trigger * t, void *data) log_error("could not perform gate::handle()\n"); return -1; } - unused_arg(data); + UNUSED_ARG(data); return 0; } diff --git a/src/triggers/giveitem.c b/src/triggers/giveitem.c index d4a56162b..9bc2c56e1 100644 --- a/src/triggers/giveitem.c +++ b/src/triggers/giveitem.c @@ -17,7 +17,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "giveitem.h" /* kernel includes */ @@ -71,7 +70,7 @@ static int giveitem_handle(trigger * t, void *data) else { log_error("could not perform giveitem::handle()\n"); } - unused_arg(data); + UNUSED_ARG(data); return 0; } diff --git a/src/triggers/killunit.c b/src/triggers/killunit.c index 23275a6af..3e6c9defe 100644 --- a/src/triggers/killunit.c +++ b/src/triggers/killunit.c @@ -17,7 +17,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "killunit.h" #include @@ -49,7 +48,7 @@ static int killunit_handle(trigger * t, void *data) /* we can't remove_unit() here, because that's what's calling us. */ set_number(u, 0); } - unused_arg(data); + UNUSED_ARG(data); return 0; } diff --git a/src/triggers/shock.c b/src/triggers/shock.c index 75904e346..31424e979 100644 --- a/src/triggers/shock.c +++ b/src/triggers/shock.c @@ -17,7 +17,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "shock.h" #include "magic.h" @@ -61,8 +60,8 @@ static void do_shock(unit * u, const char *reason) if (u->number > 0) { /* HP - Verlust */ int hp = (unit_max_hp(u) * u->number) / 10; - hp = _min(u->hp, hp); - u->hp = _max(1, hp); + hp = MIN(u->hp, hp); + u->hp = MAX(1, hp); } /* Aura - Verlust */ @@ -84,7 +83,7 @@ static void do_shock(unit * u, const char *reason) } /* Dies ist ein Hack, um das skillmod und familiar-Attribut beim Mage - * zu lschen wenn der Familiar gettet wird. Da sollten wir ber eine + * zu l�schen wenn der Familiar get�tet wird. Da sollten wir �ber eine * saubere Implementation nachdenken. */ if (strcmp(reason, "trigger") == 0) { @@ -103,7 +102,7 @@ static int shock_handle(trigger * t, void *data) if (u && u->number) { do_shock(u, "trigger"); } - unused_arg(data); + UNUSED_ARG(data); return 0; } @@ -118,7 +117,7 @@ static void shock_write(const trigger * t, struct storage *store) next = next->next; } if (next && u) { - log_error("more than one shock-attribut for %s on a unit. FIXED.\n", unitid(u)); + log_error("more than one shock-attribut for %s on a unit. FIXED.\n", itoa36(u->no)); write_unit_reference(NULL, store); } else { diff --git a/src/triggers/timeout.c b/src/triggers/timeout.c index 06fa18363..43bb061c8 100644 --- a/src/triggers/timeout.c +++ b/src/triggers/timeout.c @@ -17,7 +17,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include #include "timeout.h" /* util includes */ @@ -62,7 +61,7 @@ static int timeout_handle(trigger * t, void *data) handle_triggers(&td->triggers, NULL); return -1; } - unused_arg(data); + UNUSED_ARG(data); return 0; } diff --git a/src/triggers/triggers.c b/src/triggers/triggers.c index 152fdcb58..8826fcba2 100644 --- a/src/triggers/triggers.c +++ b/src/triggers/triggers.c @@ -17,7 +17,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #include -#include /* triggers includes */ #include @@ -25,12 +24,10 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include -#include #include #include #include #include -#include #include /* util includes */ @@ -46,11 +43,9 @@ void register_triggers(void) tt_register(&tt_createcurse); tt_register(&tt_createunit); tt_register(&tt_gate); - tt_register(&tt_unguard); tt_register(&tt_giveitem); tt_register(&tt_killunit); tt_register(&tt_shock); - tt_register(&tt_unitmessage); tt_register(&tt_timeout); tt_register(&tt_clonedied); } diff --git a/src/triggers/unguard.c b/src/triggers/unguard.c deleted file mode 100644 index e6471f977..000000000 --- a/src/triggers/unguard.c +++ /dev/null @@ -1,76 +0,0 @@ -/* - +-------------------+ Christian Schlittchen - | | Enno Rehling - | Eressea PBEM host | Katja Zedel - | (c) 1998 - 2003 | Henning Peters - | | Ingo Wilken - +-------------------+ Stefan Reich - - This program may not be used, modified or distributed - without prior permission by the authors of Eressea. - */ -#include -#include -#include "unguard.h" - -/* kernel includes */ -#include -#include -#include -#include - -/* util includes */ -#include -#include -#include -#include -#include - -/* libc includes */ -#include - -static int unguard_handle(trigger * t, void *data) -{ - building *b = (building *)t->data.v; - - if (b) { - fset(b, BLD_UNGUARDED); - } - else { - log_error("could not perform unguard::handle()\n"); - return -1; - } - unused_arg(data); - return 0; -} - -static void unguard_write(const trigger * t, struct storage *store) -{ - write_building_reference((building *)t->data.v, store); -} - -static int unguard_read(trigger * t, gamedata *data) -{ - int rb = read_reference(&t->data.v, data, read_building_reference, - resolve_building); - if (rb == 0 && !t->data.v) { - return AT_READ_FAIL; - } - return AT_READ_OK; -} - -struct trigger_type tt_unguard = { - "building", - NULL, - NULL, - unguard_handle, - unguard_write, - unguard_read -}; - -trigger *trigger_unguard(building * b) -{ - trigger *t = t_new(&tt_unguard); - t->data.v = (void *)b; - return t; -} diff --git a/src/triggers/unguard.h b/src/triggers/unguard.h deleted file mode 100644 index f36f527f8..000000000 --- a/src/triggers/unguard.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - +-------------------+ Christian Schlittchen - | | Enno Rehling - | Eressea PBEM host | Katja Zedel - | (c) 1998 - 2003 | Henning Peters - | | Ingo Wilken - +-------------------+ Stefan Reich - - This program may not be used, modified or distributed - without prior permission by the authors of Eressea. -*/ - -#ifndef UNGUARD_H -#define UNGUARD_H -#ifdef __cplusplus -extern "C" { -#endif - -/* all types we use are defined here to reduce dependencies */ - struct trigger_type; - struct trigger; - struct region; - struct building; - - extern struct trigger_type tt_unguard; - - extern struct trigger *trigger_unguard(struct building *b); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/triggers/unitmessage.c b/src/triggers/unitmessage.c deleted file mode 100644 index 2d869fc49..000000000 --- a/src/triggers/unitmessage.c +++ /dev/null @@ -1,125 +0,0 @@ -/* -+-------------------+ Enno Rehling -| Eressea PBEM host | Christian Schlittchen -| (c) 1998 - 2008 | Katja Zedel -+-------------------+ -This program may not be used, modified or distributed -without prior permission by the authors of Eressea. -*/ - -#include -#include -#include "unitmessage.h" - -/* kernel includes */ -#include -#include -#include - -/* util includes */ -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -/* ansi includes */ -#include -#include -#include -#include - -/*** -** give an item to someone -**/ - -typedef struct unitmessage_data { - struct unit *target; - char *string; - int type; - int level; -} unitmessage_data; - -static void unitmessage_init(trigger * t) -{ - t->data.v = calloc(sizeof(unitmessage_data), 1); -} - -static void unitmessage_free(trigger * t) -{ - unitmessage_data *sd = (unitmessage_data *)t->data.v; - free(sd->string); - free(t->data.v); -} - -static int unitmessage_handle(trigger * t, void *data) -{ - /* call an event handler on unitmessage. - * data.v -> ( variant event, int timer ) - */ - unitmessage_data *td = (unitmessage_data *)t->data.v; - if (td->target && td->target->no) { - struct faction *f = td->target->faction; - const char * str = LOC(f->locale, td->string); - /* bug found in turn 733: sometimes, alps have f*cked up messages */ - if (td->string && td->string[0]) { - addmessage(td->target->region, f, str, td->type, - td->level); - } - } - unused_arg(data); - return 0; -} - -static void unitmessage_write(const trigger * t, struct storage *store) -{ - unitmessage_data *td = (unitmessage_data *)t->data.v; - write_unit_reference(td->target, store); - WRITE_TOK(store, td->string); - WRITE_INT(store, td->type); - WRITE_INT(store, td->level); -} - -static int unitmessage_read(trigger * t, gamedata *data) -{ - unitmessage_data *td = (unitmessage_data *)t->data.v; - char zText[256]; - - int result = read_reference(&td->target, data, read_unit_reference, - resolve_unit); - READ_TOK(data->store, zText, sizeof(zText)); - td->string = _strdup(zText); - READ_INT(data->store, &td->type); - READ_INT(data->store, &td->level); - - if (result == 0 && td->target == NULL) { - return AT_READ_FAIL; - } - return AT_READ_OK; -} - -trigger_type tt_unitmessage = { - "unitmessage", - unitmessage_init, - unitmessage_free, - unitmessage_handle, - unitmessage_write, - unitmessage_read -}; - -trigger *trigger_unitmessage(unit * target, const char *string, int type, - int level) -{ - trigger *t = t_new(&tt_unitmessage); - unitmessage_data *td = (unitmessage_data *)t->data.v; - td->target = target; - td->string = _strdup(string); - td->type = type; - td->level = level; - return t; -} diff --git a/src/triggers/unitmessage.h b/src/triggers/unitmessage.h deleted file mode 100644 index 5b5b0793b..000000000 --- a/src/triggers/unitmessage.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -Copyright (c) 1998-2015, Enno Rehling -Katja Zedel - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -**/ - -#ifndef UNITMESSAGE_H -#define UNITMESSAGE_H -#ifdef __cplusplus -extern "C" { -#endif - - /* all types we use are defined here to reduce dependencies */ - struct trigger_type; - struct trigger; - struct unit; - - extern struct trigger_type tt_unitmessage; - extern struct trigger *trigger_unitmessage(struct unit *target, - const char *string, int type, int level); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/upkeep.c b/src/upkeep.c index 198ce73df..8494d7f25 100644 --- a/src/upkeep.c +++ b/src/upkeep.c @@ -16,7 +16,7 @@ #include "alchemy.h" #include "economy.h" -#include "monster.h" +#include "monsters.h" #include "donations.h" #include @@ -47,7 +47,7 @@ static void help_feed(unit * donor, unit * u, int *need_p) { int need = *need_p; int give = get_money(donor) - lifestyle(donor); - give = _min(need, give); + give = MIN(need, give); if (give > 0) { change_money(donor, -give); @@ -59,7 +59,7 @@ static void help_feed(unit * donor, unit * u, int *need_p) } static const char *hunger_damage(const race *rc) { - const char * damage = get_param(rc->parameters, "hunger.damage"); + const char * damage = rc_hungerdamage(rc); if (!damage) { damage = config_get("hunger.damage"); } @@ -98,11 +98,11 @@ static bool hunger(int number, unit * u) deathcounts(r, dead); } if (hpsub > 0) { - /* Jetzt die Schden der nicht gestorbenen abziehen. */ + /* Jetzt die Sch�den der nicht gestorbenen abziehen. */ u->hp -= hpsub; - /* Meldung nur, wenn noch keine fr Tote generiert. */ + /* Meldung nur, wenn noch keine f�r Tote generiert. */ if (dead == 0) { - /* Durch unzureichende Ernhrung wird %s geschwcht */ + /* Durch unzureichende Ern�hrung wird %s geschw�cht */ ADDMSG(&u->faction->msgs, msg_message("malnourish", "unit region", u, r)); } } @@ -125,13 +125,13 @@ void get_food(region * r) return; } /* 1. Versorgung von eigenen Einheiten. Das vorhandene Silber - * wird zunchst so auf die Einheiten aufgeteilt, dass idealerweise - * jede Einheit genug Silber fr ihren Unterhalt hat. */ + * wird zun�chst so auf die Einheiten aufgeteilt, dass idealerweise + * jede Einheit genug Silber f�r ihren Unterhalt hat. */ for (u = r->units; u; u = u->next) { int need = lifestyle(u); - /* Erstmal zurcksetzen */ + /* Erstmal zur�cksetzen */ freset(u, UFL_HUNGER); if (u->ship && (u->ship->flags & SF_FISHING)) { @@ -161,7 +161,7 @@ void get_food(region * r) * food from the peasants - should not be used with WORK */ if (owner != NULL && (get_alliance(owner, u->faction) & HELP_MONEY)) { int rm = rmoney(r); - int use = _min(rm, need); + int use = MIN(rm, need); rsetmoney(r, rm - use); need -= use; } @@ -174,7 +174,7 @@ void get_food(region * r) for (v = r->units; need && v; v = v->next) { if (v->faction == u->faction && help_money(v)) { int give = get_money(v) - lifestyle(v); - give = _min(need, give); + give = MIN(need, give); if (give > 0) { change_money(v, -give); change_money(u, give); @@ -191,7 +191,7 @@ void get_food(region * r) int need = lifestyle(u); faction *f = u->faction; - need -= _max(0, get_money(u)); + need -= MAX(0, get_money(u)); if (need > 0) { unit *v; @@ -230,7 +230,7 @@ void get_food(region * r) } /* 3. bestimmen, wie viele Bauern gefressen werden. - * bei fehlenden Bauern den Dmon hungern lassen + * bei fehlenden Bauern den D�mon hungern lassen */ for (u = r->units; u; u = u->next) { if (u_race(u) == rc_demon) { @@ -247,7 +247,7 @@ void get_food(region * r) unit *donor = u; while (donor != NULL && hungry > 0) { int blut = get_effect(donor, pt_blood); - blut = _min(blut, hungry); + blut = MIN(blut, hungry); if (blut) { change_effect(donor, pt_blood, -blut); hungry -= blut; @@ -293,9 +293,9 @@ void get_food(region * r) } rsetpeasants(r, peasantfood / 10); - /* 3. Von den berlebenden das Geld abziehen: */ + /* 3. Von den �berlebenden das Geld abziehen: */ for (u = r->units; u; u = u->next) { - int need = _min(get_money(u), lifestyle(u)); + int need = MIN(get_money(u), lifestyle(u)); change_money(u, -need); } } diff --git a/src/upkeep.test.c b/src/upkeep.test.c index 1013314aa..2a91a0df1 100644 --- a/src/upkeep.test.c +++ b/src/upkeep.test.c @@ -1,4 +1,4 @@ -#include +#include #include "upkeep.h" #include @@ -35,7 +35,7 @@ void test_upkeep_default(CuTest * tc) config_set("rules.food.flags", "0"); i_change(&u1->items, i_silver, 20); get_food(r); - // since u1 and u2 are not allied, u1 should not help u2 with upkeep + /* since u1 and u2 are not allied, u1 should not help u2 with upkeep */ CuAssertIntEquals(tc, 10, i_get(u1->items, i_silver)); CuAssertIntEquals(tc, 0, fval(u1, UFL_HUNGER)); CuAssertIntEquals(tc, UFL_HUNGER, fval(u2, UFL_HUNGER)); @@ -63,7 +63,7 @@ void test_upkeep_hunger_damage(CuTest * tc) config_set("rules.food.flags", "0"); u1->hp = 100; get_food(r); - // since u1 and u2 are not allied, u1 should not help u2 with upkeep + /* since u1 and u2 are not allied, u1 should not help u2 with upkeep */ CuAssertTrue(tc, u1->hp < 100); test_cleanup(); @@ -81,10 +81,11 @@ void test_upkeep_from_pool(CuTest * tc) i_silver = it_find("money"); assert(i_silver); r = findregion(0, 0); + assert(r); u1 = test_create_unit(test_create_faction(test_create_race("human")), r); assert(u1); u2 = test_create_unit(u1->faction, r); - assert(r && u1 && u2); + assert(u2); config_set("rules.food.flags", "0"); i_change(&u1->items, i_silver, 30); @@ -151,7 +152,7 @@ void test_upkeep_free(CuTest * tc) u = test_create_unit(test_create_faction(test_create_race("human")), r); assert(r && u); - config_set("rules.food.flags", "4"); // FOOD_IS_FREE + config_set("rules.food.flags", "4"); /* FOOD_IS_FREE */ get_food(r); CuAssertIntEquals(tc, 0, i_get(u->items, i_silver)); CuAssertIntEquals(tc, 0, fval(u, UFL_HUNGER)); diff --git a/src/util/CMakeLists.txt b/src/util/CMakeLists.txt index 7eda87132..91ed118ae 100644 --- a/src/util/CMakeLists.txt +++ b/src/util/CMakeLists.txt @@ -14,7 +14,7 @@ gamedata.test.c language.test.c # lists.test.c # log.test.c -# message.test.c +message.test.c # nrmessage.test.c parser.test.c password.test.c @@ -28,6 +28,7 @@ log.test.c # translation.test.c umlaut.test.c unicode.test.c +variant.test.c # xml.test.c ) @@ -56,6 +57,7 @@ strings.c translation.c umlaut.c unicode.c +variant.c xml.c ) FOREACH(_FILE ${_FILES}) diff --git a/src/util/attrib.c b/src/util/attrib.c index e6392aeeb..b3b9c0a6e 100644 --- a/src/util/attrib.c +++ b/src/util/attrib.c @@ -28,6 +28,119 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include #include +#include + +int read_attribs(gamedata *data, attrib **alist, void *owner) { + int result; + if (data->version < ATHASH_VERSION) { + result = a_read_orig(data, alist, owner); + } + else { + result = a_read(data, alist, owner); + } + if (result == AT_READ_DEPR) { + /* handle deprecated attributes */ + attrib *a = *alist; + while (a) { + if (a->type->upgrade) { + a->type->upgrade(alist, a); + } + a = a->nexttype; + } + } + return result; +} + +void write_attribs(storage *store, attrib *alist, const void *owner) +{ +#if RELEASE_VERSION < ATHASH_VERSION + a_write_orig(store, alist, owner); +#else + a_write(store, alist, owner); +#endif +} + +int a_readint(attrib * a, void *owner, struct gamedata *data) +{ + int n; + READ_INT(data->store, &n); + if (a) a->data.i = n; + return AT_READ_OK; +} + +void a_writeint(const attrib * a, const void *owner, struct storage *store) +{ + WRITE_INT(store, a->data.i); +} + +int a_readshorts(attrib * a, void *owner, struct gamedata *data) +{ + int n; + READ_INT(data->store, &n); + a->data.sa[0] = (short)n; + READ_INT(data->store, &n); + a->data.sa[1] = (short)n; + return AT_READ_OK; +} + +void a_writeshorts(const attrib * a, const void *owner, struct storage *store) +{ + WRITE_INT(store, a->data.sa[0]); + WRITE_INT(store, a->data.sa[1]); +} + +int a_readchars(attrib * a, void *owner, struct gamedata *data) +{ + int i; + for (i = 0; i != 4; ++i) { + int n; + READ_INT(data->store, &n); + a->data.ca[i] = (char)n; + } + return AT_READ_OK; +} + +void a_writechars(const attrib * a, const void *owner, struct storage *store) +{ + int i; + + for (i = 0; i != 4; ++i) { + WRITE_INT(store, a->data.ca[i]); + } +} + +#define DISPLAYSIZE 8192 +int a_readstring(attrib * a, void *owner, struct gamedata *data) +{ + char buf[DISPLAYSIZE]; + char * result = 0; + int e; + size_t len = 0; + do { + e = READ_STR(data->store, buf, sizeof(buf)); + if (result) { + result = realloc(result, len + DISPLAYSIZE - 1); + strcpy(result + len, buf); + len += DISPLAYSIZE - 1; + } + else { + result = strdup(buf); + } + } while (e == ENOMEM); + a->data.v = result; + return AT_READ_OK; +} + +void a_writestring(const attrib * a, const void *owner, struct storage *store) +{ + assert(a->data.v); + WRITE_STR(store, (const char *)a->data.v); +} + +void a_finalizestring(attrib * a) +{ + free(a->data.v); +} #define MAXATHASH 61 static attrib_type *at_hash[MAXATHASH]; @@ -40,7 +153,7 @@ static unsigned int __at_hashkey(const char *s) while (i > 0) { key = (s[--i] + key * 37); } - return key & 0x7fffffff; //TODO: V112 http://www.viva64.com/en/V112 Dangerous magic number 0x7fffffff used: return key & 0x7fffffff;. + return key & 0x7fffffff; } void at_register(attrib_type * at) @@ -48,7 +161,7 @@ void at_register(attrib_type * at) attrib_type *find; if (at->read == NULL) { - log_warning("registering non-persistent attribute %s.\n", at->name); //TODO: V111 http://www.viva64.com/en/V111 Call of function 'log_warning' with variable number of arguments. Second argument has memsize type. + log_warning("registering non-persistent attribute %s.\n", at->name); } at->hashkey = __at_hashkey(at->name); find = at_hash[at->hashkey % MAXATHASH]; @@ -56,7 +169,7 @@ void at_register(attrib_type * at) find = find->nexthash; } if (find && find == at) { - log_warning("attribute '%s' was registered more than once\n", at->name); //TODO: V111 http://www.viva64.com/en/V111 Call of function 'log_warning' with variable number of arguments. Second argument has memsize type. + log_warning("attribute '%s' was registered more than once\n", at->name); return; } else { @@ -66,7 +179,7 @@ void at_register(attrib_type * at) at_hash[at->hashkey % MAXATHASH] = at; } -static attrib_type *at_find(unsigned int hk) +static attrib_type *at_find_key(unsigned int hk) { const char *translate[3][2] = { { "zielregion", "targetregion" }, /* remapping: from 'zielregion, heute targetregion */ @@ -80,13 +193,18 @@ static attrib_type *at_find(unsigned int hk) int i = 0; while (translate[i][0]) { if (__at_hashkey(translate[i][0]) == hk) - return at_find(__at_hashkey(translate[i][1])); + return at_find_key(__at_hashkey(translate[i][1])); ++i; } } return find; } +struct attrib_type *at_find(const char *name) { + unsigned int hash = __at_hashkey(name); + return at_find_key(hash); +} + attrib *a_select(attrib * a, const void *data, bool(*compare) (const attrib *, const void *)) { @@ -97,6 +215,7 @@ attrib *a_select(attrib * a, const void *data, attrib *a_find(attrib * a, const attrib_type * at) { + assert(at); while (a && a->type != at) a = a->nexttype; return a; @@ -295,7 +414,7 @@ void at_deprecate(const char * name, int(*reader)(attrib *, void *, struct gamed static int a_read_i(gamedata *data, attrib ** attribs, void *owner, unsigned int key) { int retval = AT_READ_OK; int(*reader)(attrib *, void *, struct gamedata *) = 0; - attrib_type *at = at_find(key); + attrib_type *at = at_find_key(key); attrib * na = 0; if (at) { diff --git a/src/util/attrib.h b/src/util/attrib.h index b9378ab55..6043a960f 100644 --- a/src/util/attrib.h +++ b/src/util/attrib.h @@ -19,6 +19,8 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef ATTRIB_H #define ATTRIB_H +#include + #ifdef __cplusplus extern "C" { #endif @@ -30,14 +32,14 @@ extern "C" { typedef struct attrib { const struct attrib_type *type; union { - afun f; //TODO: V117 http://www.viva64.com/en/V117 Memsize type is used in the union. - void *v; //TODO: V117 http://www.viva64.com/en/V117 Memsize type is used in the union. + afun f; + void *v; int i; float flt; char c; short s; short sa[2]; - char ca[4]; //TODO: V112 http://www.viva64.com/en/V112 Dangerous magic number 4 used: char ca[4];. + char ca[4]; } data; /* internal data, do not modify: */ struct attrib *next; /* next attribute in the list */ @@ -63,16 +65,19 @@ extern "C" { unsigned int hashkey; } attrib_type; - extern void at_register(attrib_type * at); - extern void at_deprecate(const char * name, int(*reader)(attrib *, void *, struct gamedata *)); + void at_register(attrib_type * at); + void at_deprecate(const char * name, int(*reader)(attrib *, void *, struct gamedata *)); + struct attrib_type *at_find(const char *name); - extern attrib *a_select(attrib * a, const void *data, - bool(*compare) (const attrib *, const void *)); - extern attrib *a_find(attrib * a, const attrib_type * at); - extern attrib *a_add(attrib ** pa, attrib * at); - extern int a_remove(attrib ** pa, attrib * at); - extern void a_removeall(attrib ** a, const attrib_type * at); - extern attrib *a_new(const attrib_type * at); + void write_attribs(struct storage *store, struct attrib *alist, const void *owner); + int read_attribs(struct gamedata *store, struct attrib **alist, void *owner); + + attrib *a_select(attrib * a, const void *data, bool(*compare) (const attrib *, const void *)); + attrib *a_find(attrib * a, const attrib_type * at); + attrib *a_add(attrib ** pa, attrib * at); + int a_remove(attrib ** pa, attrib * at); + void a_removeall(attrib ** a, const attrib_type * at); + attrib *a_new(const attrib_type * at); int a_age(attrib ** attribs, void *owner); int a_read_orig(struct gamedata *data, attrib ** attribs, void *owner); @@ -81,6 +86,20 @@ extern "C" { int a_read(struct gamedata *data, attrib ** attribs, void *owner); void a_write(struct storage *store, const attrib * attribs, const void *owner); + int a_readint(struct attrib *a, void *owner, struct gamedata *); + void a_writeint(const struct attrib *a, const void *owner, + struct storage *store); + int a_readshorts(struct attrib *a, void *owner, struct gamedata *); + void a_writeshorts(const struct attrib *a, const void *owner, + struct storage *store); + int a_readchars(struct attrib *a, void *owner, struct gamedata *); + void a_writechars(const struct attrib *a, const void *owner, + struct storage *store); + int a_readstring(struct attrib *a, void *owner, struct gamedata *); + void a_writestring(const struct attrib *a, const void *owner, + struct storage *); + void a_finalizestring(struct attrib *a); + void attrib_done(void); #define DEFAULT_AGE NULL diff --git a/src/util/attrib.test.c b/src/util/attrib.test.c index 0f189015a..b44afeec2 100644 --- a/src/util/attrib.test.c +++ b/src/util/attrib.test.c @@ -1,8 +1,13 @@ #include #include "attrib.h" +#include + +#include +#include #include #include +#include static void test_attrib_new(CuTest * tc) { @@ -16,7 +21,6 @@ static void test_attrib_new(CuTest * tc) CuAssertPtrEquals(tc, 0, a); } - static void test_attrib_add(CuTest * tc) { attrib_type at_foo = { "foo" }; @@ -52,7 +56,6 @@ static void test_attrib_remove_self(CuTest * tc) { a_removeall(&alist, NULL); } - static void test_attrib_removeall(CuTest * tc) { const attrib_type at_foo = { "foo" }; const attrib_type at_bar = { "bar" }; @@ -110,6 +113,86 @@ static void test_attrib_nexttype(CuTest * tc) a_removeall(&alist, &at_bar); } +static void test_attrib_rwstring(CuTest *tc) { + gamedata data; + storage store; + attrib a = { 0 }; + + test_setup(); + a.data.v = strdup("Hello World"); + mstream_init(&data.strm); + gamedata_init(&data, &store, RELEASE_VERSION); + a_writestring(&a, NULL, &store); + a_finalizestring(&a); + data.strm.api->rewind(data.strm.handle); + a_readstring(&a, NULL, &data); + CuAssertStrEquals(tc, "Hello World", (const char *)a.data.v); + mstream_done(&data.strm); + gamedata_done(&data); + test_cleanup(); +} + +static void test_attrib_rwint(CuTest *tc) { + gamedata data; + storage store; + attrib a = { 0 }; + + test_setup(); + a.data.i = 42; + mstream_init(&data.strm); + gamedata_init(&data, &store, RELEASE_VERSION); + a_writeint(&a, NULL, &store); + a.data.i = 0; + data.strm.api->rewind(data.strm.handle); + a_readint(&a, NULL, &data); + CuAssertIntEquals(tc, 42, a.data.i); + mstream_done(&data.strm); + gamedata_done(&data); + test_cleanup(); +} + +static void test_attrib_rwchars(CuTest *tc) { + gamedata data; + storage store; + attrib a = { 0 }; + + test_setup(); + a.data.ca[0] = 1; + a.data.ca[3] = 42; + mstream_init(&data.strm); + gamedata_init(&data, &store, RELEASE_VERSION); + a_writeint(&a, NULL, &store); + memset(a.data.ca, 0, 4); + data.strm.api->rewind(data.strm.handle); + a_readint(&a, NULL, &data); + CuAssertIntEquals(tc, 1, a.data.ca[0]); + CuAssertIntEquals(tc, 42, a.data.ca[3]); + mstream_done(&data.strm); + gamedata_done(&data); + test_cleanup(); +} + +static void test_attrib_rwshorts(CuTest *tc) { + gamedata data; + storage store; + attrib a = { 0 }; + a.data.sa[0] = -4; + a.data.sa[1] = 42; + + test_setup(); + mstream_init(&data.strm); + gamedata_init(&data, &store, RELEASE_VERSION); + a_writeint(&a, NULL, &store); + memset(a.data.ca, 0, 4); + data.strm.api->rewind(data.strm.handle); + a_readint(&a, NULL, &data); + CuAssertIntEquals(tc, -4, a.data.sa[0]); + CuAssertIntEquals(tc, 42, a.data.sa[1]); + mstream_done(&data.strm); + gamedata_done(&data); + test_cleanup(); +} + CuSuite *get_attrib_suite(void) { CuSuite *suite = CuSuiteNew(); @@ -119,5 +202,9 @@ CuSuite *get_attrib_suite(void) SUITE_ADD_TEST(suite, test_attrib_removeall); SUITE_ADD_TEST(suite, test_attrib_remove_self); SUITE_ADD_TEST(suite, test_attrib_nexttype); + SUITE_ADD_TEST(suite, test_attrib_rwstring); + SUITE_ADD_TEST(suite, test_attrib_rwint); + SUITE_ADD_TEST(suite, test_attrib_rwchars); + SUITE_ADD_TEST(suite, test_attrib_rwshorts); return suite; } diff --git a/src/util/base36.c b/src/util/base36.c index 7edb46027..285e9760e 100644 --- a/src/util/base36.c +++ b/src/util/base36.c @@ -39,9 +39,9 @@ int atoi36(const char *str) while (isalnum(*(unsigned char *)s)) { if (isupper(*(unsigned char *)s)) i = i * 36 + (*s) - 'A' + 10; - else if (islower(*(unsigned char *)s)) + else if (islower(*s)) i = i * 36 + (*s) - 'a' + 10; - else if (isdigit(*(unsigned char *)s)) + else if (isdigit(*s)) i = i * 36 + (*s) - '0'; else break; diff --git a/src/util/bsdstring.c b/src/util/bsdstring.c index 98d2d00f5..0f3d49801 100644 --- a/src/util/bsdstring.c +++ b/src/util/bsdstring.c @@ -13,7 +13,7 @@ int wrptr(char **ptr, size_t * size, int result) { size_t bytes = (size_t)result; if (result < 0) { - // _snprintf buffer was too small + /* buffer was too small */ if (*size > 0) { **ptr = 0; *size = 0; diff --git a/src/util/bsdstring.test.c b/src/util/bsdstring.test.c index 0fffd187c..d4276ef61 100644 --- a/src/util/bsdstring.test.c +++ b/src/util/bsdstring.test.c @@ -32,7 +32,7 @@ static void test_strlcpy(CuTest * tc) CuAssertIntEquals(tc, 4, (int)strlcpy(buffer, "herp", 4)); CuAssertStrEquals(tc, "her", buffer); - CuAssertIntEquals(tc, 4, (int)strlcpy(buffer, "herp", 8)); + CuAssertIntEquals(tc, 4, (int)strlcpy(buffer, "herp", 8)); /*-V666 */ CuAssertStrEquals(tc, "herp", buffer); CuAssertIntEquals(tc, 0x7f, buffer[5]); diff --git a/src/util/crmessage.c b/src/util/crmessage.c index 98afe0f05..47bb6bf7d 100644 --- a/src/util/crmessage.c +++ b/src/util/crmessage.c @@ -145,21 +145,21 @@ int cr_render(const message * msg, char *buffer, const void *userdata) int cr_string(variant var, char *buffer, const void *userdata) { sprintf(buffer, "\"%s\"", (const char *)var.v); - unused_arg(userdata); + UNUSED_ARG(userdata); return 0; } int cr_int(variant var, char *buffer, const void *userdata) { sprintf(buffer, "%d", var.i); - unused_arg(userdata); + UNUSED_ARG(userdata); return 0; } int cr_ignore(variant var, char *buffer, const void *userdata) { - unused_arg(var); - unused_arg(buffer); - unused_arg(userdata); + UNUSED_ARG(var); + UNUSED_ARG(buffer); + UNUSED_ARG(userdata); return -1; } diff --git a/src/util/dice.c b/src/util/dice.c index e28a4bccd..6fa50261d 100644 --- a/src/util/dice.c +++ b/src/util/dice.c @@ -49,7 +49,7 @@ static int term_eval(const char **sptr) int state = 1; for (;;) { - if (isdigit(*(unsigned char *)c)) { + if (isdigit(*(const unsigned char *)c)) { k = k * 10 + (*c - '0'); } else if (*c == '+' || *c == '-' || *c == 0 || *c == '*' || *c == ')' diff --git a/src/util/event.c b/src/util/event.c index ad5a9e725..78a6d6fbc 100644 --- a/src/util/event.c +++ b/src/util/event.c @@ -153,7 +153,7 @@ static int read_handler(attrib * a, void *owner, gamedata *data) handler_info *hi = (handler_info *)a->data.v; READ_TOK(store, zText, sizeof(zText)); - hi->event = _strdup(zText); + hi->event = strdup(zText); read_triggers(data, &hi->triggers); if (hi->triggers != NULL) { return AT_READ_OK; @@ -200,7 +200,7 @@ void add_trigger(struct attrib **ap, const char *eventname, struct trigger *t) if (a == NULL || a->type != &at_eventhandler) { a = a_add(ap, a_new(&at_eventhandler)); td = (handler_info *)a->data.v; - td->event = _strdup(eventname); + td->event = strdup(eventname); } tp = &td->triggers; while (*tp) @@ -244,7 +244,7 @@ void tt_register(trigger_type * tt) trigger_type *tt_find(const char *name) { trigger_type *tt = triggertypes; - while (tt && strcmp(tt->name, name)) + while (tt && strcmp(tt->name, name)!=0) tt = tt->next; return tt; } diff --git a/src/util/filereader.c b/src/util/filereader.c index ee5ec398c..d36d3ca71 100644 --- a/src/util/filereader.c +++ b/src/util/filereader.c @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -18,7 +19,7 @@ static void unicode_warning(const char *bp) log_warning("invalid sequence in UTF-8 string: %s\n", bp); } -INLINE_FUNCTION int eatwhite(const char *ptr, size_t * total_size) +static int eatwhite(const char *ptr, size_t * total_size) { int ret = 0; @@ -30,7 +31,7 @@ INLINE_FUNCTION int eatwhite(const char *ptr, size_t * total_size) ret = unicode_utf8_to_ucs4(&ucs, ptr, &size); if (ret != 0) break; - if (!iswxspace((wint_t)ucs)) + if (!iswspace((wint_t)ucs)) break; *total_size += size; ptr += size; @@ -52,7 +53,7 @@ static const char *getbuf_latin1(FILE * F) if (bp == NULL) return NULL; - while (*bp && isxspace(*(unsigned char *)bp)) + while (*bp && isspace(*(unsigned char *)bp)) ++bp; /* eatwhite */ comment = (bool)(comment && cont); @@ -113,15 +114,15 @@ static const char *getbuf_latin1(FILE * F) if (iscntrl(c)) { if (!comment && cp < fbuf + MAXLINE) { - *cp++ = isxspace(c) ? ' ' : '?'; + *cp++ = isspace(c) ? ' ' : '?'; } ++bp; continue; } - else if (isxspace(c)) { + else if (isspace(c)) { if (!quote) { ++bp; - while (*bp && isxspace(*(unsigned char *)bp)) + while (*bp && isspace(*(unsigned char *)bp)) ++bp; /* eatwhite */ if (!comment && *bp && *bp != COMMENT_CHAR && cp < fbuf + MAXLINE) *(cp++) = ' '; @@ -136,7 +137,7 @@ static const char *getbuf_latin1(FILE * F) } else if (c == CONTINUE_CHAR) { const char *end = ++bp; - while (*end && isxspace(*(unsigned char *)end)) + while (*end && isspace(*(unsigned char *)end)) ++end; /* eatwhite */ if (*end == '\0') { bp = end; @@ -269,7 +270,7 @@ static const char *getbuf_utf8(FILE * F) break; } - if (iswxspace((wint_t)ucs)) { + if (iswspace((wint_t)ucs)) { if (!quote) { bp += size; ret = eatwhite(bp, &size); diff --git a/src/util/functions.c b/src/util/functions.c index 82792faaf..3776820eb 100644 --- a/src/util/functions.c +++ b/src/util/functions.c @@ -51,4 +51,5 @@ void register_function(pf_generic fun, const char *name) void free_functions(void) { cb_clear(&cb_functions); -} \ No newline at end of file +} + diff --git a/src/util/gamedata.h b/src/util/gamedata.h index bb1632838..75a750452 100644 --- a/src/util/gamedata.h +++ b/src/util/gamedata.h @@ -32,10 +32,11 @@ #define NOCRYPT_VERSION 352 /* passwords are plaintext again */ #define ATHASH_VERSION 353 /* attribute-type hash, not name */ #define NOWATCH_VERSION 354 /* plane->watchers is gone */ +#define KEYVAL_VERSION 355 /* at_keys has values */ /* unfinished: */ #define CRYPT_VERSION 400 /* passwords are encrypted */ -#define RELEASE_VERSION NOWATCH_VERSION /* current datafile */ +#define RELEASE_VERSION KEYVAL_VERSION /* current datafile */ #define MIN_VERSION INTPAK_VERSION /* minimal datafile we support */ #define MAX_VERSION RELEASE_VERSION /* change this if we can need to read the future datafile, and we can do so */ diff --git a/src/util/goodies.c b/src/util/goodies.c index 2444d0f47..c478bcf83 100644 --- a/src/util/goodies.c +++ b/src/util/goodies.c @@ -113,7 +113,7 @@ int set_email(char **pemail, const char *newmail) free(*pemail); *pemail = 0; if (newmail) { - *pemail = _strdup(newmail); + *pemail = strdup(newmail); } return 0; } diff --git a/src/util/language.c b/src/util/language.c index d8b899742..b3cce61af 100644 --- a/src/util/language.c +++ b/src/util/language.c @@ -86,7 +86,7 @@ locale *get_or_create_locale(const char *name) *lp = l = (locale *)calloc(sizeof(locale), 1); assert_alloc(l); l->hashkey = hkey; - l->name = _strdup(name); + l->name = strdup(name); l->index = nextlocaleindex++; assert(nextlocaleindex <= MAXLOCALES); if (default_locale == NULL) default_locale = l; @@ -101,16 +101,23 @@ locale *get_or_create_locale(const char *name) void make_locales(const char *str) { const char *tok = str; - while (*tok) { - char zText[32]; - while (*tok && *tok != ',') - ++tok; - strncpy(zText, str, tok - str); - zText[tok - str] = 0; - get_or_create_locale(zText); - if (*tok) { - str = ++tok; + while (tok) { + char zText[16]; + size_t len; + + tok = strchr(str, ','); + if (tok) { + len = tok - str; + assert(sizeof(zText) > len); + memcpy(zText, str, len); + str = tok + 1; } + else { + len = strlen(str); + memcpy(zText, str, len); + } + zText[len] = 0; + get_or_create_locale(zText); } } @@ -202,15 +209,15 @@ void locale_setstring(locale * lang, const char *key, const char *value) find->nexthash = lang->strings[id]; lang->strings[id] = find; find->hashkey = hkey; - find->key = _strdup(key); - find->str = _strdup(value); + find->key = strdup(key); + find->str = strdup(value); } else { if (strcmp(find->str, value) != 0) { log_warning("multiple translations for key %s\n", key); } free(find->str); - find->str = _strdup(value); + find->str = strdup(value); } } @@ -232,7 +239,7 @@ char *mkname_buf(const char *space, const char *name, char *buffer) const char *mkname(const char *space, const char *name) { - static char zBuffer[128]; // FIXME: static return value + static char zBuffer[128]; /* FIXME: static return value */ return mkname_buf(space, name, zBuffer); } @@ -265,7 +272,7 @@ void add_translation(struct critbit_tree **cbp, const char *key, int i) { if (str) { size_t len = strlen(str); if (!cb) { - // TODO: this will leak, because we do not know how to clean it up */ + /* TODO: this will leak, because we do not know how to clean it up */ *cbp = cb = (struct critbit_tree *)calloc(1, sizeof(struct critbit_tree)); } len = cb_new_kv(str, len, &i, sizeof(int), buffer); @@ -285,13 +292,17 @@ void init_translations(const struct locale *lang, int ut, const char * (*string_ assert(maxstrings > 0); tokens = get_translations(lang, ut); for (i = 0; i != maxstrings; ++i) { - // TODO: swap the name of s and key + /* TODO: swap the name of s and key */ const char * s = string_cb(i); if (s) { - struct critbit_tree ** cb = (struct critbit_tree **)tokens; const char * key = locale_string(lang, s, false); - if (!key) key = s; - add_translation(cb, key, i); + if (key) { + struct critbit_tree ** cb = (struct critbit_tree **)tokens; + add_translation(cb, key, i); + } + else { + log_warning("no translation for %s in locale %s", s, lang->name); + } } } } @@ -316,10 +327,10 @@ static int locale_init = 0; void init_locales(void) { - int l; + locale * lang; if (locale_init) return; - for (l = 0; localenames[l]; ++l) { - struct locale *lang = get_or_create_locale(localenames[l]); + assert(locales); + for (lang = locales; lang; lang = lang->next) { init_locale(lang); } locale_init = 1; @@ -338,7 +349,7 @@ void free_locales(void) { for (i = UT_PARAMS; i != UT_RACES; ++i) { struct critbit_tree ** cb = (struct critbit_tree **)get_translations(locales, i); if (*cb) { - // TODO: this crashes? + /* TODO: this crashes? */ cb_clear(*cb); free(*cb); } @@ -362,5 +373,5 @@ void free_locales(void) { free(locales); locales = next; } - memset(lstrs, 0, sizeof(lstrs)); // TODO: does this data need to be free'd? + memset(lstrs, 0, sizeof(lstrs)); /* TODO: does this data need to be free'd? */ } diff --git a/src/util/language.h b/src/util/language.h index a8d9096e7..36bc58378 100644 --- a/src/util/language.h +++ b/src/util/language.h @@ -19,7 +19,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef MY_LOCALE_H #define MY_LOCALE_H -#include +#include #ifdef __cplusplus extern "C" { @@ -30,33 +30,34 @@ extern "C" { struct locale; struct critbit_tree; + extern const char *localenames[]; + extern struct locale *default_locale; + extern struct locale *locales; + extern struct locale *nextlocale(const struct locale *lang); + /** managing multiple locales: **/ - extern struct locale *get_locale(const char *name); - extern struct locale *get_or_create_locale(const char *key); + struct locale *get_locale(const char *name); + struct locale *get_or_create_locale(const char *key); void init_locales(void); void free_locales(void); void reset_locales(void); /** operations on locales: **/ - extern void locale_setstring(struct locale *lang, const char *key, + void locale_setstring(struct locale *lang, const char *key, const char *value); - extern const char *locale_getstring(const struct locale *lang, + const char *locale_getstring(const struct locale *lang, const char *key); - extern const char *locale_string(const struct locale *lang, const char *key, bool warn); /* does fallback */ - extern unsigned int locale_index(const struct locale *lang); - extern const char *locale_name(const struct locale *lang); + const char *locale_string(const struct locale *lang, const char *key, bool warn); /* does fallback */ + unsigned int locale_index(const struct locale *lang); + const char *locale_name(const struct locale *lang); - extern const char *mkname(const char *namespc, const char *key); - extern char *mkname_buf(const char *namespc, const char *key, char *buffer); + const char *mkname(const char *namespc, const char *key); + char *mkname_buf(const char *namespc, const char *key, char *buffer); - extern void make_locales(const char *str); + void make_locales(const char *str); #define LOC(lang, s) (lang?locale_string(lang, s, true):s) - extern struct locale *default_locale; - extern struct locale *locales; - extern struct locale *nextlocale(const struct locale *lang); - enum { UT_PARAMS, UT_KEYWORDS, diff --git a/src/util/language.test.c b/src/util/language.test.c index d86f1b2a7..40a6775fa 100644 --- a/src/util/language.test.c +++ b/src/util/language.test.c @@ -1,5 +1,4 @@ #include -#include #include "language.h" #include @@ -17,9 +16,20 @@ static void test_language(CuTest *tc) test_cleanup(); } +static void test_make_locales(CuTest *tc) +{ + test_setup(); + make_locales("aa,bb,cc"); + CuAssertPtrNotNull(tc, get_locale("aa")); + CuAssertPtrNotNull(tc, get_locale("bb")); + CuAssertPtrNotNull(tc, get_locale("cc")); + test_cleanup(); +} + CuSuite *get_language_suite(void) { CuSuite *suite = CuSuiteNew(); SUITE_ADD_TEST(suite, test_language); + SUITE_ADD_TEST(suite, test_make_locales); return suite; } diff --git a/src/util/lists.c b/src/util/lists.c index d61327fa0..be3deeffd 100644 --- a/src/util/lists.c +++ b/src/util/lists.c @@ -127,7 +127,7 @@ void addstrlist(strlist ** SP, const char *s) { strlist *slist = malloc(sizeof(strlist)); slist->next = NULL; - slist->s = _strdup(s); + slist->s = strdup(s); addlist(SP, slist); } diff --git a/src/util/log.c b/src/util/log.c index f61d50848..24ddce757 100644 --- a/src/util/log.c +++ b/src/util/log.c @@ -64,11 +64,11 @@ void log_destroy(log_t *handle) { #define LOG_MAXBACKUPS 5 static int -cp_convert(const char *format, char *buffer, size_t length, int codepage) +cp_convert(const char *format, unsigned char *buffer, size_t length, int codepage) { /* when console output on MSDOS, convert to codepage */ const char *input = format; - char *pos = buffer; + unsigned char *pos = buffer; while (pos + 1 < buffer + length && *input) { size_t size = 0; @@ -137,7 +137,7 @@ static int check_dupe(const char *format, int level) static char last_message[32]; /* STATIC_XCALL: used across calls */ static int dupes = 0; /* STATIC_XCALL: used across calls */ if (strncmp(last_message, format, sizeof(last_message)) == 0) { - // TODO: C6054: String 'last_message' might not be zero - terminated. + /* TODO: C6054: String 'last_message' might not be zero - terminated. */ ++dupes; return 1; } @@ -157,10 +157,10 @@ static void _log_write(FILE * stream, int codepage, const char *format, va_list { if (codepage) { char buffer[MAXLENGTH]; - char converted[MAXLENGTH]; + unsigned char converted[MAXLENGTH]; vsnprintf(buffer, sizeof(buffer), format, args); if (cp_convert(buffer, converted, MAXLENGTH, codepage) == 0) { - fputs(converted, stream); + fputs((char *)converted, stream); } else { /* fall back to non-converted output */ @@ -197,16 +197,16 @@ static void log_write(int flags, const char *module, const char *format, va_list int level = flags & LOG_LEVELS; if (lg->flags & level) { int dupe = 0; - va_list copy; - - va_copy(copy, args); if (lg->flags & LOG_BRIEF) { dupe = check_dupe(format, level); } if (dupe == 0) { + va_list copy; + + va_copy(copy, args); lg->log(lg->data, level, NULL, format, copy); + va_end(copy); } - va_end(copy); } } } @@ -220,7 +220,7 @@ void log_fatal(const char *format, ...) va_end(args); } -void log_error(const char *format, ...) +void log_error(const char *format, ...) /*-V524 */ { va_list args; va_start(args, format); diff --git a/src/util/log.test.c b/src/util/log.test.c index 95cbefa96..1558ee3e3 100644 --- a/src/util/log.test.c +++ b/src/util/log.test.c @@ -9,10 +9,10 @@ void log_string(void *data, int level, const char *module, const char *format, va_list args) { char *str = (char *)data; const char *arg = va_arg(args, const char *); - unused_arg(format); - unused_arg(module); - unused_arg(level); - strncpy(str, arg, 32); + UNUSED_ARG(format); + UNUSED_ARG(module); + UNUSED_ARG(level); + strcpy(str, arg); } static void test_logging(CuTest * tc) diff --git a/src/util/message.c b/src/util/message.c index f19fc3313..c5285835e 100644 --- a/src/util/message.c +++ b/src/util/message.c @@ -16,7 +16,7 @@ #include "strings.h" #include "log.h" -#include "quicklist.h" +#include "selist.h" /* libc includes */ #include @@ -73,7 +73,7 @@ message_type *mt_new(const char *name, const char *args[]) while (args[nparameters]) ++nparameters; } mtype->key = 0; - mtype->name = _strdup(name); + mtype->name = strdup(name); mtype->nparameters = nparameters; if (nparameters > 0) { mtype->pnames = (char **)malloc(sizeof(char *) * nparameters); @@ -87,19 +87,21 @@ message_type *mt_new(const char *name, const char *args[]) for (i = 0; args[i]; ++i) { const char *x = args[i]; const char *spos = strchr(x, ':'); - if (spos == NULL) { - mtype->pnames[i] = _strdup(x); - mtype->types[i] = NULL; + struct arg_type *atype = NULL; + if (spos != NULL) { + atype = find_argtype(spos + 1); + } + if (!atype) { + log_error("unknown argument type %s for message type %s\n", spos + 1, mtype->name); + assert(atype); } else { - char *cp = strncpy((char *)malloc(spos - x + 1), x, spos - x); + char *cp; + cp = malloc(spos - x + 1); + memcpy(cp, x, spos - x); cp[spos - x] = '\0'; mtype->pnames[i] = cp; - mtype->types[i] = find_argtype(spos + 1); - if (mtype->types[i] == NULL) { - log_error("unknown argument type %s for message type %s\n", spos + 1, mtype->name); - } - assert(mtype->types[i]); + mtype->types[i] = atype; } } } @@ -160,7 +162,7 @@ message *msg_create(const struct message_type *mtype, variant args[]) } #define MT_MAXHASH 1021 -static quicklist *messagetypes[MT_MAXHASH]; +static selist *messagetypes[MT_MAXHASH]; static void mt_free(void *val) { message_type *mtype = (message_type *)val; @@ -177,9 +179,9 @@ static void mt_free(void *val) { void mt_clear(void) { int i; for (i = 0; i != MT_MAXHASH; ++i) { - quicklist *ql = messagetypes[i]; - ql_foreach(ql, mt_free); - ql_free(ql); + selist *ql = messagetypes[i]; + selist_foreach(ql, mt_free); + selist_free(ql); messagetypes[i] = 0; } } @@ -187,11 +189,11 @@ void mt_clear(void) { const message_type *mt_find(const char *name) { unsigned int hash = hashstring(name) % MT_MAXHASH; - quicklist *ql = messagetypes[hash]; + selist *ql = messagetypes[hash]; int qi; - for (qi = 0; ql; ql_advance(&ql, &qi, 1)) { - message_type *data = (message_type *)ql_get(ql, qi); + for (qi = 0; ql; selist_advance(&ql, &qi, 1)) { + message_type *data = (message_type *)selist_get(ql, qi); if (strcmp(data->name, name) == 0) { return data; } @@ -213,9 +215,9 @@ static unsigned int mt_id(const message_type * mtype) const message_type *mt_register(message_type * type) { unsigned int hash = hashstring(type->name) % MT_MAXHASH; - quicklist **qlp = messagetypes + hash; + selist **qlp = messagetypes + hash; - if (ql_set_insert(qlp, type)) { + if (selist_set_insert(qlp, type, NULL)) { type->key = mt_id(type); } return type; diff --git a/src/util/message.test.c b/src/util/message.test.c new file mode 100644 index 000000000..d114e33f2 --- /dev/null +++ b/src/util/message.test.c @@ -0,0 +1,29 @@ +#include +#include "message.h" + +#include +#include + +static void test_mt_new(CuTest *tc) +{ + message_type *mt; + test_setup(); + mt = mt_new_va("test", "name:string", "number:int", NULL); + CuAssertPtrNotNull(tc, mt); + CuAssertStrEquals(tc, "test", mt->name); + CuAssertIntEquals(tc, 2, mt->nparameters); + CuAssertPtrNotNull(tc, mt->pnames); + CuAssertStrEquals(tc, "name", mt->pnames[0]); + CuAssertStrEquals(tc, "number", mt->pnames[1]); + CuAssertPtrNotNull(tc, mt->types); + CuAssertStrEquals(tc, "string", mt->types[0]->name); + CuAssertStrEquals(tc, "int", mt->types[1]->name); + test_cleanup(); +} + +CuSuite *get_message_suite(void) +{ + CuSuite *suite = CuSuiteNew(); + SUITE_ADD_TEST(suite, test_mt_new); + return suite; +} diff --git a/src/util/nrmessage.c b/src/util/nrmessage.c index e3b0bcc0b..717c4dc1f 100644 --- a/src/util/nrmessage.c +++ b/src/util/nrmessage.c @@ -91,7 +91,7 @@ const nrsection *section_add(const char *name) } if (!*mcp) { nrsection *mc = calloc(sizeof(nrsection), 1); - mc->name = _strdup(name); + mc->name = strdup(name); *mcp = mc; } return *mcp; @@ -130,14 +130,14 @@ const char *string, int level, const char *section) nrt->section = NULL; nrtypes[hash] = nrt; assert(string && *string); - nrt->string = _strdup(string); + nrt->string = strdup(string); *c = '\0'; for (i = 0; i != mtype->nparameters; ++i) { if (i != 0) *c++ = ' '; c += strlcpy(c, mtype->pnames[i], sizeof(zNames)-(c-zNames)); } - nrt->vars = _strdup(zNames); + nrt->vars = strdup(zNames); } } @@ -178,3 +178,16 @@ const char *nrt_section(const nrmessage_type * nrt) { return nrt ? nrt->section : NULL; } + +void free_nrmesssages(void) { + int i; + for (i = 0; i != NRT_MAXHASH; ++i) { + while (nrtypes[i]) { + nrmessage_type *nr = nrtypes[i]; + nrtypes[i] = nr->next; + free(nr->string); + free(nr->vars); + free(nr); + } + } +} diff --git a/src/util/nrmessage.h b/src/util/nrmessage.h index 5d775be9e..6cc02bfe2 100644 --- a/src/util/nrmessage.h +++ b/src/util/nrmessage.h @@ -12,6 +12,9 @@ #ifndef H_UTIL_NRMESSAGE #define H_UTIL_NRMESSAGE + +#include + #ifdef __cplusplus extern "C" { #endif @@ -28,18 +31,20 @@ extern "C" { extern nrsection *sections; - extern void nrt_register(const struct message_type *mtype, + void free_nrmesssages(void); + + void nrt_register(const struct message_type *mtype, const struct locale *lang, const char *script, int level, const char *section); - extern struct nrmessage_type *nrt_find(const struct locale *, + struct nrmessage_type *nrt_find(const struct locale *, const struct message_type *); - extern const char *nrt_string(const struct nrmessage_type *type); - extern const char *nrt_section(const struct nrmessage_type *mt); + const char *nrt_string(const struct nrmessage_type *type); + const char *nrt_section(const struct nrmessage_type *mt); - extern size_t nr_render(const struct message *msg, const struct locale *lang, + size_t nr_render(const struct message *msg, const struct locale *lang, char *buffer, size_t size, const void *userdata); - extern int nr_level(const struct message *msg); - extern const char *nr_section(const struct message *msg); + int nr_level(const struct message *msg); + const char *nr_section(const struct message *msg); /* before: * fogblock;movement:0;de;{unit} konnte von {region} nicht nach {$dir direction} ausreisen, der Nebel war zu dicht. diff --git a/src/util/nrmessage_struct.h b/src/util/nrmessage_struct.h index 6a3a1d9b0..57f8e644d 100644 --- a/src/util/nrmessage_struct.h +++ b/src/util/nrmessage_struct.h @@ -8,8 +8,8 @@ typedef struct nrmessage_type { const struct message_type *mtype; const struct locale *lang; - const char *string; - const char *vars; + char *string; + char *vars; struct nrmessage_type *next; int level; const char *section; diff --git a/src/util/parser.c b/src/util/parser.c index 741fd573f..fca066cb1 100644 --- a/src/util/parser.c +++ b/src/util/parser.c @@ -31,7 +31,7 @@ static int eatwhitespace_c(const char **str_p) for (;;) { unsigned char utf8_character = (unsigned char)*str; if (~utf8_character & 0x80) { - if (!iswxspace(utf8_character)) + if (!iswspace(utf8_character)) break; ++str; } @@ -41,7 +41,7 @@ static int eatwhitespace_c(const char **str_p) log_warning("illegal character sequence in UTF8 string: %s\n", str); break; } - if (!iswxspace((wint_t)ucs)) + if (!iswspace((wint_t)ucs)) break; str += len; } @@ -105,7 +105,7 @@ void skip_token(void) log_warning("illegal character sequence in UTF8 string: %s\n", states->current_token); } } - if (iswxspace((wint_t)ucs) && quotechar == 0) { + if (iswspace((wint_t)ucs) && quotechar == 0) { return; } else { @@ -162,7 +162,7 @@ char *parse_token(const char **str, char *lbuf, size_t buflen) copy = true; escape = false; } - else if (iswxspace((wint_t)ucs)) { + else if (iswspace((wint_t)ucs)) { if (quotechar == 0) break; copy = true; @@ -250,7 +250,8 @@ unsigned int atoip(const char *s) int n; assert(s); - n = atoi(s); + n = (s[0] >='0' && s[0]<='9'); + n = n ? atoi(s) : 0; if (n < 0) n = 0; diff --git a/src/util/parser.h b/src/util/parser.h index 839968480..0c8306931 100644 --- a/src/util/parser.h +++ b/src/util/parser.h @@ -10,6 +10,10 @@ #ifndef UTIL_PARSER_H #define UTIL_PARSER_H + +#include +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/src/util/parser.test.c b/src/util/parser.test.c index da0d8dacb..942aa1866 100644 --- a/src/util/parser.test.c +++ b/src/util/parser.test.c @@ -2,8 +2,16 @@ #include "parser.h" #include +#include #include +static void test_atoip(CuTest *tc) { + CuAssertIntEquals(tc, 0, atoip("ALLES")); + CuAssertIntEquals(tc, 0, errno); + CuAssertIntEquals(tc, 42, atoip("42")); + CuAssertIntEquals(tc, 0, atoip("-1")); +} + static void test_parse_token(CuTest *tc) { char lbuf[8]; const char *tok; @@ -41,11 +49,11 @@ static void test_parse_token_limit_utf8(CuTest *tc) { tok = parse_token(&str, lbuf, sizeof(lbuf)); CuAssertPtrEquals(tc, (void *)(orig + strlen(orig)), (void *)str); - CuAssertStrEquals(tc, tok, "\xc3\xa4\xc3\xb6\xc3\xbc"); // just three letters fit, 6 bytes long + CuAssertStrEquals(tc, tok, "\xc3\xa4\xc3\xb6\xc3\xbc"); /* just three letters fit, 6 bytes long */ tok = parse_token(&str, lbuf, sizeof(lbuf)); CuAssertPtrEquals(tc, NULL, (void *)tok); - str = orig; // now with an extra byte in the front, maxing out lbuf exactly + str = orig; /* now with an extra byte in the front, maxing out lbuf exactly */ tok = parse_token(&str, lbuf, sizeof(lbuf)); CuAssertPtrEquals(tc, (void *)(orig + strlen(orig)), (void *)str); CuAssertStrEquals(tc, tok, "a\xc3\xa4\xc3\xb6\xc3\xbc"); @@ -103,12 +111,6 @@ static void test_getstrtoken(CuTest *tc) { CuAssertPtrEquals(tc, NULL, (void *)getstrtoken()); } -static void test_atoip(CuTest *tc) { - CuAssertIntEquals(tc, 42, atoip("42")); - CuAssertIntEquals(tc, 0, atoip("-42")); - CuAssertIntEquals(tc, 0, atoip("NOPE")); -} - CuSuite *get_parser_suite(void) { CuSuite *suite = CuSuiteNew(); diff --git a/src/util/password.h b/src/util/password.h index e1d49fb6d..ba55f6cb9 100644 --- a/src/util/password.h +++ b/src/util/password.h @@ -1,11 +1,12 @@ #pragma once +#include #define PASSWORD_PLAINTEXT 0 #define PASSWORD_DEFAULT PASSWORD_PLAINTEXT -#define VERIFY_OK 0 // password matches hash -#define VERIFY_FAIL 1 // password is wrong -#define VERIFY_UNKNOWN 2 // hashing algorithm not supported +#define VERIFY_OK 0 +#define VERIFY_FAIL 1 +#define VERIFY_UNKNOWN 2 int password_verify(const char *hash, const char *passwd); const char * password_encode(const char *passwd, int algo); bool password_is_implemented(int algo); diff --git a/src/util/rand.c b/src/util/rand.c index d98b9b8f9..f5c8a28bc 100644 --- a/src/util/rand.c +++ b/src/util/rand.c @@ -28,6 +28,14 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include +int lovar(double xpct_x2) +{ + int n = (int)(xpct_x2 * 500) + 1; + if (n == 0) + return 0; + return (rng_int() % n + rng_int() % n) / 1000; +} + /* NormalRand aus python, random.py geklaut, dort ist Referenz auf * den Algorithmus. mu = Mittelwert, sigma = Standardabweichung. * http://de.wikipedia.org/wiki/Standardabweichung#Diskrete_Gleichverteilung.2C_W.C3.BCrfel @@ -95,13 +103,13 @@ void random_source_inject_constant(double value) { r_source = &constant_provider; } -static int i = 0; static double *values; -static int value_size = 0; +static int value_size; +static int value_index; static double array_source (void) { - assert(i 0); value_size = size; if (values) @@ -117,7 +126,7 @@ void random_source_inject_array(double inject[], int size) { for (i=0; i < size; ++i) { values[i] = inject[i]; } - i = 0; + value_index = 0; r_source = &array_provider; } diff --git a/src/util/rand.h b/src/util/rand.h index e9e5d19ee..e9d9062b7 100644 --- a/src/util/rand.h +++ b/src/util/rand.h @@ -1,3 +1,4 @@ +#pragma once /* Copyright (c) 1998-2015, Enno Rehling Katja Zedel + #ifdef __cplusplus extern "C" { #endif /* in dice.c: */ - extern int dice_rand(const char *str); - extern int dice(int count, int value); + int dice_rand(const char *str); + int dice(int count, int value); /* in rand.c: */ - extern double normalvariate(double mu, double sigma); - extern int ntimespprob(int n, double p, double mod); - extern bool chance(double x); + int lovar(double xpct_x2); + double normalvariate(double mu, double sigma); + int ntimespprob(int n, double p, double mod); + bool chance(double x); /* a random source that generates numbers in [0, 1). By calling the random_source_inject... functions you can set a special random source, diff --git a/src/util/strings.h b/src/util/strings.h index 7178cf179..05a435e2c 100644 --- a/src/util/strings.h +++ b/src/util/strings.h @@ -18,6 +18,9 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #ifndef STRINGS_H #define STRINGS_H + +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/src/util/translation.c b/src/util/translation.c index 829a1fe05..fb89a5af9 100644 --- a/src/util/translation.c +++ b/src/util/translation.c @@ -21,6 +21,7 @@ /* libc includes */ #include #include +#include #include #include @@ -353,7 +354,7 @@ static const char *parse(opstack ** stack, const char *inn, return parse_symbol(stack, ++b, userdata); break; default: - if (isdigit(*(unsigned char *)b) || *b == '-' || *b == '+') { + if (isdigit(*(const unsigned char *)b) || *b == '-' || *b == '+') { return parse_int(stack, b); } else @@ -414,7 +415,7 @@ static void eval_lt(opstack ** stack, const void *userdata) int b = opop_i(stack); int rval = (b < a) ? 1 : 0; opush_i(stack, rval); - unused_arg(userdata); + UNUSED_ARG(userdata); } static void eval_eq(opstack ** stack, const void *userdata) @@ -423,7 +424,7 @@ static void eval_eq(opstack ** stack, const void *userdata) int b = opop_i(stack); int rval = (a == b) ? 1 : 0; opush_i(stack, rval); - unused_arg(userdata); + UNUSED_ARG(userdata); } static void eval_add(opstack ** stack, const void *userdata) @@ -431,14 +432,14 @@ static void eval_add(opstack ** stack, const void *userdata) int a = opop_i(stack); int b = opop_i(stack); opush_i(stack, a + b); - unused_arg(userdata); + UNUSED_ARG(userdata); } static void eval_isnull(opstack ** stack, const void *userdata) { /* (int, int) -> int */ void *a = opop_v(stack); opush_i(stack, (a == NULL) ? 1 : 0); - unused_arg(userdata); + UNUSED_ARG(userdata); } static void eval_if(opstack ** stack, const void *userdata) @@ -447,14 +448,14 @@ static void eval_if(opstack ** stack, const void *userdata) void *b = opop_v(stack); int cond = opop_i(stack); opush_v(stack, cond ? b : a); - unused_arg(userdata); + UNUSED_ARG(userdata); } static void eval_strlen(opstack ** stack, const void *userdata) { /* string -> int */ const char *c = (const char *)opop_v(stack); opush_i(stack, c ? (int)strlen(c) : 0); - unused_arg(userdata); + UNUSED_ARG(userdata); } #include "base36.h" diff --git a/src/util/translation.h b/src/util/translation.h index 01c19a72d..76206021b 100644 --- a/src/util/translation.h +++ b/src/util/translation.h @@ -12,6 +12,9 @@ #ifndef H_UTIL_TRANSLATION #define H_UTIL_TRANSLATION + +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/src/util/umlaut.c b/src/util/umlaut.c index 6be0bdde5..d29cb78ac 100644 --- a/src/util/umlaut.c +++ b/src/util/umlaut.c @@ -168,7 +168,7 @@ void addtoken(tnode ** root, const char *str, variant id) next = next->nexthash; if (!next) { tref *ref; - tnode *node = mknode(); // TODO: what is the reason for this empty node to exist? + tnode *node = mknode(); /* TODO: what is the reason for this empty node to exist? */ if (ucs < 'a' || ucs > 'z') { lcs = towlower((wint_t)ucs); diff --git a/src/util/unicode.c b/src/util/unicode.c index 94b6e3d5a..161983ba7 100644 --- a/src/util/unicode.c +++ b/src/util/unicode.c @@ -1,4 +1,4 @@ -/* +/* * +-------------------+ Christian Schlittchen * | | Enno Rehling * | Eressea PBEM host | Katja Zedel @@ -14,6 +14,7 @@ #include #include #include +#include #define B00000000 0x00 #define B10000000 0x80 @@ -31,6 +32,50 @@ #define B00000011 0x03 #define B00000001 0x01 +int unicode_utf8_trim(utf8_t *buf) +{ + int result = 0, ts = 0; + utf8_t *op = buf, *ip = buf, *lc = buf; + while (*ip) { + size_t size = 1; + wint_t wc = *ip; + if (wc & 0x80) { + ucs4_t ucs = 0; + if (ip[1]) { + int ret = unicode_utf8_to_ucs4(&ucs, ip, &size); + if (ret != 0) { + return ret; + } + wc = (wint_t)ucs; + } + else { + wc = *op = '?'; + size = 1; + ++result; + } + } + if (op == buf && iswspace(wc)) { + ++result; + } + else if (iswprint(wc)) { + if (op != ip) { + memmove(op, ip, size); + } + op += size; + if (iswspace(wc)) ++ts; + else { + lc = op; + ts = 0; + } + } else { + ++result; + } + ip += size; + } + *lc = '\0'; + return result + ts; +} + int unicode_utf8_tolower(utf8_t * op, size_t outlen, const utf8_t * ip) { while (*ip) { @@ -49,7 +94,7 @@ int unicode_utf8_tolower(utf8_t * op, size_t outlen, const utf8_t * ip) } low = towlower((wint_t)ucs); if (low == ucs) { - memcpy(op, ip, size); + memmove(op, ip, size); ip += size; op += size; outlen -= size; @@ -71,7 +116,7 @@ int unicode_utf8_tolower(utf8_t * op, size_t outlen, const utf8_t * ip) int unicode_latin1_to_utf8(utf8_t * dst, size_t * outlen, const char *in, -size_t * inlen) + size_t * inlen) { int is = (int)*inlen; int os = (int)*outlen; @@ -104,7 +149,7 @@ size_t * inlen) return (int)*outlen; } -int unicode_utf8_strcasecmp(const utf8_t * a, const char *b) +int unicode_utf8_strcasecmp(const utf8_t * a, const utf8_t *b) { while (*a && *b) { int ret; @@ -147,7 +192,7 @@ int unicode_utf8_strcasecmp(const utf8_t * a, const char *b) /* Convert a UCS-4 character to UTF-8. */ int unicode_ucs4_to_utf8(utf8_t * utf8_character, size_t * size, -ucs4_t ucs4_character) + ucs4_t ucs4_character) { int utf8_bytes; @@ -214,7 +259,7 @@ ucs4_t ucs4_character) /* Convert a UTF-8 encoded character to UCS-4. */ int unicode_utf8_to_ucs4(ucs4_t * ucs4_character, const utf8_t * utf8_string, -size_t * length) + size_t * length) { utf8_t utf8_character = utf8_string[0]; @@ -317,8 +362,8 @@ size_t * length) /** Convert a UTF-8 encoded character to CP437. */ int -unicode_utf8_to_cp437(char *cp_character, const utf8_t * utf8_string, -size_t * length) +unicode_utf8_to_cp437(unsigned char *cp_character, const utf8_t * utf8_string, + size_t * length) { ucs4_t ucs4_character; int result; @@ -330,174 +375,173 @@ size_t * length) } if (ucs4_character < 0x7F) { - *cp_character = (char)ucs4_character; + *cp_character = (unsigned char)ucs4_character; } else { struct { ucs4_t ucs4; unsigned char cp437; } xref[160] = { - { - 0x00A0, 255 }, { - 0x00A1, 173 }, { - 0x00A2, 155 }, { - 0x00A3, 156 }, { - 0x00A5, 157 }, { - 0x00A7, 21 }, { - 0x00AA, 166 }, { - 0x00AB, 174 }, { - 0x00AC, 170 }, { - 0x00B0, 248 }, { - 0x00B1, 241 }, { - 0x00B2, 253 }, { - 0x00B5, 230 }, { - 0x00B6, 20 }, { - 0x00B7, 250 }, { - 0x00BA, 167 }, { - 0x00BB, 175 }, { - 0x00BC, 172 }, { - 0x00BD, 171 }, { - 0x00BF, 168 }, { - 0x00C4, 142 }, { - 0x00C5, 143 }, { - 0x00C6, 146 }, { - 0x00C7, 128 }, { - 0x00C9, 144 }, { - 0x00D1, 165 }, { - 0x00D6, 153 }, { - 0x00DC, 154 }, { - 0x00DF, 225 }, { - 0x00E0, 133 }, { - 0x00E1, 160 }, { - 0x00E2, 131 }, { - 0x00E4, 132 }, { - 0x00E5, 134 }, { - 0x00E6, 145 }, { - 0x00E7, 135 }, { - 0x00E8, 138 }, { - 0x00E9, 130 }, { - 0x00EA, 136 }, { - 0x00EB, 137 }, { - 0x00EC, 141 }, { - 0x00ED, 161 }, { - 0x00EE, 140 }, { - 0x00EF, 139 }, { - 0x00F1, 164 }, { - 0x00F2, 149 }, { - 0x00F3, 162 }, { - 0x00F4, 147 }, { - 0x00F6, 148 }, { - 0x00F7, 246 }, { - 0x00F9, 151 }, { - 0x00FA, 163 }, { - 0x00FB, 150 }, { - 0x00FC, 129 }, { - 0x00FF, 152 }, { - 0x0192, 159 }, { - 0x0393, 226 }, { - 0x0398, 233 }, { - 0x03A3, 228 }, { - 0x03A6, 232 }, { - 0x03A9, 234 }, { - 0x03B1, 224 }, { - 0x03B4, 235 }, { - 0x03B5, 238 }, { - 0x03C0, 227 }, { - 0x03C3, 229 }, { - 0x03C4, 231 }, { - 0x03C6, 237 }, { - 0x2022, 7 }, { - 0x203C, 19 }, { - 0x207F, 252 }, { - 0x20A7, 158 }, { - 0x2190, 27 }, { - 0x2191, 24 }, { - 0x2192, 26 }, { - 0x2193, 25 }, { - 0x2194, 29 }, { - 0x2195, 18 }, { - 0x21A8, 23 }, { - 0x2219, 249 }, { - 0x221A, 251 }, { - 0x221E, 236 }, { - 0x221F, 28 }, { - 0x2229, 239 }, { - 0x2248, 247 }, { - 0x2261, 240 }, { - 0x2264, 243 }, { - 0x2265, 242 }, { - 0x2302, 127 }, { - 0x2310, 169 }, { - 0x2320, 244 }, { - 0x2321, 245 }, { - 0x2500, 196 }, { - 0x2502, 179 }, { - 0x250C, 218 }, { - 0x2510, 191 }, { - 0x2514, 192 }, { - 0x2518, 217 }, { - 0x251C, 195 }, { - 0x2524, 180 }, { - 0x252C, 194 }, { - 0x2534, 193 }, { - 0x253C, 197 }, { - 0x2550, 205 }, { - 0x2551, 186 }, { - 0x2552, 213 }, { - 0x2553, 214 }, { - 0x2554, 201 }, { - 0x2555, 184 }, { - 0x2556, 183 }, { - 0x2557, 187 }, { - 0x2558, 212 }, { - 0x2559, 211 }, { - 0x255A, 200 }, { - 0x255B, 190 }, { - 0x255C, 189 }, { - 0x255D, 188 }, { - 0x255E, 198 }, { - 0x255F, 199 }, { - 0x2560, 204 }, { - 0x2561, 181 }, { - 0x2562, 182 }, { - 0x2563, 185 }, { - 0x2564, 209 }, { - 0x2565, 210 }, { - 0x2566, 203 }, { - 0x2567, 207 }, { - 0x2568, 208 }, { - 0x2569, 202 }, { - 0x256A, 216 }, { - 0x256B, 215 }, { - 0x256C, 206 }, { - 0x2580, 223 }, { - 0x2584, 220 }, { - 0x2588, 219 }, { - 0x258C, 221 }, { - 0x2590, 222 }, { - 0x2591, 176 }, { - 0x2592, 177 }, { - 0x2593, 178 }, { - 0x25A0, 254 }, { - 0x25AC, 22 }, { - 0x25B2, 30 }, { - 0x25BA, 16 }, { - 0x25BC, 31 }, { - 0x25C4, 17 }, { - 0x25CB, 9 }, { - 0x25D8, 8 }, { - 0x25D9, 10 }, { - 0x263A, 1 }, { - 0x263B, 2 }, { - 0x263C, 15 }, { - 0x2640, 12 }, { - 0x2642, 11 }, { - 0x2660, 6 }, { - 0x2663, 5 }, { - 0x2665, 3 }, { - 0x2666, 4 }, { - 0x266A, 13 }, { - 0x266B, 14 } + { 0x00A0, 255 }, + { 0x00A1, 173 }, + { 0x00A2, 155 }, + { 0x00A3, 156 }, + { 0x00A5, 157 }, + { 0x00A7, 21 }, + { 0x00AA, 166 }, + { 0x00AB, 174 }, + { 0x00AC, 170 }, + { 0x00B0, 248 }, + { 0x00B1, 241 }, + { 0x00B2, 253 }, + { 0x00B5, 230 }, + { 0x00B6, 20 }, + { 0x00B7, 250 }, + { 0x00BA, 167 }, + { 0x00BB, 175 }, + { 0x00BC, 172 }, + { 0x00BD, 171 }, + { 0x00BF, 168 }, + { 0x00C4, 142 }, + { 0x00C5, 143 }, + { 0x00C6, 146 }, + { 0x00C7, 128 }, + { 0x00C9, 144 }, + { 0x00D1, 165 }, + { 0x00D6, 153 }, + { 0x00DC, 154 }, + { 0x00DF, 225 }, + { 0x00E0, 133 }, + { 0x00E1, 160 }, + { 0x00E2, 131 }, + { 0x00E4, 132 }, + { 0x00E5, 134 }, + { 0x00E6, 145 }, + { 0x00E7, 135 }, + { 0x00E8, 138 }, + { 0x00E9, 130 }, + { 0x00EA, 136 }, + { 0x00EB, 137 }, + { 0x00EC, 141 }, + { 0x00ED, 161 }, + { 0x00EE, 140 }, + { 0x00EF, 139 }, + { 0x00F1, 164 }, + { 0x00F2, 149 }, + { 0x00F3, 162 }, + { 0x00F4, 147 }, + { 0x00F6, 148 }, + { 0x00F7, 246 }, + { 0x00F9, 151 }, + { 0x00FA, 163 }, + { 0x00FB, 150 }, + { 0x00FC, 129 }, + { 0x00FF, 152 }, + { 0x0192, 159 }, + { 0x0393, 226 }, + { 0x0398, 233 }, + { 0x03A3, 228 }, + { 0x03A6, 232 }, + { 0x03A9, 234 }, + { 0x03B1, 224 }, + { 0x03B4, 235 }, + { 0x03B5, 238 }, + { 0x03C0, 227 }, + { 0x03C3, 229 }, + { 0x03C4, 231 }, + { 0x03C6, 237 }, + { 0x2022, 7 }, + { 0x203C, 19 }, + { 0x207F, 252 }, + { 0x20A7, 158 }, + { 0x2190, 27 }, + { 0x2191, 24 }, + { 0x2192, 26 }, + { 0x2193, 25 }, + { 0x2194, 29 }, + { 0x2195, 18 }, + { 0x21A8, 23 }, + { 0x2219, 249 }, + { 0x221A, 251 }, + { 0x221E, 236 }, + { 0x221F, 28 }, + { 0x2229, 239 }, + { 0x2248, 247 }, + { 0x2261, 240 }, + { 0x2264, 243 }, + { 0x2265, 242 }, + { 0x2302, 127 }, + { 0x2310, 169 }, + { 0x2320, 244 }, + { 0x2321, 245 }, + { 0x2500, 196 }, + { 0x2502, 179 }, + { 0x250C, 218 }, + { 0x2510, 191 }, + { 0x2514, 192 }, + { 0x2518, 217 }, + { 0x251C, 195 }, + { 0x2524, 180 }, + { 0x252C, 194 }, + { 0x2534, 193 }, + { 0x253C, 197 }, + { 0x2550, 205 }, + { 0x2551, 186 }, + { 0x2552, 213 }, + { 0x2553, 214 }, + { 0x2554, 201 }, + { 0x2555, 184 }, + { 0x2556, 183 }, + { 0x2557, 187 }, + { 0x2558, 212 }, + { 0x2559, 211 }, + { 0x255A, 200 }, + { 0x255B, 190 }, + { 0x255C, 189 }, + { 0x255D, 188 }, + { 0x255E, 198 }, + { 0x255F, 199 }, + { 0x2560, 204 }, + { 0x2561, 181 }, + { 0x2562, 182 }, + { 0x2563, 185 }, + { 0x2564, 209 }, + { 0x2565, 210 }, + { 0x2566, 203 }, + { 0x2567, 207 }, + { 0x2568, 208 }, + { 0x2569, 202 }, + { 0x256A, 216 }, + { 0x256B, 215 }, + { 0x256C, 206 }, + { 0x2580, 223 }, + { 0x2584, 220 }, + { 0x2588, 219 }, + { 0x258C, 221 }, + { 0x2590, 222 }, + { 0x2591, 176 }, + { 0x2592, 177 }, + { 0x2593, 178 }, + { 0x25A0, 254 }, + { 0x25AC, 22 }, + { 0x25B2, 30 }, + { 0x25BA, 16 }, + { 0x25BC, 31 }, + { 0x25C4, 17 }, + { 0x25CB, 9 }, + { 0x25D8, 8 }, + { 0x25D9, 10 }, + { 0x263A, 1 }, + { 0x263B, 2 }, + { 0x263C, 15 }, + { 0x2640, 12 }, + { 0x2642, 11 }, + { 0x2660, 6 }, + { 0x2663, 5 }, + { 0x2665, 3 }, + { 0x2666, 4 }, + { 0x266A, 13 }, + { 0x266B, 14 } }; int l = 0, r = 160; while (l != r) { @@ -506,10 +550,14 @@ size_t * length) *cp_character = (char)xref[m].cp437; break; } - else if (xref[m].ucs4 < ucs4_character) - l = m; - else - r = m; + else if (xref[m].ucs4 < ucs4_character) { + if (l == m) l = r; + else l = m; + } + else { + if (r == m) r = l; + else r = m; + } } if (l == r) { *cp_character = '?'; @@ -519,7 +567,7 @@ size_t * length) } /** Convert a UTF-8 encoded character to ASCII, with '?' replacements. */ -int unicode_utf8_to_ascii(char *cp_character, const utf8_t * utf8_string, +int unicode_utf8_to_ascii(unsigned char *cp_character, const utf8_t * utf8_string, size_t *length) { int result = unicode_utf8_to_cp437(cp_character, utf8_string, length); @@ -532,7 +580,7 @@ int unicode_utf8_to_ascii(char *cp_character, const utf8_t * utf8_string, } /** Convert a UTF-8 encoded character to CP1252. */ -int unicode_utf8_to_cp1252(char *cp_character, const utf8_t * utf8_string, +int unicode_utf8_to_cp1252(unsigned char *cp_character, const utf8_t * utf8_string, size_t * length) { ucs4_t ucs4_character; @@ -552,39 +600,38 @@ int unicode_utf8_to_cp1252(char *cp_character, const utf8_t * utf8_string, ucs4_t ucs4; unsigned char cp; } xref[] = { - { - 0x20ac, 0x80 }, { - 0x0081, 0x81 }, { - 0x201a, 0x82 }, { - 0x0192, 0x83 }, { - 0x201e, 0x84 }, { - 0x2026, 0x85 }, { - 0x2020, 0x86 }, { - 0x2021, 0x87 }, { - 0x02c6, 0x88 }, { - 0x2030, 0x89 }, { - 0x0160, 0x8a }, { - 0x2039, 0x8b }, { - 0x0152, 0x8c }, { - 0x008d, 0x8d }, { - 0x017d, 0x8e }, { - 0x008f, 0x8f }, { - 0x0090, 0x90 }, { - 0x2018, 0x91 }, { - 0x2019, 0x92 }, { - 0x201c, 0x93 }, { - 0x201d, 0x94 }, { - 0x2022, 0x95 }, { - 0x2013, 0x96 }, { - 0x2014, 0x97 }, { - 0x02dc, 0x98 }, { - 0x2122, 0x99 }, { - 0x0161, 0x9a }, { - 0x203a, 0x9b }, { - 0x0153, 0x9c }, { - 0x009d, 0x9d }, { - 0x017e, 0x9e }, { - 0x0178, 0x9f } + { 0x0081, 0x81 }, + { 0x008d, 0x8d }, + { 0x008f, 0x8f }, + { 0x0090, 0x90 }, + { 0x009d, 0x9d }, + { 0x0152, 0x8c }, + { 0x0153, 0x9c }, + { 0x0160, 0x8a }, + { 0x0161, 0x9a }, + { 0x0178, 0x9f }, + { 0x017d, 0x8e }, + { 0x017e, 0x9e }, + { 0x0192, 0x83 }, + { 0x02c6, 0x88 }, + { 0x02dc, 0x98 }, + { 0x2013, 0x96 }, + { 0x2014, 0x97 }, + { 0x2018, 0x91 }, + { 0x2019, 0x92 }, + { 0x201a, 0x82 }, + { 0x201c, 0x93 }, + { 0x201d, 0x94 }, + { 0x201e, 0x84 }, + { 0x2022, 0x95 }, + { 0x2026, 0x85 }, + { 0x2020, 0x86 }, + { 0x2021, 0x87 }, + { 0x2030, 0x89 }, + { 0x203a, 0x9b }, + { 0x2039, 0x8b }, + { 0x20ac, 0x80 }, + { 0x2122, 0x99 } }; int l = 0, r = sizeof(xref) / sizeof(xref[0]); while (l != r) { diff --git a/src/util/unicode.h b/src/util/unicode.h index b061cd6fb..4fd860e45 100644 --- a/src/util/unicode.h +++ b/src/util/unicode.h @@ -25,24 +25,24 @@ extern "C" { #include #define USE_UNICODE - typedef unsigned long ucs4_t; + typedef long ucs4_t; typedef char utf8_t; - int unicode_utf8_to_cp437(char *result, const utf8_t * utf8_string, + int unicode_utf8_to_cp437(unsigned char *result, const utf8_t * utf8_string, size_t * length); - int unicode_utf8_to_cp1252(char *result, const utf8_t * utf8_string, + int unicode_utf8_to_cp1252(unsigned char *result, const utf8_t * utf8_string, size_t * length); int unicode_utf8_to_ucs4(ucs4_t * result, const utf8_t * utf8_string, size_t * length); int unicode_ucs4_to_utf8(utf8_t * result, size_t * size, ucs4_t ucs4_character); - int unicode_utf8_to_ascii(char *cp_character, const utf8_t * utf8_string, + int unicode_utf8_to_ascii(unsigned char *cp_character, const utf8_t * utf8_string, size_t *length); int unicode_utf8_strcasecmp(const utf8_t * a, const utf8_t * b); int unicode_latin1_to_utf8(utf8_t * out, size_t * outlen, const char *in, size_t * inlen); - int unicode_utf8_tolower(utf8_t * out, size_t outlen, - const utf8_t * in); + int unicode_utf8_tolower(utf8_t *op, size_t outlen, const utf8_t *ip); + int unicode_utf8_trim(utf8_t *ip); #ifdef __cplusplus } diff --git a/src/util/unicode.test.c b/src/util/unicode.test.c index 958b695e2..7c1c1031a 100644 --- a/src/util/unicode.test.c +++ b/src/util/unicode.test.c @@ -5,6 +5,35 @@ #include #include +static void test_unicode_trim(CuTest * tc) +{ + char buffer[32]; + + strcpy(buffer, "Hello Word"); + CuAssertIntEquals(tc, 0, unicode_utf8_trim(buffer)); + CuAssertStrEquals(tc, "Hello Word", buffer); + + strcpy(buffer, " Hello Word "); + CuAssertIntEquals(tc, 4, unicode_utf8_trim(buffer)); + CuAssertStrEquals(tc, "Hello Word", buffer); + + strcpy(buffer, "Hello Word\n"); + CuAssertIntEquals(tc, 1, unicode_utf8_trim(buffer)); + CuAssertStrEquals(tc, "Hello Word", buffer); + + strcpy(buffer, " Hello Word\t\n"); + CuAssertIntEquals(tc, 4, unicode_utf8_trim(buffer)); + CuAssertStrEquals(tc, "Hello Word", buffer); + + strcpy(buffer, " \t Hello Word"); + CuAssertIntEquals(tc, 3, unicode_utf8_trim(buffer)); + CuAssertStrEquals(tc, "Hello Word", buffer); + + buffer[9] = -61; + CuAssertIntEquals(tc, 1, unicode_utf8_trim(buffer)); + CuAssertStrEquals(tc, "Hello Wor?", buffer); +} + static void test_unicode_tolower(CuTest * tc) { char buffer[32]; @@ -16,9 +45,92 @@ static void test_unicode_tolower(CuTest * tc) CuAssertStrEquals(tc, "helloX", buffer); } +static void test_unicode_utf8_to_other(CuTest *tc) +{ + const unsigned char uchar_str[] = { 0xc3, 0x98, 0xc5, 0xb8, 0xc2, 0x9d, 'l', 0 }; /* ØŸl */ + utf8_t *utf8_str = (utf8_t *)uchar_str; + unsigned char ch; + size_t sz; + CuAssertIntEquals(tc, 0, unicode_utf8_to_cp437(&ch, utf8_str, &sz)); + CuAssertIntEquals(tc, 2, (int)sz); + CuAssertIntEquals(tc, '?', ch); + CuAssertIntEquals(tc, 0, unicode_utf8_to_cp437(&ch, utf8_str+2, &sz)); + CuAssertIntEquals(tc, 2, (int)sz); + CuAssertIntEquals(tc, '?', ch); + CuAssertIntEquals(tc, 0, unicode_utf8_to_cp437(&ch, utf8_str+4, &sz)); + CuAssertIntEquals(tc, 2, (int)sz); + CuAssertIntEquals(tc, '?', ch); + CuAssertIntEquals(tc, 0, unicode_utf8_to_cp437(&ch, utf8_str + 6, &sz)); + CuAssertIntEquals(tc, 1, (int)sz); + CuAssertIntEquals(tc, 'l', ch); + + CuAssertIntEquals(tc, 0, unicode_utf8_to_cp1252(&ch, utf8_str, &sz)); + CuAssertIntEquals(tc, 2, (int)sz); + CuAssertIntEquals(tc, 216, ch); + CuAssertIntEquals(tc, 0, unicode_utf8_to_cp1252(&ch, utf8_str+2, &sz)); + CuAssertIntEquals(tc, 2, (int)sz); + CuAssertIntEquals(tc, 120, ch); + CuAssertIntEquals(tc, 0, unicode_utf8_to_cp1252(&ch, utf8_str + 4, &sz)); + CuAssertIntEquals(tc, 2, (int)sz); + CuAssertIntEquals(tc, 0x9d, ch); + CuAssertIntEquals(tc, 0, unicode_utf8_to_cp1252(&ch, utf8_str + 6, &sz)); + CuAssertIntEquals(tc, 1, (int)sz); + CuAssertIntEquals(tc, 'l', ch); + + CuAssertIntEquals(tc, 0, unicode_utf8_to_ascii(&ch, utf8_str, &sz)); + CuAssertIntEquals(tc, 2, (int)sz); + CuAssertIntEquals(tc, '?', ch); + CuAssertIntEquals(tc, 0, unicode_utf8_to_ascii(&ch, utf8_str + 2, &sz)); + CuAssertIntEquals(tc, 2, (int)sz); + CuAssertIntEquals(tc, '?', ch); + CuAssertIntEquals(tc, 0, unicode_utf8_to_ascii(&ch, utf8_str + 4, &sz)); + CuAssertIntEquals(tc, 2, (int)sz); + CuAssertIntEquals(tc, '?', ch); + CuAssertIntEquals(tc, 0, unicode_utf8_to_ascii(&ch, utf8_str + 6, &sz)); + CuAssertIntEquals(tc, 1, (int)sz); + CuAssertIntEquals(tc, 'l', ch); +} + +static void test_unicode_utf8_to_ucs(CuTest *tc) { + ucs4_t ucs; + size_t sz; + + CuAssertIntEquals(tc, 0, unicode_utf8_to_ucs4(&ucs, "a", &sz)); + CuAssertIntEquals(tc, 'a', ucs); + CuAssertIntEquals(tc, 1, sz); +} + +static void test_unicode_bug2262(CuTest *tc) { + char name[7]; + ucs4_t ucs; + size_t sz; + + strcpy(name, "utende"); + CuAssertIntEquals(tc, 0, unicode_utf8_to_ucs4(&ucs, name, &sz)); + CuAssertIntEquals(tc, 1, sz); + CuAssertIntEquals(tc, 'u', ucs); + CuAssertIntEquals(tc, 0, unicode_utf8_trim(name)); + + name[0] = -4; /* latin1: ü should fail to decode */ + CuAssertIntEquals(tc, EILSEQ, unicode_utf8_to_ucs4(&ucs, name, &sz)); + CuAssertIntEquals(tc, EILSEQ, unicode_utf8_trim(name)); +} + +static void test_unicode_compare(CuTest *tc) +{ + CuAssertIntEquals(tc, 0, unicode_utf8_strcasecmp("ABCDEFG", "abcdefg")); + CuAssertIntEquals(tc, 0, unicode_utf8_strcasecmp("abcdefg123", "ABCDEFG123")); + CuAssertIntEquals(tc, 1, unicode_utf8_strcasecmp("bacdefg123", "ABCDEFG123")); +} + CuSuite *get_unicode_suite(void) { CuSuite *suite = CuSuiteNew(); + SUITE_ADD_TEST(suite, test_unicode_bug2262); SUITE_ADD_TEST(suite, test_unicode_tolower); + SUITE_ADD_TEST(suite, test_unicode_trim); + SUITE_ADD_TEST(suite, test_unicode_utf8_to_other); + SUITE_ADD_TEST(suite, test_unicode_utf8_to_ucs); + SUITE_ADD_TEST(suite, test_unicode_compare); return suite; } diff --git a/src/util/variant.c b/src/util/variant.c new file mode 100644 index 000000000..c1d42808d --- /dev/null +++ b/src/util/variant.c @@ -0,0 +1,80 @@ +#include +#include "variant.h" + +#include +#include + +const variant frac_zero = { .sa = { 0, 1 } }; +const variant frac_one = { .sa = { 1, 1 } }; + +static int gcd(int a, int b) { + const int primes[] = { 3, 5, 7, 11, 13, 17, 19, 23, 0 }; + int i = 0, g = 1, p = 2; + while (p && p <= a && p <= b) { + if (a % p == 0 && b % p == 0) { + a /= p; + b /= p; + g *= p; + } + else { + p = primes[i++]; + } + } + return g; +} + +static int lcm(int a, int b) { + int x; + if (a == b) return a; + x = (a * b); + x = (x > 0 ? x : -x) / gcd(a, b); + return x; +} + +bool frac_equal(variant a, variant b) { + return frac_sign(frac_sub(a, b)) == 0; +} + +variant frac_make(int num, int den) +{ + variant v; + int g = gcd(num, den); + num /= g; + den /= g; + assert(num >= SHRT_MIN && num <= SHRT_MAX); + assert(den >= SHRT_MIN && den <= SHRT_MAX); + v.sa[0] = (short)num; + v.sa[1] = (short)den; + return v; +} + +variant frac_add(variant a, variant b) +{ + int num, den; + den = lcm(a.sa[1], b.sa[1]); + num = a.sa[0] * den / a.sa[1] + b.sa[0] * den / b.sa[1]; + return frac_make(num, den); +} + +variant frac_sub(variant a, variant b) +{ + b.sa[0] = -b.sa[0]; + return frac_add(a, b); +} + +variant frac_mul(variant a, variant b) +{ + return frac_make(a.sa[0] * b.sa[0], a.sa[1] * b.sa[1]); +} + +variant frac_div(variant a, variant b) +{ + return frac_make(a.sa[0] * b.sa[1], a.sa[1] * b.sa[0]); +} + +int frac_sign(variant a) { + if (a.sa[0] == 0) return 0; + if (a.sa[0] > 0 && a.sa[1] > 0) return 1; + if (a.sa[0] < 0 && a.sa[1] < 0) return 1; + return -1; +} diff --git a/src/util/variant.h b/src/util/variant.h index 4559264ed..ae75c5cda 100644 --- a/src/util/variant.h +++ b/src/util/variant.h @@ -1,16 +1,21 @@ +#pragma once + #ifndef STRUCT_VARIANT_H #define STRUCT_VARIANT_H + +#include + #ifdef __cplusplus extern "C" { #endif typedef union variant { - void *v; //TODO: V117 http://www.viva64.com/en/V117 Memsize type is used in the union. + void *v; int i; char c; short s; short sa[2]; - char ca[4]; //TODO: V112 http://www.viva64.com/en/V112 Dangerous magic number 4 used: char ca[4];. + char ca[4]; float f; } variant; @@ -19,6 +24,17 @@ extern "C" { VAR_FLOAT } variant_type; + extern const variant frac_zero; + extern const variant frac_one; + + variant frac_make(int num, int den); + variant frac_add(variant a, variant b); + variant frac_sub(variant a, variant b); + variant frac_mul(variant a, variant b); + variant frac_div(variant a, variant b); + int frac_sign(variant a); + bool frac_equal(variant a, variant b); + #ifdef __cplusplus } #endif diff --git a/src/util/variant.test.c b/src/util/variant.test.c new file mode 100644 index 000000000..12299720b --- /dev/null +++ b/src/util/variant.test.c @@ -0,0 +1,40 @@ +#include +#include "variant.h" + +#include + +static void test_fractions(CuTest *tc) { + variant a, b; + a = frac_make(120, 12000); + CuAssertIntEquals(tc, 1, a.sa[0]); + CuAssertIntEquals(tc, 100, a.sa[1]); + b = frac_make(23, 2300); + a = frac_add(a, b); + CuAssertIntEquals(tc, 1, a.sa[0]); + CuAssertIntEquals(tc, 50, a.sa[1]); + a = frac_mul(a, b); + CuAssertIntEquals(tc, 1, a.sa[0]); + CuAssertIntEquals(tc, 5000, a.sa[1]); + a = frac_div(b, b); + CuAssertIntEquals(tc, 1, a.sa[0]); + CuAssertIntEquals(tc, 1, a.sa[1]); + a = frac_sub(a, a); + CuAssertIntEquals(tc, 0, a.sa[0]); + a = frac_sub(frac_one, a); + CuAssertIntEquals(tc, 1, a.sa[0]); + CuAssertIntEquals(tc, 1, a.sa[1]); + a = frac_mul(a, frac_zero); + CuAssertIntEquals(tc, 0, a.sa[0]); + CuAssertIntEquals(tc, 1, frac_sign(frac_make(-1, -1))); + CuAssertIntEquals(tc, 1, frac_sign(frac_make(1, 1))); + CuAssertIntEquals(tc, -1, frac_sign(frac_make(-1, 1))); + CuAssertIntEquals(tc, -1, frac_sign(frac_make(1, -1))); + CuAssertIntEquals(tc, 0, frac_sign(frac_make(0, 1))); +} + +CuSuite *get_variant_suite(void) +{ + CuSuite *suite = CuSuiteNew(); + SUITE_ADD_TEST(suite, test_fractions); + return suite; +} diff --git a/src/util/xml.h b/src/util/xml.h index 921cd3f53..bd22e3e0a 100644 --- a/src/util/xml.h +++ b/src/util/xml.h @@ -13,6 +13,8 @@ #ifndef H_UTIL_XML #define H_UTIL_XML +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/src/volcano.c b/src/volcano.c index bd8c56b30..9734bb2cd 100644 --- a/src/volcano.c +++ b/src/volcano.c @@ -55,7 +55,7 @@ static int nb_armor(const unit * u, int index) if (!(u_race(u)->battle_flags & BF_EQUIPMENT)) return 0; - /* Normale Rstung */ + /* Normale R�stung */ for (itm = u->items; itm; itm = itm->next) { const armor_type *atype = itm->type->rtype->atype; @@ -80,7 +80,6 @@ damage_unit(unit * u, const char *dam, bool physical, bool magic) int *hp, hpstack[20]; int h; int i, dead = 0, hp_rem = 0, heiltrank; - double magres = magic_resistance(u); assert(u->number); if (fval(u_race(u), RCF_ILLUSIONARY) || u_race(u) == get_race(RC_SPELL)) { @@ -105,10 +104,14 @@ damage_unit(unit * u, const char *dam, bool physical, bool magic) /* Schaden */ for (i = 0; i < u->number; i++) { int damage = dice_rand(dam); - if (magic) - damage = (int)(damage * (1.0 - magres)); - if (physical) + if (magic) { + variant magres = magic_resistance(u); + magres = frac_sub(frac_make(1, 1), magres); + damage = damage * magres.sa[0] / magres.sa[1]; + } + if (physical) { damage -= nb_armor(u, i); + } hp[i] -= damage; } @@ -169,11 +172,11 @@ static region *rrandneighbour(region * r) for (i = 0; i != MAXDIRECTIONS; i++) { c++; } - /* Zufllig eine auswhlen */ + /* Zuf�llig eine ausw�hlen */ rr = rng_int() % c; - /* Durchzhlen */ + /* Durchz�hlen */ c = -1; for (i = 0; i != MAXDIRECTIONS; i++) { @@ -204,7 +207,7 @@ volcano_destruction(region * volcano, region * r, const char *damage) else { /* Produktion vierteln ... */ a->data.sa[0] = (short)percent; - /* Fr 6-17 Runden */ + /* F�r 6-17 Runden */ a->data.sa[1] = (short)(a->data.sa[1] + time); } @@ -255,6 +258,22 @@ void volcano_outbreak(region * r, region *rn) } } +static bool stop_smoke_chance(void) { + static int cache, percent = 0; + if (config_changed(&cache)) { + percent = config_get_int("volcano.stop.percent", 12); + } + return percent!=0 && (rng_int() % 100) < percent; +} + +static bool outbreak_chance(void) { + static int cache, percent = 0; + if (config_changed(&cache)) { + percent = config_get_int("volcano.outbreak.percent", 8); + } + return percent!=0 && (rng_int() % 100) < percent; +} + void volcano_update(void) { region *r; @@ -270,13 +289,16 @@ void volcano_update(void) r->terrain = t_volcano; } else { - if (rng_int() % 100 < 12) { + if (stop_smoke_chance()) { ADDMSG(&r->msgs, msg_message("volcanostopsmoke", "region", r)); r->terrain = t_volcano; } - else if (r->uid == 1246051340 || (r->age > 20 && rng_int() % 100 < 8)) { + else if (r->uid == 1246051340 || outbreak_chance()) { + /* HACK: a fixed E4-only region-uid in Code. + * FIXME: In E4 gibt es eine Ebene #1246051340, die Smalland heisst. + * da das kein aktiver Vulkan ist, ist dieser Test da nicht idiotisch? + * das sollte bestimmt rn betreffen? */ region *rn; - /* Zufllige Nachbarregion verwsten */ rn = rrandneighbour(r); volcano_outbreak(r, rn); r->terrain = t_volcano; @@ -284,7 +306,8 @@ void volcano_update(void) } } else if (r->terrain == t_volcano) { - if (rng_int() % 100 < 4) { + int volcano_chance = config_get_int("volcano.active.percent", 4); + if (rng_int() % 100 < volcano_chance) { ADDMSG(&r->msgs, msg_message("volcanostartsmoke", "region", r)); r->terrain = t_active; } diff --git a/src/vortex.c b/src/vortex.c index 244c83a29..7b6206d03 100644 --- a/src/vortex.c +++ b/src/vortex.c @@ -14,8 +14,9 @@ #include #include -#include #include +#include + typedef struct dir_lookup { char *name; @@ -32,7 +33,7 @@ void register_special_direction(struct locale *lang, const char *name) if (token) { void **tokens = get_translations(lang, UT_SPECDIR); variant var; - char *str = _strdup(name); + char *str = strdup(name); var.v = str; addtoken((struct tnode **)tokens, token, var); @@ -69,7 +70,7 @@ static void a_freedirection(attrib * a) static int a_agedirection(attrib * a, void *owner) { spec_direction *d = (spec_direction *)(a->data.v); - unused_arg(owner); + (void)owner; --d->duration; return (d->duration > 0) ? AT_AGE_KEEP : AT_AGE_REMOVE; } @@ -80,14 +81,14 @@ static int a_readdirection(attrib * a, void *owner, struct gamedata *data) spec_direction *d = (spec_direction *)(a->data.v); char lbuf[32]; - unused_arg(owner); + (void)owner; READ_INT(store, &d->x); READ_INT(store, &d->y); READ_INT(store, &d->duration); READ_TOK(store, lbuf, sizeof(lbuf)); - d->desc = _strdup(lbuf); + d->desc = strdup(lbuf); READ_TOK(store, lbuf, sizeof(lbuf)); - d->keyword = _strdup(lbuf); + d->keyword = strdup(lbuf); d->active = true; return AT_READ_OK; } @@ -97,7 +98,7 @@ a_writedirection(const attrib * a, const void *owner, struct storage *store) { spec_direction *d = (spec_direction *)(a->data.v); - unused_arg(owner); + (void)owner; WRITE_INT(store, d->x); WRITE_INT(store, d->y); WRITE_INT(store, d->duration); @@ -142,8 +143,8 @@ attrib *create_special_direction(region * r, region * rt, int duration, d->x = rt->x; d->y = rt->y; d->duration = duration; - d->desc = _strdup(desc); - d->keyword = _strdup(keyword); + d->desc = strdup(desc); + d->keyword = strdup(keyword); return a; } diff --git a/src/vortex.h b/src/vortex.h index af41b6111..993f5cdab 100644 --- a/src/vortex.h +++ b/src/vortex.h @@ -1,5 +1,10 @@ +#pragma once + #ifndef H_VORTEX #define H_VORTEX + +#include + #ifdef __cplusplus extern "C" { #endif diff --git a/src/wormhole.c b/src/wormhole.c index 6a115a9f7..462f4e637 100644 --- a/src/wormhole.c +++ b/src/wormhole.c @@ -30,7 +30,7 @@ #include #include #include -#include +#include #include @@ -63,7 +63,7 @@ static int wormhole_age(struct attrib *a, void *owner) region *r = entry->region; unit *u = r->units; - unused_arg(owner); + UNUSED_ARG(owner); for (; u != NULL && maxtransport != 0; u = u->next) { if (u->building == entry) { message *m = NULL; @@ -155,8 +155,8 @@ make_wormhole(const building_type * bt_wormhole, region * r1, region * r2) #define WORMHOLE_CHANCE 10000 -static void select_wormhole_regions(quicklist **rlistp, int *countp) { - quicklist *rlist = 0; +static void select_wormhole_regions(selist **rlistp, int *countp) { + selist *rlist = 0; region *r = regions; int count = 0; @@ -170,7 +170,7 @@ static void select_wormhole_regions(quicklist **rlistp, int *countp) { } if (r == NULL) break; - ql_push(&rlist, r); + selist_push(&rlist, r); ++count; r = r->next; } @@ -179,12 +179,12 @@ static void select_wormhole_regions(quicklist **rlistp, int *countp) { *rlistp = rlist; } -void sort_wormhole_regions(quicklist *rlist, region **match, int count) { - quicklist *ql; +void sort_wormhole_regions(selist *rlist, region **match, int count) { + selist *ql; int qi, i = 0; - for (ql = rlist, qi = 0; i != count; ql_advance(&ql, &qi, 1)) { - match[i++] = (region *)ql_get(ql, qi); + for (ql = rlist, qi = 0; i != count; selist_advance(&ql, &qi, 1)) { + match[i++] = (region *)selist_get(ql, qi); } qsort(match, count, sizeof(region *), cmp_age); } @@ -200,7 +200,7 @@ void make_wormholes(region **match, int count, const building_type *bt_wormhole) void wormholes_update(void) { const building_type *bt_wormhole = bt_find("wormhole"); - quicklist *rlist = 0; + selist *rlist = 0; int count = 0; region **match; @@ -214,7 +214,7 @@ void wormholes_update(void) } match = (region **)malloc(sizeof(region *) * count); sort_wormhole_regions(rlist, match, count); - ql_free(rlist); + selist_free(rlist); make_wormholes(match, count, bt_wormhole); free(match); } diff --git a/src/wormhole.test.c b/src/wormhole.test.c index ec93c5b4c..4f3036200 100644 --- a/src/wormhole.test.c +++ b/src/wormhole.test.c @@ -10,11 +10,11 @@ #include -#include +#include #include -void sort_wormhole_regions(quicklist *rlist, region **match, int count); +void sort_wormhole_regions(selist *rlist, region **match, int count); void make_wormholes(region **match, int count, const building_type *bt_wormhole); static void test_make_wormholes(CuTest *tc) { @@ -42,7 +42,7 @@ static void test_make_wormholes(CuTest *tc) { static void test_sort_wormhole_regions(CuTest *tc) { region *r1, *r2, *match[2]; terrain_type *t_plain; - quicklist *rlist = 0; + selist *rlist = 0; test_setup(); t_plain = test_create_terrain("plain", LAND_REGION); @@ -50,12 +50,12 @@ static void test_sort_wormhole_regions(CuTest *tc) { r2 = test_create_region(1, 0, t_plain); r1->age = 4; r2->age = 2; - ql_push(&rlist, r1); - ql_push(&rlist, r2); + selist_push(&rlist, r1); + selist_push(&rlist, r2); sort_wormhole_regions(rlist, match, 2); CuAssertPtrEquals(tc, r2, match[0]); CuAssertPtrEquals(tc, r1, match[1]); - ql_free(rlist); + selist_free(rlist); test_cleanup(); } diff --git a/src/xmlreport.c b/src/xmlreport.c deleted file mode 100644 index 43d7cc55b..000000000 --- a/src/xmlreport.c +++ /dev/null @@ -1,801 +0,0 @@ -/* -+-------------------+ Enno Rehling -| Eressea PBEM host | Christian Schlittchen -| (c) 1998 - 2008 | Katja Zedel -+-------------------+ -This program may not be used, modified or distributed -without prior permission by the authors of Eressea. -*/ - -#include -#include -#include "xmlreport.h" - -#define XML_ATL_NAMESPACE (const xmlChar *) "http://www.eressea.de/XML/2008/atlantis" -#define XML_XML_LANG (const xmlChar *) "lang" - -/* modules include */ -#include - -/* attributes include */ -#include -#include -#include -#include -#include - -/* gamecode includes */ -#include "laws.h" -#include "economy.h" -#include "move.h" - -/* kernel includes */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* util includes */ -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef USE_LIBXML2 -/* libxml2 includes */ -#include -#include -#ifdef USE_ICONV -#include -#endif -#endif - -/* libc includes */ -#include -#include -#include -#include -#include -#include - -#define L10N(x) x - -typedef struct xml_context { - xmlDocPtr doc; - xmlNsPtr ns_atl; - xmlNsPtr ns_xml; -} xml_context; - -static xmlNodePtr -xml_link(report_context * ctx, const xmlChar * rel, const xmlChar * ref) -{ - xml_context *xct = (xml_context *) ctx->userdata; - xmlNodePtr node = xmlNewNode(xct->ns_atl, BAD_CAST "link"); - - xmlNewNsProp(node, xct->ns_atl, BAD_CAST "rel", rel); - xmlNewNsProp(node, xct->ns_atl, BAD_CAST "ref", ref); - - return node; -} - -static const xmlChar *xml_ref_unit(const unit * u) -{ - static char idbuf[20]; - _snprintf(idbuf, sizeof(idbuf), "unit_%d", u->no); - return (const xmlChar *)idbuf; -} - -static const xmlChar *xml_ref_faction(const faction * f) -{ - static char idbuf[20]; - _snprintf(idbuf, sizeof(idbuf), "fctn_%d", f->no); - return (const xmlChar *)idbuf; -} - -static const xmlChar *xml_ref_group(const group * g) -{ - static char idbuf[20]; - _snprintf(idbuf, sizeof(idbuf), "grp_%d", g->gid); - return (const xmlChar *)idbuf; -} - -static const xmlChar *xml_ref_prefix(const char *str) -{ - static char idbuf[20]; - _snprintf(idbuf, sizeof(idbuf), "pref_%s", str); - return (const xmlChar *)idbuf; -} - -static const xmlChar *xml_ref_building(const building * b) -{ - static char idbuf[20]; - _snprintf(idbuf, sizeof(idbuf), "bldg_%d", b->no); - return (const xmlChar *)idbuf; -} - -static const xmlChar *xml_ref_ship(const ship * sh) -{ - static char idbuf[20]; - _snprintf(idbuf, sizeof(idbuf), "shp_%d", sh->no); - return (const xmlChar *)idbuf; -} - -static const xmlChar *xml_ref_region(const region * r) -{ - static char idbuf[20]; - _snprintf(idbuf, sizeof(idbuf), "rgn_%d", r->uid); - return (const xmlChar *)idbuf; -} - -static xmlNodePtr xml_inventory(report_context * ctx, item * items, unit * u) -{ - xml_context *xct = (xml_context *) ctx->userdata; - xmlNodePtr node = xmlNewNode(xct->ns_atl, BAD_CAST "items"); - item *itm; - - for (itm = items; itm; itm = itm->next) { - xmlNodePtr child; - const char *name; - int n; - - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "item")); - report_item(u, itm, ctx->f, NULL, &name, &n, true); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", (xmlChar *) name); - xmlNodeAddContent(child, (xmlChar *) itoab(n, 10)); - } - return node; -} - -#ifdef TODO /*spellbooks */ -static xmlNodePtr -xml_spells(report_context * ctx, quicklist * slist, int maxlevel) -{ - xml_context *xct = (xml_context *) ctx->userdata; - xmlNodePtr child, node = xmlNewNode(xct->ns_atl, BAD_CAST "spells"); - quicklist *ql; - int qi; - - for (ql = slist, qi = 0; ql; ql_advance(&ql, &qi, 1)) { - spell *sp = (spell *) ql_get(ql, qi); - - if (sp->level <= maxlevel) { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "spell")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "name", BAD_CAST sp->sname); - } - } - return node; -} -#endif - -static xmlNodePtr xml_skills(report_context * ctx, unit * u) -{ - xml_context *xct = (xml_context *) ctx->userdata; - xmlNodePtr child, node = xmlNewNode(xct->ns_atl, BAD_CAST "skills"); - skill *sv; - - for (sv = u->skills; sv != u->skills + u->skill_size; ++sv) { - if (sv->level > 0) { - skill_t sk = sv->id; - int esk = eff_skill(u, sk, u->region); - - child = - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "skill", BAD_CAST itoab(esk, - 10)); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", BAD_CAST skillnames[sk]); - } - } - - return node; -} - -static xmlNodePtr xml_unit(report_context * ctx, unit * u, int mode) -{ - xml_context *xct = (xml_context *) ctx->userdata; - xmlNodePtr node = xmlNewNode(xct->ns_atl, BAD_CAST "unit"); - static const curse_type *itemcloak_ct = 0; - static bool init = false; - xmlNodePtr child; - const char *str, *rcname, *rcillusion; - bool disclosure = (ctx->f == u->faction || omniscient(ctx->f)); - - /* TODO: hitpoints, aura, combatspells, curses */ - - xmlNewNsProp(node, xct->ns_xml, XML_XML_ID, xml_ref_unit(u)); - xmlNewNsProp(node, xct->ns_atl, BAD_CAST "key", BAD_CAST itoa36(u->no)); - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "name", (const xmlChar *)u->name); - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "number", - (const xmlChar *)itoab(u->number, 10)); - - /* optional description */ - str = u_description(u, ctx->f->locale); - if (str) { - child = - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "text", (const xmlChar *)str); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "public"); - if (str != u->display) { - xmlNewNsProp(child, xct->ns_atl, XML_XML_LANG, - BAD_CAST locale_name(ctx->f->locale)); - } - } - - /* possible info */ - if (is_guard(u, GUARD_ALL) != 0) { - xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "guard")); - } - - /* siege */ - if (fval(u, UFL_SIEGE)) { - building *b = usiege(u); - if (b) { - xmlAddChild(node, xml_link(ctx, BAD_CAST "siege", xml_ref_building(b))); - } - } - - /* TODO: temp/alias */ - - /* race information */ - report_race(u, &rcname, &rcillusion); - if (disclosure) { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "race")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "true"); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", (const xmlChar *)rcname); - if (rcillusion) { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "race")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "stealth"); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", - (const xmlChar *)rcillusion); - } - } else { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "race")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", - (const xmlChar *)(rcillusion ? rcillusion : rcname)); - } - - /* group and prefix information. we only write the prefix if we really must */ - if (fval(u, UFL_GROUP)) { - attrib *a = a_find(u->attribs, &at_group); - if (a != NULL) { - const group *g = (const group *)a->data.v; - if (disclosure) { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "group")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", xml_ref_group(g)); - } else { - const char *prefix = get_prefix(g->attribs); - if (prefix) { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "prefix")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", - xml_ref_prefix(prefix)); - } - } - } - } - - if (disclosure) { - unit *mage; - - str = uprivate(u); - if (str) { - child = - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "text", - (const xmlChar *)str); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "private"); - } - - /* familiar info */ - mage = get_familiar_mage(u); - if (mage) - xmlAddChild(node, xml_link(ctx, BAD_CAST "familiar_of", - xml_ref_unit(mage))); - - /* combat status */ - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "status")); - xmlSetNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "combat"); - xmlSetNsProp(child, xct->ns_atl, BAD_CAST "value", - BAD_CAST combatstatus[u->status]); - - if (fval(u, UFL_NOAID)) { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "status")); - xmlSetNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "aid"); - xmlSetNsProp(child, xct->ns_atl, BAD_CAST "value", BAD_CAST "false"); - } - - if (fval(u, UFL_STEALTH)) { - int i = u_geteffstealth(u); - if (i >= 0) { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "status")); - xmlSetNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "stealth"); - xmlSetNsProp(child, xct->ns_atl, BAD_CAST "value", BAD_CAST itoab(i, - 10)); - } - } - if (fval(u, UFL_HERO)) { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "status")); - xmlSetNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "hero"); - xmlSetNsProp(child, xct->ns_atl, BAD_CAST "value", BAD_CAST "true"); - } - - if (fval(u, UFL_HUNGER)) { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "status")); - xmlSetNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "hunger"); - xmlSetNsProp(child, xct->ns_atl, BAD_CAST "value", BAD_CAST "true"); - } - - /* skills */ - if (u->skill_size) { - xmlAddChild(node, xml_skills(ctx, u)); - } - -#ifdef TODO /*spellbooks */ - /* spells */ - if (is_mage(u)) { - sc_mage *mage = get_mage(u); - quicklist *slist = mage->spells; - if (slist) { - xmlAddChild(node, xml_spells(ctx, slist, effskill(u, SK_MAGIC))); - } - } -#endif - } - - /* faction information w/ visibiility */ - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "faction")); - if (disclosure) { - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "true"); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", - xml_ref_faction(u->faction)); - - if (fval(u, UFL_ANON_FACTION)) { - const faction *sf = visible_faction(NULL, u); - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "faction")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "stealth"); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", xml_ref_faction(sf)); - } - } else { - const faction *sf = visible_faction(ctx->f, u); - if (sf == ctx->f) { - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "stealth"); - } - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", xml_ref_faction(sf)); - } - - /* the inventory */ - if (u->items) { - item result[MAX_INVENTORY]; - item *show = NULL; - - if (!init) { - init = true; - itemcloak_ct = ct_find("itemcloak"); - } - - if (disclosure) { - show = u->items; - } else { - bool see_items = (mode >= see_unit); - if (see_items) { - if (itemcloak_ct && curse_active(get_curse(u->attribs, itemcloak_ct))) { - see_items = false; - } else { - see_items = effskill(u, SK_STEALTH) < 3; - } - } - if (see_items) { - int n = report_items(u->items, result, MAX_INVENTORY, u, ctx->f); - assert(n >= 0); - if (n > 0) - show = result; - else - show = NULL; - } else { - show = NULL; - } - } - - if (show) { - xmlAddChild(node, xml_inventory(ctx, show, u)); - } - } - - return node; -} - -static xmlNodePtr xml_resources(report_context * ctx, const seen_region * sr) -{ - xml_context *xct = (xml_context *) ctx->userdata; - xmlNodePtr node = NULL; - resource_report result[MAX_RAWMATERIALS]; - int n, size = report_resources(sr, result, MAX_RAWMATERIALS, ctx->f); - - if (size) { - node = xmlNewNode(xct->ns_atl, BAD_CAST "resources"); - for (n = 0; n < size; ++n) { - if (result[n].number >= 0) { - xmlNodePtr child; - - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "resource")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", - (xmlChar *) result[n].name); - if (result[n].level >= 0) { - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "level", - (xmlChar *) itoab(result[n].level, 10)); - } - xmlNodeAddContent(child, (xmlChar *) itoab(result[n].number, 10)); - } - } - } - return node; -} - -static xmlNodePtr xml_diplomacy(report_context * ctx, const struct ally *allies) -{ - xml_context *xct = (xml_context *) ctx->userdata; - xmlNodePtr child, node = xmlNewNode(xct->ns_atl, BAD_CAST "diplomacy"); - const struct ally *sf; - - for (sf = allies; sf; sf = sf->next) { - int i, status = sf->status; - for (i = 0; helpmodes[i].name; ++i) { - if (sf->faction && (status & helpmodes[i].status) == helpmodes[i].status) { - status -= helpmodes[i].status; - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "status")); - xmlNewNsProp(child, xct->ns_xml, BAD_CAST "faction", - xml_ref_faction(sf->faction)); - xmlNewNsProp(child, xct->ns_xml, BAD_CAST "status", - (xmlChar *) helpmodes[i].name); - } - } - } - return node; -} - -static xmlNodePtr xml_groups(report_context * ctx, const group * groups) -{ - xml_context *xct = (xml_context *) ctx->userdata; - xmlNodePtr child, node = xmlNewNode(xct->ns_atl, BAD_CAST "faction"); - const group *g; - - for (g = groups; g; g = g->next) { - const char *prefix = get_prefix(g->attribs); - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "group")); - xmlNewNsProp(child, xct->ns_xml, XML_XML_ID, xml_ref_group(g)); - xmlNewTextChild(child, xct->ns_atl, BAD_CAST "name", - (const xmlChar *)g->name); - - if (g->allies) - xmlAddChild(child, xml_diplomacy(ctx, g->allies)); - - if (prefix) { - child = xmlAddChild(child, xmlNewNode(xct->ns_atl, BAD_CAST "prefix")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", xml_ref_prefix(prefix)); - } - } - - return node; -} - -static xmlNodePtr xml_faction(report_context * ctx, faction * f) -{ - xml_context *xct = (xml_context *) ctx->userdata; - xmlNodePtr child, node = xmlNewNode(xct->ns_atl, BAD_CAST "faction"); - - /* TODO: alliance, locale */ - - xmlNewNsProp(node, xct->ns_xml, XML_XML_ID, xml_ref_faction(f)); - xmlNewNsProp(node, xct->ns_atl, BAD_CAST "key", BAD_CAST itoa36(f->no)); - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "name", (const xmlChar *)f->name); - if (f->email) - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "email", - (const xmlChar *)f->email); - if (f->banner) { - child = - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "text", - (const xmlChar *)f->banner); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "public"); - } - - if (ctx->f == f) { - xmlAddChild(node, xml_link(ctx, BAD_CAST "race", - BAD_CAST f->race->_name[0])); - - if (f->items) - xmlAddChild(node, xml_inventory(ctx, f->items, NULL)); - if (f->allies) - xmlAddChild(node, xml_diplomacy(ctx, f->allies)); - if (f->groups) - xmlAddChild(node, xml_groups(ctx, f->groups)); - - /* TODO: age, options, score, prefix, magic, immigrants, heroes, nmr, groups */ - } - return node; -} - -static xmlNodePtr -xml_building(report_context * ctx, seen_region * sr, const building * b, - const unit * owner) -{ - xml_context *xct = (xml_context *) ctx->userdata; - xmlNodePtr node = xmlNewNode(xct->ns_atl, BAD_CAST "building"); - xmlNodePtr child; - const char *bname, *billusion; - - xmlNewNsProp(node, xct->ns_xml, XML_XML_ID, xml_ref_building(b)); - xmlNewNsProp(node, xct->ns_atl, BAD_CAST "key", BAD_CAST itoa36(b->no)); - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "name", (const xmlChar *)b->name); - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "size", - (const xmlChar *)itoab(b->size, 10)); - if (b->display && b->display[0]) { - child = - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "text", - (const xmlChar *)b->display); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "public"); - } - if (b->besieged) { - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "siege", - (const xmlChar *)itoab(b->besieged, 10)); - } - if (owner) - xmlAddChild(node, xml_link(ctx, BAD_CAST "owner", xml_ref_unit(owner))); - - report_building(b, &bname, &billusion); - if (owner && owner->faction == ctx->f) { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "type")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "true"); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", (const xmlChar *)bname); - if (billusion) { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "type")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "illusion"); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", - (const xmlChar *)billusion); - } - } else { - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "type")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", - (const xmlChar *)(billusion ? billusion : bname)); - } - - return node; -} - -static xmlNodePtr -xml_ship(report_context * ctx, const seen_region * sr, const ship * sh, - const unit * owner) -{ - xml_context *xct = (xml_context *) ctx->userdata; - xmlNodePtr child, node = xmlNewNode(xct->ns_atl, BAD_CAST "ship"); - - xmlNewNsProp(node, xct->ns_xml, XML_XML_ID, xml_ref_ship(sh)); - xmlNewNsProp(node, xct->ns_atl, BAD_CAST "key", BAD_CAST itoa36(sh->no)); - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "name", - (const xmlChar *)sh->name); - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "size", - (const xmlChar *)itoab(sh->size, 10)); - - if (sh->damage) { - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "damage", - (const xmlChar *)itoab(sh->damage, 10)); - } - - if (fval(sr->r->terrain, SEA_REGION) && sh->coast != NODIRECTION) { - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "coast", - BAD_CAST directions[sh->coast]); - } - - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "type")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", - (const xmlChar *)sh->type->name[0]); - - if (sh->display && sh->display[0]) { - child = - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "text", - (const xmlChar *)sh->display); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "public"); - } - - if (owner) - xmlAddChild(node, xml_link(ctx, BAD_CAST "owner", xml_ref_unit(owner))); - - if ((owner && owner->faction == ctx->f) || omniscient(ctx->f)) { - int n = 0, p = 0; - getshipweight(sh, &n, &p); - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "cargo", - (const xmlChar *)itoab(n, 10)); - } - return node; -} - -static xmlNodePtr xml_region(report_context * ctx, seen_region * sr) -{ - xml_context *xct = (xml_context *) ctx->userdata; - const region *r = sr->r; - xmlNodePtr node = xmlNewNode(xct->ns_atl, BAD_CAST "region"); - xmlNodePtr child; - int stealthmod = stealth_modifier(sr->mode); - unit *u; - ship *sh = r->ships; - building *b = r->buildings; - plane *pl = rplane(r); - int nx = r->x, ny = r->y; - - pnormalize(&nx, &ny, pl); - adjust_coordinates(ctx->f, &nx, &ny, pl, r); - - /* TODO: entertain-quota, recruits, salary, prices, curses, borders, apparitions (Schemen), spells, travelthru, messages */ - xmlNewNsProp(node, xct->ns_xml, XML_XML_ID, xml_ref_region(r)); - - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "coordinate")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "x", xml_i(nx)); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "y", xml_i(ny)); - if (pl && pl->name) { - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "plane", (xmlChar *) pl->name); - } - - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "terrain")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", (xmlChar *) terrain_name(r)); - - if (r->land != NULL) { - child = - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "name", - (const xmlChar *)r->land->name); - if (r->land->items) { - xmlAddChild(node, xml_inventory(ctx, r->land->items, NULL)); - } - } - if (r->display && r->display[0]) { - child = - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "text", - (const xmlChar *)r->display); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "rel", BAD_CAST "public"); - } - child = xml_resources(ctx, sr); - if (child) - xmlAddChild(node, child); - - child = xmlNewNode(xct->ns_atl, BAD_CAST "terrain"); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "ref", - (const xmlChar *)terrain_name(r)); - - if (sr->mode > see_neighbour) { - /* report all units. they are pre-sorted in an efficient manner */ - u = r->units; - while (b) { - while (b && (!u || u->building != b)) { - xmlAddChild(node, xml_building(ctx, sr, b, NULL)); - b = b->next; - } - if (b) { - child = xmlAddChild(node, xml_building(ctx, sr, b, u)); - while (u && u->building == b) { - xmlAddChild(child, xml_unit(ctx, u, sr->mode)); - u = u->next; - } - b = b->next; - } - } - while (u && !u->ship) { - if (stealthmod > INT_MIN) { - if (u->faction == ctx->f || cansee(ctx->f, r, u, stealthmod)) { - xmlAddChild(node, xml_unit(ctx, u, sr->mode)); - } - } - u = u->next; - } - while (sh) { - while (sh && (!u || u->ship != sh)) { - xmlAddChild(node, xml_ship(ctx, sr, sh, NULL)); - sh = sh->next; - } - if (sh) { - child = xmlAddChild(node, xml_ship(ctx, sr, sh, u)); - while (u && u->ship == sh) { - xmlAddChild(child, xml_unit(ctx, u, sr->mode)); - u = u->next; - } - sh = sh->next; - } - } - } - return node; -} - -static xmlNodePtr report_root(report_context * ctx) -{ - int qi; - quicklist *address; - region *r = ctx->first, *rend = ctx->last; - xml_context *xct = (xml_context *) ctx->userdata; - xmlNodePtr node, child, xmlReport = xmlNewNode(NULL, BAD_CAST "atlantis"); - const char *mailto = locale_string(ctx->f->locale, "mailto"); - const char *mailcmd = locale_string(ctx->f->locale, "mailcmd"); - char zText[128]; - /* TODO: locale, age, options, messages */ - - xct->ns_xml = xmlNewNs(xmlReport, XML_XML_NAMESPACE, BAD_CAST "xml"); - xct->ns_atl = xmlNewNs(xmlReport, XML_ATL_NAMESPACE, NULL); - xmlSetNs(xmlReport, xct->ns_atl); - - node = xmlAddChild(xmlReport, xmlNewNode(xct->ns_atl, BAD_CAST "server")); - if (mailto) { - _snprintf(zText, sizeof(zText), "mailto:%s?subject=%s", mailto, mailcmd); - child = xmlAddChild(node, xmlNewNode(xct->ns_atl, BAD_CAST "delivery")); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "method", BAD_CAST "mail"); - xmlNewNsProp(child, xct->ns_atl, BAD_CAST "href", BAD_CAST zText); - } - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "game", - (xmlChar *) global.gamename); - strftime(zText, sizeof(zText), "%Y-%m-%dT%H:%M:%SZ", - gmtime(&ctx->report_time)); - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "time", (xmlChar *) zText); - xmlNewTextChild(node, xct->ns_atl, BAD_CAST "turn", (xmlChar *) itoab(turn, - 10)); - - for (qi = 0, address = ctx->addresses; address; ql_advance(&address, &qi, 1)) { - faction *f = (faction *) ql_get(address, qi); - xmlAddChild(xmlReport, xml_faction(ctx, f)); - } - - for (; r != rend; r = r->next) { - seen_region *sr = find_seen(ctx->seen, r); - if (sr != NULL) - xmlAddChild(xmlReport, xml_region(ctx, sr)); - } - return xmlReport; -} - -/* main function of the xmlreport. creates the header and traverses all regions */ -static int -report_xml(const char *filename, report_context * ctx, const char *encoding) -{ - xml_context xct; - xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0"); - - xct.doc = doc; - assert(ctx->userdata == NULL); - ctx->userdata = &xct; - - xmlDocSetRootElement(doc, report_root(ctx)); - xmlKeepBlanksDefault(0); - xmlSaveFormatFileEnc(filename, doc, "utf-8", 1); - xmlFreeDoc(doc); - - ctx->userdata = NULL; - - return 0; -} - -void register_xr(void) -{ - register_reporttype("xml", &report_xml, 1 << O_XML); -#ifdef USE_ICONV - utf8 = iconv_open("UTF-8", ""); -#endif -} - -void xmlreport_cleanup(void) -{ -#ifdef USE_ICONV - iconv_close(utf8); -#endif -} diff --git a/src/xmlreport.h b/src/xmlreport.h deleted file mode 100644 index 676fbd1a2..000000000 --- a/src/xmlreport.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - +-------------------+ Christian Schlittchen - | Eressea PBEM host | Katja Zedel - | (c) 1998 - 2005 | Enno Rehling - +-------------------+ - - This program may not be used, modified or distributed - without prior permission by the authors of Eressea. -*/ -#ifndef H_GC_XMLREPORT -#define H_GC_XMLREPORT -#ifdef __cplusplus -extern "C" { -#endif - -#include - - extern void xmlreport_cleanup(void); - extern void register_xr(void); - - extern int crwritemap(const char *filename); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/storage b/storage index 18cc3bb8f..2117191d4 160000 --- a/storage +++ b/storage @@ -1 +1 @@ -Subproject commit 18cc3bb8f8906237915eb31c9899f95340318087 +Subproject commit 2117191d4ad75e1eb14809878bc71d15b20a5d86 diff --git a/tests/eressea.ini b/tests/eressea.ini index e84171d45..faf4b1b9e 100644 --- a/tests/eressea.ini +++ b/tests/eressea.ini @@ -1,10 +1,8 @@ -[eressea] -base = . -report = reports +[game] +name = Eressea +id = 2 +email = eressea-server@kn-bremen.de verbose = 0 -lomem = 0 -debug = 0 -memcheck = 0 locales = de,en [lua] diff --git a/tests/orders.184 b/tests/orders.184 index 980993481..315c180d5 100644 --- a/tests/orders.184 +++ b/tests/orders.184 @@ -1,4 +1,4 @@ -ERESSEA 6rLo "6rLo" +PARTEI 6rLo "6rLo" EINHEIT 7Lgf NACH NW NW NAECHSTER @@ -6,7 +6,8 @@ ERESSEA w86y "w86y" EINHEIT uc3u STIRB "mrqa" NAECHSTER -ERESSEA ngij "ngij" + +FACTION ngij "ngij" EINHEIT iwbz HELFE w86y ALLES EINHEIT j536 diff --git a/tests/runtests.bat b/tests/runtests.bat index e79d27baa..41b5f8056 100644 --- a/tests/runtests.bat +++ b/tests/runtests.bat @@ -6,9 +6,8 @@ IF EXIST ..\build-vs14 SET BUILD=..\build-vs14\eressea\Debug SET SERVER=%BUILD%\eressea.exe %BUILD%\test_eressea.exe %SERVER% ..\scripts\run-tests.lua -%SERVER% ..\scripts\run-tests-e2.lua -%SERVER% ..\scripts\run-tests-e3.lua -%SERVER% ..\scripts\run-tests-e4.lua +%SERVER% -re2 ..\scripts\run-tests-e2.lua +%SERVER% -re3 ..\scripts\run-tests-e3.lua PAUSE RMDIR /s /q reports DEL score score.alliances datum turn diff --git a/tolua b/tolua deleted file mode 160000 index 32cc6a3e7..000000000 --- a/tolua +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 32cc6a3e78238278bc5b1fb8566526558e5afdda diff --git a/vs2015-build.bat b/vs2015-build.bat index 6c39659d1..262d498bf 100644 --- a/vs2015-build.bat +++ b/vs2015-build.bat @@ -9,5 +9,5 @@ IF exist build-vs%VSVERSION% goto HAVEDIR mkdir build-vs%VSVERSION% :HAVEDIR cd build-vs%VSVERSION% -"%ProgramFiles(x86)%\CMake\bin\cmake.exe" -G "Visual Studio %VSVERSION%" -DCMAKE_PREFIX_PATH="%ProgramFiles(x86)%/Lua/5.1;%ERESSEA%/dependencies-win32" -DCMAKE_MODULE_PATH="%SRCDIR%/cmake/Modules" -DCMAKE_SUPPRESS_REGENERATION=TRUE .. +"%ProgramFiles%\CMake\bin\cmake.exe" -G "Visual Studio %VSVERSION%" -DCMAKE_PREFIX_PATH="%ProgramFiles(x86)%/Lua/5.1;%ERESSEA%/dependencies-win32" -DCMAKE_MODULE_PATH="%SRCDIR%/cmake/Modules" -DCMAKE_SUPPRESS_REGENERATION=TRUE .. PAUSE