diff --git a/AI/BattleAI/CMakeLists.txt b/AI/BattleAI/CMakeLists.txt index b30be26ce..0540be017 100644 --- a/AI/BattleAI/CMakeLists.txt +++ b/AI/BattleAI/CMakeLists.txt @@ -37,11 +37,7 @@ else() endif() target_include_directories(BattleAI PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -target_link_libraries(BattleAI PRIVATE vcmi TBB::tbb) +target_link_libraries(BattleAI PRIVATE vcmi) vcmi_set_output_dir(BattleAI "AI") enable_pch(BattleAI) - -if(APPLE_IOS AND NOT USING_CONAN) - install(IMPORTED_RUNTIME_ARTIFACTS TBB::tbb LIBRARY DESTINATION ${LIB_DIR}) # CMake 3.21+ -endif() diff --git a/AI/CMakeLists.txt b/AI/CMakeLists.txt index 8326fef64..7231c65e5 100644 --- a/AI/CMakeLists.txt +++ b/AI/CMakeLists.txt @@ -8,10 +8,6 @@ else() option(FORCE_BUNDLED_FL "Force to use FuzzyLite included into VCMI's source tree" OFF) endif() -if(TBB_FOUND AND MSVC) - install_vcpkg_imported_tgt(TBB::tbb) -endif() - #FuzzyLite uses MSVC pragmas in headers, so, we need to disable -Wunknown-pragmas if(MINGW) add_compile_options(-Wno-unknown-pragmas) diff --git a/AI/Nullkiller/CMakeLists.txt b/AI/Nullkiller/CMakeLists.txt index 7d9f272a1..83fc3bff6 100644 --- a/AI/Nullkiller/CMakeLists.txt +++ b/AI/Nullkiller/CMakeLists.txt @@ -157,11 +157,7 @@ else() endif() target_include_directories(Nullkiller PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -target_link_libraries(Nullkiller PUBLIC vcmi fuzzylite::fuzzylite TBB::tbb) +target_link_libraries(Nullkiller PUBLIC vcmi fuzzylite::fuzzylite) vcmi_set_output_dir(Nullkiller "AI") enable_pch(Nullkiller) - -if(APPLE_IOS AND NOT USING_CONAN) - install(IMPORTED_RUNTIME_ARTIFACTS TBB::tbb LIBRARY DESTINATION ${LIB_DIR}) # CMake 3.21+ -endif() diff --git a/CMakeLists.txt b/CMakeLists.txt index dcbe5d562..044351c64 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -519,7 +519,7 @@ if(ENABLE_LAUNCHER OR ENABLE_EDITOR) endif() endif() -if(ENABLE_CLIENT) +if(NOT ENABLE_MINIMAL_LIB) find_package(TBB REQUIRED) endif() @@ -722,6 +722,10 @@ endif() if(WIN32) + if(TBB_FOUND AND MSVC) + install_vcpkg_imported_tgt(TBB::tbb) + endif() + if(USING_CONAN) #Conan imports enabled vcmi_install_conan_deps("\${CMAKE_INSTALL_PREFIX}") diff --git a/ChangeLog.md b/ChangeLog.md index 8f2ccba9c..9e7c573f1 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -4,9 +4,25 @@ * Saved game size reduced by approximately 3 times, especially for large maps or games with a large number of mods. * Added option to start vcmi server on randomly selected TCP port * Fixed potential desynchronization between server and clients on randomization of map objects if client and server run on different operating systems +* It is now possible to generate game statistics using `!statistic` command in game chat + +### Stability +* Fixed possible crash on connecting bluetooth mouse during gameplay on Android +* VCMI will now write more detailed information to log file on crash due to uncaught exception + +### Multiplayer +* Implemented handicap system, with options to reduce income and growth in addition to starting resources restriction + +### Mechanics +* Arrow tower will now prefer to attack more units that are viewed most dangerous instead of simply attacking top-most unit +* Score in campaigns will now be correctly tracked for games loaded from a save +* Fixed incorrect direction of Dragon Breath attack in some cases if wide creature attacks another wide creature +* Map events and town events are now triggered on start of turn of player affected by event, in line with H3 instead of triggering on start of new day for all players ### Interface * Implemented spell quick selection panel in combat +* Implemented adventure map overlay accessible via Alt key that highlights all interactive objects on screen +* Added hotkeys to reorder list of owned towns or heroes * The number of units resurrected using the Life Drain ability is now written to the combat log. * Fixed playback of audio stream with different formats from video files in some Heroes 3 versions * Video playback will not be replaced by a black square when another dialogue box is on top of the video. @@ -19,17 +35,40 @@ * Semi-transparent shadows now correctly update their transparency during fading effects, such as resource pickups * Game will now save all names for human player in hotseat mode * Added unassigned by default shortcuts for toggling visibility of visitable and blocked tiles +* Spellbook button in battle is now blocked if hero has no spellbook +* Adventure map will no longer scroll if window is not in focus + +### Random Maps Generator +* Implemented connection option 'forcePortal' +* It is now possible to connect zone to itself using pair of portals ### AI * Fixed bug where BattleAI attempts to move double-wide unit to an unreachable hex * Fixed several cases where Nullkiller AI can count same dangerous object twice, doubling expected army loss. * Nullkiller is now capable of visiting configurable objects from mods +* Nullkiller now uses whirlpools for map movement +* AI can now correctly estimate effect of Dragon Breath and other similar abilities + +### Map Editor +* Implemented tracking of building requirements for Building Dialog +* Added build/demolish/enable/disable all buildings options to Building Dialog in town properties +* It is now possible to set spells allowed or required to be present in Mages Guild +* It is now possible to add timed events to a town +* Fixed editor not marking mod as dependency if spells from mod are used in town Mages Guild or in hero starting spells ### Modding +* Fixed multiple issues with configurable town buildings +* Added documentation for configurable town buildings. See docs/Moddders/Entities_Format/Town_Buildings_Format.md +* Replaced some of hardcoded town buildings with configurable buildings. These building types are now deprecated and will be removed in future. * Added support for custom music and opening sound for a battlefield * Added support for multiple music tracks for towns * Added support for multiple music tracks for terrains on adventure map * Fixed several cases where vcmi will report errors in json without specifying filename of invalid file +* It is now possible to use .zip archive for VCMI campaigns instead of raw gzip stream +* Added support for custom region definitions (such as background images) for VCMI campaigns +* It is now possible to change minimal values of primary skills for heroes +* Added support for HotA bank building from Factory +* Added support for HotA-style 8th creature in town # 1.5.5 -> 1.5.6 diff --git a/Mods/vcmi/config/vcmi/chinese.json b/Mods/vcmi/config/vcmi/chinese.json index a3fedda51..27d4cf255 100644 --- a/Mods/vcmi/config/vcmi/chinese.json +++ b/Mods/vcmi/config/vcmi/chinese.json @@ -285,17 +285,6 @@ "vcmi.townHall.missingBase" : "必须先建造基础建筑 %s", "vcmi.townHall.noCreaturesToRecruit" : "没有可供招募的生物。", - "vcmi.townHall.greetingManaVortex" : "接近%s时,你会全身充满活力,并且你的魔法值会加倍。", - "vcmi.townHall.greetingKnowledge" : "你研究了%s的浮雕,洞察了魔法的秘密(知识+1)。", - "vcmi.townHall.greetingSpellPower" : "%s教你如何运用魔法力量(力量+1)。", - "vcmi.townHall.greetingExperience" : "参观%s可以让你学会许多新的技能(经验值+1000)。", - "vcmi.townHall.greetingAttack" : "在%s中稍待片刻可以让你学会更有效的战斗技巧(攻击力+1)。", - "vcmi.townHall.greetingDefence" : "在%s中稍待片刻,富有战斗经验的战士会教你防御技巧(防御力+1)。", - "vcmi.townHall.hasNotProduced" : "本周%s并没有产生什么资源。", - "vcmi.townHall.hasProduced" : "本周%s产生了%d个%s。", - "vcmi.townHall.greetingCustomBonus" : "%s 给予英雄 +%d %s%s。", - "vcmi.townHall.greetingCustomUntil" : "直到下一场战斗。", - "vcmi.townHall.greetingInTownMagicWell" : "%s使你的魔法值恢复到最大值。", "vcmi.logicalExpressions.anyOf" : "以下任一前提:", "vcmi.logicalExpressions.allOf" : "以下所有前提:", diff --git a/Mods/vcmi/config/vcmi/czech.json b/Mods/vcmi/config/vcmi/czech.json index 3851bfb5c..57625bd43 100644 --- a/Mods/vcmi/config/vcmi/czech.json +++ b/Mods/vcmi/config/vcmi/czech.json @@ -278,17 +278,6 @@ "vcmi.townHall.missingBase" : "Základní budova %s musí být postavena jako první", "vcmi.townHall.noCreaturesToRecruit" : "Žádné jednotky k vycvičení!", - "vcmi.townHall.greetingManaVortex" : "Při pobytu u místa %s se vaše tělo naplnilo novou energií. Máte dvojnásobné množství maximální magické energie.", - "vcmi.townHall.greetingKnowledge" : "Studujete glyfy na the %s a porozumíte fungování různých magií (+1 Znalosti).", - "vcmi.townHall.greetingSpellPower" : "%s vás učí nové cesty zaměření vaší magické síly (+1 Síla kouzel).", - "vcmi.townHall.greetingExperience" : "Návštěva %s vás naučila spoustu nových dovedností (+1000 zkušeností).", - "vcmi.townHall.greetingAttack" : "Čas strávený poblíž místa zvaného %s vám dovolil se naučit efektivnější bojové dovednosti (+1 Útočná síla).", - "vcmi.townHall.greetingDefence" : "Trávíte čas na místě zvaném %s, zkušení bojovníci vás u toho naučili nové metody obrany (+1 Obranná síla).", - "vcmi.townHall.hasNotProduced" : "%s - zatím nic nevyrobeno.", - "vcmi.townHall.hasProduced" : "%s - vyrobeno %d %s tento týden.", - "vcmi.townHall.greetingCustomBonus" : "%s vám dává +%d %s%s", - "vcmi.townHall.greetingCustomUntil" : " do další bitvy.", - "vcmi.townHall.greetingInTownMagicWell" : "%s - obnoveno na maximum vaši magickou energii.", "vcmi.logicalExpressions.anyOf" : "Něco z následujících:", "vcmi.logicalExpressions.allOf" : "Všechny následující:", diff --git a/Mods/vcmi/config/vcmi/english.json b/Mods/vcmi/config/vcmi/english.json index cd55a74a7..8db122468 100644 --- a/Mods/vcmi/config/vcmi/english.json +++ b/Mods/vcmi/config/vcmi/english.json @@ -324,17 +324,6 @@ "vcmi.townHall.missingBase" : "Base building %s must be built first", "vcmi.townHall.noCreaturesToRecruit" : "There are no creatures to recruit!", - "vcmi.townHall.greetingManaVortex" : "As you near the %s your body is filled with new energy. You have doubled your normal spell points.", - "vcmi.townHall.greetingKnowledge" : "You study the glyphs on the %s and gain insight into the workings of various magics (+1 Knowledge).", - "vcmi.townHall.greetingSpellPower" : "The %s teaches you new ways to focus your magical powers (+1 Power).", - "vcmi.townHall.greetingExperience" : "A visit to the %s teaches you many new skills (+1000 Experience).", - "vcmi.townHall.greetingAttack" : "Some time spent at the %s allows you to learn more effective combat skills (+1 Attack Skill).", - "vcmi.townHall.greetingDefence" : "Spending time in the %s, the experienced warriors therein teach you additional defensive skills (+1 Defense).", - "vcmi.townHall.hasNotProduced" : "The %s has not produced anything yet.", - "vcmi.townHall.hasProduced" : "The %s produced %d %s this week.", - "vcmi.townHall.greetingCustomBonus" : "%s gives you +%d %s%s", - "vcmi.townHall.greetingCustomUntil" : " until next battle.", - "vcmi.townHall.greetingInTownMagicWell" : "%s has restored your spell points to maximum.", "vcmi.townStructure.bank.borrow" : "You enter the bank. A banker sees you and says: \"We have made a special offer for you. You can take a loan of 2500 gold from us for 5 days. You will have to repay 500 gold every day.\"", "vcmi.townStructure.bank.payBack" : "You enter the bank. A banker sees you and says: \"You have already got your loan. Pay it back before taking a new one.\"", diff --git a/Mods/vcmi/config/vcmi/french.json b/Mods/vcmi/config/vcmi/french.json index 377f3da83..5e1e1e067 100644 --- a/Mods/vcmi/config/vcmi/french.json +++ b/Mods/vcmi/config/vcmi/french.json @@ -135,17 +135,6 @@ "vcmi.townHall.missingBase" : "Le bâtiment de base %s doit être construit avant", "vcmi.townHall.noCreaturesToRecruit" : "Il n'y a aucune créature à recruter !", - "vcmi.townHall.greetingManaVortex" : "Alors que vous approchez du %s, votre corps est rempli d'une nouvelle énergie. Vous avez doublé vos points de sort normaux.", - "vcmi.townHall.greetingKnowledge" : "Vous étudiez les glyphes sur le %s et découvrez le fonctionnement de diverses magies (+1 Connaissance).", - "vcmi.townHall.greetingSpellPower" : "Le %s vous apprend de nouvelles façons de concentrer vos pouvoirs magiques (+1 Pouvoir).", - "vcmi.townHall.greetingExperience" : "Une visite au %s vous apprend de nombreuses nouvelles compétences (+1000 Expérience).", - "vcmi.townHall.greetingAttack" : "Un peu de temps passé au %s vous permet d'apprendre des compétences de combat plus efficaces (+1 compétence d'attaque).", - "vcmi.townHall.greetingDefence" : "En passant du temps dans le %s, les guerriers expérimentés qui s'y trouvent vous enseignent des compétences défensives supplémentaires (+1 Défense).", - "vcmi.townHall.hasNotProduced" : "Le %s n'a encore rien produit.", - "vcmi.townHall.hasProduced" : "Le %s a produit %d %s cette semaine.", - "vcmi.townHall.greetingCustomBonus" : "%s vous offre +%d %s%s", - "vcmi.townHall.greetingCustomUntil" : " jusqu'à la prochaine bataille.", - "vcmi.townHall.greetingInTownMagicWell" : "%s a restauré vos points de sort au maximum.", "vcmi.logicalExpressions.anyOf" : "L'un des éléments suivants :", "vcmi.logicalExpressions.allOf" : "Tous les éléments suivants :", diff --git a/Mods/vcmi/config/vcmi/german.json b/Mods/vcmi/config/vcmi/german.json index 6fac7149d..aad6d8d11 100644 --- a/Mods/vcmi/config/vcmi/german.json +++ b/Mods/vcmi/config/vcmi/german.json @@ -324,17 +324,6 @@ "vcmi.townHall.missingBase" : "Basis Gebäude %s muss als erstes gebaut werden", "vcmi.townHall.noCreaturesToRecruit" : "Es gibt keine Kreaturen zu rekrutieren!", - "vcmi.townHall.greetingManaVortex" : "Wenn Ihr Euch den %s nähert, wird Euer Körper mit neuer Energie gefüllt. Ihr habt Eure normalen Zauberpunkte verdoppelt.", - "vcmi.townHall.greetingKnowledge" : "Ihr studiert die Glyphen auf dem %s und erhaltet Einblick in die Funktionsweise verschiedener Magie (+1 Wissen).", - "vcmi.townHall.greetingSpellPower" : "Der %s lehrt Euch neue Wege, Eure magischen Kräfte zu bündeln (+1 Kraft).", - "vcmi.townHall.greetingExperience" : "Ein Besuch bei den %s bringt Euch viele neue Fähigkeiten bei (+1000 Erfahrung).", - "vcmi.townHall.greetingAttack" : "Nach einiger Zeit im %s könnt Ihr effizientere Kampffertigkeiten erlernen (+1 Angriffsfertigkeit).", - "vcmi.townHall.greetingDefence" : "Wenn Ihr Zeit im %s verbringt, bringen Euch die erfahrenen Krieger dort zusätzliche Verteidigungsfähigkeiten bei (+1 Verteidigung).", - "vcmi.townHall.hasNotProduced" : "Die %s hat noch nichts produziert.", - "vcmi.townHall.hasProduced" : "Die %s hat diese Woche %d %s produziert.", - "vcmi.townHall.greetingCustomBonus" : "%s gibt Ihnen +%d %s%s", - "vcmi.townHall.greetingCustomUntil" : " bis zur nächsten Schlacht.", - "vcmi.townHall.greetingInTownMagicWell" : "%s hat Eure Zauberpunkte wieder auf das Maximum erhöht.", "vcmi.logicalExpressions.anyOf" : "Eines der folgenden:", "vcmi.logicalExpressions.allOf" : "Alles der folgenden:", diff --git a/Mods/vcmi/config/vcmi/polish.json b/Mods/vcmi/config/vcmi/polish.json index ceac0bd9a..cd20e3ee1 100644 --- a/Mods/vcmi/config/vcmi/polish.json +++ b/Mods/vcmi/config/vcmi/polish.json @@ -18,8 +18,8 @@ "vcmi.adventureMap.noTownWithTavern" : "Brak dostępnego miasta z karczmą!", "vcmi.adventureMap.spellUnknownProblem" : "Nieznany problem z zaklęciem, brak dodatkowych informacji.", "vcmi.adventureMap.playerAttacked" : "Gracz został zaatakowany: %s", - "vcmi.adventureMap.moveCostDetails" : "Punkty ruchu - Koszt: %TURNS tury + %POINTS punkty, Pozostałe punkty: %REMAINING", - "vcmi.adventureMap.moveCostDetailsNoTurns" : "Punkty ruchu - Koszt: %POINTS punkty, Pozostałe punkty: %REMAINING", + "vcmi.adventureMap.moveCostDetails" : "Punkty ruchu - Koszt: %TURNS tury + %POINTS punktów, Pozostanie: %REMAINING punktów", + "vcmi.adventureMap.moveCostDetailsNoTurns" : "Punkty ruchu - Koszt: %POINTS punktów, Pozostanie: %REMAINING punktów", "vcmi.adventureMap.replayOpponentTurnNotImplemented" : "Wybacz, powtórka ruchu wroga nie została jeszcze zaimplementowana!", "vcmi.capitalColors.0" : "Czerwony", @@ -72,6 +72,11 @@ "vcmi.lobby.noUnderground" : "brak podziemi", "vcmi.lobby.sortDate" : "Sortuj mapy według daty modyfikacji", "vcmi.lobby.backToLobby" : "Wróc do lobby", + "vcmi.lobby.author" : "Autor", + "vcmi.lobby.handicap" : "Balans", + "vcmi.lobby.handicap.resource" : "Przyznaje graczom zasoby na start, oprócz normalnych zasobów początkowych. Wartości ujemne są dozwolone, ale łącznie gracz nie może zaczynać na minus.", + "vcmi.lobby.handicap.income" : "Ustala procentowy współczynnik przychodu gracza. Zaokrąglone w górę.", + "vcmi.lobby.handicap.growth" : "Ustala współczynnik populacji stworzeń w miastach należących do gracza. Zaokrąglone w górę.", "vcmi.lobby.login.title" : "Lobby sieciowe VCMI", "vcmi.lobby.login.username" : "Użytkownik:", @@ -79,7 +84,7 @@ "vcmi.lobby.login.error" : "Błąd połączenia: %s", "vcmi.lobby.login.create" : "Nowe konto", "vcmi.lobby.login.login" : "Login", - "vcmi.lobby.login.as" : "Zaloguj jako %s", + "vcmi.lobby.login.as" : "Logowanie jako %s", "vcmi.lobby.header.rooms" : "Pokoje - %d", "vcmi.lobby.header.channels" : "Kanały tekstowe", "vcmi.lobby.header.chat.global" : "Chat globalny - %s", // %s -> language name @@ -88,7 +93,7 @@ "vcmi.lobby.header.history" : "Twoje poprzednie gry", "vcmi.lobby.header.players" : "Graczy online - %d", "vcmi.lobby.match.solo" : "Gra jednoosobowa", - "vcmi.lobby.match.duel" : "Graj z %s", // %s -> nickname of another player + "vcmi.lobby.match.duel" : "vs. %s", // %s -> nickname of another player "vcmi.lobby.match.multi" : "%d graczy", "vcmi.lobby.room.create" : "Stwórz nowy pokój", "vcmi.lobby.room.players.limit" : "Limit graczy", @@ -125,12 +130,12 @@ "vcmi.lobby.mod.state.version" : "Niepoprawna wersja", "vcmi.lobby.mod.state.excessive" : "Musi być wyłączony", "vcmi.lobby.mod.state.missing" : "Nie zainstalowany", - "vcmi.lobby.pvp.coin.hover" : "Moneta", - "vcmi.lobby.pvp.coin.help" : "Rzut monetą", - "vcmi.lobby.pvp.randomTown.hover" : "Losowe miasto", - "vcmi.lobby.pvp.randomTown.help" : "Wyświetli nazwę wylosowanego miasta na czacie", - "vcmi.lobby.pvp.randomTownVs.hover" : "Losowe miasto vs.", - "vcmi.lobby.pvp.randomTownVs.help" : "Wyświetli nazwę 2 wylosowanych miast na czacie", + "vcmi.lobby.pvp.coin.hover" : "Rzut monetą", + "vcmi.lobby.pvp.coin.help" : "Wyświetli symulację rzutu monetą na czacie, wskazując 0 lub 1 w zależności od rezultatu rzutu.", + "vcmi.lobby.pvp.randomTown.hover" : "Wylosuj miasto", + "vcmi.lobby.pvp.randomTown.help" : "Wyświetli nazwę wylosowanego miasta na czacie, które nie zostało zablokowane na liście", + "vcmi.lobby.pvp.randomTownVs.hover" : "Wylosuj 2 miasta", + "vcmi.lobby.pvp.randomTownVs.help" : "Wyświetli nazwę 2 wylosowanych miast na czacie, które nie zostały zablokowane na liście", "vcmi.lobby.pvp.versus" : "vs.", "vcmi.client.errors.invalidMap" : "{Błędna mapa lub kampania}\n\nNie udało się stworzyć gry! Wybrana mapa lub kampania jest niepoprawna lub uszkodzona. Powód:\n%s", @@ -237,6 +242,8 @@ "vcmi.battleOptions.skipBattleIntroMusic.help": "{Pomiń czekanie startowe}\n\n Pomija konieczność czekania podczas muzyki startowej, która jest odtwarzana na początku każdej bitwy przed rozpoczęciem akcji.", "vcmi.battleOptions.endWithAutocombat.hover": "Natychmiastowe auto-walki", "vcmi.battleOptions.endWithAutocombat.help": "{Natychmiastowe auto-walki}\n\nAuto-walka natychmiastowo toczy walkę do samego końca", + "vcmi.battleOptions.showQuickSpell.hover": "Szybki dostęp do magii", + "vcmi.battleOptions.showQuickSpell.help": "{Szybki dostęp do magii}\n\nPokazuje panel szybkiego dostępu do czarów", "vcmi.adventureMap.revisitObject.hover" : "Odwiedź obiekt ponownie", "vcmi.adventureMap.revisitObject.help" : "{Odwiedź obiekt ponownie}\n\nJeżeli bohater aktualnie stoi na polu odwiedzającym obiekt za pomocą tego przycisku może go odwiedzić ponownie.", @@ -285,17 +292,9 @@ "vcmi.townHall.missingBase" : "Podstawowy budynek %s musi zostać najpierw wybudowany", "vcmi.townHall.noCreaturesToRecruit" : "Brak stworzeń do rekrutacji!", - "vcmi.townHall.greetingManaVortex" : "Zbliżając się do %s czujesz jak twoje ciało wypełnia energia. Ilość pkt. magii, które posiadasz, zwiększa się dwukrotnie.", - "vcmi.townHall.greetingKnowledge" : "Studiując napisy na %s odkrywasz nowe aspekty stosowania magii (wiedza +1).", - "vcmi.townHall.greetingSpellPower" : "Odwiedzając %s dowiadujesz się, jak zwiększyć potęgę swojej mocy magicznej (moc +1).", - "vcmi.townHall.greetingExperience" : "Wizyta w %s zwiększa twoje doświadczenie (doświadczenie +1000).", - "vcmi.townHall.greetingAttack" : "Krótka wizyka w %s umożliwia ci polepszenie technik walki (atak +1).", - "vcmi.townHall.greetingDefence" : "Odwiedzasz %s. Doświadczeni żołnierze, którzy tam przebywają, uczą cię sztuki skutecznej obrony (obrona +1).", - "vcmi.townHall.hasNotProduced" : "%s nic jeszcze nie wyprodukował.", - "vcmi.townHall.hasProduced" : "%s wyprodukował w tym tygodniu: %d %s.", - "vcmi.townHall.greetingCustomBonus" : "%s daje tobie +%d %s%s", - "vcmi.townHall.greetingCustomUntil" : " do następnej bitwy.", - "vcmi.townHall.greetingInTownMagicWell" : "%s przywraca ci wszystkie punkty magii.", + + "vcmi.townStructure.bank.borrow" : "Wchodzisz do banku. Bankier cię widzi i mówi: \"Złożyliśmy ci specjalną ofertę. Możesz wziąć od nas pożyczkę w wysokości 2500 złota na 5 dni. Będziesz musiał spłacać 500 złota każdego dnia.\"", + "vcmi.townStructure.bank.payBack" : "Wchodzisz do banku. Bankier cię widzi i mówi: „Już dostałeś pożyczkę. Spłać ją zanim weźmiesz nową.\"", "vcmi.logicalExpressions.anyOf" : "Dowolne spośród:", "vcmi.logicalExpressions.allOf" : "Wszystkie spośród:", @@ -487,7 +486,7 @@ "core.bonus.ADDITIONAL_RETALIATION.name": "Dodatkowy odwet", "core.bonus.ADDITIONAL_RETALIATION.description": "${val} dodatkowy kontratak", "core.bonus.AIR_IMMUNITY.name": "Odporność: Powietrze", - "core.bonus.AIR_IMMUNITY.description": "Odporny na wszystkie czary szkoły powietrza", + "core.bonus.AIR_IMMUNITY.description": "Odporny na magię powietrza", "core.bonus.ATTACKS_ALL_ADJACENT.name": "Obrotowy atak", "core.bonus.ATTACKS_ALL_ADJACENT.description": "Atakuje wszystkich sąsiadujących wrogów", "core.bonus.BLOCKS_RETALIATION.name": "Bez kontrataku", @@ -509,13 +508,13 @@ "core.bonus.DEFENSIVE_STANCE.name": "Bonus do obrony", "core.bonus.DEFENSIVE_STANCE.description": "+${val} Obrony kiedy broni", "core.bonus.DESTRUCTION.name": "Destrukcja", - "core.bonus.DESTRUCTION.description": "Ma ${val}% szans na zabicie dodatkowych jednostek po ataku", + "core.bonus.DESTRUCTION.description": "${val}% szans na zabicie dodatkowych jednostek po ataku", "core.bonus.DOUBLE_DAMAGE_CHANCE.name": "Uderzenie Śmierci", "core.bonus.DOUBLE_DAMAGE_CHANCE.description": "${val}% szans na podwójne obrażenia", "core.bonus.DRAGON_NATURE.name": "Smok", "core.bonus.DRAGON_NATURE.description": "Stworzenie posiada smoczą naturę", "core.bonus.EARTH_IMMUNITY.name": "Odporność: Ziemia", - "core.bonus.EARTH_IMMUNITY.description": "Odporny na wszystkie czary szkoły ziemi", + "core.bonus.EARTH_IMMUNITY.description": "Odporny na magię ziemi", "core.bonus.ENCHANTER.name": "Czarodziej", "core.bonus.ENCHANTER.description": "Rzuca czar ${subtype.spell}", "core.bonus.ENCHANTED.name": "Zaczarowany", @@ -525,7 +524,7 @@ "core.bonus.ENEMY_DEFENCE_REDUCTION.name": "Osłabienie Obrony (${val}%)", "core.bonus.ENEMY_DEFENCE_REDUCTION.description": "Osłabia obronę wroga podczas ataku", "core.bonus.FIRE_IMMUNITY.name": "Odporność: Ogień", - "core.bonus.FIRE_IMMUNITY.description": "Odporny na wszystkie czary szkoły ognia", + "core.bonus.FIRE_IMMUNITY.description": "Odporny na magię ognia", "core.bonus.FIRE_SHIELD.name": "Ognista tarcza (${val}%)", "core.bonus.FIRE_SHIELD.description": "Odbija część obrażeń z walki wręcz", "core.bonus.FIRST_STRIKE.name": "Pierwsze Uderzenie", @@ -543,7 +542,7 @@ "core.bonus.GARGOYLE.name": "Gargulec", "core.bonus.GARGOYLE.description": "Nie może się wskrzesić i uleczyć", "core.bonus.GENERAL_DAMAGE_REDUCTION.name": "Redukcja obrażeń (${val}%)", - "core.bonus.GENERAL_DAMAGE_REDUCTION.description": "Zmiejsza obrażenia fizyczne z dystansu lub walki wręcz", + "core.bonus.GENERAL_DAMAGE_REDUCTION.description": "Zmiejsza obr. fizyczne z dystansu lub wręcz", "core.bonus.HATE.name": "${subtype.creature}", "core.bonus.HATE.description": "+${val}% dodatkowych obrażeń", "core.bonus.HEALER.name": "Uzdrowiciel", @@ -556,8 +555,8 @@ "core.bonus.KING.description": "czar POGROMCA stopnia ${val}+", "core.bonus.LEVEL_SPELL_IMMUNITY.name": "Odporność: Czary 1-${val}", "core.bonus.LEVEL_SPELL_IMMUNITY.description": "Odporny na czary 1-${val} poz.", - "core.bonus.LIMITED_SHOOTING_RANGE.name" : "Ograniczony zasięg strzelania", - "core.bonus.LIMITED_SHOOTING_RANGE.description" : "Nie może strzelać do celów będących dalej niż ${val} heksów", + "core.bonus.LIMITED_SHOOTING_RANGE.name" : "Nie może strzelać do", + "core.bonus.LIMITED_SHOOTING_RANGE.description" : "celów będących dalej niż ${val} heksów", "core.bonus.LIFE_DRAIN.name": "Wysysa życie (${val}%)", "core.bonus.LIFE_DRAIN.description": "Wysysa ${val}% zadanych obrażeń", "core.bonus.MANA_CHANNELING.name": "Transfer many ${val}%", @@ -591,13 +590,13 @@ "core.bonus.RETURN_AFTER_STRIKE.name": "Atak i Powrót", "core.bonus.RETURN_AFTER_STRIKE.description": "Wraca po ataku wręcz", "core.bonus.REVENGE.name": "Odwet", - "core.bonus.REVENGE.description": "Zadaje dodatkowe obrażenia zależne od strat własnych oddziału", + "core.bonus.REVENGE.description": "Zadaje dodat. obr. zależne od strat własnych oddziału", "core.bonus.SHOOTER.name": "Dystansowy", "core.bonus.SHOOTER.description": "Stworzenie może strzelać", "core.bonus.SHOOTS_ALL_ADJACENT.name": "Ostrzeliwuje wszystko dookoła", - "core.bonus.SHOOTS_ALL_ADJACENT.description": "Ataki dystansowe tego stworzenia uderzają we wszystkie cele na małym obszarze", + "core.bonus.SHOOTS_ALL_ADJACENT.description": "Ataki dyst. tego stworzenia uderzają we wszystkie cele na małym obszarze", "core.bonus.SOUL_STEAL.name": "Kradzież dusz", - "core.bonus.SOUL_STEAL.description": "Zdobywa ${val} nowych stworzeń za każdego zabitego wroga", + "core.bonus.SOUL_STEAL.description": "+${val} nowych stworzeń za każdego zabitego wroga", "core.bonus.SPELLCASTER.name": "Czarodziej", "core.bonus.SPELLCASTER.description": "Może rzucić ${subtype.spell}", "core.bonus.SPELL_AFTER_ATTACK.name": "${val}% szans na czar", diff --git a/Mods/vcmi/config/vcmi/portuguese.json b/Mods/vcmi/config/vcmi/portuguese.json index 5e1da5196..6df076d77 100644 --- a/Mods/vcmi/config/vcmi/portuguese.json +++ b/Mods/vcmi/config/vcmi/portuguese.json @@ -291,18 +291,8 @@ "vcmi.otherOptions.compactTownCreatureInfo.help" : "{Informações Compactas de Criaturas}\n\nMostra informações menores para criaturas da cidade no resumo da cidade (canto inferior esquerdo da tela da cidade).", "vcmi.townHall.missingBase" : "A construção base %s deve ser construída primeiro", - "vcmi.townHall.noCreaturesToRecruit" : "Não há criaturas para recrutar!", - "vcmi.townHall.greetingManaVortex" : "Ao se aproximar de %s, seu corpo é preenchido com nova energia. Você dobrou seus pontos de mana normais.", - "vcmi.townHall.greetingKnowledge" : "Estudando os glifos de %s, você adquire uma visão dos segredos sobre o funcionamento de várias magias (+1 de Conhecimento).", - "vcmi.townHall.greetingSpellPower" : "%s ensina novas maneiras de concentrar seus poderes mágicos (+1 de Força).", - "vcmi.townHall.greetingExperience" : "Uma visita em %s ensina muitas habilidades novas (+1000 de Experiência).", - "vcmi.townHall.greetingAttack" : "Algum tempo passado em %s permite que você aprenda habilidades de combate mais eficazes (+1 de Ataque).", - "vcmi.townHall.greetingDefence" : "Ao passar um tempo em %s, os guerreiros experientes lá dentro te ensinam habilidades defensivas adicionais (+1 de Defesa).", - "vcmi.townHall.hasNotProduced" : "%s ainda não produziu nada.", - "vcmi.townHall.hasProduced" : "%s produziu %d %s nesta semana.", - "vcmi.townHall.greetingCustomBonus" : "%s dá +%d %s%s", - "vcmi.townHall.greetingCustomUntil" : " até a próxima batalha.", - "vcmi.townHall.greetingInTownMagicWell" : "%s restaurou seus pontos de mana para o máximo.", + "vcmi.townHall.noCreaturesToRecruit" : "Não há criaturas para recrutar!", + "vcmi.logicalExpressions.anyOf" : "Qualquer um dos seguintes:", "vcmi.logicalExpressions.allOf" : "Todos os seguintes:", diff --git a/Mods/vcmi/config/vcmi/russian.json b/Mods/vcmi/config/vcmi/russian.json index 636d36d7c..ff088d60d 100644 --- a/Mods/vcmi/config/vcmi/russian.json +++ b/Mods/vcmi/config/vcmi/russian.json @@ -162,17 +162,6 @@ "vcmi.townHall.missingBase" : "Сначала необходимо построить: %s", "vcmi.townHall.noCreaturesToRecruit" : "Нет существ для найма!", - "vcmi.townHall.greetingManaVortex" : "Близ %s ваше тело наполняется новой силой. Ваша обычная магическая энергия ныне удвоена.", - "vcmi.townHall.greetingKnowledge" : "Вы изучили знаки %s, на вас снизошло прозрение в деле магии (+1 Знания).", - "vcmi.townHall.greetingSpellPower" : "В %s вас научили новым способам концентрации магической силы (+1 Силы)", - "vcmi.townHall.greetingExperience" : "Посетив %s, вы узнали много нового (+1000 опыта).", - "vcmi.townHall.greetingAttack" : "Пребывание в %s позволило вам лучше использовать боевые навыки (+1 Атаки).", - "vcmi.townHall.greetingDefence" : "В %s искушенные воины преподали вам свои защитные умения (+1 Защиты).", - "vcmi.townHall.hasNotProduced" : "В %s еще ничего не произведено.", - "vcmi.townHall.hasProduced" : "В %s на этой неделе произведено: %d %s", - "vcmi.townHall.greetingCustomBonus" : "%s дает вам +%d %s%s", - "vcmi.townHall.greetingCustomUntil" : " до следующей битвы.", - "vcmi.townHall.greetingInTownMagicWell" : "%s восстанавливает ваши очки заклинаний до максимума.", "vcmi.logicalExpressions.anyOf" : "Любое из:", "vcmi.logicalExpressions.allOf" : "Все перечисленное:", diff --git a/Mods/vcmi/config/vcmi/spanish.json b/Mods/vcmi/config/vcmi/spanish.json index c9d6b9a31..c4f4c5215 100644 --- a/Mods/vcmi/config/vcmi/spanish.json +++ b/Mods/vcmi/config/vcmi/spanish.json @@ -219,17 +219,6 @@ "vcmi.townHall.missingBase" : "Primero se debe construir el edificio base %s", "vcmi.townHall.noCreaturesToRecruit" : "¡No hay criaturas para reclutar!", - "vcmi.townHall.greetingManaVortex" : "Al acercarte a %s, tu cuerpo se llena de nueva energía. Has duplicado tus puntos de hechizo normales.", - "vcmi.townHall.greetingKnowledge" : "Estudias los glifos en %s y obtienes una visión de los entresijos de varias magias (+1 conocimiento).", - "vcmi.townHall.greetingSpellPower" : "El %s te enseña nuevas formas de enfocar tus poderes mágicos (+1 Poder).", - "vcmi.townHall.greetingExperience" : "Una visita a %s te enseña muchas habilidades nuevas (+1000 Experiencia).", - "vcmi.townHall.greetingAttack" : "El tiempo dedicado en %s te permite aprender habilidades de combate más efectivas (+1 habilidad de ataque).", - "vcmi.townHall.greetingDefence" : "Pasando tiempo en %s, los guerreros experimentados allí te enseñan habilidades defensivas adicionales (+1 Defensa).", - "vcmi.townHall.hasNotProduced" : "%s aún no ha producido nada.", - "vcmi.townHall.hasProduced" : "%s ha producido %d %s esta semana.", - "vcmi.townHall.greetingCustomBonus" : "%s te da +%d %s%s", - "vcmi.townHall.greetingCustomUntil" : " hasta la próxima batalla.", - "vcmi.townHall.greetingInTownMagicWell" : "%s ha restaurado tus puntos de hechizo al máximo.", "vcmi.logicalExpressions.anyOf" : "Cualquiera de lo siguiente:", "vcmi.logicalExpressions.allOf" : "Todo lo siguiente:", diff --git a/Mods/vcmi/config/vcmi/ukrainian.json b/Mods/vcmi/config/vcmi/ukrainian.json index 4a50e65ff..9ce7fa79c 100644 --- a/Mods/vcmi/config/vcmi/ukrainian.json +++ b/Mods/vcmi/config/vcmi/ukrainian.json @@ -285,17 +285,6 @@ "vcmi.townHall.missingBase" : "Спочатку необхідно звести початкову будівлю: %s", "vcmi.townHall.noCreaturesToRecruit" : "Немає істот, яких можна завербувати!", - "vcmi.townHall.greetingManaVortex" : "Неподалік %s ваше тіло наповнюється новою силою. Ваша звична магічна енергія сьогодні подвоєна.", - "vcmi.townHall.greetingKnowledge" : "Ви вивчили знаки на %s, і на вас зійшло прозріння у справах магії. (+1 Knowledge).", - "vcmi.townHall.greetingSpellPower" : "В %s вас навчили новим методам концентрації магічної сили. (+1 Power).", - "vcmi.townHall.greetingExperience" : "Відвідавши %s, ви дізналися багато нового. (+1000 Experience).", - "vcmi.townHall.greetingAttack" : "Перебування у %s дозволило вам краще використовувати бойові навички (+1 Attack Skill).", - "vcmi.townHall.greetingDefence" : "У %s досвідчені воїни виклали вам свої захисні вміння. (+1 Defense).", - "vcmi.townHall.hasNotProduced" : "Поки що %s нічого не створило.", - "vcmi.townHall.hasProduced" : "Цього тижня %s створило %d одиниць, цього разу це %s.", - "vcmi.townHall.greetingCustomBonus" : "%s дає вам +%d %s%s", - "vcmi.townHall.greetingCustomUntil" : " до наступної битви.", - "vcmi.townHall.greetingInTownMagicWell" : "%s повністю відновлює ваш запас очків магії.", "vcmi.logicalExpressions.anyOf" : "Будь-що з перерахованого:", "vcmi.logicalExpressions.allOf" : "Все з перерахованого:", diff --git a/Mods/vcmi/config/vcmi/vietnamese.json b/Mods/vcmi/config/vcmi/vietnamese.json index 5939c1db0..9b08b5e2b 100644 --- a/Mods/vcmi/config/vcmi/vietnamese.json +++ b/Mods/vcmi/config/vcmi/vietnamese.json @@ -159,17 +159,6 @@ "vcmi.townHall.missingBase": "Căn cứ %s phải được xây trước", "vcmi.townHall.noCreaturesToRecruit": "Không có quái để chiêu mộ!", - "vcmi.townHall.greetingManaVortex": "%s giúp cơ thể bạn tràn đầy năng lượng mới. Bạn được gấp đôi năng lượng tối đa.", - "vcmi.townHall.greetingKnowledge": "Bạn học chữ khắc trên %s và thấu hiểu cách vận hành của nhiều ma thuật (+1 Trí).", - "vcmi.townHall.greetingSpellPower": "%s dạy bạn hướng mới tập trung sức mạnh ma thuật (+1 Lực).", - "vcmi.townHall.greetingExperience": "Viếng thăm %s dạy bạn nhiều kĩ năng mới (+1000 Kinh nghiệm).", - "vcmi.townHall.greetingAttack": "Thời gian ở %s giúp bạn học nhiều kĩ năng chiến đấu hiệu quả (+1 Công).", - "vcmi.townHall.greetingDefence": "Thời gian ở %s, các chiến binh lão luyện tại đó dạy bạn nhiều kĩ năng phòng thủ (+1 Thủ).", - "vcmi.townHall.hasNotProduced": "%s chưa tạo được cái gì.", - "vcmi.townHall.hasProduced": "%s tạo %d %s tuần này.", - "vcmi.townHall.greetingCustomBonus": "%s cho bạn +%d %s%s", - "vcmi.townHall.greetingCustomUntil": " đến trận đánh tiếp theo.", - "vcmi.townHall.greetingInTownMagicWell": "%s đã hồi phục năng lượng tối đa của bạn.", "vcmi.logicalExpressions.anyOf": "Bất kì cái sau:", "vcmi.logicalExpressions.allOf": "Tất cả cái sau:", diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index ddc99c4b8..563e8a0ef 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -98,6 +98,7 @@ set(client_SRCS renderSDL/CTrueTypeFont.cpp renderSDL/CursorHardware.cpp renderSDL/CursorSoftware.cpp + renderSDL/ImageScaled.cpp renderSDL/RenderHandler.cpp renderSDL/SDLImage.cpp renderSDL/SDLImageLoader.cpp @@ -172,6 +173,8 @@ set(client_SRCS windows/settings/BattleOptionsTab.cpp windows/settings/AdventureOptionsTab.cpp + xBRZ/xbrz.cpp + ArtifactsUIController.cpp CGameInfo.cpp CMT.cpp @@ -303,6 +306,7 @@ set(client_HEADERS renderSDL/CTrueTypeFont.h renderSDL/CursorHardware.h renderSDL/CursorSoftware.h + renderSDL/ImageScaled.h renderSDL/RenderHandler.h renderSDL/SDLImage.h renderSDL/SDLImageLoader.h @@ -380,6 +384,9 @@ set(client_HEADERS windows/settings/BattleOptionsTab.h windows/settings/AdventureOptionsTab.h + xBRZ/xbrz.h + xBRZ/xbrz_tools.h + ArtifactsUIController.h CGameInfo.h CMT.h diff --git a/client/CPlayerInterface.cpp b/client/CPlayerInterface.cpp index b55c5bdd6..7f83bbc04 100644 --- a/client/CPlayerInterface.cpp +++ b/client/CPlayerInterface.cpp @@ -1145,7 +1145,7 @@ void CPlayerInterface::showMapObjectSelectDialog(QueryID askID, const Component if(t) { auto image = GH.renderHandler().loadImage(AnimationPath::builtin("ITPA"), t->town->clientInfo.icons[t->hasFort()][false] + 2, 0, EImageBlitMode::OPAQUE); - image->scaleFast(Point(35, 23)); + image->scaleTo(Point(35, 23)); images.push_back(image); } } diff --git a/client/adventureMap/AdventureMapInterface.cpp b/client/adventureMap/AdventureMapInterface.cpp index 24f660d2e..6d6cd8ff5 100644 --- a/client/adventureMap/AdventureMapInterface.cpp +++ b/client/adventureMap/AdventureMapInterface.cpp @@ -453,7 +453,7 @@ void AdventureMapInterface::onPlayerTurnStarted(PlayerColor playerID) widget->getInfoBar()->showDate(); onHeroChanged(nullptr); - Canvas canvas = Canvas::createFromSurface(screen); + Canvas canvas = Canvas::createFromSurface(screen, CanvasScalingPolicy::AUTO); showAll(canvas); mapAudio->onPlayerTurnStarted(); diff --git a/client/adventureMap/CMinimap.cpp b/client/adventureMap/CMinimap.cpp index a40b31d93..bc3cd2c10 100644 --- a/client/adventureMap/CMinimap.cpp +++ b/client/adventureMap/CMinimap.cpp @@ -73,7 +73,7 @@ void CMinimapInstance::redrawMinimap() CMinimapInstance::CMinimapInstance(CMinimap *Parent, int Level): parent(Parent), - minimap(new Canvas(Point(LOCPLINT->cb->getMapSize().x, LOCPLINT->cb->getMapSize().y))), + minimap(new Canvas(Point(LOCPLINT->cb->getMapSize().x, LOCPLINT->cb->getMapSize().y), CanvasScalingPolicy::IGNORE)), level(Level) { pos.w = parent->pos.w; diff --git a/client/battle/BattleFieldController.cpp b/client/battle/BattleFieldController.cpp index 8237cdaf3..409a95bab 100644 --- a/client/battle/BattleFieldController.cpp +++ b/client/battle/BattleFieldController.cpp @@ -124,6 +124,8 @@ BattleFieldController::BattleFieldController(BattleInterface & owner): rangedFullDamageLimitImages = GH.renderHandler().loadAnimation(AnimationPath::builtin("battle/rangeHighlights/rangeHighlightsGreen.json"), EImageBlitMode::COLORKEY); shootingRangeLimitImages = GH.renderHandler().loadAnimation(AnimationPath::builtin("battle/rangeHighlights/rangeHighlightsRed.json"), EImageBlitMode::COLORKEY); + cellShade->setShadowEnabled(true); + if(!owner.siegeController) { auto bfieldType = owner.getBattle()->battleGetBattlefieldType(); @@ -142,7 +144,7 @@ BattleFieldController::BattleFieldController(BattleInterface & owner): pos.w = background->width(); pos.h = background->height(); - backgroundWithHexes = std::make_unique(Point(background->width(), background->height())); + backgroundWithHexes = std::make_unique(Point(background->width(), background->height()), CanvasScalingPolicy::AUTO); updateAccessibleHexes(); addUsedEvents(LCLICK | SHOW_POPUP | MOVE | TIME | GESTURE); diff --git a/client/battle/CreatureAnimation.cpp b/client/battle/CreatureAnimation.cpp index 8fcfd1aeb..b028a597f 100644 --- a/client/battle/CreatureAnimation.cpp +++ b/client/battle/CreatureAnimation.cpp @@ -323,33 +323,6 @@ static ColorRGBA genBorderColor(ui8 alpha, const ColorRGBA & base) return ColorRGBA(base.r, base.g, base.b, ui8(base.a * alpha / 256)); } -static ui8 mixChannels(ui8 c1, ui8 c2, ui8 a1, ui8 a2) -{ - return c1*a1 / 256 + c2*a2*(255 - a1) / 256 / 256; -} - -static ColorRGBA addColors(const ColorRGBA & base, const ColorRGBA & over) -{ - return ColorRGBA( - mixChannels(over.r, base.r, over.a, base.a), - mixChannels(over.g, base.g, over.a, base.a), - mixChannels(over.b, base.b, over.a, base.a), - ui8(over.a + base.a * (255 - over.a) / 256) - ); -} - -void CreatureAnimation::genSpecialPalette(IImage::SpecialPalette & target) -{ - target.resize(8); - target[0] = genShadow(0); - target[1] = genShadow(shadowAlpha / 2); - // colors 2 & 3 are not used in creatures - target[4] = genShadow(shadowAlpha); - target[5] = genBorderColor(getBorderStrength(elapsedTime), border); - target[6] = addColors(genShadow(shadowAlpha), genBorderColor(getBorderStrength(elapsedTime), border)); - target[7] = addColors(genShadow(shadowAlpha / 2), genBorderColor(getBorderStrength(elapsedTime), border)); -} - void CreatureAnimation::nextFrame(Canvas & canvas, const ColorFilter & shifter, bool facingRight) { ColorRGBA shadowTest = shifter.shiftColor(genShadow(128)); @@ -366,11 +339,12 @@ void CreatureAnimation::nextFrame(Canvas & canvas, const ColorFilter & shifter, if(image) { - IImage::SpecialPalette SpecialPalette; - genSpecialPalette(SpecialPalette); + image->setShadowEnabled(true); + image->setOverlayEnabled(isIdle()); + if (isIdle()) + image->setOverlayColor(genBorderColor(getBorderStrength(elapsedTime), border)); - image->setSpecialPalette(SpecialPalette, IImage::SPECIAL_PALETTE_MASK_CREATURES); - image->adjustPalette(shifter, IImage::SPECIAL_PALETTE_MASK_CREATURES); + image->adjustPalette(shifter, 0); canvas.draw(image, pos.topLeft(), Rect(0, 0, pos.w, pos.h)); diff --git a/client/battle/CreatureAnimation.h b/client/battle/CreatureAnimation.h index 46d4d87da..09e3fd259 100644 --- a/client/battle/CreatureAnimation.h +++ b/client/battle/CreatureAnimation.h @@ -107,9 +107,7 @@ private: void endAnimation(); - void genSpecialPalette(IImage::SpecialPalette & target); public: - /// function(s) that will be called when animation ends, after reset to 1st frame /// NOTE that these functions will be fired only once CFunctionList onAnimationReset; diff --git a/client/eventsSDL/InputSourceMouse.cpp b/client/eventsSDL/InputSourceMouse.cpp index b8eb6e0b4..d043fa30f 100644 --- a/client/eventsSDL/InputSourceMouse.cpp +++ b/client/eventsSDL/InputSourceMouse.cpp @@ -16,6 +16,8 @@ #include "../gui/EventDispatcher.h" #include "../gui/MouseButton.h" +#include "../render/IScreenHandler.h" + #include "../../lib/Point.h" #include "../../lib/CConfigHandler.h" @@ -30,8 +32,8 @@ InputSourceMouse::InputSourceMouse() void InputSourceMouse::handleEventMouseMotion(const SDL_MouseMotionEvent & motion) { - Point newPosition(motion.x, motion.y); - Point distance(-motion.xrel, -motion.yrel); + Point newPosition = Point(motion.x, motion.y) / GH.screenHandler().getScalingFactor(); + Point distance= Point(-motion.xrel, -motion.yrel) / GH.screenHandler().getScalingFactor(); mouseButtonsMask = motion.state; @@ -45,7 +47,7 @@ void InputSourceMouse::handleEventMouseMotion(const SDL_MouseMotionEvent & motio void InputSourceMouse::handleEventMouseButtonDown(const SDL_MouseButtonEvent & button) { - Point position(button.x, button.y); + Point position = Point(button.x, button.y) / GH.screenHandler().getScalingFactor(); switch(button.button) { @@ -67,12 +69,12 @@ void InputSourceMouse::handleEventMouseButtonDown(const SDL_MouseButtonEvent & b void InputSourceMouse::handleEventMouseWheel(const SDL_MouseWheelEvent & wheel) { - GH.events().dispatchMouseScrolled(Point(wheel.x, wheel.y), GH.getCursorPosition()); + GH.events().dispatchMouseScrolled(Point(wheel.x, wheel.y) / GH.screenHandler().getScalingFactor(), GH.getCursorPosition()); } void InputSourceMouse::handleEventMouseButtonUp(const SDL_MouseButtonEvent & button) { - Point position(button.x, button.y); + Point position = Point(button.x, button.y) / GH.screenHandler().getScalingFactor(); switch(button.button) { diff --git a/client/gui/CGuiHandler.cpp b/client/gui/CGuiHandler.cpp index 9b0fbdb8d..67bd783bf 100644 --- a/client/gui/CGuiHandler.cpp +++ b/client/gui/CGuiHandler.cpp @@ -176,7 +176,7 @@ const Point & CGuiHandler::getCursorPosition() const Point CGuiHandler::screenDimensions() const { - return Point(screen->w, screen->h); + return screenHandlerInstance->getLogicalResolution(); } void CGuiHandler::drawFPSCounter() diff --git a/client/gui/CIntObject.cpp b/client/gui/CIntObject.cpp index 737263d54..7dc4dff85 100644 --- a/client/gui/CIntObject.cpp +++ b/client/gui/CIntObject.cpp @@ -238,12 +238,12 @@ void CIntObject::redraw() } else { - Canvas buffer = Canvas::createFromSurface(screenBuf); + Canvas buffer = Canvas::createFromSurface(screenBuf, CanvasScalingPolicy::AUTO); showAll(buffer); if(screenBuf != screen) { - Canvas screenBuffer = Canvas::createFromSurface(screen); + Canvas screenBuffer = Canvas::createFromSurface(screen, CanvasScalingPolicy::AUTO); showAll(screenBuffer); } diff --git a/client/gui/WindowHandler.cpp b/client/gui/WindowHandler.cpp index ba8066089..6c5940c30 100644 --- a/client/gui/WindowHandler.cpp +++ b/client/gui/WindowHandler.cpp @@ -111,7 +111,7 @@ void WindowHandler::totalRedrawImpl() { logGlobal->debug("totalRedraw requested!"); - Canvas target = Canvas::createFromSurface(screen2); + Canvas target = Canvas::createFromSurface(screen2, CanvasScalingPolicy::AUTO); for(auto & elem : windowsStack) elem->showAll(target); @@ -134,7 +134,7 @@ void WindowHandler::simpleRedrawImpl() if(windowsStack.size() > 1) CSDL_Ext::blitAt(screen2, 0, 0, screen); //blit background - Canvas target = Canvas::createFromSurface(screen); + Canvas target = Canvas::createFromSurface(screen, CanvasScalingPolicy::AUTO); if(!windowsStack.empty()) windowsStack.back()->show(target); //blit active interface/window diff --git a/client/mapView/MapRenderer.cpp b/client/mapView/MapRenderer.cpp index bbd3b6001..2de3592eb 100644 --- a/client/mapView/MapRenderer.cpp +++ b/client/mapView/MapRenderer.cpp @@ -21,6 +21,7 @@ #include "../render/IImage.h" #include "../render/IRenderHandler.h" #include "../render/Colors.h" +#include "../render/Graphics.h" #include "../../CCallback.h" @@ -477,23 +478,20 @@ void MapRendererObjects::renderImage(IMapRendererContext & context, Canvas & tar return; image->setAlpha(transparency); - image->setFlagColor(object->tempOwner); + image->setShadowEnabled(true); + image->setOverlayEnabled(object->getOwner().isValidPlayer() || object->getOwner() == PlayerColor::NEUTRAL); + + if (object->getOwner().isValidPlayer()) + image->setOverlayColor(graphics->playerColors[object->getOwner().getNum()]); + + if (object->getOwner() == PlayerColor::NEUTRAL) + image->setOverlayColor(graphics->neutralColor); Point offsetPixels = context.objectImageOffset(object->id, coordinates); if ( offsetPixels.x < image->dimensions().x && offsetPixels.y < image->dimensions().y) { Point imagePos = image->dimensions() - offsetPixels - Point(32, 32); - - //if (transparency == 255) - //{ - // Canvas intermediate(Point(32,32)); - // intermediate.enableTransparency(true); - // image->setBlitMode(EImageBlitMode::OPAQUE); - // intermediate.draw(image, Point(0, 0), Rect(imagePos, Point(32,32))); - // target.draw(intermediate, Point(0,0)); - // return; - //} target.draw(image, Point(0, 0), Rect(imagePos, Point(32,32))); } } diff --git a/client/mapView/MapRenderer.h b/client/mapView/MapRenderer.h index 46bbca888..e5bc2066c 100644 --- a/client/mapView/MapRenderer.h +++ b/client/mapView/MapRenderer.h @@ -23,7 +23,7 @@ class CAnimation; class IImage; class Canvas; class IMapRendererContext; -enum class EImageBlitMode; +enum class EImageBlitMode : uint8_t; class MapTileStorage { diff --git a/client/mapView/MapViewCache.cpp b/client/mapView/MapViewCache.cpp index 30085081b..bac30fcf2 100644 --- a/client/mapView/MapViewCache.cpp +++ b/client/mapView/MapViewCache.cpp @@ -36,9 +36,9 @@ MapViewCache::MapViewCache(const std::shared_ptr & model) , overlayWasVisible(false) , mapRenderer(new MapRenderer()) , iconsStorage(GH.renderHandler().loadAnimation(AnimationPath::builtin("VwSymbol"), EImageBlitMode::COLORKEY)) - , intermediate(new Canvas(Point(32, 32))) - , terrain(new Canvas(model->getCacheDimensionsPixels())) - , terrainTransition(new Canvas(model->getPixelsVisibleDimensions())) + , intermediate(new Canvas(Point(32, 32), CanvasScalingPolicy::AUTO)) + , terrain(new Canvas(model->getCacheDimensionsPixels(), CanvasScalingPolicy::AUTO)) + , terrainTransition(new Canvas(model->getPixelsVisibleDimensions(), CanvasScalingPolicy::AUTO)) { Point visibleSize = model->getTilesVisibleDimensions(); terrainChecksum.resize(boost::extents[visibleSize.x][visibleSize.y]); diff --git a/client/media/CVideoHandler.cpp b/client/media/CVideoHandler.cpp index 6c104c7c8..d9ed30168 100644 --- a/client/media/CVideoHandler.cpp +++ b/client/media/CVideoHandler.cpp @@ -19,6 +19,7 @@ #include "../eventsSDL/InputHandler.h" #include "../gui/CGuiHandler.h" #include "../render/Canvas.h" +#include "../render/IScreenHandler.h" #include "../renderSDL/SDL_Extensions.h" #include "../../lib/filesystem/CInputStream.h" @@ -182,8 +183,7 @@ void CVideoInstance::prepareOutput(bool scaleToScreenSize, bool useTextureOutput } else { - dimensions.x = getCodecContext()->width; - dimensions.y = getCodecContext()->height; + dimensions = Point(getCodecContext()->width, getCodecContext()->height) * GH.screenHandler().getScalingFactor(); } // Allocate a place to put our YUV image on that screen @@ -207,7 +207,7 @@ void CVideoInstance::prepareOutput(bool scaleToScreenSize, bool useTextureOutput } else { - surface = CSDL_Ext::newSurface(dimensions.x, dimensions.y); + surface = CSDL_Ext::newSurface(dimensions); sws = sws_getContext(getCodecContext()->width, getCodecContext()->height, getCodecContext()->pix_fmt, dimensions.x, dimensions.y, AV_PIX_FMT_RGB32, SWS_BICUBIC, nullptr, nullptr, nullptr); @@ -362,7 +362,7 @@ void CVideoInstance::show(const Point & position, Canvas & canvas) if(sws == nullptr) throw std::runtime_error("No video to show!"); - CSDL_Ext::blitSurface(surface, canvas.getInternalSurface(), position); + CSDL_Ext::blitSurface(surface, canvas.getInternalSurface(), position * GH.screenHandler().getScalingFactor()); } double FFMpegStream::getCurrentFrameEndTime() const @@ -639,7 +639,7 @@ bool CVideoPlayer::playIntroVideo(const VideoPath & name) void CVideoPlayer::playSpellbookAnimation(const VideoPath & name, const Point & position) { - openAndPlayVideoImpl(name, position, false, false, false); + openAndPlayVideoImpl(name, position * GH.screenHandler().getScalingFactor(), false, false, false); } std::unique_ptr CVideoPlayer::open(const VideoPath & name, bool scaleToScreen) diff --git a/client/render/CAnimation.cpp b/client/render/CAnimation.cpp index 32ef57e60..eeafff200 100644 --- a/client/render/CAnimation.cpp +++ b/client/render/CAnimation.cpp @@ -13,6 +13,7 @@ #include "../gui/CGuiHandler.h" #include "../render/IImage.h" #include "../render/IRenderHandler.h" +#include "../render/IScreenHandler.h" #include "../../lib/filesystem/Filesystem.h" #include "../../lib/json/JsonUtils.h" diff --git a/client/render/CDefFile.cpp b/client/render/CDefFile.cpp index 1c8670a09..4501b40d2 100644 --- a/client/render/CDefFile.cpp +++ b/client/render/CDefFile.cpp @@ -36,48 +36,10 @@ enum class DefType : uint32_t * DefFile, class used for def loading * *************************************************************************/ -static bool colorsSimilar (const SDL_Color & lhs, const SDL_Color & rhs) -{ - // it seems that H3 does not requires exact match to replace colors -> (255, 103, 255) gets interpreted as shadow - // exact logic is not clear and requires extensive testing with image editing - // potential reason is that H3 uses 16-bit color format (565 RGB bits), meaning that 3 least significant bits are lost in red and blue component - static const int threshold = 8; - - int diffR = static_cast(lhs.r) - rhs.r; - int diffG = static_cast(lhs.g) - rhs.g; - int diffB = static_cast(lhs.b) - rhs.b; - int diffA = static_cast(lhs.a) - rhs.a; - - return std::abs(diffR) < threshold && std::abs(diffG) < threshold && std::abs(diffB) < threshold && std::abs(diffA) < threshold; -} - CDefFile::CDefFile(const AnimationPath & Name): data(nullptr), palette(nullptr) { - //First 8 colors in def palette used for transparency - static const SDL_Color sourcePalette[8] = { - {0, 255, 255, SDL_ALPHA_OPAQUE}, - {255, 150, 255, SDL_ALPHA_OPAQUE}, - {255, 100, 255, SDL_ALPHA_OPAQUE}, - {255, 50, 255, SDL_ALPHA_OPAQUE}, - {255, 0, 255, SDL_ALPHA_OPAQUE}, - {255, 255, 0, SDL_ALPHA_OPAQUE}, - {180, 0, 255, SDL_ALPHA_OPAQUE}, - {0, 255, 0, SDL_ALPHA_OPAQUE} - }; - - static const SDL_Color targetPalette[8] = { - {0, 0, 0, 0 }, // transparency ( used in most images ) - {0, 0, 0, 64 }, // shadow border ( used in battle, adventure map def's ) - {0, 0, 0, 64 }, // shadow border ( used in fog-of-war def's ) - {0, 0, 0, 128}, // shadow body ( used in fog-of-war def's ) - {0, 0, 0, 128}, // shadow body ( used in battle, adventure map def's ) - {0, 0, 0, 0 }, // selection / owner flag ( used in battle, adventure map def's ) - {0, 0, 0, 128}, // shadow body below selection ( used in battle def's ) - {0, 0, 0, 64 } // shadow border below selection ( used in battle def's ) - }; - data = CResourceHandler::get()->load(Name)->readAll().first; palette = std::unique_ptr(new SDL_Color[256]); @@ -99,18 +61,6 @@ CDefFile::CDefFile(const AnimationPath & Name): palette[i].a = SDL_ALPHA_OPAQUE; } - // these colors seems to be used unconditionally - palette[0] = targetPalette[0]; - palette[1] = targetPalette[1]; - palette[4] = targetPalette[4]; - - // rest of special colors are used only if their RGB values are close to H3 - for (uint32_t i = 0; i < 8; ++i) - { - if (colorsSimilar(sourcePalette[i], palette[i])) - palette[i] = targetPalette[i]; - } - for (ui32 i=0; i #include -Canvas::Canvas(SDL_Surface * surface): +Canvas::Canvas(SDL_Surface * surface, CanvasScalingPolicy scalingPolicy): + scalingPolicy(scalingPolicy), surface(surface), renderArea(0,0, surface->w, surface->h) { @@ -27,6 +30,7 @@ Canvas::Canvas(SDL_Surface * surface): } Canvas::Canvas(const Canvas & other): + scalingPolicy(other.scalingPolicy), surface(other.surface), renderArea(other.renderArea) { @@ -34,6 +38,7 @@ Canvas::Canvas(const Canvas & other): } Canvas::Canvas(Canvas && other): + scalingPolicy(other.scalingPolicy), surface(other.surface), renderArea(other.renderArea) { @@ -43,20 +48,39 @@ Canvas::Canvas(Canvas && other): Canvas::Canvas(const Canvas & other, const Rect & newClipRect): Canvas(other) { - renderArea = other.renderArea.intersect(newClipRect + other.renderArea.topLeft()); + Rect scaledClipRect( transformPos(newClipRect.topLeft()), transformPos(newClipRect.dimensions())); + renderArea = other.renderArea.intersect(scaledClipRect + other.renderArea.topLeft()); } -Canvas::Canvas(const Point & size): - renderArea(Point(0,0), size), - surface(CSDL_Ext::newSurface(size.x, size.y)) +Canvas::Canvas(const Point & size, CanvasScalingPolicy scalingPolicy): + scalingPolicy(scalingPolicy), + surface(CSDL_Ext::newSurface(size * getScalingFactor())), + renderArea(Point(0,0), size * getScalingFactor()) { CSDL_Ext::fillSurface(surface, CSDL_Ext::toSDL(Colors::TRANSPARENCY) ); SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_NONE); } -Canvas Canvas::createFromSurface(SDL_Surface * surface) +int Canvas::getScalingFactor() const { - return Canvas(surface); + if (scalingPolicy == CanvasScalingPolicy::IGNORE) + return 1; + return GH.screenHandler().getScalingFactor(); +} + +Point Canvas::transformPos(const Point & input) +{ + return renderArea.topLeft() + input * getScalingFactor(); +} + +Point Canvas::transformSize(const Point & input) +{ + return input * getScalingFactor(); +} + +Canvas Canvas::createFromSurface(SDL_Surface * surface, CanvasScalingPolicy scalingPolicy) +{ + return Canvas(surface, scalingPolicy); } void Canvas::applyTransparency(bool on) @@ -81,19 +105,20 @@ void Canvas::draw(const std::shared_ptr& image, const Point & pos) { assert(image); if (image) - image->draw(surface, pos + renderArea.topLeft()); + image->draw(surface, transformPos(pos)); } void Canvas::draw(const std::shared_ptr& image, const Point & pos, const Rect & sourceRect) { + Rect realSourceRect = sourceRect * getScalingFactor(); assert(image); if (image) - image->draw(surface, pos + renderArea.topLeft(), &sourceRect); + image->draw(surface, transformPos(pos), &realSourceRect); } void Canvas::draw(const Canvas & image, const Point & pos) { - CSDL_Ext::blitSurface(image.surface, image.renderArea, surface, renderArea.topLeft() + pos); + CSDL_Ext::blitSurface(image.surface, image.renderArea, surface, transformPos(pos)); } void Canvas::drawTransparent(const Canvas & image, const Point & pos, double transparency) @@ -103,42 +128,38 @@ void Canvas::drawTransparent(const Canvas & image, const Point & pos, double tra SDL_GetSurfaceBlendMode(image.surface, &oldMode); SDL_SetSurfaceBlendMode(image.surface, SDL_BLENDMODE_BLEND); SDL_SetSurfaceAlphaMod(image.surface, 255 * transparency); - CSDL_Ext::blitSurface(image.surface, image.renderArea, surface, renderArea.topLeft() + pos); + CSDL_Ext::blitSurface(image.surface, image.renderArea, surface, transformPos(pos)); SDL_SetSurfaceAlphaMod(image.surface, 255); SDL_SetSurfaceBlendMode(image.surface, oldMode); } void Canvas::drawScaled(const Canvas & image, const Point & pos, const Point & targetSize) { - SDL_Rect targetRect = CSDL_Ext::toSDL(Rect(pos + renderArea.topLeft(), targetSize)); + SDL_Rect targetRect = CSDL_Ext::toSDL(Rect(transformPos(pos), transformSize(targetSize))); SDL_BlitScaled(image.surface, nullptr, surface, &targetRect); } void Canvas::drawPoint(const Point & dest, const ColorRGBA & color) { - CSDL_Ext::putPixelWithoutRefreshIfInSurf(surface, dest.x, dest.y, color.r, color.g, color.b, color.a); + Point point = transformPos(dest); + CSDL_Ext::putPixelWithoutRefreshIfInSurf(surface, point.x, point.y, color.r, color.g, color.b, color.a); } void Canvas::drawLine(const Point & from, const Point & dest, const ColorRGBA & colorFrom, const ColorRGBA & colorDest) { - CSDL_Ext::drawLine(surface, renderArea.topLeft() + from, renderArea.topLeft() + dest, CSDL_Ext::toSDL(colorFrom), CSDL_Ext::toSDL(colorDest)); -} - -void Canvas::drawLineDashed(const Point & from, const Point & dest, const ColorRGBA & color) -{ - CSDL_Ext::drawLineDashed(surface, renderArea.topLeft() + from, renderArea.topLeft() + dest, CSDL_Ext::toSDL(color)); + CSDL_Ext::drawLine(surface, transformPos(from), transformPos(dest), CSDL_Ext::toSDL(colorFrom), CSDL_Ext::toSDL(colorDest), getScalingFactor()); } void Canvas::drawBorder(const Rect & target, const ColorRGBA & color, int width) { - Rect realTarget = target + renderArea.topLeft(); + Rect realTarget = target * getScalingFactor() + renderArea.topLeft(); - CSDL_Ext::drawBorder(surface, realTarget.x, realTarget.y, realTarget.w, realTarget.h, CSDL_Ext::toSDL(color), width); + CSDL_Ext::drawBorder(surface, realTarget.x, realTarget.y, realTarget.w, realTarget.h, CSDL_Ext::toSDL(color), width * getScalingFactor()); } void Canvas::drawBorderDashed(const Rect & target, const ColorRGBA & color) { - Rect realTarget = target + renderArea.topLeft(); + Rect realTarget = target * getScalingFactor() + renderArea.topLeft(); CSDL_Ext::drawLineDashed(surface, realTarget.topLeft(), realTarget.topRight(), CSDL_Ext::toSDL(color)); CSDL_Ext::drawLineDashed(surface, realTarget.bottomLeft(), realTarget.bottomRight(), CSDL_Ext::toSDL(color)); @@ -150,10 +171,10 @@ void Canvas::drawText(const Point & position, const EFonts & font, const ColorRG { switch (alignment) { - case ETextAlignment::TOPLEFT: return graphics->fonts[font]->renderTextLeft (surface, text, colorDest, renderArea.topLeft() + position); - case ETextAlignment::TOPCENTER: return graphics->fonts[font]->renderTextCenter(surface, text, colorDest, renderArea.topLeft() + position); - case ETextAlignment::CENTER: return graphics->fonts[font]->renderTextCenter(surface, text, colorDest, renderArea.topLeft() + position); - case ETextAlignment::BOTTOMRIGHT: return graphics->fonts[font]->renderTextRight (surface, text, colorDest, renderArea.topLeft() + position); + case ETextAlignment::TOPLEFT: return graphics->fonts[font]->renderTextLeft (surface, text, colorDest, transformPos(position)); + case ETextAlignment::TOPCENTER: return graphics->fonts[font]->renderTextCenter(surface, text, colorDest, transformPos(position)); + case ETextAlignment::CENTER: return graphics->fonts[font]->renderTextCenter(surface, text, colorDest, transformPos(position)); + case ETextAlignment::BOTTOMRIGHT: return graphics->fonts[font]->renderTextRight (surface, text, colorDest, transformPos(position)); } } @@ -161,23 +182,23 @@ void Canvas::drawText(const Point & position, const EFonts & font, const ColorRG { switch (alignment) { - case ETextAlignment::TOPLEFT: return graphics->fonts[font]->renderTextLinesLeft (surface, text, colorDest, renderArea.topLeft() + position); - case ETextAlignment::TOPCENTER: return graphics->fonts[font]->renderTextLinesCenter(surface, text, colorDest, renderArea.topLeft() + position); - case ETextAlignment::CENTER: return graphics->fonts[font]->renderTextLinesCenter(surface, text, colorDest, renderArea.topLeft() + position); - case ETextAlignment::BOTTOMRIGHT: return graphics->fonts[font]->renderTextLinesRight (surface, text, colorDest, renderArea.topLeft() + position); + case ETextAlignment::TOPLEFT: return graphics->fonts[font]->renderTextLinesLeft (surface, text, colorDest, transformPos(position)); + case ETextAlignment::TOPCENTER: return graphics->fonts[font]->renderTextLinesCenter(surface, text, colorDest, transformPos(position)); + case ETextAlignment::CENTER: return graphics->fonts[font]->renderTextLinesCenter(surface, text, colorDest, transformPos(position)); + case ETextAlignment::BOTTOMRIGHT: return graphics->fonts[font]->renderTextLinesRight (surface, text, colorDest, transformPos(position)); } } void Canvas::drawColor(const Rect & target, const ColorRGBA & color) { - Rect realTarget = target + renderArea.topLeft(); + Rect realTarget = (target + renderArea.topLeft()) * getScalingFactor(); CSDL_Ext::fillRect(surface, realTarget, CSDL_Ext::toSDL(color)); } void Canvas::drawColorBlended(const Rect & target, const ColorRGBA & color) { - Rect realTarget = target + renderArea.topLeft(); + Rect realTarget = (target + renderArea.topLeft()) * getScalingFactor(); CSDL_Ext::fillRectBlended(surface, realTarget, CSDL_Ext::toSDL(color)); } diff --git a/client/render/Canvas.h b/client/render/Canvas.h index 7821a59fe..ae9b14fb9 100644 --- a/client/render/Canvas.h +++ b/client/render/Canvas.h @@ -17,9 +17,19 @@ struct SDL_Surface; class IImage; enum EFonts : int; +enum class CanvasScalingPolicy +{ + AUTO, // automatically scale canvas operations by global scaling factor + IGNORE // disable any scaling processing. Scaling factor will be set to 1 + +}; + /// Class that represents surface for drawing on class Canvas { + /// Upscaler awareness. Must be first member for initialization + CanvasScalingPolicy scalingPolicy; + /// Target surface SDL_Surface * surface; @@ -27,11 +37,14 @@ class Canvas Rect renderArea; /// constructs canvas using existing surface. Caller maintains ownership on the surface - explicit Canvas(SDL_Surface * surface); + explicit Canvas(SDL_Surface * surface, CanvasScalingPolicy scalingPolicy); /// copy constructor Canvas(const Canvas & other); + Point transformPos(const Point & input); + Point transformSize(const Point & input); + public: Canvas & operator = (const Canvas & other) = delete; Canvas & operator = (Canvas && other) = delete; @@ -43,11 +56,11 @@ public: Canvas(const Canvas & other, const Rect & clipRect); /// constructs canvas of specified size - explicit Canvas(const Point & size); + explicit Canvas(const Point & size, CanvasScalingPolicy scalingPolicy); /// constructs canvas using existing surface. Caller maintains ownership on the surface /// Compatibility method. AVOID USAGE. To be removed once SDL abstraction layer is finished. - static Canvas createFromSurface(SDL_Surface * surface); + static Canvas createFromSurface(SDL_Surface * surface, CanvasScalingPolicy scalingPolicy); ~Canvas(); @@ -78,9 +91,6 @@ public: /// renders continuous, 1-pixel wide line with color gradient void drawLine(const Point & from, const Point & dest, const ColorRGBA & colorFrom, const ColorRGBA & colorDest); - /// renders dashed, 1-pixel wide line with specified color - void drawLineDashed(const Point & from, const Point & dest, const ColorRGBA & color); - /// renders rectangular, solid-color border in specified location void drawBorder(const Rect & target, const ColorRGBA & color, int width = 1); @@ -102,6 +112,8 @@ public: /// fills canvas with texture void fillTexture(const std::shared_ptr& image); + int getScalingFactor() const; + /// Compatibility method. AVOID USAGE. To be removed once SDL abstraction layer is finished. SDL_Surface * getInternalSurface(); diff --git a/client/render/Colors.cpp b/client/render/Colors.cpp index d0bd8e23f..1b14130a9 100644 --- a/client/render/Colors.cpp +++ b/client/render/Colors.cpp @@ -15,6 +15,7 @@ const ColorRGBA Colors::YELLOW = { 229, 215, 123, ColorRGBA::ALPHA_OPAQUE }; const ColorRGBA Colors::WHITE = { 255, 243, 222, ColorRGBA::ALPHA_OPAQUE }; +const ColorRGBA Colors::WHITE_TRUE = { 255, 255, 255, ColorRGBA::ALPHA_OPAQUE }; const ColorRGBA Colors::METALLIC_GOLD = { 173, 142, 66, ColorRGBA::ALPHA_OPAQUE }; const ColorRGBA Colors::GREEN = { 0, 255, 0, ColorRGBA::ALPHA_OPAQUE }; const ColorRGBA Colors::CYAN = { 0, 255, 255, ColorRGBA::ALPHA_OPAQUE }; diff --git a/client/render/Colors.h b/client/render/Colors.h index ef046bd8f..cd643381b 100644 --- a/client/render/Colors.h +++ b/client/render/Colors.h @@ -23,6 +23,9 @@ public: /** the standard h3 white color */ static const ColorRGBA WHITE; + /** actual 100% white color */ + static const ColorRGBA WHITE_TRUE; + /** the metallic gold color used mostly as a border around buttons */ static const ColorRGBA METALLIC_GOLD; diff --git a/client/render/IFont.cpp b/client/render/IFont.cpp index e01e8e80a..3567a4da9 100644 --- a/client/render/IFont.cpp +++ b/client/render/IFont.cpp @@ -11,9 +11,18 @@ #include "StdInc.h" #include "IFont.h" +#include "../gui/CGuiHandler.h" + +#include "../render/IScreenHandler.h" + #include "../../lib/Point.h" #include "../../lib/texts/TextOperations.h" +int IFont::getScalingFactor() const +{ + return GH.screenHandler().getScalingFactor(); +} + size_t IFont::getStringWidth(const std::string & data) const { size_t width = 0; @@ -32,13 +41,13 @@ void IFont::renderTextLeft(SDL_Surface * surface, const std::string & data, cons void IFont::renderTextRight(SDL_Surface * surface, const std::string & data, const ColorRGBA & color, const Point & pos) const { - Point size((int)getStringWidth(data), (int)getLineHeight()); + Point size = Point(getStringWidth(data), getLineHeight()) * getScalingFactor(); renderText(surface, data, color, pos - size); } void IFont::renderTextCenter(SDL_Surface * surface, const std::string & data, const ColorRGBA & color, const Point & pos) const { - Point size((int)getStringWidth(data), (int)getLineHeight()); + Point size = Point(getStringWidth(data), getLineHeight()) * getScalingFactor(); renderText(surface, data, color, pos - size / 2); } @@ -49,31 +58,31 @@ void IFont::renderTextLinesLeft(SDL_Surface * surface, const std::vector & data, const ColorRGBA & color, const Point & pos) const { Point currPos = pos; - currPos.y -= (int)data.size() * (int)getLineHeight(); + currPos.y -= data.size() * getLineHeight() * getScalingFactor(); for(const std::string & line : data) { renderTextRight(surface, line, color, currPos); - currPos.y += (int)getLineHeight(); + currPos.y += getLineHeight() * getScalingFactor(); } } void IFont::renderTextLinesCenter(SDL_Surface * surface, const std::vector & data, const ColorRGBA & color, const Point & pos) const { Point currPos = pos; - currPos.y -= (int)data.size() * (int)getLineHeight() / 2; + currPos.y -= data.size() * getLineHeight() / 2 * getScalingFactor(); for(const std::string & line : data) { renderTextCenter(surface, line, color, currPos); - currPos.y += (int)getLineHeight(); + currPos.y += getLineHeight() * getScalingFactor(); } } diff --git a/client/render/IFont.h b/client/render/IFont.h index 80575de93..8810c4931 100644 --- a/client/render/IFont.h +++ b/client/render/IFont.h @@ -16,12 +16,14 @@ VCMI_LIB_NAMESPACE_END struct SDL_Surface; -class IFont +class IFont : boost::noncopyable { protected: /// Internal function to render font, see renderTextLeft virtual void renderText(SDL_Surface * surface, const std::string & data, const ColorRGBA & color, const Point & pos) const = 0; + int getScalingFactor() const; + public: virtual ~IFont() {} diff --git a/client/render/IImage.h b/client/render/IImage.h index 6247c1269..16637ca4f 100644 --- a/client/render/IImage.h +++ b/client/render/IImage.h @@ -21,10 +21,12 @@ class ColorRGBA; VCMI_LIB_NAMESPACE_END struct SDL_Surface; +struct SDL_Palette; class ColorFilter; +class ISharedImage; /// Defines which blit method will be selected when image is used for rendering -enum class EImageBlitMode +enum class EImageBlitMode : uint8_t { /// Preferred for images that don't need any background /// Indexed or RGBA: Image can have no transparency and can be only used as background @@ -40,28 +42,22 @@ enum class EImageBlitMode ALPHA }; -/* - * Base class for images, can be used for non-animation pictures as well - */ +/// Base class for images for use in client code. +/// This class represents current state of image, with potential transformations applied, such as player coloring class IImage { public: - using SpecialPalette = std::vector; - static constexpr int32_t SPECIAL_PALETTE_MASK_CREATURES = 0b11110011; - //draws image on surface "where" at position virtual void draw(SDL_Surface * where, const Point & pos, const Rect * src = nullptr) const = 0; - virtual void scaleFast(const Point & size) = 0; + virtual void scaleTo(const Point & size) = 0; + virtual void scaleInteger(int factor) = 0; virtual void exportBitmap(const boost::filesystem::path & path) const = 0; //Change palette to specific player virtual void playerColored(PlayerColor player) = 0; - //set special color for flag - virtual void setFlagColor(PlayerColor player) = 0; - //test transparency of specific pixel virtual bool isTransparent(const Point & coords) const = 0; @@ -77,23 +73,34 @@ public: virtual void setBlitMode(EImageBlitMode mode) = 0; //only indexed bitmaps with 7 special colors - virtual void setSpecialPalette(const SpecialPalette & SpecialPalette, uint32_t colorsToSkipMask) = 0; + virtual void setOverlayColor(const ColorRGBA & color) = 0; + + virtual void setShadowEnabled(bool on) = 0; + virtual void setBodyEnabled(bool on) = 0; + virtual void setOverlayEnabled(bool on) = 0; + virtual std::shared_ptr getSharedImage() const = 0; virtual ~IImage() = default; }; -class IConstImage +/// Base class for image data, mostly for internal use +/// Represents unmodified pixel data, usually loaded from file +/// This image can be shared between multiple image handlers (IImage instances) +class ISharedImage { public: virtual Point dimensions() const = 0; virtual void exportBitmap(const boost::filesystem::path & path) const = 0; virtual bool isTransparent(const Point & coords) const = 0; + virtual void draw(SDL_Surface * where, SDL_Palette * palette, const Point & dest, const Rect * src, const ColorRGBA & colorMultiplier, uint8_t alpha, EImageBlitMode mode) const = 0; virtual std::shared_ptr createImageReference(EImageBlitMode mode) = 0; - virtual std::shared_ptr horizontalFlip() const = 0; - virtual std::shared_ptr verticalFlip() const = 0; + virtual std::shared_ptr horizontalFlip() const = 0; + virtual std::shared_ptr verticalFlip() const = 0; + virtual std::shared_ptr scaleInteger(int factor, SDL_Palette * palette) const = 0; + virtual std::shared_ptr scaleTo(const Point & size, SDL_Palette * palette) const = 0; - virtual ~IConstImage() = default; + virtual ~ISharedImage() = default; }; diff --git a/client/render/IRenderHandler.h b/client/render/IRenderHandler.h index aa16e4acf..a28ced240 100644 --- a/client/render/IRenderHandler.h +++ b/client/render/IRenderHandler.h @@ -19,7 +19,7 @@ struct SDL_Surface; class IImage; class CAnimation; -enum class EImageBlitMode; +enum class EImageBlitMode : uint8_t; class IRenderHandler : public boost::noncopyable { diff --git a/client/render/IScreenHandler.h b/client/render/IScreenHandler.h index 49e5cd95e..32abf7711 100644 --- a/client/render/IScreenHandler.h +++ b/client/render/IScreenHandler.h @@ -41,6 +41,11 @@ public: /// Dimensions of render output virtual Point getRenderResolution() const = 0; + /// Dimensions of logical output. Can be different if scaling is used + virtual Point getLogicalResolution() const = 0; + + virtual int getScalingFactor() const = 0; + /// Window has focus virtual bool hasFocus() = 0; }; diff --git a/client/render/ImageLocator.cpp b/client/render/ImageLocator.cpp index 250fd2f47..3247acc9d 100644 --- a/client/render/ImageLocator.cpp +++ b/client/render/ImageLocator.cpp @@ -10,6 +10,9 @@ #include "StdInc.h" #include "ImageLocator.h" +#include "../gui/CGuiHandler.h" +#include "IScreenHandler.h" + #include "../../lib/json/JsonNode.h" @@ -47,10 +50,46 @@ bool ImageLocator::operator<(const ImageLocator & other) const return defFrame < other.defFrame; if(verticalFlip != other.verticalFlip) return verticalFlip < other.verticalFlip; - return horizontalFlip < other.horizontalFlip; + if(horizontalFlip != other.horizontalFlip) + return horizontalFlip < other.horizontalFlip; + if(scalingFactor != other.scalingFactor) + return scalingFactor < other.scalingFactor; + if(playerColored != other.playerColored) + return playerColored < other.playerColored; + if(layerShadow != other.layerShadow) + return layerShadow < other.layerShadow; + if(layerBody != other.layerBody) + return layerBody < other.layerBody; + if (layerOverlay != other.layerOverlay) + return layerOverlay < other.layerOverlay; + + return false; } bool ImageLocator::empty() const { return !image.has_value() && !defFile.has_value(); } + +ImageLocator ImageLocator::copyFile() const +{ + ImageLocator result; + result.image = image; + result.defFile = defFile; + result.defFrame = defFrame; + result.defGroup = defGroup; + return result; +} + +ImageLocator ImageLocator::copyFileTransform() const +{ + ImageLocator result = copyFile(); + result.horizontalFlip = horizontalFlip; + result.verticalFlip = verticalFlip; + return result; +} + +ImageLocator ImageLocator::copyFileTransformScale() const +{ + return *this; // full copy +} diff --git a/client/render/ImageLocator.h b/client/render/ImageLocator.h index 875b537c1..b538d8170 100644 --- a/client/render/ImageLocator.h +++ b/client/render/ImageLocator.h @@ -10,6 +10,7 @@ #pragma once #include "../../lib/filesystem/ResourcePath.h" +#include "../../lib/constants/EntityIdentifiers.h" struct ImageLocator { @@ -20,6 +21,11 @@ struct ImageLocator bool verticalFlip = false; bool horizontalFlip = false; + int8_t scalingFactor = 1; + PlayerColor playerColored = PlayerColor::CANNOT_DETERMINE; + bool layerShadow = false; + bool layerBody = true; + bool layerOverlay = false; ImageLocator() = default; ImageLocator(const AnimationPath & path, int frame, int group); @@ -28,4 +34,8 @@ struct ImageLocator bool operator < (const ImageLocator & other) const; bool empty() const; + + ImageLocator copyFile() const; + ImageLocator copyFileTransform() const; + ImageLocator copyFileTransformScale() const; }; diff --git a/client/renderSDL/CBitmapFont.cpp b/client/renderSDL/CBitmapFont.cpp index d3ed5bb55..8a3f7eb05 100644 --- a/client/renderSDL/CBitmapFont.cpp +++ b/client/renderSDL/CBitmapFont.cpp @@ -12,7 +12,9 @@ #include "SDL_Extensions.h" #include "../CGameInfo.h" +#include "../gui/CGuiHandler.h" #include "../render/Colors.h" +#include "../render/IScreenHandler.h" #include "../../lib/Rect.h" #include "../../lib/filesystem/Filesystem.h" @@ -24,7 +26,75 @@ #include -void CBitmapFont::loadModFont(const std::string & modName, const ResourcePath & resource) +struct AtlasLayout +{ + Point dimensions; + std::map images; +}; + +/// Attempts to pack provided list of images into 2d box of specified size +/// Returns resulting layout on success and empty optional on failure +static std::optional tryAtlasPacking(Point dimensions, const std::map & images) +{ + // Simple atlas packing algorithm. Can be extended if needed, however optimal solution is NP-complete problem, so 'perfect' solution is too costly + + AtlasLayout result; + result.dimensions = dimensions; + + // a little interval to prevent potential 'bleeding' into adjacent symbols + // should be unnecessary for base game, but may be needed for upscaled filters + constexpr int interval = 1; + int currentHeight = 0; + int nextHeight = 0; + int currentWidth = 0; + + for (auto const & image : images) + { + int nextWidth = currentWidth + image.second.x + interval; + + if (nextWidth > dimensions.x) + { + currentHeight = nextHeight; + currentWidth = 0; + nextWidth = currentWidth + image.second.x + interval; + } + + nextHeight = std::max(nextHeight, currentHeight + image.second.y + interval); + if (nextHeight > dimensions.y) + return std::nullopt; // failure - ran out of space + + result.images[image.first] = Rect(Point(currentWidth, currentHeight), image.second); + + currentWidth = nextWidth; + } + + return result; +} + +/// Arranges images to fit into texture atlas with automatic selection of image size +/// Returns images arranged into 2d box +static AtlasLayout doAtlasPacking(const std::map & images) +{ + // initial size of an atlas. Smaller size won't even fit tiniest H3 font + Point dimensions(128, 128); + + for (;;) + { + auto result = tryAtlasPacking(dimensions, images); + + if (result) + return *result; + + // else - packing failed. Increase atlas size and try again + // increase width and height in alternating form: (64,64) -> (128,64) -> (128,128) ... + if (dimensions.x > dimensions.y) + dimensions.y *= 2; + else + dimensions.x *= 2; + } +} + +void CBitmapFont::loadModFont(const std::string & modName, const ResourcePath & resource, std::unordered_map & loadedChars) { if (!CResourceHandler::get(modName)->existsResource(resource)) { @@ -49,7 +119,7 @@ void CBitmapFont::loadModFont(const std::string & modName, const ResourcePath & { CodePoint codepoint = TextOperations::getUnicodeCodepoint(static_cast(charIndex), modEncoding); - BitmapChar symbol; + EntryFNT symbol; symbol.leftOffset = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 0); symbol.width = read_le_u32(data.first.get() + baseIndex + charIndex * 12 + 4); @@ -65,7 +135,7 @@ void CBitmapFont::loadModFont(const std::string & modName, const ResourcePath & std::copy_n(pixelData, pixelsCount, symbol.pixels.data() ); - chars[codepoint] = symbol; + loadedChars[codepoint] = symbol; } } @@ -74,13 +144,70 @@ CBitmapFont::CBitmapFont(const std::string & filename): { ResourcePath resource("data/" + filename, EResType::BMP_FONT); - loadModFont("core", resource); + std::unordered_map loadedChars; + loadModFont("core", resource, loadedChars); for(const auto & modName : VLC->modh->getActiveMods()) { if (CResourceHandler::get(modName)->existsResource(resource)) - loadModFont(modName, resource); + loadModFont(modName, resource, loadedChars); } + + std::map atlasSymbol; + for (auto const & symbol : loadedChars) + atlasSymbol[symbol.first] = Point(symbol.second.width, symbol.second.height); + + auto atlas = doAtlasPacking(atlasSymbol); + + atlasImage = SDL_CreateRGBSurface(0, atlas.dimensions.x, atlas.dimensions.y, 8, 0, 0, 0, 0); + + assert(atlasImage->format->palette != nullptr); + assert(atlasImage->format->palette->ncolors == 256); + + atlasImage->format->palette->colors[0] = { 0, 255, 255, SDL_ALPHA_OPAQUE }; // transparency + atlasImage->format->palette->colors[1] = { 0, 0, 0, SDL_ALPHA_OPAQUE }; // black shadow + + CSDL_Ext::fillSurface(atlasImage, CSDL_Ext::toSDL(Colors::CYAN)); + CSDL_Ext::setColorKey(atlasImage, CSDL_Ext::toSDL(Colors::CYAN)); + + for (size_t i = 2; i < atlasImage->format->palette->ncolors; ++i) + atlasImage->format->palette->colors[i] = { 255, 255, 255, SDL_ALPHA_OPAQUE }; + + for (auto const & symbol : loadedChars) + { + BitmapChar storedEntry; + + storedEntry.leftOffset = symbol.second.leftOffset; + storedEntry.rightOffset = symbol.second.rightOffset; + storedEntry.positionInAtlas = atlas.images.at(symbol.first); + + // Copy pixel data to atlas + uint8_t *dstPixels = static_cast(atlasImage->pixels); + uint8_t *dstLine = dstPixels + storedEntry.positionInAtlas.y * atlasImage->pitch; + uint8_t *dst = dstLine + storedEntry.positionInAtlas.x; + + for (size_t i = 0; i < storedEntry.positionInAtlas.h; ++i) + { + const uint8_t *srcPtr = symbol.second.pixels.data() + i * storedEntry.positionInAtlas.w; + uint8_t * dstPtr = dst + i * atlasImage->pitch; + + std::copy_n(srcPtr, storedEntry.positionInAtlas.w, dstPtr); + } + + chars[symbol.first] = storedEntry; + } + + if (GH.screenHandler().getScalingFactor() != 1) + { + auto scaledSurface = CSDL_Ext::scaleSurfaceIntegerFactor(atlasImage, GH.screenHandler().getScalingFactor()); + SDL_FreeSurface(atlasImage); + atlasImage = scaledSurface; + } +} + +CBitmapFont::~CBitmapFont() +{ + SDL_FreeSurface(atlasImage); } size_t CBitmapFont::getLineHeight() const @@ -97,7 +224,7 @@ size_t CBitmapFont::getGlyphWidth(const char * data) const if (iter == chars.end()) return 0; - return iter->second.leftOffset + iter->second.width + iter->second.rightOffset; + return iter->second.leftOffset + iter->second.positionInAtlas.w + iter->second.rightOffset; } bool CBitmapFont::canRepresentCharacter(const char *data) const @@ -120,52 +247,21 @@ bool CBitmapFont::canRepresentString(const std::string & data) const void CBitmapFont::renderCharacter(SDL_Surface * surface, const BitmapChar & character, const ColorRGBA & color, int &posX, int &posY) const { - Rect clipRect; - CSDL_Ext::getClipRect(surface, clipRect); + int scalingFactor = GH.screenHandler().getScalingFactor(); - posX += character.leftOffset; + posX += character.leftOffset * scalingFactor; - CSDL_Ext::TColorPutter colorPutter = CSDL_Ext::getPutterFor(surface); + auto sdlColor = CSDL_Ext::toSDL(color); - uint8_t bpp = surface->format->BytesPerPixel; + if (atlasImage->format->palette) + SDL_SetPaletteColors(atlasImage->format->palette, &sdlColor, 255, 1); + else + SDL_SetSurfaceColorMod(atlasImage, color.r, color.g, color.b); - // start of line, may differ from 0 due to end of surface or clipped surface - int lineBegin = std::max(0, clipRect.y - posY); - int lineEnd = std::min(character.height, clipRect.y + clipRect.h - posY - 1); + CSDL_Ext::blitSurface(atlasImage, character.positionInAtlas * scalingFactor, surface, Point(posX, posY)); - // start end end of each row, may differ from 0 - int rowBegin = std::max(0, clipRect.x - posX); - int rowEnd = std::min(character.width, clipRect.x + clipRect.w - posX - 1); - - //for each line in symbol - for(int dy = lineBegin; dy pixels; - const uint8_t *srcLine = character.pixels.data(); - - // shift source\destination pixels to current position - dstLine += (posY+dy) * surface->pitch + posX * bpp; - srcLine += dy * character.width; - - //for each column in line - for(int dx = rowBegin; dx < rowEnd; dx++) - { - uint8_t* dstPixel = dstLine + dx*bpp; - switch(srcLine[dx]) - { - case 1: //black "shadow" - colorPutter(dstPixel, 0, 0, 0); - break; - case 255: //text colour - colorPutter(dstPixel, color.r, color.g, color.b); - break; - default : - break; //transparency - } - } - } - posX += character.width; - posX += character.rightOffset; + posX += character.positionInAtlas.w * scalingFactor; + posX += character.rightOffset * scalingFactor; } void CBitmapFont::renderText(SDL_Surface * surface, const std::string & data, const ColorRGBA & color, const Point & pos) const @@ -178,12 +274,6 @@ void CBitmapFont::renderText(SDL_Surface * surface, const std::string & data, co int posX = pos.x; int posY = pos.y; - // Should be used to detect incorrect text parsing. Disabled right now due to some old UI code (mostly pregame and battles) - //assert(data[0] != '{'); - //assert(data[data.size()-1] != '}'); - - SDL_LockSurface(surface); - for(size_t i=0; isecond, color, posX, posY); } - SDL_UnlockSurface(surface); } diff --git a/client/renderSDL/CBitmapFont.h b/client/renderSDL/CBitmapFont.h index b5fa2b4f4..fc5a8253a 100644 --- a/client/renderSDL/CBitmapFont.h +++ b/client/renderSDL/CBitmapFont.h @@ -11,32 +11,44 @@ #include "../render/IFont.h" +#include "../../lib/Rect.h" + VCMI_LIB_NAMESPACE_BEGIN class ResourcePath; VCMI_LIB_NAMESPACE_END -class CBitmapFont : public IFont +class CBitmapFont final : public IFont { + SDL_Surface * atlasImage; + using CodePoint = uint32_t; - struct BitmapChar + struct EntryFNT { int32_t leftOffset; uint32_t width; uint32_t height; int32_t rightOffset; - std::vector pixels; // pixels of this character, part of BitmapFont::data + std::vector pixels; + }; + + struct BitmapChar + { + Rect positionInAtlas; + int32_t leftOffset; + int32_t rightOffset; }; std::unordered_map chars; uint32_t maxHeight; - void loadModFont(const std::string & modName, const ResourcePath & resource); + void loadModFont(const std::string & modName, const ResourcePath & resource, std::unordered_map & loadedChars); void renderCharacter(SDL_Surface * surface, const BitmapChar & character, const ColorRGBA & color, int &posX, int &posY) const; void renderText(SDL_Surface * surface, const std::string & data, const ColorRGBA & color, const Point & pos) const override; public: explicit CBitmapFont(const std::string & filename); + ~CBitmapFont(); size_t getLineHeight() const override; size_t getGlyphWidth(const char * data) const override; diff --git a/client/renderSDL/CBitmapHanFont.h b/client/renderSDL/CBitmapHanFont.h index 707c360b2..5181787b7 100644 --- a/client/renderSDL/CBitmapHanFont.h +++ b/client/renderSDL/CBitmapHanFont.h @@ -18,7 +18,7 @@ VCMI_LIB_NAMESPACE_END class CBitmapFont; /// supports multi-byte characters for such languages like Chinese -class CBitmapHanFont : public IFont +class CBitmapHanFont final : public IFont { std::unique_ptr fallback; // data, directly copied from file diff --git a/client/renderSDL/CTrueTypeFont.cpp b/client/renderSDL/CTrueTypeFont.cpp index 0aa78d914..ac0758d62 100644 --- a/client/renderSDL/CTrueTypeFont.cpp +++ b/client/renderSDL/CTrueTypeFont.cpp @@ -29,7 +29,9 @@ std::pair, ui64> CTrueTypeFont::loadData(const JsonNode & TTF_Font * CTrueTypeFont::loadFont(const JsonNode &config) { - int pointSize = static_cast(config["size"].Float()); + int pointSizeBase = static_cast(config["size"].Float()); + int scalingFactor = getScalingFactor(); + int pointSize = pointSizeBase * scalingFactor; if(!TTF_WasInit() && TTF_Init()==-1) throw std::runtime_error(std::string("Failed to initialize true type support: ") + TTF_GetError() + "\n"); @@ -74,7 +76,7 @@ size_t CTrueTypeFont::getLineHeight() const if (fallbackFont) return fallbackFont->getLineHeight(); - return TTF_FontHeight(font.get()); + return TTF_FontHeight(font.get()) / getScalingFactor(); } size_t CTrueTypeFont::getGlyphWidth(const char *data) const @@ -83,19 +85,16 @@ size_t CTrueTypeFont::getGlyphWidth(const char *data) const return fallbackFont->getGlyphWidth(data); return getStringWidth(std::string(data, TextOperations::getUnicodeCharacterSize(*data))); - int advance; - TTF_GlyphMetrics(font.get(), *data, nullptr, nullptr, nullptr, nullptr, &advance); - return advance; } size_t CTrueTypeFont::getStringWidth(const std::string & data) const { if (fallbackFont && fallbackFont->canRepresentString(data)) - return fallbackFont->getStringWidth(data); + return fallbackFont->getStringWidth(data) / getScalingFactor(); int width; TTF_SizeUTF8(font.get(), data.c_str(), &width, nullptr); - return width; + return width / getScalingFactor(); } void CTrueTypeFont::renderText(SDL_Surface * surface, const std::string & data, const ColorRGBA & color, const Point & pos) const @@ -107,7 +106,7 @@ void CTrueTypeFont::renderText(SDL_Surface * surface, const std::string & data, } if (dropShadow && color.r != 0 && color.g != 0 && color.b != 0) // not black - add shadow - renderText(surface, data, Colors::BLACK, pos + Point(1,1)); + renderText(surface, data, Colors::BLACK, pos + Point(1,1) * getScalingFactor()); if (!data.empty()) { diff --git a/client/renderSDL/CTrueTypeFont.h b/client/renderSDL/CTrueTypeFont.h index 804217a0b..75d19f0e6 100644 --- a/client/renderSDL/CTrueTypeFont.h +++ b/client/renderSDL/CTrueTypeFont.h @@ -19,7 +19,7 @@ class CBitmapFont; using TTF_Font = struct _TTF_Font; -class CTrueTypeFont : public IFont +class CTrueTypeFont final : public IFont { std::unique_ptr fallbackFont; const std::pair, ui64> data; diff --git a/client/renderSDL/CursorHardware.cpp b/client/renderSDL/CursorHardware.cpp index dc42f9e38..cbcfaeac2 100644 --- a/client/renderSDL/CursorHardware.cpp +++ b/client/renderSDL/CursorHardware.cpp @@ -12,7 +12,7 @@ #include "CursorHardware.h" #include "../gui/CGuiHandler.h" -#include "../renderSDL/ScreenHandler.h" +#include "../render/IScreenHandler.h" #include "../render/Colors.h" #include "../render/IImage.h" #include "SDL_Extensions.h" @@ -45,7 +45,7 @@ void CursorHardware::setVisible(bool on) void CursorHardware::setImage(std::shared_ptr image, const Point & pivotOffset) { - auto cursorSurface = CSDL_Ext::newSurface(image->dimensions().x, image->dimensions().y); + auto cursorSurface = CSDL_Ext::newSurface(image->dimensions() * GH.screenHandler().getScalingFactor()); CSDL_Ext::fillSurface(cursorSurface, CSDL_Ext::toSDL(Colors::TRANSPARENCY)); diff --git a/client/renderSDL/CursorSoftware.cpp b/client/renderSDL/CursorSoftware.cpp index 29b606b96..e5d5a9c09 100644 --- a/client/renderSDL/CursorSoftware.cpp +++ b/client/renderSDL/CursorSoftware.cpp @@ -11,6 +11,8 @@ #include "StdInc.h" #include "CursorSoftware.h" +#include "../gui/CGuiHandler.h" +#include "../render/IScreenHandler.h" #include "../render/Colors.h" #include "../render/IImage.h" #include "../CMT.h" @@ -30,8 +32,8 @@ void CursorSoftware::render() SDL_Rect destRect; destRect.x = renderPos.x; destRect.y = renderPos.y; - destRect.w = 40; - destRect.h = 40; + destRect.w = cursorSurface->w; + destRect.h = cursorSurface->h; SDL_RenderCopy(mainRenderer, cursorTexture, nullptr, &destRect); } @@ -44,7 +46,7 @@ void CursorSoftware::createTexture(const Point & dimensions) if (cursorSurface) SDL_FreeSurface(cursorSurface); - cursorSurface = CSDL_Ext::newSurface(dimensions.x, dimensions.y); + cursorSurface = CSDL_Ext::newSurface(dimensions); cursorTexture = SDL_CreateTexture(mainRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, dimensions.x, dimensions.y); SDL_SetSurfaceBlendMode(cursorSurface, SDL_BLENDMODE_NONE); @@ -53,8 +55,13 @@ void CursorSoftware::createTexture(const Point & dimensions) void CursorSoftware::updateTexture() { - if (!cursorSurface || Point(cursorSurface->w, cursorSurface->h) != cursorImage->dimensions()) - createTexture(cursorImage->dimensions()); + if (!cursorSurface) + createTexture(cursorImage->dimensions() * GH.screenHandler().getScalingFactor()); + + Point currentSize = Point(cursorSurface->w, cursorSurface->h); + + if (currentSize != cursorImage->dimensions() * GH.screenHandler().getScalingFactor()) + createTexture(cursorImage->dimensions() * GH.screenHandler().getScalingFactor()); CSDL_Ext::fillSurface(cursorSurface, CSDL_Ext::toSDL(Colors::TRANSPARENCY)); diff --git a/client/renderSDL/ImageScaled.cpp b/client/renderSDL/ImageScaled.cpp new file mode 100644 index 000000000..08e097aae --- /dev/null +++ b/client/renderSDL/ImageScaled.cpp @@ -0,0 +1,149 @@ +/* + * ImageScaled.cpp, part of VCMI engine + * + * Authors: listed in file AUTHORS in main folder + * + * License: GNU General Public License v2.0 or later + * Full text of license available in license.txt file, in main folder + * + */ +#include "StdInc.h" +#include "ImageScaled.h" + +#include "SDLImage.h" +#include "SDL_Extensions.h" + +#include "../gui/CGuiHandler.h" +#include "../render/IScreenHandler.h" +#include "../render/Colors.h" + +#include "../../lib/constants/EntityIdentifiers.h" + +#include + +ImageScaled::ImageScaled(const ImageLocator & inputLocator, const std::shared_ptr & source, EImageBlitMode mode) + : source(source) + , locator(inputLocator) + , colorMultiplier(Colors::WHITE_TRUE) + , alphaValue(SDL_ALPHA_OPAQUE) + , blitMode(mode) +{ + locator.scalingFactor = GH.screenHandler().getScalingFactor(); + setBodyEnabled(true); +} + +std::shared_ptr ImageScaled::getSharedImage() const +{ + return body; +} + +void ImageScaled::scaleInteger(int factor) +{ + assert(0); +} + +void ImageScaled::scaleTo(const Point & size) +{ + if (body) + body = body->scaleTo(size, nullptr); // FIXME: adjust for scaling +} + +void ImageScaled::exportBitmap(const boost::filesystem::path &path) const +{ + source->exportBitmap(path); +} + +bool ImageScaled::isTransparent(const Point &coords) const +{ + return source->isTransparent(coords); +} + +Point ImageScaled::dimensions() const +{ + return source->dimensions(); +} + +void ImageScaled::setAlpha(uint8_t value) +{ + alphaValue = value; +} + +void ImageScaled::setBlitMode(EImageBlitMode mode) +{ + blitMode = mode; +} + +void ImageScaled::draw(SDL_Surface *where, const Point &pos, const Rect *src) const +{ + if (shadow) + shadow->draw(where, nullptr, pos, src, Colors::WHITE_TRUE, alphaValue, blitMode); + if (body) + body->draw(where, nullptr, pos, src, Colors::WHITE_TRUE, alphaValue, blitMode); + if (overlay) + overlay->draw(where, nullptr, pos, src, colorMultiplier, colorMultiplier.a * alphaValue / 255, blitMode); +} + +void ImageScaled::setOverlayColor(const ColorRGBA & color) +{ + colorMultiplier = color; +} + +void ImageScaled::playerColored(PlayerColor player) +{ + playerColor = player; + if (body) + setBodyEnabled(true); // regenerate +} + +void ImageScaled::shiftPalette(uint32_t firstColorID, uint32_t colorsToMove, uint32_t distanceToMove) +{ + // TODO: implement +} + +void ImageScaled::adjustPalette(const ColorFilter &shifter, uint32_t colorsToSkipMask) +{ + // TODO: implement +} + +void ImageScaled::setShadowEnabled(bool on) +{ + if (on) + { + locator.layerBody = false; + locator.layerShadow = true; + locator.layerOverlay = false; + locator.playerColored = PlayerColor::CANNOT_DETERMINE; + shadow = GH.renderHandler().loadImage(locator, blitMode)->getSharedImage(); + } + else + shadow = nullptr; +} + +void ImageScaled::setBodyEnabled(bool on) +{ + if (on) + { + locator.layerBody = true; + locator.layerShadow = false; + locator.layerOverlay = false; + locator.playerColored = playerColor; + body = GH.renderHandler().loadImage(locator, blitMode)->getSharedImage(); + } + else + body = nullptr; +} + + +void ImageScaled::setOverlayEnabled(bool on) +{ + if (on) + { + locator.layerBody = false; + locator.layerShadow = false; + locator.layerOverlay = true; + locator.playerColored = PlayerColor::CANNOT_DETERMINE; + overlay = GH.renderHandler().loadImage(locator, blitMode)->getSharedImage(); + } + else + overlay = nullptr; +} diff --git a/client/renderSDL/ImageScaled.h b/client/renderSDL/ImageScaled.h new file mode 100644 index 000000000..b0dedc227 --- /dev/null +++ b/client/renderSDL/ImageScaled.h @@ -0,0 +1,67 @@ +/* + * ImageScaled.h, part of VCMI engine + * + * Authors: listed in file AUTHORS in main folder + * + * License: GNU General Public License v2.0 or later + * Full text of license available in license.txt file, in main folder + * + */ +#pragma once + +#include "../render/IImage.h" +#include "../render/IRenderHandler.h" + +#include "../../lib/Color.h" +#include "../../lib/constants/EntityIdentifiers.h" + +struct SDL_Palette; + +class SDLImageShared; + +// Upscaled image with several mechanisms to emulate H3 palette effects +class ImageScaled final : public IImage +{ +private: + + /// Original unscaled image + std::shared_ptr source; + + /// Upscaled shadow of our image, may be null + std::shared_ptr shadow; + + /// Upscaled main part of our image, may be null + std::shared_ptr body; + + /// Upscaled overlay (player color, selection highlight) of our image, may be null + std::shared_ptr overlay; + + ImageLocator locator; + + ColorRGBA colorMultiplier; + PlayerColor playerColor = PlayerColor::CANNOT_DETERMINE; + + uint8_t alphaValue; + EImageBlitMode blitMode; + +public: + ImageScaled(const ImageLocator & locator, const std::shared_ptr & source, EImageBlitMode mode); + + void scaleInteger(int factor) override; + void scaleTo(const Point & size) override; + void exportBitmap(const boost::filesystem::path & path) const override; + bool isTransparent(const Point & coords) const override; + Point dimensions() const override; + void setAlpha(uint8_t value) override; + void setBlitMode(EImageBlitMode mode) override; + void draw(SDL_Surface * where, const Point & pos, const Rect * src) const override; + void setOverlayColor(const ColorRGBA & color) override; + void playerColored(PlayerColor player) override; + void shiftPalette(uint32_t firstColorID, uint32_t colorsToMove, uint32_t distanceToMove) override; + void adjustPalette(const ColorFilter & shifter, uint32_t colorsToSkipMask) override; + + void setShadowEnabled(bool on) override; + void setBodyEnabled(bool on) override; + void setOverlayEnabled(bool on) override; + std::shared_ptr getSharedImage() const override; +}; diff --git a/client/renderSDL/RenderHandler.cpp b/client/renderSDL/RenderHandler.cpp index ec4a0bdc3..522e8e544 100644 --- a/client/renderSDL/RenderHandler.cpp +++ b/client/renderSDL/RenderHandler.cpp @@ -11,9 +11,15 @@ #include "RenderHandler.h" #include "SDLImage.h" +#include "ImageScaled.h" + +#include "../gui/CGuiHandler.h" #include "../render/CAnimation.h" #include "../render/CDefFile.h" +#include "../render/Colors.h" +#include "../render/ColorFilter.h" +#include "../render/IScreenHandler.h" #include "../../lib/json/JsonUtils.h" #include "../../lib/filesystem/Filesystem.h" @@ -125,56 +131,87 @@ RenderHandler::AnimationLayoutMap & RenderHandler::getAnimationLayout(const Anim return animationLayouts[actualPath]; } -std::shared_ptr RenderHandler::loadImageFromSingleFile(const ImagePath & path) +int RenderHandler::getScalingFactor() const { - auto result = std::make_shared(path); - imageFiles[ImageLocator(path)] = result; - return result; + return GH.screenHandler().getScalingFactor(); } -std::shared_ptr RenderHandler::loadImageFromAnimationFileUncached(const AnimationPath & path, int frame, int group) +std::shared_ptr RenderHandler::createImageReference(const ImageLocator & locator, std::shared_ptr input, EImageBlitMode mode) +{ + if (getScalingFactor() == 1 || locator.scalingFactor != 1 || locator.empty()) + return input->createImageReference(mode); + else + return std::make_shared(locator, input, mode); +} + +ImageLocator RenderHandler::getLocatorForAnimationFrame(const AnimationPath & path, int frame, int group) { const auto & layout = getAnimationLayout(path); if (!layout.count(group)) - return loadImageFromSingleFile(ImagePath::builtin("DEFAULT")); + return ImageLocator(ImagePath::builtin("DEFAULT")); if (frame >= layout.at(group).size()) - return loadImageFromSingleFile(ImagePath::builtin("DEFAULT")); + return ImageLocator(ImagePath::builtin("DEFAULT")); const auto & locator = layout.at(group).at(frame); - if (locator.image) - { - return loadImageImpl(locator); - } - else - { - auto defFile = getAnimationFile(path); - return std::make_shared(defFile.get(), frame, group); - } + if (locator.image || locator.defFile) + return locator; + + return ImageLocator(path, frame, group); } -std::shared_ptr RenderHandler::loadImageFromAnimationFile(const AnimationPath & path, int frame, int group) -{ - auto result = loadImageFromAnimationFileUncached(path, frame, group); - imageFiles[ImageLocator(path, frame, group)] = result; - return result; -} - -std::shared_ptr RenderHandler::loadImageImpl(const ImageLocator & locator) +std::shared_ptr RenderHandler::loadImageImpl(const ImageLocator & locator) { auto it = imageFiles.find(locator); if (it != imageFiles.end()) return it->second; - std::shared_ptr result; + // TODO: order should be different: + // 1) try to find correctly scaled image + // 2) if fails -> try to find correctly transformed + // 3) if also fails -> try to find image from correct file + // 4) load missing part of the sequence + // TODO: check whether (load -> transform -> scale) or (load -> scale -> transform) order should be used for proper loading of pre-scaled data + auto imageFromFile = loadImageFromFile(locator.copyFile()); + auto transformedImage = transformImage(locator.copyFileTransform(), imageFromFile); + auto scaledImage = scaleImage(locator.copyFileTransformScale(), transformedImage); + return scaledImage; +} + +std::shared_ptr RenderHandler::loadImageFromFileUncached(const ImageLocator & locator) +{ if (locator.image) - result = loadImageFromSingleFile(*locator.image); - else if (locator.defFile) - result = loadImageFromAnimationFile(*locator.defFile, locator.defFrame, locator.defGroup); + { + // TODO: create EmptySharedImage class that will be instantiated if image does not exists or fails to load + return std::make_shared(*locator.image); + } - if (!result) - result = loadImageFromSingleFile(ImagePath::builtin("DEFAULT")); + if (locator.defFile) + { + auto defFile = getAnimationFile(*locator.defFile); + return std::make_shared(defFile.get(), locator.defFrame, locator.defGroup); + } + + throw std::runtime_error("Invalid image locator received!"); +} + +std::shared_ptr RenderHandler::loadImageFromFile(const ImageLocator & locator) +{ + if (imageFiles.count(locator)) + return imageFiles.at(locator); + + auto result = loadImageFromFileUncached(locator); + imageFiles[locator] = result; + return result; +} + +std::shared_ptr RenderHandler::transformImage(const ImageLocator & locator, std::shared_ptr image) +{ + if (imageFiles.count(locator)) + return imageFiles.at(locator); + + auto result = image; if (locator.verticalFlip) result = result->verticalFlip(); @@ -186,24 +223,50 @@ std::shared_ptr RenderHandler::loadImageImpl(const ImageLocator & l return result; } +std::shared_ptr RenderHandler::scaleImage(const ImageLocator & locator, std::shared_ptr image) +{ + if (imageFiles.count(locator)) + return imageFiles.at(locator); + + auto handle = image->createImageReference(EImageBlitMode::OPAQUE); + + assert(locator.scalingFactor != 1); // should be filtered-out before + + + + handle->setOverlayEnabled(locator.layerOverlay); + handle->setBodyEnabled(locator.layerBody); + handle->setShadowEnabled(locator.layerShadow); + if (locator.layerBody && locator.playerColored != PlayerColor::CANNOT_DETERMINE) + handle->playerColored(locator.playerColored); + + handle->scaleInteger(locator.scalingFactor); + + // TODO: try to optimize image size (possibly even before scaling?) - trim image borders if they are completely transparent + auto result = handle->getSharedImage(); + imageFiles[locator] = result; + return result; +} + std::shared_ptr RenderHandler::loadImage(const ImageLocator & locator, EImageBlitMode mode) { - return loadImageImpl(locator)->createImageReference(mode); + return createImageReference(locator, loadImageImpl(locator), mode); } std::shared_ptr RenderHandler::loadImage(const AnimationPath & path, int frame, int group, EImageBlitMode mode) { - return loadImageFromAnimationFile(path, frame, group)->createImageReference(mode); + auto locator = getLocatorForAnimationFrame(path, frame, group); + return loadImage(locator, mode); } std::shared_ptr RenderHandler::loadImage(const ImagePath & path, EImageBlitMode mode) { - return loadImageImpl(ImageLocator(path))->createImageReference(mode); + return loadImage(ImageLocator(path), mode); } std::shared_ptr RenderHandler::createImage(SDL_Surface * source) { - return std::make_shared(source)->createImageReference(EImageBlitMode::ALPHA); + return createImageReference(ImageLocator(), std::make_shared(source), EImageBlitMode::ALPHA); } std::shared_ptr RenderHandler::loadAnimation(const AnimationPath & path, EImageBlitMode mode) diff --git a/client/renderSDL/RenderHandler.h b/client/renderSDL/RenderHandler.h index 1d1d72755..32e152d98 100644 --- a/client/renderSDL/RenderHandler.h +++ b/client/renderSDL/RenderHandler.h @@ -16,7 +16,8 @@ class EntityService; VCMI_LIB_NAMESPACE_END class CDefFile; -class IConstImage; +class SDLImageShared; +class ISharedImage; class RenderHandler : public IRenderHandler { @@ -24,7 +25,7 @@ class RenderHandler : public IRenderHandler std::map> animationFiles; std::map animationLayouts; - std::map> imageFiles; + std::map> imageFiles; std::shared_ptr getAnimationFile(const AnimationPath & path); AnimationLayoutMap & getAnimationLayout(const AnimationPath & path); @@ -33,10 +34,19 @@ class RenderHandler : public IRenderHandler void addImageListEntry(size_t index, size_t group, const std::string & listName, const std::string & imageName); void addImageListEntries(const EntityService * service); - std::shared_ptr loadImageFromSingleFile(const ImagePath & path); - std::shared_ptr loadImageFromAnimationFileUncached(const AnimationPath & path, int frame, int group); - std::shared_ptr loadImageFromAnimationFile(const AnimationPath & path, int frame, int group); - std::shared_ptr loadImageImpl(const ImageLocator & config); + std::shared_ptr loadImageImpl(const ImageLocator & config); + + std::shared_ptr loadImageFromFileUncached(const ImageLocator & locator); + std::shared_ptr loadImageFromFile(const ImageLocator & locator); + + std::shared_ptr transformImage(const ImageLocator & locator, std::shared_ptr image); + std::shared_ptr scaleImage(const ImageLocator & locator, std::shared_ptr image); + + ImageLocator getLocatorForAnimationFrame(const AnimationPath & path, int frame, int group); + + int getScalingFactor() const; + + std::shared_ptr createImageReference(const ImageLocator & locator, std::shared_ptr input, EImageBlitMode mode); public: // IRenderHandler implementation diff --git a/client/renderSDL/SDLImage.cpp b/client/renderSDL/SDLImage.cpp index 6a9a61d6f..be5e0228f 100644 --- a/client/renderSDL/SDLImage.cpp +++ b/client/renderSDL/SDLImage.cpp @@ -14,14 +14,70 @@ #include "SDL_Extensions.h" #include "../render/ColorFilter.h" +#include "../render/Colors.h" #include "../render/CBitmapHandler.h" #include "../render/CDefFile.h" #include "../render/Graphics.h" +#include "../xBRZ/xbrz.h" +#include #include class SDLImageLoader; +//First 8 colors in def palette used for transparency +static constexpr std::array sourcePalette = {{ + {0, 255, 255, SDL_ALPHA_OPAQUE}, + {255, 150, 255, SDL_ALPHA_OPAQUE}, + {255, 100, 255, SDL_ALPHA_OPAQUE}, + {255, 50, 255, SDL_ALPHA_OPAQUE}, + {255, 0, 255, SDL_ALPHA_OPAQUE}, + {255, 255, 0, SDL_ALPHA_OPAQUE}, + {180, 0, 255, SDL_ALPHA_OPAQUE}, + {0, 255, 0, SDL_ALPHA_OPAQUE} +}}; + +static constexpr std::array targetPalette = {{ + {0, 0, 0, 0 }, // 0 - transparency ( used in most images ) + {0, 0, 0, 64 }, // 1 - shadow border ( used in battle, adventure map def's ) + {0, 0, 0, 64 }, // 2 - shadow border ( used in fog-of-war def's ) + {0, 0, 0, 128}, // 3 - shadow body ( used in fog-of-war def's ) + {0, 0, 0, 128}, // 4 - shadow body ( used in battle, adventure map def's ) + {0, 0, 0, 0 }, // 5 - selection / owner flag ( used in battle, adventure map def's ) + {0, 0, 0, 128}, // 6 - shadow body below selection ( used in battle def's ) + {0, 0, 0, 64 } // 7 - shadow border below selection ( used in battle def's ) +}}; + +static ui8 mixChannels(ui8 c1, ui8 c2, ui8 a1, ui8 a2) +{ + return c1*a1 / 256 + c2*a2*(255 - a1) / 256 / 256; +} + +static ColorRGBA addColors(const ColorRGBA & base, const ColorRGBA & over) +{ + return ColorRGBA( + mixChannels(over.r, base.r, over.a, base.a), + mixChannels(over.g, base.g, over.a, base.a), + mixChannels(over.b, base.b, over.a, base.a), + static_cast(over.a + base.a * (255 - over.a) / 256) + ); +} + +static bool colorsSimilar (const SDL_Color & lhs, const SDL_Color & rhs) +{ + // it seems that H3 does not requires exact match to replace colors -> (255, 103, 255) gets interpreted as shadow + // exact logic is not clear and requires extensive testing with image editing + // potential reason is that H3 uses 16-bit color format (565 RGB bits), meaning that 3 least significant bits are lost in red and blue component + static const int threshold = 8; + + int diffR = static_cast(lhs.r) - rhs.r; + int diffG = static_cast(lhs.g) - rhs.g; + int diffB = static_cast(lhs.b) - rhs.b; + int diffA = static_cast(lhs.a) - rhs.a; + + return std::abs(diffR) < threshold && std::abs(diffG) < threshold && std::abs(diffB) < threshold && std::abs(diffA) < threshold; +} + int IImage::width() const { return dimensions().x; @@ -32,7 +88,7 @@ int IImage::height() const return dimensions().y; } -SDLImageConst::SDLImageConst(CDefFile * data, size_t frame, size_t group) +SDLImageShared::SDLImageShared(const CDefFile * data, size_t frame, size_t group) : surf(nullptr), margins(0, 0), fullSize(0, 0), @@ -44,7 +100,7 @@ SDLImageConst::SDLImageConst(CDefFile * data, size_t frame, size_t group) savePalette(); } -SDLImageConst::SDLImageConst(SDL_Surface * from) +SDLImageShared::SDLImageShared(SDL_Surface * from) : surf(nullptr), margins(0, 0), fullSize(0, 0), @@ -61,7 +117,7 @@ SDLImageConst::SDLImageConst(SDL_Surface * from) fullSize.y = surf->h; } -SDLImageConst::SDLImageConst(const ImagePath & filename) +SDLImageShared::SDLImageShared(const ImagePath & filename) : surf(nullptr), margins(0, 0), fullSize(0, 0), @@ -83,7 +139,7 @@ SDLImageConst::SDLImageConst(const ImagePath & filename) } -void SDLImageConst::draw(SDL_Surface * where, SDL_Palette * palette, const Point & dest, const Rect * src, uint8_t alpha, EImageBlitMode mode) const +void SDLImageShared::draw(SDL_Surface * where, SDL_Palette * palette, const Point & dest, const Rect * src, const ColorRGBA & colorMultiplier, uint8_t alpha, EImageBlitMode mode) const { if (!surf) return; @@ -109,6 +165,7 @@ void SDLImageConst::draw(SDL_Surface * where, SDL_Palette * palette, const Point destShift += dest; + SDL_SetSurfaceColorMod(surf, colorMultiplier.r, colorMultiplier.g, colorMultiplier.b); SDL_SetSurfaceAlphaMod(surf, alpha); if (alpha != SDL_ALPHA_OPAQUE || (mode != EImageBlitMode::OPAQUE && surf->format->Amask != 0)) @@ -127,21 +184,143 @@ void SDLImageConst::draw(SDL_Surface * where, SDL_Palette * palette, const Point { CSDL_Ext::blitSurface(surf, sourceRect, where, destShift); } + + if (surf->format->palette) + SDL_SetSurfacePalette(surf, originalPalette); } -const SDL_Palette * SDLImageConst::getPalette() const +void SDLImageShared::optimizeSurface() { - if (originalPalette == nullptr) - throw std::runtime_error("Palette not found!"); + if (!surf) + return; - return originalPalette; + int left = surf->w; + int top = surf->h; + int right = 0; + int bottom = 0; + + // locate fully-transparent area around image + // H3 hadles this on format level, but mods or images scaled in runtime do not + if (surf->format->palette) + { + for (int y = 0; y < surf->h; ++y) + { + const uint8_t * row = static_cast(surf->pixels) + y * surf->pitch; + for (int x = 0; x < surf->w; ++x) + { + if (row[x] != 0) + { + // opaque or can be opaque (e.g. disabled shadow) + top = std::min(top, y); + left = std::min(left, x); + right = std::max(right, x); + bottom = std::max(bottom, y); + } + } + } + } + else + { + for (int y = 0; y < surf->h; ++y) + { + for (int x = 0; x < surf->w; ++x) + { + ColorRGBA color; + SDL_GetRGBA(CSDL_Ext::getPixel(surf, x, y), surf->format, &color.r, &color.g, &color.b, &color.a); + + if (color.a != SDL_ALPHA_TRANSPARENT) + { + // opaque + top = std::min(top, y); + left = std::min(left, x); + right = std::max(right, x); + bottom = std::max(bottom, y); + } + } + } + } + + if (left == surf->w) + { + // empty image - simply delete it + SDL_FreeSurface(surf); + surf = nullptr; + return; + } + + if (left != 0 || top != 0 || right != surf->w - 1 || bottom != surf->h - 1) + { + // non-zero border found + Rect newDimensions(left, top, right - left + 1, bottom - top + 1); + SDL_Rect rectSDL = CSDL_Ext::toSDL(newDimensions); + auto newSurface = CSDL_Ext::newSurface(newDimensions.dimensions(), surf); + SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_NONE); + SDL_BlitSurface(surf, &rectSDL, newSurface, nullptr); + + SDL_FreeSurface(surf); + surf = newSurface; + + margins.x += left; + margins.y += top; + } } -std::shared_ptr SDLImageConst::scaleFast(const Point & size) const +std::shared_ptr SDLImageShared::scaleInteger(int factor, SDL_Palette * palette) const +{ + if (factor <= 0) + throw std::runtime_error("Unable to scale by integer value of " + std::to_string(factor)); + + if (palette && surf->format->palette) + SDL_SetSurfacePalette(surf, palette); + + /// Convert current surface to ARGB format suitable for xBRZ + /// TODO: skip its creation if this is format matches current surface (even if unlikely) + SDL_Surface * intermediate = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_ARGB8888, 0); + SDL_Surface * scaled = CSDL_Ext::newSurface(Point(surf->w * factor, surf->h * factor), intermediate); + + assert(intermediate->pitch == intermediate->w * 4); + assert(scaled->pitch == scaled->w * 4); + + const uint32_t * srcPixels = static_cast(intermediate->pixels); + uint32_t * dstPixels = static_cast(scaled->pixels); + + // avoid excessive granulation - xBRZ prefers at least 8-16 lines per task + // TODO: compare performance and size of images, recheck values for potentially better parameters + const int granulation = std::clamp(surf->h / 64 * 8, 8, 64); + + tbb::parallel_for(tbb::blocked_range(0, intermediate->h, granulation), [factor, srcPixels, dstPixels, intermediate](const tbb::blocked_range & r) + { + xbrz::scale(factor, srcPixels, dstPixels, intermediate->w, intermediate->h, xbrz::ColorFormat::ARGB, {}, r.begin(), r.end()); + }); + + SDL_FreeSurface(intermediate); + + auto ret = std::make_shared(scaled); + + ret->fullSize.x = fullSize.x * factor; + ret->fullSize.y = fullSize.y * factor; + + ret->margins.x = margins.x * factor; + ret->margins.y = margins.y * factor; + ret->optimizeSurface(); + + // erase our own reference + SDL_FreeSurface(scaled); + + if (surf->format->palette) + SDL_SetSurfacePalette(surf, originalPalette); + + return ret; +} + +std::shared_ptr SDLImageShared::scaleTo(const Point & size, SDL_Palette * palette) const { float scaleX = float(size.x) / dimensions().x; float scaleY = float(size.y) / dimensions().y; + if (palette && surf->format->palette) + SDL_SetSurfacePalette(surf, palette); + auto scaled = CSDL_Ext::scaleSurface(surf, (int)(surf->w * scaleX), (int)(surf->h * scaleY)); if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point @@ -151,7 +330,7 @@ std::shared_ptr SDLImageConst::scaleFast(const Point & size) cons else CSDL_Ext::setDefaultColorKey(scaled);//just in case - auto ret = std::make_shared(scaled); + auto ret = std::make_shared(scaled); ret->fullSize.x = (int) round((float)fullSize.x * scaleX); ret->fullSize.y = (int) round((float)fullSize.y * scaleY); @@ -162,10 +341,13 @@ std::shared_ptr SDLImageConst::scaleFast(const Point & size) cons // erase our own reference SDL_FreeSurface(scaled); + if (surf->format->palette) + SDL_SetSurfacePalette(surf, originalPalette); + return ret; } -void SDLImageConst::exportBitmap(const boost::filesystem::path& path) const +void SDLImageShared::exportBitmap(const boost::filesystem::path& path) const { SDL_SaveBMP(surf, path.string().c_str()); } @@ -175,13 +357,7 @@ void SDLImageIndexed::playerColored(PlayerColor player) graphics->setPlayerPalette(currentPalette, player); } -void SDLImageIndexed::setFlagColor(PlayerColor player) -{ - if(player.isValidPlayer() || player==PlayerColor::NEUTRAL) - graphics->setPlayerFlagColor(currentPalette, player); -} - -bool SDLImageConst::isTransparent(const Point & coords) const +bool SDLImageShared::isTransparent(const Point & coords) const { if (surf) return CSDL_Ext::isTransparent(surf, coords.x, coords.y); @@ -189,23 +365,23 @@ bool SDLImageConst::isTransparent(const Point & coords) const return true; } -Point SDLImageConst::dimensions() const +Point SDLImageShared::dimensions() const { return fullSize; } -std::shared_ptr SDLImageConst::createImageReference(EImageBlitMode mode) +std::shared_ptr SDLImageShared::createImageReference(EImageBlitMode mode) { if (surf && surf->format->palette) - return std::make_shared(shared_from_this(), mode); + return std::make_shared(shared_from_this(), originalPalette, mode); else return std::make_shared(shared_from_this(), mode); } -std::shared_ptr SDLImageConst::horizontalFlip() const +std::shared_ptr SDLImageShared::horizontalFlip() const { SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf); - auto ret = std::make_shared(flipped); + auto ret = std::make_shared(flipped); ret->fullSize = fullSize; ret->margins.x = margins.x; ret->margins.y = fullSize.y - surf->h - margins.y; @@ -214,10 +390,10 @@ std::shared_ptr SDLImageConst::horizontalFlip() const return ret; } -std::shared_ptr SDLImageConst::verticalFlip() const +std::shared_ptr SDLImageShared::verticalFlip() const { SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf); - auto ret = std::make_shared(flipped); + auto ret = std::make_shared(flipped); ret->fullSize = fullSize; ret->margins.x = fullSize.x - surf->w - margins.x; ret->margins.y = margins.y; @@ -227,7 +403,7 @@ std::shared_ptr SDLImageConst::verticalFlip() const } // Keep the original palette, in order to do color switching operation -void SDLImageConst::savePalette() +void SDLImageShared::savePalette() { // For some images that don't have palette, skip this if(surf->format->palette == nullptr) @@ -241,8 +417,6 @@ void SDLImageConst::savePalette() void SDLImageIndexed::shiftPalette(uint32_t firstColorID, uint32_t colorsToMove, uint32_t distanceToMove) { - const SDL_Palette * originalPalette = image->getPalette(); - std::vector shifterColors(colorsToMove); for(uint32_t i=0; igetPalette(); - // Note: here we skip first colors in the palette that are predefined in H3 images for(int i = 0; i < currentPalette->ncolors; i++) { + if (i < std::size(sourcePalette) && colorsSimilar(sourcePalette[i], originalPalette->colors[i])) + continue; + if(i < std::numeric_limits::digits && ((colorsToSkipMask >> i) & 1) == 1) continue; @@ -265,13 +440,17 @@ void SDLImageIndexed::adjustPalette(const ColorFilter & shifter, uint32_t colors } } -SDLImageIndexed::SDLImageIndexed(const std::shared_ptr & image, EImageBlitMode mode) +SDLImageIndexed::SDLImageIndexed(const std::shared_ptr & image, SDL_Palette * originalPalette, EImageBlitMode mode) :SDLImageBase::SDLImageBase(image, mode) + ,originalPalette(originalPalette) { - auto originalPalette = image->getPalette(); currentPalette = SDL_AllocPalette(originalPalette->ncolors); SDL_SetPaletteColors(currentPalette, originalPalette->colors, 0, originalPalette->ncolors); + + setOverlayColor(Colors::TRANSPARENCY); + if (mode == EImageBlitMode::ALPHA) + setShadowTransparency(1.0); } SDLImageIndexed::~SDLImageIndexed() @@ -279,42 +458,117 @@ SDLImageIndexed::~SDLImageIndexed() SDL_FreePalette(currentPalette); } -void SDLImageIndexed::setSpecialPalette(const IImage::SpecialPalette & specialPalette, uint32_t colorsToSkipMask) +void SDLImageIndexed::setShadowTransparency(float factor) { - size_t last = std::min(specialPalette.size(), currentPalette->ncolors); + ColorRGBA shadow50(0, 0, 0, 128 * factor); + ColorRGBA shadow25(0, 0, 0, 64 * factor); - for (size_t i = 0; i < last; ++i) + std::array colorsSDL = { + originalPalette->colors[0], + originalPalette->colors[1], + originalPalette->colors[2], + originalPalette->colors[3], + originalPalette->colors[4] + }; + + // seems to be used unconditionally + colorsSDL[1] = CSDL_Ext::toSDL(shadow25); + colorsSDL[4] = CSDL_Ext::toSDL(shadow50); + + // seems to be used only if color matches + if (colorsSimilar(originalPalette->colors[0], sourcePalette[0])) + colorsSDL[0] = CSDL_Ext::toSDL(Colors::TRANSPARENCY); + + if (colorsSimilar(originalPalette->colors[2], sourcePalette[2])) + colorsSDL[2] = CSDL_Ext::toSDL(shadow25); + + if (colorsSimilar(originalPalette->colors[3], sourcePalette[3])) + colorsSDL[3] = CSDL_Ext::toSDL(shadow50); + + SDL_SetPaletteColors(currentPalette, colorsSDL.data(), 0, colorsSDL.size()); +} + +void SDLImageIndexed::setOverlayColor(const ColorRGBA & color) +{ + for (int i : {5,6,7}) { - if(i < std::numeric_limits::digits && ((colorsToSkipMask >> i) & 1) == 1) - currentPalette->colors[i] = CSDL_Ext::toSDL(specialPalette[i]); + if (colorsSimilar(originalPalette->colors[i], sourcePalette[i])) + currentPalette->colors[i] = CSDL_Ext::toSDL(addColors(targetPalette[i], color)); } } -SDLImageConst::~SDLImageConst() +void SDLImageIndexed::setShadowEnabled(bool on) +{ + if (on) + setShadowTransparency(1.0); + + shadowEnabled = on; +} + +void SDLImageIndexed::setBodyEnabled(bool on) +{ + if (on) + adjustPalette(ColorFilter::genEmptyShifter(), 0); + else + adjustPalette(ColorFilter::genAlphaShifter(0), 0); + + bodyEnabled = on; +} + +void SDLImageIndexed::setOverlayEnabled(bool on) +{ + if (on) + setOverlayColor(Colors::WHITE_TRUE); + else + setOverlayColor(Colors::TRANSPARENCY); + overlayEnabled = on; +} + +SDLImageShared::~SDLImageShared() { SDL_FreeSurface(surf); SDL_FreePalette(originalPalette); } -SDLImageBase::SDLImageBase(const std::shared_ptr & image, EImageBlitMode mode) +SDLImageBase::SDLImageBase(const std::shared_ptr & image, EImageBlitMode mode) :image(image) , alphaValue(SDL_ALPHA_OPAQUE) , blitMode(mode) {} +std::shared_ptr SDLImageBase::getSharedImage() const +{ + return image; +} + void SDLImageRGB::draw(SDL_Surface * where, const Point & pos, const Rect * src) const { - image->draw(where, nullptr, pos, src, alphaValue, blitMode); + image->draw(where, nullptr, pos, src, Colors::WHITE_TRUE, alphaValue, blitMode); } void SDLImageIndexed::draw(SDL_Surface * where, const Point & pos, const Rect * src) const { - image->draw(where, currentPalette, pos, src, alphaValue, blitMode); + image->draw(where, currentPalette, pos, src, Colors::WHITE_TRUE, alphaValue, blitMode); } -void SDLImageBase::scaleFast(const Point & size) +void SDLImageIndexed::scaleTo(const Point & size) { - image = image->scaleFast(size); + image = image->scaleTo(size, currentPalette); +} + +void SDLImageRGB::scaleTo(const Point & size) +{ + image = image->scaleTo(size, nullptr); +} + +void SDLImageIndexed::scaleInteger(int factor) +{ + image = image->scaleInteger(factor, currentPalette); +} + +void SDLImageRGB::scaleInteger(int factor) +{ + image = image->scaleInteger(factor, nullptr); } void SDLImageBase::exportBitmap(const boost::filesystem::path & path) const @@ -342,15 +596,27 @@ void SDLImageBase::setBlitMode(EImageBlitMode mode) blitMode = mode; } -void SDLImageRGB::setSpecialPalette(const SpecialPalette & SpecialPalette, uint32_t colorsToSkipMask) +void SDLImageRGB::setShadowEnabled(bool on) +{ + // Not supported. Theoretically we can try to extract all pixels of specific colors, but better to use 8-bit images or composite images +} + +void SDLImageRGB::setBodyEnabled(bool on) +{ + // Not supported. Theoretically we can try to extract all pixels of specific colors, but better to use 8-bit images or composite images +} + +void SDLImageRGB::setOverlayEnabled(bool on) +{ + // Not supported. Theoretically we can try to extract all pixels of specific colors, but better to use 8-bit images or composite images +} + +void SDLImageRGB::setOverlayColor(const ColorRGBA & color) {} void SDLImageRGB::playerColored(PlayerColor player) {} -void SDLImageRGB::setFlagColor(PlayerColor player) -{} - void SDLImageRGB::shiftPalette(uint32_t firstColorID, uint32_t colorsToMove, uint32_t distanceToMove) {} diff --git a/client/renderSDL/SDLImage.h b/client/renderSDL/SDLImage.h index 155eb173b..81d93c8e6 100644 --- a/client/renderSDL/SDLImage.h +++ b/client/renderSDL/SDLImage.h @@ -24,7 +24,7 @@ struct SDL_Palette; /* * Wrapper around SDL_Surface */ -class SDLImageConst final : public IConstImage, public std::enable_shared_from_this, boost::noncopyable +class SDLImageShared final : public ISharedImage, public std::enable_shared_from_this, boost::noncopyable { //Surface without empty borders SDL_Surface * surf; @@ -38,26 +38,27 @@ class SDLImageConst final : public IConstImage, public std::enable_shared_from_t // Keep the original palette, in order to do color switching operation void savePalette(); + void optimizeSurface(); + public: //Load image from def file - SDLImageConst(CDefFile *data, size_t frame, size_t group=0); + SDLImageShared(const CDefFile *data, size_t frame, size_t group=0); //Load from bitmap file - SDLImageConst(const ImagePath & filename); + SDLImageShared(const ImagePath & filename); //Create using existing surface, extraRef will increase refcount on SDL_Surface - SDLImageConst(SDL_Surface * from); - ~SDLImageConst(); + SDLImageShared(SDL_Surface * from); + ~SDLImageShared(); - void draw(SDL_Surface * where, SDL_Palette * palette, const Point & dest, const Rect * src, uint8_t alpha, EImageBlitMode mode) const; + void draw(SDL_Surface * where, SDL_Palette * palette, const Point & dest, const Rect * src, const ColorRGBA & colorMultiplier, uint8_t alpha, EImageBlitMode mode) const override; void exportBitmap(const boost::filesystem::path & path) const override; Point dimensions() const override; bool isTransparent(const Point & coords) const override; std::shared_ptr createImageReference(EImageBlitMode mode) override; - std::shared_ptr horizontalFlip() const override; - std::shared_ptr verticalFlip() const override; - std::shared_ptr scaleFast(const Point & size) const; - - const SDL_Palette * getPalette() const; + std::shared_ptr horizontalFlip() const override; + std::shared_ptr verticalFlip() const override; + std::shared_ptr scaleInteger(int factor, SDL_Palette * palette) const override; + std::shared_ptr scaleTo(const Point & size, SDL_Palette * palette) const override; friend class SDLImageLoader; }; @@ -65,36 +66,47 @@ public: class SDLImageBase : public IImage, boost::noncopyable { protected: - std::shared_ptr image; + std::shared_ptr image; uint8_t alphaValue; EImageBlitMode blitMode; public: - SDLImageBase(const std::shared_ptr & image, EImageBlitMode mode); + SDLImageBase(const std::shared_ptr & image, EImageBlitMode mode); - void scaleFast(const Point & size) override; void exportBitmap(const boost::filesystem::path & path) const override; bool isTransparent(const Point & coords) const override; Point dimensions() const override; void setAlpha(uint8_t value) override; void setBlitMode(EImageBlitMode mode) override; + std::shared_ptr getSharedImage() const override; }; class SDLImageIndexed final : public SDLImageBase { SDL_Palette * currentPalette = nullptr; + SDL_Palette * originalPalette = nullptr; + bool bodyEnabled = true; + bool shadowEnabled = false; + bool overlayEnabled = false; + + void setShadowTransparency(float factor); public: - SDLImageIndexed(const std::shared_ptr & image, EImageBlitMode mode); + SDLImageIndexed(const std::shared_ptr & image, SDL_Palette * palette, EImageBlitMode mode); ~SDLImageIndexed(); void draw(SDL_Surface * where, const Point & pos, const Rect * src) const override; - void setSpecialPalette(const SpecialPalette & SpecialPalette, uint32_t colorsToSkipMask) override; + void setOverlayColor(const ColorRGBA & color) override; void playerColored(PlayerColor player) override; - void setFlagColor(PlayerColor player) override; void shiftPalette(uint32_t firstColorID, uint32_t colorsToMove, uint32_t distanceToMove) override; void adjustPalette(const ColorFilter & shifter, uint32_t colorsToSkipMask) override; + void scaleInteger(int factor) override; + void scaleTo(const Point & size) override; + + void setShadowEnabled(bool on) override; + void setBodyEnabled(bool on) override; + void setOverlayEnabled(bool on) override; }; class SDLImageRGB final : public SDLImageBase @@ -103,9 +115,14 @@ public: using SDLImageBase::SDLImageBase; void draw(SDL_Surface * where, const Point & pos, const Rect * src) const override; - void setSpecialPalette(const SpecialPalette & SpecialPalette, uint32_t colorsToSkipMask) override; + void setOverlayColor(const ColorRGBA & color) override; void playerColored(PlayerColor player) override; - void setFlagColor(PlayerColor player) override; void shiftPalette(uint32_t firstColorID, uint32_t colorsToMove, uint32_t distanceToMove) override; void adjustPalette(const ColorFilter & shifter, uint32_t colorsToSkipMask) override; + void scaleInteger(int factor) override; + void scaleTo(const Point & size) override; + + void setShadowEnabled(bool on) override; + void setBodyEnabled(bool on) override; + void setOverlayEnabled(bool on) override; }; diff --git a/client/renderSDL/SDLImageLoader.cpp b/client/renderSDL/SDLImageLoader.cpp index 87b87c6ec..a2467a44e 100644 --- a/client/renderSDL/SDLImageLoader.cpp +++ b/client/renderSDL/SDLImageLoader.cpp @@ -17,7 +17,7 @@ #include -SDLImageLoader::SDLImageLoader(SDLImageConst * Img): +SDLImageLoader::SDLImageLoader(SDLImageShared * Img): image(Img), lineStart(nullptr), position(nullptr) diff --git a/client/renderSDL/SDLImageLoader.h b/client/renderSDL/SDLImageLoader.h index ada6c0230..caa1101af 100644 --- a/client/renderSDL/SDLImageLoader.h +++ b/client/renderSDL/SDLImageLoader.h @@ -11,13 +11,13 @@ #include "../render/IImageLoader.h" -class SDLImageConst; +class SDLImageShared; class SDLImageLoader : public IImageLoader { static constexpr int DEFAULT_PALETTE_COLORS = 256; - SDLImageConst * image; + SDLImageShared * image; ui8 * lineStart; ui8 * position; public: @@ -29,7 +29,7 @@ public: //init image with these sizes and palette void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal); - SDLImageLoader(SDLImageConst * Img); + SDLImageLoader(SDLImageShared * Img); ~SDLImageLoader(); }; diff --git a/client/renderSDL/SDL_Extensions.cpp b/client/renderSDL/SDL_Extensions.cpp index 5987e7d6c..37b519eb1 100644 --- a/client/renderSDL/SDL_Extensions.cpp +++ b/client/renderSDL/SDL_Extensions.cpp @@ -12,12 +12,17 @@ #include "SDL_PixelAccess.h" +#include "../gui/CGuiHandler.h" #include "../render/Graphics.h" +#include "../render/IScreenHandler.h" #include "../render/Colors.h" #include "../CMT.h" +#include "../xBRZ/xbrz.h" #include "../../lib/GameConstants.h" +#include + #include #include #include @@ -63,21 +68,21 @@ void CSDL_Ext::setAlpha(SDL_Surface * bg, int value) SDL_SetSurfaceAlphaMod(bg, value); } -SDL_Surface * CSDL_Ext::newSurface(int w, int h) +SDL_Surface * CSDL_Ext::newSurface(const Point & dimensions) { - return newSurface(w, h, screen); + return newSurface(dimensions, screen); } -SDL_Surface * CSDL_Ext::newSurface(int w, int h, SDL_Surface * mod) //creates new surface, with flags/format same as in surface given +SDL_Surface * CSDL_Ext::newSurface(const Point & dimensions, SDL_Surface * mod) //creates new surface, with flags/format same as in surface given { - SDL_Surface * ret = SDL_CreateRGBSurface(0,w,h,mod->format->BitsPerPixel,mod->format->Rmask,mod->format->Gmask,mod->format->Bmask,mod->format->Amask); + SDL_Surface * ret = SDL_CreateRGBSurface(0,dimensions.x,dimensions.y,mod->format->BitsPerPixel,mod->format->Rmask,mod->format->Gmask,mod->format->Bmask,mod->format->Amask); if(ret == nullptr) { const char * error = SDL_GetError(); std::string messagePattern = "Failed to create SDL Surface of size %d x %d, %d bpp. Reason: %s"; - std::string message = boost::str(boost::format(messagePattern) % w % h % mod->format->BitsPerPixel % error); + std::string message = boost::str(boost::format(messagePattern) % dimensions.x % dimensions.y % mod->format->BitsPerPixel % error); handleFatalError(message, true); } @@ -448,32 +453,35 @@ static void drawLineY(SDL_Surface * sur, int x1, int y1, int x2, int y2, const S } } -void CSDL_Ext::drawLine(SDL_Surface * sur, const Point & from, const Point & dest, const SDL_Color & color1, const SDL_Color & color2) +void CSDL_Ext::drawLine(SDL_Surface * sur, const Point & from, const Point & dest, const SDL_Color & color1, const SDL_Color & color2, int thickness) { //FIXME: duplicated code with drawLineDashed - int width = std::abs(from.x - dest.x); + int width = std::abs(from.x - dest.x); int height = std::abs(from.y - dest.y); - if ( width == 0 && height == 0) + if(width == 0 && height == 0) { - uint8_t *p = CSDL_Ext::getPxPtr(sur, from.x, from.y); + uint8_t * p = CSDL_Ext::getPxPtr(sur, from.x, from.y); ColorPutter<4>::PutColorAlpha(p, color1); return; } - if (width > height) + for(int i = 0; i < thickness; ++i) { - if ( from.x < dest.x) - drawLineX(sur, from.x, from.y, dest.x, dest.y, color1, color2); + if(width > height) + { + if(from.x < dest.x) + drawLineX(sur, from.x, from.y + i, dest.x, dest.y + i, color1, color2); + else + drawLineX(sur, dest.x, dest.y + i, from.x, from.y + i, color2, color1); + } else - drawLineX(sur, dest.x, dest.y, from.x, from.y, color2, color1); - } - else - { - if ( from.y < dest.y) - drawLineY(sur, from.x, from.y, dest.x, dest.y, color1, color2); - else - drawLineY(sur, dest.x, dest.y, from.x, from.y, color2, color1); + { + if(from.y < dest.y) + drawLineY(sur, from.x + i, from.y, dest.x + i, dest.y, color1, color2); + else + drawLineY(sur, dest.x + i, dest.y, from.x + i, from.y, color2, color1); + } } } @@ -630,8 +638,11 @@ SDL_Surface * CSDL_Ext::scaleSurface(SDL_Surface * surf, int width, int height) if(!surf || !width || !height) return nullptr; + if (surf->w * 2 == width && surf->h * 2 == height) + return scaleSurfaceIntegerFactor(surf, 2); + SDL_Surface * intermediate = SDL_ConvertSurface(surf, screen->format, 0); - SDL_Surface * ret = newSurface(width, height, intermediate); + SDL_Surface * ret = newSurface(Point(width, height), intermediate); #if SDL_VERSION_ATLEAST(2,0,16) SDL_SoftStretchLinear(intermediate, nullptr, ret, nullptr); @@ -643,6 +654,37 @@ SDL_Surface * CSDL_Ext::scaleSurface(SDL_Surface * surf, int width, int height) return ret; } +SDL_Surface * CSDL_Ext::scaleSurfaceIntegerFactor(SDL_Surface * surf, int factor) +{ + if(surf == nullptr || factor == 0) + return nullptr; + + int newWidth = surf->w * factor; + int newHight = surf->h * factor; + + SDL_Surface * intermediate = SDL_ConvertSurface(surf, screen->format, 0); + SDL_Surface * ret = newSurface(Point(newWidth, newHight), intermediate); + + assert(intermediate->pitch == intermediate->w * 4); + assert(ret->pitch == ret->w * 4); + + const uint32_t * srcPixels = static_cast(intermediate->pixels); + uint32_t * dstPixels = static_cast(ret->pixels); + + // avoid excessive granulation - xBRZ prefers at least 8-16 lines per task + // TODO: compare performance and size of images, recheck values for potentially better parameters + const int granulation = std::clamp(surf->h / 64 * 8, 8, 64); + + tbb::parallel_for(tbb::blocked_range(0, intermediate->h, granulation), [factor, srcPixels, dstPixels, intermediate](const tbb::blocked_range & r) + { + xbrz::scale(factor, srcPixels, dstPixels, intermediate->w, intermediate->h, xbrz::ColorFormat::ARGB, {}, r.begin(), r.end()); + }); + + SDL_FreeSurface(intermediate); + + return ret; +} + void CSDL_Ext::blitSurface(SDL_Surface * src, const Rect & srcRectInput, SDL_Surface * dst, const Point & dstPoint) { SDL_Rect srcRect = CSDL_Ext::toSDL(srcRectInput); @@ -732,5 +774,10 @@ void CSDL_Ext::getClipRect(SDL_Surface * src, Rect & other) other = CSDL_Ext::fromSDL(rect); } +int CSDL_Ext::CClipRectGuard::getScalingFactor() const +{ + return GH.screenHandler().getScalingFactor(); +} + template SDL_Surface * CSDL_Ext::createSurfaceWithBpp<3>(int, int); template SDL_Surface * CSDL_Ext::createSurfaceWithBpp<4>(int, int); diff --git a/client/renderSDL/SDL_Extensions.h b/client/renderSDL/SDL_Extensions.h index 9b1dec1aa..660396c93 100644 --- a/client/renderSDL/SDL_Extensions.h +++ b/client/renderSDL/SDL_Extensions.h @@ -78,20 +78,21 @@ using TColorPutterAlpha = void (*)(uint8_t *&, const uint8_t &, const uint8_t &, int blit8bppAlphaTo24bpp(const SDL_Surface * src, const Rect & srcRect, SDL_Surface * dst, const Point & dstPoint, uint8_t alpha); //blits 8 bpp surface with alpha channel to 24 bpp surface uint32_t colorTouint32_t(const SDL_Color * color); //little endian only - void drawLine(SDL_Surface * sur, const Point & from, const Point & dest, const SDL_Color & color1, const SDL_Color & color2); + void drawLine(SDL_Surface * sur, const Point & from, const Point & dest, const SDL_Color & color1, const SDL_Color & color2, int width); void drawLineDashed(SDL_Surface * sur, const Point & from, const Point & dest, const SDL_Color & color); void drawBorder(SDL_Surface * sur, int x, int y, int w, int h, const SDL_Color & color, int depth = 1); void drawBorder(SDL_Surface * sur, const Rect & r, const SDL_Color & color, int depth = 1); - SDL_Surface * newSurface(int w, int h, SDL_Surface * mod); //creates new surface, with flags/format same as in surface given - SDL_Surface * newSurface(int w, int h); //creates new surface, with flags/format same as in screen surface + SDL_Surface * newSurface(const Point & dimensions, SDL_Surface * mod); //creates new surface, with flags/format same as in surface given + SDL_Surface * newSurface(const Point & dimensions); //creates new surface, with flags/format same as in screen surface SDL_Surface * copySurface(SDL_Surface * mod); //returns copy of given surface template SDL_Surface * createSurfaceWithBpp(int width, int height); //create surface with give bits per pixels value // bilinear filtering. Always returns rgba surface SDL_Surface * scaleSurface(SDL_Surface * surf, int width, int height); + SDL_Surface * scaleSurfaceIntegerFactor(SDL_Surface * surf, int factor); template void convertToGrayscaleBpp(SDL_Surface * surf, const Rect & rect); @@ -110,11 +111,13 @@ using TColorPutterAlpha = void (*)(uint8_t *&, const uint8_t &, const uint8_t &, SDL_Surface * surf; Rect oldRect; + int getScalingFactor() const; + public: CClipRectGuard(SDL_Surface * surface, const Rect & rect): surf(surface) { CSDL_Ext::getClipRect(surf, oldRect); - CSDL_Ext::setClipRect(surf, rect); + CSDL_Ext::setClipRect(surf, rect * getScalingFactor()); } ~CClipRectGuard() diff --git a/client/renderSDL/ScreenHandler.cpp b/client/renderSDL/ScreenHandler.cpp index 604928c49..c8d99e6fa 100644 --- a/client/renderSDL/ScreenHandler.cpp +++ b/client/renderSDL/ScreenHandler.cpp @@ -38,13 +38,14 @@ SDL_Surface * screen2 = nullptr; //and hlp surface (used to store not-active int SDL_Surface * screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed static const std::string NAME = GameConstants::VCMI_VERSION; //application name +static constexpr Point heroes3Resolution = Point(800, 600); std::tuple ScreenHandler::getSupportedScalingRange() const { // H3 resolution, any resolution smaller than that is not correctly supported - static const Point minResolution = {800, 600}; + static constexpr Point minResolution = heroes3Resolution; // arbitrary limit on *downscaling*. Allow some downscaling, if requested by user. Should be generally limited to 100+ for all but few devices - static const double minimalScaling = 50; + static constexpr double minimalScaling = 50; Point renderResolution = getRenderResolution(); double reservedAreaWidth = settings["video"]["reservedWidth"].Float(); @@ -99,6 +100,24 @@ Point ScreenHandler::getPreferredLogicalResolution() const return logicalResolution; } +int ScreenHandler::getScalingFactor() const +{ + switch (upscalingFilter) + { + case EUpscalingFilter::NONE: return 1; + case EUpscalingFilter::XBRZ_2: return 2; + case EUpscalingFilter::XBRZ_3: return 3; + case EUpscalingFilter::XBRZ_4: return 4; + } + + throw std::runtime_error("invalid upscaling filter"); +} + +Point ScreenHandler::getLogicalResolution() const +{ + return Point(screen->w, screen->h) / getScalingFactor(); +} + Point ScreenHandler::getRenderResolution() const { assert(mainRenderer != nullptr); @@ -291,12 +310,64 @@ void ScreenHandler::initializeWindow() handleFatalError(message, true); } + selectUpscalingFilter(); + selectDownscalingFilter(); + SDL_RendererInfo info; SDL_GetRendererInfo(mainRenderer, &info); - SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, settings["video"]["scalingMode"].String().c_str()); logGlobal->info("Created renderer %s", info.name); } +EUpscalingFilter ScreenHandler::loadUpscalingFilter() const +{ + static const std::map upscalingFilterTypes = + { + {"auto", EUpscalingFilter::AUTO }, + {"none", EUpscalingFilter::NONE }, + {"xbrz2", EUpscalingFilter::XBRZ_2 }, + {"xbrz3", EUpscalingFilter::XBRZ_3 }, + {"xbrz4", EUpscalingFilter::XBRZ_4 } + }; + + auto filterName = settings["video"]["upscalingFilter"].String(); + auto filter = upscalingFilterTypes.at(filterName); + + if (filter != EUpscalingFilter::AUTO) + return filter; + + // for now - always fallback to no filter + return EUpscalingFilter::NONE; + + // else - autoselect +// Point outputResolution = getRenderResolution(); +// Point logicalResolution = getPreferredLogicalResolution(); +// +// float scaleX = static_cast(outputResolution.x) / logicalResolution.x; +// float scaleY = static_cast(outputResolution.x) / logicalResolution.x; +// float scaling = std::min(scaleX, scaleY); +// +// if (scaling <= 1.0f) +// return EUpscalingFilter::NONE; +// if (scaling <= 2.0f) +// return EUpscalingFilter::XBRZ_2; +// if (scaling <= 3.0f) +// return EUpscalingFilter::XBRZ_3; +// +// return EUpscalingFilter::XBRZ_4; +} + +void ScreenHandler::selectUpscalingFilter() +{ + upscalingFilter = loadUpscalingFilter(); + logGlobal->debug("Selected upscaling filter %d", static_cast(upscalingFilter)); +} + +void ScreenHandler::selectDownscalingFilter() +{ + SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, settings["video"]["downscalingFilter"].String().c_str()); + logGlobal->debug("Selected downscaling filter %s", settings["video"]["downscalingFilter"].String()); +} + void ScreenHandler::initializeScreenBuffers() { #ifdef VCMI_ENDIAN_BIG @@ -311,7 +382,7 @@ void ScreenHandler::initializeScreenBuffers() int amask = 0xFF000000; #endif - auto logicalSize = getPreferredLogicalResolution(); + auto logicalSize = getPreferredLogicalResolution() * getScalingFactor(); SDL_RenderSetLogicalSize(mainRenderer, logicalSize.x, logicalSize.y); screen = SDL_CreateRGBSurface(0, logicalSize.x, logicalSize.y, 32, rmask, gmask, bmask, amask); diff --git a/client/renderSDL/ScreenHandler.h b/client/renderSDL/ScreenHandler.h index fb3d6a334..e15958b55 100644 --- a/client/renderSDL/ScreenHandler.h +++ b/client/renderSDL/ScreenHandler.h @@ -29,9 +29,23 @@ enum class EWindowMode FULLSCREEN_EXCLUSIVE }; +enum class EUpscalingFilter +{ + AUTO, // used only for loading from config, replaced with autoselected value on init + NONE, + //BILINEAR, // TODO? + //BICUBIC, // TODO? + XBRZ_2, + XBRZ_3, + XBRZ_4, + // NOTE: xbrz also provides x5 and x6 filters, but those would require high-end gaming PC's due to huge memory usage with no visible gain +}; + /// This class is responsible for management of game window and its main rendering surface class ScreenHandler final : public IScreenHandler { + EUpscalingFilter upscalingFilter = EUpscalingFilter::AUTO; + /// Dimensions of target surfaces/textures, this value is what game logic views as screen size Point getPreferredLogicalResolution() const; @@ -69,6 +83,11 @@ class ScreenHandler final : public IScreenHandler /// Performs validation of settings and updates them to valid values if necessary void validateSettings(); + + EUpscalingFilter loadUpscalingFilter() const; + + void selectDownscalingFilter(); + void selectUpscalingFilter(); public: /// Creates and initializes screen, window and SDL state @@ -89,6 +108,10 @@ public: /// Window has focus bool hasFocus() final; + Point getLogicalResolution() const final; + + int getScalingFactor() const final; + std::vector getSupportedResolutions() const final; std::vector getSupportedResolutions(int displayIndex) const; std::tuple getSupportedScalingRange() const final; diff --git a/client/widgets/Images.cpp b/client/widgets/Images.cpp index 22e4e1819..1b968c04e 100644 --- a/client/widgets/Images.cpp +++ b/client/widgets/Images.cpp @@ -116,7 +116,7 @@ void CPicture::setAlpha(uint8_t value) void CPicture::scaleTo(Point size) { - bg->scaleFast(size); + bg->scaleTo(size); pos.w = bg->width(); pos.h = bg->height(); @@ -274,7 +274,7 @@ void CAnimImage::showAll(Canvas & to) if(auto img = anim->getImage(targetFrame, group)) { if(isScaled()) - img->scaleFast(scaledSize); + img->scaleTo(scaledSize); to.draw(img, pos.topLeft()); } @@ -326,7 +326,7 @@ bool CAnimImage::isPlayerColored() const } CShowableAnim::CShowableAnim(int x, int y, const AnimationPath & name, ui8 Flags, ui32 frameTime, size_t Group, uint8_t alpha): - anim(GH.renderHandler().loadAnimation(name, (Flags & PALETTE_ALPHA) ? EImageBlitMode::ALPHA : EImageBlitMode::COLORKEY)), + anim(GH.renderHandler().loadAnimation(name, (Flags & CREATURE_MODE) ? EImageBlitMode::ALPHA : EImageBlitMode::COLORKEY)), group(Group), frame(0), first(0), @@ -439,6 +439,8 @@ void CShowableAnim::blitImage(size_t frame, size_t group, Canvas & to) auto img = anim->getImage(frame, group); if(img) { + if (flags & CREATURE_MODE) + img->setShadowEnabled(true); img->setAlpha(alpha); to.draw(img, pos.topLeft(), src); } @@ -459,7 +461,7 @@ void CShowableAnim::setDuration(int durationMs) } CCreatureAnim::CCreatureAnim(int x, int y, const AnimationPath & name, ui8 flags, ECreatureAnimType type): - CShowableAnim(x, y, name, flags | PALETTE_ALPHA, 100, size_t(type)) // H3 uses 100 ms per frame, irregardless of battle speed settings + CShowableAnim(x, y, name, flags | CREATURE_MODE, 100, size_t(type)) // H3 uses 100 ms per frame, irregardless of battle speed settings { xOffset = 0; yOffset = 0; diff --git a/client/widgets/Images.h b/client/widgets/Images.h index 7fca9ab29..c650b9831 100644 --- a/client/widgets/Images.h +++ b/client/widgets/Images.h @@ -149,7 +149,7 @@ public: BASE=1, //base frame will be blitted before current one HORIZONTAL_FLIP=2, //TODO: will be displayed rotated VERTICAL_FLIP=4, //TODO: will be displayed rotated - PALETTE_ALPHA=8, // use alpha channel for images with palette. Required for creatures in battle and map objects + CREATURE_MODE=8, // use alpha channel for images with palette. Required for creatures in battle and map objects PLAY_ONCE=32 //play animation only once and stop at last frame }; protected: diff --git a/client/windows/CCastleInterface.cpp b/client/windows/CCastleInterface.cpp index 0daa2bd96..62793b101 100644 --- a/client/windows/CCastleInterface.cpp +++ b/client/windows/CCastleInterface.cpp @@ -781,13 +781,6 @@ void CCastleBuildings::buildingClicked(BuildingID building, BuildingSubID::EBuil enterBuilding(building); break; - case BuildingSubID::BROTHERHOOD_OF_SWORD: - if(upgrades == BuildingID::TAVERN) - LOCPLINT->showTavernWindow(town, nullptr, QueryID::NONE); - else - enterBuilding(building); - break; - case BuildingSubID::CASTLE_GATE: if (LOCPLINT->makingTurn) enterCastleGate(); @@ -819,8 +812,11 @@ void CCastleBuildings::buildingClicked(BuildingID building, BuildingSubID::EBuil break; default: + if(upgrades == BuildingID::TAVERN) + LOCPLINT->showTavernWindow(town, nullptr, QueryID::NONE); + else enterBuilding(building); - break; + break; } break; @@ -889,7 +885,7 @@ void CCastleBuildings::enterCastleGate() if(settings["general"]["enableUiEnhancements"].Bool()) { auto image = GH.renderHandler().loadImage(AnimationPath::builtin("ITPA"), t->town->clientInfo.icons[t->hasFort()][false] + 2, 0, EImageBlitMode::OPAQUE); - image->scaleFast(Point(35, 23)); + image->scaleTo(Point(35, 23)); images.push_back(image); } } @@ -939,20 +935,8 @@ void CCastleBuildings::enterFountain(const BuildingID & building, BuildingSubID: std::string hasNotProduced; std::string hasProduced; - if(this->town->town->faction->getIndex() == ETownType::RAMPART) - { - hasNotProduced = CGI->generaltexth->allTexts[677]; - hasProduced = CGI->generaltexth->allTexts[678]; - } - else - { - auto buildingName = town->town->getSpecialBuilding(subID)->getNameTranslated(); - - hasNotProduced = std::string(CGI->generaltexth->translate("vcmi.townHall.hasNotProduced")); - hasProduced = std::string(CGI->generaltexth->translate("vcmi.townHall.hasProduced")); - boost::algorithm::replace_first(hasNotProduced, "%s", buildingName); - boost::algorithm::replace_first(hasProduced, "%s", buildingName); - } + hasNotProduced = CGI->generaltexth->allTexts[677]; + hasProduced = CGI->generaltexth->allTexts[678]; bool isMysticPondOrItsUpgrade = subID == BuildingSubID::MYSTIC_POND || (upgrades != BuildingID::NONE diff --git a/client/windows/CMapOverview.cpp b/client/windows/CMapOverview.cpp index 34bd07e7d..9e96ef8dc 100644 --- a/client/windows/CMapOverview.cpp +++ b/client/windows/CMapOverview.cpp @@ -60,7 +60,7 @@ CMapOverview::CMapOverview(const std::string & mapName, const std::string & file Canvas CMapOverviewWidget::createMinimapForLayer(std::unique_ptr & map, int layer) const { - Canvas canvas = Canvas(Point(map->width, map->height)); + Canvas canvas = Canvas(Point(map->width, map->height), CanvasScalingPolicy::IGNORE); for (int y = 0; y < map->height; ++y) for (int x = 0; x < map->width; ++x) @@ -139,7 +139,7 @@ std::shared_ptr CMapOverviewWidget::buildDrawMinimap(const JsonNode & double resize = maxSideLengthSrc / maxSideLengthDst; Point newMinimapSize = Point(minimapRect.w / resize, minimapRect.h / resize); - Canvas canvasScaled = Canvas(Point(rect.w, rect.h)); + Canvas canvasScaled = Canvas(Point(rect.w, rect.h), CanvasScalingPolicy::AUTO); canvasScaled.drawScaled(minimaps[id], Point((rect.w - newMinimapSize.x) / 2, (rect.h - newMinimapSize.y) / 2), newMinimapSize); std::shared_ptr img = GH.renderHandler().createImage(canvasScaled.getInternalSurface()); diff --git a/client/windows/CMessage.cpp b/client/windows/CMessage.cpp index 140f00993..cbb947267 100644 --- a/client/windows/CMessage.cpp +++ b/client/windows/CMessage.cpp @@ -41,7 +41,7 @@ void CMessage::init() { for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++) { - dialogBorders[i] = GH.renderHandler().loadAnimation(AnimationPath::builtin("DIALGBOX"), EImageBlitMode::OPAQUE); + dialogBorders[i] = GH.renderHandler().loadAnimation(AnimationPath::builtin("DIALGBOX"), EImageBlitMode::COLORKEY); for(int j = 0; j < dialogBorders[i]->size(0); j++) { diff --git a/client/windows/CSpellWindow.cpp b/client/windows/CSpellWindow.cpp index eeb3b3ba8..967f293e0 100644 --- a/client/windows/CSpellWindow.cpp +++ b/client/windows/CSpellWindow.cpp @@ -224,32 +224,32 @@ CSpellWindow::~CSpellWindow() std::shared_ptr CSpellWindow::createBigSpellBook() { std::shared_ptr img = GH.renderHandler().loadImage(ImagePath::builtin("SpelBack"), EImageBlitMode::OPAQUE); - Canvas canvas = Canvas(Point(800, 600)); + Canvas canvas = Canvas(Point(800, 600), CanvasScalingPolicy::AUTO); // edges canvas.draw(img, Point(0, 0), Rect(15, 38, 90, 45)); canvas.draw(img, Point(0, 460), Rect(15, 400, 90, 141)); canvas.draw(img, Point(705, 0), Rect(509, 38, 95, 45)); canvas.draw(img, Point(705, 460), Rect(509, 400, 95, 141)); // left / right - Canvas tmp1 = Canvas(Point(90, 355 - 45)); + Canvas tmp1 = Canvas(Point(90, 355 - 45), CanvasScalingPolicy::AUTO); tmp1.draw(img, Point(0, 0), Rect(15, 38 + 45, 90, 355 - 45)); canvas.drawScaled(tmp1, Point(0, 45), Point(90, 415)); - Canvas tmp2 = Canvas(Point(95, 355 - 45)); + Canvas tmp2 = Canvas(Point(95, 355 - 45), CanvasScalingPolicy::AUTO); tmp2.draw(img, Point(0, 0), Rect(509, 38 + 45, 95, 355 - 45)); canvas.drawScaled(tmp2, Point(705, 45), Point(95, 415)); // top / bottom - Canvas tmp3 = Canvas(Point(409, 45)); + Canvas tmp3 = Canvas(Point(409, 45), CanvasScalingPolicy::AUTO); tmp3.draw(img, Point(0, 0), Rect(100, 38, 409, 45)); canvas.drawScaled(tmp3, Point(90, 0), Point(615, 45)); - Canvas tmp4 = Canvas(Point(409, 141)); + Canvas tmp4 = Canvas(Point(409, 141), CanvasScalingPolicy::AUTO); tmp4.draw(img, Point(0, 0), Rect(100, 400, 409, 141)); canvas.drawScaled(tmp4, Point(90, 460), Point(615, 141)); // middle - Canvas tmp5 = Canvas(Point(409, 141)); + Canvas tmp5 = Canvas(Point(409, 141), CanvasScalingPolicy::AUTO); tmp5.draw(img, Point(0, 0), Rect(100, 38 + 45, 509 - 15, 400 - 38)); canvas.drawScaled(tmp5, Point(90, 45), Point(615, 415)); // carpet - Canvas tmp6 = Canvas(Point(590, 59)); + Canvas tmp6 = Canvas(Point(590, 59), CanvasScalingPolicy::AUTO); tmp6.draw(img, Point(0, 0), Rect(15, 484, 590, 59)); canvas.drawScaled(tmp6, Point(0, 545), Point(800, 59)); // remove bookmarks @@ -535,13 +535,13 @@ void CSpellWindow::setCurrentPage(int value) void CSpellWindow::turnPageLeft() { if(settings["video"]["spellbookAnimation"].Bool() && !isBigSpellbook) - CCS->videoh->playSpellbookAnimation(VideoPath::builtin("PGTRNLFT.SMK"), pos.topLeft() + Point(13, 15)); + CCS->videoh->playSpellbookAnimation(VideoPath::builtin("PGTRNLFT.SMK"), pos.topLeft() + Point(13, 14)); } void CSpellWindow::turnPageRight() { if(settings["video"]["spellbookAnimation"].Bool() && !isBigSpellbook) - CCS->videoh->playSpellbookAnimation(VideoPath::builtin("PGTRNRGH.SMK"), pos.topLeft() + Point(13, 15)); + CCS->videoh->playSpellbookAnimation(VideoPath::builtin("PGTRNRGH.SMK"), pos.topLeft() + Point(13, 14)); } void CSpellWindow::keyPressed(EShortcut key) diff --git a/client/windows/CWindowWithArtifacts.cpp b/client/windows/CWindowWithArtifacts.cpp index 62f6ddcbd..24daa3d1c 100644 --- a/client/windows/CWindowWithArtifacts.cpp +++ b/client/windows/CWindowWithArtifacts.cpp @@ -238,7 +238,7 @@ void CWindowWithArtifacts::setCursorAnimation(const CArtifactInstance & artInst) { assert(artInst.getScrollSpellID().num >= 0); auto image = GH.renderHandler().loadImage(AnimationPath::builtin("spellscr"), artInst.getScrollSpellID().num, 0, EImageBlitMode::COLORKEY); - image->scaleFast(Point(44,34)); + image->scaleTo(Point(44,34)); CCS->curh->dragAndDropCursor(image); } diff --git a/client/xBRZ/Changelog.txt b/client/xBRZ/Changelog.txt new file mode 100644 index 000000000..f7cef74d8 --- /dev/null +++ b/client/xBRZ/Changelog.txt @@ -0,0 +1,66 @@ +xBRZ 1.8 [2019-11-28] +--------------------- +Consider ARGB outside area as transparent +Fixed ARGB scaling issue on image borders + + +xBRZ 1.7 [2019-07-04] +--------------------- +Fixed asymmetric color distance +New parameter: "Center direction bias" + + +xBRZ 1.6 [2018-02-27] +--------------------- +Added bilinear scaling +Option to skip color buffer creation +Updated license info + + +xBRZ 1.5 [2017-08-07] +--------------------- +Added RGB conversion routines + + +xBRZ 1.4 [2015-07-25] +--------------------- +Added 6xBRZ scaler +Create color distance buffer lazily + + +xBRZ 1.3 [2015-04-03] +--------------------- +Improved ARGB performance by 15% +Fixed alpha channel gradient bug + + +xBRZ 1.2 [2014-11-21] +--------------------- +Further improved performance by over 30% + + +xBRZ 1.1 [2014-11-02] +--------------------- +Support images with alpha channel +Improved color analysis + + +xBRZ 1.0 [2013-02-11] +--------------------- +Fixed xBRZ scaler compiler issues for GCC + + +xBRZ 0.2 [2012-12-11] +--------------------- +Added 5xBRZ scaler +Optimized xBRZ scaler performance by factor 3 +Further improved image quality of xBRZ scaler + + +xBRZ 0.1 [2012-09-26] +--------------------- +Initial release: +- scale while preserving small image features +- support multithreading +- support 64-bit architectures +- support processing image slices diff --git a/client/xBRZ/License.txt b/client/xBRZ/License.txt new file mode 100644 index 000000000..94a045322 --- /dev/null +++ b/client/xBRZ/License.txt @@ -0,0 +1,621 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS diff --git a/client/xBRZ/xbrz.cpp b/client/xBRZ/xbrz.cpp new file mode 100644 index 000000000..2fab57f3c --- /dev/null +++ b/client/xBRZ/xbrz.cpp @@ -0,0 +1,1367 @@ +// **************************************************************************** +// * This file is part of the xBRZ project. It is distributed under * +// * GNU General Public License: https://www.gnu.org/licenses/gpl-3.0 * +// * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved * +// * * +// * Additionally and as a special exception, the author gives permission * +// * to link the code of this program with the following libraries * +// * (or with modified versions that use the same licenses), and distribute * +// * linked combinations including the two: MAME, FreeFileSync, Snes9x, ePSXe * +// * You must obey the GNU General Public License in all respects for all of * +// * the code used other than MAME, FreeFileSync, Snes9x, ePSXe. * +// * If you modify this file, you may extend this exception to your version * +// * of the file, but you are not obligated to do so. If you do not wish to * +// * do so, delete this exception statement from your version. * +// **************************************************************************** + +#include "xbrz.h" +#include +#include +#include +#include //std::sqrt +#include "xbrz_tools.h" + +#if defined _MSC_VER +#pragma warning(disable:5051) +#endif + +using namespace xbrz; + + +namespace +{ +template inline +uint32_t gradientRGB(uint32_t pixFront, uint32_t pixBack) //blend front color with opacity M / N over opaque background: https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending +{ + static_assert(0 < M && M < N && N <= 1000); + + auto calcColor = [](unsigned char colFront, unsigned char colBack) -> unsigned char { return (colFront * M + colBack * (N - M)) / N; }; + + return makePixel(calcColor(getRed (pixFront), getRed (pixBack)), + calcColor(getGreen(pixFront), getGreen(pixBack)), + calcColor(getBlue (pixFront), getBlue (pixBack))); +} + + +template inline +uint32_t gradientARGB(uint32_t pixFront, uint32_t pixBack) //find intermediate color between two colors with alpha channels (=> NO alpha blending!!!) +{ + static_assert(0 < M && M < N && N <= 1000); + + const unsigned int weightFront = getAlpha(pixFront) * M; + const unsigned int weightBack = getAlpha(pixBack) * (N - M); + const unsigned int weightSum = weightFront + weightBack; + if (weightSum == 0) + return 0; + + auto calcColor = [=](unsigned char colFront, unsigned char colBack) + { + return static_cast((colFront * weightFront + colBack * weightBack) / weightSum); + }; + + return makePixel(static_cast(weightSum / N), + calcColor(getRed (pixFront), getRed (pixBack)), + calcColor(getGreen(pixFront), getGreen(pixBack)), + calcColor(getBlue (pixFront), getBlue (pixBack))); +} + + +//inline +//double fastSqrt(double n) +//{ +// __asm //speeds up xBRZ by about 9% compared to std::sqrt which internally uses the same assembler instructions but adds some "fluff" +// { +// fld n +// fsqrt +// } +//} +// + + +#ifdef _MSC_VER + #define FORCE_INLINE __forceinline +#elif defined __GNUC__ + #define FORCE_INLINE __attribute__((always_inline)) inline +#else + #define FORCE_INLINE inline +#endif + + +enum RotationDegree //clock-wise +{ + ROT_0, + ROT_90, + ROT_180, + ROT_270 +}; + +//calculate input matrix coordinates after rotation at compile time +template +struct MatrixRotation; + +template +struct MatrixRotation +{ + static const size_t I_old = I; + static const size_t J_old = J; +}; + +template //(i, j) = (row, col) indices, N = size of (square) matrix +struct MatrixRotation +{ + static const size_t I_old = N - 1 - MatrixRotation(rotDeg - 1), I, J, N>::J_old; //old coordinates before rotation! + static const size_t J_old = MatrixRotation(rotDeg - 1), I, J, N>::I_old; // +}; + + +template +class OutputMatrix +{ +public: + OutputMatrix(uint32_t* out, int outWidth) : //access matrix area, top-left at position "out" for image with given width + out_(out), + outWidth_(outWidth) {} + + template + uint32_t& ref() const + { + static const size_t I_old = MatrixRotation::I_old; + static const size_t J_old = MatrixRotation::J_old; + return *(out_ + J_old + I_old * outWidth_); + } + +private: + uint32_t* out_; + const int outWidth_; +}; + + +template inline +T square(T value) { return value * value; } + + +#if 0 +inline +double distRGB(uint32_t pix1, uint32_t pix2) +{ + const double r_diff = static_cast(getRed (pix1)) - getRed (pix2); + const double g_diff = static_cast(getGreen(pix1)) - getGreen(pix2); + const double b_diff = static_cast(getBlue (pix1)) - getBlue (pix2); + + //euklidean RGB distance + return std::sqrt(square(r_diff) + square(g_diff) + square(b_diff)); +} +#endif + + +inline +double distYCbCr(uint32_t pix1, uint32_t pix2, double lumaWeight) +{ + //https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion + //YCbCr conversion is a matrix multiplication => take advantage of linearity by subtracting first! + const int r_diff = static_cast(getRed (pix1)) - getRed (pix2); //we may delay division by 255 to after matrix multiplication + const int g_diff = static_cast(getGreen(pix1)) - getGreen(pix2); // + const int b_diff = static_cast(getBlue (pix1)) - getBlue (pix2); //substraction for int is noticeable faster than for double! + + //const double k_b = 0.0722; //ITU-R BT.709 conversion + //const double k_r = 0.2126; // + const double k_b = 0.0593; //ITU-R BT.2020 conversion + const double k_r = 0.2627; // + const double k_g = 1 - k_b - k_r; + + const double scale_b = 0.5 / (1 - k_b); + const double scale_r = 0.5 / (1 - k_r); + + const double y = k_r * r_diff + k_g * g_diff + k_b * b_diff; //[!], analog YCbCr! + const double c_b = scale_b * (b_diff - y); + const double c_r = scale_r * (r_diff - y); + + //we skip division by 255 to have similar range like other distance functions + return std::sqrt(square(lumaWeight * y) + square(c_b) + square(c_r)); +} + + +inline +double distYCbCrBuffered(uint32_t pix1, uint32_t pix2) +{ + //30% perf boost compared to plain distYCbCr()! + //consumes 64 MB memory; using double is only 2% faster, but takes 128 MB + static const std::vector diffToDist = [] + { + std::vector tmp; + + for (uint32_t i = 0; i < 256 * 256 * 256; ++i) //startup time: 114 ms on Intel Core i5 (four cores) + { + const int r_diff = static_cast(getByte<2>(i)) * 2; + const int g_diff = static_cast(getByte<1>(i)) * 2; + const int b_diff = static_cast(getByte<0>(i)) * 2; + + const double k_b = 0.0593; //ITU-R BT.2020 conversion + const double k_r = 0.2627; // + const double k_g = 1 - k_b - k_r; + + const double scale_b = 0.5 / (1 - k_b); + const double scale_r = 0.5 / (1 - k_r); + + const double y = k_r * r_diff + k_g * g_diff + k_b * b_diff; //[!], analog YCbCr! + const double c_b = scale_b * (b_diff - y); + const double c_r = scale_r * (r_diff - y); + + tmp.push_back(static_cast(std::sqrt(square(y) + square(c_b) + square(c_r)))); + } + return tmp; + }(); + + //if (pix1 == pix2) -> 8% perf degradation! + // return 0; + //if (pix1 < pix2) + // std::swap(pix1, pix2); -> 30% perf degradation!!! + + const int r_diff = static_cast(getRed (pix1)) - getRed (pix2); + const int g_diff = static_cast(getGreen(pix1)) - getGreen(pix2); + const int b_diff = static_cast(getBlue (pix1)) - getBlue (pix2); + + const size_t index = (static_cast(r_diff / 2) << 16) | //slightly reduce precision (division by 2) to squeeze value into single byte + (static_cast(g_diff / 2) << 8) | + (static_cast(b_diff / 2)); + +#if 0 //attention: the following calculation creates an asymmetric color distance!!! (e.g. r_diff=46 will be unpacked as 45, but r_diff=-46 unpacks to -47 + const size_t index = (((r_diff + 0xFF) / 2) << 16) | //slightly reduce precision (division by 2) to squeeze value into single byte + (((g_diff + 0xFF) / 2) << 8) | + (( b_diff + 0xFF) / 2); +#endif + return diffToDist[index]; +} + + +#if defined _MSC_VER && !defined NDEBUG + const int debugPixelX = -1; + const int debugPixelY = 58; + + thread_local bool breakIntoDebugger = false; +#endif + + +enum BlendType +{ + BLEND_NONE = 0, + BLEND_NORMAL, //a normal indication to blend + BLEND_DOMINANT, //a strong indication to blend + //attention: BlendType must fit into the value range of 2 bit!!! +}; + +struct BlendResult +{ + BlendType + /**/blend_f, blend_g, + /**/blend_j, blend_k; +}; + + +struct Kernel_3x3 +{ + uint32_t + a, b, c, + d, e, f, + g, h, i; +}; + +struct Kernel_4x4 //kernel for preprocessing step +{ + uint32_t + a, b, c, // + e, f, g, // support reinterpret_cast from Kernel_4x4 => Kernel_3x3 + i, j, k, // + m, n, o, + d, h, l, p; +}; + +/* input kernel area naming convention: +----------------- +| A | B | C | D | +|---|---|---|---| +| E | F | G | H | evaluate the four corners between F, G, J, K +|---|---|---|---| input pixel is at position F +| I | J | K | L | +|---|---|---|---| +| M | N | O | P | +----------------- +*/ +template +FORCE_INLINE //detect blend direction +BlendResult preProcessCorners(const Kernel_4x4& ker, const xbrz::ScalerCfg& cfg) //result: F, G, J, K corners of "GradientType" +{ +#if defined _MSC_VER && !defined NDEBUG + if (breakIntoDebugger) + __debugbreak(); //__asm int 3; +#endif + + BlendResult result = {}; + + if ((ker.f == ker.g && + ker.j == ker.k) || + (ker.f == ker.j && + ker.g == ker.k)) + return result; + + auto dist = [&](uint32_t pix1, uint32_t pix2) { return ColorDistance::dist(pix1, pix2, cfg.luminanceWeight); }; + + double jg = dist(ker.i, ker.f) + dist(ker.f, ker.c) + dist(ker.n, ker.k) + dist(ker.k, ker.h) + cfg.centerDirectionBias * dist(ker.j, ker.g); + double fk = dist(ker.e, ker.j) + dist(ker.j, ker.o) + dist(ker.b, ker.g) + dist(ker.g, ker.l) + cfg.centerDirectionBias * dist(ker.f, ker.k); + + if (jg < fk) //test sample: 70% of values max(jg, fk) / min(jg, fk) are between 1.1 and 3.7 with median being 1.8 + { + const bool dominantGradient = cfg.dominantDirectionThreshold * jg < fk; + if (ker.f != ker.g && ker.f != ker.j) + result.blend_f = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL; + + if (ker.k != ker.j && ker.k != ker.g) + result.blend_k = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL; + } + else if (fk < jg) + { + const bool dominantGradient = cfg.dominantDirectionThreshold * fk < jg; + if (ker.j != ker.f && ker.j != ker.k) + result.blend_j = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL; + + if (ker.g != ker.f && ker.g != ker.k) + result.blend_g = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL; + } + return result; +} + +#define DEF_GETTER(x) template uint32_t inline get_##x(const Kernel_3x3& ker) { return ker.x; } +//we cannot and NEED NOT write "ker.##x" since ## concatenates preprocessor tokens but "." is not a token +DEF_GETTER(a) DEF_GETTER(b) DEF_GETTER(c) +DEF_GETTER(d) DEF_GETTER(e) DEF_GETTER(f) +DEF_GETTER(g) DEF_GETTER(h) DEF_GETTER(i) +#undef DEF_GETTER + +#define DEF_GETTER(x, y) template <> [[maybe_unused]] inline uint32_t get_##x(const Kernel_3x3& ker) { return ker.y; } +DEF_GETTER(a, g) DEF_GETTER(b, d) DEF_GETTER(c, a) +DEF_GETTER(d, h) DEF_GETTER(e, e) DEF_GETTER(f, b) +DEF_GETTER(g, i) DEF_GETTER(h, f) DEF_GETTER(i, c) +#undef DEF_GETTER + +#define DEF_GETTER(x, y) template <> [[maybe_unused]] inline uint32_t get_##x(const Kernel_3x3& ker) { return ker.y; } +DEF_GETTER(a, i) DEF_GETTER(b, h) DEF_GETTER(c, g) +DEF_GETTER(d, f) DEF_GETTER(e, e) DEF_GETTER(f, d) +DEF_GETTER(g, c) DEF_GETTER(h, b) DEF_GETTER(i, a) +#undef DEF_GETTER + +#define DEF_GETTER(x, y) template <> [[maybe_unused]] inline uint32_t get_##x(const Kernel_3x3& ker) { return ker.y; } +DEF_GETTER(a, c) DEF_GETTER(b, f) DEF_GETTER(c, i) +DEF_GETTER(d, b) DEF_GETTER(e, e) DEF_GETTER(f, h) +DEF_GETTER(g, a) DEF_GETTER(h, d) DEF_GETTER(i, g) +#undef DEF_GETTER + + +//compress four blend types into a single byte +//inline BlendType getTopL (unsigned char b) { return static_cast(0x3 & b); } +inline BlendType getTopR (unsigned char b) { return static_cast(0x3 & (b >> 2)); } +inline BlendType getBottomR(unsigned char b) { return static_cast(0x3 & (b >> 4)); } +inline BlendType getBottomL(unsigned char b) { return static_cast(0x3 & (b >> 6)); } + +inline void clearAddTopL(unsigned char& b, BlendType bt) { b = static_cast(bt); } +inline void addTopR (unsigned char& b, BlendType bt) { b |= (bt << 2); } //buffer is assumed to be initialized before preprocessing! +inline void addBottomR (unsigned char& b, BlendType bt) { b |= (bt << 4); } //e.g. via clearAddTopL() +inline void addBottomL (unsigned char& b, BlendType bt) { b |= (bt << 6); } // + +inline bool blendingNeeded(unsigned char b) +{ + static_assert(BLEND_NONE == 0); + return b != 0; +} + +template inline +unsigned char rotateBlendInfo(unsigned char b) { return b; } +template <> inline unsigned char rotateBlendInfo(unsigned char b) { return ((b << 2) | (b >> 6)) & 0xff; } +template <> inline unsigned char rotateBlendInfo(unsigned char b) { return ((b << 4) | (b >> 4)) & 0xff; } +template <> inline unsigned char rotateBlendInfo(unsigned char b) { return ((b << 6) | (b >> 2)) & 0xff; } + + +/* input kernel area naming convention: +------------- +| A | B | C | +|---|---|---| +| D | E | F | input pixel is at position E +|---|---|---| +| G | H | I | +------------- +*/ +template +FORCE_INLINE //perf: quite worth it! +void blendPixel(const Kernel_3x3& ker, + uint32_t* target, int trgWidth, + unsigned char blendInfo, //result of preprocessing all four corners of pixel "e" + const xbrz::ScalerCfg& cfg) +{ + //#define a get_a(ker) +#define b get_b(ker) +#define c get_c(ker) +#define d get_d(ker) +#define e get_e(ker) +#define f get_f(ker) +#define g get_g(ker) +#define h get_h(ker) +#define i get_i(ker) + +#if defined _MSC_VER && !defined NDEBUG + if (breakIntoDebugger) + __debugbreak(); //__asm int 3; +#endif + + const unsigned char blend = rotateBlendInfo(blendInfo); + + if (getBottomR(blend) >= BLEND_NORMAL) + { + auto eq = [&](uint32_t pix1, uint32_t pix2) { return ColorDistance::dist(pix1, pix2, cfg.luminanceWeight) < cfg.equalColorTolerance; }; + auto dist = [&](uint32_t pix1, uint32_t pix2) { return ColorDistance::dist(pix1, pix2, cfg.luminanceWeight); }; + + const bool doLineBlend = [&]() -> bool + { + if (getBottomR(blend) >= BLEND_DOMINANT) + return true; + + //make sure there is no second blending in an adjacent rotation for this pixel: handles insular pixels, mario eyes + if (getTopR(blend) != BLEND_NONE && !eq(e, g)) //but support double-blending for 90° corners + return false; + if (getBottomL(blend) != BLEND_NONE && !eq(e, c)) + return false; + + //no full blending for L-shapes; blend corner only (handles "mario mushroom eyes") + if (!eq(e, i) && eq(g, h) && eq(h, i) && eq(i, f) && eq(f, c)) + return false; + + return true; + }(); + + const uint32_t px = dist(e, f) <= dist(e, h) ? f : h; //choose most similar color + + OutputMatrix out(target, trgWidth); + + if (doLineBlend) + { + const double fg = dist(f, g); //test sample: 70% of values max(fg, hc) / min(fg, hc) are between 1.1 and 3.7 with median being 1.9 + const double hc = dist(h, c); // + + const bool haveShallowLine = cfg.steepDirectionThreshold * fg <= hc && e != g && d != g; + const bool haveSteepLine = cfg.steepDirectionThreshold * hc <= fg && e != c && b != c; + + if (haveShallowLine) + { + if (haveSteepLine) + Scaler::blendLineSteepAndShallow(px, out); + else + Scaler::blendLineShallow(px, out); + } + else + { + if (haveSteepLine) + Scaler::blendLineSteep(px, out); + else + Scaler::blendLineDiagonal(px, out); + } + } + else + Scaler::blendCorner(px, out); + } + + //#undef a +#undef b +#undef c +#undef d +#undef e +#undef f +#undef g +#undef h +#undef i +} + + +class OobReaderTransparent +{ +public: + OobReaderTransparent(const uint32_t* src, int srcWidth, int srcHeight, int y) : + s_m1(0 <= y - 1 && y - 1 < srcHeight ? src + srcWidth * (y - 1) : nullptr), + s_0 (0 <= y && y < srcHeight ? src + srcWidth * y : nullptr), + s_p1(0 <= y + 1 && y + 1 < srcHeight ? src + srcWidth * (y + 1) : nullptr), + s_p2(0 <= y + 2 && y + 2 < srcHeight ? src + srcWidth * (y + 2) : nullptr), + srcWidth_(srcWidth) {} + + void readDhlp(Kernel_4x4& ker, int x) const //(x, y) is at kernel position F + { + [[likely]] if (const int x_p2 = x + 2; 0 <= x_p2 && x_p2 < srcWidth_) + { + ker.d = s_m1 ? s_m1[x_p2] : 0; + ker.h = s_0 ? s_0 [x_p2] : 0; + ker.l = s_p1 ? s_p1[x_p2] : 0; + ker.p = s_p2 ? s_p2[x_p2] : 0; + } + else + { + ker.d = 0; + ker.h = 0; + ker.l = 0; + ker.p = 0; + } + } + +private: + const uint32_t* const s_m1; + const uint32_t* const s_0; + const uint32_t* const s_p1; + const uint32_t* const s_p2; + const int srcWidth_; +}; + + +class OobReaderDuplicate +{ +public: + OobReaderDuplicate(const uint32_t* src, int srcWidth, int srcHeight, int y) : + s_m1(src + srcWidth * std::clamp(y - 1, 0, srcHeight - 1)), + s_0 (src + srcWidth * std::clamp(y, 0, srcHeight - 1)), + s_p1(src + srcWidth * std::clamp(y + 1, 0, srcHeight - 1)), + s_p2(src + srcWidth * std::clamp(y + 2, 0, srcHeight - 1)), + srcWidth_(srcWidth) {} + + void readDhlp(Kernel_4x4& ker, int x) const //(x, y) is at kernel position F + { + const int x_p2 = std::clamp(x + 2, 0, srcWidth_ - 1); + ker.d = s_m1[x_p2]; + ker.h = s_0 [x_p2]; + ker.l = s_p1[x_p2]; + ker.p = s_p2[x_p2]; + } + +private: + const uint32_t* const s_m1; + const uint32_t* const s_0; + const uint32_t* const s_p1; + const uint32_t* const s_p2; + const int srcWidth_; +}; + + +template //scaler policy: see "Scaler2x" reference implementation +void scaleImage(const uint32_t* src, uint32_t* trg, int srcWidth, int srcHeight, const xbrz::ScalerCfg& cfg, int yFirst, int yLast) +{ + yFirst = std::max(yFirst, 0); + yLast = std::min(yLast, srcHeight); + if (yFirst >= yLast || srcWidth <= 0) + return; + + const int trgWidth = srcWidth * Scaler::scale; + + //(ab)use space of "sizeof(uint32_t) * srcWidth * Scaler::scale" at the end of the image as temporary + //buffer for "on the fly preprocessing" without risk of accidental overwriting before accessing + unsigned char* const preProcBuf = reinterpret_cast(trg + yLast * Scaler::scale * trgWidth) - srcWidth; + + //initialize preprocessing buffer for first row of current stripe: detect upper left and right corner blending + //this cannot be optimized for adjacent processing stripes; we must not allow for a memory race condition! + { + const OobReader oobReader(src, srcWidth, srcHeight, yFirst - 1); + + //initialize at position x = -1 + Kernel_4x4 ker4 = {}; + oobReader.readDhlp(ker4, -4); //hack: read a, e, i, m at x = -1 + ker4.a = ker4.d; + ker4.e = ker4.h; + ker4.i = ker4.l; + ker4.m = ker4.p; + + oobReader.readDhlp(ker4, -3); + ker4.b = ker4.d; + ker4.f = ker4.h; + ker4.j = ker4.l; + ker4.n = ker4.p; + + oobReader.readDhlp(ker4, -2); + ker4.c = ker4.d; + ker4.g = ker4.h; + ker4.k = ker4.l; + ker4.o = ker4.p; + + oobReader.readDhlp(ker4, -1); + + { + const BlendResult res = preProcessCorners(ker4, cfg); + clearAddTopL(preProcBuf[0], res.blend_k); //set 1st known corner for (0, yFirst) + } + + for (int x = 0; x < srcWidth; ++x) + { + ker4.a = ker4.b; //shift previous kernel to the left + ker4.e = ker4.f; // ----------------- + ker4.i = ker4.j; // | A | B | C | D | + ker4.m = ker4.n; // |---|---|---|---| + /**/ // | E | F | G | H | (x, yFirst - 1) is at position F + ker4.b = ker4.c; // |---|---|---|---| + ker4.f = ker4.g; // | I | J | K | L | + ker4.j = ker4.k; // |---|---|---|---| + ker4.n = ker4.o; // | M | N | O | P | + /**/ // ----------------- + ker4.c = ker4.d; + ker4.g = ker4.h; + ker4.k = ker4.l; + ker4.o = ker4.p; + + oobReader.readDhlp(ker4, x); + + /* preprocessing blend result: + --------- + | F | G | evaluate corner between F, G, J, K + |---+---| current input pixel is at position F + | J | K | + --------- */ + const BlendResult res = preProcessCorners(ker4, cfg); + addTopR(preProcBuf[x], res.blend_j); //set 2nd known corner for (x, yFirst) + + if (x + 1 < srcWidth) + clearAddTopL(preProcBuf[x + 1], res.blend_k); //set 1st known corner for (x + 1, yFirst) + } + } + //------------------------------------------------------------------------------------ + + for (int y = yFirst; y < yLast; ++y) + { + uint32_t* out = trg + Scaler::scale * y * trgWidth; //consider MT "striped" access + + const OobReader oobReader(src, srcWidth, srcHeight, y); + + //initialize at position x = -1 + Kernel_4x4 ker4 = {}; + oobReader.readDhlp(ker4, -4); //hack: read a, e, i, m at x = -1 + ker4.a = ker4.d; + ker4.e = ker4.h; + ker4.i = ker4.l; + ker4.m = ker4.p; + + oobReader.readDhlp(ker4, -3); + ker4.b = ker4.d; + ker4.f = ker4.h; + ker4.j = ker4.l; + ker4.n = ker4.p; + + oobReader.readDhlp(ker4, -2); + ker4.c = ker4.d; + ker4.g = ker4.h; + ker4.k = ker4.l; + ker4.o = ker4.p; + + oobReader.readDhlp(ker4, -1); + + unsigned char blend_xy1 = 0; //corner blending for current (x, y + 1) position + { + const BlendResult res = preProcessCorners(ker4, cfg); + clearAddTopL(blend_xy1, res.blend_k); //set 1st known corner for (0, y + 1) and buffer for use on next column + + addBottomL(preProcBuf[0], res.blend_g); //set 3rd known corner for (0, y) + } + + for (int x = 0; x < srcWidth; ++x, out += Scaler::scale) + { +#if defined _MSC_VER && !defined NDEBUG + breakIntoDebugger = debugPixelX == x && debugPixelY == y; +#endif + ker4.a = ker4.b; //shift previous kernel to the left + ker4.e = ker4.f; // ----------------- + ker4.i = ker4.j; // | A | B | C | D | + ker4.m = ker4.n; // |---|---|---|---| + /**/ // | E | F | G | H | (x, y) is at position F + ker4.b = ker4.c; // |---|---|---|---| + ker4.f = ker4.g; // | I | J | K | L | + ker4.j = ker4.k; // |---|---|---|---| + ker4.n = ker4.o; // | M | N | O | P | + /**/ // ----------------- + ker4.c = ker4.d; + ker4.g = ker4.h; + ker4.k = ker4.l; + ker4.o = ker4.p; + + oobReader.readDhlp(ker4, x); + + //evaluate the four corners on bottom-right of current pixel + unsigned char blend_xy = preProcBuf[x]; //for current (x, y) position + { + /* preprocessing blend result: + --------- + | F | G | evaluate corner between F, G, J, K + |---+---| current input pixel is at position F + | J | K | + --------- */ + const BlendResult res = preProcessCorners(ker4, cfg); + addBottomR(blend_xy, res.blend_f); //all four corners of (x, y) have been determined at this point due to processing sequence! + + addTopR(blend_xy1, res.blend_j); //set 2nd known corner for (x, y + 1) + preProcBuf[x] = blend_xy1; //store on current buffer position for use on next row + + [[likely]] if (x + 1 < srcWidth) + { + //blend_xy1 -> blend_x1y1 + clearAddTopL(blend_xy1, res.blend_k); //set 1st known corner for (x + 1, y + 1) and buffer for use on next column + + addBottomL(preProcBuf[x + 1], res.blend_g); //set 3rd known corner for (x + 1, y) + } + } + + //fill block of size scale * scale with the given color + fillBlock(out, trgWidth * sizeof(uint32_t), ker4.f, Scaler::scale, Scaler::scale); + //place *after* preprocessing step, to not overwrite the results while processing the last pixel! + + //blend all four corners of current pixel + if (blendingNeeded(blend_xy)) + { +#ifndef _MSC_VER +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif + const auto& ker3 = reinterpret_cast(ker4); //"The Things We Do for Perf" + blendPixel(ker3, out, trgWidth, blend_xy, cfg); + blendPixel(ker3, out, trgWidth, blend_xy, cfg); + blendPixel(ker3, out, trgWidth, blend_xy, cfg); + blendPixel(ker3, out, trgWidth, blend_xy, cfg); +#ifndef _MSC_VER +#pragma GCC diagnostic pop +#endif + } + } + } +} + +//------------------------------------------------------------------------------------ + +template +struct Scaler2x : public ColorGradient +{ + static const int scale = 2; + + template //bring template function into scope for GCC + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad(pixBack, pixFront); } + + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<1, 0>(), col); + alphaGrad<1, 4>(out.template ref<0, 1>(), col); + alphaGrad<5, 6>(out.template ref<1, 1>(), col); //[!] fixes 7/8 used in xBR + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 2>(out.template ref<1, 1>(), col); + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaGrad<21, 100>(out.template ref<1, 1>(), col); //exact: 1 - pi/4 = 0.2146018366 + } +}; + + +template +struct Scaler3x : public ColorGradient +{ + static const int scale = 3; + + template //bring template function into scope for GCC + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad(pixBack, pixFront); } + + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + + alphaGrad<3, 4>(out.template ref(), col); + out.template ref() = col; + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col); + + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + out.template ref<2, scale - 1>() = col; + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<2, 0>(), col); + alphaGrad<1, 4>(out.template ref<0, 2>(), col); + alphaGrad<3, 4>(out.template ref<2, 1>(), col); + alphaGrad<3, 4>(out.template ref<1, 2>(), col); + out.template ref<2, 2>() = col; + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 8>(out.template ref<1, 2>(), col); //conflict with other rotations for this odd scale + alphaGrad<1, 8>(out.template ref<2, 1>(), col); + alphaGrad<7, 8>(out.template ref<2, 2>(), col); // + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaGrad<45, 100>(out.template ref<2, 2>(), col); //exact: 0.4545939598 + //alphaGrad<7, 256>(out.template ref<2, 1>(), col); //0.02826017254 -> negligible + avoid conflicts with other rotations for this odd scale + //alphaGrad<7, 256>(out.template ref<1, 2>(), col); //0.02826017254 + } +}; + + +template +struct Scaler4x : public ColorGradient +{ + static const int scale = 4; + + template //bring template function into scope for GCC + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad(pixBack, pixFront); } + + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + + alphaGrad<3, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col); + + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + alphaGrad<3, 4>(out.template ref<3, scale - 2>(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<3, 4>(out.template ref<3, 1>(), col); + alphaGrad<3, 4>(out.template ref<1, 3>(), col); + alphaGrad<1, 4>(out.template ref<3, 0>(), col); + alphaGrad<1, 4>(out.template ref<0, 3>(), col); + + alphaGrad<1, 3>(out.template ref<2, 2>(), col); //[!] fixes 1/4 used in xBR + + out.template ref<3, 3>() = col; + out.template ref<3, 2>() = col; + out.template ref<2, 3>() = col; + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 2>(out.template ref(), col); + alphaGrad<1, 2>(out.template ref(), col); + out.template ref() = col; + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaGrad<68, 100>(out.template ref<3, 3>(), col); //exact: 0.6848532563 + alphaGrad< 9, 100>(out.template ref<3, 2>(), col); //0.08677704501 + alphaGrad< 9, 100>(out.template ref<2, 3>(), col); //0.08677704501 + } +}; + + +template +struct Scaler5x : public ColorGradient +{ + static const int scale = 5; + + template //bring template function into scope for GCC + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad(pixBack, pixFront); } + + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + + alphaGrad<3, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col); + alphaGrad<1, 4>(out.template ref<4, scale - 3>(), col); + + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + alphaGrad<3, 4>(out.template ref<3, scale - 2>(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + out.template ref<4, scale - 1>() = col; + out.template ref<4, scale - 2>() = col; + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col); + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + + alphaGrad<2, 3>(out.template ref<3, 3>(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + out.template ref<4, scale - 1>() = col; + + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 8>(out.template ref(), col); //conflict with other rotations for this odd scale + alphaGrad<1, 8>(out.template ref(), col); + alphaGrad<1, 8>(out.template ref(), col); // + + alphaGrad<7, 8>(out.template ref<4, 3>(), col); + alphaGrad<7, 8>(out.template ref<3, 4>(), col); + + out.template ref<4, 4>() = col; + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaGrad<86, 100>(out.template ref<4, 4>(), col); //exact: 0.8631434088 + alphaGrad<23, 100>(out.template ref<4, 3>(), col); //0.2306749731 + alphaGrad<23, 100>(out.template ref<3, 4>(), col); //0.2306749731 + //alphaGrad<1, 64>(out.template ref<4, 2>(), col); //0.01676812367 -> negligible + avoid conflicts with other rotations for this odd scale + //alphaGrad<1, 64>(out.template ref<2, 4>(), col); //0.01676812367 + } +}; + + +template +struct Scaler6x : public ColorGradient +{ + static const int scale = 6; + + template //bring template function into scope for GCC + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad(pixBack, pixFront); } + + + template + static void blendLineShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + + alphaGrad<3, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineSteep(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col); + alphaGrad<1, 4>(out.template ref<4, scale - 3>(), col); + + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + alphaGrad<3, 4>(out.template ref<3, scale - 2>(), col); + alphaGrad<3, 4>(out.template ref<5, scale - 3>(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + out.template ref<4, scale - 1>() = col; + out.template ref<5, scale - 1>() = col; + + out.template ref<4, scale - 2>() = col; + out.template ref<5, scale - 2>() = col; + } + + template + static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col); + alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col); + alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col); + alphaGrad<3, 4>(out.template ref<3, scale - 2>(), col); + + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<1, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + alphaGrad<3, 4>(out.template ref(), col); + + out.template ref<2, scale - 1>() = col; + out.template ref<3, scale - 1>() = col; + out.template ref<4, scale - 1>() = col; + out.template ref<5, scale - 1>() = col; + + out.template ref<4, scale - 2>() = col; + out.template ref<5, scale - 2>() = col; + + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendLineDiagonal(uint32_t col, OutputMatrix& out) + { + alphaGrad<1, 2>(out.template ref(), col); + alphaGrad<1, 2>(out.template ref(), col); + alphaGrad<1, 2>(out.template ref(), col); + + out.template ref() = col; + out.template ref() = col; + out.template ref() = col; + } + + template + static void blendCorner(uint32_t col, OutputMatrix& out) + { + //model a round corner + alphaGrad<97, 100>(out.template ref<5, 5>(), col); //exact: 0.9711013910 + alphaGrad<42, 100>(out.template ref<4, 5>(), col); //0.4236372243 + alphaGrad<42, 100>(out.template ref<5, 4>(), col); //0.4236372243 + alphaGrad< 6, 100>(out.template ref<5, 3>(), col); //0.05652034508 + alphaGrad< 6, 100>(out.template ref<3, 5>(), col); //0.05652034508 + } +}; + +//------------------------------------------------------------------------------------ + +struct ColorDistanceRGB +{ + static double dist(uint32_t pix1, uint32_t pix2, double luminanceWeight) + { + return distYCbCrBuffered(pix1, pix2); + + //if (pix1 == pix2) //about 4% perf boost + // return 0; + //return distYCbCr(pix1, pix2, luminanceWeight); + } +}; + +struct ColorDistanceARGB +{ + static double dist(uint32_t pix1, uint32_t pix2, double luminanceWeight) + { + const double a1 = getAlpha(pix1) / 255.0 ; + const double a2 = getAlpha(pix2) / 255.0 ; + /* + Requirements for a color distance handling alpha channel: with a1, a2 in [0, 1] + + 1. if a1 = a2, distance should be: a1 * distYCbCr() + 2. if a1 = 0, distance should be: a2 * distYCbCr(black, white) = a2 * 255 + 3. if a1 = 1, ??? maybe: 255 * (1 - a2) + a2 * distYCbCr() + */ + + //return std::min(a1, a2) * distYCbCrBuffered(pix1, pix2) + 255 * abs(a1 - a2); + //=> following code is 15% faster: + const double d = distYCbCrBuffered(pix1, pix2); + if (a1 < a2) + return a1 * d + 255 * (a2 - a1); + else + return a2 * d + 255 * (a1 - a2); + + //alternative? return std::sqrt(a1 * a2 * square(distYCbCrBuffered(pix1, pix2)) + square(255 * (a1 - a2))); + } +}; + + +struct ColorDistanceUnbufferedARGB +{ + static double dist(uint32_t pix1, uint32_t pix2, double luminanceWeight) + { + const double a1 = getAlpha(pix1) / 255.0 ; + const double a2 = getAlpha(pix2) / 255.0 ; + + const double d = distYCbCr(pix1, pix2, luminanceWeight); + if (a1 < a2) + return a1 * d + 255 * (a2 - a1); + else + return a2 * d + 255 * (a1 - a2); + } +}; + + +struct ColorGradientRGB +{ + template + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) + { + pixBack = gradientRGB(pixFront, pixBack); + } +}; + +struct ColorGradientARGB +{ + template + static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) + { + pixBack = gradientARGB(pixFront, pixBack); + } +}; +} + + +void xbrz::scale(size_t factor, const uint32_t* src, uint32_t* trg, int srcWidth, int srcHeight, ColorFormat colFmt, const xbrz::ScalerCfg& cfg, int yFirst, int yLast) +{ + if (factor == 1) + { + std::copy(src + yFirst * srcWidth, src + yLast * srcWidth, trg); + return; + } + + static_assert(SCALE_FACTOR_MAX == 6); + switch (colFmt) + { + case ColorFormat::RGB: + switch (factor) + { + case 2: + return scaleImage, ColorDistanceRGB, OobReaderDuplicate>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 3: + return scaleImage, ColorDistanceRGB, OobReaderDuplicate>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 4: + return scaleImage, ColorDistanceRGB, OobReaderDuplicate>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 5: + return scaleImage, ColorDistanceRGB, OobReaderDuplicate>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 6: + return scaleImage, ColorDistanceRGB, OobReaderDuplicate>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + } + break; + + case ColorFormat::ARGB: + switch (factor) + { + case 2: + return scaleImage, ColorDistanceARGB, OobReaderTransparent>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 3: + return scaleImage, ColorDistanceARGB, OobReaderTransparent>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 4: + return scaleImage, ColorDistanceARGB, OobReaderTransparent>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 5: + return scaleImage, ColorDistanceARGB, OobReaderTransparent>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 6: + return scaleImage, ColorDistanceARGB, OobReaderTransparent>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + } + break; + + case ColorFormat::ARGB_UNBUFFERED: + switch (factor) + { + case 2: + return scaleImage, ColorDistanceUnbufferedARGB, OobReaderTransparent>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 3: + return scaleImage, ColorDistanceUnbufferedARGB, OobReaderTransparent>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 4: + return scaleImage, ColorDistanceUnbufferedARGB, OobReaderTransparent>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 5: + return scaleImage, ColorDistanceUnbufferedARGB, OobReaderTransparent>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + case 6: + return scaleImage, ColorDistanceUnbufferedARGB, OobReaderTransparent>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast); + } + break; + } + assert(false); +} + + +bool xbrz::equalColorTest(uint32_t col1, uint32_t col2, ColorFormat colFmt, double luminanceWeight, double equalColorTolerance) +{ + switch (colFmt) + { + case ColorFormat::RGB: + return ColorDistanceRGB::dist(col1, col2, luminanceWeight) < equalColorTolerance; + case ColorFormat::ARGB: + return ColorDistanceARGB::dist(col1, col2, luminanceWeight) < equalColorTolerance; + case ColorFormat::ARGB_UNBUFFERED: + return ColorDistanceUnbufferedARGB::dist(col1, col2, luminanceWeight) < equalColorTolerance; + } + assert(false); + return false; +} + + +void xbrz::bilinearScale(const uint32_t* src, int srcWidth, int srcHeight, + /**/ uint32_t* trg, int trgWidth, int trgHeight) +{ + bilinearScale(src, srcWidth, srcHeight, srcWidth * sizeof(uint32_t), + trg, trgWidth, trgHeight, trgWidth * sizeof(uint32_t), + 0, trgHeight, [](uint32_t pix) { return pix; }); +} + + +void xbrz::nearestNeighborScale(const uint32_t* src, int srcWidth, int srcHeight, + /**/ uint32_t* trg, int trgWidth, int trgHeight) +{ + nearestNeighborScale(src, srcWidth, srcHeight, srcWidth * sizeof(uint32_t), + trg, trgWidth, trgHeight, trgWidth * sizeof(uint32_t), + 0, trgHeight, [](uint32_t pix) { return pix; }); +} + + +#if 0 +//#include +void bilinearScaleCpu(const uint32_t* src, int srcWidth, int srcHeight, + /**/ uint32_t* trg, int trgWidth, int trgHeight) +{ + const int TASK_GRANULARITY = 16; + + concurrency::task_group tg; + + for (int i = 0; i < trgHeight; i += TASK_GRANULARITY) + tg.run([=] + { + const int iLast = std::min(i + TASK_GRANULARITY, trgHeight); + xbrz::bilinearScale(src, srcWidth, srcHeight, srcWidth * sizeof(uint32_t), + trg, trgWidth, trgHeight, trgWidth * sizeof(uint32_t), + i, iLast, [](uint32_t pix) { return pix; }); + }); + tg.wait(); +} + + +//Perf: AMP vs CPU: merely ~10% shorter runtime (scaling 1280x800 -> 1920x1080) +//#include +void bilinearScaleAmp(const uint32_t* src, int srcWidth, int srcHeight, //throw concurrency::runtime_exception + /**/ uint32_t* trg, int trgWidth, int trgHeight) +{ + //C++ AMP reference: https://msdn.microsoft.com/en-us/library/hh289390.aspx + //introduction to C++ AMP: https://msdn.microsoft.com/en-us/magazine/hh882446.aspx + using namespace concurrency; + //TODO: pitch + + if (srcHeight <= 0 || srcWidth <= 0) return; + + const float scaleX = static_cast(trgWidth ) / srcWidth; + const float scaleY = static_cast(trgHeight) / srcHeight; + + array_view srcView(srcHeight, srcWidth, src); + array_view< uint32_t, 2> trgView(trgHeight, trgWidth, trg); + trgView.discard_data(); + + parallel_for_each(trgView.extent, [=](index<2> idx) restrict(amp) //throw ? + { + const int y = idx[0]; + const int x = idx[1]; + //Perf notes: + // -> float-based calculation is (almost) 2x as fas as double! + // -> no noticeable improvement via tiling: https://msdn.microsoft.com/en-us/magazine/hh882447.aspx + // -> no noticeable improvement with restrict(amp,cpu) + // -> iterating over y-axis only is significantly slower! + // -> pre-calculating x,y-dependent variables in a buffer + array_view<> is ~ 20 % slower! + const int y1 = srcHeight * y / trgHeight; + int y2 = y1 + 1; + if (y2 == srcHeight) --y2; + + const float yy1 = y / scaleY - y1; + const float y2y = 1 - yy1; + //------------------------------------- + const int x1 = srcWidth * x / trgWidth; + int x2 = x1 + 1; + if (x2 == srcWidth) --x2; + + const float xx1 = x / scaleX - x1; + const float x2x = 1 - xx1; + //------------------------------------- + const float x2xy2y = x2x * y2y; + const float xx1y2y = xx1 * y2y; + const float x2xyy1 = x2x * yy1; + const float xx1yy1 = xx1 * yy1; + + auto interpolate = [=](int offset) + { + /* + https://en.wikipedia.org/wiki/Bilinear_interpolation + (c11(x2 - x) + c21(x - x1)) * (y2 - y ) + + (c12(x2 - x) + c22(x - x1)) * (y - y1) + */ + const auto c11 = (srcView(y1, x1) >> (8 * offset)) & 0xff; + const auto c21 = (srcView(y1, x2) >> (8 * offset)) & 0xff; + const auto c12 = (srcView(y2, x1) >> (8 * offset)) & 0xff; + const auto c22 = (srcView(y2, x2) >> (8 * offset)) & 0xff; + + return c11 * x2xy2y + c21 * xx1y2y + + c12 * x2xyy1 + c22 * xx1yy1; + }; + + const float bi = interpolate(0); + const float gi = interpolate(1); + const float ri = interpolate(2); + const float ai = interpolate(3); + + const auto b = static_cast(bi + 0.5f); + const auto g = static_cast(gi + 0.5f); + const auto r = static_cast(ri + 0.5f); + const auto a = static_cast(ai + 0.5f); + + trgView(y, x) = (a << 24) | (r << 16) | (g << 8) | b; + }); + trgView.synchronize(); //throw ? +} +#endif diff --git a/client/xBRZ/xbrz.h b/client/xBRZ/xbrz.h new file mode 100644 index 000000000..492fb43ad --- /dev/null +++ b/client/xBRZ/xbrz.h @@ -0,0 +1,79 @@ +// **************************************************************************** +// * This file is part of the xBRZ project. It is distributed under * +// * GNU General Public License: https://www.gnu.org/licenses/gpl-3.0 * +// * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved * +// * * +// * Additionally and as a special exception, the author gives permission * +// * to link the code of this program with the following libraries * +// * (or with modified versions that use the same licenses), and distribute * +// * linked combinations including the two: MAME, FreeFileSync, Snes9x, ePSXe * +// * You must obey the GNU General Public License in all respects for all of * +// * the code used other than MAME, FreeFileSync, Snes9x, ePSXe. * +// * If you modify this file, you may extend this exception to your version * +// * of the file, but you are not obligated to do so. If you do not wish to * +// * do so, delete this exception statement from your version. * +// **************************************************************************** + +#ifndef XBRZ_HEADER_3847894708239054 +#define XBRZ_HEADER_3847894708239054 + +#include //size_t +#include //uint32_t +#include +#include "xbrz_config.h" + + +namespace xbrz +{ +/* +------------------------------------------------------------------------- +| xBRZ: "Scale by rules" - high quality image upscaling filter by Zenju | +------------------------------------------------------------------------- +using a modified approach of xBR: +http://board.byuu.org/viewtopic.php?f=10&t=2248 +- new rule set preserving small image features +- highly optimized for performance +- support alpha channel +- support multithreading +- support 64-bit architectures +- support processing image slices +- support scaling up to 6xBRZ +*/ + +enum class ColorFormat //from high bits -> low bits, 8 bit per channel +{ + RGB, //8 bit for each red, green, blue, upper 8 bits unused + ARGB, //including alpha channel, BGRA byte order on little-endian machines + ARGB_UNBUFFERED, //like ARGB, but without the one-time buffer creation overhead (ca. 100 - 300 ms) at the expense of a slightly slower scaling time +}; + +const int SCALE_FACTOR_MAX = 6; + +/* +-> map source (srcWidth * srcHeight) to target (scale * width x scale * height) image, optionally processing a half-open slice of rows [yFirst, yLast) only +-> if your emulator changes only a few image slices during each cycle (e.g. DOSBox) then there's no need to run xBRZ on the complete image: + Just make sure you enlarge the source image slice by 2 rows on top and 2 on bottom (this is the additional range the xBRZ algorithm is using during analysis) + CAVEAT: If there are multiple changed slices, make sure they do not overlap after adding these additional rows in order to avoid a memory race condition + in the target image data if you are using multiple threads for processing each enlarged slice! + +THREAD-SAFETY: - parts of the same image may be scaled by multiple threads as long as the [yFirst, yLast) ranges do not overlap! + - there is a minor inefficiency for the first row of a slice, so avoid processing single rows only; suggestion: process at least 8-16 rows +*/ +void scale(size_t factor, //valid range: 2 - SCALE_FACTOR_MAX + const uint32_t* src, uint32_t* trg, int srcWidth, int srcHeight, + ColorFormat colFmt, + const ScalerCfg& cfg = ScalerCfg(), + int yFirst = 0, int yLast = std::numeric_limits::max()); //slice of source image + +void bilinearScale(const uint32_t* src, int srcWidth, int srcHeight, + /**/ uint32_t* trg, int trgWidth, int trgHeight); + +void nearestNeighborScale(const uint32_t* src, int srcWidth, int srcHeight, + /**/ uint32_t* trg, int trgWidth, int trgHeight); + + +//parameter tuning +bool equalColorTest(uint32_t col1, uint32_t col2, ColorFormat colFmt, double luminanceWeight, double equalColorTolerance); +} + +#endif diff --git a/client/xBRZ/xbrz_config.h b/client/xBRZ/xbrz_config.h new file mode 100644 index 000000000..fcfda99ab --- /dev/null +++ b/client/xBRZ/xbrz_config.h @@ -0,0 +1,35 @@ +// **************************************************************************** +// * This file is part of the xBRZ project. It is distributed under * +// * GNU General Public License: https://www.gnu.org/licenses/gpl-3.0 * +// * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved * +// * * +// * Additionally and as a special exception, the author gives permission * +// * to link the code of this program with the following libraries * +// * (or with modified versions that use the same licenses), and distribute * +// * linked combinations including the two: MAME, FreeFileSync, Snes9x, ePSXe * +// * You must obey the GNU General Public License in all respects for all of * +// * the code used other than MAME, FreeFileSync, Snes9x, ePSXe. * +// * If you modify this file, you may extend this exception to your version * +// * of the file, but you are not obligated to do so. If you do not wish to * +// * do so, delete this exception statement from your version. * +// **************************************************************************** + +#ifndef XBRZ_CONFIG_HEADER_284578425345 +#define XBRZ_CONFIG_HEADER_284578425345 + +//do NOT include any headers here! used by xBRZ_dll!!! + +namespace xbrz +{ +struct ScalerCfg +{ + double luminanceWeight = 1; + double equalColorTolerance = 30; + double centerDirectionBias = 4; + double dominantDirectionThreshold = 3.6; + double steepDirectionThreshold = 2.2; + double newTestAttribute = 0; //unused; test new parameters +}; +} + +#endif diff --git a/client/xBRZ/xbrz_tools.h b/client/xBRZ/xbrz_tools.h new file mode 100644 index 000000000..b8bb8aa0c --- /dev/null +++ b/client/xBRZ/xbrz_tools.h @@ -0,0 +1,266 @@ +// **************************************************************************** +// * This file is part of the xBRZ project. It is distributed under * +// * GNU General Public License: https://www.gnu.org/licenses/gpl-3.0 * +// * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved * +// * * +// * Additionally and as a special exception, the author gives permission * +// * to link the code of this program with the following libraries * +// * (or with modified versions that use the same licenses), and distribute * +// * linked combinations including the two: MAME, FreeFileSync, Snes9x, ePSXe * +// * You must obey the GNU General Public License in all respects for all of * +// * the code used other than MAME, FreeFileSync, Snes9x, ePSXe. * +// * If you modify this file, you may extend this exception to your version * +// * of the file, but you are not obligated to do so. If you do not wish to * +// * do so, delete this exception statement from your version. * +// **************************************************************************** + +#ifndef XBRZ_TOOLS_H_825480175091875 +#define XBRZ_TOOLS_H_825480175091875 + +#include +#include +#include + + +namespace xbrz +{ +template inline +unsigned char getByte(uint32_t val) { return static_cast((val >> (8 * N)) & 0xff); } + +inline unsigned char getAlpha(uint32_t pix) { return getByte<3>(pix); } +inline unsigned char getRed (uint32_t pix) { return getByte<2>(pix); } +inline unsigned char getGreen(uint32_t pix) { return getByte<1>(pix); } +inline unsigned char getBlue (uint32_t pix) { return getByte<0>(pix); } + +inline uint32_t makePixel(unsigned char a, unsigned char r, unsigned char g, unsigned char b) { return (a << 24) | (r << 16) | (g << 8) | b; } +inline uint32_t makePixel( unsigned char r, unsigned char g, unsigned char b) { return (r << 16) | (g << 8) | b; } + +inline uint32_t rgb555to888(uint16_t pix) { return ((pix & 0x7C00) << 9) | ((pix & 0x03E0) << 6) | ((pix & 0x001F) << 3); } +inline uint32_t rgb565to888(uint16_t pix) { return ((pix & 0xF800) << 8) | ((pix & 0x07E0) << 5) | ((pix & 0x001F) << 3); } + +inline uint16_t rgb888to555(uint32_t pix) { return static_cast(((pix & 0xF80000) >> 9) | ((pix & 0x00F800) >> 6) | ((pix & 0x0000F8) >> 3)); } +inline uint16_t rgb888to565(uint32_t pix) { return static_cast(((pix & 0xF80000) >> 8) | ((pix & 0x00FC00) >> 5) | ((pix & 0x0000F8) >> 3)); } + + +template inline +Pix* byteAdvance(Pix* ptr, int bytes) +{ + using PixNonConst = typename std::remove_cv::type; + using PixByte = typename std::conditional::value, char, const char>::type; + + static_assert(std::is_integral::value, "Pix* is expected to be cast-able to char*"); + + return reinterpret_cast(reinterpret_cast(ptr) + bytes); +} + + +//fill block with the given color +template inline +void fillBlock(Pix* trg, int pitch /*[bytes]*/, Pix col, int blockWidth, int blockHeight) +{ + //for (int y = 0; y < blockHeight; ++y, trg = byteAdvance(trg, pitch)) + // std::fill(trg, trg + blockWidth, col); + + for (int y = 0; y < blockHeight; ++y, trg = byteAdvance(trg, pitch)) + for (int x = 0; x < blockWidth; ++x) + trg[x] = col; +} + + +//nearest-neighbor (going over target image - slow for upscaling, since source is read multiple times missing out on cache! Fast for similar image sizes!) +template +void nearestNeighborScale(const PixSrc* src, int srcWidth, int srcHeight, int srcPitch /*[bytes]*/, + /**/ PixTrg* trg, int trgWidth, int trgHeight, int trgPitch /*[bytes]*/, + int yFirst, int yLast, PixConverter pixCvrt /*convert PixSrc to PixTrg*/) +{ + static_assert(std::is_integral::value, "PixSrc* is expected to be cast-able to char*"); + static_assert(std::is_integral::value, "PixTrg* is expected to be cast-able to char*"); + + static_assert(std::is_same::value, "PixConverter returning wrong pixel format"); + + if (srcPitch < srcWidth * static_cast(sizeof(PixSrc)) || + trgPitch < trgWidth * static_cast(sizeof(PixTrg))) + { + assert(false); + return; + } + + yFirst = std::max(yFirst, 0); + yLast = std::min(yLast, trgHeight); + if (yFirst >= yLast || srcHeight <= 0 || srcWidth <= 0) return; + + for (int y = yFirst; y < yLast; ++y) + { + const int ySrc = srcHeight * y / trgHeight; + const PixSrc* const srcLine = byteAdvance(src, ySrc * srcPitch); + PixTrg* const trgLine = byteAdvance(trg, y * trgPitch); + + for (int x = 0; x < trgWidth; ++x) + { + const int xSrc = srcWidth * x / trgWidth; + trgLine[x] = pixCvrt(srcLine[xSrc]); + } + } +} + + +//nearest-neighbor (going over source image - fast for upscaling, since source is read only once +template +void nearestNeighborScaleOverSource(const PixSrc* src, int srcWidth, int srcHeight, int srcPitch /*[bytes]*/, + /**/ PixTrg* trg, int trgWidth, int trgHeight, int trgPitch /*[bytes]*/, + int yFirst, int yLast, PixConverter pixCvrt /*convert PixSrc to PixTrg*/) +{ + static_assert(std::is_integral::value, "PixSrc* is expected to be cast-able to char*"); + static_assert(std::is_integral::value, "PixTrg* is expected to be cast-able to char*"); + + static_assert(std::is_same::value, "PixConverter returning wrong pixel format"); + + if (srcPitch < srcWidth * static_cast(sizeof(PixSrc)) || + trgPitch < trgWidth * static_cast(sizeof(PixTrg))) + { + assert(false); + return; + } + + yFirst = std::max(yFirst, 0); + yLast = std::min(yLast, srcHeight); + if (yFirst >= yLast || trgWidth <= 0 || trgHeight <= 0) return; + + for (int y = yFirst; y < yLast; ++y) + { + //mathematically: ySrc = floor(srcHeight * yTrg / trgHeight) + // => search for integers in: [ySrc, ySrc + 1) * trgHeight / srcHeight + + //keep within for loop to support MT input slices! + const int yTrgFirst = ( y * trgHeight + srcHeight - 1) / srcHeight; //=ceil(y * trgHeight / srcHeight) + const int yTrgLast = ((y + 1) * trgHeight + srcHeight - 1) / srcHeight; //=ceil(((y + 1) * trgHeight) / srcHeight) + const int blockHeight = yTrgLast - yTrgFirst; + + if (blockHeight > 0) + { + const PixSrc* srcLine = byteAdvance(src, y * srcPitch); + /**/ PixTrg* trgLine = byteAdvance(trg, yTrgFirst * trgPitch); + int xTrgFirst = 0; + + for (int x = 0; x < srcWidth; ++x) + { + const int xTrgLast = ((x + 1) * trgWidth + srcWidth - 1) / srcWidth; + const int blockWidth = xTrgLast - xTrgFirst; + if (blockWidth > 0) + { + xTrgFirst = xTrgLast; + + const auto trgPix = pixCvrt(srcLine[x]); + fillBlock(trgLine, trgPitch, trgPix, blockWidth, blockHeight); + trgLine += blockWidth; + } + } + } + } +} + + +template +void bilinearScale(const uint32_t* src, int srcWidth, int srcHeight, int srcPitch, + /**/ PixTrg* trg, int trgWidth, int trgHeight, int trgPitch, + int yFirst, int yLast, PixConverter pixCvrt /*convert uint32_t to PixTrg*/) +{ + static_assert(std::is_integral::value, "PixTrg* is expected to be cast-able to char*"); + static_assert(std::is_same::value, "PixConverter returning wrong pixel format"); + + if (srcPitch < srcWidth * static_cast(sizeof(uint32_t)) || + trgPitch < trgWidth * static_cast(sizeof(PixTrg))) + { + assert(false); + return; + } + + yFirst = std::max(yFirst, 0); + yLast = std::min(yLast, trgHeight); + if (yFirst >= yLast || srcHeight <= 0 || srcWidth <= 0) return; + + const double scaleX = static_cast(trgWidth ) / srcWidth; + const double scaleY = static_cast(trgHeight) / srcHeight; + + //perf notes: + // -> double-based calculation is (slightly) faster than float + // -> pre-calculation gives significant boost; std::vector<> memory allocation is negligible! + struct CoeffsX + { + int x1 = 0; + int x2 = 0; + double xx1 = 0; + double x2x = 0; + }; + std::vector buf(trgWidth); + for (int x = 0; x < trgWidth; ++x) + { + const int x1 = srcWidth * x / trgWidth; + int x2 = x1 + 1; + if (x2 == srcWidth) --x2; + + const double xx1 = x / scaleX - x1; + const double x2x = 1 - xx1; + + buf[x] = { x1, x2, xx1, x2x }; + } + + for (int y = yFirst; y < yLast; ++y) + { + const int y1 = srcHeight * y / trgHeight; + int y2 = y1 + 1; + if (y2 == srcHeight) --y2; + + const double yy1 = y / scaleY - y1; + const double y2y = 1 - yy1; + + const uint32_t* const srcLine = byteAdvance(src, y1 * srcPitch); + const uint32_t* const srcLineNext = byteAdvance(src, y2 * srcPitch); + PixTrg* const trgLine = byteAdvance(trg, y * trgPitch); + + for (int x = 0; x < trgWidth; ++x) + { + //perf: do NOT "simplify" the variable layout without measurement! + const int x1 = buf[x].x1; + const int x2 = buf[x].x2; + const double xx1 = buf[x].xx1; + const double x2x = buf[x].x2x; + + const double x2xy2y = x2x * y2y; + const double xx1y2y = xx1 * y2y; + const double x2xyy1 = x2x * yy1; + const double xx1yy1 = xx1 * yy1; + + auto interpolate = [=](int offset) + { + /* https://en.wikipedia.org/wiki/Bilinear_interpolation + (c11(x2 - x) + c21(x - x1)) * (y2 - y ) + + (c12(x2 - x) + c22(x - x1)) * (y - y1) */ + const auto c11 = (srcLine [x1] >> (8 * offset)) & 0xff; + const auto c21 = (srcLine [x2] >> (8 * offset)) & 0xff; + const auto c12 = (srcLineNext[x1] >> (8 * offset)) & 0xff; + const auto c22 = (srcLineNext[x2] >> (8 * offset)) & 0xff; + + return c11 * x2xy2y + c21 * xx1y2y + + c12 * x2xyy1 + c22 * xx1yy1; + }; + + const double bi = interpolate(0); + const double gi = interpolate(1); + const double ri = interpolate(2); + const double ai = interpolate(3); + + const auto b = static_cast(bi + 0.5); + const auto g = static_cast(gi + 0.5); + const auto r = static_cast(ri + 0.5); + const auto a = static_cast(ai + 0.5); + + const uint32_t trgPix = (a << 24) | (r << 16) | (g << 8) | b; + + trgLine[x] = pixCvrt(trgPix); + } + } +} +} + +#endif //XBRZ_TOOLS_H_825480175091875 diff --git a/config/buildingsLibrary.json b/config/buildingsLibrary.json new file mode 100644 index 000000000..fc5133fb9 --- /dev/null +++ b/config/buildingsLibrary.json @@ -0,0 +1,202 @@ +{ + "mageGuild1": { "id" : 0 }, + "mageGuild2": { "id" : 1, "upgrades" : "mageGuild1" }, + "mageGuild3": { "id" : 2, "upgrades" : "mageGuild2" }, + "mageGuild4": { "id" : 3, "upgrades" : "mageGuild3" }, + "mageGuild5": { "id" : 4, "upgrades" : "mageGuild4" }, + "tavern": { + "id" : 5, + "bonuses": [ + { + "type": "MORALE", + "val": 1 + } + ] + }, + "shipyard": { "id" : 6 }, + "fort": { "id" : 7 }, + "citadel": { "id" : 8, "upgrades" : "fort" }, + "castle": { "id" : 9, "upgrades" : "citadel" }, + + "villageHall": { + "id" : 10, + "mode" : "auto", + "produce": { "gold": 500 } + }, + + "townHall": { + "id" : 11, + "upgrades" : "villageHall", + "requires" : [ "tavern" ], + "produce": { "gold": 1000 } + }, + "cityHall": { + "id" : 12, + "upgrades" : "townHall", + "requires" : [ "allOf", [ "mageGuild1" ], [ "marketplace" ], [ "blacksmith" ] ], + "produce": { "gold": 2000 } + }, + "capitol": { + "id" : 13, + "upgrades" : "cityHall", + "requires" : [ "castle" ], + "produce": { "gold": 4000 } + }, + + "marketplace": { "id" : 14 }, + "resourceSilo": { "id" : 15, "requires" : [ "marketplace" ] }, + "blacksmith": { "id" : 16 }, + + // Previously hardcoded buildings that might be used by mods + // Section 1 - building with bonuses during sieges + "brotherhoodOfSword" : { + "bonuses": [ + { + "type": "MORALE", + "val": 2 + } + ] + }, + + "fountainOfFortune" : { + "bonuses": [ + { + "type": "LUCK", + "val": 2 + } + ] + }, + + "spellPowerGarrisonBonus" : { + "bonuses": [ + { + "type": "PRIMARY_SKILL", + "subtype": "primarySkill.spellpower", + "val": 2 + } + ] + }, + + "attackGarrisonBonus" : { + "bonuses": [ + { + "type": "PRIMARY_SKILL", + "subtype": "primarySkill.attack", + "val": 2 + } + ] + }, + + "defenseGarrisonBonus" : { + "bonuses": [ + { + "type": "PRIMARY_SKILL", + "subtype": "primarySkill.defence", + "val": 2 + } + ] + }, + + "lighthouse" : { + "bonuses": [ + { + "propagator": "PLAYER_PROPAGATOR", + "type": "MOVEMENT", + "subtype": "heroMovementSea", + "val": 500 + } + ] + }, + + // Section 2 - buildings that are visitable by hero + "stables": { + "configuration" : { + "visitMode" : "bonus", + "rewards" : [ + { + "message" : "@core.genrltxt.580", + "movePoints" : 400, + "bonuses" : [ { "type" : "MOVEMENT", "subtype" : "heroMovementLand", "val" : 400, "valueType" : "ADDITIVE_VALUE", "duration" : "ONE_WEEK"} ] + } + ] + } + }, + "manaVortex": { + "configuration" : { + "resetParameters" : { + "period" : 7, + "visitors" : true + }, + "visitMode" : "hero", // Should be 'once' to match (somewhat buggy) H3 logic + "rewards" : [ + { + "limiter" : { + "noneOf" : [ { "manaPercentage" : 200 } ] + }, + "message" : "@core.genrltxt.579", + "manaPercentage" : 200 + } + ] + } + }, + + "attackVisitingBonus": { + "configuration" : { + "visitMode" : "hero", + "rewards" : [ + { + "message" : "@core.genrltxt.584", + "primary" : { "attack" : 1 } + } + ] + } + }, + + "defenceVisitingBonus": { + "configuration" : { + "visitMode" : "hero", + "rewards" : [ + { + "message" : "@core.genrltxt.585", + "primary" : { "defence" : 1 } + } + ] + } + }, + + "spellPowerVisitingBonus": { + "configuration" : { + "visitMode" : "hero", + "rewards" : [ + { + "message" : "@core.genrltxt.582", + "primary" : { "spellpower" : 1 } + } + ] + } + }, + + "knowledgeVisitingBonus": { + "configuration" : { + "visitMode" : "hero", + "rewards" : [ + { + "message" : "@core.genrltxt.581", + "primary" : { "knowledge" : 1 } + } + ] + } + }, + + "experienceVisitingBonus": { + "configuration" : { + "visitMode" : "hero", + "rewards" : [ + { + "message" : "@core.genrltxt.583", + "heroExperience" : 1000 + } + ] + } + } +} \ No newline at end of file diff --git a/config/factions/castle.json b/config/factions/castle.json index 1d8c02d65..66336c156 100644 --- a/config/factions/castle.json +++ b/config/factions/castle.json @@ -153,29 +153,60 @@ "buildings" : { - "mageGuild1": { "id" : 0 }, - "mageGuild2": { "id" : 1, "upgrades" : "mageGuild1" }, - "mageGuild3": { "id" : 2, "upgrades" : "mageGuild2" }, - "mageGuild4": { "id" : 3, "upgrades" : "mageGuild3" }, - "tavern": { "id" : 5 }, - "shipyard": { "id" : 6 }, - "fort": { "id" : 7 }, - "citadel": { "id" : 8, "upgrades" : "fort" }, - "castle": { "id" : 9, "upgrades" : "citadel" }, - "villageHall": { "id" : 10, "mode" : "auto", "produce": { "gold": 500 } }, - "townHall": { "id" : 11, "upgrades" : "villageHall", "requires" : [ "tavern" ], "produce": { "gold": 1000 } }, - "cityHall": { "id" : 12, "upgrades" : "townHall", "requires" : [ "allOf", [ "mageGuild1" ], [ "marketplace" ], [ "blacksmith" ] ], "produce": { "gold": 2000 } }, - "capitol": { "id" : 13, "upgrades" : "cityHall", "requires" : [ "castle" ], "produce": { "gold": 4000 } }, - "marketplace": { "id" : 14 }, - "resourceSilo": { "id" : 15, "requires" : [ "marketplace" ], "produce": { "ore": 1, "wood": 1 } }, - "blacksmith": { "id" : 16 }, + "mageGuild1": { }, + "mageGuild2": { }, + "mageGuild3": { }, + "mageGuild4": { }, + "tavern": { }, + "shipyard": { }, + "fort": { }, + "citadel": { }, + "castle": { }, + "villageHall": { }, + "townHall": { }, + "cityHall": { }, + "capitol": { }, + "marketplace": { }, + "resourceSilo": { "produce": { "ore": 1, "wood": 1 } }, + "blacksmith": { }, - "special1": { "type" : "lighthouse", "requires" : [ "shipyard" ] }, + "special1": { + "bonuses": [ + { + "propagator": "PLAYER_PROPAGATOR", + "type": "MOVEMENT", + "subtype": "heroMovementSea", + "val": 500 + } + ], + "requires" : [ "shipyard" ] + }, "horde1": { "id" : 18, "upgrades" : "dwellingLvl3" }, "horde1Upgr": { "id" : 19, "upgrades" : "dwellingUpLvl3", "requires" : [ "horde1" ], "mode" : "auto" }, "ship": { "id" : 20, "upgrades" : "shipyard" }, - "special2": { "type" : "stables", "requires" : [ "dwellingLvl4" ] }, - "special3": { "type" : "brotherhoodOfSword", "upgrades" : "tavern" }, + "special2": { + "requires" : [ "dwellingLvl4" ], + "configuration" : { + "visitMode" : "bonus", + "rewards" : [ + { + "message" : "@core.genrltxt.580", + "movePoints" : 400, + "bonuses" : [ { "type" : "MOVEMENT", "subtype" : "heroMovementLand", "val" : 400, "valueType" : "ADDITIVE_VALUE", "duration" : "ONE_WEEK"} ] + } + ] + } + }, + "special3": { + "upgradeReplacesBonuses" : true, + "bonuses": [ + { + "type": "MORALE", + "val": 2 + } + ], + "upgrades" : "tavern" + }, "grail": { "id" : 26, "mode" : "grail", "produce": { "gold": 5000 }, "bonuses": [ { "type": "MORALE", "val": 2, "propagator": "PLAYER_PROPAGATOR" } ] }, "dwellingLvl1": { "id" : 30, "requires" : [ "fort" ] }, diff --git a/config/factions/conflux.json b/config/factions/conflux.json index 69307372c..d760cf80f 100644 --- a/config/factions/conflux.json +++ b/config/factions/conflux.json @@ -157,23 +157,23 @@ "buildings" : { - "mageGuild1": { "id" : 0 }, - "mageGuild2": { "id" : 1, "upgrades" : "mageGuild1" }, - "mageGuild3": { "id" : 2, "upgrades" : "mageGuild2" }, - "mageGuild4": { "id" : 3, "upgrades" : "mageGuild3" }, - "mageGuild5": { "id" : 4, "upgrades" : "mageGuild4" }, - "tavern": { "id" : 5 }, - "shipyard": { "id" : 6 }, - "fort": { "id" : 7 }, - "citadel": { "id" : 8, "upgrades" : "fort" }, - "castle": { "id" : 9, "upgrades" : "citadel" }, - "villageHall": { "id" : 10, "mode" : "auto", "produce": { "gold": 500 } }, - "townHall": { "id" : 11, "upgrades" : "villageHall", "requires" : [ "tavern" ], "produce": { "gold": 1000 } }, - "cityHall": { "id" : 12, "upgrades" : "townHall", "requires" : [ "allOf", [ "mageGuild1" ], [ "marketplace" ], [ "blacksmith" ] ], "produce": { "gold": 2000 } }, - "capitol": { "id" : 13, "upgrades" : "cityHall", "requires" : [ "castle" ], "produce": { "gold": 4000 } }, - "marketplace": { "id" : 14 }, - "resourceSilo": { "id" : 15, "requires" : [ "marketplace" ], "produce": { "mercury": 1 } }, - "blacksmith": { "id" : 16 }, + "mageGuild1": { }, + "mageGuild2": { }, + "mageGuild3": { }, + "mageGuild4": { }, + "mageGuild5": { }, + "tavern": { }, + "shipyard": { }, + "fort": { }, + "citadel": { }, + "castle": { }, + "villageHall": { }, + "townHall": { }, + "cityHall": { }, + "capitol": { }, + "marketplace": { }, + "resourceSilo": { "produce": { "mercury": 1 } }, + "blacksmith": { }, "special1": { "type" : "artifactMerchant", "requires" : [ "marketplace" ] }, "horde1": { "id" : 18, "upgrades" : "dwellingLvl1" }, diff --git a/config/factions/dungeon.json b/config/factions/dungeon.json index 84a4d1b13..9d5c2dacd 100644 --- a/config/factions/dungeon.json +++ b/config/factions/dungeon.json @@ -154,29 +154,57 @@ "buildings" : { - "mageGuild1": { "id" : 0 }, - "mageGuild2": { "id" : 1, "upgrades" : "mageGuild1" }, - "mageGuild3": { "id" : 2, "upgrades" : "mageGuild2" }, - "mageGuild4": { "id" : 3, "upgrades" : "mageGuild3" }, - "mageGuild5": { "id" : 4, "upgrades" : "mageGuild4" }, - "tavern": { "id" : 5 }, - "fort": { "id" : 7 }, - "citadel": { "id" : 8, "upgrades" : "fort" }, - "castle": { "id" : 9, "upgrades" : "citadel" }, - "villageHall": { "id" : 10, "mode" : "auto", "produce": { "gold": 500 } }, - "townHall": { "id" : 11, "upgrades" : "villageHall", "requires" : [ "tavern" ], "produce": { "gold": 1000 } }, - "cityHall": { "id" : 12, "upgrades" : "townHall", "requires" : [ "allOf", [ "mageGuild1" ], [ "marketplace" ], [ "blacksmith" ] ], "produce": { "gold": 2000 } }, - "capitol": { "id" : 13, "upgrades" : "cityHall", "requires" : [ "castle" ], "produce": { "gold": 4000 } }, - "marketplace": { "id" : 14 }, - "resourceSilo": { "id" : 15, "requires" : [ "marketplace" ] }, - "blacksmith": { "id" : 16 }, + "mageGuild1": { }, + "mageGuild2": { }, + "mageGuild3": { }, + "mageGuild4": { }, + "mageGuild5": { }, + "tavern": { }, + "fort": { }, + "citadel": { }, + "castle": { }, + "villageHall": { }, + "townHall": { }, + "cityHall": { }, + "capitol": { }, + "marketplace": { }, + "resourceSilo": { "produce": { "sulfur": 1 } }, + "blacksmith": { }, "special1": { "type" : "artifactMerchant", "requires" : [ "marketplace" ] }, "horde1": { "id" : 18, "upgrades" : "dwellingLvl1" }, "horde1Upgr": { "id" : 19, "upgrades" : "dwellingUpLvl1", "requires" : [ "horde1" ], "mode" : "auto" }, - "special2": { "type" : "manaVortex", "requires" : [ "mageGuild1" ] }, + "special2": { + "requires" : [ "mageGuild1" ], + "configuration" : { + "resetParameters" : { + "period" : 7, + "visitors" : true + }, + "visitMode" : "hero", // Should be 'once' to match (somewhat buggy) H3 logic + "rewards" : [ + { + "limiter" : { + "noneOf" : [ { "manaPercentage" : 200 } ] + }, + "message" : "@core.genrltxt.579", + "manaPercentage" : 200 + } + ] + } + }, "special3": { "type" : "portalOfSummoning" }, - "special4": { "type" : "experienceVisitingBonus" }, + "special4": { + "configuration" : { + "visitMode" : "hero", + "rewards" : [ + { + "message" : "@core.genrltxt.583", + "heroExperience" : 1000 + } + ] + } + }, "grail": { "id" : 26, "mode" : "grail", "produce": { "gold": 5000 }, "bonuses": [ { "type": "PRIMARY_SKILL", "subtype": "primarySkill.spellpower", "val": 12 } ] }, diff --git a/config/factions/fortress.json b/config/factions/fortress.json index 082dfd38f..d66054168 100644 --- a/config/factions/fortress.json +++ b/config/factions/fortress.json @@ -153,28 +153,57 @@ "buildings" : { - "mageGuild1": { "id" : 0 }, - "mageGuild2": { "id" : 1, "upgrades" : "mageGuild1" }, - "mageGuild3": { "id" : 2, "upgrades" : "mageGuild2" }, - "tavern": { "id" : 5 }, - "shipyard": { "id" : 6 }, - "fort": { "id" : 7 }, - "citadel": { "id" : 8, "upgrades" : "fort" }, - "castle": { "id" : 9, "upgrades" : "citadel" }, - "villageHall": { "id" : 10, "mode" : "auto", "produce": { "gold": 500 } }, - "townHall": { "id" : 11, "upgrades" : "villageHall", "requires" : [ "tavern" ], "produce": { "gold": 1000 } }, - "cityHall": { "id" : 12, "upgrades" : "townHall", "requires" : [ "allOf", [ "mageGuild1" ], [ "marketplace" ], [ "blacksmith" ] ], "produce": { "gold": 2000 } }, - "capitol": { "id" : 13, "upgrades" : "cityHall", "requires" : [ "castle" ], "produce": { "gold": 4000 } }, - "marketplace": { "id" : 14 }, - "resourceSilo": { "id" : 15, "requires" : [ "marketplace" ], "produce": { "wood": 1, "ore": 1 } }, - "blacksmith": { "id" : 16 }, + "mageGuild1": { }, + "mageGuild2": { }, + "mageGuild3": { }, + "tavern": { }, + "shipyard": { }, + "fort": { }, + "citadel": { }, + "castle": { }, + "villageHall": { }, + "townHall": { }, + "cityHall": { }, + "capitol": { }, + "marketplace": { }, + "resourceSilo": { "produce": { "wood": 1, "ore": 1 } }, + "blacksmith": { }, - "special1": { "type" : "defenceVisitingBonus", "requires" : [ "allOf", [ "townHall" ], [ "special2" ] ] }, + "special1": { + "requires" : [ "allOf", [ "townHall" ], [ "special2" ] ], + "configuration" : { + "visitMode" : "hero", + "rewards" : [ + { + "message" : "@core.genrltxt.585", + "primary" : { "defence" : 1 } + } + ] + } + }, "horde1": { "id" : 18, "upgrades" : "dwellingLvl1" }, "horde1Upgr": { "id" : 19, "upgrades" : "dwellingUpLvl1", "requires" : [ "horde1" ], "mode" : "auto" }, "ship": { "id" : 20, "upgrades" : "shipyard" }, - "special2": { "type" : "defenseGarrisonBonus", "requires" : [ "fort" ] }, - "special3": { "type" : "attackGarrisonBonus", "requires" : [ "special2" ] }, + "special2": { + "bonuses": [ + { + "type": "PRIMARY_SKILL", + "subtype": "primarySkill.defence", + "val": 2 + } + ], + "requires" : [ "fort" ] + }, + "special3": { + "bonuses": [ + { + "type": "PRIMARY_SKILL", + "subtype": "primarySkill.defence", + "val": 2 + } + ], + "requires" : [ "special2" ] + }, "grail": { "id" : 26, "mode" : "grail", "produce": { "gold": 5000 }, "bonuses": [ { "type": "PRIMARY_SKILL", "subtype": "primarySkill.attack", "val": 10 }, diff --git a/config/factions/inferno.json b/config/factions/inferno.json index db1b7675a..3764c938e 100644 --- a/config/factions/inferno.json +++ b/config/factions/inferno.json @@ -154,28 +154,48 @@ "buildings" : { - "mageGuild1": { "id" : 0 }, - "mageGuild2": { "id" : 1, "upgrades" : "mageGuild1" }, - "mageGuild3": { "id" : 2, "upgrades" : "mageGuild2" }, - "mageGuild4": { "id" : 3, "upgrades" : "mageGuild3" }, - "mageGuild5": { "id" : 4, "upgrades" : "mageGuild4" }, - "tavern": { "id" : 5 }, - "fort": { "id" : 7 }, - "citadel": { "id" : 8, "upgrades" : "fort" }, - "castle": { "id" : 9, "upgrades" : "citadel" }, - "villageHall": { "id" : 10, "mode" : "auto", "produce": { "gold": 500 } }, - "townHall": { "id" : 11, "upgrades" : "villageHall", "requires" : [ "tavern" ], "produce": { "gold": 1000 } }, - "cityHall": { "id" : 12, "upgrades" : "townHall", "requires" : [ "allOf", [ "mageGuild1" ], [ "marketplace" ], [ "blacksmith" ] ], "produce": { "gold": 2000 } }, - "capitol": { "id" : 13, "upgrades" : "cityHall", "requires" : [ "castle" ], "produce": { "gold": 4000 } }, - "marketplace": { "id" : 14 }, - "resourceSilo": { "id" : 15, "requires" : [ "marketplace" ], "produce": { "mercury": 1 } }, - "blacksmith": { "id" : 16 }, + "mageGuild1": { }, + "mageGuild2": { }, + "mageGuild3": { }, + "mageGuild4": { }, + "mageGuild5": { }, + "tavern": { }, + "fort": { }, + "citadel": { }, + "castle": { }, + "villageHall": { }, + "townHall": { }, + "cityHall": { }, + "capitol": { }, + "marketplace": { }, + "resourceSilo": { "produce": { "mercury": 1 } }, + "blacksmith": { }, "horde1": { "id" : 18, "upgrades" : "dwellingLvl1" }, "horde1Upgr": { "id" : 19, "upgrades" : "dwellingUpLvl1", "requires" : [ "horde1" ], "mode" : "auto" }, - "special2": { "type" : "spellPowerGarrisonBonus", "requires" : [ "fort" ] }, + "special2": { + "bonuses": [ + { + "type": "PRIMARY_SKILL", + "subtype": "primarySkill.spellpower", + "val": 2 + } + ], + "requires" : [ "fort" ] + }, "special3": { "type" : "castleGate", "requires" : [ "citadel" ] }, - "special4": { "type" : "spellPowerVisitingBonus", "requires" : [ "mageGuild1" ] }, + "special4": { + "requires" : [ "mageGuild1" ], + "configuration" : { + "visitMode" : "hero", + "rewards" : [ + { + "message" : "@core.genrltxt.582", + "primary" : { "spellpower" : 1 } + } + ] + } + }, "horde2": { "id" : 24, "upgrades" : "dwellingLvl3" }, "horde2Upgr": { "id" : 25, "upgrades" : "dwellingUpLvl3", "requires" : [ "horde2" ], "mode" : "auto" }, "grail": { "id" : 26, "mode" : "grail", "produce": { "gold": 5000 }}, diff --git a/config/factions/necropolis.json b/config/factions/necropolis.json index 425a3a550..08dd7aed8 100644 --- a/config/factions/necropolis.json +++ b/config/factions/necropolis.json @@ -158,23 +158,23 @@ "buildings" : { - "mageGuild1": { "id" : 0 }, - "mageGuild2": { "id" : 1, "upgrades" : "mageGuild1" }, - "mageGuild3": { "id" : 2, "upgrades" : "mageGuild2" }, - "mageGuild4": { "id" : 3, "upgrades" : "mageGuild3" }, - "mageGuild5": { "id" : 4, "upgrades" : "mageGuild4" }, - "tavern": { "id" : 5 }, - "shipyard": { "id" : 6 }, - "fort": { "id" : 7 }, - "citadel": { "id" : 8, "upgrades" : "fort" }, - "castle": { "id" : 9, "upgrades" : "citadel" }, - "villageHall": { "id" : 10, "mode" : "auto", "produce": { "gold": 500 } }, - "townHall": { "id" : 11, "upgrades" : "villageHall", "requires" : [ "tavern" ], "produce": { "gold": 1000 } }, - "cityHall": { "id" : 12, "upgrades" : "townHall", "requires" : [ "allOf", [ "mageGuild1" ], [ "marketplace" ], [ "blacksmith" ] ], "produce": { "gold": 2000 } }, - "capitol": { "id" : 13, "upgrades" : "cityHall", "requires" : [ "castle" ], "produce": { "gold": 4000 } }, - "marketplace": { "id" : 14 }, - "resourceSilo": { "id" : 15, "requires" : [ "marketplace" ], "produce": { "ore": 1, "wood": 1 } }, - "blacksmith": { "id" : 16 }, + "mageGuild1": { }, + "mageGuild2": { }, + "mageGuild3": { }, + "mageGuild4": { }, + "mageGuild5": { }, + "tavern": { }, + "shipyard": { }, + "fort": { }, + "citadel": { }, + "castle": { }, + "villageHall": { }, + "townHall": { }, + "cityHall": { }, + "capitol": { }, + "marketplace": { }, + "resourceSilo": { "produce": { "ore": 1, "wood": 1 } }, + "blacksmith": { }, "special1": { "requires" : [ "fort" ], "bonuses": [ { "type": "DARKNESS", "val": 20 } ] }, "horde1": { "id" : 18, "upgrades" : "dwellingLvl1", "requires" : [ "special3" ] }, diff --git a/config/factions/rampart.json b/config/factions/rampart.json index 4c2ba145d..01e86fb0c 100644 --- a/config/factions/rampart.json +++ b/config/factions/rampart.json @@ -157,27 +157,35 @@ "buildings" : { - "mageGuild1": { "id" : 0 }, - "mageGuild2": { "id" : 1, "upgrades" : "mageGuild1" }, - "mageGuild3": { "id" : 2, "upgrades" : "mageGuild2" }, - "mageGuild4": { "id" : 3, "upgrades" : "mageGuild3" }, - "mageGuild5": { "id" : 4, "upgrades" : "mageGuild4" }, - "tavern": { "id" : 5 }, - "fort": { "id" : 7 }, - "citadel": { "id" : 8, "upgrades" : "fort" }, - "castle": { "id" : 9, "upgrades" : "citadel" }, - "villageHall": { "id" : 10, "mode" : "auto", "produce": { "gold": 500 } }, - "townHall": { "id" : 11, "upgrades" : "villageHall", "requires" : [ "tavern" ], "produce": { "gold": 1000 } }, - "cityHall": { "id" : 12, "upgrades" : "townHall", "requires" : [ "allOf", [ "mageGuild1" ], [ "marketplace" ], [ "blacksmith" ] ], "produce": { "gold": 2000 } }, - "capitol": { "id" : 13, "upgrades" : "cityHall", "requires" : [ "castle" ], "produce": { "gold": 4000 } }, - "marketplace": { "id" : 14 }, - "resourceSilo": { "id" : 15, "requires" : [ "marketplace" ], "produce": { "crystal": 1 } }, - "blacksmith": { "id" : 16 }, + "mageGuild1": { }, + "mageGuild2": { }, + "mageGuild3": { }, + "mageGuild4": { }, + "mageGuild5": { }, + "tavern": { }, + "fort": { }, + "citadel": { }, + "castle": { }, + "villageHall": { }, + "townHall": { }, + "cityHall": { }, + "capitol": { }, + "marketplace": { }, + "resourceSilo": { "produce": { "crystal": 1 } }, + "blacksmith": { }, "special1": { "type" : "mysticPond" }, "horde1": { "id" : 18, "upgrades" : "dwellingLvl2" }, "horde1Upgr": { "id" : 19, "upgrades" : "dwellingUpLvl2", "requires" : [ "horde1" ], "mode" : "auto" }, - "special2": { "type" : "fountainOfFortune", "upgrades" : "special1" }, + "special2": { + "bonuses": [ + { + "type": "LUCK", + "val": 2 + } + ], + "upgrades" : "special1" + }, "special3": { "type" : "treasury", "requires" : [ "horde1" ] }, "horde2": { "id" : 24, "upgrades" : "dwellingLvl5" }, "horde2Upgr": { "id" : 25, "upgrades" : "dwellingUpLvl5", "requires" : [ "horde2" ], "mode" : "auto" }, diff --git a/config/factions/stronghold.json b/config/factions/stronghold.json index c1eeb8397..73bc9ff52 100644 --- a/config/factions/stronghold.json +++ b/config/factions/stronghold.json @@ -151,27 +151,38 @@ "buildings" : { - "mageGuild1": { "id" : 0 }, - "mageGuild2": { "id" : 1, "upgrades" : "mageGuild1" }, - "mageGuild3": { "id" : 2, "upgrades" : "mageGuild2" }, - "tavern": { "id" : 5 }, - "fort": { "id" : 7 }, - "citadel": { "id" : 8, "upgrades" : "fort" }, - "castle": { "id" : 9, "upgrades" : "citadel" }, - "villageHall": { "id" : 10, "mode" : "auto", "produce": { "gold": 500 } }, - "townHall": { "id" : 11, "upgrades" : "villageHall", "requires" : [ "tavern" ], "produce": { "gold": 1000 } }, - "cityHall": { "id" : 12, "upgrades" : "townHall", "requires" : [ "allOf", [ "mageGuild1" ], [ "marketplace" ], [ "blacksmith" ] ], "produce": { "gold": 2000 } }, - "capitol": { "id" : 13, "upgrades" : "cityHall", "requires" : [ "castle" ], "produce": { "gold": 4000 } }, - "marketplace": { "id" : 14 }, - "resourceSilo": { "id" : 15, "requires" : [ "marketplace" ], "produce": { "ore": 1, "wood": 1 } }, - "blacksmith": { "id" : 16 }, + "mageGuild1": { }, + "mageGuild2": { }, + "mageGuild3": { }, + "tavern": { }, + "fort": { }, + "citadel": { }, + "castle": { }, + "villageHall": { }, + "townHall": { }, + "cityHall": { }, + "capitol": { }, + "marketplace": { }, + "resourceSilo": { "produce": { "ore": 1, "wood": 1 } }, + "blacksmith": { }, "special1": { "type" : "escapeTunnel", "requires" : [ "fort" ] }, "horde1": { "id" : 18, "upgrades" : "dwellingLvl1" }, "horde1Upgr": { "id" : 19, "upgrades" : "dwellingUpLvl1", "requires" : [ "horde1" ], "mode" : "auto" }, "special2": { "type" : "freelancersGuild", "requires" : [ "marketplace" ] }, "special3": { "type" : "ballistaYard", "requires" : [ "blacksmith" ] }, - "special4": { "type" : "attackVisitingBonus", "requires" : [ "fort" ] }, + "special4": { + "requires" : [ "fort" ], + "configuration" : { + "visitMode" : "hero", + "rewards" : [ + { + "message" : "@core.genrltxt.584", + "primary" : { "attack" : 1 } + } + ] + } + }, "grail": { "id" : 26, "mode" : "grail", "produce": { "gold": 5000 }, "bonuses": [ { "type": "PRIMARY_SKILL", "subtype": "primarySkill.attack", "val": 20 } ] }, diff --git a/config/factions/tower.json b/config/factions/tower.json index edc3ab29f..452f884a8 100644 --- a/config/factions/tower.json +++ b/config/factions/tower.json @@ -152,29 +152,40 @@ "buildings" : { - "mageGuild1": { "id" : 0 }, - "mageGuild2": { "id" : 1, "upgrades" : "mageGuild1" }, - "mageGuild3": { "id" : 2, "upgrades" : "mageGuild2" }, - "mageGuild4": { "id" : 3, "upgrades" : "mageGuild3" }, - "mageGuild5": { "id" : 4, "upgrades" : "mageGuild4" }, - "tavern": { "id" : 5 }, - "fort": { "id" : 7 }, - "citadel": { "id" : 8, "upgrades" : "fort" }, - "castle": { "id" : 9, "upgrades" : "citadel" }, - "villageHall": { "id" : 10, "mode" : "auto", "produce" : { "gold": 500 } }, - "townHall": { "id" : 11, "upgrades" : "villageHall", "requires" : [ "tavern" ], "produce" : { "gold": 1000 } }, - "cityHall": { "id" : 12, "upgrades" : "townHall", "requires" : [ "allOf", [ "mageGuild1" ], [ "marketplace" ], [ "blacksmith" ] ], "produce": { "gold": 2000 } }, - "capitol": { "id" : 13, "upgrades" : "cityHall", "requires" : [ "castle" ], "produce" : { "gold": 4000 } }, - "marketplace": { "id" : 14 }, - "resourceSilo": { "id" : 15, "requires" : [ "marketplace" ], "produce" : { "gems": 1 } }, - "blacksmith": { "id" : 16 }, + "mageGuild1": { }, + "mageGuild2": { }, + "mageGuild3": { }, + "mageGuild4": { }, + "mageGuild5": { }, + "tavern": { }, + "fort": { }, + "citadel": { }, + "castle": { }, + "villageHall": { }, + "townHall": { }, + "cityHall": { }, + "capitol": { }, + "marketplace": { }, + "resourceSilo": { "produce" : { "gems": 1 } }, + "blacksmith": { }, "special1": { "type" : "artifactMerchant", "requires" : [ "marketplace" ] }, "horde1": { "id" : 18, "upgrades" : "dwellingLvl2" }, "horde1Upgr": { "id" : 19, "upgrades" : "dwellingUpLvl2", "requires" : [ "horde1" ], "mode" : "auto" }, - "special2": { "type" : "lookoutTower", "height" : "high", "requires" : [ "fort" ] }, + "special2": { "height" : "high", "requires" : [ "fort" ] }, "special3": { "type" : "library", "requires" : [ "mageGuild1" ] }, - "special4": { "type" : "knowledgeVisitingBonus", "requires" : [ "mageGuild1" ] }, + "special4": { + "requires" : [ "mageGuild1" ], + "configuration" : { + "visitMode" : "hero", + "rewards" : [ + { + "message" : "@core.genrltxt.581", + "primary" : { "knowledge" : 1 } + } + ] + } + }, "grail": { "height" : "skyship", "produce" : { "gold": 5000 }, "bonuses": [ { "type": "PRIMARY_SKILL", "subtype": "primarySkill.knowledge", "val": 15 } ] }, "dwellingLvl1": { "id" : 30, "requires" : [ "fort" ] }, diff --git a/config/schemas/bonus.json b/config/schemas/bonus.json index 2789994c8..ffc1ab53b 100644 --- a/config/schemas/bonus.json +++ b/config/schemas/bonus.json @@ -179,7 +179,10 @@ "description" : "stacking" }, "description" : { - "type" : "string", + "anyOf" : [ + { "type" : "string" }, + { "type" : "number" } + ], "description" : "description" } } diff --git a/config/schemas/objectType.json b/config/schemas/objectType.json index b470bc1cc..3d582bafa 100644 --- a/config/schemas/objectType.json +++ b/config/schemas/objectType.json @@ -34,6 +34,9 @@ } } }, + "name" : { + "type" : "string" + }, "templates" : { "type" : "object", "additionalProperties" : { diff --git a/config/schemas/rewardable.json b/config/schemas/rewardable.json new file mode 100644 index 000000000..bc76b743f --- /dev/null +++ b/config/schemas/rewardable.json @@ -0,0 +1,327 @@ +{ + "type" : "object", + "$schema" : "http://json-schema.org/draft-04/schema", + "title" : "VCMI map object format", + "description" : "Description of map object class", + "required" : [ "rewards" ], + "additionalProperties" : false, + + "definitions" : { + "value" : { + "anyOf" : [ + { + "type" : "number" + }, + { + "type" : "string" // variable name + }, + { + "type" : "array", + "items" : { + "$ref" : "#/definitions/value" + } + }, + { + "type" : "object", + "additionalProperties" : true, + "properties" : { + "amount" : { "$ref" : "#/definitions/value" }, + "min" : { "$ref" : "#/definitions/value" }, + "max" : { "$ref" : "#/definitions/value" } + } + } + ] + }, + "identifier" : { + "anyOf" : [ + { + "type" : "string" + }, + { + "type" : "object", + "additionalProperties" : true, + "properties" : { + "type" : { + "$ref" : "#/definitions/identifier" + }, + "anyOf" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/identifier" + } + }, + "noneOf" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/identifier" + } + } + } + } + ] + }, + "identifierList" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/identifier" + } + }, + "identifierWithValueList" : { + "anyOf" : [ + { + "type" : "array", + "items" : { + "allOf" : [ + { "$ref" : "#/definitions/identifier" }, + { "$ref" : "#/definitions/value" } + ] + } + }, + { + "type" : "object", + "additionalProperties" : { + "$ref" : "#/definitions/value" + } + }, + ], + }, + "reward" : { + "type" : "object", + "additionalProperties" : false, + "properties" : { + "appearChance" : { + "type" : "object", + "additionalProperties" : false, + "properties" : { + "dice" : { "type" : "number" }, + "min" : { "type" : "number", "minimum" : 0, "exclusiveMaximum" : 100 }, + "max" : { "type" : "number", "exclusiveMinimum" : 0, "maximum" : 100 } + } + }, + "limiter" : { "$ref" : "#/definitions/limiter" }, + "message" : { "$ref" : "#/definitions/message" }, + "description" : { "$ref" : "#/definitions/message" }, + + "heroExperience" : { "$ref" : "#/definitions/value" }, + "heroLevel" : { "$ref" : "#/definitions/value" }, + "movePercentage" : { "$ref" : "#/definitions/value" }, + "movePoints" : { "$ref" : "#/definitions/value" }, + "manaPercentage" : { "$ref" : "#/definitions/value" }, + "manaPoints" : { "$ref" : "#/definitions/value" }, + "manaOverflowFactor" : { "$ref" : "#/definitions/value" }, + + "removeObject" : { "type" : "boolean" }, + "bonuses" : { + "type":"array", + "description": "List of bonuses that will be granted to visiting hero", + "items": { "$ref" : "bonus.json" } + }, + + "resources" : { "$ref" : "#/definitions/identifierWithValueList" }, + "secondary" : { "$ref" : "#/definitions/identifierWithValueList" }, + "creatures" : { "$ref" : "#/definitions/identifierWithValueList" }, + "primary" : { "$ref" : "#/definitions/identifierWithValueList" }, + + "artifacts" : { "$ref" : "#/definitions/identifierList" }, + "spells" : { "$ref" : "#/definitions/identifierList" }, + + "spellCast" : { + "type" : "object", + "additionalProperties" : false, + "properties" : { + "spell" : { "$ref" : "#/definitions/identifier" }, + "schoolLevel" : { "type" : "number" } + } + }, + "revealTiles" : { + "type" : "object", + "additionalProperties" : false, + "properties" : { + "hide" : { "type" : "boolean" }, + "radius" : { "type" : "number" }, + "surface" : { "type" : "number" }, + "subterra" : { "type" : "number" }, + "water" : { "type" : "number" }, + "rock" : { "type" : "number" } + } + }, + "changeCreatures" : { + "type" : "object", + "additionalProperties" : { "type" : "string" } + } + } + }, + "limiter" : { + "type" : "object", + "additionalProperties" : false, + "properties" : { + "dayOfWeek" : { "$ref" : "#/definitions/value" }, + "daysPassed" : { "$ref" : "#/definitions/value" }, + "heroExperience" : { "$ref" : "#/definitions/value" }, + "heroLevel" : { "$ref" : "#/definitions/value" }, + "manaPercentage" : { "$ref" : "#/definitions/value" }, + "manaPoints" : { "$ref" : "#/definitions/value" }, + + "canLearnSkills" : { "type" : "boolean" }, + + "resources" : { "$ref" : "#/definitions/identifierWithValueList" }, + "secondary" : { "$ref" : "#/definitions/identifierWithValueList" }, + "creatures" : { "$ref" : "#/definitions/identifierWithValueList" }, + "primary" : { "$ref" : "#/definitions/identifierWithValueList" }, + + "canLearnSpells" : { "$ref" : "#/definitions/identifierList" }, + "heroClasses" : { "$ref" : "#/definitions/identifierList" }, + "artifacts" : { "$ref" : "#/definitions/identifierList" }, + "spells" : { "$ref" : "#/definitions/identifierList" }, + "colors" : { "$ref" : "#/definitions/identifierList" }, + "heroes" : { "$ref" : "#/definitions/identifierList" }, + + "anyOf" : { + "type" : "array", + "items" : { "$ref" : "#/definitions/limiter" } + }, + "allOf" : { + "type" : "array", + "items" : { "$ref" : "#/definitions/limiter" } + }, + "noneOf" : { + "type" : "array", + "items" : { "$ref" : "#/definitions/limiter" } + }, + } + }, + "message" : { + "anyOf" : [ + { + "type" : "array", + "items" : { + "anyOf" : [ + { "type" : "number" }, + { "type" : "string" } + ] + } + }, + { + "type" : "number" + }, + { + "type" : "string" + } + ] + }, + "variableList" : { + "type" : "object", + "additionalProperties" : { + "$ref" : "#/definitions/identifier" + } + } + }, + + "properties" : { + "rewards" : { + "type" : "array", + "items" : { "$ref" : "#/definitions/reward" } + }, + "onVisited" : { + "type" : "array", + "items" : { "$ref" : "#/definitions/reward" } + }, + "onEmpty" : { + "type" : "array", + "items" : { "$ref" : "#/definitions/reward" } + }, + + "variables" : { + "type" : "object", + "additionalProperties" : false, + "properties" : { + "number" : { + "type" : "object", + "additionalProperties" : { + "$ref" : "#/definitions/value" + } + }, + "artifact" : { + "$ref" : "#/definitions/variableList" + }, + "spell" : { + "$ref" : "#/definitions/variableList" + }, + "primarySkill" : { + "$ref" : "#/definitions/variableList" + }, + "secondarySkill" : { + "$ref" : "#/definitions/variableList" + }, + }, + }, + + "onSelectMessage" : { + "$ref" : "#/definitions/message" + }, + "description" : { + "$ref" : "#/definitions/message" + }, + "notVisitedTooltip" : { + "$ref" : "#/definitions/message" + }, + "visitedTooltip" : { + "$ref" : "#/definitions/message" + }, + "onVisitedMessage" : { + "$ref" : "#/definitions/message" + }, + "onEmptyMessage" : { + "$ref" : "#/definitions/message" + }, + + "canRefuse": { + "type" : "boolean" + }, + + "showScoutedPreview": { + "type" : "boolean" + }, + + "showInInfobox": { + "type" : "boolean" + }, + + "visitMode": { + "enum" : [ "unlimited", "once", "hero", "bonus", "limiter", "player" ], + "type" : "string" + }, + + "visitLimiter": { + "type" : "object" + }, + + "selectMode": { + "enum" : [ "selectFirst", "selectPlayer", "selectRandom", "selectAll" ], + "type" : "string" + }, + + "resetParameters" : { + "type" : "object", + "additionalProperties" : false, + "properties" : { + "visitors" : { "type" : "boolean" }, + "rewards" : { "type" : "boolean" }, + "period" : { "type" : "number" } + } + }, + + // Properties that might appear since this node is shared with object config + "compatibilityIdentifiers" : { }, + "blockedVisitable" : { }, + "removable" : { }, + "aiValue" : { }, + "index" : { }, + "base" : { }, + "name" : { }, + "rmg" : { }, + "templates" : { }, + "battleground" : { }, + "sounds" : { } + } +} diff --git a/config/schemas/settings.json b/config/schemas/settings.json index 4e710ecf8..d1e70bc4f 100644 --- a/config/schemas/settings.json +++ b/config/schemas/settings.json @@ -166,7 +166,8 @@ "showfps", "targetfps", "vsync", - "scalingMode" + "upscalingFilter", + "downscalingFilter" ], "properties" : { "resolution" : { @@ -230,7 +231,12 @@ "type" : "boolean", "default" : true }, - "scalingMode" : { + "upscalingFilter" : { + "type" : "string", + "enum" : [ "auto", "none", "xbrz2", "xbrz3", "xbrz4" ], + "default" : "auto" + }, + "downscalingFilter" : { "type" : "string", "enum" : [ "nearest", "linear", "best" ], "default" : "best" @@ -587,7 +593,7 @@ }, "defaultRepositoryURL" : { "type" : "string", - "default" : "https://raw.githubusercontent.com/vcmi/vcmi-mods-repository/develop/vcmi-1.5.json", + "default" : "https://raw.githubusercontent.com/vcmi/vcmi-mods-repository/develop/vcmi-1.6.json", }, "extraRepositoryEnabled" : { "type" : "boolean", diff --git a/config/schemas/townBuilding.json b/config/schemas/townBuilding.json index 7a86acdab..b273e66a9 100644 --- a/config/schemas/townBuilding.json +++ b/config/schemas/townBuilding.json @@ -31,11 +31,12 @@ "type" : "string" }, "description" : { - "description" : "Localizable decsription of this building", + "description" : "Localizable description of this building", "type" : "string" }, "type" : { "type" : "string", + "enum" : [ "mysticPond", "artifactMerchant", "freelancersGuild", "magicUniversity", "castleGate", "creatureTransformer", "portalOfSummoning", "ballistaYard", "library", "escapeTunnel", "treasury", "thievesGuild", "bank" ], "description" : "Subtype for some special buildings" }, "mode" : { @@ -56,6 +57,14 @@ "description" : "Optional, indicates that this building upgrades another base building", "type" : "string" }, + "upgradeReplacesBonuses" : { + "description" : "If set to true, this building will replace all bonuses from base building, leaving only bonuses defined by this building", + "type" : "boolean" + }, + "configuration" : { + "description" : "Optional, configuration of building that can be activated by visiting hero", + "$ref" : "rewardable.json" + }, "cost" : { "type" : "object", "additionalProperties" : false, @@ -84,23 +93,9 @@ "gems" : { "type" : "number"} } }, - "overrides" : { - "type" : "array", - "items" : [ - { - "description" : "The buildings which bonuses should be overridden with bonuses of the current building", - "type" : "string" - } - ] - }, "bonuses" : { "type" : "array", - "description" : "Bonuses, provided by this special building on build using bonus system", - "items" : { "$ref" : "bonus.json" } - }, - "onVisitBonuses" : { - "type" : "array", - "description" : "Bonuses, provided by this special building on hero visit and applied to the visiting hero", + "description" : "Bonuses that are provided by this building in any town where this building has been built. Only affects town itself (including siege), to propagate effect to player or team please use bonus propagators", "items" : { "$ref" : "bonus.json" } } } diff --git a/docs/modders/Entities_Format/Faction_Format.md b/docs/modders/Entities_Format/Faction_Format.md index a7c9935be..e68fb72c4 100644 --- a/docs/modders/Entities_Format/Faction_Format.md +++ b/docs/modders/Entities_Format/Faction_Format.md @@ -341,100 +341,7 @@ Each town requires a set of buildings (Around 30-45 buildings) ``` ## Building node - -```jsonc -{ - // Numeric identifier of this building - "id" : 0, - - // Localizable name of this building - "name" : "", - - // Localizable decsription of this building - "description" : "", - - // Optional, indicates that this building upgrades another base building - "upgrades" : "baseBuilding", - - // List of town buildings that must be built before this one. See below for full format - "requires" : [ "allOf", [ "mageGuild1" ], [ "tavern" ] ], - - // Resources needed to build building - "cost" : { ... }, - - // TODO: Document me: Subtype for some special buildings - "type" : "", - - // TODO: Document me: Height for lookout towers and some grails - "height" : "average" - - // Resources produced each day by this building - "produce" : { ... }, - - //determine how this building can be built. Possible values are: - // normal - default value. Fulfill requirements, use resources, spend one day - // auto - building appears when all requirements are built - // special - building can not be built manually - // grail - building requires grail to be built - "mode" : "auto", - - // Buildings which bonuses should be overridden with bonuses of the current building - "overrides" : [ "anotherBuilding ] - - // Bonuses, provided by this special building on build using bonus system - "bonuses" : BONUS_FORMAT - - // Bonuses, provided by this special building on hero visit and applied to the visiting hero - "onVisitBonuses" : BONUS_FORMAT -} -``` - -Building requirements can be described using logical expressions: - -```jsonc -"requires" : -[ - "allOf", // Normal H3 "build all" mode - [ "mageGuild1" ], - [ - "noneOf", // available only when none of these building are built - [ "dwelling5A" ], - [ "dwelling5AUpgrade" ] - ], - [ - "anyOf", // any non-zero number of these buildings must be built - [ "tavern" ], - [ "blacksmith" ] - ] -] -``` +See [Town Building Format](Town_Building_Format.md) ## Structure node - -```jsonc -{ - // Main animation file for this building - "animation" : "", - - // Horizontal position on town screen - "x" : 0, - - // Vertical position on town screen - "y" : 0, - - // used for blit order. Higher value places structure close to screen and drawn on top of buildings with lower values - "z" : 0, - - // Path to image with golden border around building, displayed when building is selected - "border" : "", - - // Path to image with area that indicate when building is selected - "area" : "", - - //TODO: describe me - "builds": "", - - // If upgrade, this building will replace parent animation but will not alter its behaviour - "hidden" : false -} -``` \ No newline at end of file +See [Town Building Format](Town_Building_Format.md) \ No newline at end of file diff --git a/docs/modders/Entities_Format/Town_Building_Format.md b/docs/modders/Entities_Format/Town_Building_Format.md new file mode 100644 index 000000000..964b52b56 --- /dev/null +++ b/docs/modders/Entities_Format/Town_Building_Format.md @@ -0,0 +1,250 @@ +# Town Building Format + +## Required data + +Each building requires following assets: + +- Town animation file (1 animation file) +- Selection highlight (1 image) +- Selection area (1 image) +- Town hall icon (1 image) + +## Examples +These are just a couple of examples of what can be done in VCMI. See vcmi configuration files to check how buildings from Heroes III are implemented or other mods for more examples +#### + +##### Order of Fire from Inferno: +```jsonc +"special4": { + "requires" : [ "mageGuild1" ], + "name" : "Order of Fire", + "description" : "Increases spellpower of visiting hero", + "cost" : { + "mercury" : 5, + "gold" : 1000 + }, + "configuration" : { + "visitMode" : "hero", + "rewards" : [ + { + // NOTE: this forces vcmi to load string from H3 text file. In order to define own string simply write your own message without '@' symbol + "message" : "@core.genrltxt.582", + "primary" : { "spellpower" : 1 } + } + ] + } +} +``` + +##### Mana Vortex from Dungeon +```jsonc +"special2": { + "requires" : [ "mageGuild1" ], + "name" : "Mana Vortex", + "description" : "Doubles mana points of the first visiting hero each week", + "cost" : { + "gold" : 5000 + }, + "configuration" : { + "resetParameters" : { + "period" : 7, + "visitors" : true + }, + "visitMode" : "once", + "rewards" : [ + { + "limiter" : { + "noneOf" : [ { "manaPercentage" : 200 } ] + }, + "message" : "As you near the mana vortex your body is filled with new energy. You have doubled your normal spell points.", + "manaPercentage" : 200 + } + ] + } +} +``` + +#### Resource Silo with custom production +```jsonc +"resourceSilo": { + "name" : "Wood Resource Silo", + "description" : "Produces 2 wood every day", + "cost" : { + "wood" : 10, + "gold" : 5000 + }, + "produce" : { + "wood": 2 + } +}, +``` + +#### Brotherhood of Sword - bonuses in siege +```jsonc +"special3": { + // replaces +1 Morale bonus from Tavern + "upgradeReplacesBonuses" : true, + // Gives +2 bonus to morale to town (effective only during siege) + "bonuses": [ + { + "type": "MORALE", + "val": 2 + } + ], + "upgrades" : "tavern" +}, +``` + +#### Lighthouse - bonus to all heroes under player control +```jsonc +"special1": { + "bonuses": [ + { + "propagator": "PLAYER_PROPAGATOR", // bonus affects everything under player control + "type": "MOVEMENT", + "subtype": "heroMovementSea", + "val": 500 // +500 movement points + } + ], + "requires" : [ "shipyard" ] +}, +``` + +## Town Building node + +```jsonc +{ + // Numeric identifier of this building + "id" : 0, + + // Localizable name of this building + "name" : "", + + // Localizable decsription of this building + "description" : "", + + // Optional, indicates that this building upgrades another base building + "upgrades" : "baseBuilding", + + // List of town buildings that must be built before this one. See below for full format + "requires" : [ "allOf", [ "mageGuild1" ], [ "tavern" ] ], + + // Resources needed to build building + "cost" : { + "wood" : 20, + "ore" : 20, + "gold" : 10000 + }, + + // Allows to define additional functionality of this building, usually using logic of one of original H3 town building + // Generally only needs to be specified for "special" buildings + // See 'List of unique town buildings' section below for detailed description of this field + "type" : "", + + // If set, building will have Lookout Tower logic - extend sight radius of a town. + // Possible values: + // low - increases town sight radius by 5 tiles + // average - sight radius extended by 15 tiles + // high - sight radius extended by 20 tiles + // skyship - entire map will be revealed + // If not set, building will not affect sight radius of a town + "height" : "average" + + // Resources produced each day by this building + "produce" : { + "sulfur" : 1, + "gold" : 2000 + }, + + //determine how this building can be built. Possible values are: + // normal - default value. Fulfill requirements, use resources, spend one day + // auto - building appears when all requirements are built + // special - building can not be built manually + // grail - building requires grail to be built + "mode" : "auto", + + // Buildings which bonuses should be overridden with bonuses of the current building + "overrides" : [ "anotherBuilding ] + + // Bonuses provided by this special building if this building or any of its upgrades are constructed in town + "bonuses" : [ BONUS_FORMAT ] + + // If set to true, this building will replace all bonuses from base building, leaving only bonuses defined by this building" + "upgradeReplacesBonuses" : false, +} +``` + +Building requirements can be described using logical expressions: + +```jsonc +"requires" : +[ + "allOf", // Normal H3 "build all" mode + [ "mageGuild1" ], + [ + "noneOf", // available only when none of these building are built + [ "dwelling5A" ], + [ "dwelling5AUpgrade" ] + ], + [ + "anyOf", // any non-zero number of these buildings must be built + [ "tavern" ], + [ "blacksmith" ] + ] +] +``` +### List of unique town buildings + +#### Buildings from Heroes III +Following Heroes III buildings can be used as unique buildings for a town. Their functionality should be identical to a corresponding H3 building. H3 buildings that are not present in this list contain no hardcoded functionality. See vcmi json configuration to see how such buildings can be implemented in a mod. +- `mysticPond` +- `artifactMerchant` +- `freelancersGuild` +- `magicUniversity` +- `castleGate` +- `creatureTransformer` +- `portalOfSummoning` +- `ballistaYard` +- `library` +- `escapeTunnel` +- `treasury` + +#### Buildings from other Heroes III mods +Following HotA buildings can be used as unique building for a town. Functionality should match corresponding HotA building: +- `thievesGuild` +- `bank` + +#### Custom buildings +In addition to above, it is possible to use same format as [Rewardable](../Map_Objects/Rewardable.md) map objects for town buildings. In order to do that, configuration of a rewardable object must be placed into `configuration` json node in building config. + +``` + +### Town Structure node + +```jsonc +{ + // Main animation file for this building + "animation" : "", + + // Horizontal position on town screen + "x" : 0, + + // Vertical position on town screen + "y" : 0, + + // used for blit order. Higher value places structure close to screen and drawn on top of buildings with lower values + "z" : 0, + + // Path to image with golden border around building, displayed when building is selected + "border" : "", + + // Path to image with area that indicate when building is selected + "area" : "", + + //TODO: describe me + "builds": "", + + // If upgrade, this building will replace parent animation but will not alter its behaviour + "hidden" : false +} +``` diff --git a/launcher/settingsView/csettingsview_moc.cpp b/launcher/settingsView/csettingsview_moc.cpp index 85f352537..038fb986b 100644 --- a/launcher/settingsView/csettingsview_moc.cpp +++ b/launcher/settingsView/csettingsview_moc.cpp @@ -39,6 +39,15 @@ static constexpr std::array cursorTypesList = }; static constexpr std::array upscalingFilterTypes = +{ + "auto", + "none", + "xbrz2", + "xbrz3", + "xbrz4" +}; + +static constexpr std::array downscalingFilterTypes = { "nearest", "linear", @@ -138,10 +147,14 @@ void CSettingsView::loadSettings() Languages::fillLanguages(ui->comboBoxLanguage, false); fillValidRenderers(); - std::string upscalingFilter = settings["video"]["scalingMode"].String(); + std::string upscalingFilter = settings["video"]["upscalingFilter"].String(); int upscalingFilterIndex = vstd::find_pos(upscalingFilterTypes, upscalingFilter); ui->comboBoxUpscalingFilter->setCurrentIndex(upscalingFilterIndex); + std::string downscalingFilter = settings["video"]["downscalingFilter"].String(); + int downscalingFilterIndex = vstd::find_pos(downscalingFilterTypes, downscalingFilter); + ui->comboBoxDownscalingFilter->setCurrentIndex(downscalingFilterIndex); + ui->sliderMusicVolume->setValue(settings["general"]["music"].Integer()); ui->sliderSoundVolume->setValue(settings["general"]["sound"].Integer()); ui->sliderRelativeCursorSpeed->setValue(settings["general"]["relativePointerSpeedMultiplier"].Integer()); @@ -645,10 +658,16 @@ void CSettingsView::on_buttonIgnoreSslErrors_clicked(bool checked) void CSettingsView::on_comboBoxUpscalingFilter_currentIndexChanged(int index) { - Settings node = settings.write["video"]["scalingMode"]; + Settings node = settings.write["video"]["upscalingFilter"]; node->String() = upscalingFilterTypes[index]; } +void CSettingsView::on_comboBoxDownscalingFilter_currentIndexChanged(int index) +{ + Settings node = settings.write["video"]["downscalingFilter"]; + node->String() = downscalingFilterTypes[index]; +} + void CSettingsView::on_sliderMusicVolume_valueChanged(int value) { Settings node = settings.write["general"]["music"]; diff --git a/launcher/settingsView/csettingsview_moc.h b/launcher/settingsView/csettingsview_moc.h index 406a926d2..f18f0d811 100644 --- a/launcher/settingsView/csettingsview_moc.h +++ b/launcher/settingsView/csettingsview_moc.h @@ -67,6 +67,7 @@ private slots: void on_buttonIgnoreSslErrors_clicked(bool checked); void on_comboBoxUpscalingFilter_currentIndexChanged(int index); + void on_comboBoxDownscalingFilter_currentIndexChanged(int index); void on_sliderMusicVolume_valueChanged(int value); void on_sliderSoundVolume_valueChanged(int value); void on_buttonRelativeCursorMode_toggled(bool value); diff --git a/launcher/settingsView/csettingsview_moc.ui b/launcher/settingsView/csettingsview_moc.ui index cdb69905f..2c6d46df9 100644 --- a/launcher/settingsView/csettingsview_moc.ui +++ b/launcher/settingsView/csettingsview_moc.ui @@ -48,8 +48,8 @@ 0 0 - 730 - 1691 + 729 + 1396 @@ -57,7 +57,6 @@ - 75 true @@ -301,7 +300,6 @@ - 75 true @@ -516,7 +514,6 @@ Fullscreen Exclusive Mode - game will cover entirety of your screen and will use - 75 true @@ -532,7 +529,6 @@ Fullscreen Exclusive Mode - game will cover entirety of your screen and will use - 75 true @@ -606,7 +602,7 @@ Fullscreen Exclusive Mode - game will cover entirety of your screen and will use - + Nearest @@ -619,7 +615,7 @@ Fullscreen Exclusive Mode - game will cover entirety of your screen and will use - Best (Linear) + Automatic (Linear) @@ -747,7 +743,6 @@ Fullscreen Exclusive Mode - game will cover entirety of your screen and will use - 75 true @@ -852,7 +847,6 @@ Fullscreen Exclusive Mode - game will cover entirety of your screen and will use - 75 true @@ -894,9 +888,9 @@ Fullscreen Exclusive Mode - game will cover entirety of your screen and will use - + - Upscaling Filter + Downscaling Filter @@ -942,7 +936,6 @@ Fullscreen Exclusive Mode - game will cover entirety of your screen and will use - 75 true @@ -1020,7 +1013,6 @@ Fullscreen Exclusive Mode - game will cover entirety of your screen and will use - 75 true @@ -1160,6 +1152,42 @@ Fullscreen Exclusive Mode - game will cover entirety of your screen and will use + + + + Upscaling Filter + + + + + + + + Automatic + + + + + None + + + + + xBRZ x2 + + + + + xBRZ x3 + + + + + xBRZ x4 + + + + diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 1eaab7cd4..140e58df8 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -122,7 +122,7 @@ set(lib_MAIN_SRCS mapObjects/CGMarket.cpp mapObjects/CGObjectInstance.cpp mapObjects/CGPandoraBox.cpp - mapObjects/CGTownBuilding.cpp + mapObjects/TownBuildingInstance.cpp mapObjects/CGTownInstance.cpp mapObjects/CObjectHandler.cpp mapObjects/CQuest.cpp @@ -496,7 +496,7 @@ set(lib_MAIN_HEADERS mapObjects/CGMarket.h mapObjects/CGObjectInstance.h mapObjects/CGPandoraBox.h - mapObjects/CGTownBuilding.h + mapObjects/TownBuildingInstance.h mapObjects/CGTownInstance.h mapObjects/CObjectHandler.h mapObjects/CQuest.h @@ -731,7 +731,7 @@ endif() set_target_properties(vcmi PROPERTIES COMPILE_DEFINITIONS "VCMI_DLL=1") target_link_libraries(vcmi PUBLIC - minizip::minizip ZLIB::ZLIB + minizip::minizip ZLIB::ZLIB TBB::tbb ${SYSTEM_LIBS} Boost::boost Boost::thread Boost::filesystem Boost::program_options Boost::locale Boost::date_time ) @@ -796,6 +796,8 @@ if(NOT ENABLE_STATIC_LIBS) endif() if(APPLE_IOS AND NOT USING_CONAN) + install(IMPORTED_RUNTIME_ARTIFACTS TBB::tbb LIBRARY DESTINATION ${LIB_DIR}) # CMake 3.21+ + get_target_property(LINKED_LIBS vcmi LINK_LIBRARIES) foreach(LINKED_LIB IN LISTS LINKED_LIBS) if(NOT TARGET ${LINKED_LIB}) diff --git a/lib/IGameCallback.cpp b/lib/IGameCallback.cpp index 169668007..3a70daa64 100644 --- a/lib/IGameCallback.cpp +++ b/lib/IGameCallback.cpp @@ -27,6 +27,7 @@ #include "mapObjectConstructors/AObjectTypeHandler.h" #include "mapObjectConstructors/CObjectClassesHandler.h" #include "mapObjects/CGMarket.h" +#include "mapObjects/TownBuildingInstance.h" #include "mapObjects/CGTownInstance.h" #include "mapObjects/CObjectHandler.h" #include "mapObjects/CQuest.h" diff --git a/lib/Rect.h b/lib/Rect.h index 11213d2d0..9a378c8ac 100644 --- a/lib/Rect.h +++ b/lib/Rect.h @@ -119,6 +119,13 @@ public: return Rect(x-p.x,y-p.y,w,h); } + template + Rect operator*(const T &mul) const + { + return Rect(x*mul, y*mul, w*mul, h*mul); + } + + Rect& operator=(const Rect &p) { x = p.x; diff --git a/lib/bonuses/IBonusBearer.cpp b/lib/bonuses/IBonusBearer.cpp index a0bfc7087..8f5c6fe31 100644 --- a/lib/bonuses/IBonusBearer.cpp +++ b/lib/bonuses/IBonusBearer.cpp @@ -84,11 +84,9 @@ bool IBonusBearer::hasBonusOfType(BonusType type, BonusSubtypeID subtype) const bool IBonusBearer::hasBonusFrom(BonusSource source, BonusSourceID sourceID) const { - boost::format fmt("source_%did_%s"); - fmt % static_cast(source) % sourceID.toString(); - - return hasBonus(Selector::source(source,sourceID), fmt.str()); + return hasBonus(Selector::source(source,sourceID)); } + std::shared_ptr IBonusBearer::getBonus(const CSelector &selector) const { auto bonuses = getAllBonuses(selector, Selector::all); diff --git a/lib/constants/Enumerations.h b/lib/constants/Enumerations.h index 199e409e6..55fff9988 100644 --- a/lib/constants/Enumerations.h +++ b/lib/constants/Enumerations.h @@ -25,35 +25,20 @@ namespace BuildingSubID { DEFAULT = -50, NONE = -1, - STABLES, - BROTHERHOOD_OF_SWORD, CASTLE_GATE, CREATURE_TRANSFORMER, MYSTIC_POND, FOUNTAIN_OF_FORTUNE, ARTIFACT_MERCHANT, - LOOKOUT_TOWER, LIBRARY, - MANA_VORTEX, PORTAL_OF_SUMMONING, ESCAPE_TUNNEL, FREELANCERS_GUILD, BALLISTA_YARD, - ATTACK_VISITING_BONUS, MAGIC_UNIVERSITY, - SPELL_POWER_GARRISON_BONUS, - ATTACK_GARRISON_BONUS, - DEFENSE_GARRISON_BONUS, - DEFENSE_VISITING_BONUS, - SPELL_POWER_VISITING_BONUS, - KNOWLEDGE_VISITING_BONUS, - EXPERIENCE_VISITING_BONUS, - LIGHTHOUSE, TREASURY, THIEVES_GUILD, - BANK, - CUSTOM_VISITING_BONUS, - CUSTOM_VISITING_REWARD + BANK }; } diff --git a/lib/constants/StringConstants.h b/lib/constants/StringConstants.h index 2fdf9b9d9..4ba4186bb 100644 --- a/lib/constants/StringConstants.h +++ b/lib/constants/StringConstants.h @@ -185,22 +185,9 @@ namespace MappedKeys { "creatureTransformer", BuildingSubID::CREATURE_TRANSFORMER },//only skeleton transformer yet { "portalOfSummoning", BuildingSubID::PORTAL_OF_SUMMONING }, { "ballistaYard", BuildingSubID::BALLISTA_YARD }, - { "stables", BuildingSubID::STABLES }, - { "manaVortex", BuildingSubID::MANA_VORTEX }, - { "lookoutTower", BuildingSubID::LOOKOUT_TOWER }, { "library", BuildingSubID::LIBRARY }, - { "brotherhoodOfSword", BuildingSubID::BROTHERHOOD_OF_SWORD },//morale garrison bonus { "fountainOfFortune", BuildingSubID::FOUNTAIN_OF_FORTUNE },//luck garrison bonus - { "spellPowerGarrisonBonus", BuildingSubID::SPELL_POWER_GARRISON_BONUS },//such as 'stormclouds', but this name is not ok for good towns - { "attackGarrisonBonus", BuildingSubID::ATTACK_GARRISON_BONUS }, - { "defenseGarrisonBonus", BuildingSubID::DEFENSE_GARRISON_BONUS }, { "escapeTunnel", BuildingSubID::ESCAPE_TUNNEL }, - { "attackVisitingBonus", BuildingSubID::ATTACK_VISITING_BONUS }, - { "defenceVisitingBonus", BuildingSubID::DEFENSE_VISITING_BONUS }, - { "spellPowerVisitingBonus", BuildingSubID::SPELL_POWER_VISITING_BONUS }, - { "knowledgeVisitingBonus", BuildingSubID::KNOWLEDGE_VISITING_BONUS }, - { "experienceVisitingBonus", BuildingSubID::EXPERIENCE_VISITING_BONUS }, - { "lighthouse", BuildingSubID::LIGHTHOUSE }, { "treasury", BuildingSubID::TREASURY }, { "thievesGuild", BuildingSubID::THIEVES_GUILD }, { "bank", BuildingSubID::BANK } diff --git a/lib/entities/building/CBuilding.h b/lib/entities/building/CBuilding.h index 991326330..fff475922 100644 --- a/lib/entities/building/CBuilding.h +++ b/lib/entities/building/CBuilding.h @@ -38,9 +38,8 @@ public: BuildingID bid; //structure ID BuildingID upgrade; /// indicates that building "upgrade" can be improved by this, -1 = empty BuildingSubID::EBuildingSubID subId; /// subtype for special buildings, -1 = the building is not special - std::set overrideBids; /// the building which bonuses should be overridden with bonuses of the current building + bool upgradeReplacesBonuses = false; BonusList buildingBonuses; - BonusList onVisitBonuses; Rewardable::Info rewardableObjectInfo; ///configurable rewards for special buildings @@ -89,23 +88,6 @@ public: return bid == BuildingID::MARKETPLACE || subId == BuildingSubID::ARTIFACT_MERCHANT || subId == BuildingSubID::FREELANCERS_GUILD; } - STRONG_INLINE - bool IsWeekBonus() const - { - return subId == BuildingSubID::STABLES || subId == BuildingSubID::MANA_VORTEX; - } - - STRONG_INLINE - bool IsVisitingBonus() const - { - return subId == BuildingSubID::ATTACK_VISITING_BONUS || - subId == BuildingSubID::DEFENSE_VISITING_BONUS || - subId == BuildingSubID::SPELL_POWER_VISITING_BONUS || - subId == BuildingSubID::KNOWLEDGE_VISITING_BONUS || - subId == BuildingSubID::EXPERIENCE_VISITING_BONUS || - subId == BuildingSubID::CUSTOM_VISITING_BONUS; - } - void addNewBonus(const std::shared_ptr & b, BonusList & bonusList) const; friend class CTownHandler; diff --git a/lib/entities/faction/CTown.cpp b/lib/entities/faction/CTown.cpp index d630744d2..30ce48495 100644 --- a/lib/entities/faction/CTown.cpp +++ b/lib/entities/faction/CTown.cpp @@ -78,14 +78,4 @@ BuildingID CTown::getBuildingType(BuildingSubID::EBuildingSubID subID) const return building == nullptr ? BuildingID::NONE : building->bid.num; } -std::string CTown::getGreeting(BuildingSubID::EBuildingSubID subID) const -{ - return CTownHandler::getMappedValue(subID, std::string(), specialMessages, false); -} - -void CTown::setGreeting(BuildingSubID::EBuildingSubID subID, const std::string & message) const -{ - specialMessages.insert(std::pair(subID, message)); -} - VCMI_LIB_NAMESPACE_END diff --git a/lib/entities/faction/CTown.h b/lib/entities/faction/CTown.h index f61b1213a..a9046f7cb 100644 --- a/lib/entities/faction/CTown.h +++ b/lib/entities/faction/CTown.h @@ -49,8 +49,6 @@ public: std::string getBuildingScope() const; std::set getAllBuildings() const; const CBuilding * getSpecialBuilding(BuildingSubID::EBuildingSubID subID) const; - std::string getGreeting(BuildingSubID::EBuildingSubID subID) const; - void setGreeting(BuildingSubID::EBuildingSubID subID, const std::string & message) const; //may affect only mutable field BuildingID getBuildingType(BuildingSubID::EBuildingSubID subID) const; std::string getRandomNameTextID(size_t index) const; @@ -106,10 +104,6 @@ public: std::string towerIconLarge; } clientInfo; - -private: - ///generated bonusing buildings messages for all towns of this type. - mutable std::map specialMessages; //may be changed by CGTownBuilding::getVisitingBonusGreeting() const }; VCMI_LIB_NAMESPACE_END diff --git a/lib/entities/faction/CTownHandler.cpp b/lib/entities/faction/CTownHandler.cpp index 0d54cff5d..9bdf8a9be 100644 --- a/lib/entities/faction/CTownHandler.cpp +++ b/lib/entities/faction/CTownHandler.cpp @@ -30,14 +30,16 @@ #include "../../texts/CGeneralTextHandler.h" #include "../../texts/CLegacyConfigParser.h" #include "../../json/JsonBonus.h" +#include "../../json/JsonUtils.h" VCMI_LIB_NAMESPACE_BEGIN const int NAMES_PER_TOWN=16; // number of town names per faction in H3 files. Json can define any number -CTownHandler::CTownHandler(): - randomTown(new CTown()), - randomFaction(new CFaction()) +CTownHandler::CTownHandler() + : buildingsLibrary(JsonPath::builtin("config/buildingsLibrary")) + , randomTown(new CTown()) + , randomFaction(new CFaction()) { randomFaction->town = randomTown; randomTown->faction = randomFaction; @@ -240,66 +242,7 @@ void CTownHandler::loadBuildingRequirements(CBuilding * building, const JsonNode bidsToLoad.push_back(hlp); } -void CTownHandler::addBonusesForVanilaBuilding(CBuilding * building) const -{ - std::shared_ptr b; - static const TPropagatorPtr playerPropagator = std::make_shared(CBonusSystemNode::ENodeTypes::PLAYER); - - if(building->bid == BuildingID::TAVERN) - { - b = createBonus(building, BonusType::MORALE, +1); - } - - switch(building->subId) - { - case BuildingSubID::BROTHERHOOD_OF_SWORD: - b = createBonus(building, BonusType::MORALE, +2); - building->overrideBids.insert(BuildingID::TAVERN); - break; - case BuildingSubID::FOUNTAIN_OF_FORTUNE: - b = createBonus(building, BonusType::LUCK, +2); - break; - case BuildingSubID::SPELL_POWER_GARRISON_BONUS: - b = createBonus(building, BonusType::PRIMARY_SKILL, +2, BonusSubtypeID(PrimarySkill::SPELL_POWER)); - break; - case BuildingSubID::ATTACK_GARRISON_BONUS: - b = createBonus(building, BonusType::PRIMARY_SKILL, +2, BonusSubtypeID(PrimarySkill::ATTACK)); - break; - case BuildingSubID::DEFENSE_GARRISON_BONUS: - b = createBonus(building, BonusType::PRIMARY_SKILL, +2, BonusSubtypeID(PrimarySkill::DEFENSE)); - break; - case BuildingSubID::LIGHTHOUSE: - b = createBonus(building, BonusType::MOVEMENT, +500, BonusCustomSubtype::heroMovementSea, playerPropagator); - break; - } - - if(b) - building->addNewBonus(b, building->buildingBonuses); -} - -std::shared_ptr CTownHandler::createBonus(CBuilding * build, BonusType type, int val) const -{ - return createBonus(build, type, val, BonusSubtypeID(), emptyPropagator()); -} - -std::shared_ptr CTownHandler::createBonus(CBuilding * build, BonusType type, int val, BonusSubtypeID subtype) const -{ - return createBonus(build, type, val, subtype, emptyPropagator()); -} - -std::shared_ptr CTownHandler::createBonus(CBuilding * build, BonusType type, int val, BonusSubtypeID subtype, const TPropagatorPtr & prop) const -{ - auto b = std::make_shared(BonusDuration::PERMANENT, type, BonusSource::TOWN_STRUCTURE, val, build->getUniqueTypeID(), subtype); - - b->description.appendTextID(build->getNameTextID()); - - if(prop) - b->addPropagator(prop); - - return b; -} - -void CTownHandler::loadSpecialBuildingBonuses(const JsonNode & source, BonusList & bonusList, CBuilding * building) +void CTownHandler::loadBuildingBonuses(const JsonNode & source, BonusList & bonusList, CBuilding * building) const { for(const auto & b : source.Vector()) { @@ -311,6 +254,8 @@ void CTownHandler::loadSpecialBuildingBonuses(const JsonNode & source, BonusList bonus->description.appendTextID(building->getNameTextID()); //JsonUtils::parseBuildingBonus produces UNKNOWN type propagator instead of empty. + assert(bonus->propagator == nullptr || bonus->propagator->getPropagatorType() != CBonusSystemNode::ENodeTypes::UNKNOWN); + if(bonus->propagator != nullptr && bonus->propagator->getPropagatorType() == CBonusSystemNode::ENodeTypes::UNKNOWN) bonus->addPropagator(emptyPropagator()); @@ -324,7 +269,7 @@ void CTownHandler::loadBuilding(CTown * town, const std::string & stringID, cons assert(!source.getModScope().empty()); auto * ret = new CBuilding(); - ret->bid = getMappedValue(stringID, BuildingID::NONE, MappedKeys::BUILDING_NAMES_TO_TYPES, false); + ret->bid = vstd::find_or(MappedKeys::BUILDING_NAMES_TO_TYPES, stringID, BuildingID::NONE); ret->subId = BuildingSubID::NONE; if(ret->bid == BuildingID::NONE && !source["id"].isNull()) @@ -339,9 +284,9 @@ void CTownHandler::loadBuilding(CTown * town, const std::string & stringID, cons ret->mode = ret->bid == BuildingID::GRAIL ? CBuilding::BUILD_GRAIL - : getMappedValue(source["mode"], CBuilding::BUILD_NORMAL, CBuilding::MODES); + : vstd::find_or(CBuilding::MODES, source["mode"].String(), CBuilding::BUILD_NORMAL); - ret->height = getMappedValue(source["height"], CBuilding::HEIGHT_NO_TOWER, CBuilding::TOWER_TYPES); + ret->height = vstd::find_or(CBuilding::TOWER_TYPES, source["height"].String(), CBuilding::HEIGHT_NO_TOWER); ret->identifier = stringID; ret->modScope = source.getModScope(); @@ -350,70 +295,35 @@ void CTownHandler::loadBuilding(CTown * town, const std::string & stringID, cons VLC->generaltexth->registerString(source.getModScope(), ret->getNameTextID(), source["name"].String()); VLC->generaltexth->registerString(source.getModScope(), ret->getDescriptionTextID(), source["description"].String()); + ret->subId = vstd::find_or(MappedKeys::SPECIAL_BUILDINGS, source["type"].String(), BuildingSubID::NONE); ret->resources = TResources(source["cost"]); ret->produce = TResources(source["produce"]); - if(ret->bid == BuildingID::TAVERN) - addBonusesForVanilaBuilding(ret); - else if(ret->bid.IsSpecialOrGrail()) + loadBuildingBonuses(source["bonuses"], ret->buildingBonuses, ret); + + if(!source["configuration"].isNull()) + ret->rewardableObjectInfo.init(source["configuration"], ret->getBaseTextID()); + + //MODS COMPATIBILITY FOR pre-1.6 + if(ret->produce.empty() && ret->bid == BuildingID::RESOURCE_SILO) { - loadSpecialBuildingBonuses(source["bonuses"], ret->buildingBonuses, ret); - - if(ret->buildingBonuses.empty()) + logGlobal->warn("Resource silo in town '%s' does not produces any resources!", ret->town->faction->getJsonKey()); + switch (ret->town->primaryRes.toEnum()) { - ret->subId = getMappedValue(source["type"], BuildingSubID::NONE, MappedKeys::SPECIAL_BUILDINGS); - addBonusesForVanilaBuilding(ret); - } - - loadSpecialBuildingBonuses(source["onVisitBonuses"], ret->onVisitBonuses, ret); - - if(!ret->onVisitBonuses.empty()) - { - if(ret->subId == BuildingSubID::NONE) - ret->subId = BuildingSubID::CUSTOM_VISITING_BONUS; - - for(auto & bonus : ret->onVisitBonuses) - bonus->sid = BonusSourceID(ret->getUniqueTypeID()); - } - - if(source["type"].String() == "configurable" && ret->subId == BuildingSubID::NONE) - { - ret->subId = BuildingSubID::CUSTOM_VISITING_REWARD; - ret->rewardableObjectInfo.init(source, ret->getBaseTextID()); - } - } - //MODS COMPATIBILITY FOR 0.96 - if(!ret->produce.nonZero()) - { - switch (ret->bid.toEnum()) { - break; case BuildingID::VILLAGE_HALL: ret->produce[EGameResID::GOLD] = 500; - break; case BuildingID::TOWN_HALL : ret->produce[EGameResID::GOLD] = 1000; - break; case BuildingID::CITY_HALL : ret->produce[EGameResID::GOLD] = 2000; - break; case BuildingID::CAPITOL : ret->produce[EGameResID::GOLD] = 4000; - break; case BuildingID::GRAIL : ret->produce[EGameResID::GOLD] = 5000; - break; case BuildingID::RESOURCE_SILO : - { - switch (ret->town->primaryRes.toEnum()) - { - case EGameResID::GOLD: - ret->produce[ret->town->primaryRes] = 500; - break; - case EGameResID::WOOD_AND_ORE: - ret->produce[EGameResID::WOOD] = 1; - ret->produce[EGameResID::ORE] = 1; - break; - default: - ret->produce[ret->town->primaryRes] = 1; - break; - } - } + case EGameResID::GOLD: + ret->produce[ret->town->primaryRes] = 500; + break; + case EGameResID::WOOD_AND_ORE: + ret->produce[EGameResID::WOOD] = 1; + ret->produce[EGameResID::ORE] = 1; + break; + default: + ret->produce[ret->town->primaryRes] = 1; + break; } } loadBuildingRequirements(ret, source["requires"], requirementsToLoad); - if(ret->bid.IsSpecialOrGrail()) - loadBuildingRequirements(ret, source["overrides"], overriddenBidsToLoad); - if (!source["upgrades"].isNull()) { // building id and upgrades can't be the same @@ -898,10 +808,41 @@ void CTownHandler::loadCustom() loadRandomFaction(); } +void CTownHandler::beforeValidate(JsonNode & object) +{ + if (object.Struct().count("town") == 0) + return; + + const auto & inheritBuilding = [this](const std::string & name, JsonNode & target) + { + if (buildingsLibrary.Struct().count(name) == 0) + return; + + JsonNode baseCopy(buildingsLibrary[name]); + baseCopy.setModScope(target.getModScope()); + JsonUtils::inherit(target, baseCopy); + }; + + for (auto & building : object["town"]["buildings"].Struct()) + { + inheritBuilding(building.first, building.second); + if (building.second.Struct().count("type")) + inheritBuilding(building.second["type"].String(), building.second); + + // MODS COMPATIBILITY FOR pre-1.6 + // convert old buildigns with onVisitBonuses into configurable building + if (building.second.Struct().count("onVisitBonuses")) + { + building.second["configuration"]["visitMode"] = JsonNode("bonus"); + building.second["configuration"]["visitMode"]["rewards"][0]["message"] = building.second["description"]; + building.second["configuration"]["visitMode"]["rewards"][0]["bonuses"] = building.second["onVisitBonuses"]; + } + } +} + void CTownHandler::afterLoadFinalization() { initializeRequirements(); - initializeOverridden(); initializeWarMachines(); } @@ -932,22 +873,6 @@ void CTownHandler::initializeRequirements() requirementsToLoad.clear(); } -void CTownHandler::initializeOverridden() -{ - for(auto & bidHelper : overriddenBidsToLoad) - { - auto jsonNode = bidHelper.json; - auto scope = bidHelper.town->getBuildingScope(); - - for(const auto & b : jsonNode.Vector()) - { - auto bid = BuildingID(VLC->identifiers()->getIdentifier(scope, b).value()); - bidHelper.building->overrideBids.insert(bid); - } - } - overriddenBidsToLoad.clear(); -} - void CTownHandler::initializeWarMachines() { // must be done separately after all objects are loaded diff --git a/lib/entities/faction/CTownHandler.h b/lib/entities/faction/CTownHandler.h index 7a3303616..a503d07dc 100644 --- a/lib/entities/faction/CTownHandler.h +++ b/lib/entities/faction/CTownHandler.h @@ -25,6 +25,8 @@ class CTown; class DLL_LINKAGE CTownHandler : public CHandlerBase { + JsonNode buildingsLibrary; + struct BuildingRequirementsHelper { JsonNode json; @@ -39,7 +41,6 @@ class DLL_LINKAGE CTownHandler : public CHandlerBase createBonus(CBuilding * build, BonusType type, int val) const; - std::shared_ptr createBonus(CBuilding * build, BonusType type, int val, BonusSubtypeID subtype) const; - std::shared_ptr createBonus(CBuilding * build, BonusType type, int val, BonusSubtypeID subtype, const TPropagatorPtr & prop) const; - /// loads CStructure's into town void loadStructure(CTown & town, const std::string & stringID, const JsonNode & source) const; void loadStructures(CTown & town, const JsonNode & source) const; @@ -68,11 +65,6 @@ class DLL_LINKAGE CTownHandler : public CHandlerBase - static R getMappedValue(const K key, const R defval, const std::map & map, bool required = true); - template - static R getMappedValue(const JsonNode & node, const R defval, const std::map & map, bool required = true); - CTown * randomTown; CFaction * randomFaction; @@ -83,40 +75,19 @@ public: void loadObject(std::string scope, std::string name, const JsonNode & data) override; void loadObject(std::string scope, std::string name, const JsonNode & data, size_t index) override; - void addBonusesForVanilaBuilding(CBuilding * building) const; void loadCustom() override; void afterLoadFinalization() override; + void beforeValidate(JsonNode & object) override; std::set getDefaultAllowed() const; std::set getAllowedFactions(bool withTown = true) const; - static void loadSpecialBuildingBonuses(const JsonNode & source, BonusList & bonusList, CBuilding * building); - protected: + + void loadBuildingBonuses(const JsonNode & source, BonusList & bonusList, CBuilding * building) const; const std::vector & getTypeNames() const override; std::shared_ptr loadFromJson(const std::string & scope, const JsonNode & data, const std::string & identifier, size_t index) override; }; -template -R CTownHandler::getMappedValue(const K key, const R defval, const std::map & map, bool required) -{ - auto it = map.find(key); - - if(it != map.end()) - return it->second; - - if(required) - logMod->warn("Warning: Property: '%s' is unknown. Correct the typo or update VCMI.", key); - return defval; -} - -template -R CTownHandler::getMappedValue(const JsonNode & node, const R defval, const std::map & map, bool required) -{ - if(!node.isNull() && node.getType() == JsonNode::JsonType::DATA_STRING) - return getMappedValue(node.String(), defval, map, required); - return defval; -} - VCMI_LIB_NAMESPACE_END diff --git a/lib/mapObjectConstructors/CRewardableConstructor.cpp b/lib/mapObjectConstructors/CRewardableConstructor.cpp index abe1edb07..90da5925b 100644 --- a/lib/mapObjectConstructors/CRewardableConstructor.cpp +++ b/lib/mapObjectConstructors/CRewardableConstructor.cpp @@ -10,6 +10,7 @@ #include "StdInc.h" #include "CRewardableConstructor.h" +#include "../json/JsonUtils.h" #include "../mapObjects/CRewardableObject.h" #include "../texts/CGeneralTextHandler.h" #include "../IGameCallback.h" @@ -23,6 +24,8 @@ void CRewardableConstructor::initTypeData(const JsonNode & config) if (!config["name"].isNull()) VLC->generaltexth->registerString( config.getModScope(), getNameTextID(), config["name"].String()); + + JsonUtils::validate(config, "vcmi:rewardable", getJsonKey()); } diff --git a/lib/mapObjects/CGMarket.cpp b/lib/mapObjects/CGMarket.cpp index d30b210f2..8b6cf877e 100644 --- a/lib/mapObjects/CGMarket.cpp +++ b/lib/mapObjects/CGMarket.cpp @@ -85,7 +85,7 @@ void CGBlackMarket::newTurn(vstd::RNG & rand) const int resetPeriod = VLC->settings()->getInteger(EGameSettings::MARKETS_BLACK_MARKET_RESTOCK_PERIOD); bool isFirstDay = cb->getDate(Date::DAY) == 1; - bool regularResetTriggered = resetPeriod != 0 && ((cb->getDate(Date::DAY)-1) % resetPeriod) != 0; + bool regularResetTriggered = resetPeriod != 0 && ((cb->getDate(Date::DAY)-1) % resetPeriod) == 0; if (!isFirstDay && !regularResetTriggered) return; diff --git a/lib/mapObjects/CGTownBuilding.cpp b/lib/mapObjects/CGTownBuilding.cpp deleted file mode 100644 index 3d84843ea..000000000 --- a/lib/mapObjects/CGTownBuilding.cpp +++ /dev/null @@ -1,536 +0,0 @@ -/* - * CGTownBuilding.cpp, part of VCMI engine - * - * Authors: listed in file AUTHORS in main folder - * - * License: GNU General Public License v2.0 or later - * Full text of license available in license.txt file, in main folder - * - */ - -#include "StdInc.h" -#include "CGTownBuilding.h" -#include "CGTownInstance.h" -#include "../texts/CGeneralTextHandler.h" -#include "../IGameCallback.h" -#include "../gameState/CGameState.h" -#include "../mapObjects/CGHeroInstance.h" -#include "../networkPacks/PacksForClient.h" -#include "../entities/building/CBuilding.h" - - -#include - -VCMI_LIB_NAMESPACE_BEGIN - -CGTownBuilding::CGTownBuilding(IGameCallback * cb) - : IObjectInterface(cb) - , town(nullptr) -{} - -CGTownBuilding::CGTownBuilding(CGTownInstance * town) - : IObjectInterface(town->cb) - , town(town) -{} - -PlayerColor CGTownBuilding::getOwner() const -{ - return town->getOwner(); -} - -MapObjectID CGTownBuilding::getObjGroupIndex() const -{ - return -1; -} - -MapObjectSubID CGTownBuilding::getObjTypeIndex() const -{ - return 0; -} - -int3 CGTownBuilding::visitablePos() const -{ - return town->visitablePos(); -} - -int3 CGTownBuilding::getPosition() const -{ - return town->getPosition(); -} - -std::string CGTownBuilding::getVisitingBonusGreeting() const -{ - auto bonusGreeting = town->getTown()->getGreeting(bType); - - if(!bonusGreeting.empty()) - return bonusGreeting; - - switch(bType) - { - case BuildingSubID::MANA_VORTEX: - bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingManaVortex")); - break; - case BuildingSubID::KNOWLEDGE_VISITING_BONUS: - bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingKnowledge")); - break; - case BuildingSubID::SPELL_POWER_VISITING_BONUS: - bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingSpellPower")); - break; - case BuildingSubID::ATTACK_VISITING_BONUS: - bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingAttack")); - break; - case BuildingSubID::EXPERIENCE_VISITING_BONUS: - bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingExperience")); - break; - case BuildingSubID::DEFENSE_VISITING_BONUS: - bonusGreeting = std::string(VLC->generaltexth->translate("vcmi.townHall.greetingDefence")); - break; - } - auto buildingName = town->getTown()->getSpecialBuilding(bType)->getNameTranslated(); - - if(bonusGreeting.empty()) - { - bonusGreeting = "Error: Bonus greeting for '%s' is not localized."; - logGlobal->error("'%s' building of '%s' faction has not localized bonus greeting.", buildingName, town->getTown()->faction->getNameTranslated()); - } - boost::algorithm::replace_first(bonusGreeting, "%s", buildingName); - town->getTown()->setGreeting(bType, bonusGreeting); - return bonusGreeting; -} - -std::string CGTownBuilding::getCustomBonusGreeting(const Bonus & bonus) const -{ - if(bonus.type == BonusType::TOWN_MAGIC_WELL) - { - MetaString wellGreeting = MetaString::createFromTextID("vcmi.townHall.greetingInTownMagicWell"); - - wellGreeting.replaceTextID(town->getTown()->getSpecialBuilding(bType)->getNameTextID()); - return wellGreeting.toString(); - } - - MetaString greeting = MetaString::createFromTextID("vcmi.townHall.greetingCustomBonus"); - - std::string paramTextID; - std::string until; - - if(bonus.type == BonusType::MORALE) - paramTextID = "core.genrltxt.384"; // Morale - - if(bonus.type == BonusType::LUCK) - paramTextID = "core.genrltxt.385"; // Luck - - greeting.replaceTextID(town->getTown()->getSpecialBuilding(bType)->getNameTextID()); - greeting.replaceNumber(bonus.val); - greeting.replaceTextID(paramTextID); - - if (bonus.duration == BonusDuration::ONE_BATTLE) - greeting.replaceTextID("vcmi.townHall.greetingCustomUntil"); - else - greeting.replaceRawString("."); - - return greeting.toString(); -} - -COPWBonus::COPWBonus(IGameCallback *cb) - : CGTownBuilding(cb) -{} - -COPWBonus::COPWBonus(const BuildingID & bid, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown) - : CGTownBuilding(cgTown) -{ - bID = bid; - bType = subId; - indexOnTV = static_cast(town->bonusingBuildings.size()); -} - -void COPWBonus::setProperty(ObjProperty what, ObjPropertyID identifier) -{ - switch (what) - { - case ObjProperty::VISITORS: - visitors.insert(identifier.as()); - break; - case ObjProperty::STRUCTURE_CLEAR_VISITORS: - visitors.clear(); - break; - } -} - -void COPWBonus::onHeroVisit (const CGHeroInstance * h) const -{ - ObjectInstanceID heroID = h->id; - if(town->hasBuilt(bID)) - { - InfoWindow iw; - iw.player = h->tempOwner; - - switch (this->bType) - { - case BuildingSubID::STABLES: - if(!h->hasBonusFrom(BonusSource::OBJECT_TYPE, BonusSourceID(Obj(Obj::STABLES)))) //does not stack with advMap Stables - { - GiveBonus gb; - gb.bonus = Bonus(BonusDuration::ONE_WEEK, BonusType::MOVEMENT, BonusSource::OBJECT_TYPE, 600, BonusSourceID(Obj(Obj::STABLES)), BonusCustomSubtype::heroMovementLand); - gb.id = heroID; - cb->giveHeroBonus(&gb); - - cb->setMovePoints(heroID, 600, false); - - iw.text.appendRawString(VLC->generaltexth->allTexts[580]); - cb->showInfoDialog(&iw); - } - break; - - case BuildingSubID::MANA_VORTEX: - if(visitors.empty()) - { - if(h->mana < h->manaLimit() * 2) - { - cb->setManaPoints (heroID, 2 * h->manaLimit()); - //TODO: investigate line below - //cb->setObjProperty (town->id, ObjProperty::VISITED, true); - iw.text.appendRawString(getVisitingBonusGreeting()); - cb->showInfoDialog(&iw); - town->addHeroToStructureVisitors(h, indexOnTV); - } - } - break; - } - } -} - -CTownBonus::CTownBonus(IGameCallback *cb) - : CGTownBuilding(cb) -{} - -CTownBonus::CTownBonus(const BuildingID & index, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown) - : CGTownBuilding(cgTown) -{ - bID = index; - bType = subId; - indexOnTV = static_cast(town->bonusingBuildings.size()); -} - -void CTownBonus::setProperty(ObjProperty what, ObjPropertyID identifier) -{ - if(what == ObjProperty::VISITORS) - visitors.insert(identifier.as()); -} - -void CTownBonus::onHeroVisit (const CGHeroInstance * h) const -{ - ObjectInstanceID heroID = h->id; - if(town->hasBuilt(bID) && visitors.find(heroID) == visitors.end()) - { - si64 val = 0; - InfoWindow iw; - PrimarySkill what = PrimarySkill::NONE; - - switch(bType) - { - case BuildingSubID::KNOWLEDGE_VISITING_BONUS: //wall of knowledge - what = PrimarySkill::KNOWLEDGE; - val = 1; - iw.components.emplace_back(ComponentType::PRIM_SKILL, PrimarySkill::KNOWLEDGE, 1); - break; - - case BuildingSubID::SPELL_POWER_VISITING_BONUS: //order of fire - what = PrimarySkill::SPELL_POWER; - val = 1; - iw.components.emplace_back(ComponentType::PRIM_SKILL, PrimarySkill::SPELL_POWER, 1); - break; - - case BuildingSubID::ATTACK_VISITING_BONUS: //hall of Valhalla - what = PrimarySkill::ATTACK; - val = 1; - iw.components.emplace_back(ComponentType::PRIM_SKILL, PrimarySkill::ATTACK, 1); - break; - - case BuildingSubID::EXPERIENCE_VISITING_BONUS: //academy of battle scholars - what = PrimarySkill::EXPERIENCE; - val = static_cast(h->calculateXp(1000)); - iw.components.emplace_back(ComponentType::EXPERIENCE, val); - break; - - case BuildingSubID::DEFENSE_VISITING_BONUS: //cage of warlords - what = PrimarySkill::DEFENSE; - val = 1; - iw.components.emplace_back(ComponentType::PRIM_SKILL, PrimarySkill::DEFENSE, 1); - break; - - case BuildingSubID::CUSTOM_VISITING_BONUS: - const auto building = town->getTown()->buildings.at(bID); - if(!h->hasBonusFrom(BonusSource::TOWN_STRUCTURE, BonusSourceID(building->getUniqueTypeID()))) - { - const auto & bonuses = building->onVisitBonuses; - applyBonuses(const_cast(h), bonuses); - } - break; - } - - if(what != PrimarySkill::NONE) - { - iw.player = cb->getOwner(heroID); - iw.text.appendRawString(getVisitingBonusGreeting()); - cb->showInfoDialog(&iw); - if (what == PrimarySkill::EXPERIENCE) - cb->giveExperience(cb->getHero(heroID), val); - else - cb->changePrimSkill(cb->getHero(heroID), what, val); - - town->addHeroToStructureVisitors(h, indexOnTV); - } - } -} - -void CTownBonus::applyBonuses(CGHeroInstance * h, const BonusList & bonuses) const -{ - auto addToVisitors = false; - - for(const auto & bonus : bonuses) - { - GiveBonus gb; - InfoWindow iw; - - if(bonus->type == BonusType::TOWN_MAGIC_WELL) - { - if(h->mana >= h->manaLimit()) - return; - cb->setManaPoints(h->id, h->manaLimit()); - bonus->duration = BonusDuration::ONE_DAY; - } - gb.bonus = * bonus; - gb.id = h->id; - cb->giveHeroBonus(&gb); - - if(bonus->duration == BonusDuration::PERMANENT) - addToVisitors = true; - - iw.player = cb->getOwner(h->id); - iw.text.appendRawString(getCustomBonusGreeting(gb.bonus)); - cb->showInfoDialog(&iw); - } - if(addToVisitors) - town->addHeroToStructureVisitors(h, indexOnTV); -} - -CTownRewardableBuilding::CTownRewardableBuilding(IGameCallback *cb) - : CGTownBuilding(cb) -{} - -CTownRewardableBuilding::CTownRewardableBuilding(const BuildingID & index, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown, vstd::RNG & rand) - : CGTownBuilding(cgTown) -{ - bID = index; - bType = subId; - indexOnTV = static_cast(town->bonusingBuildings.size()); - initObj(rand); -} - -void CTownRewardableBuilding::initObj(vstd::RNG & rand) -{ - assert(town && town->town); - configuration = generateConfiguration(rand); -} - -Rewardable::Configuration CTownRewardableBuilding::generateConfiguration(vstd::RNG & rand) const -{ - Rewardable::Configuration result; - auto building = town->town->buildings.at(bID); - - building->rewardableObjectInfo.configureObject(result, rand, cb); - for(auto & rewardInfo : result.info) - { - for (auto & bonus : rewardInfo.reward.bonuses) - { - bonus.source = BonusSource::TOWN_STRUCTURE; - bonus.sid = BonusSourceID(building->getUniqueTypeID()); - } - } - return result; -} - -void CTownRewardableBuilding::newTurn(vstd::RNG & rand) const -{ - if (configuration.resetParameters.period != 0 && cb->getDate(Date::DAY) > 1 && ((cb->getDate(Date::DAY)-1) % configuration.resetParameters.period) == 0) - { - auto newConfiguration = generateConfiguration(rand); - cb->setRewardableObjectConfiguration(town->id, bID, newConfiguration); - - if(configuration.resetParameters.visitors) - { - cb->setObjPropertyValue(town->id, ObjProperty::STRUCTURE_CLEAR_VISITORS, indexOnTV); - } - } -} - -void CTownRewardableBuilding::setProperty(ObjProperty what, ObjPropertyID identifier) -{ - switch (what) - { - case ObjProperty::VISITORS: - visitors.insert(identifier.as()); - break; - case ObjProperty::STRUCTURE_CLEAR_VISITORS: - visitors.clear(); - break; - case ObjProperty::REWARD_SELECT: - selectedReward = identifier.getNum(); - break; - } -} - -void CTownRewardableBuilding::heroLevelUpDone(const CGHeroInstance *hero) const -{ - grantRewardAfterLevelup(cb, configuration.info.at(selectedReward), town, hero); -} - -void CTownRewardableBuilding::blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const -{ - if(answer == 0) - return; // player refused - - if(visitors.find(hero->id) != visitors.end()) - return; // query not for this building - - if(answer > 0 && answer-1 < configuration.info.size()) - { - auto list = getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT); - grantReward(list[answer - 1], hero); - } - else - { - throw std::runtime_error("Unhandled choice"); - } -} - -void CTownRewardableBuilding::grantReward(ui32 rewardID, const CGHeroInstance * hero) const -{ - town->addHeroToStructureVisitors(hero, indexOnTV); - - grantRewardBeforeLevelup(cb, configuration.info.at(rewardID), hero); - - // hero is not blocked by levelup dialog - grant remainder immediately - if(!cb->isVisitCoveredByAnotherQuery(town, hero)) - { - grantRewardAfterLevelup(cb, configuration.info.at(rewardID), town, hero); - } -} - -bool CTownRewardableBuilding::wasVisitedBefore(const CGHeroInstance * contextHero) const -{ - switch (configuration.visitMode) - { - case Rewardable::VISIT_UNLIMITED: - return false; - case Rewardable::VISIT_ONCE: - return !visitors.empty(); - case Rewardable::VISIT_PLAYER: - return false; //not supported - case Rewardable::VISIT_BONUS: - { - const auto building = town->getTown()->buildings.at(bID); - return contextHero->hasBonusFrom(BonusSource::TOWN_STRUCTURE, BonusSourceID(building->getUniqueTypeID())); - } - case Rewardable::VISIT_HERO: - return visitors.find(contextHero->id) != visitors.end(); - case Rewardable::VISIT_LIMITER: - return configuration.visitLimiter.heroAllowed(contextHero); - default: - return false; - } -} - -void CTownRewardableBuilding::onHeroVisit(const CGHeroInstance *h) const -{ - auto grantRewardWithMessage = [&](int index) -> void - { - auto vi = configuration.info.at(index); - logGlobal->debug("Granting reward %d. Message says: %s", index, vi.message.toString()); - - town->addHeroToStructureVisitors(h, indexOnTV); //adding to visitors - - InfoWindow iw; - iw.player = h->tempOwner; - iw.text = vi.message; - vi.reward.loadComponents(iw.components, h); - iw.type = EInfoWindowMode::MODAL; - if(!iw.components.empty() || !iw.text.toString().empty()) - cb->showInfoDialog(&iw); - - grantReward(index, h); - }; - auto selectRewardsMessage = [&](const std::vector & rewards, const MetaString & dialog) -> void - { - BlockingDialog sd(configuration.canRefuse, rewards.size() > 1); - sd.player = h->tempOwner; - sd.text = dialog; - - if (rewards.size() > 1) - for (auto index : rewards) - sd.components.push_back(configuration.info.at(index).reward.getDisplayedComponent(h)); - - if (rewards.size() == 1) - configuration.info.at(rewards.front()).reward.loadComponents(sd.components, h); - - cb->showBlockingDialog(&sd); - }; - - if(!town->hasBuilt(bID) || cb->isVisitCoveredByAnotherQuery(town, h)) - return; - - if(!wasVisitedBefore(h)) - { - auto rewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT); - - logGlobal->debug("Visiting object with %d possible rewards", rewards.size()); - switch (rewards.size()) - { - case 0: // no available rewards, e.g. visiting School of War without gold - { - auto emptyRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_NOT_AVAILABLE); - if (!emptyRewards.empty()) - grantRewardWithMessage(emptyRewards[0]); - else - logMod->warn("No applicable message for visiting empty object!"); - break; - } - case 1: // one reward. Just give it with message - { - if (configuration.canRefuse) - selectRewardsMessage(rewards, configuration.info.at(rewards.front()).message); - else - grantRewardWithMessage(rewards.front()); - break; - } - default: // multiple rewards. Act according to select mode - { - switch (configuration.selectMode) { - case Rewardable::SELECT_PLAYER: // player must select - selectRewardsMessage(rewards, configuration.onSelect); - break; - case Rewardable::SELECT_FIRST: // give first available - grantRewardWithMessage(rewards.front()); - break; - case Rewardable::SELECT_RANDOM: // give random - grantRewardWithMessage(*RandomGeneratorUtil::nextItem(rewards, cb->gameState()->getRandomGenerator())); - break; - } - break; - } - } - } - else - { - logGlobal->debug("Revisiting already visited object"); - - auto visitedRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_ALREADY_VISITED); - if (!visitedRewards.empty()) - grantRewardWithMessage(visitedRewards[0]); - else - logMod->debug("No applicable message for visiting already visited object!"); - } -} - - -VCMI_LIB_NAMESPACE_END diff --git a/lib/mapObjects/CGTownBuilding.h b/lib/mapObjects/CGTownBuilding.h deleted file mode 100644 index b8617d784..000000000 --- a/lib/mapObjects/CGTownBuilding.h +++ /dev/null @@ -1,149 +0,0 @@ -/* - * CGTownBuilding.h, part of VCMI engine - * - * Authors: listed in file AUTHORS in main folder - * - * License: GNU General Public License v2.0 or later - * Full text of license available in license.txt file, in main folder - * - */ - -#pragma once - -#include "IObjectInterface.h" -#include "../rewardable/Interface.h" - -VCMI_LIB_NAMESPACE_BEGIN - -class CGTownInstance; -class CBuilding; - -class DLL_LINKAGE CGTownBuilding : public IObjectInterface -{ -///basic class for town structures handled as map objects -public: - CGTownBuilding(CGTownInstance * town); - CGTownBuilding(IGameCallback *cb); - - si32 indexOnTV = 0; //identifies its index on towns vector - - CGTownInstance * town; - - STRONG_INLINE - BuildingSubID::EBuildingSubID getBuildingSubtype() const - { - return bType; - } - - STRONG_INLINE - const BuildingID & getBuildingType() const - { - return bID; - } - - STRONG_INLINE - void setBuildingSubtype(BuildingSubID::EBuildingSubID subId) - { - bType = subId; - } - - PlayerColor getOwner() const override; - MapObjectID getObjGroupIndex() const override; - MapObjectSubID getObjTypeIndex() const override; - - int3 visitablePos() const override; - int3 getPosition() const override; - - template void serialize(Handler &h) - { - h & bID; - h & indexOnTV; - h & bType; - } - -protected: - BuildingID bID; //from buildig list - BuildingSubID::EBuildingSubID bType = BuildingSubID::NONE; - - std::string getVisitingBonusGreeting() const; - std::string getCustomBonusGreeting(const Bonus & bonus) const; -}; - -class DLL_LINKAGE COPWBonus : public CGTownBuilding -{///used for OPW bonusing structures -public: - std::set visitors; - void setProperty(ObjProperty what, ObjPropertyID identifier) override; - void onHeroVisit (const CGHeroInstance * h) const override; - - COPWBonus(const BuildingID & index, BuildingSubID::EBuildingSubID subId, CGTownInstance * TOWN); - COPWBonus(IGameCallback *cb); - - template void serialize(Handler &h) - { - h & static_cast(*this); - h & visitors; - } -}; - -class DLL_LINKAGE CTownBonus : public CGTownBuilding -{ -///used for one-time bonusing structures -///feel free to merge inheritance tree -public: - std::set visitors; - void setProperty(ObjProperty what, ObjPropertyID identifier) override; - void onHeroVisit (const CGHeroInstance * h) const override; - - CTownBonus(const BuildingID & index, BuildingSubID::EBuildingSubID subId, CGTownInstance * TOWN); - CTownBonus(IGameCallback *cb); - - template void serialize(Handler &h) - { - h & static_cast(*this); - h & visitors; - } - -private: - void applyBonuses(CGHeroInstance * h, const BonusList & bonuses) const; -}; - -class DLL_LINKAGE CTownRewardableBuilding : public CGTownBuilding, public Rewardable::Interface -{ - /// reward selected by player, no serialize - ui16 selectedReward = 0; - - std::set visitors; - - bool wasVisitedBefore(const CGHeroInstance * contextHero) const; - - void grantReward(ui32 rewardID, const CGHeroInstance * hero) const; - - Rewardable::Configuration generateConfiguration(vstd::RNG & rand) const; - -public: - void setProperty(ObjProperty what, ObjPropertyID identifier) override; - void onHeroVisit(const CGHeroInstance * h) const override; - - void newTurn(vstd::RNG & rand) const override; - - /// gives second part of reward after hero level-ups for proper granting of spells/mana - void heroLevelUpDone(const CGHeroInstance *hero) const override; - - void initObj(vstd::RNG & rand) override; - - /// applies player selection of reward - void blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const override; - - CTownRewardableBuilding(const BuildingID & index, BuildingSubID::EBuildingSubID subId, CGTownInstance * town, vstd::RNG & rand); - CTownRewardableBuilding(IGameCallback *cb); - - template void serialize(Handler &h) - { - h & static_cast(*this); - h & static_cast(*this); - h & visitors; - } -}; - -VCMI_LIB_NAMESPACE_END diff --git a/lib/mapObjects/CGTownInstance.cpp b/lib/mapObjects/CGTownInstance.cpp index f82849523..64eddc418 100644 --- a/lib/mapObjects/CGTownInstance.cpp +++ b/lib/mapObjects/CGTownInstance.cpp @@ -10,7 +10,8 @@ #include "StdInc.h" #include "CGTownInstance.h" -#include "CGTownBuilding.h" + +#include "TownBuildingInstance.h" #include "../spells/CSpellHandler.h" #include "../bonuses/Bonus.h" #include "../battle/IBattleInfoCallback.h" @@ -59,13 +60,13 @@ void CGTownInstance::setPropertyDer(ObjProperty what, ObjPropertyID identifier) switch (what) { case ObjProperty::STRUCTURE_ADD_VISITING_HERO: - bonusingBuildings[identifier.getNum()]->setProperty(ObjProperty::VISITORS, visitingHero->id); + rewardableBuildings.at(identifier.getNum())->setProperty(ObjProperty::VISITORS, visitingHero->id); break; case ObjProperty::STRUCTURE_CLEAR_VISITORS: - bonusingBuildings[identifier.getNum()]->setProperty(ObjProperty::STRUCTURE_CLEAR_VISITORS, NumericID(0)); + rewardableBuildings.at(identifier.getNum())->setProperty(ObjProperty::STRUCTURE_CLEAR_VISITORS, NumericID(0)); break; case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors - bonusingBuildings[identifier.getNum()]->setProperty(ObjProperty::VISITORS, garrisonHero->id); + rewardableBuildings.at(identifier.getNum())->setProperty(ObjProperty::VISITORS, garrisonHero->id); break; case ObjProperty::BONUS_VALUE_FIRST: bonusValue.first = identifier.getNum(); @@ -254,8 +255,8 @@ CGTownInstance::CGTownInstance(IGameCallback *cb): CGTownInstance::~CGTownInstance() { - for (auto & elem : bonusingBuildings) - delete elem; + for (auto & elem : rewardableBuildings) + delete elem.second; } int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const @@ -283,8 +284,8 @@ void CGTownInstance::setOwner(const PlayerColor & player) const void CGTownInstance::blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const { - for (auto building : bonusingBuildings) - building->blockingDialogAnswered(hero, answer); + for (auto building : rewardableBuildings) + building.second->blockingDialogAnswered(hero, answer); // FIXME: why call for every building? } void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const @@ -322,8 +323,9 @@ void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const cb->heroVisitCastle(this, h); } } - else if(h->visitablePos() == visitablePos()) + else { + assert(h->visitablePos() == this->visitablePos()); bool commander_recover = h->commander && !h->commander->alive; if (commander_recover) // rise commander from dead { @@ -344,10 +346,6 @@ void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const cb->showInfoDialog(&iw); } } - else - { - logGlobal->error("%s visits allied town of %s from different pos?", h->getNameTranslated(), getNameTranslated()); - } } void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const @@ -372,42 +370,12 @@ bool CGTownInstance::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) return town->getBuildingType(subId) != BuildingID::NONE; } -void CGTownInstance::initOverriddenBids() -{ - for(const auto & bid : builtBuildings) - { - const auto & overrideThem = town->buildings.at(bid)->overrideBids; - - for(const auto & overrideIt : overrideThem) - overriddenBuildings.insert(overrideIt); - } -} - -bool CGTownInstance::isBonusingBuildingAdded(BuildingID bid) const -{ - auto present = std::find_if(bonusingBuildings.begin(), bonusingBuildings.end(), [&](CGTownBuilding* building) - { - return building->getBuildingType() == bid; - }); - - return present != bonusingBuildings.end(); -} - -void CGTownInstance::addTownBonuses(vstd::RNG & rand) +void CGTownInstance::initializeConfigurableBuildings(vstd::RNG & rand) { for(const auto & kvp : town->buildings) { - if(vstd::contains(overriddenBuildings, kvp.first)) - continue; - - if(kvp.second->IsVisitingBonus()) - bonusingBuildings.push_back(new CTownBonus(kvp.second->bid, kvp.second->subId, this)); - - if(kvp.second->IsWeekBonus()) - bonusingBuildings.push_back(new COPWBonus(kvp.second->bid, kvp.second->subId, this)); - - if(kvp.second->subId == BuildingSubID::CUSTOM_VISITING_REWARD) - bonusingBuildings.push_back(new CTownRewardableBuilding(kvp.second->bid, kvp.second->subId, this, rand)); + if(!kvp.second->rewardableObjectInfo.getParameters().isNull()) + rewardableBuildings[kvp.first] = new TownRewardableBuildingInstance(this, kvp.second->bid, rand); } } @@ -447,34 +415,6 @@ DamageRange CGTownInstance::getKeepDamageRange() const }; } -void CGTownInstance::deleteTownBonus(BuildingID bid) -{ - size_t i = 0; - CGTownBuilding * freeIt = nullptr; - - for(i = 0; i != bonusingBuildings.size(); i++) - { - if(bonusingBuildings[i]->getBuildingType() == bid) - { - freeIt = bonusingBuildings[i]; - break; - } - } - if(freeIt == nullptr) - return; - - auto building = town->buildings.at(bid); - auto isVisitingBonus = building->IsVisitingBonus(); - auto isWeekBonus = building->IsWeekBonus(); - - if(!isVisitingBonus && !isWeekBonus) - return; - - bonusingBuildings.erase(bonusingBuildings.begin() + i); - - delete freeIt; -} - FactionID CGTownInstance::randomizeFaction(vstd::RNG & rand) { if(getOwner().isValidPlayer()) @@ -529,8 +469,7 @@ void CGTownInstance::initObj(vstd::RNG & rand) ///initialize town structures creatures[level].second.push_back(town->creatures[level][upgradeNum]); } } - initOverriddenBids(); - addTownBonuses(rand); //add special bonuses from buildings to the bonusingBuildings vector. + initializeConfigurableBuildings(rand); recreateBuildingsBonuses(); updateAppearance(); } @@ -552,17 +491,6 @@ void CGTownInstance::newTurn(vstd::RNG & rand) const cb->setObjPropertyValue(id, ObjProperty::BONUS_VALUE_FIRST, resID); cb->setObjPropertyValue(id, ObjProperty::BONUS_VALUE_SECOND, resVal); } - - for(const auto * manaVortex : getBonusingBuildings(BuildingSubID::MANA_VORTEX)) - cb->setObjPropertyValue(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex - - //get Mana Vortex or Stables bonuses - //same code is in the CGameHandler::buildStructure method - if (garrisonHero != nullptr) //garrison hero first - consistent with original H3 Mana Vortex and Battle Scholar Academy levelup windows order - cb->visitCastleObjects(this, garrisonHero); - - if (visitingHero != nullptr) - cb->visitCastleObjects(this, visitingHero); if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns { @@ -617,8 +545,8 @@ void CGTownInstance::newTurn(vstd::RNG & rand) const } } - for(const auto * rewardableBuilding : getBonusingBuildings(BuildingSubID::CUSTOM_VISITING_REWARD)) - rewardableBuilding->newTurn(rand); + for(const auto & building : rewardableBuildings) + building.second->newTurn(rand); if(hasBuilt(BuildingSubID::BANK) && bonusValue.second > 0) { @@ -863,9 +791,21 @@ void CGTownInstance::recreateBuildingsBonuses() for(const auto & b : bl) removeBonus(b); + + for(const auto & bid : builtBuildings) { - if(vstd::contains(overriddenBuildings, bid)) //tricky! -> checks tavern only if no bratherhood of sword + bool bonusesReplacedByUpgrade = false; + + for(const auto & upgradeID : builtBuildings) + { + const auto & upgrade = town->buildings.at(upgradeID); + if (upgrade->getBase() == bid && upgrade->upgradeReplacesBonuses) + bonusesReplacedByUpgrade = true; + } + + // bonuses from this building are disabled and replaced by bonuses from an upgrade + if (bonusesReplacedByUpgrade) continue; auto building = town->buildings.at(bid); @@ -990,18 +930,6 @@ const CArmedInstance * CGTownInstance::getUpperArmy() const return this; } -std::vector CGTownInstance::getBonusingBuildings(BuildingSubID::EBuildingSubID subId) const -{ - std::vector ret; - for(auto * const building : bonusingBuildings) - { - if(building->getBuildingSubtype() == subId) - ret.push_back(building); - } - return ret; -} - - bool CGTownInstance::hasBuiltSomeTradeBuilding() const { for(const auto & bid : builtBuildings) @@ -1306,4 +1234,24 @@ void CGTownInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &s } } +void CGTownInstance::postDeserialize() +{ + setNodeType(CBonusSystemNode::TOWN); + for(auto & building : rewardableBuildings) + building.second->town = this; +} + +std::map CGTownInstance::convertOldBuildings(std::vector oldVector) +{ + std::map result; + + for(auto & building : oldVector) + { + result[building->getBuildingType()] = new TownRewardableBuildingInstance(*building); + delete building; + } + + return result; +} + VCMI_LIB_NAMESPACE_END diff --git a/lib/mapObjects/CGTownInstance.h b/lib/mapObjects/CGTownInstance.h index d105c3a87..fc0c5a7d4 100644 --- a/lib/mapObjects/CGTownInstance.h +++ b/lib/mapObjects/CGTownInstance.h @@ -11,16 +11,19 @@ #include "IMarket.h" #include "CGDwelling.h" -#include "CGTownBuilding.h" -#include "../LogicalExpression.h" #include "../entities/faction/CFaction.h" // TODO: remove #include "../entities/faction/CTown.h" // TODO: remove VCMI_LIB_NAMESPACE_BEGIN class CCastleEvent; +class CTown; +class TownBuildingInstance; +class TownRewardableBuildingInstance; struct DamageRange; +template +class LogicalExpression; class DLL_LINKAGE CTownAndVisitingHero : public CBonusSystemNode { @@ -47,6 +50,8 @@ struct DLL_LINKAGE GrowthInfo class DLL_LINKAGE CGTownInstance : public CGDwelling, public IShipyard, public IMarket, public INativeTerrainProvider, public ICreatureUpgrader { std::string nameTextId; // name of town + + std::map convertOldBuildings(std::vector oldVector); public: using CGDwelling::getPosition; @@ -61,8 +66,7 @@ public: PlayerColor alignmentToPlayer; // if set to non-neutral, random town will have same faction as specified player std::set forbiddenBuildings; std::set builtBuildings; - std::set overriddenBuildings; ///buildings which bonuses are overridden and should not be applied - std::vector bonusingBuildings; + std::map rewardableBuildings; std::vector possibleSpells, obligatorySpells; std::vector > spells; //spells[level] -> vector of spells, first will be available in guild std::vector events; @@ -86,11 +90,18 @@ public: h & obligatorySpells; h & spells; h & events; - h & bonusingBuildings; - - for(auto * bonusingBuilding : bonusingBuildings) - bonusingBuilding->town = this; - + + if (h.version >= Handler::Version::NEW_TOWN_BUILDINGS) + { + h & rewardableBuildings; + } + else + { + std::vector oldVector; + h & oldVector; + rewardableBuildings = convertOldBuildings(oldVector); + } + if (h.saving) { CFaction * faction = town ? town->faction : nullptr; @@ -106,23 +117,14 @@ public: h & townAndVis; BONUS_TREE_DESERIALIZATION_FIX - if(town) + if (h.version < Handler::Version::NEW_TOWN_BUILDINGS) { - vstd::erase_if(builtBuildings, [this](BuildingID building) -> bool - { - if(!town->buildings.count(building) || !town->buildings.at(building)) - { - logGlobal->error("#1444-like issue in CGTownInstance::serialize. From town %s at %s removing the bogus builtBuildings item %s", nameTextId, pos.toString(), building); - return true; - } - return false; - }); + std::set overriddenBuildings; + h & overriddenBuildings; } - h & overriddenBuildings; - if(!h.saving) - this->setNodeType(CBonusSystemNode::TOWN); + postDeserialize(); } ////////////////////////////////////////////////////////////////////////// @@ -130,6 +132,7 @@ public: std::string nodeName() const override; void updateMoraleBonusFromArmy() override; void deserializationFix(); + void postDeserialize(); void recreateBuildingsBonuses(); void setVisitingHero(CGHeroInstance *h); void setGarrisonedHero(CGHeroInstance *h); @@ -165,7 +168,6 @@ public: GrowthInfo getGrowthInfo(int level) const; bool hasFort() const; bool hasCapitol() const; - std::vector getBonusingBuildings(BuildingSubID::EBuildingSubID subId) const; bool hasBuiltSomeTradeBuilding() const; //checks if special building with type buildingID is constructed bool hasBuilt(BuildingSubID::EBuildingSubID buildingID) const; @@ -231,9 +233,7 @@ private: void onTownCaptured(const PlayerColor & winner) const; int getDwellingBonus(const std::vector& creatureIds, const std::vector >& dwellings) const; bool townEnvisagesBuilding(BuildingSubID::EBuildingSubID bid) const; - bool isBonusingBuildingAdded(BuildingID bid) const; - void initOverriddenBids(); - void addTownBonuses(vstd::RNG & rand); + void initializeConfigurableBuildings(vstd::RNG & rand); }; VCMI_LIB_NAMESPACE_END diff --git a/lib/mapObjects/CRewardableObject.h b/lib/mapObjects/CRewardableObject.h index 9e1735a5f..5e424db2a 100644 --- a/lib/mapObjects/CRewardableObject.h +++ b/lib/mapObjects/CRewardableObject.h @@ -95,7 +95,6 @@ public: // class DLL_LINKAGE CGPyramid : public CBank // EXTRA -// class DLL_LINKAGE COPWBonus : public CGTownBuilding // class DLL_LINKAGE CTownBonus : public CGTownBuilding // class DLL_LINKAGE CGKeys : public CGObjectInstance //Base class for Keymaster and guards // class DLL_LINKAGE CGKeymasterTent : public CGKeys diff --git a/lib/mapObjects/TownBuildingInstance.cpp b/lib/mapObjects/TownBuildingInstance.cpp new file mode 100644 index 000000000..a82411695 --- /dev/null +++ b/lib/mapObjects/TownBuildingInstance.cpp @@ -0,0 +1,279 @@ +/* + * TownBuildingInstance.cpp, part of VCMI engine + * + * Authors: listed in file AUTHORS in main folder + * + * License: GNU General Public License v2.0 or later + * Full text of license available in license.txt file, in main folder + * + */ + +#include "StdInc.h" +#include "TownBuildingInstance.h" + +#include "CGTownInstance.h" +#include "../texts/CGeneralTextHandler.h" +#include "../IGameCallback.h" +#include "../gameState/CGameState.h" +#include "../mapObjects/CGHeroInstance.h" +#include "../networkPacks/PacksForClient.h" +#include "../entities/building/CBuilding.h" + + +#include + +VCMI_LIB_NAMESPACE_BEGIN + +TownBuildingInstance::TownBuildingInstance(IGameCallback * cb) + : IObjectInterface(cb) + , town(nullptr) +{} + +TownBuildingInstance::TownBuildingInstance(CGTownInstance * town, const BuildingID & index) + : IObjectInterface(town->cb) + , town(town) + , bID(index) +{} + +PlayerColor TownBuildingInstance::getOwner() const +{ + return town->getOwner(); +} + +MapObjectID TownBuildingInstance::getObjGroupIndex() const +{ + return -1; +} + +MapObjectSubID TownBuildingInstance::getObjTypeIndex() const +{ + return 0; +} + +int3 TownBuildingInstance::visitablePos() const +{ + return town->visitablePos(); +} + +int3 TownBuildingInstance::getPosition() const +{ + return town->getPosition(); +} + +TownRewardableBuildingInstance::TownRewardableBuildingInstance(IGameCallback *cb) + : TownBuildingInstance(cb) +{} + +TownRewardableBuildingInstance::TownRewardableBuildingInstance(CGTownInstance * town, const BuildingID & index, vstd::RNG & rand) + : TownBuildingInstance(town, index) +{ + initObj(rand); +} + +void TownRewardableBuildingInstance::initObj(vstd::RNG & rand) +{ + assert(town && town->town); + configuration = generateConfiguration(rand); +} + +Rewardable::Configuration TownRewardableBuildingInstance::generateConfiguration(vstd::RNG & rand) const +{ + Rewardable::Configuration result; + auto building = town->town->buildings.at(getBuildingType()); + + building->rewardableObjectInfo.configureObject(result, rand, cb); + for(auto & rewardInfo : result.info) + { + for (auto & bonus : rewardInfo.reward.bonuses) + { + bonus.source = BonusSource::TOWN_STRUCTURE; + bonus.sid = BonusSourceID(building->getUniqueTypeID()); + } + } + return result; +} + +void TownRewardableBuildingInstance::newTurn(vstd::RNG & rand) const +{ + if (configuration.resetParameters.period != 0 && cb->getDate(Date::DAY) > 1 && ((cb->getDate(Date::DAY)-1) % configuration.resetParameters.period) == 0) + { + auto newConfiguration = generateConfiguration(rand); + cb->setRewardableObjectConfiguration(town->id, getBuildingType(), newConfiguration); + + if(configuration.resetParameters.visitors) + { + cb->setObjPropertyValue(town->id, ObjProperty::STRUCTURE_CLEAR_VISITORS, getBuildingType()); + } + } +} + +void TownRewardableBuildingInstance::setProperty(ObjProperty what, ObjPropertyID identifier) +{ + switch (what) + { + case ObjProperty::VISITORS: + visitors.insert(identifier.as()); + break; + case ObjProperty::STRUCTURE_CLEAR_VISITORS: + visitors.clear(); + break; + case ObjProperty::REWARD_SELECT: + selectedReward = identifier.getNum(); + break; + } +} + +void TownRewardableBuildingInstance::heroLevelUpDone(const CGHeroInstance *hero) const +{ + grantRewardAfterLevelup(cb, configuration.info.at(selectedReward), town, hero); +} + +void TownRewardableBuildingInstance::blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const +{ + if(answer == 0) + return; // player refused + + if(visitors.find(hero->id) != visitors.end()) + return; // query not for this building + + if(answer > 0 && answer-1 < configuration.info.size()) + { + auto list = getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT); + grantReward(list[answer - 1], hero); + } + else + { + throw std::runtime_error("Unhandled choice"); + } +} + +void TownRewardableBuildingInstance::grantReward(ui32 rewardID, const CGHeroInstance * hero) const +{ + town->addHeroToStructureVisitors(hero, getBuildingType()); + + grantRewardBeforeLevelup(cb, configuration.info.at(rewardID), hero); + + // hero is not blocked by levelup dialog - grant remainder immediately + if(!cb->isVisitCoveredByAnotherQuery(town, hero)) + { + grantRewardAfterLevelup(cb, configuration.info.at(rewardID), town, hero); + } +} + +bool TownRewardableBuildingInstance::wasVisitedBefore(const CGHeroInstance * contextHero) const +{ + switch (configuration.visitMode) + { + case Rewardable::VISIT_UNLIMITED: + return false; + case Rewardable::VISIT_ONCE: + return !visitors.empty(); + case Rewardable::VISIT_PLAYER: + return false; //not supported + case Rewardable::VISIT_BONUS: + { + const auto building = town->getTown()->buildings.at(getBuildingType()); + return contextHero->hasBonusFrom(BonusSource::TOWN_STRUCTURE, BonusSourceID(building->getUniqueTypeID())); + } + case Rewardable::VISIT_HERO: + return visitors.find(contextHero->id) != visitors.end(); + case Rewardable::VISIT_LIMITER: + return configuration.visitLimiter.heroAllowed(contextHero); + default: + return false; + } +} + +void TownRewardableBuildingInstance::onHeroVisit(const CGHeroInstance *h) const +{ + auto grantRewardWithMessage = [&](int index) -> void + { + auto vi = configuration.info.at(index); + logGlobal->debug("Granting reward %d. Message says: %s", index, vi.message.toString()); + + town->addHeroToStructureVisitors(h, getBuildingType()); //adding to visitors + + InfoWindow iw; + iw.player = h->tempOwner; + iw.text = vi.message; + vi.reward.loadComponents(iw.components, h); + iw.type = EInfoWindowMode::MODAL; + if(!iw.components.empty() || !iw.text.toString().empty()) + cb->showInfoDialog(&iw); + + grantReward(index, h); + }; + auto selectRewardsMessage = [&](const std::vector & rewards, const MetaString & dialog) -> void + { + BlockingDialog sd(configuration.canRefuse, rewards.size() > 1); + sd.player = h->tempOwner; + sd.text = dialog; + + if (rewards.size() > 1) + for (auto index : rewards) + sd.components.push_back(configuration.info.at(index).reward.getDisplayedComponent(h)); + + if (rewards.size() == 1) + configuration.info.at(rewards.front()).reward.loadComponents(sd.components, h); + + cb->showBlockingDialog(&sd); + }; + + if(!town->hasBuilt(getBuildingType())) + return; + + if(!wasVisitedBefore(h)) + { + auto rewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT); + + logGlobal->debug("Visiting object with %d possible rewards", rewards.size()); + switch (rewards.size()) + { + case 0: // no available rewards, e.g. visiting School of War without gold + { + auto emptyRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_NOT_AVAILABLE); + if (!emptyRewards.empty()) + grantRewardWithMessage(emptyRewards[0]); + else + logMod->warn("No applicable message for visiting empty object!"); + break; + } + case 1: // one reward. Just give it with message + { + if (configuration.canRefuse) + selectRewardsMessage(rewards, configuration.info.at(rewards.front()).message); + else + grantRewardWithMessage(rewards.front()); + break; + } + default: // multiple rewards. Act according to select mode + { + switch (configuration.selectMode) { + case Rewardable::SELECT_PLAYER: // player must select + selectRewardsMessage(rewards, configuration.onSelect); + break; + case Rewardable::SELECT_FIRST: // give first available + grantRewardWithMessage(rewards.front()); + break; + case Rewardable::SELECT_RANDOM: // give random + grantRewardWithMessage(*RandomGeneratorUtil::nextItem(rewards, cb->gameState()->getRandomGenerator())); + break; + } + break; + } + } + } + else + { + logGlobal->debug("Revisiting already visited object"); + + auto visitedRewards = getAvailableRewards(h, Rewardable::EEventType::EVENT_ALREADY_VISITED); + if (!visitedRewards.empty()) + grantRewardWithMessage(visitedRewards[0]); + else + logMod->debug("No applicable message for visiting already visited object!"); + } +} + + +VCMI_LIB_NAMESPACE_END diff --git a/lib/mapObjects/TownBuildingInstance.h b/lib/mapObjects/TownBuildingInstance.h new file mode 100644 index 000000000..cdb690eb2 --- /dev/null +++ b/lib/mapObjects/TownBuildingInstance.h @@ -0,0 +1,109 @@ +/* + * TownBuildingInstance.h, part of VCMI engine + * + * Authors: listed in file AUTHORS in main folder + * + * License: GNU General Public License v2.0 or later + * Full text of license available in license.txt file, in main folder + * + */ + +#pragma once + +#include "IObjectInterface.h" +#include "../rewardable/Interface.h" + +VCMI_LIB_NAMESPACE_BEGIN + +class CGTownInstance; +class CBuilding; + +class DLL_LINKAGE TownBuildingInstance : public IObjectInterface +{ +///basic class for town structures handled as map objects +public: + TownBuildingInstance(CGTownInstance * town, const BuildingID & index); + TownBuildingInstance(IGameCallback *cb); + + CGTownInstance * town; + + const BuildingID & getBuildingType() const + { + return bID; + } + + PlayerColor getOwner() const override; + MapObjectID getObjGroupIndex() const override; + MapObjectSubID getObjTypeIndex() const override; + + int3 visitablePos() const override; + int3 getPosition() const override; + + template void serialize(Handler &h) + { + h & bID; + if (h.version < Handler::Version::NEW_TOWN_BUILDINGS) + { + // compatibility code + si32 indexOnTV = 0; //identifies its index on towns vector + BuildingSubID::EBuildingSubID bType = BuildingSubID::NONE; + h & indexOnTV; + h & bType; + } + } + +private: + BuildingID bID; //from building list +}; + +class DLL_LINKAGE TownRewardableBuildingInstance : public TownBuildingInstance, public Rewardable::Interface +{ + /// reward selected by player, no serialize + ui16 selectedReward = 0; + std::set visitors; + + bool wasVisitedBefore(const CGHeroInstance * contextHero) const; + void grantReward(ui32 rewardID, const CGHeroInstance * hero) const; + Rewardable::Configuration generateConfiguration(vstd::RNG & rand) const; + +public: + void setProperty(ObjProperty what, ObjPropertyID identifier) override; + void onHeroVisit(const CGHeroInstance * h) const override; + + void newTurn(vstd::RNG & rand) const override; + + /// gives second part of reward after hero level-ups for proper granting of spells/mana + void heroLevelUpDone(const CGHeroInstance *hero) const override; + + void initObj(vstd::RNG & rand) override; + + /// applies player selection of reward + void blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const override; + + TownRewardableBuildingInstance(CGTownInstance * town, const BuildingID & index, vstd::RNG & rand); + TownRewardableBuildingInstance(IGameCallback *cb); + + template void serialize(Handler &h) + { + h & static_cast(*this); + if (h.version >= Handler::Version::NEW_TOWN_BUILDINGS) + h & static_cast(*this); + h & visitors; + } +}; + +/// Compatibility for old code +class DLL_LINKAGE CTownCompatBuilding1 : public TownRewardableBuildingInstance +{ +public: + using TownRewardableBuildingInstance::TownRewardableBuildingInstance; +}; + +/// Compatibility for old code +class DLL_LINKAGE CTownCompatBuilding2 : public TownRewardableBuildingInstance +{ +public: + using TownRewardableBuildingInstance::TownRewardableBuildingInstance; +}; + +VCMI_LIB_NAMESPACE_END diff --git a/lib/networkPacks/NetPacksLib.cpp b/lib/networkPacks/NetPacksLib.cpp index c242b23b9..6946b11ab 100644 --- a/lib/networkPacks/NetPacksLib.cpp +++ b/lib/networkPacks/NetPacksLib.cpp @@ -36,6 +36,7 @@ #include "mapObjects/CBank.h" #include "mapObjects/CGCreature.h" #include "mapObjects/CGMarket.h" +#include "mapObjects/TownBuildingInstance.h" #include "mapObjects/CGTownInstance.h" #include "mapObjects/CQuest.h" #include "mapObjects/MiscObjects.h" @@ -1332,18 +1333,8 @@ void NewStructures::applyGs(CGameState *gs) { assert(t->town->buildings.at(id) != nullptr); t->builtBuildings.insert(id); - t->updateAppearance(); - auto currentBuilding = t->town->buildings.at(id); - - if(currentBuilding->overrideBids.empty()) - continue; - - for(const auto & overrideBid : currentBuilding->overrideBids) - { - t->overriddenBuildings.insert(overrideBid); - t->deleteTownBonus(overrideBid); - } } + t->updateAppearance(); t->built = built; t->recreateBuildingsBonuses(); } @@ -2431,11 +2422,26 @@ void EntitiesChanged::applyGs(CGameState * gs) void SetRewardableConfiguration::applyGs(CGameState * gs) { auto * objectPtr = gs->getObjInstance(objectID); - auto * rewardablePtr = dynamic_cast(objectPtr); - assert(rewardablePtr); + if (!buildingID.hasValue()) + { + auto * rewardablePtr = dynamic_cast(objectPtr); + assert(rewardablePtr); + rewardablePtr->configuration = configuration; + } + else + { + auto * townPtr = dynamic_cast(objectPtr); + TownBuildingInstance * buildingPtr = nullptr; - rewardablePtr->configuration = configuration; + for (auto & building : townPtr->rewardableBuildings) + if (building.second->getBuildingType() == buildingID) + buildingPtr = building.second; + + auto * rewardablePtr = dynamic_cast(buildingPtr); + assert(rewardablePtr); + rewardablePtr->configuration = configuration; + } } void SetBankConfiguration::applyGs(CGameState * gs) diff --git a/lib/registerTypes/RegisterTypesMapObjects.h b/lib/registerTypes/RegisterTypesMapObjects.h index 5e8d96f32..4c2528030 100644 --- a/lib/registerTypes/RegisterTypesMapObjects.h +++ b/lib/registerTypes/RegisterTypesMapObjects.h @@ -12,7 +12,7 @@ #include "../mapObjectConstructors/CBankInstanceConstructor.h" #include "../mapObjects/MapObjects.h" #include "../mapObjects/CGCreature.h" -#include "../mapObjects/CGTownBuilding.h" +#include "../mapObjects/TownBuildingInstance.h" #include "../mapObjects/ObjectTemplate.h" #include "../battle/BattleInfo.h" #include "../battle/CObstacleInstance.h" @@ -86,10 +86,10 @@ void registerTypesMapObjects(Serializer &s) //order of type registration is critical for loading old savegames //Other object-related - s.template registerType(); - s.template registerType(); - s.template registerType(); - s.template registerType(); + s.template registerType(); + s.template registerType(); + s.template registerType(); + s.template registerType(); s.template registerType(); diff --git a/lib/serializer/ESerializationVersion.h b/lib/serializer/ESerializationVersion.h index d4c0d9e89..e0e9002f8 100644 --- a/lib/serializer/ESerializationVersion.h +++ b/lib/serializer/ESerializationVersion.h @@ -63,7 +63,8 @@ enum class ESerializationVersion : int32_t STATISTICS, // 852 - removed random number generators from library classes CAMPAIGN_REGIONS, // 853 - configurable campaign regions EVENTS_PLAYER_SET, // 854 - map & town events use std::set instead of bitmask to store player list - STATISTICS_SCREEN, // 855 - extent statistic functions + NEW_TOWN_BUILDINGS, // 855 - old bonusing buildings have been removed + STATISTICS_SCREEN, // 856 - extent statistic functions CURRENT = STATISTICS_SCREEN }; diff --git a/lib/spells/CSpellHandler.cpp b/lib/spells/CSpellHandler.cpp index 037ff4a4f..cbed923e9 100644 --- a/lib/spells/CSpellHandler.cpp +++ b/lib/spells/CSpellHandler.cpp @@ -687,7 +687,7 @@ std::vector CSpellHandler::spellRangeInHexes(std::string input) const std::set ret; std::string rng = input + ','; //copy + artificial comma for easier handling - if(rng.size() >= 2 && rng[0] != 'X') //there is at least one hex in range (+artificial comma) + if(rng.size() >= 2 && rng[0] != 'X' && rng[0] != 'x') //there is at least one hex in range (+artificial comma) { std::string number1; std::string number2; diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index b65d81c91..a1ae33d57 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -57,6 +57,7 @@ #include "../lib/mapObjects/CGCreature.h" #include "../lib/mapObjects/CGMarket.h" +#include "../lib/mapObjects/TownBuildingInstance.h" #include "../lib/mapObjects/CGTownInstance.h" #include "../lib/mapObjects/MiscObjects.h" #include "../lib/mapObjectConstructors/AObjectTypeHandler.h" @@ -631,10 +632,21 @@ void CGameHandler::onPlayerTurnStarted(PlayerColor which) events::PlayerGotTurn::defaultExecute(serverEventBus.get(), which); turnTimerHandler->onPlayerGetTurn(which); - handleTimeEvents(which); + const auto * playerState = gs->getPlayerState(which); - for (auto t : getPlayerState(which)->towns) + handleTimeEvents(which); + for (auto t : playerState->towns) handleTownEvents(t); + + for (auto t : playerState->towns) + { + //garrison hero first - consistent with original H3 Mana Vortex and Battle Scholar Academy levelup windows order + if (t->garrisonHero != nullptr) + objectVisited(t, t->garrisonHero); + + if (t->visitingHero != nullptr) + objectVisited(t, t->visitingHero); + } } void CGameHandler::onPlayerTurnEnded(PlayerColor which) @@ -1411,18 +1423,6 @@ void CGameHandler::setOwner(const CGObjectInstance * obj, const PlayerColor owne if (town->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING)) setPortalDwelling(town, true, false); } - - if (oldOwner.isValidPlayer()) //old owner is real player - { - if (getPlayerState(oldOwner)->towns.empty() && getPlayerState(oldOwner)->status != EPlayerStatus::LOSER) //previous player lost last town - { - InfoWindow iw; - iw.player = oldOwner; - iw.text.appendLocalString(EMetaText::GENERAL_TXT, 6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated. - iw.text.replaceName(oldOwner); - sendAndApply(&iw); - } - } } const PlayerState * p = getPlayerState(owner); @@ -1522,11 +1522,14 @@ void CGameHandler::takeCreatures(ObjectInstanceID objid, const std::vectorid; - vc.tid = obj->id; - vc.flags |= 1; - sendAndApply(&vc); + if (obj->visitingHero != hero && obj->garrisonHero != hero) + { + HeroVisitCastle vc; + vc.hid = hero->id; + vc.tid = obj->id; + vc.flags |= 1; + sendAndApply(&vc); + } visitCastleObjects(obj, hero); giveSpells (obj, hero); @@ -1537,8 +1540,8 @@ void CGameHandler::heroVisitCastle(const CGTownInstance * obj, const CGHeroInsta void CGameHandler::visitCastleObjects(const CGTownInstance * t, const CGHeroInstance * h) { - for (auto building : t->bonusingBuildings) - building->onHeroVisit(h); + for (auto & building : t->rewardableBuildings) + building.second->onHeroVisit(h); } void CGameHandler::stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) @@ -2491,9 +2494,9 @@ bool CGameHandler::buildStructure(ObjectInstanceID tid, BuildingID requestedID, changeFogOfWar(t->getSightCenter(), t->getSightRadius(), t->getOwner(), ETileVisibility::REVEALED); if(t->garrisonHero) //garrison hero first - consistent with original H3 Mana Vortex and Battle Scholar Academy levelup windows order - visitCastleObjects(t, t->garrisonHero); + objectVisited(t, t->garrisonHero); if(t->visitingHero) - visitCastleObjects(t, t->visitingHero); + objectVisited(t, t->visitingHero); checkVictoryLossConditionsForPlayer(t->tempOwner); return true; diff --git a/server/battles/BattleFlowProcessor.cpp b/server/battles/BattleFlowProcessor.cpp index c4c1235db..e81f975bc 100644 --- a/server/battles/BattleFlowProcessor.cpp +++ b/server/battles/BattleFlowProcessor.cpp @@ -23,6 +23,7 @@ #include "../../lib/mapObjects/CGTownInstance.h" #include "../../lib/networkPacks/PacksForClientBattle.h" #include "../../lib/spells/BonusCaster.h" +#include "../../lib/spells/CSpellHandler.h" #include "../../lib/spells/ISpellMechanics.h" #include "../../lib/spells/ObstacleCasterProxy.h" @@ -128,7 +129,7 @@ void BattleFlowProcessor::tryPlaceMoats(const CBattleInfoCallback & battle) void BattleFlowProcessor::onBattleStarted(const CBattleInfoCallback & battle) { tryPlaceMoats(battle); - + gameHandler->turnTimerHandler->onBattleStart(battle.getBattle()->getBattleID()); if (battle.battleGetTacticDist() == 0) @@ -321,13 +322,15 @@ void BattleFlowProcessor::activateNextStack(const CBattleInfoCallback & battle) if(!removeGhosts.changedStacks.empty()) gameHandler->sendAndApply(&removeGhosts); - + gameHandler->turnTimerHandler->onBattleNextStack(battle.getBattle()->getBattleID(), *next); if (!tryMakeAutomaticAction(battle, next)) { - setActiveStack(battle, next); - break; + if(next->alive()) { + setActiveStack(battle, next); + break; + } } } } @@ -757,8 +760,14 @@ void BattleFlowProcessor::stackTurnTrigger(const CBattleInfoCallback & battle, c }); spells::BattleCast parameters(&battle, st, spells::Mode::ENCHANTER, spell); parameters.setSpellLevel(bonus->val); - parameters.massive = true; - parameters.smart = true; + + auto &levelInfo = spell->getLevelInfo(bonus->val); + bool isDamageSpell = spell->isDamage() || spell->isOffensive(); + if (!isDamageSpell || levelInfo.smartTarget || !levelInfo.range.empty()) + { + parameters.massive = true; + parameters.smart = true; + } //todo: recheck effect level if(parameters.castIfPossible(gameHandler->spellEnv, spells::Target(1, spells::Destination()))) { diff --git a/server/processors/HeroPoolProcessor.cpp b/server/processors/HeroPoolProcessor.cpp index 7e8d327ba..c6e328d27 100644 --- a/server/processors/HeroPoolProcessor.cpp +++ b/server/processors/HeroPoolProcessor.cpp @@ -242,10 +242,7 @@ bool HeroPoolProcessor::hireHero(const ObjectInstanceID & objectID, const HeroTy gameHandler->giveResource(player, EGameResID::GOLD, -GameConstants::HERO_GOLD_COST); if(town) - { - gameHandler->visitCastleObjects(town, recruitedHero); - gameHandler->giveSpells(town, recruitedHero); - } + gameHandler->objectVisited(town, recruitedHero); // If new hero has scouting he might reveal more terrain than we saw before gameHandler->changeFogOfWar(recruitedHero->getSightCenter(), recruitedHero->getSightRadius(), player, ETileVisibility::REVEALED); diff --git a/test/spells/effects/CatapultTest.cpp b/test/spells/effects/CatapultTest.cpp index 1cb55c5f2..a67e9204a 100644 --- a/test/spells/effects/CatapultTest.cpp +++ b/test/spells/effects/CatapultTest.cpp @@ -14,6 +14,7 @@ #include #include "../../../lib/mapObjects/CGTownInstance.h" +#include "../../../lib/json/JsonNode.h" namespace test